{"text": "\\section{Wavefunction optimization}\n\\label{sec:optimization}\n\nOptimizing wavefunction is critical in all kinds of real-space QMC calculations\nbecause it significantly improves both the accuracy and efficiency of computation.\nHowever, it is very difficult to directly adopt deterministic minimization approaches because of the stochastic nature of evaluating quantities with MC.\nThanks to the algorithmic breakthrough during the first decade of this century and the tremendous computer power available, \nit is now feasible to optimize tens of thousands of parameters in a wavefunction for a solid or molecule.\nQMCPACK has multiple optimizers implemented based on the state-of-the-art linear method.\nWe are continually improving our optimizers for robustness and friendliness and are trying to provide a single solution.\nBecause of the large variation of wavefunction types carrying distinct characteristics, using several optimizers might be needed in some cases.\nWe strongly suggested reading recommendations from the experts who maintain these optimizers.\n\nA typical optimization block looks like the following. It starts with method=``linear\" and contains three blocks of parameters.\n\\begin{lstlisting}[style=QMCPXML]\n \n \n \n 256 \n 2867200 \n 1 \n 5 \n 5 \n 70 \n 1.0 \n no \n \n ...\n \n 0.3 \n 0.95 \n 0.00 \n 0.05 \n ...\n \n OneShiftOnly \n ...\n \n \n\\end{lstlisting}\n\\begin{itemize}\n\\item Loop is helpful to repeatedly execute identical optimization blocks.\n\\item The first part is highly identical to a regular VMC block.\n\\item The second part is to specify the correlated sampling options and define the cost function.\n\\item The last part is used to specify the options of different optimizers, which can be very distinct from one to another.\n\\end{itemize}\n\n\\subsection{VMC run for the optimization}\nThe VMC calculation for the wavefunction optimization has a strict requirement \nthat \\ixml{samples} or \\ixml{samplesperthread} must be specified because of the optimizer needs for the stored \\ixml{samples}.\nThe input parameters of this part are identical to the VMC method.\n\nRecommendations:\n\\begin{itemize}\n\\item Run the inclusive VMC calculation correctly and efficiently because this takes a significant amount of time during optimization.\nFor example, make sure the derived \\ixml{steps} per block is 1 and use larger \\ixml{substeps} to control the correlation between \\ixml{samples}.\n\\item A reasonable starting wavefunction is necessary. A lot of optimization fails because of a bad wavefunction starting point.\nThe sign of a bad initial wavefunction includes but is not limited to a very long equilibration time, low acceptance ratio, and huge variance.\nThe first thing to do after a failed optimization is to check the information provided by the VMC calculation via \\texttt{*.scalar.dat files}.\n\\end{itemize}\n\n\\subsection{Correlated sampling and cost function}\nAfter generating the samples with VMC, the derivatives of the wavefunction with respect to the parameters are computed for proposing a new set of parameters by optimizers.\nAnd later, a correlated sampling calculation is performed to quickly evaluate values of the cost function on the old set of parameters and the new set for further decisions.\nThe input parameters are listed in the following table.\n\\begin{table}[h]\n\\begin{center}\n\\begin{tabularx}{\\textwidth}{l l l l l X }\n\\hline\n\\multicolumn{6}{l}{\\texttt{linear} method} \\\\\n\\hline\n\\multicolumn{2}{l}{parameters} & \\multicolumn{4}{l}{}\\\\\n & \\bfseries name & \\bfseries datatype & \\bfseries values & \\bfseries default & \\bfseries description \\\\\n & \\texttt{nonlocalpp} & text & yes, no & no & include non-local PP energy in the cost function\\\\\n% & \\texttt{GEVMethod} & text & mixed, H2 & mixed & methods of generalized eigenvalue problem\\\\\n% & \\texttt{beta} & real & any value & 0.0 & a parameter for GEVMethod\\\\\n% & \\texttt{use\\_nonlocalpp\\_deriv} & text & yes, no & no & include the derivatives of non-local PP\\\\\n & \\texttt{minwalkers} & real & 0--1 & 0.3 & Lower bound of the effective weight\\\\\n & \\texttt{maxWeight} & real & $>1$ & 1e6 & Maximum weight allowed in reweighting\\\\\n \\hline\n\\end{tabularx}\n\\end{center}\n\\end{table}\n\nAdditional information:\n\\begin{itemize}\n\\item \\ixml{maxWeight}: The default should be good.\n\\item \\ixml{nonlocalpp}: The \\texttt{nonlocalpp} contribution to the local energy depends on the wavefunction.\nWhen a new set of parameters is proposed, this contribution needs to be updated if the cost function consists of local energy.\nFortunately, nonlocal contribution is chosen small when making a PP for small locality error.\nWe can ignore its change and avoid the expensive computational cost.\nAn implementation issue with GPU code is that a large amount of memory is consumed with this option.\n\\item \\ixml{minwalkers}: This is a \\textit{critical} parameter. When the ratio of effective samples to actual number of samples in a reweighting step goes lower than \\ixml{minwalkers},\nthe proposed set of parameters is invalid. % The last set of acceptable parameters is kept.\n\\end{itemize}\n\nThe cost function consists of three components: energy, unreweighted variance, and reweighted variance.\n\\begin{lstlisting}[style=QMCPXML]\n 0.95 \n 0.00 \n 0.05 \n\\end{lstlisting}\n\n\\subsection{Optimizers}\nQMCPACK implements a number of different optimizers each with different priorities for accuracy, convergence, memory usage, and stability.\nThe optimizers can be switched among ``OneShiftOnly'' (default), ``adaptive,'' ``descent,'' ``hybrid,'' and ``quartic'' (old) using the following line in the optimization block:\n\\begin{lstlisting}\n THE METHOD YOU LIKE \n\\end{lstlisting}\n\n\\subsection{OneShiftOnly Optimizer}\nThe OneShiftOnly optimizer targets a fast optimization by moving parameters more aggressively. It works with OpenMP and GPU and can be considered for large systems.\nThis method relies on the effective weight of correlated sampling rather than the cost function value to justify a new set of parameters.\nIf the effective weight is larger than \\ixml{minwalkers}, the new set is taken whether or not the cost function value decreases.\nIf a proposed set is rejected, the standard output prints the measured ratio of effective samples to the total number of samples\nand adjustment on \\ixml{minwalkers} can be made if needed.\n\n\\begin{table}[h]\n\\begin{center}\n\\begin{tabularx}{\\textwidth}{l l l l l X }\n\\hline\n\\multicolumn{6}{l}{\\texttt{linear} method} \\\\\n\\hline\n\\multicolumn{2}{l}{parameters} & \\multicolumn{4}{l}{}\\\\\n & \\bfseries name & \\bfseries datatype & \\bfseries values & \\bfseries default & \\bfseries description \\\\\n & \\texttt{shift\\_i} & real & $>0$ & 0.01 & Direct stabilizer added to the Hamiltonian matrix\\\\\n & \\texttt{shift\\_s} & real & $>0$ & 1.00 & Initial stabilizer based on the overlap matrix\\\\\n \\hline\n\\end{tabularx}\n\\end{center}\n\\end{table}\n\nAdditional information:\n\\begin{itemize}\n\\item \\ixml{shift_i}: This is the direct term added to the diagonal of the Hamiltonian matrix.\n It provides more stable but slower optimization with a large value.\n\\item \\ixml{shift_s}: This is the initial value of the stabilizer based on the overlap matrix added to the Hamiltonian matrix.\n It provides more stable but slower optimization with a large value. The used value is auto-adjusted by the optimizer.\n\\end{itemize}\n\n\nRecommendations:\n\\begin{itemize}\n \\item Default \\ixml{shift_i}, \\ixml{shift_s} should be fine.\n \\item For hard cases, increasing \\ixml{shift_i} (by a factor of 5 or 10) can significantly stabilize the optimization by reducing the pace towards the optimal parameter set.\n \\item If the VMC energy of the last optimization iterations grows significantly, increase \\ixml{minwalkers} closer to 1 and make the optimization stable.\n \\item If the first iterations of optimization are rejected on a reasonable initial wavefunction, \n lower the \\ixml{minwalkers} value based on the measured value printed in the standard output to accept the move.\n\\end{itemize}\n\nWe recommended using this optimizer in two sections with a very small \\ixml{minwalkers} in the first and a large value in the second, such as the following.\nIn the very beginning, parameters are far away from optimal values and large changes are proposed by the optimizer.\nHaving a small \\ixml{minwalkers} makes it much easier to accept these changes.\nWhen the energy gradually converges, we can have a large \\ixml{minwalkers} to avoid risky parameter sets.\n\\begin{lstlisting}[style=QMCPXML]\n \n \n \n 1 \n 10000 \n 1 \n 5 \n 5 \n 25 \n 1.0 \n no \n \n \n OneShiftOnly \n 1e-4 \n \n \n \n \n \n 1 \n 20000 \n 1 \n 5 \n 2 \n 50 \n 1.0 \n no \n \n \n OneShiftOnly \n 0.5 \n \n \n\\end{lstlisting}\n\nFor each optimization step, you will see\\\\\n\\begin{lstlisting}\nThe new set of parameters is valid. Updating the trial wave function!\n\\end{lstlisting}\\par\nor\\par\n\\begin{lstlisting}\nThe new set of parameters is not valid. Revert to the old set!\n\\end{lstlisting}\nOccasional rejection is fine. Frequent rejection indicates potential problems, and users should inspect the VMC calculation or change optimization strategy.\nTo track the progress of optimization, use the command \\texttt{qmca -q ev *.scalar.dat} to look at the VMC energy and variance for each optimization step.\n\n\\subsection{Adaptive Optimizer}\n\nThe default setting of the adaptive optimizer is to construct the linear method Hamiltonian and overlap matrices explicitly and add different shifts to the Hamiltonian matrix \nas ``stabilizers.''\nThe generalized eigenvalue problem is solved for each shift to obtain updates to the wavefunction parameters.\nThen a correlated sampling is performed for each shift's updated wavefunction and the initial trial wavefunction\nusing the middle shift's updated wavefunction as the guiding function.\nThe cost function for these wavefunctions is compared, and the update corresponding to the best cost function is selected.\nIn the next iteration, the median magnitude of the stabilizers is set to the magnitude that generated the best update in the current iteration, thus adapting the magnitude of\nthe stabilizers automatically.\n\nWhen the trial wavefunction contains more than 10,000 parameters, constructing and storing the linear method matrices could become a memory bottleneck. \nTo avoid explicit construction of these matrices, the adaptive optimizer implements the block linear method (BLM) approach. \\cite{Zhao:2017:blocked_lm}\nThe BLM tries to find an approximate \nsolution\\: $\\vec{c}_{opt}$ to the standard LM generalized eigenvalue problem by dividing the variable space into a number of blocks\nand making intelligent estimates for which directions within those blocks will be most important for constructing\\: $\\vec{c}_{opt}$, \nwhich is then obtained by solving a smaller, more memory-efficient \neigenproblem in the basis of these supposedly important block-wise directions. \n\n\\begin{table}[h]\n\\begin{center}\n\\begin{tabularx}{\\textwidth}{l l l l l X }\n\\hline\n\\multicolumn{6}{l}{\\texttt{linear} method} \\\\\n\\hline\n\\multicolumn{2}{l}{parameters} & \\multicolumn{4}{l}{}\\\\\n & \\bfseries name & \\bfseries datatype & \\bfseries values & \\bfseries default & \\bfseries description \\\\\n %& \\texttt{stepsize} & real & 0--1 & 0.25 & Step size for moving parameters\\\\\n & \\texttt{max\\_relative\\_change} & real & $>0$ & 10.0 & Allowed change in cost function\\\\\n & \\texttt{max\\_param\\_change} & real & $>0$ & 0.3 & Allowed change in wavefunction parameter\\\\\n & \\texttt{shift\\_i} & real & $>0$ & 0.01 & Initial diagonal stabilizer added to the Hamiltonian matrix\\\\\n & \\texttt{shift\\_s} & real & $>0$ & 1.00 & Initial overlap-based stabilizer added to the Hamiltonian matrix\\\\\n & \\texttt{target\\_shift\\_i} & real & any & -1.0 & Diagonal stabilizer value aimed for during adaptive method (disabled if $\\leq$ 0)\\\\\n & \\texttt{cost\\_increase\\_tol} & real & $\\geq 0$ & 0.0 & Tolerance for cost function increases\\\\\n & \\texttt{chase\\_lowest} & text & yes, no & yes & Chase the lowest eigenvector in iterative solver\\\\\n & \\texttt{chase\\_closest} & text & yes, no & no & Chase the eigenvector closest to initial guess\\\\\n & \\texttt{block\\_lm} & text & yes, no & no & Use BLM\\\\\n & \\texttt{nblocks} & integer & $>0$ & & Number of blocks in BLM\\\\\n & \\texttt{nolds} & integer & $>0$ & & Number of old update vectors used in BLM\\\\\n & \\texttt{nkept} & integer & $>0$ & & Number of eigenvectors to keep per block in BLM\\\\\n \\hline\n\\end{tabularx}\n\\end{center}\n\\end{table}\n\nAdditional information:\n\\begin{itemize}\n \\item \\ixml{shift_i}: This is the initial coefficient used to scale the diagonal stabilizer.\n More stable but slower optimization is expected with a large value.\n The adaptive method will automatically adjust this value after each linear method iteration.\n \\item \\ixml{shift_s}: This is the initial coefficient used to scale the overlap-based stabilizer.\n More stable but slower optimization is expected with a large value.\n The adaptive method will automatically adjust this value after each linear method iteration.\n \\item \\ixml{target_shift_i}: If set greater than zero, the adaptive method will choose the update whose shift\\_i value is closest to\n this target value so long as the associated cost is within cost\\_increase\\_tol of the lowest cost.\n Disable this behavior by setting target\\_shift\\_i to a negative number.\n \\item \\ixml{cost_increase_tol}: Tolerance for cost function increases when selecting the best shift.\n \\item \\ixml{nblocks}: This is the number of blocks used in BLM. The amount of memory required to store LM matrices decreases\n as the number of blocks increases. But the error introduced by BLM would increase as the number of blocks increases. \n \\item \\ixml{nolds}: In BLM, the interblock correlation is accounted for by including a small number of wavefunction update vectors\n outside the block. Larger \\ixml{nolds} would include more interblock correlation and more accurate results but \n also higher memory requirements. \n \\item \\ixml{nkept}: This is the number of update directions retained from each block in the BLM. If all directions are retained in each block, \n then the BLM becomes equivalent to the standard LM. Retaining five or fewer directions per block is often sufficient.\n\\end{itemize}\n\nRecommendations:\n\\begin{itemize}\n \\item Default \\ixml{shift_i}, \\ixml{shift_s} should be fine. \n \\item When there are fewer than about 5,000 variables being optimized, the traditional LM is preferred because it has a lower overhead than the BLM when the number of variables is small.\n \\item Initial experience with the BLM suggests that a few hundred blocks and a handful of \\ixml{nolds} and \\ixml{nkept}\n often provide a good balance between memory use and accuracy. In general, using fewer blocks should be more accurate but would require more memory.\n\\end{itemize}\n\n\\begin{lstlisting}[style=QMCPXML]\n \n \n \n 1 \n 20000 \n 1 \n 5 \n 5 \n 50 \n 1.0 \n no \n \n \n 1.00 \n 0.00 \n 0.00 \n \n adaptive\n 10.0\n 1.00 \n 1.00 \n 0.3 \n yes \n yes \n no \n \n \n \n\\end{lstlisting}\n%To activate this optimizer, add ``-D BUILD\\_LMYENGINE\\_INTERFACE=1'' in the CMake command line.\n\nThe adaptive optimizer is also able to optimize individual excited states directly. \\cite{Zhao:2016:dir_tar}\nIn this case, it tries to minimize the following function: \n\\begin{equation*}\n\\Omega[\\Psi]=\\frac{\\left<\\Psi|\\omega-H|\\Psi\\right>}{\\left<\\Psi|{\\left(\\omega-H\\right)}^2|\\Psi\\right>}\\:.\n\\end{equation*}\nThe global minimum of this function corresponds to the state whose energy lies immediately above the shift parameter $\\omega$ in the energy spectrum.\nFor example, if $\\omega$ were placed in between the ground state energy and the first excited state energy and the wavefunction ansatz was capable of a good\ndescription for the first excited state, then the wavefunction would be optimized for the first excited state.\nNote that if the ansatz is not capable of a good description of the excited state in question, the optimization could converge to a different\nstate, as is known to occur in some circumstances for traditional ground state optimizations.\nNote also that the ground state can be targeted by this method by choosing $\\omega$ to be below the ground state energy, although we should stress that this\nis not the same thing as a traditional ground state optimization and will in general give a slightly different wavefunction.\nExcited state targeting requires two additional parameters, as shown in the following table.\\\\\n\n\\begin{table}[h]\n\\begin{center}\n\\begin{tabularx}{\\textwidth}{l l l l l X }\n\\hline\n\\multicolumn{6}{l}{Excited state targeting} \\\\\n\\hline\n\\multicolumn{2}{l}{parameters} & \\multicolumn{4}{l}{}\\\\\n & \\bfseries name & \\bfseries datatype & \\bfseries values & \\bfseries default & \\bfseries description \\\\\n %& \\texttt{stepsize} & real & 0--1 & 0.25 & Step size for moving parameters\\\\\n & \\texttt{targetExcited} & text & yes, no & no & Whether to use the excited state targeting optimization\\\\\n & \\texttt{omega} & real & real numbers & none & Energy shift used to target different excited states\\\\\n \\hline\n\\end{tabularx}\n\\end{center}\n\\end{table}\n\nExcited state recommendations:\n\\begin{itemize}\n \\item Because of the finite variance in any approximate wavefunction, we recommended setting $\\omega=\\omega_0-\\sigma$, where $\\omega_0$ is placed just\n below the energy of the targeted state and $\\sigma^2$ is the energy variance.\n \\item To obtain an unbiased excitation energy, the ground state should be optimized with the excited state variational principle as well by setting\n \\ixml{omega} below the ground state energy. Note that using the ground state variational principle for the ground state and the excited state variational\n principle for the excited state creates a bias in favor of the ground state. \n\\end{itemize}\n\n\\subsection{Descent Optimizer}\nGradient descent algorithms are an alternative set of optimization methods to the OneShiftOnly and adaptive optimizers based on the linear method.\nThese methods use only first derivatives to optimize trial wave functions and convergence can be accelerated by retaining a memory of previous derivative values.\nMultiple flavors of accelerated descent methods are available. They differ in details such as the schemes for adaptive adjustment of step sizes.\\cite{Otis2019}\nDescent algorithms avoid the construction of matrices that occurs in the linear method and consequently can be applied to larger sets of\noptimizable parameters.\nCurrently, descent optimization is only available for ground state calculations.\nParameters for descent are shown in the table below.\\\\\n\n\\begin{table}[H]\n\\begin{center}\n\\begin{tabularx}{\\textwidth}{l l l l l X }\n\\hline\n\\multicolumn{6}{l}{\\texttt{descent} method} \\\\\n\\hline\n\\multicolumn{2}{l}{parameters} & \\multicolumn{4}{l}{}\\\\\n & \\bfseries name & \\bfseries datatype & \\bfseries values & \\bfseries default & \\bfseries description \\\\\n & \\texttt{flavor} & text & \\begin{tabular}{@{}c@{}}RMSprop,Random \\\\ ADAM,AMSGrad\\end{tabular} & RMSprop & Particular type of descent method\\\\\n & \\texttt{Ramp\\_eta} & text & yes,no & no & Whether to gradually ramp up step sizes\\\\\n & \\texttt{Ramp\\_num} & integer & $>0$ & 30 & Number of steps over which to ramp up step size\\\\\n & \\texttt{TJF\\_2Body\\_eta} & real & $>0$ & 0.01 & Step size for two body Jastrow parameters\\\\\n & \\texttt{TJF\\_1Body\\_eta} & real & $>0$ & 0.01 & Step size for one body Jastrow parameters\\\\\n & \\texttt{F\\_eta} & real & $>0$ & 0.001 & Step size for number counting Jastrow F matrix parameters\\\\\n & \\texttt{Gauss\\_eta} & real & $>0$ & 0.001 & Step size for number counting Jastrow gaussian basis parameters\\\\\n & \\texttt{CI\\_eta} & real & $>0$ & 0.01 & Step size for CI parameters\\\\\n & \\texttt{Orb\\_eta} & real & $>0$ & 0.001 & Step size for orbital parameters\\\\\n \\hline\n\\end{tabularx}\n\\end{center}\n\\end{table}\n\nAdditional information and recommendations:\n\\begin{itemize}\n\n \\item It is generally advantageous to set different step sizes for different types of parameters.\n\tMore nonlinear parameters such as those for number counting Jastrow factors or orbitals typically require\n\tsmaller steps sizes than those for CI coefficients or traditional Jastrow parameters. There are defaults for \n\tseveral parameter types and a default of .001 has been chosen for all other parameters.\n \\item The ability to gradually ramp up step sizes to their input values is useful for avoiding spikes in the average local energy\n\tduring early iterations of descent optimization. This initial rise in the energy occurs as a memory of past gradients is being\n\tbuilt up and it may be possible for the energy to recover without ramping if there are enough iterations in the optimization.\n \\item The step sizes chosen can have a substantial influence on the quality of the optimization and the final variational energy achieved.\n\tLarger step sizes may be helpful if there is reason to think the descent optimization is not reaching the minimum energy. There are also\n\tadditional hyperparameters in the descent algorithms with default values.\\cite{Otis2019} They seem to have limited influence\n\ton the effectiveness of the optimization compared to step sizes, but users can adjust them within the source code of the descent engine if they wish.\n \\item The sampling effort for individual descent steps can be small compared that for linear method iterations as shown in the example input below. Something in the range of 10,000 to 30,000\n\tseems sufficient for molecules with tens of electrons. However, descent optimizations may require anywhere from a few hundred to a few thousand iterations.\n \\item In cases where a descent optimization struggles to reach the minimum and a linear method optimization is not possible or unsatisfactory, it may be useful to try\n\tthe hybrid optimization approach described in the next subsection.\n\\end{itemize}\n\n\\begin{lstlisting}[style=QMCPXML]\n \n \n \n \n \n 2000\n 1\n 20000\n 100\n 0.05\n\n descent\n \n yes\n\n \n \n\t \n RMSprop\n\n no\n 30\n \n .02\n .02\n .001\n .001\n .1\n .0001\n\n\n \n \n \\end{lstlisting}\n\n\n\\subsection{Hybrid Optimizer}\n\nAnother optimization option is to use a hybrid combination of accelerated descent and blocked linear method.\nIt provides a means to retain the advantages of both individual methods while scaling to large numbers of parameters beyond the traditional 10,000 parameter limit of the linear method.\\cite{Otis2019}\nIn a hybrid optimization, alternating sections of descent and BLM optimization are used.\nGradient descent is used to identify the previous important directions in parameter space used by the BLM, the number of which is set by the \\texttt{nold} input for the BLM.\nOver the course of a section of descent, vectors of parameter differences are stored and then passed to the linear method engine after the optimization changes to the BLM.\nOne motivation for including sections of descent is to counteract noise in linear method updates due to uncertainties in its step direction and allow for a smoother movement to the minimum.\nThere are two additional parameters used in the hybrid optimization and it requires a slightly different format of input to specify the constituent methods as shown below in the example.\n\n\\begin{table}[H]\n\\begin{center}\n\\begin{tabularx}{\\textwidth}{l l l l l X }\n\\hline\n\\multicolumn{6}{l}{\\texttt{descent} method} \\\\\n\\hline\n\\multicolumn{2}{l}{parameters} & \\multicolumn{4}{l}{}\\\\\n & \\bfseries name & \\bfseries datatype & \\bfseries values & \\bfseries default & \\bfseries description \\\\\n & \\texttt{num\\_updates} & integer & $>0$ & & Number of steps for a method\\\\\n & \\texttt{Stored\\_Vectors} & integer & $>0$ & 5 & Number of vectors to transfer to BLM\\\\\n \\hline\n\\end{tabularx}\n\\end{center}\n\\end{table}\n\n\n\\begin{lstlisting}[style=QMCPXML]\n \n \n \n hybrid \n\n \n\n\t1000\n 1\n 20000\n 1000\n 0.05\n \n \n \n descent \n 5\n RMSprop\n .01\n .01\n .1\n\n no\n 10\n \n\n \n \n 2000\n 1\n 1000000\n 1000\n 0.05\n \n \n \n adaptive \n 10.0\n 3\n 0.01\n 1.00\n\n yes\n 2\n 5\n 5\n\n \n \n\n \\end{lstlisting}\n\nAdditional information and recommendations:\n\\begin{itemize}\n\n \\item In the example above, the input for \\texttt{loop} gives the total number of steps for the full optimization while the inputs for \\texttt{num\\_updates} specify\n\tthe number of steps in the constituent methods. For this case, the optimization would begin with 100 steps of descent using the parameters in the first \\texttt{optimizer} block\n\tand then switch to the BLM for 3 steps before switching back to descent for the final 100 iterations of the total of 203.\n \\item The design of the hybrid method allows for more than two \\texttt{optimizer} blocks to be used and the optimization will cycle through the individual methods. However, the effectiveness\n\tof this in terms of the quality of optimization results is unexplored.\n \\item As the descent algorithms are currently only implemented for ground state optimizations, this hybrid combination of them with the BLM is also restricted to the ground state for now.\n \\item It can be useful to follow a hybrid optimization with a section of pure descent optimization and take an average energy over the last few hundred iterations as the final variational energy.\n\tThis approach can achieve a lower statistical uncertainty on the energy for less overall sampling effort compared to what a pure linear method optimization would require.\n\\end{itemize}\n\n\\subsection{Quartic Optimizer}\n\\textit{This is an older optimizer method retained for compatibility. We recommend starting with the newest OneShiftOnly or adaptive optimizers.}\nThe quartic optimizer fits a quartic polynomial to 7 values of the cost function obtained using reweighting along the chosen direction and determines the optimal move.\nThis optimizer is very robust but is a bit conservative when accepting new steps, especially when large parameters changes are proposed.\n\\begin{table}[h]\n\\begin{center}\n\\begin{tabularx}{\\textwidth}{l l l l l X }\n\\hline\n\\multicolumn{6}{l}{\\texttt{linear} method} \\\\\n\\hline\n\\multicolumn{2}{l}{parameters} & \\multicolumn{4}{l}{}\\\\\n & \\bfseries name & \\bfseries datatype & \\bfseries values & \\bfseries default & \\bfseries description \\\\\n %& \\texttt{stepsize} & real & 0--1 & 0.25 & Step size for moving parameters\\\\\n & \\texttt{bigchange} & real & $>0$ & 50.0 & Largest parameter change allowed\\\\\n & \\texttt{alloweddifference} & real & $>0$ & 1e-4 & Allowed increased in energy\\\\\n & \\texttt{exp0} & real & any value & -16.0 & Initial value for stabilizer\\\\\n & \\texttt{stabilizerscale} & real & $>0$ & 2.0 & Increase in value of \\texttt{exp0} between iterations\\\\\n & \\texttt{nstabilizers} & integer & $>0$ & 3 & Number of stabilizers to try\\\\\n & \\texttt{max\\_its} & integer & $>0$ & 1 & Number of inner loops with same samples\\\\\n \\hline\n\\end{tabularx}\n\\end{center}\n\\end{table}\n\nAdditional information:\n\\begin{itemize}\n\\item \\ixml{exp0}. This is the initial value for stabilizer (shift to diagonal of H). The actual value of stabilizer is $10^{\\textrm{exp0}}$.\n\\end{itemize}\n\nRecommendations:\n\\begin{itemize}\n \\item{For hard cases (e.g., simultaneous optimization of long MSD and 3-Body J), set \\ixml{exp0}\nto 0 and do a single inner iteration (max its=1) per sample of configurations.}\n\\end{itemize}\n\n\\begin{lstlisting}[style=QMCPXML]\n \n quartic\n -6\n 1.0e-4 \n 1 \n 15.0\n\\end{lstlisting}\n\n\\subsection{General recommendations}\nHere are a few recommendations to make wavefunction optimization easier.\n\\begin{itemize}\n\\item All electron wavefunctions are typically more difficult to optimize than pseudopotential wavefunctions because of the importance of the wavefunction near the nucleus.\n\\item Two-body Jastrow contributes the largest portion of correlation energy from bare Slater determinants. Consequently, the recommended order for optimizing wavefunction components is two-body, one-body, three-body Jastrow factors and MSD coefficients.\n\\item For two-body spline Jastrows, always start from a reasonable one. The lack of physically motivated constraints in the functional form at large distances can cause slow convergence if starting from zero. \n\\item One-body spline Jastrow from old calculations can be a good starting point.\n\\item Three-body polynomial Jastrow can start from zero. It is beneficial to first optimize one-body and two-body Jastrow factors without adding three-body terms in the calculation and then add the three-body Jastrow and optimize all the three components together.\n\\end{itemize}\n\\subsubsection{Optimization of CI coefficients}\nWhen storing a CI wavefunction in HDF5 format, the CI coefficients and the $\\alpha$ and $\\beta$ components of each CI are not in the XML input file. When optimizing the CI coefficients, they will be stored in HDF5 format. \nThe optimization header block will have to specify that the new CI coefficients will be saved to HDF5 format. If the tag is not added coefficients will not be saved. \n\\begin{lstlisting}[style=QMCPXML]\n \n\\end{lstlisting}\n\nThe rest of the optimization block remains the same. \n\nWhen running the optimization, the new coefficients will be stored in a *.sXXX.opt.h5 file, where XXX coressponds to the series number. The H5 file contains only the optimized coefficients. The corresponding *.sXXX.opt.xml will be updated for each optimization block as follow: \n\\begin{lstlisting}[style=QMCPXML]\n\n\\end{lstlisting}\n\nThe opt\\_coeffs tag will then reference where the new CI coefficients are stored.\\\\\n\nWhen restarting the run with the new optimized coeffs, you need to specify the previous hdf5 containing the basis set, orbitals,\nand MSD, as well as the new optimized coefficients. The code will read the previous data but will rewrite the coefficients that\nwere optimized with the values found in the *.sXXX.opt.h5 file. Be careful to keep the pair of optimized CI coefficients and\nJastrow coefficients together to avoid inconsistencies.\n\n\n\n", "meta": {"hexsha": "f59057361e5f02b1c5e46e923b1b1b45ce150644", "size": 37531, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "legacy_manual/opt.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/opt.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/opt.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": 61.7286184211, "max_line_length": 280, "alphanum_fraction": 0.7239881698, "num_tokens": 9273, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.38491214448393346, "lm_q1q2_score": 0.19997006613770812}}
{"text": "\\section{The Importance of Inelastic Collisions}\nThe treatment of the inelastic collisions will not be as detailed as for the elastic case as we will focus on the qualitative implications of allowing inelastic annihilation and creation processes during thermalization. A full treatment of all inelastic effects is nearly impossible and even today it is not yet fully understood which processes are the most relevant ones driving the system towards the equilibrium state. I will try to highlight the most important observations and refer to the respective research papers for further details. \\\\\n\\noindent \nFirst of all we observe that the inelastic processes will modify the collision integral on the right hand side of eqn. (\\ref{eqn:transport}). Interestingly it can be shown that this modification leaves the relation for the scattering time $t$ unchanged and therefore also the evolution equation for the defining scales $\\Lambda$ and $\\Lambda_{\\mathrm{s}}$. Implications on the condensate formation can be obtained via an extensive numerical study of solutions of the complete transport equation. The elastic contributions to the collision integral provide a source term for the condensate whereas the inelastic contributions may be interpreted as sink term. The task is to understand the balancing of the source and sink contributions which may allow a condensate to exist during most of the thermalization process.\\\\\n\\noindent\nOne could consider for example the effect of the strong longitudinal expansion of matter involved in relativistic heavy-ion collisions, i.\\,e. the flattening of an isotropic initial distribution in the direction of the collision axis, by introducing a suitable drift term on the left hand side of the transport equation or instabilities in the isotropy of $p_z$ and the transversal momentum $p_{\\mathrm{T}}$ (cf. \\cite{Blaizot2012}). Another important effect is the influence of gluon radiation allowing transport of momenta over a wide range of momenta on a very short time scale. This can be understood as a certain feature of gauge theories. For more details the interested reader is referred to publication \\cite{Blaizot2016}.", "meta": {"hexsha": "3b061aa9c64f32b81c4515e929e19db92a6751c8", "size": 2165, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "summary/content/03_inelastic.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/03_inelastic.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/03_inelastic.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": 360.8333333333, "max_line_length": 817, "alphanum_fraction": 0.8189376443, "num_tokens": 430, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.39606816627404173, "lm_q1q2_score": 0.19958119293562748}}
{"text": "% !TEX root = ParticleFilter.tex\n\\section{Method\\label{method}}\n\n\n\\subsection{The Agent-Based Model: StationSim}\n\n\\textit{StationSim} is a simple agent-based model that has been designed to very loosely represent the behaviour of a crowd of people moving from an entrance on one side of a rectangular environment to an exit on the other side. This is analogous to a train arriving at a train station and passengers moving across the concourse to leave. A number of agents, $N$, which varies in the later experiments, are created when the model starts. They are able to enter the environment (leave their train) at a uniform rate through one of three entrances. They move across the `concourse' and then leave by one of the two exits. The entrances and exits have a set size, such that only a limited number of agents can pass through them in any given iteration. Once all agents have entered the environment and passed through the concourse then the simulation ends. The model environment is illustrated in Figure \\ref{fig:StationSim}, with the trajectories of two interacting agents for illustration. \n%The model is also outlined in full as per the ODD protocol~\\citep{grimm_odd_2010} in Appendix~\\ref{odd}.\n\n\\begin{figure}[ht]\n\\centering\n\\includegraphics[width=0.5\\textwidth]{figures/PF_ABM}\n\\caption{StationSim environment with 3 entrance and 2 exit doors}.\\label{fig:StationSim}\n\\end{figure}\n\nThe model has deliberately been designed to be extremely simple and does not attempt to match the behavioural realism offered by more developed crowd models \\citep{chen_multiagentbased_2017, helbing_simulating_2000, klugl_largescale_2007, vanderwal_simulating_2017}. The reason for this simplicity is so that: (1) the model can execute relatively quickly; (2) the probabilistic elements in the model are limited (we know precisely from where probabilistic behaviour arises); (3) the model can be described fully using a relatively simple state vector, as discussed in Section~\\ref{state_vector}. Importantly, the model is able to capture the emergence of \\textit{crowding}. This results because each agent has a different maximum speed that they can travel at. Therefore, when a fast agent approaches a slower one, they attempt to get past by making a random binary choice to move left or right around them. Depending on the agents in the vicinity, this behaviour can start to lead to the formation of crowds. To illustrate this, Figure~\\ref{fig:crowding} shows the paths of the agents (\\ref{fig:crowding-trails}) and the total agent density (\\ref{fig:crowding-density}) during an example simulation. The degree and location of crowding depends on the random allocation of maximum speeds to agents and their random of direction taken to avoid slower agents; these cannot be estimated \\textit{a priori}. Unlike in previous work where the models did not necessarily meet the common criteria that define agent-based models \\citep[e.g.]{lloyd_exploring_2016, ward_dynamic_2016} this model respects three of the most important characteristics: \n\n\\begin{figure}\n \\centering\n \\begin{subfigure}[b]{0.48\\textwidth}\n \\centering\n \\includegraphics[width=.95\\linewidth]{figures/crowding-trails}\n \\caption{Individual trails showing the paths taken by agents}\n \\label{fig:crowding-trails}\n \\end{subfigure}\n \\label{fig:crowding}\n \\begin{subfigure}[b]{0.48\\textwidth}\n \\centering\n \\includegraphics[width=.95\\linewidth]{figures/crowding-density}\n \\caption{The total crowd density over the simulation run.}\n \\label{fig:crowding-density}\n \\end{subfigure}\n \\caption{An example of crowding in the StationSim model}\n \\label{fig:crowding}\n\\end{figure}\n\n\\begin{itemize}\n\t\\item individual heterogeneity -- agents have different maximum travel speeds; \n\t\\item agent interactions -- agents are not allowed to occupy the same space and try to move around slower agents who are blocking their path; \n\t\\item emergence -- crowding is an emergent property of the system that arises as a result of the choice of exit that each agent is heading to and their maximum speed.\n\\end{itemize}\n\nThe model code is relatively short and easy to understand. It is written in Python, and is available in its entirety at in the project repository \\citep{stationsimgit}.\n% \\footnote{\\url{XXXX Link to repo}}.\n\n\n\\subsection{Data Assimilation - Introduction and Definitions}\n\nDA methods are built on the following assumptions: \n\n\\begin{enumerate}\n\t\\item Although they have low uncertainty, observational data are often spatio-temporally sparse. Therefore there are typically insufficient amounts of data to to describe the system in sufficient detail and a data-driven approach would not work.\n\t\\item Models are not sparse; they can represent the target system in great detail and hence fill in the spatio-temporal gaps in observational data by propagating data from observed to unobserved areas \\citep{carrassi_data_2018}. For example, some parts of a building might be more heavily observed than others, so a model that assimilated data from the observed areas might be able to estimate the state of the unobserved areas. However, if the underlying systems are complex, a model will rapidly diverge from the real system in the absence of \\textit{up to date} data \\citep{ward_dynamic_2016}.\n\t\\item The combination a model and up-to-date observational data allow ``all the available information'' to be used to determine the state of the system as accurately as possible \\citep{talagrand_use_1991}. \n\\end{enumerate}\n\nDA algorithms work by running a model forward in time up to the point that some new observational data become available. This is typically called the \\textit{predict} step. At this point, the algorithm has an estimate of the current system state and its uncertainty (the prior). The next step, \\textit{update}, involves using the new observations, and their uncertainties, to update the current state estimate to create a posterior estimate of the state. As the posterior has combined the best guess of the state from the model \\textit{and} the best guess of the state from the observations, it should be a closer estimate of the true system state than that which could be estimated from the observations or the model in isolation.\n\n\\subsection{The Particle Filter\\label{particle_filter}}\n\nThere are many different ways to perform data assimilation, as discussed in Section \\ref{da_pf}. Here, a potentially appropriate solution to the data assimilation problem for agent-based models is the particle filter -- also known as a Bayesian bootstrap filter or a sequential Monte Carlo method -- which represents the posterior state using a collection of model samples, called particles \\citep{gordon_novel_1993,carpenter_improved_1999,wang_data_2015, carrassi_data_2018}. Figure~\\ref{fig:PF_flowchart} illustrates the process of running a particle filter. Note that the `pseudo-truth model' is a single instance of the agent-based model that is used as a proxy for the real system as per the identical twin experimental framework that we have adopted.\n\nThe data assimilation `window' determines how often new observations are assimilated into the particle filter. The size of the window is an important factor -- larger windows result in the particles deviating further from the real system state -- but here we fix the window at 100 iterations. The simulation terminates when all agents have left the system.\n\n\\begin{figure}[ht]\n\\centering\n\\includegraphics[width=0.8\\textwidth]{figures/PF_flowchart2}\n\\caption{Flowchart of data assimilation process using a particle filter.\\label{fig:PF_flowchart}}\n\\end{figure}\n\n\\subsubsection{The State Vector and Transition Function\\label{state_vector}} \n\nHere, the \\textit{state vector}, at a time $t$, contains all the information that a transition function needs to iterate the model forward by one step, including all of the agent ($i = \\{ 0, 1, \\dots, N \\} $) parameters ($\\overrightarrow{p_i}$) and variables ($\\overrightarrow{v_i}$) as well as global model parameters $\\overrightarrow{P}$:\n\\begin{equation}\n S_t = \\left[ \\begin{array}{cccccccc}\n\\overrightarrow{p_0} & \\overrightarrow{v_0} & \\overrightarrow{p_1} & \\overrightarrow{v_1} & \\dots & \\overrightarrow{p_N} & \\overrightarrow{v_N} & \\overrightarrow{P} \n\\end{array} \\right]\n\\end{equation} \n\nA similar structure, the \\textit{observation vector}, contains all of the observations made from the `real world' (in this case the pseudo-truth model) at a time $t$. Here, the particle filter is only used to estimate the state of the models variables ($\\overrightarrow{v_i}$), not any of the parameters ($\\overrightarrow{p_i}$ and $\\overrightarrow{P}$) (although it is worth noting that parameter estimation is technically feasible and will be experimented with in future work). Also, the current speed of an agent can be calculated from its current location and the locations of the agents surrounding it, so in effect the observation vector only needs to include the positions of the agents with the addition of some Gaussian noise, $\\epsilon$:\n\\begin{equation}\n O_t = \\left[ \\begin{array}{ccccccc}\nx_0 & y_0 & x_1 & y_1 & \\dots & x_n & y_n \n\\end{array} \\right]\n\\end{equation} \n\n Therefore in the experiments conducted here, all model parameters are fixed. Hence a further vector is required to map the observations to the state vector that the particles can actually manipulate. We define the partial state vector $S'$ to match the shape of $O$, i.e.:\n\\begin{equation}\n S'_t = \\left[ \\begin{array}{ccccccc}\nx_0 & y_0 & x_1 & y_1 & \\dots & x_n & y_n \n\\end{array} \\right]\n\\end{equation} \n\nThis has the effect of `pairing' agents in the particles to those in the pseudo-truth data, in a similar approach to that taken by \\citep{wang_data_2015}. It is worth noting that, because the particle filter will not be tasked with parameter estimation, then the data assimilation is somewhat simpler than it would be in a real application. For example, one of the agent parameters is used to store the location of the exit out of the environment that the agent is moving towards. As this parameter is set \\textit{a priori} for each agent, then the particle filter does not need to estimate where the agents are ultimately going, only where they currently are.\n\n\\subsubsection{Observations from the pseudo-truth data}\n\nIn a real application, the particle filter would be assimilating data in real time from sensors of the real world. This is not the case here so instead, we take `observations' from the pseudo-truth data (which are, as it happens, generated by the StationSim model). Each particle evolves in time according to the StationSim dynamics and receives new observations at regular intervals. Measurement error (i.e. noise, $\\epsilon$) is added to the observations (in the real world, sensors observations will be noisy). Here, observations take the form of the $(x,y)$ locations of all agents. This is analogous to tracking all individuals in a crowd and providing snapshots of their locations at discrete points in time to the particle filter. This `synthetic observation' is probably more detailed than reality, so future work will vary the amount of detail provided to the algorithm. It will firstly reduce the number of agents who are observed (e.g. tracking only \\textit{some} people) and then provide only aggregate population counts (which is analogous to using a camera or other sensor to count the number of people at a certain point). \n\n\\subsubsection{Particle Weights}\n\nEach particle in the particle filter has a weight associated with it that quantifies how similar a particle is to an observation. The weights are calculated at the end of each data assimilation window (i.e. when observations become available). At the start of the following window the particles then evolve independently from each other \\citep{fearnhead_particle_2018}. The weights are, in effect, the average distance between agents in that particle and the corresponding agents in StationSim (recall that there is a one-to-one mapping between agents in the particles and agents in the truth model). Formally, let $x^n(i,t)$ be the location of the $i$-th agent at time $t$ in the $n$-th particle for $n \\in \\{1,\\dots,N\\}$ and let $x(i,t)$ be the location of the $i$-th agent in StationSim for $i \\in \\{1,\\dots,I\\}$. The error of the $n$-th particle $\\epsilon^n(t)$ at time $t$ is then given by\n\\begin{equation}\n\\epsilon^n(t) = \\frac{1}{I} \\sum_{i=1}^I |x(i,t) - x^n(i,t)|,\n\\end{equation}\nand the particle filter error $\\nu(t)$ at time $t$ is given by\n\\begin{equation}\n\\label{eqn:particle_error}\n\\begin{split}\n\\nu(t) =& \\frac{1}{N} \\sum_{n=1}^{N} \\epsilon^n(t), \\\\\n=& \\frac{1}{NI} \\sum_{n=1}^{N}\\sum_{i=1}^I |x(i,t) - x^n(i,t)|.\n\\end{split}\n\\end{equation}\n\nIt is worth noting that, because the agent locations are the only data stored in the partial state vector, the particle error is equivalent to the Euclidean distance ($l_2$-norm) between the particle partial state vector $S'_{t}$ and the observation vector $O_t$,\n\\begin{equation}\n \\nu(t) = || S'_{t} - O_t ||_2.\n\\end{equation} \n\nParticles with relatively large error are likely to be removed during the sampling procedure (discussed in the following section), whereas those with low error are likely to be duplicated. In addition for their use in resampling, the population of particle weights can be used to gain insight into how well the particle filter is able to represent the `true' system state overall. \n\n\\subsubsection{Sampling Procedure\\label{particle_sampling}}\n\nHere, a bootstrap filter is implemented which uses systematic resampling \\citep{doucet_introduction_2001, douc_comparison_2005, wang_data_2015, long_spatial_2017, carrassi_data_2018}. This begins by taking a random sample $U$ from the uniform distribution on the interval $[0,1/N]$ and then selecting $N$ points $U^i$ for $i \\in \\{1,\\dots,N\\}$ on the interval $[0,1]$ such that\n\\begin{equation}\nU^i = (i-1)/N + U.\n\\end{equation}\nLet the particles currently have locations $x_i$. Using the inversion method, we calculate the cumulative sum of the normalised particle weights $w_i$ and define the inverse function $D$ of this cumulative sum, that is:\n\\begin{equation}\nD(u) = i \\text{ for } u \\in \\left(\\sum_{j=1}^{i-1}w_j,\\sum_{j=1}^{i}w_j\\right].\n\\end{equation}\nFinally, the new locations of the resampled particles are given by $x_{D(U^i)}$.\n\nAs discussed in Section~\\ref{background}, a well-studied issue that particle filters face is that of particle deprivation \\citep{snyder_obstacles_2008}, which refers to the problem of particles converging to a single point such that all particles, but one, vanish \\citep{kong_sequential_1994}. \n% This vastly reduces the size of the state space covered by the population of particles and will make it difficult or impossible to find particles with low error in later windows. Common approaches to resolve the deprivation problem include increasing the number of particles or trying to reduce the dimensionality of the state space. Bespoke approaches also exist; for example \\citep{wang_data_2015} develop a technique called `component set resampling' that samples \\textit{parts} of particles (i.e. those parts that are working well) rather than whole particles in their entirety. \nHere, the problem is addressed in two ways. Firstly by simply using large numbers of particles relative to the size of the state space and, secondly, by diversifying the particles \\citep{vadakkepat_improved_2006} -- also known as roughening, jittering, and diffusing \\citep{li_fight_2014, shephard_learning_2009, pantrigo_combining_2005}. In each iteration of the model we add Gaussian white noise to the particles' state vector to increase their variance, which increases particle diversity. This encourages a greater variety of particles to be resampled and therefore makes the algorithm more likely to represent the state of the underlying model. This method is a special case of the resample-move method presented in \\citep{gilks_following_2001}. The amount of noise to add is a key hyper-parameter -- too little and it has no effect, too much and the state of the particles moves far away from the true state -- as discussed in the following section. \n", "meta": {"hexsha": "9be8f2b0b61911735f27295b8e4130b3d1db8536", "size": 16243, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Writing/2019-ParticleFilter-Preprint/method.tex", "max_stars_repo_name": "RobertClay/DUST-RC", "max_stars_repo_head_hexsha": "09f7ec9d8d093021d068dff8a7a48c15ea318b86", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15, "max_stars_repo_stars_event_min_datetime": "2018-11-21T14:57:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-04T15:42:09.000Z", "max_issues_repo_path": "Writing/2019-ParticleFilter-Preprint/method.tex", "max_issues_repo_name": "RobertClay/DUST-RC", "max_issues_repo_head_hexsha": "09f7ec9d8d093021d068dff8a7a48c15ea318b86", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 125, "max_issues_repo_issues_event_min_datetime": "2019-11-06T13:03:35.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-07T13:38:33.000Z", "max_forks_repo_path": "Writing/2019-ParticleFilter-Preprint/method.tex", "max_forks_repo_name": "RobertClay/DUST-RC", "max_forks_repo_head_hexsha": "09f7ec9d8d093021d068dff8a7a48c15ea318b86", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2018-11-20T15:56:49.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-08T10:21:06.000Z", "avg_line_length": 118.5620437956, "max_line_length": 1641, "alphanum_fraction": 0.7811980545, "num_tokens": 3897, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.19958119293562745}}
{"text": "%!TEX root = ../main.tex\n\n\\section{Dielectric Laser Acceleration}\n\nIn the public sphere, particle accelerators most commonly conjure images of giant facilities for performing particle physics experiments, such as the Large Hadron Collider.\nHowever, in fact, most particle accelerators are used in other applications, such as radiotherapy, X-ray generation, and ion implantation for semiconductor device fabrication \\cite{england2014dielectric}.\nConventional radio-frequency (RF) accelerators use a metal or superconducting cavity, driven with microwave radiation, to provide sustained acceleration to charged particles traversing the structure.\nHowever, the amount of achievable acceleration per unit length is fundamentally limited by the material breakdown and damage limit of the cavity.\nTherefore, for an accelerator already driven at its damage threshold, the only option to achieve high total energy gains from an accelerator is to make the device longer.\nThe largest current particle accelerators reach several of kilometers in length, requiring substantial resources to operate and maintain.\n\nDielectric laser acceleration (DLA) is an emerging method that seeks to revolutionize particle accelerator technology by exploiting the decades of progress in nanofabrication, materials science, and laser technology.\nIn DLA, instead of using metal structures driven by microwaves, dielectric structures are illuminated with infrared laser light, which creates an electromagnetic field pattern in their vicinity that may accelerate electrically charged particles, such as electrons.\nWhen compared to metal surfaces at microwave frequencies, dielectric materials have very high damage thresholds at short pulse durations and infrared wavelengths \\cite{mcneur2016elements, soong2012laser}.\nThis fact allows DLAs to achieve energy gains per length that are between 10 to 100 times higher than those found in conventional radio frequency (RF) accelerators.\n\nExperimental demonstrations of these acceleration gradients have been made practical in recent years by the availability of robust nanofabrication techniques combined with modern solid state laser systems \\cite{dawson2008analysis}.\nAs a result, the development of DLA may lead to compact particle accelerators that enable new applications.\nBy providing the potential for generating relativistic electron beams in relatively short length scales, DLA technology is projected to have numerous applications where tabletop accelerators may be useful, including medical imaging, radiation therapy, and X-ray generation \\cite{plettner2008microstructure,england2014dielectric}.\n\nSeveral recently demonstrated candidate DLA structures consist of a planar dielectric structure that is periodic along the particle axis with either an semi-open geometry or a narrow (micron to sub-micron) vacuum gap in which the particles travel \\cite{plettner2006proposed, peralta2013demonstration, mcneur2016elements, leedle2015dielectric, chang_silicon_2014, breuer2014dielectric, breuer2014dielectric2, kozak2016dielectric}.\nThese structures are then side-illuminated by laser pulses.\n\\fig{DLA_def} shows a schematic of the setup, with a laser pulse incident from the bottom.\n\n\\figdef{DLA_definition.pdf}{DLA_def}{\n Diagram outlining the system setup for side-coupled DLA with an arbitrary die,lectric structure $\\eps(x,y)$ (green).\n A charged particle moves through the vacuum gap with speed $\\beta c_0$.\n The periodicity is set at $\\beta \\lambda$ where $\\lambda$ is the central wavelength of the laser pulse.\n}\n\nThe laser field may also be treated with a pulse front tilt \\cite{hebling1996derivation, akturk2004pulse} to enable group velocity matching over a distance greater than the laser's pulse length.\n\n\\section{Adjoint Method for Accelerator}\n\n\nTo achieve high energy gain in a compact size, it is of principle interest to design structures that may produce the largest acceleration gradients possible without exceeding their respective damage thresholds.\nHere we will discuss the use of the adjoint method and inverse design to design such a structure, as explained originally in Ref. \\citenum{hughes_method_2017}.\nTo begin, we must first define the optimization figure of merit and design parameters.\n\n\\subsection{Mathematical Definition}\n\nWe first seek to maximize the \\textit{acceleration gradient} of the device, which is defined as the amount of energy gain per unit length achieved by a particle that is phased correctly with the driving field.\nFor acceleration to occur, the dielectric structure must be designed such that the particle feels an electric field that is largely parallel to its trajectory over many optical periods.\nHere we consider framing an optimization problem to maximize the acceleration gradient, which take as our figure of merit (labelled $J$ in previous discussions).\nIn a general DLA device, the acceleration gradient `$G$' over a time period `$T$' is defined mathematically as\n%\n\\eqdef{Gintro}{\n G = \\frac{1}{T}\\int_0^{T}{ E_{||}(\\vr(t),t)\\ dt},\n}\n%\nwhere $\\vr(t)$ is the position of the electron over time and $E_{||}$ signifies the (real) electric field component parallel to the electron trajectory.\n\nSince we assume the structure is invariant in the $\\hat{z}$ direction, we may work in two dimensions, examining only the $H_z$, $E_x$ and $E_y$ field components.\nWhile this approximation neglects fringing fields that will be present in any fabricated device, it is a good approximation for the fields experienced by particles traversing the center of the acceleration channel.\nFor an approximately monochromatic input laser source with angular frequency $\\omega$, the electric fields are, in general, of the form\n%\n\\eqdef{}{\n \\vE(\\vr,t) = \\real{\\tE(\\vr)e^{i\\omega t}},\n}\nwhere $\\tE$ is complex-valued.\nIn the following chapter we discuss the generalization of this analysis to broadband light.\n\nLet us assume the particle we wish to accelerate is moving on the line $y=0$ with velocity $\\vec{v} = \\beta c_0 \\hat{x}$, where $c_0$ is the speed of light in vacuum and $\\beta \\leq 1$.\nThe $x$ position of the particle as a function of time is given by $x(t) = x_0 + \\beta c_0 t$, where $x_0$ represents an arbitrary choice of initial starting position.\nFor normal incidence of the laser (laser propagating in the $+\\hat{y}$ direction), phase velocity matching between the particle and the electromagnetic fields is established by introducing a spatial periodicity in our structure of period $\\beta \\lambda$ along $\\hat{x}$ , where $\\lambda$ is the laser wavelength.\nIn the limit of an infinitely long structure (or equivalently, $T \\to \\infty $) we may rewrite our expression for the gradient in Eq. (\\ref{eq:Gintro}) as an integral over one spatial period, given by\n%\n\\eqdef{}{\n G = \\frac{1}{\\beta\\lambda}\\real{ e^{-i\\phi_0}\\int_0^{\\beta\\lambda}{dx \\ }E_x(x,0)e^{i\\frac{2\\pi}{\\beta\\lambda}x}}.\n}\n%\nHere the quantity $\\phi_0 = \\frac{2\\pi x_0}{\\beta\\lambda}$ is representative of the phase of the particle as it enters the spatial period.\nIn further calculations, we set $\\phi_0 = 0$, only examining the acceleration gradients experienced by particles entering the accelerator with this specific phase.\nSince we have arbitrary control over our input laser phase, this does not impose any constraint on the acceleration gradient attainable.\n\nTo simplify the following derivations, we define the following inner product operation involving the integral over two vector quantities $\\va$ and $\\vb$ over a single period volume $V'$\n%\n\\eqdef{}{\n \\bracket{\\va}{\\vb} = \\int_{V'} dv\n \\left(\\va \\cdot \\vb \\right) = \\int_0^{\\beta\\lambda}dx\\int_{-\\infty}^\\infty dy \\left(\\va\\cdot\\vb\\right).\n}\n%\nWith this definition, we then may express the gradient simply as\n%\n\\eqdef{G}{\n G = \\real{\\bracket{\\vE}{\\veta}},\n}\n%\nwhere we define the vector field `$\\veta$' to signify the position and phase of the moving electron as\n\\eqdef{}{\n \\veta(x,y) = \\frac{1}{\\beta\\lambda}e^{i\\frac{2\\pi}{\\beta\\lambda}x}\\delta(y)\\hat{x}.\n}\nThe physical interpretation of $\\veta$ is digrammed in \\fig{eta_def}.\n\n\\figdef{DLA_eta_definition.png}{eta_def}{\n Definition of the vector field, $\\veta$, which defines the position of the electron in the frequency domain.\n The green regions represent domains where we will optimize the material properties using the adjoint method.\n The central gap is constrained to vacuum to allow passage of the electron beam.\n The red arrow signifies the driving laser.\n}\n\nOur goal in designing the accelerator for maximum acceleration gradient is to create a permittivity distribution that maximizes $G$ subject to a few constraints.\nWe assume geometry of the DLA structure is represented by a spatially varying dielectric constant $\\eps(x,y)$.\nAs mentioned, we assume invariance in one coordinate ($\\hat{z}$) in keeping with the planar symmetry of most current designs.\nHowever the methodology we present can be extended to include a third dimension.\nWe consider performing this optimization in a small design region surrounding a small gap defined for the electron to travel through the structure.\nSecondly, we assume that the structure has a finite extent along the direction of the incoming laser beam.\nWe also consider realizing this device through the patterning of a material with permittivity $\\eps_\\textrm{max}$.\nTherefore, the final device should have permittivity of either 1 or $\\eps_\\textrm{max}$ at all points.\n\nTo perform this optimization task, we discretize our entire spatial domain into a rectangular grid, which will be necessary for numerical simulation.\nWe define our design parameters, $\\bfphi$, as the relative permittivity of each grid cell within the design region.\nOur problem then becomes finding the permittivity of each cell that will maximize the acceleration gradient, subject to each grid cell having a permittivity value of either 1 or $\\eps_\\textrm{max}$.\n\nTo accomplish this, the most naive approach would involve performing a direct search over the full design space.\nFor example, one could label each cell within the design region with an identifier `0' or `1' corresponding to `vaccuum' and `material', respectively.\nThen, one would generate all possible structures and check their respective acceleration gradients.\nHowever, this method would be far too computationally expensive to perform in practice.\nFor example, even considering a very small design region consisting of 10 $\\times$ 10 = 100 grid cells would result in $2^{100} \\approx 10^{30}$ device simulations, which is far too many to realistically perform.\nWhile one may consider more efficient ways of searching through this device space without checking each structure, for example using global optimization approaches such as genetic algorithms \\cite{whitley_genetic_1994} or particle swarm optimization \\cite{noauthor_particle_nodate}, this problem is still quite computationally expensive and the size of design space becomes exponentially larger as the number of design parameters are increased.\n\nAs mentioned, a more effective approach involves performing $\\textit{gradient-based optimization}$, in which we search the design space according to the local gradient of the figure of merit with respect to each of the parameters.\nFor example, we may start with an initially random device, compute how the performance will change with respect to a change in the permittivity of each cell in the design region, and make a small update.\nThis process may be repeated until convergence on a locally optimal solution.\nIf the design space contains several local optima, then this whole process may be repeated several times with different initial conditions.\n\nFor gradient-based optimization to be useful, one would like an efficient means to compute the gradient of the figure of merit with respect to the design parameters.\nFor photonic devices, one may achieve this using the \\textit{adjoint method}, which allows one to analytically compute the gradient directly from Maxwell's Equations and evaluate the result with only one additional electromagnetic simulation.\nThis remarkable efficiency is largely responsible for the success of inverse design in photonics.\n\n\\subsection{Adjoint Formalism}\n\nThe adjoint method is typically introduced for linear optical systems, although, as we will show in a later chapter, it may be extended to nonlinear systems without much additional complication.\nIn the frequency domain, Maxwell's equations may be written as\n%\n\\eqdef{FDFD_analytical}{\n \\dcurl \\vE (\\vr)\\ -\\ k_0^2\\ \\eps_r(\\vr)\\ \\vE(\\vr) \\equiv A\\vE(\\vr) = -i\\mu_0\\omega\\vJ(\\vr),\n}\n%\nHere, $\\vE(\\vr)$ and $\\vJ(\\vr)$ are the electric field and electric current distributions, respectively. $k_0 = \\omega/c_0$, $\\eps_r$ is the relative permittivity and a non-magnetic material is assumed ($\\mu = \\mu_0$).\n\\eq{FDFD_analytical} can be solved with the \\textit{finite-difference frequency-domain} (FDFD) method \\cite{shin2012choice, taflove2000computational}, where both the structure and the fields are discretized on a finite-difference grid.\n\nMore abstractly, we may write \\eq{FDFD_analytical} as\n%\n\\eqdef{FDFD_simple}{\n A \\bfx = \\bfb,\n}\n%\nwhere $A$ is a sparse, complex symmetric matrix that encodes Maxwell's equations in the presence of the device.\n$\\bfx$ is a vector containing the electromagnetic fields at each position in the domain, which are the solution to \\eq{FDFD_simple} given the vector $\\bfb$ describing the electric current source distribution in the domain.\nWhen the number of grid points is small, \\eq{FDFD_simple} is typically solved using lower-upper (LU) decomposition techniques.\nHowever, in several cases, it must be solved using iterative methods instead \\cite{shin2012choice}.\n\nOur device is described by a set of design variables $\\bm{\\phi}$, which influence the system matrix, $A = A(\\bfphi)$.\nDifferentiating \\eq{FDFD_analytical} with respect to $\\bfphi$, and assuming that the current source, $\\bfb$, does not depend on $\\bfphi$, we may recover the change in the solution with respect to the parameters as\n%\n\\eqdef{dEdgamma}{\n \\ddfrac{\\bfx}{\\bfphi} = -\\invA \\pfrac{A}{\\bfphi} \\invA \\bfb = -\\invA \\pfrac{A}{\\bfphi}\\bfx\n}\n\nNow, we consider differentiating an objective function $J = J(\\bfx)$ that depends explicitly on the field solution.\nBy the chain rule, this gives\n%\n\\eqdef{dGdgamma_2}{\n \\ddfrac{J}{\\bfphi} =\n - \\real{ \\pfrac{J}{\\bfx} \\ddfrac{\\bfx}{\\bfphi} } = 2 \\real{ -\\pfrac{J}{\\bfx} A^{-1} \\pfrac{A}{\\bfphi} \\bfx }.\n}\nWe note that the factor of $2\\real{\\cdot}$ comes from the fact that $\\bfx$ is complex-valued, and therefore in taking the derivative of (real-valued) $J$, one must consider the dependence on both $\\bfx$ and $\\bfx^*$.\n\nTo evaluate \\eq{dGdgamma_2}, we define a second simulation with source term $-\\pfrac{J}{\\bfx}^T$,\n%\n\\eqdef{adjoint_source}{\n A^T\\bfx_\\aj = A\\bfx_\\aj = -\\pfrac{J}{\\bfx}^T,\n}\nwhere we have used the fact that $A$ is symmetric.\nThen, the field solution, $\\bfx_\\aj = -A^{-1}\\pfrac{J}{\\bfx}^T$, can be easily identified in \\eq{dGdgamma_2}, which gives the expression\n%\n\\eqdef{final_form_DGdgamma}{\n \\ddfrac{G}{\\bfphi} = 2 \\real{ \\bfx_\\aj^T \\pfrac{A}{\\bfphi} \\bfx }.\n}\n%\nThe only quantity in this expression that depends on the parameter $\\bfphi$ is $\\pfrac{A}{\\bfphi}$.\nAs we will soon discuss, this quantity will generally be trivial to compute.\nOn the other hand, the full field calculations of $\\bfx$ and $\\bfx_\\aj$ are computationally expensive, but may be computed once and used for an arbitrarily large set of parameters $\\bfphi_i$.\nThis gives the adjoint method a significant scaling advantage with respect to traditional direct sensitivity methods, such as the numerical, 'finite-difference' differentiation approach, in which each parameter is independently perturbed a small amount and the resulting change in objective function is measured.\n\nPreviously, we expressed the acceleration gradient as the inner product of the electric fields $\\vE(\\vr)$ and our vector field $\\veta(\\vr)$ as\n%\n\\eqdef{G2}{\n G = \\real{\\bracket{\\vE}{\\veta}},\n}\n%\nwhich we may express in matrix notation as\n%\n\\eqdef{G2}{\n G = \\real{\\bfeta^T \\bfx},\n}\n%\nwhere $\\bfeta$ is a vector representing $\\veta$ on the finite difference grid and $\\bfx$ is a vector containing the electric fields, as before.\n\nIn this notation, the adjoint problem is therefore\n%\n\\eqdef{adjoint_DLA}{\n A^T \\bfx_\\aj = -\\pfrac{G}{\\bfx}^T = -\\bfeta.\n}\n%\n\n\\subsection{Interpretation of the Adjoint Field as Radiation}\n\nIntuitively, the adjoint source, $-\\bfeta$, represents a line of electric current located at the central gap where the accelerator is traversing the structure.\nTo make this connection to radiation more explicit, let us now consider the fields radiated by a point particle of charge $q$ flowing through our domain at $y = 0$ with velocity $\\vec{v} = \\beta c_0 \\hat{x}$.\nIn the time domain, we can represent the current density of this particle as\n%\n\\eqdef{point-current-setup}{\n \\vJ_\\textrm{rad}(x,y;t) = q \\beta c_0 \\delta(x-x_0-c_0\\beta t)\\delta(y)\\hat{x}.\n}\n%\nTo express this in the frequency domain, we take the Fourier transform of $\\vJ_\\textrm{rad}$ with respect to time, giving\n%\n\\begin{align}\n \\vec{J}_{rad}(x,y;\\omega) &= q \\beta c_0 \\delta(y)\\hat{x}\\int _{-\\infty}^{\\infty}{dt\\ }\\exp(i\\omega t)\\delta(x-x_0-c_0\\beta t)\\\\\n &= q\\ \\exp\\Big(i\\frac{\\omega\\ (x-x_0)}{c_0 \\beta}\\Big)\\delta(y)\\hat{x}\\\\\n &= q\\ \\exp\\Big(i\\frac{2\\pi}{ \\beta\\lambda}x\\Big)\\ \\exp(-i\\phi_0)\\delta(y)\\hat{x}.\n\\label{eq:point-current}\n\\end{align}\n%\nComparing with the source of our adjoint problem, $\\vJ_\\aj = \\frac{-i}{\\omega\\mu_0}\\veta$, we see that \n%\n\\eqdef{J-eta}{\n \\vec{J}_{aj} = \\frac{-i\\ \\exp(i\\phi_0)}{2\\pi q\\beta c_0\\mu_0}\\vJ_\\textrm{rad}.\n}\n\nThis finding shows that the adjoint field solution ($\\vE_\\aj$) corresponds (up to a complex constant) to the field radiating from a test particle flowing through the accelerator structure.\nTo put this another way, in order to calculate the acceleration gradient sensitivity with the adjoint method, we must simulate the same structure operating both as an accelerator ($A\\vE=-i\\omega\\mu_0\\vJ_\\textrm{acc}$) and as a radiator ($A\\vE_\\aj=-i\\omega\\mu_0\\vJ_\\aj$).\n\nIt is understood that one way to create acceleration is to run a radiative process in reverse.\nIndeed, this is the working principle behind accelerator schemes such as inverse free electron lasers \\cite{musumeci2005high, courant1985high}, inverse Cherenkov accelerators \\cite{kimura1995laser, fontana1983high}, and inverse Smith-Purcell accelerators \\cite{bae1992experimental, mizuno1987experimental}.\nHere, we see that this relationship can be expressed in an elegant fashion using the adjoint method.\n\n\\subsection{Application to Design Parameters}\n\nTo test our adjoint formalism, we examine a simple accelerator geometry composed of two opposing dielectric squares each of relative permittivity $\\epsilon$.\nWe take a single $\\phi$ parameter to be the relative permittivity of the entire square region.\nBecause we only change the region inside the dielectric square, we may identify the $\\pfrac{A}{\\bfphi}$ operator from \\eq{FDFD_analytical} as\n%\n\\eqdef{dAdepsilon}{\n \\ddfrac{A}{\\epsilon}(\\vr) = \\Bigg\\{\n \\begin{array}{ll}\n -2k_0^2 &\\textrm{if } \\vr \\textrm{ in square} \\\\\n 0 &\\textrm{otherwise}\n \\end{array}.\n}\n\nThus, given the form of the sensitivity of the acceleration gradient from \\eq{final_form_DGdgamma}, combined with \\eq{dAdepsilon}, the change in acceleration gradient with respect to changing the entire square permittivity is simply given by the integral of the two field solutions over the square region, labeled `$sq$'\n%\n\\eqdef{}{\n \\ddfrac{G}{\\epsilon_{sq}} = -2k_0^2 \\ \\real{\\int_{sq}{d^2\\vr}.\n \\vE(\\vr) \\cdot \\vE_\\aj(\\vr)}.\n}\n\nIn Fig. \\fig{DLA_test} we compare this result with the direct sensitivity calculation where the system is manually changed and simulated again, using a finite difference derivative.\nThe two methods agree with excellent precision, which confirms that the adjoint formalism is giving the correct results.\n\n\\figdef{DLA_test}{DLA_test}{\n Demonstration of adjoint method in calculating accelerator sensitivities.\n (a) The acceleration gradient ($G$) of a square accelerator structure (inset) as a function of the square's relative permittivity.\n We express the acceleration gradient in its dimensionless form, normalized by the electric field amplitude of the incident plane wave $(E_0)$.\n The particle traverses along the dotted line with a velocity of $c_0$ ($\\beta = 1$) and a plane wave is incident from the bottom of the structure.\n (b) The sensitivity $\\ddfrac{G}{\\epsilon}$ of the gradient with respect to changing the square relative permittivity for direct central difference (solid line) $\\ddfrac{G}{\\epsilon} = \\frac{G(\\epsilon+\\Delta\\epsilon)-G(\\epsilon-\\Delta\\epsilon)}{2\\Delta\\epsilon}$ and using the adjoint method (circles).\n The two calculations agree with excellent precision.\n The dotted line at $\\ddfrac{G}{\\epsilon}=0$, corresponds to local minima and maxima of $G(\\epsilon)$ above.\n}\n\nExtending this example to the general case of perturbing the permittivity at an arbitrary position $\\vr$, we see that\n%\n\\begin{align}\n \\ddfrac{G}{\\epsilon}(\\vr) &= -k_0^2 \\ \\real{ \\int{d^2\\vr'}.\n \\vE(\\vr') \\cdot \\vE_\\aj(\\vr')~\n \\delta(\\vr-\\vr') } \\\\\n &= -2k_0^2 \\ \\real{ \\vE(\\vr) \\cdot \\vE_\\aj(\\vr) }.\n\\end{align}\n%\n\\section{Inverse Design of Accelerator}\n\n\\subsection{Maximization of Acceleration Gradient}\n\nWith the mathematical form of the adjoint problem discussed, now we focus on the optimization and inverse design of the DLA device.\nIn our FDFD simulation, we use a grid spacing that corresponds to 200 grid points per free space wavelength in each dimension.\nPerfectly matched layers are implemented as absorbing regions on the edges parallel to the electron trajectory, with periodic boundary conditions employed on boundaries perpendicular to the electron trajectory.\nA total-field scattered-field \\cite{taflove2000computational} formalism is used to create a perfect plane wave input for the acceleration mode.\n\nSince the adjoint method gives us a highly efficient method to calculate $\\ddfrac{G}{\\epsilon_{i}}$, we use this information in an iterative optimization procedure.\nDuring each iteration, we first calculate $\\ddfrac{G}{\\epsilon_{i}}$ for all pixels `$i$' within some specified design region.\nThen, we update the $\\epsilon_i$ of each grid cell as follows\n%\n\\eqdef{}{\n \\epsilon_{i} := \\epsilon_{i} + \\alpha\\ddfrac{G}{\\epsilon_{i}}.\n}\n%\nHere, $\\alpha$ is a step parameter that we can tune.\nWe need $\\alpha$ to be small enough to find local maxima, but large enough to have the optimization run in reasonable amount of time.\nThis process is repeated until convergence on $G$, as diagrammed in \\fig{opt_loop}.\n\n\\figdef{DLA_optimization_routine.png}{opt_loop}{Optimization routine for DLA.}\n\nDuring the course of optimization, the permittivity distribution is considered as a continuous variable, which is not realistic in physical devices.\nTo address this issue, we employ a permittivity capping scheme during optimization.\nWe define a maximum permittivity `$\\epsilon_m$' corresponding to a material of interest.\nDuring the iterative process, if the relative permittivity of any cell becomes either less than $1$ (vacuum) or greater than $\\epsilon_m$, that cell is pushed back into the acceptable range.\nIt was found that with this capping scheme, the structures converged to binary (each pixel being either vacuum or material with a permittivity of $\\epsilon_m$) after a number of iterations without specifying this choice of binary materials as a requirement of the optimization.\nTherefore, only minimal post-processing of the structures was required.\nSince high index contrast is favorable for maximizing the acceleration gradient, the optimization often favors increasing index contrast within the structure, which leads to each pixel being pushed towards either $1$ or $\\epsilon_m$.\nThis is a possible explanation for why the structures converge to binary distributions under our optimization procedure.\n\nThe results of this optimization scheme are shown in Figs. \\ref{fig:optimization-results_beta0.5}(b)-\\ref{fig:optimization-results_beta0.5}(d) for three different $\\epsilon_m$ values corresponding to commonly explored DLA materials.\nThe design region was taken to be a rectangle fully surrounding but not including the particle gap.\nThe design region was made smaller for higher index materials, since making it too large led to divergence during the iteration.\nWe found that a totally vacuum initial structure worked well for these optimizations.\nHowever, initially random values between 1 and $\\epsilon_m$ for each pixel within the design region also gave reasonable results.\nFor materials of Si, Si$_3$N$_4$, and SiO$_2$, the achieved gradients (normalized by the incident field, $E_0$) were 0.90, 0.56, and 0.31 ($E_0$), respectively.\nAssuming incident field values consistent with the laser damage thresholds given in Ref. \\cite{soong2012laser}, these correspond to acceleration gradients of 0.25, 0.83, and 1.33 $\\textrm{GV}\\,\\textrm{m}^{-1}$, respectively.\nWithout the dielectric mirrors, these structures give normalized acceleration gradients of 0.28, 0.15, and 0.07 ($E_0$), respectively.\nFor comparison, the Si dual pillar structures presented in Ref. \\cite{leedle2015dielectric} give gradients of around 0.3 $(E_0)$.\nTherefore, the adjoint optimized structures show about a three-fold improvement in acceleration gradient over established structures.\n\n\\figdef{DLA_Adjoint.png}{optimization-results_beta0.5}{\n Demonstration of the structure optimization for $\\beta=0.5$, laser wavelength $\\lambda=2\\,\\mu$m, and a gap size of $400$\\,nm.\n A plane wave is incident from the bottom in all cases.\n (a) Acceleration gradient as a function of iteration number for different maximum relative permittivity values, corresponding to those of Si, Si$_3$N$_4$, and SiO$_2$ at the laser wavelength.\n The acceleration gradient is normalized by the electric field amplitude of the incident plane wave $(E_0)$.\n The optimizations converge after about five-hundred iterations.\n (b-d) Final structure permittivity distributions (white = vacuum, black = $\\epsilon_m$) corresponding to the three curves in (a).\n Eight periods are shown, corresponding to four laser wavelengths.\n For each (b-d), design region widths on each side of the particle gap were given by $1$, $2$, and $4\\,\\mu$m for Si, Si$_3$N$_4$, and SiO$_2$, respectively.\n}\n\nThis optimization scheme seems to favor geometries consisting of a staggered array of field-reversing pillars surrounding the vacuum gap, which is already a popular geometry for DLA.\nHowever, these optimal designs also include reflective mirrors on either side of the pillar array, which suggests that for strictly higher acceleration gradients, it is useful to use dielectric mirrors to resonantly enhance the fields in the gap.\n\nIt was observed that for random initial starting permittivity distributions, the same structures as shown in \\fig{optimization-results_beta0.5} are generated every time.\nFurthermore, as shown in \\fig{DLA_sim}, the geometries found using this method are remarkably similar to those recently proposed through human design using physical intuition \\cite{ACHIP_meeting3}.\nThese findings together suggest that the proposed structures may be close to the globally optimal structure for maximizing $G$.\n\n\\figdef{DLA_Similarity.png}{DLA_sim}{Similarity between DLA structures designed using adjoint method (left) and those independently proposed using human intuition.}\n\nThere are several variants of gradient descent which speed up the optimization in most cases. ‘Momentum’ is one such technique in which the design parameters are updated not only from the gradient information at the current iteration, but also a weighted sum of previous gradients.\nIntuitively, this means if an optimization has been trending in a given direction, it will be more likely to continue in this direction, which can improve speed and stability.\nSpecifically, the momentum term term corresponds to the sensitivity calculated at the last iteration multiplied by a constant, $\\alpha' < 1$. For iteration number `$j$' and pixel `$i$' the update is defined as\n\n\\eqdef{}{\n \\epsilon_i^{ (j+1) } := \\epsilon_i^{ (j) } + \\alpha\\Bigg[ \\ddfrac{G}{\\epsilon_i}^{ (j) } + \\alpha'\\ddfrac{G}{\\epsilon_i}^{ (j-1) }\\Bigg].\n}\n\n\n\\subsection{Maximization of Acceleration Factor}\n\nDLAs are often driven with the highest input field possible before damage occurs.\nTherefore, another highly relevant quantity to maximize is the \\textit{acceleration factor}, given by the acceleration gradient divided by the maximum electric field amplitude in the system.\nThis quantity will ultimately limit the amount of acceleration gradient we can achieve when running at damage threshold.\nExplicitly, the acceleration factor is given by\n\n\\eqdef{}{\n f_{A} = \\frac{G}{\\max\\{|\\vec{E}|\\}}.\n}\n%\nHere, $|\\vec{E}|$ is a vector of electric field amplitudes in our system, which are normalized, as in the case of $G$, by the electric field amplitude of the incident plane wave ($E_0$).\nThe $\\max\\{\\}$ function is designed to pick out the highest value of this vector in either our design or material region, depending on the context.\nThe \\textit{design region} is defined as the total region outside of the particle gap where the permittivity is updated.\nThe \\textit{material region} is defined as any region where the permittivity is equal to $\\epsilon_m$.\nWe would like to use the same basic formalism to maximize $f_{A}$.\nHowever, since the $\\max\\{\\}$ function is not differentiable, this is not possible directly.\nInstead we may use a `smooth-max' function to approximate $\\max\\{\\}$ as a weighted sum of vector components\n%\n\\eqdef{}{\n \\max\\{|\\vec{E}|\\} \\approx \\frac{\\sum_i |\\vec{E}_i| \\ \\textrm{exp}\\big({a|\\vec{E}_i|}\\big)} {\\sum_i \\textrm{exp}\\big({a|\\vec{E}_i|}\\big)}.\n}\n%\nHere, the parameter $a \\geq 0$ controls the relative strength of the exponential sum terms, for $a = 0$, this function simply gives the average value of the field amplitudes.\nBy sweeping $a$ and examining the acceleration factors of the resulting optimized structures, we determined that $a = 3$ gave the best improvement in $f_A$.\nIf $a$ is too large, the calculation may induce floating point overflow or rounding error issues.\n\n\nUsing this smooth-max function, one may calculate $\\ddfrac{f_{A}}{\\epsilon_i}$ analytically and perform structure optimizations in the same way that was discussed previously.\nTwo structures with identical parameters but optimized, respectively, for maximum $G$ and $f_A$ are shown in Fig. \\ref{fig:optimization-results_fAC}.\nOn the left, we see that the $G$ maximized structure shows the characteristic dielectric mirrors, giving resonant field enhancement.\nOn the right is the structure optimized for $f_A$, which has eliminated most of its dielectric mirrors and also introduces interesting pillar shapes.\nIn Table \\ref{tb:table} the main DLA performance quantities of interest are compared between these two structures.\nWhereas the acceleration gradient is greatly reduced when maximizing for $f_A$, the $f_A$ value itself is improved by about 25\\% or 23\\% depending on whether one measures the maximum field in the design region or the material region, respectively.\nAs a comparison with the geometry from Ref. \\cite{leedle2015dielectric}, a SiO$_2$ dual pillar structure with a 400 nm gap was optimized for acceleration gradient, giving an acceleration gradient of 0.025 ($E_0$) with a pillar radius of 670 nm.\nThis structure was found to have $\\max\\{|\\vec{E}|\\}$ in the design region of 1.612 ($E_0$) and $\\max\\{|\\vec{E}|\\}$ in the material region of 1.209 ($E_0$), leading to acceleration factors of 0.016 and 0.021, respectively.\nComparing these numbers to those in Table \\ref{tb:table}, it is apparent that the optimized structures perform better than the dual pillar structures in terms of both gradient and acceleration factor.\n\nThese findings suggest that the inverse design strategy is effective in designing not only resonant, high acceleration gradient structures, but also non-resonant structures that are more damage resistant.\nIn the future, when more components of DLA are moved on-chip (such as the optical power delivery), it will be important to have control over the resonance characteristics of the DLA structures to prevent damage breakdown at the input facet.\nOur technique may be invaluable in designing structures with tailor-made quality factors for this application.\n\n\\figdef{DLA_Adjoint_fA}{optimization-results_fAC}{\n Demonstration of the final structures after optimization for (a) maximizing gradient only, (b) maximizing the acceleration factor.\n $\\beta = 0.5$, laser wavelength $\\lambda=2\\,\\mu$m, gap size of $400$\\,nm.\n $\\epsilon_m = 2.1$, corresponding to SiO$_2$.\n In (a), the high gradients are achieved using reflective dielectric mirrors to confine and enhance the fields in the center region.\n In (b), these dielectric mirrors are removed and the pillar structures are augmented.\n The structure in (b) shows a 23\\% increase in the acceleration factor in the material region when compared to (a).\n}\n\n\\begin{table}[ht!]\n\\centering\n\\caption{Acceleration factor ($f_A$) before and after maximization.}\n\\begin{tabular}{lccc}\n\\hline\nQuantity & Value (max $G$) & Value (max $f_A$) & Chang.\n\\\\ \\hline\nGradient ($E_0$) & 0.1774 & 0.0970 & -45.32\\%\\\\ \n$\\max\\{|\\vec{E}|\\}$ in design region ($E_0$) & 4.1263 & 1.7940 & -56.52\\%\\\\ \n$\\max\\{|\\vec{E}|\\}$ in material region ($E_0$) & 2.7923 & 1.2385 & -55.84\\% \\\\ \n$f_A$ in design region & 0.0430 & 0.0541 & +25.81\\% \\\\\n$f_A$ in material region & 0.0635 & 0.0783 & +23.31\\% \\\\ \\hline\n\\end{tabular}\n\\label{tb:table}\n\\end{table}\n\n\\section{Conclusions}\n\n%1. Major findings\nWe found that the adjoint method is a reliable method for optimizing DLA structures for both maximum acceleration gradient and also acceleration factor.\nThe optimization algorithm discussed shows good convergence and rarely requires further post-processing of structures to create binary permittivity distributions.\nTherefore, it is a simple and effective method for designing DLAs.\n%2. What is new and novel\nWhereas most structure optimization in this field uses parameter sweeps to search the design space, the efficiency of our method allows us to more intelligently find optimal geometries without shape parameterization.\nFurthermore, the structures that we design are fabricable.\n\n%3. How does it compare with literature?\nAlthough no DLA structures have been tested at the proposed wavelength of $2\\, \\mu$m, both simulations \\cite{plettner2006proposed} and experimental results from other wavelengths \\cite{leedle2015dielectric} show gradients far below those presented here.\n%4. What are the limitations?\nWe had limited success designing DLA structures in the regime of $\\beta > 1 / n$, where $n$ is the refractive index of the DLA structure. In this regime, the electron is moving faster than the speed of light in the material region, which leads to stronger coupling between the electron beam and incident plane wave. This fact causes optimizations that are more unstable and do not converge on the same structure for several starting parameters.\n\nIn addition to the side-incident geometry explored, this technique is applicable to designing other dielectric-based accelerator structures.\nThis includes particle-laser co-propagating schemes \\cite{cowan2008three} and dielectric wakefield acceleration\n\\cite{zhang1997stimulated}, among others.\nTherefore, we expect that our results may find use in the larger advanced accelerator community.\n\nIn this chapter, we have introduced the adjoint variable method as a powerful tool for designing dielectric laser accelerators for high gradient acceleration and high acceleration factor.\nWe have further shown that the adjoint simulation is sourced by a point charge flowing through the accelerator, which quantifies the reciprocal relationship between an accelerator and a radiator.\n\nOptimization algorithms built on this approach allow us to search a substantially larger design space and generate structures that give acceleration gradients far above those normally used for each material.\nFurthermore, the structures designed by adjoint are fundamentally not constrained by shape parameterization, allowing never-before-seen geometries to be generated and tested.\nThis theme will continue to be explored in other chapters.\n", "meta": {"hexsha": "824fd6f0ec296d3fcb0f8495bf371fdd27441e59", "size": 36584, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "chapters/2_ACHIP_adjoint.tex", "max_stars_repo_name": "twhughes/PhD_Thesis", "max_stars_repo_head_hexsha": "4cacb47a5238c881bb21dd9d336318635545bdd4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-11-06T13:39:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-20T05:40:24.000Z", "max_issues_repo_path": "chapters/2_ACHIP_adjoint.tex", "max_issues_repo_name": "twhughes/PhD_Thesis", "max_issues_repo_head_hexsha": "4cacb47a5238c881bb21dd9d336318635545bdd4", "max_issues_repo_licenses": ["MIT"], "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/2_ACHIP_adjoint.tex", "max_forks_repo_name": "twhughes/PhD_Thesis", "max_forks_repo_head_hexsha": "4cacb47a5238c881bb21dd9d336318635545bdd4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2019-10-17T01:00:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T21:22:34.000Z", "avg_line_length": 81.6607142857, "max_line_length": 446, "alphanum_fraction": 0.7752842773, "num_tokens": 8833, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.19958119293562745}}
{"text": "% Neutrino physics\n% Target length: 30 pages\n\n\\chapter{Neutrino Physics}\\label{chap:NeutrinoPhysics}\n\nNeutrino physics will be discussed! \\\\\n\\\\\n-- Theory\\\\\n-- Experiments\\\\\n-- Future Experiments\\\\\n\\\\\nIt may make sense to discuss the experiments as we go along...\\\\\n\\\\\nI think the chapter will work best with both past, present and future woven together.\\\\\nAnd no distinct separation between theory and experiment (this is an experimental thesis after all...).\\\\\nCan discuss the `neutrino problems' to motivate the theory of neutrino oscillations, and include the SNO and Kamiokande results within.\\\\\nThen something similar with mass.\\\\\nAnd as we get onto unanswered questions, can weave the propsed experiments into this.\\\\\nI feel a section on the technology and concept of LAr TPCs will fit nicely into this setup.\\\\\n\n%----------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n\\section{Neutrino Theory}\\label{sec:NeutrinoTheory}\n\n\\subsection{Neutrino Oscillations}\\label{sec:NeutrinoOscillations}\n\nDerive 2-flavour case.\\\\\nExtend to 3 flavour.\\\\\nDiscuss CP violation.\\\\\n\n\\subsection{Neutrino Mass}\\label{sec:NeutrinoMass}\n\nMass hierarchy.\\\\\nAbsolute mass.\\\\\n\n\n%----------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n\\section{Future Neutrino Experiments}\\label{sec:FutureNeutrinoExperiments}\n\n%----------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n\\section{The LAr TPC Concept}\\label{sec:LArTPC}\n\nThe use of a liquid argon time projection chamber (LArTPC) as a high-precision fine-grained detector medium holds much promise for the successful resolution of the open questions in neutrino physics. A great amount of R\\&D work has taken place to advance the maturity of the technology and pioneering experiments, such as ICARUS \\cite{ICARUS2004}, have further increased the understanding of the neutrino community of the detector techniques. Past and currently running experiments at Fermilab, such as ArgoNeuT [], LArIAT [] and MicroBooNE [], are successfully using LArTPCs to take and analyse data and it seems certain to be the future of neutrino physics in the U.S.\n\nThis section will provide a brief history of LArTPC technology and motivate its potential when used in a huge experiment such as DUNE. The basic operation of such a detector will also be described to provide background for discussion of the DUNE and 35t experiments, and of reconstruction in LArTPCs, in future chapters.\n\n\\subsection{A Brief History of Time (Projection Chambers)}\\label{sec:LArTPCHistory}\n\nThe use of a time projection chamber as a potential particle detector was put forward by David Nygren in 1974 \\cite{Nygren1974}. He envisioned bubble-chamber quality data but with the possiblity of digital readout of the data, fascilitating extremely fine spatial resolution, good timing resolution and fast recovery after triggering. The basic concept is a drift chamber containing a noble gas placed within a field to drift ionisation electrons created by a propagating particle towards a multielectron array. This setup allows full three-dimensional reconstruction by combining information from the two-dimensional readout plane with the drift time. Nygren also included a magnetic field to assist particle identification in his design, shown in Fig. \\ref{fig:NygrenTPC}.\n\n\\begin{figure}[ht]\n \\centering\n \\includegraphics[width=10cm]{NygrenTPC.png}\n \\caption{The original concept of the time projection chamber particle detector, drawn by David Nygren in 1974 \\cite{Nygren1974}.}\n \\label{fig:NygrenTPC}\n\\end{figure}\n\nThe extension of this concept to a liquid argon TPC and it potential as a high-precision fine-grained detector medium in neutrino physics was proposed by Carlo Rubbia in 1977 \\cite{Rubbia1977}. The use of a noble liquid rather than gas is necessary in neutrino experiments to provide a high enough target mass to increase the probability of a neutrino interaction. Noble liquids have high electron mobility and low diffusion, favourable properties as the detection of particles is from the ionisation and scintillation light created by the particles. Given the necessity of a high electric field in order to drift these electrons to the readout places, excellent dielectric properties are also required; noble liquids possess such qualities. The properties of liquid argon which make it almost perfect for this use are demonstrated in the table in Table \\ref{tab:NobleProperties}.\n\n\\begin{table}[ht]\n \\caption{Properties of noble elements relevant when considering a TPC medium for a neutrino experiment.}\n \\label{tab:NobleProperties}\n \\centering\n \\begin{tabular}{ m{5cm} || m{1.5cm} | m{1.5cm} | m{1.5cm} | m{1.5cm} | m{1.5cm} | m{1.5cm} }\n & Water & He & Ne & \\color{red} Ar & Kr & Xe \\\\\n \\hline\\hline\n Boiling point [K] @ 1 atm & 373 & 4.2 & 27.1 & \\color{red} 87.3 & 120.0 & 165.0 \\\\\n \\hline\n Density [g/cm$^3$] & 1 & 0.125 & 1.2 & \\color{red} 1.4 & 2.4 & 3.0 \\\\\n \\hline\n Radiation length [cm] & 36.1 & 755.2 & 24.0 & \\color{red} 14.0 & 4.9 & 2.8 \\\\\n \\hline\n Scintillation [$\\gamma$/MeV] & - & 19 000 & 30 000 & \\color{red} 40 000 & 25 000 & 42 000 \\\\\n \\hline\n dE/dx [MeV/cm] & 1.9 & & 1.4 & \\color{red} 2.1 & 3.0 & 3.8 \\\\\n \\hline\n Scintillation $\\lambda$ [nm] & & 80 & 78 & \\color{red} 128 & 150 & 175 \\\\\n \\hline\n Natural abundance (Earth atm) [ppm] & & 5.2 & 18.2 & \\color{red} 9340.0 & 1.10 & 0.09 \\\\\n \\hline\n Electron mobility [cm$^2$/Vs] & & low & low & \\color{red} 400 & 1200 & 2200 \\\\\n \\hline\\hline\n \\end{tabular}\n\\end{table}\n\nAn additional advantage of this technology is the low threshold for detection; this is set by the ionisation threshold of liquid argon and is only $23.6 \\pm 0.5$ eV []. Rubbia realised that a LArTPC could be the digital replacement for the high quality particle detection methods used in bubble chambers, very common in neutrino physics in the 1970s. He proposed the first LArTPC detector design, shown in Fig. \\ref{fig:RubbiaLArTPC}, which bears a striking resemblense to the LArTPC used in experiments today.\n\n\\begin{figure}[ht]\n \\centering\n \\includegraphics[width=10cm]{RubbiaLArTPC.png}\n \\caption{The LArTPC detector proposed by Carlo Rubbia in 1977 \\cite{Rubbia1977}.}\n \\label{fig:RubbiaLArTPC}\n\\end{figure}\n\nConstructing and operating such a detector was beyond the technology of the time, and is still being understood today. The operation of a LArTPC detector and the challenges associated with this are the subject of section \\ref{sec:LArTPCOperation}.\n\n\\subsection{LAr TPC Operation}\\label{sec:LArTPCOperation}\n\nexplain how they work\n\nnew subsubsection\n\n[FIND OR MAKE A FIGURE TO GO WITH THE FOLLOWING DESCRIPTION...]\n\nA LArTPC typically consists of a single, or multiple anode and cathode, at either end of an active drift region. An ionising particle passing through a LArTPC causes electrons to become free from argon atoms and, in the presence of a field, drift towards an anode where they are read out.\n\nThe readout consists of multiple wires planes with different orientations to facilitate the reconstruction. The wires are either `induction' wires, which allow the electrons to deposit charge but continue past, or `collection' wires, on which the electric field lines end and all the charge on the electron is collected. Each wire plane is therefore held at a different `bias voltage' to prevent any field lines ending on the induction wire, thus creating local electric fields which promote the continuing forward motion of the electrons. The signal seen is therefore dependent on the type of wire plane; a bipolar pulse on an induction plane wire and unipolar on a collection plane wire. It is also common, though not essential, to make use of a `grid plane' upstream of the signal planes in order to shield them from the electron charge until they are close. Without such a plane, the bipolar pulse would be highly asymmetric, though would still have zero integral. It also makes changing the drift voltage (controlling the electric field) slightly easier as the signal planes are somewhat shielded from its effects. MicroBooNE does not operate with a grid plane and, although the 35t and the DUNE reference design make use of a grid plane, it is uncertain whether the benefit outweighs the cost for a huge LArTPC detector such as the DUNE far detector. It is worth mentioning alternative readout possibilities have been suggested but, given the scale of future LArTPCs, it is highly unlikely a viable solution which delivers superior readout at a comparable cost will be found.\n\n\nGiven the positive ions that are left in the medium, there is the possibility of recombination at a later time and therefore a loss of information about the initial interaction.\n\n\nThis is however accompanied by a flash of scintillation light which is hugely useful as a means of determining the event `start time' ($t_0$); without this information it would be impossible to place an absolute time scale on the interaction and we would therefore not be able to resolve the coordinate along the drift direction. The magnitude of the electric field applied is the key to both processes and there is thus a compromise which must be struck in order to preserve as much information as possible. The graph in Fig. \\ref{fig:ElectricFieldScintillationIonisation} demonstrates this; a field of $500$ V/cm is often chosen in current LAr neutrino experiments.\n\n\\begin{figure}[ht]\n \\centering\n \\includegraphics[width=12cm]{ElectricFieldScintillationIonisation.png}\n \\caption{Demonstration of the competing effect the electric field has on the luminosity of the ionisation electrons and scintillation light arriving at the detector readout. Since both are essential in reconstructing the complete interactions, a balance must be found. [PLACEHOLDER IMAGE].}\n \\label{fig:ElectronFieldScintiallationIonisation}\n\\end{figure}\n\nA cathode is held at a high voltage\n\n\n\nFlesh this stuff out...\n\n\nU plane, V plane and collection all held at different fields. Slightly increasing in order to promote forward motion of the electrons. V held at 0V because it's cheaper (don't need crazy voltages, just some negative (still quite high, ~100V), 0V and some positive.\nGrid plane (also held at potential) is to sheild the APAs from the electrons until they are close. Not needed, but if not present then pulse wouldn't be very bipolar! The charge in both portions will still equate but the leading end will be muchhhh longer. All electric field lines (generated from movement of electrons) end on the cathode; don't want them to end on the induction wires (hence making sure the field increases). We want them to end on the collection planes, which collects the charge. Signal shaping time (along with gain, the two front-end ASIC parameters) is to let the charge leave the wire before being hit again (or something like this!). Deconvolution I still need to understand...\n\n\nIn 35t, we have FE ASICs which are the very front end and apply the signal shaping and gain. Have regulators to control the power these receive (these are noisy...). Also ADC ASICs to do digitisation in the cold. MicroBooNE don't do this, this just have the front end and do everything else in the warm. FE ASICs are the problem, same for uBooNE and 35t. ADC ASIC has stuck code problem.\n", "meta": {"hexsha": "5cabfd3d408cc189b9a05b71800162661681bcf9", "size": 11632, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "old/NeutrinoPhysics/NeutrinoPhysics.tex", "max_stars_repo_name": "mike-wallbank/thesis", "max_stars_repo_head_hexsha": "ebd856669d3ec628c8e4f025ee4196845d9282b7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-09-11T11:07:09.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-11T11:07:09.000Z", "max_issues_repo_path": "old/NeutrinoPhysics/NeutrinoPhysics.tex", "max_issues_repo_name": "mike-wallbank/thesis", "max_issues_repo_head_hexsha": "ebd856669d3ec628c8e4f025ee4196845d9282b7", "max_issues_repo_licenses": ["MIT"], "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/NeutrinoPhysics/NeutrinoPhysics.tex", "max_forks_repo_name": "mike-wallbank/thesis", "max_forks_repo_head_hexsha": "ebd856669d3ec628c8e4f025ee4196845d9282b7", "max_forks_repo_licenses": ["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.4586466165, "max_line_length": 1589, "alphanum_fraction": 0.7389099037, "num_tokens": 2828, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.19953807839114812}}
{"text": "\\section{Introduction}\n\nAge is one of the most elusive stellar parameters, particularly for stars on\nthe main sequence.\nIsochrone fitting methods suffer from poor precision, especially when only\nphotometric information is available, and asteroseismology is limited to a\nsmall sample of bright \\kepler\\ short cadence targets.\nStellar rotation is often used to infer ages via gyrochronology, however it\nremains relatively untested at old ages due to the sparsity of precise data.\nThe data in hand tell an intriguing story: they indicate that magnetic braking\nmay cease altogether for old, slowly rotating stars.\nHere we investigate another dating method: galactic kinematics.\n\nObservations of stars with a range of ages reveal that older stars have\ngreater velocity dispersions than younger stars \\citep[\\eg][]{casagrande2011,\naumer2011}\n% Aumer M., Binney J. J., 2011, MNRAS, 397, 1286\n% Casagrande L., Scho ̈nrich R., Asplund M., Cassisi S., Ram ́ırez I., Mele ́ndez\rJ., Bensby T.,\n% Feltzing S., 2011, A&A, 530, A138\nWe calculate the dispersion in vertical action for Gaia DR1 targets in the\n\\kepler\\ field.\nAlthough expected to be a weak tracer of age, vertical action dispersion\nshould be an accurate one as the underlying physical processes are relatively\nsimple and well understood.\nWe test the potential of vertical action dispersion as a clock, by comparing\nage predictions to asteroseismic ages.\nUsing the rotation periods of \\kepler\\ stars we also test the gyrochronology\nrelations: does magnetic braking cease at late ages?\n\nThe processes behind the formation of the galaxy and the formation of\nexoplanets are two complex topics in astrophysics connected by a common theme:\nstellar ages.\nMain sequence (MS) stars comprise the majority of our galaxy but unfortunately\ntheir ages are notoriously difficult to measure \\citep[see][for a\nreview]{Soderblom2010}.\nTheir positions on the HR diagram don't change significantly during their\nhydrogen burning lifetimes, a fact that is convenient for life on Earth but\ninconvenient for galactic archaeologists.\nNow, due to the abundance of rotation periods for MS stars provided by Kepler\nand to-be provided by TESS, LSST and Wfirst, rotation-dating has the potential\nto be the most readily available precise method for inferring stellar ages.\nRotation-dating works well for young stars but its accuracy is questionable\nfor stars older than the Sun: old \\kepler\\ asteroseismic stars rotate more\nrapidly than expected given their age \\citep{Angus2015, Vansaders2016,\nMetcalfe2016}.\n\\citet{Vansaders2016} attribute this to an evolving magnetic dynamo: as stars\nreach an critical Rossby number (the ratio of rotation period to the\nconvective overturn timescale), their magnetic field `switches off' and stars\nmaintain a constant rotation period after that time.\nThe data sets typically used to test the age-rotation relations are highly\nheterogeneous and each set has its own detection and selection biases.\nFor example, asteroseismology favours quiet stars whereas rotation periods are\neasiest to measure for active stars.\nHere, we test the age-rotation relations by comparing rotational (gyrochronal)\nage with dynamical age.\nData from the first \\Gaia\\ data release (DR1) provides kinematic ages for\nseveral MS \\Kepler\\ stars with detectable rotation periods.\nWe use these kinematic ages to test the gyrochronology relations at all ages.\n% We use the vertical action-age relation for red giants to test the\n% vertical action-age relation for MS stars.\n\n% A history of rotation-dating.\n\\subsection{The status of gyrochronology}\nThe phenomenon of magnetic braking in MS stars was first observed almost fifty\nyears ago by \\citet{Skumanich1972} who noticed that the rotation periods of\nthe Sun and young cluster stars decayed with the square-root of time.\n% Later, a mass-dependence was added to the relation between age and rotation\n% period --- less massive stars lose angular momentum faster than more massive\n% one.\n\\citet{Kawaler1988} derived a formalism for this angular momentum loss.\n % and his\n% relation depended on the mass loss rate, the ....\nMore recently, \\citet{Barnes2003} demonstrated that a simple relation could be\nused to describe `gyrochronology', the method of rotation-dating, and further\nworks \\citep[\\eg][]{Barnes2007, Mamajek2008, Barnes2010, Meibom2011},\ndemonstrated that the relation between rotation period and age holds true\nwhile theorists \\citep[\\eg][]{Matt2012, Epstein2014, Vansaders2013,\nVansaders2015} modify and extend physical models that reproduce the\nobservations.\n\nAs discussed above, the performance of the age-rotation relations for old\nstars was recently called into question \\citep{Angus2015, Vansaders2016,\nMetcalfe2016}.\nA simple straight-line model for rotational age does not reproduce the ages\npredicted by asteroseismology for stars older than the Sun.\nThis phenomenon is attributed to a transitioning magnetic dynamo at a critical\nRossby number, $Ro$, of 2.6, the solar value \\citep{Vansaders2016}.\nAs rotation periods slow, $Ro$ decreases until it hits the critical value and\nmagnetic braking switches off: stars maintain their rotation period from that\npoint onward.\nThis restricts the applicability of gyrochronology to young, rapidly rotating\nstars only.\nThis hypothesis is supported by the existing data, however these data are\nsparse~---~the analyses demonstrating the discrepancies were conducted on the\nsmall number of main sequence, Solar-like oscillators observed by Kepler in\nshort cadence mode with detectable rotation periods: a sample size of around\n20.\n% Furthermore, asteroseismology favors stars with low surface gravities since\n% they show the largest amplitudes of oscillation and the majority of stars in\n% this sample were slightly evolved.\nA larger sample of old main sequence stars with precise ages is required to\nconfirm and further characterize the Rossby saturation mechanism introduced by\n\\citep{Vansaders2016}.\nHowever, old main sequence stars are difficult to age-date with any other\nmethod than asteroseismology.\nWe use the age gradients in the kinematic properties of stars to investigate\nthe \\citet{Vansaders2016} model.\n\n\\subsection{Kinematic ages}\nThe age-velocity dispersion relations are based on relatively simple physics.\nThere is evidence to suggest that stars in the Milky Way form in the thin disc\nof the galaxy with relatively small vertical velocities and angular momenta\n\\racomment{add citations}.\nAs time passes these stars are scattered via close encounters with other\nstars and interactions with galactic spiral arms.\nThe more time passes, the more scattering events, and stars slowly accumulate\nangular momentum in the vertical direction, known as vertical action.\nThis results in a slow heating of stellar orbits.\nOlder stars can be identified in Gaia DR1 by integrating their orbits in the\npotential of the Milky Way to convert their proper motions, positions and\nparallaxes into vertical actions.\nIt is the {\\it dispersion} in vertical action that truly traces age, far\nbetter than vertical action itself.\nHowever for single stars only the individual's vertical action is available.\nNonetheless, $J_z^2$ increases over time for any given star, and is a weak\ntracer of age.\n", "meta": {"hexsha": "bbd91907e1a062dc3410a8f73f8105f526f4031e", "size": 7224, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "paper/intro.tex", "max_stars_repo_name": "RuthAngus/gauge", "max_stars_repo_head_hexsha": "110cb96830d230367f8d57fe9f0139e9be1f2920", "max_stars_repo_licenses": ["MIT"], "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.tex", "max_issues_repo_name": "RuthAngus/gauge", "max_issues_repo_head_hexsha": "110cb96830d230367f8d57fe9f0139e9be1f2920", "max_issues_repo_licenses": ["MIT"], "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.tex", "max_forks_repo_name": "RuthAngus/gauge", "max_forks_repo_head_hexsha": "110cb96830d230367f8d57fe9f0139e9be1f2920", "max_forks_repo_licenses": ["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.8818897638, "max_line_length": 96, "alphanum_fraction": 0.8113233666, "num_tokens": 1646, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.19953807839114812}}
{"text": "\\chapter{Firms}\n\\label{chap:firms}\n\\index{Firms%\n@\\emph{Firms}}%\n\n\n\n\\section{Firms}\n\nThere at least one representative firm for each production industry. Most industries will have a both corporate and non-corporate firms. Corporate firms may be as many as three - with a domestic corporation, a multi-national parent corporation, and a multi-national subsidiary corporation (the follows the structure of the CORTAX model in terms of the types of corporations). However, for computational and calibration issues, we will simplify and have just a single multinational corporation for each production industry. The extent of overseas operations will be a an element of calibration - therefore the degree to which each industries firm is multinational will vary across industry. \n\nThe costs of making this simplification is that it would be more difficult to handle legislation about corporate inversion (but even that isn't handled well in the CORTAX structure). It also makes it more difficult to do multi-country interactions of tax policy, which is what CORTAX is designed for. I think out other features, such as a diverse set of industries and corporate and non-corporate firms, are more relevant for US tax policy and are difficult to fit in the CORTAX framework due to computational and calibration issues.\n\nWe start by describing a fully domestic corporate firm and it's optimal investment, employment, and financial policies. We then add the international components that describe the multinational nature of this firm. Next, we discuss the problem of the non-corporate firm. The functional forms describing the technologies and constraints of the firms are the same across industry, but the parameter values (of both the policy variant and policy invariant) parameters may vary across sector. In the notation below, we drop the industry subscripts for clarify of exposition.\n\n\\section{The Problem of the Domestic Corporation}\n\nThe objective of the firm is to maximize firm value. Firms do this by choosing investment and labor demand, as well as financial policies such as new equity issues, dividend distributions, and borrowing. There are a total of six endogenous variables in the domestic corporation's problem: investment demand ($I$), demand of effective labor units ($EL$), the stock of corporate debt ($B$), the amount of new equity issues ($VN$), dividend distributions, $DIV$, and the price of output ($p$). The firm makes choices over the first five of these variables. The last is determined by an assumption about market structure. In particular, we assume that firms have a decreasing returns to scale production function and thus realize economic profits. \\textcolor{red}{We pin down the price of output by assuming that there is free entry into the market. Thus, firms must set price at marginal cost. With a decreasing returns to scale function, such a price still produces economic profits. This condition then provides the final equation to identify our six exogenous variables.} \n\n\n\n\\textcolor{red}{One issue to be resolved is how we handle differential returns on equity across industry and corporate/non-corporate status. For example, the returns to some firms might differ because they have more overseas profits and/or more ability to shift income overseas to avoid US taxation.}\n\n\\subsection{The Value of the Firm}\n\nThe household's portfolio problem described in Section \\ref{sec:portfolio} allows for differential returns on debt and equity. It also makes clear that after tax returns differ across savers as they face different tax treatment. In the formulation of the value of the firm, we use the tax rate on the marginal investor. \\textcolor{red}{It is an open question as to who this investor is, but we will take it to be the domestic investor with the median amount of savings.} Noting that all individual level tax rates represent those on this marginal investor, we can derive the value of the firm in period $t$, $V_{t}$ in the following way. The after-tax return on firm equity in period $t$ is given by:\n\n\\begin{equation}\n\\label{eqn:equity_return}\nr_{e,t} = \\frac{(1-\\tau^{d}_{t})DIV_{t}+(1-\\tau^{g}_{t})(V_{t+1}-V_{t}-VN_{t})}{V_{t}},\n\\end{equation} \n\n\\noindent\\noindent where $VN_{t}$ are new equity issues in period $t$ (that dilute the value of period $t$ shareholders) and $DIV_{t}$ are dividends distributed in period $t$. The policy parameters $\\tau^{d}_{t}$ and $\\tau^{g}$ are the period $t$ marginal tax rates on dividends and capital gains for the marginal investor.\n\n\\subsubsection{An aside on after-tax rates of return}\n\n\\textcolor{red}{Note that the notation for the return on equity differs from that in Section \\ref{sec:portfolio}, where $r_{e,t}$ is the before tax return. In the current section, $r_{e,t}$ denotes the after-tax return for the marginal investor. To the after-tax return for all investors, we have two options. First, we can use the decision rules of firms (which imply dividend distributions an firm value) to find the pre-tax rate of return, call it $r^{pre}_{e,t}$:}\n\n\\begin{equation}\nr^{pre}_{e,t}=\\frac{DIV_{t}+V_{t+1}-V_{t}-VN_{t}}{V_{t}},\n\\end{equation}\n\n\\noindent\\noindent \\textcolor{red}{We then define the gross, after-tax return for a individual of lifetime income group $j$, age $s$, in period $t$ as in Section \\ref{sec:portfolio}: $\\rho_{e,s,j,t}=(1+r^{pre}_{e,t}(1-\\tau^{cap}(y_{j,s,t})))$.}\n\n\\textcolor{red}{A second way to do this would be to use the firms decision rules to find the after tax return for each investor:}\n\n\\begin{equation}\nr_{e,j,s,t} = \\frac{(1-\\tau^{d}_{j,s,t})DIV_{t}+(1-\\tau^{g}_{j,s,t})(V_{t+1}-V_{t}-VN_{t})}{V_{t}},\n\\end{equation} \n\n\\noindent\\noindent \\textcolor{red}{where the gross, after-tax return would be described by $\\rho_{e,s,j,t}=1+r_{e,j,s,t}$.}\n\n\\textcolor{red}{The main difference between the two methods is that the first allows for the model to include some elements of the dividend clientele hypothesis (depending on the detail on asset holdings imputed to the micro simulation model). In particular, the tax rate, $\\tau^{cap}(y_{j,s,t})$ would be calibrated from the microsimulation model and therefore would be a weighted average of the tax rates on dividends and capital gains for filers in a particular age-income group, where the weighting depends on the amount of capital gains versus dividend income for those filers. In contract, the second method assumed that all households get the same mix of dividends and capital gain income. However, the second method benefits from using the model's endogenous split between dividend and capital gains income, rather than assuming that the split is the same over time (but varies in the cross-section). So, to summarize, the first method allows for cross-sectional variation in the split between dividend and capital gains income (but no variation over time within a filer type), while the second method allows for variation over time (but not across filer types).}\n\n\\subsection{The Value of the Firm, cont'd}\nWe can rearrange Equation \\ref{eqn:equity_return} to solve for $V_{t}$:\n\n\\begin{equation}\n\\begin{split}\n(1-\\tau^{g}_{t})V_{t+1} &=V_{t}r_{e,t}-(1-\\tau^{d}_{t})DIV_{t}+(1-\\tau^{g}_{t})V_{t}+(1-\\tau^{g}_{t})VN_{t}\\\\\n\\implies V_{t+1} & = \\frac{r_{e,t}V{t}-(1-\\tau^{d}_{t})DIV_{t}}{(1-\\tau^{g}_{t})}+V_{t}+VN_{t} \\\\\n\\implies V_{t+1} & = V_{t}\\left(\\frac{r_{e,t}}{(1-\\tau^{g}_{t})}+1\\right)+VN_{t} - \\left(\\frac{1-\\tau^{d}_{t}}{1-\\tau^{g}_{t}}\\right)DIV_{t} \\\\\n\\implies V_{t} &= \\left(\\frac{1}{1+\\frac{r_{e,t}}{(1-\\tau^{g}_{t})}}\\right)\\left[V_{t+1} - VN_{t} + \\left(\\frac{1-\\tau^{d}_{t}}{1-\\tau^{g}_{t}}\\right)DIV_{t}\\right] \\\\\n\\end{split}\n\\end{equation}\n\n\\noindent\\noindent Letting $ \\left(\\frac{1}{1+\\frac{r_{e,t}}{(1-\\tau^{g}_{t})}}\\right) = 1+\\theta_{t}$, we can solve for $V_{t}$ by repeatedly substituting for $V_{t+1}$ and applying the transversality condition ($\\lim_{T \\to \\infty} \\prod_{t=1}^{T}(1+\\theta_{t})V_{T}=0$):\n\n\\begin{equation}\n\\label{eqn:solve_vs}\n\\begin{split}\n& V_{t}=\\frac{V_{t+1}}{(1+\\theta_{t})} - \\frac{VN_{t}}{(1+\\theta_{t})} + \\frac{\\left(\\frac{1-\\tau^{d}_{t}}{1-\\tau^{g}_{t}}\\right)DIV_{t}}{(1+\\theta_{t})} \\\\\n\\implies & V_{t}=\\frac{V_{t+2}}{(1+\\theta_{t})(1+\\theta_{t+1})} - \\frac{VN_{t+1}}{(1+\\theta_{t})(1+\\theta_{t+1})} + \\frac{\\left(\\frac{1-\\tau^{d}_{t+1}}{1-\\tau^{g}_{t+1}}\\right)DIV_{t+1}}{(1+\\theta_{t})(1+\\theta_{t+1})} - \\frac{VN_{t}}{(1+\\theta_{t})} + \\frac{\\left(\\frac{1-\\tau^{d}_{t}}{1-\\tau^{g}_{t}}\\right)DIV_{t}}{(1+\\theta_{t})} \\\\\n\\implies & V_{t}= \\frac{V_{t+3}}{(1+\\theta_{t})(1+\\theta_{t+1})(1+\\theta_{t+2})} - \\frac{VN_{t+2}}{(1+\\theta_{t})(1+\\theta_{t+1})(1+\\theta_{t+2})} + \\frac{\\left(\\frac{1-\\tau^{d}_{t+2}}{1-\\tau^{g}_{t+2}}\\right)DIV_{t+2}}{(1+\\theta_{t})(1+\\theta_{t+1})(1+\\theta_{t+2})} \\\\\n& - \\frac{VN_{t+1}}{(1+\\theta_{t})(1+\\theta_{t+1})} + \\frac{\\left(\\frac{1-\\tau^{d}_{t+1}}{1-\\tau^{g}_{t+1}}\\right)DIV_{t+1}}{(1+\\theta_{t})(1+\\theta_{t+1})} - \\frac{VN_{t}}{(1+\\theta_{t})} + \\frac{\\left(\\frac{1-\\tau^{d}_{t}}{1-\\tau^{g}_{t}}\\right)DIV_{t}}{(1+\\theta_{t})} \\\\\n& \\text{and so on...} \\\\\n\\implies & V_{t}=\\underbrace{\\prod_{\\nu=t}^{\\infty}\\left(\\frac{1}{1+\\theta_{\\nu}}\\right)V_{\\infty}}_{=0 \\text{ by transversality condition}} - \\sum_{u=t}^{\\infty} \\prod_{\\nu=t}^{u}\\left(\\frac{1}{1+\\theta_{\\nu}}\\right)\\left[VN_{u} - \\left(\\frac{1-\\tau^{d}_{u}}{1-\\tau^{g}_{u}}\\right)DIV_{u}\\right]\\\\\n\\implies & V_{t}= \\sum_{u=t}^{\\infty} \\prod_{\\nu=t}^{u}\\left(\\frac{1}{1+\\theta_{\\nu}}\\right)\\left[ \\left(\\frac{1-\\tau^{d}_{u}}{1-\\tau^{g}_{u}}\\right)DIV_{u}-VN_{u}\\right]\\\\\n\\end{split}\n\\end{equation}\n\n\\subsection{Firm Production}\n\nFirm's combine capital, $K$, and effective labor, $EL$, with a fixed factor of production, $A$ to produce output, $X$. We can think of the fixed factor of production as ``location specific capital\". It is fixed in the sense that its supply is perfectly inelastic. It is location specific in the sense that it is proportional to the size of the population in the firm's home country at time $t$. \\textcolor{red}{CORTAX documentation at first suggests this factor is chosen optimally by the firm, but there is not first order condition for this choice shown. The documentation does state that this factor is paid its marginal product. So there are only economic profits before you account for the return to this factor of production. I'm also not sure if we need this fixed factor of production to be proportional to the population. CORTAX says yes so that you don't have productivity differential arising from differences in country size. They consider multi-country model, but only steady state. Do we need something similar so productivity doesn't depend upon population at time $t$?} We write the amount of output produced as a function of this fixed factor and the value added, $VA$, from the input of capital and labor:\n\n\\begin{equation}\nX_{t} = A_{t}(VA_{t})^{\\alpha_{v}},\n\\end{equation} \n\n\\noindent\\noindent where $\\alpha_{v}$ is the share of output attributable to the firm's value added and the fixed factor of production is given by:\n\n\\begin{equation}\nA_{t} = (A_{0,t}\\omega_{t}N_{t})^{1-\\alpha_{v}}\n\\end{equation}\n\n\\noindent\\noindent So the input from fixed factor of production used by the firm is given by the level of total factor productivity (TFP), $A_{0,t}$, and a exogenous share of the population, $N_{t}$ where the share is given by the parameter $\\omega_{t}$ (\\textcolor{red}{Not sure if we want this to vary by time, or just across production industry.}). The share parameters must sum to one. That is, $\\sum_{m=1}^{M} \\omega_{m,t} = 1$. We assume that TFP grows at the same rate across industry, with the growth rate given by $g_{a}$. The value added is given by a CES function:\n\n\\begin{equation}\n\\label{eqn:prod_fun}\nF(A_{0,t},K_{t},EL_{t})=VA_{t} =A_{0,t} \\left[(\\gamma_{})^{1/\\epsilon_{}}(K_{t})^{(\\epsilon-1)/\\epsilon_{}}+(1-\\gamma_{})^{1/\\epsilon_{}}(e^{g_{y}t}EL_{t})^{(\\epsilon_{}-1)/\\epsilon_{}}\\right]^{(\\epsilon_{}/(\\epsilon_{}-1))},\n\\end{equation}\n\n\\noindent\\noindent where $\\epsilon$ gives the elasticity of substitution between capital and labor and $\\gamma$ is the share parameter in the CES production function. Effective labor units are affected by labor augmenting technological change. The growth rate of this technology is give by $g_{y}$. If $\\alpha_{v}<1$, then the production function exhibits decreasing returns to scale with respect the firm's inputs of capital and labor.\n\nWe can derive the marginal products of capital and labor as:\n\n\\begin{equation}\n\\label{eqn:mpk}\nMPK_{t}=\\frac{\\partial X_{t}}{\\partial K_{t}}=A_{0,t}^{\\frac{\\epsilon-1}{\\epsilon}} \\left(\\frac{\\alpha_{v}X_{t}}{VA_{t}}\\right)\\left(\\frac{\\gamma VA_{t}}{K_{t}}\\right)^{\\frac{1}{\\epsilon}}\n\\end{equation}\n\n\\begin{equation}\n\\label{eqn:mpl}\nMPL_{t}=\\frac{\\partial X_{t}}{\\partial EL_{t}}=A_{0,t}^{\\frac{\\epsilon-1}{\\epsilon}} \\left(\\frac{\\alpha_{v}X_{t}}{VA_{t}}\\right)\\left(\\frac{(1-\\gamma) VA_{t}}{EL_{t}}\\right)^{\\frac{1}{\\epsilon}}\n\\end{equation}\n\n\n\\subsection{Firm Accounting}\n\nHere we define a few accounting concepts and constraints relevant to the firm's problem.\n\n\\subsubsection{Cash Flow Constraint}\nThe firm's choices of investment and labor demand, as well as financial policies to finance these expenditures must satisfy the firm's cash flow constraint, which is given by:\n\n\\begin{equation}\n\\label{eqn:cash_flow}\n\\begin{split}\n& \\underbrace{p_{t}X_{t}+B_{t+1}+VN_{t}}_{\\text{financial inflows}} =\\\\\n & \\underbrace{w_{t}EL_{t} + (1+r_{b,t})B_{t} + c(B_{t+1},K_{t}) + p^{k}_{t}I_{t}(1+\\Phi_{t}) + DIV_{t} + \\tau^{p}_{t}p^{k}_{t}K_{t} + TE_{t} + \\Psi(VN_{t})}_{\\text{financial outflows}}\n\\end{split}\n\\end{equation}\n\n\\noindent\\noindent Here, $p_{t}$ is the price of output, $B_{t+1}$ is the stock of debt at the beginning of period $t+1$ (so that new debt issues in period $t$ are equal to $B_{t+1}-B_{t}$), $VN_{t}$ are new equity issues (as noted above). Labor costs are given by the wage rate times the number of effective labor units employed, $w_{t}EL_{t}$. The interest rate of bond holdings is given by $r_{b,t}$ and the costs of holding debt are given by $c(B_{t+1},K_{t+1})$. These costs might represent bankruptcy costs and other frictions in the debt markets. The variable $p^{k}_{t}$ denotes the price of capital, $I_{t}$ represents investment, and $\\Phi_{t}$ are the costs to adjusting the capital stock through new investment. The firm also pays dividends, $DIV_{t}$, property taxes at a marginal rate of $\\tau^{p}$ on the nominal value of its capital stock, income taxes $TE_{t}$, and costs to new equity issues, $\\Psi(VN_{t})$. Costs to new equity issues represent frictions in the equity markets such as those arising from information asymmetries. \n\nWe impose to constraints on variables in the cash flow constraint: $DIV_{t}\\geq0$ and $VN_{t}\\geq0$. In practice, firm's can and do buy back shares, but we restrict share repurchases in the model since the IRS treats share repurchases as dividends if they are done on a regular basis. Our model therefore restricts the distribution of firm value to shareholders to be through dividend issues. Note that we do not impose a constraint debt. Positive values of $B$ indicate firm borrowing, while negative values represent firm saving. Thus, retained earnings are held in the form of bonds that earn a rate of return $r_{b,t}$.\n\nThe law of motion of the capital stock is given by:\n\\begin{equation}\n\\label{eqn:lom_capital}\nK_{t+1}=(1-\\delta)K_{t} + I_{t},\n\\end{equation}\n\nIt is assumed that costs of debt take the following form:\n\n\\begin{equation}\n\\label{eqn:debt_cost}\nc(B_{t+1},K_{t}) = \\chi_{bk}\\left(\\frac{B_{t+1}}{K_{t}}\\right)^{\\ve_{bk}},\n\\end{equation}\n\n\\noindent\\noindent where $\\chi_{bk}$ is a scaling parameter and $\\ve_{bk}$ is the curvature parameter. \\textcolor{red}{Note the timing convention used here. Leverage is determined by the current capital stock, not the one-period ahead capital stock. While the investment made with the loan may be used as collateral for the loan, we assume that the costs of debt depend upon the ratio the loan to the current capital stock. This seems realistic if there is uncertainty about the potential value of the investments. We will need to adjust this cost function in a way so that savings (i.e., $B<0$) result in no cost.}\n\nAdjustment costs are assumed to be a quadratic function of deviations from the steady-state investment rate:\n\\begin{equation}\n\\label{eqn:adj_cost}\n\\Phi_{t}=\\frac{\\left(\\frac{\\beta}{2}\\right)\\left(\\frac{I_{t}}{K_{t}}-\\mu\\right)^{2}}{\\left(\\frac{I_{t}}{K_{t}}\\right)}\n\\end{equation}\n\n\\noindent\\noindent The parameter $\\beta$ is the scaling parameter for the adjustment cost function and $\\mu$ is the steady-state investment rate, which is determined as $\\mu=\\delta+g_{y}+g_{n}$\n\nCosts to new equity issues are assumed to be of the form:\n\n\\begin{equation}\n\\label{eqn:equity_cost}\n\\Psi(VN_{t})= \\psi_{1}VN_{t} + \\psi_{2}VN_{t}^{2}\n\\end{equation}\n\n\\textcolor{red}{We can play around with these function forms. The key points are that we have increasing marginal costs in each. It's also very convenient for the steady state costs of adjusting the capital stock to equal zero. We also need to think about forms that are easy to calibrate and want to avoid fixed costs (and other non-convexities) that may make computation difficult.}\n\nIf the firm has a net financial surplus before choosing it's financial policy (dividends, new equity, bond holdings), then it will either save the excess, earning a rate of return $r_{b,t}$ or will distribute the excess as dividends. In making this choice it will consider the corporate income tax rate to the gains return on retained earnings as well as the capital gains taxes on the marginal investor in the benefits to the retained earnings. It will consider taxes on dividend income in the benefits to dividend distributions. If the firm has net financial deficit, then it will use new equity and/or bond issues to satisfy the cash flow constraint. In making this choice, it will consider the costs of debt and equity as well as the tax implications of each. In particular, that interest payments on debt may be tax deductible and that the after-tax dilution of shareholder value is affected by the capital gains tax rate.\n\n\n\n\\subsubsection{Accounting Concepts}\n\nIt is useful to define some accounting concepts. We define firm profits from a financial accounting perspective as:\n\n\\begin{equation}\n\\label{eqn:profit_book}\n\\Pi^{book}_{t} = p_{t}X_{t}-w_{t}EL_{t}-\\delta K_{t} -\\Phi_{t}p^{k}_{t}I_{t}-(1+r_{b,t})B_{t}- c(B_{t+1},K_{t})-\\tau^{p}_{t}K_{t}-TE_{t}\n\\end{equation}\n\nWe define firm profits from a tax accounting perspective as:\n\\begin{equation}\n\\label{eqn:profit_tax}\n\\begin{split}\n\\Pi^{tax}_{t}= & p_{t}X_{t}-w_{t}EL_{t}-f_{e,t}p^{K}_{t}I_{t}-\\Phi_{t}I_{t}-f_{i,t}r_{b,t}B_{t}-f_{c,t}c(B_{t+1},K_{t})+f_{p,t}\\delta B_{t}+...\\\\\n& f_{b,t}B_{t+1}-f_{d,t}\\delta^{\\tau}_{t}K^{\\tau}_{t}-f_{ace,t}r_{ace,t}K^{\\tau}_{t}-\\tau^{p}_{t}p^{k}_{t}K_{t}\n\\end{split}\n\\end{equation}\n\n\\noindent\\noindent Note that we are assuming that investment may or may not be deductible (depending upon the dummy variable $f_{e,t}$), but that investment adjustment costs are always deductible (i.e., they are not preceded by $f_{e,t}$). Under a pre-pay consumption tax system, investments are not deductible from the tax base. Whether or not adjustment costs are deductible under a pre-pay consumption tax depends upon what you think these costs derive from. For example, if adjustment costs are from retraining employees to use new equipment, then these costs may be deductible under a consumption tax system (pre or post-pay) because they would likely be in the form of wage/labor costs.\\footnote{It's not clear how best to handle this and \\citet{DZ2013} are vague on this point.} The other indicator variables, $f_{i,t}$, $f_{c,t}$,$f_{p,t}$, $f_{b,t}$, $f_{d}$, and $f_{ace,t}$, allow for various consumption tax policies to be incorporated into the model. The parameter $f_{i,t}=1$ if interest on debt is deductible and 0 if not (\\textcolor{red}{Since we will allow firms to lend with their retained earnings, we need to think about that fact that this indicator is not always symmetric. That is, one might have a tax system where interest income is taxes, but interest payments are not deductible (or fully deductible).}). The indicator $f_{c,t}$ equals one if debt costs are deductible (\\textcolor{red}{Not sure if we want this - maybe just assume they are deductible are capital adjustment costs are.}). The parameter $f_{p,t}$ is equal to one the principle on corporate borrowing is deductible from the corporate income tax based. Principle on loans would be deductible in a post-pay consumption tax system. The parameter $f_{b,t}$ is equal to one if the proceeds from firm borrowing is included in the corporate tax base. Such proceeds would be included in a pre-pay consumption tax system. The parameter $f_{d,t}$ is equal to one if capital can be depreciated and zero if not. For example, in a post-pay consumption tax framework, $f_{e,t}=1$ and $f_{d,t}=0$. We allow for allowance of corporate equity (ACE) policies through the $f_{ace,t}$ indicator variable, which equals one if there is an allowance for corporate equity. We use the notation $r_{ace,t}$ for the rate of return use for the corporate equity allowance. In practice, this maybe set to $r_{b,t}$ or $r_{e,t}$ or another rate of return. \\textcolor{red}{The fiscal capital stock is currently used as the basis for the ACE system. I think this needs to be adjusted for the fraction of the capital stock that is supported by equity, but I'm not totally sure.}\n\nThe tax basis of the capital stock is given by $K^{\\tau}_{t}$. The law of motion for the tax basis of the capital stock is given by:\n\n\\begin{equation}\n\\label{eqn:lom_taxcapital}\nK^{\\tau}_{t+1}=(1-\\delta^{\\tau}_{t})(K^{\\tau}_{t} + (1-f_{e})p^{K}_{t}I_{t}),\n\\end{equation}\n\n%\\noindent\\noindent where $\\delta^{\\tau}$ is the rate if depreciation for tax purposes. Note how we form the law of motion for the tax basis. The above formulation accounts for the fact that investment in year $t$ receives a depreciation deduction in year $t$.\\footnote{The IRS specifies a partial year rule, where one deducts the value of investment proportional to the amount of the year in which the asset was in place. We ignore this detail and assume all assets are in place for the entire year.} We can think about modifying this so that you get no deduction in the year the investment is made, which may or may not be more consistent with the ``time to build\" built into the law of motion for the physical capital stock.\n%\n%\n%\\noindent\\noindent Note that $K^{\\tau}_{u}$ tracks depreciation deductions in in all periods $u=t,...,\\infty$. Future depreciation deductions on the tax basis of the capital stock in existence at time $u$ do not affect investment decisions at time $u$ (or forward) since the tax basis is predetermined.\\footnote{Note that if there were financial frictions (e.g. a borrowing constraint or costly external finance), then investment would be dependent on cash flow and would then be affected by changes in the value of deductions for the existing capital basis.} However, future depreciation deductions for investments made at time $u$ do affect investment decisions (since they lower the after-tax cost of investment). Therefore it's useful to distinguish between old and new capital. \n%\n%The time $u$ value of future depreciation deductions on the capital stock existing at the beginning of period $u$ is given by $K^{\\tau}_{u-1}$. We can determine this value as:\n%\n%\\begin{equation}\n%\\label{eqn:z}\n%\\begin{split}\n%f_{d}Z_{u}K^{\\tau}_{u-1} &= \\sum^{\\infty}_{j=u} \\prod_{\\nu=u}^{j} \\left(\\frac{1}{1+\\theta_{\\nu}}\\right)f_{d}\\Omega_{j}\\tau^{b}_{j}\\delta^{\\tau}(1-\\delta^{\\tau})^{j-u}K^{\\tau}_{u} \\\\\n%&= f_{d} K^{\\tau}_{u-1} \\underbrace{\\sum^{\\infty}_{j=u} \\prod_{\\nu=u}^{j} \\left(\\frac{1}{1+\\theta_{\\nu}}\\right)f_{d}\\Omega_{j}\\tau^{b}_{j}\\delta^{\\tau}(1-\\delta^{\\tau})^{j-u}}_{Z_{u}} \\\\\n%& = f_{d} K^{\\tau}_{u-1} Z_{u},\n%\\end{split}\n%\\end{equation}\n%\n%\\noindent\\noindent where $Z_{u}$ is the net present value of future depreciation deductions per dollar of investment. With this, we derive the time $u$ value of future depreciation deductions on investments made at time $u$, $I^{\\tau}_{u}$. These are given by $f_{d}(1-f_{e})Z_{u}I_{u}$. Now we can rewrite Equation \\ref{eqn:vs} describing the value of the firm at time $t$ as: \n%\n% \\begin{equation}\n%\\label{eqn:vs_w_z}\n%\\begin{split}\n%V_{t} = & \\sum_{u=t}^{\\infty} \\prod_{\\nu=t}^{u}\\left(\\frac{1}{1+\\theta_{\\nu}}\\right) (1-\\tau^{b}_{u})\\Omega_{u}(p_{u}X_{u}-w_{u}EL_{u}) \\\\ \n% & - K_{t} \\left\\{(1-\\tau^{b}_{u})\\Omega_{u}\\tau^{p}_{u}+(1-f_{i}\\tau^{i}_{u})i_{u}\\Omega_{u}b-\\delta(p_{u}-b-\\Omega_{u}(p_{u}-f_{p}\\tau^{b}_{u}b))\\right\\} \\\\\n% & - I_{u}\\left\\{1-b+\\Omega_{u}f_{b}\\tau^{b}_{u}b-\\Omega_{u}f_{e}\\tau^{b}_{u} - f_{d}(1-f_{e})Z_{u} + (1-\\Omega_{u}\\tau^{b}_{u})\\Phi_{u}\\right\\} \\\\\n% & + f_{d}Z_{t}K^{\\tau}_{t-1} \\\\\n%\\end{split}\n%\\end{equation}\n\n\n\nTotal income taxes on the firm are thus given by:\n\n\\begin{equation}\n\\label{eqn:corp_tax}\n\\begin{split}\nTE_{t}= \\tau^{b}_{t}\\Pi^{tax}_{t} +\\tau^{ic}_{t}p^{K}_{t}I_{t},\n\\end{split}\n\\end{equation}\n\n\\noindent\\noindent where $\\tau^{b}_{t}$ is the tax rate on business income will be used to represent either an entity level tax or the tax rate on the distributions of income to owners for those firms not subject to an entity level tax. \n\n\\subsection{Optimal Firm Policy}\n\nUsing the cash flow constraint, we can solve for dividends as a function of the other endogenous variables, exogenous variables, and parameters:\n\n\\begin{equation}\n\\label{eqn:div}\n\\begin{split}\nDIV_{t}&=\\Pi^{book}_{t} + B_{t+1} + VN_{t}\\\\\n & = p_{t}X_{t}+ B_{t+1} + VN_{t}-w_{t}EL_{t}-\\delta K_{t} -\\Phi_{t}p^{k}_{t}I_{t}-(1+r_{b,t})B_{t} - c(B_{t+1},K_{t})-\\tau^{p}_{t}K_{t}-TE_{t}\n\\end{split}\n\\end{equation}\n\nThe problem of the firm is maximize firm value, $V_{t}$, to the constraints on dividends and equity issues, and the laws of motion for the economic and fiscal capital stock. That is, it solves:\n\n\\begin{equation}\n\\label{eqn:V_max}\n\\begin{split}\n &V_{t}= \\max_{\\{DIV_{u},VN_{u}, I_{u}, K_{u+1}, EL_{u}, B_{u+1}, K^{\\tau}_{u+1},p_{u}\\}^{\\infty}_{u=t}} \\sum_{u=t}^{\\infty} \\prod_{\\nu=t}^{u}\\left(\\frac{1}{1+\\theta_{\\nu}}\\right)\\left[ \\left(\\frac{1-\\tau^{d}_{u}}{1-\\tau^{g}_{u}}\\right)DIV_{u}-VN_{u}\\right]\\\\\n &\\text{subject to:} \\\\\n &DIV_{u}\\geq 0\\\\\n &VN_{u}\\geq 0\\\\\n &K{u+1}=(1-\\delta)K_{u}+ I_{u} \\\\\n &K^{\\tau}_{t+1}=(1-\\delta^{\\tau}_{t})(K^{\\tau}_{t} + (1-f_{e})p^{K}_{t}I_{t})\n \\end{split}\n \\end{equation}\n\nWe can substitute in Equation \\ref{eqn:div} for $DIV_{t}$ in the above and write the Lagrangian of the firm's problem as:\n\n \\begin{equation}\n\\label{eqn:lagrangian}\n\\begin{split}\n\\mathcal{L}_{t} =& \\max_{\\{VN_{u}, I_{u}, K_{u+1}, EL_{u}, B_{u+1}, K^{\\tau}_{u+1},p_{u}\\}^{\\infty}_{u=t}} \\sum_{u=t}^{\\infty} \\prod_{\\nu=t}^{u}\\left(\\frac{1}{1+\\theta_{\\nu}}\\right) \\left[ \\left(\\frac{1-\\tau^{d}_{u}}{1-\\tau^{g}_{u}}\\right) \\left(p_{u}X_{t}+ B_{u+1}... \\right. \\right. \\\\\n& \\left. \\left. + VN_{u}-w_{u}EL_{u}-\\delta K_{u} -\\Phi_{u}p^{k}_{u}I_{t}-(1+r_{b,u})B_{u} - c(B_{t+1},K_{t})-\\tau^{p}_{u}K_{u}-TE_{u}\\right) - VN_{u} ...\\right. \\\\\n&\\left. + q_{u}\\left((1-\\delta)K_{u}+I_{u}-K_{u+1}\\right) + \\lambda^{\\tau}\\left((1-\\delta^{\\tau}_{u})(K^{\\tau}_{u}+(1-f_{e,u})p^{k}_{u}I_{u})-K^{\\tau}_{u+1}\\right) ...\\right. \\\\\n& \\left.+ \\lambda^{v}_{t}VN_{u} ... \\right. \\\\\n& \\left. + \\lambda^{d}\\left(p_{u}X_{u}+ B_{u+1} + VN_{u} - w_{u}EL_{u} - (1+r_{b,u})B_{u} - c(B_{u+1},K_{u+1})... \\right.\\right.\\\\\n& \\left.\\left. - p^{k}_{u}I_{u}(1+\\Phi_{u}) - \\tau^{p}_{u}p^{k}_{u} - TE_{u} -\\Psi(VN_{u})\\right) \\right]\n\\end{split}\n\\end{equation}\n\nThe maximization problem yields the following first order conditions:\n\nWith respect to labor:\n\\begin{equation}\n\\label{eqn:foc_l}\n\\begin{split}\n&\\frac{\\partial \\mathcal{L}_{t}}{\\partial EL_{u}} = \\prod_{\\nu=t}^{u}\\left(\\frac{1}{1+\\theta_{\\nu}}\\right)\\left[ \\left(\\frac{1-\\tau^{d}_{u}}{1-\\tau^{g}_{u}}\\right)\\left[p_{u}MPL_{u} - w_{u} - \\frac{\\partial TE_{u}}{\\partial EL_{u}}\\right] ... \\right. \\\\\n& \\left. - \\lambda^{d}_{u}\\left[p_{u}MPL_{u} - w_{u} - \\frac{\\partial TE_{u}}{\\partial EL_{u}}\\right] \\right] = 0 \\\\\n& \\implies p_{u}MPL_{u}- \\frac{\\partial TE_{u}}{\\partial EL_{u}} = w_{u}\n\\end{split}\n\\end{equation}\n\nLabor demand is determined through this intratemporal trade off between the costs and benefits of employing additional labor in the production process. The left hand side gives the marginal revenue, or benefits from employing more labor, and the right hand save gives the costs, which are the wages paid to the additional labor.\n\nWith respect to investment:\n \\begin{equation}\n\\label{eqn:foc_i}\n\\begin{split}\n\\frac{\\partial \\mathcal{L}_{t}}{\\partial I_{u}} & = \\prod_{\\nu=t}^{u}\\left(\\frac{1}{1+\\theta_{\\nu}}\\right) \\left[ q_{u} + \\lambda^{\\tau}_{u}(1-\\delta^{\\tau}_{u})(1-f_{e,u})p^{k}_{u} - \\left(\\frac{1-\\tau^{d}_{u}}{1-\\tau^{g}_{u}}\\right) \\left[p^{k}_{u}(1+ \\frac{\\partial \\Phi_{u}}{\\partial I_{u}}I_{u} + \\Phi_{u}) + \\frac{\\partial TE_{u}}{\\partial I_{u}} \\right] - \\right. \\\\\n& \\left. \\lambda^{d}_{u}\\left[p^{k}_{u}(1+ \\frac{\\partial \\Phi_{u}}{\\partial I_{u}}I_{u} + \\Phi_{u}) + \\frac{\\partial TE_{u}}{\\partial I_{u}} \\right]\\right]= 0 \\\\\n& \\implies q_{u} + \\lambda^{\\tau}_{u}(1-\\delta^{\\tau}_{u})(1-f_{e,u})p^{k}_{u} = \\left(\\frac{1-\\tau^{d}_{u}}{1-\\tau^{g}_{u}} + \\lambda^{d}_{u}\\right)\\left[p^{k}_{u}(1+ \\frac{\\partial \\Phi_{u}}{\\partial I_{u}}I_{u} + \\Phi_{u}) + \\frac{\\partial TE_{u}}{\\partial I_{u}}\\right]\n\\end{split}\n\\end{equation}\n\nWith respect to the one-period ahead capital stock:\n\n \\begin{equation}\n\\label{eqn:foc_k}\n\\begin{split}\n \\frac{\\partial \\mathcal{L}_{t}}{\\partial K_{u+1}} &= - \\prod_{\\nu=t}^{u}\\left(\\frac{1}{1+\\theta_{\\nu}}\\right)q_{u} + \\prod_{\\nu=t}^{u+1}\\left(\\frac{1}{1+\\theta{\\nu}}\\right)\\left[(1-\n\\delta)q_{u+1} ... \\right. \\\\\n&\\left. + \\left(\\frac{1-\\tau^{d}_{u+1}}{1-\\tau^{g}_{u+1}}\\right)\\left[p_{u+1}MPK_{u+1} - p^{k}_{u+1}\\frac{\\partial \\Phi_{u+1}}{\\partial K_{u+1}}I_{u+1} - \\frac{\\partial c(B_{u+2},K_{u+1})}{\\partial K_{u+1}}-\\tau^{p}_{u+1}p^{k}_{u+1}-\\frac{\\partial TE_{u+1}}{\\partial K_{u+1}} \\right] \\right. \\\\\n& \\left. - \\lambda^{d}_{u}\\left[p_{u+1}MPK_{u+1} - p^{k}_{u+1}\\frac{\\partial \\Phi_{u+1}}{\\partial K_{u+1}}I_{u+1} - \\frac{\\partial c(B_{u+2},K_{u+1})}{\\partial K_{u+1}}-\\tau^{p}_{u+1}p^{k}_{u+1}-\\frac{\\partial TE_{u+1}}{\\partial K_{u+1}} \\right] \\right] = 0 \\\\\n&\\implies q_{u} = \\left(\\frac{1}{1+\\theta_{u+1}}\\right)\\left[(1-\\delta)q_{u+1} ... \\right. \\\\\n& \\left. + \\left(\\frac{1-\\tau^{d}_{u+1}}{1-\\tau^{g}_{u+1}} + \\lambda^{d}_{u+1} \\right)\\left[p_{u+1}MPK_{u+1}- p^{k}_{u+1}\\frac{\\partial \\Phi_{u+1}}{\\partial K_{u+1}}I_{u+1} ... \\right.\\right. \\\\\n& \\left.\\left.- \\frac{\\partial c(B_{u+2},K_{u+1})}{\\partial K_{u+1}}-\\tau^{p}_{u+1}p^{k}_{u+1}-\\frac{\\partial TE_{u+1}}{\\partial K_{u+1}} \\right] \\right]\n\\end{split}\n\\end{equation}\n\n\\noindent\\noindent The Euler equation described in Equation \\ref{eqn:foc_i} relates Tobin's $q$, given by $q_{u}$, to the marginal costs of investment. Tobin's $q$ defines the marginal change in firm value for a dollar of investment. It is the shadow price of additional capital. The FOC for investment says that the firm invests until the marginal benefit (the LHS of Equation \\ref{eqn:foc_i}) is equal to the marginal cost of investment (the RHS of Equation \\ref{eqn:foc_i}). The cost of investment in the absence of taxes and frictions is equal to the price of capital (the first term on the RHS of Equation \\ref{eqn:foc_i}). The second term reflects the reduction in the cost of capital due to debt financing. The third term on the RHS of Equation \\ref{eqn:foc_i} is the change in the cost of capital due to debt being included or excluded from business entity-level income taxes. The fourth term reflects the reduction in the cost of capital due to depreciation deductions. The last term reflects the component of the cost of capital that is due to adjustment costs (net of the expensing of adjustment costs for tax purposes).\n\nWith respect to one-period ahead bond holdings:\n \\begin{equation}\n\\label{eqn:foc_b}\n\\begin{split}\n \\frac{\\partial \\mathcal{L}_{t}}{\\partial B_{u+1}} &= \\prod_{\\nu=t}^{u}\\left(\\frac{1}{1+\\theta{\\nu}}\\right)\\left[\\left(\\frac{1-\\tau^{d}_{u}}{1-\\tau^{g}_{u}}\\right)\\left(1-\\frac{\\partial c(B_{u+1},K_{u}}{\\partial B_{u+1}}-\\frac{\\partial TE_{u}}{\\partial B_{u+1}}\\right) ... \\right. \\\\\n & \\left. + \\lambda^{d}_{u}\\left(1-\\frac{\\partial c(B_{u+1},K_{u})}{\\partial B_{u+1}}-\\frac{\\partial TE_{u}}{\\partial B_{u+1}}\\right) \\right] ... \\\\\n & - \\prod_{\\nu=t}^{u+1}\\left(\\frac{1}{1+\\theta{\\nu}}\\right)\\left[\\left(\\frac{1-\\tau^{d}_{u+1}}{1-\\tau^{g}_{u+1}}\\right)\\left((1+r_{b,u+1})+\\frac{\\partial TE_{u+1}}{\\partial B_{u+1}}\\right)... \\right. \\\\\n & \\left. + \\lambda^{d}_{u+1}\\left((1+r_{b,u+1})+\\frac{\\partial TE_{u+1}}{\\partial B_{u+1}}\\right)\\right] = 0 \\\\\n& \\implies \\left(\\frac{1-\\tau^{d}_{u}}{1-\\tau^{g}_{u}} + \\lambda^{d}_{u} \\right)\\left(1-\\frac{\\partial c(B_{u+1},K_{u})}{\\partial B_{u+1}}-\\frac{\\partial TE_{u}}{\\partial B_{u+1}}\\right)= \\\\\n& \\left(\\frac{1}{1+\\theta_{u+1}}\\right) \\left(\\frac{1-\\tau^{d}_{u+1}}{1-\\tau^{g}_{u+1}} + \\lambda^{d}_{u} \\right) \\left((1+r_{b,u+1})+\\frac{\\partial TE_{u+1}}{\\partial B_{u+1}}\\right)\n \\end{split}\n\\end{equation}\n\nWith respect to new equity issues:\n \\begin{equation}\n\\label{eqn:foc_vn}\n\\begin{split}\n \\frac{\\partial \\mathcal{L}_{t}}{\\partial VN_{u}} &= \\prod_{\\nu=t}^{u}\\left(\\frac{1}{1+\\theta{\\nu}}\\right)\\left[\\left(\\frac{1-\\tau^{d}_{u}}{1-\\tau^{g}_{u}}\\right)\\left(1-\\frac{\\partial \\Psi(VN_{u})}{\\partial VN_{u}}\\right) - 1 + \\lambda^{v}_{u} + \\lambda^{d}_{u}\\left(1-\\frac{\\partial \\Psi(VN_{u})}{\\partial VN_{u}}\\right) \\right] = 0 \\\\\n & \\implies 1 = \\left(\\frac{1-\\tau^{d}_{u}}{1-\\tau^{g}_{u}} + \\lambda^{d}_{u}\\right)\\left(1-\\frac{\\partial \\Psi(VN_{u})}{\\partial VN_{u}}\\right) + \\lambda^{v}_{u}\n \\end{split}\n\\end{equation}\n\nWith respect to the one-period ahead fiscal capital stock:\n \\begin{equation}\n\\label{eqn:foc_ktau}\n\\begin{split}\n \\frac{\\partial \\mathcal{L}_{t}}{\\partial K^{\\tau}_{u+1}} &= - \\prod_{\\nu=t}^{u}\\left(\\frac{1}{1+\\theta{\\nu}}\\right)\\lambda^{\\tau}_{u} - \\\\\n & \\prod_{\\nu=t}^{u+1}\\left(\\frac{1}{1+\\theta{\\nu}}\\right)\\left[\\left(\\frac{1-\\tau^{d}_{u+1}}{1-\\tau^{g}_{u+1}}\\right)\\frac{\\partial TE_{u+1}}{\\partial K^{\\tau}_{u+1}} - \\lambda^{\\tau}_{u+1}(1-\\delta^{\\tau}_{u+1}) + \\lambda^{d}_{u+1}\\frac{\\partial TE_{u+1}}{\\partial K^{\\tau}_{u+1}} \\right] = 0 \\\\\n& \\implies \\lambda^{\\tau}_{u} = \\left(\\frac{1}{1+\\theta_{u+1}}\\right)\\left[\\left(\\frac{1-\\tau^{d}_{u+1}}{1-\\tau^{g}_{u+1}} + \\lambda^{d}_{u+1} \\right)\\frac{- \\partial TE_{u+1}}{\\partial K^{\\tau}_{u+1}} + \\lambda^{\\tau}_{u+1}(1-\\delta^{\\tau}_{u+1})\\right] \n \\end{split}\n\\end{equation}\n\n\n\nThe final endogenous variable to solve for is the value of the firm at any point in time, $V_{u}$. As \\citet{Hayashi1982} shows, with a constant returns to scale production function and quadratic adjustment costs, there is an equivalence between marginal $q$ and average $q$. \\textcolor{red}{Is it ok that we have a production function that is CRS, but DRS with respect to capital and labor???} Note that in our case, we must make an adjustment for the value of depreciation deductions on the tax basis of the capital stock already in place at time $u$. The relation between marginal $q$, given by $q_{u}$, and average $q$, given by $Q_{u}$ is:\n \\begin{equation}\n\\label{eqn:avg_q}\n\\begin{split}\nq_{u}=\\frac{[V_{u}-f_{d}Z_{u}K^{\\tau}_{u-1}]}{K_{u}} \\text{ and } Q_{u}=\\frac{V_{u}}{K_{u}},\n\\end{split}\n\\end{equation}\n\n\\noindent\\noindent where $Z_{u}$ is the net present value of depreciation deductions on the existing capital stock. This relationship thus allows use to determine the value of the firm as:\n\n \\begin{equation}\n\\label{eqn:solve_firmvalue}\n\\begin{split}\n V_{u}=q_{u}K_{u}+f_{d}Z_{u}K^{\\tau}_{u-1}\n\\end{split}\n\\end{equation}\n\n\n\\textcolor{red}{Note that price is endogenous, but there is no first order condition for this choice that makes sense here since we don't have a demand function. To pin down this endogenous variable we'll use the condition that with free entry, the equilibrium price will equal the firm's marginal cost. To do this, we need to write the marginal cost of producing a unit of output. And for price to be determined, we need this to be constant over all amounts of output (which is not the case with a DRS production function). Or, can we set price equal to marginal cost then solve for the output price as a function of the factor prices (r,w)? }\n\nWe can write the derivatives of the tax function with respect to the endogenous variables as:\n\n\\begin{equation}\n\\label{eqn:d_te_l}\n\\frac{\\partial TE_{u}}{\\partial EL_{u}}= \\tau^{b}_{u}\\left(p_{u}MPL_{u}- w_{u} \\right)\n\\end{equation}\n\n\\begin{equation}\n\\label{eqn:d_te_i}\n\\frac{\\partial TE_{u}}{\\partial I_{u}}= -\\tau^{b}_{u}\\left(f_{e,u}p^{k}_{u} + p^{k}_{u}\\left(\\frac{\\partial \\Phi_{u}}{\\partial I_{u}} + \\Phi_{u}\\right)\\right) + \\tau^{ic}_{t}p^{k}_{t}\n\\end{equation}\n\n\\begin{equation}\n\\label{eqn:d_te_kp1}\n\\frac{\\partial TE_{u}}{\\partial K_{u+1}}= 0\n\\end{equation}\n\n\\begin{equation}\n\\label{eqn:d_te_k}\n\\frac{\\partial TE_{u}}{\\partial K_{u}}= \\tau^{b}_{u}\\left( p_{u}MPK_{u} - p^{k}_{u}\\frac{\\partial \\Phi_{u}}{\\partial K_{u}}I_{u} - f_{c,u}\\frac{\\partial c(B_{u+1},K_{u})}{\\partial K_{u}}- \\tau^{p}_{u}p^{k}_{u}\\right)\n\\end{equation}\n\n\\begin{equation}\n\\label{eqn:d_te_bp1}\n\\frac{\\partial TE_{u}}{\\partial B_{u+1}}= -\\tau^{b}_{u}\\left( f_{c,u}\\frac{\\partial c(B_{u+1},K_{u})}{\\partial B_{u+1}} + f_{b,u}\\right)\n\\end{equation}\n\n\\begin{equation}\n\\label{eqn:d_te_b}\n\\frac{\\partial TE_{u}}{\\partial B_{u}}= -\\tau^{b}_{u}\\left(f_{i,u}r_{b,u} + f_{p,u} \\right)\n\\end{equation}\n\n\\begin{equation}\n\\label{eqn:d_te_b}\n\\frac{\\partial TE_{u}}{\\partial K^{\\tau}_{u}}= -\\tau^{b}_{u}\\left(f_{d,u}\\delta^{\\tau}_{u}+f_{ace,u}r_{ace,u} \\right)\n\\end{equation}\n\n\nUsing these partial derivatives of the tax function with respect to the endogenous variables, we can rewrite the FOCs as:\n\n\n\\begin{equation}\n\\label{eqn:foc_l_tax}\n\\begin{split}\n p_{u}MPL_{u} = w_{u} \n \\end{split}\n\\end{equation}\n\n \\begin{equation}\n\\label{eqn:foc_i_tax}\n\\begin{split}\n & q_{u} + \\lambda^{\\tau}_{u}(1-\\delta^{\\tau}_{u})(1-f_{e,u})p^{k}_{u} = \\left(\\frac{1-\\tau^{d}_{u}}{1-\\tau^{g}_{u}} + \\lambda^{d}_{u}\\right)\\left[(1-f_{e,u}\\tau^{b}_{u} - \\tau^{ic}_{t})p^{k}_{u}+ (1-\\tau^{b}_{u})p^{k}_{u}\\left(\\frac{\\partial \\Phi_{u}}{\\partial I_{u}} + \\Phi_{u}\\right) \\right]\n\\end{split}\n\\end{equation}\n\n\n \\begin{equation}\n\\label{eqn:foc_k_tax}\n\\begin{split}\n q_{u} & = \\left(\\frac{1}{1+\\theta_{u+1}}\\right)\\left[(1-\\delta)q_{u+1} ... \\right. \\\\\n& \\left. + \\left(\\frac{1-\\tau^{d}_{u+1}}{1-\\tau^{g}_{u+1}} + \\lambda^{d}_{u+1} \\right)\\left[(1-\\tau^{b}_{u+1})\\left(p_{u+1}MPK_{u+1}- p^{k}_{u+1}\\frac{\\partial \\Phi_{u+1}}{\\partial K_{u+1}}I_{u+1}\\right) ... \\right.\\right. \\\\\n& \\left.\\left.-(1-f_{c,u+1}\\tau^{b}_{u+1}) \\frac{\\partial c(B_{u+2},K_{u+1})}{\\partial K_{u+1}} \\right] \\right]\n\\end{split}\n\\end{equation}\n\n \\begin{equation}\n\\label{eqn:foc_b_tax}\n\\begin{split}\n& \\left(\\frac{1-\\tau^{d}_{u}}{1-\\tau^{g}_{u}} + \\lambda^{d}_{u} \\right)\\left((1-\\tau^{b}_{u}f_{b,u})-(1-\\tau^{b}_{u}f_{c,u})\\frac{\\partial c(B_{u+1},K_{u})}{\\partial B_{u+1}}\\right)= \\\\\n& \\left(\\frac{1}{1+\\theta_{u+1}}\\right) \\left(\\frac{1-\\tau^{d}_{u+1}}{1-\\tau^{g}_{u+1}} + \\lambda^{d}_{u} \\right) \\left((1+\\tau^{b}_{u+1}f_{p,u+1})+(1-\\tau^{b}_{u+1}f_{i,u+1})r_{b,u+1}\\right)\n \\end{split}\n\\end{equation}\n\n \\begin{equation}\n\\label{eqn:foc_vn_tax}\n\\begin{split}\n1 = \\left(\\frac{1-\\tau^{d}_{u}}{1-\\tau^{g}_{u}} + \\lambda^{d}_{u}\\right)\\left(1-\\frac{\\partial \\Psi(VN_{u})}{\\partial VN_{u}}\\right) + \\lambda^{v}_{u}\n \\end{split}\n\\end{equation}\n\n \\begin{equation}\n\\label{eqn:foc_ktau_tax}\n\\begin{split}\n \\lambda^{\\tau}_{u} = \\left(\\frac{1}{1+\\theta_{u+1}}\\right)\\left[\\left(\\frac{1-\\tau^{d}_{u+1}}{1-\\tau^{g}_{u+1}} + \\lambda^{d}_{u+1} \\right)\\left(f_{d,u+1}\\delta^{\\tau}_{u+1}+f_{ace,u+1}r_{ace,u+1}\\right)\\tau^{b}_{u+1} + \\lambda^{\\tau}_{u+1}(1-\\delta^{\\tau}_{u+1})\\right] \n \\end{split}\n\\end{equation}\n\n\n\n\\subsubsection{Optimal Investment Policy}\n\n\\ \\\\\n\\noindent\\noindent \\emph{User cost of capital}\n\nLet $ucc_{t}$ denote the user cost of capital of the firm in period $t$. We define $ucc_{t}$ such that it is equal to the entity-level-tax marginal cash flow from an additional dollar of investment:\n\n\\begin{equation}\nucc_{t} = (1-\\tau^{b}_{t+1})\\left(p_{t+1}MPK_{t+1}-\\tau^{p}_{t+1}p^{k}_{t+1}\\right)- (1-\\tau^{b}_{t+1}) \\frac{\\partial c(B_{t+2},K_{t+1})}{\\partial K_{t+1}}\n\\end{equation}\n\n\nWe can use Equation \\ref{eqn:foc_k_tax} to rewrite the LHS:\n\n\\begin{equation}\nucc_{t} = \\left[\\left({1+\\theta_{u+1}}\\right)q_{t} - (1-\\delta)q_{u+1}\\right] \\left(\\frac{1-\\tau^{d}_{u+1}}{1-\\tau^{g}_{u+1}} + \\lambda^{d}_{u+1} \\right)^{-1}\n\\end{equation}\n\nUsing Equation \\ref{eqn:foc_i_tax} we have:\n\n\\begin{equation}\n\\begin{split}\nucc_{t} &= \\left[\\left({1+\\theta_{u+1}}\\right)\\left[\\left(\\frac{1-\\tau^{d}_{t}}{1-\\tau^{g}_{t}} + \\lambda^{d}_{t}\\right)\\left[(1-f_{e,t}\\tau^{b}_{t}-\\tau^{ic}_{t})p^{k}_{t}+ (1-\\tau^{b}_{t})p^{k}_{t}\\left(\\frac{\\partial \\Phi_{t}}{\\partial I_{t}} + \\Phi_{t}\\right)\\right]... \\right.\\right. \\\\\n& \\left.\\left. -\\lambda^{\\tau}_{t}(1-\\delta^{\\tau}_{t})(1-f_{e,t})p^{k}_{t}\\right] - (1-\\delta)\\left[\\left(\\frac{1-\\tau^{d}_{t+1}}{1-\\tau^{g}_{t+1}} + \\lambda^{d}_{t+1}\\right)... \\right.\\right. \\\\\n& \\left.\\left. \\times \\left[(1-f_{e,t+1}\\tau^{b}_{t+1}-\\tau^{ic}_{t+1})p^{k}_{t+1}+ (1-\\tau^{b}_{t+1})p^{k}_{t+1}\\left(\\frac{\\partial \\Phi_{t+1}}{\\partial I_{t+1}} + \\Phi_{t}\\right)\\right]... \\right.\\right. \\\\\n& \\left.\\left. -\\lambda^{\\tau}_{t+1}(1-\\delta^{\\tau}_{t+1})(1-f_{e,t})p^{k}_{t+1}\\right]\\right] \\left(\\frac{1-\\tau^{d}_{t+1}}{1-\\tau^{g}_{t+1}} + \\lambda^{d}_{t+1} \\right)^{-1}\n\\end{split}\n\\end{equation}\n\n\nUsing Equation \\ref{eqn:foc_ktau_tax} and iterating forward, we can find the value of $\\lambda^{\\tau}$ as:\n\\begin{equation}\n\\begin{split}\n& \\lambda^{\\tau}_{t}=\\underbrace{\\prod_{\\nu=t+!}^{\\infty}\\left(\\frac{1}{1+\\theta_{\\nu}}\\right)\\lambda^{\\tau}_{\\infty}}_{=0 \\text{ by transversality condition}} + \\sum_{u=t+1}^{\\infty} \\prod_{\\nu=t+1}^{u}\\left(\\frac{1}{1+\\theta_{\\nu}}\\right)\\left[\\left(\\frac{1-\\tau^{d}_{u}}{1-\\tau^{g}_{u}}+\\lambda^{d}_{u}\\right)\\left( f_{d,u}\\delta^{\\tau}_{u}+f_{ace,u}r_{ace,u} \\right)\\tau^{b}_{u}\\right]\\\\\n&\\implies \\lambda^{\\tau}_{t}= \\sum_{u=t+1}^{\\infty} \\prod_{\\nu=t+1}^{u}\\left(\\frac{1}{1+\\theta_{\\nu}}\\right)\\left[\\left(\\frac{1-\\tau^{d}_{u}}{1-\\tau^{g}_{u}}+\\lambda^{d}_{u}\\right)\\left( f_{d,u}\\delta^{\\tau}_{u}+f_{ace,u}r_{ace,u} \\right)\\tau^{b}_{u}\\right]\n\\end{split}\n\\end{equation}\n\nSubstituting in for $\\lambda^{\\tau}$ and multiplying through we have:\n\n\\begin{equation}\n\\begin{split}\nucc_{t} &= \\left({1+\\theta_{u+1}}\\right)\\left[\\left(\\frac{\\frac{1-\\tau^{d}_{t}}{1-\\tau^{g}_{t}} + \\lambda^{d}_{t}}{\\frac{1-\\tau^{d}_{t+1}}{1-\\tau^{g}_{t+1}} + \\lambda^{d}_{t+1}}\\right)\\left[(1-f_{e,t}\\tau^{b}_{t}-\\tau^{ic}_{t})p^{k}_{t}+ (1-\\tau^{b}_{t})p^{k}_{t}\\left(\\frac{\\partial \\Phi_{t}}{\\partial I_{t}} + \\Phi_{t}\\right)\\right]... \\right. \\\\\n& \\left. - \\left( \\sum_{u=t+1}^{\\infty} \\prod_{\\nu=t+1}^{u}\\left(\\frac{1}{1+\\theta_{\\nu}}\\right)\\left[\\left(\\frac{1-\\tau^{d}_{u}}{1-\\tau^{g}_{u}}+\\lambda^{d}_{u}\\right)\\left( f_{d,u}\\delta^{\\tau}_{u}+f_{ace,u}r_{ace,u} \\right)\\tau^{b}_{u}\\right]\\right) (1-\\delta^{\\tau}_{t})(1-f_{e,t})p^{k}_{t}\\right] ... \\\\\n& - (1-\\delta)\\left[ \\left((1-f_{e,t+1}\\tau^{b}_{t+1}-\\tau^{ic}_{t+1})p^{k}_{t+1}+ (1-\\tau^{b}_{t+1})p^{k}_{t+1}\\left(\\frac{\\partial \\Phi_{t+1}}{\\partial I_{t+1}} + \\Phi_{t}\\right)\\right] ... \\right. \\\\\n& \\left. - \\left( \\sum_{u=t+2}^{\\infty} \\prod_{\\nu=t+2}^{u}\\left(\\frac{1}{1+\\theta_{\\nu}}\\right)\\left[\\left(\\frac{1-\\tau^{d}_{u}}{1-\\tau^{g}_{u}}+\\lambda^{d}_{u}\\right)\\left( f_{d,u}\\delta^{\\tau}_{u}+f_{ace,u}r_{ace,u} \\right)\\tau^{b}_{u}\\right] \\right)(1-\\delta^{\\tau}_{t+1})(1-f_{e,t})p^{k}_{t+1}\\right]\n\\end{split}\n\\end{equation}\n\nIf taxes are equal to zero, adjustment costs are zero, and the dividend constraint is not binding then this simplifies to:\n\n\\begin{equation}\nucc_{t}= (r_{e,t}+ \\delta)p^{k}_{t} - (p^{k}_{t}-p^{k}_{t})\n\\end{equation}\n\nWhich is the familiar user cost of capital in models without taxes and frictions affecting investment. Where the cost of capital is equal to the market rental rate for capital plus the rate of depreciation, less capital gains from holding capital.\\\\\n\n\\ \\\\\n\\noindent\\noindent \\emph{Optimality Condition for Investment}\n\nWe can use Equations \\ref{eqn:foc_i_tax}, \\ref{eqn:foc_k_tax}, and \\ref{eqn:foc_b_tax} to find the optimality condition for investment as:\n\n\\begin{equation}\n\\begin{split}\n&\\underbrace{ \\left[(1-\\tau^{b}_{t}f_{e,t}-\\tau^{ic}_{t})p^{k}_{t} + \\left(\\frac{\\partial \\Phi_{t}}{\\partial I_{t}} + \\Phi_{t}\\right)(1-\\tau^{b}_{t})\\right]\\left(\\frac{1-\\tau^{d}_{t}}{1-\\tau^{g}_{t}} + \\lambda^{d}_{t}\\right)}_{\\text{MC of investment}} = \\\\\n& \\left(\\frac{1}{1+\\theta_{t+1}}\\right)\\left[(1-\\delta)q_{t+1} + \\left(\\frac{1-\\tau^{d}_{t+1}}{1-\\tau^{g}_{t+1}} + \\lambda^{d}_{t+1} \\right)\\left[(1-\\tau^{b}_{t+1})\\left(p_{t+1}MPK_{t+1}- p^{k}_{t+1}\\frac{\\partial \\Phi_{t+1}}{\\partial K_{t+1}}I_{t+1}\\right) ... \\right.\\right. \\\\\n& \\left.\\left.-(1-f_{c,t+1}\\tau^{b}_{t+1}) \\frac{\\partial c(B_{t+2},K_{t+1})}{\\partial K_{t+1}} \\right] \\right] ...\\\\\n& + (1-\\delta^{\\tau}_{t})(1-f_{e,t})p^{k}_{t}\\left(\\sum_{u=t}^{\\infty} \\prod_{\\nu=t}^{u}\\left(\\frac{1}{1+\\theta_{\\nu}}\\right)\\left[\\left(\\frac{1-\\tau^{d}_{u}}{1-\\tau^{g}_{u}}+\\lambda^{d}_{u}\\right)\\left( f_{d,u}\\delta^{\\tau}_{u}+f_{ace,u}r_{ace,u} \\right)\\tau^{b}_{u}\\right]\\right)\n\\end{split}\n\\end{equation}\n\nWe can solve for $q_{t}$ using Equation \\ref{eqn:foc_i_tax} and repeated iteration of Equation \\ref{eqn:foc_ktau_tax} to find $\\lambda^{\\tau}_{t}$:\n\n\\begin{equation}\n\\begin{split}\nq_{t+1} & = \\left(\\frac{1-\\tau^{d}_{t+1}}{1-\\tau^{g}_{t+1}} + \\lambda^{d}_{t+1}\\right)\\left[(1-f_{e,t+1}\\tau^{b}_{t+1}-\\tau^{ic}_{t+1})p^{k}_{t+1}+ (1-\\tau^{b}_{t+1})p^{k}_{t+1}\\left(\\frac{\\partial \\Phi_{t+1}}{\\partial I_{t+1}} + \\Phi_{t+1}\\right)\\right]... \\\\\n& - (1-\\delta^{\\tau}_{t+1})(1-f_{e,t+1})p^{k}_{t+1}\\left(\\sum_{u=t}^{\\infty} \\prod_{\\nu=t}^{u}\\left(\\frac{1}{1+\\theta_{\\nu}}\\right)\\left[\\left(\\frac{1-\\tau^{d}_{u}}{1-\\tau^{g}_{u}}+\\lambda^{d}_{u}\\right)\\left( f_{d,u}\\delta^{\\tau}_{u}+f_{ace,u}r_{ace,u} \\right)\\tau^{b}_{u}\\right]\\right)\n\\end{split}\n\\end{equation}\n\nWith this, we rewrite the condition for optimal investment as: \n\n\\begin{equation}\n\\begin{split}\n&\\underbrace{ \\left[(1-\\tau^{b}_{t}f_{e,t}-\\tau^{ic}_{t})p^{k}_{t} + \\left(\\frac{\\partial \\Phi_{t}}{\\partial I_{t}} + \\Phi_{t}\\right)(1-\\tau^{b}_{t})\\right]\\left(\\frac{1-\\tau^{d}_{t}}{1-\\tau^{g}_{t}} + \\lambda^{d}_{t}\\right)}_{\\text{MC of investment}} = \\\\\n& \\left(\\frac{1}{1+\\theta_{t+1}}\\right)\\left[(1-\\delta)\\left[\\left(\\frac{1-\\tau^{d}_{t+1}}{1-\\tau^{g}_{t+1}} + \\lambda^{d}_{t+1}\\right)\\left[(1-f_{e,t+1}\\tau^{b}_{t+1}-\\tau^{ic}_{t+1})p^{k}_{t+1}+ (1-\\tau^{b}_{t+1})p^{k}_{t+1}\\left(\\frac{\\partial \\Phi_{t+1}}{\\partial I_{t+1}} + \\Phi_{t+1}\\right)\\right]...\\right.\\right. \\\\\n& \\left.\\left. - (1-\\delta^{\\tau}_{t+1})(1-f_{e,t+1})p^{k}_{t+1}\\left(\\sum_{u=t}^{\\infty} \\prod_{\\nu=t}^{u}\\left(\\frac{1}{1+\\theta_{\\nu}}\\right)\\left[\\left(\\frac{1-\\tau^{d}_{u}}{1-\\tau^{g}_{u}}+\\lambda^{d}_{u}\\right)\\left( f_{d,u}\\delta^{\\tau}_{u}+f_{ace,u}r_{ace,u} \\right)\\tau^{b}_{u}\\right]\\right)\\right]... \\right. \\\\\n& \\left. + \\left(\\frac{1-\\tau^{d}_{t+1}}{1-\\tau^{g}_{t+1}} + \\lambda^{d}_{t+1} \\right)\\left[(1-\\tau^{b}_{t+1})\\left(p_{t+1}MPK_{t+1}- p^{k}_{t+1}\\frac{\\partial \\Phi_{t+1}}{\\partial K_{t+1}}I_{t+1}\\right) ... \\right.\\right. \\\\\n& \\left.\\left.-(1-f_{c,t+1}\\tau^{b}_{t+1}) \\frac{\\partial c(B_{t+2},K_{t+1})}{\\partial K_{t+1}} \\right] \\right] ...\\\\\n& + (1-\\delta^{\\tau}_{t})(1-f_{e,t})p^{k}_{t}\\left(\\sum_{u=t}^{\\infty} \\prod_{\\nu=t}^{u}\\left(\\frac{1}{1+\\theta_{\\nu}}\\right)\\left[\\left(\\frac{1-\\tau^{d}_{u}}{1-\\tau^{g}_{u}}+\\lambda^{d}_{u}\\right)\\left( f_{d,u}\\delta^{\\tau}_{u}+f_{ace,u}r_{ace,u} \\right)\\tau^{b}_{u}\\right]\\right)\n\\end{split}\n\\end{equation}\n\nA few notes about this condition. First, if dividend policy does not change from one period to the next (i.e., $\\lambda^{d}_{t}=\\lambda^{d}_{t+1}$ for all $t$), and if the ratio of the net of tax rates for dividend and capital gains income does not change (i.e., $\\frac{1-\\tau^{d}_{t}}{1-\\tau^{g}_{t}}=\\frac{1-\\tau^{d}_{t+1}}{1-\\tau^{g}_{t+1}}$ for all $t$), then dividend taxes have no impact on investment. This corresponds to the ``new view\" of dividend taxation. In this case, dividend taxes have no effect on investment decisions whether that investment is financed by retained earnings or not. The key is that the marginal source of finance is constant (i.e., $\\lambda^{d}_{t}=\\lambda^{d}_{t+1}$, for all $t$) . Instead, dividend taxes are capitalized into the value of the firm, but has no effect on marginal investment decisions. The second thing to note is that in the absence of taxes and investment frictions and with the prices of capital and output normalized to one, we get the familiar optimal condition for investment $r=MPK-\\delta$.\n\n\\subsubsection{Optimal Financial Policy}\n\n\\begin{proposition}\n\\label{prop:vn_div}\nNew equity issues and dividend distributions will not both be positive if the capital gains tax rate is less than the dividends tax rate (i.e., if $\\tau^{g}_{u}<\\tau^{d}_{u}$).\n\\end{proposition}\n\n\\begin{proof}\nSuppose that $DIV_{u}>0$ and $VN_{u}>0$, then Equation \\ref{eqn:foc_vn} simplifies to:\n \\begin{equation}\n\\label{eqn:foc_vn_pos}\n 1 = \\left(\\frac{1-\\tau^{d}_{u}}{1-\\tau^{g}_{u}}\\right)\\left(1-\\frac{\\partial \\Psi(VN_{u})}{\\partial VN_{u}}\\right) \n \\end{equation}\n \nWhich implies that :\n \\begin{equation}\n \\label{eqn:foc_vn_pos2}\n 1-\\tau^{g}_{u} = (1-\\tau^{d}_{u})\\left(1-\\frac{\\partial \\Psi(VN_{u})}{\\partial VN_{u}}\\right) \n \\end{equation}\n\n\nBut Equation \\ref{eqn:foc_vn_pos2} can't hold if $\\tau^{g}_{u}<\\tau^{d}_{u}$, because so long as $\\frac{\\partial \\Psi(VN_{u})}{\\partial VN_{u}}\\geq0$, then the left hand side of the equality exceeds the right hand side. Thus, firms will never both issue equity and distribute dividends in the same period.\n\\end{proof}\n\nIn fact, we do observe firms in the data do both, and the behavior has been terms the ``dividend puzzle\". To model this, you need to suppose some capital market imperfections that our model abstracts from. \n\nNote that if $\\tau^{g}_{u}>\\tau^{d}_{u}$, firms may issue new equity and distribute dividends. If the marginal costs of new equity issues is increase, firms will issue new equity up to the point that the marginal cost of new equity (through dilution of after-tax capital gains to current share holders) is equal to the marginal benefit (the after-tax dividend income to current shareholders). If marginal costs to new equity issues are flat or constant, we are in one of two cases. The first is where costs are relatively high (relative to the differential in capital gains and dividend taxes) and firms never issues dividends and new equity in the same period. The second is where costs are relatively low and no equilibrium exists. In this case, the marginal benefits of new equity issues always exceed the marginal costs and so they firm issues infinite amounts of new equity to finance dividend distributions.\\\\\n\n\\ \\\\\n\n\\noindent\\noindent \\emph{The Marginal Cost of Finance}\n\n\\textcolor{red}{Is there a way to write the marginal cost of finance? Is it always the same? I see it changing as the source of financing changes between debt, equity, and retained earnings.}\n\nIf the firm's marginal source of finance is debt, then the marginal cost of finance is given by:\n\n\\begin{equation}\n\\begin{split}\nmcf_{b,t} & = \\left(\\frac{1}{1+\\theta_{t+1}}\\right)\\left(\\frac{1-\\tau^{d}_{t+1}}{1-\\tau^{g}_{t+1}} + \\lambda^{d}_{t+1}\\right)\\left((1-\\tau^{b}_{t+1}f_{i,t+1})r_{b,t+1}+(1-\\tau^{b}_{t+1}f_{p,t+1})\\right)... \\\\\n& + \\left(\\frac{1-\\tau^{d}_{t}}{1-\\tau^{g}_{t}} + \\lambda^{d}_{t}\\right)(1-\\tau^{b}_{t})\\frac{\\partial c(B_{t+1},K_{t})}{\\partial B_{t+1}}\n\\end{split}\n\\end{equation}\n\n\\textcolor{red}{Can we determine when/if a firm will raise debt and distribute dividends? It's a bit harder here since the firm can lend (i.e., hold negative debt), but there should be some condition on the benefits to a dollar inside of the firm versus a dollar of debt. For example, if $mcf_{b,t}>1$, then the firm does not both issue debt and distribute dividends.}\n\n\\textcolor{red}{Since the opportunity cost of using retained earnings for investment is that it can't be lent out (where it earns a rate of return $r_{b,t}$), isn't the marginal cost of finance from retained earnings similar to the above? Or at least something like the following (which explicitly shows that the cost of debt is asymmetric (i.e., the cost is zero when lending):}\n\n\\begin{equation}\nmcf_{re,t} = \\left(\\frac{1}{1+\\theta_{t+1}}\\right)\\left(\\frac{1-\\tau^{d}_{t+1}}{1-\\tau^{g}_{t+1}} + \\lambda^{d}_{t+1}\\right)(1-\\tau^{b}_{t+1}r_{b,t+1}\n\\end{equation}\n\nThe marginal cost of equity finance is given by the dilution of shareholder value plus the costs due to financial frictions that lower the amount raised that can be used for investment:\n\n\\begin{equation}\nmcf_{e,t} = 1+ \\left(\\frac{1-\\tau^{d}_{t}}{1-\\tau^{g}_{t}} + \\lambda^{d}_{t}\\right)\\frac{\\partial \\Psi(VN_{t})}{\\partial VN_{t}}\n\\end{equation}\n\nIf use external finance, the firm may use both debt and equity. If this is the case, then their marginal costs must be equivalent in equilibrium.\n\n\\textcolor{red}{HOW DOES THIS FINANCIAL POLICY FIT WITH INVESTMENT POLICY? I think that the FOCs for investment and labor demand determine the amount of labor and capital. Then financing is determined by what is needed finance the purchase of these factors of production. Where the firm using the cheaper source until it is exhausted or it's marginal cost equals that of the other sources. However, it seems like there marginal costs of finance would be important in determining the investment policy (e.g., if financing is cheaper, then you invest more...). Is that all contained in $\\lambda^{d}_{t}$?}\n\n\n\\subsection{Firm Policy in the Steady State}\n\nIn the steady state, the first order conditions of the firm look like the following:\n\n\\begin{equation}\n\\label{eqn:foc_l_ss}\n \\bar{p}\\overline{MPL} - \\frac{\\partial \\overline{TE}}{\\partial \\overline{EL}}= \\bar{w}\n\\end{equation}\n\n \\begin{equation}\n\\label{eqn:foc_i_ss}\n\\bar{q} + \\bar{\\lambda}^{\\tau}(1-\\bar{\\delta}^{\\tau})(1-\\bar{f}_{e})\\bar{p}^{k} = \\left(\\frac{1-\\bar{\\tau}^{d}}{1-\\bar{\\tau}^{g}} + \\bar{\\lambda}^{d}\\right)\\left[\\bar{p}^{k}(1 + \\frac{\\partial \\overline{TE}}{\\partial \\bar{I}}\\right]\n\\end{equation}\n\n \\begin{equation}\n\\label{eqn:foc_k_ss}\n\\bar{q}_{u} = \\left(\\frac{1}{\\bar{\\theta}+\\delta}\\right) \\left(\\frac{1-\\bar{\\tau}^{d}}{1-\\bar{\\tau}^{g}} + \\bar{\\lambda}^{d} \\right)\\left[\\bar{p}\\overline{MPK} - \\frac{\\partial c(\\bar{B},\\bar{K})}{\\partial \\bar{K}}-\\bar{\\tau}^{p}\\bar{p}^{k}-\\frac{\\partial \\overline{TE}}{\\partial \\bar{K}} \\right]\n\\end{equation}\n\n\n \\begin{equation}\n\\label{eqn:foc_b_ss}\n\\left(1-\\frac{\\partial c(\\bar{B},\\bar{K})}{\\partial \\bar{B}}-\\frac{\\partial \\overline{TE}}{\\partial \\bar{B}}\\right)= \\left(\\frac{1}{1+\\bar{\\theta}}\\right) \\left((1+\\bar{r}_{b})+\\frac{\\partial \\overline{TE}}{\\partial \\bar{B}}\\right)\n\\end{equation}\n\n\n \\begin{equation}\n\\label{eqn:foc_vn_ss}\n 1 = \\left(\\frac{1-\\bar{\\tau}^{d}}{1-\\bar{\\tau}^{g}} + \\bar{\\lambda}^{d}\\right)\\left(1-\\frac{\\partial \\Psi(\\overline{VN})}{\\partial \\overline{VN}}\\right) + \\bar{\\lambda}^{v}\n\\end{equation}\n\n \\begin{equation}\n\\label{eqn:foc_ktau_ss}\n \\bar{\\lambda}^{\\tau} = - \\left(\\frac{1}{\\bar{\\theta}+\\bar{\\delta}^{\\tau}}\\right)\\left(\\frac{1-\\bar{\\tau}^{d}}{1-\\bar{\\tau}^{g}} + \\bar{\\lambda}^{d} \\right)\\frac{\\partial \\overline{TE}}{\\partial \\bar{K}^{\\tau}} \n\\end{equation}\n\nUsing these partial derivatives of the tax function with respect to the endogenous variables in the SS, we can rewrite the FOCs as:\n\n\n\\begin{equation}\n\\label{eqn:foc_l_tax_ss}\n\\begin{split}\n \\bar{p}\\overline{MPL} = \\bar{w} \n \\end{split}\n\\end{equation}\n\n \\begin{equation}\n\\label{eqn:foc_i_tax_ss}\n\\begin{split}\n & \\bar{q} + \\bar{\\lambda}^{\\tau}(1-\\bar{\\delta}^{\\tau})(1-\\bar{f}_{e})\\bar{p}^{k} = \\left(\\frac{1-\\bar{\\tau}^{d}}{1-\\bar{\\tau}^{g}} + \\bar{\\lambda}^{d}\\right)\\left[(1-\\bar{f}_{e}\\bar{\\tau}^{b}-\\bar{\\tau}^{ic})\\bar{p}^{k}\\right]\n\\end{split}\n\\end{equation}\n\n\n \\begin{equation}\n\\label{eqn:foc_k_tax_ss}\n\\begin{split}\n\\bar{q}_{u} = \\left(\\frac{1}{\\bar{\\theta}+\\delta}\\right) \\left(\\frac{1-\\bar{\\tau}^{d}}{1-\\bar{\\tau}^{g}} + \\bar{\\lambda}^{d} \\right)\\left[(1-\\bar{\\tau}^{b})\\left(\\bar{p}\\overline{MPK}\\right)-(1-\\bar{f}_{c}\\bar{\\tau}^{b}) \\frac{\\partial c(\\bar{B},\\bar{K})}{\\partial \\bar{K}} \\right]\n\\end{split}\n\\end{equation}\n\n \\begin{equation}\n\\label{eqn:foc_b_tax}\n\\begin{split}\n \\left((1-\\bar{\\tau}^{b}\\bar{f}_{b})-(1-\\bar{\\tau}^{b}\\bar{f}_{c})\\frac{\\partial c(\\bar{B}_{u},\\bar{K})}{\\partial \\bar{B}}\\right)= \\left(\\frac{1}{1+\\bar{\\theta}}\\right) \\left((1+\\bar{\\tau}^{b}\\bar{f}_{p})+(1-\\bar{\\tau}^{b}\\bar{f}_{i})\\bar{r}_{b}\\right)\n \\end{split}\n\\end{equation}\n\n \\begin{equation}\n\\label{eqn:foc_vn_tax_ss}\n\\begin{split}\n 1 = \\left(\\frac{1-\\bar{\\tau}^{d}}{1-\\bar{\\tau}^{g}} + \\bar{\\lambda}^{d}\\right)\\left(1-\\frac{\\partial \\Psi(\\overline{VN})}{\\partial \\overline{VN}}\\right) + \\bar{\\lambda}^{v}\n \\end{split}\n\\end{equation}\n\n \\begin{equation}\n\\label{eqn:foc_ktau_tax_ss}\n\\begin{split}\n \\bar{\\lambda}^{\\tau} = \\left(\\frac{1}{\\bar{\\theta}+\\bar{\\delta}^{\\tau}}\\right)\\left(\\frac{1-\\bar{\\tau}^{d}}{1-\\bar{\\tau}^{g}} + \\bar{\\lambda}^{d} \\right)\\bar{\\tau}^{b}\\left(\\bar{f}_{d}\\bar{\\delta}^{\\tau}+\\bar{f}_{ace}\\bar{r}_{ace}\\right)\n \\end{split}\n\\end{equation}\n\n\nWe also can write the laws of motion for the physical and fiscal capital stocks in the steady state as:\n\n\\begin{equation}\n\\label{eqn:lom_k_ss}\n\\bar{I}=\\delta\\bar{K}\n\\end{equation}\n\n\\begin{equation}\n\\label{eqn:lom_ktau_ss}\n\\bar{K}^{\\tau}=(1-\\bar{f}_{e})\\bar{p}^{k}\\bar{K}\n\\end{equation}\n\nIn equilibrium, firm value must be positive. This implies that $\\overline{DIV}>\\overline{VN}$. As shown in Proposition \\ref{prop:vn_div}, if $\\bar{\\tau}^{g}<\\bar{\\tau}^{d}$, the firm will not both issue new equity and distribute dividends. Therefore, if $\\bar{\\tau}^{g}<\\bar{\\tau}^{d}$ we know that $\\overline{DIV}>0$ and $\\overline{VN}=0$. The means that $\\bar{\\lambda}^{v}>0$ and $\\bar{\\lambda}^{d}=0$. \n\n\\subsubsection{Solving for the Steady State}\n\nBy the above argument, we know that $\\overline{DIV}>0$ and $\\overline{VN}=0$. Therefore $\\bar{\\lambda}^{d}=0$ . We can thus solve for $\\bar{\\lambda}^{v}$ by Equation \\ref{eqn:foc_vn_tax_ss} and $\\bar{\\lambda}^{\\tau}$ by Equation \\ref{eqn:foc_ktau_tax_ss}. With these in hand, we can then solve for $\\bar{q}(\\bar{p}^{k})$ from Equation \\ref{eqn:foc_i_tax_ss}. Equations \\ref{eqn:foc_l_tax_ss}, \\ref{eqn:foc_k_tax_ss}, and \\ref{eqn:foc_b_tax_ss} then imply $\\bar{EL}$, $\\bar{K}$, $\\bar{B}$ as functions of $\\bar{p}^{k}$ and $\\bar{p}$. We can then use the laws of motion (Equations \\ref{eqn:lom_k_ss} and \\ref{eqn:lom_ktau_ss}) to get $\\bar{I}$ and $\\bar{K}^{\\tau}$ as functions of the input and output prices. \\textcolor{red}{The key is then to solve for the output prices as a function of the parameters and factor input prices ($\\bar{r}_{b}$, $\\bar{r}_{e}$ and $\\bar{w}$). To do this, we need to use the assumption of free entry and that prices equals marginal cost in equilibrium???}. With the output price in hand, we use the fixed coefficient matrix relating industry outputs to industry inputs to find $\\bar{p}^{k}$. We are then able so solve the system of equations for given factor prices. \n\n\n\n\\section{The Problem of the Multinational Parent Corporation}\n\nThe problem of the multinational parent corporation will be defined similarly to that of the domestic corporation. In particular, the functional forms for the production function and financial frictions will remain the same, though parameter values may differ. What differs for the multinational parent is it's relations with foreign subsidiaries. The parent provides intermediate inputs to the foreign subsidiaries and can choose the price at which these transactions occur. This ability to engage in transfer pricing allows the multinational to lower it's worldwide tax liability by shifting net income to low tax jurisdictions. Second, the parent can engage in more general income shifting by moving profits to tax havens. The ability to shift income in this way captures the ability of corporations to shift income through other mechanisms that we do not explicitly model. Finally, multinational corporations face a discrete location choice with respect to a firm-specific fixed factor of production. \n\n\\subsection{Firm Production}\n\nFirm's combine capital, $K$, and effective labor, $EL$, with a location-specific fixed factor of production, $A$, and firm-specific fixed-factor of production, $H$, to produce output, $X$. We can think of the location-specific fixed factor of production as ``location specific capital\". It is fixed in the sense that its supply is perfectly inelastic. It is location specific in the sense that it is proportional to the size of the population in the firm's home country at time $t$. \\textcolor{red}{CORTAX documentation at first suggests this factor is chosen optimally by the firm, but there is not first order condition for this choice shown. The documentation does state that this factor is paid its marginal product. So there are only economic profits before you account for the return to this factor of production. I'm also not sure if we need this fixed factor of production to be proportional to the population. CORTAX says yes so that you don't have productivity differential arising from differences in country size. They consider multi-country model, but only steady state. Do we need something similar so productivity doesn't depend upon population at time $t$?} The firm-specific fixed factor of production can be thought of as intangibles, such as patents or trade secrets the firms has. These intangibles earn economic rents and can easily be transfered to different tax jurisdictions (\\textcolor{red}{Is this what we want to think of it as? Then you'd think it could affect productivity not just in the country is is located. Also, we need to be very careful about how to enter this into the model. In particular, we don't want to have to keep track of the capital and labor entering into production functions in other counties as CORTAX does.}). We write the amount of output produced in the home country as a function of this fixed factor and the value added, $VA$, from the input of capital and labor:\n\n\\begin{equation}\nX_{t} = A_{t}H_{t}^{\\alpha_{H}}(VA_{t})^{\\alpha_{v}},\n\\end{equation} \n\n\\noindent\\noindent where $\\alpha_{v}$ is the share of output attributable to the firm's value added and $\\alpha_{H}$ is the share of output attributable to the firm-specific capital. The location-specific fixed factor of production is given by:\n\n\\begin{equation}\nA_{t} = (A_{0,t}\\omega_{t}N_{t})^{1-\\alpha_{H}-\\alpha_{v}}\n\\end{equation}\n\n\\noindent\\noindent Thus the input from fixed factor of production used by the firm is given by the level of total factor productivity (TFP), $A_{0,t}$, and a exogenous share of the population, $N_{t}$ where the share is given by the parameter $\\omega_{t}$ (\\textcolor{red}{Not sure if we want this to vary by time, or just across production industry.}). The share parameters must sum to one. That is, $\\sum_{m=1}^{M} \\omega_{m,t} = 1$. We assume that TFP grows at the same rate across industry, with the growth rate given by $g_{a}$. The value added is given by a CES function:\n\n\\begin{equation}\n\\label{eqn:prod_fun}\nF(A_{0,t},K_{t},EL_{t})=VA_{t} =A_{0,t} \\left[(\\gamma_{})^{1/\\epsilon_{}}(K_{t})^{(\\epsilon-1)/\\epsilon_{}}+(1-\\gamma_{})^{1/\\epsilon_{}}(e^{g_{y}t}EL_{t})^{(\\epsilon_{}-1)/\\epsilon_{}}\\right]^{(\\epsilon_{}/(\\epsilon_{}-1))},\n\\end{equation}\n\n\\subsection{Firm Accounting}\n\nThe multinational corporation is going to maximize firm value, which is determined by its worldwide after-tax profit. Thus we' will need to define domestic and foreign profits.\n\n\\subsubsection{Domestic Profits}\n\nAfter-tax US profits from a financial accounting perspective are:\n\n\\begin{equation}\n\\label{eqn:profit_book_mnc_us}\n\\begin{split}\n\\Pi^{US,book}_{t} = & p_{t}X_{t}+\\underbrace{(p_{row,t}-1)Q_{row,t}-c^{q}(Q_{row,t})}_{\\text{Transfer pricing}}-w_{t}EL_{t}-\\delta K_{t} -\\Phi_{t}p^{k}_{t}I_{t}-(1+r_{b,t})B_{t}- c(B_{t+1},K_{t})...\\\\\n& -\\tau^{p}_{t}K_{t}-TE(\\tilde{\\Pi}^{US, tax}_{t})\n\\end{split}\n\\end{equation}\n\nTransfer pricing operates through the multinational charging its subsidiaries in the rest of the world a price $p_{row,t}$ for one dollar of intermediate good. The variable $Q_{row,t}$ denotes the quantity of intermediate goods (in dollars) that the firm sells/buys from its subsidiaries in the rest of the world. There is a cost to transfer pricing, given by the function $c^{q}(Q_{row,t})$. \n\nNote that total taxes, $TE$ are a function of taxable income after profit shifting, $\\tilde{\\Pi}^{US, tax}_{t}$. We define the firm's US profits from a tax accounting perspective as:\n\\begin{equation}\n\\label{eqn:profit_tax}\n\\begin{split}\n\\Pi^{US, tax}_{t}= & p_{t}X_{t}+\\underbrace{(p_{row,t}-1)Q_{row,t}-c^{q}(Q_{row,t})}_{\\text{Transfer pricing}}-w_{t}EL_{t}-f_{e,t}p^{K}_{t}I_{t}-\\Phi_{t}I_{t}-f_{i,t}r_{b,t}B_{t}...\\\\\n& -f_{c,t}c(B_{t+1},K_{t})+f_{p,t}\\delta B_{t}+ f_{b,t}B_{t+1}-f_{d,t}\\delta^{\\tau}_{t}K^{\\tau}_{t}-f_{ace,t}r_{ace,t}K^{\\tau}_{t}-\\tau^{p}_{t}p^{k}_{t}K_{t}\n\\end{split}\n\\end{equation}\n\nWe let $\\theta$ be the amount of profits shifted overseas. Thus, $\\tilde{\\Pi}^{US, tax}_{t}=\\theta \\Pi^{US, tax}_{t}$. Shifting profits comes a a cost, $c^{ps}(\\theta)$. This cost function is a convex function so that the marginal cost of shifting income is increasing and will make it infinitely expensive to shift 100\\% of profits.\n\n\\subsubsection{Foreign Profits}\n\nOur model does not capture the the rich detail of production in each country. Instead, we take the component of foreign profits due to foreign economic activity as exogenous. We define two foreign jurisdictions. The ``rest of the world\" refers to non-tax haven countries. Thus we bifurcate foreign economies into tax havens and non-tax havens. We assume that transfer pricing activities tax place with corporate subsidiaries in the ``rest of the world\", which we think of as trading partners. Profit shifting activities represent interactions with tax havens. We let pre-tax foreign earnings in period $t$ be defined as $EARN^{row}_{t}$ and $EARN^{h}_{t}$ for the rest of the world and tax haven jurisdictions, repsectively. Foreign after-tax profits from an accounting perspective are thus defined as:\n\n\\begin{equation}\n\\label{eqn:profit_book_mnc_row}\n\\begin{split}\n&\\Pi^{row,book}_{t} =EARN^{row}_{t} - (p_{row,t}-1)Q_{row,t} - TE^{row}_{t}(\\Pi^{row, tax}_{t})\\\\\n&\\text{and} \\\\\n&\\Pi^{h,book}_{t} EARN^{h}_{t} + \\theta\\Pi^{US,book}_{t} - TE^{h}_{t}(\\tilde{\\Pi}^{h, tax}_{t}),\n\\end{split}\n\\end{equation}\n\nwhere\n\\begin{equation}\n\\label{eqn:profit_tax_mnc_row}\n\\begin{split}\n&\\Pi^{row, tax}_{t} = EARN^{row}_{t} - (p_{row,t}-1)Q_{row,t}\\\\\n&\\text{and} \\\\\n&\\Pi^{h, tax}_{t} = EARN^{h}_{t} \\\\\n&\\text{and} \\\\\n&\\tilde{\\Pi}^{h, tax}_{t}= EARN^{h}_{t} + (1-\\theta)\\Pi^{US,tax}_{t},\n\\end{split}\n\\end{equation}\n\n\n\n\\subsubsection{Multinational Cash Flow}\n\nThe multinational's cash flow is defined by the sum of its profits at home and abroad:\n\n\n\\begin{equation}\n\\label{eqn:cash_flow_mnc}\n\\begin{split}\nDIV_{t} = & \\underbrace{(1-\\theta)\\Pi^{US,book}_{t}}_{\\text{After tax domestic profits}} + \\underbrace{\\Pi^{row,book}_{t} + \\Pi^{h,book}_{t}}_{\\text{After tax foreign profits}} + B_{t+1} + VN_{t}\n\\end{split}\n\\end{equation}\n\nNote that the above formulation makes some implicit assumptions about accounting rules. The most relevant of which is that a dollar of taxable income shifted from the US equals one dollar of taxable income abroad.\n\nThe foreign tax functions are:\n\n\\begin{equation}\n\\label{eqn:foreign_tax_row}\nTE^{row}_{t}(EARN^{row}_{t}- (p_{row,t}-1)Q_{row,t}) = \\tau^{b,row}_{t}(EARN^{row}_{t} - (p_{row,t}-1)Q_{row,t}),\n\\end{equation}\n\n\\begin{equation}\n\\label{eqn:foreign_tax_h}\nTE^{h}_{t}(EARN^{h}_{t} + \\theta\\Pi^{US,tax}_{t}) = \\tau^{b,h}_{t}(EARN^{h}_{t} + \\theta\\Pi^{US,tax}_{t}),\n\\end{equation}\n\n\\noindent\\noindent where $\\tau^{b,row}_{t}$ and $\\tau^{b,h}_{t}$ is the marginal effective tax rate on foreign profits in the non-tax haven and tax haven jurisdictions. \\textcolor{red}{Note about calibration: We likely calculate these as a weighted average of the corporate income tax rate on trading partners for firms in a given industry (for the rest of world) and to a rate amongst tax havens (probably zero).}\n\nLetting $\\Pi^{x,pre}_{t}$ denote pre-tax (and pre-transfer pricing) accounting profits in jurisdiction $x$ in period $t$, we can rewrite the firm's cash flow constraint as:\n\n\\begin{equation}\n\\label{eqn:cash_flow_mnc2}\n\\begin{split}\nDIV_{t} = & (1-\\theta)\\Pi^{US,pre}_{t} + (p_{row,t}-1)Q_{row,t} - \\tau^{b,US}_{t}((1-\\theta)\\Pi^{US,tax}_{t}) + \\tau^{ic}_{t}p^{k}_{t}I_{t} ... \\\\\n& + \\Pi^{row,pre}_{t}- (p_{row,t}-1)Q_{row,t} - \\tau^{b,row}_{t}\\Pi^{row,tax}_{t} ...\\\\\n& + \\Pi^{h,pre}_{t}- \\tau^{b,row}_{t}(\\Pi^{h,tax}_{t} + \\theta\\Pi^{US,tax}_{t}) + B_{t+1} + VN_{t} \\\\\n = & \\Pi^{US,pre}_{t} + EARN^{row}_{t} + EARN^{h}_{t} - ((1-\\theta)\\tau^{b,US}_{t} + \\theta\\tau^{b,h}_{t})\\Pi^{US,tax}_{t} ...\\\\\n & + \\tau^{b,row}(p_{row,t}-1)Q_{row,t} + \\tau^{ic}_{t}p^{k}_{t}I_{t} - \\tau^{b,row}_{t}(EARN^{row}_{t}) - \\tau^{b,h}_{t}(EARN^{h}_{t}) + B_{t+1} + VN_{t}\n\\end{split}\n\\end{equation}\n\n\\textcolor{red}{What about repatriation? Do we need to wall off foreign profits from domestic dividends (or for use for domestic investment) unless they are subjected to the US tax? Or should we assume they are freely available since the firm can use intracompany debt to move them? If the latter, there should be some cost of this - a cost which is affected by policies on intracompany debt. If the former, we'll need to keep track of the stock of foreign earnings.}\n\n\\textcolor{red}{Also, should we think about foreign tax credits in the above? If repatriation, yes. Then need to think about stock of earnings in tax havens and not...}\n\n\n\\subsubsection{Discrete Location Choice}\n\nRecall the production function:\n\n\\begin{equation}\nX_{i,t} = (A_{0,i,t}\\omega_{i,t}N_{i,t})^{1-\\alpha_{v}-\\alpha_{H}}H_{i,t}^{\\alpha_{H}}VA_{i,t}^{\\alpha_{v}},\n\\end{equation}\n\n\\noindent\\noindent where $i$ denotes the country and $H$ is the firm-specific capital that is mobile across countries. We will assume that there are no adjustment costs associated with moving $H$. This is helpful so that we do not need to keep track on the amount of firm-specific capital in the various tax jurisdictions. It may therefore be best to think of this capital as firm-specific intangible capital like patents, brandnames, and managerial talent that may be relocated at relatively low cost. \\textcolor{red}{One problem with this interpretation is that it would seem that the effect of $H$ could affect the firm's subsidiaries in all countries - regardless of where is was located.}\n\n\\textcolor{red}{\\citet{DD2009} separate this decision from all others by showing that $H$ will be distributed in a way that is proportional to the tax rates and amount of capital and labor employed across countries. Can we do this? Seems like you need to choose $H$ jointly with $K$, and $EL$ since $H$ affects marginal productivities of these... But can you separate given the functional form of the production function?} \n\nNote that we don't want to have to track the capital and labor employed abroad. But with the functional form of this production function, we don't have to. Consider:\n\n\\begin{equation}\n\\begin{split}\n EARN_{i,t}=p_{i,t}X_{i,t} = p_{i,t}(A_{0,i,t}\\omega_{i,t}N_{i,t})^{1-\\alpha_{v}-\\alpha_{H}}H_{i,t}^{\\alpha_{H}}VA_{i,t}^{\\alpha_{v}} \\\\\n\\end{split}\n\\end{equation}\n\nIf we increase $H$ by a factor of $\\lambda$ we increase earnings by $\\lambda^{\\alpha_{H}}$:\n\\begin{equation}\n\\begin{split}\nX2_{i,t} = (A_{0,i,t}\\omega_{i,t}N_{i,t})^{1-\\alpha_{v}-\\alpha_{H}}(\\lambda H_{i,t})^{\\alpha_{H}}VA_{i,t}^{\\alpha_{v}} \\\\\nX2_{i,t} = (A_{0,i,t}\\omega_{i,t}N_{i,t})^{1-\\alpha_{v}-\\alpha_{H}}\\lambda^{\\alpha_{H}} H_{i,t}^{\\alpha_{H}}VA_{i,t}^{\\alpha_{v}} \\\\\nX2_{i,t} = \\lambda^{\\alpha_{H}}(A_{0,i,t}\\omega_{i,t}N_{i,t})^{1-\\alpha_{v}-\\alpha_{H}} H_{i,t}^{\\alpha_{H}}VA_{i,t}^{\\alpha_{v}} \\\\\nX2_{i,t} = \\lambda^{\\alpha_{H}}X_{i,t}\n\\end{split}\n\\end{equation}\n\nThus, we can just increase foreign pre-tax earnings by the amount that $H$ is shifted to that jurisdiction.\n\n\\subsubsection{Why 3 ways to shift profits?}\n\nThere are three ways that multinational firms can shift income across tax jurisdictions:\n\\begin{enumerate}\n\\item Transfer pricing\n\\item Shifting of profits\n\\item Location of firm-specific capital\n\\end{enumerate}\n\nThere three all differ in how they affect the firm. Transfer pricing and profit shifting affect firm profits in very similar ways. The fundamental difference between the two in the model is the effective tax rate the shifted income faces. We assume that transfer pricing is done with trading partners and therefore faces the tax rate $\\tau^{b,row}$. On the other hand, profit shifting is doing to a particularly low tax jurisdiction and faces a rate that applies to tax havens, $\\tau^{b,h}$. If the US corporate rate would drop, this relieves pressure on transfer pricing to a greater degree than profit shifting because of the differences in rates between tax haven and non-tax haven countries (the tax haven's having very low rates).\n\nThe third channel through which firms can shift profits is by locating firm-specific capital abroad. The movement of this capital not only affects income, but affects firm productivity in domestic and foreign jurisdictions. That is to say that this form of profit shifting will have direct equilibrium effects on the pre-tax returns to labor and capital. It should also be the cast that this discrete locational choice is based on average tax rates, rather than marginal tax rates. \\textcolor{red}{Not sure if the model has is set up this way.}\n\n\\section{Multinational Subsidiaries}\n\nI think we can get away with the exogenous foreign pre-tax earnings as noted above and we do not need to model foreign subs. We can also probably get away with just one firm per production industry with a level of exogenous foreign activity that varies across industry. We can also have the parameters of income shifting vary across industry to match observed income shifting activity across sectors.\n\n \\section{Relating Firm Investment and Production Goods}\\label{sec:prod_invest_map}\n \n Our model contains $M$ production industries, each of which chooses investment that is a composite good from these production processes. We denote the quantity of production good $m$ in period $t$ as $X_{m,t}$. We relate the output of the production sectors to their inputs using a fixed coefficient model. That is, each investment good is made up of a mix of the outputs of different production sectors. This means that the composition of these investment goods do not respond to prices. The weights that determine the mix for each consumption goods are given in the matrix $\\Xi$. Element $\\xi_{j,m}$ of the matrix $\\Xi$ corresponds to the percentage contribute of the output of industry $m$ in the production of the investment good for industry $j$. The total supply of investment good $j$ in the economy at time $t$ is thus given by: \n \n \\begin{equation} \\label{eqn:mix_cons}\n I_{j,t} = \\sum_{m=1}^{M}\\xi_{j,m}X_{m,t} \n \t\\end{equation}\n\t\n\tAnd thus the price of a unit of investment good for industry $m$ at time $t$ is:\n\t\n \\begin{equation} \\label{eqn:mix_cons_price}\n p^{K}_{j,t} = \\sum_{m=1}^{M}\\xi_{j,m}p_{m,t}, \n \t\\end{equation}\n \n Where $p_{m}$ is the price of output of production sector $m$ at time $t$.\n\n\n\n", "meta": {"hexsha": "80a3830b4f2153575295fc6b2e5b21fe1eeed305", "size": 76272, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Model Writeup/Firms_description.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": "Model Writeup/Firms_description.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": "Model Writeup/Firms_description.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": 82.9945593036, "max_line_length": 2651, "alphanum_fraction": 0.6873688903, "num_tokens": 25283, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185351961013, "lm_q2_score": 0.3522017956470284, "lm_q1q2_score": 0.19935274446556764}}
{"text": "\\documentclass[12pt]{article}\n\n\\usepackage{amsmath}\n\\usepackage{graphicx}\n\\usepackage{hyperref}\n\\usepackage{cite}\n\\usepackage[margin=1.2in]{geometry}\n\n\\providecommand{\\eqn}[1]{eqn.~(\\ref{eqn:#1})}\n\\providecommand{\\tab}[1]{Table~\\ref{tab:#1}}\n\\providecommand{\\fig}[1]{Figure~\\ref{fig:#1}}\n\n\\providecommand{\\vecsymbol}[1]{\\ensuremath{\\boldsymbol{#1}}}\n%\\providecommand{\\pv}{\\vecsymbol{p}}\n%\\providecommand{\\deltav}{\\vecsymbol{\\delta}}\n\n\\title{Observing Hour Angle Assignments\\\\\nfor the DESI Survey\\\\\n\\vspace{5mm}{\\large\\bf DESI-doc-3060-v1}}\n\\author{David Kirkby, Kyle Dawson}\n\n\\begin{document}\n\\maketitle\n\n\\section{Introduction}\n\nThis note briefly describes the algorithm used to assign a near-optimal observing hour angle (HA) to each tile in the DESI footprint~\\cite{desi-717} and documents the result for the current baseline survey strategy~\\cite{desi-1767, desi-1770}.\n\nThe algorithm is implemented in python code in the {\\tt desisurvey} package\\footnote{\\url{https://github.com/desihub/desisurvey}} and the reader is referred there for implementation details. A jupyter notebook to create the plots in this note is provided under {\\tt desisurvey/doc/nb/}. The LaTeX source for this note is maintained under {\\tt desimodel/doc/tex/desi3060/}.\n\n\\section{Algorithm Description}\n\nThe algorithm is run separately for each program (DARK, GRAY, BRIGHT) and has two main inputs:\n\\begin{itemize}\n \\item the date range to optimize the program for, and\n \\item a list of tiles remaining to observe in the program.\n\\end{itemize}\nThe date range determines the available hours at each apparent local sidereal time (LST) for the specified program, taking into account planned shutdowns (during the annual monsoon and full-moon), expected weather outages each month, and the solar and lunar ephemerides that determine the time available to the program during each night. The list of tiles determines the required exposure time at each LST, given HA assignments and an exposure-time calculator.\n\nThe basic idea of the algorithm is to iteratively adjust the HA assignments of each tile to minimize a score function that accounts for two metrics:\n\\begin{itemize}\n \\item the matching of available and planned LST usage, and\n \\item the total required exposure time.\n\\end{itemize}\nWe run the algorithm in two different modes:\n\\begin{itemize}\n \\item Start of survey: optimize all tiles over the nominal five-year survey dates.\n \\item Afternoon planning: optimize all tiles not yet observed for the remainder of the survey.\n\\end{itemize}\nThe first mode is only used before the survey starts and then only needs to be rerun after a change in the definition of the tiles, programs, or nominal observing schedule. The second mode is run regularly during the survey and adjusts HA assignments to reflect actual observing progress and any schedule changes.\n\nMost of the assumptions used in the survey planning and program definitions are listed in a text configuration parameter file\\footnote{\\url{https://github.com/desihub/desisurvey/blob/master/py/desisurvey/data/config.yaml}}. One parameter, in particular, limits the HA solution space by requiring that all tiles are observed above a minimum altitude angle of $30^\\circ$. In order to allow some leeway for exposure duration, we calculate a maximum $|\\text{HA}|$ for each tile corresponding to its declination and a minimum altitude of $35^\\circ$.\n\n\\subsection{Initialization}\n\nThe initial HA assignments that are subsequently optimized can be set in three different ways:\n\\begin{itemize}\n \\item Read HAs from a file.\n \\item Set all HAs to zero.\n \\item Assign HAs to approximately match the cummulative distribution functions of available and planned LST usage.\n\\end{itemize}\nThe first method is used during afternoon planning, while the last two methods bootstrap the optimization at the start of the survey.\n\nAssigning zero initial HAs minimizes the total exposure time required, but generally leads to a large mismatch between the available and planned LST usage. While conceptually simple, this approach is inefficient since it requires a large number of iterations to converge to a near-optimal solution. \\fig{LST_zero0} compares the available and planned LST usage after initializing\nall HAs to zero.\n\n\\begin{figure}[htb]\n\\begin{center}\n\\includegraphics[width=6in]{LST_zero0}\n\\caption{Available (red) and planned (blue) LST usage for the HA=0 initialization method. The blue outline histogram shows the planned usage rescaled to the area of the available LST histogram. The LST axis starts at $-60^\\circ$ and the gaps in the planned usage correspond to the breaks between the southern and northern galactic caps in the DESI footprint.}\n\\label{fig:LST_zero0}\n\\end{center}\n\\end{figure}\n\nAn alternative bootstrap initialization, which we refer to as the ``flat'' method, is to approximately match the cummulative distribution of available LST to planned LST usage. We first tabulate the available survey time $a_j$ in $n$ LST bins\n$$\n\\theta_j \\le \\theta < \\theta_{j+1} \\quad , \\quad \\theta_j = (j/n) 360^\\circ \\; ,\n$$\nwhere $j$ ranges from $0$ to $n-1$, then calculate its cummulative distribution function (CDF) in $n+1$ steps as\n$$\nA_0 = 0 \\quad , \\quad\nA_{j+1} = \\frac{\\sum_{k=0}^{j} a_k}{\\sum_{k=0}^{n-1} a_k} \\; .\n$$\nNext, we approximate the CDF of planned LST usage of $i = 0, 1, \\ldots, N-1$ tiles with all HAs equal zero as:\n$$\nP_i = \\frac{\\sum_{k=0}^{i} \\Delta t_k}{\\sum_{k=0}^N \\Delta t_k} \\; ,\n$$\nwhere $\\Delta t_k$ is the expected exposure time for tile $k$ at HA=0 and tiles are ordered in increasing right ascension (RA). Finally, we match the available and planned CDFs by adjusting each tile's LST $\\tilde{\\theta}_i$ using linear interpolation of the inverse mapping $A_j \\rightarrow \\theta_j$ evaluated at each $P_i$. We then select\n$$\n\\text{HA}_i = \\tilde{\\theta}_i - \\text{RA}_i\n$$\nas the initial HA for tile $i$.\n\nSince LST and RA are periodic, the initial HAs obtained with this method depend on an arbitrary choice of starting angle, which corresponds to an LST where all tiles will have HA=0. In practice, we repeat this initialization on a grid of possible starting angles and select the one with the minimum score function (defined below). \\fig{LST_flat0} compares the available and planned LST usage after initializing all HAs with this method. \\fig{HA_flat0} shows the distribution of initial HAs over the sky for each pass of each program.\n\n\\begin{figure}[htb]\n\\begin{center}\n\\includegraphics[width=6in]{LST_flat0}\n\\caption{Available (red) and planned (blue) LST usage for the flat initialization method. The blue outline histogram shows the planned usage rescaled to the area of the available LST histogram. The LST axis starts at $-60^\\circ$.}\n\\label{fig:LST_flat0}\n\\end{center}\n\\end{figure}\n\n\\begin{figure}[htb]\n\\begin{center}\n\\includegraphics[width=6in]{HA_flat0}\n\\caption{All-sky maps of the tiles in each pass (0-7) color coded by their initial HA assignment using the ``flat'' initialization method. Passes 0-1 (top row), 2-4 (middle row) and 5-7 (bottom row) correspond to the DARK (0-3), GRAY (4) and BRIGHT (5-7) programs. Histograms show the HA distribution in each pass, color coded by the pass program: black (DARK), gray (GRAY) and orange (BRIGHT).}\n\\label{fig:HA_flat0}\n\\end{center}\n\\end{figure}\n\nThis CDF-matching ``flat'' method does a good job of matching the available and planned LST usage, but generally increases the total exposure time required more than necessary. The approximations in this method are that:\n\\begin{itemize}\n \\item Exposure times are calculated for HA=0 and then used to estimate non-zero HAs for each tile.\n \\item The contribution from each exposure is assumed to contribute at a single LST rather than being spread of LST in proportion to the length of the exposure.\n \\item The CDF matching procedure enforces that the ordering of tile LSTs matches the ordering of tile RAs, but this may not be optimal.\n\\end{itemize}\nThe iterative improvement scheme described below does not have any of these limitations.\n\n\\subsection{Exposure Times}\n\nExposure times for observing during the DARK program are estimated as:\n$$\n\\Delta t = \\Delta t_{\\text{nom}}\\, f_{\\text{dust}}\\, f_{\\text{airmass}}\\,\nf_{\\text{seeing}}\\, f_{\\text{transp}} \\; ,\n$$\nwhere the nominal exposure time $\\Delta t_{\\text{nom}}$ is specified by the program (1000 seconds for DARK and GRAY, and 300s for BRIGHT) and the remaining dimensionless factors correct for the actual versus nominal observing conditions: dust extinction, airmass, seeing, and atmospheric transparency.\n\nThe dust factor is fixed by the median value of $E_{B-V}(\\text{RA}, \\text{DEC})$ over the tile and given by:\n$$\nf_{\\text{dust}} = 10^{\\alpha E_{B-V}}\n\\quad, \\quad \\alpha = 2.6424 \\; .\n$$\nThe airmass factor is a function of the airmass $X(\\text{DEC}, \\text{RA})$ and given by:\n$$\nf_{\\text{airmass}} = X^{1.25} \\; .\n$$\n\nThe remaining DARK program exposure factors are due to atmospheric seeing and transparency, which vary stochastically during actual observing. For the purposes of HA optimization, we only need to account for their mean time-integrated effects, $F_x = \\langle f_x\\rangle$. Our assumptions for seeing and transparency are detailed in~\\cite{desi-3087} and summarized in \\tab{expfac}. The combined effect seeing and transparency, which we assume to be uncorrelated, is a $\\simeq 9$\\% increase in exposure time which we\nround up to 10\\%.\n\n\\begin{table}[htb]\n\\begin{center}\n\\begin{tabular}{lcccccccc}\nCondition & Nominal & Median & Mean & $F_x$ \\\\\n\\hline\n Seeing & $1.1$\" & $1.10$\" & $1.17$\" & $1.03$ \\\\\nTransparency & $1.0$ & $0.98$ & $0.94$ & $1.06$ \\\\\n\\hline\n\\end{tabular}\n\\caption{Summary of atmospheric seeing and transparency assumptions, and estimated time-integrated exposure-time factors. See~\\cite{desi-3087} for details.}\n\\label{tab:expfac}\n\\end{center}\n\\end{table}\n\nExposure times during the GRAY and BRIGHT programs have an additional factor due to scattered moonlight, but further study is needed to accurately estimate its impact. We therefore assign average exposure time factors to account for seeing, transparency and moon of: 1.10 (DARK), ?? (GRAY) and ?? (BRIGHT). These factors multiply the exposure times derived from dust and airmass in our HA optimization algorithm, but are expected to have a negligible impact on the assigned HAs.\n\n\\subsection{Iteration}\n\nFor details on the iteration scheme, refer to the {\\tt optimize.Optimizer.improve} method of the {\\tt desisurvey} package. Here we just provide a high-level sketch of the algorithm.\n\nEach iteration is governed by an HA adjustment size parameter, $\\delta\\text{HA}$, which we gradually decrease in an outer loop as described in the next section. Given an adjustment size, we select a single tile to adjust then recompute the planned LST usage using its new HA and exposure time (due to its change of airmass with HA). The total number of iterations (single-tile adjustments) required to obtain near-optimal HA assignments starting from HA=0 is typically 20--30 times the total number of tiles. The algorithm has several stochastic elements in order to avoid getting stuck in a local minimum, but uses a single source of pseudo-random numbers to ensure reproducibility.\n\nThe score function that each iteration attempts to improve combines two figures of merit which we refer to as RSME and LOSS.\n\nRMSE measures the fractional deviation between the available ($A_i$) and planned ($P_i$) LST usage histograms using\n$$\n\\text{RMSE} \\equiv \\frac{1}{\\sum_i^n P_i}\n\\left( n \\sum_i^n (s A_i - P_i)^2 \\right)^{1/2}\n$$\nwhere the scale factor\n$$\ns = (\\sum_i^n P_i) / (\\sum_i^n A_i)\n$$\nnormalizes the total available LST to the total planned usage so that RMSE measures deviations in shape only. LOSS compares the total exposure time required with the current plan ($T_P$) with the minimum possible total time ($T_0$) when all tiles are observed with HA=0, using\n$$\n\\text{LOSS} \\equiv (T_P - T_0) / T_0 \\; .\n$$\nAfter some experimentation, we combine these dimensionless metrics with equal weight,\n$$\n\\text{SCORE} = \\text{RMSE} + \\text{LOSS} \\; ,\n$$\nso that RMSE typically dominates during the first phase of optimization, then LOSS dominates towards the end. Typical final values after optimization are RMS $\\simeq 1$\\% and LOSS $\\simeq 3$\\%.\n\nWe automatically switch between two algorithms to select the set of candidate tiles to adjust during each iteration: a fast algorithm that is typically selected when RMSE dominates the score, and a slower brute-force algorithm that is typically selected when LOSS dominates. The fast algorithm first identifies which LST bin would maximally improve RMSE when tiles are shifted away from it, and then only considers tiles whose exposures overlap that bin. The slow algorithm considers a 20\\% random subset of all tiles. We next rank all tiles in the candidate set according to how much they improve the SCORE when adjusted. We usually pick the tile with the best improvement but will sometimes randomly pick a lower-ranked tile. The size of the HA adjustment is randomly generated from a Rayleigh distribution with mean fixed to the input adjustment-size parameter $\\delta\\text{HA}$.\n\n\\subsection{Annealing and Termination}\n\nThe {\\tt surveyinit} script uses the {\\tt optimize.Optimizer} class to coordinate the overall HA assignment task. Optimization proceeds in ``cycles'' of $n$ adjustments with fixed parameters, where $n$ equals the number of tiles to optimize. After each cycle, the distribution of HAs is smoothed over the sky,\n$$\n\\text{HA}_j = (1 - \\alpha)\\,\\text{HA}_j + \\alpha\\,\\overline{\\text{HA}}_j\n$$\nwhere $\\overline{\\text{HA}}_j$ is the weighted average of neighboring HAs,\n$$\n\\overline{\\text{HA}}_j = \\sum_{k\\ne j} \\omega_{jk}\\,\\text{HA}_k \\; ,\n$$\nand $\\alpha$ controls the amount of smoothing. Smoothing weights are Gaussian in the separation angle $\\theta_{jk}$ between pairs of tiles,\n$$\n\\omega_{jk} = \\exp\\left( -0.5(\\theta_{jk} / \\sigma_S)^2 \\right) \\; ,\n$$\nwith a smoothing length $\\sigma_S \\simeq 10^\\circ$.\n\nAfter each complete cycle, the adjustment size $\\delta\\text{HA}$ and amount of smoothing $\\alpha$ are annealed according to:\n$$\n\\delta\\text{HA} \\rightarrow a \\delta\\text{HA} \\quad, \\quad\n\\alpha\\rightarrow a \\alpha \\; ,\n$$\nwith an annealing factor $a \\simeq 0.95$.\n\nCycles are terminated once both of the following conditions are met:\n\\begin{itemize}\n \\item RMSE below a preset threshold $\\simeq 2$\\%, and\n \\item fractional change in SCORE larger than a preset threshold $\\simeq -1\\%$.\n\\end{itemize}\nCycles also terminate after a preset maximum number of cycles. All of these presets can be modified via {\\tt surveyinit} command-line arguments.\n\n\\section{Results}\n\n\\fig{LST_zero} and \\fig{LST_flat} show the LST distributions obtained after optimizing initial HAs set to be zero or ``flat''. \\fig{HA_zero} and \\fig{HA_flat} show the corresponding all-sky distributions of HAs for each tile. Both methods match the available and planned LST usage to high accuracy and predict similar total exposure times and corresponding safety margins. However, they use qualitatively different HA distributions to achieve similar results, indicating that the HA-assignment optimization problem has many comparable local minima. In the following, we select the ``flat'' initialization method since it has slightly better performance and more closely matches the algorithm used for BOSS and eBOSS. \\tab{summary} summarizes the planned LST usage in each program using ``flat'' initialization. There is some safety margin for all programs with our assumed exposure-time model and survey schedule.\n\n\\begin{figure}[htb]\n\\begin{center}\n\\includegraphics[width=6in]{LST_zero}\n\\caption{Available (red) and planned (blue) LST usage after optimizing initial HA=0 assignments. The blue outline histogram shows the planned usage rescaled to the area of the available LST histogram. The LST axis starts at $-60^\\circ$.}\n\\label{fig:LST_zero}\n\\end{center}\n\\end{figure}\n\n\\begin{figure}[htb]\n\\begin{center}\n\\includegraphics[width=6in]{LST_flat}\n\\caption{Available (red) and planned (blue) LST usage after optimizing initial HAs obtained with the ``flat'' method. The blue outline histogram shows the planned usage rescaled to the area of the available LST histogram. The LST axis starts at $-60^\\circ$.}\n\\label{fig:LST_flat}\n\\end{center}\n\\end{figure}\n\n\\begin{figure}[htb]\n\\begin{center}\n\\includegraphics[width=6in]{HA_zero}\n\\caption{All-sky maps of the tiles in each pass (0-7) color coded by their initial HA assignment after optimizing initial HA=0 assignments.}\n\\label{fig:HA_zero}\n\\end{center}\n\\end{figure}\n\n\\begin{figure}[htb]\n\\begin{center}\n\\includegraphics[width=6in]{HA_flat}\n\\caption{All-sky maps of the tiles in each pass (0-7) color coded by their initial HA assignment after optimizing initial HA=0 assignments.}\n\\label{fig:HA_flat}\n\\end{center}\n\\end{figure}\n\n\\begin{table}[htb]\n\\begin{center}\n\\begin{tabular}{lcccc}\nProgram & Available & Planned & Stretch & Margin \\\\\n\\hline\nDARK & 5319.0h & 4784.9h & 1.4 & 11.2\\% \\\\\nGRAY & 1357.8h & 1284.4h & 1.5 & 5.7\\% \\\\\nBRIGHT & 1899.8h & 1553.0h & 2.0 & 22.3\\% \\\\\n\\hline\n\\end{tabular}\n\\caption{Summary of observing plan for each program based on the observing hour angle assignments obtained with the ``flat'' initialization method.}\n\\label{tab:summary}\n\\end{center}\n\\end{table}\n\n\\def\\apjl{ApJL} %Astrophysical Journal Letters\n\\def\\aj{AJ} %Astronomical Journal\n\\def\\apj{ApJ} %Astrophysical Journal\n\\def\\pasp{PASP} %Publications of the Astronomical Society of the Pacific\n\\def\\spie{SPIE} %\n\\def\\apjs{ApJS} %Astrophysical Journal Supplement\n\\def\\araa{ARAA} %Annual Review of Astronomy and Astrophysics\n\\def\\aap{A\\&A} %Astronomy and Astrophysics\n\\def\\aaps{A\\&A~Supl.} %Astronomy and Astrophysics Supplement\n\\def\\nat{Nature} %Nature\n\\def\\nar{New Astron. Rev.} %New Astronomy Review\n\\def\\mnras{MNRAS} %Monthly Notices of the Royal Astronomical Society\n\\def\\jcap{JCAP} %Journal of Cosmology and Astroparticle physics\n\\def\\prd{{Phys.~Rev.~D}} % Physical Review D\n\\def\\physrep{{Phys.~Reports}} % Physics Reports\n\n\\bibliographystyle{unsrt}\n\\bibliography{design_ha}\n\n\\end{document}\n", "meta": {"hexsha": "5b0bf1daf0c2ac12aa0c2f0a0a58a5560b065d82", "size": 18172, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/tex/desi3060/design_ha.tex", "max_stars_repo_name": "michaelJwilson/desisurvey", "max_stars_repo_head_hexsha": "dfd875918beec919eb746946dc792a6db318b2ff", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2015-07-22T10:04:08.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-30T05:53:37.000Z", "max_issues_repo_path": "doc/tex/desi3060/design_ha.tex", "max_issues_repo_name": "michaelJwilson/desisurvey", "max_issues_repo_head_hexsha": "dfd875918beec919eb746946dc792a6db318b2ff", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 120, "max_issues_repo_issues_event_min_datetime": "2015-07-27T16:52:49.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-25T22:39:03.000Z", "max_forks_repo_path": "doc/tex/desi3060/design_ha.tex", "max_forks_repo_name": "michaelJwilson/desisurvey", "max_forks_repo_head_hexsha": "dfd875918beec919eb746946dc792a6db318b2ff", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2015-08-11T15:12:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-24T13:58:30.000Z", "avg_line_length": 63.0972222222, "max_line_length": 918, "alphanum_fraction": 0.7617763592, "num_tokens": 4829, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.35936414516010196, "lm_q1q2_score": 0.19925680465702822}}
{"text": "\\documentclass{article}\n\\usepackage[margin=2.5cm]{geometry}\n\n\\usepackage{kpfonts}\n\\usepackage{amsmath}\n\\usepackage{mathtools}\n\\usepackage{hyperref}\n\\usepackage{todonotes}\n\\usepackage{xspace}\n\\usepackage{listings}\n\n\\newcommand{\\pOut}{{!}}\n\\newcommand{\\bOut}{{!\\!!}}\n\\newcommand{\\pIn}{{?}}\n\\newcommand{\\bIn}{{?\\!?}}\n\\newcommand{\\new}[2]{(\\nu\\!#1) #2}\n\\newcommand{\\freshFor}{\\mathrel{\\#}}\n\\newcommand{\\rec}{\\mathtt{rec}}\n\\newcommand{\\nil}{\\mathbf{0}}\n\\newcommand{\\invoke}[1]{\\langle #1 \\rangle}\n\n\\newcommand{\\psicalculus}{psi-calculus\\xspace}\n\n\\newcommand{\\refinedBy}{\\precsim}\n\n\\newtheorem{lemma}{Lemma}\n\\newtheorem{definition}{Definition}\n\n\\lstset{basicstyle=\\ttfamily\\small}\n\\lstdefinelanguage{Coq}{\n morekeywords={Require,Import,Open,Scope,Section,Context,Inductive,forall,Fixpoint,match,with,end,End,Arguments,return,Definition,Fact,Qed}\n }\n\n\\DeclareMathOperator{\\bn}{bn}\n\\DeclareMathOperator{\\n}{n}\n\\DeclareMathOperator{\\len}{len}\n\\DeclareMathOperator{\\chain}{chain}\n\n\\begin{document}\n\n\\title{Asynchronous Embedded Psi-Calculus}\n\\author{Edsko de Vries}\n\\maketitle\n\n\\section{Motivation}\n\nThe \\psicalculus \\cite{DBLP:journals/corr/abs-1101-3262} is a parametric process\ncalculus with support for broadcast communication \\cite{Borgström2015} and\nequipped with a formally verified metatheory. Its parameterization allows for\nmodelling of various cryptographic and other primitives, and its definition of\nbroadcast communication is very general. As such, it is a suitable candidate for\nmodelling the Proas algorithm and proving some of its properties. Its metatheory\nincludes a definition of bisimularity, along with a formal proof that\nbisimularity is ``sound'', in the sense two bisimilar processes are\ninterchangeable in any context (sound with respect to a high-level observational\nequivalence).\n\nUnfortunately, such soundness comes at a cost. The relation between processes\n(bisimilarity) must be detailed and is often complex; the definition of\nbisimilarity for the \\psicalculus in particular is non-trivial. Consequently,\nproving bisimilarity between processes is often difficult and must be supported\nby additional formal infrastructure. Although such infrastructure exists for the\n\\psicalculus in the form of up-to techniques, it currently does not support the\nbroadcast extension \\cite{AmanPohjola:2016:BUT:2854065.2854080}.\n\nSecondly, in order to be able to use \\emph{any} kind of sound theory (one that\nwould allow us to conclude that we can replace a process by another in an\narbitrary context), we would have to fully characterize the behaviour of those\nprocesses. This is a proof obligation which we currently don't have the\nresources to take on, and instead we will only give partial specification.\n\nOn the positive side giving up on full specifications allows us to be more\nflexible in what kind of calculus we use. When we use the \\psicalculus directly,\nevery additional operation (such as encryption) that isn't explicitly supported\nin the calculus must be encoded using the \\psicalculus parameters. If however we\ndon't intend to use the existing \\psicalculus metatheory, and don't intend to do\nany metatheoretical reasoning ourselves (and instead only intend to reason about\nconcrete processes), we can define a process calculus that reuses infrastructure\nfrom the host language (such as Isabelle) to give us additional power. For\nexample, in the Verdi project \\cite{Wilcox:2015:VFI:2737924.2737958} processes\nare simply host-language functions from inputs to outputs.\n\nEmbedding host-language functions in a calculus is known as higher order\nabstract syntax (HOAS), and is typically associated with three problems in\nformal verification. First, for a higher order abstract syntax the use of HOAS\nis problematic as it requires a non-positive datatype. Since the psi-calculus is\nfirst order, this is not an issue. Second, HOAS introduces ``exotic'' terms that\nextend the power of the calculus; often these terms are undesirable but in our\ncase this is precisely the reason for introducing HOAS. We do have to be careful\nthat processes cannot distinguish one ``fresh'' name from another; it suffices\nto require that the functions are equivariant. Finally, HOAS makes it difficult\nor impossible to do induction over the syntax of the calculus (although there\nare workarounds \\cite{Röckl2001}). Since we don't intend to do metatheoretical\nreasoning, but only plan to reason about concrete processes, I don't think that\nthis will be an issue.\n\nHaving said all that, it \\emph{is} useful to stay as close to the \\psicalculus\nas possible, so that if in the future we do want to take advantage of the\n\\psicalculus metatheory the transition is not more difficult than it needs to\nbe. For this reason in this document we introduce an embedded process calculus\n(``embedded'' in the sense that it is embedded in a host language with a\nfunction space), which is closely modelled after the \\psicalculus as it is\ndefined in \\cite{Borgström2015}. The embedded nature of the calculus however\nmeans that we can simplify the \\psicalculus in various ways; this is documented\nin detail in Section~\\ref{sec:deviations}.\n\n\\section{Deviations from the \\psicalculus}\n\\label{sec:deviations}\n\nSince we want to work with a semantics in which we can model network\nlimitations, we work in an asynchronous process calculus (i.e., the output\nprocess does not have a continuation). In an asynchronous process calculus there\nis no guaranteed message delivery and no guaranteed message ordering. It\n\\emph{does} guarantee that messages don't get duplicated, but this is also\nstraight-forward to guard against in ``real'' code and moreover likely less\nof a problem. The translation from an asynchronous calculus to the corresponding\nsynchronous calculus is trivial.\n\nThe \\psicalculus as defined in\n\\cite{DBLP:journals/corr/abs-1101-3262,Borgström2015} uses the classical\n``replication'' operator $!P$, modelling an unbounded number of instances of $P$\nin parallel. This operator is convenient for modelling but less convenient for\ninterpretation. The \\psicalculus workbench\n\\cite{Borgstrom:2015:PWG:2724585.2682570} uses named processes, effectively\nintroducing general recursion; we do the same. It is important that these named\nprocesses are actually (host language) \\emph{functions} from values to\nprocesses, so that we can model things like process state.\nAppendix~\\ref{app:namedproc} shows one way in which we might model this formally\n(the example uses Coq); I experimented also with using PHOAS for this purpose\nbut it turned out to be non-trivial (\\emph{cf}.\n\\cite{Chlipala:2010:VCI:1706299.1706312}).\n\nThe rules for point-to-point communication in the \\psicalculus rely on a\nname-matching predicate $\\xleftrightarrow{.}$; this is used for instance to\nexpress that $\\mathtt{fst}(c,d)$ and $c$ denote the same channel. Our use of\nHOAS means that $\\mathtt{fst}(c,d)$ will simply \\emph{evaluate} to $c$ and hence\nwe don't need the name matching construct. Formally, we instantiate\n$\\xleftrightarrow{.}$ to be diagonal relation on the set of names (name\nequality).\n\nSimilarly, the rules for broadcast connectivity use two predicates\n$\\overset{.}{\\prec}$ and $\\overset{.}{\\succ}$, denoting ``output connectivity''\nand ``input connectivity'' respectively. We simplify this to the trivial case:\nwe only use a single broadcast channel, that all processes can send to and\nreceive from. Formally, if $b$ is the single broadcast channel, we instantiate\nboth $\\overset{.}{\\prec}$ and $\\overset{.}{\\succ}$ to be trivial diagonal\nrelation on the set $\\{b\\}$.\n\nIn the \\psicalculus the relations $\\xleftrightarrow{.}$, $\\overset{.}{\\prec}$\nand $\\overset{.}{\\succ}$ are all parameterized by the ``frame'' of the process;\na set of formulas that are asserted to be true at any point during the process'\nlifecycle. Frames are also used to determine the branch to take in a case\nstatement. Since our instantiations of $\\xleftrightarrow{.}$,\n$\\overset{.}{\\prec}$ and $\\overset{.}{\\succ}$ are all trivial, and pattern\nmatching is taken care of by evaluation, we have no use for frames and omit them\nfrom the calculus. Formally, we instantiate $\\mathbf{A} = \\{\\top\\}$, containing\nonly the trivial assertion, let $\\mathbf{1} = \\top$ and $\\top \\otimes \\top =\n\\top$.\n\nWe follow the presentation of the psi-calculus from \\cite{Borgström2015}\nclosely. In particular, we use nominal logic to deal with name binding\n\\cite{Pitts2001,DBLP:journals/corr/abs-0809-3960}. As stated, however, we use\nHOAS for the input prefix, so that we can take advantage of the expressive power\nof the host language to express processes. We do insist that these functions are\nequivariant, to ensure that fresh names cannot be distinguished from each other.\n\nThe resulting calculus closely follows the \\psicalculus, although the\nresemblance is somewhat misleading: the introduction of HOAS significantly\nextends the expressive power of the calculus. If and when we decide to use the\n\\psicalculus as stated in the literature, along with its metatheory, we need to\nfind ways to model all the primitives that we use in our processes.\n\n\\section{Formal Definition}\n\n\\subsection{Syntax}\n\n\\begin{tabular}{llll}\n$P, Q$ & $::=$ && Process \\\\\n && $\\nil$ & Nil \\\\\n && $c \\pOut V$ & Output \\\\\n && $c \\pIn \\mathcal{F}$ & Input \\\\\n && $\\new{a}{P}$ & Restriction \\\\\n && $P \\parallel Q$ & Parallel \\\\\n && $\\bOut V$ & Broadcast output \\\\\n && $\\bIn \\mathcal{F}$ & Broadcast input \\\\\n && $\\invoke{A} V$ & Process invocation \\\\\n\\\\\n\\end{tabular}\n\nWe let $a, b, c$ range over channels, $V$ ranges over values, and $\\mathcal{F}$\nranges over equivariant functions from values to processes, $\\alpha$ over\narbitrary actions, and $A$ over process names. We allow arbitrary values in the\nhost language.\n\n\\subsection{Operational Semantics}\n\nIn the semantics below we do not give a rule for process invocation. Ideally,\nall rules should be extended with an environment $\\Gamma$ and an additional rule\nshould be added that $\\invoke{A}(V)$ can take whatever step that $\\Gamma(A)(V)$\ncan.\n\n\\begin{itemize}\n\n\\item Point-to-point communication\n\n\\begin{equation*}\n%\n% PIn\n%\n\\frac{\n}{\nc \\pIn \\mathcal{F} \\xrightarrow{c \\pIn V} \\mathcal{F}(V)\n}\n\\mathtt{In}\n%\n\\qquad\n%\n% POut\n%\n\\frac{\n}{\nc \\pOut V \\xrightarrow{c \\pOut V} \\nil\n}\n\\mathtt{Out}\n%\n\\qquad\n%\n\\frac{\nP \\xrightarrow{\\new{\\bar{a}}{c \\pOut V}} P' \\qquad\nQ \\xrightarrow{c \\pIn V} Q' \\qquad\n\\bar{a} \\freshFor Q\n}{\nP \\parallel Q \\xrightarrow{\\tau} \\new{\\bar{a}}{(P' \\parallel Q')}\n}\n\\mathtt{Com}\n%\n\\end{equation*}\n%\n\\begin{equation*}\n\\frac{\nP \\xrightarrow{\\new{\\bar{a}}{c \\pOut V}} P' \\qquad\nb \\freshFor \\bar{a}, c \\qquad\nb \\in \\n(V)\n}{\n\\new{b}{P} \\xrightarrow{\\new{\\bar{a},b}{c \\pOut V}} P'\n}\n\\mathtt{Open}\n\\end{equation*}\n%\nwhere\n%\n\\begin{itemize}\n\\item Symmetric version of $\\mathtt{Com}$ elided.\n\\item Rule $\\mathtt{Com}$ doubles as a closing rule.\n\\end{itemize}\n\n\\todo[inline]{The psi calculus paper states some additional assumptions here,\nbut I \\emph{think} they online pertain to frames, which we make no use of. But\nwe may need an additional freshness requirement somewhere.}\n\n\\item Broadcast communication\n\n\\begin{equation*}\n%\n% BOut\n%\n\\frac{\n}{\n\\bOut V \\xrightarrow{\\bOut V} \\nil\n}\n\\mathtt{BrOut}\n%\n\\qquad\n%\n% BrIn\n%\n\\frac{\n}{\n\\bIn \\mathcal{F} \\xrightarrow{\\bIn V} \\mathcal{F}(V)\n}\n\\mathtt{BrIn}\n%\n\\qquad\n%\n% BCom\n%\n\\frac{\nP \\xrightarrow{\\new{\\bar{a}}{\\bOut V}} P' \\qquad\nQ \\xrightarrow{\\bIn V} Q' \\qquad\n\\bar{a} \\freshFor Q\n}{\nP \\parallel Q \\xrightarrow{\\new{\\bar{a}}{\\bOut V}} P' \\parallel Q'\n}\n\\mathtt{BrCom}\n\\end{equation*}\n%\n\\begin{equation*}\n%\n% BrOpen\n%\n\\frac{\nP \\xrightarrow{\\new{\\bar{a}}{\\bOut V}} P' \\qquad\nb \\freshFor \\bar{a} \\qquad\nb \\in \\n(V)\n}{\n\\new{b}{P} \\xrightarrow{\\new{\\bar{a},b}{\\bOut V}} P'\n}\n\\mathtt{BrOpen}\n%\n\\qquad\n%\n% Close\n%\n\\frac{\nP \\xrightarrow{\\new{\\bar{a}}{\\bOut V}} P'\n}{\nP \\xrightarrow{\\tau} \\new{\\bar{a}}{P'}\n}\n\\mathtt{BrClose}\n\\end{equation*}\n%\n\\begin{equation*}\n%\n% BrMerge\n%\n\\frac{\nP \\xrightarrow{\\bIn V} P' \\qquad\nQ \\xrightarrow{\\bIn V} Q'\n}{\nP \\parallel Q \\xrightarrow{\\bIn V} P' \\parallel Q'\n}\n\\mathtt{BrMerge}\n\\end{equation*}\n%\nwhere\n%\n\\begin{itemize}\n\\item Symmetric version of rule $\\mathtt{BrCom}$ is elided; note that the psi\ncalculus paper also elides rule $\\mathtt{BrOpen}$ (we stated it explicitly).\n\\item Rule $\\mathtt{BrMerge}$ would not be necessary if we had an explicit rule\n\\begin{math}\n\\displaystyle\n\\frac{\nP \\equiv P' \\xrightarrow{\\alpha} Q' \\equiv Q\n}{\nP \\xrightarrow{\\alpha} Q'\n}\n\\end{math}.\nIf we want such a rule to be \\emph{derivable} instead (which makes the semantics\neasier to use) rule $\\mathtt{BrMerge}$ is needed.\n\\item Rule $\\mathtt{BrClose}$ is slightly more permissive than its equivalent in\nthe psi calculus presentation, where it only applies at the point where the\nchannel is bound. I'm not entirely sure why that restriction is in place; it\nis unusual (the closing rule for point-to-point communication has no similar\nrestriction).\n\\item Since we assume the existance of a single, global, broadcast channel,\nrestriction does not apply to broadcast channels. However, it \\emph{is} possible\nto extrude a point-to-point communication channel through a broadcast communication.\n\\item The rules for broadcast communication together mean that a single\nbroadcast output can be paired with any number (zero or more) inputs, and once\npaired (i.e., after the action) the output is no longer available. No\nassumptions can be made about who will receive the message, and so broadcast\ncommunication is ``unreliable'' in the sense that message may be ``lost''.\nMoreover, since broadcast output, like regular output, is asynchronous,\nbroadcast communication is unordered.\n\\end{itemize}\n\n\\item Congruence rules\n\n\\begin{equation*}\n%\n% Par\n%\n\\frac{\nP \\xrightarrow{\\alpha} P' \\qquad\n\\bn(\\alpha) \\freshFor Q\n}{\nP \\parallel Q \\xrightarrow{\\alpha} P' \\parallel Q\n}\n\\mathtt{Par}\n%\n\\qquad\n%\n% Scope\n%\n\\frac{\nP \\xrightarrow{\\alpha} P' \\qquad\na \\freshFor \\alpha\n}{\n\\new{a}{P} \\xrightarrow{\\alpha} \\new{a}{P'}\n}\n\\mathtt{Scope}\n%\n\\qquad\n\\end{equation*}\n\nSymmetric version of $\\mathtt{Par}$ elided.\n\n\\end{itemize}\n\n\\section{Stating properties}\n\n\\todo[inline]{This section serves as a rough sketch only on how we might state\nproperties.}\n\\newcommand{\\node}{\\mathtt{Node}}\n\nOne of the main properties we want to state and prove is that a node can always\nevolve to a state where its internal chain matches the chain of the environment\n(given some compatibility conditions). If $\\node$ is the function from a node's\ninternal state to the corresponding \\psicalculus process, for the published\nPraos algorithm we can state this simply as:\n%\n\\begin{lemma}[Praos]\nIn any state $s$ and for any chain $c$ such that $\\len(c) > \\len(\\chain(s))$,\nthere exists state $s'$ such that\n\\begin{equation*}\n\\node_P(s) \\xrightarrow{\\bIn c} \\node_P(s')\n\\end{equation*}\nand $\\chain(s') = c$.\n\\end{lemma}\n%\nFor the ``block Proas'' algorithm, the property is somewhat more complicated\nsince the node might be missing blocks.\n%\n\\begin{lemma}[Block Praos]\n\\label{lem:blockpraos}\nIn any state $s$ and for any block $b$ such that $b$ is a valid successor of\n$\\chain(s)$ (though perhaps not the \\emph{immediate} successor), there exists\n$s', s'', \\mu^*$ such that\n\\begin{equation*}\n\\node_B(s) \\xrightarrow{\\bIn b} \\node(s') \\xRightarrow{\\mu^*} \\node_B(s'')\n\\end{equation*}\nand $b \\in \\chain(s'')$.\n\\end{lemma}\n%\nWe can also try to relate the two implementations more directly. For example,\nwe could state that whenever the Praos node broadcasts a chain, the Block Praos\nnodes will broadcast a series of blocks using the following coinductive\ndefinition:\n%\n\\begin{definition}[Simulation]\nWe say that $\\node_B(s_B)$ can simulate $\\node_P(s_P)$, written\n$\\node_P(s_P) \\refinedBy \\node_B(s_B)$, iff for all $s_P', c$ such that\n\\begin{equation*}\n\\node_P(s_P) \\xrightarrow{\\bOut c} \\node_P(s_P')\n\\end{equation*}\nthere exists $s_B'$ and blocks $b^*$, a suffix of $c$, such that\n\\begin{equation*}\n\\node_B(s_B) \\xRightarrow{\\bOut b^*} \\node_B(s_B')\n\\end{equation*}\nand $\\node_P(s_P') \\refinedBy \\node_B(s_B')$.\n\\end{definition}\n%\nWe would then prove that\n%\n\\begin{lemma}[Block Praos simulates Praos]\n\\label{lem:BlockSimPraos}\nFor all $s_P, s_C$ such that $\\chain(s_P) = \\chain(s_B)$,\n\\begin{equation*}\n\\node_P(s_P) \\refinedBy \\node_B(s_B)\n\\end{equation*}\n\\end{lemma}\n%\nWe may of course also wish to prove something about how the other actions\nrelate, or prove something in the other direction too (bisimulation rather than\nsimulation). Note that such a (bi)simulation doesn't necessarily obsolete the\nneed for additional lemmas such as Lemma~\\ref{lem:blockpraos}, since in the\nproof of Lemma~\\ref{lem:BlockSimPraos} we can pick paths in which no messages\nget lost.\n\n\\appendix\n\n\\section{Appendix: Named Processes}\n\\label{app:namedproc}\n\nExample Coq development of defining a process calculus with named\nprocess invocation. Relies on some supporting definitions for vectors and\ndependent vectors, shown in Appendix~\\ref{app:coqaux}.\n\n\\begin{lstlisting}[language=Coq]\nSection Syntax.\n\n Context {n : nat}.\n Context {typ : Vec Set n}.\n\n Inductive Proc : Type :=\n Done : Proc\n | Out : nat -> Proc -> Proc\n | Inv : forall (i : Fin n), nth i typ -> Proc.\n\n Definition Env := DepVec (fun a => a -> Proc) typ.\n\nEnd Syntax.\n\nArguments Proc {n} typ.\nArguments Env {n} typ.\nArguments Inv {n} typ.\n\nSection Semantics.\n\n Context {n : nat}.\n Context {typ : Vec Set n}.\n Context {env : Env typ}.\n\n Inductive HasTrace : Proc typ -> list nat -> Prop :=\n TNil : forall P, HasTrace P nil\n | TOut : forall n P t, HasTrace P t -> HasTrace (Out n P) (cons n t)\n | TInv : forall i x t, HasTrace (dnth i env x) t -> HasTrace (Inv _ i x) t.\n\nEnd Semantics.\n\nArguments HasTrace {n} {typ} env.\n\nSection Example.\n\n Definition typ : Vec Set 2 := (nat, (nat, tt)).\n\n Definition left (n : nat) : Proc typ := Out n (Inv typ (FS FZ) (n + 1)).\n Definition right (n : nat) : Proc typ := Out n (Inv typ FZ (n + 1)).\n\n Definition env : Env typ := (left, (right, tt)).\n\n Fact trace123 : HasTrace env (left 1) (1 :: 2 :: 3 :: nil).\n repeat constructor.\n Qed.\n\nEnd Example.\n\\end{lstlisting}\n\n\\section{Appendix: Supporting definitions}\n\\label{app:coqaux}\n\nSome supporting Coq infrastructure for the development in Appendix~\\ref{app:namedproc}.\n\n\\begin{lstlisting}[language=coq]\nSection Vec.\n\n Context (A : Type).\n\n Inductive Fin : nat -> Set :=\n FZ : forall {n}, Fin (S n)\n | FS : forall {n}, Fin n -> Fin (S n).\n\n Fixpoint Vec (n : nat) : Type :=\n match n with\n O => unit\n | S n' => A * Vec n'\n end.\n\n Fixpoint nth {n : nat} (i : Fin n) : Vec n -> A :=\n match i with\n FZ => fun xs => match xs with (x, xs') => x end\n | FS i' => fun xs => match xs with (x, xs') => nth i' xs' end\n end.\n\nEnd Vec.\nArguments nth {A} {n} i.\n\nSection DepVec.\n\n Fixpoint DepVec (f : Set -> Set) {n : nat} : Vec Set n -> Set :=\n match n return Vec Set n -> Set with\n 0 => fun _ => unit\n | S n' => fun As => match As with (A, As') => (f A * DepVec f As')%type end\n end.\n\n Fixpoint dnth {n : nat} {f : Set -> Set} (i : Fin n) :\n forall {xs : Vec Set n}, DepVec f xs -> f (nth i xs) :=\n match i in Fin n return forall (xs : Vec Set n), DepVec f xs -> f (nth i xs) with\n FZ => fun As =>\n match As with (A, As') => fun xs =>\n match xs with (x, xs') => x end\n end\n | FS i' => fun As =>\n match As with (A, As') => fun xs =>\n match xs with (x, xs') => dnth i' xs' end\n end\n end.\n\nEnd DepVec.\n\\end{lstlisting}\n\n\\bibliographystyle{acm}\n\\bibliography{references}\n\n\\end{document}\n", "meta": {"hexsha": "2c62027e5b2c94a04ba4ef63325b64721f1fbdfe", "size": 19749, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Exploration/Asynchronous ψ-calculus/async-psi.tex", "max_stars_repo_name": "input-output-hk/ouroboros-high-assurance", "max_stars_repo_head_hexsha": "c89ba00e18c940a3795548a5c53ddc59da83e44b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-05-18T05:51:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-20T17:08:39.000Z", "max_issues_repo_path": "Exploration/Asynchronous ψ-calculus/async-psi.tex", "max_issues_repo_name": "input-output-hk/ouroboros-high-assurance", "max_issues_repo_head_hexsha": "c89ba00e18c940a3795548a5c53ddc59da83e44b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 20, "max_issues_repo_issues_event_min_datetime": "2020-11-19T19:49:53.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-08T18:03:10.000Z", "max_forks_repo_path": "Exploration/Asynchronous ψ-calculus/async-psi.tex", "max_forks_repo_name": "input-output-hk/ouroboros-high-assurance", "max_forks_repo_head_hexsha": "c89ba00e18c940a3795548a5c53ddc59da83e44b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-06-18T20:04:45.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T00:28:48.000Z", "avg_line_length": 33.6439522998, "max_line_length": 140, "alphanum_fraction": 0.7181123095, "num_tokens": 5663, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6334102775181399, "lm_q2_score": 0.31405054499180746, "lm_q1q2_score": 0.19892284285798387}}
{"text": "In this section, we assess our framework for characterizing process variation\npresented in \\sref{bayes-solution}. All the experiments are conducted on a\n\\up{GNU}/Linux machine equipped with an Intel Core i7 2.66~\\up{GH}z and\n8~\\up{GB} of \\up{RAM}. All the configuration files used in the experiments are\navailable online at \\cite{eslab2014a}.\n\nOur goal is to infer the effective channel length \\g from temperature \\h. Such a\nhigh-level parameter as temperature constitutes a challenging task for the\ninference of such a low-level parameter as the effective channel length, which\nimplies a rigorous assessment of the proposed technique. The performance of our\napproach is expected only to increase when the auxiliary parameter \\h is closer\nto the target parameter \\g with respect to the data model $\\h = \\f(\\g)$\ndescribed in \\sref{bayes-data-model}. For instance, such a closer quantity \\h\ncould be the leakage current, but this might not always be the most preferable\nparameter to measure. Lastly, let us note that the chosen effective channel\nlength is an important target, as it is strongly affected by process variation\nand considerably impacts power consumption and heat dissipation\n\\cite{chandrakasan2000, srivastava2010, juan2011, juan2012}. It also affects\nother process-related parameters, such as the threshold voltage.\n\nWe first describe the default configuration, which will be adjusted later on\naccording to the purpose of each particular experiment. We consider a 45-nm\ntechnological process. The diameter of the wafer is 20 dies, and the total\nnumber of dies \\nd is 316. The number of measured dies \\hnd is 20, and these\ndies are chosen by an algorithm that strives for even coverage of the wafer. The\nfabricated platform has four processing elements, and they are the points at\nwhich measurements are taken; that is, $\\np = 4$. The floorplan of the platform\nis constructed in such a way that the processing elements form a regular grid.\nThe dynamic power profiles involved in the experiments are based on simulations\nof applications randomly generated by \\up{TGFF} \\cite{dick1998}. The model of\nstatic power parameterized by temperature and the effective channel length is\nconstructed by fitting to \\up{SPICE} simulations of reference electrical\ncircuits that are composed of \\up{BSIM4} devices \\cite{bsim} configured\naccording to the 45-nm \\up{PTM} \\up{HP} model \\cite{ptm}. The construction of\nthermal \\up{RC} circuits is delegated to HotSpot \\cite{skadron2003}, and\ntemperature analysis is performed as described in \\sref{transient-solution}. The\nsampling interval of power and temperature profiles is 1~ms.\n\nThe input data set $H$ is obtained as follows: \\one~draw a sample of \\g from a\nGaussian distribution with a mean of 17.5~nm (in accordance with the\ntechnological process under consideration \\cite{ptm}) and a covariance function\nequal to \\eref{bayes-covariance} with a standard deviation of 2.25~nm;\n\\two~perform one fine-grained temperature simulation for each of the \\hnd dies\nselected for measurement; \\three~thin the obtained temperature profiles so that\neach has only \\ns, which is 20 by default, evenly spaced moments in time; and\n\\four~perturb the resulting data using white Gaussian noise with a standard\ndeviation of \\celsius{1}.\n\nLet us turn to the statistical model in \\sref{bayes-statistical-model} and\nsummarize the intuition behind the model's parameters and the process by which\nthey are assigned. In the correlation function given in\n\\eref{bayes-correlation}, the weight parameter $w$ and the two length-scale\nparameters $\\ell_\\SE$ and $\\ell_\\OU$ should be set according to the variation\npatterns that are typical for the fabrication process at hand\n\\cite{chandrakasan2000, cheng2011}; we set $w$ to 0.7 and $\\ell_\\SE$ and\n$\\ell_\\OU$ to half the radius of the wafer. The threshold parameter $\\eta$ of\nthe model-order-reduction procedure shown in \\eref{karhunen-loeve} and utilized\nin \\eref{bayes-reduction} should be set high enough in order to preserve a\nsufficiently large portion of the variance of the data, thereby keeping the\nmodel sufficiently accurate; we set it to 0.99. The resulting dimensionality \\nz\nof \\vz in \\eref{bayes-reduction} is found to be 27 or 28. The parameters $\\mu_0$\nand $\\tau_\\g$ of the prior given in \\eref{bayes-prior} are specific to the\ntechnological process under consideration; we set $\\mu_0$ to 17.5~nm and\n$\\tau_\\g$ to 2.25~nm. The parameters $\\sigma_0$ and $\\nu_\\g$ used in\n\\eref{bayes-prior} determine the precision of the information about $\\mu_0$ and\n$\\tau_\\g$ and are set according to the beliefs of the designer; we set\n$\\sigma_0$ to 0.45~nm and $\\nu_\\g$ to 10. The latter can be thought of as the\nnumber of imaginary observations that the choice of $\\tau_\\g$ is based on. The\nparameter $\\tau_\\epsilon$ in \\eref{bayes-prior} represents the precision of the\nequipment utilized for collecting $H$ and can be found in the technical\nspecification of that equipment; we set $\\tau_\\epsilon$ to \\celsius{1}. The\nparameter $\\nu_\\epsilon$ in \\eref{bayes-prior} has the same interpretation as\n$\\nu_\\g$; we set it to 10 as well. In \\eref{bayes-proposal}, $\\nu$ and $\\alpha$\nare tuning parameters, which are configured based on experiments; we set $\\nu$\nto 8 and $\\alpha$ to 0.5. The number of sample draws is another tuning\nparameter, which we set to \\power{10}{4}. The first half of these samples is\nascribed to the burn-in period mentioned in \\xref{bayesian-statistics}, and the\nsecond one constitutes $G$; in this case, $\\no = 5 \\times 10^3$. In the\noptimization described in \\sref{bayes-optimization}, we use the quasi-Newton\nalgorithm \\cite{press2007}. For parallel computations, we utilize four\ncomputational cores.\n\nIn order to ensure that the experimental setup is adequate, we first perform a\ndetailed inspection of the results obtained for one particular example with the\ndefault configuration. The true and inferred distributions of the quantity of\ninterest are shown in \\fref{bayes-motivation-distribution} where the \\ac{NRMSE}\nis below 2.8\\%, and the absolute error is bounded by 1.4~nm, which suggests that\nour framework produces a close match to the true value of the quantity. We also\ninvestigate the behavior of the constructed Markov chains and the quality of the\nproposal distribution. All the observations indicate that the optimization and\nsampling procedures are properly configured.\n\nIn the following subsections, we consider the experimental setup described above\nand alter a single parameter at a time in order to investigate its impact.\nSpecifically, we change \\one~the number of measurement sites \\hnd, which is 20\nby default; \\two~the number of measurement points per site \\np, which is 4 by\ndefault; \\three~the number of data instances per point \\ns, which is 20 by\ndefault; and \\four~the standard deviation of measurement noise\n$\\sigma_\\epsilon$, which is \\celsius{1} by default.\n\n\\subsection{Number of Measurement Sites}\n\n\\inputtable{bayes-sites}\nLet us vary the number of measured sites or dies \\hnd. The scenarios being\nconsidered are 1, 10, 20, 40, 80, and 160 dies. The obtained results are shown\nin \\tref{bayes-sites}. In this and the following tables, we report the\noptimization time and sampling time separately, which correspond to Stage~2 and\nStage~3 in \\fref{bayes-overview}, respectively. In addition, the sampling time\nis given for two cases: sequential and parallel computing, which is followed by\nthe total time and resulting error. The computation time of the post-processing\nstage, Stage~4, is not given, as it is negligibly small. The sequential sampling\ntime is the most representative indicator of the computational complexity of the\nproposed framework, since the number of samples is always fixed, and there is no\nparallelization. Therefore, we refer to this value in most of the discussions\ngiven below.\n\nIt can be seen in \\tref{bayes-sites} that the more data the proposed framework\nneeds to process, the longer the execution time becomes, which is reasonable.\nThe trend, however, is modest: when \\hnd is doubled, the computation time\nincreases by less than a factor of two. Regarding accuracy, the error decreases\ndefinitively and drops below 4\\% when around 20 sites are measured, which is\nonly 6\\%--7\\% of the total number of dies on the wafer under consideration.\n\n\\subsection{Number of Measurement Points}\n\n\\inputtable{bayes-points}\nIn this subsection, we consider five platforms with different numbers of\nprocessing elements or, equivalently, measurement points \\np. The scenarios\nbeing considered are 2, 4, 8, 16, and 32 processing elements. The results are\nsummarized in \\tref{bayes-points}. The computation time grows along with \\np.\nThis is expected, since the granularity of the temperature model is bound to the\nnumber of processing elements: each processing element contributes four thermal\nnodes to the thermal \\up{RC} circuit that temperature analysis is based on;\nrecall \\sref{temperature-model}. Hence, temperature analysis becomes more\nexpensive. Nevertheless, even for large examples, taking into account the\ncomplexity of the inference procedure and the yielded accuracy, the time\nrequirement is readily acceptable. An interesting observation can be made with\nrespect to the \\ac{NRMSE}: the error tends to decrease as \\np grows. The reason\nis that, with each measurement point, $H$ delivers more information for the\ninference to work with.\n\n\\subsection{Number of Data Instances}\n\n\\inputtable{bayes-instances}\nNow we change the number of data instances \\ns, which, in this case, is the\nnumber of moments in time captured by temperature profiles. The scenarios being\nconsidered are 1, 10, 20, 40, 80, and 160 moments. The results are aggregated in\n\\tref{bayes-instances}. It can be seen that the growth in computation time is\nrelatively small. One might expect this growth due to \\ns to be the same as the\none due to \\np, since, technically, the influence of \\np and \\ns on the\ndimensionality of $H$ is identical; recall that $\\hvh \\in \\real^{\\hnd \\np \\ns}$.\nHowever, the meanings of \\np and \\ns are completely different, and hence the\nways they manifest themselves in the inference algorithm are also different,\nwhich explains the discordant figures shown in \\tref{bayes-points} and\n\\tref{bayes-instances}. The \\ac{NRMSE} in \\tref{bayes-instances} has a\ndecreasing trend; however, this trend is less steady than the ones noted before.\nThe finding can be explained as follows. The temporal distribution of the\nmoments in time that are present in $H$ changes, since these moments are kept\nevenly spaced across the time spans of the corresponding applications. Some\nmoments can be more informative than others. Consequently, more or less\nrepresentative samples can be accumulated in $H$, helping or misleading the\ninference. Additionally, we can conclude that a larger number of spatial\nmeasurements is more advantageous than a larger number of temporal measurements.\n\n\\subsection{Deviation of Measurement Noise}\n\n\\inputtable{bayes-noise}\nIn this subsection, we vary the standard deviation of measurement noise, which\ncorrupts $H$. The cases being considered are \\celsius{0}, \\celsius{0.5},\n\\celsius{1}, and \\celsius{2} \\cite{mesa-martinez2007}. Note that the\ncorresponding prior in \\eref{bayes-prior} is kept unchanged. The results are\ngiven in \\tref{bayes-noise}. It can be seen that the sampling time is\napproximately constant. However, we observe an increase in the optimization time\nwhen the level of noise decreases, which can be ascribed to greater\nopportunities for perfection for the optimization procedure. Another observation\nrevealed by this experiment is that, in spite of the fact that the inference\noperates on indirect and incomplete data, a thoroughly calibrated piece of\nequipment can considerably improve the quality of prediction. However, even with\na noise of \\celsius{2}---meaning that measurements are dispersed over a wide\nband of \\celsius{8} with a probability of more than 0.95---the \\ac{NRMSE} is\nstill only 4\\%.\n\n\\subsection{Sequential and Parallel Sampling}\n\nLastly, we elaborate on the sequential and parallel sampling strategies. In the\nsequential Metropolis--Hastings algorithm, the optimization time is typically\nsmaller than the time needed for drawing posterior samples. The situation\nchanges when parallel computing is utilized. When four cores are working in\nparallel, the sampling time decreases by a factor of 3.81 on average, which\nindicates good parallelization properties of the chosen sampling strategy. The\noverall speedup ranges from 1.49 to 2.75 with an average value of 1.77, which\ncan be pushed even further by employing more computational cores.\n", "meta": {"hexsha": "e58d47cc30a97341c4c4ec41d3bb43bf8f29469d", "size": 12637, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "include/uncertainty/process/fabrication/results.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/fabrication/results.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/fabrication/results.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": 65.4766839378, "max_line_length": 80, "alphanum_fraction": 0.7933845058, "num_tokens": 3096, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3886180267058489, "lm_q1q2_score": 0.19886229715274964}}
{"text": "\\section{Language Versions and Cost Models}\n\\label{sec:protocol-parameters}\n\nWe require the following types (see Figure~\\ref{fig:defs:protocol-parameters})\nin addition to those that are already defined in the Shelley specification~\\cite{XX}. \\TODO{Add the citation}\n\n\\vspace{12pt}\n\\begin{tabular}{lp{5in}}\n $\\Language$ &\n This represents the language name/tag (including the\n version number).\n \\\\\n $\\ExUnits$ &\n A term of this type contains two integer values,\n $(mem, steps)$.\n These represent abstract notions of the relative memory usage and script execution steps,\n respectively.\n \\\\\n $\\CostMod$ &\n A term of this type represents the vector of coefficients that are used to generate\n a term of type $\\ExUnits$ given a vector of some resource primitives. The mapping is defined\n concretely by the specific version of the Plutus interpreter that is associated with $\\Language$.\n We keep this type as abstract in the specification.\n \\\\\n $\\Prices$ &\n A term of this type comprises two integer values that correspond to the components of $\\ExUnits$,\n $\\var{pr_{mem}, pr_{steps})}$:\n $pr_{mem}$ is the price (in Ada) per unit of memory, and $pr_{steps}$ is the price (in Ada) per\n reduction step. This is used to calculate the Ada cost for a specific script execution.\n\\end{tabular}\n\\vspace{12pt}\n\nWe also need a number of additional protocol parameters and accessor functions: ...\\todo{List these.}\n\n\\begin{tabular}{||l|l||}\n \\textbf{Item} & \\textbf{Use} \\\\\n \\\n \\end{tabular}\n\n\\subsection{Language Versions and Backwards Compatibility Requirements}\n\\label{sec:versions}\n\nIn the $\\Language$ type, each \\emph{version} of a language is considered to be a different language (so there might be several versions of the Plutus language, each of which would be considered to\nbe different).\nEach such language needs to be interpreted by a language-specific interpreter that is called from the ledger implementation.\nThe interpreter is provided with the (language- and version-specific) arguments that it requires.\nIt is necessary for the ledger to be capable of executing scripts in languages it ever supported.\nThis implies that it is necessary to maintain all forms of ledger\ndata that is needed by any past or current language, which constrains future ledger designs.\nIntroducing a new language will require a major protocol version update, since the datatypes need to support the new language and the ledger rules must be updated to use the new interpreter.\n\n\\subsection{Determinism of Script Evaluation}\n\\label{sec:determinism}\n\nThe data that is passed to the interpreter\nincludes the validator script, the redeemer, possibly a datum from the UTxO, information about the transaction that\nembeds the script, any relevant ledger data, and any relevant protocol parameters.\nIt is necessary for the validation outcome of any scripts to remain the same during the entire\nperiod between transaction\nsubmission and completion of the script processing.\n%\nIn order to achieve this,\nany data that is passed to the interpreter must be determined by the transaction itself.\nThe transaction therefore includes a hash of any data that is not determined by the transaction or the UTXO.\nWhen the transaction is processed, as part of the UTXOW rule, this hash is compared with a hash of the data that is passed to the interpreter. This\nensures that scripts are only executed if they have been provided with the intended data.\n\nThe $\\fun{getLanguageView}$ function (Figure~\\ref{fig:defs:protocol-parameters}) selects the protocol parameters that are relevant to\na given set of languages.\n%\nAt the time of writing, the only parameter that needs to be passed to the interpreter is the cost model.\n\n\\subsection{Script Evaluation Cost Model and Prices}\n\\label{sec:cost-mod}\n\nTo convert resource primitives into the\nmore abstract $\\ExUnits$ during script execution a cost model needs to be supplied to the interpreter.\nThe cost models required for this purpose are recorded in the $\\var{costmdls}$ protocol parameter.\n%\nThe calculation of the actual cost, in Ada, of running\na script that takes $\\var{exunits} \\in \\ExUnits$ resources to run,\nis done by a formula in the ledger rules, which uses the\n$\\var{prices}$ parameter. This is a parameter that applies to all\nscripts and that cannot be varied for individual languages. This parameter\nreflects the real-world costs in terms of energy usage, hardware resources etc.\n\n\\textbf{Limiting Script Execution Costs.}\nThe $\\var{maxTxExUnits}$ and $\\var{maxBlockExUnits}$ protocol parameters are\nused to limit the total per-transaction and per-block resource use. These only apply to non-native scripts.\nThe parameters are used to ensure that the time and memory that are required to verify a block are bounded.\n\n\\begin{figure*}[htb]\n \\emph{Abstract types}\n %\n \\begin{equation*}\n \\begin{array}{r@{~\\in~}l@{\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad}r}\n \\var{cm} & \\CostMod & \\text{Coefficients for the cost model} \\\\\n \\var{ldv} & \\LangDepView & \\text{Language-dependent view of the protocol parameters}\n \\end{array}\n \\end{equation*}\n %\n \\emph{Derived types}\n \\begin{equation*}\n \\begin{array}{r@{~\\in~}l@{\\quad=\\quad}l@{\\qquad}r}\n \\var{lg}\n & \\Language\n & \\{\\Plutus, \\dotsb\\}\n & \\text{Script Language}\n \\\\\n \\var{pr_{mem}, pr_{steps})}\n & \\Prices\n & \\Coin \\times \\Coin\n & \\text {Coefficients for $\\ExUnits$ prices}\n \\\\\n \\var{(mem, steps)}\n & \\ExUnits\n & \\N \\times \\N\n & \\text{Abstract execution units} \\\\\n \\end{array}\n \\end{equation*}\n %\n \\emph{Protocol Parameters}\n %\n \\begin{equation*}\n \\begin{array}{r@{~\\in~}l@{\\qquad}r}\n \\var{costmdls} \\mapsto (\\Language \\mapsto \\CostMod) & \\PParams & \\text{Script exec. cost model}\\\\\n \\var{prices} \\mapsto \\Prices & \\PParams & \\text{Coefficients for $\\ExUnits$ prices} \\\\\n \\var{maxTxExUnits} \\mapsto \\ExUnits & \\PParams & \\text{Max. total tx script exec. resources}\\\\\n \\var{maxBlockExUnits} \\mapsto \\ExUnits & \\PParams & \\text{Max. total block script exec. resources}\\\\\n \\end{array}\n \\end{equation*}\n %\n \\emph{Accessor Functions}\n %\n \\begin{center}\n \\fun{costmdls},~\\fun{maxTxExUnits},~\\fun{maxBlockExUnits},~\\fun{prices}\n \\end{center}\n %\n \\emph{Helper Functions}\n %\n \\begin{align*}\n & \\fun{getLanguageView} \\in \\PParams \\to \\Language \\to \\LangDepView \\\\\n & \\fun{getLanguageView}~\\var{pp}~\\Plutus = \\{\\Plutus\\} \\restrictdom \\fun{costmdls}~{pp}\n \\end{align*}\n %\n \\caption{Definitions Used in Protocol Parameters}\n \\label{fig:defs:protocol-parameters}\n\\end{figure*}\n", "meta": {"hexsha": "653358946ba2f9be2858db2fd0a1d60e6dea3eb4", "size": 6618, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "alonzo/formal-spec/protocol-parameters.tex", "max_stars_repo_name": "obsidiansystems/cardano-ledger-specs", "max_stars_repo_head_hexsha": "3f98101379ac2a184423af6aa0e16eaeaea49f8d", "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/protocol-parameters.tex", "max_issues_repo_name": "obsidiansystems/cardano-ledger-specs", "max_issues_repo_head_hexsha": "3f98101379ac2a184423af6aa0e16eaeaea49f8d", "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/protocol-parameters.tex", "max_forks_repo_name": "obsidiansystems/cardano-ledger-specs", "max_forks_repo_head_hexsha": "3f98101379ac2a184423af6aa0e16eaeaea49f8d", "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.4161073826, "max_line_length": 196, "alphanum_fraction": 0.7331520097, "num_tokens": 1731, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526660244837, "lm_q2_score": 0.34864513533394575, "lm_q1q2_score": 0.1986763598665159}}
{"text": "% Abstract\n\n% We show however, that if mass-dependent heating is responsible, the\n% differential heating rate is not constant over logarithmic time intervals\n% which implies that different heating processes must be acting before and after\n% ages of around 1 Gyr.\n% Perhaps a more likely scenario is that the relation between rotation period\n% and color changes over time, undergoing a particularly sharp transition at\n% around 1 Gyr.\n% If we assume that mass-dependent heating does not affect the data,\n\n% (similar to the age of the rotation gap and the 1.1 Gyr NGC 6811\n% cluster, shown to have a different period-color relation to Praesepe).\n% We find that the ages of field stars with measured rotation periods do not\n% exceed 4-6 Gyrs, resolving a long-standing degeneracy between age and magnetic\n% braking efficiency.\n% We also show that stars rotating just below the rotation period gap are\n% dynamically young, ruling out the possibility that the rotation period gap is\n% caused by incorrect period measurements or binary companions.\n\n% INTRO\n\n% This relation was calibrated by fitting a 5th-order polynomial to the relation\n% between (log) rotation period and (log) \\gaia\\ \\gcolor\\ color for around 800\n% members of the Praesepe cluster, and a straight line in (log) age to Praesepe\n% and the Sun.\n\n% In this paper, we shed light on the rotational evolution of old K dwarfs using\n% population-based dynamical ages.\n% Unfortunately, open clusters with rotation period measurements are mostly\n% young -- currently the oldest is 2.5 Gyr (NGC 6819).\n% Without rotation periods for precisely dated old stars, it is extremely\n% difficult to calibrate the relationship between rotation period and color at\n% old ages.\n% For this reason, we used a population-based stellar age indicator, velocity\n% dispersion, to investigate the period-color relations at old ages in the\n% field.\n\n% Stellar velocities have a history of being used as an age proxy, with several\n% notable examples within stellar astronomy \\citep[\\eg][]{faherty2009,\n% west2011}.\n\n% Vertical {\\it actions} are better age indicators than velocities, because\n% actions are calculated by integrating angular momentum over the Milky Way's\n% potential, and are therefore position invariant -- \\eg\\ a star will have the\n% same action at periapsis and apoapsis.\n% In contrast, orbital velocities are different at periapsis and apoapsis -- so\n% in this sense, {\\it actions} are the natural quantities to use as age proxies.\n\n% \\subsection{The degeneracy between gyrochronology and mass-dependent heating}\n\n% Although only calibrated using Praesepe ($\\sim$ 650 Myr) and the Sun (4.56\n% Gyr), the \\citet{angus2019} gyrochronology relation predicts accurate ages for\n% members of NGC 6819, a 2.5 Gyr open cluster.\n% However there are no rotation periods for K or M dwarfs in this cluster -- its\n% coolest members with rotation periods are G dwarfs.\n% The period-color relation of Praesepe is nearly identical to the period-color\n% relation of the Hyades, a cluster of around the same age: $\\sim$ 650 years\n% \\citep{douglas2016, douglas2017, rebull2017}.\n% However, Praesepe and the Hyades do {\\it not} have the same period-color\n% relation as NGC 6811, a 1.1 Gyr cluster \\citep{curtis2019}.\n% The G dwarfs in NGC 6811 rotate at the same rate as the K dwarfs and it\n% appears as though the K stars have `stalled' -- their spin-down has been\n% halted.\n\n% The \\citet{angus2019} gyrochronology relation assumes that the rotation\n% period-color relation of Praesepe is applicable to stars of all ages: the same\n% polynomial relation fit to Praesepe is used to describe the period-color\n% relation for all stars.\n% However, the NGC 6811 cluster suggests that this assumption does not hold for\n% K dwarfs past around 1 Gyr.\n% If the period-color relation of the \\citet{angus2019} gyrochronology model\n% {\\it were} a perfect model for the rotational evolution of stars, then groups\n% of stars selected to be similar ages using this relation should fall on an\n% isochrone on a CMD.\n% % and have the same velocity dispersion across all colors.\n% Unfortunately, uncertainties on \\gaia\\ photometry and parallaxes, plus\n% variations in metallicity and extinction, blur out the main sequence enough\n% that differences between stars in different age and rotation bins are not\n% easily discernable on the CMD, although there is still a general age and\n% rotation period gradient on the CMD, as seen in figures \\ref{fig:CMD_cuts} and\n% \\ref{fig:age_gradient}.\n% For this reason, we chose to use {\\it kinematic} `isochrones', instead of\n% magnitude and color-based isochrones: although kinematics as an age indicator\n% is not necessarily as well calibrated to an absolute age scale as CMD\n% position, it can be very sensitive to {\\it differences} in the ages of stellar\n% populations.\n\n% Isochrones and stellar evolution tracks are highly dependent on choices made\n% about input physics and assumptions.\n% % and have often been calibrated using\n% % different types of stars.\n% As a result, different sets of models can have very different shapes on the\n% CMD, particularly at low masses.\n% In fact, only empirical models, not physical ones, are currently able to\n% reproduce the CMD positions of M dwarfs.\n% Instead of relying on CMD position to age-date groups of stars, we opted to\n% explore age trends via kinematics.\n% Kinematic age-dating has the advantage of being relatively model independent,\n% or at least, having a very simple model: that velocity dispersion increases\n% over time.\n% This means that it is relatively easy to rank groups of stars by age: older\n% groups have a larger velocity dispersion.\n\n% METHOD\n\n% \\begin{figure}\n% \\caption{\n% A \\gaia\\ color magnitude diagram showing the \\citet{mcquillan2014} sample with\n% extinction-corrected magnitudes, colored by rotation period.\n% We excluded photometric binaries and subgiants from our analysis by removing\n% stars above the two dashed lines.\n% % The rotation periods of binaries and subgiants do not follow a Skumanich-like\n% % braking law.\n% % The 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% % since we rely on a simple scaling\n% % between rotation period and age to make the argument that the rotation period\n% % is not caused by incorrect period measurements.\n% }\n% \\centering\n% \\includegraphics[width=1\\textwidth]{CMD_cuts}\n% \\label{fig:CMD_cuts}\n% \\end{figure}\n% To explore the age of this stellar population from a rotation standpoint, it\n% was first necessary to remove visual binaries and subgiants from the sample.\n% The rotational evolution of these two types of stars is generally different to\n% that of single stars which more usually follow a Skumanich-like spin-down law.\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.\n\n% \\begin{figure}\n% \\caption{\n% the rotation periods of stars in the \\citet{mcquillan2014} sample vs.\n% effective temperature.\n% black points are dwarf stars identified as non-photometric binaries, hotter\n% than 4800 k.\n% blue circle points are non-photometric binary dwarfs, cooler than 4800 k, with\n% a rotation period and \\gaia\\ color indicating they are older than 1.1 gyr.\n% orange squares are stars that with rotation periods that fall just below the\n% gap: they have rotation-ages between 0.5 and 1.1 gyrs.\n% green triangles are stars with rotation periods faster than the main envelop\n% of stars.\n% these are probably binaries whose rotation periods are synchronized to their\n% orbits 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\n% This allowed us to remove the degeneracy between mass and age that would\n% confound evidence for mass-dependent heating among more massive stars.\n% In a sample of massive stars with short MS lifetimes, lower-mass stars\n% typically have greater velocity dispersion, but this could be either because\n% dynamical heating is more efficient in lower mass stars, or because lower mass\n% stars tend to be older because they live longer.\n% In a sample of late K and M dwarfs, whose MS lifetime is longer than the age\n% of the Universe, we can assume that none have evolved into giants and any\n% additional heating seen in the lower-mass stars must be caused by\n% mass-dependent heating.\n\n% \\begin{figure}\n% \\caption{\n% A \\gaia\\ color-magnitude diagram, showing all \\kepler\\ targets.\n% We selected K and M dwarfs by applying color and magnitude cuts at \\gcolor\\ =\n% 1.2 (\\teff\\ $\\sim$ 4800 K) and $G$ = 4.\n% We eliminated visual binaries by fitting a 6th order polynomial to the MS and\n% removing stars above it.\n% Selected K and M dwarfs are shown as darker points.\n% }\n% \\centering\n% \\includegraphics[width=1\\textwidth]{mdwarf_CMD}\n% \\label{fig:mdwarf_CMD}\n% \\end{figure}\n\n% A slight excess of non-Gaussian outliers at lower temperatures leads to a\n% marginal increase in velocity dispersion at low temperatures when sigma\n% clipping is not performed.\n% Figure \\ref{fig:vb_vs_color} shows velocity and velocity dispersion as a\n% function of \\gaia\\ \\gcolor\\ color.\n% There is no clear trend between velocity dispersion and color.\n\n% \\begin{figure}\n% \\caption{\n% Top: Stellar velocity (\\vb) as a function of \\gaia\\ \\gcolor\\ color for\n% \\kepler\\ K and M dwarfs.\n% Vertical lines indicate different color-groupings used to calculate velocity\n% dispersion.\n% Pink stars were not included in velocity dispersion calculations as they were\n% removed as outliers during a sigma clipping process.\n% Bottom: velocity dispersion as a function of color.\n% There is no obvious trend between velocity dispersion and stellar color\n% indicating that mass-dependent heating does not significantly effect\n% low-mass stars in the \\kepler\\ field.\n% }\n% \\centering\n% \\includegraphics[width=1\\textwidth]{vb_vs_color}\n% \\label{fig:vb_vs_color}\n% \\end{figure}\n\n% RESULTS\n\n% The shape of the upper envelope of rotation periods in the top panels of\n% figures \\ref{fig:age_cut} and \\ref{fig:dispersion_period_teff} also hints at\n% this.\n\n% If we assume that the gap is located at a single (gyrochronal) age, its age is\n% remarkably similar to the NGC 6811 cluster (measured from MS turn-off) of 1.1\n% Gyr \\citep{meibom2011}.\n\n% DISCUSSION\n\n% The \\vb\\ AVR is not directly comparable to the \\vz\\ AVR, so, to draw a\n% comparison with results from the literature, we calculated a \\vz\\ AVR for\n% the subset of 290 cool stars in the \\mct\\ sample with \\gaia\\ RVs.\n% We measured an AVR exponent of 0.47 $\\pm$ 0.1, which falls within the range of\n% values (0.45-0.53) reported from measurements of F and G stars in the Solar\n% neighborhood \\citep{holmberg2009, aumer2009, aumer2016}.\n% It is a little lower than the values of 0.56 $\\pm$ 0.14 (for low-z) and 0.51\n% $\\pm$ 0.15 (for high-z stars), calculated using \\LAMOST\\ \\racomment{(LAMOST\n% citation)} K giants \\citep{yu2018}.\n% K giants are more massive than K dwarfs \\racomment{(how much more massive?)},\n% so this slightly higher value contradicts the mass-dependent heating\n% hypothesis.\n% \\racomment{Add some words about selection functions...}\n\n% To investigate further, we calculated the exponent of the (\\vb) AVR for each\n% temperature bin in figure \\ref{fig:age_cut}.\n% \\begin{figure}\n% \\caption{\n% The exponent of the (\\vb) AVR as a function of effective temperature.\n% }\n% \\centering\n% \\includegraphics[width=1\\textwidth]{AVR_exponent}\n% \\label{fig:AVR_exponent}\n% \\end{figure}\n% Figure \\ref{fig:AVR_exponent} shows the significant rise the in AVR exponent\n% as a function of effective temperature.\n% The hottest stars in our sample (\\teff\\ = 4833-5000 K) have a (\\vb) AVR\n% exponent of 0.39 $\\pm$ 0.02 and the coolest (\\teff\\ = 3500-3667 K) have an\n% exponent of 0.74 $\\pm$ 0.02.\n% The masses of stars in our sample differ by less than a factor of two,\n% so mass-dependent heating cannot be entirely responsible for this large spread\n% in heating rates.\n% \\racomment{Need to look into this further.}\n\n% If mass-dependent heating is strongly affecting our data, the exponent of the\n% AVR should increase with decreasing effective temperature, \\ie\\ the heating\n% rate should be greater for lower-mass stars.\n% Figure \\ref{fig:AVR_exponent} shows the AVR exponent does indeed increase with\n% decreasing effective temperature, however, the AVR exponent calculated using\n% more massive stars from the Geneva Copenhagen Survey (GCS)\n% \\citep{holmberg2009} is also shown on this plot as a dashed horizontal line.\n% Most GCS stars are F and G type: 1-3 times more massive than the K dwarfs used\n% in our study.\n% If mass-dependent orbital heating is the main cause the rise in velocity\n% dispersion with decreasing \\teff\\ seen in figure \\ref{fig:age_cut}, then the\n% AVR exponent of the more massive GCS stars should fall {\\it below} the AVR\n% exponent for the most massive stars in our sample.\n% In other words, the dynamical heating rate should be lowest for the highest\n% mass stars and highest for the lowest mass stars.\n% % nordstrom2004, jorgensen2005,\n% These AVR exponents were calculated with different populations of stars,\n% subject to different selection effects, so directly comparing them comes with\n% some risk.\n% The most important difference is that the GCS AVR is calculated using \\vz,\n% however our AVRs are calculated using \\vb\\ since most stars in our sample do\n% not have radial velocities.\n% The median galactic latitude of these \\kepler\\ stars is 12.3\\degrees, with\n% latitudes ranging from 5.5\\degrees\\ to 21.4\\degrees, so \\vb\\ is a relatively\n% close approximation to \\vz.\n% Only 290 out of the 6820 stars in our sample, plotted in color in figure\n% \\ref{fig:age_cut}, have \\gaia\\ radial velocities, however we used the ones\n% that do to compare the \\vz\\ AVR to the \\vb\\ AVR, across all temperatures\n% between 3500 and 5000 K.\n% For stars with gyrochronal ages between 0.5 and 4.5 Gyr, we measured a \\vz\\\n% AVR exponent of 0.519 $\\pm$ ... and a \\vb\\ AVR exponent of 0.514 $\\pm$... .\n% The similarity of these two AVR exponents suggests that directly comparing\n% these two quantities {\\it may} be a reasonable approach.\n% For now, given the large difference between the (\\vz) AVR exponent of the GCS\n% sample and the (\\vb) AVR exponent of the hottest stars in our sample, we\n% assume that the increased velocity dispersion at cooler temperatures is mostly\n% caused by incorrect age-grouping due to an incorrect period-color relation at\n% old ages, and that any mass-dependent heating, while it may contribute at a\n% low level to this result, is not the dominant driver.\n% However, differentiating the effects of mass-dependent heating and the shape\n% of the gyrochronology relations is certainly warranted in a follow-up study.\n% }\n\n% Figure \\ref{fig:age_comparison} shows the ages of star groups, predicted with\n% the \\citet{angus2019} gyrochronology relation, compared with the ages of star\n% groups, predicted with the \\citet{holmberg2009} AVR.\n% \\citet{holmberg2009} only provide an exponent (0.53), not an intercept, for the\n% relation between logarithmic age (in Gyr) and logarithmic, \\vz\\ velocity\n% dispersion (in \\kms), so we fit the intercept to the mean \\vb\\ velocity\n% dispersion across all temperatures, of our sample.\n% \\begin{figure}\n% \\caption{\n% Ages predicted by the \\citet{holmberg2009} \\vz\\ AVR, against ages\n% predicted by the \\citet{angus2019} gyrochronology relation, for stars in\n% different temperature ranges.\n% Points are colored by the effective temperature in the center of the \\teff\\\n% bin.\n% The dashed line shows the y=x relation.\n% Predicted kinematic ages fan out over gyrochronal time, either because the AVR\n% is temperature-dependent or because the gyrochronology relations have an\n% age-dependent period-color relation.\n% }\n% \\centering\n% \\includegraphics[width=1\\textwidth]{age_comparison}\n% \\label{fig:age_comparison}\n% \\end{figure}\n% Figure \\ref{fig:age_comparison} shows a comparison between ages predicted by\n% the \\citet{holmberg2009} \\vz\\ AVR (using \\vb\\ as a proxy for \\vz) and ages\n% predicted by the \\citet{angus2019} gyrochronology relation, for stars in\n% different temperature ranges.\n% The predicted kinematic ages fan out over gyrochronal time, either because the\n% AVR is temperature-dependent or because the gyrochronology relations have an\n% age-dependent period-color relation.\n% Figure \\ref{fig:age_comparion} also suggests that dynamical heating does not\n% begin until after around ... Gyr:\n\n% Alternatively, the ages of these young stars could be under-predicted by\n% gyrochronology.\n% These young stars have similar rotation periods to the Praesepe cluster, which\n% was used to calibrate the gyrochronology relation used in this analysis.\n% The ages of these young stars should, therefore, be the most accurate of the\n% entire sample.\n% However, they are tied to the age of the Praesepe cluster, whose age is not\n% accurately known.\n% \\citet{angus2019} adopted an age for Praesepe of 650 Myrs, however the\n% kinematic age-prediction for these stars is around 400 Myrs.\n% Other studies have assigned a much older age of 800 Myrs to Praesepe\n% \\citep{brandt2015}.\n% If the age assumed for Praesepe in the \\citet{angus2019} gyrochronology\n% calibration was inaccurate, the entire age {\\it scale} would be incorrect.\n% However, this is not what figure \\ref{fig:age_comparion} shows -- it shows\n% that the {\\it relative} age of these youngest stars are under-predicted by\n% kinematics or over-predicted by gyrochronology.\n\n% If we assume that the rise in velocity dispersions at cooler effective\n% temperatures is caused by an inaccurate period-color relation rather than\n% mass-dependent dynamical heating, we can estimate what the shape of the\n% period-color relations {\\it should} be.\n% Figure \\ref{fig:age_cut} indicates that the period-color relation flattens\n% out, so we applied the same analysis to groups of stars with similar rotation\n% periods, equivalent to a completely flat period-color relation.\n% The top panel of figure \\ref{fig:period_cut} shows the \\mct\\ sample with stars\n% in different period ranges plotted in different colors.\n% The bottom panel shows the velocity dispersion of each group as a function of\n% effective temperature.\n% \\begin{figure}\n% \\caption{\n% This figure is similar to figure \\ref{fig:age_cut}, with stars divided into\n% period groups rather than age groups.\n% The velocity dispersion is more constant across effective temperatures for the\n% most slowly rotating stars, compared to the stars selected with the\n% \\citet{angus2019} gyrochronology model, indicating that the gyrochronology\n% models flatten out, and possibly even invert, at old ages.\n% }\n% \\centering\n% \\includegraphics[width=1\\textwidth]{period_cut}\n% \\label{fig:period_cut}\n% \\end{figure}\n% Once again, the velocity dispersion increases with rotation period overall.\n% For the most rapidly rotating groups of stars, velocity dispersion decreases\n% with \\teff\\ as expected given the positively sloped period-color relation of\n% Praesepe and other young clusters: late K dwarfs rotate more slowly than early\n% K dwarfs of the same age.\n% Between rotation periods of 15 and 25 days, the temperature dependence of the\n% velocity dispersion starts to disappear, indicating that the period-color\n% relation becomes flat: late K dwarfs rotate at the same rate as early K dwarfs\n% of the same age.\n% At long rotation periods, the velocity dispersion still increases with\n% effective temperature, although the increase is much more modest compared to\n% the oldest stars in figure \\ref{fig:age_cut}.\n\n% If we assume the rise in velocity dispersion at cooler effective temperatures\n% is caused by an inaccurate period-color relation rather than mass-dependent\n% dynamical heating, we can generate a graphical representation of what the\n% relations {\\it should} look like.\n\n% Aside from the assumption that mass-dependent dynamical heating is {\\it not}\n% the main cause of the increased velocity dispersion for cooler stars, a number\n% of assumptions went into this analysis which should be addressed before a\n% strong conclusion about the nature of stellar spin down is drawn.\n% There are some potential confounders that could produce trends between\n% velocity dispersion and effective temperature, of which the main ones are\n% listed below.\n% \\begin{itemize}\n\n % \\item{{\\bf Extinction.}\n% Although we dereddened stars before their ages were estimated, if the\n % reddening values were underestimated, the gyrochronal ages of stars\n % would be under-estimated.\n% This effect would be largest for the late Ks and early Ms, where the shape of\n % the period-color relation is more steeply sloped, and stars can more\n % easily move into the wrong age bin with a small perturbation in color\n % or temperature.\n% Old stars would be incorrectly assigned young ages, and this would happen more\n % often for cooler stars.\n% This effect could lead to an increase in velocity dispersion with \\teff, even\n% if the gyrochronology relation was perfect.}\n\n % \\item{{\\bf Mass-dependent orbital heating.}\n% A key assumption going into this analysis is that the orbits of all stars are\n% heated at the same rate, regardless of their mass.\n% However, if the heating mechanism leads to preferential heating of lower mass\n% stars, those stars would have a larger velocity dispersion, not caused by\n% ageing.\n% No strong evidence has yet been provided to show a mass-dependence in orbital\n% heating, however this is an extremely difficult exercise because mass and age\n% are so strongly correlated.\n% The mass-age degeneracy is reduced in the lowest mass stars which represent\n % the initial mass function of the Solar neighborhood.\n% No mass-dependent heating was found by \\citet{faherty2009} who looked\n% at the velocity dispersions of low-mass stars.\n% Another argument against the increased velocity dispersion as a function of\n % \\teff\\ being caused by mass-dependent orbital heating, is that heating\n % acts most strongly at young ages and most weakly at old ages, \\ie\\ on\n % a logarithmic timescale.\n% This is related to the fact that stars are more difficult to scatter once they\n% are on orbits with a large out-of-plane component and they spend more time out\n% of the mid-plane.\n% Our data show the opposite trend: stars show little mass-dependent heating\n % before around 1 Gyr.\n% Moreover, the stars in the Geneva-Copenhagen study, used to calibrate the AVR\n % \\citep{holmberg2009} are F and G stars, around 1-3 times as massive as\n % the K stars in our sample.\n% % nordstrom2004, jorgensen2005,\n% The ages for our sample of K stars, predicted by gyrochronology agree with the\n % AVR calibrated using F and G stars, which implies that either\n % mass-dependent heating is a weak effect, or, mass-dependent heating is\n % strong and, by coincidence, gyrochronology underpredicts the ages of\n % the early K dwarfs by just the right amount that they still appear to\n % agree with the \\citet{holmberg2009} AVR.\n% We therefore expect that the increased velocity dispersion at cooler\n % temperatures is mostly caused by incorrect age-grouping, \\ie\\ the\n % period-color relation is incorrect for old, low-mass stars, and that\n % any mass-dependent heating, while it may contribute at a low level to\n % this result, is not the dominant cause.\n% }\n\n % \\item{{\\bf Selection bias.}\n% The \\gaia\\\n% catalog is incompletebecause they are too faint.\n% This is simply due to the fact that \\kepler's field of view was aimed at low\n % galactic latitudes, so nearby \\kepler\\ stars are close to the galactic\n % plane.\n% The heights of stars above the galactic plane, and correspondingly their\n % velocities and ages, are therefore correlated with distance.\n% Almost no high velocity stars appear in our sample at temperatures cooler than\n% 3500, which is why the coolest stars were excluded from our sample, however\n% the selection function could still affect stars hotter than 3500 K, and is\n% suggested by the decrease in velocity dispersions for cool stars of all ages\n% in figure \\ref{fig:age_cut}.\n% However, this selection effect would act in opposition to the observed trend.\n% }\n\n% \\item{{\\bf Weakened magnetic braking.}\n% The rotation periods of old stars are faster than predicted by Skumanich-like\n% magnetic braking \\citep{angus2015, vansaders2016, metcalfe2019}.\n% Magnetic braking is expected to become inefficient once stars approach a\n% Rossby number (the ratio of rotation period to convective turnover time) of\n% around 2 \\citep{vansaders2016, vansaders2018}.\n% Since hot stars have shallow convection zones and shorter overturn timescales,\n% they reach $Ro = 2$ and stop spinning down at shorter rotation periods than\n% cool stars.\n% For this reason, some of the hotter stars in the sample may already have\n% stopped spinning down, and could be much older than a traditional\n% gyrochronology relation (like the simple Praesepe-based relation used in this\n% analysis) would suggest.\n% However, this effect would work to cancel out the trend observed in figure\n% \\ref{fig:age_cut} because hotter groups of stars would contain more old stars\n% with large velocities.\n% }\n\n% \\item{Stellar or exoplanet companions.}\n% Hotter stars are more likely to be binaries.\n% This would make synchronized some stars seem younger, more likely for massive\n% stars, although really only likely at short rotation periods.\n\n% \\end{itemize}\n\n% CONCLUSION\n\n% This indicates that either the \\citep{angus2019} period-color relation is\n% incorrect, or that mass-dependent dynamical heating is affecting this data set.\n% We presented three pieces of evidence that suggest mass-dependent heating\n% cannot be responsible for all of the increasing velocity dispersion.\n\n% \\begin{itemize}\n\n% \\item{\n% No strong evidence for mass-dependent heating has been found among M, L\n% and T-type stars.\n% These low-mass stars live longer than the current age of the Universe and\n% therefore do not suffer from a mass-age degeneracy\n% \\citep{faherty2009}.\n% }\n\n% \\item{\n% Literature measurements of the (\\vz) AVR exponent are slightly higher\n% than the value measured from our data set, but calculated using more massive\n% stars.\n% Mass-dependent dynamical heating should however produce a {\\it smaller} AVR\n% exponent for higher-mass stars.\n% We acknowledge that the stars in the \\mct\\ sample, analyzed in this work, are\n% subject to different selection biases than those used to calculate\n% AVRs in the literature \\citep{holmberg2009, aumer2009, yu2018}, so\n% drawing direct comparisons between them does not provide a reliable\n% test.\n% }\n\n% \\item{\n% The differences in the (\\vb) AVR exponent between the hottest and\n% coolest K dwarfs in our sample are extremely large, spanning values between\n% 0.4 and 0.75, yet the difference in mass is less than a factor of two.\n% Such a large spread in AVR exponents cannot be explained by mass-dependent\n% heating alone.\n% }\n\n% \\end{itemize}\n\n% \\racomment{Words about the significance of an inverted period-color relation.}\n\n% \\racomment{How does the weakened van Saders braking law fit into all this?}\n\n% \\racomment{Talk about the fact that the stars in each bin are not necessarily\n% the same age.}\n\n% \\racomment{Dispersion could be dependent on the selection function.\n% We cut stars at high b, because we find that these do lead to a bias.\n% We find no evidence for increased velocity dispersion with decreasing teff in\n% either vb or vz.\n% We find that sigma clipping is necessary for vb but not vz and do not find\n% that the outliers are distributed towards higher galactic latitudes.\n% }\n\n% \\racomment{Trevor suggest that stars forming in clusters could be the reason\n% why young stars are so dynamically cool.}\n\n% \\racomment{Are there any asteroseismic stars in this sample that could help\n% pin down the age?}\n", "meta": {"hexsha": "24fa8b1f0eeddcf87e2de497dde76436183f28c5", "size": 28433, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "paper/comments.tex", "max_stars_repo_name": "adrn/kinematics-and-rotation", "max_stars_repo_head_hexsha": "c16ce41fdff8574410c37b9fb40094b0f51b18f4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-01-23T18:24:18.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-15T10:37:05.000Z", "max_issues_repo_path": "paper/comments.tex", "max_issues_repo_name": "adrn/kinematics-and-rotation", "max_issues_repo_head_hexsha": "c16ce41fdff8574410c37b9fb40094b0f51b18f4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2020-03-11T16:46:55.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-23T15:10:58.000Z", "max_forks_repo_path": "paper/comments.tex", "max_forks_repo_name": "adrn/kinematics-and-rotation", "max_forks_repo_head_hexsha": "c16ce41fdff8574410c37b9fb40094b0f51b18f4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-01-23T14:11:57.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-21T11:51:15.000Z", "avg_line_length": 51.8850364964, "max_line_length": 81, "alphanum_fraction": 0.761017128, "num_tokens": 6939, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.37387581579519075, "lm_q1q2_score": 0.1986063378281652}}
{"text": "\\section{EOS Calls}\n\n\\subsection{Initialization}\n\n\\subsection{{\\tt advance\\_timestep}}\n\n\\begin{description}\n\\item[Step 1.] {\\em Define the average expansion at time $t^\\nph$ and the new $w_0.$}\\\\ \\\\\nif \\runparam{dpdt\\_factor} $>$ 0 then\n%\n\\begin{itemize}\n\\item In {\\tt makePfromRhoH}, we compute a thermodynamic $p^n$ for the volume discrepancy \nterm using $(\\rho,h,X)^n$.\n\\end{itemize}\nend if\n\\item[Step 2.] {\\em Construct the provisional edge-based advective velocity, $\\uadvone.$}\n\\item[Step 3.] {\\em React the full state and base state through the first time interval \nof $\\dt/2.$}\n\\begin{itemize}\n\\item In {\\tt react\\_state} $\\rightarrow$ {\\tt burner}, we compute $c_p$ and $\\xi_k$ \nfor inputs to {\\tt VODE} using $(\\rho,T,X)^n$.\n\\item In {\\tt react\\_state}, we compute $T^{(1)}$ using $(\\rho,h,X)^{(1)}$ \n(if \\runparam{use\\_tfromp} {\\tt = F}) or $(\\rho,X)^{(1)}$ and $p_0^n$ (if {\\tt use\\_tfromp = T})\n\\end{itemize}\nif \\runparam{evolve\\_base\\_state} {\\tt = T} then\n\\begin{itemize}\n\\item In {\\tt make\\_gamma}, we compute $\\Gamma_1$ using $(\\rho,X)^{(1)}$ and $p_0^n$.\n\\end{itemize}\nend if\n\\item[Step 4.] {\\em Advect the base state, then the full state, through a time interval \nof $\\dt.$}\\\\ \\\\\nif \\runparam{use\\_thermal\\_diffusion} {\\tt = T} then\n\\begin{itemize}\n\\item In {\\tt advance} before {\\tt make\\_explicit\\_thermal}, we compute the coefficients for \n$\\nabla\\cdot(\\kth/c_p)\\nabla h + \\cdots$ using $(\\rho,T,X)^{(1)}$.\n\\item In {\\tt enthalpy\\_advance} $\\rightarrow$ {\\tt update\\_scal}, we compute $h$ above\nthe \\runparam{base\\_cutoff\\_density} using $(\\rho,X)^{(2),*}$ and $p_0^{n+1,*}$.\n\\item In {\\tt thermal\\_conduct}, we compute $T^{(2),*}$ using $(\\rho,h,X)^{(2),*}$\n(if {\\tt use\\_tfromp = F}) or $(\\rho,X)^{(2),*}$ and $p_0^{n+1,*}$ (if {\\tt use\\_tfromp = T}).\n\\end{itemize}\nelse\n\\begin{itemize}\n\\item In {\\tt enthalpy\\_advance} $\\rightarrow$ {\\tt update\\_scal}, we compute $h$ above\nthe \\runparam{base\\_cutoff\\_density} using $(\\rho,X)^{(2),*}$ and $p_0^{n+1,*}$.\n\\item In {\\tt enthalpy\\_advance}, we compute $T^{(2),*}$ using $(\\rho,h,X)^{(2),*}$\n(if {\\tt use\\_tfromp = F}) or $(\\rho,X)^{(2),*}$ and $p_0^{n+1,*}$ (if {\\tt use\\_tfromp = T}).\n\\end{itemize}\nend if\n\\item[Step 5.] {\\em React the full state through a second time interval of $\\dt/2.$}\n\\begin{itemize}\n\\item In {\\tt react\\_state} $\\rightarrow$ {\\tt burner}, we compute $c_p$ and $\\xi_k$ \nfor inputs to {\\tt VODE} using $(\\rho,T,X)^{(2),*}$.\n\\item In {\\tt react\\_state}, we compute $T^{n+1,*}$ using $(\\rho,h,X)^{n+1,*}$ \n(if {\\tt use\\_tfromp = F}) or $(\\rho,X)^{n+1,*}$ and $p_0^{n+1,*}$ (if {\\tt use\\_tfromp = T}).\n\\end{itemize}\nif {\\tt evolve\\_base\\_state} then\n\\begin{itemize}\n\\item In {\\tt make\\_gamma}, we compute $\\Gamma_1$ using $(\\rho,X)^{n+1,*}$ and $p_0^{n+1,*}$.\n\\end{itemize}\nend if\n\\item[Step 6.] {\\em Define a new average expansion rate at time $t^\\nph.$}\\\\ \\\\\nif \\runparam{use\\_thermal\\_diffusion} then\n\\begin{itemize}\n\\item In {\\tt advance} before {\\tt make\\_explicit\\_thermal}, we compute the coefficients for \n$\\nabla\\cdot(\\kth/c_p)\\nabla h + \\cdots$ using $(\\rho,T,X)^{n+1,*}$.\n\\end{itemize}\nend if\n\\begin{itemize}\n\\item In {\\tt make\\_S}, we compute thermodynamic variables using $(\\rho,T,X)^{n+1,*}$.\n\\end{itemize}\nif \\runparam{dpdt\\_factor} $>$ 0 then\n\\begin{itemize}\n\\item In {\\tt makePfromRhoH}, we compute a thermodynamic $p^{n+1,*}$ for the volume \ndiscrepancy term using $(\\rho,h,X)^{n+1,*}$.\n\\end{itemize}\nend if\n\\item[Step 7.] {\\em Construct the final edge-based advective velocity, $\\uadvtwo.$}\n\\item[Step 8.] {\\em Advect the base state, then the full state, through a time interval \nof $\\dt.$}\\\\ \\\\\nif \\runparam{use\\_thermal\\_diffusion} = T then\n\\begin{itemize}\n\\item In {\\tt enthalpy\\_advance} $\\rightarrow$ {\\tt update\\_scal}, we compute $h$ above\nthe \\runparam{base\\_cutoff\\_density} using $(\\rho,X)^{(2)}$ and $p_0^{n+1}$.\n\\item In {\\tt advance} before {\\tt thermal\\_conduct}, we compute the coefficients for \n$\\nabla\\cdot(\\kth/c_p)\\nabla h + \\cdots$ using $(\\rho,T,X)^{(2),*}$.\n\\item In {\\tt thermal\\_conduct}, we compute $T^{(2)}$ using $(\\rho,h,X)^{(2)}$\n(if \\runparam{use\\_tfromp} {\\tt = F}) or $(\\rho,X)^{(2)}$ and $p_0^{n+1}$ (if {\\tt use\\_tfromp} {\\tt = T}).\n\\end{itemize}\nelse\n\\begin{itemize}\n\\item In {\\tt enthalpy\\_advance} $\\rightarrow$ {\\tt update\\_scal}, we compute $h$ above\nthe {\\tt base\\_cutoff\\_density} using $(\\rho,X)^{(2)}$ and $p_0^{n+1}$.\n\\item In {\\tt enthalpy\\_advance}, we compute $T^{(2)}$ using $(\\rho,h,X)^{(2)}$\n(if {\\tt use\\_tfromp} {\\tt = F}) or $(\\rho,X)^{(2)}$ and $p_0^{n+1}$ (if {\\tt use\\_tfromp = T}).\n\\end{itemize}\nend if\n\\item[Step 9.] {\\em React the full state and base state through a second time interval \nof $\\dt/2.$}\n\\begin{itemize}\n\\item In {\\tt react\\_state} $\\rightarrow$ {\\tt burner}, we compute $c_p$ and $\\xi_k$ \nfor inputs to {\\tt VODE} using $(\\rho,T,X)^{(2)}$.\n\\item In {\\tt react\\_state}, we compute $T^{n+1}$ using $(\\rho,h,X)^{n+1}$ \n(if {\\tt use\\_tfromp = F}) or $(\\rho,X)^{n+1}$ and $p_0^{n+1}$ (if {\\tt use\\_tfromp = T}).\n\\end{itemize}\nif \\runparam{evolve\\_base\\_state} {\\tt = T} then\n\\begin{itemize}\n\\item In {\\tt make\\_gamma}, we compute $\\Gamma_1$ using $(\\rho,X)^{n+1}$ and $p_0^{n+1}$.\n\\end{itemize}\nend if\n\\item[Step 10.] {\\em Compute $S^{n+1}$ for the final projection.}\\\\ \\\\\nif {\\tt make\\_explicit\\_thermal} then\n\\begin{itemize}\n\\item In {\\tt advance} before {\\tt make\\_explicit\\_thermal}, we compute the coefficients for \n$\\nabla\\cdot(\\kth/c_p)\\nabla h + \\cdots$ using $(\\rho,T,X)^{n+1}$.\n\\end{itemize}\nend if\n\\begin{itemize}\n\\item In {\\tt make\\_S}, we compute thermodynamic variables using $(\\rho,T,X)^{n+1}$.\n\\end{itemize}\n\\item[Step 11.] {\\em Update the velocity.}\\\\ \\\\\nif \\runparam{dpdt\\_factor} $>$ 0 then\n\\begin{itemize}\n\\item In {\\tt makePfromRhoH}, we compute a thermodynamic $p^{n+1}$ for the volume \ndiscrepancy term using $(\\rho,h,X)^{n+1}$.\n\\end{itemize}\nend if\n\\item[Step 12.] {\\em Compute a new $\\dt.$}\n\\end{description}\n\n\\subsection{{\\tt make\\_plotfile}}\n\n\\section{Temperature Usage}\n\n\\subsection{{\\tt advance\\_timestep}}\n\\begin{description}\n\\item[Step 1.] {\\em Define the average expansion at time $t^\\nph$ and the new $w_0.$}\n\\item[Step 2.] {\\em Construct the provisional edge-based advective velocity, $\\uadvone.$}\n\\item[Step 3.] {\\em React the full state and base state through the first time interval \nof $\\dt/2.$}\n\\begin{itemize}\n\\item In {\\tt react\\_state} $\\rightarrow$ {\\tt burner}, we compute $c_p$ and $\\xi_k$ \nfor inputs to {\\tt VODE} using $(\\rho,T,X)^n$.\n\\item In {\\tt react\\_state}, we compute $T^{(1)}$ using $(\\rho,h,X)^{(1)}$ \n(if \\runparam{use\\_tfromp} {\\tt = F}) or $(\\rho,X)^{(1)}$ and $p_0^n$ (if {\\tt use\\_tfromp = T}).\n\\end{itemize}\n\\item[Step 4.] {\\em Advect the base state, then the full state, through a time interval \nof $\\dt.$}\\\\ \\\\\nif \\runparam{use\\_thermal\\_diffusion} {\\tt = T} then\n\\begin{itemize}\n\\item In {\\tt advance} before {\\tt make\\_explicit\\_thermal}, we compute the coefficients for \n$\\nabla\\cdot(\\kth/c_p)\\nabla h + \\cdots$ using $(\\rho,T,X)^{(1)}$.\n\\item In {\\tt thermal\\_conduct}, we compute $T^{(2),*}$ using $(\\rho,h,X)^{(2),*}$\n(if {\\tt use\\_tfromp = F}) or $(\\rho,X)^{(2),*}$ and $p_0^{n+1,*}$ (if {\\tt use\\_tfromp = T}).\n\\end{itemize}\nelse\n\\begin{itemize}\n\\item In {\\tt enthalpy\\_advance}, we compute $T^{(2),*}$ using $(\\rho,h,X)^{(2),*}$\n(if {\\tt use\\_tfromp = F}) or $(\\rho,X)^{(2),*}$ and $p_0^{n+1,*}$ (if {\\tt use\\_tfromp = T}).\n\\end{itemize}\nend if\n\\item[Step 5.] {\\em React the full state through a second time interval of $\\dt/2.$}\n\\begin{itemize}\n\\item In {\\tt react\\_state} $\\rightarrow$ {\\tt burner}, we compute $c_p$ and $\\xi_k$ \nfor inputs to {\\tt VODE} using $(\\rho,T,X)^{(2),*}$.\n\\item In {\\tt react\\_state}, we compute $T^{n+1,*}$ using $(\\rho,h,X)^{n+1,*}$ \n(if {\\tt use\\_tfromp = F}) or $(\\rho,X)^{n+1,*}$ and $p_0^{n+1,*}$ (if {\\tt use\\_tfromp = T}).\n\\end{itemize}\n\\item[Step 6.] {\\em Define a new average expansion rate at time $t^\\nph.$}\\\\ \\\\\nif \\runparam{use\\_thermal\\_diffusion} {\\tt = T} then\n\\begin{itemize}\n\\item In {\\tt advance} before {\\tt make\\_explicit\\_thermal}, we compute the coefficients for \n$\\nabla\\cdot(\\kth/c_p)\\nabla h + \\cdots$ using $(\\rho,T,X)^{n+1,*}$.\n\\end{itemize}\nend if\n\\begin{itemize}\n\\item In {\\tt make\\_S}, we compute thermodynamic variables using $(\\rho,T,X)^{n+1,*}$.\n\\end{itemize}\n\\item[Step 7.] {\\em Construct the final edge-based advective velocity, $\\uadvtwo.$}\n\\item[Step 8.] {\\em Advect the base state, then the full state, through a time interval \nof $\\dt.$}\\\\ \\\\\nif {\\tt use\\_thermal\\_diffusion = T} then\n%\n\\begin{itemize}\n\\item In {\\tt advance} before {\\tt thermal\\_conduct}, we compute the coefficients for \n$\\nabla\\cdot(\\kth/c_p)\\nabla h + \\cdots$ using $(\\rho,T,X)^{(2),*}$.\n\\item In {\\tt thermal\\_conduct}, we compute $T^{(2)}$ using $(\\rho,h,X)^{(2)}$\n(if {\\tt use\\_tfromp = F}) or $(\\rho,X)^{(2)}$ and $p_0^{n+1}$ (if {\\tt use\\_tfromp = T}).\n\\end{itemize}\nelse\n\\begin{itemize}\n\\item In {\\tt enthalpy\\_advance}, we compute $T^{(2)}$ using $(\\rho,h,X)^{(2)}$\n(if {\\tt use\\_tfromp = F}) or $(\\rho,X)^{(2)}$ and $p_0^{n+1}$ (if {\\tt use\\_tfromp = T}).\n\\end{itemize}\nend if\n\\item[Step 9.] {\\em React the full state and base state through a second time interval \nof $\\dt/2.$}\n\\begin{itemize}\n\\item In {\\tt react\\_state} $\\rightarrow$ {\\tt burner}, we compute $c_p$ and $\\xi_k$ \nfor inputs to {\\tt VODE} using $(\\rho,T,X)^{(2)}$.\n\\item In {\\tt react\\_state}, we compute $T^{n+1}$ using $(\\rho,h,X)^{n+1}$ \n(if {\\tt use\\_tfromp = F}) or $(\\rho,X)^{n+1}$ and $p_0^{n+1}$ (if {\\tt use\\_tfromp = T}).\n\\end{itemize}\n\\item[Step 10.] {\\em Compute $S^{n+1}$ for the final projection.}\\\\ \\\\\nif {\\tt make\\_explicit\\_thermal} then\n\\begin{itemize}\n\\item In {\\tt advance} before {\\tt make\\_explicit\\_thermal}, we compute the coefficients for \n$\\nabla\\cdot(\\kth/c_p)\\nabla h + \\cdots$ using $(\\rho,T,X)^{n+1}$.\n\\end{itemize}\nend if\n\\begin{itemize}\n\\item In {\\tt make\\_S}, we compute thermodynamic variables using $(\\rho,T,X)^{n+1}$.\n\\end{itemize}\n\\item[Step 11.] {\\em Update the velocity.}\n\\item[Step 12.] {\\em Compute a new $\\dt.$}\n\\end{description}\n", "meta": {"hexsha": "3639dd2eb465b0ee6e6bed5dc599399669abc675", "size": 10042, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Docs/eos_notes/eos_notes.tex", "max_stars_repo_name": "sailoridy/MAESTRO", "max_stars_repo_head_hexsha": "f957d148d2028324a2a1076be244f73dad63fd67", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL"], "max_stars_count": 17, "max_stars_repo_stars_event_min_datetime": "2017-05-15T15:28:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-09T08:13:32.000Z", "max_issues_repo_path": "Docs/eos_notes/eos_notes.tex", "max_issues_repo_name": "sailoridy/MAESTRO", "max_issues_repo_head_hexsha": "f957d148d2028324a2a1076be244f73dad63fd67", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2017-06-14T23:05:00.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-28T16:40:42.000Z", "max_forks_repo_path": "Docs/eos_notes/eos_notes.tex", "max_forks_repo_name": "sailoridy/MAESTRO", "max_forks_repo_head_hexsha": "f957d148d2028324a2a1076be244f73dad63fd67", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2017-06-14T14:52:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-04T07:16:09.000Z", "avg_line_length": 46.4907407407, "max_line_length": 107, "alphanum_fraction": 0.6383190599, "num_tokens": 3694, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.3380771374883919, "lm_q1q2_score": 0.19780932335418258}}
{"text": "\\section{Introduction}\n\\label{sec:intro}\n\nWith the discovery of a new scalar particle the Higgs boson~\\cite{HIGG-2012-27,CMS-HIG-12-028} at the LHC~\\cite{Evans:2008zzb} by the ATLAS and CMS collaborations with a mass of 125 GeV~\\cite{HIGG-2016-33,HIGG-2013-12,HIGG-2014-14,CMS-HIG-14-009}, the whole content of the Standard Model (SM) of particle physics became complete. A priority of the ATLAS and CMS collaborations has been to better understand its properties and couplings.\nAfter the EWSB and the higgs field acquires the vev, the higgs potential obtained in Equation.. can be obtained as following:\n\\begin{align}\n\tV(\\phi) \\rightarrow V(\\phi)_{\\text{EWSB}} = -\\lambda \\nu^2 h^2 - \\lambda \\nu h^3 - \\frac{1}{4} \\lambda h^4 + \\text{const.}\n\t\\label{eq:higgs_pot}\n\\end{align}\nThe first term of the above equation is the Higgs mass term, and the remaining are the trilinear and quadri-linear Higgs-self couplings,\n\\begin{align}\n\t\\underbrace{m_{h} = \\sqrt{ - 2 \\mu^2} = \\sqrt{ 2 \\lambda v^2 }}_\\text{Higgs boson mass} \\hspace{1cm} \\underbrace{\\lambda_{hhh} \\propto \\frac{m_h^2}{v} \\hspace{1cm} \\lambda_{hhhh} \\propto \\frac{m_h^2}{v^2}}_\\text{Trilinear and quadri-linear Higgs self-couplings}.\n\t\\label{eq:higgs_self_couplings}\n\\end{align}\nA measurements of this couplings would therefore give a hint about the actual structure of the potential, whose shape can have theoretical consequences. The quartic Higgs coupling, $\\lambda_{hhhh}$, can not be measured at LHC since the cross-section of triple Higgs production is small~\\cite{PhysRevD.74.113008}~\\cite{PhysRevD.93.035026}, while the trilinear coupling can be probed directly in Higgs pair production. \n\nThe trilinear coupling leads to non-resonant pair production of Higgs bosons, where an off-shell\nHiggs decays to a pair of Higgs bosons, the leading production mechanism being $gg$-fusion.\nDirect observation of Higgs pair production would lead to measurements directly sensitive to\n$\\lambda$ but in the SM there are competing diagrams, proceeding via quark (re: top quark) loops\nthat are instead senstive to the Yukawa coupling of the Higgs rather than the trilinear coupling\n$\\lambda$. These \\dihiggs production mechanisms are illustrated in the Feynman diagrams presented\nin Figure \\ref{fig:sm_nonres_hh}. Not only does the quark-loop induced process present\nitself as an irreducible background to the process senstive to the Higgs self-coupling, but\nit interfereces \\textit{destructively} with the latter, making the observation of this\ntype of Higgs pair production more challenging.\n\n\n% Due to its lower cross section, diHiggs production is not expected to be observed in the current data taking setup, however it is possible to define limits on the measurement to constrain the BSM physics theories. \n\\begin{figure}[!htb]\n \\centering\n \\includegraphics[width=0.9\\textwidth]{figures/sm_nonres_hh_production}\n \\caption{Representative diagrams that contribute to non-resonant \\hh production.\n \\textit{Left}: Diagram that is sensitive to the trilinear coupling, $\\lambda$.\n \\textit{Right}: Box diagram that interferese destructively with the $\\lambda$-sensitive\n process.} \n \\label{fig:sm_nonres_hh}\n\\end{figure}\n\n\nAs a result of the destructive interference, and the already relatively large Higgs mass of\n125 \\GeV, the SM \\dihiggs production has a total cross-section of $\\sim 33.4$ fb ~\\cite{CERN-YR-4}\nat a \\pp center-of-mass collision energy of 13 \\TeV. The inclusive cross-section for the pair-production\nof top quarks, which will be one of the dominant SM backgrounds in the present\nanalysis, is nearly 1000 pb, or $1\\times10^6$ fb ~\\cite{TOPQ-2015-09, ATLAS-CONF-2015-049}. That\nof \\textit{single} Higgs production is $\\sim 50$ pb, or $5 \\times 10^4$ fb ~\\cite{ATLAS-CONF-2015-060}.\n\nFurthermore, enhancements to the di-Higgs production rate, either non-resonantly or through a resonance, may be observable with the full Run2 dataset and would point to new physics beyond the Standard Model, making such analyses interesting now. The wide class of two Higgs double models (2HDM) predict an altered and enlarged\nHiggs sector from which the currently Higgs is built.\nThe Minimal Supersymmetric Standard Model\n(MSSM) is a class of 2HDM. For the latter set, one such model is a Randall-Sundrum\ntype graviton or the lightest Kaluza-Klein excitation which have masses of at least\n$2\\times$ the mass of the SM Higgs boson. The presence of such BSM scenarios would act to alter\nthe measured value of $\\lambda$ with respect to that of the SM, potentially enlarging it.\nAs a result, early evidence for the pair-production of Higgs bosons within the current\nRun-2 dataset may indicate the presence of new physics without having to resort to\nprecision measurements of $\\lambda$. Examples of such decay\nscenarios are illustrated in example Feynman diagrams in Figure \\ref{fig:2hdm_feynman_diagrams}.\n\n\\begin{figure}[!htb]\n \\centering\n \\includegraphics[width=0.8\\textwidth]{figures/mg5_hh_heavy_scalar.png}\n \\includegraphics[width=0.8\\textwidth]{figures/mg5_hh_2hdm_cp_even.png}\n \\caption\n {\n Diagrams contributing to enhanced $hh$ production scenarios.\n \\textit{Top}: A heavy scalar, $H$, that couples to the Standard Model Higgs\n boson, $h$, contributes to the Standard Model processes (left two diagrams).\n \\textit{Bottom}: CP-even diagrams in 2HDM scenario that contribute to enhanced\n non-resonant production of Standard Model Higgs bosons as well as resonant\n channels with the heavy CP-even Higgs, $H^0$, decaying to the Standard Model\n low-mass CP-even Higgs, $h$.\n }\n \\label{fig:2hdm_feynman_diagrams}\n\\end{figure}\n\n\nIn addition to the hh production mechanisms described above, the searches for evidence of an dditional extended Higgs sector model that introduces two new heavy Higgs bosons, X and S~\\cite{vonBuddenbrock:2016rmr}. In this model, $X$ couples strongly to both $S$ and $h$. $S$ couples weakly to SM particles, suppressing direct production, but has the same mass-dependent branching ratios as $h$. \n\nSearches for resonant Higgs pair production have been performed in a number of final states, $b\\bar{b}b\\bar{b}$, $b\\bar{b}\\tau^{\\pm}\\tau^{\\mp}$, $b\\bar{b}\\gamma\\gamma$, $W^{\\pm}W^{\\mp *}\\gamma\\gamma$, $b\\bar{b}VV$ (With $V$ either $Z$ or $W$) and $W^+W^-W^+W^-$ at $\\sqrt{s}=8\\,\\TeV$ and $\\sqrt{s}=13\\,\\TeV$ by ATLAS~\\cite{HIGG-2013-33,Aad:2019uzh} and CMS collaborations~\\cite{CMS-HIG-13-032,CMS-HIG-15-013,PhysRevLett.122.121803} including the combination of multiple final states. \n\nIn this note, the searches for the \\dihiggs non-resonant production in multilepton final states is described. Typically the decay modes of \\dihiggs of $W^+W^-W^+W^-$, $ZZ^*bb$, $VV\\tauh\\tauh$, $\\tauh\\tauh\\tauh\\tauh$, $ZZZZ$ are the dominant ones which corresponds to 5.7\\% of all \\dihiggs decays. Additionally, $\\gamma\\gamma + X$ final states are studied which corresponds to 0.13\\% of \\dihiggs decays. Simple extension of the SM by introducing two new scalars $gg \\rightarrow X \\rightarrow SH$ signature is investigated.\n\n\nThis note is organised as follows: Section~\\ref{sec:dataset} describes the Monte Carlo (MC) samples as well as the \nrecorded dataset used in this analysis. The object definition and event preselection are detailed in Section~\\ref{sec:objselec}. \nThe signal region definitions and the multivariate analysis discriminants are described in Section~\\ref{sec:eventselec}. \nThe reducible background estimates using data-driven method are explained in Section~\\ref{sec:nonpromptbkg}. \n%Section~\\ref{sec:bkgval} shows the data and MC agreement of the prompt lepton background contributions in \nvarious validation regions. \nTheoretical and experimental systematic uncertainties are described in Section~\\ref{sec:systematics}. \nAn overview of the signal regions before the fit can be found in Section~\\ref{sec:signalregion}.\nSection~\\ref{sec:results} describes the expected fit results for each individual channel and the \nexpected and observed fit results for the combination. \nFinally, the conclusions are summarised in Section~\\ref{sec:conclusion}.\n\n\n\n", "meta": {"hexsha": "afc95ca573e1ee4e7108a6b542d72eb751c5483b", "size": 8124, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Tex/Introduction.tex", "max_stars_repo_name": "phreborn/multilep_INT", "max_stars_repo_head_hexsha": "8ac1d430e04f8a97c749645bce28df0d5dc4b0ba", "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/Introduction.tex", "max_issues_repo_name": "phreborn/multilep_INT", "max_issues_repo_head_hexsha": "8ac1d430e04f8a97c749645bce28df0d5dc4b0ba", "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/Introduction.tex", "max_forks_repo_name": "phreborn/multilep_INT", "max_forks_repo_head_hexsha": "8ac1d430e04f8a97c749645bce28df0d5dc4b0ba", "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.0606060606, "max_line_length": 521, "alphanum_fraction": 0.768586903, "num_tokens": 2250, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.1977009496470258}}
{"text": "\n\\section{Introduction}\\label{sec:intro}\n\nFish population (aka \"stock\") assessment models determine the impact of past fishing on the historical and current abundance of the population, evaluate sustainable rates of removals (catch), and project future levels of catch reflecting one or more risk-averse catch rules. These catch rules are codified in regional Fishery Management Plans according to requirements of the Sustainable Fisheries Act. In the U.S., approximately 500 federally managed fish and shellfish populations are managed under approximately 50 Fishery Management Plans. About 200 of these populations are assessed each year, based on a prioritized schedule for their current status. Despite this, many minor species have never been quantitatively assessed. Although the pace is slower than that for weather forecasting, fish stock assessments are operational models for fisheries management.\n\nAssessment models typically assimilate annual catches, data on fish abundance from diverse surveys and fishery sources, and biological information regarding fish body size and proportions at age. A suite of models is available depending on the degree of data availability and unique characteristics of the fish population or its fishery. Where feasible, environmental time series are used as indicators of changes in population or observation processes, especially to improve the accuracy of the projections of abundance and sustainable catch into the future. Such linkages are based principally on correlations given the challenge of conducting field observations on an appropriate scale. The frontier of model development is in the rapid estimation of parameters to include random temporal effects, in the simultaneous modeling of a suite of interacting species, and in the explicit treatment of the spatial distribution of the population.\n\nAssessment models are loosely coupled to other models. For example, an ocean-temperature or circulation model or benthic-habitat map may be directly included in the pre-processing of the fish abundance survey. A time series of a derived ocean factor, like the North Atlantic Oscillation, can be included as an indicator of a change in a population process. Output of a multi-decadal time series of derived fish abundance can be an input to ecosystem and economic models to better understand cumulative impacts and benefits. \n\nStock Synthesis is an age- and size-structured assessment model in the class of models termed integrated analysis models. Stock Synthesis has evolved since its initial inception in order to model a wide range of fish populations and dynamics. The most recent major revision to Stock Synthesis occurred in 2016, when version 3.30 was introduced. This new version of Stock Synthesis required major revisions to the input files relative to earlier versions (see the \\hypertarget{ConvIssues}{Converting Files} section for more information). The acronym for Stock Synthesis has evolved over time with earlier versions being referred to as SS2 (SS v.2.+), SS3 (SS v.3.+), or just simply SS. The current official abbreviation of Stock Synthesis is SS3 for all versions greater than SS v.3.+. \n\n\nSS3 has a population sub-model that simulates a stock's growth, maturity, fecundity, recruitment, movement, and mortality processes, an observation sub-model estimates expected values for various types of data, a statistical sub-model characterizes the data’s goodness of fit and obtains best-fitting parameters with associated variance, and a forecast sub-model projects needed management quantities. SS3 outputs the quantities, with confidence intervals, needed to implement risk-averse fishery control rules. The model is coded in C++ with parameter estimation enabled by automatic differentiation (\\href{http://www.admb-project.org}{admb}). Windows, Linux, and iOS versions are available. Output processing and associated tools are in R, and a graphical interface is in QT. SS is available from NOAA’s VLAB. The rich feature set in SS allows it to be configured for a wide range of situations. SS3 has become the basis for a large fraction of U.S. assessments and many other assessments around the world. \n\nThis manual provides a guide for using SS. The guide contains a description of the input and output files and usage instructions. An overview and technical description of the model itself is in \\citet{methotstock2013}. However, SS3 has continued to evolve and grow since the publication in 2013, with this manual reflecting the most up to date information regarding SS. The model and a graphical user interface are available from the NOAA \\href{https://vlab.noaa.gov/group/stock-synthesis/home}{VLAB}. The VLAB site also provides a user forum for posting questions and for accessing various additional materials. An output processor package, r4ss, in R is available for download from CRAN or \\href{https://github.com/r4ss/r4ss}{GitHub}.\n\nAdditional guidance for new users can be found in the SS3 \\href{https://vlab.noaa.gov/group/stock-synthesis/document-library}{document library} within the NOAA VLAB website. The \"Begin Here - Introduction to Stock Synthesis\" folder located in the Document Library contains step-by-step guidance for running Stock Synthesis. \n\n\\pagebreak\n\t\t\n\\section{File Organization}\\label{FileOrganization}\t\t\n\t\\subsection{Input Files}\n\t\\begin{enumerate}\n\t\t\\item starter.ss: required file containing filenames of the data file and the control file plus other run controls (required).\n\t\t\\item datafile: file containing model dimensions and the data (required)\n\t\t\\item control file: file containing set-up for the parameters (required)\n\t\t\\item forecast.ss: file containing specifications for reference points and forecasts (required) \n\t\t\\item ss.par: previously created parameter file that can be read to overwrite the initial parameter values in the control file (optional)\n\t\t\\item wtatage.ss: file containing empirical input of body weight by fleet and population and empirical fecundity-at-age (optional)\n\t\t\\item runnumber.ss: file containing a single number used as run number in output to CumReport.sso and in the processing of profilevalues.ss (optional)\n\t\t\\item profilevalues.ss: file contain special conditions for batch file processing (optional)\n\t\\end{enumerate}\n\t\n\t\\subsection{Output Files}\n\t\\begin{enumerate}\n\t\t\\item data.ss\\textunderscore new: Contains a user-specified number of datafiles, generated through a parametric bootstrap procedure, and written sequentially to this file.\n\t\t\\item control.ss\\textunderscore new: Updated version of the control file with final parameter values replacing the initial parameter values.\n\t\t\\item starter.ss\\textunderscore new: New version of the starter file with annotations.\n\t\t\\item Forecast.ss\\textunderscore new: New version of the forecast file with annotations.\n\t\t\\item warning.sso: This file contains a list of warnings generated during program execution.\n\t\t\\item echoinput.sso: This file is produced while reading the input files and includes an annotated echo of the input. The sole purpose of this output file is debugging input errors.\n\t\t\\item Report.sso: This file is the primary report file.\n\t\t\\item ss\\_summary.sso: Output file that contains all the likelihood components, parameters, derived quantities, total biomass, summary biomass, and catch. This file offers an abridged version of the report file that is useful for quick model evaluation. This file is only available in SS3 v.3.30.08.03 and greater.\n\t\t\\item CompReport.sso: Observed and expected composition data in a list-based format.\n\t\t\\item Forecast-report.sso: Output of management quantities and for forecasts.\n\t\t\\item CumReport.sso: This file contains a brief version of the run output, output is appended to current content of file so results of several runs can be collected together. This is useful when a batch of runs is being processed.\n\t\t\\item Covar.sso: This file replaces the standard ADMB ss.cor with an output of the parameter and derived quantity correlations in database format.\n\t\t\\item ss.par: This file contains all estimated and fixed parameters from the model run. \n\t\t\\item ss.std, ss.rep, ss.cor etc.: Standard ADMB output files.\n\t\t\\item checkup.sso: Contains details of selectivity parameters and resulting vectors. This is written during the first call of the objective function.\n\t\t\\item Gradient.dat: New for SS3 v.3.30, this file shows parameter gradients at the end of the run.\n\t\t\\item rebuild.dat: Output formatted for direct input to Andre Punt's rebuilding analysis package. Cumulative output is output to REBUILD.SS (useful when doing MCMC or profiles).\n\t\t\\item SIS\\_table.sso: Output formatted for reading into the NMFS Species Information System.\n\t\t\\item Parmtrace.sso: Parameter values at each iteration.\n\t\t\\item posteriors.sso, derived\\_posteriors.sso, posterior\\_vectors.sso: Files associated with MCMC.\n\t\\end{enumerate}\n\n\t\n\t\\subsection{Auxiliary Files}\n\tThese files are additional files (e.g. excel files) which allow for exploration or understanding of specific parameterization which can assist in selecting appropriate starting values. These files are available for download from the Vlab website. \n\t\\begin{enumerate}\n\t\t\\item SS3-OUTPUT.xls: Excel file with macros to read report.sso and display results.\n\t\t\\item SS\\_330\\_Control\\_Setup.xls:\n\t\t\\begin{enumerate}\n\t\t\t\\item Shows how to setup an example control file for SS.\n\t\t\\end{enumerate}\n\t\t\\item SS\\_330\\_Data\\_Input.xls:\n\t\t\\begin{enumerate}\n\t\t\t\\item Shows how to setup an example data input file for SS.\n\t\t\\end{enumerate}\n\t\t\\item SS\\_330\\_Starter\\&Forecast.xls:\n\t\t\\begin{enumerate}\n\t\t\t\\item Shows how to setup an example starter and forecast input files for SS.\n\t\t\\end{enumerate}\n\n\t\\end{enumerate}\n\n\\pagebreak\n\t\t\n\\section{Starting Stock Synthesis}\nSS3 is typically run through the command line interface, although it can also be called from another program, R, the SS-GUI or a script file (such as a DOS batch file). SS3 is compiled for Windows, Mac, and Linux operating systems. The memory requirements depend on the complexity of the model you run, but in general, SS3 will run much slower on computers with inadequate memory. See the Running Stock Synthesis section on page \\pageref{sec:RunningSS} for additional notes on methods of running SS3.\n\nCommunication with the program is through text files. When the program first starts, it reads the file starter.ss, which typically must be located in the same directory from which SS3 is being run. The file starter.ss contains required input information plus references to other required input files, as described in the File Organization section on page \\pageref{FileOrganization}. The names of the control and data files must match the names specified in the starter.ss file. File names, including starter.ss, are case-sensitive on Linux and Mac systems but not on Windows. The echoinput.sso file outputs how the executable read each input file and can be used for troubleshooting when trying to setup a model correctly. Output from SS3 consists of text files containing specific keywords. Output processing programs, such as the SS3 GUI, Excel, or R can search for these keywords and parse the specific information located below that keyword in the text file.\n\n\\pagebreak", "meta": {"hexsha": "212fa1be2e5ee81e24502950c7b152e0995163ac", "size": 11273, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "1_4sections.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": "1_4sections.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": "1_4sections.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": 132.6235294118, "max_line_length": 1015, "alphanum_fraction": 0.8013838375, "num_tokens": 2416, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.19770094964702578}}
{"text": " \\documentclass [12pt]{article} \n\n\\usepackage {amsmath}\n\\usepackage {amsthm}\n\\usepackage {amssymb}\n\\usepackage {graphicx} \n\\usepackage {float}\n\\usepackage {multirow}\n\\usepackage {xcolor}\n\\usepackage [ruled,vlined,commentsnumbered,titlenotnumbered]{algorithm2e} \\usepackage {array} \n\\usepackage {booktabs} \n\\usepackage {url} \n\\usepackage {parskip} \n\\usepackage [margin=1in]{geometry} \n\\usepackage [T1]{fontenc} \n\\usepackage {cmbright} \n\\usepackage [many]{tcolorbox} \n\\usepackage [colorlinks = true,\n linkcolor = blue,\n urlcolor = blue,\n citecolor = blue,\n anchorcolor = blue]{hyperref} \n\\usepackage {enumitem} \n\\usepackage {xparse} \n\\usepackage {verbatim}\n\\usepackage{algpseudocode}\n\\usepackage{listings}\n\\usepackage{xcolor}\n\\lstset { %\n language=C++,\n backgroundcolor=\\color{black!5}, % set backgroundcolor\n basicstyle=\\footnotesize,% basic font setting\n}\n\\newtheorem{theorem}{Theorem}\n\\newtheorem{remark}{Remark}\n\\newtheorem{lemma}[theorem]{Lemma}\n\\theoremstyle{definition}\n\\newtheorem{definition}{Definition}[section]\n\\newtheorem{claim}{Claim}\n\n\n\n\n\n\n\\DeclareTColorBox {Solution}{}{breakable, title={Solution}} \\DeclareTColorBox {Solution*}{}{breakable, title={Solution (provided)}} \\DeclareTColorBox {Instruction}{}{boxrule=0pt, boxsep=0pt, left=0.5em, right=0.5em, top=0.5em, bottom=0.5em, arc=0pt, toprule=1pt, bottomrule=1pt} \\DeclareDocumentCommand {\\Expecting }{+m}{\\textbf {[We are expecting:} #1\\textbf {]}} \\DeclareDocumentCommand {\\Points }{m}{\\textbf {(#1 pt.)}} \n\n\\begin {document} \n\n\\vspace {1em} \n\\begin {Instruction} \nAdapted From Virginia Williams' lecture notes.\n\\end {Instruction} \n\n{\\LARGE \\textbf {COMP 285 (NC A\\&T, Spr `22)}\\hfill \\textbf {Lecture 27} } \n\n\\begin{centering}\n\\section*{Dynamic Programmig V - 0/1 Knapsack and Maximal Independent Set}\n\\end{centering}\n\n\\section{The Knapsack Problem}\n \nThis is a classic problem, defined as the following:\n\nWe have $n$ items, each with a value and a positive weight. The $i$-th item has weight $w_i$ and value $v_i$. We have a knapsack that holds a maximum weight of $W$. Which items do we put in our knapsack to maximize the value of the items in our knapsack? For example, let’s say that $W = 10$; that is, the knapsack holds a weight of at most 10. Also suppose that we have four items, with weight and value:\n\n\\begin{table}[h!]\n\\centering\n\\begin{tabular}{c|c|c}\nItem & Weight & Value \\\\\n\\hline\nA & 6 & 25 \\\\\nB & 3 & 13 \\\\\nC & 4 & 15 \\\\\nD & 2 & 8\n\\end{tabular}\n\\end{table}\n\nWe will talk about two variations of this problem, one where you have infinite copies of each item (commonly known as Unbounded Knapsack), and one where you have only one of each item (commonly known as 0-1 Knapsack). \n\nWhat are some useful subproblems? Perhaps it’s having knapsacks of smaller capacities, or maybe it’s having fewer items to choose from. In fact, both of these ideas for subproblems are useful. As we saw last lecture, the first idea is useful for the Unbounded Knapsack problem, and a combination of the two ideas is useful for the 0-1 Knapsack problem.\n\n\\subsection{The 0-1 Knapsack Problem}\n\nWe consider what happens when we can take at most one of each item. Going back to the initial example, we would pick item $A$ and item $C$, having a total weight of $10$ and a total value of $40$.\n\nThe subproblems that we need must keep track of the knapsack size as well as which items are allowed to be used in the knapsack. Because we need to keep track of more information in our state, we add another parameter to the recurrence (and therefore, another dimension to the DP table). Let $K(x, j)$ be the maximum value that we can get with a knapsack of capacity $x$ considering only items at indices from $1, \\cdots , j$. Consider the optimal solution for $K(x, j)$. There are two cases: \n\n\\begin{enumerate}\n \\item Item $j$ is used in $K(x, j)$. Then, the remaining items that we choose to put in the knapsack must be the optimum solution for $K(x - w_j , j - 1)$. In this case, $K(x, j) = K(x - w_j , j - 1) + v_j$ .\n \\item Item $j$ is not used in $K(x, j)$. Then, $K(x, j)$ is the optimum solution for K(x, j - 1). In this case, $K(x, j) = K(x, j - 1)$.\n\\end{enumerate}\n\nSo, our recurrence relation is: $K(x, j) = \\max\\{K(x -w_j , j -1) +v_j , K(x, j -1)\\}$. Now, we’re done: we simply calculate each entry up to $K(W, n)$, which gives us our final answer. Note that this also runs in $O(nW)$ time despite the additional dimension in the DP table. This is because at each entry of the DP table, we do $O(1)$ work.\n\n\\begin{algorithm}\n\\caption{ZeroOneKnapsack(W, n, w, v)}\n\\label{alg:zerooneknapsack}\n\\begin{algorithmic}\n\\State \\For{$j = 1, \\cdots, n$}{\n $K[0,j] \\gets 0$\n}\n\\State \\For{$x = 0, \\cdots, W$}{\n $K[x, 0] \\gets 0$\n}\n\\State \\For{$x = 1, \\cdots, W$} {\n \\State \\For{$j = 1, \\cdots, n$} {\n \\State $K[x, j] \\gets K[x, j-1]$\n \\State \\If {$w_j <= x$} {\n $K[x, j] = \\max\\{K[x - w_j, j-1] + v_j, K[x, j] \\}$\n }\n }\n}\n\\State \\Return $K[W, n]$\n\\end{algorithmic}\n\\end{algorithm}\n\n\n\\section{The Independent Set Problem}\n\nThis problem is as follows: \n\nSay that we have an undirected graph $G = (V, E)$. We call a subset $S \\subseteq V$ of vertices ``independent'' if there are no edges between vertices in $S$. Let vertex $i$ have weight $w_i$ , and denote $w(S)$ as the sum of weights of vertices in $S$. Given $G$, find an independent set of maximum weight $arg\\max_{S\\subseteq V} w(S)$.\n\nActually, this problem is NP-hard for a general graph $G$. However, if our graph is a tree, then we can solve this problem in linear time. In the following figure, the maximum weight independent set is highlighted in blue.\n\n\\begin{remark}\nDynamic programming is especially useful to keep in mind when you are solving a problem that involves trees. The tree structure often lends itself to dynamic programming solutions.\n\\end{remark}\n\n\\begin{figure}[h!]\n\\centering\n\\includegraphics[scale=0.5]{max_is.png}\n\\end{figure}\n\nAs usual, the key question to ask is, ``What should our subproblem(s) be?'' Intuitively, if the problem has to do with trees, then subtrees often play an important role in identifying our subproblems. Let's pick any vertex $r$ and designate it as the root. Denoting the subtree rooted at $u$ as $T_u$, we define $A(u)$ to be the weight of the maximum weight independent set in $T_u$. How can we express $A(u)$ recursively? Letting $S_u$ be the maximum weight independent set of $T_u$, there are two cases:\n\n\\begin{enumerate}\n \\item If $u \\notin S_u$, then $A(u) = \\sum_{v} A(v )$ for all children $v$ of $u$.\n \\item If $u \\in S_u$, then $A(u) = w_u + \\sum_{v} A(v )$ for all grandchildren $v$ of $u$. \n\\end{enumerate}\n\nTo avoid solving the subproblem for trees rooted at grandchildren, we introduce $B(u)$ as the weight of the maximum weight independent set in $T_u \\setminus \\{u\\}$. That is, $B(u) = \\sum_{v} A(v )$ for all children $v$ of $u$. Equivalently, we have the following cases: \n\n\\begin{enumerate}\n \\item If $u \\notin S_u$, then $A(u) = \\sum_{v} A(v )$ for all children $v$ of $u$.\n \\item If $u \\in S_u$, then $A(u) = w_u + \\sum_{v} B(v )$ for all children $v$ of $u$. \n\\end{enumerate}\n\nSo, we can calculate the weight of the maximum weight independent set:\n$$\nA(u) = \\max\\left\\{w(u) + \\sum_{v \\in Children(u)} B(u), \\sum_{v \\in Children(u)} A(v) \\right\\}\n$$\n\nTo create an algorithm out of this recurrence, we can compute the $A(u)$ and $B(u)$ values in a bottom-up manner (a post-order traversal on the tree), arriving at the answer, $A(r)$. This\ntakes $O(|V|)$ time.\n\n\n\n\n\\begin{algorithm}\n\\caption{MaxWeightIndependentSet(G)}\n\\label{alg:MaxWeightIndependentSet}\n\\begin{algorithmic}\n\\State \\texttt{// G is a tree}\n\\State $r \\gets \\text{ArbitraryVertex}(G)$\n\\State $T \\gets \\text{RootTreeAt}(r)$\n\\Procedure{SolveSubtreeAt}{$u$}\n \\State \\eIf{Children$(T, u) = \\emptyset$} {\n \\State $A(u) \\gets w_u$\n \\State $B(u) \\gets 0$\n }{\n \\State \\For{$v \\in \\text{Children}(u)$} {\n \\State \\texttt{SolveSubTreeAt}(v)\n }\n \\State $A(u) \\gets \\max\\left\\{\\sum_{v \\in \\text{Children}(u)} A(v), w_u + \\sum_{v \\in \\text{Children}(u)} B(v) \\right\\}$\n \\State $B(u) \\gets \\sum_{v \\in \\text{Children}(u)} A(v)$\n }\n\\EndProcedure\n\\State \\texttt{SolveSubtreeAt}$(r)$\n\\State \\Return $A(r)$\n\\end{algorithmic}\n\\end{algorithm}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\\end{document}\n", "meta": {"hexsha": "7e9bc22570af6e878c5bf4734545ff00133a34ce", "size": 8364, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "assets/lectures/lecture27.tex", "max_stars_repo_name": "facebookEIR/algorithms-course", "max_stars_repo_head_hexsha": "f0893b43aaf3b321eb134c82512bd7b9271fdea6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-16T02:47:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-16T02:47:46.000Z", "max_issues_repo_path": "assets/lectures/lecture27.tex", "max_issues_repo_name": "facebookEIR/algorithms-course", "max_issues_repo_head_hexsha": "f0893b43aaf3b321eb134c82512bd7b9271fdea6", "max_issues_repo_licenses": ["MIT"], "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/lectures/lecture27.tex", "max_forks_repo_name": "facebookEIR/algorithms-course", "max_forks_repo_head_hexsha": "f0893b43aaf3b321eb134c82512bd7b9271fdea6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2022-01-20T21:52:09.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-21T03:00:16.000Z", "avg_line_length": 40.8, "max_line_length": 505, "alphanum_fraction": 0.6863940698, "num_tokens": 2636, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.480478678047907, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.19753000697979806}}
{"text": "%!TEX root = thesis.tex\n\n\\chapter{Timing Constraints}\n\\label{chapter-TimingConstraints}\n\n\\section{AUTOSAR Timing Extensions}\n\tAUTOSAR is a development partnership in the automotive industry. The main goal is to define a standardized interface and increase the interoperability, exchangeability and re-usability of parts and therefore simplifying development and production.\\\\ %Three different layers are defined in the specification. \\emph{Basic Software} is an abstraction layer from components, like network or diagnostic protocols, or operating systems. \\emph{AUTOSAR-Software} defines the methods, how applications have to be build. For Basic Software and AUTOSAR Software, there are definitions for standardized Interfaces to enable the communication via the \\emph{AUTOSAR Runtime Environment}. It works as middleware, in which the \\emph{virtual function bus} is defined ~\\cite{Virtual_Functional_Bus}.\n\tThe AUTOSAR Timing Extension are describing timing constraints for actions and reactions of components. The constraints are defined via \\emph{events}, which consist of a time value and, if needed, a data value of an arbitrary type. To describe the logical relationship between groups of events, \\emph{event chains} are defined, consisting of \\emph{stimulus} and \\emph{response} events. The \\emph{response} event is understood as the answer to the \\emph{stimulus} event.\\\\\n\tThe AUTOSAR Release 4.4.0 (\\cite{TIMEX}) is used for this thesis. There are 12 timing constraints defined in this version of the AUTOSAR Timing Extensions.\n\t\\begin{enumerate}\n\t\t\\item\n\t\t\tThe subset of 5 \\textbf{EventTriggeringConstraints} is describing, at which points in time specific events may occur.\n\t\t\t\\begin{enumerate}[1]\n\t\t\t\t\\item\n\t\t\t\t\tThe \\textbf{PeriodicEventTriggering} defines repetitions of events with the same time distance and offers the possibility to set an allowed deviation from this pattern. Additionally, the minimal distance between two subsequent events can be defined.\n\t\t\t\t\\item\n\t\t\t\t\tThe \\textbf{SporadicEventTriggering} specifies sporadic event occurrences by defining the minimal and maximal distance between subsequent events. Optionally, periodic repetitions and allowed deviations from the period can be described.\n\t\t\t\t\\item\n\t\t\t\t\tWith the \\textbf{ConcreteEventTriggering}, offsets between a set of subsequent events in a time interval can be described. These intervals may not overlap, and periodic repetitions of them can be defined optionally.\n\t\t\t\t\\item\n\t\t\t\t\tThe \\textbf{BurstPatternEventTriggering} describes non-overlapping event clusters with a minimal and maximal number of events. Optionally periodic repetitions of these clusters can also be described.\n\t\t\t\t\\item\n\t\t\t\t\tThe \\textbf{ArbitraryEventTriggering} defines the distance between subsequent events by defining \\emph{ConfidenceIntervals}, which describe the probability in which time interval the following event will occur.\n\t\t\t\\end{enumerate}\n\t\t\\item\n\t\t\tThe \\textbf{LatencyTimingConstraint} specifies the minimal, nominal and maximal time distance between the stimulus and response events of an event chain.\n\t\t\\item\n\t\t\tThe \\textbf{AgeConstraint} is a simpler form of the \\emph{LatencyTimingConstraint} by defining the minimal and maximal age an event may have at the point of time when it is processed.\n\t\t\\item\n\t\t\tThe \\textbf{SynchronizationTimingConstraint} is used to describe events of different kinds that occur synchronized in a time interval of a specific length.\n\t\t\\item\n\t\t\tThe \\textbf{SynchronizationPointConstraint} defines two sets of executables and events. Every element of the first set must have finished or occurred before the first element of the second set may start or occur.\n\t\t\\item\n\t\t\tThe \\textbf{OffsetTimingConstraint} specifies the minimal and maximal time distance between the corresponding \\emph{source} and \\emph{target} events.\n\t\t\\item\n\t\t\tThe \\textbf{ExecutionOrderConstraint} defines the order in which a list of executables must start and finish.\n\t\t\\item\n\t\t\tThe \\textbf{ExecutionTimeConstraint} defines the minimal and maximal runtime of an executable, including or excluding the runtime of external functions and interruptions.\n\t\\end{enumerate}\n\n\tIn this simplified form, some constraints are redundant. The semantic differences will be shown in section~\\ref{comparisonConstraints}.\n\n\tProblematic with the AUTOSAR Timing Extensions is that the constraints are not formally defined and have room left for different interpretations. As an example, the \\emph{BurstPatternEventTriggering} will be analyzed in the following. This constraint describes events clusters, with events that occur with short time distances, with larger time distances between the clusters. These following attributes define how the events may occur:\n\t\\begin{itemize}\n\t\t\\item\n\t\t\t\\textbf{\\emph{maxNumberOfOccurrences}} (positive integer)\\\\\n\t\t\tMaximal number of events per burst\n\t\t\\item\n\t\t\t\\textbf{\\emph{minNumberOfOccurrences}} (positive integer)\\\\\n\t\t\tMinimal number of events per burst (optional)\n\t\t\\item\n\t\t\t\\textbf{\\emph{minimumInterArrivalTime}} (time value)\\\\\n\t\t\tMinimal distance between subsequent events\n\t\t\\item\n\t\t\t\\textbf{\\emph{patternLength}} (time value)\\\\\n\t\t\tLength of each burst\n\t\t\\item\n\t\t\t\\textbf{\\emph{patternPeriod}} (time value)\\\\\n\t\t\tTime distance between the starting points of subsequent burst(optional)\n\t\t\\item\n\t\t\t\\textbf{\\emph{patternJitter}} (time value)\\\\\n\t\t\tMaximal allowed deviation from the periodic pattern\t(optional)\n\t\\end{itemize}\n\nAs example, we set:\n\\begin{itemize}\n\t\\item\n\t$maxNumberOfOccurrences = 3$\n\t\\item\n\t$minNumberOfOccurrences = 1$\n\t\\item\n\t$minimumInterArrivalTime = 1$\n\t\\item\n\t$patternLength = 3$\n\t\\item\n\t$patternPeriod = 3.5$\n\t\\item\n\t$patternJitter = 1.5$\n\\end{itemize}\n\n\\begin{figure}\n\t\\centering\n\t\\begin{tikzpicture}[thick, xscale=0.9]\n\t% time axis\n\t\\foreach \\x in {0,...,15}\n\t\\draw (\\x,-4) -- (\\x,-4.2) node[anchor=north] {\\x};\n\t\\draw[->] (0, -4.1) -- (15.4, -4.1);\n\t\\node at(15, -5) {time};\n\t\n\t% bursts\n\t\\node[gray] at (0, -2){Bursts};\n\t\\draw [fill=lightgray, lightgray] (1, -2) rectangle (4,-2.5);\n\t\\draw [fill=lightgray, lightgray] (6, -2) rectangle (9,-2.5);\n\t\\draw [fill=lightgray, lightgray] (11, -2) rectangle (14,-2.5);\n%\t\\draw [fill=lightgray, lightgray] (16, -2) rectangle (19,-2.5);\n\t% events\n\t\\node at (0, -2.4){Events};\n\t%\\node at (0, -2.15){events};\n\t\\foreach \\x in {1, 6, 11}\n\t{\n\t\t% events\n\t\t\\draw[-] (\\x, -2) -- (\\x, -2.5);\n\t\t\\draw[-] (\\x+1, -2) -- (\\x+1, -2.5);\n\t\t\\draw[-] (\\x+2, -2) -- (\\x+2, -2.5);\n\t\t% periods\n\t\t\\draw[->, green] (\\x, -3) -- (\\x+3.5, -3);\n\t\t\\node[green] at (\\x+1.75, -3.3){period};\n\t\t%jitters\n\t\t\\draw[->, blue] (\\x+3.5,-3.4) -- (\\x+5, -3.4);\n\t\t\\node[blue] at (\\x+4.25, -3.7) {jitter};\n\t}\n\t\\end{tikzpicture}\n\t\\caption{BurstPatternEventTriggering \\textit{patternPeriod} and \\textit{patternJitter} \\textbf{accumulating}}\n\t\\label{fig:BurstPatternEventTriggering1}\n\\end{figure}\n\\begin{figure}\n\t\\centering\n\t\\begin{tikzpicture}[thick, xscale=0.9]\n\t% time axis\n\t\\foreach \\x in {0,...,15}\n\t\\draw (\\x,-4.2) -- (\\x,-4.4) node[anchor=north] {\\x};\n\t\\draw[->] (0, -4.3) -- (15.4, -4.3);\n\t\\node at(15, -5.2) {time};\n\t\n\t% bursts\n\t\\node[gray] at (0, -2){Bursts};\n\t\\draw [fill=lightgray, lightgray] (1, -2) rectangle (4,-2.5);\n\t\\node at (0, -2.4){Events};\n\t\n\t%period 1\n\t\\draw[->, green] (1, -3) -- (4.5, -3);\n\t\\node[green] at (2.75, -3.3){period};\n\t\n\t% jitter 1\n\t\\draw[->, blue] (4.5,-3.6) -- (6, -3.6);\n\t\\node[blue] at (5.25, -3.9) {jitter};\n\t\n\t\\foreach \\y in {0, 1, 2}\n\t\\draw[-] (1+\\y, -2) -- (1+\\y, -2.5);\n\t\\foreach \\x in {4.5, 8, 11.5}{\n\t\t%bursts\t\n\t\t\\draw [fill=lightgray, lightgray] (\\x+1.5, -2) rectangle (\\x+4.5,-2.5);\n\t\t% events\n\t\t\\foreach \\y in {0, 1, 2}\n\t\t\t\\draw[-] (\\x+\\y+1.5, -2) -- (\\x+\\y+1.5, -2.5);\n\t\t\t\n\t}\n\t\\foreach \\x in {4.5, 8, 11.5}\n\t{\n\t\t% periods\n\t\t\\draw[->, green] (\\x, -3) -- (\\x+3.5, -3);\n\t\t\\node[green] at (\\x+1.75, -3.3){period};\n\t\t% jitters\n\t\t\\draw[->, blue] (\\x+3.5,-3.6) -- (\\x+5, -3.6);\n\t\t\\node[blue] at (\\x+4.25, -3.9) {jitter};\n\t\t\n\t}\n\n\t\n\t\\end{tikzpicture}\n\t\\caption{BurstPatternEventTriggering \\textit{patternPeriod} and \\textit{patternJitter} \\textbf{non-accumulating}}\n\t\\label{fig:BurstPatternEventTriggering2}\n\\end{figure}\n\nThe combination of $patternPeriod$ and $patternJitter$ can be interpreted in an accumulating way, as seen in figure~\\ref{fig:BurstPatternEventTriggering1}, or in a non-accumulating way, as seen in figure~\\ref{fig:BurstPatternEventTriggering2}. In the accumulating interpretation, the reference for the periodic occurrences is only the start point of the previous burst. In the non-accumulating way, there is a global reference point for the periodic repetitions.\n\nWith the definition of $patternPeriod$ (''time distance between the beginnings of subsequent repetitions of the given burst pattern''\\cite{TIMEX}), you would think that the accumulating variant is meant. Against that, the period attribute in the \\textit{PeriodicEventTriggering} constraint is defined as ''distance between subsequent occurrences of the event''\\cite{TIMEX} in the text. Hence it is also understandable the accumulating way. However, there is the formal definition\n\n\\begin{math}\n\\exists t_{reference}\\forall t_n: t_{reference}+(n+1)*period\\leq t_n\\leq t_{reference}+(n-1)*period+jitter,\n\\end{math}\n\nwhere $t_n$ is the time of the $n$-th event and $t_{reference}$ is a reference point from which the periodic pattern starts, so the $PeriodicEventTriggering$ constraint is meant to be understood in the non-accumulating way. It remains unclear in which way the $BurstPatternEventTriggering$ is meant to be understood.\n\nAnother problem with the AUTOSAR Timing Extensions is that they were made for design purposes. Monitoring them can be difficult, as a monitor may need time and memory resources, which continuously grow with every input event. This makes online monitoring unsuitable in nearly all scenarios (more on monitorability in chapter~\\ref{chapter-monitorability}). As an example, we will use the \\textit{BurstPatternEventTriggering} again. This time we use the attributes\n\\begin{itemize}\n\t\\item\n\t$maxNumberOfOccurrences = INT\\_MAX$\\textcolor{gray}{or any significant large number}\n\t\\item\n\t$minNumberOfOccurrences = 1$\n\t\\item\n\t$minimumInterArrivalTime = 0$\n\t\\item\n\t$patternLength = 3$\n\t\\item\n\t\\textcolor{gray}{$patternPeriod$} \\textcolor{gray}{unused}\n\t\\item\n\t\\textcolor{gray}{$patternJitter$} \\textcolor{gray}{unused}\n\\end{itemize}\n\nFigure~\\ref{fig:BurstPatternEventTriggering3} shows the application of the \\emph{BurstPatternEventTriggering} constraint with the given parameters on a stream with events at the timestamps 3, 3.5, 4, 4.5. The development of possible burst clusters with ongoing time is visualized. The gray bars show the range in which the burst cluster can lay. The black lines show where they definitely are. In timestamp 3, with only one event so far, only one burst has to be considered and it can lay between timestamp 0 and 6. The only limitation is that it must include timestamp 3 with the event at that point. In Timestamp 3.5, there are two events (at 3 and 3.5) so far, and there are two possibilities for burst placements. The first possibility is with only one burst with both events in it, and the second possibility, where the events are in different bursts. The third graphic shows the trace in timestamp 4 with three different events so far (3, 3.5, 4) and three different possibilities for burst placements to consider. One possible burst contains all three events, the second possibility has one burst with the event at timestamp 3 and one burst with the events at 3.5 and 4 and the third possibility has one Burst with the events at 3 and 3.5 and one burst with the event at 4. The possible bursts in graphic 4 are analog to the third graphic, one possibility with one burst containing all 4 events and 3 possibilities with the first burst containing the first event, the first and second event or the first, the second and the third event and the second burst containing the remaining events. Because the minimal distance between subsequent events is not specified, an arbitrarily large number of events can be placed in any interval with the length $patternLenth$.\\\\\nIn this example, we see that it is possible to create an unlimited number of possibilities for burst placements within one burst length when the \\textit{minimumInterArrivalTime}-attribute is 0, which results in infeasible resource consumption because unlimited memory and time is needed to check the constraint in following events. Therefore, online monitoring of this constraint is unsuitable in most cases.\n\n\\begin{figure}\n\t\\centering\n\t\\begin{tikzpicture}[thick]\n\t%time axis\n\t\\foreach \\x in {0,...,10}\n\t{\n\t\t\\draw (\\x,0) -- (\\x,-0.2);\n\t\t\\node at (0+\\x, 0.2) {\\x};\n\t}\n\t\\foreach \\x in {0,...,9}\n\t\\draw (\\x+0.5,0) -- (\\x+0.5,-0.1);\n\t\\draw[->] (0, -0.1) -- (10.4, -0.1);\n\t\\node at(10, -0.4) {time};\n\t\n\t\\node[red] at(-1, -0.45) {timestamp};\n\t%watched time\n\t\\draw[->, red] (3, -0.7)--(3, -0.3);\n\t\n\t\\node at (-1, -1.5) {Events};\n\t\\draw[-] (3, -1.25) -- (3, -1.75);\n\t\n\t\\node at (-1, -2.2) {Possible};\n\t\\node at (-1, -2.6) {Burst};\n\t\\node at (-1, -3) {ranges};\n\t\n\t%Burst range\n\t\\draw[|-|, lightgray] (0, -2.4) -- (6, -2.4);\n\t\\end{tikzpicture}\n\t\n\t\\begin{tikzpicture}[thick]\n\t%time axis\n\t\\foreach \\x in {0,...,10}\n\t{\n\t\t\\draw (\\x,0) -- (\\x,-0.2);\n\t\t\\node at (0+\\x, 0.2) {\\x};\n\t}\n\t\\foreach \\x in {0,...,9}\n\t\\draw (\\x+0.5,0) -- (\\x+0.5,-0.1);\n\t\\draw[->] (0, -0.1) -- (10.4, -0.1);\n\t\\node at(10, -0.4) {time};\n\t\n\t\\node[red] at(-1, -0.45) {timestamp};\n\t%watched time\n\t\\draw[->, red] (3.5, -0.7)--(3.5, -0.3);\n\t\n\t\\node at (-1, -1.5) {Events};\n\t\\draw[-] (3, -1.25) -- (3, -1.75);\n\t\\draw[-] (3.5, -1.25) -- (3.5, -1.75);\n\t\n\t\\node at (-1, -2.2) {Possible};\n\t\\node at (-1, -2.6) {Burst};\n\t\\node at (-1, -3) {ranges};\n\t\n\t%Burst range 1\n\t\\draw[|-|, lightgray] (0.5, -2.2) -- (6, -2.2);\n\t\\draw[-] (3, -2.2) -- (3.5, -2.2);\n\t% Burst range 2\n\t\\draw[|-|, lightgray] (0, -2.6) -- (3.5, -2.6);\n\t\\draw[-] (0.5, -2.6) -- (3, -2.6);\n\t\\draw[|-|, lightgray] (3, -2.7) -- (6.5, -2.7);\n\t\\draw[-] (3.5, -2.7) -- (6, -2.7);\n\t\\end{tikzpicture}\n\t\\begin{tikzpicture}[thick]\n\t%time axis\n\t\\foreach \\x in {0,...,10}\n\t{\n\t\t\\draw (\\x,0) -- (\\x,-0.2);\n\t\t\\node at (0+\\x, 0.2) {\\x};\n\t}\n\t\\foreach \\x in {0,...,9}\n\t\\draw (\\x+0.5,0) -- (\\x+0.5,-0.1);\n\t\\draw[->] (0, -0.1) -- (10.4, -0.1);\n\t\\node at(10, -0.4) {time};\n\t\n\t\\node[red] at(-1, -0.45) {timestamp};\n\t%watched time\n\t\\draw[->, red] (4, -0.7)--(4, -0.3);\n\t\n\t\\node at (-1, -1.5) {Events};\n\t\\draw[-] (3, -1.25) -- (3, -1.75);\n\t\\draw[-] (3.5, -1.25) -- (3.5, -1.75);\n\t\\draw[-] (4, -1.25) -- (4, -1.75);\n\t\n\t\\node at (-1, -2.2) {Possible};\n\t\\node at (-1, -2.6) {Burst};\n\t\\node at (-1, -3) {ranges};\n\t\n\t%Burst ranges poss. 1\n\t\\draw[|-|, lightgray] (1, -2.2) -- (6, -2.2);\n\t\\draw[-] (3, -2.2) -- (4, -2.2);\n\t% Burst ranges poss. 3 2.6,2.7\n\t\\draw[|-|, lightgray] (0, -2.6) -- (3.5, -2.6);\n\t\\draw[-] (0.5, -2.6) -- (3, -2.6);\n\t\\draw[|-|, lightgray] (3, -2.7) -- (6.5, -2.7);\n\t\\draw[-] (3.5, -2.7) -- (6, -2.7);\n\t% Burst ranges poss. 2\n\t\\draw[|-|, lightgray] (0.5, -3.1) -- (4, -3.1);\n\t\\draw[-] (1, -3.1) -- (3.5, -3.1);\n\t\\draw[|-|, lightgray] (3.5, -3.2) -- (7, -3.2);\n\t\\draw[-] (4, -3.2) -- (6.5, -3.2);\n\t\\end{tikzpicture}\n\t\\begin{tikzpicture}[thick]\n\t%time axis\n\t\\foreach \\x in {0,...,10}\n\t{\n\t\t\\draw (\\x,0) -- (\\x,-0.2);\n\t\t\\node at (0+\\x, 0.2) {\\x};\n\t}\n\t\\foreach \\x in {0,...,9}\n\t\\draw (\\x+0.5,0) -- (\\x+0.5,-0.1);\n\t\\draw[->] (0, -0.1) -- (10.4, -0.1);\n\t\\node at(10, -0.4) {time};\n\t\n\t\\node[red] at(-1, -0.45) {timestamp};\n\t%watched time\n\t\\draw[->, red] (4.5, -0.7)--(4.5, -0.3);\n\t\n\t\\node at (-1, -1.5) {Events};\n\t\\draw[-] (3, -1.25) -- (3, -1.75);\n\t\\draw[-] (3.5, -1.25) -- (3.5, -1.75);\n\t\\draw[-] (4, -1.25) -- (4, -1.75);\n\t\\draw[-] (4.5, -1.25) -- (4.5, -1.75);\n\t\n\t\\node at (-1, -2.5) {Possible};\n\t\\node at (-1, -2.9) {Burst};\n\t\\node at (-1, -3.3) {ranges};\n\t\n\t%Burst ranges poss. 1\n\t\\draw[|-|, lightgray] (1.5, -2.2) -- (6, -2.2);\n\t\\draw[-] (3, -2.2) -- (4.5, -2.2);\n\t% Burst ranges poss. 2\n\t\\draw[|-|, lightgray] (0, -2.6) -- (3.5, -2.6);\n\t\\draw[-] (0.5, -2.6) -- (3, -2.6);\n\t\\draw[|-|, lightgray] (3, -2.7) -- (6.5, -2.7);\n\t\\draw[-] (3.5, -2.7) -- (6, -2.7);\n\t% Burst ranges poss. 3\n\t\\draw[|-|, lightgray] (0.5, -3.1) -- (4, -3.1);\n\t\\draw[-] (1, -3.1) -- (3.5, -3.1);\n\t\\draw[|-|, lightgray] (3.5, -3.2) -- (7, -3.2);\n\t\\draw[-] (4, -3.2) -- (6.5, -3.2);\n\t% Burst ranges poss. 4\n\t\\draw[|-|, lightgray] (1, -3.6) -- (4.5, -3.6);\n\t\\draw[-] (1, -3.6) -- (4, -3.6);\n\t\\draw[|-|, lightgray] (4, -3.7) -- (7.5, -3.7);\n\t\\draw[-] (4.5, -3.7) -- (7, -3.7);\n\t\\end{tikzpicture}\n\t\\caption{BurstPatternEventTriggering Possible bursts, \\textcolor{red}{$\\uparrow$} shows the current time}\n\t\\label{fig:BurstPatternEventTriggering3}\n\t\n%TODO weiteres Beispiel für unsaubere Definition von AUTOSAR-> falsches Beispiel für file:///home/hendrik/Documents/Uni/Semester8/Quellen%20Bachelorarbeit/AutoSar%20TimEx/MethodologyAndTemplates/AUTOSAR_TPS_TimingExtensions.pdf\n\\end{figure}\n\n\\newpage\n\n\\section{Timing Augmented Description Language\\cite{TIMMO2USE}}\n\tAs timing extension to EAST-ADL(\\textbf{E}lectronics \\textbf{A}rchitecture and \\textbf{S}oftware \\textbf{T}echnology-\\\\ \\textbf{A}rchitecture \\textbf{D}escription \\textbf{L}anguage), the TIMMO (\\textbf{Tim}ing \\textbf{Mo}del) project, and its successor, TIMMO-2-USE, were initiated. A part of this project was the \\textbf{T}iming \\textbf{A}ugmented \\textbf{D}escription \\textbf{L}anguage V2 (TADL2), were created. TADL2 has similar goals as the AUTOSAR Timing Extensions, but the definitions are written in a more formalized fashion. While the definitions of the AUTOSAR Timing Extensions are only textually described often, the TADL2 definitions are defined more formally. They offer a formal definition of each constraint in the timing constraint logic TiCL \\cite{TIMMO2USE}. EAST-ADL is much less used in the automotive industry, but the EAST-ADL Timing Constraints are partly compatible with the AUTOSAR Timing Extensions, as they are sub- or supersets of each other. Many of the AUTOSAR Timing Extensions can be defined via a combination of TADL2 Constraints, as explained in section~\\ref{comparisonConstraints}.\\\\\n\tThe timing constraints are defined on events or event chains, similar to the AUTOSAR Timing Extensions. In TADL2, all events of an event chain have a color attribute, which shows the logical connection of associated events. This attribute is defined as an abstract and possibly infinite datatype. The only restriction is that an equality test on these color values must be defined. TADL2 offers 18 timing constraints, which will be briefly explained in the following.\n\t\\begin{itemize}\n\t\t\\item\n\t\t\tThe \\textbf{StrongDelayConstraint} defines the minimal and maximal time distance of the events from two event sets (\\emph{source} and \\emph{target}).\n\t\t\\item\n\t\t\tThe \\textbf{DelayConstraint} is a less strict variant of the \\textbf{StrongDelayConstraint} because it allows additional events in the \\emph{target} events.\n\t\t\\item\n\t\t\tThe \\textbf{RepeatConstraint}, \\textbf{RepetitionConstraint}, \\textbf{PeriodicConstraint},\\\\ \\textbf{SporadicConstraint} and \\textbf{ArbitraryConstraint} describe the time distance between subsequent events, whereby they have small semantic differences. An exact distinction between these constraints will be given in section~\\ref{tadl2Constraints}.\n\t\t\\item\n\t\t\tThe \\textbf{SynchronizationConstraint} and \\textbf{StrongSynchronizationConstraint} define\\\\groups of event sets, whose events occur in common time intervals. The SynchronizationConstraint allows more than one event of each group per interval, while the StrongSynchronizationConstraint does not.\n\t\t\\item\n\t\t\tThe \\textbf{ExecutionTimeConstraint} sets a minimum and a maximum for the runtime of a task, not counting interruptions in the execution.\n\t\t\\item\n\t\t\tThe \\textbf{OrderConstraint} defines that the $n^{th}$ event of one event set must occur before or at the $n^{th}$ event of a second event set.\n\t\t\\item\n\t\t\tThe \\textbf{ComparisonConstraint} is used to describe ordering relations of timestamps.\n\t\t\\item\n\t\t\tThe \\textbf{PatternConstraint} defines the time distance between periodic points in time and several events.\n\t\t\\item\n\t\t\tThe \\textbf{BurstConstraint} regulates the maximum number of events in time intervals of a specific length.\n\t\t\\item\n\t\t\tThe \\textbf{ReactionConstraint} describes the minimal and maximal time a response event must occur after the associated stimulus event. Additional response events are allowed, additional stimulus events are not.\n\t\t\\item\n\t\t\tThe \\textbf{AgeConstraint} is similar to the ReactionConstraint, but it is defined the other way around. Therefore, it describes the minimal and maximal time a stimulus event must occur before the associated response event. Additional stimulus events are allowed, additional response events are not.\n\t\t\\item\n\t\t\tThe \\textbf{OutputSynchronizationConstraint} is used to describe groups of event chains, which all have the same response events. The response events of the event chain must occur in common time intervals, like in the SynchronizationConstraint. In the \\textbf{InputSynchronizationConstraint}, the roles of the stimulus and response events are swapped.\t\t\t\n\t\\end{itemize}\n\t\n\\subsection{Parenthesis - Simple and Flexible Timing Constraint Logic}\n\tThe formal definitions of the TADL2 timing constraint are written in \\emph{Timing Constraint Logic} (short: \\emph{TiCL}), which was developed as part of the TIMMO-2-USE project. TiCL was formally introduced in \\cite{TiCL}. For better understanding, the key aspects of this paper will be explained in the following.\\\\\n\tThe main goal of TiCL is to be formal and expandable and offering the possibility of defining finite and infinite behaviors of events. In TiCL, only points in time in which events occur are considered. Therefore every event only consists of a real number as a timestamp, without the possibility of adding a data value. There are seven syntactic categories in TiCL.\n\t\\begin{align*}\n\t\t\\mathbb{R} &\\text{(arithmetic constants)}\\\\\n\t\tAvar &\\text{(arithmetic variables)}\\\\\n\t\tAExp &\\text{(arithmetic expressions)}\\\\[10pt]\n\t\t%\\vspace{1cm}\n\t\tSvar &\\text{(set variables)}\\\\\n\t\tSExp &\\text{(set expressions)}\\\\[10pt]\n\t\t%\\vspace{1cm}\n\t\tTVar &\\text{(time variables)}\\\\\n\t\tCExp &\\text{(constraint expressions)}\n\t\\end{align*}\n\tArithmetic expressions can be defined as arithmetic constants, as arithmetic variables, as an application of $+,-,*,/$ on arithmetic expressions, as an application of the cardinality operator on a set ($|E|$, $E\\in SExp$) or as measure $\\lambda(E)$ ($E\\in SExp$). $\\lambda(E)$ is defined as the Lebesgue measure, which is figuratively speaking, the length of all continuous intervals of $E$. In figure~\\ref{fig:TiCLMeasureExample}, an example of the measure operator $\\lambda$ is visualized. The set $E$ contains all Events between the timestamps $1$ and $9$. The set $F$ contains the events at the timestamps between 2 and 4 and 6 and 7. Therefore $E\\setminus F$ contains the events at the timestamps $\\{1, 1.5, 4.5, 5, 5.5, 7.5, 8, 8.5, 9\\}$.\n\t$E$ consists of one continuous interval from timestamp 1 to 9 with the length of 8, $F$ consists of two continuous intervals from 2 to 4 with the length of 2 and from 6 to 7 with the length of 1, therefore $\\lambda(F)=3$. $E\\setminus F$ consists of three continuous intervals, the first from 1 to 1.5 (length = 0.5), the second from 4.5 to 5.5 (length = 1) and the last from 7.5 to 9 (length = 1.5). Consequently, the total length of the continuous intervals of $E\\setminus F$ is 3.\\\\\n\t% TODO richtig? vgl. executionTimeConstraint-> ja richtig. [x..y] beschreibt Interval mit allen mögl. Zeitpunkten dadrin.\n\t\\begin{figure}\n\t\t\\centering\n\t\t\\begin{tikzpicture}[thick]\n\t\t\t\\foreach \\x in {0,...,10}\n\t\t\t{\n\t\t\t\t\\draw[very thin, lightgray](\\x, 1.8) -- (\\x, -4);\n\t\t\t\t\n\t\t\t\t\\draw (\\x,-3.6) -- (\\x,-3.9);\n\t\t\t\t\\node at (0+\\x, -4.2) {\\x};\n\t\t\t}\n\t\t\t\\draw[->] (-0.2, -3.75) -- (10.5, -3.75);\n\t\t\t\n\t\t\t\\node at (-1, 0) {E};\n\t\t\t\\draw [fill=gray,gray] (1,0.25) rectangle (9,-0.25); \n\t\t\t\n\t\t\t\\node at (-1, -1.5) {F};\n\t\t\t\\draw [fill=gray,gray] (2,-1.25) rectangle (4,-1.75); \n\t\t\t\\draw [fill=gray,gray] (6,-1.25) rectangle (7,-1.75);\n\t\t\t\n\t\t\t\\node at (-1, -3) {$E \\setminus F$};\n\t\t\t\\draw [fill=gray,gray] (1,-2.75) rectangle (1.5,-3.25); \n\t\t\t\\draw [fill=gray,gray] (4.5,-2.75) rectangle (5.5,-3.25);\n\t\t\t\\draw [fill=gray,gray] (7.5,-2.75) rectangle (9,-3.25);\n\t\t\t\n\t\t\t\\node at (11, 0) {$\\lambda(E) = 8$};\n\t\t\t\\node at (11, -1.5) {$\\lambda(F) = 3$};\n\t\t\t\\node at (11.36, -3) {$\\lambda(E\\setminus F) = 3$};\n\t\t\t\n\t\t\t\\node at (-1.5, 1.5){Events};\n\t\t\t\\foreach \\x in {0, 0.5, ...,10}\n\t\t\t\\draw (\\x, 1.7) -- (\\x, 1.3);\n\t\t\\end{tikzpicture}\n\t\t\\caption{Graphical example of $\\lambda(E), \\lambda(F)$ and $\\lambda(E\\setminus F)$}\n\t\t\\label{fig:TiCLMeasureExample}\n\t\\end{figure}\n\tSet expressions can be defined as set variables or as a set of time variables that fulfill a given constraint expression.\\\\\n\tConstraint expressions can be defined as an application of the $\\leq$ operator on time or arithmetic expressions, the $\\in$ operator on time variables and set expressions, the logical conjunction ($\\land$) on constraint expressions, the negation of constraint expressions and the $\\forall$-Quantifier on arithmetic, set and time variables over a constraint expression.\\\\\n\tAs an extension to this definition, well known syntactic abbreviations like $true\\equiv 0\\leq 1$ or the $\\exists$-quantifier are defined. There are also some TiCL-specific syntactic abbreviations, such as interval constructors, which will be defined and explained in the following.\\\\\n\tLet $x, y\\in Tvar$ and $E, F\\in SExp$.\n\t\\begin{itemize}\n\t\t\\item\n\t\t\tThe interval constructor $[x<]$($[x\\leq]$) is defined as $\\{y: x < y\\}$($\\{y: x \\leq y\\}$), therefore the interval contains all points in time laying behind of $x$ (including $x$).\n\t\t\\item\n\t\t\t$[\\leq x]$($[< x]$) is defined as complement of $[x<]$($[x\\leq]$) and contains all timestamps laying before $x$.\n\t\t\\item\n\t\t\t$[x..y]$ is defined as $[x\\leq]\\cap[ X is subsequence of Y needed???\n\\subsection{TADL2-Timing Constraints}\n\t\\label{tadl2Constraints}\n\tFor a better understanding of the following chapters, the TADL Constraints will be presented next. As abbreviation and unification, all timing expressions are defined over set $\\mathbb{T}$, which is understood as real numbers but expanded with $\\infty$ and $-\\infty$ in this chapter. Other value ranges for time expressions are possible and will be used later in this thesis.\\\\\n\tWe define an event as a time value, possibly combined with a data value. The range of the data values is arbitrary. Infinite data types are possible, as well as empty data types when only the point in time is relevant for the constraint. All TADL constraints are defined with attributes, which can be events, timing or arithmetic expressions or sets of them. Also, \\emph{EventChains} can be used as attributes. An \\emph{EventChain} consists of two sets of events (\\emph{stimulus} and \\emph{response}), which are causally related. All events in an \\emph{EventChain} must have a color value in their data field. This color possibly has an infinite type and an equality check on the datatype of the color must be defined. It is used to check which events of an \\emph{EventChain} are directly related.\n\t\\subsubsection{DelayConstraint}\n\t\tThe \\emph{DelayConstraint} has four attributes\n\t\t\\begin{align*}\n\t\t\t\\emph{source} & \\hspace{.5cm}\\text{event set}\\\\\n\t\t\t\\emph{target} & \\hspace{.5cm}\\text{event set}\\\\\n\t\t\t\\emph{lower} & \\hspace{.5cm}\\text{$\\mathbb{T}$ (time expression)}\\\\\n\t\t\t\\emph{upper} & \\hspace{.5cm}\\text{$\\mathbb{T}$}\n\t\t\\end{align*}\n\t\tand is defined as\\\\[10pt]\n\t\t\\begin{math}\n\t\t\tDelayConstraint ( source, target, lower, upper )\\\\\n\t\t\t\\Leftrightarrow \\forall x\\in source:\\exists y\\in target: lower\\leq y-x\\leq upper.\n\t\t\\end{math}\\\\[10pt]\n\t\tFor all events $x$ in \\emph{source}, there must be an event $y$ in \\emph{target}, so that the time distance between $x$ and $y$ is between \\emph{lower} and \\emph{upper}. Note that \\emph{lower} and \\emph{upper} can have negative values and that additional events in \\emph{target} without an associated \\emph{source} event are allowed.\\\\\n\t\tFigure~\\ref{fig:delayConstraintExample} shows a visualized example of the \\emph{DelayConstraint} with the attributes $lower=2$, $upper=3$, $source=\\{1, 5, 6\\}$ and $target=\\{2, 3.5, 5, 7, 8.2, 9\\}$. The first element of source at timestamp 1 results in a required event in target between the timestamp 3 and 4 that is fulfilled by the event at 3.5. The second event of source requires a target event between 7 and 8, fulfilled by the event at 7. The last event of source is satisfied by the target event at 8.2 and 9.\n\t\t\\begin{figure}\n\t\t\t\\centering\n\t\t\t\\begin{tikzpicture}[thick]\n\t\t\t\t% source events\n\t\t\t\t\\node[] at (0,-0.2){source};\n\t\t\t\t\\draw (1, 0) -- (1, -0.4);\n\t\t\t\t\\draw (5, 0) -- (5, -0.4);\n\t\t\t\t\\draw (6, 0) -- (6, -0.4);\n\t\t\t\t\n\t\t\t\t% upper/lower 1\n\t\t\t\t\\draw [fill=lightgray, lightgray] (3, -0.7) rectangle (4,-2.3);\n\t\t\t\t\\node at (2, -0.5){lower};\n\t\t\t\t\\node at (2, -1){upper};\n\t\t\t\t\\draw[->] (1,-0.7) -- (3, -0.7);\n\t\t\t\t\\draw[->] (1, -0.8) -- (4, -0.8);\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t% upper/lower 2\n\t\t\t\t\\draw [fill=lightgray, lightgray] (7, -0.7) rectangle (8,-2.3);\n\t\t\t\t\\node at (6, -0.5){lower};\n\t\t\t\t\\node at (6, -1){upper};\n\t\t\t\t\\draw[->] (5,-0.7) -- (7, -0.7);\n\t\t\t\t\\draw[->] (5, -0.8) -- (8, -0.8);\n\t\t\t\t\n\t\t\t\t% upper/lower 3\n\t\t\t\t\\draw [fill=lightgray, lightgray] (8, -0.7) rectangle (9,-2.3);\n\t\t\t\t\\node at (7, -1.1){lower};\n\t\t\t\t\\node at (7, -1.6){upper};\n\t\t\t\t\\draw[->] (6,-1.3) -- (8, -1.3);\n\t\t\t\t\\draw[->] (6, -1.4) -- (9, -1.4);\n\t\t\t\t% target events\n\t\t\t\t\\node[] at (0,-2.1){target};\n\t\t\t\t\\draw (2, -1.9) -- (2, -2.3);\n\t\t\t\t\\draw (3.5, -1.9) -- (3.5, -2.3);\n\t\t\t\t\\draw (5, -1.9) -- (5, -2.3);\n\t\t\t\t\\draw (7, -1.9) -- (7, -2.3);\n\t\t\t\t\\draw (8.2, -1.9) -- (8.2, -2.3);\n\t\t\t\t\\draw (9, -1.9) -- (9, -2.3);\n\t\t\t\t\n\t\t\t\t\\foreach \\x in {0, 1, ..., 10}{\n\t\t\t\t\t\\draw (\\x, -2.6) -- (\\x, -2.8);\n\t\t\t\t\t\\node at(\\x, -3.1) {\\x};\n\t\t\t\t}\n\t\t\t\n\t\t\t\t\\foreach \\x in {0.5, 1.5, ..., 9.5}{\n\t\t\t\t\t\\draw (\\x, -2.7) -- (\\x, -2.6);\n\t\t\t\t}\n\t\t\t\t\\draw[->] (-0.1, -2.7) -- (10.2, -2.7);\n\t\t\t\t\n\t\t\t\t\\draw[gray] (8,-0.7)--(8,-2.3);\n\t\t\t\t\t\n\t\t\t\\end{tikzpicture}\n\t\t\t\\caption{Example DelayConstraint - $lower = 2$, $upper = 3$}\n\t\t\t\\label{fig:delayConstraintExample}\n\t\t\\end{figure}\n\t\\subsubsection{StrongDelayConstraint}\n\t\tThe \\emph{StrongDelayConstraint} has four attributes\n\t\t\\begin{align*}\n\t\t\t\\emph{source} & \\hspace{.5cm}\\text{event set}\\\\\n\t\t\t\\emph{target} & \\hspace{.5cm}\\text{event set}\\\\\n\t\t\t\\emph{lower} & \\hspace{.5cm}\\text{$\\mathbb{T}$}\\\\\n\t\t\t\\emph{upper} & \\hspace{.5cm}\\text{$\\mathbb{T}$}\n\t\t\\end{align*}\n\t\tand is defined as\\\\[10pt]\n\t\t\\begin{math}\n\t\t\tStrongDelayConstraint( source, target, lower, upper )\\\\\n\t\t\t\\Leftrightarrow|source| = |target| \\land\\\\\n\t\t\t\\forall i: \\forall x: x=source(i) \\Rightarrow \\exists y: y=target(i)\\land lower\\leq y-x\\leq upper.\n\t\t\\end{math}\\\\[10pt]\n\t\tThe \\emph{StrongDelayConstraint} is a stricter version of the \\emph{DelayConstraint}, as it requires a bijective assignment between the source and target events. Therefore additional events in target without matching source event are not allowed. Figure~\\ref{fig:StrongDelayConstraintExample} shows an example of the \\emph{StrongDelayConstraint}. The example is the same as in the previous constraint, but without the additional target events at 2, 5 and 8.2.\n \t\t\\begin{figure}\n\t\t\t\\centering\n\t\t \t\\begin{tikzpicture}[thick]\n\t\t \t% source events\n\t\t \t\\node[] at (0,-0.2){source};\n\t\t \t\\draw (1, 0) -- (1, -0.4);\n\t\t \t\\draw (5, 0) -- (5, -0.4);\n\t\t \t\\draw (6, 0) -- (6, -0.4);\n\t\t \t\n\t\t \t% upper/lower 1\n\t\t \t\\draw [fill=lightgray, lightgray] (3, -0.7) rectangle (4,-2.3);\n\t\t \t\\node at (2, -0.5){lower};\n\t\t \t\\node at (2, -1){upper};\n\t\t \t\\draw[->] (1,-0.7) -- (3, -0.7);\n\t\t \t\\draw[->] (1, -0.8) -- (4, -0.8);\n\t\t \t\n\t\t \t\n\t\t \t% upper/lower 2\n\t\t \t\\draw [fill=lightgray, lightgray] (7, -0.7) rectangle (8,-2.3);\n\t\t \t\\node at (6, -0.5){lower};\n\t\t \t\\node at (6, -1){upper};\n\t\t \t\\draw[->] (5,-0.7) -- (7, -0.7);\n\t\t \t\\draw[->] (5, -0.8) -- (8, -0.8);\n\t\t \t\n\t\t \t% upper/lower 3\n\t\t \t\\draw [fill=lightgray, lightgray] (8, -0.7) rectangle (9,-2.3);\n\t\t \t\\node at (7, -1.1){lower};\n\t\t \t\\node at (7, -1.6){upper};\n\t\t \t\\draw[->] (6,-1.3) -- (8, -1.3);\n\t\t \t\\draw[->] (6, -1.4) -- (9, -1.4);\n\t\t \t% target events\n\t\t \t\\node[] at (0,-2.1){target};\n\t\t \t\\draw (3.5, -1.9) -- (3.5, -2.3);\n\t\t \t\\draw (7, -1.9) -- (7, -2.3);\n\t\t \t\\draw (9, -1.9) -- (9, -2.3);\n\t\t \t\n\t\t\t\\foreach \\x in {0, 1, ..., 10}{\n\t\t\t\t\\draw (\\x, -2.6) -- (\\x, -2.8);\n\t\t\t\t\\node at(\\x, -3.1) {\\x};\n\t\t\t}\n\t\t\n\t\t\t\\foreach \\x in {0.5, 1.5, ..., 9.5}{\n\t\t\t\t\\draw (\\x, -2.7) -- (\\x, -2.6);\n\t\t\t}\n\t\t\t\\draw[->] (-0.1, -2.7) -- (10.2, -2.7);\n\t\t \t\n\t\t \t\\draw[gray] (8,-0.7)--(8,-2.3);\n\t\t \t\\end{tikzpicture}\n\t\t \t\\caption{Example StrongDelayConstraint - $lower = 2$, $upper = 3$}\n\t\t \t\\label{fig:StrongDelayConstraintExample}\n\t\t \\end{figure}\n \t\\newpage\n\t\\subsubsection{RepeatConstraint}\n\t\tThe \\emph{RepeatConstraint} also has four attributes\n\t\t\\begin{align*}\n\t\t\t\\emph{event} & \\hspace{.5cm}\\text{event set}\\\\\n\t\t\t\\emph{lower} & \\hspace{.5cm}\\text{$\\mathbb{T}$}\\\\\n\t\t\t\\emph{upper} & \\hspace{.5cm}\\text{$\\mathbb{T}$}\\\\\n\t\t\t\\emph{span}\t & \\hspace{.5cm}\\text{$integer$}\n\t\t\\end{align*}\n\t\tand is defined as\n\t\t\\begin{math}\n\t\t\tRepeatConstraint ( event, lower, upper, span )\\\\\n\t\t\t\\Leftrightarrow\\forall X\\leq event: |X|=span+1\\Rightarrow lower \\leq \\lambda([X])\\leq upper.\n\t\t\\end{math}\\\\[10pt]\n\t\tAs a reminder, the $\\leq$-operator over two sets of events $A, B$ describes that $A$ is a subsequence of $B$, the $\\lambda(A)$-function calculates the total length of all continuous intervals in $A$ and $[A]$ is the time interval between the oldest and newest event in $A$.\\\\ \\\\\n\t\tThe definition of the \\textit{RepeatConstraint} specifies that the length of each time interval containing $span+1$ subsequent events must be between $upper$ and $lower$.\\\\\n\t\tThe idea behind this constraint is to define repeated occurrences of events, with the possibility of overlapping, specified by the \\emph{span} attribute. After any event $x$, there are $span-1$ events and then the next event must be between $lower$ and $upper$ after $x$.\\\\\n\t\tFigure~\\ref{fig:RepeatConstraintExample1} shows an example of the RepeatConstraint with the attributes $event=\\{3,5,8,...\\}$, $lower=upper=2$ and $span=1$. Because $lower$ is equal to $upper$ and $span$ is 1, the events follow a strictly periodic pattern after the first event. Figure~\\ref{fig:RepeatConstraintExample2} shows a more complex example with events at $\\{0, 2, 4, 7, 9, 11,...\\}$, $lower=4$, $upper=5$ and $span=2$. The $span$-attribute is 2, so the time distances between all subsequent events with an even index are considered, as well as the distances between subsequent events with an uneven index. \n\t\t\n\t\t\\begin{figure}\n\t\t\t\\centering\n\t\t\t\\begin{tikzpicture}[thick]\n\t\t\t\t% events\n\t\t\t\t\\node at(-1 , 0.2){Event}; \n\t\t\t\t\\foreach \\x in {3,5,...,9}{\n\t\t\t\t\t\\draw (\\x, 0.4) -- (\\x, 0);\n\t\t\t\t\t\\draw[->] (\\x, -0.6) -- (\\x+2, -0.6);\n\t\t\t\t\t\\node at(\\x+1, -0.8){lower};\n\t\t\t\t\t\\node at(\\x+1, -0.4){upper};\n\t\t\t\t}\n\t\t\t\t\\draw (11, 0.4) -- (11, 0);\n\t\t\t\t% time axis\n\t\t\t\t\\foreach \\x in {0,...,11}{\n\t\t\t\t\t\\draw (\\x, -1.4) -- (\\x, -1.6);\n\t\t\t\t\t\\node at(\\x, -1.8){\\x};\n\t\t\t\t}\n\t\t\t\t\\draw[->] (-0.1, -1.5) -- (11.2, -1.5);\n\t\t\t\\end{tikzpicture}\n\t\t\t\\caption{Example RepeatConstraint - $lower = 2$, $upper = 2$, $span = 1$}\n\t\t\t\\label{fig:RepeatConstraintExample1}\n\t\t\\end{figure}\n\t\t\\begin{figure}\n\t\t\t\\centering\n\t\t\t\\begin{tikzpicture}[thick]\n\t\t\t\t\\node at(-1, 0.2){Event};\n\t\t\t\t%eventreihe 1\n\t\t\t\t\\foreach \\x in {0, 4, 9} {\n\t\t\t\t\t\\draw (\\x,0) -- (\\x, 0.4);\n\t\t\t\t}\n\t\t\t\t\\foreach \\x in {0} {\n\t\t\t\t\t\\node at (\\x+2, 0) {upper};\n\t\t\t\t\t\\draw[->] (\\x, -0.2) -- (\\x+5, -0.2);\n\t\t\t\t\t\\draw[->] (\\x, -0.4) -- (\\x+4, -0.4);\n\t\t\t\t\t\\node at (\\x+2, -0.6) {lower};\n\t\t\t\t}\n\t\t\t\t\\foreach \\x in {9} {\n\t\t\t\t\t\\node at (\\x+2, 0) {upper};\n\t\t\t\t\t\\draw[-] (\\x, -0.2) -- (12, -0.2);\n\t\t\t\t\t\\draw[-] (\\x, -0.4) -- (12, -0.4);\n\t\t\t\t\t\\node at (\\x+2, -0.6) {lower};\n\t\t\t\t}\n\t\t\t\t\\foreach \\x in {4} {\n\t\t\t\t\t\\node at (\\x+2, -0.4) {upper};\n\t\t\t\t\t\\draw[->] (\\x, -0.6) -- (\\x+5, -0.6);\n\t\t\t\t\t\\draw[->] (\\x, -0.8) -- (\\x+4, -0.8);\n\t\t\t\t\t\\node at (\\x+2, -1) {lower};\n\t\t\t\t}\n\t\t\t\t%eventreihe 2\n\t\t\t\t\\foreach \\x in {2, 7, 11} {\n\t\t\t\t\t\\draw (\\x,-1.4) -- (\\x, -1.8);\n\t\t\t\t}\n\t\t\t\t\\foreach \\x in {2} {\n\t\t\t\t\t\\node at (\\x+2, -1.8) {upper};\n\t\t\t\t\t\\draw[->] (\\x, -2) -- (\\x+5, -2);\n\t\t\t\t\t\\draw[->] (\\x, -2.2) -- (\\x+4, -2.2);\n\t\t\t\t\t\\node at (\\x+2, -2.4) {lower};\n\t\t\t\t}\n\t\t\t\t\\foreach \\x in {11} {\n\t\t\t\t\t\\node at (\\x+0.5, -1.8) {upper};\n\t\t\t\t\t\\draw[-] (\\x, -2) -- (12, -2);\n\t\t\t\t\t\\draw[-] (\\x, -2.2) -- (12, -2.2);\n\t\t\t\t\t\\node at (\\x+0.5, -2.6) {lower};\n\t\t\t\t}\n\t\t\t\t\\foreach \\x in {7} {\n\t\t\t\t\t\\node at (\\x+2, -2.2) {upper};\n\t\t\t\t\t\\draw[->] (\\x, -2.4) -- (\\x+5, -2.4);\n\t\t\t\t\t\\draw[->] (\\x, -2.6) -- (\\x+4, -2.6);\n\t\t\t\t\t\\node at (\\x+2, -2.8) {lower};\n\t\t\t\t}\n\t\t\t\t%time axis\n\t\t\t\t\\foreach \\y in {-3.2}{\n\t\t\t\t\t\\foreach \\x in {0,...,11}{\n\t\t\t\t\t\t\\draw (\\x, \\y) -- (\\x, \\y-0.2);\n\t\t\t\t\t\t\\node at(\\x, \\y-0.4){\\x};\n\t\t\t\t\t}\n\t\t\t\t\t\\draw[->] (-0.1, \\y-0.1) -- (11.2, \\y-0.1);\n\t\t\t\t}\n\t\t\t\\end{tikzpicture}\n\t\t\t\\caption{Example RepeatConstraint - $lower = 4$, $upper = 5$, $span = 2$}\n\t\t\t\\label{fig:RepeatConstraintExample2}\n\t\t\\end{figure}\n\t%\\newpage\n\t\\subsubsection{RepetitionConstraint}\n\t\tThe \\emph{RepetitionConstraint} has five attributes\n\t\t\\begin{align*}\n\t\t\t\\emph{event} & \\hspace{.5cm}\\text{event set}\\\\\n\t\t\t\\emph{lower} & \\hspace{.5cm}\\text{$\\mathbb{T}$}\\\\\n\t\t\t\\emph{upper} & \\hspace{.5cm}\\text{$\\mathbb{T}$}\\\\\n\t\t\t\\emph{span}\t & \\hspace{.5cm}\\text{$integer$}\\\\\n\t\t\t\\emph{jitter}& \\hspace{.5cm}\\mathbb{T}\n\t\t\\end{align*}\n\t\tand is defined via the \\emph{RepeatConstraint} and the \\emph{StrongDelayConstraint} as\\\\[10pt]\n\t\t\\begin{math}\n\t\t\tRepetitionConstraint ( event, lower, upper, span, jitter )\\\\\n\t\t\t\\Leftrightarrow\n\t\t\t\\exists X: RepeatConstraint(X, lower, upper, span) \\land \\\\\n\t\t\t\\text{\\hspace{1cm}}StrongDelayConstraint(X, event, 0, jitter)\n\t\t\\end{math}\\\\[10pt]\n\t\twhere $X$ is a set of arbitrary timestamps that follow the structure of the \\emph{RepeatConstraint} (various(\\emph{span}) loose periodic repetitions). The actual points in time of \\emph{event} lay between the timestamps of $X$ and $jitter$ after that. For each point of time there is exactly one, corresponding timestamp in $X$.\n\t\tFigure~\\ref{fig:RepetitionConstraintExample} shows an example of the \\emph{RepetitionConstraint} with the attributes $event=\\{0.5, 3.3, 4.7, 7.6, 9.9, ...\\}$, $lower=4$, $upper=5$, $span=2$ and $jitter=1$. The shown timestamps of $X$ are only one possibility and may change due to later elements of $event$.\n\t\t\n\t\t\\begin{figure}\n\t\t\t\\centering\n\t\t\t\\begin{tikzpicture}[thick]\n\t\t\t\t% time axis\n\t\t\t\t\\foreach \\y in {-4}{\n\t\t\t\t\t\\foreach \\x in {0,...,11}\n\t\t\t\t\t\\draw (\\x,\\y) -- (\\x,\\y-0.2) node[anchor=north] {\\x};\n\t\t\t\t\t\\foreach \\x in {0.5,1.5,...,10.5}\n\t\t\t\t\t\\draw (\\x,\\y) -- (\\x,\\y-0.1);\n\t\t\t\t\t\\draw[->] (0,\\y-0.1) -- (11.2, \\y-0.1);\n\t\t\t\t}\n\t\t\t\\node[] at (-1, 0) {event};\n\t\t\t\\foreach \\x in {0.5, 3.3, 4.7, 7.6, 9.9}\n\t\t\t\t\\draw (\\x, 0.2) -- (\\x, -0.2);\n\t\t\t\n\t\t\t\\node[] at (-1, -0.9) {X};\n\t\t\t\\foreach \\x in {0, 3, 4.5, 7.5, 9}{\n\t\t\t\t\\draw (\\x, -0.7) -- (\\x, -1.1);\n\t\t\t\t\\draw[->] (\\x, -1.3) -- (\\x+1, -1.3);\n\t\t\t\t\\node at (\\x+0.5, -1.5) {jitter};\n\t\t\t}\n\t\t\t\\foreach \\x in {0, 4.5}{\n\t\t\t\t\\node at (\\x+2, -1.8) {lower};\n\t\t\t\t\\draw[|->] (\\x, -2) -- (\\x+4, -2);\n\t\t\t\t\\draw[|->] (\\x, -2.2) -- (\\x+5, -2.2);\n\t\t\t\t\\node at (\\x+2, -2.4) {upper};\n\t\t\t}\n\t\t\t\\foreach \\x in {3}{\n\t\t\t\t\\node at (\\x+2, -3) {lower};\n\t\t\t\t\\draw[|->] (\\x, -3.2) -- (\\x+4, -3.2);\n\t\t\t\t\\draw[|->] (\\x, -3.4) -- (\\x+5, -3.4);\n\t\t\t\t\\node at (\\x+2, -3.6) {upper};\n\t\t\t}\n\t\t\t\n\t\t\t\\node at (11, -1.8) {lower};\n\t\t\t\\draw[|-] (9, -2) -- (11.5, -2);\n\t\t\t\\draw[|-] (9, -2.2) -- (11.5, -2.2);\n\t\t\t\\node at (11, -2.4) {upper};\n\t\t\t\n\t\t\t\\foreach \\x in {7.5}{\n\t\t\t\t\\node at (\\x+2, -3) {lower};\n\t\t\t\t\\draw[|-] (\\x, -3.2) -- (11.5, -3.2);\n\t\t\t\t\\draw[|-] (\\x, -3.4) -- (11.5, -3.4);\n\t\t\t\t\\node at (\\x+2, -3.6) {upper};\n\t\t\t}\n\t\t\t\\end{tikzpicture}\n\t\t\t\\caption{Example RepetitionConstraint - $lower = 4$, $upper = 5$, $span = 2$, $jitter=1$}\n\t\t\t\\label{fig:RepetitionConstraintExample}\n\t\t\\end{figure}\n\t\t\n\t\n\t\\subsubsection{SynchronizationConstraint}\n\t\tThe \\emph{SynchronizationConstraint} has two attributes\n\t\t\\begin{align*}\n\t\t\t\\emph{event} & \\hspace{.5cm}\\text{set of event sets, $|event|\\geq 2$}\\\\\n\t\t\t\\emph{tolerance} & \\hspace{.5cm}\\mathbb{T}\n\t\t\\end{align*}\n\t\tand is defined via the \\emph{DelayConstraint} as\\newpage\n\t\t\\begin{math}\n\t\t\tSynchronizationConstraint ( event_1, ..., event_n, tolerance )\\\\\n\t\t\t\\Leftrightarrow\\exists X: \\forall i: DelayConstraint(X, event_i, 0, tolerance) \\land\\\\\n\t\t\t\\text{\\hspace{1cm}}DelayConstraint(event_i, X, -tolerance, 0)\n\t\t\\end{math}\\\\[10pt]\n\t\t$X$ is a set of timestamps, and there must be at least one timestamp between an element of $X$ and $tolerance$ after that in each set of \\emph{event}. Also, there must be a matching element of $X$ for each element in any set of \\emph{event}. \\\\\n\t\tIn figure~\\ref{fig:SynchronizationConstraintExample} is an example of the \\emph{SynchronizationConstraint} with the attributes $event=\\{\\{0.5, 3, 7, 7.5\\}, \\{0.7, 2.5, 7.3, 7.8\\}, \\{1.2, 3.2, 3.3, 3.4, 7.6, 8.4\\}\\}$ and $tolerance = 1$. The first points in time of each element of event form the first cluster, the corresponding element of $X$ can be between $0.2$ and $0.5$. For simplification, only the latest possible value for the element of $X$ is shown, which is the first event of the synchronization cluster. In the second cluster of events, it can be seen that multiple timestamps from one element of $event$ can be associated with a single element of $X$. The third and fourth clusters show that overlapping is also possible.\n\t\t\\begin{figure}\n\t\t\t\\centering\t\n\t\t\t\\begin{tikzpicture}[thick]\n\t\t\t\t% tolerance rectangles\n\t\t\t\t\\foreach \\x in {0.5, 2.5, 7}\n\t\t\t\t\t\\draw [fill=lightgray, lightgray] (\\x, 0.2) rectangle (\\x+1, -3.3);\n\t\t\t\t\\draw [fill=lightgray, lightgray] (7.5, 0.2) rectangle (8.5, -3.5);\n\t\t\t\t\\draw [fill=gray, gray] (7.5, 0.2) rectangle (8, -3.5);\n\t\t\t\t% time axis\n\t\t\t\t\\foreach \\y in {-4}{\n\t\t\t\t\t\\foreach \\x in {0,...,11}\n\t\t\t\t\t\t\\draw (\\x,\\y) -- (\\x,\\y-0.2) node[anchor=north] {\\x};\n\t\t\t\t\t\\foreach \\x in {0.5,1.5,...,10.5}\n\t\t\t\t\t\t\\draw (\\x,\\y) -- (\\x,\\y-0.1);\n\t\t\t\t\t\\draw[->] (0,\\y-0.1) -- (11.2, \\y-0.1);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\\node at (-1, 0){$event_1$};\n\t\t\t\t\\foreach \\x in {0.5, 3, 7, 7.5}\n\t\t\t\t\t\\draw (\\x, 0.2) -- (\\x, -0.2);\n\t\t\t\t\n\t\t\t\t\\node at (-1, -1){$event_2$};\n\t\t\t\t\\foreach \\x in {0.7, 2.5, 7.3, 7.8}\n\t\t\t\t\t\\draw (\\x, -0.8) -- (\\x, -1.2);\n\t\t\t\t\n\t\t\t\t\\node at (-1, -2){$event_3$};\n\t\t\t\t\\foreach \\x in {1.2, 3.2, 3.3, 3.4, 7.6, 8.4}\n\t\t\t\t\t\\draw (\\x, -1.8) -- (\\x, -2.2);\n\t\t\t\t\t\n\t\t\t\t\\node at (-1, -3){$X$};\n\t\t\t\t\\foreach \\x in {0.5, 2.5}{\n\t\t\t\t\t\\draw (\\x, -2.8) -- (\\x, -3.2);\n\t\t\t\t\t\\draw[->] (\\x, -3.3) -- (\\x+1, -3.3);\n\t\t\t\t\t\\node at (\\x+0.5, -3.5){$tolerance$};\n\t\t\t\t}\n\t\t\t\t\\foreach \\x in {7}{\n\t\t\t\t\t\\draw (\\x, -2.8) -- (\\x, -3.2);\n\t\t\t\t\t\\draw[->] (\\x, -3.3) -- (\\x+1, -3.3);\n\t\t\t\t}\n\t\t\t\t\\foreach \\x in {7.5}{\n\t\t\t\t\t\\draw (\\x, -2.8) -- (\\x, -3.2);\n\t\t\t\t\t\\draw[->] (\\x, -3.5) -- (\\x+1, -3.5);\n\t\t\t\t\t\\node at (\\x+0.5, -3.7){$tolerance$};\n\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\\end{tikzpicture}\n\t\t\t\\caption{Example SynchronizationConstraint - $tolerance = 1$}\n\t\t\t\\label{fig:SynchronizationConstraintExample}\n\t\t\\end{figure}\n\t\t\n\t\t\n\t\t\n\t\\subsubsection{StrongSynchronizationConstraint}\n\t\tThe \\emph{StrongSynchronizationConstraint} has the same two attributes as the \\emph{SynchronizationConstraint}\n\t\t\\begin{align*}\n\t\t\t\\emph{event} & \\hspace{.5cm}\\text{set of event sets, $|event|\\geq 2$}\\\\\n\t\t\t\\emph{tolerance} & \\hspace{.5cm}\\mathbb{T}\n\t\t\\end{align*}\n\t\tand is defined as\\\\[10pt]\n\t\t\\begin{math}\\\\\n\t\t\tStrongSynchronizationConstraint ( event_1, \\dots, event_n, tolerance )\\\\\n\t\t\t\\Leftrightarrow\\exists X: \\forall i: StrongDelayConstraint(X, event_i, 0, tolerance)\n\t\t\\end{math}\\\\[10pt]\n\t\tThis constraint is a stricter variant of the \\emph{SynchronizationConstraint}, as it requires a bijective assignment between the elements of $X$ to one element of each set of $event$. For every $x\\in X$, only one corresponding timestamp per set in $event$ is allowed, as seen in figure~\\ref{fig:StrongSynchronizationConstraintExample}, which shows the same example as the one for the \\emph{SynchronizationConstraint}, but the excess time stamps at $3.2$ and $3.3$ have been removed.\n\t\t\t\\begin{figure}\n\t\t\t\t\\centering\t\n\t\t\t\t\\begin{tikzpicture}[thick]\n\t\t\t\t% tolerance rectangles\n\t\t\t\t\\foreach \\x in {0.5, 2.5, 7}\n\t\t\t\t\\draw [fill=lightgray, lightgray] (\\x, 0.2) rectangle (\\x+1, -3.3);\n\t\t\t\t\\draw [fill=lightgray, lightgray] (7.5, 0.2) rectangle (8.5, -3.5);\n\t\t\t\t\\draw [fill=gray, gray] (7.5, 0.2) rectangle (8, -3.5);\n\t\t\t\t% time axis\n\t\t\t\t\\foreach \\y in {-4}{\n\t\t\t\t\t\\foreach \\x in {0,...,11}\n\t\t\t\t\t\\draw (\\x,\\y) -- (\\x,\\y-0.2) node[anchor=north] {\\x};\n\t\t\t\t\t\\foreach \\x in {0.5,1.5,...,10.5}\n\t\t\t\t\t\\draw (\\x,\\y) -- (\\x,\\y-0.1);\n\t\t\t\t\t\\draw[->] (0,\\y-0.1) -- (11.2, \\y-0.1);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\\node at (-1, 0){$Event_1$};\n\t\t\t\t\\foreach \\x in {0.5, 3, 7, 7.5}\n\t\t\t\t\\draw (\\x, 0.2) -- (\\x, -0.2);\n\t\t\t\t\n\t\t\t\t\\node at (-1, -1){$Event_2$};\n\t\t\t\t\\foreach \\x in {0.7, 2.5, 7.3, 7.8}\n\t\t\t\t\\draw (\\x, -0.8) -- (\\x, -1.2);\n\t\t\t\t\n\t\t\t\t\\node at (-1, -2){$Event_3$};\n\t\t\t\t\\foreach \\x in {1.2, 3.4, 7.6, 8.4}\n\t\t\t\t\\draw (\\x, -1.8) -- (\\x, -2.2);\n\t\t\t\t\n\t\t\t\t\\node at (-1, -3){$X$};\n\t\t\t\t\\foreach \\x in {0.5, 2.5}{\n\t\t\t\t\t\\draw (\\x, -2.8) -- (\\x, -3.2);\n\t\t\t\t\t\\draw[->] (\\x, -3.3) -- (\\x+1, -3.3);\n\t\t\t\t\t\\node at (\\x+0.5, -3.5){$tolerance$};\n\t\t\t\t}\n\t\t\t\t\\foreach \\x in {7}{\n\t\t\t\t\t\\draw (\\x, -2.8) -- (\\x, -3.2);\n\t\t\t\t\t\\draw[->] (\\x, -3.3) -- (\\x+1, -3.3);\n\t\t\t\t}\n\t\t\t\t\\foreach \\x in {7.5}{\n\t\t\t\t\t\\draw (\\x, -2.8) -- (\\x, -3.2);\n\t\t\t\t\t\\draw[->] (\\x, -3.5) -- (\\x+1, -3.5);\n\t\t\t\t\t\\node at (\\x+0.5, -3.7){$tolerance$};\n\t\t\t\t}\n\t\t\t\n\t\t\t\\end{tikzpicture}\n\t\t\t\\caption{Example StrongSynchronizationConstraint - $tolerance = 1$}\n\t\t\t\\label{fig:StrongSynchronizationConstraintExample}\n\t\t\\end{figure}\n\t\t\n\t\t\n\t\\subsubsection{ExecutionTimeConstraint}\n\t\tThe \\emph{ExecutionTimeConstraints} takes six attributes\n\t\t\\begin{align*}\n\t\t\t\\emph{start} & \\hspace{.5cm}\\text{set of events}\\\\\n\t\t\t\\emph{stop} & \\hspace{.5cm}\\text{set of events}\\\\\n\t\t\t\\emph{preempt} & \\hspace{.5cm}\\text{set of events}\\\\\n\t\t\t\\emph{resume} & \\hspace{.5cm}\\text{set of events}\\\\\n\t\t\t\\emph{lower} & \\hspace{.5cm}\\mathbb{T}\\\\\n\t\t\t\\emph{upper} & \\hspace{.5cm}\\mathbb{T}\\\\\n\t\t\\end{align*}\n\t\tand is defined as\\\\[10pt]\n\t\t\\begin{math}\n\t\t\tExecutionTimeConstraint (start, stop, preempt, resume, lower, upper)\\\\\n\t\t\t\\Leftrightarrow\\forall x\\in start: lower\\leq \\lambda([x..stop]\\setminus[preempt..resume]) \\leq upper\n\t\t\\end{math}\\\\[10pt]\n\t\tThe interval constructor $\\forall x\\in start: [x..stop]$ defines the time interval between each point in time of $start$ until the next element of $stop$, excluding the $stop$ timestamp. $[preempt..resume]$ defines the intervals between each event of $preempt$ and the next timestamp of $resume$. These intervals are removed from the considered interval length.\n\t\tThe Idea behind this constraint is to define the runtime of a task without counting interruptions.\\\\\n\t\tFigure~\\ref{fig:ExecutionTimeConstraintExample} shows an example of the \\emph{ExecutionTimeConstraints} with $start=\\{1\\}$, $end=\\{7\\}$, $preempt=\\{2, 5\\}$ and $resume = \\{3, 6.5\\}$. Therefore, $[start..end]$ spans the interval from time 1 to 7 with the length of 6 and $[preempt..resume]$ spans two intervals, 2 to 3 and 5 to 6.5 with the lengths 1 and 1.5. As a result, $\\lambda([x..stop]\\setminus[preempt..resume])$ for $x = 1$ is 3.5 and the constraint is fulfilled, if, and only if, lower is equal or \\emph{lower} than 3.5 and \\emph{upper} is greater than that.\n\t\t\\begin{figure}\n\t\t\t\\centering\n \t\t\t\\begin{tikzpicture}[thick]\n\t\t\t\t% time axis\n\t\t\t\t\\foreach \\y in {-4}{\n\t\t\t\t\t\\foreach \\x in {0,...,11}\n\t\t\t\t\t\\draw (\\x,\\y) -- (\\x,\\y-0.2) node[anchor=north] {\\x};\n\t\t\t\t\t\\foreach \\x in {0.5,1.5,...,10.5}\n\t\t\t\t\t\\draw (\\x,\\y) -- (\\x,\\y-0.1);\n\t\t\t\t\t\\draw[->] (0,\\y-0.1) -- (11.2, \\y-0.1);\n\t\t\t\t}\n\t\t\t\t% start\n\t\t\t\t\\node at (-1, -0.2) {start};\n\t\t\t\t\\draw[] (1,0) -- (1,-0.4);\n\t\t\t\t% end\n\t\t\t\t\\node at (-1, -0.8) {end};\n\t\t\t\t\\draw[] (7, -0.6) -- (7, -1);\n\t\t\t\t%preempt\n\t\t\t\t\\node at (-1, -1.4) {preempt};\n\t\t\t\t\\draw[] (2, -1.2) -- (2, -1.6);\n\t\t\t\t\\draw[] (5, -1.2) -- (5, -1.6);\n\t\t\t\t%resume\n\t\t\t\t\\node at (-1, -2) {resume};\n\t\t\t\t\\draw[] (3, -1.8) -- (3, -2.2);\n\t\t\t\t\\draw[] (6.5, -1.8) -- (6.5, -2.2);\n\t\t\t\t\n\t\t\t\t\\node at (-1, -2.8) {[start..end]};\n\t\t\t\t\\draw [fill=lightgray, lightgray] (1, -2.6) rectangle (7, -3.0);\n\t\t\t\t\n\t\t\t\t\\node at (-1, -3.4) {[preempt..resume]};\n\t\t\t\t\\draw [fill=lightgray, lightgray] (2, -3.2) rectangle (3, -3.6);\n\t\t\t\t\\draw [fill=lightgray, lightgray] (5, -3.2) rectangle (6.5, -3.6);\n\t\t\t\\end{tikzpicture}\n\t\t\t\\caption{Example ExecutionTimeConstraint}\n\t\t\t\\label{fig:ExecutionTimeConstraintExample}\n\t\t\\end{figure}\n\t\\newpage\n\t\\subsubsection{OrderConstraint}\n\t\tThe \\emph{OrderConstraint} takes two attributes\n\t\t\\begin{align*}\n\t\t\t\\emph{source} & \\hspace{.5cm}\\text{set of events}\\\\\n\t\t\t\\emph{target} & \\hspace{.5cm}\\text{set of events}\n\t\t\\end{align*}\n\t\tand is defined as\\\\[10pt]\n\t\t\\begin{math}\n\t\t\tOrderConstraint ( source, target )\\\\\n\t\t\t\\Leftrightarrow|source| = |target| \\land \\forall i:\\exists x: x=source(i)\\Rightarrow \\exists y: y=target(i)\\land < x \\leq y\n\t\t\\end{math}\\\\[10pt]\n\t\tThis constraint ensures the order of events so that the $i^{th}$ event of $target$ occurs after the $i^{th}$ event of $source$. Also, the number of events in \\emph{source} and \\emph{target} must be equal.\\\\\n\t\tFigure~\\ref{fig:OrderConstraintExample} visualizes an example of the \\emph{OrderConstraint} with $source = \\{1, 4, 6, 7\\}$ and $target = \\{3, 5, 9, 9.5\\}$. The constraint is fulfilled because the number of elements is equal and each $i^{th}$ timestamp in \\emph{target} is later than the $i^{th}$ timestamp of $source$.\n\t\t\\begin{figure}\n\t\t\t\\centering\n\t\t\t\\begin{tikzpicture}[thick]\n\t\t\t\t% time axis\n\t\t\t\t\\foreach \\y in {-1.5}{\n\t\t\t\t\t\\foreach \\x in {0,...,11}\n\t\t\t\t\t\\draw (\\x,\\y) -- (\\x,\\y-0.2) node[anchor=north] {\\x};\n\t\t\t\t\t\\foreach \\x in {0.5,1.5,...,10.5}\n\t\t\t\t\t\\draw (\\x,\\y) -- (\\x,\\y-0.1);\n\t\t\t\t\t\\draw[->] (0,\\y-0.1) -- (11.2, \\y-0.1);\n\t\t\t\t}\n\t\t\t\t% start\n\t\t\t\t\\node at (-1, -0.2) {source};\n\t\t\t\t\\foreach \\x in {1, 4, 6, 7}{\n\t\t\t\t\t\\draw[] (\\x,0) -- (\\x,-0.4);\n\t\t\t\t}\n\t\t\t\t\\node at (1, 0.2) {1};\n\t\t\t\t\\node at (4, 0.2) {2};\n\t\t\t\t\\node at (6, 0.2) {3};\n\t\t\t\t\\node at (7, 0.2) {4};\n\t\t\t\t% end\n\t\t\t\t\\node at (-1, -0.8) {target};\n\t\t\t\t\\foreach \\x in {3, 5, 9, 9.5}{\n\t\t\t\t\t\\draw[] (\\x,-0.6) -- (\\x,-1);\n\t\t\t\t}\n\t\t\t\t\\node at (3, -1.2) {1};\n\t\t\t\t\\node at (5, -1.2) {2};\n\t\t\t\t\\node at (9, -1.2) {3};\n\t\t\t\t\\node at (9.5, -1.2) {4};\n\t\t\t\\end{tikzpicture}\n\t\t\t\\caption{Example OrderConstraint}\n\t\t\t\\label{fig:OrderConstraintExample}\n\t\t\\end{figure}\n\t\t\n\t\\subsubsection{ComparisonConstraint}\n\t\tThe \\emph{ComparisonConstraint} is significantly different from all previous and following constraints, as it does not describe the behavior of events and only compares two time expressions. It takes three attributes\n\t\t\\newpage\n\t\t\\begin{align*}\n\t\t\t\\emph{leftOperand} \t& \\hspace{.5cm}\\mathbb{T}\\\\\n\t\t\t\\emph{rightOperand} & \\hspace{.5cm}\\mathbb{T}\\\\\n\t\t\t\\emph{operator}\t\t& \\hspace{.5cm} \\text{comparisonOperator}(\\in \\{LessThanOrEqual, LessThan,\\\\\n\t\t\t\t\t\t\t\t& \\hspace{3.5cm} GreaterThanOrEqual, GreaterThan, Equal\\})\n\t\t\\end{align*}\n\t\tThe definition is pretty straight forward as it only applies the given operator to the operands:\\\\[10pt]\n\t\t\\begin{math}\n\t\t\tComparisonConstraint(leftOperand, rightOperand, LessThanOrEqual)\\\\\n\t\t\t\t\\Leftrightarrow leftOperand \\leq rightOperand\\\\[5pt]\n\t\t\tComparisonConstraint(leftOperand, rightOperand, LessThan)\\\\\n\t\t\t\t\\Leftrightarrow leftOperand < rightOperand\\\\[5pt]\n\t\t\tComparisonConstraint(leftOperand, rightOperand, GreaterThanOrEqual)\\\\\n\t\t\t\t\\Leftrightarrow leftOperand \\geq rightOperand\\\\[5pt]\n\t\t\tComparisonConstraint(leftOperand, rightOperand, GreaterThan)\\\\\n\t\t\t\t\\Leftrightarrow leftOperand > rightOperand\\\\[5pt]\n\t\t\tComparisonConstraint(leftOperand, rightOperand, Equal)\\\\\n\t\t\t\t\\Leftrightarrow leftOperand = rightOperand\n\t\t\\end{math}\\\\[10pt]\n\t\tDue to the simplicity of this constraint, no explicit example is given.\n\t\t\n\t\\subsubsection{SporadicConstraint}\n\t\tThe \\emph{SporadicConstraint} takes 5 attributes\n\t\t\\begin{align*}\n\t\t\t\\emph{event} \t& \\hspace{.5cm}\\text{set of events}\\\\\n\t\t\t\\emph{lower} \t& \\hspace{.5cm}\\mathbb{T}\\\\\n\t\t\t\\emph{upper} \t& \\hspace{.5cm}\\mathbb{T}\\\\\n\t\t\t\\emph{jitter}\t& \\hspace{.5cm}\\mathbb{T}\\\\\n\t\t\t\\emph{minimum}\t& \\hspace{.5cm}\\mathbb{T}\n\t\t\\end{align*}\n\t\tand is defined as combination of the \\emph{RepetitionConstraint} and the \\emph{RepeatConstraint} as\\\\[10pt]\n\t\t\\begin{math}\n\t\t\tSporadicConstraint ( event, lower, upper, jitter, minimum )\\\\\n\t\t\t\\Leftrightarrow RepetitionConstraint(event, lower, upper, 1, jitter)\\\\\n\t\t\t\\hspace*{.5cm}\\land RepeatConstraint(event, minimum, \\infty, 1)\n\t\t\\end{math}\\\\[10pt]\n\t\tThe second part of the definition, using the \\emph{RepeatConstraint}, ensures that all events in \\emph{event} lay at least \\emph{minimum} apart. The application of the \\emph{RepetitionConstraint} generates a set of events $X$ that lay between $lower$ and $upper$ apart from each other. For each point in time in $X$, there must be exactly one timestamp in \\emph{event} that is not before the corresponding element of $X$ and not later than \\emph{jitter} after that.\\\\\n\t\tFigure~\\ref{fig:SporadicConstraintExample} shows a application of the \\emph{SporadicConstraint} with the attributes $lower=2$, $upper=2.5$, $jitter=1$, $minimum=2$ and $event=\\{1, 3.5, 6, 8.2, 10.5,...\\}$. Like in the \\emph{RepetitionConstraint}, the exact position of the timestamps in $X$ is variable and may need to be changed due to later entries in $event$.\n\t\t\\begin{figure}\n\t\t\t\\centering\n\t\t\t\\begin{tikzpicture}[thick]\n\t\t\t% time axis\n\t\t\t\\foreach \\y in {-2.5}{\n\t\t\t\t\\foreach \\x in {0,...,11}\n\t\t\t\t\\draw (\\x,\\y) -- (\\x,\\y-0.2) node[anchor=north] {\\x};\n\t\t\t\t\\foreach \\x in {0.5,1.5,...,10.5}\n\t\t\t\t\\draw (\\x,\\y) -- (\\x,\\y-0.1);\n\t\t\t\t\\draw[->] (0,\\y-0.1) -- (11.2, \\y-0.1);\n\t\t\t}\n\t\t\t% event\n\t\t\t\\node at (-1, 0.4) {event};\n\t\t\t\\foreach \\x in {1, 3.5, 6, 8.2}{\n\t\t\t\t\\draw[] (\\x,0.2) -- (\\x,+0.6);\n\t\t\t\t%minimum\n\t\t\t\t\\draw[->] (\\x, 0) -- (\\x+2, 0);\n\t\t\t\t\\node at (\\x+1, 0.2) {min.};\n\t\t\t}\n\t\t\t\\foreach \\x in {10.5}{\n\t\t\t\t\\draw[] (\\x,0.2) -- (\\x,+0.6);\n\t\t\t\t%minimum\n\t\t\t\t\\draw[-] (\\x, 0) -- (11.5, 0);\n\t\t\t\t\\node at (\\x+0.5, 0.2) {min.};\n\t\t\t}\n\t\t\t% X\n\t\t\t\\node at (-1, -0.8) {X};\n\t\t\t\\foreach \\x in {0.8, 2.8, 5.3, 7.8, 10}{\n\t\t\t\t\\draw[] (\\x,-0.6) -- (\\x,-1);\n\t\t\t\t%jitter\n\t\t\t\t\\draw[->] (\\x, -0.25) -- (\\x+1, -0.25);\n\t\t\t\t\\node at (\\x+0.5, -0.5) {jitter};\n\t\t\t}\n\t\t\t%lower/upper\n\t\t\t\\foreach \\x in {0.8, 5.3}{\n\t\t\t\t\\node at (\\x+1, -1.1){lower};\n\t\t\t\t\\draw[->] (\\x, -1.3) -- (\\x+2, -1.3);\n\t\t\t\t\\draw[->] (\\x, -1.5) -- (\\x+2.5, -1.5);\n\t\t\t\t\\node at (\\x+1, -1.7){upper};\n\t\t\t}\n\t\t\t\\foreach \\x in {2.8, 7.8}{\n\t\t\t\t\\node at (\\x+1, -1.6){lower};\n\t\t\t\t\\draw[->] (\\x, -1.8) -- (\\x+2, -1.8);\n\t\t\t\t\\draw[->] (\\x, -2) -- (\\x+2.5, -2);\n\t\t\t\t\\node at (\\x+1, -2.2){upper};\n\t\t\t}\n\n\t\t\t\\end{tikzpicture}\n\t\t\t\\caption{Example SporadicConstraint - $lower=2$, $upper=2.5$, $jitter=1$, $minimum=2$}\n\t\t\t\\label{fig:SporadicConstraintExample}\n\t\t\\end{figure}\n\t\n\t\\subsubsection{PeriodicConstraint}\n\t\tThe \\emph{PeriodicConstraint} takes 4 attribute\n\t\t\\begin{align*}\n\t\t\t\\emph{event} \t& \\hspace{.5cm}\\text{set of events}\\\\\n\t\t\t\\emph{period} \t& \\hspace{.5cm}\\mathbb{T}\\\\\n\t\t\t\\emph{jitter}\t& \\hspace{.5cm}\\mathbb{T}\\\\\n\t\t\t\\emph{minimum}\t& \\hspace{.5cm}\\mathbb{T}\n\t\t\\end{align*}\n\t\tand defines a specialized form of the \\emph{SporadicConstraint}\\\\[10pt]\n\t\t\\begin{math}\n\t\t\tPeriodicConstraint ( event, period, jitter, minimum )\\\\\n\t\t\t\\Leftrightarrow SporadicConstraint(event, period, period, jitter, minimum)\n\t\t\\end{math}\\\\[10pt]\n\t\tThe variable timestamps in the set $X$ are following a strictly periodic pattern, where subsequent elements of this set lay exactly \\emph{period} apart. Each element of \\emph{event} lays between one element of $X$ and \\emph{jitter} after that. Again, there must be a bijective mapping between the elements of \\emph{event} and $X$.\\\\\n\t\tIn figure~\\ref{fig:PeriodicConstraintExample}, the \\emph{PeriodicConstraint} with the attributes $period=3$, $jitter=1$, $minimum=2.5$ and $event = \\{1.2, 4.0, 8, 10.6, ...\\}$ is visualized. The timestamps of $X$ lay exactly \\emph{period} apart and the $events$ behind that in the previously described way. Also, the minimum time distance between all points of time in \\emph{event} is \\emph{minimum}.\n\t\t\\begin{figure}\n\t\t\t\\centering\n\t\t\t\\begin{tikzpicture}[thick]\n\t\t\t% time axis\n\t\t\t\\foreach \\y in {-2}{\n\t\t\t\t\\foreach \\x in {0,...,11}\n\t\t\t\t\\draw (\\x,\\y) -- (\\x,\\y-0.2) node[anchor=north] {\\x};\n\t\t\t\t\\foreach \\x in {0.5,1.5,...,10.5}\n\t\t\t\t\\draw (\\x,\\y) -- (\\x,\\y-0.1);\n\t\t\t\t\\draw[->] (0,\\y-0.1) -- (11.2, \\y-0.1);\n\t\t\t}\n\t\t\t% event\n\t\t\t\\node at (-1, 0.6) {event};\n\t\t\t\\foreach \\x in {1.2, 4.0, 8}{\n\t\t\t\t%timestamp\n\t\t\t\t\\draw[] (\\x,0.2) -- (\\x,+0.6);\n\t\t\t\t%minimum\n\t\t\t\t\\draw[->] (\\x, 0) -- (\\x+2.5, 0);\n\t\t\t\t\\node at (\\x+1.25, 0.2) {min.};\n\t\t\t}\n\t\t\t\\foreach \\x in {10.6}{\n\t\t\t\t%timestamp\n\t\t\t\t\\draw[] (\\x,0.2) -- (\\x,+0.6);\n\t\t\t\t%minimum\n\t\t\t\t\\draw[-] (\\x, 0) -- (11.5, 0);\n\t\t\t\t\\node at (\\x+0.5, 0.2) {min.};\n\t\t\t}\n\t\t\t% X\n\t\t\t\\node at (-1, -0.8) {X};\n\t\t\t\\foreach \\x in {1, 4, 7}{\n\t\t\t\t%timestamp\n\t\t\t\t\\draw[] (\\x,-0.6) -- (\\x,-1);\n\t\t\t\t%jitter\n\t\t\t\t\\draw[->] (\\x, -0.25) -- (\\x+1, -0.25);\n\t\t\t\t\\node at (\\x+0.5, -0.5) {jitter};\n\t\t\t\t%period\n\t\t\t\t\\draw[->] (\\x, -1.25) -- (\\x+3, -1.25);\n\t\t\t\t\\node at (\\x+1.5, -1.5) {period};\n\t\t\t}\n\t\t\t\\foreach \\x in {10}{\n\t\t\t\t%timestamp\n\t\t\t\t\\draw[] (\\x,-0.6) -- (\\x,-1);\n\t\t\t\t%jitter\n\t\t\t\t\\draw[->] (\\x, -0.25) -- (\\x+1, -0.25);\n\t\t\t\t\\node at (\\x+0.5, -0.5) {jitter};\n\t\t\t\t%period\n\t\t\t\t\\draw[-] (\\x, -1.25) -- (11.5, -1.25);\n\t\t\t\t\\node at (\\x+0.5, -1.5) {period};\n\t\t\t}\n\t\t\t\\end{tikzpicture}\n\t\t\t\\caption{Example PeriodicConstraint - $period=3$, $jitter=1$, $minimum=2.5$}\n\t\t\t\\label{fig:PeriodicConstraintExample}\n\t\t\\end{figure}\n\t\t\n\t\t\n\t\\subsubsection{PatternConstraint}\n\t\t\\label{sec:patterConstraintDefinition}\n\t\tThe \\emph{PatternConstraint} takes 5 attributes\n\t\t\\begin{align*}\n\t\t\t\\emph{event} \t& \\hspace{.5cm}\\text{set of events}\\\\\n\t\t\t\\emph{period} \t& \\hspace{.5cm}\\mathbb{T}\\\\\n\t\t\t\\emph{offset}\t& \\hspace{.5cm} \\text{set of }\\mathbb{T}\\\\\n\t\t\t\\emph{jitter}\t& \\hspace{.5cm}\\mathbb{T}\\\\\n\t\t\t\\emph{minimum}\t& \\hspace{.5cm}\\mathbb{T}\n\t\t\\end{align*}\n\t\tand is defined as \\\\[10pt]\n\t\t\\begin{math}\n\t\t\tPatternConstraint( event, period, \\text{\\textit{offset}}_1, ..., \\text{\\textit{offset}}_n, jitter, minimum )\\\\\n\t\t\t\\Leftrightarrow\\exists X: PeriodicConstraint(X, period, 0, 0)\\\\\n\t\t\t\\text{\\hspace{.5cm}} \\land \\forall i: DelayContraint(X, event, \\text{\\textit{offset}}_i, \\text{\\textit{offset}}_i+jitter)\\\\\n\t\t\t\\text{\\hspace{.5cm}} \\land RepeatConstraint(event, minimum, \\infty, 1)\n\t\t\\end{math}\\\\[10pt]\n\t\tThis constraint can be understood as a modification of the \\emph{PeriodicConstraint}, as it describes periodic behavior, but not from single events, but from groups of $| \\text{\\textit{offset}}_i|$ subsequent events, that follow specific time distances (specified by $\\text{\\textit{offset}}$) after the strictly periodic timestamps of $X$.\\\\\n\t\tThere is a major weak spot in the definition of this constraint because the set $X$ can be set to the empty set. In this case, the part of the definition, which uses the \\emph{PeriodicConstraint} and the \\emph{DelayContraint}, is always satisfied, irrespective of the events in $event$. Therefore, the \\emph{PatternConstraint} only ensures the minimal distance between two events, which should not be the purpose of this constraint. \n\t\tThe obvious countermeasure to this problem would be to restrict $X$ in a way that ensures that it is not empty and the first element of $X$ must lay before the first $event$ occurrence. The textual description of the constraint, which says literally the ''PatternConstraint requires the constrained event occurrences to appear at a predetermined series of offsets from a sequence of reference points'' contradicts this countermeasure because the \\emph{DelayConstraint} allows additional events in the $target$ events with no matching $source$ event. Therefore, any event occurrences besides the events following the offset scheme would be allowed, which conflicts with the citation. Because of this problem, the \\emph{PatternConstraint} is redefined as \\\\[10pt]\n\t\t\\begin{math}\n\t\t\tPatternConstraint( event, period, \\text{\\textit{offset}}_1, ..., \\text{\\textit{offset}}_n, jitter, minimum )\\\\\n\t\t\t\\Leftrightarrow\\exists X: PeriodicConstraint(X, period, 0, 0)\\\\\n\t\t\t\\text{\\hspace{.5cm}} \\land \\forall i: \\textbf{\\emph{Strong}}DelayContraint(X, event, offset_i, offset_i+jitter)\\\\\n\t\t\t\\text{\\hspace{.5cm}} \\land RepeatConstraint(event, minimum, \\infty, 1)\n\t\t\\end{math}\\\\[10pt]\n\t\tfor the scope of this thesis. The usage of the \\emph{StrongDelayConstraint}, instead of the \\emph{DelayConstraint}, ensures that each event occurrence is following the time distances defined by the offsets. This notion of the \\emph{PatternConstraint} is also carried by the described relations between the TADL2 timing constraints and the AUTOSAR Timing Extensions, which were done as part of the development of TADL2\\cite{TIMMO2USE}. These descriptions equate the \\emph{PatternConstraint} and AUTOSARs \\emph{ConcretePatternEventTriggering}, which is clearly defined in the way of this redefinition.\\\\\n\t\tFigure~\\ref{fig:PatternConstraintExample} shows an application of the \\emph{PeriodicConstraint} with the attributes $period=5$, $\\text{\\textit{offset}}=\\{1, 2, 2.5\\}$, $jitter=0.5$, $minimum=0.5$ and\\\\\n\t\t$event = \\{1.2, 2.2, 2.8, 6, 7, 8, 11.5, 12, 12.5, ...\\}$. Like in the previously described constraint, the exact position of all points in time of $X$ may change due to later timestamps of $event$.\n\t\t\\begin{figure}\n\t\t\\centering\n\t\t\t\\begin{tikzpicture}[thick]\n\t\t\t% time axis\n\t\t\t\\foreach \\y in {-3.5}{\n\t\t\t\t\\foreach \\x in {0,...,14}\n\t\t\t\t\\draw (\\x,\\y) -- (\\x,\\y-0.2) node[anchor=north] {\\x};\n\t\t\t\t\\foreach \\x in {0.5,1.5,...,13.5}\n\t\t\t\t\\draw (\\x,\\y) -- (\\x,\\y-0.1);\n\t\t\t\t\\draw[->] (0,\\y-0.1) -- (14.2, \\y-0.1);\n\t\t\t}\n\t\t\t% event\n\t\t\t\\node at (-1, 0.6) {event};\n\t\t\t\\foreach \\x in {1.2, 2.2, 2.8, 6, 7, 8, 11.5, 12, 12.5}{\n\t\t\t\t%timestamp\n\t\t\t\t\\draw[] (\\x,0.2) -- (\\x,+0.6);\n\t\t\t\t%minimum\n\t\t\t\t\\draw[->] (\\x, 0.8) -- (\\x+.5, 0.8);\n\t\t\t\t\\node at (\\x+0.25, 1) {min.};\n\t\t\t}\n\t\t\t% X\n\t\t\t\\node at (-1, -2.2) {X};\n\t\t\t\\foreach \\x in {0,5, 10}{\n\t\t\t\t%timestamp\n\t\t\t\t\\draw[] (\\x,-2) -- (\\x,-2.4);\n\t\t\t\t%offset 1\n\t\t\t\t\\draw[->] (\\x, -0.5) -- (\\x+1, -0.5);\n\t\t\t\t\\node at (\\x+0.5, -0.7) {offset$_1$};\n\t\t\t\t\\draw[->] (\\x+1, -0.5) -- (\\x+1.5, -0.5);\n\t\t\t\t\\node at (\\x+1.25, -0.3) {jitter};\n\t\t\t\t%offset 2\n\t\t\t\t\\draw[->] (\\x, -1) -- (\\x+2, -1);\n\t\t\t\t\\node at (\\x+1, -1.2) {offset$_2$};\n\t\t\t\t\\draw[->] (\\x+2, -1) -- (\\x+2.5, -1);\n\t\t\t\t\\node at (\\x+2.25, -0.8) {jitter};\n\t\t\t\t%offset 3\n\t\t\t\t\\draw[->] (\\x, -1.5) -- (\\x+2.5, -1.5);\n\t\t\t\t\\node at (\\x+1.25, -1.7) {offset$_3$};\n\t\t\t\t\\draw[->] (\\x+2.5, -1.5) -- (\\x+3, -1.5);\n\t\t\t\t\\node at (\\x+2.75, -1.3) {jitter};\n\n\t\t\t}\n\t\t\t%period\n\t\t\t\\draw[->] (0, -2.6) -- (0+5, -2.6);\n\t\t\t\\node at (0+2.5, -2.83) {period};\n\t\t\t%period\n\t\t\t\\draw[->] (5, -2.6) -- (5+5, -2.6);\n\t\t\t\\node at (5+2.5, -2.83) {period};\n\t\t\t%period\n\t\t\t\\draw[-] (10, -2.6) -- (14, -2.6);\n\t\t\t\\node at (10+2.5, -2.83) {period};\n\t\t\t\\end{tikzpicture}\n\t\t\t\\caption{Example PatternConstraint - $period=5$, $offset=\\{1, 2, 2.5\\}$, $jitter=0.5$, $minimum=0.5$}\n\t\t\t\\label{fig:PatternConstraintExample}\n\t\t\\end{figure}\n\t\t\n\t\\subsubsection{ArbitraryConstraint}\n\t\tThe \\emph{ArbitraryConstraint} takes 3 attributes\n\t\t\\begin{align*}\n\t\t\t\\emph{event} \t& \\hspace{.5cm}\\text{set of events}\\\\\n\t\t\t\\emph{minimum}\t& \\hspace{.5cm}\\text{set of }\\mathbb{T}\\\\\n\t\t\t\\emph{maximum}\t& \\hspace{.5cm}\\text{set of }\\mathbb{T}\n\t\t\\end{align*}\n\t\twhere $|minimum|=|maximum|$. It is defined as \\\\[10pt]\n\t\t\\begin{math}\\\\\n\t\t\tArbitraryConstraint ( event, minimum_1, ..., minimum_n, maximum_1, ..., maximum_n)\\\\\n\t\t\t\\Leftrightarrow\\forall i: RepeatConstraint(event, minimum_i, maximum_i, i)\n\t\t\\end{math}\\\\[10pt]\n\t\tThe idea behind the \\emph{ArbitraryConstraint} is to describe the time distance between each event and several following events. The first entry of \\emph{minimum} and \\emph{maximum} defines the distance between every event and its direct successor. The second entry, where the \\emph{span} attribute of the \\emph{RepeatConstraint} is 2, defines the distance between one event and its next but one successor and so on.\\\\\n\t\tFigure~\\ref{fig:ArbitraryConstraintExample} shows an example of the \\emph{ArbitraryConstraint} with the attributes $minimum=\\{1,2,3\\}$, $maximum=\\{5,6,7\\}$ and $event=\\{1, 2, 3, 5, 8, 10, ...\\}$. The time distances between subsequent events with 0, 1, 2 and more skipped events are shown in table~\\ref{tab:ArbitraryConstraintExampleTable}. The relevant distances are written in \\textbf{bold} font. The time distances are matching the ranges given by the $minimum$- and $maximum$ attributes.\\\\\n\t\t\\begin{table}\n\t\t\t\\begin{tabular}{|c|c|c|c|c|c|c|}\n\t\t\t\t\\hline\n\t\t\t\t& 1 & 2 & 3 & 5 & 8 & 10 \\\\\n\t\t\t\t\\hline\n\t\t\t\t1 & 0 & \\textbf{1} & \\textbf{2} & \\textbf{4} & 7 & 9 \\\\\n\t\t\t\t\\hline\n\t\t\t\t2 & & 0 & \\textbf{1} & \\textbf{3} & \\textbf{6} & 8 \\\\\n\t\t\t\t\\hline\n\t\t\t\t3 & & & 0 & \\textbf{2} & \\textbf{5} & \\textbf{7} \\\\\n\t\t\t\t\\hline\n\t\t\t\t5 & & & & 0 & \\textbf{3} & \\textbf{5} \\\\\n\t\t\t\t\\hline\n\t\t\t\t8 & & & & & 0 & \\textbf{2} \\\\\n\t\t\t\t\\hline\n\t\t\t\t10 & & & & & & 0 \\\\\n\t\t\t\t\\hline\n\t\t\t\\end{tabular}\n\t\t\t\\centering\n\t\t\t\\caption{Time distances as seen in figure~\\ref{fig:ArbitraryConstraintExample}}\n\t\t\t\\label{tab:ArbitraryConstraintExampleTable}\n\t\t\\end{table}\n\n\t\t\\begin{figure}\n\t\t\t\\centering\n\t\t\t\\begin{tikzpicture}[thick]\n\t\t\t% time axis\n\t\t\t\\foreach \\y in {-6}{\n\t\t\t\t\\foreach \\x in {0,...,11}\n\t\t\t\t\\draw (\\x,\\y) -- (\\x,\\y-0.2) node[anchor=north] {\\x};\n\t\t\t\t\\foreach \\x in {0.5,1.5,...,10.5}\n\t\t\t\t\\draw (\\x,\\y) -- (\\x,\\y-0.1);\n\t\t\t\t\\draw[->] (0,\\y-0.1) -- (11.2, \\y-0.1);\n\t\t\t}\n\t\t\t% event\n\t\t\t\\node at (-1, 0.4) {event};\n\t\t\t\\node at (-1, -0.85) {$minimum_1$};\n\t\t\t\\node at (-1, -1.65) {$maximum_1$};\n\t\t\t\n\t\t\t\\node at (-1, -2.55) {$minimum_2$};\n\t\t\t\\node at (-1, -3.45) {$maximum_2$};\n\t\t\t\n\t\t\t\n\t\t\t\\node at (-1, -4.35) {$minimum_3$};\n\t\t\t\\node at (-1, -5.25) {$maximum_3$};\n\t\t\t\\foreach \\x in {1,2,3,5,8,10}{\n\t\t\t\t%timestamp\n\t\t\t\t\\draw[] (\\x,0.2) -- (\\x,+0.6);\n\t\t\t}\n\t\t\t% minimum 1\n\t\t\t\\draw[->] (1, -0.6) -- (2, -0.6);\n\t\t\t\\draw[->] (2, -0.7) -- (3, -0.7);\n\t\t\t\\draw[->] (3, -0.8) -- (4, -0.8);\n\t\t\t\\draw[->] (5, -0.9) -- (6, -0.9);\n\t\t\t\\draw[->] (8, -1.0) -- (9, -1.0);\n\t\t\t\\draw[->] (10, -1.1) -- (11, -1.1);\n\t\t\t% maximum 1\n\t\t\t\\draw[->] (1, -1.4) -- (6, -1.4);\n\t\t\t\\draw[->] (2, -1.5) -- (7, -1.5);\n\t\t\t\\draw[->] (3, -1.6) -- (8, -1.6);\n\t\t\t\\draw[->] (5, -1.7) -- (10, -1.7);\n\t\t\t\\draw[-] (8, -1.8) -- (11.5, -1.8);\n\t\t\t\\draw[-] (10, -1.9) -- (11.5, -1.9);\n\t\t\t\n\t\t\t% minimum 2\n\t\t\t\\draw[->] (1, -2.3) -- (3, -2.3);\n\t\t\t\\draw[->] (2, -2.4) -- (4, -2.4);\n\t\t\t\\draw[->] (3, -2.5) -- (5, -2.5);\n\t\t\t\\draw[->] (5, -2.6) -- (7, -2.6);\n\t\t\t\\draw[->] (8, -2.7) -- (10, -2.7);\n\t\t\t\\draw[-] (10, -2.8) -- (11.5, -2.8);\n\t\t\t\n\t\t\t% maximum 2\n\t\t\t\\draw[->] (1, -3.2) -- (7, -3.2);\n\t\t\t\\draw[->] (2, -3.3) -- (8, -3.3);\n\t\t\t\\draw[->] (3, -3.4) -- (9, -3.4);\n\t\t\t\\draw[->] (5, -3.5) -- (11, -3.5);\n\t\t\t\\draw[-] (8, -3.6) -- (11.5, -3.6);\n\t\t\t\\draw[-] (10, -3.7) -- (11.5, -3.7);\n\t\t\t\n\t\t\t% minimum 3\n\t\t\t\\draw[->] (1, -4.1) -- (4, -4.1);\n\t\t\t\\draw[->] (2, -4.2) -- (5, -4.2);\n\t\t\t\\draw[->] (3, -4.3) -- (6, -4.3);\n\t\t\t\\draw[->] (5, -4.4) -- (8, -4.4);\n\t\t\t\\draw[->] (8, -4.5) -- (11, -4.5);\n\t\t\t\\draw[-] (10, -4.6) -- (11.5, -4.6);\n\t\t\t\n\t\t\t% maximum 3\n\t\t\t\\draw[->] (1, -5.0) -- (8, -5.0);\n\t\t\t\\draw[->] (2, -5.1) -- (9, -5.1);\n\t\t\t\\draw[->] (3, -5.2) -- (10, -5.2);\n\t\t\t\\draw[-] (5, -5.3) -- (11.5, -5.3);\n\t\t\t\\draw[-] (8, -5.4) -- (11.5, -5.4);\n\t\t\t\\draw[-] (10, -5.5) -- (11.5, -5.5);\n\t\t\t\n\t\t\t\n\t\t\t\\end{tikzpicture}\n\t\t\t\\caption{Example ArbitraryConstraint - $minimum=\\{1,2,3\\}$ and $minimum=\\{4,5,6\\}$}\n\t\t\t\\label{fig:ArbitraryConstraintExample}\n\t\t\\end{figure}\n\t\t\n\t\\subsubsection{BurstConstraint}\n\t\tThe \\emph{BurstConstraint} takes 4 attributes\n\t\t\\begin{align*}\n\t\t\t\\emph{event} \t\t\t& \\hspace{.5cm}\\text{set of events}\\\\\n\t\t\t\\emph{length}\t\t\t& \\hspace{.5cm} \\mathbb{T}\\\\\n\t\t\t\\emph{maxOccurrences}\t& \\hspace{.5cm} integer\\\\\n\t\t\t\\emph{minimum}\t\t\t& \\hspace{.5cm} \\mathbb{T}\n\t\t\\end{align*}\n\t\tand is defined as \\\\[10pt]\n\t\t\\begin{math}\n\t\t\tBurstConstraint ( event, length, maxOccurrences, minimum )\\\\\n\t\t\t\\Leftrightarrow RepeatConstraint(event, length, \\infty, maxOccurrences)\\\\\n\t\t\t\\text{\\hspace{.5cm}}\\land RepeatConstraint(event, minimum, \\infty, 1)\n\t\t\\end{math}\\\\[10pt]\n\t\t This constraint defines the maximum number of events in a time interval of the given $length$. Additionally, all subsequent events must be at least \\emph{minimum} apart. Therefore, the intuition is different from the AUTOSAR \\emph{BurstPatternEventTriggering}, where clusters of events are described. A complete comparison of these constraints will be made in section~\\ref{comparisonConstraints}.\\\\\n\t\t In figure~\\ref{fig:BurstConstraintExample}, an application of the \\emph{BurstConstraint} with the attributes $length=5,\\\\ maxOccurrences=3$, $minimum=0.8$ and $event = \\{1,2,3,7,8,9\\}$ is visualized. In every interval of length 5, there are three or fewer events. Also, all subsequent events lay at least $0.8$ apart. Therefore, the constraint is fulfilled.\n \t\t\\begin{figure}\n \t\t\t\\centering\n\t\t \t\\begin{tikzpicture}[thick]\n\t\t\t \t% time axis\n\t\t\t \t\\foreach \\y in {-2}{\n\t\t\t \t\t\\foreach \\x in {0,...,11}\n\t\t\t \t\t\\draw (\\x,\\y) -- (\\x,\\y-0.2) node[anchor=north] {\\x};\n\t\t\t \t\t\\foreach \\x in {0.5,1.5,...,10.5}\n\t\t\t \t\t\\draw (\\x,\\y) -- (\\x,\\y-0.1);\n\t\t\t \t\t\\draw[->] (0,\\y-0.1) -- (11.2, \\y-0.1);\n\t\t\t \t}\n\t\t\t \t% event\n\t\t\t \t\\node at (-1, 0.4) {event};\n\t\t\t \t\\foreach \\x in {1, 2, 3, 7, 8, 9}{\n\t\t\t \t\t%timestamp\n\t\t\t \t\t\\draw[] (\\x,0.2) -- (\\x,+0.6);\n\t\t\t \t\t%minimum\n\t\t\t \t\t\\draw[->] (\\x, 0) -- (\\x+0.8, 0);\n\t\t\t \t\t\\node at (\\x+0.4, -0.2) {min.};\n\t\t\t \t}\n\t\t \t\t% length\n\t\t \t\t\\node at (-1, -1.2) {length};\n\t\t \t\t\\draw[->] (1, -1) -- (6, -1);\n\t \t\t\t\\draw[->] (2, -1.2) -- (7, -1.2);\n \t\t\t\t\\draw[->] (3, -1.4) -- (8, -1.4);\n \t\t\t\t\\draw[-] (7, -1) -- (11.5, -1);\n \t\t\t\t\\draw[-] (8, -1.2) -- (11.5, -1.2);\n \t\t\t\t\\draw[-] (9, -1.4) -- (11.5, -1.4);\n\t\t \t\\end{tikzpicture}\n\t\t \t\\caption{Example BurstConstraint - $length=5$, $maxOccurences=3$ $minimum=0.8$}\n\t\t \t\\label{fig:BurstConstraintExample}\n\t\t \\end{figure}\n\t\\subsubsection{ReactionConstraint}\n\t\tThe \\emph{ReactionConstraint} takes 3 attributes\n\t\t\\begin{align*}\n\t\t\t\\emph{scope} \t& \\hspace{.5cm} EventChain\\\\\n\t\t\t\\emph{minimum}\t& \\hspace{.5cm} \\mathbb{T}\\\\\n\t\t\t\\emph{maximum}\t& \\hspace{.5cm} \\mathbb{T}\n\t\t\\end{align*}\n\t\tand is defined as \\newpage\n\t\t\\begin{math}\n\t\t\tReactionConstraint ( scope, minimum, maximum )\\\\\n\t\t\t\\Leftrightarrow\\forall x\\in scope.stimulus: \\exists y\\in scope.response:\\\\\n\t\t\t\\text{\\hspace{.5cm}}x.color=y.color\\\\\n\t\t\t\\text{\\hspace{.5cm}}\\land (\\forall y'\\in scope.response: y'.color=y.color\\Rightarrow y\\leq y')\\\\\n\t\t\t\\text{\\hspace{.5cm}}\\land minimum \\leq y-x \\leq maximum\n\t\t\\end{math}\\\\[10pt]\n\t\tThe definition says that after every event $x$ of $scope.stimulus$, there is an event $y$ in $scope.res$-\\\\$ponse$ with the same color. The time distance between these events must be at least $minimum$ and at most $maximum$. Additional events with the same color as $y$ in $scope.response$ are allowed if they lay behind $y$. The definition implies that additional events with other colors are allowed in $scope.response$, but not in $scope.stimulus$.\\\\\n\t\tA visualized example with the attributes $minimum=1$, $maximum=3$,\n\t\t$scope.stimulus=\\{(1, red), (5, green), (5.5, purple), (8, orange)\\}$ and $scope.response = \\{(0.8, blue), (2.1, red),\\\\ (4.5, blue), (6.6, purple),\n\t\t(6.7, purple), (9.5, purple), (7.5, green),\n\t\t(10, orange)\\}$ can be seen in figure~\\ref{fig:ReactionConstraint}. The red $stimulus$ event is followed by the red $response$-event at 2.1, the green $stimulus$ event at 5 by the $response$ event at 7.5 and so on. The blue $response$ events at 1 and 4.5 are additional events without an associated stimulus event. The purple events at 6.7 and 9.5 are the second and third events of this color in $scope.response$ Therefore, their time distance to the $stimulus$ event with the same color is irrelevant.\n \t\t\\begin{figure}\n \t\t\t\\centering\n\t\t\t\\begin{tikzpicture}[thick]\n\t\t\t\t% time axis\n\t\t\t\t\\foreach \\y in {-3}{\n\t\t\t\t\t\\foreach \\x in {0,...,11}\n\t\t\t\t\t\\draw (\\x,\\y) -- (\\x,\\y-0.2) node[anchor=north] {\\x};\n\t\t\t\t\t\\foreach \\x in {0.5,1.5,...,10.5}\n\t\t\t\t\t\\draw (\\x,\\y) -- (\\x,\\y-0.1);\n\t\t\t\t\t\\draw[->] (0,\\y-0.1) -- (11.2, \\y-0.1);\n\t\t\t\t}\n\t\t\t\t% stimulus\n\t\t\t\t\\node at (-1, 0.4) {stimulus};\n\t\t\t\t\\draw[red, thick] (1 ,0.2) -- (1,+0.6);\n\t\t\t\t\\draw[green, thick] (5 ,0.2) -- (5,+0.6);\n\t\t\t\t\\draw[purple, thick] (5.5,0.2) -- (5.5,+0.6);\n\t\t\t\t\\draw[orange, thick] (8 ,0.2) -- (8,+0.6);\n\t\t\t\t\n\t\t\t\t% minimum\n\t\t\t\t\\draw[->, red] (1, -0.2) -- (2, -0.2);\n\t\t\t\t\\node at (1.5, 0) {min.};\n\t\t\t\t\\draw[->, green] (5, -0.2) -- (6, -0.2);\n\t\t\t\t\\node at (5.5, 0) {min.};\n\t\t\t\t\\draw[->, purple] (5.5, -1.1) -- (6.5, -1.1);\n\t\t\t\t\\node at (6, -0.9) {min.};\n\t\t\t\t\\draw[->, orange] (8, -0.2) -- (9, -0.2);\n\t\t\t\t\\node at (8.5, 0) {min.};\n\t\t\t\t%maximum\n\t\t\t\t\\draw[->, red] (1, -0.4) -- (4, -0.4);\n\t\t\t\t\\node at (1.5, -0.6) {max.};\n\t\t\t\t\\draw[->, green] (5, -0.4) -- (8, -0.4);\n\t\t\t\t\\node at (5.5, -0.6) {max.};\n\t\t\t\t\\draw[->, purple] (5.5, -1.3) -- (8.5, -1.3);\n\t\t\t\t\\node at (6, -1.5) {max.};\n\t\t\t\t\\draw[->, orange] (8, -0.4) -- (11, -0.4);\n\t\t\t\t\\node at (8.5, -0.6) {max.};\n\t\t\t\t%response\n\t\t\t\t\\node at (-1, -2.1) {response};\n\t\t\t\t\\draw[blue, thick] (.8 ,-1.9) -- (.8,-2.3);\n\t\t\t\t\\draw[blue, thick] (4.5 ,-1.9) -- (4.5,-2.3);\n\t\t\t\t\\draw[red, thick] (2.1 ,-1.9) -- (2.1,-2.3);\n\t\t\t\t\\draw[green, thick] (7.5 ,-1.9) -- (7.5,-2.3);\n\t\t\t\t\\draw[purple, thick] (6.6,-1.9) -- (6.6,-2.3);\n\t\t\t\t\\draw[purple, thick] (6.7,-1.9) -- (6.7,-2.3);\n\t\t\t\t\\draw[purple, thick] (9.5,-1.9) -- (9.5,-2.3);\n\t\t\t\t\\draw[orange, thick] (10 ,-1.9) -- (10,-2.3);\n\t\t\t\\end{tikzpicture}\n\t\t\t\\caption{Example ReactionConstraint - $minimum=1$, $maximum=3$}\n\t\t\t\\label{fig:ReactionConstraint}\n\t\t\\end{figure}\n\t\t\n\t\n\t\\subsubsection{AgeConstraint}\n\t\tThe \\emph{AgeConstraint} takes 3 attributes\n\t\t\\begin{align*}\n\t\t\t\\emph{scope} \t& \\hspace{.5cm} EventChain\\\\\n\t\t\t\\emph{minimum}\t& \\hspace{.5cm} \\mathbb{T}\\\\\n\t\t\t\\emph{maximum}\t& \\hspace{.5cm} \\mathbb{T}\n\t\t\\end{align*}\n\t\tand is defined as \\\\[10pt]\n\t\t\\begin{math}\n\t\t\tAgeConstraint ( scope, minimum, maximum )\\\\\n\t\t\t\\Leftrightarrow\\forall y\\in scope.response: \\exists x\\in scope.stimulus:\\\\\n\t\t\t\\text{\\hspace{.5cm}}x.color=y.color\\\\\n\t\t\t\\text{\\hspace{.5cm}}\\land (\\forall x'\\in scope.stimulus: x'.color=x.color\\Rightarrow x'\\leq x)\\\\\n\t\t\t\\text{\\hspace{.5cm}}\\land minimum \\leq y-x \\leq maximum\n\t\t\\end{math}\\\\[10pt]\n\t\tThe \\emph{AgeConstraint} is a turned around counterpart to the \\emph{ReactionConstraint}. For every event of $scope.response$, there must be an event with the same color in $scope.stimulus$. The time distance between these events must be between $minimum$ and $maximum$. Additional events are only allowed in $scope.stimulus$ and only before the event that matches with a $response$ event, which is implied by the correctness of the event chain.\\\\\n\t\tFigure~ \\ref{fig:AgeConstraint} shows an application of the \\emph{AgeConstraint} with the attributes $minimum=1$, $maximum=3$, $scope.stimulus=\\{(0.8, blue), (1, red), (2, green), (4.5, green),\n\t\t(5, green),\\\\ (5.5, purple), (8, orange)\\}$ and $scope.response=\\{(3.5, red), (7.5, green),\n\t\t (6.6, purple), \\\\(10, orange)\\}$. The blue timestamps are additional events without matching events in \\\\$scope.response$.\n \t\t\\begin{figure}\n \t\t\t\\centering\n\t\t\t\\begin{tikzpicture}[thick]\n\t\t\t\t% time axis\n\t\t\t\t\\foreach \\y in {-3}{\n\t\t\t\t\t\\foreach \\x in {0,...,11}\n\t\t\t\t\t\\draw (\\x,\\y) -- (\\x,\\y-0.2) node[anchor=north] {\\x};\n\t\t\t\t\t\\foreach \\x in {0.5,1.5,...,10.5}\n\t\t\t\t\t\\draw (\\x,\\y) -- (\\x,\\y-0.1);\n\t\t\t\t\t\\draw[->] (0,\\y-0.1) -- (11.2, \\y-0.1);\n\t\t\t\t}\n\t\t\t\t% stimulus\n\t\t\t\t\\node at (-1, 0.4) {stimulus};\n\t\t\t\t\\draw[red, thick] (1 ,0.2) -- (1,+0.6);\n\t\t\t\t\\draw[green, thick] (2 ,0.2) -- (2,+0.6);\n\t\t\t\t\\draw[green, thick] (5 ,0.2) -- (5,+0.6);\n\t\t\t\t\\draw[purple, thick] (5.5,0.2) -- (5.5,+0.6);\n\t\t\t\t\\draw[orange, thick] (8 ,0.2) -- (8,+0.6);\n\t\t\t\t\\draw[blue, thick] (0.8, 0.2) -- (0.8,0.6);\n\t\t\t\t\\draw[blue, thick] (4.5, 0.2) -- (4.5,0.6);\n\t\t\t\t\n\t\t\t\t% minimum\n\t\t\t\t\\draw[->, red] (3.5, -0.2) -- (2.5, -0.2);\n\t\t\t\t\\node at (3, 0) {min.};\n\t\t\t\t\\draw[->, green] (7.5, -0.2) -- (6.5, -0.2);\n\t\t\t\t\\node at (7, 0) {min.};\n\t\t\t\t\\draw[->, purple] (6.6, -1.1) -- (5.6, -1.1);\n\t\t\t\t\\node at (6.1, -0.9) {min.};\n\t\t\t\t\\draw[->, orange] (10, -1.1) -- (9, -1.1);\n\t\t\t\t\\node at (9.5, -0.9) {min.};\n\t\t\t\t%maximum\n\t\t\t\t\\draw[->, red] (3.5, -0.4) -- (0.5, -0.4);\n\t\t\t\t\\node at (3, -0.6) {max.};\n\t\t\t\t\\draw[->, green] (7.5, -0.4) -- (4.5, -0.4);\n\t\t\t\t\\node at (7, -0.6) {max.};\n\t\t\t\t\\draw[->, purple] (6.6, -1.3) -- (3.6, -1.3);\n\t\t\t\t\\node at (6.1, -1.5) {max.};\n\t\t\t\t\\draw[->, orange] (10, -1.3) -- (7, -1.3);\n\t\t\t\t\\node at (9.5, -1.5) {max.};\n\t\t\t\t%response\n\t\t\t\t\\node at (-1, -2.1) {response};\n\t\t\t\t\\draw[red, thick] (3.5 ,-1.9) -- (3.5,-2.3);\n\t\t\t\t\\draw[green, thick] (7.5 ,-1.9) -- (7.5,-2.3);\n\t\t\t\t\\draw[purple, thick] (6.6,-1.9) -- (6.6,-2.3);\n\t\t\t\t%\\draw[purple, thick] (6.7,-1.9) -- (6.7,-2.3);\n\t\t\t\t%\\draw[purple, thick] (9.5,-1.9) -- (9.5,-2.3);\n\t\t\t\t\\draw[orange, thick] (10 ,-1.9) -- (10,-2.3);\n\t\t\t\\end{tikzpicture}\n\t\t\t\\caption{Example AgeConstraint - $minimum=1$, $maximum=3$}\n\t\t\t\\label{fig:AgeConstraint}\n\t\t\\end{figure}\n\t\t\n\t\\subsubsection{OutputSynchronizationConstraint}\n\t\tThe \\emph{OutputSynchronizationConstraint} takes 2 attributes\n\t\t\\begin{align*}\n\t\t\t\\emph{scope} \t& \\hspace{.5cm} \\text{Set of }EventChain\\\\\n\t\t\t\\emph{tolerance}\t& \\hspace{.5cm} \\mathbb{T}\n\t\t\\end{align*}\n\t\twhere all elements of \\emph{scope} have the same $stimulus$ event set. It is defined as \\\\[10pt]\n\t\t\\begin{math}\n\t\t\tOutputSynchronizationConstraint ( scope_1, ..., scope_n, tolerance )\\\\\n\t\t\t\\Leftrightarrow\\forall x\\in scope_1.stimulus: \\exists t: \\forall i: \\exists y\\in scope_i.response:\\\\\n\t\t\t\\text{\\hspace{.5cm}} x.color = y.color\\\\\n\t\t\t\\text{\\hspace{.5cm}}\\land (\\forall y'\\in scope_i.response: y'.color=y.color \\Rightarrow y\\leq y')\\\\\n\t\t\t\\text{\\hspace{.5cm}}\\land 0\\leq y-t\\leq tolerance\n\t\t\\end{math}\\\\[10pt]\n\t\tThe definition says that after each event $x$ in $scope_1.stimulus$, there must be an interval with the length of $tolerance$, in which every $scope_i.response$ must have an event $y$ with the same color as $x$. Additional response events with this color are only allowed after $y$.\n\t\tFigure~\\ref{fig:OutputSynchronizationConstraint} shows an example of the \\emph{OutputSynchronizationConstraint} with the attributes $tolerance = 1$,\\\\\n\t\t $scope[1].stimulus=scope[2].stimulus=scope[3].stimulus=\\{(1, red), (4, green), (5, purple)\\}$,\\\\\n\t\t$scope[1].response=\\{(2, red), (6, purple), (6.2, purple), (8.2, green)\\}$,\\\\\n\t\t$scope[2].response=\\{(2.6, red), (6.2, purple), (8, green), (10.5, green)\\}$,\\\\\n\t\t$scope[3].response=\\{(2.3, red), (6.5, purple), (8.5, green)\\}$.\\\\\n\t\t\n \t\t\\begin{figure}\n\t \t\t\\centering\n\t\t\t\\begin{tikzpicture}[thick]\n\t\t\t\t% time axis\n\t\t\t\t\\foreach \\y in {-3.5}{\n\t\t\t\t\t\\foreach \\x in {0,...,11}\n\t\t\t\t\t\\draw (\\x,\\y) -- (\\x,\\y-0.2) node[anchor=north] {\\x};\n\t\t\t\t\t\\foreach \\x in {0.5,1.5,...,10.5}\n\t\t\t\t\t\\draw (\\x,\\y) -- (\\x,\\y-0.1);\n\t\t\t\t\t\\draw[->] (0,\\y-0.1) -- (11.2, \\y-0.1);\n\t\t\t\t}\n\t\t\t\t% stimulus\n\t\t\t\t\\node at (-1, 0.4) {scope\\textcolor{black}{[1]}.stimulus};\n\t\t\t\t\\draw[red, thick] (1 ,0.2) -- (1,+0.6);\n\t\t\t\t\\draw[green, thick] (4 ,0.2) -- (4,+0.6);\n\t\t\t\t\\draw[purple, thick] (5,0.2) -- (5,+0.6);\n\t\t\t\t\n\t\t\t\t\\node at(-1, -0.6) {scope[1].response};\n\t\t\t\t\\draw[red, thick] (2, -0.4) -- (2, -0.8);\n\t\t\t\t\\draw[green, thick] (8.3, -0.4) -- (8.3, -0.8);\n\t\t\t\t\\draw[purple, thick] (6, -0.4) -- (6, -0.8);\n\t\t\t\t\\draw[purple, thick] (6.2, -0.4) -- (6.2, -0.8);\n\t\t\t\t\n\t\t\t\t\\node at(-1, -1.2) {scope[2].response};\n\t\t\t\t\\draw[red, thick] (2.6, -1) -- (2.6, -1.4);\n\t\t\t\t\\draw[green, thick] (8, -1) -- (8, -1.4);\n\t\t\t\t\\draw[green, thick] (10.5, -1) -- (10.5, -1.4);\n\t\t\t\t\\draw[purple, thick] (6.2, -1) -- (6.2, -1.4);\n\t\t\t\t\n\t\t\t\t\\node at(-1, -1.8) {scope[3].response};\n\t\t\t\t\\draw[red, thick] (2.3, -1.6) -- (2.3, -2);\n\t\t\t\t\\draw[green, thick] (8.5, -1.6) -- (8.5, -2);\n\t\t\t\t\\draw[purple, thick] (6.5, -1.6) -- (6.5, -2);\n\t\t\t\t\n\t\t\t\t\\node at (-1, -2.8) {t \\& tolerance};\n\t\t\t\t\\foreach \\i in {2, 6, 8} {\n\t\t\t\t\t\\draw[thick] (\\i, -2.6) -- (\\i, -3);\n\t\t\t\t\t\\draw[->] (\\i, -2.8) -- (\\i+1, -2.8);\n\t\t\t\t}\n\n\t\t\t\\end{tikzpicture}\n\t\t\t\\caption{Example OutputSynchronizationConstraint - $tolerance=1$}\n\t\t\t\\label{fig:OutputSynchronizationConstraint}\n\t\t\\end{figure}\n\t\t\n\t\\subsubsection{InputSynchronizationConstraint}\n\tThe \\emph{InputSynchronizationConstraint} takes 2 attributes\n\t\\begin{align*}\n\t\t\\emph{scope} \t& \\hspace{.5cm} \\text{Set of }EventChain\\\\\n\t\t\\emph{tolerance}& \\hspace{.5cm} \\mathbb{T}\n\t\\end{align*}\n\twhere all elements of \\emph{scope} have the same $response$ event set. It is defined as \\\\[10pt]\n\t\\begin{math}\n\t\tInputSynchronizationConstraint ( scope_1, ..., scope_n, tolerance )\\\\\n\t\t\\Leftrightarrow\\forall y\\in scope_1.response: \\exists t: \\forall i: \\exists x\\in scope_i.stimulus:\\\\\n\t\t\\text{\\hspace{.5cm}} x.color = y.color\\\\\n\t\t\\text{\\hspace{.5cm}}\\land (\\forall x'\\in scope_i.stimulus: x'.color=x.color \\Rightarrow x\\leq x')\\\\\n\t\t\\text{\\hspace{.5cm}}\\land 0\\leq x-t\\leq tolerance\n\t\\end{math}\\\\[10pt]\n\tThe \\emph{InputSynchronizationConstraint} is a counterpart of the \\emph{OutputSynchronizationConstraint}, as the \\emph{stimulus} events must be synchronized, not the \\emph{response} events.\\\\\n\tFigure~\\ref{fig:InputSynchronizationConstraint} contains an example of the \\emph{InputSynchronizationConstraint} with the attributes $tolerance=1$\\\\\n\t$scope[1].stimulus=\\{(1, red), (1.5, green), (4.6, green), (8, purple)\\}$\\\\\n\t$scope[2].stimulus=\\{(1.2, red), (4, green), (8.3, purple), (8.5, purple)\\}$\\\\\n\t$scope[3].stimulus=\\{(1.5, red), (4, green), (8.9, purple)\\}$\\\\\n\t$scope[1].response=scope[2].response=scope[3].response=\\{(2.5, red), (6, green), (10, purple)\\}$\\\\\n\t\\begin{figure}\n\t\t\\centering\n\t\t\\begin{tikzpicture}[thick]\n\t\t\t% time axis\n\t\t\t\\foreach \\y in {-3.5}{\n\t\t\t\t\\foreach \\x in {0,...,11}\n\t\t\t\t\\draw (\\x,\\y) -- (\\x,\\y-0.2) node[anchor=north] {\\x};\n\t\t\t\t\\foreach \\x in {0.5,1.5,...,10.5}\n\t\t\t\t\\draw (\\x,\\y) -- (\\x,\\y-0.1);\n\t\t\t\t\\draw[->] (0,\\y-0.1) -- (11.2, \\y-0.1);\n\t\t\t}\n\t\t\t% stimulus\n\t\t\t\\node at (-1, 0.4) {scope[1].stimulus};\n\t\t\t\\draw[red, thick] (1 ,0.2) -- (1,+0.6);\n\t\t\t\\draw[green, thick] (1.5 ,0.2) -- (1.5,+0.6);\n\t\t\t\\draw[green, thick] (4.6 ,0.2) -- (4.6,+0.6);\n\t\t\t\\draw[purple, thick] (8,0.2) -- (8,+0.6);\n\t\t\t\n\t\t\t\\node at (-1, -0.2) {scope[2].stimulus};\n\t\t\t\\draw[red, thick] (1.2,0) -- (1.2, -0.4);\n\t\t\t\\draw[green, thick] (4 ,0) -- (4,-0.4);\n\t\t\t\\draw[purple, thick] (8.3, 0) -- (8.3,-0.4);\n\t\t\t\\draw[purple, thick] (8.5, 0) -- (8.5,-0.4);\n\t\t\t\n\t\t\t\\node at (-1, -0.8) {scope[3].stimulus};\n\t\t\t\\draw[red, thick] (1.5,-0.6) -- (1.5, -1);\n\t\t\t\\draw[green, thick] (4, -0.6) -- (4,-1);\n\t\t\t\\draw[purple, thick] (8.9,-0.6) -- (8.9,-1);\n\t\t\t\n\t\t\t\\node at(-1, -1.8) {scope[1].response};\n\t\t\t\\draw[red, thick] (2.5, -1.6) -- (2.5, -2);\n\t\t\t\\draw[green, thick] (6, -1.6) -- (6, -2);\n\t\t\t\\draw[purple, thick] (10, -1.6) -- (10, -2);\n\t\t\t\n\t\t\t\\node at (-1, -2.8) {t \\& tolerance};\n\t\t\t\\foreach \\i in {1, 4, 8} {\n\t\t\t\t\\draw[thick] (\\i, -2.6) -- (\\i, -3);\n\t\t\t\t\\draw[->] (\\i, -2.8) -- (\\i+1, -2.8);\n\t\t\t}\n\t\t\t\n\t\t\\end{tikzpicture}\n\t\t\\caption{Example InputSynchronizationConstraint - $tolerance=1$}\n\t\t\\label{fig:InputSynchronizationConstraint}\n\t\\end{figure}\n\t\t\t\n\\subsection{Comparison TADL2 - AUTOSAR Timing Extension}\n\\label{comparisonConstraints}\n\tAs said before, the \\emph{TADL2 Timing Constraints} and the \\emph{AUTOSAR Timing Extensions} are compatible in parts. Many of the \\emph{AUTOSAR Timing Extension} can be expressed as equivalent combinations of the \\emph{TADL2 Timing Constraints}. In \\cite{TIMMO2USE}, the relationship between these constraints is shown, but this comparison is based on an outdated AUTOSAR version. Therefore each \\textit{AUTOSAR Timing Extensions} will be listed in this chapter, and it will be explained if and how they can be expressed using \\textit{TADL2 Timing Constraints}.\\\\\n\tThe types used in the AUTOSAR Timing Extension are similar to the ones in TADL2. TADL2 \\emph{Events} are called \\emph{TimingDescriptionEvent} in AUTOSAR. The same goes for \\emph{EventChains}, which are called \\emph{TimingDescriptionEventChains}. A larger difference can be seen in the definition of time. While TADL2 defines time as real numbers, the time definition used in the AUTOSAR Timing Extension can also be multidimensional, for example, when the real time and the crankshaft angle are regarded. For simplification, all timestamps are considered as real numbers in the following, but an extension to multidimensional time stamps is possible, as AUTOSAR requires a strict order between all time stamps. Some of the AUTOSAR Timing Extensions are defined on \\emph{Executable Entities}, which describe things, that can be executed. An example of this is a program routine, which starts and finishes at certain times. In the analysis of their timing, only striking points in time of these entities are relevant, like the start and endpoints or interruptions. Therefore \\emph{Executable Entities} can be transformed into events if needed.\n\t\n\tIt should be noted that the set of TADL2 timing constraints are not equal to the AUTOSAR Timing Extension and that there are constraints that cannot be expressed using the corresponding counterpart.\n\n\t\\subsubsection{PeriodicEventTriggering}\n\t\tThe \\emph{PeriodicEventTriggering} defined in AUTOSAR with the attributes\\\\ $(\\textcolor{black}{event}, period, jitter, minimumInterArrivalTime)$ is equivalent to the \\emph{TADL2}\\\\ \\emph{PeriodicConstraint} with the same attributes.\n\t\t\n\t\\subsubsection{SporadicEventTriggering}\n\t\tAUTOSARs \\emph{SporadicEventTriggering} with the attributes\\\\\n\t\t $(\\textcolor{black}{event}, jitter, maximumInterArrivalTime, minimumInterArrivalTime, period)$ is equivalent to the \\emph{TADL2} \\emph{SporadicConstraint}, except for the names of the attributes:\\\\\n\t\t\\begin{math}\n\t\t\tlower\\widehat{=}period\\\\\n\t\t\tupper\\widehat{=}maximumInterArrivalTime\\\\\n\t\t\tjitter\\widehat{=}jitter\\\\\n\t\t\tminimum\\widehat{=}minimumInterArrivalTime\n\t\t\\end{math}\n\t\n\t\\subsubsection{ConcretePatternEventTriggering}\n\t\tThe idea behind the \\emph{ConcretePatternEventTriggering} from \\textit{AUTOSAR} is the same as behind \\textit{TADL2s} \\emph{PatternConstraint}, but some details are different. Both constraints define a periodic behavior and offsets that describe time distances between the periods and the actual events. The main difference is the \\emph{jitter} attribute. In AUTOSARs \\emph{ConcretePatternEventTriggering}, the \\emph{patternJitter} attribute defines the allowed deviation from the start points from the periodic repetitions. In TADL2, the $jitter$ value describes the deviation between the offsets and the actual event.\\\\\n\t\tThe \\emph{ConcretePatternEventTriggering} from AUTOSAR also defines the attribute \\textit{patternLength}, which defines the intervals' length, in which the clusters of events will occur. It is constrained by\\\\[10pt]\n\t\t\\begin{math}\n\t\t\t0\\leq max(\\text{\\textit{offset}})\\leq patternLength\\\\\n\t\t\t\\land \\hspace{1cm}patternLength + patternJitter < patternPeriod\n\t\t\\end{math}\\\\[10pt]\n\t\tThe \\emph{patternLength} attribute can not be described with TADL2 timing constraints, as it would require to determine the distance of filtered events, which is not possible with the TADL2 constraints.\\\\\n\t\tTADL2 defines the \\emph{minimum} attribute for the \\emph{PatternConstraint} that describes the minimal time distance between subsequent events. In AUTOSAR, this must be described by using the \\emph{ArbitraryEventTriggering}, where $minimumDistance_1$ is \\emph{minimum} and $maximumDistance_1$ is $\\infty$.\n\t\t\n\t\\subsubsection{BurstPatternEventTriggering}\n\t\tThe \\textit{BurstPatternEventTriggering} defined in AUTOSAR and the \\textit{BurstConstraint} defined in TADL2s share the same target. They define a maximal number of events in time intervals of a specific length and the minimal distance of events. Additionally to the attributes of the \\textit{BurstConstraint}, the \\textit{BurstPatternEventTriggering} define more attributes. Periodic repetitions of burst clusters and the minimal number of events in each cluster can also be defined, which are no part of the TADL2 definition.\\\\\n\t\tA stream fulfilling the TADL2 \\textit{BurstConstraint} also fulfills the AUTOSAR \\textit{BurstPatternEventTriggering}, if the attributes are renamed to the AUTOSAR equivalents ($length \\rightarrow patternLength,$ $maxOccurences \\rightarrow maxNumberOfOccurences,$ $minimum$ $\\rightarrow$ $minimum$- $InterArrivalTime$), and the other attributes remain undefined.\n\t\tA stream fulfilling AUTOSARs \\textit{BurstPatternEventTriggering} does not necessarily fulfill the \\textit{BurstConstraint}. The reason for this is that the bursts always start at events in the \\textit{BurstConstraint}. In the \\textit{BurstPatternEventTriggering}, those can start at any point in time.\n\t\t\n\t\\subsubsection{ArbitraryEventTriggering}\n\t\tAUTOSARs \\emph{ArbitraryEventTriggering} is similar to the \\emph{ArbitraryConstraint} as defined in TADL2, but the \\emph{ArbitraryEventTriggering} allows to set a list of \\emph{ConfidenceInterval}s, to describe the probability, how far the events may lay apart. These probabilities can not be expressed in TADL2.\n\t\t\n\t\\subsubsection{LatencyTimingConstraint}\n\t\tThe \\emph{LatencyTimingConstraint} of AUTOSAR takes 5 attributes, a latency type $latencyConstr$- $aintType\\in \\{age, reaction\\}$, three time values $maximum$, $minimum$ and $nominal$ and an event chain $scope$, consisting of the stimulus and response events. The $nominal$-value is not defined in the $TADL2$ constraint. If this attribute is not required for the specification, the \\emph{LatencyTimingConstraint} can be expressed with the $AgeConstraint$ defined in TADL2 if the $latencyConstraintType$ is $age$. If the $latencyConstraintType$ is $reaction$, it can be expressed by the $reactionConstraint$.\n\t\n\t\\subsubsection{AgeConstraint}\n\t\tThe goal of the \\emph{AgeConstraint} in AUTOSAR is to define a minimal and maximal age of an event at the point in time when it is processed. There is no counterpart to this in the TADL2 constraints because the point in time when the event is processed is unknown. If this point in time is known, AUTOSARs \\emph{AgeConstraint} can be expressed using TADL2s \\emph{AgeConstraint}, but in that case, it could also be expressed using AUTOSARs \\emph{LatencyTimingConstraint}.\n\t\t\n\t\\subsubsection{SynchronizationTimingConstraint}\n\t\tThe \\emph{SynchronizationTimingConstraint} is similar to TADL2s \\emph{SynchronizationConstraint}, \n\t\t\\emph{Strong- SynchronizationConstraint}, \\emph{OutputSynchronizationConstraint}, \\emph{InputSynchronizationConstraint} or combinations of them, depending on the attributes. Table~\\ref{ComparisonSynchronizationConstraints} shows with which attributes the \\emph{SynchronizationTimingConstraint} is equivalent to which TADL2 Constraint(s).\n\t\t\\begin{table}\n\t\t\t\\begin{tabular}{|c|c|c|c|c|}\n\t\t\t\t\\hline\n\t\t\t\t\\makecell{event\\\\Occurrence-\\\\Kind} \t& \\makecell{scope/\\\\scopeEvent} & \\makecell{synchronization-\\\\ConstraintType} \t& tolerance & TADL2 Constraints\\\\\n\t\t\t\t\\hline\n\t\t\t\t\\makecell{multiple\\\\Occurrences} & scopeEvent & \\emph{not set} & tolerance & \\makecell{SynchronizationConstraint\\\\\\hspace{.5cm}(scopeEvent, tolerance)}\\\\\n\t\t\t\t\\hline\n\t\t\t\t\\makecell{single\\\\Occurrences} & scopeEvent & \\emph{not set} & tolerance & \\makecell{Strong-\\\\SynchronizationConstraint\\\\\\hspace{.5cm}(scopeEvent, tolerance)}\\\\\n\t\t\t\t\\hline\n\t\t\t\t\\makecell{multiple\\\\Occurrences} & scope & \\makecell{response\\\\Synchronization} & tolerance & \\makecell{Output-\\\\SynchronizationConstraint\\\\\\hspace{.5cm}(scope, tolerance)\\\\ $\\land$ SynchronizationConstraint\\\\\\hspace{.5cm}(scope.response, tolerance)}\\\\\n\t\t\t\t\\hline\n\t\t\t\t\\makecell{single\\\\Occurrences} & scope & \\makecell{response\\\\Synchronization} & tolerance & \\makecell{Output-\\\\SynchronizationConstraint\\\\\\hspace{.5cm}(scope, tolerance)\\\\ $\\land$ Strong-\\\\SynchronizationConstraint\\\\\\hspace{.5cm}(scope.response, tolerance)}\\\\\n\t\t\t\t\\hline\n\t\t\t\t\\makecell{multiple\\\\Occurrences} & scope & \\makecell{stimulus\\\\Synchronization} & tolerance & \\makecell{Input-\\\\SynchronizationConstraint\\\\\\hspace{.5cm}(scope, tolerance)\\\\ $\\land$ SynchronizationConstraint\\\\\\hspace{.5cm}(scope.stimulus, tolerance)}\\\\\n\t\t\t\t\\hline\n\t\t\t\t\\makecell{single\\\\Occurrences} & scope & \\makecell{stimulus\\\\Synchronization} & tolerance & \\makecell{Input-\\\\SynchronizationConstraint\\\\\\hspace{.5cm}(scope, tolerance)\\\\ $\\land$ SynchronizationConstraint\\\\\\hspace{.5cm}(scope.stimulus, tolerance)}\\\\\n\t\t\t\t\\hline\n\t\t\t\\end{tabular}\n\t\t\t\\caption{SynchronizationTimingConstraint $\\Leftrightarrow$ TADL2 Constraints}\n\t\t\t\\label{ComparisonSynchronizationConstraints}\n\t\t\\end{table}\n\t\n\t\\subsubsection{SynchronizationPointConstraint}\n\t\tThe \\emph{SynchronizationPointConstraint} describes that a list of executables and a set of events or executable entities, defined in \\emph{sourceEec} and \\emph{sourceEvent}, must finish and occur before the executables and events in \\emph{targetEec} and \\emph{targetEvent} will start or occur. There is no counterpart to this in the TADL2 constraints.\n\t\t\n\t\\subsubsection{OffsetTimingConstraint}\n\t\tThe \\emph{OffsetTimingConstraint}, defined in the AUTOSAR Timing Extensions, is semantically the same as the TADL2 \\emph{DelayConstraint}, just some attributes are named differently. The \\emph{maximum} attribute of the \\emph{OffsetTimingConstraint} is named \\emph{upper} and the \\emph{minimum} attribute \\emph{lower} in the \\emph{DelayConstraint}.\n\t\t\n\t\\subsubsection{ExecutionOrderConstraint}\n\t\tThe goal of \\emph{ExecutionOrderConstraint} of the AUTOSAR Timing Extensions is used to describe the order of events or the execution order of executable entities, defined as \\emph{orderedElement} attribute. There is no constraint in TADL2 that describes exactly this, but if the \\emph{ExecutionOrderConstraint} is used to describe only the order of events, it can be described as \\\\[10pt]\n\t\t\\begin{math}\n\t\t\tOrderConstraint(orderedElement_1, orderedElement_2)\\\\\n\t\t\t\\land ... \\land\\\\\n\t\t\tOrderConstraint(orderedElement_{n-1}, orderedElement_n)\n\t\t\\end{math}\\\\[10pt]\n\t\tIf the \\emph{ExecutionOrderConstraint} is used for executable entities, each executable entity must be turned into one or more events to be described via TADL2 Constraints, depending on the other attributes. For example, if the attribute \\emph{executionOrderConstraintType} is set to \\emph{ordinaryEOC}, the start and finish points of the entities define the observed events.\n\t\t\n\t\\subsubsection{ExecutionTimeConstraint}\n\t\tThe idea behind the \\emph{ExecutionTimeConstraint} is similar in AUTOSAR and TADL2. Both describe the minimal and maximal allowed runtime of an executable entity, not counting interruptions. AUTOSARs \\emph{ExecutionTimeConstraint} is defined directly on an executable entity and the TADL2 constraint on events describing the \\emph{start}, \\emph{stop}, \\emph{preemption} and \\emph{resume} timestamps. Therefore the executable entity must be turned into these events to express the AUTOSAR \\emph{ExecutionTimeConstraint} via TADL2 constraints. The start and stop points of the executable must be turned into these events, the start and stop points of the interruptions must be turned into the events in the \\emph{preempt} and \\emph{resume} event sets. If external calls should be excluded from the runtime (which can be set in \\textit{AUTOSARs} \\emph{ExecutionTimeConstraint}), they must also be transferred into the \\emph{preempt} and \\emph{resume} event sets.\n", "meta": {"hexsha": "3fe53ab0ea4949262d571880b6d01927ff98abc6", "size": 96466, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "timingConstraints.tex", "max_stars_repo_name": "HendrikStreichhahn/Bachelorarbeit", "max_stars_repo_head_hexsha": "e6a346d88303518b693e4669c226fe99d8692ffa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "timingConstraints.tex", "max_issues_repo_name": "HendrikStreichhahn/Bachelorarbeit", "max_issues_repo_head_hexsha": "e6a346d88303518b693e4669c226fe99d8692ffa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "timingConstraints.tex", "max_forks_repo_name": "HendrikStreichhahn/Bachelorarbeit", "max_forks_repo_head_hexsha": "e6a346d88303518b693e4669c226fe99d8692ffa", "max_forks_repo_licenses": ["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.1943820225, "max_line_length": 1771, "alphanum_fraction": 0.6395206601, "num_tokens": 35584, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.19734484463400281}}
{"text": "\\documentclass[12pt,modern,tighten,times,apj]{aastex61}\n\n\\newcommand{\\sigv}{{\\ensuremath{\\langle \\sigma v \\rangle}}}\n\\newcommand{\\eg}{e.g.}\n\\newcommand{\\alp}{\\ensuremath{\\alpha}}\n\\newcommand{\\thsp}{\\thinspace}\n\\newcommand{\\cc}{\\ensuremath {\\mathrm{cm^{3}}}}\n\\newcommand{\\gcc}{\\ensuremath{\\mathrm{\\thsp g \\thsp cm^{-3}}}}\n\\newcommand{\\kel}{\\ensuremath{\\mathrm{\\thsp K}}}\n\\newcommand{\\gk}{\\ensuremath{\\mathrm{\\thsp GK}}}\n\\newcommand{\\calN}{\\ensuremath {\\mathcal N}}\n\\newcommand{\\calZ} {\\ensuremath {\\mathcal {Z}}}\n\\newcommand{\\isotope}[2]{\\ensuremath{\\mathrm{^{#2}#1}}}\n\\newcommand{\\ye}{\\ensuremath{Y_{e}}}\n\n\n\\begin{document}\n\n\\title{XNet}\n\n\\section{Introduction}\n\nRepresented numerically as a system of first order differential equations, the nuclear reaction network has sink and source terms representing each of the many nuclear reactions involved. \nXNet is group of routines, written in FORTRAN95, designed to solve arbitrary nuclear reaction networks of astrophysical interest. \nTo explain the functionality of XNet, we begin by briefly outlining the sets of reactions we must solve to evolve the nuclear composition. \nTo this end, we present a brief overview of the thermonuclear reaction rates of interest and how these rates are assembled into the differential equations that must ultimately be solved.\nFor more detailed information, we refer the reader to several textbooks covering this subjects \\cite{Clay83,RoRo88,Arne96}. \nWe follow this with a discussion of the solvers included within XNet.\nBecause the rate equations in nucleosynthetic applications involve a wide range of timescales, implicit methods have proven mandatory, leading to the need to solve matrix equations. \nEfforts to improve the performance of such rate equation methods are focused on efficient solution of these matrix equations, in particular by making best use of the sparseness of these matrices, and finding methods that require less frequent matrix solutions. \n\n\\section{Reaction Rates}\\label{sect:reacrate}\n\nThere are a large number of types of nuclear reactions which are of astrophysical interest, most of which are included in XNet. \nIn addition to the emission or absorption of nuclei and nucleons, nuclear reactions can involve the emission or absorption of photons ($\\gamma$-rays) and leptons (electrons, neutrinos, and their anti-particles). \nAs a result, nuclear reactions involve three of the four fundamental forces, the nuclear strong, electromagnetic and nuclear weak forces. \nReactions involving leptons (termed weak interactions) proceed much more slowly than those involving only nucleons and photons; however, these reactions are important because only weak interactions can change the global ratio of protons to neutrons.\n\nThe most basic piece of information about any nuclear reaction is the nuclear cross section. \nThe cross section for a reaction between target $j$ and projectile $k$ is defined by \n\\begin{equation}\n \\sigma = {\\rm{number\\ of\\ reactions\\ target^{-1} sec^{-1}} \\over\n {flux\\ of\\ incoming\\ projectiles}} = {{r/n_j} \\over {n_k v}}. \n \\label{eq:sigma}\n\\end{equation}\nThe second equality holds when the relative velocity between targets of number density $n_j$ and projectiles of number density $n_k$ is constant and has the value $v$. \nThen $r$, the number of reactions per $cm^{-3}$\\ and sec, can be expressed as $r=\\sigma v n_j n_k$. \nMore generally, the targets and projectiles have distributions of velocities, in which case $r$ is given by\n\\begin{equation}\n r_{j,k}=\\int \\sigma (\\vert \\vec v_j -\\vec v_k\\vert) \\vert \\vec v_j \n -\\vec v_k\\vert d^3 n_j d^3 n_k.\n \\label{eq:rate}\n\\end{equation}\nThe evaluation of this integral depends on the types of particles and distributions which are involved. For nuclei $j$ and $k$ in an astrophysical plasma, Maxwell-Boltzmann statistics generally apply; thus,\n\\begin{equation}\n d^3n=n ({{m} \\over {2\\pi k_B T}})^{3/2} \\exp (-{{mv^2} \\over {2 k_B T}}) d^3v,\n\\end{equation}\nallowing $n_j$ and $n_k$ to be moved outside of the integral. \nEq.~\\ref{eq:rate} can then be written as $r_{j,k}=\\sigv_{j,k} n_j n_k$, where \\sigv\\ is the velocity integrated cross section. \nEquivalently, one can express the reaction rate in terms of a mean lifetime of particle $j$ against destruction by particle $k$, \n\\begin{equation}\n \\tau_{k}(j)= {1 \\over {\\sigv_{j,k} n_{k}}}\n \\label{eq:tau}\n\\end{equation}\n\nFor thermonuclear reactions, these integrated cross sections have the form \\cite{Clay83,FoCZ67}\n\\begin{equation}\n \\langle j,k \\rangle \\equiv \\sigv_{j,k}= ({8 \\over {\\mu \\pi}})^{1/2} \n (k_B T)^{-3/2} \\int_0 ^\\infty E \\sigma (E) {\\rm exp}(-E/k_B T) dE, \n \\label{eq:sigv}\n\\end{equation}\nwhere $\\mu$ denotes the reduced mass of the target-projectile system, $E$ the center of mass energy, $T$ the temperature and $k_{B}$ is Boltzmann's constant.\n\nExperimental measurements and theoretical predictions for these reaction rates provide the data input necessary to study astrophysical thermonuclear kinetics. \nWhile detailed discussion of individual rates is beyond the scope of this article, the interested reader is directed to the following reviews, in this volume and elsewhere. \nExperimental nuclear rates and the methodology for measuring them have been reviewed in detail by \\cite{RoRo88,KaTW98}. \nA number of articles in this volume review the charged particle reaction rates which are important in the Sun \\cite{HaPR04}, in later stages of stellar evolution \\cite{BuBa04}, and for explosive burning on compact objects \\cite{AnSB04,HeJI04,ReSc04}. \nExperimental neutron capture cross sections are also summarized \\cite{KaMe04,BaKa00}. \nTheoretical modeling of these rates \\cite{RaDe04,MaNW04} is vitally important to provide the many rates for which experimental information is incomplete or non-existant. \nBeyond measuring or calculating these rates, progress in nuclear astrophysics also requires the compilation and dissemination (in a usable form) of this hard-earned nuclear data to the broadest astrophysical community \\cite{CaFo88,GRSD04,Smit03}. \n\nWhen particle $k$ in Eq.~\\ref{eq:rate} is a photon, the distribution $d^3n_k$ is given by the Plank distribution, \n\\begin{equation}\n d^3n_{\\gamma} = {{8 \\pi} \\over {c^3 h^3}} {{E_{\\gamma}^2} \\over\n {\\exp \\left(E_{\\gamma} /k_B T\\right)-1}} dE_{\\gamma} \\ .\n\\end{equation}\nFurthermore, the relative velocity is always $c$ and thus the integral is separable, simplifying to \n\\begin{equation}\n r_j = {{\\int d^3n_j}\\over {\\pi ^2 (c \\hbar )^3}} \\int_0 ^\\infty {{c \n \\sigma(E_\\gamma ) E_{\\gamma}^2} \\over {{\\rm exp}(E_\\gamma /k_B T) -1}} dE_\n \\gamma \\equiv \\lambda_{j,\\gamma} (T) n_j. \n \\label{eq:phrate}\n\\end{equation}\nIn practice it is not usually necessary to directly evaluate the photodisintegration cross sections (see, however, \\cite{MoZU04} for exceptions), because they can be expressed by detailed balance in terms of the capture cross sections for the inverse reaction, $l+m\\rightarrow j+\\gamma$ \\cite{FoCZ67} .\n\\begin{equation}\n \\lambda_{j,\\gamma} (T)= ({{G_l G_m} \\over G_j}) ({{A_l A_m} \\over A_j})\n ^{3/2} ({{m_u k_B T} \\over {2\\pi \\hbar^2}})^{3/2} \\langle l,m \\rangle \n \\exp (-Q_{lm}/k_B T).\n \\label{eq:detbal}\n\\end{equation}\nThis expression depends on the partition functions, $G_{k}=\\sum_i (2J_i+1) \\exp (-E_i/k_B T)$ (which account for the populations of the excited states of the nucleus), the mass numbers, $A$, the temperature $T$, the inverse reaction rate $\\langle l,m \\rangle$, and the reaction $Q$-value (the energy released by the reaction), $Q_{lm}=(m_l+m_m-m_j) c^2$. \nSince photodisintegrations are endoergic, their rates are vanishingly small until sufficient photons exist in the high energy tail of the Planck distribution with energies $> Q_{{lm}}$. \nAs a rule of thumb this requires $T$$\\approx$$Q_{lm}/30 k_{B}$.\n\nIn practice, these experimental and theoretical reaction rates are determined for bare nuclei, while in astrophysical plasmas, these reactions occur among a background of other nuclei and electrons. \nAs a result of this background, the reacting nuclei experience a Coulomb repulsion modified from \nthat of bare nuclei. \nFor high densities and/or low temperatures, the effects of this screening of reactions becomes very important. \nUnder most conditions (with non-vanishing temperatures) the generalized reaction rate integral can be separated into the traditional expression without screening [Eq.~\\ref{eq:sigv}] and a screening factor, \n\\begin{equation}\n \\langle j,k \\rangle^*=f_{scr}(Z_j,Z_k,\\rho,T,n_i) \\langle j,k \\rangle. \n \\label{eq:screen}\n\\end{equation}\nThis screening factor is dependent on the charge of the involved particles, the density, temperature, and the composition of the plasma. For more details on the form of $f_{scr}$, see, \\eg, \\cite{Salp54,DeGC73,Ichi93,BrSa97}. \nAt high densities and low temperatures screening factors can enhance reactions by many orders of magnitude and lead to {\\em pycnonuclear ignition}.\nIn the extreme case of very low temperatures, where reactions are only possible via ground state oscillations of the nuclei in a Coulomb lattice, Eq.~\\ref{eq:screen} breaks down, because it was derived under the assumption of a Boltzmann distribution \\cite{SaVa69,IcKi99}.\n\nIn stellar plasmas, target nuclei also do not exist solely in their ground states. \nThis complicates the rate expression in Eq.~\\ref{eq:sigv}, which now must take into account the cross sections for capture out of the different excited states and properly weight them according to their probability of occurrence in the ensemble of target nuclei. \nBecause the timescales for transitions between excited states of a nucleus are typically much shorter than other reaction timescales, it is usually valid to assume that the nuclei are internally equilibrated and a given excited state is populated in the ensemble by the usual Boltzmann factor $\\propto e^{-E/k_BT}$, where $E$ now is the excitation energy of that state. \nFrom this, one may derive a factor, called the {\\em stellar enhancement factor} (SEF), to correct the ground-state reaction rate for the population of excited states (see, e.g., \\cite{RaTh00,AARD99}).\n\nInteresting complications to this prescription arise when the internal\nequilibration timescale for a nucleus exceeds the other reaction\ntimescales in the problem. This usually occurs when a large spin\ndifference between the ground state of an isotope and its first excited state\nprevents them from communicating directly via internal transitions.\nThe isotope $^{26}$Al is the prototypical example, with a ground and isomeric state of spin and parity $5^+$ and $0^+$, respectively. When these two states equilibrate, it is not through a direct transition between the states--that simply takes too long. Rather the equilibration occurs\nthrough transitions to higher-lying levels that communicate effectively\nwith both levels. This problem has been studied in detail (e.g.,\n\\cite{WaFo80}), and the most straightforward way of dealing with this is\nto assume that the higher-lying levels are in a steady state since their\ndestruction timescales are so rapid. When this is done, the population of\nthe target nucleus break up into two ensembles, one tied to the ground\nstate and one tied to the isomer \\cite{GuMe01}. These may then be treated\nas separate species in the network, each with its own rates to and from\nother isotopes and with effective rates for transitions between the two\nensembles. Fortunately, the number of nuclei requiring such treatment is\nsmall and does not add much computational burden to running the nuclear\nreaction network.\n\nA procedure similar to that used to derive Eq.~\\ref{eq:phrate} applies to captures of electrons by nuclei. Because the electron is 1836 times less massive than a \nnucleon, the velocity of the nucleus $j$ in the center of mass system is \nnegligible in comparison to the electron velocity ($\\vert \\vec v_j- \\vec \nv_e \\vert \\approx \\vert \\vec v_e \\vert$). In the neutral, completely \nionized plasmas typical of the astrophysical sites of nucleosynthesis, the \nelectron number density, $n_{e}$, is equal to the total density of protons \nin nuclei, $\\sum_i Z_i n_i$. However in many of these astrophysical \nsettings the electrons are at least partially degenerate, therefore the \nelectron distribution cannot be assumed to be Maxwellian. Instead the \ncapture cross section may be integrated over a Boltzmann, partially \ndegenerate, or degenerate Fermi distribution of electrons, depending on the \nastrophysical conditions. The resulting electron capture rates are \nfunctions of $T$ and $n_e$, $r_j=\\lambda_{j,e} (T,n_e) n_j.$ Similar equations apply for the capture of positrons which are in thermal equilibrium with photons, electrons, and nuclei. Electron and positron capture calculations have been performed for a large variety of nuclei with mass numbers between A=20 and A=100 (see \\cite{LiMF04} for more information). \nFor normal decays, like beta or alpha decays, with a characteristic half-life\n$\\tau_{1/2}$, Eq.~\\ref{eq:phrate} also applies, with the\ndecay constant $\\lambda_j=\\ln 2/\\tau_{1/2}$. In addition to innumerable\nexperimental half-life determinations, beta-decay half-lives for a wide range of unstable nuclei have been predicted (see \\cite{Borz04,MoNK97}).\n\nEven though the size of the neutrino scattering cross section on nuclei and electrons is very small, at high densities ($\\rho \\sim 10^{13} \\gcc$), enough scattering events occur to thermalize the neutrino distribution. Under such conditions the inverse process to electron capture (neutrino capture) can occur in significant numbers and the neutrino capture rate can be expressed in a form similar to Eqs.~\\ref{eq:phrate} by integrating over the thermal \nneutrino distribution (e.g. \\cite{FuMe95}). Inelastic neutrino scattering \non nuclei can also be expressed in this form. The latter can cause \nparticle emission, similar to photodisintegration. See \\cite{BuRe04,Brue85,Voge04} for more complete discussion of the interactions of neutrinos with matter. The calculation of these rates \ncan be further complicated by the neutrinos being out of thermal \nequilibrium with the local environment. When thermal equilibrium among \nneutrinos was established at a different location, then the neutrino \ndistribution might be characterized by a chemical potential and a \ntemperature different from the local values. Otherwise, the neutrino \ndistribution must be evolved in detail (see, \\eg, \\cite{MeMe99}). \n\n\\subsection{Screening}\n\nWhile much of the literature on the screening of nuclear reactions has focused on the screening of fusion reactions, this same physics is important when reaction pairs have equilibrated, be it local quasi-equilibrium (QSE) or global Nuclear Statistical Equilibrium (NSE) \\citep{HiTh96,BrGa99}.\nIf equilibrium abundances calculated from thermonuclear reaction networks using these fusion rates are to match the abundances calculated from equilibrium expressions, the relevant screening factors must be calculated consistently.\nUsing the velocity integrated cross section $\\langle \\sigma v \\rangle$, the screened cross section for the reaction of nuclei $i$ and $j$ is defined in terms of the unscreened cross section by\n\\begin{equation}\n{\\langle \\sigma v \\rangle}_{screened\\ nuclei} = \\exp(H_{ij}) {\\langle \n\\sigma v \\rangle}_{bare\\ nuclei} \\ ,\n\\end{equation}\nwhere $\\exp(H_{ij})$ is termed the screening enhancement factor, sometimes denoted $f_{scr}$.\n \nScreening enters the equilibrium expressions for NSE or QSE as a modification of the nuclear binding energy, $H(Z)$, that is the difference in the Helmholtz free energy due to screening in assembling the nucleus $^AZ$.\nSome screening laws, like Salpeter's original weak and strong screening laws \\citep{Salp54}, are derived analytically from this same change in the free energy \\citep[see also][]{DeGrCo73}. \nGiven an expression for the change in free energy $H(Z)$, the screening factor for reaction rates can be computed from \n\\begin{equation}\nH_{ij} = (H(Z_i+Z_j)-H(Z_i)-H(Z_j))/k_B T.\n\\end{equation} \nOther screening laws are the product of fits to Monte Carlo plasma simulations \\citep[see, for example,]{OgIyIc91}\nWithin statistical uncertainties, these alternative methods produce consistent results \\citep[see, for example,][]{DeSl99,Rose92}.\n\nPreviously, \\citet{HiTh96} had constructed the NSE screening term sequentially from $H_{p,\\gamma}$ terms to maintain consistency with the nuclear reaction network results, whereas \\citet{BrGa99} computed NSE screening terms from global Coulomb corrections using various moments in powers of $Z$ over the NSE abundance distribution. \nWhere $H_{p,\\gamma} = (H(Z+1)-H(Z)-H(1))/k_B T$, these results should be consistent. (Note $H(1)=0$, there is no reaction that builds a proton.) \n\nThe necessity of this functional form for screening comes from the requirement that the change in the difference in the binding energy due to screening between two species must be independent of the reaction pathway. \nFor example, the abundances of $^AZ$ and $^{(A+4)}(Z+2)$ can be kept in equilibrium by $(\\alpha,\\gamma)$ and it reverse or by the series $(p,\\gamma) (p,\\gamma) (n,\\gamma) (n,\\gamma)$ and their reverses. \nWhen constructed from $H(Z)$, this is requirement is manifestly met, $\\Delta BE = H(Z+2)-H(Z)$.\nWithout this, you can not define a unique relation for the equilibrium screening correction that covers all of the reaction paths that are simultaneously in equilibrium between $^AZ$ and $^{(A+4)}(Z+2)$.\nFurther note that because the reaction pathways $(p,\\gamma) (p,\\gamma) (n,\\gamma) (n,\\gamma)$ and $(p,\\gamma) (n,\\gamma) (p,\\gamma) (n,\\gamma)$ are simultaneously in equilibrium, H(Z) can not depend on A.\n%for example, $H_{\\alpha,\\gamma}$ = $H_{p,\\gamma} + H_{p,\\gamma} + H_{n,\\gamma} + H_{n,\\gamma} = H_{p,\\gamma} + H_{n,\\gamma} + H_{p,\\gamma} + H_{n,\\gamma}$, etc. \n\nFor three reactant reactions, the screening factor for reaction rates is conventionally calculated as $H_{ijk} = H_{ij} + H_{(i+j)k}$ because three particle reactions of importance in astrophysics are generally sequential pairs of reactions where a short-lived intermediate nucleus $(i+j)$ is formed by the first pair of reactants and captures the third reactant before it decays.\nTo remain consistent with the requirements of equilibrium screening, we must construct $H_{ijk}$ from $H$.\nIn general, this approach should work as well for astrophysical 3 reactant reactions as for 2. \n\\begin{eqnarray}\nH(Z_i+Z_j+Z_k) &-&H(Z_i) - H(Z_j) - H(Z_k) \\\\\n&=& \\left(H(Z_i+Z_j+Z_k) - H(Z_i+Z_j) - H(Z_k)\\right) \\\\\n&+& \\left(H(Z_i+Z_j) - H(Z_i) - H(Z_j)\\right) \\\\\n&=& H_{(i+j)k} + H_{ij} \\\\\n&=& H_{ijk} \\ . \n\\end{eqnarray}\nThus the screening factors of 3 reactant reactions can be adequately calculated from the change in free energy. \n\n\\subsubsection{Weak Screening}\n\nFor weak screening, Graboske, Dewitt, Grossman \\& Cooper (1973; ApJ 181 457), give $H_{12}$ in terms of charge independent parameter $\\Lambda_0$, an average charge parameter $\\tilde z$ which depends on the abundances of all nuclear species, and the ion charges $Z_i$ and $Z_j$ as \n\\begin{equation}\nH_{ij} = Z_i Z_j \\tilde{z} \\Lambda_0. \n\\end{equation} \n$\\Lambda_0$ and $\\tilde z$ are defined in \\citet{DeGrCo73}. \nThis expression approaches the classical Debye-H\\\"uckel case as the electrons become non-degenerate. \nChoosing the corresponding \n\\begin{equation}\nH(Z) = {1\\over2} Z^2 \\tilde{z} \\Lambda_0 \\ ,\n\\end{equation} \nthen \n\\begin{equation}\nH(Z_i+Z_j) - H(Z_i) - H(Z_j) = {1\\over2}\\left((Z_i+Z_j)^2 - Z_i^2 - Z_j^2\\right) \\tilde{z} \\Lambda_0 = Z_i Z_j \\tilde{z} \\Lambda_0 = H_{ij}\n\\end{equation} \nThus the equivalence of the approaches does indeed hold for two-reactant reactions. \nFor three-reactant reactions, \n\\begin{equation}\nH_{ijk} = H_{ij} + H_{(i+j)k} = Z_i Z_j \\tilde{z} \\Lambda_0 + (Z_i+Z_j) Z_k \\tilde{z} \\Lambda_0 = (Z_i Z_j + Z_i Z_k + Z_j Z_k) \\tilde{z} \\Lambda_0 \\ .\n\\end{equation}\nIn terms of H(Z)\n\\begin{eqnarray}\nH(Z_i+Z_j+Z_k) &-&H(Z_i) - H(Z_j) - H(Z_k) \\\\\n&=& {1\\over2}\\left((Z_i+Z_j+Z_k)^2 - Z_i^2 - Z_j^2- Z_k^2\\right) \\tilde{z} \\Lambda_0 \\\\\n&=& (Z_i Z_j + Z_i Z_k + Z_j Z_k) \\tilde{z} \\Lambda_0 = H_{ijk} \\ , \n\\end{eqnarray}\nthus the equivalence of the approaches also holds for three-reactant reactions. \n\n\\subsubsection{Intermediate Screening}\n\nFor intermediate screening, \\citet{DeGrCo73} give $H_{12}$ in terms of charge independent parameter $\\Lambda_0$, and several average charge parameters $\\tilde z$, $\\bar z$, and $\\langle z^{1.58}\\rangle$, which depends on the abundances of all nuclear species, and the ion charges $Z_i$ and $Z_j$ as \n\\begin{equation}\nH_{ij} = 0.380 {\\langle z^{1.58}\\rangle \\over \\tilde{z}^{0.58}\\bar{z}^{0.28}} \\Lambda_0^{0.860} \\left[(Z_i + Z_j)^{1.860} - Z_i^{1.860} - Z_j^{1.860}\\right]. \n\\end{equation} \nChoosing the corresponding \n\\begin{equation}H(Z) = 0.380 {\\langle z^{1.58}\\rangle \\over \\tilde{z}^{0.58}\\bar{z}^{0.28}} \\Lambda_0^{0.860} Z^{1.860}, \\end{equation} then \n\\begin{eqnarray}\nH(Z_i+Z_j) &-& H(Z_i) - H(Z_j) \\\\\n&=& 0.380 {\\langle z^{1.58}\\rangle \\over \\tilde{z}^{0.58}\\bar{z}^{0.28}} \\Lambda_0^{0.860} \\left[(Z_i + Z_j)^{1.860} - Z_i^{1.860} - Z_j^{1.860}\\right]= H_{ij}\n\\end{eqnarray} \nThus the equivalence of the approaches does indeed hold for two-reactant reactions. \nFor three-reactant reactions, \n\\begin{eqnarray}\nH_{ijk} &=& H_{ij} + H_{(i+j)k} \\\\\n&=& 0.380 {\\langle z^{1.58}\\rangle \\over \\tilde{z}^{0.58}\\bar{z}^{0.28}} \\Lambda_0^{0.860} \\left[(Z_i + Z_j)^{1.860} - Z_i^{1.860} - Z_j^{1.860}\\right] \\\\\n&+& 0.380 {\\langle z^{1.58}\\rangle \\over \\tilde{z}^{0.58}\\bar{z}^{0.28}} \\Lambda_0^{0.860} \\left[(Z_i + Z_j+Z_k)^{1.860} - (Z_i + Z_j)^{1.860} - Z_k^{1.860}\\right] \\\\\n&=& 0.380 {\\langle z^{1.58}\\rangle \\over \\tilde{z}^{0.58}\\bar{z}^{0.28}} \\Lambda_0^{0.860} \\left[(Z_i + Z_j+Z_k)^{1.860} - Z_i^{1.860} - Z_j^{1.860} - Z_k^{1.860} \\right]\n\\ .\n\\end{eqnarray}\nIn terms of H(Z)\n\\begin{eqnarray}\nH(Z_i+Z_j+Z_k) &-& H(Z_i) - H(Z_j) - H(Z_k) \\\\\n&=& 0.380 {\\langle z^{1.58}\\rangle \\over \\tilde{z}^{0.58}\\bar{z}^{0.28}} \\Lambda_0^{0.860} \\left[(Z_i + Z_j+Z_k)^{1.860} - Z_i^{1.860} - Z_j^{1.860} - Z_k^{1.860} \\right]\\\\\n&=& H_{ijk} \\ , \n\\end{eqnarray}\nthus the equivalence of the approaches also holds for three-reactant reactions.\n\n\\subsubsection{Strong Screening} \n\n\n\n\\section{Solvers}\n\nThe large number of reaction types discussed in \\S \\ref{sect:reacrate} can \nbe divided into 3 functional categories based on the number of reactants \nwhich are nuclei. The reactions involving a single nucleus, which include \ndecays, electron and positron captures, photodisintegrations, and neutrino \ninduced reactions, depend on the number density of only the target species. \nFor reaction involving two nuclei, the reaction rate depends on the number \ndensities of both target and projectile nuclei. There are also a few \nimportant three-particle process (like the triple-\\alp\\ process, see \\S \\ref{sect:hyb}) which are commonly successive captures with an \nintermediate unstable target (see, \\eg, \\cite{NoTM85,GoWT95}). Using an \nequilibrium abundance for the unstable intermediate, the contributions of \nthese reactions are commonly written in the form of a three-particle \nprocesses, depending on a trio of number densities. Grouping reactions by \nthese 3 functional categories, the time derivatives of the number densities \nof each nuclear species in an astrophysical plasma can be written in terms \nof the reaction rates, $r$, as\n\\begin{equation}\n \\left. {{\\partial n_i} \\over {\\partial t}} \\right|_{\\rho =const}= \\sum_j \n \\calN^i _j r_j + \\sum_{j,k} \\calN^i _{j,k} r_{j,k} + \\sum_{j,k,l} \n \\calN^i _{j,k,l} r_{j,k,l},\n \\label{eq:ndot}\n\\end{equation}\nwhere the three sums are over reactions which produce or destroy a nucleus \nof species $i$ with 1, 2 \\& 3 reactant nuclei, respectively. The \\calN\\ s\nprovide for proper accounting of numbers of nuclei and are given by: \n$\\calN^i_j = N_i$, $\\calN^i_{j,k} = N_i / \\prod_{m=1}^{n_{j,k}} | N_{m} |! \n$, and $\\calN^i_{j,k,l} = N_i / \\prod_{m=1}^{n_{j,k,l}} |N_{m}|!$. The $N_i's$ \ncan be positive or negative numbers that specify how many particles of \nspecies $i$ are created or destroyed in a reaction, while the denominators, \nincluding factorials, run over the $n_{j,k}$ or $n_{j,k,l}$ different species destroyed in the reaction and avoid double counting of the number of reactions when identical particles react with each other (for example in the \\isotope{C}{12} + \\isotope{C}{12} or the triple-\\alp\\ reactions; for details see \\cite{FoCZ67}).\n\nIn addition to nuclear reactions, expansion or contraction of the plasma \ncan also produce changes in the number densities $n_i$. To separate the \nnuclear changes in composition from these hydrodynamic effects, the nuclear abundance $Y_i =n_i/\\rho N_A$, where $N_{A}$ is Avogadro's number, is commonly used. For a nucleus with atomic weight $A_i$, $A_iY_i$ \nrepresents the mass fraction of this nucleus, therefore $\\sum A_iY_i=1$. \nLikewise, the equation of charge conservation becomes $\\sum Z_i Y_i = Y_e$, \nwhere $\\ye (= n_e /\\rho N_A)$ is the electron abundance (also termed the electron fraction). By recasting Eq.~\\ref{eq:ndot} in terms of nuclear abundances $Y_i$, a set of ordinary differential equations \nfor the evolution of $\\dot Y_i$ results which depends only on nuclear \nreactions. In terms of the reaction cross sections introduced in \\S \n\\ref{sect:reacrate}, this reaction network is described by the following \nset of differential equations\n%\\begin{eqnarray}\n% \\dot Y_i & = & \\sum_j \\calN^i _j \\lambda_j Y_j + \\sum_{j,k} \\calN^i _{j,k} \n% \\rho N_A \\langle j,k \\rangle Y_j Y_k \\nonumber \\\\ \n% & + & \\sum_{j,k,l} \\calN^i _{j,k,l} \\rho^2 N_A^2 \\langle j,k,l \\rangle \n%\tY_j Y_k Y_l. \n% \\label{eq:ydot}\n%\\end{eqnarray}\n\\begin{equation}\n \\dot Y_i = \\sum_j \\calN^i _j \\lambda_j Y_j + \\sum_{j,k} \\calN^i _{j,k} \n\\rho N_A \\langle j,k \\rangle Y_j Y_k + \\sum_{j,k,l} \\calN^i _{j,k,l} \\rho^2 N_A^2 \\langle j,k,l \\rangle Y_j Y_k Y_l. \\label{eq:ydot}\n\\end{equation}\n\nIn principle, the initial value problem presented by the nuclear reaction network \ncan be solved by any of a large number of methods discussed in the \nliterature. However the physical nature of the problem, reflected in the \n$\\lambda$'s and \\sigv 's, greatly restricts the optimal choice. The large \nnumber of reactions display a wide range of reaction timescales, $\\tau$ \n(see Eq.~\\ref{eq:tau}). Numerical systems whose solutions depend on a wide range of timescales are termed \\emph{stiff}. Gear \\cite{Gear71} demonstrated that \neven a single equation can be stiff if it has both rapidly and slowly varying \ncomponents. Practically, stiffness occurs when the limitation of the \ntimestep size is due to numerical stability rather than accuracy. A more \nrigorous definition \\cite{Lamb80} is that a system of equations $\\vec{\\dot Y}\n(\\vec Y)$ is stiff if the eigenvalues $\\lambda_{j}$ of the Jacobian \n$\\partial \\vec{\\dot Y} / \\partial \\vec Y$ obey the criterion that for negative $\\Re(\\lambda_{j})$ (the real part of the eigenvalues $\\lambda_j$)\n\\begin{equation}\n {\\mathcal S} = {{max |\\Re(\\lambda_{j})|} \\over {min |\\Re(\\lambda_{j})|}} \n \\gg 1 \n \\label{eq:lambdastiff}\n\\end{equation}\nfor $j=1,\\cdots,N$. As we will explain in this section, $\\mathcal S > 10^{15}$ is not uncommon in astrophysics.\n\nAstrophysical calculations of nucleosynthesis belong to the general field of\nreactive flows, and therefore share some characteristics with related\nterrestrial fields. In particular, chemical kinetics, the study of the\nevolution of chemical abundances, is an important part of atmospheric and\ncombustion physics and produces sets of equations much like Eq.~\\ref{eq:ndot}\n(see \\cite{OrBo01} for a through introduction). These chemical kinetics systems\nare known for their stiffness and a great deal of effort has been expended on\ndeveloping methods to solve these equations. Many of the considerations for\nthe choice of solution method for chemical kinetics also \napply to thermonuclear kinetics. In both cases, temporal integration of\nthe reaction rate equations is broken up into short intervals because of the\nneed to update the hydrodynamics variables. This favors one step, self\nstarting algorithms. Because abundances must be tracked for a large number of\ncomputational cells (hundreds to thousands for one dimensional models,\nmillions to billions for the coming generation of three dimensional models), memory storage concerns favor low order methods since they don't require the storage of as much data from prior steps. In any event, both the errors in fluid dynamics and in the reaction rates are typically a few percent or more, so the greater precision of these higher order methods often does not result in greater accuracy. Note that these statements do not in general apply to calculations of Big Bang nucleosynthesis (at least those that assume homogeniety). As a result quite different methods are employed in these calculations \\cite{FiOl04}\n\nBecause of the wide range in timescales between strong, electromagnetic and \nweak reactions, nuclear reaction networks are extraordinarily stiff. PP chain\nnucleosynthesis, responsible for the energy output of the Sun, offers an\nexcellent example of the difficulties. The first reaction of the PP1 chain is\n$\\isotope{H}{1}(p,e^{+} \\nu) \\isotope{H}{2}$, the fusion of two protons to form\ndeuterium. This is a weak reaction, requiring the conversion of a proton into\na neutron, and releasing a positron and a neutrino. As a result, the reaction\ntimescale $\\tau_{p}(\\isotope{H}{1})$ is very long, billions of years for\nconditions like those in the solar interior. The second reaction of the PP1\nchain is the capture of a proton on the newly formed deuteron,\n$\\isotope{H}{2}(p,\\gamma) \\isotope{He}{3}$. For conditions like those in the solar\ninterior, the characteristic timescale, $\\tau_{p}(\\isotope{H}{2})$ is a few\nseconds. Thus the timescales for two of the most important reactions for\nhydrogen burning in stars like our Sun differ by more than 17 orders of\nmagnitude (see \\cite{Clay83,HaPR04} for a more complete discussion of the PP chain). \nThis disparity results not from a lack of \\isotope{H}{1} + \\isotope{H}{1} collisions (which occur at a rate $Y(\\isotope{H}{1})/ Y(\\isotope{H}{2}) \\sim 10^{17}$ times more often than \\isotope{H}{1} + \\isotope{H}{2} collisions), but from the rarity of the transformation of a proton to a neutron. While the presence of weak reactions\namong the dominant energy producing reactions is unique to hydrogen burning,\nmost nucleosynthesis calculations are similarly stiff, in part because of the\nneed to include weak interactions but also the potential for neutron capture\nreactions, which occur very rapidly even at low temperature, following any\nrelease of free neutrons. The nature of the nuclear reaction network equations has thus far limited the astrophysical usefulness of the most sophisticated methods to solve stiff equations developed for chemical kinetics. \n\n\\subsection{Euler Methods}\n\nFor a set of nuclear abundances $\\vec Y$, one can calculate the time \nderivatives of the abundances, $\\dot {\\vec Y}$ using Eq.~\\ref{eq:ydot}. The\ndesired solution is the abundance at a future time, $\\vec Y(t+\\Delta t)$,\nwhere $\\Delta t$ is the network timestep. For simplicity, most past and present nucleosynthesis calculations use the simple finite difference prescription\n\\begin{equation}\n\t{{\\vec Y(t+\\Delta t)- \\vec Y(t)} \\over {\\Delta t}} = (1-\\Theta) \\dot \n\t{\\vec Y}(t+\\Delta t) + \\Theta \\dot {\\vec Y}(t).\n \\label{eq:deriv}\n\\end{equation}\nThis choice is also supported by the advantages of coupling low order, single step methods with hydrodynamics. With $\\Theta=1$, Eq.~\\ref{eq:deriv} becomes the explicit Euler method \nwhile for $\\Theta=0$ it is the implicit backward Euler method, both of \nwhich are first order accurate. For $\\Theta=1/2$, Eq.~\\ref{eq:deriv} is \nthe semi-implicit trapezoidal method, which is second order accurate. For \nthe stiff set of non-linear differential equations which form most nuclear reaction \nnetworks, a fully implicit treatment is generally most successful \n\\cite{ArTr69}, though the trapezoidal method has been used in Big Bang \nnucleosynthesis calculations \\cite{Wago73}, where coupling to hydrodynamics \nis less important. Solving the fully implicit version of Eq.~\\ref{eq:deriv} \nis equivalent to finding the zeros of the set of equations\n\\begin{equation}\n \\vec \\calZ(t+\\Delta t)\\equiv {{\\vec Y(t+\\Delta t)- \\vec Y(t)} \\over \n {\\Delta t}} - \\dot {\\vec Y}(t+\\Delta t) =0 \\ .\n\t\\label{eq:zer}\n\\end{equation}\nThis is done using the Newton-Raphson method (see, \\eg, \\cite{NumRec}), \nwhich is based on the Taylor series expansion of $\\vec \\calZ(t+\\Delta t)$, \nwith the trial change in abundances given by\n\\begin{equation}\n\t\\Delta \\vec Y = \\left( \\partial \\vec \\calZ (t+\\Delta t) \\over \n\t\\partial \\vec Y (t+\\Delta t) \\right)^{-1} \\vec \\calZ \\ ,\n\t\\label{eq:dely}\n\\end{equation}\nwhere $\\partial \\vec \\calZ / \\partial \\vec Y $ is the Jacobian of $\\vec \n\\calZ$. \n\nHistorically \\cite{ArTr69} and in some modern applications (see, \\eg, \\cite{Khok96}), each timestep consists of only a single application of the procedure outlined in Eqs.~\\ref{eq:zer} \\& \\ref{eq:dely}. This semi-implicit backward Euler method has the advantage of a relatively small and predictable number of matrix solutions, but there are only heuristic checks that the chosen timestep results in a stable or accurate solution. In fully implicit backward Euler schemes, iteration using the procedure of Eqs.~\\ref{eq:zer} \\& \\ref{eq:dely} continues until both $\\Delta \\vec Y$ and $\\vec \\calZ$ are below some tolerance, providing a measure of the stability and accuracy. If this convergence does not occur within a reasonable number of iterations, the timestep is subdivided into smaller intervals until a converged solution can be achieved, allowing the fully implicit backward Euler integration to respond to instability or inaccuracy in a way that is impossible with the semi-implicit backward Euler approach. Higher order methods allow better estimates of the truncation error by comparing the solutions of different order schemes and sub-dividing the timestep if these errors are too large.\n\n\\subsection{Bader-Deuflhard}\n\nIn the variable order Bader-Deuflhard method, the timestep is divided into m substeps with $\\delta t = \\Delta t /m$ and the matrix\n\\begin{equation}\n{\\mathcal A} = {\\mathcal I} - {{\\partial \\vec{\\dot Y}} \\over {\\partial \\vec Y}}\n\\end{equation}\n\nFor the first substep, the matrix equation\n\\begin{equation}\n{\\mathcal A} \\cdot \\Delta {\\vec Y}_0 = \\delta t \\vec {\\dot Y_0}\n\\end{equation}\nis solved and abundance is iterated ${\\vec Y}_1 = {\\vec Y}_0 + \\delta {\\vec Y}_0$. \nFor substeps $k = 1$ to $k=m-1$, the equation \n\\begin{equation}\n{\\mathcal A} \\cdot x = \\delta t \\vec {\\dot Y_k} - \\Delta {\\vec Y}_{k-1}\n\\end{equation}\nis solved, with the abundance updated as ${\\vec Y}_{k+1} = {\\vec Y}_{k} + \\delta {\\vec Y}_{k}$ where $\\delta {\\vec Y}_{k} = \\delta {\\vec Y}_{k-1} + 2 x$.\nFor the last substep (k = m), the equation \n\\begin{equation}\n{\\mathcal A} \\cdot \\Delta {\\vec Y}_m = \\delta t (\\vec {\\dot Y_m} - \\Delta {\\vec Y}_{m-1})\n\\end{equation}\nis solved, and the final abundance update given by ${\\vec Y}(t+\\Delta t) = {\\vec Y}_{m} + \\delta {\\vec Y}_{m} $.\n\n\\subsection{Gear Methods}\n\n\\subsection{Matrix Equations}\n\nA common feature of all of these methods is the expression of the system as a matrix equation.\nA potential numerical problem with the solution is the singularity of the this matrix. \nFor example, the Jacobian matrix in the Backward Euler case, $\\partial \\vec \\calZ (t+\\Delta t)/ \\partial \n\\vec Y (t+ \\Delta t)$.\nFrom Eq.~\\ref{eq:zer}, the individual matrix elements of the Jacobian have the form\n\\begin{equation}\n\t {\\partial \\calZ_{i} \\over \\partial Y_{j}} = \n\t{\\delta_{ij} \\over \\Delta t} - {\\partial \\dot Y_{i} \\over \n\t\\partial Y_{j}}\\nonumber \n\t= {\\delta_{ij} \\over \\Delta t} - \\sum {1 \\over \\tau_{j}(i)} \\ ,\n\t\\label{eq:jacobian}\n\\end{equation}\nwhere $\\delta_{ij}$ is the Kronecker delta, and $\\tau_{j}(i)$ is the destruction timescale of nucleus $i$ with respect to nucleus $j$ for a given reaction, as defined in Eq.~\\ref{eq:tau}. \nThe sum accounts for the fact that there may be more than one reaction by which nucleus $j$ is involved in the creation or destruction of nucleus $i$. \nAlong the diagonal of the Jacobian, there are two competing terms, $1/\\Delta t$ and $\\sum 1/\\tau_{i}(i)$. \nThis sum is over all reactions which destroy nucleus $i$, and is dominated by the fastest reactions. \nAs a result, $\\sum 1/\\tau_{i}(i)$ can be orders of magnitude larger than the reciprocal of the desired timestep, $1/\\Delta t$. \nThis is especially a problem near equilibrium, where both destruction and the balancing production timescales are very short in comparison to the preferred timestep size, resulting in differences close to the numerical accuracy (i.e. 14 or more orders of magnitude). \nIn such cases, the term $1/\\Delta t$ is numerically neglected, leading to numerically singular matrices. \nOne approach to avoiding this problem is to artificially scale these short, equilibrium timescales by a factor which brings their timescale closer to $\\Delta t$, but leaves them small enough to ensure equilibrium.\nWhile this approach has been used successfully, the ad hoc nature of this artificial scaling renders these methods fragile. \n%A more promising approach is to make directly use of equilibrium expressions for abundances, which, as we will discuss in \\S\\ref{sect:hyb}, also ensures the economical use of computer resources.\n\nFor larger nuclear reaction networks, the Newton-Raphson method requires solution of a moderately large ($N=100-3000$) matrix equation for each zone. \nSince general solution of a dense matrix scales as $O(N^{3})$, this can make these large networks progressively much more expensive. \nWhile in principal, every species reacts with each of the hundreds of others, resulting in a dense Jacobian matrix, \nin practice it is possible to neglect most of these reactions. Because of \nthe $Z_{i}Z_{j}$ dependence of the repulsive Coulomb term in the nuclear \npotential, captures of free neutrons and isotopes of H and He on heavy \nnuclei occur much faster than fusions of heavier nuclei. Furthermore, with \nthe exception of the Big Bang nucleosynthesis and PP-chains, reactions \ninvolving secondary isotopes of H (deuterium and tritium) and He are \nneglectable. Likewise, photodisintegrations tend to eject free nucleons or \n\\alp-particles. Thus, with a few important exceptions, for each nucleus we \nneed only consider twelve reactions linking it to its nuclear neighbors by the \ncapture of an $n,p,\\alpha$ or $\\gamma$ and release a different one of these \nfour. The exceptions to this rule are the few heavy ion reactions important \nfor burning stages like carbon and oxygen burning where the dearth of light \nnuclei cause the heavy ion collisions to dominate.\n\n\\begin{figure}\n \\begin{center}\n \t \\includegraphics[width=.6\\textwidth]{sparse}\n \\end{center}\n\t\\caption{Graphic demonstration of the sparseness of the Jacobian\n\tmatrix. The filled squares represent the non-zero elements.}\n \\label{fig:sparse} \n\\end{figure}\n\nFig.~\\ref{fig:sparse} demonstrates the sparseness of the resulting Jacobian \nmatrix, for a 300 nuclei network chosen to handle all the energy generating stages in the life of a massive star. The nuclei are indexed in order of increasing Z and then A. Of the 90,000 matrix elements, fewer than 5,000 are non-zero. In terms of\nthe standard forms for sparse matrices, this Jacobian is best described\nas doubly bordered, band diagonal. With a border width, $\\Delta B$, of\n45 necessary to include the heavy ion reactions among \\isotope{C}{12}, \n\\isotope{O}{16} and \\isotope{Ne}{20} along with the free neutrons, protons and\n\\alp -particles and a band diagonal width, $\\Delta D$, of\n54, even this sparse form includes almost 50,000 elements. With solution\nof the matrix equation consuming 90+\\% of the computational time, there\nis clearly a need for custom tailored solvers which take better advantage \nof the sparseness of the Jacobian \\cite{PrAA87}. To date best results for small (N$<$100) matrices are obtained with machine optimized dense solvers (\\eg\\ LAPACK) or matrix specific solvers generated by symbolic processing \\cite{Mull98,Mull86}.\nFor large matrices, generalized sparse solvers, both custom built and from\nsoftware libraries, are used (see, \\cite{Timm99}). \n\n\\bibliographystyle{apj}\n\\bibliography{apj_journals,add_journals,network,rspn_process,ccsn,sn-obs,stellar}\n\n\\end{document}", "meta": {"hexsha": "e39eb30064c481334915c18963fe2a8b5dff8a71", "size": 40776, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/xnet/XNet.tex", "max_stars_repo_name": "vishaltiwari/XNet", "max_stars_repo_head_hexsha": "a7ad8d9a610edb1d522fef56b8ed1067fb39f30f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-03-05T22:56:32.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-11T15:54:47.000Z", "max_issues_repo_path": "doc/xnet/XNet.tex", "max_issues_repo_name": "vishaltiwari/XNet", "max_issues_repo_head_hexsha": "a7ad8d9a610edb1d522fef56b8ed1067fb39f30f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-10-07T16:31:55.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-14T16:50:27.000Z", "max_forks_repo_path": "doc/xnet/XNet.tex", "max_forks_repo_name": "vishaltiwari/XNet", "max_forks_repo_head_hexsha": "a7ad8d9a610edb1d522fef56b8ed1067fb39f30f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-06-20T20:36:56.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-28T18:17:55.000Z", "avg_line_length": 78.7181467181, "max_line_length": 1200, "alphanum_fraction": 0.7484059251, "num_tokens": 11219, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.19715089903964625}}
{"text": "\n\\chapter{MPMICE} \\label{Sec:MPMICE}\n\n\\section{Introduction}\n\nMPMICE is a marriage of the multi-material ICE method, described in\nSection~\\ref{Sec:ICE} and MPM, described in Section~\\ref{Sec:MPM}.\nThe equations of motion solved for both fluid and solid are essentially\nthe same, although the physical behavior of these two states of matter\ndiffer, largely due to their constitutive relationships. MPM is used\nto track the evolution of solid materials in a Lagrangian frame of\nreference, while fluids are evolved in the Eulerian frame.\n\n\\section{Theory - Algorithm Description}\n\nAt this time, the reader is directed to the manuscript by Guilkey,\nHarman and Banerjee~\\cite{fourthmit} for the theoretical and algorithmic\ndescription of the method.\n\n%\\subsection{Uintah Specification}\n\n%\\subsubsection{ICE}\n\n%\\subsubsection{Basic Inputs}\n%\\subsubsection{Physical Constants}\n%\\subsubsection{Material Properties}\n%\\subsubsection{Equation of State}\n%\\subsubsection{Exchange Properties}\n%\\subsubsection{BoundaryConditions}\n%\\subsubsection{Solvers}\n\n\n%\\subsection{MPM}\n\n%\\subsubsection{Basic Inputs}\n%\\subsubsection{Physical Constants}\n%\\subsubsection{Material Properties}\n%\\subsubsection{Constitutive Models}\n%\\subsubsection{Contact}\n%\\subsubsection{BoundaryConditions}\n%\\subsubsection{Physical Boundary Conditions}\n\n\\section{Solid State Kinetic Models}\n\nA generalized reaction model for solid state kinetics based on the\nassumption that the temperature dependence of the rate can be separated\nfrom the reaction model as embodied by the equation:\n\n\\begin{equation}\n\\frac{d\\alpha}{dt}=k(T)f(\\alpha)\n\\end{equation}\n\n\\noindent is implemented in Uintah and named \\textbf{SolidReactionModel}. To\nuse the \\textbf{SolidReactionModel} one must specify both a temperature\ndependent rate constant model and a rate model. The model is a grid based\nmodel, so should work with both MPM and ICE materials. In the case where an MPM\nmaterial is used as the reactant or product, the thermodynamic quantities\nthat are interpolated to the grid are used to calculate reaction rates. \n\nAdditional rate constant and rate models may be added by either subclassing \\textbf{RateConstantModel}\nor \\textbf{RateModel}. Examples of this can be found in the \n\\textbf{src/CCA/Components/Models/SolidReactionModel}\ndirectory. Two models currently exist for the rate constant $k(T)$, Arrhenius and\nModified Arrhenius. These two models have the forms:\n\n\\begin{equation}\nk(T)=Ae^{\\frac{-E_a}{RT}}\n\\end{equation}\n\n\\noindent and:\n\n\\begin{equation}\nk(T)=AT^be^{\\frac{-Ea}{RT}}\n\\end{equation}\n\nVarious rate models of different classes exist for use. These classes include\nreaction-order models, diffusion models, geometrical contraction models and\nnucleation models. The following table shows the various models available. Models\nwere taken from \\cite{ref:vyazovkinwight} and \\cite{ref:khawamflanagan}.\\newline\\newline\n\n\\begin{tabular}{ |l | c | c |}\n\\hline\n\\textbf{Model} & $f(\\alpha)$ & \\textbf{Uintah 'type'} \\\\\n\\hline\n\\hline\n\\multicolumn{3}{|c|}{\\textbf{Reaction-order Models}} \\\\\n\\hline\nNth Order & $(1-\\alpha)^n$ & NthOrder \\\\\n\\hline\n\\multicolumn{3}{|c|}{\\textbf{Diffusion Models}} \\\\\n\\hline\n1-D Diffusion & $1/2\\alpha$ & Diffusion \\\\\n\\hline\n2-D Diffusion & $-1/ln(1-\\alpha)$ & Diffusion \\\\\n\\hline\n3-D Diffusion& $3/2(1-\\alpha)^{2/3}(1-(1-\\alpha)^{1/3})$ & Diffusion \\\\\n\\hline\n4-D Diffusion& $3/2(1/\\alpha^{1/3}-1)$ & Diffusion \\\\\n\\hline\n\\multicolumn{3}{|c|}{\\textbf{Geometrical Contraction Models}} \\\\\n\\hline\nContracting Cylinder& $2\\sqrt{1-\\alpha}$ & ContractingCylinder \\\\\n\\hline\nContracting Sphere& $3(1-\\alpha)^{2/3}$ & ContractingSphere \\\\\n\\hline\n\\multicolumn{3}{|c|}{\\textbf{Nucleation Models}} \\\\\n\\hline\nPower & $a\\alpha^b$ & Power \\\\\n\\hline\nAvarami-Erofe'ev & $a(1-\\alpha)(-ln(1-\\alpha))^b$ & AvaramiErofeev \\\\\n\\hline\n\\end{tabular} \\newline\\newline\n\nThe input file specification is as follows:\n\n\\begin{verbatim}\n \n \n \n ....\n \n \n ....\n \n \n \n\\end{verbatim}\n\n\\noindent Here, the type attribute for \\textbf{RateConstantModel} should be either \\textbf{Arrhenius} or \\textbf{ModifiedArrhenius}\nwhich both take an activation energy \\textbf{Ea}, and frequency factor \\textbf{A}. In addition, the modified Arrhenius\nmodel takes a temperature dependence exponent, \\textbf{b}.\n\nThe specification of type attribute for \\textbf{RateModel} should be one of those listed in the previous table.\nThe \\textbf{NthOrder} model must have a positive integral value for the reaction order \\textbf{n}. \nThe \\textbf{Diffusion} based models require a \\textbf{dimension} value that should be 1, 2, 3 or 4 depending\non the dimensionality of the desired rate model. Both geometric contraction models take no additional\ninput parameters. Both nucleation based models, \\textbf{Power} and \\textbf{AvaramiErofeev}, take both \nan \\textbf{a} and a \\textbf{b} input parameter. \n\n\\section{HE Reaction Models}\n\nThree models exist for reaction of high explosive materials. Each\nsimulation using one of these models utilize MPMICE's material\ninteractions as its foundation. The components work by taking several\nmaterial specific constants as well as a reactant and product material\nfrom the model input section of the .ups file. Following are brief\ndescriptions of each model, as well as their input parameters.\n\n\\subsection{Simple Burn} \\label{Sec:SimpleBurn}\n\nSimple Burn, as the name implies, is a simple model of combustion of HMX based on the rate equation:\n\n\\begin{equation}\n\\dot{m}=A P^{0.778}\n\\label{simburneqn}\n\\end{equation}\n\nWhere $\\dot{m}$ is the mass flux, $P$ is the pressure and $n$ is the pressure dependence coefficient. The pressure coefficient in Equation (\\ref{simburneqn}) is that of HMX. The models input section for a Simple Burn simulation takes the form: \n\n\\begin{verbatim}\n\n \n reactant \n product \n true \n 450.0 \n 50000.0 \n 2000000.0 \n 75.3 \n 101325.0 \n \n\n\\end{verbatim}\n\nThe first two tags take names of materials previously defined in the input file, defining both reactant and product used by the model. See Section \\ref{sec:ICEmat_props} and \\ref{Sec:mat_props} for in depth description for defining materials. $<$Active$>$ is a debugging parameter that takes a boolean value indicating whether the model is on (i.e. the actual computations take place during the timestep). True is the value to set for $<$Active$>$ in most situations. Each of the other parameters take double values. Threshold temperature and pressure tags define two criteria the cell must have in order to be flagged burning. The reference pressure is used to scale the cell centered pressure as well as make it an unitless value. The burn coefficient corresponds to $A$ in the rate equation. Enthalpy is simply the enthalpy value for conversion of reactant to product.\n\\newpage\n\\subsection{Steady Burn} \\label{Sec:SteadyBurn}\n\nSteady Burn is a more accurate model than Simple Burn. It is based on WSB model of combustion developed by Ward, Son and Brewster in \\cite{ref:wardsonbrewster}. WSB is based on a simplified two-step chemical model with an initial zero-order, thermally activated ($E_c > 0$), mildly exothermic, solid-to-gas reaction, modeled as a thermal decomposition of the solid:\n\n\\begin{equation}\nA(solid)\\rightarrow B(gas)\n\\end{equation}\n\nIntermediate $B$, in the presence of any gas phase collision partner $M$, reacts in a highly exothermic fashion producing a flame. This step is modelled as a second-order, gas phase, free radical chain reaction based on the assumption that $E_g = 0$:\n\n\\begin{equation}\nB(gas)+M(gas)\\rightarrow C(gas)+M(gas)\n\\end{equation}\n\nAs such, this second equation represents the reaction in the gas phase that causes heat convection back to the surface that activate the first reaction. In Steady Burn, a solution is found by iteratively solving two equations: one for mass burning rate $\\dot{m}$ and one for surface temperature $T_s$. Mass flux is initially solved with an assumed value $T_s$ (in the model set to $850.0 K$) using WSB:\n\n\\begin{equation}\n\\dot{m}\\left(T_s\\right)=\\sqrt{\\frac{\\displaystyle \\kappa_c \\rho_c A_c R T_s^2 \\exp\\left({\\frac{\\displaystyle -E_c}{\\displaystyle R T_s}}\\right)}{\\displaystyle C_p E_c \\left(T_s - T_0 - \\frac{Q_c}{2 C_p}\\right)}}\n\\label{WSB1}\n\\end{equation}\n\nThe solution to this equation is used to refine the surface temperature and vice-versus until a self-consistent solution for surface temperature and mass flux has been found. The surface temperature equation takes the form:\n\n\\begin{equation}\nT_s(\\dot{m},P)=T_0 + \\frac{\\displaystyle Q_c}{\\displaystyle C_p} + \\frac{Q_g}{Cp\\left(1+\\frac{\\displaystyle x_g\\left(\\dot{m},P\\right)}{\\displaystyle x_{cd}(\\dot{m})}\\right)}\n\\label{WSB2}\n\\end{equation}\n\n$x_g$ in the third term of Equation (\\ref{WSB2}) is the flame standoff distance, computed from:\n\n\\begin{equation}\nx_g\\left(\\dot{m},P\\right)=\\frac{2 x_{cd}\\left(\\dot{m}\\right)}{\\displaystyle \\sqrt{1 + D_a\\left(\\dot{m},P\\right)} - 1}\n\\label{WSB3}\n\\end{equation}\n\nwhere $x_{cd}$ and $D_a$ are the convective-diffusive length and Damkohler number, respectively:\n\n\\begin{equation}\nx_{cd} \\left(\\dot{m}\\right)=\\frac{\\kappa_g}{\\displaystyle \\dot{m} C_p}\n\\label{WSB4}\n\\end{equation}\n\\begin{equation}\nD_a\\left(\\dot{m},P\\right) = \\frac{4 B_g M C_p P^2}{\\displaystyle R^2 \\kappa_g} x_{cd}\\left(\\dot{m}\\right)^2\n\\label{WSB5}\n\\end{equation}\n\nWSB model is valid as a 1D model, but needs extension to work in a 3D multimaterial CFD environment. As such, Steady Burn is WSB extended with logic for ignition of energetic materials and computation of surface area for burning cells. Ignition of a cell is based on three criteria: \n\\begin{itemize}\n \\item The cell must contain one particle of energetic solid\n \\item The cell is near a surface of an energetic solid (e.g. ratio of minimum node-centered mass to maximum node-centered mass is less than 0.7)\n \\item One neighboring cell must have at most two particles of energetic material\n\\end{itemize}\nIf a cell is ignited, the model will be applied and mass will be transferred from reactant material to product material. Total mass burned is computed using mass flux $\\dot{m}$, $\\Delta t$ of the timestep and the calculated surface area, found using:\n\n\\begin{equation}\nA=\\frac{\\delta x \\delta y \\delta z}{\\displaystyle \\delta x |g_x| + \\delta y |g_y| + \\delta z |g_z|}\n\\label{WSB6}\n\\end{equation} where $\\delta x$, $\\delta y$, and $\\delta z$ are the dimensions of the cell and components of $\\overrightarrow{g}$ are the normalized density gradients of the particle mass in a cell. A more thorough examination of Steady Burn can be read about in \\cite{ref:wighteddings}.\n\nThe following table describes the input parameters for Steady Burn. The final column of the table indicates parameters for combustion of HMX. \n\n\\begin{center}\n\\begin{tabular}{| l | c | p{4cm} | l |}\n\\hline\n \\multicolumn{4}{|c|}{\\textbf{Steady Burn Input Parameters}} \\\\\n\\hline\n\\hline\n \\textbf{Tag} & \\textbf{Type} & \\textbf{Description} & \\textbf{HMX Value} \\\\\n\\hline\n $<$fromMaterial$>$ & String & `Name' of reactant material (mass source) & \\\\\n\\hline\n $<$toMaterial$>$ & String & `Name' of product material (mass sink) & \\\\\n\\hline\n $<$IdealGasConst$>$ & double & Ideal gas constant ($R$) & $8.314 J/(K\\times mol)$ \\\\\n\\hline\n $<$PreExpCondPh$>$ & double & Condensed phase pre-exponential coefficient ($A_c$) & $1.637\\times10^{15} s^{-1}$ \\\\\n\\hline\n $<$ActEnergyCondPh$>$ & double & Condensed phase activation energy ($E_c$) & $1.76\\times10^5 J/mol$ \\\\\n\\hline\n $<$PreExpGasPh$>$ & double & Gas phase frequency factor ($B_g$) & $1.6\\times10^{-3} m^3/(kg\\times s\\times K)$ \\\\\n\\hline\n $<$CondPhaseHeat$>$ & double & Condensed phase heat release per unit mass ($Q_c$) & $4.0\\times10^5 J/kg$ \\\\\n\\hline\n $<$GasPhaseHeat$>$ & double & Gas phase heat release per unit mass ($Q_g$) & $3.018\\times10^6 J/kg$ \\\\\n\\hline\n $<$HeatConductGasPh$>$ & double & Thermal conductivity of gas ($\\kappa_g$) & $0.07 W/(m\\times K)$ \\\\\n\\hline\n $<$HeatConductCondPh$>$ & double & Thermal conductivity of condensed phase ($\\kappa_c$) & $0.02 W/(m\\times K)$ \\\\\n\\hline\n $<$SpecificHeatBoth$>$ & double & Specific heat at constant pressure ($c_p$) & $1.4\\times10^3 J/(kg\\times K)$ \\\\\n\\hline\n $<$MoleWeightGasPh$>$ & double & Molecular weight of gas ($W$) & $3.42\\times10^{-2} kg/mol$ \\\\\n\\hline\n $<$BoundaryParticles$>$ & int & Max \\# of particles a cell can have and be burning & Resolution dependent \\\\\n\\hline\n $<$ThresholdPressure$>$ & double & Threshold pressure cell must have $\\ge$ to burn mass & $50000 Pa$ \\\\\n\\hline\n $<$IgnitionTemp$>$ & double & Temperature cell must have $\\ge$ to be burning & $550 K$ \\\\\n\\hline\n\\end{tabular}\n\\end{center}\n\n\\newpage\n\\subsection{Unsteady Burn} \\label {Sec:UnsteadyBurn}\n\nUnsteady Burn is a model developed at the University of Utah as an extension of Steady Burn to better represent mass burning rates when pressure at the burning surface fluctuates. A pressure-coupled response is accounted for in the model such that, qualitatively a pressure increase causes gas phase reaction rates to increase as well as move the gas phase reactions closer to the burning surface. Increase of near surface gas phase reactions increases the rate of thermally activated solid state reactions, ultimately causing a higher steady burn rate. Unsteady Burn more accurately models the transition from low pressure to high pressure than Steady Burn by taking into account the initially overshot burn rate at the time when the pressure increases, and the relaxation period to steady burn rate. Similarly, Unsteady Burn models undershot pressures during pressure drops. \n\nThe model is an extension of Steady Burn by partial decoupling of the gas phase and solid state Equations (\\ref{WSB1}) and (\\ref{WSB2}). An expression for the temperature gradient of the solid:\n\n\\begin{equation}\n \\beta = \\left(T_s - T_0\\right) \\frac{m c_p}{\\displaystyle\\kappa_c}\n \\label{WSB7}\n\\end{equation}\n\nis reaarranged for $(T_s-T_0)$ and substituted in Equation (\\ref{WSB1}) leading to the quadradic equation:\n\n\\begin{equation}\n\\dot{m}^2 - \\frac{2 \\beta \\kappa_c}{Q_c} \\dot{m} + \\frac{2 A_c R T_s^2 \\kappa_c \\rho_c }{E_c Q_C} \\exp\\left({\\frac{-E_c}{R T_s}}\\right)=0\n\\label{WSB8}\n\\end{equation}\n\nwhich allows independent tracking of temperature gradient $\\beta$ and surface temperature $T_s$. The gas phase response is computed using a runnning average of $T_s$ as it approaches the steady burning value. A solid state response is obtained by computing a running average of $\\beta$ as it approaches the steady burning value. A slow relaxation time for $\\beta$ and a fast relaxation time for $T_s$ models the overshoot or undershoot in burn rate. Burning criteria for a cell is the same as Steady Burn. For more information on Unsteady Burn see \\cite{ref:wighteddings}.\n\nThe following table describes the input parameters for Unsteady Burn.\n\n\\begin{center}\n\\begin{tabular}{| l | c | p{7cm} |}\n\\hline \n \\multicolumn{3}{|c|}{\\textbf{Unsteady Burn Input Parameters}} \\\\\n\\hline\n\\hline\n \\textbf{Tag} & \\textbf{Type} & \\textbf{Description}\\\\\n\\hline\n $<$fromMaterial$>$ & String & `Name' of reactant material (mass source)\\\\\n\\hline\n $<$toMaterial$>$ & String & `Name' of product material (mass sink)\\\\\n\\hline\n $<$IdealGasConst$>$ & double & Ideal gas constant ($R$)\\\\\n\\hline\n $<$PreExpCondPh$>$ & double & Condensed phase pre-exponential coefficient ($A_c$) \\\\\n\\hline\n $<$ActEnergyCondPh$>$ & double & Condensed phase activation energy ($E_c$)\\\\\n\\hline\n $<$PreExpGasPh$>$ & double & Gas phase frequency factor ($B_g$)\\\\\n\\hline\n $<$CondPhaseHeat$>$ & double & Condensed phase heat release per unit mass ($Q_c$)\\\\\n\\hline\n $<$GasPhaseHeat$>$ & double & Gas phase heat release per unit mass ($Q_g$)\\\\\n\\hline\n $<$HeatConductGasPh$>$ & double & Thermal conductivity of gas ($\\kappa_g$)\\\\\n\\hline\n $<$HeatConductCondPh$>$ & double & Thermal conductivity of condensed phase ($\\kappa_c$)\\\\\n\\hline\n $<$SpecificHeatBoth$>$ & double & Specific heat at constant pressure ($c_p$)\\\\\n\\hline\n $<$MoleWeightGasPh$>$ & double & Molecular weight of gas ($W$)\\\\\n\\hline\n $<$BoundaryParticles$>$ & int & Max \\# of particles a cell can have and be burning\\\\\n\\hline\n $<$BurnrateModCoef$>$ & double & if $\\neq$1.0, scale unsteady rate with steady rate as $\\dot{m}_u=\\dot{m}_s\\left(\\frac{\\displaystyle\\dot{m}_u}{\\displaystyle\\dot{m}_s}\\right)^{B_m}$\\\\\n\\hline\n $<$CondUnsteadyCoef$>$ & double & Coefficient for condensed phase pressure response relaxation \\\\\n\\hline\n $<$GasUnsteadyCoef$>$ & double & Coefficient for gas phase pressure response relaxation \\\\\n\\hline\n $<$ThresholdPressure$>$ & double & Threshold pressure cell must be $\\ge$ to burn mass\\\\\n\\hline\n $<$IgnitionTemp$>$ & double & Temperature cell must be at $\\ge$ to be burning\\\\\n\\hline\n\\end{tabular}\n\\end{center}\n\n\n\\newpage\n\\subsection{Ignition \\& Growth} \\label {Sec:IandG}\n\nThe Ignition \\& Growth model created by Lee and Tarver \\cite{ref:Lee1980} to simulate shock-to-detonation\ntransitions in condensed explosives. The rate equation takes the form:\n\n\\begin{equation}\n\\frac{dF}{dt}=I(1-F)^b\\left(\\frac{\\rho}{\\rho_0}-1-a\\right)^x+G_1(1-F)^cF^dP^y+G_2(1-F)^eF^gP^z\n\\label{IandGEqn}\n\\end{equation}\n\nwhere $F$ is the extent of reaction in a cell, $P$ is the pressure, $\\rho$ and $\\rho_0$ are the current and initial density of the\nexplosive and $I$, $G_1$, $G_2$, $a$, $b$, $c$, $d$, $e$, $g$, $x$, $y$ and $z$ are constant fit parameters. \nThe three terms are the ignition, growth and completion terms respectively. The ignition term is used to emulate \nhot-spot formation and strengthening and runs over $0$ & String & `Name' of reactant material (mass source)\\\\\n\\hline\n $<$toMaterial$>$ & String & `Name' of product material (mass sink)\\\\\n\\hline\n $<$I$>$ & double & Ignition rate constant (hot-spot frequency) \\\\\n\\hline\n $<$G1$>$ & double & Growth rate constant \\\\\n\\hline\n $<$G2$>$ & double & Completion rate constant \\\\\n\\hline\n $<$a$>$ & double & Ignition constant \\\\\n\\hline\n $<$b$>$ & double & Ignition exponent \\\\\n\\hline\n $<$c$>$ & double & Growth exponent \\\\\n\\hline\n $<$d$>$ & double & Growth exponent \\\\\n\\hline\n $<$e$>$ & double & Completion exponent \\\\\n\\hline\n $<$g$>$ & double & Completion exponent \\\\\n\\hline\n $<$x$>$ & double & Ignition density exponent \\\\\n\\hline\n $<$y$>$ & double & Growth pressure exponent \\\\\n\\hline\n $<$z$>$ & double & Completion pressure exponent \\\\\n\\hline\n $<$Figmax$>$ & double & Maximum reaction extent for hot-spot (ignition) term \\\\\n\\hline\n $<$FG1max$>$ & double & Maximum reaction extent for fast (growth) term \\\\\n\\hline\n $<$FG2min$>$ & double & Minimum reaction extent for slow (completion) term \\\\\n\\hline\n $<$rho0$>$ & double & The initial density of the explosive \\\\\n\\hline\n $<$E0$>$ & double & The energy of detonation \\\\\n\\hline\n $<$ThresholdPressure$>$ & double & Reaction is allowed to occur above this pressure \\\\\n\\hline\n\\end{tabular}\n\\end{center}\n\n\n\n\\newpage\n\\subsection{JWL++} \\label {Sec:JWLpp}\n\nThe JWL++ model by Souers et al. \\cite{ref:JWL} is related to the Ignition and Growth model (see Section \\ref{Sec:IandG}),\nbut much simplified in its form for ease of rate constant fit. The rate is described by:\n\n\\begin{equation}\n\\frac{dF}{dt}=G(1-F)P^b\n\\label{JWLppEqn}\n\\end{equation}\n\nwhere $F$ is the extent of reaction, $P$ is the pressure and $G$ and $b$ are fit constants. Several other\nforms of the JWL++ model have been formulated, however this is the only one that is currently supported in \nUintah. Input paramters are shown in the follwoing table.\n\n\\begin{center}\n\\begin{tabular}{| l | c | p{7cm} |}\n\\hline\n \\multicolumn{3}{|c|}{\\textbf{Ignition \\& Growth Input Parameters}} \\\\\n\\hline\n\\hline\n \\textbf{Tag} & \\textbf{Type} & \\textbf{Description}\\\\\n\\hline\n $<$fromMaterial$>$ & String & `Name' of reactant material (mass source)\\\\\n\\hline\n $<$toMaterial$>$ & String & `Name' of product material (mass sink)\\\\\n\\hline\n $<$G$>$ & double & Growth rate constant \\\\\n\\hline\n $<$b$>$ & double & Completion rate constant \\\\\n\\hline\n $<$rho0$>$ & double & The initial density of the explosive \\\\\n\\hline\n $<$E0$>$ & double & The energy of detonation \\\\\n\\hline\n $<$ThresholdPressure$>$ & double & Reaction is allowed to occur above this pressure \\\\\n\\hline\n $<$ThresholdVolFrac$>$ & double & (Optional; default 0.01) Minimum volume of explosive in a cell for reaction \\\\\n\\hline\n\\end{tabular}\n\\end{center}\n\n\n\n\n\\newpage\n\\subsection{DDT0} \\label {Sec:DDT0}\n\nDeflagration-to-detonation model 0 (DDT0) was the first incarnation of a model \nthat contains two rate models to represent three different reaction modes. The \nmodel is capable of surface burning, convective burning and detonation. Burning\nis accomplished using the same model as Simple Burn (see Section \\ref{Sec:SimpleBurn}). Detonation\nis accounted for by the JWL++ model (see Section \\ref{Sec:JWLpp}) presented by P. Clark Souers \\cite{ref:JWL}. \nThe simple threshold pressure separates detonation and deflagration regimes. In addition,\na crack-size dependent model may be optionally used to allow convective burning to \noccur in the bulk material. The crack-size threshold is computed via an expression fit by\nBerghout et al. \\cite{ref:Berghout2002} The parameters are presented in the following table.\n\n\\begin{center}\n\\begin{tabular}{| l | c | p{7cm} |}\n\\hline\n \\multicolumn{3}{|c|}{\\textbf{DDT0 Input Parameters}} \\\\\n\\hline\n\\hline\n \\textbf{Tag} & \\textbf{Type} & \\textbf{Description}\\\\\n\\hline\n $<$fromMaterial$>$ & String & `Name' of reactant material (mass source)\\\\\n\\hline\n $<$toMaterial$>$ & String & `Name' of product material (mass sink)\\\\\n\\hline\n $<$G$>$ & double & Rate constant for detonation (JWL++ model) \\\\\n\\hline\n $<$b$>$ & double & Pressure exponent for detonation (JWL++ model) \\\\\n\\hline\n $<$E0$>$ & double & Energy of reaction for detonation (JWL++ model) \\\\\n\\hline\n $<$ThresholdPressureJWL$>$ & double & Threshold pressure for onset of detonation \\\\\n\\hline\n $<$ThresholdVolFrac$>$ & double & (Optional; default 0.01) Minimum volume fraction of reactant for detonation to occur in a cell \\\\\n\\hline\n $<$Enthalpy$>$ & double & Energy of reaction for deflagration (Simple Burn model) \\\\\n\\hline\n $<$BurnCoeff$>$ & double & Rate constant for deflagration (Simple Burn model) \\\\\n\\hline\n $<$refPressure$>$ & double & Reference pressure for deflagration (Simple Burn model) \\\\\n\\hline\n $<$ThresholdTemp$>$ & double & Threshold temperature for combustion (Simple Burn model) \\\\\n\\hline\n $<$TresholdPressureSB$>$ & double & Threshold pressure required for combustion (Simple Burn model) \\\\\n\\hline\n $<$useCrackModel$>$ & boolean & (Optional; default false) Switch that allows convective burning \\\\\n\\hline\n $<$Gcrack$>$ & double & (Required for 'useCrackModel') Rate constant for convective deflagration \\\\\n\\hline\n $<$CrackVolThreshold$>$ & double & (Optional; default 1e-14) Volume fraction of reactant above temperature needed for convective deflagration \\\\\n\\hline\n $<$nCrack$>$ & double & (Required for 'useCrackModel') Pressure exponent for convective deflagration \\\\\n\\hline\n\\end{tabular}\n\\end{center}\n\n\n\n\\newpage\n\\subsection{DDT1} \\label {Sec:DDT1}\n\nDeflagration-to-detonation model 1 (DDT1) \\cite{ref:Peterson2012} was the second incarnation of a model\nthat contains two rate models to represent three different reaction modes. The\nmodel is capable of surface burning, convective burning and detonation. Burning\nis accomplished using the same model as Steady Burn (see Section \\ref{Sec:SteadyBurn}). Detonation\nis accounted for by the JWL++ model (see Section \\ref{Sec:JWLpp}) presented by P. Clark Souers \\cite{ref:JWL}.\nThe simple threshold pressure separates detonation and deflagration regimes. In addition,\na crack-size dependent model may be optionally used to allow convective burning to\noccur in the bulk material. The crack-size threshold is computed via an expression fit by\nBerghout et al. \\cite{ref:Berghout2002} The parameters are presented in the following table.\n\n\\begin{center}\n\\begin{tabular}{| l | c | p{7cm} |}\n\\hline\n \\multicolumn{3}{|c|}{\\textbf{DDT1 Input Parameters}} \\\\\n\\hline\n\\hline\n \\textbf{Tag} & \\textbf{Type} & \\textbf{Description}\\\\\n\\hline\n $<$fromMaterial$>$ & String & `Name' of reactant material (mass source)\\\\\n\\hline\n $<$toMaterial$>$ & String & `Name' of product material (mass sink)\\\\\n\\hline\n $<$burnMaterial$>$ & String & (Optional; default `toMaterial') `Name' of product material for deflagration\\\\\n\\hline\n $<$G$>$ & double & Rate constant for detonation (JWL++ model) \\\\\n\\hline\n $<$b$>$ & double & Pressure exponent for detonation (JWL++ model) \\\\\n\\hline\n $<$E0$>$ & double & Energy of reaction for detonation (JWL++ model) \\\\\n\\hline\n $<$ThresholdPressureJWL$>$ & double & Threshold pressure for detonation \\\\\n\\hline\n $<$ThresholdVolFrac$>$ & double & (Optional; default 0.01) Minimum volume fraction of reactant for detonation to occur in a cell \\\\\n\\hline\n $<$IdealGasConst$>$ & double & Ideal gas constant ($R$) \\\\\n\\hline\n $<$PreExpCondPh$>$ & double & Condensed phase pre-exponential coefficient ($A_c$) \\\\\n\\hline\n $<$ActEnergyCondPh$>$ & double & Condensed phase activation energy ($E_c$) \\\\\n\\hline\n $<$PreExpGasPh$>$ & double & Gas phase frequency factor ($B_g$) \\\\\n\\hline\n $<$CondPhaseHeat$>$ & double & Condensed phase heat release per unit mass ($Q_c$) \\\\\n\\hline\n $<$GasPhaseHeat$>$ & double & Gas phase heat release per unit mass ($Q_g$) \\\\\n\\hline\n $<$HeatConductGasPh$>$ & double & Thermal conductivity of gas ($\\kappa_g$) \\\\\n\\hline\n $<$HeatConductCondPh$>$ & double & Thermal conductivity of condensed phase ($\\kappa_c$) \\\\\n\\hline\n $<$SpecificHeatBoth$>$ & double & Specific heat at constant pressure ($c_p$) \\\\\n\\hline\n $<$MoleWeightGasPh$>$ & double & Molecular weight of gas ($W$) \\\\\n\\hline\n $<$BoundaryParticles$>$ & int & Max \\# of particles a cell can have and be burning \\\\\n\\hline\n $<$ThresholdPressure$>$ & double & Threshold pressure cell must have $\\ge$ to burn mass \\\\\n\\hline\n $<$IgnitionTemp$>$ & double & Temperature cell must have $\\ge$ to be burning \\\\\n\\hline\n $<$TresholdPressureSB$>$ & double & Threshold pressure required for combustion \\\\\n\\hline\n $<$useCrackModel$>$ & boolean & (Optional; default false) Switch that allows convective burning \\\\\n\\hline\n\\end{tabular}\n\\end{center}\n\n\n\n\\newpage\n\\subsubsection{Dynamic Output Intervals} \\label {Sec:DDT1}\nThe dynamic output intervals section is used to change how frequently the output interval and check point interval are saved. The intervals can be changed when the pressure is a cell with reactant is greater than the set pressure threshold and/or when detonation is detected. This only works when using the DDT1 reaction model.\n\n\n\\begin{center}\n\\begin{tabular}{| l | c | p{7cm} |}\n\\hline\n \\multicolumn{3}{|c|}{\\textbf{Dynamic Output Intervals Input Parameters}} \\\\\n\\hline\n\\hline\n \\textbf{Tag} & \\textbf{Type} & \\textbf{Description}\\\\\n\\hline\n $<$PressureThreshold$>$ & double & Pressure threshold to switch output interval (Pa)\\\\\n\\hline\n $<$newOutputInterval$>$ & double & Output interval after switch is reached\\\\\n\\hline\n $<$newCheckPointInterval$>$ & double & Check point interval after switch is reached\\\\\n\\hline\n $<$remainingTimesteps$>$ & double & Number of timesteps after detonation when the simulation will shut down\\\\\n\\hline\n\\end{tabular}\n\\end{center}\n\n\nThe input file specification is as follows:\n\\begin{verbatim}\n\n....\n\n\n 4.0e9 \n 1e-7 \n 1e-7 \n\n\n\n 20 \n 1e-6\n 1e-6 \n\n\n....\n \n\\end{verbatim}\n\n\\newpage\n\\subsubsection{Induction Time} \\label {Sec:Induction Time }\nTo accurately represent the propagation of deflagration an \"induction\" period, or wait time was introduced. This induction period is the time a cell must wait before reactant mass would be converted to product gas using the WSB burn model \\cite{ref:wardsonbrewster}. The induction time is dependent on the surrounding pressure and the size of the cell. The induction time model is based off experimentally determined flame propagation on a surface as seen in equation \\ref{FlameSpread} \\cite{flameProp}, where P is the dimensionless pressure (p/p$_0$) and S$_f$ is the flame propagation in $cm/s$. Equation \\ref{FlameSpread} is used in determining the induction time as seen by equation \\ref{inducTime} where x is the size of the cell and A is a constant used to speed up or slow down the propagation of convective deflagration. A varies depending on the length of the cell but should be used to give the correct propagation of convective deflagration only. The model determines which direction the flame is coming from in turn adjusting A according to the angle of penetration.\nFor instance if the flame is propagating along a surface but not into the solid A = 1 but if the flame is propagating directly into the surface A equals the value set in the input file.\n\n\\begin{equation}\nS_f = 0.259{\\displaystyle P^{0.538}}\n\\label{FlameSpread}\n\\end{equation}\n\\begin{equation}\n\\tau = \\frac{\\Delta x A}{S_f} \n\\label{inducTime}\n\\end{equation}\n\n\\begin{center}\n\\begin{tabular}{| l | c | p{7cm} |}\n\\hline\n \\multicolumn{3}{|c|}{\\textbf{Dynamic Output Intervals Input Parameters}} \\\\\n\\hline\n\\hline\n \\textbf{Tag} & \\textbf{Type} & \\textbf{Description}\\\\\n\\hline\n $<$useIndcutionTime$>$ & boolean & (Optional; default false) Switch that slows down deflagration propagation\\\\\n\\hline\n $<$IgnitionConst$>$ & double & Constant used to speed up or slow down the convective deflagration propagation\\\\\n\\hline\n $<$PressureShift$>$ & double & Pressure used to make dimensionless pressure (p$_0$)\\\\\n\\hline\n $<$ExponentialConst$>$ & double & Exponential constant used in flame propagation equation\\\\\n\\hline\n $<$PreexopConst$>$ & double & Pre-exponential constant used in flame propagation equation\\\\\n\\hline\n\\end{tabular}\n\\end{center}\n\n\nThe input file specification is as follows:\n\\begin{verbatim}\n\n....\n true \n 0.00009 \n 1.0e5 \n 0.538 \n 0.00259 \n....\n \n\\end{verbatim}\n\nThe pressure shift, exponential and pre-exponential constants presented above are given by Son et al. \\cite{flameProp} for experimentally determined values for the explosive PBX9501.\n\n\n\\newpage\n\n\\section{Examples} \\label {Sec:MPMICE_EXAMPLES}\n\n\\subsection*{\\center Mach 2 Wedge}\n\\addcontentsline{toc}{subsection}{Mach 2 Wedge}\n\\subsubsection*{\\underline{Problem Description}}\nThis is a simulation of a symmetric $20^o$ wedge traveling through initially\nquiescent air at Mach 2.0. A shock forms at the leading edge of the\nwedge and an expansion fan over its top. Consultation of oblique shock\ntables, e.g.~\\cite{ref:Saad} (pp.308-309) reveals that the angle of the leading\nshock compares quite well with the expected value. In addition, this\nsimulation demonstrates a few other useful features of the fluid-structure\ninteraction capability. In this case, the structure is rigid, and as\nsuch, essentially provides a boundary condition to the compressible flow\ncalculation. Furthermore, the geometry of the wedge is described via a\ntriangulated surface, rather than the geometric primitives usually used.\nThis allows the user to study flow around arbitrarily complex objects,\nwithout the difficulty of generating a body fitted mesh around that object.\n\n\\subsubsection*{\\underline{Simulation Specifics}}\n\\begin{description}\n\\item [Component used:] \\hfill rmpmice (Rigid MPM-ICE)\n\\item [Input file name:] \\hfill Mach2wedge.ups\n\\item [Command used to run input file:]\\hfill sus inputs/UintahRelease/MPMICE/Mach2wedge.ups\n(Note: The files wedge40.pts and wedge40.tri must also be copied to\nthe same directory as sus.)\n\n\\item [Simulation Domain:]\\hfill 0.25 x 0.0375 x 0.001 m\n\n\\item [Cell Spacing:]\\hfill \\\\\n.0005 x .0005 x .001 m (Level 0)\n\n\\item [Example Runtimes:] \\hfill \\\\\n 20 minutes (1 processor, 3.16 GHz Xeon)\\\\\n\n\\item [Physical time simulated:] \\hfill 0.3 milliseconds\n\n\\item [Associated visit session:] \\hfill M2wedge.session\n\n\\end{description}\n\n\\newpage\n\n\\subsubsection*{\\underline{Results}}\n\nFigure~\\ref{figwedge} shows a snapshot of the simulation. Contour\nplot depicts pressure and reflects the presence of a leading shock\nand an expansion fan.\n\\begin{figure}\n \\center\n \\includegraphics[scale=.4]{M2wedge.png}\n\n \\caption{$20^o$ wedge moving at Mach 2.0 through initially stationary\nair. Contour plot depicts pressure.}\n \\label{figwedge}\n\\end{figure}\n\\newpage\n%\n%__________________________________\n\\subsection*{\\center Cylinder in a Crossflow}\n\\addcontentsline{toc}{subsection}{Cylinder in a Crossflow}\n\\subsubsection*{\\underline{Problem Description}}\nIn this example the domain is initially filled with air moving at a uniform velocity of $0.03m/s$ A ridgid cylinder $O.D. = 0.02m$ is placed $0.1m$ from the inlet and a passive scalar is injected into the domain through a $0.002m$ hole on in the inlet boundary of the domain. A velocity perturbation is placed upstream of the cylinder to produce an instablity that will help trigger the onset of the K\\'arm\\'an vortex street.\n%\n\\subsection*{\\underline{Simulation Specifics}}\n\\begin{description}\n\\item [Component used:] \\hfill rmpmice (Rigid MPM-ICE)\n\\item [Input file name:] \\hfill \\TT{cylinderCrossFlow.ups}\n\\item [Command used to run input file:]\\hfill \\\\\n\\TT{mpirun -np 6 sus inputs/UintahRelease/MPMICE/cylinderCrossFlow.ups}\n\n\\item [Simulation Domain:]\\hfill 0.3 x 0.15 x 0.001 m\n\n\\item [Cell Spacing:]\\hfill \\\\\n.00015 x .001 x .001 m (Level 0)\n\n\\item [Example Runtimes:] \\hfill \\\\\n 7ish hrs (6 processor, 3.16 GHz Xeon)\\\\\n\n\\item [Physical time simulated:] \\hfill 60 seconds\n\n\\item [Associated visit session:] \\hfill cyl\\_crossFlow.session\n\n\\end{description}\n\n\\section*{\\underline{Results}}\n\nFigure~\\ref{fig:cylCrossFlow} shows a snapshot of the simulation at time $t=60sec$. The contour\nplot of the passive scalar shows the K\\'arm\\'an vortex street behind the cylinder at $Re=700$.\n\\begin{figure}\n \\center\n \\includegraphics[scale=.5]{cylCrossFlow.png}\n \\caption{Flow over a stationary cylinder, $Re=700$, a passive scalar is used as a flow marker}\n \\label{fig:cylCrossFlow}\n\\end{figure}\n%\nA movie of the results is located at\n\\begin{Verbatim}[fontsize=\\footnotesize]\n movies/cyl_crossFlow.mpg\n\\end{Verbatim}\n\\newpage\n\n%__________________________________\n\\subsection*{\\center Copper Clad Rate Stick (aka ``Cylinder Test\")}\n\\addcontentsline{toc}{subsection}{\"Cylinder Test\"}\n\\subsubsection*{\\underline{Problem Description}}\n\nThis is a two-dimensional version of the ``cylinder test\" which is used to\ncharacterize equations of state for explosive products. In those tests, a\ncopper tube is filled with a high explosive and a detonation is initiated\nat one end. Various means are used to measure the velocity of the tube as\nthe high pressure product gases expand inside of it.\n\nHere, a cylinder ($r=2.54 cm$) of QM100 is jacketed with a copper cylinder\nthat has a wall thickness of $0.52 cm.$ Detonation is initiated by giving\na thin layer of the explosive a high initial velocity in the axial direction\nwhich generates a pressure that is sufficiently high to reach trigger the\ndetonation model. As the detonation proceeds, the copper is pushed out of\nthe domain by the expanding product gases.\n\nNote that in this example, to make run times brief, the domain is very short\nin the axial direction, and is probably not sufficient for the detonation to\nreach steady state. Additionally, the domain has been reduced to two\ndimensions, as symmetry is assumed in the Z-plane. Finally, the spatial\nresolution of $1.0 mm$ is a bit coarse to achieve \nconvergent results. The full three dimensional result can quickly be\nobtained by commenting out the symmetry condition on the z+ plane and\nuncommenting the Neumann conditions, as well as changing the spatial extents\nand resolution in the Z direction to match those in the Y direction.\n\n%\n\\subsubsection*{\\underline{Simulation Specifics}}\n\\begin{description}\n\\item [Component used:] \\hfill mpmice (MPM-ICE)\n\\item [Input file name:] \\hfill \\TT{QM100CuRS.ups}\n\\item [Command used to run input file:]\\hfill \\\\\n\\TT{sus inputs/UintahRelease/MPMICE/QM100CuRS.ups}\n\n\\item [Simulation Domain:]\\hfill 0.055 x 0.032 x 0.0005 m\n\n\\item [Cell Spacing:]\\hfill \\\\\n1.0 mm x 1.0 mm x 1.0 mm (Level 0)\n\n\\item [Example Runtimes:] \\hfill \\\\\n 20 minutes (1 processor, 3.16 GHz Xeon)\\\\\n\n\\item [Physical time simulated:] \\hfill 30 $\\mu$seconds\n\n\\item [Associated visit session:] \\hfill QM100.session\n\n\\end{description}\n\n\\subsubsection*{\\underline{Results}}\n\nFigure~\\ref{fig:QM100} shows a snapshot of the simulation at time $t=60sec$.\nParticles are colored by velocity magnitude, contours reflect the density of\nexplosive, note the highly compressed region near the shock front.\n\\begin{figure}\n \\center\n \\includegraphics[scale=.45]{QM100.png}\n \\caption{Detonation in a copper cylinder (2-D). Particles are colored by\n velocity magnitude, contours indicate density of unreacted\n explosive.}\n \\label{fig:QM100}\n\\end{figure}\n%\n\\newpage\n\n%________________\n\\section*{\\center Cylinder Pressurization Using Simple Burn}\n\\addcontentsline{toc}{subsection}{Cylinder Pressurization Using Simple Burn}\n\\subsection*{\\underline{Problem Description}}\nThis example demonstrates use of the Simple Burn algorithm in an explosive scenario. \nThe exact situation consists of a cylinder of PBX encased in steel. For simplicity it is set up \nas a 2D simulation. It demonstrates Symmetric boundaries as a useful construct for simplifying\nthe computational requirements of a problem. The end result is the pressurization of a quarter\nof a cylinder by combustion of PBX 9501. Damage and failure models simulate cylinder failure\nin a detonation scenario. The simulation as it stands falls far short of the required physical time \nsimulated for actual detonation, but demonstrates how Simple Burn can be used to pressurize \na cylinder. For description of Simple Burn see \\ref{Sec:SimpleBurn}.\n\n\\subsection*{\\underline{Simulation Specifics}}\n\\begin{description}\n\\item [Component used:] \\hfill mpmice (MPM-ICE)\n\\item [Input file name:] \\hfill guni2dRT.ups\n\\item [Preprocessing on input file:]\\hfill \\\\ 1) Comment out or remove $<$max\\_Timesteps$>$ on line 21 \\\\\n2) Comment out $<$outputTimestepInterval$>$ on line 96 \\\\ \n3) add $<$outputInterval$>$5e-5$<$outputInterval$>$ on line 97 \\\\\n\\item [Command used to run input file:]\\hfill mpirun -np 4 sus inputs/UintahRelease/MPMICE/guni2dRT.ups\n\n\\item [Simulation Domain:]\\hfill 8.636 x 8.636 x 0.16933 cm\n\n\\item [Example Runtimes:] \\hfill \\\\\n2 minutes (1 processor, 2.8 GHz Xeon)\\\\\n\n\\item [Physical time simulated:] \\hfill 8 microseconds \\\\ \n\n\n\\item [Associated visit session:] \\hfill SimpleBurn.session\n\n\\end{description}\n\n\\newpage\n\n\\section*{\\underline{Results}}\nWith the recession of mass comes a pressure increase that causes the\ncase to expand outward. A snapshot of pressure after the 0.4\nmilliseconds can be seen in Figure~\\ref{figsimburn1}. At this time\npressure has increased to three-fold its initial value. A later\nsnapshot Figure~\\ref{figsimburn2} shows the response of the steel\ncylinder to increased pressure. Note that mass flux will scale\naccording to \\ref{simburneqn}. Another interesting view of the\nsimulation can be seen in Figure~\\ref{figsimburn3}. On the left is\nthe normal particle and pseudocolor map representing solid mass and\npressure respectively. On the top right, change in pressure during\nthe timestep can be seen (delP\\_Dilatate). The bottom shows change in\npressure due to mass exchange (del\\_MassX). See table\n\\ref{table:iceLabels} for description of these variables.\n\n\n% \\begin{figure}\n% \\center\n% \\includegraphics[scale=.3]{SimpleBurn0000.png}\n\n% \\caption{Receding PBX9501 leads to pressure increase in cylindrical steel shell.}\n% \\label{figsimburn1}\n% \\end{figure}\n\n% \\begin{figure}\n% \\center\n% \\includegraphics[scale=.3]{SimpleBurn0001.png}\n\n% \\caption{Pressure increase causes cylinder to respond.}\n% \\label{figsimburn2}\n% \\end{figure}\n\n% \\begin{figure}\n% \\center\n% \\includegraphics[scale=.3]{SimpleBurn0002.png}\n\n% \\caption{The left half of the image represents particles as spheres colored according to mass and pressure as background color. Top-right shows delP\\_Dilatate and bottom-right shows delP\\_MassX.}\n% \\label{figsimburn3}\n% \\end{figure}\n\n\n\\begin{figure}\n \\centering\n \\vspace{-60pt}\n \\subfloat[Receding PBX9501 leads to pressure increase in cylindrical steel shell]{\\label{figsimburn1}\n \\includegraphics[width=.4\\textwidth]{SimpleBurn0000.png}}\n \\hspace{10pt}\n \\subfloat[Pressure increase causes cylinder to respond]{\\label{figsimburn2}\n \\includegraphics[width=.4\\textwidth]{SimpleBurn0001.png}}\n \\hspace{10pt}\n \\subfloat[The left half of the image represents particles as spheres colored according to mass and pressure as background color. Top-right shows delP\\_Dilatate and bottom-right shows delP\\_MassX]{\\label{figsimburn3}\n \\includegraphics[width=.4\\textwidth]{SimpleBurn0002.png}}\n \\caption{}\n \\label{}\n \\vspace{-20pt}\n\\end{figure}\n\n\n\\newpage\n\n\n%\n\\section*{\\center Exploding Cylinder Using Steady Burn}\n\\addcontentsline{toc}{subsection}{Exploding Cylinder Using Steady Burn}\n\\subsection*{\\underline{Problem Description}}\nThis problem consistes of a cylinder initially at 600 K causing burning. Steady Burn acts as the model for burning of HE material. More information on Steady Burn can be found in \\ref{Sec:SteadyBurn}. The cylinder is build from an outer shell of steel covering a hollow bored cylinder of PBX9501. The simulation demonstrates the violence of explosions when large voids allow rapid expansion of surface area due to collapse of explosive material into the bore. Information on the violence of explosions with solid and hollow cores can be attained in \\cite{ref:wighteddings}. \n\n\\subsection*{\\underline{Simulation Specifics}}\n\\begin{description}\n\\item [Component used:] \\hfill mpmice (MPM-ICE)\n\\item [Input file name:] \\hfill SteadyBurn\\_2dRT.ups\n\\item [Preprocessing on input file:]\\hfill \\\\ 1) Comment out or remove $<$max\\_Timesteps$>$ \\\\ 2) Comment out $<$outputTimestepInterval$>$ and uncomment $<$outputInterval$>$ around line 101 \\\\\n\\item [Command used to run input file:]\\hfill mpirun -np 4 sus inputs/UintahRelease/MPMICE/SteadyBurn\\_2dRT.ups\n\n\\item [Simulation Domain:]\\hfill 9 x 9 x 0.1 cm\n\n\\item [Example Runtimes:] \\hfill \\\\\n 5 hours (1 processor, 2.8 GHz Xeon)\n\n\\item [Physical time simulated:] \\hfill 3 milliseconds \\\\ \n\n\n\\item [Associated visit session:] \\hfill SteadyBurn.session\n\n\\end{description}\n\n\\newpage\n\n\\section*{\\underline{Results}}\n\nFigure~\\ref{figsteadyburn1} shows a nice view of the cylinder as the\nPBX particles within is collapsing into the void, creating more\nburnable surface area resulting in more violent explosion. Figure\n~\\ref{figsteadyburn2} shows a view of the cylinder as the steel\ncontainer begins to expand outward. Arrows represent the speed at\nwhich the particles in the steel case are expanding outward.\nFigure~\\ref{figsteadyburn3} shows cell flagged as burning by Steady\nBurn.\n\n% \\begin{figure}\n% \\center\n% \\includegraphics[scale=.3]{SteadyBurn0000.png}\n\n% \\caption{Collapse of PBX into hollow bore of explosive device.}\n% \\label{figsteadyburn1}\n% \\end{figure}\n\n% \\begin{figure}\n% \\center\n% \\includegraphics[scale=.4]{SteadyBurn0001.png}\n\n% \\caption{Expansion of steel casing as explosion occurs--response to pressure build-up.}\n% \\label{figsteadyburn2}\n% \\end{figure}\n\n% \\begin{figure}\n% \\center\n% \\includegraphics[scale=.4]{SteadyBurn0002.png}\n\n% \\caption{Burning Cells denoted by red squares.}\n% \\label{figsteadyburn3}\n% \\end{figure}\n\n\n\\begin{figure}\n \\centering\n \\vspace{-40pt}\n \\subfloat[Collapse of PBX into hollow bore of explosive device]{\\label{figsteadyburn1}\n \\includegraphics[width=.4\\textwidth]{SteadyBurn0000.png}}\n \\hspace{10pt}\n \\subfloat[Expansion of steel casing as explosion occurs--response to pressure build-up]{\\label{figsteadyburn2}\n \\includegraphics[width=.4\\textwidth]{SteadyBurn0001.png}}\n \\hspace{10pt}\n \n \\subfloat[Burning Cells denoted by red squares]{\\label{figsteadyburn3}\n \\includegraphics[width=.4\\textwidth]{SteadyBurn0002.png}}\n \\caption{}\n \\label{}\n \n\n\\end{figure}\n\n\n\\newpage\n%\n\\newpage\n\\section*{\\center T-Burner Example Using Unsteady Burn}\n\\addcontentsline{toc}{subsection}{T-Burner Example Using Unsteady Burn}\n\\subsection*{\\underline{Problem Description}}\nThe T-Burner problem was inspired by an article by Jerry Finlinson, Richard Stalnaker and Fred Blomshield in which a T-Burner apparatus was pressurized to a given pressure and ignited \\cite{ref:finlinson1}. The T-Burner composed of a cylinder with HMX on each circular ends, and a pressure inlet halfway between the HMX caps pumps pressure into the vessel parallel to those walls. Finlinson, et. al. measured pressure oscillations in the chamber and this simulation mimics the behavior found of Finlinson's 500 psi experiment. For simplicity and resource minimization, the simulation is set up as a 2D T-Burner. The graphs below shows the pressure oscillations over time compared with that from \\cite{ref:finlinson1}. This simulation demonstrates the utility of Unsteady Burn in simulations where pressure oscillations occur in small places. For more information on Unsteady Burn see \\ref{Sec:UnsteadyBurn}.\n\n\\subsection*{\\underline{Simulation Specifics}}\n\\begin{description}\n\\item [Component used:] \\hfill mpmice (MPM-ICE)\n\\item [Input file name:] \\hfill \\TT{TBurner\\_2dRT.ups}\n\\item [Command used to run input file:]\\hfill mpirun -np 4 sus TBurner\\_2dRT.ups\n\n\\item [Simulation Domain:]\\hfill 0.822 x 0.138 x 0.003 m\n\n\\item [Example Runtimes:] \\hfill \\\\\n 25 minutes (1 processor, 2.8 GHz Xeon)\\\\\n\n\\item [Physical time simulated:] \\hfill 0.46 milliseconds \\\\ \n0.46 milliseconds of simulation equates flag $<$max\\_Timesteps$>$410$$max\\_Timesteps$>$ \\\\ \\\\\nNotes: \\\\\n1)Remove line from input file to allow simulation to run full 0.25 seconds \\\\\n2)Comment out $<$outputTimestepInterval$>$ and uncomment $<$outputInterval$>$ to make output $\\Delta t$ constant \\\\ \n\n\\item [Associated visit session:] \\hfill TBurner.session\n\n\\end{description}\n\n\\newpage\n\n\\section*{\\underline{Results}}\n\nFigure~\\ref{figtburn1}, ~\\ref{figtburn2} and ~\\ref{figtburn3} show successive snapshots of the simulation. Contour plot depicts pressure and represents the wave front as it oscillates between two sheets of burning PBX 9501. Figure ~\\ref{figtburnVel} shows velocities of gas cells.\n% \\begin{figure}\n% \\center\n% \\includegraphics[scale=.4]{TBurner0000.png}\n\n% \\caption{Time 1: Oscillatory behavior in the form of a pressure wave in a T-Burner. Contour plot depicts pressure.}\n% \\label{figtburn1}\n% \\end{figure}\n\n% \\begin{figure}\n% \\center\n% \\includegraphics[scale=.4]{TBurner0001.png}\n\n% \\caption{Time 2: Oscillatory behavior in the form of a pressure wave in a T-Burner. Contour plot depicts pressure.}\n% \\label{figtburn2}\n% \\end{figure}\n% \\begin{figure}\n% \\center\n% \\includegraphics[scale=.4]{TBurner0002.png}\n\n% \\caption{Time 3: Oscillatory behavior in the form of a pressure wave in a T-Burner. Contour plot depicts pressure.}\n% \\label{figtburn3}\n% \\end{figure}\n\n\n\\begin{figure}[H]\n \\centering\n \\vspace{-80pt}\n \\subfloat[Time 1: Oscillatory behavior in the form of a pressure wave in a T-Burner. Contour plot depicts pressure]{\\label{figtburn1}\n \\includegraphics[scale=.4]{TBurner0000.png}}\n\n \\subfloat[Time 2: Oscillatory behavior in the form of a pressure wave in a T-Burner. Contour plot depicts pressure]{\\label{figtburn2}\n \\includegraphics[scale=.4]{TBurner0001.png}}\n\n \\subfloat[Time 3: Oscillatory behavior in the form of a pressure wave in a T-Burner. Contour plot depicts pressure]{\\label{figtburn3}\n \\includegraphics[scale=.4]{TBurner0002.png}}\n\n \\subfloat[Velocity vectors of cell material. Shows how the pressure causes gas to move]{\\label{figtburnVel}\n \\includegraphics[scale=.4]{TBurnerVel0000.png}}\n\n \\caption{}\n \\label{}\n \\vspace{-30pt}\n\\end{figure}\n\n\nFigure~\\ref{figtburnVel} shows a snapshot of the simulation at the same instant as the \nprevious figure. The contour plot depicts pressure. The arrows are vectors depicting\nthe importance \n% \\begin{figure}\n% \\center\n% \\includegraphics[scale=.4]{TBurnerVel0000.png}\n\n% \\caption{Velocity vectors of cell material. Shows how the pressure causes gas to move.}\n% \\label{figtburnVel}\n% \\end{figure}\n\n%\n\\iffalse \n%The pinwheel example was never commited. \n%__________________________________\n\\newpage\n\\section*{\\center Pinwheel}\n\\addcontentsline{toc}{subsection}{Pinwheel}\n\\subsection*{\\underline{Problem Description}}\nThis simulation provides an example of fluid-solid interaction through driving a pinwheel via a supersonic jet of air. A 500 m/s jet of air is directed at the face of one of four fins attached to a hollowed cylinder surrounding a pin. This continuous jet of air spins the wheel around the stationary pin creating an easily visually verifiable fluid-solid interaction model. \n\n\\subsection*{\\underline{Simulation Specifics}}\n\\begin{description}\n\\item [Component used:] \\hfill mpmice (MPM-ICE)\n\\item [Input file name:] \\hfill \\TT{pinWheel.ups}\n\\item [Command used to run input file:]\\hfill \nmpirun -np 6 sus inputs/UintahRelease/MPMICE/pinWheel.ups\n\n\\item [Simulation Domain:]\\hfill 4.5 x 3.0 x 4.5 m\n\n\\item [Example Runtimes:] \\hfill \\\\\n 10 hours (6 processors, 2.66 GHz Xeon)\\\\\n\n\\item [Physical time simulated:] \\hfill 1 second \\\\ \n\n\\item [Associated visit session:] \\hfill pinWheel.session\n\n\\end{description}\n\n\\newpage\n\n\\section*{\\underline{Results}}\n\n\\begin{figure}\n \\centering\n \\vspace{-40pt}\n \\subfloat[Pinwheel driven by a jet of air]{\\label{pinwheel1}\n \\includegraphics[width=.8\\textwidth]{pinWheel.png}}\n \\hspace{10pt}\n \\caption{}\n \\label{}\n\n\\end{figure}\n\nFigure~\\ref{pinwheel1} shows a visualization of the pinwheel alongside the air jet represented by the velocity vectors. The air jet contacts a fin on the wheel causing it to continuously rotate counterclockwise as seen by the colored velocity of the boxes. \n\n\\fi \n\n%__________________________________\n\\newpage\n\\section*{\\center Lizard Lung}\n\\addcontentsline{toc}{subsection}{Lizard Lung}\n\\subsection*{\\underline{Problem Description}}\nThis simulation provides an example of fluid-solid interaction using both a\ncompliant MPM material, as well as a rigid material that is given a prescribed\ntime-velocity profile. The latter acts as a piston that pushes or pulls air\nthough a pair of valves, one of which opens and the other of which closes,\ndepending on the direction of the flow. In addition to the input file, a\nsecond file, ``breathe.txt\", describes the velocity of the piston.\n\nA post-processing script has been added, massFlowRateLL.m. This allows one to \ncompute the mass flow rate through each of the valves. The script runs through\nmatlab, and requires minor editing to modify the uda name, and whether output is\nwanted regarding the top or bottom valve.\n\n\\subsection*{\\underline{Simulation Specifics}}\n\\begin{description}\n\\item [Component used:] \\hfill mpmice (MPM-ICE)\n\\item [Code modification required:]\n\nBecause symmetry boundary conditions are used on the z- and z+ faces, without\nmodification, the center section of the solid geometry, shown in\nFigure~\\ref{lizard}, would rotate into a more favorable aerodynamic position,\nas there is nothing stopping it, other than its inertia. Therefore,\nSerialMPM.cc was modified to keep a block within that section fixed in space.\nThe particles to hold fixed are identified by their ``color\":\n\n\\begin{verbatim}\n // Update the particle's position and velocity\n if(pColor[idx] < 1.0){\n pxnew[idx] = px[idx] + vel*delT*move_particles;\n pdispnew[idx] = pdisp[idx] + vel*delT;\n pvelocitynew[idx] = pvelocity[idx] + acc*delT;\n // pxx is only useful if we're not in normal grid resetting mode.\n pxx[idx] = px[idx] + pdispnew[idx];\n pTempNew[idx] = pTemperature[idx] + tempRate*delT;\n pTempPreNew[idx] = pTemperature[idx]; // for thermal stress\n } else {\n pxnew[idx] = px[idx];\n pdispnew[idx] = pdisp[idx];\n pvelocitynew[idx] = pvelocity[idx];\n // pxx is only useful if we're not in normal grid resetting mode.\n pxx[idx] = px[idx];\n pTempNew[idx] = pTemperature[idx];\n pTempPreNew[idx] = pTemperature[idx]; // for thermal stress\n }\n\\end{verbatim}\n\nThis modification occurs in interpolateToParticlesAndUpdate, around line 3450\nin this file.\n\n\\item [Input file name:] \\hfill \\TT{lizardLung4.ups}\n\\item [Instruction to run input file:] \\hfill \\newline Copy breathe.txt to the same directory as sus.\n\\item [Command used to run input file:]\\hfill \nmpirun -np 16 sus inputs/UintahRelease/MPMICE/lizardLung4.ups\n\n\\item [Simulation Domain:]\\hfill 0.6 x 0.3 x 0.002 m\n\n\\item [Example Runtimes:] \\hfill \\\\\n 18 hours (16 processors, 2.40 GHz Xeon) (Much less time is needed to\nsee the behavior, 18 hours is enough for many piston oscillations.)\\\\\n\n\\item [Physical time simulated:] \\hfill 10 seconds \\\\ \n\n\n\\end{description}\n\n\\section*{\\underline{Results}}\n\n\n\\begin{figure}\n \\centering\n \\vspace{-40pt}\n \\subfloat[Air pushed and pulled by a piston through two check valves.]{\\label{lizard}\n \\includegraphics[width=1.1\\textwidth]{LizardLung.png}}\n \\hspace{10pt}\n \\caption{}\n \\label{}\n\n\\end{figure}\n\nFigure~\\ref{lizard} shows a visualization of the geometry having been deformed by the movement of air caused by the motion of the piston at about x=0.18. The \npiston moves sinusoidally according to the velocity table prescribed in ``breathe.txt\".\n\n\\bibliographystyle{plain}\n\\bibliography{ice}\n", "meta": {"hexsha": "39c2c6ff3bbc2adc4956936c1c38fd26e59ff534", "size": 55354, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/UserGuide/mpmice.tex", "max_stars_repo_name": "abagusetty/Uintah", "max_stars_repo_head_hexsha": "fa1bf819664fa6f09c5a7cd076870a40816d35c9", "max_stars_repo_licenses": ["MIT"], "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/UserGuide/mpmice.tex", "max_issues_repo_name": "abagusetty/Uintah", "max_issues_repo_head_hexsha": "fa1bf819664fa6f09c5a7cd076870a40816d35c9", "max_issues_repo_licenses": ["MIT"], "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/mpmice.tex", "max_forks_repo_name": "abagusetty/Uintah", "max_forks_repo_head_hexsha": "fa1bf819664fa6f09c5a7cd076870a40816d35c9", "max_forks_repo_licenses": ["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.6201733649, "max_line_length": 1080, "alphanum_fraction": 0.7372366947, "num_tokens": 15747, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.531209388216861, "lm_q2_score": 0.37022538564692037, "lm_q1q2_score": 0.196667200611852}}
{"text": "% *********** Document name and reference:\n% Title of document\n\\renewcommand{\\ndoctitle}{NuPyCEE} \n% Document category acronym \n\\renewcommand{\\ndocname}{NuPyCEE} \n% svn dir\n\\renewcommand{\\svndir}{svn://forum.astro.keele.ac.uk/utils/GCE/NuPyCEE} \n% Contributors to this document\n\\renewcommand{\\ndoccontribs}{Christian Ritter, Benoit C\\^ot\\'e}\n\n%\\input{chap}\n\nDocument name: \\ndocname \\\\\nSVN directory: \\svndir\\\\\nContributors: \\ndoccontribs\\\\\nPlease send any feedback to critter@uvic.ca or bcote@uvic.ca. Thank you.\n\n\n{ \\textbf{Abstract:} %\\slshape{}\n%\\begin{abstract}\n\\noindent The Nugrid-Python-Chemical-Evolution Environment, short NuPyCEE, provides\na framework to simulate the ejecta of simple stellar populations with the 1-zone code\nStellar Yields for Galactic Modeling Applications as well as galaxies\nwith the One-zone Model for the Evolution of Galaxies.\nVarious chemical evolution input parameters can be specified through a python-based interface.\nBoth tools provide extraction and plotting methods.\nWe also provide a web interface with limited capabilities which allows to download\nyield tables containing the ejecta of SSPs. \nTo compare the results to observational data, the user can utilize the STELLAB module\nwhich provides various spectroscopic abundance ratios of stars observed in the \nMilky Way and local dwarf spheroidal galaxies.\n%\\end{abstract}\n}\n\n%##############################################################\n%# Section: Introduction\n%##############################################################\n\n\n\\section{Introduction}\n\\index{\\ndocname}\nWelcome to the \\ndocname\\ user Guide. The purpose of \\ndocname\\ is to \nprovide the user with a framework to perform chemical evolution calculations.\nThe focus lies on simplification and user-friendliness.\nThe user can choose between the \\textit{Stellar Yields for Galactic Modeling Applications} (SYGMA) module \nand the \\textit{One-zone Model for the Evolution of Galaxies} (OMEGA) module.\nSYGMA allows to follow the ejecta of simple stellar populations in a closed box while OMEGA deals with\nthe simulation of galaxies with inflows and outflows.\nBoth tools can be used in a similar manner through the ipython command line or\nipython notebooks.\n%However included are low-mass, intermediate and massive star contributions, including\n%SN2 and SN1a.\n\n%This section will provide the user with a \n%tutorial and walk through of the tools contained within \\ndocname\\ and\n%how a typical user would go about using and working with this python module.\n%Note also that each SYGMA version provides a python-based function documentation (Sphinx) \n%in Sphinx\\textunderscore DOC which can be accessed with the web brower through build/html/index.hmtl.\n\n\\subsection{Fastest possible instruction}\n\nTo download the code\nyou need to have git installed on your local machine.\nThen download the code from github at\n\n\\url{https://github.com/NuGrid/NuPyCEE}\n\ninto your local directory via\n\n\\begin{verbatim}\ngit clone https://github.com/NuGrid/NuPyCEE.git .\n\\end{verbatim}\n\nInstall ipython with numpy and matplotlib and\nnugridpy via\n\n\\begin{verbatim}\npip install nugridpy\n\\end{verbatim}\n\nStart ipython in the NuPyCEE directory with\n\n\\begin{verbatim}\nipython -pylab -p numpy\n\\end{verbatim}\n\nTo run a SYGMA calculation:\n\n\\begin{verbatim}\nimport sygma as s\ns1=s.sygma()\n\\end{verbatim}\n\nThat's it! To plot the total mass ejected:\n\n\\begin{verbatim}\ns1.plot_totmasses(source='all')\t\n\\end{verbatim}\n\n%More plot functions are available: s1.plot$<$tab$>$.\n%Use a question mark after the plotting function\n%for more infos.\n\nTo run OMEGA:\n\n\\begin{verbatim}\nimport omega as o\no1=o.omega()\n\\end{verbatim}\n\n\\begin{verbatim}\no1.plot_spectro(xaxis='[Fe/H]',yaxis='[O/Fe]')\n\\end{verbatim}\n\nNow you might want to compare the prediction with\nobservations through the STELLAB module.\n\n\\begin{verbatim}\nimport stellab as st\nst1=st.stellab()\nst1.plot_spectro(xaxis='[Fe/H]', yaxis='[O/Fe]')\n\\end{verbatim}\n\n\n\n\n%Check out the documentation in Section \\ref{sect_omega}. \n\n\\subsection{Preparing the environment}%Tutorial and Walkthough}\n\nTo take advantage of the interactive ipython environment \nSYGMA and OMEGA are both launched after starting\nipython with\n\n\n\\begin{verbatim}\nipython -pylab -p numpy\n\\end{verbatim}\n\nwhere the modules numpy and matploblib have to be installed.\nAlso you might need to install other python modules (e.g., h5py).\n\nA necessary dependence is NuGrid's pylib toolbox nugridpy which\ncontains a number of python scripts. It can simply be installed via\npip:\n\n\\begin{verbatim}\npip install nugridpy\n\\end{verbatim}\n\n\n%Make sure your PYTHONPATH variable is pointing to this directory.\n\n\\subsection{SYGMA}\n\n\\subsubsection{General concepts}\n\nIn order to follow the chemical enrichment via gas particles\nin hydrodynamical simulations one has to describe the ejecta of material\nfrom such star particles, essentially simple stellar populations. \nWith SYGMA one can follow the ejecta of such populations via\ndiagrams and you can extract the composition of the ejecta via tables.\n\n\n\\subsubsection{Getting started}\n\nIf one wants to start SYGMA from outside the SYGMA directory\none has to specify the $SYGMADIR$ variable which\npoints to the SYGMA dir.\n\nImport the module:\n\n\\begin{verbatim}\nimport sygma as s\n\\end{verbatim}\n\nNext, we create an SSP instance, initiate a class instance $s1$ of SYGMA:\n\n\n\\begin{verbatim}\ns1=sygma.sygma(iniZ=0.0001,tend=1e10,mgal=1e9)\n\\end{verbatim}\n\nA single stellar population of mass $1\\times10^{9}\\msun$ and metal fraction\nof $0.0001$ is created and evolved in time steps of $10^{8}$ years\nto the final time of 1e10 years. Other not specified and hence\ndefault parameter include for example the choice of the initial-mass function.\n%range of $1\\msun$ up to $30\\msun$ is used. NuGrid tables \n%and SN1a yields from Thielemann86 are taken\n\n\nOne can check the definition of these input parameter online via\n\\url{http://nugrid.github.io/NuPyCEE/SPHINX/build/html/sygma.html}.\n\n\nNo yield tables are defined and hence the NuGrid tables as the\ndefault choice were selected. These are the Set1 and Set1extension\nyields which are\n%\\begin{verbatim}\n%s1=sygma.sygma(alphaimf=2.35,sfr='input',iniZ=0.0001,dt=1e8,tend=1e10,mgal=1e9,\n% table='yield_tables/isotope_yield_table.txt',\n% sn1a_table='yield_tables/sn1a_t86.txt',\n% bb_table='yield_tables/bb_walker91.txt')\n%\\end{verbatim} \nAGB and massive star yields for five different metallicities.\nIn this mode the user specifies $iniZ$\nwhich can be either $Z=2e-2, 1e-2, 6e-3, 1e-3, 1e-4$ and $0.0$.\nScaled abundances for Z=1e-t65, 1e-6 will be available soon.\nCurrently for $Z=0$ the PopIII stars from Heger et al. (2010) are set\nas default.\n\n\\subsubsection{Providing your own yield tables}\n\nYield tables are available in the NuPyCEE subdirectory \nyield\\textunderscore tables. Add your yield tables to\nthis directory and SYGMA will be able read the table\nif you have specified the $table$ variable. Only\nfor table of Z=0 the variable $pop3\\textunderscore table$ is used.\nBoth tables need yields specified in the SYGMA (and OMEGA)\nyield input format. See for the structure the default table.\nIt is important to provide an initial abundance\nfile which has to match the number of species provided in the yield tables.\nProvide the file in the iniAbu directory inside the directory yield\\textunderscore tables.\nThe input variable with which the table file can be specified is $iniabu\\textunderscore table$.\nFor the necessary structure see again the default choice of that variable.\n%Another subdirectory,\n%plotting\\textunderscore scripts, contains various \n%plotting scripts. The latter use SYGMA's plotting functions.\n\n\n\\subsubsection{What do I get out?}\n\n\nThe output during execution shows some initial parameters,\ne.g. the isotopes being part of chemical evolution,\nas well as the time and metallicity evolution.\nAlso shown is the contribution time of stars of \ncertain initial mass.\n\n\n\n%For more examples, see the SYGMA ipython notebooks available\n%at \\\\http://208.75.74.161:8888/tree/Publicnotebooks/intro\\textunderscore SYGMA.\n\nTo analyze the run afterwards we provide a variety of plotting functions\nwhich are described in detail at \\url{http://nugrid.github.io/NuPyCEE/SPHINX/build/html/sygma.html}.\nIn following we give some examples. The function plot\\textunderscore mass() shows the evolution\nof the yield in solar masses.\n\n\n\\begin{verbatim}\ns1.plot_mass()\n\\end{verbatim}\n\nWith SYGMA you can look at different contributions\nfor AGB stars, massive stars, and SN~Ia.\n\n\\begin{verbatim}\ns1.plot_mass(source='agb')\ns1.plot_mass(source='massive')\ns1.plot_mass(source='sn1a')\n\n\\end{verbatim}\n\nNote that those lines appear all in one figure.\n%The solar abundance distribution is taken from GN93 (NuGrid file).\n\n%To get an overview over the available abundance distribution\n%(in mass fraction divided by solar mass fraction) of the gas\n%reservoir at a certain timestep, a function\n%called plot\\textunderscore abu\\textunderscore distr() is available.\nThe function $plot\\textunderscore mass\\textunderscore range\\textunderscore contributions()$\nshows the yield contribution of stars as a function of their initial mass.\nIt allows to identify which mass range contributes to certain elements.\n%Also plotted is to each yield (grid input) corresponding mass range\n%as vertical lines. In these intervals the yields are the same (for one \n%simple stellar population).\nTo monitor the evolution of the mass of the gas reservoir ejected\nmasses over time, use plot\\textunderscore totmasses().\nThe star formation rate as a function of time can be plotted with the function $plot\\textunderscore sfr()$.\nIn the case you want to write out detailed chemical evolution tables\nof isotopes, use the function $write\\textunderscore evol\\textunderscore table()$.\nIt writes out the mass of isotopes ejected by stars as a function of time\n(each line represents a timestep).\n\n\\subsection{OMEGA}\n\n\\subsubsection{General concepts}\nOMEGA is a classical one-zone, open-box galaxy model with\nan input star formation history where stars form and inject new elements within\nthe same gas reservoir, using SYGMA to create a SSP at every timestep.\nAt any time, each existing SSP ejects material that reflects its age, mass, and initial metallicity.\nOMEGA can mimic known local galaxies, such as Sculptor, Carina, and Fornax,\nby using the observed star formation history and current mass, which is taken\nfrom the literature. It also offers the possibility to mimic the Milky Way, but we\nwarn the user that a one-zone model is probably too simplistic to simulate the\nevolution of massive and complex galaxies, although they are useful for testing\nstellar yields.\n\nThe code offers three different prescriptions for treating gas inflows and outflows\n(see the OMEGA Userguide ipython notebook on WENDI, \\url{http://www.nugridstars.org/projects/wendi}). \nInflows and outflows can be independently switched off to consider a semi-open box or a closed box model.\nThe different prescriptions can also be found in C\\^ot\\'e et al. (2016, \\url{http://adsabs.harvard.edu/abs/2016arXiv160407824C}).\n\nA complete description of OMEGA's input parameters and functions can\nbe found in the Sphinx documentation (\\url{http://nugrid.github.io/NuPyCEE/SPHINX/build/html/omega.html}). \nAll the SSP parameters associated with SYGMA are available with OMEGA as well.\n\n\\subsubsection{Getting Started with OMEGA}\n\nWe refer to the OMEGA Userguide ipython notebook on WENDI (\\url{http://www.nugridstars.org/projects/wendi})\nfor more information about how to use OMEGA with command lines, and how to use plotting functions\nto analyze the predicted chemical evolution of the target galaxy.\n\n\n\\subsection{STELLAB}\n\nSTELLAB (short for Stellar Abundances) is a module that allows to plot the stellar abundances \nobserved in different galaxies. So far, data are available for the Milky Way, Sculptor, Fornax, Carina,\nand the LMC. This code uses an input collection of data and plots any abundance ratio [X/Y] as \na function of another one. It also offers the possibility to re-normalize all data to the same solar\nnormalization. It is a useful and complementary tool that enables to confront numerical predictions\nwith observations.\n\nWe refer to the STELLAB Userguide ipython notebook on WENDI (\\url{http://www.nugridstars.org/projects/wendi})\nfor more information on its usage, options, and collection of data. It should be noted that observational\ndata have not been curated, but have rather been blindly taken from the literature. We are currently\nworking on a curation process in collaboration with JINA-CEE members (\\url{http://www.jinaweb.org}).\n\n\\section{Disclaimer}\n\n\t\t\n\\section{History} \nThis document history complements the svn log.\n\n\\begin{tabular*}{\\textwidth}{lll}\n\\hline\nAuthors & yymmdd & Comment \\\\\nCR & 130926 & Update of links and details \\\\\n\\hline\nCR & 160513 & creation \\\\\n\\end{tabular*}\n\n\n\\subsection{Contact}\nIf any bugs do appear or if there are any questions, please email critter@uvic.ca or bcote@uvic.ca\n% --------------- latex template below ---------------------------\n\\begin{verbatim}\n\n\\end{verbatim}\n\n\n%\\begin{figure}[htbp]\n% \\centering\n%% \\includegraphics[width=\\textwidth]{layers.jpg} % \n% \\caption{} \\includegraphics[width=0.48\\textwidth]{FIGURES/HRD90ms.png} \n% \\includegraphics[width=0.48\\textwidth]{FIGURES/HRD150ms.png} \n%\n% \\label{fig:one}\n%\\end{figure}\n%\n%\\begin{equation}\n%Y\\_a = Y\\_k + \\sum\\_{i \\neq k} Y\\_i\n%\\end{equation}\n%\n%{\n%%\\color{ForestGreen}\n%\\sffamily \n% {\\center --------------- \\hfill {\\bf START: Some special text} \\hfill ---------------}\\\\\n%$Y\\_c$ does not contain ZZZ but we may assign one $Y_n$ to XYZ which is the decay product of the unstable nitrogen isotope JJHJ. %\n%\n%{\\center --------------- \\hfill {\\bf END:Some special text} \\hfill ---------------}\\\\\n%}\n\n\n\n", "meta": {"hexsha": "b91d2b25a064d506b058cff6a21e5b791d4b1ee7", "size": 13799, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "DOC/nupycee.tex", "max_stars_repo_name": "GuoZiYi-astro/NuPyCEE", "max_stars_repo_head_hexsha": "9d54ffa6aa120ef60f2a06de353d1bcbfee6ca16", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 22, "max_stars_repo_stars_event_min_datetime": "2016-05-24T15:59:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-16T08:32:31.000Z", "max_issues_repo_path": "DOC/nupycee.tex", "max_issues_repo_name": "GuoZiYi-astro/NuPyCEE", "max_issues_repo_head_hexsha": "9d54ffa6aa120ef60f2a06de353d1bcbfee6ca16", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 15, "max_issues_repo_issues_event_min_datetime": "2016-05-30T15:57:40.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-23T14:20:54.000Z", "max_forks_repo_path": "DOC/nupycee.tex", "max_forks_repo_name": "GuoZiYi-astro/NuPyCEE", "max_forks_repo_head_hexsha": "9d54ffa6aa120ef60f2a06de353d1bcbfee6ca16", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2016-10-20T10:13:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-13T09:14:49.000Z", "avg_line_length": 36.6021220159, "max_line_length": 131, "alphanum_fraction": 0.7676643235, "num_tokens": 3506, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.3702253925955866, "lm_q1q2_score": 0.1966671988077545}}
{"text": "\\subsubsection{\\stid{3.01} hypre} \n\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 has some 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. Current interpolation strategies that lead to best convergence and performance on distributed memory machines are not suitable for implementation on GPUs or similar architectures requiring extreme parallelism. 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 two 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 will also investigate the use of HIP and SYCL for AMD and Intel accelerators that will be available on future exascale computers.\n\n\\paragraph{Recent Progress}\n\nPreviously, we enabled the structured solvers, SMG and PFMG\\cite{AsFa1996}, both setup and solve phase, to completely run on GPUs, using both CUDA or OpenMP4.5, and to not require unified memory. In addition, options to use RAJA and Kokkos are available.\nPorting the unstructured solver, BoomerAMG turned out to be far more complex. We first ported the solve phase to GPUs for select smoothers, mainly Jacobi smoothers, requiring unified memory. During the last year, we focused on enabling selected components of the setup phase to run on GPUs, specifically PMIS coarsening, direct interpolation, and the generation of the coarse grid operator, which consists of the multiplication of three sparse matrices. Figure \\ref{fig:rap} shows runtime comparisons of different implementations of the coarse grid operator generation on one V-100 GPU or one Power 9, which demonstrate that the hypre GPU implementation outperforms state-of-the-art implementations such as CUSP and cuSPARSE. It is now possible to perform a complete linear system solve with BoomerAMG on GPUs using specific settings.\n\n\\begin{figure}\n\\centering\n\t\\includegraphics[width=5in]{projects/2.3.3-MathLibs/2.3.3.12-SUNDIALS-hypre/hypre-rap-1gpu.png}\n\t\\caption{\\label{fig:rap} Runtimes to generate a coarse grid operator for a 7pt 3d Laplace problem matrix on 1 V-100 GPU or Power 9 CPU with up to 20 OMP threads for various implementations}\n\\end{figure}\n\nWe also implemented a new integer datatype called HYPRE$\\_$BigInt to avoid the requirement that all integers need to be converted to 64 bit integers when solving linear systems greater than 2 billions using the unstructured solvers. The new datatype allows to only convert variables that need to be 64 bit integers and improves memory usage and performance, as illustrated in Figure \\ref{fig:mixed-int}.\n\n\\begin{figure}\n\\centering\n\t\\includegraphics[width=3in]{projects/2.3.3-MathLibs/2.3.3.12-SUNDIALS-hypre/hypre-mixed-int.png}\n\t\\caption{\\label{fig:mixed-int} Weak scaling study on LLNL Linux cluster Quartz: Total runtimes in seconds for AMG-PCG using 1M points/core for 2 different 3D diffusion problems.The new mixed-int capability performs about 20-25 percent better than the 64 bit integer version while using less memory and is capable to solve larger problems than the 32 bit integer version.}\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}. This includes converting various components that are currently running only on the CPU to be usable on the GPU using CUDA or OpenMP 4.5. We will particularly focus on additional setup components, such as interpolation operators, to achieve better convergence.\n\\item We also plan on improving the efficiency of interfacing applications with {\\sl hypre}'s solvers.\n\\end{itemize}\nIn addition, we will work with ECP application teams who are using {\\sl hypre}, such as ExaWind, or would like to use it, to achieve best performance by tuning the solvers for them and potentially implementing suitable algorithmic changes. \n\n\n", "meta": {"hexsha": "c54c984e486ed5272a96e5c022b5530bd8333dd0", "size": 7201, "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": "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-hypre.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-hypre.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": 156.5434782609, "max_line_length": 1624, "alphanum_fraction": 0.8153034301, "num_tokens": 1555, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583270090337583, "lm_q2_score": 0.35220177524832036, "lm_q1q2_score": 0.19664376375077466}}
{"text": "\\section{Experiments and Results}\n\nWe conducted a variety of experiments to audit our previously\ndescribed approach. As a running example we used a DNN which we\ntrained on images from a generated dataset we dubbed \\emph{Picasso\n Dataset}. The foundation are images of human faces we took from the\nFASSEG dataset~\\cite{khan2015multi,khan2017head}.\nThe Picasso Dataset contains collage images of faces with the facial\nfeatures (eyes, mouth, nose) either in the correct constellation\n(positive class) or in a mixed-up constellation (negative class). See\nFig.~\\ref{fig:picasso} for examples.\nNo distinction is made between originally left and right eyes.\n\n\\begin{figure}\n \\begin{center}\n \\includegraphics[width=.15\\textwidth]{pic_00001_pos.png}\\quad\n \\includegraphics[width=.15\\textwidth]{pic_00009_pos.png}\\qquad\\qquad\n \\includegraphics[width=.15\\textwidth]{pic_00000_neg.png}\\quad\n \\includegraphics[width=.15\\textwidth]{pic_00001_neg.png}\n \\end{center}\n \\caption{Examples from the Picasso Dataset\n (\\textit{left:} positive class, \\textit{right:} negative).}\n \\label{fig:picasso}\n\\end{figure}\n\nIn order to not establish a divergence in the image space of the two\nclasses, the positive and negative classes contain facial features\nthat were cut out of a set of images from the original FASSEG\ndataset. As a canvas to include the features, we took a set of\noriginal faces and got rid of the facial features by giving the\ncomplete facial area a similar skin-like texture. Then we included the\ncut out facial features onto the original positions of the original\nfeatures in the faces.\n\nThe face images in Fig.~\\ref{fig:picasso} show that\nthe resulting dataset is rather constructed. This however will suffice for\na proof of concept to show that our approach in fact exploits object parts\nand their relations. In the future we plan on moving towards more natural\ndatasets.\n\n\\subsection{Analyzed DNNs}\nWe evaluated our method on three different architectures from the pytorch\nmodel-zoo\\footnote{\\url{https://pytorch.org/docs/stable/torchvision/models.html}}:\nAlexNet~\\cite{krizhevsky_one_2014},\nVGG16~\\cite{simonyan_very_2015}, and\nResNeXt-50~\\cite{xie_aggregated_2017}.\nThe convolutional parts of the networks were initialized with weights\npre-trained on the ImageNet dataset.\nFor fine-tuning the DNNs for the Picasso Dataset task,\n% \nthe output dimension was reduced to one and the in- and output\ndimension of the second to last hidden dense layer was reduced to 512\nfor AlexNet and VGG16.\nThen the dense layers and the last two convolutional layers\n(AlexNet, VGG16) respectively bottleneck blocks (ResNeXt) were fine-tuned.\n% \nThe fine-tuning was conducted in one epoch on a training set of 18,002\ngenerated, $224\\times224$-sized picasso samples with equal\ndistribution of positive and negative class.\nAll models achieved accuracy greater than 99\\%\non a test set of 999 positive and 999 negative samples.\n\n% The fine-tuning failed for VGG16 when initialized with weights from\n% the VGG face dataset, which we explain with the sub-optimal alignment\n% of the objectives between VGG face and the Picasso Dataset.\n\n\\subsection{Training the Concept Models}\n%%% Concept Data\nIn our example we determined the best ensembled detection concept vectors for\nthe concepts \\textsc{eyes}, \\textsc{mouth} and \\textsc{nose} amongst the\nconsidered layers.\n% \n%%% Analyzed Model Layers\nWe excluded layers with low receptive field, as they are assumed to\nhold only very local features\n(for the layers used see Fig.~\\ref{fig:layerwiseresults}).\nConvolutional output was only considered after the activation.\n% ResNeXt: starting at bottleneck modules 4/16,\n% VGG16: starting at conv layer 5/13,\n% AlexNet: starting at conv layer 2/5\n% \n\\begin{figure}%\n \\centering%\n \\hspace*{-0.08\\textwidth}\\includegraphics[width=1.16\\textwidth]{layerwise_results_concept_embedding}\n \\caption{The layer-wise mean set IoU results of the concept analysis runs.}\n \\label{fig:layerwiseresults}\n\\end{figure}\n% \nFor each concept, 452 training/validation, and 48 test picasso samples\nwith segmentation masks were used.\n% The concept window size determining the kernel size of the concept\n% model convolution was chosen as the mean boxed size of the concept.\n% The latter was chosen as\n% $0.15\\times0.05$ for the nose,\n% $0.08\\times0.2$ for the mouth, and\n% $0.08\\times0.16$ for an eye.\nThe training objective was: Predict at each activation map pixel\nwhether the kernel window centered there lies \\enquote{over}\nan instance of the concept. Over meant that the fuzzy intersection of\nthe concept segmentation and the kernel window area exceeds a threshold\n(\\emph{intersection encoding}).\nThis fuzzy definition of a box center\n% introduces some noise to the ground truth, but\ntackles the problem of sub-optimal intersections in later layers\ndue to low resolution.\n% At a threshold greater or equal 0.5 masks are smoothed and sharpened.\nToo high values may lead to elimination of an instance,\n% Intersection over union (IoU) encoding is especially vulnerable to this for\n% small concepts, wherefore we preferred intersection encoding.\nand thresholds were chosen to avoid such issues with\nvalues 0.5/0.8/0.7 for nose/mouth/eye.\nWe implemented the encoding via a convolution.\nAs evaluation metric we use set IoU (sIoU) between the detection\nmasks and the intersection encoded masks as in Net2Vec.\n% \n%%% Optimization Method\nOn each dataset and each layer, 15 concept models were trained in\nthree 5-fold-cross-validation runs with the following settings:\nAdam optimization with mean best learning rate of 0.001,\na weighting of 5:1 of Dice to bBCE loss,\nbatch size of 8, and\ntwo epochs (all layers showed quick convergence).\n% \\begin{align*}\n % \\text{Loss}(M_\\text{pred}, M)\n % &= \\lambda_\\text{Dice} \\text{Dice}(M_\\text{pred}, M) +\n % \\lambda_\\text{bBCE} \\text{bBCE}(M_\\text{pred}, M) \\\\\n % \\text{Dice}(M_\\text{pred}, M)\n % &= \\frac{2\\cdot MM_\\text{pred}}\n % {2\\cdot MM_\\text{pred} + (1-M)M_\\text{pred} + M(1-M_\\text{pred})} \\\\\n % \\text{bBCE}(M_\\text{pred}, M)\n % &= b M \\log(M_\\text{pred}) + (1-b) (1-M) \\log(1-M_\\text{pred})\n % \\end{align*}\n % for a ground truth intersection encoded mask $M$,\n % a predicted mask $M_\\text{pred}$,\n % $b=0.99$ the mean proportion of background pixels in a concept mask\n % (chosen for nose 0.999, else 0.995),\n % and $\\lambda_\\text{Dice}=0.5$ and $\\lambda_{bBCE}=0.1$.\n % We recorded slightly worse results for higher weighting of the binary\n % cross-entropy part or balancing of the Dice loss towards less false\n % positives or less false negatives as described in\n % \\cite{salehi_tversky_2017}.\n % \n\n\\paragraph{Results}\n%%% ensemble performance pretty well coincides with mean performance, sometimes slightly better (possibly due to implicit confidence calibration)\nOur normalized ensembling approach proved valuable as it yielded\nmean or slightly better performance compared to the single runs.\nFor the considered models, meaningful embeddings of all concepts could\nbe found (see Tab.~\\ref{tab:bestembeddings}): The layers all reached\nsIoU values greater than 0.22\n%%% influence of resolution\ndespite of the still seemingly high influence of sub-optimal\nresolutions of the activation maps.\nFig.~\\ref{fig:conceptsamples} shows some exemplary outputs.\n%%% embeddings in early layers\nThe concepts were best embedded in earlier layers,\n%%% embeddings in different layers\nwhile different concepts did not necessarily share the same layer.\n\\begin{table}\n \\centering\n \\caption{Results for ensemble embeddings with\n set IoU (sIoU), mean cosine distance to the runs (Cos.d.),\n and index of conv layer or block (L) (cf. Fig.~\\ref{fig:layerwiseresults}).\n \\label{tab:bestembeddings}}%\n \\footnotesize%\n \\newcommand*{\\normentry}[1]{\\multicolumn{1}{c}{#1}}%\n \\newcommand{\\model}[1]{\\multirow{4}{*}{\n \\begin{tabular}{@{}c@{}}\n \\rotatebox[origin=c]{90}{\\strut#1}\n \\end{tabular}}}%\n \\newenvironment{statstable}[1]{%\n \\begin{tabular}{@{}l >{\\scshape}l c@{~~} S[table-auto-round] S[table-auto-round]@{}}%\n \\toprule%\n \\model{#1}\n & \n & \\normentry{L~~}\n & \\normentry{sIoU}\n & \\normentry{Cos.d.}\\\\%\n \\cmidrule[\\heavyrulewidth]{2-5}\n }{\\bottomrule\\end{tabular}}%\n \\mbox{%\n \\begin{statstable}{AlexNet}\n & nose & 2 & 0.227925 & 0.04030534426371257 \\\\ % 0.290909\n & mouth & 2 & 0.239023 & 0.04018515348434448 \\\\ % 0.290484\n & eyes & 2 & 0.271918 & 0.0581478198369344 \\\\ % 0.347822 \n \\end{statstable}\\hspace*{1em}%\n \\begin{statstable}{VGG16}\n & nose & 7 & 0.332171 & 0.10435034632682805 \\\\ % 0.468819\n & mouth & 6 & 0.295552 & 0.15369088053703306 \\\\ % 0.561507\n & eyes & 6 & 0.349707 & 0.1969874024391174 \\\\ % 0.628199\n \\end{statstable}\\hspace*{1em}%\n \\begin{statstable}{ResNeXt}\n & nose & 6 & 0.263708 & 0.017367599999999928 \\\\ % 0.192076\n & mouth & 5 & 0.236788 & 0.020498533333333402 \\\\ % 0.208507\n & eyes & 7 & 0.302339 & 0.019860466666666854 \\\\ % 0.205269\n \\end{statstable}%\n }\n\\end{table}\n\\begin{figure}%\n \\centering%\n \\includegraphics[width=0.6\\textwidth]{vis_concept_predictions_vgg16}\\\\\n \\includegraphics[width=0.6\\textwidth]{vis_concept_predictions_alexnet}%\n \\caption{\n Ensemble embedding outputs of\n \\textsc{nose} (green), \\textsc{mouth} (blue), \\textsc{eyes} (red).}\n \\label{fig:conceptsamples}\n\\end{figure}\n\n\n\\subsection{Example Selection for ILP Training}\nThe goal of the ILP model is to approximate the behavior of the main\nDNN, \\idest its decision boundary.\nFor this, few but meaningful training samples and their DNN output\nare needed: class-prototypes as well as ones that tightly frame the\nDNN decision boundary.\nFrom the 1,998 samples in the picasso test set, in total 100 samples\nwere chosen from the DNN test set to train the ILP model.\nThe DNN confidence score here was used to estimate\nthe proximity of a data point to the decision boundary.\nFor each class, we selected the 50 samples predicted to be in this\nclass and with confidence closest to the class boundary of 0.5.\nIn our setup this provided a wide range of confidence values\n(including 0 and 1).\n\n\\subsection{Finding the Symbolic Explanation}\nIn order to find the background knowledge needed for Aleph to generate\nthe explanation, we need to extract the information about the facial\nfeatures and their constellations from the masks of the samples drawn in the\nprevious step. Abiding the procedure described in\nSec.~\\ref{sec:bkextraction}, we first find contiguous clusters in the\nmask layers to then infer the positional information for them. This is\nstraight-forward for the nose and the mouth but imposes a problem for\nthe eyes, since we do not want to have a single position proposal for\nthem in the eye that produces the biggest cluster in the mask\nlayer. Thus, we allow for the top two biggest clusters to infer a\nposition. Although we give them unique constants in the BK, we both\ngive them the type \\ilprule{eye} $\\in C$.\n\nThe next step consists of the extraction of the spatial features\nbetween the found parts. Since the relation pair\n\\ilprule{left\\_of}\\,/ \\ilprule{right\\_of} as well as\n\\ilprule{top\\_of}\\,/ \\ilprule{bottom\\_of} can be seen as the inverses of\nthe respective other relation, we omit the relations\n\\ilprule{right\\_of} and \\ilprule{bottom\\_of} in the BK. This is\npossible, because the \\emph{Closed World Assumption} holds (Everything\nthat is not stated explicitly is false).\n\nOnce the BK is found for all examples, we can let Aleph induce a\ntheory of logic rules. Consider the induced theory for the trained\nVGG16 network:\n\\ilprule{\n \\begin{align*}\n \\text{face(F) :- } &\\text{contains(F, A), isa(A, nose), contains(F, B), isa(B, mouth),}\\\\\n &\\text{top\\_of(A, B), contains(F, C), top\\_of(C, A).}\n \\end{align*}\n}\nThe rule explicitly names the required facial concepts \\ilprule{nose}\nand \\ilprule{mouth} and the fact that the nose has to be above the\nmouth in order for an image to be a face. Further there is another\nunnamed component \\ilprule{C} required which has to be placed above\nthe nose. By construction this has to be one of the eyes. The rule\nmakes sense intuitively as it describes a subset of correct\nconstellations of the features of a human face.\n\nTo further test the fidelity of the generated explanations to the\noriginal black-box network, we calculated several performance metrics\nfor a test set of 1998 test images (999 positive and 999 negative\nexamples). We handled the learned explanation rules as binary\nclassification model for the test images in BK representation. If an\nimage representation is covered by the explanation rules, it is\npredicted to be positive, otherwise negative. We now can handle the\nbinary output of the black-box model as ground truth to our\nexplanation predictions. The performance metrics together with the\ninduced explanation rules for several DNN architectures are listed in\nTab.~\\ref{tab:ilp_results}. It can be seen that the explanations stay\ntrue to the original black-box model.\n\n\\begin{table}[t]\n \\newcommand*{\\rulepart}[1]{\\ilprule{\\scriptsize #1}}\n \\caption{Learned rules for different architectures and their\n fidelity scores (accuracy and F1 score wrt.\\ to the original model\n predictions).\n Learned rules are of common form\n \\rulepart{face(F) :- contains(F, A), isa(A, nose), contains(F, B), isa(B, mouth), distinctPart}\n }\n \\label{tab:ilp_results}\n \\begin{tabular*}{\\textwidth}{lcc@{\\extracolsep{\\fill}}l}\n \\toprule\n \\textbf{Arch.} & \\textbf{Accuracy} & \\textbf{F1} & \\textbf{Distinct rule part}\\\\\n \\midrule[\\heavyrulewidth]\n VGG16 & 99.60\\% & 99.60\\% & \\rulepart{top\\_of(A, B), contains(F, C), top\\_of(C, A)} \\\\\n AlexNet & 99.05\\% & 99.04\\% & \\rulepart{contains(F, C), left\\_of(C, A), top\\_of(C, B), top\\_of(C, A)} \\\\\n ResNext & 99.75\\% & 99.75\\% & \\rulepart{top\\_of(A, B), contains(F, C), top\\_of(C, A)}\\\\\n \\bottomrule\n \\end{tabular*}\n\\end{table}\n\n% When it comes to explaining the network behavior it is\n% particularly important to look at edge cases. This can be cases\n% where the network is not sure about a prediction or is even\n% wrong. We expect an explanation to accurately resemble the\n% decisions of the original network. We therefore investigated if\n% the false positives in the test set are correctly labeled as\n% positives and the false negatives are correctly labeled as\n% negatives by the explanation rules. This was in fact the case all\n% occurring\n\n\n\n\n%%% Local Variables:\n%%% mode: latex\n%%% TeX-master: \"concept_embeddings_and_ilp\"\n%%% End:\n", "meta": {"hexsha": "0cb509886a3e389fc7a3059c0533e9215fca2b3c", "size": 15017, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "paper-tex/experiments_results.tex", "max_stars_repo_name": "lthamm/concept-embeddings-and-ilp", "max_stars_repo_head_hexsha": "27592c6424147a2fbb54d7daebc92cd72b3f4a0c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-11-02T12:21:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-02T14:01:37.000Z", "max_issues_repo_path": "paper-tex/experiments_results.tex", "max_issues_repo_name": "lthamm/concept-embeddings-and-ilp", "max_issues_repo_head_hexsha": "27592c6424147a2fbb54d7daebc92cd72b3f4a0c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-11-06T07:58:13.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T16:11:30.000Z", "max_forks_repo_path": "paper-tex/experiments_results.tex", "max_forks_repo_name": "lthamm/concept-embeddings-and-ilp", "max_forks_repo_head_hexsha": "27592c6424147a2fbb54d7daebc92cd72b3f4a0c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-11-03T14:54:16.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-03T14:54:16.000Z", "avg_line_length": 47.673015873, "max_line_length": 145, "alphanum_fraction": 0.7231803956, "num_tokens": 4066, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.19656440062496058}}
{"text": "\\chapter{Height Field Files}\n\nThis appendix describes the format of the files that store data\nfor the height field primitive.\nThe format is an historical relic; a better format is needed.\n\nHeight field data is stored in binary form.\nThe first record in the file is a\n32-bit integer giving the square root of number of data\npoints in the file.\nWe'll call this number\nthe size of the height field.\n\nThe size is\nfollowed by altitude ($z$) values stored as 32-bit\nfloating point values. The 0th value in the file specifies the $z$\ncoordinate\nof the lower-left corner of the height field (0, 0).\nThe next\nspecifies the Z coordinate for $(1/(size-1), 0)$. The last specifies the\ncoordinate for $(1., 1.)$. In other words, the $i^{th}$ value \nin the heightfield file specifies the $z$ coordinate for the point\nwhose $x$ coordinate is\n$(i \\% size) / (size -1)$, and whose\n$y$ coordinate is $(i / size) / (size -1)$.\nNon-square height fields may be rendered by specifying altitude values\nless than or equal to the magic value\n$-1000$. Triangles that have any vertex less than\nor equal in altitude to this value are not rendered.\n\nWhile this file format is compact, it sacrifices portability for\nease of use. While creating and handling height field files is\nsimple, transporting a height field from one machine to another\nis problematical due to the fact that differences in byte order\nand floating-point format between machines is not taken into\naccount.\n\nThese problems could be circumvented by writing the height field file\nin a fixed-point format, taking care to write the bytes that\nencode a given value in a consistent way from machine to machine.\nAn even better idea would be to write a set of tools for\nmanipulating arbitrary 2D arrays of floating-point values in a compact,\nportable way, allowing for comments and the like in the file\\ldots\n", "meta": {"hexsha": "4357d1de7ac79a32d91a8d815e1a57d8c7caa6e0", "size": 1846, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Doc/Guide/height.tex", "max_stars_repo_name": "stricaud/rayshade4", "max_stars_repo_head_hexsha": "08ea3c0697442e7446442383456644bd915ece36", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 27, "max_stars_repo_stars_event_min_datetime": "2015-11-11T09:35:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-29T02:18:10.000Z", "max_issues_repo_path": "Doc/Guide/height.tex", "max_issues_repo_name": "dspinellis/rayshade4", "max_issues_repo_head_hexsha": "08ea3c0697442e7446442383456644bd915ece36", "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/Guide/height.tex", "max_forks_repo_name": "dspinellis/rayshade4", "max_forks_repo_head_hexsha": "08ea3c0697442e7446442383456644bd915ece36", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2015-11-11T09:34:50.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-03T17:08:24.000Z", "avg_line_length": 41.9545454545, "max_line_length": 73, "alphanum_fraction": 0.7730227519, "num_tokens": 441, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926665999540697, "lm_q2_score": 0.3311197462295937, "lm_q1q2_score": 0.1962436141755477}}
{"text": "% !TEX root = thesis.tex\n\n\\chapter{Implementing higher-dimensional representations and operations}\n\\label{ch:implementation}\n\nThe higher-dimensional representations described in \\refpa{pa:representation} and the operations described in \\refpa{pa:operations} can be difficult to implement, especially when we expect these implementations to be fast, robust, generic, compact and dimension-independent.\nThis is true even when the basic ideas and algorithms are provided, as has been done in this thesis.\n\nFor the sake of full reproducibility, this chapter shows some of the key implementation details that are used to efficiently implement the representations and operations described in this thesis.\n\\refse{se:libraries} lists the main libraries that were used and how they were used.\n\\refse{se:computerarithmetic} explains the main techniques that are used to perform arithmetic and geometric operations robustly.\nFinally, \\refse{se:traits} describes the traits programming technique and its use in CGAL and this thesis to produce dimension-independent efficient implementations.\n\n\\section{Main libraries used within this thesis}\n\\label{se:libraries}\n\n\\begin{description}\n\n\\item[CGAL\\footnotemark]\n\\footnotetext{\\url{http://www.cgal.org}}\n(the Computational Geometry Algorithms Library) contains a wide variety of 2D/3D/$n$D data structures and computational geometry algorithms.\nSome of its basic packages are directly used within this thesis to store and manipulate numbers and basic shapes, namely: Algebraic Foundations, Number Types, 2D and 3D Linear Geometry Kernel, and $d$D Geometry Kernel.\nMost significantly, the packages Combinatorial Maps and Linear Cell Complex are used in most of the implementations described in the previous chapters.\nFinally, other packages are used as temporary data structures and to process and clean input data: 3D Polyhedral Surface, Halfedge Data Structures, 3D Boolean Operations on Nef Polyhedra, 2D Triangulation, and Principal Component Analysis.\nA few other packages are used as dependencies of the aforementioned packages.\n\n\\item[GDAL\\footnotemark]\n\\footnotetext{\\url{http://www.gdal.org}}\n(the Geospatial Data Abstraction Library) reads and writes commonly used GIS file formats.\nWithin this thesis, its OGR vector module is mainly used to read and write polygons described as well-known text \\citep{SimpleFeatures1}, or in Esri Shapefile \\citep{Shapefile} and FileGDB files.\n\n\\item[IfcOpenShell\\footnotemark]\n\\footnotetext{\\url{http://www.ifcopenshell.org}}\nis a library that is able to read and write IFC files \\citep{ISO16739:2013}.\nIt internally uses the Open CASCADE geometry types, including to convert implicit geometries (\\eg\\ those built using constructive-solid geometry or sweeps as in \\reffig{fig:ifc}) into explicit ones that can be stored using boundary representation, or to create meshes of a given degree of accuracy from curved surfaces.\n\n\\item[Open CASCADE\\footnotemark]\n\\footnotetext{\\url{http://www.opencascade.org}}\nis a library that is able to manipulate geometric representations in CAD applications.\nIn theory, it supports complex geometric operations between implicit geometries, including Boolean set operations with 3D point sets.\nHowever, in practice it performs poorly with GIS data, often failing due to numerical errors or imperfect data.\n\n\\end{description}\n\n\\section{Geometric operations using computer arithmetic}\n\\label{se:computerarithmetic}\n\nTheoretical descriptions of geometric objects and geometric algorithms generally start from the notions of the Euclidean space $\\mathbb{R}^n$, in which the coordinates of a point can be described precisely using real numbers ($\\mathbb{R}$).\nHowever, as real numbers cannot be represented on (digital) computers, implementations usually opt for a combination of \\emph{integer numbers} to represent whole numbers of known precision that are known to fall within a given interval and \\emph{floating-point numbers} in all other cases.\nWhile integers can be precisely expressed as a sequence of binary digits of a given length, floating-point numbers often cannot.\nThe latter are therefore usually\\footnote{This is only the most common representation among those provided by the much broader IEEE 754 standard \\citep{IEEE754-2008}, which provides for decimal numbers as well as special values for $\\pm \\infty$ and NaN (not a number), among other features.} expressed using binary numbers with a predefined number of bits.\n% as:\n\n% \\begin{equation*}\n% {(-1)}^\\mathrm{sign} \\times 2^\\mathrm{exponent} \\times \\mathrm{significand}\n% \\end{equation*}\n\n% where the exponent is a positive integer and the significand is expressed as a normalised number.\n% As a normalised binary number always begins with \\texttt{1.}, the first binary digit is known and therefore not stored.\n% The \\emph{fraction} of the number (\\ie\\ the digits following the \\texttt{1.}) is stored instead.\n% Single precision (or 32-bit) floating-point numbers use 1 bit for the sign, 8 bits for the exponent and 23 bits for the significand.\n% Double precision (or 64-bit) floating-point numbers use 1 bit for the sign, 11 bits for the exponent and 52 bits for the significand.\n\nFloating-point numbers can represent a wide range of values and work well in many instances.\nHowever, arithmetic performed using floating-point numbers needs special care, as it often leads to a loss of precision \\citep{Goldberg91}.\nWhile this is a problem for all kinds of algorithms \\citep{Hoffmann88}, geometric operations are particularly vulnerable as they often rely on getting a correct result for a large number of predicates, which can fail when dealing with edge cases \\citep{Kettner08}, such as almost collinear or coplanar points.\n\nMany alternatives have been developed to deal with various limitations of integer and floating-point numbers.\nAmong these, the ones described below are those that have been used for the implementations related to this thesis.\n\\emph{Multiple precision arithmetic} is a generic solution that can achieve an arbitrary level of precision by using numbers with a user-definable number of digits.\nIt is widely implemented in libraries such as GMP\\footnote{\\url{https://gmplib.org/}} and MPFR\\footnote{\\url{http://www.mpfr.org}}.\n\nSimple arithmetic operations can be computed precisely by using \\emph{rational arithmetic}, where a number is stored as a ratio of two other numbers, most commonly integers.\nIn a geometric context, this type of representation is often used in the form of homogeneous coordinates, where a single number is used as a common denominator for all of the coordinates.\nThis common denominator can be used to represent special values, such as a point at infinity by setting it to zero.\n\nIn \\emph{interval arithmetic} numbers are substituted with intervals.\nWhen these are used to represent the error bounds of an operation\\footnote{combined with correct rounding in the case of floating-point numbers}, it is possible to compute arithmetic operations with provably correct results \\citep[Ch.~2]{Ratschek88}, such as those provided by the MPFI library\\footnote{\\url{https://perso.ens-lyon.fr/nathalie.revol/software.html}}.\nUnfortunately, while this setup using multiple precision interval arithmetic can be applied to most problems with relative ease, it is also very slow.\nFor instance, \\citet{Held11} reports a factor of 70 for the computation of Voronoi diagrams.\n\nIt is possible to go around this problem by fine-tuning a multiple-precision approach to a specific problem.\nNotably, this is done with very good results for a few geometric predicates by \\citet{Shewchuk97}, and the simulation of simplicity paradigm advocated by \\citet{Edelsbrunner90}.\nA more generic and easier to implement solution is provided by the lazy evaluation scheme used in CGAL \\citep{Pion11}, which is based on interval arithmetic and is the one used in this thesis.\n% , which is used in the implementations mentioned in this thesis.\nIn it, the computationally expensive multiple precision operations are only computed when floating-point precision is not sufficient.\nAs these cases are important to get correct results, but also relatively rare, it significantly improves the performance of most operations while maintaining their correctness.\n\n\\section{Efficient and flexible dimension-independent programming}\n\\label{se:traits}\n\nPreviously, \\refse{ss:dimensions} discussed how higher-dimensional representations have large sizes and methods using them have high computational complexities, which often increase exponentially on the dimension.\nHowever, there are also practical obstacles that make it difficult to implement dimension-independent structures and methods efficiently, especially when these have to be used in a generic setting such as in GIS, where varied objects of different dimensions need to be dynamically created and modified, as well as appended with possibly multiple attributes of various types.\n\nOne of these obstacles is the need to allocate and use structures that are dimension- and data-independent, and therefore flexible enough to cover all the aforementioned use cases, but at the same time remain compact and allow their contents to be accessed efficiently.\nThese structures can range from simple ones that can be handled by standard data types and containers, to more complex ones that need to be dynamically defined.\nFor instance, some simple types are directly dependent on the dimension, such as $n$-tuples storing the coordinates of a point in $\\mathbb{R}^n$, and can thus be stored as arrays or vectors.\n\nAt the opposite end, consider the sets of extrusion intervals that were associated to each cell in \\refch{ch:extrusion}, where an unknown number of cells need to be each associated with an unknown number of intervals.\nAs the number of intervals per cell is not known, it is not possible to store the intervals in a fixed-length structure that is integrated into the embedding structure of each cell.\nAlso, while it is possible to directly link a cell to its set of intervals from its embedding structure, these intervals are only temporarily needed, so allocating space for the intervals directly in the embedding structure is wasteful at all other times and thus difficult to justify.\nThe end result was that the intervals per cell were kept in an external structure, where a \\texttt{map} linked a cell embedding to a \\texttt{set} of intervals.\nAs \\reftab{tab:complexitystd} shows, this means that accessing a given interval of a given cell---an operation that is performed a very large number of times---, takes logarithmic rather than constant time, significantly slowing the extrusion algorithm in practice.\n\\marginpar{\n\\captionsetup{type=table}\n\\centering\n\\caption[Computational complexity of accessing an element in C++ containers]{The typical computational complexity of accessing a given element in common C++ containers \\citep{ISO14882:2015}}\n\\label{tab:complexitystd}\n\\small\n\\begin{tabular}{cc}\n\\toprule\nstructure & complexity \\\\\n\\midrule\nhard-coded & $O(1)$ \\\\\narray/vector & $O(1)$ \\\\\nmap/set & $O(\\log n)$ \\\\\nlist & $O(n)$ \\\\\n\\bottomrule\n\\end{tabular}\n}\n\nA possible solution to the aforementioned problems is based on \\emph{template meta-programming}.\nTemplate meta-programming is a technique that uses templates to generate certain data structures or perform certain computations during the compilation of a program rather than during its execution.\nTemplates are normally used as a way to support generic programming, enabling the creation of functions that can deal with different data types indistinctly.\nA template might thus be instantiated with the dimension of an object or a particular attribute type, thus generating a data structure of the appropriate size and disposition whose members can be accessed in constant time.\n\\reffig{fig:template-conversion} shows a slightly more complex example, where a template can be used to convert a string into any number type, which is used in this thesis to parse numbers from various types of files (\\eg\\ coordinates and identifiers).\n\\begin{figure}[tb]\n\\centering\n\\small\n\\lstinputlisting[language=C++]{figs/templateconversion.txt}\n\\caption[Using C++ templates to convert a \\texttt{string} into any number type]{Using C++ templates to convert a \\texttt{string} containing a number into any number type $T$, including scientific notation. Adapted from \\url{http://www.cplusplus.com/forum/articles/9645/}.}\n\\label{fig:template-conversion}\n\\end{figure}\n\nHowever, apart from their use in generic programming, templates can also be used to create complex dimension-dependent structures, such as through the use of the traits programming technique \\citep{Myers95} used in CGAL, which exploits C++'s \\texttt{typedef} declarations to create custom dependent types.\\@\nAs an example, \\reffig{fig:extrudedlcc} shows how the implementation of the extrusion algorithm defines a combinatorial map that is one dimension higher than the input, which is created during compilation.\n\\begin{figure*}[tb]\n\\centering\n\\small\n\\lstinputlisting[language=C++,numbers=left]{figs/extrudedlcc.txt}\n\\caption[Creating a dependent type using C++ templates]{Using C++ templates it is possible to create dependent types such as the \\texttt{Higher\\_dimensional\\_cell\\_complex} defined in line 5 and used in line 15.}\n\\label{fig:extrudedlcc}\n\\end{figure*}\n\nThis type of mechanism can be used to a much higher degree by defining \\emph{recursive templates}, which are used extensively in the CGAL Combinatorial Maps package.\nAs an example, \\reffig{fig:dimensionindependent} shows how this was applied in order to store the extrusion ranges maps for each dimension separately, which is necessary because the embedding structures of each cell are different depending on the dimension.\n\\begin{figure*}[tb]\n\\centering\n\\small\n\\lstinputlisting[language=C++,numbers=left]{figs/dimensionindependent.txt}\n\\caption[Using recursive C++ templates to produce dimension independent code]{Recursive C++ templates can be used to generate dimension independent code.\nThe first structure \\texttt{Extrusion\\_ranges\\_map\\_of\\_dimension} (lines 1--8) contains the extrusion map for a single dimension.\nThe second structure \\texttt{Extrusion\\_ranges\\_tuple\\_per\\_dimension\\_up\\_to} (lines 10--23) uses as a triplet of definitions to create copies of the first for every dimension up to a given one.\nThis is done using a template specialisation for dimension 0 which stops the recursion.\nThe last structure \\texttt{Extrusion\\_ranges\\_tuple\\_per\\_dimension} (lines 25--32) creates all structures using the dimension of a passed combinatorial map \\texttt{LCC}.\nNote the non-ideal use of \\texttt{std::map} in line 5.}\n\\label{fig:dimensionindependent}\n\\end{figure*}\n\nThe same technique can be used to create algorithms that are also fully dimension-independent.\nIn fact, C++ templates are known to be Turing-complete \\citep{Veldhuizen03}, and thus can be used to compute general-purpose problems.\n\\reffig{fig:manifoldvalidation} shows one such example from the implementation of the incremental construction algorithm of \\refch{ch:incremental-construction}, which shows the validation that a set of $(n-1)$-cells form a quasi-$n$-manifold.\n\\begin{figure*}[tb]\n\\centering\n\\small\n\\lstinputlisting[language=C++]{figs/manifoldvalidation.txt}\n\\caption[Dimension-independent algorithms using recursive C++ templates]{Recursive C++ templates can also be used to implement dimension-independent algorithms. In this case, the \\texttt{dimension} that is passed to the templated function is passed on to other functions to obtain appropriate orbits for a given facet (\\texttt{dimension-1}) or ridge (\\texttt{dimension-2}), which are then compared dart by dart.}\n\\label{fig:manifoldvalidation}\n\\end{figure*}\n", "meta": {"hexsha": "53c90a7961bf404f27b3bc8a14ec975277cba9dc", "size": 15740, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "implementation.tex", "max_stars_repo_name": "kenohori/thesis", "max_stars_repo_head_hexsha": "31c026184ba535a491d6a3981c29dd897cba84b5", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 38, "max_stars_repo_stars_event_min_datetime": "2016-03-04T13:55:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T07:28:24.000Z", "max_issues_repo_path": "implementation.tex", "max_issues_repo_name": "kenohori/thesis", "max_issues_repo_head_hexsha": "31c026184ba535a491d6a3981c29dd897cba84b5", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-02-23T16:34:29.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-27T10:12:11.000Z", "max_forks_repo_path": "implementation.tex", "max_forks_repo_name": "kenohori/thesis", "max_forks_repo_head_hexsha": "31c026184ba535a491d6a3981c29dd897cba84b5", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2018-10-11T04:08:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-28T23:58:06.000Z", "avg_line_length": 92.5882352941, "max_line_length": 412, "alphanum_fraction": 0.8049555273, "num_tokens": 3457, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203638047914, "lm_q2_score": 0.373875808818685, "lm_q1q2_score": 0.19569421186968672}}
{"text": "\\section{Longitudinal string excitation.}\n\n\\subsection{Hadron--nucleon inelastic collision.}\n\n\\hspace{1.0em}Let us consider collision of two hadrons with their c. m. momenta \n$P_1 = \\{E^{+}_1,m^2_1/E^{+}_1,{\\bf 0}\\}$ and $P_2 =\n\\{E^{-}_2,m^2_2/E^{-}_2,{\\bf 0}\\}$, where the light-cone variables\n$E^{\\pm}_{1,2} = E_{1,2} \\pm P_{z1,2}$ are defined through hadron\nenergies $E_{1,2}=\\sqrt{m^2_{1,2} + P^2_{z1,2}}$, hadron longitudinal\nmomenta $P_{z1,2}$ and hadron masses $m_{1,2}$, respectively. Two\nhadrons collide by two partons with momenta $p_1 = \\{x^{+}E^{+}_1,0,{\\bf\n0}\\}$ and $p_2 = \\{0, x^{-}E^{-}_2,{\\bf 0}\\}$, respectively.\n\n\\subsection{The diffractive string excitation.} \n\nIn the diffractive string excitation (the Fritiof approach \\cite{FRITIOF87})\n only momentum can be transferred:\n\\begin{equation}\n\\label{LSE1}\n\\begin{array}{cc}\nP^{\\prime}_1 = P_1 + q\\\\\nP^{\\prime}_2 = P_2 -q,\n\\end{array}\n\\end{equation}\nwhere \n\\begin{equation}\n\\label{LSE2}q=\\{-q^2_t/(x^{-}E^{-}_2),q^2_t/(x^{+}E^{+}_1),\\bf q_t \\}\n\\end{equation}\n is parton \nmomentum transferred and ${\\bf q_t}$ is its transverse component.\nWe use the Fritiof approach to simulate the diffractive excitation of \nparticles.\n \n\\subsection{The string excitation by parton exchange.}\n\n\\hspace{1.0em}For this case the parton exchange (rearrangement) and\nthe momentum exchange are allowed \\cite{QGSM82},\\cite{DPM94}:\n\\begin{equation}\n\\label{LSE3}\n\\begin{array}{cc}\nP^{\\prime}_1 = P_1 - p_1 + p_2 + q \\\\\nP^{\\prime}_2 = P_2 + p_1 - p_2 - q,\n\\end{array}\n\\end{equation}\nwhere $q= \\{0,0, {\\bf q_t}\\}$ is parton momentum transferred, i. e. only\nits transverse components ${\\bf q_t}$ is taken into account \\cite{Am86}.\n\n\\subsection{Transverse momentum sampling.}\n\n\\hspace{1.0em}The transverse component of the parton momentum\ntransferred is generated according to probability\n\\begin{equation}\n\\label{LSE4}P({\\bf q_t})d{\\bf q_t} = \n\\sqrt{\\frac{a}{\\pi}} \\exp{(-aq^2_t)}d{\\bf q_t},\n\\end{equation}\nwhere parameter $a = 1.4$ GeV$^{-2}$.\n\n{\\bf $x^{+}$ and $x^{-}$ samplings.}\n\nLight cone parton quantities $x^{+}$ and $x^{-}$ are generated\nindependently and according to distribution:\n\\begin{equation}\n\\label{LSE5} u(x) \\sim x^{\\alpha}(1 - x)^{\\beta},\n\\end{equation}\nwhere $x=x^{+}$ or $x=x^{-}$.\nParameters $\\alpha =-1$ and $\\beta = 0$ are chosen for the FRITIOF approach \n\\cite{FRITIOF87}. In the case of the QGSM approach \\cite{Am86} $\\alpha = -0.5$ \nand $\\beta = 1.5$ or $\\beta = 2.5$. Masses of the excited strings\nshould satisfy the kinematical constraints:\n\\begin{equation}\n\\label{LSE6} P^{\\prime +}_1 P^{\\prime -}_1 \\geq m^2_{h1} + q^2_t\n\\end{equation}\nand\n\\begin{equation}\n\\label{LSE7} P^{\\prime +}_2 P^{\\prime -}_2 \\geq m^2_{h2} + q^2_t,\n\\end{equation}\nwhere hadronic masses $m_{h1}$ and $m_{h2}$ (model parameters) are\ndefined by string quark contents. Thus, the random selection of the\nvalues $x^{+}$ and $x^{-}$ is limited by above constraints.\n\n\\subsection{The string excitation by quark or diquark annihilation.}\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\n\n\\subsection{Hadron--nucleus or nucleus--nucleus inelastic collisions.}\n\n\\hspace{1.0em}Hadron-nucleus or nucleus-nucleus collisions in the both\napproaches (diffractive and parton exchange) are considered \nas a set of the independent hadron-nucleon or\nnucleon-nucleon collisions. However, the string excitation procedures\nin these approaches are rather different.\n\n\\subsection{The diffractive string excitation.} \n\n\\hspace{1.0em}In the diffractive string excitation (the \nFRITIOF approach \\cite{FRITIOF87}) for each\ninelastic hadron--nucleon or nucleon--nucleon collision we have to select\nrandomly the transverse momentum transferred ${\\bf q_t}$ (in accordance\nwith the probability given by Eq. ($\\ref{LSE4}$)) and select randomly\nthe values of $x^{\\pm}$ (in accordance with distribution defined by\nEq. ($\\ref{LSE5}$)). Then we have to calculate the parton momentum\ntransferred $q$ using Eq. ($\\ref{LSE2}$) and update scattered hadron\nand nucleon or scatterred nucleon and nucleon momenta using\nEq. ($\\ref{LSE3}$). For each collision we have to check the constraints\n($\\ref{LSE6}$) and ($\\ref{LSE7}$), which can be written more\nexplicitly:\n\\begin{equation}\n\\label{LSE8} [E_1^{+} -\\frac{q^2_t}{x^{-}E^{-}_2}][\\frac{m_1^2}{E^{+}_1} + \n\\frac{q^2_t}{x^{+}E^{+}_1}]\\geq m^2_{h1} + q^2_t\n\\end{equation}\nand\n\\begin{equation}\n\\label{LSE9} [E_2^{-} +\\frac{q^2_t}{x^{-}E^{-}_2}][\\frac{m_2^2}{E^{-}_2} - \n\\frac{q^2_t}{x^{+}E^{+}_1}]\\geq m^2_{h1} + q^2_t.\n\\end{equation}\n\n\\subsection{The string excitation by parton rearrangement.} \n\n\\hspace{1.0em}In this approach \\cite{Am86} strings (as result of parton\nrearrangement) should be spanned not only between valence quarks of\ncolliding hadrons, but also between valence and sea quarks and between\nsea quarks. The each participant hadron or nucleon should be splitted\ninto set of partons: valence quark and antiquark for meson or valence\nquark (antiquark) and diquark (antidiquark) for baryon (antibaryon) and\nadditionaly the $(n-1)$ sea quark-antiquark pairs (their flavours are\nselected according to probability ratios $ u:d:s = 1:1:0.35$), if hadron\nor nucleon is participating in the $n$ inelastic collisions. Thus for\neach participant hadron or nucleon we have to generate a set of light\ncone variables $x_{2n}$, where $x_{2n}=x^{+}_{2n}$ or\n$x_{2n}=x^{-}_{2n}$ according to distribution:\n\\begin{equation}\n\\label{LS10} f^{h}(x_1,x_2,...,x_{2n})=f_{0}\\prod_{i=1}^{2n}u^h_{q_i}(x_i)\n\\delta{(1-\\sum_{i=1}^{2n}x_i)},\n\\end{equation}\nwhere $f_0$ is the normalization constant.\nHere, the quark structure functions $u_{q_i}^h(x_i)$ for valence quark \n(antiquark) $q_v$, \nsea quark and antiquark $q_s$ and valence diquark (antidiquark) $qq$ are:\n\\begin{equation}\n\\label{LS11}\nu^h_{q_v}(x_v)=x_v^{\\alpha_v},\\ u^h_{q_s}(x_s)=x_s^{\\alpha_s},\\ u^h_{qq}(x_{qq})\n=x_{qq}^{\\beta_{qq}},\n\\end{equation}\nwhere $\\alpha_v = -0.5$ and $\\alpha_s = -0.5$ \\cite{QGSM82} \n for the non-strange quarks (antiquarks) and $\\alpha_v =\n0$ and $\\alpha_s = 0$ for strange quarks (antiquarks), $\\beta_{uu} =\n1.5$ and $\\beta_{ud} = 2.5$ for proton (antiproton) and $\\beta_{dd} =\n1.5$ and $\\beta_{ud} = 2.5$ for neutron (antineutron). Usualy $x_i$ are\nselected between $x^{min}_i \\leq x_i \\leq 1$, where model parameter\n$x^{min}$ is a function of initial energy, to prevent from production of\nstrings with low masses (less than hadron masses), when whole selection\nprocedure should be repeated. Then the transverse momenta of partons\n${\\bf q_{it}}$ are generated according to the Gaussian probability\nEq. ($\\ref{LSE4}$) and under the constraint: $\\sum_{i=1}^{2n}{\\bf\nq_{it}}=0$. The partons are considered as the off-shell partons,\ni. e. $m^2_i \\neq 0$.\n\n\\subsection{Barion and meson splitting.}\n\\hspace{1.0em}To perform\n a simulation of the string excitation we need to split hadron and\nchoose valence quark (antiquark) and diquark (antidiquark). In the case \nof a meson we split it into valence quark and antiquark (for neutral mixed \nmesons this sampling is performed according to mixing probabilities.)\nIn the case of barion we determine probabilities of baryon (antbarion) \nstate (a quark (antiquark) and \ndiquark (antidiquark) with given spin and isospin)\n from $SU(6)$ symmetric wave barion functions. These probabilities are \n given in the Table 3.1. \n\\hspace{1.0em}\n\\begin{table}\n\\begin{center}\n\\begin{tabular}{|c|c|}\n\\hline\nBaryon type & Quark content \\\\\n\\hline\n$p$ &$1/3uu_{11}d+1/6(1/12)ud_{11}u+1/2(7/12)ud_{00}u$ \\\\\n$n$ &$1/6(1/12)ud_{11}d+1/2(7/12)ud_{00}d+1/3dd_{11}u$ \\\\\n$\\Sigma^{+}$&$1/3uu_{11}s+1/6us_{11}u+1/2us_{00}u$ \\\\\n$\\Sigma^{0}$&$1/3ud_{11}s+1/12us_{11}d+1/4us_{00}d+1/12ds_{11}u+1/4ds_{00}u$\\\\\n$\\Sigma^{-}$&$1/3dd_{11}s+1/6ds_{11}d+1/2ds_{00}d$ \\\\\n$\\Xi^{-}$ &$1/6ds_{11}s+1/2ds_{00}s+1/3ss_{11}d$ \\\\\n$\\Xi^{0}$ &$1/6us_{11}s+1/2us_{00}s+1/3ss_{11}u$ \\\\\n$\\Lambda^{0}$&$1/3ud_{00}s+1/4us_{11}d+1/12us_{00}d+1/4ds_{11}u+1/12ds_{00}u$\\\\\n$\\Delta^{++}$&$uu_{11}u$ \\\\\n$\\Delta^{+}$ &$1/3uu_{11}d+2/3ud_{11}u$ \\\\\n$\\Delta^{0}$ &$2/3ud_{11}d+1/3dd_{11}u$ \\\\\n$\\Delta^{-}$ &$dd_{11}d$ \\\\\n$\\Sigma^{*+}$&$1/3uu_{11}s+2/3us_{11}u$ \\\\\n$\\Sigma^{*0}$&$1/3ud_{11}s+1/3us_{11}d+1/3ds_{11}u$\\\\\n$\\Sigma^{*-}$&$1/3dd_{11}s+2/3ds_{11}d$ \\\\\n$\\Xi^{*0}$ &$1/3us_{11}s+2/3ss_{11}u$ \\\\\n$\\Xi^{*-}$ &$2/3ds_{11}s+1/3ss_{11}d$ \\\\\n$\\Omega^{-}$ &$ss_{11}s$ \\\\\n\\hline\n\\end{tabular}\n\\end{center}\nTable 3.1: Baryon quark contents. Diquark indices indicate spin-isospin states.\n\\end{table}\nWe also use these probability to sample barion or barion resonance in \nthe string fragmentation, assuming that a valence diquark (antidiquark) \nkeeps its spin and isospin during whole reaction.\n", "meta": {"hexsha": "ec43c904bb6b0a7708ab05ca785132c0be86aba0", "size": 11300, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "geant4/hadronic/theory_driven/PartonString/LongitudinalStringExcitation.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/LongitudinalStringExcitation.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/LongitudinalStringExcitation.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": 45.3815261044, "max_line_length": 80, "alphanum_fraction": 0.7074336283, "num_tokens": 3991, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.36296921930155557, "lm_q1q2_score": 0.19563431882964674}}
{"text": "\\chapter{Methodology}\n\\newtheorem{definition}{Definition}\n% \\label{ch:relatedwork}\nAs mentioned in the previous sections, the rapid increase in IoT devices as well as its use-cases has \nsignificantly impacted and at times more often than not, improved our experiences. However, when these \npersonal, and usually hand-held or wearable devices like smart phones and smart watches, have a \nplethora of added functionality, it also poses the problem of increased energy consumption. This results \non a less uptime for one charge of a battery which corresponds to the device not being utilized for proper \namounts of time. This is especially important in the healthcare sector where a device monitoring a patient's \nvitals should be able to do so for prolonged lengths of time. \\\\\nIn this thesis, our study focused on optimizing energy consumption for communication. Most applications \non an edge device usually communicate with a remote server to exchange different data and it varies from \napplication to application. But within these applications, communication is a core aspect which is not \nbeing investigated by researchers. \nThe best general practice used when designing these applications is to send data in sizes multiples of 2, which \ngenerally means faster communication without unwanted packet drops but on the other hand, is no where near \noptimal. This is due to the fact that each edge device may have different hardware and different software \nversions, and the energy cost for communication for each possible variation of these is different \\cite{6200281}. It has no \noptimal trend, therefore, the best practice is to use general values of chunk sizes that the protocol \ncan easily handle. Our work focuses on communication cost because most of the times other hardware related \nfactors are not flexible or would otherwise compromise the integrity of the task. \\\\\n\nThis work is divided into two portions. First, we present a pretty straightforward way to estimate an \napplication's energy consumption over time. Next, we present an approach to compute optimal chunk sizes \nfor respective edge devices. We evaluate and confirm whether this optimal chunk size approach consumes less \nenergy or not with the help of our energy estimation approach, on two real-world applications. \\\\\n\\section{Estimating Energy Usage}\nThere have been other approaches in the past to estimate energy consumption of applications \\cite{6606555} but we \nadopt an approach that is similar to energest \\cite{energest} which is an energy profiling approach for Contiki OS. \nWe combine runtime information from applications with static information from data sheets of specific \nhardware components to estimate energy consumption. Before getting into the details, we will define some \nterminologies. \\\\\n\n\\begin{definition}\n \\textbf{Current }(I) is defined as the flow of electrical charge (q) over time (t). It is measured in Amperes (A).\n\\end{definition}\n\n\\begin{definition}\n \\textbf{Power}(P) is defined as the amount of charge (q) moved through voltage (V) in a time interval (t). It is measured in Watts (W).\n\\end{definition}\n\nFor devices powered by a battery, both current and voltage is an important factor and is heavily dependent \non the components used on the device itself. Different electrical components operate on different voltages, thereby, \ndrawing different amounts of current, resulting in different power consumption. However, in order to calculate the \nenergy consumption, the dynamic factor is time. Power used or spent over a specific period of time equals the \nenergy used by the specific device or specific component of device. \n\n\\begin{definition}\n \\textbf{Energy}(E) is defined as the amount of power (P) expended over a time interval (t). It is measured in Joules (J).\n\\end{definition}\n\nWe use these definitions to be able to express how we estimate the energy consumption of a specific edge IoT device. \nAlmost all hardware components when designed and brought to market have a corresponding data sheet publicly available, \nwith important information such as circuit diagrams, and current and voltage values for different modes (if possible). Current \nand voltage are dynamic factors however by using information from said data sheets, we can estimate these values by \ncomputing the mean average sum of values corresponding to different operating modes. The data sheet for BCM43455, the \nwifi adapter used in Raspberry Pi 4 Model B \\cite{cypress} contains valuable information regarding different technical \ndetails such as frequency, circuit design, power management etc. However, \nwhat is interesting to us is current and voltage values. Figure \\ref{fig:bcm} provides a snapshot from one such table. \nIt outlines the different current values corresponding to different voltage values for different modes. In a \nreal world setting, the devices switch between these modes depending on various factors. A reasonable assumption \nin this case would be to take the mean average sum of values for different modes. \\\\\n\n\\begin{figure}\n \\begin{center}\n \\includegraphics[scale=0.25]{Figs/datasheet.png} \n \\end{center}\n \\caption{Current and Voltage values for BCM43455}\n \\label{fig:bcm}\n\\end{figure}\n\nGiven this information, we can estimate the power \\texttt{P} that the wifi adapter would use in this case when it is \nturned on. Consider an app \\texttt{A} which finishes executing in about \\texttt{t} seconds. The total energy \nconsumed (by the wifi adapter) by running \\texttt{A} would then be calculated by \\texttt{E = P * t}. \\\\\nIn order to calculate the estimated energy for specific block of code, such as ones which handle communication, all one \nneeds to do is instrument the app to log execution time for that specific block of code. And then we can \ncalculate the energy usage of that specific portion of program. The main idea behind this approach to \nestimate energy is that software developers don't usually have the technical equipment required to \nindividually measure current and voltage values of actual devices. Given that setback, estimating energy \nconsumption off of publicly available data sheets and runtime information from the app itself is a \npretty reliable way to gather the required data. \\\\\n\\section{Calculating Optimal Chunk Size}\nAs mentioned before, our study focuses on optimizing communication cost of applications for IoT edge devices. \nEven though the best practices involved in this case do perform well for average case, our hypothesis \nis that after a communication pipe is established between the client and the server, having data sent or \nreceived in different chunk sizes could have an impact on the energy consumption of the whole process. \nThe motivation behind this is that even though hardware optimizations such as power saving modes improve \nenergy consumption efficiency, there are still software related configurations that can be altered to reduce \nthe overall energy usage. We chose to focus on communication cost because it is an integral part of more or less \nevery app deployed on an edge device where it communicated with the server one way or another to transmit \nsome sort of data. \\\\\nBut why communication cost? Indeed, there are multiple code related factors that can help optimize energy \nconsumption but our work is done under the assumption that these factors, such as data collection, via the \nsensor, the disk I/O operations etc. differ heavily from use-case to use-case and any alteration in code \nfunctionality to them, may affect their usage in real world. For example, a device monitoring a patient's \nheartbeat continuously is bound to use more energy than, let's say, monitoring every five minutes. \nHowever, in these kinds of critical health monitoring applications, such types of optimizations severely undermine the actual \nfunctionality of the app. Therefore, our approach addresses a factor that is independent of the sensor \nusage in such a context and can potentially work on diverse examples. \\\\\nTo better explain how we calculate the optimal chunk size, we will first define energy-per-byte or EPB. \nIt is a metric we use to determine which chunk size consumes the least amount of energy. \\\\\n\n\\begin{definition}\n \\textbf{EPB} or Energy-per-Byte is defined as the amount of energy consumed when a single byte of data is sent from one device to another.\n\\end{definition}\n\nBut why is EPB an important factor rather than the overall energy consumed for the corresponding chunk size? \nWe will explain this with the help of an example. Consider an app \\texttt{C} on the edge device \\texttt{EdgeD} that needs \nto send 256 bytes to the server-side app \\texttt{S}. Assume you calculated the energy to send data at a \nchunk size of 64 bytes was the lowest at \\texttt{E1} Joules. However, if you used 128 bytes at a time to \nsend this data, you consume \\texttt{E2} Joules which is slightly more than \\texttt{E1}. In this case, \nwe can not say the 64 bytes is the optimal chunk size for \\texttt{EdgeD} because it would take \\texttt{E1*4} \namounts of energy to send the complete data and \\texttt{E2*2} on the other hand. For the sake of this \nexample, assume \\texttt{E1} has the arbitrary value of 2 Joules (actual values are way way less and are usually \nin microJoules) and \\texttt{E2} has the arbitrary value of 3 Joules. 64 bytes would take 8 Joules in total \nto send 256 bytes of data where as 128 bytes of chunk size would only use 6 Joules. That is why, EPB is an \nimportant factor and metric in this case. So what we need to do is divide \\texttt{E1} by 64 and \\texttt{E2} \nby 128 to get the EPB for their respective chunk sizes. Now, the lower energy consumption value of the \ntwo would be the optimal one as it would consume the lowest amount of energy among different chunk sizes. \\\\\nTo calculate the optimal chunk size on an edge device, we deploy a Python script which comprises of a \nlist of different chunk sizes of order \\texttt{$2^{n}$} where \\texttt{n} by default can be anything between \n1 and 30 (included). The upper limit can be adjusted depending on the use case of the program. It then \nproceeds to send data in different chunk sizes and then measure the time it took for the communication to take \nplace. This time is then used to calculated the overall energy consumption for sending a specific amount of \ndata. It must be mentioned here that the chunk size is also bounded by the protocol being used and \nthe local disk space of the device. \nIt is provided as a pseudocode in algorithm \\ref{alg:two} on the next page. For both evaluation subjects, \nwe use the same pseudocode but had to implement it in Python and Java for both applications respectively. \\\\\n\\SetKwComment{Comment}{/* }{ */}\n\n\\begin{algorithm}\n\\caption{Pseudocode for determining optimal chunk size}\\label{alg:two}\n\\Comment{n is the upper limit of chunk size as exponent of 2, p is the power computed from datasheet }\n\\KwData{$n \\geq 0, p$}\n\\Comment{Array of energy consumption for each chunk size}\n\\KwResult{$energyArray$}\n$N \\gets n$\\;\n$P \\gets p$\\;\n% $timeArray \\gets \\phi$\\;\n$energyArray \\gets \\phi$\\;\n\\While{$N \\neq 0$}{\n \\Comment{Create a byte array of the given size using a helper function}\n $array \\gets CreateByteArray(2^N)$\\;\n \\Comment{Start a timer}\n $start \\gets GetCurrentTime()$\\;\n \\Comment{Send the data to the server}\n $SendToServer(array)$\\;\n \\Comment{Stop the timer and compute the difference}\n $end \\gets GetCurrentTime()$\\;\n $executionTime \\gets end-start$\\;\n \\Comment{Compute the EPB and store it in array}\n $energy \\gets P * executionTime$\\;\n $EPB \\gets energy/2^N$\\;\n $energyArray \\gets energyArray \\cup EPB$\\;\n}\n\\end{algorithm}\nThis is a pretty straightforward but novel approach to aid programmers in developing applications for \na target edge device where they can optimize the communication cost in terms of energy. In some use cases, the \ndifference is considerable while in others it may not be that much. In short, it depends on the nature of the app \nitself. The following section will clarify more as to why it is as we describe our experimental and nature of the \napplications, and discuss our results. \\\\", "meta": {"hexsha": "ce9fae4cd482d795457a32cd67b6972631f30d0e", "size": 12186, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Chapters/Chapter4.tex", "max_stars_repo_name": "assaaassin/TXST-ThesisTemplate-LaTeX", "max_stars_repo_head_hexsha": "04a295e343f7ec4b28b10c1f1f3d5274190f838f", "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/Chapter4.tex", "max_issues_repo_name": "assaaassin/TXST-ThesisTemplate-LaTeX", "max_issues_repo_head_hexsha": "04a295e343f7ec4b28b10c1f1f3d5274190f838f", "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/Chapter4.tex", "max_forks_repo_name": "assaaassin/TXST-ThesisTemplate-LaTeX", "max_forks_repo_head_hexsha": "04a295e343f7ec4b28b10c1f1f3d5274190f838f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-09T02:00:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-09T02:00:19.000Z", "avg_line_length": 75.6894409938, "max_line_length": 142, "alphanum_fraction": 0.7842606269, "num_tokens": 2688, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.19546295367409278}}
{"text": "\\documentclass[11pt]{article}\n\\usepackage{times}\n\\newif\\ifpdf\n\\ifx\\pdfoutput\\undefined\n \\pdffalse\n \\usepackage[dvips]{graphicx} \n \\usepackage[dvips]{color} \n\\else\n \\pdftrue\n \\usepackage[pdftex]{graphicx} \n \\usepackage[pdftex]{color} \n\\fi\n\\usepackage{fullpage}\n\\usepackage{url}\n\\usepackage{cite}\n\\usepackage{alg}\n\\bibliographystyle{bmc_bioinformatics}\n\n% \\draftfalse: submission version. Figure legends & table at end. No figures included.\n% \\drafttrue: online preprint. Figures and table inline.\n\\newif\\ifdraft\n\\draftfalse\n\n\n% Double-spacing. You can't use the doublespace.sty package; it\n% conflicts with algorithm.sty.\n\\ifdraft\n \\relax\n\\else\n \\renewcommand{\\baselinestretch}{1.5}\n\\fi\n\n\\def\\argmax{\\mathop{\\mathrm{argmax}}\\limits}\n\\def\\argmin{\\mathop{\\mathrm{argmin}}\\limits}\n\n\\setcounter{secnumdepth}{0}\n\n\\begin{document}\n\n\\title{A memory-efficient dynamic programming algorithm for optimal\nalignment of a sequence to an RNA secondary structure}\n\\author{Sean R. Eddy\\\\\nHoward Hughes Medical Institute \\& Department of Genetics, \\\\\nWashington University School of Medicine \\\\\nSaint Louis, Missouri 63110 USA \\\\\neddy@genetics.wustl.edu} \n\\date{\\today}\n\\maketitle\n\n\\abstract{\\textbf{Background:} Covariance models (CMs) are probabilistic models of RNA\nsecondary structure, analogous to profile hidden Markov models of\nlinear sequence. The dynamic programming algorithm for aligning a CM\nto an RNA sequence of length $N$ is $O(N^3)$ in memory. This is only\npractical for small RNAs. \n\n\\textbf{Results:} I describe a divide and conquer variant of the\nalignment algorithm that is analogous to memory-efficient Myers/Miller\ndynamic programming algorithms for linear sequence alignment. The new\nalgorithm has an $O(N^2 \\log N)$ memory complexity, at the expense of\na small constant factor in time.\n\n\\textbf{Conclusions:} Optimal ribosomal RNA structural alignments that\npreviously required up to 150 GB of memory now require less than 270\nMB.}\n\n\\section{Background}\n\nThere are a growing number of RNA gene families and RNA motifs\n\\cite{Eddy01,Erdmann01}. Many (though not all) RNAs conserve a\nbase-paired RNA secondary structure. Computational analyses of RNA\nsequence families are more powerful if they take into account both\nprimary sequence and secondary structure consensus\n\\cite{Eddy02,Dandekar95}. \n\nSome excellent approaches have been developed for database searching\nwith RNA secondary structure consensus patterns. Exact- and\napproximate-match pattern searches (analogous to PROSITE patterns for\nproteins) have been extended to allow patterns to specify long-range\nbase pairing constraints \\cite{Laferriere94,Dsouza97}. In several\ncases, specialized programs have been developed to recognize specific\nRNA structures \\cite{Dandekar95} -- for example, programs exist for\ndetecting transfer RNA genes\n\\cite{Fichant91,El-MabroukLisacek96,LoweEddy97}, group I catalytic\nintrons \\cite{Lisacek94}, and small nucleolar RNAs\n\\cite{Nicoloso96,LoweEddy98}. All of these approaches, though\npowerful, lack generality, and they require expert knowledge about\neach particular RNA family of interest.\n\nIn primary sequence analysis, the most useful analysis techniques are\ngeneral primary sequence alignment algorithms with probabilistically\nbased scoring systems -- for example, the BLAST \\cite{Altschul97},\nFASTA \\cite{Pearson88}, or CLUSTALW \\cite{Thompson94b} algorithms, and\nthe PAM \\cite{Dayhoff78} or BLOSUM \\cite{Henikoff92} score\nmatrices. Unlike specialized programs, a general alignment algorithm\ncan be applied to find homologs of any query sequence(s). Unlike\npattern searches, which give yes/no answers for whether a candidate\nsequence is a match, a scoring system gives a meaningful score that\nallows ranking candidate hits by their statistical significance. It is\nof interest to develop general alignment algorithms for RNA secondary\nstructures.\n\nThe problem I consider here is as follows. I am given a multiple\nalignment of an RNA sequence family for which I know the consensus\nsecondary structure. I want to search a sequence database for homologs\nthat significantly match the sequence \\emph{and structure} of my\nquery. The sequence analysis analogue is the use of profile hidden\nMarkov models (profile HMMs) to model multiple alignments of conserved\nprotein domains, and to discover new homologues in sequence databases\n\\cite{Krogh94,Eddy98}. For instance, if we had an RNA structure\nequivalent of the HMMER profile HMM program suite\n(\\url{http://hmmer.wustl.edu/}) it would be possible to develop and\nefficiently maintain databases of conserved RNA structures and\nmultiple alignments, analogous to the Pfam or SMART databases of\nconserved protein domains \\cite{Bateman02,LetunikBork02}.\n\nStochastic context free grammar (SCFG) algorithms provide a general\napproach to RNA structure alignment\n\\cite{Eddy94,Sakakibara94c,Durbin98}. SCFGs allow the strong pairwise\nresidue correlations in non-pseudoknotted RNA secondary structure to\nbe taken into account in RNA alignments. SCFGs can be aligned to\nsequences using a dynamic programming algorithm that guarantees\nfinding a mathematically optimal solution in polynomial time. SCFG\nalignment algorithms can be thought of as an extension of sequence\nalignment algorithms (particularly those with fully probabilistic,\nhidden Markov model formulations) into an additional dimension\nnecessary to deal with 2D RNA secondary structure.\n\nWhile SCFGs provide a natural mathematical framework for RNA secondary\nstructure alignment problems, SCFG algorithms have high computational\ncomplexity that has impeded their practical application. Optimal\nSCFG-based structural alignment of an RNA structure to a sequence\ncosts $O(N^3)$ memory and $O(N^4)$ time for a sequence of length $N$,\ncompared to $O(N^2)$ memory and time for sequence alignment\nalgorithms. (Corpet and Michot described a program that implements a\ndifferent general dynamic programming algorithm for RNA alignment;\ntheir algorithm solves the same problem but even less efficiently,\nrequiring $O(N^4)$ memory and $O(N^5)$ time \\cite{Corpet94}.)\nSCFG-based alignments of small structural RNAs are feasible. Using my\nCOVE software\n(\\url{http://www.genetics.wustl.edu/eddy/software#cove}), transfer RNA\nalignments ($\\sim 75$ nucleotides) take about 0.2 cpu second and 3 Mb\nof memory. Most genome centers now use an COVE-based search program,\ntRNAscan-SE, for annotating transfer RNA genes\n\\cite{LoweEddy97}. However, many larger RNAs of interest are outside\nthe capabilities of the standard SCFG alignment algorithm. Alignment\nof a small subunit (SSU) ribosomal RNA sequence to the SSU rRNA\nconsensus structure would take about 23 GB of RAM and an hour of CPU\ntime. Applying SCFG methods to RNAs this large has required clever\nheuristics, such as using a precalculation of confidently predicted\nregions of primary sequence alignment to strongly constrain which\nparts of the SCFG dynamic programming matrix need to be calculated\n\\cite{Brown00}. The steep memory requirement remains a significant\nbarrier to the practicality of SCFG algorithms.\n\nNotredame \\emph{et al.} pointed specifically to this problem\n\\cite{Notredame97}. They described RAGA, a program that uses a\ngenetic algorithm (GA) to optimize a pairwise RNA alignment using an\nobjective function that includes base pairing terms. Because GAs have\nan $O(N)$ memory requirement, RAGA can find reasonable solutions for\nlarge RNA alignment problems, including ribosomal RNA alignments. A\ndifferent memory-efficient approach has also been described\n\\cite{Lenhof98,LenhofVingron98}. However, both approaches are\napproximate and cannot guarantee a mathematically optimal solution, in\ncontrast to the (mathematically) optimal but more expensive dynamic\nprogramming approaches.\n\nHere, I introduce a dynamic programming solution to the problem of\nstructural alignment of large RNAs. The central idea is a divide and\nconquer strategy. For linear sequence alignment, a divide and conquer\nalgorithm was introduced by Hirschberg \\cite{Hirschberg75}, an\nalgorithm known in the computational biology community as the\nMyers/Miller algorithm \\cite{MyM-88a}. (Ironically, at the time,\ndynamic programming methods for optimal sequence alignment were well\nknown, but were considered impractical on 1970's era computers because\nof the ``extreme'' $O(N^2)$ memory requirement.) Myers/Miller reduces\nthe memory complexity of a dynamic programming sequence alignment\nalgorithm from $O(N^2)$ to $O(N)$, at the cost of a roughly two-fold\nincrease in CPU time. Here I show that a divide and conquer strategy\ncan also be applied to the RNA structural alignment problem, greatly\nreducing the memory requirement of SCFG alignments and making optimal\nstructural alignment of large RNAs possible.\n\nI will strictly be dealing with the problem of aligning a target\nsequence of unknown secondary structure to a query of known RNA\nstructure. By ``secondary structure'' I mean nested (nonpseudoknotted)\npairwise RNA secondary structure interactions, primarily Watson-Crick\nbase pairs but also permitting noncanonical base pairs. This RNA\nstructural alignment problem is different from the problem of aligning\ntwo known RNA secondary structures together \\cite{Shapiro90}, and from\nthe problem of aligning two RNA sequences of unknown structure\ntogether under a secondary structure-aware scoring system\n\\cite{Sankoff85,KnudsenHein99,Gorodkin01,HolmesRubin02,MathewsTurner02}.\n\n\\section{Algorithm}\n\n\\subsection{Prelude: the simpler case of sequence alignment}\n\nThe essential concepts of a divide and conquer alignment algorithm are\nmost easily understood for the case of linear sequence alignment\n\\cite{Hirschberg75,MyM-88a}.\n\nDynamic programming (DP) algorithms for sequence alignment fill in an\n$N \\times M$ DP matrix of scores $F(i,j)$ for two sequences of lengths\n$N$ and $M$ ($N < M$) \\cite{Needleman70,Smith81}. Each score\n$F(i,j)$ is the score of the optimal alignment of prefix $x_1..x_i$ of\none sequence to prefix $y_1..y_j$ of the other. These scores are\ncalculated iteratively, e.g. for global (Needleman/Wunsch) alignment:\n\n\\[ F(i,j) = \\max \\left\\{ \\begin{array}{l}\n F(i-1,j-1) + \\mbox{score for aligning $x_i, y_j$} \\\\\n F(i-1,j) - \\mbox{cost of a gap character} \\\\\n F(i,j-1) - \\mbox{cost of a gap character} \\\\\n \\end{array} \\right. \\]\n\nAt the end, $F(N,M)$ contains the score of the optimal alignment. The\nalignment itself is recovered by tracing the individual optimal steps\nbackwards through the matrix, starting from cell $(N,M)$. The\nalgorithm is $O(NM)$ in both time and memory.\n\nIf we are only interested in the score, not the alignment itself, the\nwhole $F$ matrix does not have to be kept in memory. The iterative\ncalculation only depends on the current and previous row of the\nmatrix. Keeping two rows in memory suffices (in fact, a compulsively\nefficient implementation can get away with $N+1$ cells). A score-only\ncalculation can be done in $O(N)$ space.\n\nThe fill stage of DP alignment algorithms may be run either forwards\nand backwards. We can just as easily calculate the optimal score\n$B(i,j)$ of the best alignment of the \\emph{suffix} $i+1..N$ of\nsequence 1 to the suffix $j+1..M$ of sequence 2, until one obtains\n$B(0,0)$, the overall optimal score -- the same number as $F(N,M)$.\n\nThe sum of $F(i,j)$ and $B(i,j)$ at any cell in the optimal path\nthrough the DP matrix is also the optimal overall alignment score.\nMore generally, $F(i,j) + B(i,j)$ at any cell $(i,j)$ is the score of\nthe best alignment that uses that cell. Therefore, since we know the\noptimal alignment must pass through any given row $i$\n\\emph{somewhere}, we can pick some row $i$ in the middle of sequence\n$x$, run the forward calculation to $i$ to obtain row $F(i)$, run the\nbackwards calculation back to $i$ to get row $B(i)$, and then find\n$\\argmax\\nolimits_j F(i,j) + B(i,j)$. Now I know the optimal alignment\npasses through cell $(i,j)$. (For clarity, I am leaving out details of\nhow indels and local alignments are handled.)\n\nThis divides the alignment into two smaller alignment problems, and\nthese smaller problems can themselves be subdivided by the same trick.\nThus, the complete optimal alignment can be found by a recursive\nseries of split point calculations. Although this seems laborious --\neach calculation is giving us only a single point in the alignment --\nif we choose our split row $i$ to be in the middle, the size of the\ntwo smaller DP problems is decreased by about 4-fold at each split. A\ncomplete alignment thus costs only about $1 + \\frac{2}{4} +\n\\frac{4}{16} + \\ldots \\simeq 2$ times as much CPU time as doing the\nalignment in a single DP matrix calculation, but the algorithm is\n$O(N)$ in memory.\n\nA standard dynamic programming alignment algorithm for SCFGs is the\nCocke-Younger-Kasami (CYK) algorithm, which finds an optimal parse\ntree (e.g. alignment) for a model and a sequence\n\\cite{Kasami65,Younger67,HopcroftUllman79,Durbin98}. (CYK is usually\ndescribed in the literature as a dynamic programming recognition\nalgorithm for nonstochastic CFGs in Chomsky normal form, rather than\nas a dynamic programming parsing algorithm for SCFGs in any form. The\nuse of the name ``CYK'' here is therefore a little imprecise\n\\cite{Durbin98}.) CYK can be run in a memory-saving ``score only''\nmode. The DP matrix for CYK can also be filled in two opposite\ndirections - either ``inside'' or ``outside'', analogous to forward\nand backward DP matrix fills for linear sequence alignment. I will\nrefer to these algorithms as CYK/inside and CYK/outside (or just\n\\texttt{inside} and \\texttt{outside}), but readers familiar with SCFG\nalgorithms should not confuse them with the SCFG Inside and Outside\nalgorithms \\cite{Lari90,Lari91} which sum over all possible parse\ntrees rather than finding one optimal parse tree. I am always talking\nabout the CYK algorithm in this paper, and by ``inside'' and\n``outside'' I am only referring generically to the direction of the\nCYK DP calculation.\n\nThe CYK/inside and CYK/outside algorithms are not as nicely\nsymmetrical as the forward and backward DP fills are in sequence\nalignment algorithms. The splitting procedure that one obtains does\nnot generate identical types of subproblems, so the divide and conquer\nprocedure for SCFG-based RNA alignment is not as obvious.\n\n\\subsection{Definition and construction of a covariance model}\n\nThe divide and conquer algorithm I will describe is specific for RNA\n``covariance models'' (CMs). A covariance model is a profile\nstochastic context free grammar designed to model a consensus RNA\nsecondary structure with position-specific scores\n\\cite{Eddy94,Durbin98}. My algorithm takes advantage of features of\nCMs that do not apply to SCFGs in general. Therefore I start with an\nintroduction to what CMs are, how they correspond to a known RNA\nsecondary structure, and how they are built and parameterized.\n\n\\subsubsection{Definition of a stochastic context free grammar}\n\nA stochastic context free grammar (SCFG) consists of the following:\n\n\\begin{itemize}\n\\item $M$ different nonterminals (here called \\emph{states}). I will use capital\n letters to refer to specific nonterminals; $V$ and $Y$ will be used\n to refer generically to unspecified nonterminals.\n\\item $K$ different terminal symbols (e.g. the observable alphabet,\n {a,c,g,u} for RNA). I will use small letters $a,b$ to refer\n generically to terminal symbols.\n\\item a number of \\emph{production rules} of the form: $V \\rightarrow\n\\gamma$, where $\\gamma$ can be any string of nonterminal and/or\nterminal symbols, including (as a special case) the empty string\n$\\epsilon$.\n\\item Each production rule is associated with a probability, such that\n the sum of the production probabilities for any given\n nonterminal $V$ is equal to 1.\n\\end{itemize} \n\n\\subsubsection{SCFG productions allowed in covariance models}\n\nA covariance model is a specific repetitive ``profile SCFG''\narchitecture consisting of groups of model states that are associated\nwith base pairs and single-stranded positions in an RNA secondary\nstructure consensus. A covariance model has seven types of states and\nproduction rules:\n\n\\vspace{0.5em}\n\\begin{tabular}{lllll}\nState type & Description & Production & Emission & Transition\\\\ \\hline\nP & (pair emitting) & $P \\rightarrow a Y b$ & $e_v(a,b)$ & $t_v(Y)$ \\\\\nL & (left emitting) & $L \\rightarrow a Y$ & $e_v(a)$ & $t_v(Y)$ \\\\\nR & (right emitting) & $R \\rightarrow Y a$ & $e_v(a)$ & $t_v(Y)$ \\\\\nB & (bifurcation) & $B \\rightarrow S S$ & 1 & 1 \\\\\nD & (delete) & $D \\rightarrow Y$ & 1 & $t_v(Y)$ \\\\\nS & (start) & $S \\rightarrow Y$ & 1 & $t_v(Y)$ \\\\\nE & (end) & $E \\rightarrow \\epsilon$ & 1 & 1 \\\\\n\\end{tabular}\n\\vspace{0.5em}\n\nEach overall production probability is the independent product of an\nemission probability $e_v$ and a transition probability $t_v$, both of\nwhich are position-dependent parameters that depend on the state $v$\n(analogous to hidden Markov models). For example, a particular pair\n(P) state $v$ produces two correlated letters $a$ and $b$ (e.g. one of\n16 possible base pairs) with probability $e_v(a,b)$ and transits to\none of several possible new states $Y$ of various types with\nprobability $t_v(Y)$. A bifurcation (B) state splits into two new\nstart ($S$) states with probability 1. The E state is a special case\n$\\epsilon$ production that terminates a derivation.\n\nA CM consists of many states of these seven basic types, each with its\nown emission and transition probability distributions, and its own set\nof states that it can transition to. Consensus base pairs will be\nmodeled by P states, consensus single stranded residues by L and\nR states, insertions relative to the consensus by more L and R\nstates, deletions relative to consensus by D states, and the\nbranching topology of the RNA secondary structure by B, S, and E\nstates. The procedure for starting from an input multiple alignment\nand determining how many states, what types of states, and how they\nare interconnected by transition probabilities is described next.\n\n\\subsubsection{From consensus structural alignment to guide tree}\n\nFigure~\\ref{fig:input_alignment} shows an example input file: a\nmultiple sequence alignment of homologous RNAs, with a line describing\nthe consensus RNA secondary structure. The first step of building a CM\nis to produce a binary \\emph{guide tree} of \\emph{nodes} representing\nthe consensus secondary structure. The guide tree is a parse tree for\nthe consensus structure, with nodes as nonterminals and alignment\ncolumns as terminals.\n\n\\ifdraft\n\\begin{figure}[t]\n\\begin{center}\n\\includegraphics[width=5in]{Figures/input_alignment}\n\\end{center}\n\\caption{\\textbf{An example RNA sequence family.} Top: a toy multiple\nalignment of three sequences, with 28 total columns, 24 of which will\nbe modeled as consensus positions. The [structure] line annotates the\nconsensus secondary structure: $>$ and $<$ symbols mark base pairs,\nx's mark consensus single stranded positions, and .'s mark\n``insert'' columns that will not be considered part of the consensus\nmodel. Bottom: the secondary structure of the ``human'' sequence.} \n\\label{fig:input_alignment}\n\\end{figure}\n\\fi\n\nThe guide tree has eight types of nodes:\n\n\\vspace{0.5em}\n\\begin{tabular}{lll}\nNode & Description & Main state type \\\\ \\hline\nMATP & (pair) & P \\\\\nMATL & (single strand, left) & L \\\\\nMATR & (single strand, right) & R \\\\\nBIF & (bifurcation) & B \\\\\nROOT & (root) & S \\\\\nBEGL & (begin, left) & S \\\\\nBEGR & (begin, right) & S \\\\\nEND & (end) & E \\\\\n\\end{tabular}\n\\vspace{0.5em}\n \nThese consensus node types correspond closely with a CM's final state\ntypes. Each node will eventually contain one or more states. The guide\ntree deals with the consensus structure. For individual sequences, we\nwill need to deal with insertions and deletions with respect to this\nconsensus. The guide tree is the skeleton on which we will organize\nthe CM. For example, a MATP node will contain a P-type state to\nmodel a consensus base pair; but it will also contain several other\nstates to model infrequent insertions and deletions at or adjacent to\nthis pair.\n\nThe input alignment is first used to construct a consensus secondary\nstructure (Figure~\\ref{fig:cm_nodetree}) that defines which aligned\ncolumns will be ignored as non-consensus (and later modeled as\ninsertions relative to the consensus), and which consensus alignment\ncolumns are base-paired to each other. Here I assume that both the\nstructural annotation and the labeling of insert versus consensus\ncolumns is given in the input file, as shown in the line marked\n``[structure]'' in the alignment in Figure~\\ref{fig:input_alignment}.\nAlternatively, automatic methods might be employed. A consensus\nstructure could be predicted from comparative analysis of the\nalignment \\cite{Chiu91,Gutell92,Eddy94}. The consensus columns could\nbe chosen as those columns with less than a certain fraction of gap\nsymbols, or by a maximum likelihood criterion, as is done for profile\nHMM construction \\cite{Krogh94,Durbin98}.\n\n\\ifdraft\n\\begin{figure}[t]\n\\begin{center}\n\\includegraphics[width=5in]{Figures/cm_nodetree}\n\\end{center}\n\\caption{\\textbf{The structural alignment is converted to a guide\ntree.} Left: the consensus secondary structure is derived from the\nannotated alignment in Figure~\\ref{fig:input_alignment}. Numbers in\nthe circles indicate alignment column coordinates: e.g. column 4 base\npairs with column 14, and so on. Right: the CM guide tree\ncorresponding to this consensus structure. The nodes of the tree are\nnumbered 1..24 in preorder traversal (see text). MATP, MATL, and MATR\nnodes are associated with the columns they generate: e.g., node 6 is a\nMATP (pair) node that is associated with the base-paired columns 4 and\n14.}\n\\label{fig:cm_nodetree}\n\\end{figure}\n\\fi\n\nGiven the consensus structure, consensus base pairs are assigned to\nMATP nodes and consensus unpaired columns are assigned to MATL or MATR\nnodes. One ROOT node is used at the head of the tree. Multifurcation\nloops and/or multiple stems are dealt with by assigning one or more\nBIF nodes that branch to subtrees starting with BEGL or BEGR head\nnodes. (ROOT, BEGL, and BEGR start nodes are labeled differently\nbecause they will be expanded to different groups of states; this has\nto do with avoiding ambiguous parse trees for individual sequences, as\ndescribed below.) Alignment columns that are considered to be\ninsertions relative to the consensus structure are ignored at this\nstage.\n\nIn general there will be more than one possible guide tree for any\ngiven consensus structure. Almost all of this ambiguity is eliminated\nby three conventions: (1) MATL nodes are always used instead of MATR\nnodes where possible, for instance in hairpin loops; (2) in describing\ninterior loops, MATL nodes are used before MATR nodes; and (3) BIF\nnodes are only invoked where necessary to explain branching secondary\nstructure stems (as opposed to unnecessarily bifurcating in single\nstranded sequence). One source of ambiguity remains. In invoking a\nbifurcation to explain alignment columns $i..j$ by two substructures\non columns $i..k$ and $k+1..j$, there will be more than one possible\nchoice of $k$ if $i..j$ is a multifurcation loop containing three or\nmore stems. The choice of $k$ impacts the performance of the divide\nand conquer algorithm; for optimal time performance, we will want\nbifurcations to split into roughly equal sized alignment problems, so\nI choose the $k$ that makes $i..k$ and $k+1..j$ as close to the same\nlength as possible.\n\nThe result of this procedure is the guide tree. The nodes of the guide\ntree are numbered in preorder traversal (e.g. a recursion of ``number\nthe current node, visit its left child, visit its right child'': thus\nparent nodes always have lower indices than their children). The guide\ntree corresponding to the input multiple alignment in\nFigure~\\ref{fig:input_alignment} is shown in\nFigure~\\ref{fig:cm_nodetree}.\n\n\\subsubsection{From guide tree to covariance model}\n\nA CM must deal with insertions and deletions in individual sequences\nrelative to the consensus structure. For example, for a consensus base\npair, either partner may be deleted leaving a single unpaired residue,\nor the pair may be entirely deleted; additionally, there may be\ninserted nonconsensus residues between this pair and the next pair in\nthe stem. Accordingly, each node in the master tree is expanded into\none or more \\emph{states} in the CM as follows:\n\n\\vspace{0.5em}\n\\begin{tabular}{llccc}\n & & total \\#& \\# of split& \\# of insert\\\\\nNode & States & states & states & states \\\\ \\hline\nMATP & [MP ML MR D] IL IR & 6 & 4 & 2 \\\\\nMATL & [ML D] IL & 3 & 2 & 1 \\\\\nMATR & [MR D] IR & 3 & 2 & 1 \\\\\nBIF & [B] & 1 & 1 & 0 \\\\\nROOT & [S] IL IR & 3 & 1 & 2 \\\\\nBEGL & [S] & 1 & 1 & 0 \\\\\nBEGR & [S] IL & 2 & 1 & 1 \\\\\nEND & [E] & 1 & 1 & 0 \\\\ \\hline\n\\end{tabular}\n\\vspace{0.5em}\n\nHere we distinguish between consensus (``M'', for ``match'') states\nand insert (``I'') states. ML and IL, for example, are both L type\nstates with L type productions, but they will have slightly different\nproperties, as described below.\n\nThe states are grouped into a \\emph{split set} of 1-4 states (shown in\nbrackets above) and an \\emph{insert set} of 0-2 insert states. The\nsplit set includes the main consensus state, which by convention is\nfirst. One and only one of the states in the split set must be visited\nin every parse tree (and this fact will be exploited by the divide and\nconquer algorithm). The insert state(s) are not obligately visited,\nand they have self-transitions, so they will be visited zero or more\ntimes in any given parse tree.\n\nState transitions are then assigned as follows. For bifurcation nodes,\nthe B state makes obligate transitions to the S states of the child\nBEGL and BEGR nodes. For other nodes, each state in a split set has a\npossible transition to every insert state in the \\emph{same} node, and\nto every state in the split set of the \\emph{next} node. An IL state\nmakes a transition to itself, to the IR state in the same node (if\npresent), and to every state in the split set of the next node. An IR\nstate makes a transition to itself and to every state in the split set\nof the next node.\n\nThis arrangement of transitions guarantees that (given the guide tree)\nthere is unambiguously one and only one parse tree for any given\nindividual structure. This is important. The algorithm will find a\nmaximum likelihood parse tree for a given sequence, and we wish to\ninterpret this result as a maximum likelihood structure, so there must\nbe a one to one relationship between parse trees and secondary\nstructures \\cite{Giegerich00}.\n\nThe final CM is an array of $M$ states, connected as a directed graph\nby transitions $t_v(y)$ (or probability 1 transitions $v \\rightarrow\n(y,z)$ for bifurcations) with the states numbered such that $(y,z)\n\\geq v$. There are no cycles in the directed graph other than cycles\nof length one (e.g. the self-transitions of the insert states). We can\nthink of the CM as an array of states in which all transition\ndependencies run in one direction; we can do an iterative dynamic\nprogramming calculation through the model states starting with the\nlast numbered end state $M$ and ending in the root state $1$. An\nexample CM, corresponding to the input alignment of\nFigure~\\ref{fig:input_alignment}, is shown in\nFigure~\\ref{fig:cm_graph}.\n\nAs a convenient side effect of the construction procedure, it is\nguaranteed that the transitions from any state are to a\n\\emph{contiguous} set of child states, so the transitions for state\n$v$ may be kept as an offset and a count. For example, in\nFigure~\\ref{fig:cm_graph}, state 12 (an MP) connects to states 16, 17,\n18, 19, 20, and 21. We can store this as an offset of 4 to the first\nconnected state, and a total count of 6 connected states. We know\nthat the offset is the distance to the next non-split state in the\ncurrent node; we also know that the count is equal to the number of\ninsert states in the current node, plus the number of split set states\nin the next node. These properties make establishing the connectivity\nof the CM trivial. Similarly, all the parents of any given state are\nalso contiguously numbered, and can be determined analogously. We are\nalso guaranteed that the states in a split set are numbered\ncontiguously. This contiguity is exploited by the divide and conquer\nimplementation.\n\n\\ifdraft\n\\begin{figure}[tp]\n\\begin{center}\n\\includegraphics[width=5in]{Figures/cm_graph}\n\\end{center}\n\\caption{\\textbf{A complete covariance model.} Right: the CM\ncorresponding to the alignment in Figure~\\ref{fig:input_alignment}.\nThe model has 81 states (boxes, stacked in a vertical array). Each\nstate is associated with one of the 24 nodes of the guide tree (text\nto the right of the state array). States corresponding to the\nconsensus are in white. States responsible for insertions and\ndeletions are gray. The transitions from bifurcation state B10 to\nstart states S11 and S46 are in bold because they are special: they\nare an obligate (probability 1) bifurcation. All other transitions\n(thin arrows) are associated with transition probabilities. Emission\nprobability distributions are not represented in the figure. Left: the\nstates are also arranged according to the guide tree. A blow up of\npart of the model corresponding to nodes 6, 7, and 8 shows\nmore clearly the logic of the connectivity of transition probabilities\n(see main text), and also shows why any parse tree must transit through\none and only one state in each ``split set''.}\n\\label{fig:cm_graph}\n\\end{figure}\n\\fi\n\n\\subsubsection{Parameterization}\n\nUsing the guide tree and the final CM, each individual sequence in the\ninput multiple alignment can be converted unambiguously to a CM parse\ntree, as shown in Figure~\\ref{fig:parsetrees}. Counts for observed\nstate transitions and singlet/pair emissions are then collected from\nthese parse trees. The observed counts are converted to transition and\nemission probabilities by standard procedures. I calculate maximum a\nposteriori parameters, using Dirichlet priors.\n\n\\ifdraft\n\\begin{figure}[t]\n\\begin{center}\n\\includegraphics[width=5in]{Figures/parsetrees}\n\\end{center}\n\\caption{\\textbf{Example parse trees.} Parse trees are shown for the\nthree sequences/structures from Figure~\\ref{fig:input_alignment},\ngiven the CM in Figure~\\ref{fig:cm_graph}. For each sequence, each\nresidue must be associated with a state in the parse tree. (The\nsequences can be read off its parse tree by starting at the upper left\nand reading counterclockwise around the edge of parse tree.) Each\nparse tree corresponds directly to a secondary structure -- base pairs\nare pairs of residues aligned to MP states. A collection of parse\ntrees also corresponds to a multiple alignment, by aligning residues\nthat are associated with the same state -- for example, all three\ntrees have a residue aligned to state ML4, so these three residues\nwould be aligned together. Insertions and deletions relative to the\nconsensus use nonconsensus states, shown in gray.}\n\\label{fig:parsetrees}\n\\end{figure}\n\\fi\n\n\\subsubsection{Comparison to profile HMMs}\n\nThe relationship between an SCFG and a covariance model is analogous\nto the relationship of hidden Markov models (HMMs) and profile HMMs\nfor modeling multiple sequence alignments\n\\cite{Krogh94,Durbin98,Eddy98}. A comparison may be instructive to\nreaders familiar with profile HMMs. A profile HMM is a repetitive HMM\narchitecture that associates each consensus column of a multiple\nalignment with a single type of model node -- a MATL node, in the\nabove notation. Each node contains a ``match'', ``delete'', and\n``insert'' HMM state -- ML, IL, and D states, in the above notation.\nThe profile HMM also has special begin and end states. Profile HMMs\ncould therefore be thought of as a special case of CMs. An\nunstructured RNA multiple alignment would be modeled by a guide tree\nof all MATL nodes, and converted to an unbifurcated CM that would\nessentially be identical to a profile HMM. (The only difference is\ntrivial; the CM root node includes a IR state, whereas the start node\nof a profile HMM does not.) All the other node types (especially MATP,\nMATR, and BIF) and state types (e.g. MP, MR, IR, and B) are SCFG\naugmentations necessary to extend profile HMMs to deal with RNA\nsecondary structure.\n\nThe SCFG Inside and Outside algorithms are analogous to the Forward\nand Backward algorithms for HMMs \\cite{Rabiner89,Durbin98}. The\nCYK/inside parsing algorithm is analogous to the Viterbi HMM alignment\nalgorithm run in the forward direction. CYK/outside is analogous to a\nViterbi DP algorithm run in the backwards direction.\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\subsection{Divide and conquer algorithm}\n\n\\subsubsection{Notation}\n\nI use $r$, $v$, $w$, $y$, and $z$ as indices of states in the model,\nwhere $r \\leq (v,w,y) \\leq z$. These indices will range from $1..M$,\nfor a CM $G$ that contains $M$ states. $G^r_z$ refers to a subgraph of\nthe model, rooted at state $r$ and ending at state $z$, for a\ncontiguous set of states $r..z$. $G^r$, without a subscript, refers to\na subgraph of the model rooted at state $r$ and ending at the highest\nnumbered E state descendant from state $r$. The complete model is\n$G^1_M$, or $G^1$, or just $G$.\n\n$S_v$ refers to the \\emph{type} of state $v$; it will be one of seven\ntypes \\{D,P,L,R,S,E,B\\}. $C_v$ is a list of children for state $v$\n(e.g. the states that $v$ can transit to); it will contain up to six\ncontiguous indices $y$ with $v \\leq y \\leq M$. $P_v$ is a list of\nparents for state $v$ (states that could have transited to state $v$);\nit will contain up to six contiguous indices $y$ with $1 \\leq y \\leq\nv$. ($P_v$ parent lists should not be confused with P state types.)\n\nI use $g$, $h$, $i$, $j$, $k$, $p$, and $q$ as indices referring to\npositions in a sequence $x$, where $g \\leq h \\leq p \\leq q$ and $i\n\\leq j$ for all subsequences of nonzero length. These indices range\nfrom $1..L$, for a sequence of length $L$. Some algorithms will also\nuse $d$ to refer to a subsequence length, where $d = j-i+1$ for a\nsubsequence $x_i..x_j$.\n\nThe algorithms will have to account for subsequences of zero length\n(because of deletions). By convention, these will be in the\noff-diagonal where $j = i-1$ or $i = j+1$. This special case (usually\nan initialization condition) is the reason for the qualification that\n$i \\leq j$ for subsequences of \\emph{nonzero} length.\n\nThe CYK/inside algorithm calculates a three-dimensional matrix of\nnumbers $\\alpha_v(i,j)$, and CYK/outside calculates numbers\n$\\beta_v(i,j)$. I will refer to $v$ (state indices) as \\emph{deck}\ncoordinates in the three-dimensional matrices, whereas $j$ and $i$\n(sequence positions) are row and column coordinates within each deck.\n$\\alpha_{v}$ and $\\beta_{v}$ refer to whole two-dimensional decks\ncontaining scores $\\alpha_v(i,j)$ and $\\beta_v(i,j)$ for a particular\nstate $v$. The dividing and conquering will be done in the $v$\ndimension, by choosing particular decks as split points.\n\n\\subsubsection{The CYK/inside algorithm}\n\nThe CYK/inside algorithm iteratively calculates $\\alpha_v(i,j)$ -- the\nlog probability of the most likely CM parse subtree rooted at state\n$v$ that generates subsequence $x_i..x_j$ of sequence $x$. The\ncalculation initializes at the smallest subgraphs and subsequences\n(e.g. subgraphs rooted at E states, generating subsequences of length\n0), and iterates outwards to progessively longer subsequences and\nlarger CM subgraphs.\n\nFor example, if we're calculating $\\alpha_v(i,j)$ and $S_v =$ P (that\nis, $v$ is a pair state), $v$ will generate the pair $x_i,x_j$ and\ntransit to a new state $y$ (one of its possible transitions $C_v$)\nwhich then will have to account for the smaller subsequence\n$x_{i+1}..x_{j-1}$. The log probability for a particular choice of\nnext state $y$ is the sum of three terms: an emission term $\\log\ne_v(x_i,x_j)$, a transition term $\\log t_v(y)$, and an already\ncalculated solution for the smaller optimal parse tree rooted at $y$,\n$\\alpha_y(i+1,j-1)$. The answer for $\\alpha_v(i,j)$ is the maximum\nover all possible choices of child states $y$ that $v$ can transit to.\n\nThe algorithm \\texttt{inside} is as follows:\n\n\\begin{algorithm}\n\\alginout{A CM subgraph $G^r_z$ and subsequence $x_g..x_q$.}\n {Scoring matrix decks $\\alpha_r..\\alpha_z$.}\n\\algname{inside}{r,z; g,q} \n\\begin{algtab*}\n\\algforto{$v \\leftarrow z$ \\textbf{down}}{$r$}\n \\algforto{$j \\leftarrow g-1$}{$q$} \n \\algforto{$i \\leftarrow j+1$ \\textbf{down}}{$g$}\n $d \\leftarrow j-i+1$\\\\\n \\algif{$S_v =$ D or S:}\n \t$\\alpha_v(i,j) = \\max\\limits_{y \\in C_v} \\left[ \\alpha_y(i,j) + \\log t_v(y) \\right]$\\\\\n \\algelseif{$S_v =$ P and $d \\geq 2$:}\n\t$\\alpha_v(i,j) = \\log e_v(x_i, x_j) + \\max\\limits_{y \\in C_v} \\left[ \\alpha_y(i+1,j-1) + \\log t_v(y) \\right]$\\\\\n \\algelseif{$S_v =$ L and $d\\geq1$:}\n $\\alpha_v(i,j) = \\log e_v(x_i) + \\max\\limits_{y \\in C_v} \\left[ \\alpha_y(i+1,j) + \\log t_v(y) \\right]$\\\\\n \\algelseif{$S_v =$ R and $d\\geq1$:}\n $\\alpha_v(i,j) = \\log e_v(x_j) + \\max\\limits_{y \\in C_v} \\left[ \\alpha_y(i,j-1) + \\log t_v(y) \\right]$ \\\\\n \\algelseif{$S_v =$ B:}\n $(y,z) \\leftarrow $ left and right S children of state $v$\\\\\n $\\alpha_v(i,j) = \\max\\limits_k \\left[ \\alpha_y(i,k) + \\alpha_z(k+1,j) \\right]$ \\\\\n \\algelseif{$S_v =$ E and $d=0$:}\n\t$\\alpha_v(i,j) = 0$ (initializations)\\\\\n \\algelse\n\t$\\alpha_v(i,j) = -\\infty$ (initializations)\\\\\n\\end{algtab*}\n\\end{algorithm}\n\nGiven a sequence $x$ of length $L$ and a CM $G$ of length $M$, we\ncould call \\texttt{inside(1,M; 1,L)} to align the whole model (states\n$1..M$) to the whole sequence ($x_1..x_L$). When \\texttt{inside}\nreturns, $\\alpha_1(1,L)$ would contain the log probability of the best\nparse of the complete sequence with the complete model. \n\nWe do not have to keep the entire $\\alpha$ three-dimensional matrix in\nmemory to calculate these scores. As we reach higher decks $\\alpha_v$\nin the three dimensional dynamic programming matrix, our calculations\nno longer depend on certain lower decks. A lower deck $y$ can be\ndeallocated whenever all the parent decks $P_y$ that depend on it\nhave been calculated. (The implementation goes even further\nand recycles decks when possible, saving some initialization steps and\nmany memory allocation calls; for example, since values in all E decks\nare identical, only one E deck needs to be calculated and that\nprecalculated deck can be reused whenever $S_v = E$.)\n\nThis deallocation rule has an important property that the divide and\nconquer algorithm takes advantage of when solving smaller subproblems\nfor CM subgraphs rooted at some state $w$. When the root state $w$ is\nan S state, the $\\alpha$ matrix returned by \\texttt{inside} contains\nonly one active deck $\\alpha_w$. (No lower state $>w$ can be reached\nfrom any state $$ and $<$ symbols mark base pairs,\nx's mark consensus single stranded positions, and .'s mark\n``insert'' columns that will not be considered part of the consensus\nmodel. Bottom: the secondary structure of the ``human'' sequence.} \n\\label{fig:input_alignment}\n\\end{figure}\n\n\\begin{figure}[h]\n\\caption{\\textbf{The structural alignment is converted to a guide\ntree.} Left: the consensus secondary structure is derived from the\nannotated alignment in Figure~\\ref{fig:input_alignment}. Numbers in\nthe circles indicate alignment column coordinates: e.g. column 4 base\npairs with column 14, and so on. Right: the CM guide tree\ncorresponding to this consensus structure. The nodes of the tree are\nnumbered 1..24 in preorder traversal (see text). MATP, MATL, and MATR\nnodes are associated with the columns they generate: e.g., node 6 is a\nMATP (pair) node that is associated with the base-paired columns 4 and\n14.}\n\\label{fig:cm_nodetree}\n\\end{figure}\n\n\\begin{figure}[h]\n\\caption{\\textbf{A complete covariance model.} Right: the CM\ncorresponding to the alignment in Figure~\\ref{fig:input_alignment}.\nThe model has 81 states (boxes, stacked in a vertical array). Each\nstate is associated with one of the 24 nodes of the guide tree (text\nto the right of the state array). States corresponding to the\nconsensus are in white. States responsible for insertions and\ndeletions are gray. The transitions from bifurcation state B10 to\nstart states S11 and S46 are in bold because they are special: they\nare an obligate (probability 1) bifurcation. All other transitions\n(thin arrows) are associated with transition probabilities. Emission\nprobability distributions are not represented in the figure. Left: the\nstates are also arranged according to the guide tree. A blow up of\npart of the model corresponding to nodes 6, 7, and 8 shows\nmore clearly the logic of the connectivity of transition probabilities\n(see main text), and also shows why any parse tree must transit through\none and only one state in each ``split set''.}\n\\label{fig:cm_graph}\n\\end{figure}\n\n\\begin{figure}[h]\n\\caption{\\textbf{Example parse trees.} Parse trees are shown for the\nthree sequences/structures from Figure~\\ref{fig:input_alignment},\ngiven the CM in Figure~\\ref{fig:cm_graph}. For each sequence, each\nresidue must be associated with a state in the parse tree. (The\nsequences can be read off its parse tree by starting at the upper left\nand reading counterclockwise around the edge of parse tree.) Each\nparse tree corresponds directly to a secondary structure -- base pairs\nare pairs of residues aligned to MP states. A collection of parse\ntrees also corresponds to a multiple alignment, by aligning residues\nthat are associated with the same state -- for example, all three\ntrees have a residue aligned to state ML4, so these three residues\nwould be aligned together. Insertions and deletions relative to the\nconsensus use nonconsensus states, shown in gray.}\n\\label{fig:parsetrees}\n\\end{figure}\n\n\\begin{figure}[h]\n\\caption{\\textbf{The three types of problems that need to be split.}\nThe sequence axis (e.g. $x_g..x_q$) is horizontal. The model subgraph\naxis for a contiguous set of states (e.g. states $r..z$) is vertical,\nwhere a solid lines means an unbifurcated model subgraph, and a dashed\nline means a model subgraph that may contain bifurcations. Closed\ncircles indicate ``inclusive of'', and open circles indicate\n``exclusive of''.}\n\\label{fig:splitter_schematic}\n\\end{figure}\n\n\\begin{figure}[h]\n\\caption{\\textbf{Empirical time and memory requirements for structural\nalignment.} Plots of data from Table~\\ref{tbl:results}. Filled\ncircles: divide and conquer algorithm; open circles: standard CYK\nalgorithm. Left: Memory use in megabytes on a log-log scale. Lines\nrepresent weighted least-squares regression fits to the theoretically\nexpected memory scaling: $aN^2 \\log N$ for divide and conquer (solid\nline) and $aN^3$ for standard CYK (dashed line). Right: CPU times in\nseconds on a log-log scale. Lines represent least-squares regression\nfits to a power law ($aN^b$). According to this fit, divide and\nconquer time (solid line) empirically scales as $N^{3.24}$, and\nstandard CYK without traceback (dashed line) scales as $N^{3.29}$. A\nline representing $O(N^4)$ scaling (the theoretical upper bound on\nperformance) is shown for comparison.}\n\\label{fig:graphs}\n\\end{figure}\n\n\\newpage\n\n\n\n\\fi\n\n\n\n\\end{document}\n\n\n\n", "meta": {"hexsha": "cde25211c9bf4051e0502e7c5dd2a55ebb3d5bf5", "size": 75857, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Manuscripts/divide-and-conquer/main.tex", "max_stars_repo_name": "lamby/infernal", "max_stars_repo_head_hexsha": "a358a4984a90efd8177a82440f7576204735ae5c", "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": "Manuscripts/divide-and-conquer/main.tex", "max_issues_repo_name": "lamby/infernal", "max_issues_repo_head_hexsha": "a358a4984a90efd8177a82440f7576204735ae5c", "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": "Manuscripts/divide-and-conquer/main.tex", "max_forks_repo_name": "lamby/infernal", "max_forks_repo_head_hexsha": "a358a4984a90efd8177a82440f7576204735ae5c", "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.9716732543, "max_line_length": 120, "alphanum_fraction": 0.7406831275, "num_tokens": 20759, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.19546295367409278}}
{"text": "\\section{Transactions}\n\\label{sec:transactions}\n\nIn this chapter, we outline the changes necessary to transaction and\nUTxO type structure to introduce native multicurrency functionality\ninto the Cardano\nsystem.\n\n\\textbf{Representing Multicurrency.}\nSome new types (and changes to existing types) are are required for\nan MC-supporting ledger, see Figure~\\ref{fig:defs:utxo-shelley-1}.\nThe types not appearing in the Figure below are consistent with the\ncurrent Shelley ledger design.\n\n\\begin{itemize}\n\n \\item $\\Language$ is a natural number-valued language tag used to represent\n the type scripting language, e.g.\n $\\mathsf{nativeMSigTag}$ and $\\mathsf{nativeMCTag}$\n\n \\item $\\CurrencyId$ is the identifier of a specific currency. The monetary\n policy of a currency with the ID $cid$ is given by the monetary policy script\n (MPS) $s$, such that $\\fun{hashScript}~s~=~cid$. The script is called a\n monetary policy script because when run, it verifies that the tokens of a currency\n with the corresponding $cid$ are according to the restrictions imposed by the\n monetary policy. If the restrictions are complied with, it returns\n $\\mathsf{True}$, and\n $\\mathsf{False}$ otherwise. More on MPS below.\n\n \\item $\\Token$ : for each currency ID $cid$, in the MC model, we can associate\n some tokens with this currency. A term $t\\in\\Token$ is an identifier of a\n kind of token in a given currency $cid$. Within the currency $cid$,\n tokens of the same type (with the same identifier $t\\in\\Token$) are fungible\n with each other. That is, they are effectively the \"same\" token, in the same way that\n every Ada coin is indistinguishable from another Ada coin. Ada\n has the currency ID $\\mathsf{adaID}$. The statement \\textit{all of the tokens\n of this currency must\n be the same}, in a MC scheme, means that there is only one kind of term of\n type $\\Token$ associated\n with $\\mathsf{adaID}$, and we call it $\\mathsf{adaToken}$.\n See below for a more detailed discussion of Ada representation.\n\n Note that currencies with different IDs may have tokens with the same names.\n For example, a new currency $\\mathsf{NotAda}$ can also have an $\\mathsf{adaToken}$.\n These are not the same tokens and are not fungible with each other.\n\n \\item $\\Quantity$ is an integer type representing an amount. This type is used\n specifically to represent an amount of a specific $\\Token$. We associate\n a term $q\\in\\Quantity$ with a specific token to keep track of how much of\n this token there is in a given value.\n\n \\item $\\Value$ is the multicurrency type used to represent\n all tokens, including Ada. The key of this finite map type is\n the hash of the monetary policy script for this currency.\n A value $v\\in\\Value$ is a finite map that assciates to each of its\n currency ID keys a finite map $tkns\\in\\Token \\mapsto \\Quantity$,\n which represents all the tokens (of that particular\n currency) that are contained in $v$.\n\n The map $tkns$ associates to each key $t\\in\\Token$ the quantity of tokens of\n this kind (i.e. with this identifier).\n\n \\item $\\TxOut$ : The type of outputs carried by a transaction. This type\n is different from the Shelley $\\TxOut$ type because it contains a $\\Value$\n instead of a $\\Coin$\n\n \\item $\\UTxOOut$ is the type of UTxO entry that gets created when a transaction\n output is processed. In this specification, it has the same structure as\n the transaction output $\\TxOut$, but we give it a different name, taking into\n account that $\\Value$ is stored differently in the outputs of $\\UTxO$ and $\\Tx$\n (due to optimization in the $\\UTxO$)\n\n \\item $\\UTxO$ entries are stored in the finite map $\\TxIn\\mapsto \\UTxOOut$\n (this type is also different than the Shelley $\\UTxO$ type)\n\n\\end{itemize}\n\n\n\\begin{figure*}[htb]\n %\n \\emph{Scripts}\n %\n \\begin{equation*}\n \\begin{array}{r@{~\\in~}l@{\\qquad=\\qquad}lr}\n\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{lng} & \\Language & \\N \\\\\n %\\text{script language}\n \\var{cid} & \\CurrencyId & \\ScriptHash\\\\\n % \\text{currency ID}\\\\\n \\var{tok} & \\Token & \\mathbb{H}\\\\\n % \\text{token identifier}\\\\\n \\var{quan} & \\Quantity & \\Z \\\\\n %\\text{quantity of a token}\\\\\n \\var{val} & \\Value\n & \\ScriptHash \\mapsto (\\Token \\mapsto \\Quantity) \\\\\n% & \\text{a collection of tokens}\n \\var{txout}\n & \\TxOut\n & \\Addr \\times \\Value\n% & \\text{tx outputs}\n \\\\\n \\var{utxoout}\n & \\UTxOOut\n & \\Addr \\times \\Value \\\\\n% & \\text{utxo outputs}\n \\var{utxo}\n & \\UTxO\n & \\TxIn \\to \\UTxOOut\n% & \\text{unspent tx outputs}\n \\end{array}\n \\end{equation*}\n %\n \\emph{Language Tags}\n %\n \\begin{align*}\n & s_{mc} & ~\\in~ \\ScriptMPS \\\\\n & \\mathsf{nativeMCTag} & ~=~ \\fun{language}~s_{mc}\n \\end{align*}\n \\caption{Definitions used in the UTxO transition system}\n \\label{fig:defs:utxo-shelley-1}\n\\end{figure*}\n\n\\textbf{The Multicurrency Scripting Language.}\nRecall that the ID of a currency is the hash of its MPS.\nIn Figure~\\ref{fig:defs:tx-mc-script}, we give the types related to multicurrency\nscripts. The $\\Script$ type\nis made up of multisig scripts and multicurrency scripts.\nThe multicurrency script type, $\\ScriptMPS$, has several constructurs, each of which\nis used in a different way during script evaluation (see MPS script evaluation\ndiscussion below).\n\nThe abstract\nfunction $\\fun{language}$ returns the tag corresponding to\nthe type of the language of a given script.\n\n\\begin{figure*}[htb]\n \\emph{Script Types}\n %\n \\begin{equation*}\n \\begin{array}{r@{~\\in~}l@{~}lr}\n \\var{smc} & \\ScriptMPS & \\text{monetary policy script} \\\\\n \\var{scr} & \\Script &=~ \\ScriptMSig \\uniondistinct \\ScriptMPS\n \\end{array}\n \\end{equation*}\n %\n \\emph{Helper Functions}\n %\n \\begin{align*}\n \\fun{language} ~\\in~& \\Script \\to \\Language \\\\\n &\\text{returns the language tag, e.g. $\\mathsf{mcTag}$ for the MPS language} \\\\\n \\caption{Languages}\n \\end{align*}\n %\n \\emph{MPS Script definition}\n %\n \\begin{equation*}\n \\begin{array}{rll}\n \\ScriptMPS & \\subseteq & \\Script \\\\\n \\\\~\\\\\n \\var{s_{mc}}\\in\\ScriptMPS & = & \\type{JustMSig}~ \\ScriptMSig\\\\\n & \\uniondistinct &\n \\type{MaxMinTimedTotal}~(\\Token \\mapsto (\\Slot\\times\\Slot\\times\\Quantity\\times\\Quantity)) \\\\\n & \\uniondistinct&\n \\type{RequireAll}~\\powerset{\\ScriptMPS}\n \\end{array}\n \\end{equation*}\n \\caption{The Multicurrency Scripting Language}\n \\label{fig:defs:tx-mc-script}\n\\end{figure*}\n\n\\textbf{Multicurrency Script Evaluation.}\nA monetary policy is a collection of restrictions on the tokens of a\nspecific multicurrency. MP scripts are evaluated for the purpose of checking that\nthe given currency adheres to its monetary policy.\nHere we define a basic scripting language that\nallows for expressing some of the most common restrictions, e.g.\nthe maximum total number of different kinds of tokens of a given currency.\nThe type function $\\fun{evalMPSScript}$, which evaluates MPS scripts, is given in\nFigure~\\ref{fig:defs:tx-mc-eval}. As inputs, it takes\n\n\\begin{itemize}\n\\item the script getting evaluated\n\\item the currency ID of the currency being forged\n\\item the current slot number,\n\\item a set of key hashes (needed to use MSig scripts as MPS scripts)\n\\item the transaction body\n\\item the inputs of the transaction as a UTxO finite map (with addresses and values),\ni.e. the outputs it is spending\n\\end{itemize}\n\nThe constructors which make up the MPS script scheme are used to express the following\naspects of monetary policy :\n\n\\begin{itemize}\n\\item $\\type{JustMSig}$~ :~ evaluates an MSig script\n\n\\item $\\type{RequireAll}$~:~evaluates all MPS scripts in the given set\n\n\\item Others will be here once decided on\n\\end{itemize}\n\nThe Figures~\\ref{fig:defs:tx-mc-eval},~\\ref{fig:whitelist-example},\n~\\ref{fig:defs:tx-mc-eval-2}, and~\\ref{fig:defs:tx-mc-eval-3} give\npossible constructors of the MPS language.\n\n\\begin{note}\n sort out the constructors\n\\end{note}\n\n\\begin{figure*}[htb]\n \\begin{align*}\n & \\fun{evalMPSScript} \\in\\ScriptMPS\\to\\ScriptHash\\to\\Slot\\to\\powerset\\KeyHash \\\\\n &~~~~\\to\\TxBody\\to\\UTxO \\to\\Bool \\\\\n & \\text{UTxO is only for the outputs THIS tx is spending, not global UTxO, i.e.} \\\\\n & \\text{when called,}~\\var{spentouts}~=~(\\fun{txins}~\\var{txb}) ~\\restrictdom~\\var{utxo} \\\\~\\\\\n %\n & \\fun{evalMPSScript} ~(\\type{JustMSig}~s)~\\var{cid}~\\var{slot}~\\var{vhks}\n ~\\var{txb}~\\var{spentouts} \\\\\n &~~~~ =~ \\fun{evalMultiSigScript}~s~\\var{vhks} \\\\\n & \\text {checks the msig script}\\\\~\\\\\n %\n & \\fun{evalMPSScript}\n ~\\type{DoForge}~\\var{cid}~ \\var{slot}~\\var{vhks} ~\\var{txb}~\\var{spentouts} \\\\\n &~~~~ =~ \\var{cid} \\notin \\dom~(\\fun{forge}~\\var{txb}) \\\\\n & \\text {checks that script hash of this script is not a currency ID being forged by tx} \\\\~\\\\\n %\n & \\fun{evalMPSScript}\n ~\\type{SignedByCIDToken}~\\var{cid}~ \\var{slot}~\\var{vhks} ~\\var{txb}~\\var{spentouts} \\\\\n &~~~~ =~ \\exists~t\\mapsto ~\\_~\\in~ \\fun{range}~(\\var{cid}~ \\restrictdom~(\\fun{balance}~\\var{spentouts})) ~:~ t~\\in~\\var{vhks} \\\\\n & \\text{checks that tx is signed by a key whose hash is the name of a token in this currency}\n \\\\~\\\\\n & \\fun{evalMPSScript}\n ~(\\type{SpendsCur}~\\var{cid'})~\\var{cid}~ \\var{slot}~\\var{vhks} ~\\var{txb}~\\var{spentouts} \\\\\n &~~~~ =~ (\\var{cid'}~\\neq~\\Nothing ~\\wedge ~\\var{cid'}~\\in~ \\dom~(\\fun{balance}~\\var{spentouts}))\\\\\n &~~~~~~ \\vee (\\var{cid'}~=~\\Nothing ~\\wedge ~\\var{cid}~\\in~ \\dom~(\\fun{balance}~\\var{spentouts})) \\\\\n & \\text{checks that this transaction spends currency cid' OR itself if}~\\var{cid'}~=~\\Nothing\n \\\\~\\\\\n &\\fun{evalMPSScript}~(\\type{Not}~s)~\\var{cid}~\\var{slot}~\\var{vhks}\n ~\\var{txb}~\\var{spentouts}\n \\\\\n &~~~~ = \\neg ~\\fun{evalMPSScript}~s~\\var{cid}~\\var{slot}~\\var{vhks}\n ~\\var{txb}~\\var{spentouts}\\\\~\\\\\n %\n &\\fun{evalMPSScript}~(\\type{RequireAll}~ls)~\\var{cid}~\\var{slot}~\\var{vhks}\n ~\\var{txb}~\\var{spentouts}\n \\\\\n &~~~~ = \\forall ~s'~ \\in~ ls~:~\\fun{evalMPSScript}~s'~\\var{cid}~\\var{slot}~\\var{vhks}\n ~\\var{txb}~\\var{spentouts}\\\\~\\\\\n %\n &\\fun{evalMPSScript}~(\\type{RequireOr}~ls)~\\var{cid}~\\var{slot}~\\var{vhks}\n ~\\var{txb}~\\var{spentouts}\n \\\\\n &~~~~ = \\exists ~s'~ \\in~ ls~:~\\fun{evalMPSScript}~s'~\\var{cid}~\\var{slot}~\\var{vhks}\n ~\\var{txb}~\\var{spentouts}\\\\\n \\end{align*}\n \\caption{Multicurrency Script Evaluation}\n \\label{fig:defs:tx-mc-eval}\n\\end{figure*}\n\n\n\n\\begin{figure*}[htb]\n \\begin{align*}\n & \\fun{evalMPSScript}\n ~(\\type{CurrencyToAddress}~\\var{cid'}~\\var{addr})~\\var{cid}~ \\var{slot}~\\var{vhks} ~\\var{txb}~\\var{spentouts} \\\\\n &~~~~ =~ (\\var{cid'}~\\neq~\\Nothing ~\\wedge ~\\var{addr}~\\neq~\\Nothing ~\\wedge \\\\\n &~~~~~~ \\forall~(a, v)~\\in~\\fun{range}~(\\fun{outs}~txb),~\\\\\n &~~~~~~ \\var{cid'}~\\in~\\dom~v~\\Rightarrow~(a~=~\\var{addr} ~\\wedge~ \\\\\n &~~~~~~ v~=~\\var{cid'}~ \\restrictdom~(\\fun{balance}~(\\fun{outs}~txb))) \\\\\n &~~~~~~ \\vee \\\\\n &~~~~~~ (\\var{cid'}~=~\\Nothing ~\\wedge~ \\var{addr}~\\neq~\\Nothing ~\\wedge \\\\\n &~~~~~~ \\forall~(a, v)~\\in~\\fun{range}~(\\fun{outs}~txb),~\\\\\n &~~~~~~ \\var{cid}~\\in~\\dom~v~\\Rightarrow~(a~=~\\var{addr} ~\\wedge~\\\\\n &~~~~~~ v~=~\\var{cid}~ \\restrictdom~(\\fun{balance}~(\\fun{outs}~txb))) \\\\\n &~~~~~~ \\vee \\\\\n &~~~~~~ (\\var{cid'}~\\neq~\\Nothing ~\\wedge~ \\var{addr}~=~\\Nothing ~\\wedge \\\\\n &~~~~~~ \\forall~(a, v)~\\in~\\fun{range}~(\\fun{outs}~txb),~\\\\\n &~~~~~~ \\var{cid'}~\\in~\\dom~v~\\Rightarrow~(a~=~\\var{(cid',cid')} ~\\wedge~\\\\\n &~~~~~~ v~=~\\var{cid'}~ \\restrictdom~(\\fun{balance}~(\\fun{outs}~txb))) \\\\\n &~~~~~~ \\vee \\\\\n &~~~~~~ (\\var{cid'}~=~\\Nothing ~\\wedge~ \\var{addr}~=~\\Nothing ~\\wedge \\\\\n &~~~~~~ \\forall~(a, v)~\\in~\\fun{range}~(\\fun{outs}~txb),~\\\\\n &~~~~~~ \\var{cid}~\\in~\\dom~v~\\Rightarrow~(a~=~\\var{(cid,cid)} ~\\wedge~\\\\\n &~~~~~~ v~=~\\var{cid}~ \\restrictdom~(\\fun{balance}~(\\fun{outs}~txb))) \\\\\n & \\text{checks that tx outputs any cid tokens by themselves to the specified address} \\\\\n & \\text {the script address of the given currency when addr unspecified}\n \\end{align*}\n \\caption{Multicurrency Script Evaluation, cont.}\n \\label{fig:defs:tx-mc-eval-2}\n\\end{figure*}\n\n\\begin{figure*}[htb]\n \\begin{align*}\n & \\fun{evalMPSScript}\n ~(\\type{TrancheTokens}~\\var{tts}~\\var{txin})~\\var{cid}~\\var{slot}~\\var{vhks}\n ~\\var{txb}~\\var{spentouts} \\\\\n &~~~~ =~(\\var{cid}\\mapsto\\var{tts}~\\in~\\var{val})~ \\wedge~(\\var{txin}~\\in~\\fun{txins}~{txb}) \\\\\n & \\text{tranche tokens is incomplete} \\\\~\\\\\n %\n & \\fun{evalMPSScript}\n ~(\\type{FreshTokens})~\\var{cid}~\\var{slot}~\\var{vhks}\n ~\\var{txb}~\\var{spentouts}\n \\\\\n &~~~~ =~\\forall~\\var{cid}~ \\mapsto ~tkns ~\\in~ \\var{val}~:~ \\\\\n &~~~~ \\forall~t~\\in~\\var{tkns},~\n \\fun{nameToken}~(\\fun{indexof}~\\var{t}~\\var{tkns},~\\fun{txins}~{txb})~=~t\n \\end{align*}\n \\caption{Multicurrency Script Evaluation, cont.}\n \\label{fig:defs:tx-mc-eval-3}\n\\end{figure*}\n\n\\begin{figure*}[htb]\n \\begin{align*}\n & \\fun{whitelist} \\in\\ScriptMSig\\to\\Script \\\\~\\\\\n %\n & \\type{whitelist} ~\\var{msig}~ =~ \\type{RequireOr}~\n (\\type{RequireAll}~(\\type{DoForge};~\\type{JustMSig}~\\var{msig});~\\\\\n &~~~~~~ \\type{RequireAll}~(\\type{CurrencyToAddress}~\\Nothing~\\Nothing ;\\\\\n &~~~~~~ (\\type{Not}~\\type{DoForge});~\\type{SignedByCIDToken})) \\\\\n %\n & \\text{msig is some MSig script containing signatures of some accreditation authority} \\\\\n & \\text{i.e. this authority can do any forging or spending of this token} \\\\~\\\\\n %\n & (\\fun{hashScript}~(\\type{SpendsCur}~(\\fun{hashScript}~(\\type{whitelist}~\\var{msig}))),~ \\var{tkns}) \\\\\n & \\text{an example of an output spending which requires to be on a whitelist made by msig authority}\n \\end{align*}\n \\caption{Whitelist Script Example}\n \\label{fig:whitelist-example}\n\\end{figure*}\n\n\n\n\\textbf{MPS Script Validation.}\n\nIn the Shelley spec, there is a script validation function which\nis used to evaluate all types of native (ledger-rule-defined) scripts.\nIn Figure~\\ref{fig:defs:tx-mc-valid}, we modify this function to also call the\nevaluation function specific to the MPS script type being added in this spec.\n\nThe arguments passed to the $\\fun{validateScript}$ function include all those\nneeded for MPS and MSig script evaluation. Because of the extra arguments\n(the slot number and the UTxO), we also modify the call to this function, made\nby the UTXOW rule.\n\n\\begin{figure*}[htb]\n \\begin{align*}\n \\fun{validateScript} & \\in\\Script\\to\\ScriptHash\\to\\Slot\\to\n \\powerset{\\KeyHash}\\to\\TxBody\\to\\UTxO\\to\\Bool \\\\\n \\fun{validateScript} & ~s~\\var{cid}~\\var{slot}~\\var{vhks}\n ~\\var{txb}~\\var{spentouts} =\n \\begin{cases}\n \\fun{evalMultiSigScript}~s~vhks & \\text{if}~s \\in\\MSig \\\\\n \\fun{evalMPSScript}~s~\\var{cid}~\\var{slot}~\\var{vhks} \\\\\n ~~~~txb~\\var{utxo} & \\text{if}~s \\in\\ScriptMPS \\\\\n \\mathsf{False} & \\text{otherwise}\n \\end{cases} \\\\\n \\end{align*}\n \\caption{Script Validation}\n \\label{fig:defs:tx-mc-valid}\n\\end{figure*}\n\n\\begin{note}\n give right arguments to validateScript in UTXOW rule\n\n check about validation interval - ok with just ttl?\n\n Fresh tokens - can’t unforge, quantity 1\n\\end{note}\n\n\\textbf{The Forge Field.}\n\nThe body of a transaction with multicurrency support contains one additional\nfield, the $\\fun{forge}$ field (see Figure~\\ref{fig:defs:utxo-shelley-2}).\nThe $\\fun{forge}$ field is a term of type $\\Value$, which contains\ntokens the transaction is putting into circulation or taking out of\ncirculation. Here, by \"circulation\", we mean specifically \"the UTxO on the\nledger\". Since the administrative fields cannot contain tokens other than Ada,\nand Ada cannot be forged, they are not affected in any way by forging.\n\nPutting tokens into circulation is done with positive values in the $\\Quantity$\nfields of the tokens forged, and taking tokens out of circulation can be done\nwith negative quantities.\n\nA transaction cannot simply forge arbitrary tokens. Recall that restrictions on\nMC tokens are imposed, for each currency with ID $cid$, by the script\nwith the hash $cid$. Whether a given currency adheres to the restrictions\nprescribed by its script is verified at forging time (i.e. when the transaction\nforging it is being processed). Another restriction on forging is imposed by\nthe preservation of value conditition. Also, no forging Ada\nis permitted. In Section~\\ref{sec:utxo}, we specify the mechanism by which\nforging is done, and rules which enforce these restrictions.\n\n\\textbf{Transaction Body.}\n\nBesides the addition of the $\\fun{forge}$ field to the transaction body,\nnote that the $\\TxOut$ type in the body is not the same as\nthe $\\TxOut$ in the system without multicurrency support. Instead of\n$\\Coin$, the transaction outputs now have type $\\Value$.\n\nThe only change to the types related to transaction witnessing is the addition\nof MPS scripts to the $\\Script$ type, so we do not include the whole $\\Tx$ type here.\n\n\\begin{figure*}[htb]\n \\emph{Transaction Type}\n %\n \\begin{equation*}\n \\begin{array}{r@{~~}l@{~~}l@{\\qquad}l}\n \\var{txbody} ~\\in~ \\TxBody ~=~\n & \\powerset{\\TxIn} & \\fun{txinputs}& \\text{inputs}\\\\\n &\\times ~(\\Ix \\mapsto \\TxOut) & \\fun{txouts}& \\text{outputs}\\\\\n & \\times~ \\seqof{\\DCert} & \\fun{txcerts}& \\text{certificates}\\\\\n & \\times ~\\Value & \\fun{forge} &\\text{value forged}\\\\\n & \\times ~\\Coin & \\fun{txfee} &\\text{non-script fee}\\\\\n & \\times ~\\Slot & \\fun{txttl} & \\text{time to live}\\\\\n & \\times~ \\Wdrl & \\fun{txwdrls} &\\text{reward withdrawals}\\\\\n & \\times ~\\Update & \\fun{txUpdates} & \\text{update proposals}\\\\\n & \\times ~\\MetaDataHash^? & \\fun{txMDhash} & \\text{metadata hash}\\\\\n \\end{array}\n \\end{equation*}\n %\n \\emph{Accessor Functions}\n \\begin{equation*}\n \\begin{array}{r@{~\\in~}lr}\n \\fun{getValue} & \\TxOut \\uniondistinct \\UTxOOut \\to \\Value & \\text{output value} \\\\\n \\fun{getAddr} & \\TxOut \\uniondistinct \\UTxOOut \\to \\Addr & \\text{output address} \\\\\n \\end{array}\n \\end{equation*}\n \\caption{Definitions used in the UTxO transition system, cont.}\n \\label{fig:defs:utxo-shelley-2}\n\\end{figure*}\n\n\\textbf{Coin and Multicurrency Tokens}\nWhen multicurrency is introduced, Ada is still expected to be\nthe most common type of token on the ledger.\nThe $\\Coin$ type is used to represent an amount of Ada.\nIt is the only\ntype of token which can be used for all non-UTxO ledger accounting, including deposits,\nfees, rewards, treasury, and the proof of stake protocol. Under no circumstances\nare these administrative fields and calculations ever expected to operate on\nany types of tokens besides Ada. These fiels will continue to have the type $\\Coin$.\n\nThe exact representation of tokens in the UTxO and inside transactions\nis an implementation detail, which we omit here.\nNote that it necessarily is equivalent to $\\Value$, optimized\nfor Ada-only cases, has a unique representation for Ada tokens,\nand does not allow Ada to have tokens denoted by anything other than $\\mathsf{adaToken}$.\n\nIn Figure \\ref{fig:defs:functions-helper} we give the following helper functions\nand constants, needed for using Ada in a multicurrency setting.\n\n\\begin{itemize}\n \\item $\\mathsf{adaID}$ is a random script hash value with no known associated\n script. It is the currency ID of Ada. While extremely unlikely, guessing a\n script that hashes to this value\n and validates will allow a user to forge unlimited amounts of Ada\n \\item $\\mathsf{adaToken}$ is a byte string representation of the word \"Ada\".\n The ledger should never allow the use of any other token name associated\n with Ada's currency ID\n \\item $\\fun{qu}$ and $\\fun{co}$ are type conversions from quantity to\n coin. Both of these types are synonyms for $\\Z$, so they are\n type re-naming conversions that are mutual inverses, with\n\n $\\fun{qu} ~(\\fun{co} ~q )~= ~q$, and\n\n $\\fun{co}~ (\\fun{qu}~ c) ~=~ c$, for $c \\in \\Coin,~q \\in \\Quantity$.\n\n \\item $\\fun{coinToValue}$ takes a coin value and generates a $\\Value$ type representation\n of it\n\\end{itemize}\n\nAn amount of Ada can also be represented as a multicurrency value\nusing the notation in Figure \\ref{fig:defs:functions-helper}, as\n$\\fun{coinToValue}~c$ where $c \\in \\Coin$. We must use this representation\nwhen adding or subtracting Ada and other tokens as $\\Value$, e.g. in the\npreservation of value calculations.\n\n\\begin{figure*}[htb]\n \\emph{Abstract Functions and Values}\n %\n \\begin{align*}\n \\mathsf{adaID} \\in& ~\\ScriptHash\n & \\text{Ada currency ID} \\\\\n \\mathsf{adaToken} \\in& ~\\Token\n & \\text{Ada Token} \\\\\n \\mathsf{co} \\in& ~\\Quantity \\to \\Coin\n & \\text{type conversion} \\\\\n \\mathsf{qu} \\in& ~\\Coin \\to \\Quantity\n & \\text{type conversion} \\\\\n \\end{align*}\n \\emph{Helper Functions}\n %\n \\begin{align*}\n \\fun{coinToValue} \\in & ~\\Coin\\to \\Value \\\\\n \\fun{coinToValue}~ c = & \\{\\mathsf{adaID} \\mapsto \\{\\mathsf{adaToken} \\mapsto \\fun{qu}~c\\}\\} \\\\\n &\\text{convert a Coin amount to a Value} \\\\\n \\end{align*}\n \\caption{Multicurrency}\n \\label{fig:defs:functions-helper}\n\\end{figure*}\n\n\\clearpage\n", "meta": {"hexsha": "e186a1eef287d614c138992fca3d951c8effe26d", "size": 21319, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "shelley-mc/formal-spec/transactions.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/transactions.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/transactions.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": 41.884086444, "max_line_length": 132, "alphanum_fraction": 0.6638679113, "num_tokens": 6889, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.37022539954425293, "lm_q1q2_score": 0.19522597055448662}}
{"text": "\\chapter{State of the Art of Trustless Timestamping}\n\\label{chpr:state-of-art}\nWe analysed the reasons why Bitcoin chain is a valid tool to produce timestamps of arbitrary data and we showed two procedures to create such proofs.\nHowever each one may follow his own set of rules to create and formalize proofs. \nOne can use a different set of commitment operations and time attestations or the same set but formalized in a different way, or even a mixture ot the preceding cases. \nAlthough various set of rules may be valid and completely reasonable, such situation would be a nightmare for users, both creators and verifiers; during the creation procedure one may ask himself if challenger will retain his proof correctly formalized, verifiers should equip themselves with several tools increasing the cost of verifying proofs.\nIn addition this setting has huge security issues: an higher number of accepted formalizations increases the surface of attack through which proofs may be corrupted. \n\nMoreover Bitcoin chain is not the only place where to bind attestation in a trustless manner. \nThere are other similar technologies that can be used as a notary with analogous techniques, for instance Litecoin, Ethereum or MimbleWimble.\nAlthough timestamping with other chains is possible, it is fundamental to realize that it changes the security of the time attestations.\nEach chain has its own rules and its own community behind, in some settings some assumptions may be weaker or false, while in others they may be an improvement.\nFor each specific case one should realize which is the best notary to use in order to properly address the problem.\n\nFor these reasons is important to have a common an shared standard to agree on the format used to create timestamps. \nSuch standard should be open source to let everyone analyse its security and contribute to it with improvement proposals.\n\nIn 2012 Peter Todd started working on \\textit{OpenTimestamps} \\cite{OTSWeb, OpenTimestampsGithub, OTSannouncment}, a project that provides a solution to the above issues.\n\n\\begin{quotation}\n\tOpenTimestamps aims to be a standard format for blockchain timestamping. The format is flexible enough to be vendor and blockchain independent.\n\\end{quotation}\n\nIn the following years other developers contributed to the source code improving the standard with more libraries, features and implementations. \n\n\\section{OpenTimestamps as a Standard}\nOpenTimestamps defines a standard for creating a proof that can be verified in an easy way and that is not prone to inconsistent behaviours. The definition comes from the implementation, precisely from the python library which is currently taken as a reference by the other libraries.\nProofs consist in a sequence of commitment operations heading to at least one time attestation. \n\nCommitment operations take one (unary) or two (binary) inputs to produce a single output. Note that a binary operation can be turned in a unary operation by fixing one of the inputs. The available operations are:\n\\begin{itemize}\n\t\\item\n\t\\verb|OpAppend| binary\n\t\\item \\verb|OpPrepend| binary\n\t\\item \\verb|OpReverse| unary, may get removed\\footnote{https://github.com/opentimestamps/python-opentimestamps/issues/5}\n\t\\item \\verb|OpHexlify| unary\n\t\\item \\verb|OpSHA256| unary, cryptographic\n\t\\item \\verb|OpRIPEMD160| unary, cryptographic\n\t\\item \\verb|OpSHA1| unary, cryptographic\n\t\\item \\verb|OpKECCAK256| unary, cryptographic\n\\end{itemize}\n\nTime attestations are time-attesting signature, they link a commitment to an event which has a time associated to. As of writing, the available ones are:\n\\begin{itemize}\n\t\\item \\verb|UnknownAttestation| Placeholder for attestations that aren't support\n\t\\item \\verb|PendingAttestation| Commitment has been recorded in a remote server for future attestation\n\t\\item \\verb|BitcoinBlockHeaderAttestation| Signed by the Bitcoin blockchain: the commitment digest will be the merkleroot of the blockheader\n\t\\item \\verb|EthereumBlockHeaderAttestation| Signed by the Ethereum blockchain: the commitment digest will be the merkleroot of the blockheader\\footnote{Ethereum attestations were developed for a PoC proving the flexibility of the protocol, however they are in the \\textit{dubious} module of the OpenTimestamps repository, the reason given is:\n\t\t\\begin{quotation}\n\t\t\t... Ethereum has changed repeatedly in the past due to consensus failures and forks; as of writing the Ethereum developers plan to radically change Ethereum's consensus model to proof-of-stake, whose security model is at best dubious.\n\t\\end{quotation}}\n\t\\item \n\t\\verb|LitecoinBlockHeaderAttestation| Signed by the Litecoin blockchain: the commitment digest will be the merkleroot of the blockheader\n\\end{itemize}\nIn the case of a single attestation, a proof is an ordered list of unary operations ending with a time attestation. \nHowever timestamps may have more than one attestation, in fact they are not limited to be linear lists of operations, instead they can be structured as a \\textit{tree} with $d$ as the root, commitment operations as edges and attestations as leaves.\nThis enables the possibility to attach different attestations to a proof, with possibly completely different meanings.\nA proof is conveniently serialized in a receipt, which is conventionally stored in a file whose name ends with \\verb|.ots|;\nlet's examine an example of a receipt for a file \\verb|test.txt| containing \\verb|b'Hello World!\\n'|. \nIts receipts \\verb|test.txt.ots| is:\n\\begin{Verbatim}[frame=single]\nFile sha256: 03ba204e50d126e4674c005e04d82e84c21366780af1f43bd\n 54a37816b6ab340\nTimestamp:\nripemd160\nprepend 0100000001e482f9d32ecc3ba657b69d898010857b54457a904979\n 82ff56f97c4ec58e6f98010000006b483045022100b253add1d1cf\n 90844338a475a04ff13fc9e7bd242b07762dea07f5608b2de36702\n 2000b268ca9c3342b3769cdd062891317cdcef87aac310b6855e9d\n 93898ebbe8ec0121020d8e4d107d2b339b0050efdd4b4a09245aa0\n 56048f125396374ea6a2ab0709c6ffffffff026533e60500000000\n 1976a9140bf057d40fbba6744862515f5b55a2310de5772f88aca0\n 860100000000001976a914\nappend 88ac00000000\n# Bitcoin transaction id\n7e9f0f7d9daa2d9e51b2e22f4abe814c3f90539afa778a9bef88dc64627cb2\nec\nsha256\nsha256\nprepend a987f716c533913c314c78e35d35884cac943fa42cac49d2b2c69f\n 4003f85f88\nsha256\nsha256\nprepend dec55b3487e1e3f722a49b55a7783215862785f4a3acb392846019\n f71dc64a9d\nsha256\nsha256\nprepend b2ca18f485e080478e025dab3d464b416c0e1ecb6629c9aefce8c8\n 214d042432\nsha256\nsha256\nappend 11b0e90661196ff4b0813c3eda141bab5e91604837bdf7a0c9df37d\n b0e3a1198\nsha256\nsha256\nappend c34bc1a4a1093ffd148c016b1e664742914e939efabe4d3d3565159\n 14b26d9e2\nsha256\nsha256\nappend c3e6e7c38c69f6af24c2be34ebac48257ede61ec0a21b9535e44432\n 77be30646\nsha256\nsha256\nprepend 0798bf8606e00024e5d5d54bf0c960f629dfb9dad69157455b6f26\n 52c0e8de81\nsha256\nsha256\nappend 3f9ada6d60baa244006bb0aad51448ad2fafb9d4b6487a0999cff26\n b91f0f536\nsha256\nsha256\nprepend c703019e959a8dd3faef7489bb328ba485574758e7091f01464eb6\n 5872c975c8\nsha256\nsha256\nappend cbfefff513ff84b915e3fed6f9d799676630f8364ea2a6c7557fad9\n 4a5b5d788\nsha256\nsha256\nprepend 0be23709859913babd4460bbddf8ed213e7c8773a4b1face30f8ac\n fdf093b705\nsha256\nsha256\nverify BitcoinBlockHeaderAttestation(358391)\n# Bitcoin block merkle root\n8a1b66ecb7cbd07d8139a7e7d7f2c41aab1f5009b8364aaf61d03ad245e47e\n00\n\\end{Verbatim}\nThe recepit is attesting that the file whose hash is \\verb|03ba204e...| is committed into the block header number 358391, which has the \\verb|nTime| field set to \\verb|\"May 28, 2015, 17:41:18 +0200\"|. This means that the file existed prior to that time, still this is not completely safe: we are assuming that the miner has not lied \\cite{TimeInaccuracy}. However he cannot put an extremely different date and he does not have a great incentive to put a false timestamp, nevertheless, we stay conservative and say that the data contained in the file existed prior to May 28, 2015.\n\nThis timestamp was created with an address commitment, to clarify how it is committed in the chain in Table \\ref{tab:ots-ex} it is shown the receipt execution.\nAt the end, the value remaining on the stack is tested against the transaction Merkle root of block 358391. \nIf they are equal the proof is correct.\n\n\\begin{table}\n\\begin{center}\n\\begin{tabular}{|p{3cm}|p{4cm}|}\n\t\\hline\n\t\\textbf{Operation} & \\textbf{Object on the stack} \\\\ \\hline\n & file \\\\ \n\t\\verb|sha256| & hash of the file \\\\ \n\t\\verb|ripemd160| & address commitment \\\\ \n\t\\verb|prepend 0100...| & \\\\ \n\t\\verb|append 88ac...| & raw transaction \\\\ \n\t\\verb|sha256| & \\\\ \n\t\\verb|sha256| & TXID in little endian \\\\ \n\t\\verb|...| & \\\\ \n\t\\verb|sha256| & \\\\ \n\t\\verb|sha256| & transactions merkle root \\\\ \\hline\n\\end{tabular}\n\\end{center}\n\\caption[OpenTimestamp receipt execution.]{OpenTimestamp receipt execution.}\n\\label{tab:ots-ex}\n\\end{table}\nThe raw transaction of the example is:\n\\begin{Verbatim}[commandchars=+\\[\\], frame=single]\n0100000001e482f9d32ecc3ba657b69d898010857b54457a90497982ff56f9\n7c4ec58e6f98010000006b483045022100b253add1d1cf90844338a475a04f\nf13fc9e7bd242b07762dea07f5608b2de367022000b268ca9c3342b3769cdd\n062891317cdcef87aac310b6855e9d93898ebbe8ec0121020d8e4d107d2b33\n9b0050efdd4b4a09245aa056048f125396374ea6a2ab0709c6ffffffff0265\n33e605000000001976a9140bf057d40fbba6744862515f5b55a2310de5772f\n88aca0860100000000001976a914+underline[1df8859e60bc679503d16dcb870e6ce91a]\n+underline[57e9df]88ac00000000\n\\end{Verbatim}\nIt can be decoded with the Bitcoin Core client with:\n\\begin{verbatim}\n$ bitcoin-cli decoderawtransction \n\\end{verbatim}\nDecoding the transaction one can see the commitment address\\footnote{It is possible to verify that it is still unspent.}:\n\\begin{verbatim}\n13jUKAuPDfgVPVgsVbeKVNWBv6wAh31vkN\n\\end{verbatim}\nwhich is the base58 encoding of:\n\\begin{verbatim}\n1df8859e60bc679503d16dcb870e6ce91a57e9df\n\\end{verbatim}\nwhich can be spotted inside the transaction.\n\nMoving forward from the example it is possible to define procedures to include the timestamp in the Bitcoin chain, create and verify the corresponding proof as outlined in Algorithm \\ref{alg:create-timestamp}.\n\\begin{algorithm}\n\\caption{Create timestamp on the Bitcoin chain}\n\\label{alg:create-timestamp}\n\\begin{algorithmic}[1]\n\\Procedure{IncludeTimestamp}{$d$}\n\\Comment{$d$ data to timestamp}\n\\State choose sequence of commitment operations $S_d^C=[C_i]_{i=1}^n$\n\\State apply $S_d^C$ to $d$, obtain $C$\n\\Comment{$d$ to $C$}\n\\State include $C$ in a transaction $TX$\n\\State broadcast the transaction to the network\n\\State wait until the transaction is confirmed\n\\State \\textbf{return} $d$, $S_d^C$, $C$, $TX$\n\\EndProcedure\n\\Statex \n\\Procedure{CreateTimestamp}{$d$, $S_d^C$, $C$, $TX$}\n\\State decompose the transaction, $TX = TX_p||C||TX_a$\n\\State $S_C^{TXID} = [\\verb|prepend | TX_p,\\verb| append | TX_a,\\verb| sha256|,\\verb| sha256|]$\n\\Statex\n\\Comment{$C$ to TXID}\n\\State find the block $B$ including $TX$\n\\State store $B$ transactions Merkle root $MR$ and height $H$\n\\State retrieve the Merkle path $S_{TXID}^{MR} \\gets [C^{TXID}_i]_{i=1}^{n_{TXID}}$\n\\Comment{TXID to $MR$}\n\\State $proof \\gets S_d^C + S_C^{TXID} + S_{TXID}^{MR}$ \n\\Comment{join the commitment operations}\n\\State attach at the end of $proof$ \\verb|BitcoinBlockHeaderAttestation(H)|\n\\State \\textbf{return} $proof$\n\\EndProcedure\n\\Statex\n\\Procedure{VerifyTimestamp}{$d$, $proof$, $MR$}\n\\Statex\n\\Comment{$MR$ is retrieved from a \\textit{trustworthy} source}\n\\State apply $proof$ to $d$, obtain $MR_V$\n\\Comment{execute commitment operations}\n\\If{$MR = MR_V$}{\\textbf{ return }\\verb|TRUE|}\n\\Comment{verify attestation}\n\\Else{\\textbf{ return }\\verb|FALSE|}\n\\EndIf\n\\EndProcedure\n\\end{algorithmic}\n\\end{algorithm}\nThe procedures could be easily generalized to more general settings, for instance to timestamp on another chain with slightly different rules.\nIt is important to highlight that the creator of the proof should always verify its correctness right after the creation. If the verification is successful he can store the file containing the proof in several insecure places, since it does not reveal anything more than the hash of the timestamped data, and store the file containing the data in a secure (if he needs) location; when challenged to prove the existence of that data prior to a certain time he will provide data and the corresponding timestamp to who he needs to convince.\n\n\\section{OpenTimestamps as a Scalability Solution}\nAs we have seen in the previous section, to create a timestamp is necessary to do a transaction. \nTo timestamp multiple files it is possible to commit those in a single hash value using a Merkle tree. As a result, the initial part of each proof will have different operations, going through different branches of the tree, while, from the transaction on, the operations will be identical.\n\nHowever, each time one has to timestamp, he has to do a bitcoin transaction, which is not sustainable if too many people have timestamp needs: it implies an effort for the network and higher fees for all the users.\n\nThe solution proposed by the OpenTimestamps developers includes a \\textit{centralized trust-minimized} system to aggregate timestamps, it involves an \\textit{aggregation server} and a \\textit{public calendar server} which actually timestamp.\nTheir operation is descibed in Algorithm \\ref{alg:calendar-working}.\n\n\\begin{algorithm}\n\t\\caption{Client - aggregator - calendar simplified working}\n\t\\label{alg:calendar-working}\n\t\\begin{algorithmic}[1]\n\t\t\\State clients send data to timestamp to the aggregator\\Comment{timestamp requests}\n\t\t\\State aggregator \\Call{merklelize}{} requests received each second\\Comment{aggregation}\n\t\t\\State aggregator sends to calendar the Merkle tip to timestamp\n\t\t\\State calendar promise he will timestamp the tip\\Comment{pending attestation}\n\t\t\\State aggregator sends back to clients incomplete proof until the tip\n\t\t\\State calendar aggregates pending tips in a merkle tree\\Comment{aggregation}\n\t\t\\State calendar sends a transaction including a merkle tip\\Comment{timestamp}\n\t\t\\State the transaction gets confirmed\\footnotemark \\Comment{attestation complete}\n\t\t\\State clients ask to the calendar to upgrade the timestamp\\Comment{upgrade}\n\t\t\\State calendar sends back clients the complete proofs\n\t\t\\State clients verify their proofs\\Comment{verification}\n\t\\end{algorithmic}\t\n\\end{algorithm}\n\\footnotetext{As pointed out in Section \\ref{bitcoin}, a transaction is considered confirmed when it is 6 or more blocks deep.}\n\nClients do not send their data directly, instead they send salted hash values of the data, so the aggregator does not dig into their privacy.\nAt the first aggregation phase the aggregator append to each value received by clients a random nonce, so that a client sending malicious data instead of an hash do not pollute the proof of the leaf adjacent to his.\nThis system is trust-minimized beacause the clients trust that the calendar will create timestamp for them. Both calendar and aggregator can censor them, sending back incorrect proofs or malicious data. However once the calendar has sent them a correct proof they are fine, the proof will be valid forever regardless of any future bad behaviour of the aggregator or calendar.\n\nThe OpenTimestamp standard supports multiple branch for the commitment operations to include multiple attestations inside a single proof. With this feature one request can be forwarded to multiple public calendars, giving the redundancy that mitigates the problem when a calendar server is down and lowering the trust put in each single calendar.\n\n\\begin{figure}\n\t\\begin{center}\n\t\t\\includegraphics[width=\\linewidth]{Images/bitcoin-chain-calendar.png}\n\t\t\\caption[Calendar timestamping]{Calendar timestamping. $TX_3$ is the transaction made by the calendar, it includes a commitment to $\\{data_i\\}_{i=1}^n$ obtained with a Merkle tree. Note that transaction must follow the consensus rules to be included in the chain, instead data are completely arbitrary.}\n\t\t\\label{fig:chain-calendar}\n\t\\end{center}\n\\end{figure}\n\nA calendar spends its own bitcoin to do a transaction, this implies that he won't be able to perform an extremely high number of transactions, leading to less frequent timestamps. As of writing, the calendars use the \\textit{replace by fee} (\\textit{RBF}) mechanism to spend a fix amount of bitcoin each day. In Algorithm \\ref{alg:calendar-rbf} is described a simplified scheme of its working.\nThis procedure makes the calendar expenditures fixed: each day has approximately 144 block, so the amount spent in fee per day is $144 \\cdot a$, where $a$ is a fixed value set by who run the calendar.\n\nThus if the mean fee to get into the next block is high, then the calendar may wait several blocks before timestamping and clients will have to wait for a long time to have their receipt upgraded and their data timestamped. This issue can be addressed if someone is timestamping in place of the calendar, which could be facilitated by the technique we are showing in Chapter \\ref{chpr:ec-commitments}. \n\nDespite all these considerations, the existence of public calendars is an extremely remarkable achievement for users: they enable clients to timestamp completely for free their own data. \nThe solution involves some trust\\footnote{Actually a client may implement a trustless system involving the calendar to timestamp his data. He would first ask the calendar to timestamp and then wait for the completed proofs; after a reasonable amount of time, if the calendar delivered what promised, then the client is fine, otherwise he timestamps by himself.}, but for a limited interval of time and with minimal possible downsides; once the proof is completed, it is not important if it was created through a central hub, it has the exact same respectability of any other proof. \nFurthermore the calendar learned nothing about the data timestamped since it received only an hash value. \nUltimately the efficient aggregation reduces the burden caused to the network, making timestamping sustainable even on large scale.\n\n\\begin{algorithm}\n\t\\caption{Calendar replace by fee}\n\t\\label{alg:calendar-rbf}\n\t\\begin{algorithmic}[1]\n\t\t\\Procedure{calendarRBF}{$a,LT$}\\Comment{step $a$, last timestamp $LT$}\n\t\t\\State $fee \\gets 0$\n\t\t\\Repeat \n\t\t\\State $fee \\gets fee + a$\n\t\t\\State $S \\gets \\{h_i\\}_{i=1}^n$ \\Comment{collect clients timestamp requests}\n\t\t\\State $MR \\gets$ \\Call{merklelize}{$S$}\n\t\t\\State $TX \\gets$ \\Call{maketx}{$fee, MR$} \\Comment{create transaction including $MR$}\n\t\t\\State broacast $TX$\n\t\t\\Until{$TX$ is mined}\n\t\t\\State \\textbf{return} $LT$ \\Comment{$LT$ to restart the procedure}\n\t\t\\EndProcedure\n\t\\end{algorithmic}\n\\end{algorithm}", "meta": {"hexsha": "e5a3949d777a3c53c1247fe0e31ed11d1c94f624", "size": 18704, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Chapters/Trustless_Timestamping_State_of_the_Art.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/Trustless_Timestamping_State_of_the_Art.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/Trustless_Timestamping_State_of_the_Art.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": 63.619047619, "max_line_length": 582, "alphanum_fraction": 0.8000962361, "num_tokens": 5106, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165233795672, "lm_q2_score": 0.37022539259558657, "lm_q1q2_score": 0.19522596689034008}}
{"text": "\\documentclass[12pt]{article}\n\n\\oddsidemargin 0pt\n\\evensidemargin 0pt\n\\textwidth 16.2cm\n\n\\newcommand{\\vect}[1]{{\\bf #1}}\n\\newcommand{\\tens}[1]{{\\bf #1}}\n\\newcommand{\\gvect}[1]{\\mathbf{#1}}\n\\newcommand{\\gtens}[1]{\\mathbf{#1}}\n\\newcommand{\\ti}[2]{\\tens{#1}^{#2}}\n\\newcommand{\\gti}[2]{\\gtens{#1}^{#2}}\n\\newcommand{\\vr}{\\vect{r}}\n\\newcommand{\\vR}{\\vect{R}}\n\\newcommand{\\vE}{\\vect{E}}\n\\newcommand{\\vv}{\\vect{v}}\n\\newcommand{\\vF}{\\vect{F}}\n\\newcommand{\\vU}{\\vect{U}}\n\\newcommand{\\tzeta}{\\gtens{\\zeta}}\n\\newcommand{\\tmu}{\\gtens{\\mu}}\n\\newcommand{\\prog}[1]{{\\tt #1}}\n\\newcommand{\\name}[1]{{\\sc #1}}\n\\newcommand{\\btitle}[1]{{#1,}}\n\\newcommand{\\vol}[1]{{\\bf #1}}\n\n\\newcommand{\\wsp}{\\hspace*{0.5cm}}\n\n\\begin{document}\n\n\\title{HYDROLIB: installation and usage guide}\n\\author{K. Hinsen\\\\\n Institut f\\\"ur Theoretische Physik A\\\\\n RWTH Aachen}\n\\date{}\n\\maketitle\n\\tableofcontents\n\\newpage\n\n\\section{Overview}\n\nThe Hydrodynamic Interactions Library (\\prog{HYDROLIB}) consists of a\nset of Fortran subroutines that calculate hydrodynamic interactions in\nan arbitrary configuration of equal hard spheres with stick boundary\nconditions, optionally with arbitrary rigid links between the\nspheres. The quantities that can be calculated are:\n\\begin{itemize}\n\\item the friction matrix for a given particle configuration\n\\item the mobility matrix for a given particle configuration\n\\item the forces on all particles of a given configuration moving\nwith given velocities\n\\item particle velocities for a given particle configuration and a given set\nof forces\n\\end{itemize}\nThe main features of the library are:\n\\begin{itemize}\n\\item controllable and adjustable accuracy\n\\item efficient calculation\n\\item suitability for finite and periodic geometries\n\\end{itemize}\n\nThe program has been checked intensively for various configurations,\nranging from two spheres (for which it produces exact results) to more\nthan a hundred. In addition, many internal consistency checks have\nbeen done and the code has been checked with\n\\prog{ftnchek}.\\footnote{\\prog{ftnchek} checks Fortran programs for\nsemantic errors that compilers normally don't detect. It is available\nby \\prog{ftp} from \\prog{netlib.att.com}.} Nevertheless, I cannot\nguarantee for anything; if you use \\prog{HYDROLIB}, you do so at your\nown risk.\n\n\n\\section{Friction and mobility matrices}\n\n\\subsection{Physical background}\n\nWhen spheres immersed into a liquid move with prescribed linear\nvelocities $\\vect{U}$ and angular velocities $\\gvect{\\Omega}$, the\nforces $\\vect{F}$ and torques $\\vect{T}$ acting on them are described\nby the {\\em friction matrix} $\\tzeta$:\n\\[\n\\left(\\begin{array}{c} \\vect{F}\\\\ \\vect{T} \\end{array}\\right) = \n\\left(\\begin{array}{cc}\n\\tzeta^{tt} & \\tzeta^{tr} \\\\\n\\tzeta^{rt} & \\tzeta^{rr}\n\\end{array}\\right) \\left(\\begin{array}{c}\n\\vv_0-\\vU\\\\ \\frac{1}{2}\\nabla\\times\\vv_0-\\gvect{\\Omega}\n\\end{array}\\right)\n\\]\nThe velocity field $\\vv_0$ is the incident velocity field, to be\nevaluated at the particle centers.\n\nForce and torque vectors are described by three components for each\nparticle, therefore the friction matrix has the size $6N\\times 6N$,\nwhere $N$ is the number of particles. The friction matrix can be shown\nto be symmetric.\n\nWhen the forces and torques are given, the velocities can be obtained\nfrom the\n{\\em mobility matrix} $\\tmu$:\n\\[\n\\left(\\begin{array}{c}\n\\vv_0-\\vU\\\\ \\frac{1}{2}\\nabla\\times\\vv_0-\\gvect{\\Omega}\n\\end{array}\\right) = \n\\left(\\begin{array}{cc}\n\\tmu^{tt} & \\tmu^{tr} \\\\\n\\tmu^{rt} & \\tmu^{rr}\n\\end{array}\\right) \\left(\\begin{array}{c}\n\\vect{F}\\\\ \\vect{T}\n\\end{array}\\right)\n\\]\nThe mobility matrix is the inverse of the friction matrix.\n\nA more detailed description of hydrodynamic interactions and an explanation\nof the theory on which the calculations are based can be found in\n\\cite{cifehiwabl}. A description of this implementation has been\npublished in \\cite{hi}.\n\n\\subsection{Units}\n\nDimensionless quantities are used for all numerical calculations.\nThey are obtained as follows:\n\\begin{itemize}\n\\item[-] the radius $a$ of the spheres is set to 1.\n\\item[-] the viscosity $\\eta$ of the liquid is set to $1/4\\pi$.\n\\end{itemize}\nThis leaves one unit undetermined (e.g. velocity or force), which can\nbe chosen arbitrarily since it affects only the velocities and forces,\nbut not their ratios, i.e.\\ the friction and mobility matrices are\nindependent of this choice.\n\n\\subsection{Numerical calculation}\n\\label{sec:numcalc}\n\nThe numerical calculation of hydrodynamic interactions is based on a\nmultipole expansion to take into account long-range interactions, and\non results from lubrication theory to correctly include short-range\ninteractions. The accuracy of the results can be controlled with the\ninteger parameter $l_{\\rm max}$, which is related to the highest\nmultipole order included in the calculation. The parameter $l_{\\rm\nmax}$ must be in the range $0\\ldots 3$. Increasing this parameter\ngives better accuracy, but increases the amount of memory and CPU time\nneeded by the program. The parameter $l_{\\rm max}$ is related to\nthe multipole order $L$ used in \\cite{cifehiwabl} and \\cite{hi}\nby $l_{\\rm max} = L-1$.\n\nThe following table indicates how much memory is needed for a given\nvalue of $l_{\\rm max}$, expressed in terms of the number of unknowns\nper particle in the system of equations that must be solved, and a\nrough estimate of the accuracy of the friction matrix elements:\n\n\\begin{center}\n\\begin{tabular}{|l|r|l|}\n\\hline\n$l_{\\rm max}$ & Unknowns & Accuracy\\\\\n\\hline\n0 & 9 & 10--20\\% \\\\\n1 & 24 & 1--5\\% \\\\\n2 & 45 & $< 1\\%$ \\\\\n3 & 84 & $<< 1\\%$ \\\\\n\\hline\n\\end{tabular}\n\\end{center}\n\nIt is recommended to use $l_{\\rm max} > 1$ only, since otherwise not\nall long-range terms are taken into account (see \\cite{cifehiwabl} for\ndetails).\n\n\n\\section{Installation and usage}\n\n\\subsection{System requirements}\n\n\\prog{HYDROLIB} can be used with most standard Unix systems.\nIn addition to standard Unix tools, it needs a C preprocessor and a\nFortran compiler. Unfortunately, Fortran compilers vary a lot in their\nabilities and command line syntax; some configuration is therefore\nunavoidable.\n\nYou also need a linear algebra library. Currently only \\prog{LAPACK}\nis supported.\\footnote{The source code contains optional calls to\n\\prog{IMSL}, dating back to early versions of this library. However,\nthey have not been updated to the current versions of\n\\prog{HYDROLIB} and \\prog{IMSL}, since \\prog{IMSL} was not\navailable for testing. The calls have been left in to facilitate later\nwork on full \\prog{IMSL} support. In their current state, they are\ndefinitely incomplete and probably not functional.} \\prog{LAPACK}\nroutines are free and available from several sources, e.g.\\ by\n\\prog{ftp} from \\prog{netlib.att.com}\\footnote{Login as\n\\prog{anonymous} and use your e-mail address as password.} or by e-mail\nfrom \\prog{netlib@ornl.gov}\\footnote{Send a mail with the single word\n``help'' to that address to get detailed information.}. The \\prog{HYDROLIB}\narchive file contains all the necessary files from \\prog{LAPACK} and\n\\prog{BLAS} (a set of low-level routines used by \\prog{LAPACK}).\nHowever, you might wish to install a newer version or a version optimized\nfor your machine.\n\nLinear algebra functions are needed for the calculation of eigenvalues\n(which is done only during initialization and for small matrices, so\nefficiency is not important) and for solving systems of linear\nequations. For some types of calculation, a matrix inversion routine\nis also called. Users who have experience with linear algebra packages\nand with the C preprocessor should be able to add support for other\nlibraries. To do this, check all occurrences of\n\\prog{\\#ifdef LAPACK} in the source files. Add an appropriate\nsection for whatever library functions you want to use, and delimit it\nby \\prog{\\#ifdef} and \\prog{\\#endif} with a suitable label. Replace\nall \\prog{\\#define LAPACK} lines in the file \\prog{config.h} and in\nyour application programs with a definition of the new label you have\nchosen. Add an appropriate section in the script file \\prog{install\\_lib}\nby copying and modifying the one for \\prog{LAPACK}. Then reinstall the\nlibrary.\n\nPorting \\prog{HYDROLIB} to other operating systems is certainly\npossible, but some knowledge of Unix and the target system is\nrequired. However, porting the library is not necessary for running\nworking programs on other machines, since it is possible to create\n``clean'' Fortran-77 code on a Unix system that can then be used\nwherever a Fortran compiler is available.\n\n\n\\subsection{Installation}\n\n\\begin{enumerate}\n\n\\item\nEdit the file \\prog{local.def}. The supplied version already contains\nthe correct configurations for the most common Unix systems. If you are\nusing one of these systems, simply uncomment the respective lines. For\nother machines, you must find the correct values from the manual for\nthe Fortran compiler. The values of the variables have the following\nmeaning:\n\\begin{description}\n\\item[\\prog{FC}] The name of the command that invokes the Fortran compiler.\n\\item[\\prog{RANLIB}] The name of the command that creates a table of\ncontents for archives. If your system has a command called \\prog{ranlib} (check\nwith \\prog{which ranlib}), use it. Otherwise, try \\prog{touch} (which actually\ndoes nothing). If this leads to error messages during linking, check the\nman page for the \\prog{ar} command.\n\\item[\\prog{FCFLAGS1}] The options for compilation of a single file without\nlinking. These options are used to compile the invariable parts of the\nlibrary during installation.\n\\item[\\prog{FCFLAGS2}] The options for compilation and linking of one\nor several Fortran files. These options are used when compiling\na program that uses \\prog{HYDROLIB}.\n\\item[\\prog{cpp}] This variable should have the value \\prog{1} if\nthe Fortran compiler understands the option \\prog{-cpp}, which\ncauses it to run programs through the C preprocessor before compiling\nthem, and if your Fortran compiler accepts the non-standard statement\n``implicit none''. Otherwise it should have the value \\prog{0}.\n\\item[\\prog{dpoption}] If your Fortran compiler has an option to\nconvert single precision programs to double precision, this option\nshould become the value of this variable. Otherwise the value must\nbe \\prog{NONE}.\n\\end{description}\n\nAt the end of \\prog{local.def}, there is a line starting with\n\\prog{set lalib =}. You need to change this line only if you\nuse another linear algebra library than \\prog{LAPACK} or another\nversion of \\prog{LAPACK} than the one supplied with \\prog{HYDROLIB}.\nChange the contents of the following string to\nwhatever compiler options are necessary on your system to make the\ncompiler find the linear algebra libraries.\n\n\\item\nType\\\\\n\\wsp\\prog{install\\_lib}\\\\\nThis will initiate the installation procedure. Installation might take several\nminutes, and in the course of it a series of Fortran compiler calls will\nbe displayed.\n\n\\item\nTo check the installation, type\\\\\n\\wsp\\prog{fc example.f}\\\\\nThis will compile a short test program. After\ncompilation is finished, type\\\\\n\\wsp\\prog{a.out}\\\\\nto run the test program. The ouptut should be\\\\\n\\wsp\\prog{N = 6}\\\\\n\\wsp\\prog{3.288792419691321 4.296910545080898}\\\\\n\\wsp\\prog{9.912899454371797 94.71505251108327}\\\\\nThe accuracy of the printed results will be system dependent.\n\n\\end{enumerate}\n\n\\subsection{Preparing application programs}\n\nTo use the library in an application program, insert the following two lines\nbefore the first subroutine, function, or program statement:\\\\\n\\wsp\\prog{\\#include \"}{\\em program}\\prog{.h\"}\\\\\\\n\\wsp\\prog{\\#include }\\\\\n{\\em program} should be the name of the program file without the\nextension \\prog{.f}. The file {\\em program}\\prog{.h} should be a\ncopy of \\prog{config.h} in which the parameters have been modified\nappropriately (see section~\\ref{sec:config} for details).\nNote that the character \\prog{\\#} in the lines above may not be\npreceeded by white space.\n\nThe available library calls are explained in section~\\ref{sec:imp}.\n\n\\subsection{Compilation and Fortran source code generation}\n\nTwo commands are supplied to handle compilation and generation of\nportable Fortran source code. The command \\prog{fc} will compile an\napplication program using all necessary compiler options and link it\nwith the library. File arguments and additional compiler options\nshould be specified as for the standard \\prog{f77} command. The\nname of the configuration file can be specified using the option\n\\prog{-h}~{\\em config-file}\\/. If this option is missing, \\prog{fc}\nwill use the name of the first source code file given and\nreplace its extension \\prog{.f} by \\prog{.h}. If no file with\nthis name exists, \\prog{fc} will issue a warning and assume\nthe name \\prog{config.h}.\n\nThe command \\prog{fprog} will produce a complete Fortran source\nprogram that contains all necessary code (except for routines from the\nlinear algebra package) and can be ported to any machine with a\nFortran 77 compiler. It accepts the name of a single file with\nextension \\prog{.f} and produces a file with the same name and\nextension \\prog{.fsrc}. To run this program on another machine,\ntransfer the generated program file {\\em and} the files \\prog{z2cl*},\n\\prog{ocoeff} and \\prog{hcoeff} from the folder \\prog{hydrolib}\nto this machine. \n\n\\section{Configuration files}\n\\label{sec:config}\n\nThe Hydrodynamic Interactions Library requires some numerical parameters\nand some options that determine what is to be calculated. A special\nconfiguration file contains all this information. An example of such\na file is the file \\prog{config.h} supplied with the library. For each\napplication program, create a copy of this file and modify it according\nto your needs.\n\n\\subsection{Numerical parameters}\n\nThese are specified by lines of the type\\\\\n\\wsp\\prog{\\#define }{\\em parameter\\_name value}\n\n\\begin{description}\n\n\\item[]\n\\prog{\\_NP\\_}\\\\\nThis parameter must be set to the number of particles.\n\n\\item[]\n\\prog{\\_LM\\_}\\\\\nThis parameter must be set to the value of $l_{\\rm max}$, described in\nsection~\\ref{sec:numcalc}. It must be a number between 0 and 3.\n\n\\end{description}\n\n\n\\subsection{Compile-time options}\n\nCompile-time options are used to adapt the program code to the\nrequirements of the application and the programming environment. They\nall result in different sections of code being included in the final\nprogram. An option is activated by a line of the type\\\\\n\\wsp\\prog{\\#define }{\\em option\\_name}\\\\\nand switched off by\\\\\n\\wsp\\prog{\\#undef }{\\em option\\_name}\\\\\n(In principle lines starting with \\prog{\\#undef} could be completely\nremoved, but for ease of modification this is not recommended.)\n\nThe first set of compile-time options is related to the type of\nproblem being solved:\n\n\\begin{description}\n\n\\item[]\n\\prog{PERIODIC}\\\\\nIf defined, hydrodynamic interactions are calculated for a\nsystem with periodic boundary conditions. Only cubic elementary cells\nare supported. A common block named \\prog{pbc} contains a variable\n\\prog{box} of type \\prog{real} which must be set to the edge length of\nthe cubic cell. The coordinates that specify the particle\nconfiguration must be positive and less than the edge length. The\nparticle configuration must be consistent with periodic boundary\nconditions, i.e.\\ the particles may not overlap with each other or\nwith each other's periodic images. This is {\\em not} checked by the\nprogram.\\\\\nIf \\prog{PERIODIC} is not defined, a finite assembly of\nspheres in an infinite fluid is assumed. The particles may not overlap\nwith each other; again this is {\\em not} checked by the program. The\nparticle coordinates can otherwise be arbitrary.\n\n\\item[]\n\\prog{RIGID}\\\\\nIf defined, \\prog{HYDROLIB} is able to handle\nrigid connections between the particles. A ``rigid connection'' between\ntwo particles means that no relative motion, neither translational nor\nrotational, is possible between these particles. Other than that, the\n``connections'' have no influence on the calculations; they are assumed\nto have no masses and no influence on the fluid flow. From this definition it\nfollows that connectivity is transitive: if particle~1 is connected with\nparticle~2 and particle~3, there is also an implicit connection between\nparticles~2 and 3, since no relative motion between them is possible.\nThe specification of connections is explained in section~\\ref{sec:imp}.\\\\\nThe presence of connections means that the number of degrees of freedom\nof the system is reduced, since any cluster of interconnected particles\nhas only 6 degrees of freedom in total. Consequently, the friction and\nmobility matrices have fewer elements, namely 6 times the number of\nrigid clusters in the system. A particle cluster is described by the\ntranslational velocity of its ``center of mass'' (or rather what would\nbe its center of mass if all particles had identical mass; in fact masses\nnever enter in any calculation) and by an angular velocity about this\npoint\\footnote{In principle any point could be chosen as reference\npoint for describing clusters, but this choice makes the interpretation\nof results easier if the cluster happens to have some symmetry.}.\nTo make use of the results, the application program needs some information\nabout the rigid clusters, which are available in a common block named\n\\prog{rb}, which has the following form:\\\\\n\\wsp\\prog{real vrb(6*\\_NP\\_,6*\\_NP\\_)}\\\\\n\\wsp\\prog{integer nrb,irb(\\_NP\\_)}\\\\\n\\wsp\\prog{common /rb/ vrb,nrb,irb}\\\\\nThe variable \\prog{nrb} contains the number of rigid clusters. The\narray \\prog{irb} contains for each particle the number of the cluster\nit belongs to (i.e.\\ a number between 1 and \\prog{nrb}). All particles\nwith the same number form a cluster. The array \\prog{vrb} makes it\npossible to convert forces and velocities between the rigid-cluster\ndescription (\\prog{6*nrb} degrees of freedom) and the single-sphere\ndescription (6$N$ variables). Its first index runs from 1 to $6N$, its\nsecond index from 1 to \\prog{6*nrb}. Multiplying a \\prog{6*nrb}-dimensional\nvelocity vector from the right gives the individual particle velocities,\nwhereas multiplying by a 6$N$-dimensional force vector from the left gives\nthe total forces and torques acting on the rigid clusters.\\\\\n\n\\item[]\n\\prog{FIXED}\\\\\nIf defined, mobility calculations can be performed on systems\nin which some spheres are fixed while others can freely move.\nAn additional common block named \\prog{fix} is defined,\nwhich has the following form:\\\\\n\\wsp\\prog{integer nfixed}\\\\\n\\wsp\\prog{logical full}\\\\\n\\wsp\\prog{common /fix/ nfixed,full}\\\\\nThe variable \\prog{nfixed} contains the number of fixed particles.\nThe fixed particles are always the {\\em last} \\prog{nfixed}\nparticles in the configuration. If the variable \\prog{full} has\nthe value \\prog{.true.}, everything will be recalculated.\nIf it has the value \\prog{.false.}, the program will assume that\nthe fixed particles have not moved since the evaluation for the\nprevious configuration. The variable \\prog{full} must always be\nset to \\prog{.true.} initially.\n\n\\item[]\n\\prog{FIXED\\_FAST}\\\\\nIdentical to \\prog{FIXED}, except that the calculations are\nperformed faster at the expense of a higher memory requirement.\n\n\\item[]\n\\prog{LUBRICATION}\\\\\nIf defined, the program adds short-range corrections calculated from\nlubrication theory to the results of the multipole\nexpansion. This should always be done unless it is known that these\ncorrections are negligible.\\\\\nA potential problem is caused by the fact that the short-range\ncorrections diverge for touching spheres. This will cause loss of\nprecision for short distances and a program crash for actually\ntouching spheres. The latter can be avoided by enabling the option\n\\prog{RIGID} and defining a rigid connection between the touching\nparticles (this does not affect the results since with stick\nboundary conditions, there can never be any relative motion between\ntouching spheres). Specifying rigid connections also removes the\nloss of precision at small non-zero distances, but in that case the\nconnection will also lead to different results.\n\n\\item[]\n\\prog{FRICTION}\\\\\nIf defined, the program calculates the friction matrix. The friction\nmatrix is returned in a common block named \\prog{frict} of the form\\\\\n\\wsp\\prog{real fr(6*\\_NP\\_,6*\\_NP\\_)}\\\\\n\\wsp\\prog{common /frict/ fr}\\\\\n\\begin{sloppy}\nThe friction matrix consists of $6\\times 6$-submatrices for each particle\npair. It is always symmetric. The order of the 6 coordinates is\n$(x,y,z)_{\\rm Translation},$ $(x,y,z)_{\\rm Rotation}$.\\\\\n\\end{sloppy}\nIf the option \\prog{RIGID} is used (see description above), the friction\nmatrix has dimensions \\prog{6*nrb}$\\times$\\prog{6*nrb}. Since\n\\prog{nrb} is calculated at runtime, the array containing the friction\nmatrix is still dimensioned as $6N\\times 6N$, but not all elements\nare used.\n\n\\item[]\n\\prog{MOBILITY}\\\\\nIf defined, the program calculates the mobility matrix. The mobility\nmatrix is returned in a common block named \\prog{mobil} of the form\\\\\n\\wsp\\prog{real mo(6*\\_NP\\_,6*\\_NP\\_)}\\\\\n\\wsp\\prog{common /mobil/ mo}\\\\\n\\begin{sloppy}\nThe mobility matrix consists of $6\\times 6$-submatrices for each particle\npair. It is always symmetric. The order of the 6 coordinates is\n$(x,y,z)_{\\rm Translation},$ $(x,y,z)_{\\rm Rotation}$.\\\\\n\\end{sloppy}\nIf the option \\prog{RIGID} is used (see description above), the mobility\nmatrix has dimensions \\prog{6*nrb}$\\times$\\prog{6*nrb}. Since\n\\prog{nrb} is calculated at runtime, the array containing the mobility\nmatrix is still dimensioned as $6N\\times 6N$, but not all elements\nare used.\\\\\nIf the option \\prog{FIXED} is used, only the mobility matrix elements\nfor the freely moving particles have meaningful values.\n\n\\item[]\n\\prog{VELOCITIES}\\\\\nIf defined, the program calculates particle velocities for a given set of\nforces and torques. The forces (input) and velocities (output) are\ncontained in a common block named \\prog{fv} of the form\\\\\n\\wsp\\prog{real f(6*\\_NP\\_),v(6*\\_NP\\_)}\\\\\n\\wsp\\prog{common /fv/ f,v}\\\\\n\\begin{sloppy}\nThe arrangement of the components of \\prog{f} is\n$F_x^{(1)},F_y^{(1)},F_z^{(1)},$ $T_x^{(1)},T_y^{(1)},T_z^{(1)},\n\\ldots,$ $T_z^{(N)}$. Similarly, \\prog{v} is arranged as\n$U_x^{(1)},U_y^{(1)},U_z^{(1)},$ $\\Omega_x^{(1)},\\Omega_y^{(1)},\n\\Omega_z^{(1)},\\ldots,$ $\\Omega_z^{(N)}$.\\\\\n\\end{sloppy}\nIf the option \\prog{RIGID} is used, the forces and velocities are still\nsingle-particle quantities, but of course their calculation procedes\nin a different way. If the rigid-body velocities of the particle\nclusters are needed, the option \\prog{RB\\_VELOCITIES} (explained below)\nshould be used.\\\\\nIf the option \\prog{FIXED} is used, only the velocity components\nreferring to the freely moving particles have meaningful values.\n\n\\item[]\n\\prog{RB\\_VELOCITIES}\\\\\nThis option must be combined with \\prog{RIGID} (see above).\nIt is similar to\n\\prog{VELOCITIES}, except that input forces and output velocities \ndescribe the rigid-body motion of particle clusters. Consequently\nonly the first \\prog{6*nrb} elements are used.\n\n\\item[]\n\\prog{NORMALIZE}\\\\\nIf defined, the friction and mobility matrices are normalized by their\none-particle values. Since for a single particle there is no coupling\nbetween translation and rotation, normalization is possible only for\nthe pure translation and rotation submatrices $\\tzeta^{tt}$,\n$\\tzeta^{rr}$, $\\tmu^{tt}$ and $\\tmu^{rr}$. Consequently it should\n{\\em not} be done if combinations of translational and rotational\nmotion are to be used.\\\\\nParticle velocities calculated using the option \\prog{VELOCITIES} are\nnever normalized.\n\n\\item[]\n\\prog{POSDEF}\\\\\nThe system of linear equations that is solved to obtain the friction\nor mobility matrix can be shown to be positive definite. However, for\nlarge systems the coefficient matrix may not be positive definite from\na numerical point of view. Linear algebra packages might therefore\nissue error messages when special algorithms for positive definite\nmatrices are used. Therefore the decision whether or not to use these\nalgorithms is left to the user.\\\\ If \\prog{POSDEF} is defined,\nroutines from \\prog{LAPACK} are called that are optimized for positive\ndefinite matrices. Otherwise, routines for general symmetric matrices\nare used. It is recommended to leave \\prog{POSDEF} defined until an\nactual warning about indefinite matrices occurs.\\\\\n\n\\end{description}\n\nThe second set of compile-time options is related to the programming\nenvironment:\n\n\\begin{description}\n\n\\item[]\n\\prog{PACKED}\\\\\nIf defined, the coefficient matrix for the system of linear equations\nto be solved is stored in a packed format suitable for symmetric\nmatrices. This saves almost 50\\% of memory space, but can lead to\nslightly higher execution times. In most applications the memory\nsaving will outweigh the increased execution time, therefore it is\nrecommended to leave this option enabled. In some cases, a\nsmall {\\em decrease} of execution time was even observed with packed\nstorage.\n\n\\item[]\n\\prog{DP}\\\\\nIf defined, double precision code is used everywhere, and all external\nlibrary functions are called in their version for double-precision\ncalculations. If your Fortran compiler has an option for treating\nsingle-precision code as double precision (most compilers have), this\nwill be applied to your application program. In this case, defining\nand undefining \\prog{DP} is sufficient to switch between single and\ndouble precision versions. If your compiler does not have such an\noption, you must prepare your code manually for double-precision\ncalculations. However, there is no need to ever modify \\prog{HYDROLIB}\ncode.\n\n\\item[]\n\\prog{LAPACK}\\\\\nIf defined, routines from the linear algebra package \\prog{LAPACK} are\nused for the calculation of eigenvalues, for the solution of a system\nof linear equations, and for matrix inversion.\\\\\nNote that currently no other linear algebra libraries are\nsupported. If you add support for another library, you can\ndefine the label you have chosen for that library instead\nof \\prog{LAPACK}.\n\n\\end{description}\n\n\n\\section{Fortran subroutines in the library}\n\\label{sec:imp}\n\nTo calculate hydrodynamic interactions for a certain configuration of\nparticles, you must write a Fortran program that calls subroutines\nfrom \\prog{HYDROLIB}. For illustrational\npurposes, an example program (\\prog{example.f}) is included that\ncalculates the four independent friction coefficients for a linear\nchain of touching particles.\n\nDuring the initialization of the program, the subroutine \\prog{init}\nmust be called. If periodic boundary conditions are used, the\nvariable \\prog{box} in the common block \\prog{pbc} must be set to the\nedge length of the cubic box, as explained in section~\\ref{sec:config}.\n\nAfter that, the subroutine \\prog{eval} can be called any number of times.\nThis subroutine has no arguments, all input and output data are\npassed via common blocks. Which quantities are calculated by\n\\prog{eval} depends on the compile-time options used, see\nsection~\\ref{sec:config} for details.\n\nBefore calling \\prog{eval}, the particle configuration must be\nstored in a two-dimensional array in the\ncommon block \\prog{conf}. The first dimension of this array is 3, for\nthe $x$-, $y$-, and $z$-coordinates, the second dimension is the\nnumber of particles. An example of a definition for this common block\nis\\\\\n\\wsp\\prog{real c(3,\\_NP\\_)}\\\\\n\\wsp\\prog{common /conf/ c}\\\\\nIf the option \\prog{RIGID} is activated, the particle configuration\nmust be extended by a list of rigid connections between the particles.\nThis takes the form of a $N\\times N$-array of \\prog{character*1}. Any\ncharacter other than a space stands for a rigid connection between\ntwo particles. Only the upper-diagonal part of this array, i.e.\\ elements\nfor which the second index is larger than the first one, are used.\nWith this addition, the common block \\prog{conf} takes the form\\\\\n\\wsp\\prog{real c(3,\\_NP\\_)}\\\\\n\\wsp\\prog{character*1 cnct(\\_NP\\_,\\_NP\\_)}\\\\\n\\wsp\\prog{common /conf/ c,cnct}\\\\\n\nWhen particle velocities are to be calculated (option\n\\prog{VELOCITIES}), the forces must be defined before calling\n\\prog{eval}. This is done in the common block\n\\prog{fv} as explained in section~\\ref{sec:config}.\n\nAfter calling \\prog{eval}, the results can be found in various common\nblocks as explained in section~\\ref{sec:config}. The input data\nare not changed, with the possible exception of the character array\nspecifying rigid connections. The contents of this array may have been\nchanged to another equivalent specification of the same set of\nconnections.\n\n\n\\begin{thebibliography}{9}\n\n\\bibitem{cifehiwabl}\n \\name{B. Cichocki, B.U. Felderhof, K. Hinsen,\n E. Wajnryb, J. B{\\l}awzdziewicz},\n Friction and mobility of many spheres in Stokes flow,\n J. Chem. Phys. \\vol{100}, 3780~(1994)\n\n\\bibitem{hi}\n \\name{K. Hinsen},\n \\prog{HYDROLIB}: a library for the evaluation of hydrodynamic\n interactions in colloidal suspensions,\n Computer Physics Communications (1995)\n\n\\end{thebibliography}\n\n\\end{document}\n", "meta": {"hexsha": "5d7c2855c71793a532ccc9da309a06daa14998e6", "size": 28887, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/guide.tex", "max_stars_repo_name": "khinsen/HYDROLIB", "max_stars_repo_head_hexsha": "c0e7834a17c7046a6e4c0a27b980aaf5919aecd5", "max_stars_repo_licenses": ["BSD-3-Clause-Clear"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-10-12T22:57:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-09T12:52:41.000Z", "max_issues_repo_path": "doc/guide.tex", "max_issues_repo_name": "khinsen/HYDROLIB", "max_issues_repo_head_hexsha": "c0e7834a17c7046a6e4c0a27b980aaf5919aecd5", "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": "doc/guide.tex", "max_forks_repo_name": "khinsen/HYDROLIB", "max_forks_repo_head_hexsha": "c0e7834a17c7046a6e4c0a27b980aaf5919aecd5", "max_forks_repo_licenses": ["BSD-3-Clause-Clear"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-10-12T22:57:46.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-12T22:57:46.000Z", "avg_line_length": 42.8590504451, "max_line_length": 79, "alphanum_fraction": 0.7695156991, "num_tokens": 7527, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.35936415888237616, "lm_q1q2_score": 0.1950856071454125}}
{"text": "\\section{Measurement of fiducial cross section}\n\\label{sec:xsec}\n\nThe fiducial cross section for inclusive $ZZjj$ production, including both EW and QCD components, is then measured.\nThe definition of fiducial volume, which is used for cross section measurement, follows closely to the detector-level selection\nbut use physics objects at particle-level, which are reconstructed in simulation from stable final-state particles,\nprior to their interactions with the detector.\n\nFor electrons and muons, QED final-state radiation is for the most part recovered \nby adding the four-momenta of surrounding photons that are not originating from hadrons and within an angular distance $\\Delta R < 0.1$\nto the lepton four-momentum, called lepton ``dressing\" at truth level.\nParticle-level jets are built with anti-$k_{T}$ algorithm with radius parameter $R = 0.4$ using all final-state particles except leptons and neutrinos as inputs.\nComparing to the events selection at detector-level in section~\\ref{sec:vbszz_selection},\nat particle-level, the selected dilepton pair mass required is relaxed to be within 60 to 120~\\gev~ for the reasons of reducing the migration effect,\nas well as being more compatibility with CMS publication~\\cite{2017682}.\nAll other kinematic selections are the same as the definition at detector-level.\n\n\\subsection{Calculation of C-factor}\n\\label{sec:cf}\n\nC-factor is defined as the ratio between the number of selected events at detector-level and the number of particle-level events in fiducial volume (FV):\n\\begin{equation}\n\t\\mathcal{C} = \\frac{N_{detector-level}}{N_{FV.}}\n\\end{equation}\nThe value of C-factor for each $ZZjj$ process are firstly calculated from each individual simulation samples together with their systematics.\n%\\begin{table}[H]\n%\\begin{center}\n% \\begin{tabular}{|c|c|c|c|c|}\n% \\hline\n% Process & $\\mathcal{C}$ & $\\Delta$C (stats.) & $\\Delta$C (sys.) & $\\Delta$C (theo.) \\\\\n% \\hline\n% EWK $ZZjj$ & 0.663 & $\\pm$0.002 & $\\pm^{0.032}_{0.031}$ & NA \\\\\n% \\hline\n% QCD \\qqZZ & 0.702 & $\\pm$0.003 & $\\pm^{0.061}_{0.051}$ & $\\pm^{0.015}_{0.018}$ \\\\\n% \\hline\n% QCD \\ggZZ & 0.741 & $\\pm$0.021 & $\\pm^{0.143}_{0.072}$ & $\\pm{0.002}$ \\\\\n% \\hline\n%\\end{tabular}\n%\\end{center}\n%\\caption{C Factor of different $ZZjj$ processes.}\n%\\label{tab:xs_cf}\n%\\end{table}\nThen the $\\mathcal{C}$ from different processes are combined together according to their fraction of events in fiducial volume,\nand used as inputs for cross section calculation:\n\\begin{equation}\n\t\\mathcal{C} = \\Sigma_{i} \\frac{N_{FV.}^{i}}{\\Sigma_{j} N_{FV.}^{j}} \\times \\mathcal{C}_{i} = 0.699\\pm0.003(stats.)\\pm^{0.011}_{0.013}(theo.)\\pm0.028(exp.)\n\\end{equation}\nThe ``stats.\" refers to the statistical uncertainty from MC simulation statistics.\nThe ``theo.\" and ``exp.\" denote the theoretical and experimental uncertainties described in section~\\ref{sec:systematics}.\n\n\\subsection{Result of fiducial cross section}\n\nThe cross section in fiducial volume is computed as:\n\\begin{equation}\\label{eq:xs}\n\t\\sigma^{FV.} = \\frac{N_{data} - N_{bkg}}{\\mathcal{C} \\times Lumi}\n\\end{equation}\nwhere $N_{data}$ and $N_{bkg}$ denote the number of events selected from detector-level selection from data and sum of backgrounds,\nand $\\mathcal{C}$ is the C-factor calculated above, Lumi represents the integrated luminosity of data from 2015 to 2018 of 139~\\ifb.\n%As shown in table~\\ref{tab:yield_prefit}, in inclusive measurement, only the ``Others\" represents background, \n%processes of EW-$ZZjj$, QCD-\\qqZZ and QCD-\\ggZZ are signals.\nTable~\\ref{tab:xs} shows the fiducial cross section for \\llll final state measured from equation~\\ref{eq:xs}, \nas well as the predicted cross section measured from MC simulation directly.\n\n\\begin{table}[!htbp]\n\\begin{center}\n\\scalebox{0.90}{\n\\begin{tabular}{ c | c}\n\\hline\n\\hline\\noalign{\\smallskip}\nMeasured fiducial $\\sigma$ [fb] & Predicted fiducial $\\sigma$ [fb] \\\\\n\\noalign{\\smallskip}\\hline\\noalign{\\smallskip}\n$1.27 \\pm 0.12(\\mathrm{stat}) \\pm 0.02(\\mathrm{theo}) \\pm 0.07(\\mathrm{exp}) \\pm 0.01(\\mathrm{bkg}) \\pm 0.02(\\mathrm{lumi})$ & $1.14 \\pm 0.04(\\mathrm{stat}) \\pm 0.20(\\mathrm{theo})$ \\\\\n\\noalign{\\smallskip}\\hline\n\\hline\n\\end{tabular}}\n\\end{center}\n\\caption{\nMeasured and predicted fiducial cross-sections in \\lllljj final-state.\nUncertainties due to different sources are presented.\n}\n\\label{tab:xs}\n\\end{table}\nThe measured cross section has a total uncertainty of 11\\%, and is found to be compatible with SM prediction.\nThis measurement is still dominant by data statistic.\n", "meta": {"hexsha": "698a3ee0b668201c873d1255c1793a4b1d3059a9", "size": 4638, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "chapters/VBSZZ/xsec.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/xsec.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/xsec.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": 54.5647058824, "max_line_length": 184, "alphanum_fraction": 0.7179818887, "num_tokens": 1355, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.19507638209139166}}
{"text": "\\chapter{Discussion}\n\nIn this chapter, we review results of our experiments and discuss applications of the analyzed models in other systems. We also give tips on how to perhaps further improve performance of our models and which aspects of human memory could be considered in future research.\n\n\\section{Results}\n\nIn chapter~\\ref{analysis}, we analyzed several models based on timing information (taking into account either ages of past trials of items or past response times of students). Most promising results in the context of learning geography facts shows the PFA/E/T model with a staircase time effect function, although the power function proves to be almost as equally a good choice. Main advantage of the staircase function is that the parameters are easy to learn for the purpose of online learning, i.e. there is no need to periodically run parameter optimization procedure since the parameters are slightly adjusted with each new answer.\n\nThe PFA/G/T model suffers from the inability to account for multiple-choice questions. It might be interesting to analyze the models on data from adaptive systems where questions with multiple-choice options are not used---this is not possible using the data set described in section~\\ref{data-set} since the system adaptively selects number of options in multiple choice tests, i.e. filtering out all multiple-choice questions creates data set with skewed difficulties and abilities of students.\n\nThe PFA/E/RT model that considers past response times of students shows in most cases only a very small improvement. However, very interesting results provides the PFA/G model with values of the decay factor lower then 0.5, this may indicate that the past trials of items do not actually influence model's performance in the context of learning geography facts as much as we thought. When we compare the PFA/G model and the PFA/G/T model, it seems that penalizing old trials based on order of answers leads in most cases to a better performance than the penalty of trials based on timing information.\n\n\\section{Applications and Recommendations}\n\nCurrently, models used in the adaptive system Outline Maps do not take into account ages of past trials. We have demonstrated that the timing information improves model's performance and thus, the extensions of presented models should be considered in production. As we already discussed in previous section, the best choice is the PFA/E/T model with a time effect function fitted by gradient descent described in chapter~\\ref{approx-gradient}.\n\nAnother application of our models could be considered in the adaptive system for practicing medical anatomy (\\url{practiceanatomy.com}) targeted mostly at medical students. The system allows the practice of various organ systems, body parts, bones, muscles, etc. The evaluation of our models on data from students who practice anatomy could also open interesting questions about difficulty of items and the effect of forgetting where most students are collage students.\n\n\\section{Possible Extensions and Alternative Models}\n\nThe examined models approximate the effect of human memory decay with a time effect function which ignores some very important aspects of memory and forgetting. For example, in our models the spacing effect is completely disregarded. One extension of the PFA/G/T model could reuse some properties of the memory activation equation~\\ref{eq-pavlik-activation} described in chapter~\\ref{spacing-effect}. Next, an extension of the PFA/G/T model which considers multiple-choice questions might also be possible and could significantly improve its performance.\n\nAnother extension of the models could consider the fact that students mix up the places that are, for instance, geographically very close, have similar names, or seem somehow similar for entirely different reasons. Students typically know the approximate geographical location of the Nordic countries, however, they might struggle when determining exact location of each country, often they confuse Norway with Sweden as can be seen in Figure~\\ref{fig:confusion-network}. If a students chooses Finland when the highlighted place is actually Norway, it usually does not mean that they have no knowledge of the country's location. In such cases it might be more accurate to slightly increase student's memory activation of the place.\n\n\\begin{figure}[htbp]\n \\centering\n \\includegraphics[width=\\textwidth]{img/confusion-network}\n \\caption{Confusion network of European countries. The edges between countries represent confusion of students. Dark blue edge means that the two connected countries are confused by students quite often while light blue indicates that the countries are still sometimes confused but at least less often.}\n \\label{fig:confusion-network}\n\\end{figure}\n\nA completely different approach on student modeling is the usage of Recurrent Neural Networks (RNNs), the family of RNN model have important advantage over models analyzed in our thesis---they do not require explicit encoding of the essential aspects of human memory and can capture more complex patterns of learning. The usage of RNNs in education, especially the Long Short Term Memory (LSTM) model, has been already explored and shows promising results~\\cite{piech2015deep}. It might be interesting to analyze the RNN model in the context of the system for learning geography and also compare the performance with PFA models.\n", "meta": {"hexsha": "0440e82635d5247cc00e615c221946db0a822bd5", "size": 5430, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "text/discussion.tex", "max_stars_repo_name": "paveldedik/thesis", "max_stars_repo_head_hexsha": "9a2f1cd0589b3dfe0c221066174d9c560c0366fb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2015-06-07T15:33:39.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-04T08:15:03.000Z", "max_issues_repo_path": "text/discussion.tex", "max_issues_repo_name": "paveldedik/thesis", "max_issues_repo_head_hexsha": "9a2f1cd0589b3dfe0c221066174d9c560c0366fb", "max_issues_repo_licenses": ["MIT"], "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/discussion.tex", "max_forks_repo_name": "paveldedik/thesis", "max_forks_repo_head_hexsha": "9a2f1cd0589b3dfe0c221066174d9c560c0366fb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2015-10-03T21:40:54.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-03T21:40:54.000Z", "avg_line_length": 164.5454545455, "max_line_length": 731, "alphanum_fraction": 0.8174953959, "num_tokens": 1033, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.19507638209139166}}
{"text": "% $Id: a36f51514b47d1c52a9dbe2f8e29a2addeafd1ac $\n\n\\section{Introduction}\n\nThese days, Boolean satisfiability (SAT) solvers are undeniably quite reliable\ntools despite the worst-case exponential run time of all known\nalgorithms. Modern SAT solvers provide a ``black-box'' procedure that can often\nsolve hard structured problems with over a million variables and several million\nconstraints. These tools are therefore used in many applications outside the\nscope of knowledge representation and reasoning, which nonetheless was their\ninitial domain of application. The underlying representational formalism of SAT\nsolvers is propositional logic, and even if a given problem is not a pure\npropositional problem, it is not unusual to encode it so that it can be viewed\nas a propositional reasoning task. This encoding may be complex and possibly\ncostly, but the effectiveness of SAT solvers generally compensates for the cost\nof this encoding.\n\nThis growing interest for SAT solvers has steered them toward a more first order\napproach, with the possibility to deal with first order literals and reason\nmodulo theories. This resulted in the design of Satisfiability Modulo Theories\n(SMT) solvers, which are built on top of SAT solvers. Over the last past few\nyears, SMT solvers have appeared as very efficient tools to reason over some\nwell identified theories (equality, uninterpreted functions, linear arithmetic,\narrays, etc.), and have allowed us to drag SAT solving toward first order logic.\nAlthough modern SMT solvers support first order logic, most of them use\nheuristic quantifier instantiation for incorporating quantifier reasoning with\nground decision procedures. This mechanism is relatively effective in some cases\nin practice, but it is not refutationally complete for first order logic. Hints\n(triggers) are usually required, and it is sensitive to the syntactic structure\nof the formula, so that it fails to prove formulas that can be easily discharged\nby provers based on more traditional first order proof search methods (tableaux,\nresolution, etc.).\n\nIn this paper, we propose to overcome this problem of completeness for first\norder logic in SMT solving by combining a SAT solver core with tableau\ncalculus. The tableau calculus is introduced as a regular theory of SMT solving,\nand the rules are used to unfold propositional content into clauses while atomic\nformulas are handled using satisfiability decision procedures as in\nSMT solvers. To deal with quantified first order formulas, we use\nmetavariables and perform rigid unification modulo equalities and rewriting, for\nwhich we introduce an algorithm based on superposition, but where all clauses\ncontain a single atomic formula.\n\nWe also propose to improve proof search by introducing rewriting into the SAT\nsolver as a regular SMT theory and along the lines of deduction modulo\ntheory. Deduction modulo theory~\\cite{DA03} focuses on the computational part of\na theory, where axioms are transformed into rewrite rules, which induces a\ncongruence over propositions, and where reasoning is performed modulo this\ncongruence. In deduction modulo theory, this congruence is then induced by a set\nof rewrite rules over both terms and propositions.\n\nOur approach provides several advantages compared to usual SMT solving and first\norder proof search methods. First, we benefit from the efficiency of a SAT\nsolver core together with a complete method of instantiation (when a\npropositional model is found, we try to find a conflict between two literals by\nunification). Second, it should be noted that our approach requires no change in\nthe architecture of the SMT solver, since the tableau calculus and rewriting are\nseen as regular theories. Finally, no preliminary Skolemization and Conjunctive\nNormal Form (CNF) transformation is required. This transformation is performed\nlazily by applying the tableau rules progressively when a literal is propagated\nor decided. This makes the production of genuine output proofs easier, contrary\nto the usual approach, where the Skolemization/CNF translation is realized at\nthe beginning and externalized with respect to the proof search.\n\nOur proposal combining SAT solving with tableau calculus and rewriting has been\nimplemented and the corresponding tool is called \\archsat{}. This tool is able\nto deal with first order logic extended to polymorphic types à la ML, through a\ntype system in the spirit of~\\cite{BP13}. To test this tool, we propose a\nbenchmark in the framework of the set theory of the \\bmth{}\nmethod~\\cite{B-Book}. This theory~\\cite{BA15} has been expressed using first\norder logic extended to polymorphic types and turned into a theory that is\ncompatible with deduction modulo theory, i.e. where a large part of axioms has\nbeen turned into rewrite rules. The benchmark itself gathers 319~lemmas coming\nfrom Chap.~2 of the \\bbook{}~\\cite{B-Book}.\n\nThe paper is organized as follows: in Sec.~\\ref{sec:smt}, we recall the classic\narchitecture of SMT solvers, and we introduce the tableau and rewriting\ntheories; we then describe, in Sec.~\\ref{sec:super}, our mechanism of equational\nreasoning by means of rigid unit superposition; finally, in\nSec.~\\ref{sec:bench}, we present some experimental results obtained by running\nour implementation over a benchmark of problems in the \\bmth{} set theory.\n", "meta": {"hexsha": "a36f51514b47d1c52a9dbe2f8e29a2addeafd1ac", "size": 5321, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "papers/ijcar18/intro.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/intro.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/intro.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": 64.8902439024, "max_line_length": 80, "alphanum_fraction": 0.8171396354, "num_tokens": 1153, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3812195662561499, "lm_q1q2_score": 0.19507638209139164}}
{"text": "\\def\\pathToRoot{../../}\n\\input{\\pathToRoot/headers/uebungsheader.tex}\n\n\\def\\issolution{}\n\n\\begin{document}\n\n% {Sheet number}{headline}{deadline}\n\\exercisehead{5}{}{15.12.2020, 23:59}\n\n\\section*{Instructions}\nSubmit the jupyter notebook with the solution for exercise 5.2 b) in an archive along with the latex file.\n\n\n\\section*{Exercises}\n\n\\begin{exercise}[Computing Jacobian and Hessian][1 + 1 = 2]\n\nLet $f(x,y) = 3x^2 y + 4x^3 y^4 - 7x^9 y^4$. Compute Jacobian and Hessian matrices of $f$.\n\\end{exercise}\n\n\n\\begin{solution}\n % write the solution here\n\\end{solution}\n\n\n\\begin{exercise}[Taylor Series and Newton's Method][1 + 2 + 1 + 1 = 5]\n\n \\begin{enumerate}\n \\item Derive the first 5 terms of the Taylor series about $x_0 = 0$ for $f(x) = cos(x)$, and write the series in sigma notation (e.g. as an infinite sum).\n \n \\item In python, apply Newton's method to find the nearest critical point of \\\\\n \\begin{center} $f(x, y) = x^2 - y^2 + 4 - 3xy$\\\\\n from the initial point $x_0 = -0.3, y_0 = 0.3$.\\\\ \\end{center}\n After each iteration, check the value of the first derivative, i.e. Jacobian: if Jacobian is 0, then we reached the critical point.\\\\\n Plot the original function for x and y in range from -0.5 to 0.5 with step size of 0.01, along with the initial point and the points computed after each iteration.\n Use method \\href{https://matplotlib.org/3.1.0/gallery/mplot3d/surface3d.html}{.surface\\_plot()} with parameter $alpha=0.3$ for plotting the function and \\href{https://matplotlib.org/mpl_toolkits/mplot3d/tutorial.html}{.scatter()} for plotting the points. \\\\\n\tWhat kind of problem of function minimization task is illustrated with this example?\n \n \\item How is Newton’s Method related to gradient descent?\n \n\t\\item In which case is it impossible to apply Newton's method? Hint: look at the multidimensional generalization of the formula.\n\t\n\t\n \n \\end{enumerate}\n \n\\end{exercise}\n\n\n\\begin{solution}\n % write the solution here\n\\end{solution}\n\n\n\\begin{exercise}[Activation Functions][1.5 + 1 + 0.5 = 3]\n\n \\begin{enumerate}\n \\item Three of the most commonly-used activation functions are the sigmoid function, hyperbolic tangent, and ReLU. The equations for these are given below. Compute the first derivative of each function. Note that your final derivative for tanh should not be written in terms of other hyperbolic functions, though you may use these in your calculation. Hint: ReLU is not differentiable at x = 0. For the purposes of your derivative, you may define its derivative piecewise, ignoring this point.\n \\[\\sigma(x) = \\frac{1}{1+e^{-x}}\\,\\,\\,\\,\\,\\tanh(x) = \\frac{e^{2x} - 1}{e^{2x} + 1}\\]\n \\[ReLU(x) = \\left\\{\n\\begin{array}{ll}\n 0 & x < 0 \\\\\n x & x > 0 \\\\\n\\end{array} \n\\right. \\]\n \n \\item Using an online resource like Wolfram Alpha or Desmos, graph each function along with its derivative. Discuss the differences you observe. What are the advantages and disadvantages of each? In particular, think about how the range of the function and the amplitude of the derivative would affect a network.\n \n \\item Which activation function would be most appropriate for a classification problem when there are only two classes? Would adding more classes change your choice? Why or why not?\n \\end{enumerate}\n \n\\end{exercise}\n\n\n\\begin{solution}\n % write the solution here\n\\end{solution}\n\n\n\n\\section*{Submission instructions}\n\n\\framebox{\n\t\\begin{minipage}{\\linewidth}\n\t\tThe following instructions are mandatory. If you are not following them, tutors can\n\t\tdecide to not correct your exercise.\n\t\\end{minipage}\n}\n\n\\begin{itemize}\n \\item You have to submit the solutions of this assignment sheet as a team of 2-3 students.\n \\item Hand in a \\textbf{single} PDF file with your solutions.\n \\item Make sure to write the student teams ID and the name of each\n member of your team on your submission.\n \\item Your assignment solution must be uploaded by only \\textbf{one} of your team members to the course website.\n \\item If you have any trouble with the submission, contact your tutor \\textbf{before} the deadline.\n\\end{itemize}\n\n\\end{document}\n", "meta": {"hexsha": "fd56adf3e71f96c823a2e7f7061bcfe7ff1ef976", "size": 4166, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "neural-networks/assignment5/solution.tex", "max_stars_repo_name": "sangeet2020/ws-20-21", "max_stars_repo_head_hexsha": "316d2c1495cd540ce390eced52d41c57efed1f64", "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": "neural-networks/assignment5/solution.tex", "max_issues_repo_name": "sangeet2020/ws-20-21", "max_issues_repo_head_hexsha": "316d2c1495cd540ce390eced52d41c57efed1f64", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-12-03T00:05:20.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-03T00:05:20.000Z", "max_forks_repo_path": "neural-networks/assignment5/solution.tex", "max_forks_repo_name": "sangeet2020/WS-20-21", "max_forks_repo_head_hexsha": "316d2c1495cd540ce390eced52d41c57efed1f64", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-01-05T06:55:52.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-17T00:19:30.000Z", "avg_line_length": 40.8431372549, "max_line_length": 501, "alphanum_fraction": 0.7143542967, "num_tokens": 1148, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4416730056646256, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.19507504393282435}}
{"text": "% !TEX root = atlas_iros_16.tex\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{\\large Collision Detection}\n\\label{sec:CollDet}\n%\nIn the following experiments (Sec.~\\ref{sec:CollDet_EE} and \\ref{sec:CollDet_Link}), we used the collision handling (\\ref{eqn:CollDet}) and (\\ref{eqn:CollReact}) to detect collisions with the Atlas robot with a disturbance joint torque threshold $\\bm{\\zeta}$ of $11$~Nm for each joint.\nA lower threshold frequently leads to false alarms due to remaining modeling errors (see Fig.~\\ref{fig:ident_torque_compare}) and the large friction effects (see Fig.~\\ref{fig:ident_friction_char}).\nOur model is not able to reliably remove the static friction torque from the observer ($\\kappa_{\\mathrm{f}}=1$ in (\\ref{eqn:observer_settings})) due to the indeterminate friction state for low velocities \\cite{BidardLibArhMea2005}.\nThe friction compensation in (\\ref{eqn:controller}) currently leads to unwanted oscillations indicating closed-loop stability problems originating in the velocity feedback, as described in \\cite{ConnerKohRomStu2015}.\nTherefore, this feature is disabled in the experiments with $\\kappa_{\\mathrm{f}}=0$. \nHowever, it is possible to reliably detect soft collisions at moderate velocity (100~mm/s) in adequate time with the Atlas system.\nFor the collision detection and reaction experiments, the disturbance compensation in (\\ref{eqn:controller}) was disabled ($\\kappa_\\varepsilon=0$).\nThe first joint was selected for evaluation of the experiments, since the collision is detected at this joint first. The other axes show qualitatively the same behavior.\n\n\\subsection{End-effector Collision}\n\\label{sec:CollDet_EE}\n%\n\\begin{figure}\n\\begin{subfigure}{.24\\textwidth}\n \\centering\n \\includegraphics[trim=550 250 350 100,clip,width=.98\\linewidth]{figures/CollDetCinderblock/ImpCtrlv5_E057_R04_impCtrl_K300_wall_colldet_move_away_021.jpg}\n \\caption{Enabled (``Coll.Det'' in Fig.~\\ref{fig:CinderCollisionSummary})}\n \\label{fig:CinderColl_zerog}\n\\end{subfigure}%\n\\begin{subfigure}{.24\\textwidth}\n \\centering\n \\includegraphics[trim=550 250 350 100,clip,width=.98\\linewidth]{figures/CollDetCinderblock/ImpCtrlv5_E057_R05_impCtrl_K300_wall_nocolldet_collision_022.jpg}\n \\caption{Disabled (``Stiff'' in Fig.~\\ref{fig:CinderCollisionSummary})}\n \\label{fig:CinderColl_push}\n\\end{subfigure}\n\\caption{Result after the end-effector collision with and without detection and reaction (snapshot at $t\\approx1.5$~s of Fig.~\\ref{fig:CinderCollisionSummary})}\n\\label{fig:CinderCollPictures}\n\\SkipBeforeText\n\\end{figure}\n%\n\\begin{figure}\n\\centering\n\\parbox{\\columnwidth}{\n\\includegraphics{figures/CollDetCinderblock/Collision_Summary_Cinderblock.pdf}\n}\n\\vspace*{-1ex}\n\\caption{Absolute external force $|\\bm{f}_\\mathrm{ext,EE}|$, observed disturbance torque $\\hat{\\tau}_{\\varepsilon,1}$ and joint position $q_1$ are depicted for the cinderblock collision experiment (see also Fig.~\\ref{fig:CinderCollPictures}).\nFor the ``Stiff'' and ``Coll.Det'' mode, $k_i=300$~Nm/rad and for the ``Compliant'' mode $k_i=100$~Nm/rad were chosen.}\n\\label{fig:CinderCollisionSummary}\n\\SkipBeforeText\n\\end{figure}\n%\nThe first experiment lets the end-effector collide with a styrofoam-protected cinderblock, see Fig.~\\ref{fig:CinderCollPictures}.\nThe protection aimed to protect the robot from damage and has no major influence on the collision detection.\nThe measured data during the three runs with different settings is depicted in Fig.~\\ref{fig:CinderCollisionSummary}.\nUsing a rather stiff joint impedance controller with joint-wise $k_i=300$~Nm/rad (``Stiff'') and deactivated collision handling leads to pushing the cinderblock away and tipping it over till reaching the final goal position, see Fig.~\\ref{fig:CinderCollPictures}~(b) and Fig.~\\ref{fig:CinderCollisionSummary}.\nReducing the joint stiffness to \\mbox{$k_i=100$~Nm/rad} (``Compliant'') leads to smaller resulting quasi-static contact forces, while the positioning error increases, see Fig.~\\ref{fig:CinderCollisionSummary}.\n\nUsing the collision detection and reaction (``Col. Det.''), the arm drifts away after the collision has been detected and the contact force decays to zero, see Fig.~\\ref{fig:CinderCollPictures}~(a) and Fig.~\\ref{fig:CinderCollisionSummary}.\nThe collision in Fig.~\\ref{fig:CinderCollisionSummary} is detected at $t=1.1$~s, when the disturbance torque line crosses the detection threshold $\\bm{\\zeta}$.\nAt this point in time, the maximum contact force of about 69~N is already reached, which is caused by the relatively slow dynamics of the observer (\\mbox{$k_{\\mathrm{o},i}=5~\\mathrm{s}^{-1}$}).\nA larger gain would allow an earlier detection with less reaction force.\nUsing retract reflexes would allow further reduction of contact forces.\nIn turn, larger observer gain causes vibrations when being used as disturbance compensation.\nTo overcome this issue, two observers could be used in parallel: a slower one for compensation and a faster one for collision detection.\n\n\\subsection{Link Collision}\n\\label{sec:CollDet_Link}\n%\n\\begin{figure}\n\\centering\n\\parbox{\\columnwidth}{\n% \\includegraphics[trim=550 50 350 340,clip,width=\\linewidth]{figures/CollDetStick/GOPR2201_ImpCtrlv5_E055_part4_t036.jpg}\n\\input{./figures/CollDetStick/GOPR2201_ImpCtrlv5_E055_part4_t036_bearb.pdf_tex}\n}\n\\caption{Scene during the collision from Fig.~\\ref{fig:StickCollisionSummary} at $t\\approx5.5$~s.}\n\\label{fig:StickCollisionPhoto}\n\\SkipBeforePicture\n\\end{figure}\n%\n\\begin{figure}\n\\centering\n\\parbox{\\columnwidth}{\n\\includegraphics{figures/CollDetStick/CollDetStickIROS.pdf}\n}\n\\vspace*{-1ex}\n\\caption{Joint position $q_1$, model torque $\\tau_{\\mathrm{mdl},1}$, estimated disturbance torque $\\hat{\\tau}_{\\varepsilon,1}$ and motor-side joint torque $\\tau_{\\mathrm{m},1}$ during link collision, see Fig.~\\ref{fig:StickCollisionPhoto}.}\n\\label{fig:StickCollisionSummary}\n\\SkipBeforeText\n\\end{figure}\n%\nThe second experiment shows that collisions at the proximal links and not only at the end-effector are detected as well.\nThe arm was pushed at the elbow with a cardboard stick against the moving direction during a joint trajectory, see Fig.~\\ref{fig:StickCollisionPhoto} (in the depicted situation, the elbow was moving to the right).\nThe movement speed was $\\approx50~\\mathrm{mm/s}$ at the collision location.\nFigure~\\ref{fig:StickCollisionSummary} depicts the measurement data. The collision at link $4$ starts at $t\\approx5.5$~s, which one can see from the high motor torque in joint 1.\nThe detection threshold is reached at $t\\approx5.6$~s, leading to the halt in gravity compensation mode.\n\n", "meta": {"hexsha": "8d22921aae8a2618d051406b28e1d3ae2e7a9425", "size": 6620, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "paper/sec_colldet.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_colldet.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_colldet.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": 71.1827956989, "max_line_length": 310, "alphanum_fraction": 0.7791540785, "num_tokens": 1768, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.37754066179448903, "lm_q1q2_score": 0.194667484216486}}
{"text": "%\\section{Radiation}\n{\\bf \\Large\n\\begin{tabular}{ccc}\n\\hline\n Corresponding author & : & Hisashi Yashiro\\\\\n\\hline\n\\end{tabular}\n}\n\\\\\n\n\\subsection{mstrnX}\nSCALE implements a broadband atmospheric radiative transfer model named ``Model Simulation radiation TRaNsfer code version X (mstrn-X)'' developed by \\citet{nakajima_2000} and \\citet{sekiguchi_2008}. \\verb|mstrn| is based on the discrete ordinate method with a delta two-stream approximation and the correlated k-distribution method. The model calculates long- and short-wave radiation fluxes using the atmospheric states, the three dimensional distribution of clouds/gases/aerosols, and the property of land/ocean surface.\nThe spectrum between 0.2 and \\SI{200}{\\micro m} is divided into 29 spectral bands and 111 integration points.\n\nThe calculation of solar insolation is based on the parameterization of \\citet{berger_1978}. The expected top of atmosphere in the radiation model is 100 km above sea level. However, it is sometimes higher than the top of the domain used in the limited-area simulations.\nThus, SCALE can add the climatological profile to the upper part of the model domain, as needed. The COSPAR International Reference Atmosphere (CIRA-86) \\citep{CSR_2006} is used for the climatological profile of temperature and pressure. The standard profiles of trace gases such as oxygen, carbon dioxide, ozone, water vapor, methane, etc., are referred to the MIPAS reference atmospheres (\\citet{Remedios_2007}).\n", "meta": {"hexsha": "252f37a880dc69df3751dcfe62805cf4e3b6dec0", "size": 1477, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/descriptions/radiation.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/descriptions/radiation.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/descriptions/radiation.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": 86.8823529412, "max_line_length": 523, "alphanum_fraction": 0.7975626269, "num_tokens": 366, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.19423646169227826}}
{"text": "\\section{Methods}\nThe computational methodology described herein has been implemented in the open-source C\\_MPI program\\footnote{MPI is the abbreviation of message passing interface.} \\texttt{fitoog}.\\autocite{mccluskey_arm61/fitoog_2019}\n\n\\subsection{Simulation Methodology}\n%\n\\begin{marginfigure}\n \\centering\n \\includegraphics[width=\\linewidth]{smallangle/director}\n \\caption{A graphical description of the severe coarse-graining applied to the MARTINI description of the \\emph{n}-decyltrimethylammonium surfactant molecule for the use of the particle swarm algorithm.}\n \\label{fig:director}\n\\end{marginfigure}\n%\nThe \\texttt{fitoog} software takes a series of input files that define the molecules, intramolecular interactions, and scattering lengths for the constituent particles.\nThe molecule input file is a space-separated file consisting of an index, particle name, \\emph{x}-coordinate, \\emph{y}-coordinate, \\emph{z}-coordinate, and scattering length.\nWhen \\texttt{fitoog} reads in a molecular input file, a \\texttt{differences} object is created, this stores the differential between the atomistic, or near-atomistic\\footnote{Such as the MARTINI-style beading use in this work.} description and the more severe coarse-grained description that is used in the PSO.\n\nInspired by the coarse-graining methodology applied to directional colloid self-assembly by Law \\emph{et al.},\\autocite{law_coarse-grained_2016} a severe coarse-graining methodology was developed for use on surfactant molecules in \\texttt{fitoog}.\nThis allowed for a significantly reduced parameter dimensionality to which the PSO\\footnote{Which is described in Section \\ref{sec:partswarm}.} could be applied.\nThe severe coarse-graining reduced the surfactant to a ``director'' description; where each surfactant molecule is defined by a position and a direction, shown pictorially in Figure~\\ref{fig:director}.\nThis reduced the parameter dimensionality to just six variables per molecule; three of which described the centre-of-mass position of the molecule and three that describe the angular orientation of the surfactant in space.\\footnote{Given the symbols, $a$, $b$, $c$ for the positions and $\\phi$, $\\omega$, and $\\kappa$ for the angles.}\nAdditionally, if the molecule was a single particle in length, as is the case for the \\ce{NO3-} anion in the Section~\\ref{sec:real_data}, then the dimensionality is just three, as the direction is arbitrary.\n\nThe methodology for the particle swarm in this work followed the implementation discussed in Section~\\ref{sec:partswarm}.\nWhere the parameters to be optimised where the position and orientation of the input molecules.\\footnote{The $a$, $b$, $c$, $\\phi$, $\\omega$, and $\\kappa$ mentioned above.}\nFollowing each PSO iteration, the molecule director is expanded from the position variable\\footnote{Using the \\texttt{differences} object mentioned above.}.\nThis representation is then rotated based on a rotation matrix, in this work the rotation matrix was constructed by first rotating the rotation axis by $-\\phi$ and $-\\omega$, then rotating by $\\kappa$ in around the $z$-axis, before rotating the axis back to the original position by $\\omega$ and $\\phi$.\\sidecite[Figure~\\ref{fig:rot} defines these angles]{evans_rotations_2001}\nFollowing the expansion and reorientation, the scattering profile is then calculated using the Debye equation,\\autocite{debye_zerstreuung_1915} this was used over the more efficient Golden Vectors\\autocite{watson_rapid_2013} or Fibonacci sequence\\autocite{svergun_solution_1994} methods as the aim of this work was to assess the application of the PSO method and efficiency was not the initial goal.\nThe agreement between the calculated scattering profile and the experimental input scattering was used as a figure of merit, $\\zeta$, that was to be optimised by the particle swarm algorithm.\nThis $\\zeta$ was a simple $\\chi^2$ value found as follows,\n%\n\\begin{equation}\n\\zeta = \\chi^2 = \\sum\\frac{(I_{\\text{exp}}(q) - I_{\\text{calc}}(q))^2}{\\text{d}I_{\\text{exp}}(q)},\n\\end{equation}\n%\nwhere $I_{\\text{exp}}(q)$ is the experimental scattering intensity, $I_{\\text{calc}}(q)$ is the calculated scattering intensity, and $\\text{d}I_{\\text{exp}}(q)$ is the uncertainty in the experimental scattering intensity, all at a given $q$-vector.\n%\n\\begin{marginfigure}\n \\centering\n\\includegraphics[width=\\linewidth]{smallangle/rotdia}\n \\caption{The definitation of the polar angles used in the coarse grained representation of the surfactant molecule.}\n \\label{fig:rot}\n\\end{marginfigure}\n%\n\nThroughout this work, an interia weight for the PSO of 0.4 was used.\nGenerally, values of between 0 and 2 are used for the global and personal acceleration coefficients\\footnote{These are standard values for the PSO method following \\cite{sun_study_2010}.}.\nFor the test case discussed below a value of 2 was used for both acceleration coefficients, however, in the real case discussed later, the global acceleration coefficient was reduced to 1.\nThis was chosen to reduce the acceleration toward the global best and improve the ability for the PSO to search the parameter space available in this much larger problem.\n\n\\subsection{Parallelisation}\n\\label{sec:para}\nThe use of a population-based optimisation method, such as the PSO, allowed for easy access to highly parallel simulation.\nParallelisation was achieved by spreading the population evenly across the cores that were available to the simulation.\nInter-core messaging was performed using the MPI libraries, and to ensure efficiency only the figures of merit and the best possible structure were shared across the cores.\nThis means that during a given \\texttt{fitoog} run, the only serial component was the determination of the lowest figure of merit.\nThe efficiency of the parallelisation was defined by considering the strong and weak scaling of the software.\nIt was possible to determine the percentage of serial, $s$, and parallel, $p$, components of the software by fitting the speedup\\footnote{The time taken for a job to run on a single core divided by the time taken on multiple cores.} with Amdahl's law,\\autocite{amdahl_validity_1967}\n%\n\\begin{equation}\n\\text{speedup} = \\frac{1}{s + \\sfrac{p}{N}},\n\\end{equation}\n%\nwhere, $N$ is the number of cores in the parallel job, and $s + p = 1$.\nWhile more sophisticated methodologies could be used to further reduce the serial component, such as having a core-level best population that is only occasionally communicated with the entire swarm, this implementation was shown to be highly parallelised and useful for assessing the utility of the PSO method.\n", "meta": {"hexsha": "ec6be661507e0eaa0dbe5e3f8f2d8a1f800a3af0", "size": 6629, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "reports/chapters/smallangle/methods.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/smallangle/methods.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/smallangle/methods.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": 101.9846153846, "max_line_length": 399, "alphanum_fraction": 0.7918238045, "num_tokens": 1593, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.34510527769342453, "lm_q1q2_score": 0.19401007745091106}}
{"text": "% !TEX root = ../zeth-protocol-specification.tex\n\n\\section{\\zeth~statement after primitive instantiation}\\label{instantiation:statement}\n\nAfter instantiating the various primitives and providing security proofs to justify that they comply with the security requirements listed in previous sections, $\\RELCIRC$ now becomes:\n\n\\begin{itemize}\n \\item For each $i \\in [\\jsin]$:\n \\begin{enumerate}\n \\item $ \\auxinputs.\\jsins{i}.\\znote.\\apk = \\blake{2s}{\\taggedaddr \\concat \\pad{0}{\\blakeCompLen}}$ \\\\ with $\\taggedaddr$ defined in~\\cref{instantiation:prf-comm-crh:prf}\n \\item $\\auxinputs.\\jsins{i}.\\nf{} = \\blake{2s}{\\taggednf \\concat \\auxinputs.\\jsins{i}.\\znote.\\rho}$ \\\\ with $\\taggednf$ defined in~\\cref{instantiation:prf-comm-crh:prf}\n \\item $\\auxinputs.\\jsins{i}.\\cm{} = \\blake{2s}{\\auxinputs.\\jsins{i}.\\znote.\\noter{} \\concat \\msg}$ \\\\ with $\\msg = \\auxinputs.\\jsins{i}.\\znote.\\apk \\concat \\auxinputs.\\jsins{i}.\\znote.\\rrho \\concat \\auxinputs.\\jsins{i}.\\znote.\\notev$\n \\item $\\auxinputs.\\htags{i} = \\blake{2s}{ \\taggedpk \\concat \\priminputs.\\hsig}$ (malleability fix, see~\\cref{appendix:trnm}) with $\\taggedpk$ defined in~\\cref{instantiation:prf-comm-crh:prf}\n \\item $(\\auxinputs.\\jsins{i}.\\znote.\\notev) \\cdot (1 - e) = 0$ is satisfied for the boolean value $e$ set such that if $\\auxinputs.\\jsins{i}.\\znote.\\notev > 0$ then $e = 1$.\n \\item The Merkle root $\\mkroot'$ used to check the Merkle authentication path $\\auxinputs.\\jsins{i}.\\mkpath$ of commitment $\\auxinputs.\\jsins{i}.\\cm{}$, with $\\mimcMPPrime{\\rCURVE}$, equals $\\priminputs.\\mkroot$ if $e = 1$.\n \\item $\\priminputs.\\nfs{i}$ \\\\ $= \\indexedset{\\pack{\\slice{\\auxinputs.\\jsins{i}.\\nf{}}{k \\cdot \\fieldBitCap}{(k+1) \\cdot \\fieldBitCap}}{\\FFx{\\rCURVE}}}{k \\in [\\floor{\\prfNfOutLen/\\fieldBitCap}]}$\n \\item $\\priminputs.\\htags{i}$ \\\\ $= \\indexedset{\\pack{\\slice{\\auxinputs.\\htags{i}}{k \\cdot \\fieldBitCap}{(k+1) \\cdot \\fieldBitCap}}{\\FFx{\\rCURVE}}}{k \\in [\\floor{\\prfPkOutLen/\\fieldBitCap}]}$\n \\end{enumerate}\n \\item For each $j \\in [\\jsout]$:\n \\begin{enumerate}\n \\item $\\auxinputs.\\znotes{j}.\\rrho = \\blake{2s}{ \\taggedrho \\concat \\priminputs.\\hsig}$ (malleability fix, see~\\cref{appendix:trnm}) with $\\taggedrho$ defined in~\\cref{instantiation:prf-comm-crh:prf}\n \\item $\\priminputs.\\cms{j} = \\blake{2s}{\\auxinputs.\\znotes{j}.\\noter{} \\concat \\msg }$ \\\\ with $\\msg = \\auxinputs.\\znotes{j}.\\apk \\concat \\auxinputs.\\znotes{j}.\\rrho \\concat \\auxinputs.\\znotes{j}.\\notev$\n \\end{enumerate}\n \\item $\\priminputs.\\hsig = \\indexedset{\\pack{\\slice{\\auxinputs.\\hsig}{k \\cdot \\fieldBitCap}{(k+1) \\cdot \\fieldBitCap}}{\\FFx{\\rCURVE}}}{k \\in [\\floor{\\crhhsigOutLen/\\fieldBitCap}]}$\n \\item $\\priminputs.\\resbits = \\packResBits{\\indexedset{\\auxinputs.\\jsins{i}.\\nf{}}{i \\in [\\jsin]}, \\auxinputs.\\vin, \\auxinputs.\\vout, \\auxinputs.\\hsig, \\indexedset{\\auxinputs.\\htags{i}}{i \\in [\\jsin]}}$\n \\item Check that the ``\\gls{joinsplit} is balanced'', i.e.~check that the \\gls{joinsplit-eq} holds:\n \\begin{align*}\n &\\pack{\\auxinputs.\\vin}{\\FFx{\\rCURVE}} + \\sum_{i \\in [\\jsin]} \\pack{\\auxinputs.\\jsins{i}.\\znote.\\notev}{\\FFx{\\rCURVE}} \\\\\n & = \\sum_{j \\in [\\jsout]} \\pack{\\auxinputs.\\znotes{j}.\\notev}{\\FFx{\\rCURVE}} + \\pack{\\auxinputs.\\vout}{\\FFx{\\rCURVE}}\n \\end{align*}\n\\end{itemize}\n\n\\begin{remark}\n For higher security, we could use \\blake{2b}{} with 32-byte output instead of \\sha{256}. In fact, since a precompiled contract computing the \\blake{2}{}~compression function~\\cite{blakecompietf} has been added to the Istanbul release of \\ethereum~(EIP 152~\\cite{blake-eip}), it could be possible to write a small wrapper on the smart contracts, in order to hash with \\blake{2b}{} with any parameter.\n\\end{remark}\n\n\\subsection{Instantiating the packing functions}\\label{instantiation:statement:pack}\n\nAs we consider SNARKs based on arithmetic circuits defined over a prime field, all variables in the constraint system are interpreted as field elements. Nevertheless, as illustrated in~\\cref{zeth-protocol:statement}, part of the statement consists of functions whose co-domains are sets of binary strings (which may be longer than the bit representation of elements of the finite field). While a bit (i.e.~$\\{0, 1\\}$) is an element of $\\FF_p$ ($p$ prime), it is important to minimize the number of gates in the arithmetic circuit (for proof generation efficiency), and to minimize the number of input wires (to improve verification time). This can be done by representing fragments of binary strings as the base 2 decomposition of field elements, thereby ``packing'' binary strings into multiple elements. Converting binary strings into field elements requires the addition of some arithmetic gates (extending the statement to be proven), but reduces the number of primary inputs (reducing the complexity of the SNARK verification carried out on-chain).\nThe cost of $\\groth$ zk-SNARK~\\cite{groth2016size} proof verification is linear in the number of primary inputs, since each input acts as a scalar in a costly scalar multiplication of a curve point in $\\gset_1$. Hence, while packing slightly increases the prover cost -- by adding constraints to the circuit -- it simplifies the verifier's work.\n\nIn this section, we detail the method by which we encode (resp.~decode) a set of binary strings to (resp.~from) sets of field elements. In the rest of this section, the notion of \\emph{packing policy} refers to the set of \\emph{packing} and \\emph{unpacking} functions.\n\nThe set of primary inputs is composed of the input nullifiers, the output commitments, the public values (see~\\cite[Section 3.4.3]{zethpaper}) along with the signature hash and the authentication tags for security (malleability fix, see~\\cref{appendix:trnm}). The complete description of the public inputs is represented in~\\cref{instantiation:eq:primary-inputs}.\n%\n\\begin{equation}\\label{instantiation:eq:primary-inputs}\n (\\indexedset{\\priminputs.\\nf{i}}{i \\in [\\jsin]}, \\indexedset{\\priminputs.\\cms{j}}{j \\in [\\jsout]}, \\vin, \\vout, \\hsig, \\indexedset{\\priminputs.\\htags{i}}{i \\in [\\jsin]})\n\\end{equation}\n\nThe primary inputs that consist of binary strings are: the nullifiers $\\nfs{}$, the public values $\\vin$ and $\\vout$, the signature hash $\\hsig$ and the authentication tags $\\htags{}$.\n\nFor a binary string $x$, let $\\alpha_x = \\ceil{\\len{x} / \\fieldBitCap}$ be the number of field elements required to completely encode $x$ and let $\\beta_x = \\floor{\\len{x} / \\fieldBitCap}$ be the number of field elements whose capacity is fully used. Let $\\gamma_x = \\len{x} \\pmod{\\fieldBitCap}$ be the number of ``residual'' bits remaining after fully using $\\beta_x$ field elements.\n\n\\begin{example}\\label{instantiation:eg:packing}\n Consider binary strings $A \\in \\bin^7$ of length 7, to be encoded over the field $\\FFx{41}$. This field has a capacity of $5$ bits, and therefore $\\alpha_A = 2$, $\\beta_A = 1$, and $\\gamma_A = 2$. That is, $A$ can be represented as 2 field elements, or as 1 field element with 2 ``residual'' bits.\n\n Consider $A = (1111011)$. \\cref{instantiation:fig:packingA} illustrates how $A$ can be packed as field elements. Note that the 2 residual bits are taken from the ``beginning'' of the bit string, that is, the highest order bits.\n\\end{example}\n\n\\begin{figure}[ht]\n \\centering\n \\includegraphics[width=1\\textwidth]{images/bit-packing-stringA.png}\n \\caption{Packing of string $A$ (see~\\cref{instantiation:eg:packing})}\\label{instantiation:fig:packingA}\n\\end{figure}\n\nWe now consider strategies to pack all primary inputs that are binary strings. A naive approach is to encode each binary string $x$ as $\\alpha_x$ field elements. In general, this results in significant waste (and consequently more field elements than necessary), especially when the number of residual bits is small compared to $\\fieldBitCap$ (see~\\cref{instantiation:fig:packing-multi-strings}). An alternative strategy could be to concatenate all binary strings into a single string $y$ and pack this string into $\\alpha_y$ field elements. While this approach minimizes the set of unused bits, each unpack operation would require different shift and mask operations over 2 or 3 field elements. This significantly increases the complexity of the unpacking operation that must be performed on-chain, resulting in a higher gas cost (due to extra logic) or more contract code (if each unpack operation is hard-coded).\n\nThe \\zeth~protocol requires that each binary string variable $x$ is packed into $\\beta_x$ field elements, and the residual bits from all binary strings, along with the public values $\\vin$ and $\\vout$, are aggregated into a variable $\\resbits$. Let $\\resBitsBLen$ be the total number of residual bits, and $\\resBitsFLen$ be the number of field elements required to represent $\\resbits$. We assume that $\\zvalueLen < \\fieldBitCap$, and define the notation $\\gamma_\\notev = \\zvalueLen$ for the bit lengths of public values $\\vin$ and $\\vout$. Thus $\\resBitsBLen$ is given by\n\\[\n \\resBitsBLen = \\gamma_\\hsig + 2 \\cdot \\gamma_\\notev + \\jsin \\cdot (\\gamma_{\\nf{}} + \\gamma_{\\htag{}} )\n\\]\nand the lengths, in field elements, of each of the correponding public inputs are\n\\begin{align*}\n \\nfFLen &= \\beta_{\\nf{}} \\\\\n \\hsigFLen &= \\beta_{\\hsig} \\\\\n \\htagFLen &= \\beta_{\\htag{}} \\\\\n \\resBitsFLen &= \\ceil{\\resBitsBLen / \\fieldBitCap}\n\\end{align*}\n\n\\begin{figure}[ht]\n \\centering\n \\includegraphics[width=1\\textwidth]{images/bit-packing-multi-strings.png}\n \\caption{Packing of multiple strings. Observe that, by carefully arranging the bits of the input strings, it is possible to output fewer field elements}\\label{instantiation:fig:packing-multi-strings}\n\\end{figure}\n\nThe residual bits $\\resbits$ are formatted as follows:\n\\[\n \\widetilde{\\hsig} \\concat \\widetilde{\\nfs{}} \\concat \\widetilde{\\htags{}} \\concat \\vin \\concat \\vout\n\\]\nwhere $\\widetilde{\\hsig}, \\widetilde{\\nfs{}}, \\widetilde{\\htags{}}$ are, respectively, the $\\gamma_\\hsig, \\gamma_\\nf{}, \\gamma_\\htag{}$ bits.\n\nNote that the public values are packed into the ``last'', or lowest order, $2 \\cdot \\gamma_\\notev$ bits of the resulting field element(s). In this way, their unpack functions are independent of the values $\\jsin$ and $\\jsout$ and of the number of residual bits required for each bit string (and consequently, independent of the finite field used).\n\nTo format the unpacked primary inputs into field elements, we define the following functions.\nGiven a bit string of length less than $\\fieldBitCap$, the algorithm \\pack{}{} (see~\\cref{zeth-protocol:fig:packing-alg}) returns a field element. Given the nullifiers, public values and authentication tags, the algorithm \\packResBits{}{} (see~\\cref{zeth-protocol:fig:packing-resbits-alg}) outputs the residual bits. Given a set of packed field elements and the residual bits, the algorithm \\unpack{}{} returns the variables reassembled as binary strings. In particular, we have that $\\unpack{\\priminputs.\\nfs{}, \\resbits}{\\nf{}} = \\indexedset{\\auxinputs.\\jsins{i}.\\nf{}}{i \\in [\\jsin]}$.\n\\begin{align*}\n &\\pack{}{\\FFx{\\rCURVE}} : \\BB^{\\leq \\fieldBitCap} \\to \\FFx{\\rCURVE} \\\\\n &\\packResBits{} : {(\\BB^\\prfNfOutLen)}^{\\jsin} \\times {(\\BB^\\zvalueLen)}^2 \\times \\BB^\\crhhsigOutLen \\times {(\\BB^\\prfPkOutLen)}^{\\jsin} \\to (\\FFx{\\rCURVE})^\\resBitsFLen \\\\\n &\\unpack{}{} : \\FFx{\\rCURVE}^* \\times (\\FFx{\\rCURVE})^{\\resBitsFLen} \\to \\BB^* \\\\\n\\end{align*}\n\nThe $\\unpack{}{}$ functions for nullifiers, public values and signature hash are represented as follows.\n\\begin{align*}\n &\\unpack{}{}_{\\hsig} : (\\FFx{\\rCURVE})^\\hsigFLen \\times (\\FFx{\\rCURVE})^{\\resBitsFLen} \\to \\BB^\\crhhsigOutLen \\\\\n &\\unpack{}{}_{\\nf{}} : (\\FFx{\\rCURVE})^\\nfFLen \\times (\\FFx{\\rCURVE})^{\\resBitsFLen} \\to \\BB^\\prfNfOutLen \\\\\n &\\unpack{}{}_{\\vin} : \\FFx{\\rCURVE}^0 \\times (\\FFx{\\rCURVE})^{\\resBitsFLen} \\to \\BB^\\zvalueLen \\\\\n &\\unpack{}{}_{\\vout} : \\FFx{\\rCURVE}^0 \\times (\\FFx{\\rCURVE})^{\\resBitsFLen} \\to \\BB^\\zvalueLen\n\\end{align*}\n\n\\begin{figure*}\n \\begin{minipage}[t]{.4\\textwidth}\n \\centering\n \\procedure{\\pack{x}{\\FFx{\\rCURVE}}}{%\n out \\gets 0_{\\FFx{\\rCURVE}}; \\\\\n \\pcfor i \\in [\\len{x}] \\pcdo: \\\\\n \\t \\pcif x[i] = 1 \\pcdo: \\\\\n \\t \\t out \\gets out +_{\\FFx{\\rCURVE}} 2^{\\len{x}-1-i} \\\\\n \\pcreturn out;\n }\n \\caption{Algorithm to pack bits into a field element.}\\label{zeth-protocol:fig:packing-alg}\n \\end{minipage}%\n \\begin{minipage}[t]{.6\\textwidth}\n \\centering\n \\procedure{\\packResBits{\\nfs{}, \\vin, \\vout, \\hsig, \\htags{}}}{%\n out \\gets []; r \\gets \\epsilon; \\\\\n r \\gets \\vout; \\\\\n r \\gets \\vin \\concat r; \\\\\n %\n \\pcfor i \\in [\\jsin] \\pcdo:\\\\\n \\t r \\gets \\slice{\\htags{i}}{\\beta_{\\htags{i}} \\cdot \\fieldBitCap}{} \\concat r; \\\\\n %\n \\pcfor i \\in [\\jsin] \\pcdo:\\\\\n \\t r \\gets \\slice{\\nfs{i}}{\\beta_{\\nfs{i}} \\cdot \\fieldBitCap}{} \\concat r; \\\\\n %\n r \\gets \\slice{\\hsig}{\\beta_{\\hsig} \\cdot \\fieldBitCap}{} \\concat r; \\\\\n %\n \\pcfor i \\in [ \\ceil{\\len{r}/ \\fieldBitCap} ] \\pcdo: \\\\\n \\t out[i] \\gets \\pack{\\slice{r}{i \\cdot \\fieldBitCap}{ (i+1) \\cdot \\fieldBitCap}}{\\FFx{\\rBN}}; \\\\\n \\pcreturn out;\n }\n \\caption{Algorithm to pack residual bits.}\\label{zeth-protocol:fig:packing-resbits-alg}\n \\end{minipage}\n\\end{figure*}\n\n\\subsubsection{Packing Policy Security}\n\\begin{proposition}[Packing security]\n For a binary string $x$, it holds that $\\unpack{\\pack{x}{}}{} = x$ and $\\unpack{\\packResBits{x}}{} = x$.\n\\end{proposition}\n\n\\subsubsection{Packing Policy Example}\n\nIn the case where $\\jsin=\\jsout=2$, the \\BNCurve~is being used (in which field elements hold $\\bnFieldBitCap$ bits) and all PRFs and $\\crhhsig{}$ output bit-strings of length 256, the unpacked primary inputs are 2167-bit long.\nThe packing parameters are therefore:\n\\begin{align*}\n & \\resBitsBLen = 5 \\times 3 + 64 + 64 = 143 \\\\\n & \\nfFLen = \\hsigFLen = \\htagFLen = \\resBitsFLen = 1\n\\end{align*}\nThe packed primary inputs are 2277 bits long, corresponding to a small space overhead of $\\approx 5\\%$ unused bits. Moreover, the 143-bit residual bits can be packed into a single field element. As such, the primary inputs are encoded as 9 field elements.\nFinally, the residual bits are formatted as follows,\n\\[\n \\underbrace{padding}_{\\text{113 bits}}\n \\concat \\underbrace{\\hsig}_{3\\ bits}\n \\concat \\underbrace{\\nf{1}}_{3\\ bits}\n \\concat \\underbrace{\\nf{0}}_{3\\ bits}\n \\concat \\underbrace{\\htag{1}}_{3\\ bits}\n \\concat \\underbrace{\\htag{0}}_{3\\ bits}\n \\concat \\underbrace{\\vin\\vphantom{g}}_{64\\ bits}\n \\concat \\underbrace{\\vout\\vphantom{g}}_{64\\ bits}\n\\]\n\nFor the analogous case using \\BLSCurve (in which field elements hold $\\blsFieldBitCap$ bits), the packing parameters are:\n\\begin{align*}\n & \\resBitsBLen = 5 \\times 4 + 64 + 64 = 148 \\\\\n & \\nfFLen = \\hsigFLen = \\htagFLen = \\resBitsFLen = 1\n\\end{align*}\nThe residual bits can be packed into a single field element of the form\n\\[\n \\underbrace{padding}_{\\text{108 bits}} \\concat \\underbrace{\\hsig}_{4\\ bits} \\concat \\underbrace{\\nf{0}}_{4\\ bits} \\concat \\underbrace{\\nf{1}}_{4\\ bits} \\concat \\underbrace{\\htag{0}}_{4\\ bits} \\concat \\underbrace{\\htag{1}}_{4\\ bits} \\concat \\underbrace{\\vin\\vphantom{g}}_{64\\ bits} \\concat \\underbrace{\\vout\\vphantom{g}}_{64\\ bits}\n\\]\nand the primary inputs are again encoded as 9 field elements.\n", "meta": {"hexsha": "f64818bbb7b110e5e300f5fb6969ab29b7295f3b", "size": 15543, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "chapters/chap03-sec03.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-sec03.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-sec03.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": 85.8729281768, "max_line_length": 1053, "alphanum_fraction": 0.6915009972, "num_tokens": 4773, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621764862150634, "lm_q2_score": 0.3451052574867685, "lm_q1q2_score": 0.19401006102825624}}
{"text": "\n% JuliaCon proceedings template\n\\documentclass{juliacon}\n\\setcounter{page}{1}\n\\usepackage{graphicx}\n\n\\hypersetup{colorlinks=true}\n\\begin{document}\n\n\\input{header}\n\n\\maketitle\n\n\\begin{abstract}\n\nFlux \\cite{innes:2018} is a machine learning framework, written using the numerical computing\nlanguage Julia\\cite{bezanson2017julia}. The framework makes writing layers as simple as\nwriting mathematical formulae, and it's advanced AD,\nZygote \\cite{DBLP:journals/corr/abs-1810-07951} , applies automatic differentiation (AD) to\ncalculate derivatives and train the model. It makes heavy use of Julia's language and\ncompiler features to carry out code analysis and make optimisations. For example, Julia's\nGPU compilation support \\cite{besard:2017} can be used to JIT-compile custom GPU kernels for\nmodel layers \\cite{CuArrays.jl}. Flux also supports a number of a hardware options, from CPUs,\nGPUs and even TPUs via XLA.jl, that compiles Julia code to XLA: an advanced compiler for\nlinear algebra that is capable of greatly optimizing speed and memory usage in large\ndeep learning models. \n\nONNX.jl is an Open Neural Network Exchange backend for the Flux.jl deep learning framework.\nONNX.jl supports directly importing high quality ONNX standard models into Flux, thus saving\ntime and reducing the need for additional computation resources. This paper aims at introducing \nONNX.jl and explaining how it fits into the bigger picture: How we can use the Julia Language, \nspecifically Flux.jl and ONNX.jl as a starting for high quality transfer learning of large deep\nlearning models.\n\n\\end{abstract}\n\n\\section{Introduction}\n\nThe Julia language was introduced to solve the two language problem: In simple words, languages that\nare simple to write (high-level) are very slow but those which are difficult to use (low-level) are\nway faster. This is because most of the high-level languages weren't written to process a large \namount of data. Thus engineers, researchers and developers have a hard time developing a lot of \nhigh performance languages. At the moment, the common protocol is to write the core of the software\nin a low-level language (C/C++/Fortran) and wrap it in a high-level language (Python). This results\nin optimized performance and ease of use. The Julia language aims to make best of both worlds. It \nprovides a high level syntax but manages to perform as fast as C (sometimes even faster). \n\nFlux.jl is a library for implementing machine learning models, written completely in the Julia\nprogramming language. At the heart of Flux.jl lies Zygote.jl: A source-to-source automatic\ndifferentiation (AD) library that makes complete use of the Julia language compiler to generate\nbackward pass during training phase of a neural network, with complete support for control flow,\nrecursion, closures and data structures. \nImplementing models in Flux.jl is as simple as writing regular Julia code. Implementing models\nis as simple as writing the formulae for those, and Zygote.jl will compute the derivatives \nseamlessly. \n\nFlux.jl also provides support for other hardware options using external packages such as CuArrays.jl\nand CLArrays.jl. CuArrays is written completely in Julia, making implementing GPU kernels very simple.\nMaking a model run on GPU can be done in a hassle-free manner: It is as simple as calling a few functions\nto transfer data to GPU. Flux.jl also has support for running models on Google's Tensor Processing\nUnit (TPU). TPUs help in very fast linear algebra computation. Running Flux models on TPUs is possible\nthrough XLA.jl that compiles Julia code to XLA. \n\nThe FluxML ecosystem provides a number of supporting packages that provide additional functionalities , some of them being (apart from the aforementioned Flux.jl, Zygote.jl and XLA.jl);\n\n\\begin{itemize}\n \\item ONNX.jl : Open Neural Network eXchange backend for Flux.jl\n \\item Metalhead.jl \\cite{Metalhead.jl}: Simple plug and play pretrained Flux.jl computer vision models.\n \\item Torch.jl \\cite{Torch.jl}: This package aims at exposing Torch.tensor types in Julia.\n \\item IRTools.jl \\cite{IRTools.jl} : Provides an IR format that is easy to manipulate.\n \\item FluxJS.jl \\cite{FluxJS.jl} : Runs Flux models in the browser, via tensorflow.js\n \\item model-zoo \\cite{model-zoo}: Collection of implementation of various Flux deep learning models.\n\\end{itemize}\n\n\\section{Open Neural Network eXchange (ONNX)}\nOpen Neural Network Exchange (ONNX) \\cite{bai2019} is an open ecosystem that empowers AI developers to\nchoose the right tools as their project evolves. ONNX provides an open source format for AI\nmodels, both deep learning and traditional machine learning. ONNX defines the computation graph for a deep learning model along with various operators used in the model.\nIt provides a set of specifications to convert a model to a basic ONNX format, and\nanother set of specifications to get the model back from this ONNX form. At a high\nlevel, ONNX is designed to allow framework inter-operability. There are many excellent\nmachine learning libraries in various languages : PyTorch \\cite{bai2019} , TensorFlow \\cite{abadi2016tensorflow} , MXNet \\cite{chen2015mxnet} , and Caffe \\cite{jia2014caffe} are\njust a few that have become very popular in recent years, but there are many others as well.\nMachine learning models can be converted to a serialized ONNX format which can then be run\non a number devices. ONNX Runtime is an inference engine written in C++ framework used to \ndeploy ONNX format models into production. It works on diverse hardware and support both\ndeep learning as well as traditional machine learning models.\n\n\\subsection{Where does ONNX come in?}\nONNX is a format for representing deep learning models, which can be further run on numerous devices\nwithout worrying much about the implementation. This helps researchers, developers and engineer to\nfocus on the problem in hand without worrying much about the peripherals, such as the framework\nto use, the ability to run a model trained using this particular framework on specialized hardware.\nONNX is is usable anywhere from small mobile devices to large server farms, across chipsets and vendors,\nand with extensive runtimes and tools support. ONNX reduces the friction of moving trained AI\nmodels among your favorite tools and frameworks and platforms. A simple example of how ONNX is ideal\nfor ML is the case when large deep learning models need to be deployed. Consider \nthe simple case of deploying a Deep Learning model to an iOS application. This particular model can \nbe implemented in any framework : TensorFlow, PyTorch, MXNet just to name a few. However, iOS \napplications expect to use CoreML inside the application. Up until now, developers have been porting\nlarge models to different frameworks,\nwhich is a waste of time and energy, better spent somewhere else. This is also retraining the entire model from scratch, which isn't efficient. This makes the entire process cumbersome and impractical. ONNX exists to solve this very problem : By connecting the common dots from\ndifferent frameworks, ONNX makes it possible to express a model of type A to type B, thus saving time and the need to train the model again. \n\n\\section{ONNX backend in Julia}\n\nONNX.jl is an ONNX backend written in Julia for the Flux.jl machine learning framework. It can be\nused for high-quality inference of pretrained ONNX format machine learning models. At the heart of it, ONNX.jl solves a compiler problem by dealing with intermediate code representations to generate readable graphs. While doing this, ONNX operators are mapped to corresponding Flux layers, thus tracing out the model's computation graph at the end. This graph can then be travelled to generate the Julia code for the model. \n\nThe first step towards reading any ONNX model in Julia is to have access to all the data structures in the model,\nthat essentially hold all the required information to load the model. This information includes everything that\nis used to completely define the model: Hyper-parameters and parameters in the model. So in the case of a simple\nConvolutional Neural Network, this may contain information such as the number of layers, number of units in each \nlayer, strides, padding, kernel size, number of filters as hyper-parameters and the trained values associated\nwith each layer as parameters. \n\nSince ONNX models as protobuf serialized, we need a way to read this serialized data into specific data\nstructures. ProtoBuf.jl is a Julia implementation of protocol buffers that solves this very issue (covered in \nsection 3.1). It is used to read the ONNX model into the generated Julia data structures. Once we have the \nentire model present as a complex Julia structure, we need to read through this structure and map ONNX operators\nto corresponding Flux layers/operations (covered in section 3.2). At the same time, model weights or \nparameters are separately stored and saved externally as BSON serialized file. Once the model has been loaded,\nwe end up with two files: `model.jl`: The Julia code for the machine learning model and `weights.bson`: The \nweights associated with the layers defined in the `model.jl` file (section 3.3). In the further sections we'll walk through the internals of these individual processes \n\n\\subsection{ProtoBuf.jl}\n\n \n\nProtoBuf.jl \\cite{Protobuf.jl} is a Julia implementation of Protocol Buffers. It provides a way to read and write data to and \nfrom Julia types from I/O streams. What ProtoBuf.jl gives from onnx.proto3 is the Julian definition of various\ndata structures that in themselves have all the required attributes to load any ONNX serialized model. As an \nexample, as simple message defined in onnx.proto3 as:\n\n\\begin{lstlisting}[language=julia]\nmessage NodeProto {\n repeated string input = 1; // namespace Value\n repeated string output = 2; // namespace Value\n\n // An optional identifier for this node in a graph.\n // This field MAY be absent in ths version of the\n // IR.\n string name = 3; // namespace Node\n\n // The symbolic identifier of the Operator to \n // execute.\n string op_type = 4; // namespace Operator\n string domain = 7; // namespace Domain\n\n // Additional named attributes.\n repeated AttributeProto attribute = 5;\n\n string doc_string = 6;\n}\n\\end{lstlisting}{}\n\\textit{(Code snippet taken from onnx/onnx.proto3)} \n\nResults in the corresponding Julia definition of the model as :\n\n\\begin{lstlisting}[language=julia]\nmutable struct NodeProto <: ProtoType\n input::Vector{AbstractString}\n output::Vector{AbstractString}\n name::AbstractString\n op_type::AbstractString\n domain::AbstractString\n attribute::Vector{AttributeProto}\n doc_string::AbstractString\n NodeProto(; kwargs...) = (o=new(); fillunset(o); isempty(kwargs) || ProtoBuf._protobuild(o, kwargs); o)\nend\n\\end{lstlisting}\n\nSince ONNX tries to inherit properties from diverse frameworks, ONNX serialized models can be large and complicated. While there are a number of complex generated data structures, three of those are essential towards\nunderstanding how data is stored internally: \n\n\\begin{itemize}\n \\item ModelProto: A very high-level struct that holds all the information. ONNX models are read directly into\n this structure.\n \\item GraphProto: This structure captures the entire computation graph of the model.\n \\item NodeProto and TensorProto: Information regarding individual nodes in the graph (inputs, outputs and finer attributes) and weights associated with the nodes.\n\\end{itemize}\n\n\\subsection{ModelProto}\n\nModelProto structure is the structure that holds all the information needed to load a model. Internally, it holds\ndata such as the version information, model version, docstring, producer details and most importantly: the \ncomputation graph. \\newpage\n\n\\begin{lstlisting}[language=julia]\nmutable struct ModelProto <: ProtoType\n ir_version::Int64\n opset_import::Vector{OperatorSetIdProto}\n producer_name::AbstractString\n producer_version::AbstractString\n domain::AbstractString\n model_version::Int64\n doc_string::AbstractString\n graph::GraphProto\n metadata_props::Vector{StringStringEntryProto}\nend #mutable struct ModelProto\n\\end{lstlisting}\n\nAn ONNX model, once read using ProtoBuf.jl is loaded into this ModelProto object before extracting the graph \ndetails. Naturally, at the heart of this is the \\textit{graph::GraphProto} attribute that stores the computation\ngraph of the model.\n\n\\subsection{GraphProto}\n\nThe GraphProto structure stores information about particular nodes in the graph. This includes\nthe node metadata, name, input, output and the pre-trained parameters in the \\textit{initializer} attribute.\n\n\\begin{lstlisting}[language=julia]\nmutable struct GraphProto <: ProtoType\n node::Vector{NodeProto}\n name::AbstractString\n initializer::Vector{TensorProto}\n doc_string::AbstractString\n input::Vector{ValueInfoProto}\n output::Vector{ValueInfoProto}\n value_info::Vector{ValueInfoProto}\nend #mutable struct GraphProto\n\\end{lstlisting}\n\n\\subsection{TensorProto}\nThis is the main structure that holds the raw model parameters. For example, in comvolutional layers, the weights\nassociated with the kernel as available as dense vectors in the \\textit{raw\\_data} attribute. During graph\ntraversal, these weights are extracted and reshaped according the shape that is available as a node attribute.\n\n\\begin{lstlisting}[language=julia]\nmutable struct TensorProto <: ProtoType\n dims::Vector{Int64}\n data_type::Int32\n segment::TensorProto_Segment\n float_data::Vector{Float32}\n int32_data::Vector{Int32}\n string_data::Vector{Array{UInt8,1}}\n int64_data::Vector{Int64}\n name::AbstractString\n doc_string::AbstractString\n raw_data::Array{UInt8,1}\n double_data::Vector{Float64}\n uint64_data::Vector{UInt64}\nend #mutable struct TensorProto\n\\end{lstlisting}\n\nThis is most of the information needed to build the model. In the next section, we discuss how we use DataFlow.jl to\ntravel this graph and extract model parameters and other relevant information.\n\n\\subsection{Graph operations via DataFlow.jl}\n\nOnce we have the entire model data present as a ModelProto object, the next step is to travel the computation \ngraph and capture all the operation being done in the graph while mapping those simultaneously to the\ncorresponding Flux operators. \n\nDataFlow.jl \\cite{DataFlow.jl} is a code intermediate representation format, representing Julia code as an expression graph. It provides functions for graph re-structuring , even on cyclic graphs. Graphs can then also be used to generate Julia expression. It can be efficiently used to traverse our \\textit{ModelProto.graph} object. However,\nduring this traversal we want to map ONNX operators to Flux layers and functions. In DataFlow.jl, this becomes\nequivalent to creating a new vertex for the required operator and calling in with appropriate Flux functions\n, which are inferred from the ONNX operator itself. As an example, let's consider the simple case of the \n\\textit{BatchNorm} operator in ONNX. Relu is a commonly used activation function in neural networks that can be \nexpressed as :\n\n\\[ relu(x) = max(x, 0) \\]\n\nIt basically just turns negative neurons off (sets them to 0) and bypasses positive neurons. The Relu operator\nin ONNX performs the same operation on an entire vector elementwise. It takes in a single parameter: The input\nvector and returns a single value: the result of applying relu on the input. Using DataFlow.jl, this \noperator is mapped as :\n\\newline \\newline\n\\begin{lstlisting}[language=julia]\nops[:Relu] = function (params, x)\n vcall(broadcast, :relu, x)\nend\n\\end{lstlisting}\n\nThe definition of \\textit{relu} here is defined in Flux: Once the model is written to an external model.jl file,\nwe can include the file directly after importing Flux and all definitions should be ready for use. \n\nOther complex layers such as Convolution have more complicated implementations, but the essence remains the same,\nto collect all inputs and call them with the corresponding Flux function. During this process, model weights \nalso computed and stored in a dictionary, mapping layer name to the parameters. At the end of the graph traversal,\nwe have both the required values: the DataFlow graph containing Flux layers and the model weights corresponding to\neach of these layers. The DataFlow graph can converted to Julia code using \\textit{DataFlow.syntax} that also\nassigns variable names as and when needed. This Julia code is then written to an external \\textit{model.jl} file.\nFor saving the weights, we use the BSON.jl package. BSON stands for Binary JSON, a binary encoded serialization\nof JSON objects. BSON.jl \\cite{BSON.jl} can be used to store and load such structures, our dictionary containing the model weights being one of them.\n\\subsection{Interface and Design:}\nAt a top level, ONNX.jl provides a minimal interface for the user; it is just a tool for loading ONNX format\nmodels. Once the model and weight file has been successfully generated, ONNX.jl provides no further functionality.\nUsers can then treat the resultant model as any other Flux model. \n\n\\begin{lstlisting}[language=Julia]\nusing ONNX, Flux\nONNX.load_model(\"path_to_onnx_file\")\nweights = ONNX.load_weights(\"weights.bson\")\nmodel = include(\"model.jl\")\n\\end{lstlisting}{}\n\n\\textit{ONNX.load\\_model} here generates the required model and weights file. Internally, it carries out all the \nabove mentioned graph operations. \\textit{model} above can be treated as any other Flux model. \n\nThe significant advantage the ONNX.jl provides is that is treats a compiler problem as a graph problem. It \ngenerates the Flux code for the model, which makes it very easy and intuitive to use the same model for\nfurther applications, such as fine-tuning or even replacing existing layers for some other use case. This\nis ideal in the case of applications such as neural style transfer, where it is very common to use a pre-trained\nnetwork and modify it a bit as a starting point. The generated code can also be helpful for finer debugging of \nthe model. \n\nOverall, the entire process from the ONNX serialized file to generation of model and weight file can be\nsummarized as: \n\n\\includegraphics[width=8.8cm]{onnx-3.png}\n\n\\begin{center}\n \\textit{Fig. 1: Flow diagram of ONNX.jl} \n\\end{center}\n\nAdditionally, ONNX.jl also provides helper functions for inspecting the model before loading it. \\textit{ONNX.layers} reads an ONNX file and returns a list of all the layers in the model. With the growing \ninterest around more complicated and deep models, it is possible that an ONNX model might have layers that Flux\nitself doesn't support. For handling these, ONNX.jl leaves a \\textit{hook} for the users to implement\nadditional functionality. A \\textit{hook} is a function that doesn't have an existing implementation: one\nwould have to write an implementation for it themselves. However any operator that also has a corresponding\nimplementation in Flux is completely recognized by ONNX.jl at the moment.\n\n\\section{Usage Scenarios}\nThe ONNX format and ONNX.jl can be used for transfer learning in Flux, where we store knowledge while training a model and\nuse this knowledge for some other task. The idea is that rather than random initialization of parameters for training a neural network, it's better to take an already trained model, since\nit leads to faster convergence. In transfer learning, we take a pretrained model and train it on another \ndataset, which might also have a different class distribution. Fine tuning is an approach to transfer learning\nwhere we train on a subset of training data with a smaller learning rate. Transfer learning learning has shown\ntremendous results in image classification, object detection, simulations, sentiment and NLP based classification \nin recent past. \nThis is also pretty common when talking about tasks such as neural style transfer where we want to change the \nstyle of an image in accordance with the style of another image. Generative Adversarial Networks (GANs) have shown\nto deliver high quality results when trained on top of a pre-trained model. StyleGAN \\cite{DBLP:journals/corr/abs-1812-04948} , for example, can use a\npre-trained model to train a custom model to deliver high quality super-resolution results.\n\n\\section{Related Work}\n\nIn recent times several projects have come up that solve similar issue. One of the most notable project is\nTensorFlow's mlir (Multi-Level Intermediate Representation) \\cite{lattner2020mlir} . mlir is an evolution of LLVM \n\\cite{LLVM:CGO04} that defines a \ncommon Intermediate Representation (IR) format, which can be used to represent any DataFlow graph. This common \nformat unifies machine learning models in TensorFlow or other frameworks. \nOther noteworthy approaches in this direction are PFA and NNVM. PFA \\cite{10.1145/2939672.2939731} or Portable Format for Analytics is a common\nlanguage that aims as easing the transition from development to production. It can be expressed within\nthe common JSON format and has functionalities such as control structures, loops and user-defined functions.\n \nNNVM\\cite{nnvm} is an end-to-end compiler for AI frameworks. It aims at solving the challenges posed by using different\ndiverse machine learning frameworks. It consist if two major components: NNVM (Neural Network Virtual Machine)\nand TVM (Tensor Virtual Machine) \\cite{article} . NNVM defines a common computational graph intermediate representation\nformat and TVM implements the operators used in these computation graphs while optimizing them for the backend hardware.\n\n\\section{Future Work}\n\nAs ONNX.jl becomes the beginning point for various researchers interested in using Julia for their research,\nit is important to note that it also has certain shortcomings. The most significant is that a model can't\nbe completely loaded unless there's an equivalent implementation of the operator in Flux.jl. An example of this\nis Grouped Convolutions. These variants of Convolutional layers were used in AlexNet \\cite{NIPS2012_4824} and showed amazing \nresults. However, since Flux doesn't support these at the moment, the users will need to have an implementation\nready if they choose to import an ONNX model with this particular layer into Flux using ONNX.jl. On the plus side,\na lot of the most commonly used layers are available in Flux and can be readily used. Another thing to note is\nthat to run ONNX.jl generated code in some other hardware, one might need to do a little restructuring. The model\nshould work directly on the CPU. \n\nAnother challenge moving forward is that we need to constantly update ONNX.jl to support Flux's latest API\nchanges. This also applies for the other way round: As ONNX operators are updated, we would have to update these\ncorresponding implementations in ONNX.jl to support the newer models using these updated specifications. Over\nthe long run, we'd need to constantly keep an eye out for such changes and adapt ONNX.jl to those. Moreover,\nthere are subtle differences in the way Flux implements operators as compared to other frameworks. As an example,\nconsider the simple \\textit{AveragePool} layer. The way Flux implements this is by padding the input tensor \nappropriately and then performing the pooling operation. However, Keras-tensorflow does this by pooling and then \npadding. This leads to subtle changes along the edges of the tensor in the output. Such differences occur due to\nthe way most frameworks deal with such layers, and the only way to avoid this is to check for such\ndiscrepancies.\n\nIn recent past, DataFlow.jl has been superseded by another intermediate representation format tool: IRTools.jl. \nIt provides the ability to work with both lowered and typed Julia code and can be used together with \nmetaprogramming tools such as Cassette.jl. \n\nThere has also been some talk about splitting ONNX.jl into two packages: The first one would do the code \ngeneration and DataFlow related functions while the other would be solely responsible for implementation of the\nONNX operators. This would be greater control and ease while implementing layers or debugging a loaded model. This\nshould also make implementation pretty straight-forward wherever missing.\nFor the moment, all this continues to be done by a single package.\n\n\n\n\\section{Conclusion}\n\nDeveloping ONNX.jl has been tremendous learning experience. From studying about Intermediate Representation formats for deep \nlearning models with millions of parameters to loading them in just a couple of lines of code, ONNX.jl has \nmade it very easy and straight-forward to use a high quality trained model as a starting point for many projects.\nOnce such example I'd like to point out is DenseNet-121 model. This is deep convolutional network that has \nmultiple Convolutional, Dense and Pooling blocks. Naturally, implementing this in any framework is going to be\na challenging task. However, thanks to ONNX, we can now use an earlier implementation to import this model into\nany other framework. Importing this model (train in Caffe2) via ONNX.jl into Flux can be done in ~3 lines of code.\n \n\nI was also able to load several large computer vision models loaded from ONNX format at the time of actively\ndeveloping the package. Most of these have been added to FluxML/Metalhead.jl for a direct plug-and-play use. These\nincluded:\n\n\\begin{itemize}\n \\item SqueezeNet \\cite{i2016squeezenet}\n \\item DenseNet 121 \\cite{huang2016densely}\n \\item ResNet 50 \\cite{he2015deep}\n \\item GoogleNet \\cite{szegedy2014going}\n\\end{itemize}\n\n\nONNX.jl serves as a entry point for people looking to use Flux for their research, but want quick results. It \ncombines the power of the Julia language, the elegance of Flux and the availability of a vast number of pre-trained models. This enables researchers to spend time focusing on the real issues, rather than model portability. \\newpage\n\n\\input{bib.tex}\n\n\\end{document}\n\n% Inspired by the International Journal of Computer Applications template\n", "meta": {"hexsha": "f4ec983c23716628d8cc93ff728723a3fceb191d", "size": 26094, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "archives/paper/paper.tex", "max_stars_repo_name": "gwbyeon/ONNX.jl", "max_stars_repo_head_hexsha": "83c7eb0804cea6f2fa277643ff8f5ade7bb616d5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 105, "max_stars_repo_stars_event_min_datetime": "2018-02-11T14:16:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-06T07:02:56.000Z", "max_issues_repo_path": "archives/paper/paper.tex", "max_issues_repo_name": "gwbyeon/ONNX.jl", "max_issues_repo_head_hexsha": "83c7eb0804cea6f2fa277643ff8f5ade7bb616d5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 52, "max_issues_repo_issues_event_min_datetime": "2018-03-15T23:26:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T18:43:47.000Z", "max_forks_repo_path": "archives/paper/paper.tex", "max_forks_repo_name": "gwbyeon/ONNX.jl", "max_forks_repo_head_hexsha": "83c7eb0804cea6f2fa277643ff8f5ade7bb616d5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26, "max_forks_repo_forks_event_min_datetime": "2018-02-09T17:09:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-15T16:27:42.000Z", "avg_line_length": 62.276849642, "max_line_length": 425, "alphanum_fraction": 0.795470223, "num_tokens": 5832, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.19395960471703508}}
{"text": "% !TeX root = ./paper.tex\n\\documentclass[modern]{aastex62}\n\n% Load the corTeX style definitions\n\\input{cortex}\n\n% Bibliography stuff\n\\bibliographystyle{aasjournal}\n\n% Begin!\n\\begin{document}\n\n% Title\n%\\title{Inferring a time dependent map of Io's surface from occultations and phase curves.}\n\\title{Occultation mapping of Io's surface in the near-infrared II: Inferring time variable maps using latent Nonnegative Matrix Factorization}\n\n% Author list\n\\author{Fran Bartoli\\'c}\n\\email{fbartolic@flatironinstitute.org}\n\\affil{Center~for~Computational~Astrophysics, Flatiron~Institute, New~York, NY}\n\\affil{Centre for Exoplanet Science, SUPA, School of Physics and Astronomy, University of St. Andrews, St. Andrews, UK}\n\\author{Rodrigo Luger}\n\\author{Daniel Foreman-Mackey}\n\\affil{Center~for~Computational~Astrophysics, Flatiron~Institute, New~York, NY}\n%\n\n\\begin{abstract}\n \n\\end{abstract}\n\n%\n\\section{Introduction}\n\\section{Data}\n\\label{sec:data}\n\n\\begin{figure}[h!]\n \\begin{centering}\n \\includegraphics[width=0.5\\linewidth]{figures/irtf_max_flux.pdf}\n \\oscaption{irtf_dataset}{%\n Maximum flux for each curve taken using NASA's IRTF telescope during an\n occultation of Io by Jupiter.\n \\label{fig:irtf_max_flux}\n }\n \\end{centering}\n\\end{figure}\n\nThe dataset we use to infer maps of Io's surface consists of 112 observations of Io in the near infrared taken from 1996 until 2018 using various instruments at NASA's IRTF observatory.\nFigure~\\ref{fig:irtf_max_flux} shows the maximum flux in $\\mathrm{GW}/\\mu \\mathrm{m}/\\mathrm{sr}$ for each light curve plotted as a function of time which approximately corresponds to the disc integrated flux of Io at the beginning of ingress or the end of egress prior to it being occulted by Jupiter.\nTwo features of this plot are apparent.\nFirst although the observations span decades the cadence is non-uniform with only a few observations taken between 2008 and 2016.\nSecond, the baseline brightness is varying stochastically by a large amount and there are several notable events of increased volcanic activity.\nAll of the observations were taken while Io was \\emph{in eclipse}, meaning that it was in Jupiter's shadow and all of the observed emission from the surface is due to thermal radiation.\nObservations of Io \\emph{in sunlight} on the other hand probe both the thermal (volcanic) emission and the surface albedo variations in the near infrared.\n\n\n\\begin{figure}[h!]\n \\begin{centering}\n \\includegraphics[width=0.5\\linewidth]{figures/irtf_sample_lightcurves.pdf}\n \\oscaption{irtf_dataset}{%\n A selection of sample light curves taken during occultations of Io by Jupiter in our dataset.\n The step-like morphology of the light curves is due to bright volcanoes on Io's surface coming in or out of view during an occultation.\n These light curves thus visibly encode information about the features on the surface.\n \\label{fig:irtf_sample_lightcurves}\n }\n \\end{centering}\n\\end{figure}\n\nIn Figure~\\ref{fig:irtf_sample_lightcurves} we display a random subset of all the light curves\nin the dataset.\nAll occultations last for $\\sim4$ min and the cadence for each light varies but it on the order of a second.\nIt follows that over the course of a single exposure Jupiter's limb move by about 15km which provides a lower bound for the size of the features on the surface that we can reliably estimate.\nThe shapes of light curves strongly deviate from the smooth variability one would expect assuming a homogeneous distribution of thermal emission on the surface.\nEspecially prominent are light curves with clear step-like features which are present when bright spots come in or out of view during the course of an occultation.\nThe fact that these features are so clearly visible means that even individual light curves encode a wealth of information about the surface.\n\nThe photometric quality varies from year to year because multiple instruments were used over the years.\nAn additional issue is that estimated errorbars aren't provided.\nAs with all ground based photometry, the observations are influenced by atmospheric variability which induces correlated noise in the light curves.\nBecause of this the flux isn't always monotonically increasing or decreasing as one would expect.\nAll of these issues need to be accounted for in the final model.\n\n\\section{Nonnegative Matrix Factorization}\n\\label{sec:nmf}\nIn the case when we cannot assume a static map, the situation is considerably more complicated.\nIn principle, the surface map is different for each \\emph{data point}.\nOf course, fitting one map per data point is intractable so we might instead fit a single map per light curve, generated by Eq.~\\ref{eq:linear_model_pix}.\nEven then, we would need to fit on the order of 1k parameters!\nThis is both becuse the number of spherical coefficients scales as $(l+1)^2$ and because when fitting in pixel space we need many more pixels than spherical harmonics to ensure positivity.\nAlthough fitting a model of such high dimensionality for a single IRTF light curve of high signal to noise ratio is tractable thanks to exact gradients provided by autodifferentiation in \\textsf{starry}, we don't want to do that for a hundred or so separate light curves.\nSuch a model would be very difficult to fit and it would require strong regularization between successive maps in time.\nIt also wouldn't directly provide much physical insight into the volcanic activity, we would have to conduct a separate analysis on the inferred maps to constrain the time variability of the volcanoes.\nInstead, we need an approach which reduces the dimensionality of the problem.\nOne way of accomplishing that is to expand the spherical harmonic coefficients (or pixels) in a Taylor series in time about a certain point.\nThis is the approach \\cite{luger_tess_2019} took to model a map of Earth's albedo in reflected light from stray Earthshine in the aperture of the TESS space telescope.\nThis issue with this approach and similar series expansions such as the Fourier series is that with the very long baseline of IRTF data and the observations being scattered throughout the years sporadically, it is unclear which point should be the origin of the expansion.\nMore importantly, there likely doesn't exist a well defined global time-averaged map of Io so requiring too much smoothness between successive maps wouldn't work.\nAnother way of reducing the dimensionality of the problem would be a parametric approach where where we place a few spots on the sphere and then fit only for the locations and intensities of each spot.\nThis is assuming that we know a priori that the surface features are spot like and roughly how many we should expect.\nWhile such a strong assumption might work for studying individual spots in the context of Io, it certainly isn't justified for exoplanets.\nIn Section~\\ref{sec:inverse_problem} we do assume stronger priors on the locations of and shapes of surface features to better constrain the variability of individual volcanoes, but we still fit for pixels, at least in principle allowing the data to override our assumptions.\n\nThe approach approach opted for is to treat the problem of inferring a single map per light curve as a probabilistic matrix factorization problem.\nThe idea is to assume that a map for any given light curve can be expressed as a linear combination of $K$ \"basis maps\".\nConsider $L$ lightcurves, the model for the $l$-th light curve is\n\\begin{equation}\n \\mathbf{f}_l=\\mathbf{A}_l\\,\\mathbf{P}^\\dagger\\,\\mathbf{p}_l'\n\\end{equation}\nWe can stack the column vectors $\\mathbf{p}_l$ into a matrix $\\mathbf{Y}$ of shape $(N_p, L)$ where $N_p$ is the number of pixels for each light curve.\nWe then assume that the $\\mathbf{Y}$ can be decomposed into a product of two matrices $\\mathbf{B}$ and $\\mathbf{Q}$ as\n\\begin{equation}\n \\mathbb{Y}=\\mathbf{B}\\,\\mathbf{Q}\n \\label{eq:nmf}\n\\end{equation}\nwhere $\\mathbf{B}$ has shape $(N_p, K)$ and $\\mathbf{Q}$ has shape $(K, L)$.\nThe model for all light curves can be written as\n\\begin{equation}\n \\mathbb{f}=\\mathbb{A}\\,\\mathrm{vec}(\\mathbf{\\mathbb{Y}})\n \\label{eq:model_all_lcs}\n\\end{equation}\nWhere $\\mathbf{f}$ is a tall column vector consisting of predictions for all light curves stacked together, $\\mathbb{A}$ is a block diagonal matrix with matrices $\\mathbf{A}_l\\,\\mathbf{P}^\\dagger$ on the diagonal for $l=1\\dots, L$ and the $\\mathrm{vec}$ operator stacks the columns of $\\mathbb{Y}$ into a tall vector.\nThe model is \\emph{bilinear} which means that is linear in the matrices $\\mathbf{B}$ and $\\mathbf{Q}$ separately.\nThe interpretation of Equation~\\ref{eq:nmf} is simple, each of the $K$ columns of $\\mathbf{B}$ represents pixels of a basis map and the columns of $\\mathbf{Q}$ determine how those maps add together to produce a final map for the $l$-th light curve.\nFor this reason we call $\\mathbf{B}$ the \\emph{basis matrix} and the matrix $\\mathbf{Q}$ the \\emph{encoding matrix}.\nIdeally, we want the basis maps to be physically meaningful and the coefficients encode the time variability.\nA nice feature of this model is that there is no requirement that successive maps are smoothly varying between different light curves.\n\nThe matrix factorization problem as written in Equation~\\ref{eq:nmf} is highly degenerate and practically intractable a probabilistic framework with a small dataset.\nSince each of the columns of $\\mathbf{B}$ are pixels representing emitted light or albedo, we can substantially reduce the ambiguity in the decomposition by requiring that both matrices are strictly positive.\nThis matrix factorization problem is known as \\emph{Nonnegative Matrix Factorization} (NMF) \\citep{paatero_positive_1994,lee_algorithms_2001} and it has a rich history across many different fields.\nIt is commonly used for decomposing physical signals in the spectral or the time domain.\nEven though NMF is more tractable than unconstrained matrix factorization, it is still an NP hard problem \\citep{vavasis_complexity_2009} and it requires additional constraints or priors to be tractable.\nSimultaneously transforming $\\mathbf{B}\\leftarrow \\mathbf{B}\\,\\mathbf{S}^{-1}$ and\n$\\mathbf{Q}\\leftarrow \\,\\mathbf{S}\\mathbf{Q}$ with a nonsingular matrix $\\mathbf{S}$ doesn't change the value of the objective function.\nThe objective function is also invariant to a simultaneous permutation of the columns of $\\mathbf{B}$ and rows of $\\mathbf{Q}$ and rescaling either of the two matrices by a scalar.\nNevertheless, getting around these degeneracies in practice is possible, especially when we have a lot of prior knowledge on the problem.\nFor a recent review article with a detalied analysis of these degeneracies and common algorithms, see \\cite{fu_nonnegative_2019}.\n\n\nBroadly, there are two approaches to fitting NMF models, the constrained optimization approach and the probabilistic approach.\nIn the optimization approach we optimize $\\mathbb{Y}$ in a least-squares sense under a set of constraints on either one or both of the matrices \\citep[see][for recent examples from the astronomical literature]{acosta-pulido_new_2017, melchior_scarlet_2018,ren_non-negative_2018,ren_using_2020} with the goal of obtaining a point estimate for the two matrices.\nThe probabilistic approach introduces priors and the inference is usually done with variational inference in order to obtain an approximate posterior distribution over the matrices.\nIn this work we opt for the probabilistic approach because we care about the uncertainties on the map features a lot.\n\nOne difference between most applications of NMF in the literature and NMF within the context of inferring surface maps from 1D light curves is that\nin the majority of the work in the literature \\citep[except][]{kawahara_global_2020} the matrix $\\mathbb{Y}$ is assumed to be directly observed up to a simple noise term.\nIn our case the problem is considerably more challenging because we observe the light curves\n$\\mathbb{A}\\,\\mathrm{vec}(\\mathbf{\\mathbb{Y}})$ instead of $\\mathbb{Y}$ directly, a process in which some information is lost because, depending on the geometry of the occultations, certain combinations of spherical harmonic coefficients will be in the nullspace.\n\\cite{kawahara_global_2020} are using NMF to model phase variations in directly imaged exoplanets with the goal of simultaneously inferring a surface map and a spectral decomposition of the map into several components, a case in which the\nmatrix which is to be decomposed is also unobserved.\nAlthough we don't attempt to solve the problem of spectrally decomposing the maps, our approach is directly applicable to that problem as well. (TODO: should I add more details here?)\nOne could also imagine inferring a multi spectral component and time dependent map by solving two NMF problems simultaneously.\nWe leave this application for future work.\n\n\n\\subsection{The likelihood}\n\\label{ssec:likelihood}\nGiven Eq.~\\ref{eq:nmf} we can write down the likelihood for our data and in Section~\\ref{sec:inverse_problem} we dicuss in detail the priors which make the problems of inferring static and dynamic maps tractable.\nAssuming a Gaussian noise process for the data with a dense covariance matrix, the (log) likelihood is\n\\begin{equation}\n \\ln\\mathcal{L}=-\\frac{1}{2}\\left[\\mathbb{f}_\\mathrm{obs}-(\\mathbb{f} + \\mathbb{b})\\right]^{\\top} \\boldsymbol{\\Sigma}^{-1}\\left[\\mathbb{f}_\\mathrm{obs}-(\\mathbb{f} + \\mathbb{b})\\right]\n\\end{equation}\nwhere $\\mathbb{f}_\\mathrm{obs}$ is the vector of stacked observed light curves, $\\boldsymbol{\\Sigma}$ is the data covariance matrix and $\\mathbb{b}$ is a fixed flux offset per light curve accounting for stray flux not attributed to Io (mostly due to Jupiter).\nWe model the data covariance with a Gaussian Process using the fast Celerite method\\citep{foreman-mackey_fast_2017} as implemented in the \\textsf{exoplanet} package (TODO: cite) to capute correlations imposed by the seeing plus an additional white noise term which is different for each light curve.\nThe IRTF data isn't provided with any uncertainties so we estimate the uncertainties by filtering the data with the Savitzky Golay filter as implemented in \\textsf{SciPy} (TODO: CITE) and estimating the variance of the residuals.\nWe assume identical errors for all data points in a given light curve but allow for a rescaling factor when fitting the model.\nIn the next section, we add priors to this likelihood and fit the model on simulated data using optimization and Variational Inference (VI).\n\n\\section{The inverse problem}\n\\label{sec:inverse_problem}\n\n\\subsection{Fitting a dynamic map}\n\\label{ssec:dynamic_map}\n% Priors for NMF. Optimization vs. bayesian approach to NMF. Results on simulated data. Comparison of results to matrix factorization without the positivity constraint and clever priors.\n\n\\section{Results}\n\\label{sec:results}\n\n\\subsection{Individual events}\n\\label{ssec:individual}\n% Fits of individual events. In particular, those light curves that were analyzed in previous papers.\n\n\\subsection{The time-variable map}\n\\label{ssec:time_variable_map}\n%\n\n\\subsection{Variability of known hotspots}\n\\label{ssec:variability_hotspots}\n% Plot inferred intensities of known hotspots as function of time, reference previous work.\n\n\\section{Mapping volcanic exoplanets}\n\\label{sec:exoplanets}\n% Application to exoplanets. Fitting mock JWST observations.\n\n\\section{Conclusions}\n\\label{sec:conclusions}\n\n% Bibliography\n\\bibliography{bib}\n\\end{document}\n", "meta": {"hexsha": "7d93f5f17a65f41d0e87aa95aa8e9507e3547a1d", "size": 15491, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "paper/paper.tex", "max_stars_repo_name": "fbartolic/volcano_nmf", "max_stars_repo_head_hexsha": "0e07411a49647fa12623b078effe9f28e38ab659", "max_stars_repo_licenses": ["MIT"], "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/paper.tex", "max_issues_repo_name": "fbartolic/volcano_nmf", "max_issues_repo_head_hexsha": "0e07411a49647fa12623b078effe9f28e38ab659", "max_issues_repo_licenses": ["MIT"], "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": "fbartolic/volcano_nmf", "max_forks_repo_head_hexsha": "0e07411a49647fa12623b078effe9f28e38ab659", "max_forks_repo_licenses": ["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.455, "max_line_length": 359, "alphanum_fraction": 0.7905235298, "num_tokens": 3674, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.19395960471703508}}
{"text": "\\section{Background Modelling}\n\\label{sec:background_model}\n\n\n\n\\subsection{Background modeling strategy}\n\\label{ssec:bkg_strategy}\n\nThe strategy for the continuous background modelling follows what traditionally done in $H\\to\\gamma\\gamma$ measurements, with the addition of some dedicated procedures to cope with specific issues related to insufficient MC statistics or very low-statistics categories. This section only contains a simplified description, more details could be found in HGam coupling analysis ~\\ref{ANA-HIGG-2020-16-INT1}. \n\nThe steps comprising the background modelling strategy can be summarised as follows:\n\\begin{itemize}\n\n \\item The composition of the continuous background in term of \\yy, \\yjet and \\jetjet components is estimated with data driven technique for each category entering the measurement, as detailed in \\Sect{\\ref{ssec:bkg_composition}}.\n \\item The background fractions are used to build \\myy background templates for each category entering the measurement, where the \\yy component is obtained from MC, while the \\yjet and \\jetjet components are measured from data driven control regions and used to reweight the \\yy MC, as detailed in \\Sect{\\ref{ssec:bkg_templates}}.\n\n \\item In order to improve the background modeling and reduce the impact of limited MC statistics, a smoothing procedure is being developed to be eventually applied to the background template, provided that the improvements on the results outweight the possible associated systematic uncertainties. \n\n \\item The Spurious Signal approach is used in the smoothed \\yy templates to select a functional form to describe each template, as well as the associated bias that will enter the measurement as a systematic uncertainties, as detailed in \\Sect{\\ref{ssec:spurious_signal}}. The Spurious Signal criteria are defined in order to cope with the limited MC statistics that in some case leads to non-physical large bias measurements.\n\n \\item In very low-statistic categories, defined as those categories with \\textcolor{red}{less than 10 events per bin in the \\myy sidebands}, the smoothing procedure tends to introduce large non-physical structures in the templates, and it is therefore not suited to be used for them. For this reason, for this categories we initially select the statistically-justified function performing a Wald-test on the data sidebands using a family of function based on a exponential of increasing complexity. We accept the simplest function justifies by the Wald-test, and perform the Spurious Signal measurement with this function tolerating a bias that could be larger than the criteria used for the high-statistic categories, but would have a small impact on the overall sensitivity. This procedure is described in \\Sect{\\ref{sssec:bkg_functions}}. \n\n\\end{itemize}\n\n\n\\subsection{Background compositions}\n\\label{ssec:bkg_composition}\n\nThe dominant background entering the invariant mass spectrum comes from SM continuum diphoton production. A large number of photons are produced inside jets due to de decays of neutral mesons to photon pairs. Thus, photon-jet and di-jet events in which the jets are mis-identified as photons represent a non-negligible source of background. Photon-pairs can be also faked from Drell-Yan events in which both electrons are misidentified as photons. However, this background only contributes with a small fraction ($<1\\%$).\n\nThe number of \\yy, \\yjet and \\jetjet events entering each category after the final selection is estimated by means of a double two-dimensional sideband ABCD method~\\cite{ATL-COM-PHYS-2012-592}. This data-driven method extrapolates the fraction of fake photons within the signal region from the composition of the side-band control regions, built by inverting photon identification and isolation requirements. The fractions are calculated individually in each categories and OO bins for the background template building. Table ~\\ref{tab:yyfraction} lists the \\yy fraction in all categories. More details are shown in Appendix ~\\ref{appendix:2x2DSB}. \n\n\\begin{table}[htbp]\n \\centering\n \\begin{tabular}{c|cccc}\n \\toprule\n & TT & TL & LT & LL \\\\ \n \\toprule\n OO bin1 & $0.76 \\pm 0.16$ & $0.90 \\pm 0.10$ & $0.93 \\pm 0.03$ & $0.86 \\pm 0.05$ \\\\ \\hline\n OO bin2 & $0.89 \\pm 0.10$ & $0.81 \\pm 0.10$ & $0.81 \\pm 0.06$ & $0.87 \\pm 0.07$ \\\\ \\hline\n OO bin3 & $0.79 \\pm 0.15$ & $0.75 \\pm 0.12$ & $0.88 \\pm 0.03$ & $0.83 \\pm 0.06$ \\\\ \\hline\n OO bin4 & $0.92 \\pm 0.08$ & $0.81 \\pm 0.09$ & $0.84 \\pm 0.05$ & $0.90 \\pm 0.05$ \\\\ \\hline\n OO bin5 & $0.78 \\pm 0.14$ & $0.81 \\pm 0.10$ & $0.86 \\pm 0.05$ & $0.88 \\pm 0.07$ \\\\ \\hline\n OO bin6 & $0.88 \\pm 0.10$ & $0.87 \\pm 0.09$ & $0.88 \\pm 0.05$ & $0.83 \\pm 0.04$ \\\\\n \\bottomrule\n \\end{tabular}\n \\caption{\\yy fraction calculated with double two-dimensional sideband ABCD method. \\yjet and \\jetjet components are merged together in following analysis, so the fraction is $1-f_{\\yy}$. }\n \\label{tab:yyfraction}\n\\end{table}\n\n\\begin{figure}[tbp]\n \\centering\n \\includegraphics[width=0.45\\linewidth]{figure/bkgtmpls/TT/yyfrac_TT.png}\n \\includegraphics[width=0.45\\linewidth]{figure/bkgtmpls/TL/yyfrac_TL.png} \\\\\n \\includegraphics[width=0.45\\linewidth]{figure/bkgtmpls/LT/yyfrac_LT.png}\n \\includegraphics[width=0.45\\linewidth]{figure/bkgtmpls/LL/yyfrac_LL.png} \n \\caption{\\yy, \\yjet, \\jetjet fraction in TT(upper left), TL(upper right), LT(bottom left), LL(bottom right) categories, as a function of OO. }\n \\label{fig:yyfraction}\n\\end{figure}\n\n\n\n\\clearpage\n\\subsection{Background templates}\n\\label{ssec:bkg_templates}\n\nConsidering the low \\jetjet fraction and similar performance of \\yjet and \\jetjet, those two components are merged together as \\yjet+\\jetjet for the background estimation. The shape is determined with a data control region, in TT, TL and LT categories it is defined as at least one of the two selected photons fail the tight identification and loose isolation requirement due to insufficient MC statistics, and in LL category it is defined as inverting the identification and isolation of exactly one of two photon candidates.\nContamination from \\yy has been tested to be ignorable as shown in Figure ~\\ref{fig:yjCR}, and a \\textcolor{red}{linear} reweighting is derived to match the \\yy and control region shapes. The bin width for ratio function smoothing varies from 5GeV, 2GeV, 1GeV and 0.5GeV respectively in TT, TL, LT, LL categories to match the MC statistics for an un-biased result. Uncertainty of this reweighted template contains two part: from the choice of smoothing function and from \\yy fraction, while the latter is dominant. \nThese derived shapes are combined with the measured relative event fractions to obtain the total background shape. The \\yy fraction is measured as mentioned in ~\\ref{ssec:bkg_composition} \\\\\n\nThe obtained templates show a good agreement when comparing them with events in data passing the nominal selection (with tight photon identification and isolation cuts, TI) in the sidebands, as shown in \\Fig{\\ref{fig:BkgData-MC}}.\\\\\n\n\\clearpage\n\\begin{figure}[htbp]\n \\centering\n \\subfloat[TT category OO bin1]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgtmpls/TT/CR/b1.png} }\n \\subfloat[TT category OO bin2]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgtmpls/TT/CR/b2.png} }\n \\subfloat[TT category OO bin3]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgtmpls/TT/CR/b3.png} } \\\\\n \\subfloat[TT category OO bin4]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgtmpls/TT/CR/b4.png} }\n \\subfloat[TT category OO bin5]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgtmpls/TT/CR/b5.png} }\n \\subfloat[TT category OO bin6]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgtmpls/TT/CR/b6.png} } \\\\\n \\subfloat[TL category OO bin1]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgtmpls/TL/CR/b1.png} }\n \\subfloat[TL category OO bin2]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgtmpls/TL/CR/b2.png} }\n \\subfloat[TL category OO bin3]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgtmpls/TL/CR/b3.png} } \\\\\n \\subfloat[TL category OO bin4]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgtmpls/TL/CR/b4.png} }\n \\subfloat[TL category OO bin5]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgtmpls/TL/CR/b5.png} }\n \\subfloat[TL category OO bin6]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgtmpls/TL/CR/b6.png} } \\\\\n\\end{figure}\n\\clearpage\n\\begin{figure}[htbp]\n\\centering\n \\subfloat[LT category OO bin1]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgtmpls/LT/CR/b1.png} }\n \\subfloat[LT category OO bin2]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgtmpls/LT/CR/b2.png} }\n \\subfloat[LT category OO bin3]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgtmpls/LT/CR/b3.png} } \\\\\n \\subfloat[LT category OO bin4]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgtmpls/LT/CR/b4.png} }\n \\subfloat[LT category OO bin5]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgtmpls/LT/CR/b5.png} }\n \\subfloat[LT category OO bin6]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgtmpls/LT/CR/b6.png} } \\\\\n \\subfloat[LL category OO bin1]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgtmpls/LL/CR/b1.png} }\n \\subfloat[LL category OO bin2]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgtmpls/LL/CR/b2.png} }\n \\subfloat[LL category OO bin3]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgtmpls/LL/CR/b3.png} } \\\\\n \\subfloat[LL category OO bin4]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgtmpls/LL/CR/b4.png} }\n \\subfloat[LL category OO bin5]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgtmpls/LL/CR/b5.png} }\n \\subfloat[LL category OO bin6]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgtmpls/LL/CR/b6.png} } \\\\\n \\caption{Control region data in all categories and OO bins.}\n \\label{fig:yjCR}\n\\end{figure}\n\\clearpage\n\n\\begin{figure}[htbp]\n \\centering\n \\subfloat[TT category OO bin1]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgtmpls/TT/reweight/b1.png} }\n \\subfloat[TT category OO bin2]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgtmpls/TT/reweight/b2.png} }\n \\subfloat[TT category OO bin3]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgtmpls/TT/reweight/b3.png} } \\\\\n \\subfloat[TT category OO bin4]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgtmpls/TT/reweight/b4.png} }\n \\subfloat[TT category OO bin5]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgtmpls/TT/reweight/b5.png} }\n \\subfloat[TT category OO bin6]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgtmpls/TT/reweight/b6.png} } \\\\\n \\subfloat[TL category OO bin1]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgtmpls/TL/reweight/b1.png} }\n \\subfloat[TL category OO bin2]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgtmpls/TL/reweight/b2.png} }\n \\subfloat[TL category OO bin3]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgtmpls/TL/reweight/b3.png} } \\\\\n \\subfloat[TL category OO bin4]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgtmpls/TL/reweight/b4.png} }\n \\subfloat[TL category OO bin5]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgtmpls/TL/reweight/b5.png} }\n \\subfloat[TL category OO bin6]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgtmpls/TL/reweight/b6.png} } \\\\\n\\end{figure}\n\\clearpage\n\\begin{figure}[htbp]\n\\centering\n \\subfloat[LT category OO bin1]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgtmpls/LT/reweight/b1.png} }\n \\subfloat[LT category OO bin2]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgtmpls/LT/reweight/b2.png} }\n \\subfloat[LT category OO bin3]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgtmpls/LT/reweight/b3.png} } \\\\\n \\subfloat[LT category OO bin4]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgtmpls/LT/reweight/b4.png} }\n \\subfloat[LT category OO bin5]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgtmpls/LT/reweight/b5.png} }\n \\subfloat[LT category OO bin6]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgtmpls/LT/reweight/b6.png} } \\\\\n \\subfloat[LL category OO bin1]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgtmpls/LL/reweight/b1.png} }\n \\subfloat[LL category OO bin2]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgtmpls/LL/reweight/b2.png} }\n \\subfloat[LL category OO bin3]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgtmpls/LL/reweight/b3.png} } \\\\\n \\subfloat[LL category OO bin4]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgtmpls/LL/reweight/b4.png} }\n \\subfloat[LL category OO bin5]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgtmpls/LL/reweight/b5.png} }\n \\subfloat[LL category OO bin6]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgtmpls/LL/reweight/b6.png} } \\\\\n \\caption{Reweight \\yy MC with a linear function to match the \\yjet+\\jetjet shape in each bins and categories.}\n \\label{fig:yyReweight}\n\\end{figure}\n\\clearpage\n\n\\begin{figure}[htbp]\n \\centering\n \\subfloat[TT category OO bin1]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgtmpls/TT/raw_tmpl/b1.png} }\n \\subfloat[TT category OO bin2]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgtmpls/TT/raw_tmpl/b2.png} }\n \\subfloat[TT category OO bin3]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgtmpls/TT/raw_tmpl/b3.png} } \\\\\n \\subfloat[TT category OO bin4]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgtmpls/TT/raw_tmpl/b4.png} }\n \\subfloat[TT category OO bin5]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgtmpls/TT/raw_tmpl/b5.png} }\n \\subfloat[TT category OO bin6]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgtmpls/TT/raw_tmpl/b6.png} } \\\\\n \\subfloat[TL category OO bin1]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgtmpls/TL/raw_tmpl/b1.png} }\n \\subfloat[TL category OO bin2]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgtmpls/TL/raw_tmpl/b2.png} }\n \\subfloat[TL category OO bin3]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgtmpls/TL/raw_tmpl/b3.png} } \\\\\n \\subfloat[TL category OO bin4]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgtmpls/TL/raw_tmpl/b4.png} }\n \\subfloat[TL category OO bin5]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgtmpls/TL/raw_tmpl/b5.png} }\n \\subfloat[TL category OO bin6]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgtmpls/TL/raw_tmpl/b6.png} } \\\\\n\\end{figure}\n\\clearpage\n\\begin{figure}[htbp]\n\\centering\n \\subfloat[LT category OO bin1]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgtmpls/LT/raw_tmpl/b1.png} }\n \\subfloat[LT category OO bin2]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgtmpls/LT/raw_tmpl/b2.png} }\n \\subfloat[LT category OO bin3]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgtmpls/LT/raw_tmpl/b3.png} } \\\\\n \\subfloat[LT category OO bin4]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgtmpls/LT/raw_tmpl/b4.png} }\n \\subfloat[LT category OO bin5]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgtmpls/LT/raw_tmpl/b5.png} }\n \\subfloat[LT category OO bin6]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgtmpls/LT/raw_tmpl/b6.png} } \\\\\n \\subfloat[LL category OO bin1]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgtmpls/LL/raw_tmpl/b1.png} }\n \\subfloat[LL category OO bin2]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgtmpls/LL/raw_tmpl/b2.png} }\n \\subfloat[LL category OO bin3]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgtmpls/LL/raw_tmpl/b3.png} } \\\\\n \\subfloat[LL category OO bin4]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgtmpls/LL/raw_tmpl/b4.png} }\n \\subfloat[LL category OO bin5]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgtmpls/LL/raw_tmpl/b5.png} }\n \\subfloat[LL category OO bin6]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgtmpls/LL/raw_tmpl/b6.png} } \\\\\n \\caption{Final background templates.}\n \\label{fig:BkgData-MC}\n\\end{figure}\n\\clearpage\n\n\n\\subsubsection{Background smoothing}\n\\label{ssec:bkg_smoothing}\n\\textcolor{red}{Need Simplification} \\\\\n\nBecause of the limited statistics of the simulation samples used in the calculation, the value\nof the spurious signal systematic uncertainty is subject to significant statistical fluctuations within\nmany of the analysis categories~\\cite{Hyneman:2712576}. Statistical fluctuations in the background-only sample may cause\nsignal-like bumps, which are then fit as signal by the spurious signal procedure. These statistical fluctuations do\nnot capture the shape mismodeling from the analytic function, and they often drastically inflate the\nvalue of the systematic.\n\nAlthough simply producing additional simulation samples would alleviate the issue of statistical\nfluctuations fitted as spurious signal, producing more simulated events is computationally\nexpensive. Additionally, producing events which fall into specific phase spaces is often highly inefficient. \nTherefore, an alternative solution using the available simulation samples is preferred. \n\nA Gaussian Process (GP) is defined as a set of random processes, where all finite subsets of these\nprocesses have a multivariate normal distribution~\\cite{ebden2015gaussian}. \nGiven a finite dataset – such as the bin contents of a smooth histogram – with corresponding\nmean and covariance matrices, a Gaussian Process may be defined. The “correct” mean and the\ncovariance, however, are not necessarily well defined, as they encode specific assumptions about\nthe underlying dataset. In practice, the two quantities are fit to a finite dataset using a minimization\nalgorithm. In the case of a one-dimensional histogram with a finite number of bins, the mean can\nbe interpreted as a “rough” description of the underlying shape. The diagonal elements of the\ncovariance matrix represent the error of each bin while the off-diagonal elements specify\nhow “similar” the bin content of two different bins should be.\n\nThe covariance matrix can be simplified through the introduction of a kernel, which analytically\ndetermines the level of correlation between two distinct points (i.e., the length scales in X at which points are expected to influence one another in Y). Two useful kernels are the Radial Basis Function (RBF) kernel and the Gibbs kernel~\\cite{3569,Gibbs}. \n\nThe RBF kernel has one hyperparameter, the constant length scale $l$, and it is defined as\n\n\\begin{equation}\nK_\\text{RBF}(x,x') = exp\\left(\\frac{-(x-x')^2}{2l^2}\\right)\n\\end{equation}\n\nThe RBF kernel is useful for mostly-flat functions. However, for smoothly-falling functions, it is likely that nearby points will be more correlated in some regions than in others, so a constant length scale is a suboptimal model. The Gibbs kernel allows the length scale $l(x)$ to vary linearly as a function of $x$, and thus has two hyperparameters: the initial length scale and the length scale slope. The Gibbs kernel function is: \n\n\\begin{equation}\nK_\\text{Gibbs}(x, x') = \\frac{\\sqrt{2l(x)l(x')}}{l(x)^2 + l(x')^2 } \\cdot exp\\left( \\frac{-(x-x')^2}{l(x)^2 + l(x')^2} \\right)\n\\end{equation}\n\n\nThe background templates used in the spurious signal test for the analysis categories are all smooth,\nroughly exponentially falling distributions with statistical fluctuations. Fitting a background template\nusing Gaussian Process Regression (using the Gibbs kernel with the errors as determined by the initial templates) \noffers a consistent method of estimating the underlying smooth shape of the template, without the problematic fluctuations. \nNotably, the GP smoothing technique makes no assumption on the underlying distribution other than that it is smooth and falling, hence the choice of functional form from the spurious signal test will not be biased.\n\nThe hyperparameters (initial length scale and length scale slope) are allowed to vary over a range specified by the user; the optimal hyperparameters within this range are determined by the Gaussian Process fitting procedure.\n\nA GP is fit to the original (noisy) background template in each category. The GP mean in the fits is defined as an exponential function,\nthe parameters of which are obtained by a fit to the original background template. The exponential\nshape has been observed to be a sufficiently close guess for the categories used by the analysis.\nHowever, in cases where the input template has very few statistics (less than about ten events per\nbin on average), the resulting GP fit may be nearly identical to the mean exponential shape. This\nissue occurs when the statistical uncertainties of the original template are so large that the template\nis fully compatible with the preliminary exponential shape. Although the exponential shape\nis technically an adequate descriptor of the template shape, the choice of the exponential mean\ndoes bias the functional choice of the spurious signal test in this case. Therefore, a check has been\nadded to re-perform the GP fit using a flat mean in cases where the resulting GP shape and the\nmean exponential shape disagree with a $\\chi^2/DoF < 0.1$.\n\nThe resulting smoothed shape obtained from the GP fit is then saved as a new histogram. This\nsmoothed histogram is passed as the background template to the spurious signal test, which then\ndetermines the background functional form and spurious signal systematic uncertainty as described\nin \\Sect{\\ref{ssec:spurious_signal}}.\n\nNote that based on previous study, the GPR method can only remain effectively unbiased for smoothly-falling templates containing more than an average of 20 Monte Carlo events/ bin ~\\cite{ATLAS-CONF-2020-026}. \nThe TT and TL categories in this analysis even do not have sufficient statistics for GPR. Only LT and LL categories used this method, and the treatment of TT and TL is discussed in Section ~\\ref{sssec:bkg_functions}. \n\nExamples of the smoothed templates are presented in \\Fig{\\ref{fig:exampleGPR}} for a sample category with a high\nlevel of statistics and for a category with a very low level of statistics.\nThe original templates are shown as well, for comparison. The data sidebands are also shown for\nvalidation, although the GP smoothing technique does not take into account the data sidebands.\n\n\\begin{figure}[htbp]\n \\centering\n \\subfloat[LT category OO bin1]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgtmpls/LT/smooth_tmpl/b1.png} }\n \\subfloat[LT category OO bin2]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgtmpls/LT/smooth_tmpl/b2.png} }\n \\subfloat[LT category OO bin3]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgtmpls/LT/smooth_tmpl/b3.png} } \\\\\n \\subfloat[LT category OO bin4]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgtmpls/LT/smooth_tmpl/b4.png} }\n \\subfloat[LT category OO bin5]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgtmpls/LT/smooth_tmpl/b5.png} }\n \\subfloat[LT category OO bin6]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgtmpls/LT/smooth_tmpl/b6.png} } \\\\\n \\subfloat[LL category OO bin1]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgtmpls/LL/smooth_tmpl/b1.png} }\n \\subfloat[LL category OO bin2]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgtmpls/LL/smooth_tmpl/b2.png} }\n \\subfloat[LL category OO bin3]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgtmpls/LL/smooth_tmpl/b3.png} } \\\\\n \\subfloat[LL category OO bin4]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgtmpls/LL/smooth_tmpl/b4.png} }\n \\subfloat[LL category OO bin5]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgtmpls/LL/smooth_tmpl/b5.png} }\n \\subfloat[LL category OO bin6]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgtmpls/LL/smooth_tmpl/b6.png} } \\\\\n \\caption{LT and LL category background templates after GPR smooth.}\n \\label{fig:exampleGPR}\n\\end{figure}\n\n\n%The smoothed background templates used in this analysis and the spurious signal values extracted from them can be found in the \\App{\\ref{sec:GPR_templates}}.\n\n\n%Extensive validation tests were performed with the GP smoothing technique in order to ensure that the smoothing itself does not introduce a substantial bias. These tests primarily use “toy” templates – randomly-generated background templates constructed from either simulated diphoton events or from the probability distribution function of a known analytic function. We find that GPR remains effectively unbiased for smoothly-falling templates containing more than an average of 20 Monte Carlo events/ bin. These procedures to validate the GPR smoothing are reported in \\App{\\ref{sec:GPR_validation}}.\n\n\n\n\n\n\\subsection{Spurious signal test}\n\\label{ssec:spurious_signal}\n\nThe background \\myy shape, for each analysis category, is described using an analytic function whose parameters and normalization are fitted to data. The choices for the analytic function that has been considered are:\n\\begin{itemize}\n\\item Exponential Function: $f(\\myy) = e^{c\\cdot \\myy}$\n\\item Exponential Function of $2^{nd}$ Order Polynomial: $f(\\myy) = e^{c_1\\cdot m^2_{\\gamma\\gamma}+c_2\\cdot \\myy}$\n\\item Exponential Function of $3^{nd}$ Order Polynomial: $f(\\myy) = e^{c_1\\cdot m^3_{\\gamma\\gamma}+c_2\\cdot m^2_{\\gamma\\gamma}+c_3\\cdot \\myy}$\n\\item Bernstein polynomial of order $N$: $B_{N}(\\myy) = \\sum_{i=0}^N c_i\\cdot b_{i,N}$ with $b_{i,N} = \\begin{pmatrix}N\\\\i\\end{pmatrix}\\myy^i (1-\\myy)^{N-i}$, N=3, 4, 5\n\\item First-Order Power Law Function: $f(\\myy) = \\myy^c$\n\\end{itemize}\nThe method to select the functional form in each category is based on the spurious signal. The spurious signal test is described in more detail in \\cite{Hasib:2238687}.\n\nTo perform the spurious signal test, the full analytic signal plus background model is fitted to a background-only template for each category separately. The fit is performed in the nominal diphoton mass range of $105 \\leq \\myy \\leq \\SI{160}{\\GeV}$. The number of fitted signal events as a function of the Higgs mass is computed in intervals of \\SI{1}{\\GeV} within the diphoton mass range of $120 \\leq \\myy \\leq \\SI{130}{GeV}$. Negative fluctuations are taken into account. The number of spurious signal events $N_{sp}$ is then defined as the maximum of the absolute value of the fitted number of signal events within the signal diphoton mass sub-range. The statistical error is always taken into account.\n\nThe choice of analytic function is done such that the function satisfies at least one of the following criteria:\n\\begin{itemize}\n\\item $N_{sp}$ < 10\\% $N_{s,exp}$, where $N_{s,exp}$ is the expected number of signal events within the SM in the category ($\\mu_{sp} = N_{sp} / N_{s,exp}$)\n\\item $N_{sp}$ < 20\\% $\\sigma_{bkg}$, where $\\sigma_{bkg}$ is the statistical uncertainty on the fitted number of signal events, when fitting the signal+background model to a background only Asimov dataset ($Z_{sp} = N_{sp} / \\sigma_{bkg}$).\n\\end{itemize}\n\nIf multiple functions pass the test, then the one with the least number of parameters is chosen.\n\n%The study including all the categories (also non-ttH) will be performed in the future in accordance with the method described in the previous iteration of the analysis. Due to the higher statistics, new functions (with more parameters) might be needed for the high statistics event categories, as for example the ggH categories. For the ttH only analysis, this does not need to be done.\n%These should pass at least the \n%Due to the limitation of MC statistic amount, \n A relaxed spurious signal criteria, that are made to accommodate $2\\sigma$ local statistical fluctuations in the MC template, in case the MC statistics is small compared to the expected signal. This is done by defining a new variable:\n\\begin{align}\n \\zeta_{sp} = \n \\begin{cases}\nN_{sp} + 2\\Delta_{MC},~~~~ N_{sp} + 2\\Delta_{MC}<0\\\\\nN_{sp} - 2\\Delta_{MC},~~~~ N_{sp} - 2\\Delta_{MC}>0\\\\\n0, ~~~~~~~~~~~~~~~~~~~~~~~\\text{otherwise}\\\\\n\\end{cases}\n \\label{eq:relSpuriousSignalMetric}\n\\end{align}\nwhere $\\Delta_{MC}$ is a local statistical fluctuation of the MC background template. This is illustrated in \\Fig{\\ref{fig:relaxed_ss_cartoon}}. This newly defined variable should then pass the criteria as $N_{sp}$ before. \n\nFor categories with at least 100 data events in the sideband regions defined as $105 < m_{\\gamma\\gamma} < 120$ GeV or $130 < m_{\\gamma\\gamma} < 160$ GeV, the background functions are selected to result in a $|S_{\\text{spur}}|$ that is smaller than either 10\\% of the total expected Higgs boson signal event ($S_{\\text{exp}}$) or 20\\% of the statistical uncertainty of the fitted signal yield ($\\sigma_{\\text{exp}}$). The fit of the analytic function to the background template is required to yield a $\\chi^2$ probability of at least $1\\%$~\\footnote{The $\\chi^2$ is computed with a background template uniformly binned over $105= \\lambda_{\\mathrm{data}})$ with the $\\lambda$ measured in data ($\\lambda_{\\mathrm{data}}$).\nThis procedure to reject simpler background function is called Wald test.\n\nFigure ~\\ref{fig:Wtest} shows plots of the Wald-test on the low-statistic categories. All of the categories selected exponential function as the final decison.\nWhere the lowest P-value among all categories are around 3$\\%$, corresponding to a significance of 2.2 $\\sigma$ standard deviations. \nThe background uncertainty for these categories will be the spurious signal from exponential function.\n\nAs a cross-check, a F-test is also performed in Appendix ~\\ref{append:ss}, and we draw the same conclusion that all of the categories can select exponential function.\nThe reason we use Wald test to decide the background function is the fits on side-band data are un-bin fit (so that it's consistent with the final result), \n there might be bias if we calculate the $\\chi^2$ values in an artifical bin-size for the F-test. In this case the Wald test based on likelihood ratio is more reliable.\n\n\\begin{figure}[htbp]\n \\centering\n \\subfloat[TT category OO bin1]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgtmpls/TT/wald/b1.png} }\n \\subfloat[TT category OO bin2]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgtmpls/TT/wald/b2.png} }\n \\subfloat[TT category OO bin3]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgtmpls/TT/wald/b3.png} } \\\\\n \\subfloat[TT category OO bin4]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgtmpls/TT/wald/b4.png} }\n \\subfloat[TT category OO bin5]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgtmpls/TT/wald/b5.png} }\n \\subfloat[TT category OO bin6]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgtmpls/TT/wald/b6.png} } \\\\\n \\subfloat[TL category OO bin1]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgtmpls/TL/wald/b1.png} }\n \\subfloat[TL category OO bin2]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgtmpls/TL/wald/b2.png} }\n \\subfloat[TL category OO bin3]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgtmpls/TL/wald/b3.png} } \\\\\n \\subfloat[TL category OO bin4]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgtmpls/TL/wald/b4.png} }\n \\subfloat[TL category OO bin5]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgtmpls/TL/wald/b5.png} }\n \\subfloat[TL category OO bin6]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgtmpls/TL/wald/b6.png} } \\\\\n \\caption{Wald test in TT and TL categories. In all OO bins the first order exponential function shows the lower p value and is selected.}\n \\label{fig:Wtest}\n\\end{figure}\n\n\n\n\n\\subsection{Background modelling results}\n\\label{ssec:bck_results}\n\nThe determined analytical functions modeling the baground in each category entering the measureument are found in Table~\\ref{tab:spurious_sig} , as well as the corresponsing Spurious Signal bias.\nThe background only fit on the background templates based on MC samples is shown in Figure ~\\ref{fig:bkgonly}\n\n\n\\begin{table}[htbp]\n\\centering\n\\small\n\\begin{tabular}{l|l|l|l|l|l|l|l|l}\n\\hline\n & \\multicolumn{2}{c|}{TT} & \\multicolumn{2}{c|}{TL} & \\multicolumn{2}{c|}{LT} & \\multicolumn{2}{c|}{LL} \\\\ \\hline\n & Selected func. & maxS & Selected func. & maxS & Selected func. & maxS & Selected func. & maxS \\\\ \\hline \\hline\nbin0 & Exp & -0.29 & Exp & -0.468 & Exp & 0.87 & Exp & 0.885 \\\\ \\hline\nbin1 & Exp & 0.582 & Exp & -0.882 & Exp & -0.534 & Exp & 1.54 \\\\ \\hline\nbin2 & Exp & 0.235 & Exp & -0.355 & Pow & 0.437 & ExpPoly2 & -1.64 \\\\ \\hline\nbin3 & Exp & 0.409 & Exp & -0.304 & Pow & 0.642 & Exp & -0.718 \\\\ \\hline\nbin4 & Exp & -0.404 & Exp & 0.779 & Exp & 0.775 & Exp & -1.19 \\\\ \\hline\nbin5 & Exp & 0.293 & Exp & 0.408 & Exp & 0.627 & Exp & 0.52 \\\\ \\hline\n\\end{tabular}\n\\caption{The final background modelling decision and the size of spurious signal uncertainties.}\n\\label{tab:spurious_sig}\n\\end{table}\n\n\n\\begin{figure}[htbp]\n \\centering\n \\subfloat[TT category OO bin1]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgfit/TT/b1.pdf} }\n \\subfloat[TT category OO bin2]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgfit/TT/b2.pdf} }\n \\subfloat[TT category OO bin3]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgfit/TT/b3.pdf} } \\\\\n \\subfloat[TT category OO bin4]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgfit/TT/b4.pdf} }\n \\subfloat[TT category OO bin5]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgfit/TT/b5.pdf} }\n \\subfloat[TT category OO bin6]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgfit/TT/b6.pdf} } \\\\\n \\subfloat[TL category OO bin1]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgfit/TL/b1.pdf} }\n \\subfloat[TL category OO bin2]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgfit/TL/b2.pdf} }\n \\subfloat[TL category OO bin3]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgfit/TL/b3.pdf} } \\\\\n \\subfloat[TL category OO bin4]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgfit/TL/b4.pdf} }\n \\subfloat[TL category OO bin5]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgfit/TL/b5.pdf} }\n \\subfloat[TL category OO bin6]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgfit/TL/b6.pdf} } \\\\\n\\end{figure}\n\\clearpage\n\\begin{figure}[htbp]\n\\centering\n \\subfloat[LT category OO bin1]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgfit/LT/b1.pdf} }\n \\subfloat[LT category OO bin2]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgfit/LT/b2.pdf} }\n \\subfloat[LT category OO bin3]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgfit/LT/b3.pdf} } \\\\\n \\subfloat[LT category OO bin4]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgfit/LT/b4.pdf} }\n \\subfloat[LT category OO bin5]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgfit/LT/b5.pdf} }\n \\subfloat[LT category OO bin6]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgfit/LT/b6.pdf} } \\\\\n \\subfloat[LL category OO bin1]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgfit/LL/b1.pdf} }\n \\subfloat[LL category OO bin2]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgfit/LL/b2.pdf} }\n \\subfloat[LL category OO bin3]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgfit/LL/b3.pdf} } \\\\\n \\subfloat[LL category OO bin4]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgfit/LL/b4.pdf} }\n \\subfloat[LL category OO bin5]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgfit/LL/b5.pdf} }\n \\subfloat[LL category OO bin6]{ \\includegraphics[width= 0.30\\textwidth]{figure/bkgfit/LL/b6.pdf} } \\\\\n \\caption{Background only fit on the background templates based on MC samples. }\n \\label{fig:bkgonly}\n\\end{figure}\n\n\n", "meta": {"hexsha": "45b77ac36fabadba526e8ddfed6566936db13aa0", "size": 37607, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "tex/background.tex", "max_stars_repo_name": "phreborn/vbfcp_INT", "max_stars_repo_head_hexsha": "904cd56e96a3489887bb9e808d28f6dae4d7f058", "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/background.tex", "max_issues_repo_name": "phreborn/vbfcp_INT", "max_issues_repo_head_hexsha": "904cd56e96a3489887bb9e808d28f6dae4d7f058", "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/background.tex", "max_forks_repo_name": "phreborn/vbfcp_INT", "max_forks_repo_head_hexsha": "904cd56e96a3489887bb9e808d28f6dae4d7f058", "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": 84.3206278027, "max_line_length": 844, "alphanum_fraction": 0.7541415162, "num_tokens": 10981, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.352201788847459, "lm_q1q2_score": 0.1939248990940984}}
{"text": "\\section{The Model}\n\nProtocol participants are represented as parties---formally Interactive Turing Machine instances (ITIs)---in a multi-party computation. We assume a central adversary who corrupts miners and uses them to attack the protocol. The adversary is {\\em adaptive}, i.e., can corrupt (additional) parties at any point and depending on his current view of the protocol execution. Our protocols are synchronous (G)UC protocols~\\cite{C:BMTZ17,TCC:KMTZ13}: parties have access to a (global) clock setup, denoted by~$\\gclock,$ and can communicate over a network of authenticated multicast channels. We assume instant and {\\em fetch-based} delivery channels~\\cite{TCC:KMTZ13,AC:CGHZ16}. Such channels, whenever they receive a message from their sender, they record it and deliver it to the receiver upon his request with a ``fetch'' command. In fact, all functionalities we design in this work will have such fetch-based delivery of their outputs. We remark that the instant-delivery assumption is without loss of generality as the channels are only used for communicating the timestamped object to the verifier which can anyway happen at any point after its creation. However, our treatment trivially applies also to the setting where parties communicate over bounded-delay channels as in~\\cite{C:BMTZ17}. \n\n\nWe adopt the {\\em dynamic availability} model implicit in~\\cite{C:BMTZ17} which was fleshed out in~\\cite{CCS:BGKRZ18}. We next sketch its main components: All functionalities, protocols, and global setups have a dynamic party set. i.e., they all include special instructions allowing parties to register, deregister, and allowing the adversary to learn the current set of registered parties. Additionally, global setups allow any other setup (or functionality) to register and deregister with them, and they also allow other setups to learn their set of registered parties. For more details on the registration process we refer the reader to Appendix~\\ref{se:registration}. \n\\paragraph{The Clock Functionality} $\\gclock$ (cf. Fig.~\\ref{fig:gclock}).\n%As in~\\cite{BMTZ17} we assume a global UC-functionality $\\gclock$ that allows the parties to ensure that the protocol they are running proceeds in synchronized rounds. \nThe \\emph{clock functionality} was initially proposed in~\\cite{TCC:KMTZ13} to enable synchronous execution of UC protocols. Here we adopt its global-setup version, denoted by $\\gclock$, which was proposed by~\\cite{C:BMTZ17} and was used in the (G)UC proofs of the ledger's security.\\footnote{As a global setup, $\\gclock$ also exists in the ideal world and the ledger connects to it to keep track of rounds.} $\\gclock$ allows parties (and functionalities) to ensure that the protocol they are running proceeds in synchronized rounds; it keeps track of round variable whose value can be retrieved by parties (or by functionalities) via sending to it the pair: $\\gread$. This value is increased when every honest party has sent to the clock a command $\\gupdate$.\nThe parties use the clock as follows. Each party starts every operation by reading the current round from $\\gclock$ via the command $\\gread$. Once any party has executed all its instructions\nfor that round it instructs the clock to advance by sending a $\\gupdate$ command, and gets in an idle mode where it simply reads the clock time in every activation until the round advances. %The clock advances to the next round when all the parties have requested to advance to the next round.\n%In~\\cite{KZZ16,BMTZ17}, this idea was transfered to the (G)UC setting, by assuming that the clock is a global setup. This allows different protocols to use the same clock and we will also use the latter model in this paper. In particular, we model the \\emph{time aspect} of all the functionalities that we propose, in terms of number of rounds. Therefore, when $\\gclock$ proceeds from one round to another, we say that $\\gclock$ has \\emph{ticked}. \n%For completeness, we have included the global clock functionality in Appendix~\\ref{app:funcs} We refer readers to Fig.~\\ref{fig:gclock} for a formal description of the functionality.\nTo keep more compact the description of our functionalities that rely on $\\gclock$, we implicitly assume that\nwhenever an input is received the command $\\gread$ is sent to $\\gclock$ to retrieve the current round. Moreover, before giving the output, the functionalities request to advance the clock by sending $\\gupdate$ to $\\gclock$.\n\n\n\n\n\n\n\\subsection{Ledger Consensus: Model}\\label{se:ledgermodel}\n\nIn this section, we define our notion of protocol execution following~\\cite{EC:GarKiaLeo15,FOCS:Canetti01}.\nThe execution of a protocol $\\Pi$ is driven by an\nenvironment program $\\env$ that may spawn multiple instances running the protocol $\\Pi$. The programs\nin question can be thought of as interactive Turing machines (ITM) that have communication,\ninput and output tapes. An instance of an ITM running a certain program will be referred to as\nan interactive Turing machine instance or ITI. The spawning of new ITI's by an existing ITI as\nwell as the interaction between them is at the discretion of a control program which is also an ITM\nand is denoted by $C$. The pair $(\\env, C)$ is called a system of ITM's, cf.~\\cite{FOCS:Canetti01}.\nSpecifically, the execution driven by $\\env$ is defined with respect to a protocol $\\Pi$, an adversary $\\adv$\n(also an ITM) and a set of parties $P_1,\\dots,P_n$; these are hardcoded in the control program $C$.\nInitially, the environment $\\env$ is restricted by $C$ to spawn the adversary $\\adv$. Each time the\nadversary is activated, it may send one or more messages of the form $(\\corrupt, P_i)$ to $C$. The control\nprogram $C$ will register party $P_i$ as corrupted, only provided that the environment has previously\ngiven an input of the form $(\\corrupt, P_i)$ to $\\adv$ and that the number of corrupted parties is less or\nequal $\\tcorrupt$, a bound that is also hardcoded in $C$.\n\nWe divide time into discrete units called \\emph{time slots} or {\\emph round}. Players are equipped with (roughly)\nsynchronized clocks $\\gclock$ that indicate the current slot: we assume that any clock drift is subsumed in the slot\nlength.\n%Each slot $\\slr$ is indexed by an integer $r\\in\\{1,2,\\dots\\}$.\n\n\n%The first ITI party to be spawned running protocol\n%$\\Pi$ is restricted by $C$ to be party $P_1$. After a party $P_i$ is activated, the environment is restricted to\n%activate party $P_{i+1}$, except when $P_n$ is activated in which case the next ITI to be activated is always\n%the adversary $\\adv$. Note that when a corrupted party $Pi$ is activated the adversary $\\adv$ is activated\n%instead.\n\n\n\n\\subsubsection{Ledger Consensus.}\nLedger consensus (a.k.a. ``Nakamoto consensus'') is the problem where a set of nodes\n(or parties) operate continuously accepting inputs\nthat are called transactions and incorporate them in a public data\nstructure called the {\\em ledger}.\nA ledger (denoted in calligraphic-face, e.g. $\\ledger$) is a mechanism for maintaining a sequence of transactions, often\nstored in the form of a blockchain. In this work, we denote with $\\ledger$\nthe algorithms used to maintain the sequence, and with $\\state$ all the views of the\nparticipants of the state of these algorithms when being executed. For example, the (existing) ledger Bitcoin\nconsists of the set of all transactions that ever took place in the Bitcoin network, the current UTXO set, as\nwell as the local views of all the participants.\nIn contrast, we call a \\emph{ledger state} a concrete sequence of transactions $\\tx_1,\\tx_2,\\dots$ stored in the stable\npart of a ledger state $\\state$, typically as viewed by a particular party. Hence, in every blockchain-based ledger $\\ledger$,\nevery fixed chain $\\mathcal{C}$ defines a concrete ledger state by applying the interpretation rules given as a part of the\ndescription of $\\ledger$. In this work, we assume that the ledger state is obtained from the blockchain by dropping the last $k$ blocks\nand serializing the transactions in the remaining blocks. We refer to $k$ as the \\emph{common-prefix parameter}.\nWe denote by $\\state^P[t]$ the ledger state of a ledger $\\ledger$ as viewed by a party $P$ at the beginning of a time slot $t$\nand by ${\\check \\state}^{P}[t]$ the complete state of the ledger (at time $t$) including all pending transactions that are not stable yet. $\\state^P[t]$ can be obtained from ${\\check \\state}^{P}[t]$ by dropping the last $k$ block.\n%ledger states (or, more generally, any sequences), we denote by \u0016the prefix relation.\n% and by $\\hat P^\\ledger[t]$ the complete state of the ledger (at time $t$) including all pending transactions that are not stable yet.\n\n\nFor two ledger states (or, more generally, any sequences), we denote by $\\preceq$ the prefix relation.\nRecall the definition of secure ledger protocol given in~\\cite{RSA:GarKia20}.\n\n\n\\begin{definition}\\label{de:ledger} A ledger protocol $\\ledger$ is secure if it enjoys the following properties.\n\n\n\\ignore{\n\\begin{itemize}\n\\item {\\em Consistency:} This property mandates that if a client queries\nan honest node's ledger at round $t_1$\nand receives the response $\\mc{L}_1$,\nthen a client querying an honest node's ledger at round $t_2\\geq t_1 $\n receives a response $\\mc{L}_2$ that satisfies $\\mc{L}_1 \\preceq \\mc{L}_2$,\nwhere $\\preceq$ denotes the standard prefix operation.\n\n\\item {\\em Liveness:} If a transaction $tx$ is given as input to all honest\nnodes continuously for a certain number of rounds denoted by $u$,\nand a client queries any honest node's ledger\nafter these $u$ rounds, then the node responds with a value\n$\\mc{L}$ that includes $tx$.\n%\\end{itemize}\n}\n\n\\begin{myitemize}\n \\item[]{\\bf Consistency.}\n For any two honest parties $\\party_1,\\party_2$ and two time slots $t_1\\leq t_2$,\n it holds $\\LView{\\state}{\\party_1}{t_1} \\preceq\n \\LView{\\check{\\state}}{\\party_2}{t_2}$.\n\n \\item[]{\\bf Liveness.}\n If all honest parties in the system attempt to include a transaction $\\tx$\n then, at any slot $t$ after $s$ slots (called the\n liveness parameter), any honest party $\\party$, if queried,\n will report $\\tx \\in \\LView{\\state}{\\party}{t}$.\n\\end{myitemize}\n\n\\end{definition}\n\nIn this work we also explicitly rely on the properties of \\emph{Common Prefix (CP)}, \\emph{Chain Growth (CG)} \nand \\emph{Chain Quality (CQ)}. \n\n\\begin{myitemize}\n \\item[] {\\bf Common Prefix (CP); with parameters $k\\in\\mathbb{N}$} \nstates that for any pair of honest players $P_1,P_2$ at rounds $r_1\\leq r_2$ respectively, it holds that ${ \\state}^{P_1}[r_1] \\preceq {\\check \\state}^{P_2}[r_2] $. \n \\item[] {\\bf Chain Growth (CG); with parameters $\\cg\\in (0,1]$ and $s\\in\\mathbb{N}$}. Consider the chain $\\mathcal{C}$\n adopted by an honest party at the onset of a slot and any portion of $\\mathcal{C}$ spanning $s$ prior slots; then the number of\n blocks appearing in this portion of the chain is at least $\\tau s$.\n \n \\item[] {\\bf Chain Quality (CQ) with parameters $\\mu\\in\\mathbb{R}$\nand $\\ell\\in\\mathbb{N}$}. For any honest party $P$ with chain $\\mathcal{C}$ it holds that for any $\\ell$ consecutive blocks of $\\mathcal{C}$ the ratio of honest blocks is at least $\\mu$.\n \\end{myitemize}\n\n\n\nWe consider a setting where a set of parties run a protocol maintaining a ledger $\\ledger_1$. Following~\\cite{SP:GazKiaZin19}, we denote by $\\asmp_1$\nthe assumptions for $\\ledger_1$.\n That is, if the assumption $\\asmp_1$ holds, then ledger $\\ledger_1$ is secure under the Definition~\\ref{de:ledger}.\nFormally, $\\asmp_i$ for a ledger $\\ledger_i$ is a sequence of events $\\asmp_i[t]$ for each time slot $t$ that can assume value $1$,\nif the assumption is satisfied, and $0$ otherwise.\nFor example, $\\asmp_i$ may denote that\nthere has never been a majority of hashing power (or stake in a particular\nasset, on this ledger or elsewhere) under the control of the adversary; that a\nparticular entity (in case of a centralized ledger) was not corrupted; and so\non.\nWithout loss of generality, we say that the assumption $\\asmp_1$ for the ledger $\\ledger_1$ holds if and only if the fraction of corrupted parties (the parties\nthat received the input $(\\corrupt, \\cdot)$) is below the threshold $\\tcorrupt_1$ (where $\\tcorrupt_1$ is part of the control function as described in the beginning\nof this section).\n\n\\paragraph{Chain selection rule and block validation.} We sometimes assume that a ledger protocol describes a \\emph{chain selection rule} that we denote with $\\chainsel$.\nThat is, we assume that each party in each round of the execution of the protocol collects all chains that come from the network and runs the algorithm $\\chainsel$ to decide whether to keep his current local chain $\\cloc$, or adopt one of the newly received chains. \nFollowing~\\cite{C:BMTZ17} we also assume \nthat before applying the chain-selection rule, any given chain is tested\n using the procedure $\\isvalid$. $\\isvalid$ checks filters the\n valid chains among all the chain received from the network and only\n the valid chain are used as input for $\\chainsel$.\n $\\chainsel$ in turns rely on the algorithm $\\isvalidb$.\n $\\isvalidb$ take as input a block $B$ of $\\cloc$ and outputs $1$ if $B$ is a valid block (i.e., the structure of\n the block is correct) and $0$ otherwise.\n \n \n We note that by assuming that a ledger protocol is always equipped with the algorithms $\\chainsel$, \n $\\isvalid$ and $\\isvalidb$ make some of our results less general. However, we will show that it is possible to\nobtain a better updatable ledger in the case when the two ledgers (the current ledger) and the new ledger have the same chain selection rule (among other similarities).\n\n\n\\subsection{Genesis Block Functionality}\nThe ledger protocols that we consider in this work are equipped with the description of an algorithm $\\genesis$ that, on input a random value of appropriate length, outputs a valid genesis block (i.e., the first block of the chain). The security of most of the known ledger protocols holds\nunder the additional assumption that the genesis block is correct. That is, the genesis block has been generated\naccordingly to $\\genesis$ using appropriate randomness.\nMultiple ways have been presented to generate a correct genesis block in the literature (i.e., by relying on a trusted authority, use\nunpredictable information (like in bitcoin), run a multi-party computation (MPC) protocol~\\cite{zcash}, \nrely on PoW~\\cite{PKC:GKLP18} assumptions and so on and so forth). \nIn this work we abstract the generation of the genesis block by means of an ideal functionality.\nThe ideal functionality that one might expect, upon being activated from the adversary or from an honest party, should sample a random string and use it to run the algorithm $\\genesis$. Unfortunately this simple functionality does not cover real world scenarios where an adversarial party might see the genesis block before the honest parties do. This, for example, can happen in the case when $\\genesis$ is realized via an MPC protocol and a rushing adversary\\footnote{A rushing adversary waits to receive the messages from all the honest parties and then computes its reply. Note that this means that, in general, the adversary is always able to see the output of the computation before the honest parties do.} could hold the genesis block (the output of the computation) for some bounded amount of time $\\delay$ before the honest parties can see it.\nWe note that an adversary can use this strategy to take an advantage on the generation of the blocks that extend the genesis block.\n Therefore, the first modification that we consider for our ideal functionality is to allow the adversary to see the genesis block up to $\\delay$ rounds earlier than the honest parties.\n The second relaxation allows the adversary to see up to \n $\\maxblocks$ honestly generated genesis blocks and consequently decide which of these blocks will become the \n genesis block.\n We propose the formal description of our genesis functionality $\\fgenesis$ in Fig.~\\ref{fig:genesis}. \n We note that the case where $\\delay=0$ and $\\maxblocks=1$ corresponds to the case where there is only one candidate genesis block and all the parties can see it at the same round.\n \n\n\n\\begin{figure}[]\n\\small\n\\setlength{\\fboxsep}{8pt}\n\\begin{center}\n\\begin{boxedminipage}{12cm}\n{\\bf Genesis Functionality for $\\ledger$}\n\n{\\bf Parameters.} The functionality is parametrized by $\\delay$, the maximum number of candidate genesis block $\\maxblocks$, the genesis block $\\bgen$ initialized with a default value $\\bot$ and the procedure $\\genesis()$.\nWe assume the functionality to be registered to $\\gclock$ and that it maintains a set of registered parties $\\parties$.\nOn any input $I$ the functionality queries $\\gclock$, and we denote with $\\now$ be the response obtained by $\\gclock$. \n\n\n\\begin{description}\n\\item[-] If $I=\\gengenesis$ is received from the adversary $\\adv$ then set $\\tau:=\\now$, generate $\\maxblocks$\n genesis blocks (each block is generated by running the procedure $\\genesis()$) $\\GB:=\\{\\bgen_1,\\dots, \\bgen_\\maxblocks\\}$ for $\\ledger$, and send $\\GB$ to the adversary.\n \n \\item[-] If $I=\\getgenesis$ is received from an honest party $p_i\\in\\parties$ do the following\n \\begin{itemize}\n \t\\item If $\\bgen\\neq\\bot$ then return $\\bgen$ to $p_i$.\n\t\\item If $\\bgen =\\bot$ and $R-\\tau>\\delay$ then set generate a genesis block $\\tilde \\bgen$ by running \n\t $\\genesis$, set\n\t$\\bgen\\leftarrow \\tilde \\bgen$ and send $\\bgen$ to $p_i$.\n\\end{itemize}\n \\item[-] If $I=(\\setgenesis,{\\bgen}')$ is received from the adversary do the following \n \\begin{itemize}\n \t\\item If $(R-\\tau)\\leq\\delay$ and ${\\bgen}'\\in\\GB$ then set $\\bgen:={\\bgen}'$.\n\t\\item Else, return $\\bot$ to the adversary.\n \\end{itemize}\n\n\\end{description}\n\n\\end{boxedminipage}\n\\end{center}\n\\caption{The genesis functionality $\\fgenesis$.} \n\\label{fig:genesis}\n\\end{figure}\n\n", "meta": {"hexsha": "8f5ff500c7bc2a89130081e4629f05854bec0b00", "size": 17865, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "papers/Esorics20/submitted_paper/model.tex", "max_stars_repo_name": "MitchellTesla/decentralized-software-updates", "max_stars_repo_head_hexsha": "89f5873f82c0ff438e2cd3fff83cc030a46e29da", "max_stars_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2019-01-25T19:38:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-06T02:08:38.000Z", "max_issues_repo_path": "papers/Esorics20/submitted_paper/model.tex", "max_issues_repo_name": "MitchellTesla/decentralized-software-updates", "max_issues_repo_head_hexsha": "89f5873f82c0ff438e2cd3fff83cc030a46e29da", "max_issues_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_issues_count": 120, "max_issues_repo_issues_event_min_datetime": "2019-03-06T18:29:25.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-24T10:20:09.000Z", "max_forks_repo_path": "papers/Esorics20/submitted_paper/model.tex", "max_forks_repo_name": "MitchellTesla/decentralized-software-updates", "max_forks_repo_head_hexsha": "89f5873f82c0ff438e2cd3fff83cc030a46e29da", "max_forks_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2019-07-18T13:38:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-16T10:39:00.000Z", "avg_line_length": 81.9495412844, "max_line_length": 1301, "alphanum_fraction": 0.7591939547, "num_tokens": 4502, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.35220178204788966, "lm_q1q2_score": 0.19392489535020543}}
{"text": "\n\\section{Introduction}\\label{sec:intro}\n\nFish population (aka \"stock\") assessment models determine the impact of past fishing on the historical and current abundance of the population, evaluate sustainable rates of removals (catch), and project future levels of catch reflecting one or more risk-averse catch rules. These catch rules are codified in regional Fishery Management Plans according to requirements of the Sustainable Fisheries Act. In the U.S., approximately 500 federally managed fish and shellfish populations are managed under approximately 50 Fishery Management Plans. About 200 of these populations are assessed each year, based on a prioritized schedule for their current status. Despite this, many minor species have never been quantitatively assessed. Although the pace is slower than that for weather forecasting, fish stock assessments are operational models for fisheries management.\n\nAssessment models typically assimilate annual catches, data on fish abundance from diverse surveys and fishery sources, and biological information regarding fish body size and proportions at age. A suite of models is available depending on the degree of data availability and unique characteristics of the fish population or its fishery. Where feasible, environmental time series are used as indicators of changes in population or observation processes, especially to improve the accuracy of the projections of abundance and sustainable catch into the future. Such linkages are based principally on correlations given the challenge of conducting field observations on an appropriate scale. The frontier of model development is in the rapid estimation of parameters to include random temporal effects, in the simultaneous modeling of a suite of interacting species, and in the explicit treatment of the spatial distribution of the population.\n\nAssessment models are loosely coupled to other models. For example, an ocean-temperature or circulation model or benthic-habitat map may be directly included in the pre-processing of the fish abundance survey. A time series of a derived ocean factor, like the North Atlantic Oscillation, can be included as an indicator of a change in a population process. Output of a multi-decadal time series of derived fish abundance can be an input to ecosystem and economic models to better understand cumulative impacts and benefits. \n\nStock Synthesis is an age- and size-structured assessment model in the class of models termed integrated analysis models. Stock Synthesis has evolved since its initial inception in order to model a wide range of fish populations and dynamics. The most recent major revision to Stock Synthesis occurred in 2016, when version 3.30 was introduced. This new version of Stock Synthesis required major revisions to the input files relative to earlier versions (see the \\hypertarget{ConvIssues}{Converting Files} section for more information). The acronym for Stock Synthesis has evolved over time with earlier versions being referred to as SS2 (Stock Synthesis v.2.xx) and older versions as SS3 (Stock Synthesis v.3.xx). \n\nSS3 has a population sub-model that simulates a stock's growth, maturity, fecundity, recruitment, movement, and mortality processes, an observation sub-model estimates expected values for various types of data, a statistical sub-model characterizes the data’s goodness of fit and obtains best-fitting parameters with associated variance, and a forecast sub-model projects needed management quantities. SS3 outputs the quantities, with confidence intervals, needed to implement risk-averse fishery control rules. The model is coded in C++ with parameter estimation enabled by automatic differentiation (\\href{http://www.admb-project.org}{admb}). Windows, Linux, and iOS versions are available. Output processing and associated tools are in R, and a graphical interface is in QT. SS3 is available from NOAA’s VLAB. The rich feature set in SS3 allows it to be configured for a wide range of situations. SS3 has become the basis for a large fraction of U.S. assessments and many other assessments around the world. \n\nThis manual provides a guide for using SS3. The guide contains a description of the input and output files and usage instructions. An overview and technical description of the model itself is in \\citet{methotstock2013}. However, SS3 has continued to evolve and grow since the publication in 2013, with this manual reflecting the most up to date information regarding SS3. The model and a graphical user interface are available from the NOAA \\href{https://vlab.noaa.gov/web/stock-synthesis}{VLAB}. The VLAB site also provides a user forum for posting questions and for accessing various additional materials. An output processor package, r4ss, in R is available for download from CRAN or \\href{https://github.com/r4ss/r4ss}{GitHub}.\n\nAdditional guidance for new users can be found in the SS3 \\href{https://vlab.noaa.gov/web/stock-synthesis/document-library}{document library} within the NOAA VLAB website. The \"Begin Here - Introduction to Stock Synthesis\" folder located in the Document Library contains step-by-step guidance for running Stock Synthesis.\n\n \\subsection{How To Cite}\n \nPlease cite Stock Synthesis as:\n\nMethot, R.D. and Wetzel, C.R. (2013). Stock Synthesis: A biological and statistical\nframework for fish stock assessment and fishery management. Fisheries Research, \n142: 86-99. \\href{https://doi.org/10.1016/j.fishres.2012.10.012}{https://doi.org/10.1016/j.fishres.2012.10.012}\n\nPlease cite the Stock Synthesis User Manual as:\n\nMethot, R. D., Jr., C. R. Wetzel, I. G. Taylor, and K. Doering. (2020). Stock Synthesis User Manual Version 3.30.15. U.S. Department of Commerce, NOAA Processed Report NMFS-NWFSC-PR-2020-05.\\href{https://doi.org/10.25923/5wpn-qt71}{https://doi.org/10.25923/5wpn-qt71}\n\n\\pagebreak\n\t\t\n\\section{File Organization}\\label{FileOrganization}\t\t\n\t\\subsection{Input Files}\n\t\\begin{enumerate}\n\t\t\\item starter.ss: required file containing filenames of the data file and the control file plus other run controls (required).\n\t\t\\item datafile: file containing model dimensions and the data (required)\n\t\t\\item control file: file containing set-up for the parameters (required)\n\t\t\\item forecast.ss: file containing specifications for reference points and forecasts (required) \n\t\t\\item ss.par: previously created parameter file that can be read to overwrite the initial parameter values in the control file (optional)\n\t\t\\item wtatage.ss: file containing empirical input of body weight by fleet and population and empirical fecundity-at-age (optional)\n\t\t\\item runnumber.ss: file containing a single number used as run number in output to CumReport.sso and in the processing of profilevalues.ss (optional)\n\t\t\\item profilevalues.ss: file contain special conditions for batch file processing (optional)\n\t\\end{enumerate}\n\t\n\t\\subsection{Output Files}\n\t\\begin{enumerate}\n\t\t\\item data\\_echo.ss\\_new: Contains the input data as read by the model. In model versions prior to 3.30.19 a single data.ss\\_new file was created that included the echoed data, the expected data values (data\\_expval.ss), and any bootstap data files seleected (data\\_boot\\_x.ss).\n\t\t\\item data\\_expval.ss: Contains the expected data values given the model fit. This file is only created if the value for \"Number of datafiles to produce\" in the starter file is set to 2 or greater.\n\t\t\\item data\\_boot\\_x.ss: A new data file filled with bootstrap data based on the original input data and variances. This file is only created if the value in the \"Number of datafiles to produce\" in the starter file is set to 3 or greater. A separate bootstrap data file will be written for the number of bootstrap data file requests where x in the file name indicates the bootstrap simulation number (e.g., data\\_boot\\_001.ss, data\\_boot\\_002.ss,...).\n\t\t\\item control.ss\\textunderscore new: Updated version of the control file with final parameter values replacing the initial parameter values.\n\t\t\\item starter.ss\\textunderscore new: New version of the starter file with annotations.\n\t\t\\item Forecast.ss\\textunderscore new: New version of the forecast file with annotations.\n\t\t\\item warning.sso: This file contains a list of warnings generated during program execution.\n\t\t\\item echoinput.sso: This file is produced while reading the input files and includes an annotated echo of the input. The sole purpose of this output file is debugging input errors.\n\t\t\\item Report.sso: This file is the primary report file.\n\t\t\\item ss\\_summary.sso: Output file that contains all the likelihood components, parameters, derived quantities, total biomass, summary biomass, and catch. This file offers an abridged version of the report file that is useful for quick model evaluation. This file is only available in SS3 v.3.30.08.03 and greater.\n\t\t\\item CompReport.sso: Observed and expected composition data in a list-based format.\n\t\t\\item Forecast-report.sso: Output of management quantities and for forecasts.\n\t\t\\item CumReport.sso: This file contains a brief version of the run output, output is appended to current content of file so results of several runs can be collected together. This is useful when a batch of runs is being processed.\n\t\t\\item Covar.sso: This file replaces the standard ADMB ss.cor with an output of the parameter and derived quantity correlations in database format.\n\t\t\\item ss.par: This file contains all estimated and fixed parameters from the model run. \n\t\t\\item ss.std, ss.rep, ss.cor etc.: Standard ADMB output files.\n\t\t\\item checkup.sso: Contains details of selectivity parameters and resulting vectors. This is written during the first call of the objective function.\n\t\t\\item Gradient.dat: New for SS3 v.3.30, this file shows parameter gradients at the end of the run.\n\t\t\\item rebuild.dat: Output formatted for direct input to Andre Punt's rebuilding analysis package. Cumulative output is output to REBUILD.SS (useful when doing MCMC or profiles).\n\t\t\\item SIS\\_table.sso: Output formatted for reading into the NMFS Species Information System.\n\t\t\\item Parmtrace.sso: Parameter values at each iteration.\n\t\t\\item posteriors.sso, derived\\_posteriors.sso, posterior\\_vectors.sso: Files associated with MCMC.\n\t\\end{enumerate}\n\n\\pagebreak\n\t\t\n\\section{Starting Stock Synthesis}\nSS3 is typically run through the command line interface, although it can also be called from another program, R, the Stock Synthesis Interface, or a script file (such as a DOS batch file). SS3 is compiled for Windows, Mac, and Linux operating systems. The memory requirements depend on the complexity of the model you run, but in general, SS3 will run much slower on computers with inadequate memory. See the Running Stock Synthesis section on page \\pageref{sec:RunningSS} for additional notes on methods of running SS3.\n\nCommunication with the program is through text files. When the program first starts, it reads the file starter.ss, which typically must be located in the same directory from which SS3 is being run. The file starter.ss contains required input information plus references to other required input files, as described in the File Organization section on page \\pageref{FileOrganization}. The names of the control and data files must match the names specified in the starter.ss file. File names, including starter.ss, are case-sensitive on Linux and Mac systems but not on Windows.The echoinput.sso file outputs how the executable read each input file and can be used for troubleshooting when trying to setup a model correctly. Output from SS3 consists of text files containing specific keywords. Output processing programs, such as the SSI, Excel, or R can search for these keywords and parse the specific information located below that keyword in the text file.\n\n\\pagebreak\n", "meta": {"hexsha": "9864d112d4a4cabd8c782514086f8dc8dd818b12", "size": 11788, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "1_4sections.tex", "max_stars_repo_name": "nmfs-stock-synthesis/doc", "max_stars_repo_head_hexsha": "4496c14ced182330905010588ca33fac9afa761f", "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": "1_4sections.tex", "max_issues_repo_name": "nmfs-stock-synthesis/doc", "max_issues_repo_head_hexsha": "4496c14ced182330905010588ca33fac9afa761f", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 43, "max_issues_repo_issues_event_min_datetime": "2022-01-03T20:49:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T18:21:44.000Z", "max_forks_repo_path": "1_4sections.tex", "max_forks_repo_name": "nmfs-stock-synthesis/doc", "max_forks_repo_head_hexsha": "4496c14ced182330905010588ca33fac9afa761f", "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": 149.2151898734, "max_line_length": 1017, "alphanum_fraction": 0.7999660672, "num_tokens": 2590, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.37022540649291935, "lm_q1q2_score": 0.19378351145161626}}
{"text": "\\chapter{Differentiation}\n\\section{Gradients}\n\\section{Differentiation from first principles}\n\\section{Differentiation of standard functions}\n\\section{Tangents, normals, stationary points, increasing and decreasing functions}\n\\section{Techniques of differentiation}\n\\section{Parametric and implicit differentiation}\n\\section{Constructing differential equations}", "meta": {"hexsha": "c44ad7a6c235cce24048cc3f213fce7ec8caf3ad", "size": 361, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "corpus/a-level-notes/math/content/pure/differentiation.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/differentiation.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/differentiation.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": 45.125, "max_line_length": 83, "alphanum_fraction": 0.8504155125, "num_tokens": 71, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.37022539259558657, "lm_q1q2_score": 0.19378350417746948}}
{"text": "\\documentclass[a4paper,10pt]{article}\n\\usepackage[utf8]{inputenc}\n\\usepackage{graphicx}\n%\n%opening\n\\title{}\n\\author{}\n\n\\begin{document}\n\n\\maketitle\n\n%\\begin{abstract}\n\n%\\end{abstract}\n\n\\section{Automatic generation of neural mass model kernels}\n\\subsection{High level description of a simulation of a network of neural masses}\nNeural mass models (NMMs) are mathematical tools to describe ensabled behaviour of groups of neurons through time. \nThese models contain a set of internal states which describe the system and a set of coupled differential equations which define how the states of the system evolve.\nAn instance of these models is called a node.\nThe output of the model consists of a set of observables which identify states of interest for other nodes.\nNodes are linked to each other using a coupling function.\nThis coupling function is the equivalent of a synapse in a point neuron network.\nCoupling defines how the input coming from other nodes should be treated.\nUsually the coupling involves weighting the incoming signals by a factor and then passing this through a simple function.\nThe weights used for the coupling are of such level of detail that are matchable to connectivity maps which can be obtained from experimental measurements, e.g. tractography.\n\nCertain observables of a neural mass can be post-processed to produce simulated BOLD, EEG and EMG signals among others. \nThese signals can afterwards be input to an analysis step where a measure of the ability of the model to reproduce given aspects of the signal is performed.\nThe amount of open degrees of freedom in the Neural Mass Models generates a vast parameter space. \nThe nature of the workflow described above allows the iterative modification and exploration of parameters in this admissible space.\nBrute force of more intelligent approaches can be used to optimize the behaviour of the models with respect to fitness functions defined by experts and related to the essential characteristics of the higher level signals.\n\nA general description of the simulation can be seen in Figure \\ref{fig}\n\\begin{figure}\n \\begin{center}\n \\includegraphics[scale=0.4]{DiagramNMM.eps}\n \\end{center}\n \\caption{Diagram of the interaction between the different computation stages in a neural mass model simulation.}\n \\label{fig}\n\\end{figure}\n\n\\subsection{High level description of neural mass models}\nIn order to ease the high level description of the computation models used in this workflow, we have implemented the BaseModel class.\nThis class defines a set of attributes: \n\\begin{enumerate}\n\n\\item State: Stores the internal states of the model.\n\\item Auxex: Auxiliary mathematical expressions which are used for internal calculations in the model.\n\\item Input: Stores the input comming from other neural masses into this neural mass.\n\\item Drift: Set of equations which transfer the model from a state at t-1 to another at time t.\n\\item Diffs: Differentiable variables in the system.\n\\item Observ: Observers are the data structures which contain inner states which must be available to the outside of the model. They represent the output of the model.\n\\item Const: Constant values specifically defined for a each model. \n\\item Param: Parameters provided to an specific model. \n\\item Limit: Defines the min and max limits within which the state values must be wrapped to ensure mathematical consistency.\n \n\\end{enumerate}\n\n\n\\subsection{Loopy as automatic code generation library}\nLoopy \\cite{loopy2014} is a python library intended to aid the automatic generation of parallel kernels for different target hardware platforms.\nIt includes targets for CUDA, OpenCL, KNL and CPUs.\nParallel code in Loopy is generated by enclosing a set of functions into an independent execution domains.\nThe dimensions of these domains are specified using inames. \nThese inames represent the number of parallel instances that one can process at the same time of the given set of functions.\n\nOther feature of loopy is the integration of multiple kernels into a single one.\nThe set of independent kernels is combined using a data flow which defines how variables are sent from one kernel into the next as input.\nThis allows the creation of complex kernels where data dependencies are assured.\n\nLoopy automatically analizes the data structures used within the domain and the access patterns to them. \nThe user can specify type and ranges for values and access limits to the data structures to control the way the data is handled.\nLoopy assambles the computation within a loop-like environment, where each iteration is independent.\nThe code can then be specifically ported to a target platform using its specific language.\n\n\\subsection{Implementation of neural mass models with Loopy}\nOur objective is to have a high level description of neural mass models which can then be used to automatically generate high performance parallel code for multiple platforms.\nTo achieve this goal with Loopy, we need to match the high level description language of the models to the specific API of Loopy.\n\nThe BaseModel class has functions which translate the information provided in the attributes of a model instance \nGenerate the data structures\nDefine the kernel domain\nDefine the types for the attributes of the model\nGenerate expressions for constant deffinition\nWe unpack the values for the input, state and parameters.\nGenerate expressions for the auxiliary expressions\nGenerate expressions to store observables\nWe use pybolic to build a set of symbolic expressions representing the drift, diffs and observables.\nWe wrap the output within certain limits to avoid numerical inaccuracies. \n\n\\bibliographystyle{abbrvnat}\n\\bibliography{references}\n\n\\end{document}\n", "meta": {"hexsha": "786227a88dfac4e23a8c5c1377702b9451ba9f93", "size": 5707, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "docs/AutomaticGenerationNMM.tex", "max_stars_repo_name": "DeLaVlag/tvb-hpc", "max_stars_repo_head_hexsha": "6559707dfee8ec712d9624aaf441f9901919fe63", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2017-02-22T10:17:19.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-20T13:13:53.000Z", "max_issues_repo_path": "docs/AutomaticGenerationNMM.tex", "max_issues_repo_name": "DeLaVlag/tvb-hpc", "max_issues_repo_head_hexsha": "6559707dfee8ec712d9624aaf441f9901919fe63", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 27, "max_issues_repo_issues_event_min_datetime": "2017-02-07T10:25:31.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-01T09:48:13.000Z", "max_forks_repo_path": "docs/AutomaticGenerationNMM.tex", "max_forks_repo_name": "DeLaVlag/tvb-hpc", "max_forks_repo_head_hexsha": "6559707dfee8ec712d9624aaf441f9901919fe63", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 10, "max_forks_repo_forks_event_min_datetime": "2017-03-06T10:52:02.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-20T02:17:17.000Z", "avg_line_length": 58.8350515464, "max_line_length": 221, "alphanum_fraction": 0.8126861749, "num_tokens": 1143, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.3593641451601019, "lm_q1q2_score": 0.19369124435806814}}
{"text": "\\chapter{\\MSTlong{} Methodology}\\label{chap:methodology}\nAn effective, automated \\mstlong{} (\\mst{}) methodology is key to \\cplop{}'s success as a tool to aid fecal contamination investigators.\nUntil recently, \\cp{} researchers performed most \\mst{} by hand \\cite{moritz2015application, shapiro2015source}.\nThe goal for any \\mst{} method, when used to source fecal contamination, is to take fecal matter or a substance contaminated with fecal matter and determine, or classify, the \\spec{} that provided the fecal matter; \\libdep{} \\mst{} methods leverage the known-\\spec{} information stored in their library, usually digital representations of \\fiblong{} (\\fib{}) stored in a database.\n\\cplop{} is such a \\libdep{} technique that aims to support \\mst{} using \\pyros{} of both \\itsshort{} regions of the \\fib{} \\ecoli{}.\nGiven a \\fib{} \\isol{} from an unknown-\\spec{}\\footnote{often referred to as the ``the unknown'' or ``the unknown \\isol{}''}, a \\libdep{} \\mst{} technique determines the \\spec{} of the unknown using the information in the library.\nTowards this end, we built and investigated two \\mst{} techniques, one that approaches \\spec{} classification from the perspective of strains in the database and another that directly uses \\isols{} present in the database.\nThis Chapter outlines the abstract approaches we chose to take, while \\autoref{chap:clustering} and \\autoref{chap:krap} detail the specific techniques we used for the strain-based and \\isol{}-based approaches respectively.\n\n\\section{Strain-Based}\nStrain typing is central to \\libdep{} \\mst{} methods and building a \\spec{} classification technique that uses strains directly is an intuitive approach to take.\nIf an unknown-\\spec{} matches a strain in the library, then we can make a reasonable assertion as to its \\spec{} if the strain has a dominant \\spec{}.\nThus, given an unknown-\\spec{} \\isol{}: \n\\begin{enumerate}\n \\item Incorporate the unknown-\\spec{} \\fib{} \\isol{} into \\cplop{}\n \\item Build strains of \\fib{} using the \\isols{} in \\cplop{}\n \\item Classify the source \\spec{} of the \\isol{} as the dominant \\spec{} of the strain it ended up in\n\\end{enumerate}\nStrain construction can happen in many ways, but from a computational perspective, it is very amenable to clustering.\nIf one can imagine a coordinate space that encapsulates mathematical representations (vectors) of \\fib{} \\isols{}, then strains are the close groupings (clusters) of these \\isol{} representations.\nFor \\cplop{}, this means constructing strains from the \\pyros{} of collected \\ecoli{} \\isols{}.\n\nAs explained in \\autoref{chap:clustering}, we use \\dbscan{}, a \\dbased{} clustering algorithm that we introduce in \\autoref{sec:background:dbscan}, which builds clusters using a similarity metric, allowing for the concept of noise --- datapoints that remain unclustered.\nDense groupings of similar \\isols{} fits our intuition of bacterial \\isol{} strains because closely related ``families'' of \\isols{} will appear in the same cluster.\nA primary limitation of \\dbscan{} is that it may not cluster some \\isols{}, which still aligns with our notion of strains; sometimes, \\isols{} are not part of any strain present in \\cplop{}.\nAs a result, we need a fallback \\mst{} method that can work for every \\isol{}.\n\n\\section{\\Isol{}-Based}\nUsing \\isols{} directly can give us a level of flexibility that strict strain typing may not allow.\nAn unknown-\\spec{} may not fit within the sometimes strict definition of a strain that a particular library may have, but we may still be able to make a reasonable assertion as to its \\spec{} based on the \\isols{} that are most similar to the unknown.\nThus, given an unknown-\\spec{} \\isol{}: \n\\begin{enumerate}\n \\item Find $k$ known-\\spec{} \\isols{} from \\cplop{} most similar to it, called the \\knnlong{}\n \\item Classify the source \\spec{} of the \\isol{} as the dominant \\spec{} of the \\knnlong{}\n\\end{enumerate}\n\nThe described approach is the \\kNNlong{} classification algorithm (\\kNN{}) introduced in \\autoref{sec:background:knn}, however, due to the multiple \\compfuncs{} needed between \\isols{}, \\kNN{}, in its natural form, will not work with \\cplop{}.\n\\autoref{sec:background:isolates} details why the comparison of two \\isols{} to each other requires multiple \\compfuncs{}.\n\\autoref{chap:krap} explains the \\compfunc{} resolution strategy employed by the \\kraplong{}, the \\isol{}-based \\mst{} method we built and investigated.", "meta": {"hexsha": "9e21a0b19f713ffecdbbc48e6a4dbc3e0afc04a4", "size": 4437, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "chapters/methodology/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/methodology/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/methodology/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": 113.7692307692, "max_line_length": 380, "alphanum_fraction": 0.752986252, "num_tokens": 1097, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832058771036, "lm_q2_score": 0.35936414516010196, "lm_q1q2_score": 0.19369123903567656}}
{"text": "\\documentclass[12pt]{article}\n\\setlength{\\evensidemargin}{5pt}\n\\setlength{\\marginparwidth}{0pt}\n\\setlength{\\marginparsep}{0pt}\n\\setlength{\\textheight}{9in}\n\\setlength{\\tabbingsep}{0pt}\n\\setlength{\\headsep}{30pt}\n\\setlength{\\fboxsep}{40pt}\n\\setlength{\\fboxrule}{4pt}\n\\setlength{\\footnotesep}{20pt}\n\\setlength{\\parindent}{0pt}\n\\setlength{\\parskip}{8pt plus 5pt}\n\\setlength{\\topmargin}{-0.5in}\n\\setlength{\\oddsidemargin}{0in}\n\\setlength{\\textwidth}{6.5in}\n\n\\usepackage{times}\n\\usepackage{url}\n\\usepackage{graphics}\n\\usepackage{graphicx} % extended graphics package\n\\usepackage{epsfig} % wrapper for graphicx package\n\\usepackage[noend]{algpseudocode}\n\\algrenewcommand\\algorithmicprocedure{\\textbf{ALGORITHM}}\n\n\\begin{document}\n\n\\title{An Empirical Study of the Brute-Force Closest Pairs Algorithm}\n\n\\author{Jim Teresco\\\\\njteresco@siena.edu\\\\\n\\and\nMy Partner\\\\\npartner@fake.email}\n\n\\maketitle\n\n\\begin{abstract}\n In this study, which is intended as an example of how to put\n together the writeup for an empirical study of algorithm\n performance, we present and analyze timings and operation counts for\n a straightforward brute-force closest pairs implementation. Points\n are generated randomly in a specified range, and the closest pair is\n computed and reported by a Java program.\n\\end{abstract}\n\n\\section{Introduction}\n\nThis empirical analysis study focuses on the brute-force closest pairs\nalgorithm in two dimensions. We will consider a straightforward\nimplementation of the algorithm in Java, instrumented to count basic\noperations and gather timings.\n\nThe remainder of this report is organized as follows.\nSection~\\ref{sec:environment} describes the computing environment\nused. Section~\\ref{sec:bfcp} describes the algorithm, our\nexpectations based on the theoretical analysis, presents our results,\nand relates them back to the theory. We conclude with some additional\ndiscussion in Section~\\ref{sec:conclusions}.\n\n\\section{Computing Environment}\n\\label{sec:environment}\n\nFor this study, a Java program was developed that implements the\nalgorithm of interest. Random inputs of varying sizes and other\ncharacteristics are generated, and the solution is computed.\n\nAll runs are using the following Java version:\n\n\\begin{verbatim}\njava version \"1.8.0_121\"\nJava(TM) SE Runtime Environment (build 1.8.0_121-b13)\nJava HotSpot(TM) 64-Bit Server VM (build 25.121-b13, mixed mode)\n\\end{verbatim}\n\nThe computing environment is a MacBook Pro (15-inch, 2016) with a 2.6\nGHz Intel Core i7, 16 GB of 2133 MHz LPDDR3 memory, and running macOS\nSierra Version 10.12.6. There are 4 cores, each with 256 KB L2 cache,\nand these cores share a 6 MB L3 cache.\n\n\\section{Brute-Force Closest Pairs}\n\\label{sec:bfcp}\n\nThe brute-force closest pairs algorithm as shown in\nFigure~\\ref{fig:alg} was implemented in Java, and instrumented to\ncount the number of times the distance between pairs of points is\ncomputed and to report the elapsed time for the main loops to execute.\n\n\\begin{figure}[htb]\n \\centering\n\\begin{algorithmic}\n \\Procedure{BruteForceClosestPoints}{$P$}\n \\State //Input: a set of points $P[0..n-1]$\n \\State $d_{min} \\gets \\infty$\n \\For{$i \\gets 0 .. n-2$}\n \\For{$j \\gets i+1 .. n-1$}\n %\\State $d \\gets distance(P[i], P[j])$\n \\State $d \\gets \\sqrt{(P[i].x - P[j].x)^2 +(P[i].y - P[j].y)^2}$\n \\If {$d < d_{min}$}\n \\State $d_{min} \\gets d$\n \\State $index_1 \\gets i$\n \\State $index_2 \\gets j$\n \\EndIf\n \\EndFor\n \\EndFor\n \\State \\textbf{return} $(index_1, index_2)$\n\\EndProcedure\n\\end{algorithmic}\n\\caption{The brute-force closest pairs algorithm, as implemented for\n this study.}\n\\label{fig:alg}\n\\end{figure}\n\nThe number of points for the runs is all powers of 2 from\n$2^{10}=1024$ to $2^{19}=524,288$. Points for each run are generated\nrandomly, within a range specified as a parameter to the program.\nPoints are generated within the square with x- and y-coordinates no\nfurther than that range from the origin.\n\nEach combination of the number of points and range of point positions\nis run a total of 5 times. The number of distance calculations is\nexpected to be identical for each of the runs for a given number of\npoints. Run times will vary, however, and the minimum time for a\ngiven combination of the number of points and range of point positions\nis chosen to minimize the effects from other computations that could\nbe in process on the computer during the study.\n\n\n\\subsection{Expectations}\n\nThe theoretical expectation is for both the number of distance\ncalculations and elapsed time to be $\\Theta(n^2)$ in the best,\naverage, and worst cases. There are no shortcuts out of the loops,\nwhich execute about $\\frac{n^2}{2}$ times.\n\n\\subsection{Results}\n\nThe raw results of the study are available in the file\n\\texttt{timings.dat} in the GitHub repository. Each line, such as\n\n{\\small\n\\begin{verbatim}\nBFCP 262144 64.0 92375.0 34359607296 (99936,203911) 4.069483000753879E-4\n\\end{verbatim}\n}\n\nhas 7 space-separated fields. The first field indicates the algorithm name,\nand is followed by the number of points, the range of coordinate\nvalues (each of x and y are within this distance of the origin), the\nelapsed time in milliseconds, the number of distance calculations, the\nindices of the two points that were found to be the closest pair, and\nthe distance between those points. Of these, we are interested in the\nnumber of points, the elapsed time, and distance calculation count.\n\n\\begin{figure}[htb]\n \\centering\n \\includegraphics{bfcp-times.pdf}\n \\caption{Times in milliseconds for the brute-force closest pairs to\n complete its computation for problem sizes from $2^{10}$ to\n $2^{19}$ points.}\n \\label{fig:timings}\n\\end{figure}\n\n\\begin{figure}[htb]\n \\centering\n \\includegraphics{bfcp-opcounts.pdf}\n \\caption{Number of distances between pairs of points computed the\n brute-force closest pairs to complete its computation for problem\n sizes from $2^{10}$ to $2^{19}$ points.}\n \\label{fig:opcounts}\n\\end{figure}\n\n\\begin{table}[htb]\n \\centering\n \\begin{tabular}{|c|c|c|}\n \\hline\n Problem Size & Time (ms) & Distance Calculations \\\\ \\hline \\hline\n1024 & 11.0 & 523776 \\\\ \\hline\n2048 & 15.0 & 2096128 \\\\ \\hline\n4096 & 35.0 & 8386560 \\\\ \\hline\n8192 & 81.0 & 33550336 \\\\ \\hline\n16384 & 298.0 & 134209536 \\\\ \\hline\n32768 & 1171.0 & 536854528 \\\\ \\hline\n65536 & 4607.0 & 2147450880 \\\\ \\hline\n131072 & 18496.0 & 8589869056 \\\\ \\hline\n262144 & 84123.0 & 34359607296 \\\\ \\hline\n524288 & 368682.0 & 137438691328 \\\\ \\hline\n \\end{tabular}\n \\caption{Actual times and operation counts used to create the plots\n in Figure~\\ref{fig:timings} and Figure~\\ref{fig:opcounts}.}\n \\label{tab:rawdata}\n\\end{table}\n\nFigure~\\ref{fig:timings} shows the times in milliseconds (minimum\nacross 5 runs of each) and Figure~\\ref{fig:opcounts} shows the number\nof computations of the distance between two points for this study.\nUnsurprisingly, the timings are very similar and the operation counts\nidentical for the different ranges of point placements, so\nTable~\\ref{tab:rawdata} shows the data as plotted in the figures but\nonly for the range value of 1.0.\n\n\\subsection{Discussion}\n\nBoth the timings and distance calulation counts match well with the\nexpected $\\Theta(n^2)$ behavior of this algorithm. The graphs in\nFigures~\\ref{fig:timings} and~\\ref{fig:opcounts} show the expected\nparabolic shape. The actual numbers in Table~\\ref{tab:rawdata} align\nwell. The number of distance calculations is exactly as predicted.\nAny variation there would have indicated an error in the algorithm or\nin the instrumentation that counted the operations. For the timings,\nsmall problem sizes are subject to errors due to the accuracy of the\nmillsecond timer over short timespans. However, when we look at the\nlarger problem sizes, we see exactly what we would expect: when we\ndouble the problem size, the time taken to compute the solution\nincreased by a factor of four.\n\n\\section{Conclusions}\n\\label{sec:conclusions}\n\nIn this simple study, we found that all of our results matched the\nexpected behavior from the theory. In this particular algorithm,\nsince there are no asymptotic differences among the best-, average-,\nand worst-case behavior, this should be unsurprising. The small\nvariations in run time can perhaps be explained by how soon the\nalgorithm finds the closest pair (or at least a very close pair). The\nmore times that a new closest pair is found, the more often the body\nof the \\texttt{if} statement following the distance calculation will\nneed to execute. There is also the issue that the computer used for\nthe study is a laptop system that had many processes such as web\nbrowsers with many tabs and terminal windows in regular interactive\nuse during the timing studies. This is partially accounted for by\ntaking the minimum time across 5 runs, but as each run has its own set\nof random points generated, the previously-mentioned effect from the\ndifferent numbers of times the body of the \\texttt{if} statement is\nexecuted will potentially skew the results more toward a best case\nbehavior. Any such variations are likely minor, and do not decrease\nthe confidence in our conclusions that the timing results match\nclosely with theoretical expectations.\n\n\\end{document}\n", "meta": {"hexsha": "f0a120b44928651b3f84cc7d1dfbca5982f5ebd5", "size": 9216, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "writeup/writeup.tex", "max_stars_repo_name": "SienaCSISAlgorithms/SampleEmpiricalStudy", "max_stars_repo_head_hexsha": "2276a36ded3632cf5e5def4db93174a2de9d3426", "max_stars_repo_licenses": ["MIT"], "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/writeup.tex", "max_issues_repo_name": "SienaCSISAlgorithms/SampleEmpiricalStudy", "max_issues_repo_head_hexsha": "2276a36ded3632cf5e5def4db93174a2de9d3426", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-03-18T00:41:56.000Z", "max_issues_repo_issues_event_max_datetime": "2019-03-18T00:41:56.000Z", "max_forks_repo_path": "writeup/writeup.tex", "max_forks_repo_name": "SienaCSISAlgorithms/SampleEmpiricalStudy", "max_forks_repo_head_hexsha": "2276a36ded3632cf5e5def4db93174a2de9d3426", "max_forks_repo_licenses": ["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.4, "max_line_length": 76, "alphanum_fraction": 0.7639973958, "num_tokens": 2536, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48438008427698437, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.19366079623646132}}
{"text": "% Appendix B - details of fit\n\\chapter{Details of fitting}\n\\label{ch:fit-details}\n\n\\section{Analysis of TrmD in silico}\n\\label{sec:fit-details-trmd-theory}\n\n\\subsection{$C\\alpha$ map, $T=0.3\\epsilon$}\n\\label{subsec:trmd-ce}\n\\begin{minipage}[c]{0.7\\textwidth}\n \\includegraphics[width=\\textwidth]{trmd_ce_histograms.png}\n\\end{minipage}\n\\hfill\n\\begin{minipage}[c]{0.45\\textwidth}\n \\begin{itemize}\n \\item method = 'stretch-adjust';\n \\item $p_{prot}=0.2062$\n \\item $k_{prot}=0.0041$\n \\item states = 7 (30.1, 35.2, 57.0, 63.6, 65.3, 78.9, 90.8 nm);\n \\end{itemize}\n\\end{minipage}\n\n\\begin{figure}\n \\centering\n \\includegraphics[width=\\linewidth]{trmd_ce_contour_lengths_1.png}\n \\caption{All TrmD experimental traces ($C\\alpha$ map, $T=0.3\\epsilon$).}\n \\label{fig:trmd-ce-cl1}\n\\end{figure}\n\n\\begin{table}\n \\tiny\n \\centering\n \\caption{Parameters of TrmD fitting in simulations ($C\\alpha$ map, $T=0.3\\epsilon$)}\n \\label{tab:trmd-ce-parameters}\n \\begin{tabular}{c|c|c|c}\n \\textbf{Trace} & \\textbf{$p_{prot}$} & \\textbf{$k_{prot}$} & \\textbf{States [nm]}\\\\\\hline\n 1 & 0.203 & 0.004 & 9.9, 12.4, 13.7, 15.9, 19.5, 30.1, 31.2, 34.6, 37.7, 41.3, 44.1, 58.4, 65.0, 72.4, 78.8, 90.8\\\\\n 2 & 0.205 & 0.004 & 10.8, 14.8, 19.9, 30.3, 34.5, 37.3, 43.2, 46.2, 57.8, 62.6, 65.2, 78.9, 90.8\\\\\n 3 & 0.211 & 0.004 & 8.5, 11.1, 14.3, 19.6, 30.9, 34.3, 36.4, 40.0, 43.7, 55.6, 62.6, 65.4, 78.9, 90.9\\\\\n 4 & 0.206 & 0.004 & 9.8, 13.4, 17.3, 20.8, 29.1, 30.7, 36.8, 43.0, 54.8, 60.4, 63.9, 65.3, 78.8, 90.8\\\\\n 5 & 0.205 & 0.004 & 9.4, 12.6, 18.2, 30.5, 34.9, 38.3, 53.8, 62.4, 65.3, 72.9, 78.9, 90.9\\\\\\hline\n \\end{tabular}\n\\end{table}\n\n\\subsection{$C\\alpha$ map, $T=0.4\\epsilon$}\n\\label{subsec:trmd-cc}\n\\begin{minipage}[c]{0.7\\textwidth}\n \\includegraphics[width=\\textwidth]{trmd_cc_histograms.png}\n\\end{minipage}\n\\hfill\n\\begin{minipage}[c]{0.45\\textwidth}\n \\begin{itemize}\n \\item method = 'stretch-adjust';\n \\item $p_{prot}=0.4233$\n \\item $k_{prot}=0.0060$\n \\item states = 5 (33.6, 53.0, 62.8, 75.8, 90.9 nm);\n \\end{itemize}\n\\end{minipage}\n\n\\begin{figure}\n \\centering\n \\includegraphics[width=\\linewidth]{trmd_cc_contour_lengths_1.png}\n \\caption{All TrmD experimental traces ($C\\alpha$ map, $T=0.4\\epsilon$).}\n \\label{fig:trmd-cc-cl1}\n\\end{figure}\n\n\\begin{figure}\n \\centering\n \\includegraphics[width=\\linewidth]{trmd_cc_contour_lengths_2.png}\n \\caption{All TrmD experimental traces ($C\\alpha$ map, $T=0.4\\epsilon$).}\n \\label{fig:trmd-cc-cl2}\n\\end{figure}\n\n\\begin{table}\n \\tiny\n \\centering\n \\caption{Parameters of TrmD fitting in simulations ($C\\alpha$ map, $T=0.4\\epsilon$)}\n \\label{tab:trmd-cc-parameters}\n \\begin{tabular}{c|c|c|c}\n \\textbf{Trace} & \\textbf{$p_{prot}$} & \\textbf{$k_{prot}$} & \\textbf{States [nm]}\\\\\\hline\n 1 & 0.325 & 0.006 & 17.4, 29.6, 31.7, 32.7, 35.7, 43.3, 51.5, 59.3, 63.1, 75.3, 89.5, 90.9\\\\\n 2 & 0.339 & 0.007 & 14.5, 19.8, 27.6, 31.3, 34.8, 41.7, 52.3, 61.0, 64.8, 77.0, 90.9\\\\\n 3 & 0.345 & 0.007 & 14.8, 20.3, 24.1, 31.8, 32.0, 34.5, 49.4, 51.2, 53.0, 59.6, 63.4, 65.2, 77.3, 90.9\\\\\n 4 & 0.337 & 0.006 & 18.9, 28.0, 31.9, 35.1, 42.4, 49.0, 52.6, 62.7, 65.6, 70.3, 75.8, 76.9, 90.9, 152.9\\\\\n 5 & 0.335 & 0.006 & 18.6, 32.3, 33.8, 43.6, 48.0, 52.2, 57.4, 60.0, 61.6, 63.3, 73.2, 75.1, 90.8\\\\\n 6 & 0.338 & 0.006 & 23.4, 32.3, 33.2, 35.6, 45.2, 50.7, 53.5, 55.6, 58.4, 68.4, 73.8, 76.3, 90.9\\\\\n 7 & 1.635 & 0.000 & 51.9, 55.6, 57.3, 59.9, 63.6, 65.8, 68.3, 72.7, 77.7, 84.7, 101.6, 111.1, 122.4\\\\\n 8 & 0.340 & 0.007 & 23.1, 32.3, 33.4, 39.2, 40.9, 43.6, 51.6, 54.8, 56.9, 61.4, 64.4, 76.0, 90.9\\\\\n 9 & 0.324 & 0.006 & 28.0, 32.4, 36.0, 51.0, 54.5, 57.7, 60.8, 63.5, 75.7, 90.8\\\\\n 10 & 0.335 & 0.006 & 29.6, 32.4, 34.2, 50.9, 55.6, 58.9, 62.7, 64.5, 76.2, 78.2, 90.9\\\\\n 11 & 0.334 & 0.006 & 28.0, 29.2, 33.3, 36.1, 51.0, 53.9, 56.4, 61.4, 64.1, 76.0, 89.6, 90.9\\\\\n 12 & 0.339 & 0.007 & 27.0, 29.5, 35.1, 46.1, 51.1, 54.9, 66.2, 72.2, 74.8, 76.8, 90.9\\\\\n 13 & 0.343 & 0.007 & 28.2, 32.7, 34.7, 41.7, 50.0, 52.3, 54.3, 57.0, 67.3, 72.6, 76.1, 90.9\\\\\n 14 & 0.343 & 0.007 & 18.7, 32.6, 33.0, 35.9, 51.7, 55.9, 60.5, 69.5, 73.1, 90.9\\\\\n 15 & 0.337 & 0.006 & 17.5, 27.9, 34.4, 43.6, 52.0, 52.8, 54.5, 56.9, 60.8, 68.2, 73.0, 76.0, 76.9, 90.9\\\\\\hline\n \\end{tabular}\n\\end{table}\n\n\\subsection{$C\\alpha$ map, $T=0.5\\epsilon$}\n\\label{subsec:trmd-ca}\n\\begin{minipage}[c]{0.7\\textwidth}\n \\includegraphics[width=\\textwidth]{trmd_ca_histograms.png}\n\\end{minipage}\n\\hfill\n\\begin{minipage}[c]{0.45\\textwidth}\n \\begin{itemize}\n \\item method = 'stretch-adjust';\n \\item $p_{prot}=0.4642$\n \\item $k_{prot}=0.0077$\n \\item states = 6 (44.9, 50.8, 62.2, 67.8, 71.1, 90.8 nm);\n \\end{itemize}\n\\end{minipage}\n\n\\begin{figure}\n \\centering\n \\includegraphics[width=\\linewidth]{trmd_ca_contour_lengths_1.png}\n \\caption{All TrmD experimental traces ($C\\alpha$ map, $T=0.5\\epsilon$).}\n \\label{fig:trmd-ca-cl1}\n\\end{figure}\n\n\\begin{table}\n \\tiny\n \\centering\n \\caption{Parameters of TrmD fitting in simulations ($C\\alpha$ map, $T=0.5\\epsilon$)}\n \\label{tab:trmd-ca-parameters}\n \\begin{tabular}{c|c|c|c}\n \\textbf{Trace} & \\textbf{$p_{prot}$} & \\textbf{$k_{prot}$} & \\textbf{States [nm]}\\\\\\hline\n 1 & 0.465 & 0.008 & 21.6, 27.4, 34.1, 35.8, 39.1, 41.7, 49.2, 64.5, 72.4, 87.4, 90.9\\\\\n 2 & 0.456 & 0.007 & 24.4, 28.1, 30.7, 32.8, 35.9, 38.5, 45.7, 49.9, 51.9, 53.4, 58.2, 60.4, 62.0, 64.0, 66.3, 68.4, 70.4, 83.8, 89.5, 90.9\\\\\n 3 & 0.455 & 0.007 & 21.5, 39.8, 43.0, 45.5, 48.5, 52.8, 61.9, 67.7, 71.7, 87.1, 90.9\\\\\n 4 & 0.469 & 0.008 & 23.0, 26.1, 29.2, 31.3, 35.5, 38.4, 40.5, 43.5, 49.6, 51.3, 53.3, 57.5, 59.9, 61.6, 64.8, 70.6, 73.5, 83.7, 89.0, 90.9\\\\\n 5 & 0.472 & 0.008 & 22.0, 28.9, 32.0, 37.5, 44.1, 50.1, 58.0, 60.2, 62.4, 64.3, 66.3, 69.3, 90.8\\\\\n 6 & 0.479 & 0.008 & 20.8, 23.0, 25.1, 27.2, 30.9, 34.6, 36.4, 37.8, 44.0, 52.4, 52.5, 59.8, 63.5, 64.5, 66.9, 69.3, 71.0, 87.6, 90.9\\\\\n 7 & 0.482 & 0.008 & 20.8, 23.6, 26.7, 29.8, 40.2, 42.3, 45.2, 50.6, 55.1, 59.7, 63.2, 65.2, 66.9, 69.4, 84.6, 89.3, 91.0\\\\\n 8 & 0.449 & 0.007 & 15.8, 22.4, 26.2, 30.4, 33.8, 35.9, 39.3, 44.6, 45.7, 47.7, 50.3, 55.6, 61.8, 65.2, 66.8, 68.6, 83.9, 89.4, 90.9\\\\\n 9 & 0.431 & 0.006 & 20.5, 28.9, 33.9, 36.8, 39.7, 45.1, 48.2, 51.6, 54.6, 58.5, 60.2, 66.2, 71.6, 87.3, 90.8\\\\\n 10 & 0.484 & 0.009 & 22.2, 24.4, 26.4, 28.4, 32.9, 35.4, 38.1, 44.5, 52.6, 62.6, 66.0, 68.2, 70.4, 90.9\\\\\\hline\n \\end{tabular}\n\\end{table}\n\n\\subsection{$C\\alpha$ map, $T=0.6\\epsilon$}\n\\label{subsec:trmd-cb}\n\\begin{minipage}[c]{0.7\\textwidth}\n \\includegraphics[width=\\textwidth]{trmd_cb_histograms.png}\n\\end{minipage}\n\\hfill\n\\begin{minipage}[c]{0.45\\textwidth}\n \\begin{itemize}\n \\item method = 'stretch-adjust';\n \\item $p_{prot}=0.5861$\n \\item $k_{prot}=0.0101$\n \\item states = 2 (64.0, 90.9 nm);\n \\end{itemize}\n\\end{minipage}\n\n\\begin{figure}\n \\centering\n \\includegraphics[width=\\linewidth]{trmd_cb_contour_lengths_1.png}\n \\caption{All TrmD experimental traces ($C\\alpha$ map, $T=0.6\\epsilon$).}\n \\label{fig:trmd-cb-cl1}\n\\end{figure}\n\n\\begin{figure}\n \\centering\n \\includegraphics[width=\\linewidth]{trmd_cb_contour_lengths_2.png}\n \\caption{All TrmD experimental traces ($C\\alpha$ map, $T=0.6\\epsilon$).}\n \\label{fig:trmd-cb-cl2}\n\\end{figure}\n\n\\begin{table}\n \\tiny\n \\centering\n \\caption{Parameters of TrmD fitting in simulations ($C\\alpha$ map, $T=0.6\\epsilon$)}\n \\label{tab:trmd-cb-parameters}\n \\begin{tabular}{c|c|c|c}\n \\textbf{Trace} & \\textbf{$p_{prot}$} & \\textbf{$k_{prot}$} & \\textbf{States [nm]}\\\\\\hline\n 1 & 0.594 & 0.008 & 19.4, 21.8, 24.1, 26.8, 29.6, 32.2, 34.8, 37.6, 40.8, 43.5, 46.5, 49.7, 55.9, 63.5, 69.3, 77.4, 85.8, 90.9\\\\\n 2 & 0.602 & 0.009 & 23.1, 30.6, 36.3, 40.9, 44.5, 47.3, 50.3, 56.6, 64.5, 73.9, 80.5, 83.4, 87.8, 90.9\\\\\n 3 & 0.324 & 0.008 & 18.3, 22.0, 23.9, 25.2, 27.6, 30.5, 33.1, 39.1, 44.7, 47.9, 51.5, 54.6, 56.5, 60.2, 74.3, 86.9, 90.9\\\\\n 4 & 0.626 & 0.009 & 28.2, 31.3, 37.5, 42.8, 45.0, 47.6, 50.4, 53.3, 56.0, 58.7, 62.6, 66.5, 70.5, 75.3, 79.0, 82.1, 84.8, 90.8\\\\\n 5 & 0.643 & 0.010 & 26.6, 28.8, 33.0, 35.3, 40.0, 44.5, 48.0, 51.0, 53.3, 57.9, 67.2, 81.3, 88.0, 90.9\\\\\n 6 & 0.623 & 0.009 & 27.7, 32.1, 36.2, 40.1, 43.8, 47.7, 56.1, 62.7, 67.2, 84.2, 90.9\\\\\n 7 & 0.483 & 0.015 & 17.9, 20.6, 23.4, 25.7, 27.7, 31.1, 35.7, 40.6, 42.9, 44.7, 52.3, 60.0, 61.4, 76.7, 90.9\\\\\n 8 & 0.606 & 0.009 & 26.8, 33.8, 40.1, 43.4, 45.8, 47.9, 50.1, 58.2, 62.6, 67.2, 78.9, 85.8, 90.9\\\\\n 9 & 0.648 & 0.010 & 30.3, 36.8, 43.2, 45.2, 46.6, 49.1, 50.6, 53.4, 57.6, 66.1, 80.2, 85.4, 90.0, 91.0\\\\\n 10 & 0.625 & 0.009 & 31.5, 37.2, 40.7, 43.1, 45.0, 48.1, 50.3, 53.7, 57.7, 63.2, 75.3, 76.8, 79.6, 86.7, 90.2, 90.9, 92.1\\\\\n 11 & 0.625 & 0.009 & 29.1, 31.3, 33.2, 35.4, 38.9, 42.4, 47.1, 49.7, 57.7, 66.1, 84.5, 90.9\\\\\n 12 & 0.637 & 0.010 & 42.3, 45.9, 48.5, 58.0, 64.3, 67.2, 70.1, 77.9, 78.8, 86.5, 90.6, 91.0\\\\\n 13 & 0.667 & 0.011 & 28.9, 33.3, 38.6, 44.1, 50.4, 59.3, 63.1, 66.8, 76.6, 82.7, 89.4, 91.1\\\\\n 14 & 0.610 & 0.009 & 28.9, 37.6, 41.1, 44.3, 48.0, 53.1, 58.1, 61.7, 65.5, 74.0, 79.4, 85.9, 90.3, 90.9\\\\\n 15 & 0.479 & 0.015 & 17.2, 20.8, 23.2, 26.8, 30.2, 51.3, 54.4, 55.5, 58.3, 62.2, 70.6, 74.1, 77.9, 83.8, 89.3, 91.0\\\\\\hline\n \\end{tabular}\n\\end{table}\n\n\\subsection{$C\\alpha$ map, $T=0.5\\epsilon$, $\\kappa_S=0$}\n\\label{subsec:trmd-cd}\n\\begin{minipage}[c]{0.7\\textwidth}\n \\includegraphics[width=\\textwidth]{trmd_cd_histograms.png}\n\\end{minipage}\n\\hfill\n\\begin{minipage}[c]{0.45\\textwidth}\n \\begin{itemize}\n \\item method = 'stretch-adjust';\n \\item $p_{prot}=0.2660$\n \\item $k_{prot}=0.0052$\n \\item states = 5 (33.1, 55.4, 64.8, 78.5, 90.8 nm);\n \\end{itemize}\n\\end{minipage}\n\n\\begin{figure}\n \\centering\n \\includegraphics[width=\\linewidth]{trmd_cd_contour_lengths_1.png}\n \\caption{All TrmD experimental traces ($C\\alpha$ map, $T=0.5\\epsilon$, $\\kappa_S=0$).}\n \\label{fig:trmd-cd-cl1}\n\\end{figure}\n\n\\begin{figure}\n \\centering\n \\includegraphics[width=\\linewidth]{trmd_cd_contour_lengths_2.png}\n \\caption{All TrmD experimental traces ($C\\alpha$ map, $T=0.5\\epsilon$, $\\kappa_S=0$).}\n \\label{fig:trmd-cd-cl2}\n\\end{figure}\n\n\\begin{table}\n \\tiny\n \\centering\n \\caption{Parameters of TrmD fitting in simulations ($C\\alpha$ map, $T=0.5\\epsilon$, $\\kappa_S=0$)}\n \\label{tab:trmd-cd-parameters}\n \\begin{tabular}{c|c|c|c}\n \\textbf{Trace} & \\textbf{$p_{prot}$} & \\textbf{$k_{prot}$} & \\textbf{States [nm]}\\\\\\hline\n 1 & 0.267 & 0.005 & 10.5, 12.3, 13.9, 15.6, 18.1, 21.6, 25.5, 32.7, 47.8, 49.8, 52.1, 53.7, 55.7, 59.6, 64.8, 76.3, 78.4, 90.8\\\\\n 2 & 0.263 & 0.005 & 14.0, 29.2, 31.2, 32.5, 35.8, 49.7, 50.5, 55.9, 62.8, 65.1, 72.3, 78.5, 90.8\\\\\n 3 & 0.266 & 0.006 & 17.1, 29.7, 31.6, 35.1, 37.8, 50.1, 53.4, 56.2, 60.6, 63.8, 65.3, 78.6, 90.9\\\\\n 4 & 0.271 & 0.005 & 11.9, 18.3, 29.7, 31.8, 35.7, 50.0, 53.6, 56.2, 63.9, 76.9, 78.6, 90.8\\\\\n 5 & 0.264 & 0.005 & 12.3, 16.0, 22.0, 29.4, 31.8, 35.8, 41.4, 53.5, 57.1, 60.8, 63.9, 65.1, 78.5, 90.8\\\\\n 6 & 0.269 & 0.005 & 13.0, 21.4, 32.4, 32.9, 37.2, 40.4, 53.9, 62.0, 64.9, 78.6, 90.9\\\\\n 7 & 0.267 & 0.005 & 10.5, 18.6, 27.2, 29.9, 34.4, 40.1, 53.0, 56.5, 63.2, 65.3, 78.5, 90.8\\\\\n 8 & 0.255 & 0.005 & 11.0, 15.7, 17.6, 18.5, 20.9, 32.9, 49.8, 52.4, 60.8, 65.0, 77.0, 78.7, 90.8\\\\\n 9 & 0.266 & 0.005 & 16.6, 26.7, 32.6, 36.3, 39.1, 52.9, 57.7, 64.8, 76.6, 78.7, 90.8\\\\\n 10 & 0.265 & 0.005 & 11.1, 14.5, 17.5, 24.7, 26.7, 31.5, 33.5, 36.7, 44.0, 51.6, 55.6, 57.8, 60.8, 64.9, 78.7, 90.8\\\\\n 11 & 0.264 & 0.005 & 10.6, 13.1, 15.3, 17.3, 19.5, 21.0, 28.8, 31.9, 35.6, 37.8, 52.2, 58.0, 60.7, 63.6, 65.2, 72.3, 78.6, 90.8\\\\\n 12 & 0.263 & 0.005 & 9.3, 13.1, 15.4, 17.6, 19.3, 27.8, 30.1, 34.5, 38.6, 52.1, 54.8, 58.2, 62.7, 65.0, 77.6, 78.8, 90.9\\\\\n 13 & 0.274 & 0.006 & 14.5, 18.6, 21.6, 25.9, 30.5, 32.2, 35.3, 42.6, 52.3, 61.1, 64.9, 76.8, 90.0, 90.9\\\\\n 14 & 0.266 & 0.005 & 11.0, 13.6, 22.1, 28.9, 31.3, 35.1, 40.9, 54.0, 58.4, 63.9, 65.1, 78.4, 90.8\\\\\n 15 & 0.270 & 0.005 & 15.2, 17.1, 21.2, 32.3, 32.4, 35.8, 50.2, 55.1, 63.1, 65.1, 78.5, 90.8\\\\\\hline\n \\end{tabular}\n\\end{table}\n\n\\subsection{Tsai map, $T=0.4\\epsilon$}\n\\label{subsec:trmd-pc}\n\\begin{minipage}[c]{0.7\\textwidth}\n \\includegraphics[width=\\textwidth]{trmd_pc_histograms.png}\n\\end{minipage}\n\\hfill\n\\begin{minipage}[c]{0.45\\textwidth}\n \\begin{itemize}\n \\item method = 'stretch-adjust';\n \\item $p_{prot}=0.3968$\n \\item $k_{prot}=0.0048$\n \\item states = 8 (8.4, 25.7, 40.6, 58.0, 63.1, 65.6, 77.6, 90.8 nm);\n \\end{itemize}\n\\end{minipage}\n\n\\begin{figure}\n \\centering\n \\includegraphics[width=\\linewidth]{trmd_pc_contour_lengths_1.png}\n \\caption{All TrmD experimental traces (Tsai map, $T=0.4\\epsilon$).}\n \\label{fig:trmd-pc-cl1}\n\\end{figure}\n\n\\begin{figure}\n \\centering\n \\includegraphics[width=\\linewidth]{trmd_pc_contour_lengths_2.png}\n \\caption{All TrmD experimental traces (Tsai map, $T=0.4\\epsilon$).}\n \\label{fig:trmd-pc-cl2}\n\\end{figure}\n\n\\begin{table}\n \\tiny\n \\centering\n \\caption{Parameters of TrmD fitting in simulations (Tsai map, $T=0.4\\epsilon$)}\n \\label{tab:trmd-pc-parameters}\n \\begin{tabular}{c|c|c|c}\n \\textbf{Trace} & \\textbf{$p_{prot}$} & \\textbf{$k_{prot}$} & \\textbf{States [nm]}\\\\\\hline\n 1 & 0.400 & 0.005 & 8.5, 18.3, 25.8, 30.7, 38.4, 44.0, 60.1, 65.6, 77.5, 89.9, 90.9\\\\\n 2 & 0.402 & 0.005 & 8.4, 24.8, 30.8, 40.6, 44.0, 56.2, 61.3, 65.1, 66.3, 78.1, 90.9\\\\\n 3 & 0.409 & 0.005 & 8.3, 10.6, 24.5, 30.6, 39.1, 42.5, 58.2, 64.6, 66.4, 77.8, 90.8\\\\\n 4 & 0.404 & 0.005 & 8.5, 10.7, 25.6, 37.8, 41.2, 44.6, 58.3, 63.8, 77.4, 90.8\\\\\n 5 & 0.402 & 0.005 & 8.4, 24.5, 27.5, 31.5, 40.3, 53.6, 54.7, 58.7, 62.2, 64.4, 66.1, 78.0, 89.4, 90.9\\\\\n 6 & 0.403 & 0.005 & 8.1, 9.4, 13.3, 25.5, 31.6, 40.8, 44.2, 57.1, 60.9, 63.6, 76.2, 90.8\\\\\n 7 & 0.390 & 0.004 & 8.2, 11.2, 23.2, 26.3, 30.6, 38.9, 42.3, 56.8, 62.3, 74.4, 78.0, 90.8\\\\\n 8 & 0.400 & 0.005 & 8.3, 13.7, 25.7, 37.3, 41.3, 44.7, 56.6, 62.9, 66.0, 77.9, 90.2, 90.9\\\\\n 9 & 0.343 & 0.007 & 8.1, 17.2, 24.7, 29.8, 37.3, 42.3, 54.2, 59.5, 64.0, 76.5, 90.9\\\\\n 10 & 0.399 & 0.005 & 8.3, 10.5, 17.1, 25.5, 36.7, 38.5, 40.9, 44.8, 58.1, 62.6, 77.8, 90.8\\\\\n 11 & 0.399 & 0.005 & 8.4, 24.8, 30.6, 40.3, 44.5, 57.5, 62.6, 73.7, 77.7, 90.8\\\\\n 12 & 0.399 & 0.004 & 8.7, 25.2, 30.2, 36.7, 40.9, 55.5, 57.9, 62.9, 76.2, 89.4, 90.9\\\\\n 13 & 0.405 & 0.005 & 8.2, 10.6, 25.2, 30.8, 39.1, 43.5, 56.8, 62.4, 65.4, 77.8, 90.5, 90.9\\\\\n 14 & 0.403 & 0.005 & 8.4, 10.6, 24.8, 27.9, 29.2, 31.7, 41.0, 43.4, 45.2, 57.3, 62.4, 65.5, 77.8, 90.8, 95.0\\\\\n 15 & 0.396 & 0.004 & 8.5, 25.0, 30.3, 38.1, 41.0, 43.9, 56.0, 60.0, 69.0, 74.5, 78.0, 90.8\\\\\\hline\n \\end{tabular}\n\\end{table}\n\n\\subsection{Tsai map, $T=0.5\\epsilon$}\n\\label{subsec:trmd-pa}\n\\begin{minipage}[c]{0.7\\textwidth}\n \\includegraphics[width=\\textwidth]{trmd_pa_histograms.png}\n\\end{minipage}\n\\hfill\n\\begin{minipage}[c]{0.45\\textwidth}\n \\begin{itemize}\n \\item method = 'stretch-adjust';\n \\item $p_{prot}=0.4821$\n \\item $k_{prot}=0.0072$\n \\item states = 8 (9.2, 24.7, 36.0, 52.3, 65.0, 71.5, 74.3, 90.9 nm);\n \\end{itemize}\n\\end{minipage}\n\n\\begin{figure}\n \\centering\n \\includegraphics[width=\\linewidth]{trmd_pa_contour_lengths_1.png}\n \\caption{All TrmD experimental traces (Tsai map, $T=0.5\\epsilon$).}\n \\label{fig:trmd-pa-cl1}\n\\end{figure}\n\n\\begin{table}\n \\tiny\n \\centering\n \\caption{Parameters of TrmD fitting in simulations (Tsai map, $T=0.5\\epsilon$)}\n \\label{tab:trmd-pa-parameters}\n \\begin{tabular}{c|c|c|c}\n \\textbf{Trace} & \\textbf{$p_{prot}$} & \\textbf{$k_{prot}$} & \\textbf{States [nm]}\\\\\\hline\n 1 & 0.460 & 0.007 & 9.2, 13.0, 16.6, 21.1, 25.2, 35.6, 45.7, 49.2, 56.4, 60.2, 62.0, 64.8, 71.6, 90.8\\\\\n 2 & 0.463 & 0.007 & 8.9, 13.2, 23.7, 26.5, 35.9, 50.7, 54.3, 61.0, 61.8, 66.5, 70.7, 72.1, 75.0, 87.9, 90.9\\\\\n 3 & 0.445 & 0.007 & 8.6, 10.9, 16.0, 21.8, 26.2, 35.8, 50.5, 62.5, 65.9, 71.4, 73.9, 90.8\\\\\n 4 & 0.563 & 0.007 & 9.3, 10.3, 19.9, 25.8, 30.0, 36.8, 54.3, 65.3, 70.9, 76.1, 90.9\\\\\n 5 & 0.538 & 0.006 & 8.6, 10.2, 22.0, 26.3, 37.1, 52.2, 59.7, 66.8, 72.1, 73.8, 76.3, 88.8, 90.9\\\\\n 6 & 0.462 & 0.007 & 9.4, 12.3, 15.1, 20.6, 25.5, 35.3, 51.8, 60.5, 63.8, 67.1, 69.1, 72.0, 88.1, 90.9\\\\\n 7 & 0.462 & 0.007 & 9.0, 13.2, 16.7, 18.8, 24.7, 36.4, 50.6, 60.3, 62.7, 65.0, 66.9, 69.0, 71.2, 74.5, 90.8\\\\\n 8 & 0.483 & 0.008 & 9.1, 12.7, 23.9, 35.2, 47.0, 47.7, 57.1, 61.0, 64.0, 69.5, 83.2, 89.3, 91.0\\\\\n 9 & 0.469 & 0.008 & 9.0, 19.2, 25.2, 36.5, 60.9, 64.1, 67.2, 70.5, 72.6, 73.5, 74.7, 88.8, 90.9\\\\\n 10 & 0.474 & 0.008 & 9.2, 12.4, 20.1, 22.4, 25.2, 35.5, 49.3, 60.4, 67.6, 70.1, 73.6, 90.9\\\\\\hline\n \\end{tabular}\n\\end{table}\n\n\\subsection{Tsai map, $T=0.6\\epsilon$}\n\\label{subsec:trmd-pb}\n\\begin{minipage}[c]{0.7\\textwidth}\n \\includegraphics[width=\\textwidth]{trmd_pb_histograms.png}\n\\end{minipage}\n\\hfill\n\\begin{minipage}[c]{0.45\\textwidth}\n \\begin{itemize}\n \\item method = 'stretch-adjust';\n \\item $p_{prot}=0.6279$\n \\item $k_{prot}=0.0092$\n \\item states = 4 (34.4, 36.4, 64.4, 90.8 nm);\n \\end{itemize}\n\\end{minipage}\n\n\\begin{figure}\n \\centering\n \\includegraphics[width=\\linewidth]{trmd_pb_contour_lengths_1.png}\n \\caption{All TrmD experimental traces (Tsai map, $T=0.6\\epsilon$).}\n \\label{fig:trmd-pb-cl1}\n\\end{figure}\n\n\\begin{figure}\n \\centering\n \\includegraphics[width=\\linewidth]{trmd_pb_contour_lengths_2.png}\n \\caption{All TrmD experimental traces (Tsai map, $T=0.6\\epsilon$).}\n \\label{fig:trmd-pb-cl2}\n\\end{figure}\n\n\\begin{table}\n \\tiny\n \\centering\n \\caption{Parameters of TrmD fitting in simulations (Tsai map, $T=0.6\\epsilon$)}\n \\label{tab:trmd-pb-parameters}\n \\begin{tabular}{c|c|c|c}\n \\textbf{Trace} & \\textbf{$p_{prot}$} & \\textbf{$k_{prot}$} & \\textbf{States [nm]}\\\\\\hline\n 1 & 0.598 & 0.008 & 10.3, 13.1, 17.1, 24.2, 28.0, 29.9, 31.9, 33.9, 36.9, 38.4, 43.4, 49.6, 53.2, 60.1, 66.5, 77.1, 84.1, 89.0, 90.9\\\\\n 2 & 0.646 & 0.010 & 9.9, 12.0, 13.9, 17.1, 20.3, 23.0, 25.5, 28.1, 31.3, 34.9, 40.4, 44.3, 45.7, 47.2, 55.1, 62.2, 65.8, 69.2, 84.9, 90.9\\\\\n 3 & 0.601 & 0.008 & 11.1, 15.4, 18.6, 21.0, 21.9, 25.4, 30.3, 32.3, 34.4, 36.8, 39.3, 44.1, 53.4, 63.0, 69.3, 70.7, 85.0, 89.7, 90.9\\\\\n 4 & 0.646 & 0.010 & 12.5, 23.9, 28.4, 30.2, 34.6, 36.4, 38.4, 40.7, 44.0, 60.5, 60.6, 64.8, 69.1, 83.7, 89.5, 91.0\\\\\n 5 & 0.627 & 0.009 & 11.2, 14.6, 18.0, 24.6, 29.7, 32.5, 34.1, 35.6, 37.8, 43.1, 52.2, 59.3, 61.8, 64.4, 70.5, 76.2, 84.5, 90.9\\\\\n 6 & 0.650 & 0.010 & 11.4, 14.9, 17.9, 22.6, 25.5, 28.6, 33.8, 37.4, 39.9, 49.2, 66.2, 90.8\\\\\n 7 & 0.637 & 0.010 & 11.4, 15.4, 18.0, 20.3, 22.9, 25.3, 27.0, 30.7, 34.3, 38.8, 44.9, 47.2, 49.6, 56.5, 61.1, 63.0, 66.7, 75.0, 80.9, 88.2, 91.0\\\\\n 8 & 0.639 & 0.009 & 10.5, 12.4, 14.0, 17.3, 22.3, 25.4, 28.6, 31.2, 33.7, 37.3, 41.2, 44.1, 46.4, 48.5, 50.5, 52.1, 56.9, 65.6, 74.5, 86.0, 90.9\\\\\n 9 & 0.615 & 0.009 & 9.9, 11.9, 14.8, 18.9, 23.6, 27.1, 33.1, 35.7, 38.1, 40.0, 45.5, 50.0, 53.7, 58.7, 62.7, 66.7, 81.0, 86.2, 89.6, 90.9\\\\\n 10 & 0.605 & 0.009 & 8.6, 11.3, 13.7, 18.8, 22.7, 26.0, 30.3, 35.2, 40.1, 52.4, 59.3, 61.6, 65.9, 81.5, 85.3, 89.0, 90.9\\\\\n 11 & 0.638 & 0.010 & 13.6, 18.6, 22.9, 25.9, 28.4, 31.7, 35.7, 36.0, 52.7, 57.6, 59.3, 62.5, 66.6, 73.8, 73.8, 84.5, 89.9, 90.9\\\\\n 12 & 0.643 & 0.010 & 12.7, 17.4, 20.2, 23.6, 28.2, 32.1, 35.9, 42.3, 58.7, 63.7, 65.7, 69.1, 83.8, 89.4, 91.0\\\\\n 13 & 0.580 & 0.008 & 10.4, 15.3, 17.1, 21.9, 24.6, 26.8, 29.4, 34.2, 37.5, 44.0, 48.3, 54.4, 58.8, 64.8, 84.3, 89.2, 90.9\\\\\n 14 & 0.642 & 0.010 & 12.4, 15.3, 20.7, 24.8, 26.9, 28.7, 31.3, 36.4, 42.9, 47.7, 50.3, 52.9, 55.4, 58.2, 61.8, 65.5, 73.3, 82.2, 88.8, 90.9\\\\\n 15 & 0.652 & 0.010 & 10.6, 13.6, 19.5, 24.7, 29.0, 34.0, 36.5, 39.1, 41.3, 43.2, 44.7, 55.5, 65.3, 69.0, 90.9\\\\\\hline\n \\end{tabular}\n\\end{table}\n\n\\subsection{Tsai map, $T=0.5\\epsilon$, $\\kappa_S=0$}\n\\label{subsec:trmd-pd}\n\\begin{minipage}[c]{0.7\\textwidth}\n \\includegraphics[width=\\textwidth]{trmd_pd_histograms.png}\n\\end{minipage}\n\\hfill\n\\begin{minipage}[c]{0.45\\textwidth}\n \\begin{itemize}\n \\item method = 'stretch-adjust';\n \\item $p_{prot}=0.2927$\n \\item $k_{prot}=0.0118$\n \\item states = 18 (8.4, 17.1, 21.7, 25.7, 35.2, 37.5, 47.2, 48.8, 50.4, 52.5, 55.7, 64.3, 67.7, 70.5, 73.7, 78.3, 83.2, 90.5 nm);\n \\end{itemize}\n\\end{minipage}\n\n\\begin{figure}\n \\centering\n \\includegraphics[width=\\linewidth]{trmd_pd_contour_lengths_1.png}\n \\caption{All TrmD experimental traces (Tsai map, $T=0.5\\epsilon$, $\\kappa_S=0$).}\n \\label{fig:trmd-pd-cl1}\n\\end{figure}\n\n\\begin{table}\n \\tiny\n \\centering\n \\caption{Parameters of TrmD fitting in simulations (Tsai map, $T=0.5\\epsilon$, $\\kappa_S=0$)}\n \\label{tab:trmd-pd-parameters}\n \\begin{tabular}{c|c|c|c}\n \\textbf{Trace} & \\textbf{$p_{prot}$} & \\textbf{$k_{prot}$} & \\textbf{States [nm]}\\\\\\hline\n 1 & 0.000 & 0.027 & 5.6, 7.6, 12.3, 19.3, 20.8, 23.5, 26.4, 29.9, 31.5, 32.2, 35.3, 37.8, 40.4, 42.2, 44.8, 46.6, 47.6, 49.0, 52.2, 53.7, 56.9, 59.7, 61.3, 66.2, 72.4, 74.9\\\\\n 2 & 0.440 & 0.002 & 8.3, 11.4, 15.7, 18.3, 21.2, 23.7, 26.3, 31.7, 34.5, 38.0, 51.3, 52.4, 54.4, 56.1, 57.6, 59.9, 67.1, 72.4, 76.9, 80.1, 83.5, 88.5, 90.8\\\\\n 3 & 0.361 & 0.004 & 8.2, 14.3, 18.0, 20.3, 24.6, 27.3, 32.2, 36.5, 40.6, 46.4, 50.5, 52.8, 56.4, 59.7, 62.4, 64.4, 67.2, 69.0, 71.3, 73.9, 81.8, 88.5, 90.7\\\\\n 4 & 0.388 & 0.004 & 8.4, 11.5, 14.7, 22.8, 26.1, 34.6, 36.9, 48.2, 52.1, 53.5, 56.4, 62.9, 63.6, 67.6, 71.8, 78.9, 83.3, 86.0, 89.3, 90.7\\\\\n 5 & 0.455 & 0.003 & 9.1, 12.7, 16.3, 20.1, 21.9, 26.5, 30.9, 36.1, 45.4, 46.4, 48.3, 54.3, 57.7, 60.3, 63.3, 65.7, 66.9, 68.3, 71.8, 75.8, 77.5, 83.6, 89.1, 90.7\\\\\n 6 & 0.011 & 0.016 & 6.3, 10.1, 13.1, 16.1, 17.8, 19.4, 20.7, 22.7, 25.2, 27.0, 28.7, 30.6, 34.4, 37.7, 39.5, 41.2, 45.9, 48.7, 50.7, 54.0, 57.4, 61.8, 66.6, 68.4, 70.1, 73.5, 77.7, 79.3\\\\\n 7 & 0.467 & 0.003 & 8.2, 9.5, 15.8, 23.2, 25.3, 27.2, 34.8, 38.2, 45.8, 47.0, 50.9, 52.5, 54.0, 56.6, 65.0, 67.5, 70.9, 75.0, 83.9, 86.4, 89.5, 90.8\\\\\n 8 & 0.000 & 0.031 & 5.9, 9.1, 15.4, 18.5, 20.3, 21.9, 25.7, 29.0, 31.0, 34.6, 38.3, 40.6, 42.6, 44.9, 47.7, 50.6, 52.6, 55.5, 58.9, 62.8, 65.8, 68.8, 71.5, 73.8\\\\\n 9 & 0.078 & 0.011 & 7.2, 10.3, 12.8, 18.3, 21.6, 24.1, 29.3, 31.9, 33.9, 38.6, 41.2, 42.6, 48.0, 50.4, 52.7, 56.8, 59.2, 63.8, 67.4, 70.4, 72.8, 78.1, 82.9\\\\\n 10 & 0.027 & 0.018 & 6.8, 11.0, 13.1, 15.2, 18.7, 21.7, 24.6, 28.1, 31.2, 33.8, 37.9, 41.4, 43.6, 46.3, 49.9, 53.0, 56.4, 59.0, 61.0, 67.2, 70.8, 75.4, 78.2\\\\\\hline\n \\end{tabular}\n\\end{table}\n\n\\subsection{SMOG map, $T=0.4\\epsilon$}\n\\label{subsec:trmd-sc}\n\\begin{minipage}[c]{0.7\\textwidth}\n \\includegraphics[width=\\textwidth]{trmd_sc_histograms.png}\n\\end{minipage}\n\\hfill\n\\begin{minipage}[c]{0.45\\textwidth}\n \\begin{itemize}\n \\item method = 'stretch-adjust';\n \\item $p_{prot}=0.2312$\n \\item $k_{prot}=0.0073$\n \\item states = 3 (6.2, 45.8, 88.4 nm);\n \\end{itemize}\n\\end{minipage}\n\n\\begin{figure}\n \\centering\n \\includegraphics[width=\\linewidth]{trmd_sc_contour_lengths_1.png}\n \\caption{All TrmD experimental traces (SMOG map, $T=0.4\\epsilon$).}\n \\label{fig:trmd-sc-cl1}\n\\end{figure}\n\n\\begin{figure}\n \\centering\n \\includegraphics[width=\\linewidth]{trmd_sc_contour_lengths_2.png}\n \\caption{All TrmD experimental traces (SMOG map, $T=0.4\\epsilon$).}\n \\label{fig:trmd-sc-cl2}\n\\end{figure}\n\n\\begin{table}\n \\tiny\n \\centering\n \\caption{Parameters of TrmD fitting in simulations (SMOG map, $T=0.4\\epsilon$)}\n \\label{tab:trmd-sc-parameters}\n \\begin{tabular}{c|c|c|c}\n \\textbf{Trace} & \\textbf{$p_{prot}$} & \\textbf{$k_{prot}$} & \\textbf{States [nm]}\\\\\\hline\n 1 & 0.144 & 0.009 & 5.9, 13.7, 29.6, 31.6, 35.1, 44.2, 57.4, 68.5, 73.5, 80.8, 85.4\\\\\n 2 & 0.347 & 0.005 & 6.6, 14.4, 26.5, 33.9, 38.2, 46.9, 72.7, 77.9, 90.1\\\\\n 3 & 0.016 & 0.015 & 5.1, 12.6, 20.6, 26.9, 29.8, 32.9, 41.3, 64.0, 69.0, 80.1\\\\\n 4 & 0.321 & 0.005 & 6.5, 14.7, 28.5, 33.4, 37.5, 46.7, 60.5, 72.4, 77.5, 85.0, 89.7\\\\\n 5 & 0.320 & 0.005 & 0.0, 6.5, 15.2, 27.0, 31.2, 34.0, 37.4, 46.7, 60.7, 72.3, 77.5, 85.2, 89.8\\\\\n 6 & 0.179 & 0.009 & 6.0, 13.9, 24.1, 29.1, 32.1, 35.5, 44.8, 58.2, 69.3, 74.4, 86.2\\\\\n 7 & 0.373 & 0.004 & 6.7, 14.6, 30.0, 34.1, 38.2, 47.3, 61.5, 73.2, 78.4, 90.9\\\\\n 8 & 0.161 & 0.009 & 6.0, 13.6, 23.4, 29.5, 32.3, 35.9, 44.5, 57.9, 68.9, 74.0, 85.8\\\\\n 9 & 0.255 & 0.007 & 6.3, 14.0, 27.2, 32.2, 33.5, 37.1, 45.8, 59.4, 71.0, 76.1, 88.1\\\\\n 10 & 0.093 & 0.012 & 5.6, 13.0, 27.3, 31.0, 35.0, 43.2, 56.1, 67.0, 72.0, 83.5\\\\\n 11 & 0.297 & 0.004 & 6.5, 14.1, 30.5, 33.8, 38.0, 46.5, 72.0, 77.2, 90.9\\\\\n 12 & 0.177 & 0.009 & 6.0, 13.8, 27.8, 31.8, 35.7, 44.7, 58.1, 69.3, 74.3, 86.2\\\\\n 13 & 0.254 & 0.007 & 6.3, 14.6, 30.4, 33.3, 37.1, 45.8, 71.1, 76.1, 88.1\\\\\n 14 & 0.252 & 0.007 & 6.3, 14.1, 25.8, 32.6, 36.7, 45.7, 70.8, 75.9, 87.9\\\\\n 15 & 0.278 & 0.006 & 0.0, 6.5, 14.3, 29.5, 33.1, 36.7, 46.1, 59.9, 71.5, 76.7, 88.8\\\\\\hline\n \\end{tabular}\n\\end{table}\n\n\\subsection{SMOG map, $T=0.5\\epsilon$}\n\\label{subsec:trmd-sa}\n\\begin{minipage}[c]{0.7\\textwidth}\n \\includegraphics[width=\\textwidth]{trmd_sa_histograms.png}\n\\end{minipage}\n\\hfill\n\\begin{minipage}[c]{0.45\\textwidth}\n \\begin{itemize}\n \\item method = 'stretch-adjust';\n \\item $p_{prot}=0.4815$\n \\item $k_{prot}=0.0059$\n \\item states = 3 (46.9, 77.8, 90.5 nm);\n \\end{itemize}\n\\end{minipage}\n\n\\begin{figure}\n \\centering\n \\includegraphics[width=\\linewidth]{trmd_sa_contour_lengths_1.png}\n \\caption{All TrmD experimental traces (SMOG map, $T=0.5\\epsilon$).}\n \\label{fig:trmd-sa-cl1}\n\\end{figure}\n\n\\begin{table}\n \\tiny\n \\centering\n \\caption{Parameters of TrmD fitting in simulations (SMOG map, $T=0.5\\epsilon$)}\n \\label{tab:trmd-sa-parameters}\n \\begin{tabular}{c|c|c|c}\n \\textbf{Trace} & \\textbf{$p_{prot}$} & \\textbf{$k_{prot}$} & \\textbf{States [nm]}\\\\\\hline\n 1 & 0.358 & 0.008 & 6.9, 12.8, 24.0, 31.4, 36.1, 45.4, 69.9, 75.5, 88.4\\\\\n 2 & 0.512 & 0.005 & 7.5, 13.2, 24.1, 31.7, 34.0, 37.9, 47.2, 73.4, 78.1, 90.9\\\\\n 3 & 0.475 & 0.006 & 7.3, 12.9, 24.0, 27.1, 32.4, 35.7, 37.2, 46.8, 71.8, 77.7, 89.9, 90.2\\\\\n 4 & 0.514 & 0.005 & 7.4, 13.6, 24.6, 30.0, 33.7, 37.5, 47.2, 72.5, 78.4, 90.8\\\\\n 5 & 0.518 & 0.005 & 7.4, 12.5, 26.5, 33.0, 38.0, 47.3, 72.9, 78.5, 90.8, 90.9\\\\\n 6 & 0.530 & 0.006 & 7.7, 13.1, 25.5, 28.8, 32.9, 37.7, 47.3, 66.3, 78.2, 90.9\\\\\n 7 & 0.515 & 0.005 & 7.5, 13.5, 29.4, 31.6, 34.2, 47.0, 60.4, 73.3, 78.1, 90.0, 90.9\\\\\n 8 & 0.515 & 0.005 & 7.2, 8.1, 13.1, 23.5, 29.7, 33.1, 37.6, 47.3, 61.2, 78.2, 90.9\\\\\n 9 & 0.448 & 0.007 & 7.3, 12.6, 28.0, 32.9, 37.1, 46.5, 77.0, 86.0, 89.6\\\\\n 10 & 0.429 & 0.007 & 7.1, 11.9, 14.6, 27.5, 32.2, 36.7, 45.9, 59.1, 69.9, 76.6, 88.7, 89.3\\\\\\hline\n \\end{tabular}\n\\end{table}\n\n\\subsection{SMOG map, $T=0.6\\epsilon$}\n\\label{subsec:trmd-sb}\n\\begin{minipage}[c]{0.7\\textwidth}\n \\includegraphics[width=\\textwidth]{trmd_sb_histograms.png}\n\\end{minipage}\n\\hfill\n\\begin{minipage}[c]{0.45\\textwidth}\n \\begin{itemize}\n \\item method = 'stretch-adjust';\n \\item $p_{prot}=0.6131$\n \\item $k_{prot}=0.0063$\n \\item states = 3 (45.9, 75.9, 90.8 nm);\n \\end{itemize}\n\\end{minipage}\n\n\\begin{figure}\n \\centering\n \\includegraphics[width=\\linewidth]{trmd_sb_contour_lengths_1.png}\n \\caption{All TrmD experimental traces (SMOG map, $T=0.6\\epsilon$).}\n \\label{fig:trmd-sb-cl1}\n\\end{figure}\n\n\\begin{figure}\n \\centering\n \\includegraphics[width=\\linewidth]{trmd_sb_contour_lengths_2.png}\n \\caption{All TrmD experimental traces (SMOG map, $T=0.6\\epsilon$).}\n \\label{fig:trmd-sb-cl2}\n\\end{figure}\n\n\\begin{table}\n \\tiny\n \\centering\n \\caption{Parameters of TrmD fitting in simulations (SMOG map, $T=0.6\\epsilon$)}\n \\label{tab:trmd-sb-parameters}\n \\begin{tabular}{c|c|c|c}\n \\textbf{Trace} & \\textbf{$p_{prot}$} & \\textbf{$k_{prot}$} & \\textbf{States [nm]}\\\\\\hline\n 1 & 0.578 & 0.008 & 8.5, 12.6, 28.2, 30.9, 32.2, 35.5, 45.4, 75.3, 90.8\\\\\n 2 & 0.594 & 0.004 & 8.6, 11.7, 13.3, 23.0, 30.1, 45.8, 72.9, 76.3, 90.7\\\\\n 3 & 0.601 & 0.009 & 8.5, 12.6, 29.5, 45.6, 75.2, 89.0, 90.9, 139.6\\\\\n 4 & 0.613 & 0.004 & 8.6, 12.4, 24.1, 29.6, 31.0, 45.3, 71.6, 76.5, 90.7\\\\\n 5 & 0.608 & 0.004 & 8.4, 12.3, 29.3, 29.7, 35.6, 46.1, 76.1, 89.5, 90.9\\\\\n 6 & 0.591 & 0.004 & 8.2, 11.8, 22.4, 24.8, 29.8, 36.8, 46.2, 69.0, 75.2, 90.6\\\\\n 7 & 0.593 & 0.008 & 8.3, 10.4, 13.9, 29.6, 36.2, 45.6, 75.3, 90.8\\\\\n 8 & 0.595 & 0.004 & 8.3, 12.4, 25.9, 31.7, 44.4, 46.4, 74.8, 88.7, 90.8\\\\\n 9 & 0.587 & 0.008 & 8.5, 13.0, 27.4, 30.6, 44.8, 72.4, 75.1, 89.3, 90.9\\\\\n 10 & 0.689 & 0.007 & 8.9, 13.6, 28.7, 32.7, 36.7, 46.5, 73.7, 77.4, 90.8\\\\\n 11 & 0.692 & 0.007 & 9.2, 13.2, 25.5, 28.0, 31.6, 36.6, 46.7, 77.5, 79.1, 90.9\\\\\n 12 & 0.585 & 0.008 & 9.0, 12.9, 24.9, 29.7, 35.6, 45.6, 71.2, 76.0, 90.9\\\\\n 13 & 0.675 & 0.007 & 9.0, 13.8, 30.4, 32.6, 46.6, 77.3, 90.8, 94.0\\\\\n 14 & 0.590 & 0.009 & 8.4, 12.3, 24.9, 27.4, 30.1, 34.9, 44.3, 46.3, 74.6, 90.8\\\\\n 15 & 0.604 & 0.004 & 8.7, 10.8, 13.0, 23.1, 28.2, 31.7, 46.0, 73.4, 76.5, 90.7\\\\\\hline\n \\end{tabular}\n\\end{table}\n\n\\subsection{SMOG map, $T=0.5\\epsilon$, $\\kappa_S=0$}\n\\label{subsec:trmd-sd}\n\\begin{minipage}[c]{0.7\\textwidth}\n \\includegraphics[width=\\textwidth]{trmd_sd_histograms.png}\n\\end{minipage}\n\\hfill\n\\begin{minipage}[c]{0.45\\textwidth}\n \\begin{itemize}\n \\item method = 'stretch-adjust';\n \\item $p_{prot}=0.2397$\n \\item $k_{prot}=0.0144$\n \\item states = 15 (7.6, 12.5, 15.7, 19.9, 26.8, 31.7, 37.2, 44.9, 47.1, 52.5, 60.9, 67.1, 72.0, 78.1, 90.3 nm);\n \\end{itemize}\n\\end{minipage}\n\n\\begin{figure}\n \\centering\n \\includegraphics[width=\\linewidth]{trmd_sd_contour_lengths_1.png}\n \\caption{All TrmD experimental traces (SMOG map, $T=0.5\\epsilon$, $\\kappa_S=0$).}\n \\label{fig:trmd-sd-cl1}\n\\end{figure}\n\n\\begin{table}\n \\centering\n \\caption{Parameters of TrmD fitting in simulations (SMOG map, $T=0.5\\epsilon$, $\\kappa_S=0$)}\n \\label{tab:trmd-sd-parameters}\n \\begin{tabular}{c|c|c|c}\n \\textbf{Trace} & \\textbf{$p_{prot}$} & \\textbf{$k_{prot}$} & \\textbf{States [nm]}\\\\\\hline\n 1 & 0.000 & 0.003 & 6.5, 10.8, 28.7, 35.5, 38.8, 40.8, 43.5, 45.4, 50.7, 53.8, 56.3, 58.8, 60.8, 64.6, 66.6, 67.7, 69.9, 73.6, 79.6, 80.9, 81.7\\\\\n 2 & 2.026 & 0.000 & 11.7, 22.6, 29.8, 32.9, 34.8, 36.7, 40.0, 44.0, 46.9, 50.9, 57.9, 60.7, 64.3, 70.4, 73.9, 76.1, 78.6, 80.7, 82.8, 85.9, 88.0, 91.2, 98.4, 103.3, 106.7, 112.4, 112.4, 117.4, 121.0\\\\\n 3 & 0.028 & 0.010 & 9.6, 16.4, 19.6, 25.2, 27.1, 29.9, 32.7, 37.8, 41.4, 46.5, 48.8, 51.8, 55.6, 59.6, 61.0, 64.4, 67.7, 72.0, 77.5, 80.8\\\\\n 4 & 0.000 & 0.008 & 13.0, 23.0, 25.9, 28.2, 30.3, 32.0, 34.0, 35.8, 38.4, 40.6, 43.5, 46.5, 50.8, 52.5, 54.8, 57.3, 59.3, 61.5, 64.0, 66.3, 69.6, 74.9, 79.3\\\\\n 5 & 0.425 & 0.000 & 7.8, 12.9, 15.0, 17.6, 20.4, 24.7, 28.0, 30.7, 32.9, 36.5, 46.3, 54.8, 57.6, 60.6, 64.8, 73.7, 77.2, 84.4, 90.8, 92.6\\\\\n 6 & 0.432 & 0.002 & 7.7, 12.4, 15.4, 24.7, 28.3, 33.0, 37.9, 44.8, 47.0, 53.9, 60.9, 63.4, 74.1, 77.0, 87.8, 90.5\\\\\n 7 & 0.002 & 0.005 & 5.7, 8.3, 16.7, 19.5, 22.8, 25.3, 27.8, 30.9, 34.2, 37.5, 39.5, 41.1, 45.0, 48.5, 50.8, 53.9, 56.3, 57.5, 59.4, 63.4, 64.5, 66.5, 67.9, 70.1, 71.0, 73.2, 78.5, 80.9, 81.9\\\\\n 8 & 0.593 & 0.006 & 8.1, 14.4, 20.4, 23.3, 26.1, 30.3, 33.4, 35.1, 37.5, 44.1, 47.7, 48.0, 52.0, 54.0, 59.0, 62.4, 64.8, 66.3, 68.0, 69.8, 73.3, 79.0, 87.3, 91.6, 91.9\\\\\n 9 & 0.001 & 0.006 & 5.5, 7.7, 14.9, 21.5, 28.2, 31.6, 38.0, 40.8, 44.2, 47.0, 50.5, 54.2, 56.2, 58.2, 59.4, 61.5, 65.1, 67.0, 69.8, 74.2, 79.3, 80.6\\\\\n 10 & 0.469 & 0.004 & 7.0, 8.2, 13.2, 15.6, 22.7, 26.7, 30.0, 31.9, 33.0, 34.0, 37.2, 46.4, 57.1, 60.4, 63.7, 76.4, 90.0\\\\\\hline\n \\end{tabular}\n\\end{table}\n\n\\section{Analysis of no-knot-TrmD in silico}\n\\label{sec:fit-details-no-knot-trmd-theory}\n\\subsection{$C\\alpha$ map, $T=0.4\\epsilon$}\n\\label{subsec:no-knot-trmd-cc}\n\\begin{minipage}[c]{0.7\\textwidth}\n \\includegraphics[width=\\textwidth]{trmd-no-knot_cc_histograms.png}\n\\end{minipage}\n\\hfill\n\\begin{minipage}[c]{0.45\\textwidth}\n \\begin{itemize}\n \\item method = 'stretch-adjust';\n \\item $p_{prot}=0.2450$\n \\item $k_{prot}=0.0161$\n \\item states = 10 (30.1, 35.6, 37.7, 40.3, 47.6, 50.7, 66.7, 77.8, 89.0, 90.9 nm);\n \\end{itemize}\n\\end{minipage}\n\n\\begin{figure}\n \\centering\n \\includegraphics[width=\\linewidth]{trmd-no-knot_cc_contour_lengths_1.png}\n \\caption{All no-knot-TrmD experimental traces ($C\\alpha$ map, $T=0.4\\epsilon$).}\n \\label{fig:no-knot-trmd-cc-cl1}\n\\end{figure}\n\n\\begin{table}\n \\tiny\n \\centering\n \\caption{Parameters of no-knot-TrmD fitting in simulations ($C\\alpha$ map, $T=0.4\\epsilon$)}\n \\label{tab:no-knot-trmd-cc-parameters}\n \\begin{tabular}{c|c|c|c}\n \\textbf{Trace} & \\textbf{$p_{prot}$} & \\textbf{$k_{prot}$} & \\textbf{States [nm]}\\\\\\hline\n 1 & 0.199 & 0.012 & 13.2, 21.3, 24.3, 28.6, 35.6, 39.3, 43.6, 50.1, 54.3, 57.0, 60.0, 65.0, 65.4, 76.9, 78.4, 90.6\\\\\n 2 & 0.250 & 0.016 & 10.8, 18.5, 23.9, 29.5, 38.1, 42.3, 45.1, 51.2, 55.4, 61.4, 65.4, 68.0, 70.3, 72.1, 76.8, 90.9\\\\\n 3 & 0.276 & 0.019 & 16.1, 29.1, 31.4, 35.5, 39.8, 43.9, 47.9, 50.5, 68.8, 71.9, 75.3, 78.1, 79.4, 88.6, 91.0\\\\\n 4 & 0.246 & 0.016 & 17.6, 25.6, 30.8, 36.4, 42.0, 48.8, 51.0, 52.2, 55.9, 60.4, 64.1, 75.3, 76.2, 85.0, 89.4, 90.9\\\\\n 5 & 0.254 & 0.017 & 11.8, 18.7, 24.9, 30.6, 37.3, 41.2, 45.5, 64.6, 68.3, 71.3, 81.8, 88.8, 90.9\\\\\n \\end{tabular}\n\\end{table}\n\n\\subsection{$C\\alpha$ map, $T=0.5\\epsilon$}\n\\label{subsec:no-knot-trmd-ca}\n\\begin{minipage}[c]{0.7\\textwidth}\n \\includegraphics[width=\\textwidth]{trmd-no-knot_ca_histograms.png}\n\\end{minipage}\n\\hfill\n\\begin{minipage}[c]{0.45\\textwidth}\n \\begin{itemize}\n \\item method = 'stretch-adjust';\n \\item $p_{prot}=0.3977$\n \\item $k_{prot}=0.0195$\n \\item states = 11 (49.1, 54.0, 59.4, 63.3, 67.5, 70.3, 73.8, 80.6, 86.8, 89.5, 91.0 nm);\n \\end{itemize}\n\\end{minipage}\n\n\\begin{figure}\n \\centering\n \\includegraphics[width=\\linewidth]{trmd-no-knot_ca_contour_lengths_1.png}\n \\caption{All no-knot-TrmD experimental traces ($C\\alpha$ map, $T=0.5\\epsilon$).}\n \\label{fig:no-knot-trmd-ca-cl1}\n\\end{figure}\n\n\\begin{table}\n \\tiny\n \\centering\n \\caption{Parameters of TrmD fitting in simulations ($C\\alpha$ map, $T=0.5\\epsilon$)}\n \\label{tab:no-knot-trmd-ca-parameters}\n \\begin{tabular}{c|c|c|c}\n \\textbf{Trace} & \\textbf{$p_{prot}$} & \\textbf{$k_{prot}$} & \\textbf{States [nm]}\\\\\\hline\n 1 & 0.422 & 0.021 & 17.9, 20.9, 24.2, 28.7, 31.8, 35.5, 39.9, 42.9, 45.9, 48.4, 49.5, 51.6, 55.3, 58.5, 61.8, 66.6, 72.5, 75.4, 79.8, 80.2, 87.1, 90.4, 91.0\\\\\n 2 & 0.463 & 0.027 & 25.4, 27.5, 29.7, 32.3, 34.0, 35.6, 37.6, 40.0, 42.6, 45.3, 47.4, 49.3, 51.9, 54.2, 59.4, 60.9, 63.2, 67.7, 68.9, 72.0, 74.9, 77.0, 80.3, 87.9, 89.2, 90.9\\\\\n 3 & 0.328 & 0.012 & 22.8, 26.8, 31.7, 35.2, 40.5, 43.4, 45.9, 49.4, 53.0, 54.9, 56.4, 58.1, 60.7, 64.9, 68.0, 70.4, 73.4, 75.8, 80.0, 87.0, 89.8, 91.4\\\\\n 4 & 0.380 & 0.018 & 18.0, 23.0, 25.7, 28.6, 31.8, 34.1, 39.3, 44.4, 47.7, 53.8, 59.1, 62.6, 69.3, 71.1, 73.6, 75.9, 84.2, 89.5, 90.9\\\\\n 5 & 0.395 & 0.019 & 29.0, 32.3, 34.6, 37.4, 41.5, 44.3, 58.8, 59.6, 62.2, 66.9, 74.9, 79.8, 84.8, 90.0, 90.9, 92.0\\\\\n \\end{tabular}\n\\end{table}\n\n\\subsection{$C\\alpha$ map, $T=0.6\\epsilon$}\n\\label{subsec:no-knot-trmd-cb}\n\\begin{minipage}[c]{0.7\\textwidth}\n \\includegraphics[width=\\textwidth]{trmd-no-knot_cb_histograms.png}\n\\end{minipage}\n\\hfill\n\\begin{minipage}[c]{0.45\\textwidth}\n \\begin{itemize}\n \\item method = 'stretch-adjust';\n \\item $p_{prot}=0.5312$\n \\item $k_{prot}=0.0206$\n \\item states = 4 (72.5, 80.6, 87.9, 90.9 nm);\n \\end{itemize}\n\\end{minipage}\n\n\\begin{figure}\n \\centering\n \\includegraphics[width=\\linewidth]{trmd-no-knot_cb_contour_lengths_1.png}\n \\caption{All no-knot-TrmD experimental traces ($C\\alpha$ map, $T=0.6\\epsilon$).}\n \\label{fig:no-knot-trmd-cb-cl1}\n\\end{figure}\n\n\\begin{table}\n \\tiny\n \\centering\n \\caption{Parameters of no-knot-TrmD fitting in simulations ($C\\alpha$ map, $T=0.6\\epsilon$)}\n \\label{tab:no-knot-trmd-cb-parameters}\n \\begin{tabular}{c|c|c|c}\n \\textbf{Trace} & \\textbf{$p_{prot}$} & \\textbf{$k_{prot}$} & \\textbf{States [nm]}\\\\\\hline\n 1 & 0.541 & 0.021 & 24.0, 26.7, 30.4, 34.6, 41.5, 47.3, 51.3, 54.0, 57.2, 60.8, 62.8, 64.4, 65.6, 69.5, 75.0, 77.8, 80.0, 84.5, 90.9\\\\\n 2 & 0.480 & 0.020 & 15.2, 21.2, 28.2, 33.3, 35.7, 36.9, 39.0, 42.1, 44.3, 46.8, 50.1, 53.0, 56.9, 64.5, 70.3, 75.0, 78.8, 86.6, 90.4\\\\\n 3 & 0.540 & 0.021 & 22.1, 24.1, 25.9, 28.0, 31.6, 36.6, 40.3, 42.4, 44.8, 47.2, 49.0, 51.3, 53.9, 56.9, 61.7, 70.9, 77.3, 79.9, 82.3, 87.4, 91.0, 97.4\\\\\n 4 & 0.577 & 0.022 & 17.5, 23.4, 26.5, 30.9, 35.2, 47.5, 51.8, 55.4, 61.6, 65.8, 68.6, 76.2, 76.8, 82.1, 88.1, 91.0\\\\\n 5 & 0.517 & 0.020 & 28.5, 30.9, 34.9, 39.6, 43.8, 48.9, 53.3, 57.1, 60.0, 68.3, 70.0, 72.1, 74.1, 76.7, 79.4, 81.3, 84.0, 88.8, 91.0\\\\\n \\end{tabular}\n\\end{table}\n\n\\subsection{Tsai map, $T=0.4\\epsilon$}\n\\label{subsec:no-knot-trmd-pc}\n\\begin{minipage}[c]{0.7\\textwidth}\n \\includegraphics[width=\\textwidth]{trmd-no-knot_pc_histograms.png}\n\\end{minipage}\n\\hfill\n\\begin{minipage}[c]{0.45\\textwidth}\n \\begin{itemize}\n \\item method = 'stretch-adjust';\n \\item $p_{prot}=0.2542$\n \\item $k_{prot}=0.0172$\n \\item states = 9 (7.6, 23.6, 35.9, 47.5, 64.1, 69.0, 71.3, 77.4, 90.6 nm);\n \\end{itemize}\n\\end{minipage}\n\n\\begin{figure}\n \\centering\n \\includegraphics[width=\\linewidth]{trmd-no-knot_pc_contour_lengths_1.png}\n \\caption{All no-knot-TrmD experimental traces (Tsai map, $T=0.4\\epsilon$).}\n \\label{fig:no-knot-trmd-pc-cl1}\n\\end{figure}\n\n\\begin{table}\n \\tiny\n \\centering\n \\caption{Parameters of no-knot-TrmD fitting in simulations (Tsai map, $T=0.4\\epsilon$)}\n \\label{tab:no-knot-trmd-pc-parameters}\n \\begin{tabular}{c|c|c|c}\n \\textbf{Trace} & \\textbf{$p_{prot}$} & \\textbf{$k_{prot}$} & \\textbf{States [nm]}\\\\\\hline\n 1 & 0.398 & 0.034 & 8.5, 25.1, 37.9, 50.1, 66.3, 72.5, 86.3, 90.8\\\\\n 2 & 0.179 & 0.009 & 7.3, 17.7, 22.1, 25.0, 27.5, 33.6, 36.3, 46.8, 63.7, 72.9, 77.1, 88.6, 90.9\\\\\n 3 & 0.309 & 0.023 & 7.5, 8.7, 16.2, 22.7, 26.7, 34.7, 37.1, 47.5, 63.5, 67.8, 73.1, 78.4, 90.8\\\\\n 4 & 0.179 & 0.009 & 7.3, 22.9, 32.8, 35.0, 36.9, 39.0, 46.9, 60.3, 62.5, 63.7, 65.2, 67.7, 73.7, 77.1, 90.6\\\\\n 5 & 0.205 & 0.011 & 7.3, 22.6, 34.4, 45.4, 59.2, 60.9, 62.3, 65.4, 68.3, 71.0, 74.5, 86.8, 90.5\\\\\n \\end{tabular}\n\\end{table}\n\n\\subsection{Tsai map, $T=0.5\\epsilon$}\n\\label{subsec:no-knot-trmd-pa}\n\\begin{minipage}[c]{0.7\\textwidth}\n \\includegraphics[width=\\textwidth]{trmd-no-knot_pa_histograms.png}\n\\end{minipage}\n\\hfill\n\\begin{minipage}[c]{0.45\\textwidth}\n \\begin{itemize}\n \\item method = 'stretch-adjust';\n \\item $p_{prot}=0.3306$\n \\item $k_{prot}=0.0123$\n \\item states = 10 (8.3, 21.9, 33.3, 44.0, 50.0, 73.5, 81.4, 86.4, 89.2, 91.0 nm);\n \\end{itemize}\n\\end{minipage}\n\n\\begin{figure}\n \\centering\n \\includegraphics[width=\\linewidth]{trmd-no-knot_pa_contour_lengths_1.png}\n \\caption{All no-knot-TrmD experimental traces (Tsai map, $T=0.5\\epsilon$).}\n \\label{fig:no-knot-trmd-pa-cl1}\n\\end{figure}\n\n\\begin{table}\n \\tiny\n \\centering\n \\caption{Parameters of no-knot-TrmD fitting in simulations (Tsai map, $T=0.5\\epsilon$)}\n \\label{tab:no-knot-trmd-pa-parameters}\n \\begin{tabular}{c|c|c|c}\n \\textbf{Trace} & \\textbf{$p_{prot}$} & \\textbf{$k_{prot}$} & \\textbf{States [nm]}\\\\\\hline\n 1 & 0.306 & 0.012 & 7.9, 14.5, 21.2, 22.9, 31.0, 36.9, 41.0, 48.3, 50.7, 81.7, 88.8, 90.9\\\\\n 2 & 0.325 & 0.013 & 8.5, 22.0, 33.1, 44.4, 60.5, 69.6, 72.6, 81.8, 88.9, 91.0\\\\\n 3 & 0.365 & 0.015 & 8.6, 21.4, 23.5, 33.8, 44.1, 51.8, 67.3, 70.0, 72.1, 74.9, 77.5, 81.0, 87.7, 91.0\\\\\n 4 & 0.328 & 0.013 & 8.1, 16.3, 22.3, 32.5, 42.1, 44.3, 57.0, 62.7, 66.8, 70.6, 75.6, 84.5, 89.3, 91.0\\\\\n 5 & 0.329 & 0.008 & 8.0, 9.7, 22.0, 33.6, 41.5, 47.5, 49.8, 68.2, 75.1, 79.6, 85.0, 89.7, 91.4\\\\\n \\end{tabular}\n\\end{table}\n\n\\subsection{Tsai map, $T=0.6\\epsilon$}\n\\label{subsec:no-knot-trmd-pb}\n\\begin{minipage}[c]{0.7\\textwidth}\n \\includegraphics[width=\\textwidth]{trmd-no-knot_pb_histograms.png}\n\\end{minipage}\n\\hfill\n\\begin{minipage}[c]{0.45\\textwidth}\n \\begin{itemize}\n \\item method = 'stretch-adjust';\n \\item $p_{prot}=0.5624$\n \\item $k_{prot}=0.0224$\n \\item states = 8 (21.9, 34.1, 42.6, 74.4, 82.0, 86.8, 89.2, 90.9 nm);\n \\end{itemize}\n\\end{minipage}\n\n\\begin{figure}\n \\centering\n \\includegraphics[width=\\linewidth]{trmd-no-knot_pb_contour_lengths_1.png}\n \\caption{All no-knot-TrmD experimental traces (Tsai map, $T=0.6\\epsilon$).}\n \\label{fig:no-knot-trmd-pb-cl1}\n\\end{figure}\n\n\\begin{table}\n \\tiny\n \\centering\n \\caption{Parameters of no-knot-TrmD fitting in simulations (Tsai map, $T=0.6\\epsilon$)}\n \\label{tab:no-knot-trmd-pb-parameters}\n \\begin{tabular}{c|c|c|c}\n \\textbf{Trace} & \\textbf{$p_{prot}$} & \\textbf{$k_{prot}$} & \\textbf{States [nm]}\\\\\\hline\n 1 & 0.616 & 0.025 & 12.4, 15.9, 19.4, 22.3, 24.5, 26.6, 29.4, 31.9, 34.0, 35.9, 38.2, 41.5, 43.4, 46.2, 49.4, 52.0, 55.3, 58.7, 61.8, 69.2, 75.6, 79.1, 85.9, 90.9\\\\\n 2 & 0.587 & 0.024 & 11.4, 13.3, 15.0, 17.3, 21.7, 26.1, 29.5, 32.6, 35.3, 43.7, 46.7, 49.8, 54.9, 62.3, 72.2, 73.5, 74.7, 76.7, 78.1, 81.7, 84.9, 88.6, 91.1\\\\\n 3 & 0.646 & 0.028 & 9.6, 12.1, 14.3, 17.9, 20.6, 22.7, 24.9, 27.2, 31.9, 35.9, 37.2, 46.9, 50.6, 53.5, 60.1, 69.2, 74.6, 76.5, 78.6, 80.9, 83.2, 86.2, 91.0\\\\\n 4 & 0.376 & 0.012 & 9.7, 12.1, 14.3, 17.7, 20.9, 27.9, 30.6, 31.5, 48.3, 58.9, 59.9, 63.0, 66.3, 69.6, 72.5, 75.7, 82.5, 88.1, 90.4\\\\\n 5 & 0.587 & 0.023 & 10.2, 13.7, 16.6, 20.2, 25.0, 30.7, 35.5, 36.9, 37.9, 42.2, 42.8, 62.9, 69.2, 71.8, 75.4, 81.3, 84.2, 87.6, 90.9\\\\\n \\end{tabular}\n\\end{table}\n\n\\subsection{SMOG map, $T=0.4\\epsilon$}\n\\label{subsec:no-knot-trmd-sc}\n\\begin{minipage}[c]{0.7\\textwidth}\n \\includegraphics[width=\\textwidth]{trmd-no-knot_sc_histograms.png}\n\\end{minipage}\n\\hfill\n\\begin{minipage}[c]{0.45\\textwidth}\n \\begin{itemize}\n \\item method = 'stretch-adjust';\n \\item $p_{prot}=1.7853$\n \\item $k_{prot}=0.0266$\n \\item states = 3 (6.4, 68.7, 90.8 nm);\n \\end{itemize}\n\\end{minipage}\n\n\\begin{figure}\n \\centering\n \\includegraphics[width=\\linewidth]{trmd-no-knot_sc_contour_lengths_1.png}\n \\caption{All no-knot-TrmD experimental traces (SMOG map, $T=0.4\\epsilon$).}\n \\label{fig:no-knot-trmd-sc-cl1}\n\\end{figure}\n\n\\begin{table}\n \\tiny\n \\centering\n \\caption{Parameters of no-knot-TrmD fitting in simulations (SMOG map, $T=0.4\\epsilon$)}\n \\label{tab:no-knot-trmd-sc-parameters}\n \\begin{tabular}{c|c|c|c}\n \\textbf{Trace} & \\textbf{$p_{prot}$} & \\textbf{$k_{prot}$} & \\textbf{States [nm]}\\\\\\hline\n 1 & 0.223 & 0.014 & 6.1, 13.8, 29.4, 32.9, 35.8, 44.7, 57.2, 68.7, 90.9\\\\\n 2 & 0.208 & 0.014 & 6.0, 7.0, 14.2, 29.4, 32.1, 35.6, 44.6, 57.3, 68.7, 90.7\\\\\n 3 & 3.874 & 0.100 & 15.5, 20.3, 24.0, 31.4, 37.3, 55.7, 58.4, 61.8, 67.2, 72.9, 74.7, 89.8, 92.7\\\\\n 4 & 0.589 & 0.005 & 0.0, 7.3, 16.3, 35.6, 39.6, 49.4, 63.7\\\\\n 5 & 4.032 & 0.000 & 16.0, 20.2, 24.4, 29.5, 34.9, 37.4, 39.3, 42.7, 49.2, 51.3, 61.9, 65.5, 68.2, 70.7, 74.0, 77.9, 80.3, 82.7, 87.3, 92.5\\\\\n \\end{tabular}\n\\end{table}\n\n\\subsection{SMOG map, $T=0.5\\epsilon$}\n\\label{subsec:no-knot-trmd-sa}\n\\begin{minipage}[c]{0.7\\textwidth}\n \\includegraphics[width=\\textwidth]{trmd-no-knot_sa_histograms.png}\n\\end{minipage}\n\\hfill\n\\begin{minipage}[c]{0.45\\textwidth}\n \\begin{itemize}\n \\item method = 'stretch-adjust';\n \\item $p_{prot}=0.2968$\n \\item $k_{prot}=0.0122$\n \\item states = 3 (6.6, 51.8, 90.6 nm);\n \\end{itemize}\n\\end{minipage}\n\n\\begin{figure}\n \\centering\n \\includegraphics[width=\\linewidth]{trmd-no-knot_sa_contour_lengths_1.png}\n \\caption{All no-knot-TrmD experimental traces (SMOG map, $T=0.5\\epsilon$).}\n \\label{fig:no-knot-trmd-sa-cl1}\n\\end{figure}\n\n\\begin{table}\n \\tiny\n \\centering\n \\caption{Parameters of no-knot-TrmD fitting in simulations (SMOG map, $T=0.5\\epsilon$)}\n \\label{tab:no-knot-trmd-sa-parameters}\n \\begin{tabular}{c|c|c|c}\n \\textbf{Trace} & \\textbf{$p_{prot}$} & \\textbf{$k_{prot}$} & \\textbf{States [nm]}\\\\\\hline\n 1 & 0.260 & 0.009 & 4.7, 9.7, 19.7, 25.0, 28.5, 35.7, 41.6, 73.4\\\\\n 2 & 0.269 & 0.009 & 6.5, 12.0, 27.9, 30.8, 34.8, 43.9, 56.5, 67.4, 90.5\\\\\n 3 & 0.269 & 0.010 & 6.4, 7.4, 12.5, 23.8, 30.4, 35.3, 43.8, 55.8, 67.2, 90.5\\\\\n 4 & 0.270 & 0.009 & 6.7, 12.9, 25.0, 30.4, 34.9, 43.9, 66.0, 67.8, 88.3, 90.9\\\\\n 5 & 0.416 & 0.023 & 7.0, 12.9, 24.5, 31.0, 44.6, 56.9, 68.4, 73.5, 90.7\\\\\n \\end{tabular}\n\\end{table}\n\n\\subsection{SMOGmap, $T=0.6\\epsilon$}\n\\label{subsec:no-knot-trmd-sb}\n\\begin{minipage}[c]{0.7\\textwidth}\n \\includegraphics[width=\\textwidth]{trmd-no-knot_sb_histograms.png}\n\\end{minipage}\n\\hfill\n\\begin{minipage}[c]{0.45\\textwidth}\n \\begin{itemize}\n \\item method = 'stretch-adjust';\n \\item $p_{prot}=0.4275$\n \\item $k_{prot}=0.0140$\n \\item states = 3 (42.3, 51.8, 90.7 nm);\n \\end{itemize}\n\\end{minipage}\n\n\\begin{figure}\n \\centering\n \\includegraphics[width=\\linewidth]{trmd-no-knot_sb_contour_lengths_1.png}\n \\caption{All no-knot-TrmD experimental traces (SMOG map, $T=0.6\\epsilon$).}\n \\label{fig:no-knot-trmd-sb-cl1}\n\\end{figure}\n\n\\begin{table}\n \\tiny\n \\centering\n \\caption{Parameters of no-knot-TrmD fitting in simulations (SMOG map, $T=0.6\\epsilon$)}\n \\label{tab:no-knot-trmd-sb-parameters}\n \\begin{tabular}{c|c|c|c}\n \\textbf{Trace} & \\textbf{$p_{prot}$} & \\textbf{$k_{prot}$} & \\textbf{States [nm]}\\\\\\hline\n 1 & 0.330 & 0.007 & 7.2, 11.3, 22.8, 28.2, 32.4, 45.7, 51.7, 90.6\\\\\n 2 & 0.466 & 0.016 & 8.1, 12.0, 23.5, 27.2, 30.2, 42.8, 61.7, 64.3, 80.9, 85.3, 88.4, 90.9\\\\\n 3 & 0.447 & 0.015 & 7.6, 12.0, 26.5, 40.4, 43.7, 64.3, 86.6, 90.9\\\\\n 4 & 0.442 & 0.015 & 7.7, 11.6, 21.1, 28.0, 41.9, 63.9, 90.7\\\\\n 5 & 0.453 & 0.016 & 9.2, 26.8, 42.6, 62.1, 65.5, 87.3, 90.7\\\\\n \\end{tabular}\n\\end{table}\n\n\\section{Analysis of 5wyr structure of TrmD in silico}\n\\label{sec:fit-details-5wyr-theory}\n\\subsection{$C\\alpha$ map, $T=0.4\\epsilon$}\n\\label{subsec:5wyr-cc}\n\\begin{minipage}[c]{0.7\\textwidth}\n \\includegraphics[width=\\textwidth]{5wyr_cc_histograms.png}\n\\end{minipage}\n\\hfill\n\\begin{minipage}[c]{0.45\\textwidth}\n \\begin{itemize}\n \\item method = 'stretch-adjust';\n \\item $p_{prot}=0.3025$\n \\item $k_{prot}=0.0058$\n \\item states = 5 (35.2, 58.0, 67.2, 81.3, 93.9 nm);\n \\end{itemize}\n\\end{minipage}\n\n\\begin{figure}\n \\centering\n \\includegraphics[width=\\linewidth]{5wyr_cc_contour_lengths_1.png}\n \\caption{All 5wyr TrmD experimental traces ($C\\alpha$ map, $T=0.4\\epsilon$).}\n \\label{fig:5wyr-cc-cl1}\n\\end{figure}\n\n\\begin{figure}\n \\centering\n \\includegraphics[width=\\linewidth]{5wyr_cc_contour_lengths_2.png}\n \\caption{All 5wyr TrmD experimental traces ($C\\alpha$ map, $T=0.4\\epsilon$).}\n \\label{fig:5wyr-cc-cl2}\n\\end{figure}\n\n\\begin{table}\n \\tiny\n \\centering\n \\caption{Parameters of 5wyr TrmD fitting in simulations ($C\\alpha$ map, $T=0.4\\epsilon$)}\n \\label{tab:5wyr-cc-parameters}\n \\begin{tabular}{c|c|c|c}\n \\textbf{Trace} & \\textbf{$p_{prot}$} & \\textbf{$k_{prot}$} & \\textbf{States [nm]}\\\\\\hline\n 1 & 0.299 & 0.005 & 10.5, 30.2, 34.1, 38.6, 54.3, 59.1, 64.9, 67.6, 81.4, 93.9\\\\\n 2 & 0.315 & 0.006 & 11.7, 15.7, 19.2, 24.2, 30.9, 35.9, 42.9, 53.9, 63.4, 67.6, 81.4, 93.9\\\\\n 3 & 0.313 & 0.006 & 21.8, 31.5, 37.8, 48.8, 54.8, 58.2, 63.4, 67.6, 77.9, 81.5, 93.9\\\\\n 4 & 0.312 & 0.006 & 21.1, 31.6, 32.0, 35.2, 36.8, 38.9, 44.5, 53.9, 57.4, 62.5, 67.5, 81.1, 93.9\\\\\n 5 & 0.309 & 0.006 & 21.9, 36.9, 54.4, 59.6, 66.8, 75.0, 81.5, 93.9\\\\\n 6 & 0.311 & 0.006 & 14.1, 17.0, 20.4, 29.9, 33.6, 38.8, 57.5, 66.6, 74.5, 81.2, 93.9\\\\\n 7 & 0.245 & 0.007 & 13.5, 26.2, 26.4, 30.9, 36.3, 39.3, 54.6, 62.7, 66.1, 79.0, 80.4, 92.6\\\\\n 8 & 0.313 & 0.006 & 31.7, 34.7, 37.0, 38.6, 40.7, 55.2, 58.8, 64.9, 67.7, 79.5, 81.5, 93.9\\\\\n 9 & 0.311 & 0.006 & 15.5, 19.3, 27.3, 33.9, 36.6, 38.9, 57.7, 62.9, 67.2, 70.1, 81.2, 93.9\\\\\n 10 & 0.306 & 0.005 & 20.3, 30.5, 34.2, 38.9, 53.4, 56.7, 59.5, 63.7, 67.3, 79.6, 81.5, 93.9\\\\\n 11 & 0.297 & 0.005 & 13.3, 19.7, 23.1, 27.7, 31.7, 34.2, 36.7, 55.2, 63.9, 66.5, 67.9, 81.6, 93.9\\\\\n 12 & 0.301 & 0.005 & 10.8, 13.7, 16.5, 19.4, 27.4, 33.9, 37.8, 51.7, 54.1, 56.2, 58.2, 60.5, 64.7, 67.6, 80.1, 81.5, 93.9\\\\\n 13 & 0.299 & 0.005 & 27.6, 30.6, 32.8, 53.1, 59.9, 64.6, 67.6, 81.3, 92.3, 93.9\\\\\n 14 & 0.305 & 0.006 & 31.6, 33.1, 34.5, 36.0, 48.2, 52.7, 56.1, 59.9, 65.0, 67.9, 81.3, 93.9\\\\\n 15 & 0.303 & 0.006 & 16.3, 22.2, 31.2, 34.5, 38.9, 52.9, 56.7, 61.6, 65.4, 67.2, 68.7, 81.1, 93.9\\\\\n \\end{tabular}\n\\end{table}\n\n\\subsection{$C\\alpha$ map, $T=0.5\\epsilon$}\n\\label{subsec:5wyr-ca}\n\\begin{minipage}[c]{0.7\\textwidth}\n \\includegraphics[width=\\textwidth]{5wyr_ca_histograms.png}\n\\end{minipage}\n\\hfill\n\\begin{minipage}[c]{0.45\\textwidth}\n \\begin{itemize}\n \\item method = 'stretch-adjust';\n \\item $p_{prot}=0.4581$\n \\item $k_{prot}=0.0078$\n \\item states = 5 (35.7, 54.1, 58.2, 73.3, 93.9 nm);\n \\end{itemize}\n\\end{minipage}\n\n\\begin{figure}\n \\centering\n \\includegraphics[width=\\linewidth]{5wyr_ca_contour_lengths_1.png}\n \\caption{All 5wyr TrmD experimental traces ($C\\alpha$ map, $T=0.5\\epsilon$).}\n \\label{fig:5wyr-ca-cl1}\n\\end{figure}\n\n\\begin{figure}\n \\centering\n \\includegraphics[width=\\linewidth]{5wyr_ca_contour_lengths_2.png}\n \\caption{All 5wyr TrmD experimental traces ($C\\alpha$ map, $T=0.5\\epsilon$).}\n \\label{fig:5wyr-ca-cl2}\n\\end{figure}\n\n\\begin{table}\n \\tiny\n \\centering\n \\caption{Parameters of 5wyr TrmD fitting in simulations ($C\\alpha$ map, $T=0.5\\epsilon$)}\n \\label{tab:5wyr-ca-parameters}\n \\begin{tabular}{c|c|c|c}\n \\textbf{Trace} & \\textbf{$p_{prot}$} & \\textbf{$k_{prot}$} & \\textbf{States [nm]}\\\\\\hline\n 1 & 0.465 & 0.008 & 26.4, 30.8, 36.3, 53.2, 56.3, 68.1, 73.1, 76.9, 90.7, 94.0\\\\\n 2 & 0.447 & 0.007 & 24.2, 29.1, 31.2, 34.6, 40.4, 46.4, 52.0, 55.5, 58.4, 62.3, 72.7, 77.4, 93.9\\\\\n 3 & 0.453 & 0.008 & 22.3, 30.0, 33.2, 36.9, 44.6, 54.6, 58.5, 71.3, 73.7, 76.8, 93.9\\\\\n 4 & 0.457 & 0.008 & 26.2, 36.1, 55.2, 70.2, 76.2, 93.9\\\\\n 5 & 0.443 & 0.007 & 16.5, 22.0, 25.8, 35.2, 56.1, 59.0, 62.7, 76.5, 90.9, 93.9\\\\\n 6 & 0.462 & 0.008 & 19.7, 24.8, 30.8, 35.1, 38.6, 42.9, 47.3, 53.8, 56.6, 59.4, 71.1, 76.1, 93.9\\\\\n 7 & 0.457 & 0.008 & 29.6, 33.2, 35.9, 40.1, 42.9, 44.9, 49.1, 51.4, 53.4, 55.1, 58.1, 72.9, 90.6, 93.9\\\\\n 8 & 0.465 & 0.008 & 31.1, 36.3, 44.8, 52.8, 53.0, 54.4, 58.8, 70.0, 72.9, 76.0, 93.9\\\\\n 9 & 0.488 & 0.009 & 23.7, 28.3, 34.9, 40.9, 46.6, 52.3, 57.0, 66.6, 68.9, 70.9, 72.6, 73.0, 74.3, 93.9\\\\\n 10 & 0.466 & 0.008 & 28.1, 30.9, 32.2, 36.8, 44.1, 54.1, 55.0, 58.6, 68.2, 71.0, 72.7, 91.3, 94.0\\\\\n 11 & 0.462 & 0.008 & 28.5, 34.0, 37.2, 38.7, 54.0, 56.8, 63.0, 66.3, 69.3, 72.6, 90.4, 94.0\\\\\n 12 & 0.472 & 0.009 & 21.5, 23.5, 25.9, 29.3, 31.3, 33.0, 34.8, 37.7, 41.6, 43.4, 48.1, 53.8, 56.6, 58.2, 59.7, 61.5, 75.0, 82.9, 93.9\\\\\n 13 & 0.444 & 0.007 & 22.3, 27.9, 30.3, 31.9, 34.5, 40.0, 45.0, 47.8, 50.7, 56.4, 60.9, 69.1, 73.6, 90.0, 93.9\\\\\n 14 & 0.460 & 0.008 & 25.1, 29.6, 34.0, 37.8, 41.2, 50.3, 55.3, 55.6, 59.3, 70.8, 75.5, 91.1, 94.0\\\\\n 15 & 0.432 & 0.007 & 19.6, 21.5, 24.4, 30.1, 36.2, 41.4, 44.0, 49.3, 53.9, 57.6, 72.0, 93.8\\\\\n \\end{tabular}\n\\end{table}\n\n\\subsection{$C\\alpha$ map, $T=0.6\\epsilon$}\n\\label{subsec:5wyr-cb}\n\\begin{minipage}[c]{0.7\\textwidth}\n \\includegraphics[width=\\textwidth]{5wyr_cb_histograms.png}\n\\end{minipage}\n\\hfill\n\\begin{minipage}[c]{0.45\\textwidth}\n \\begin{itemize}\n \\item method = 'stretch-adjust';\n \\item $p_{prot}=0.5809$\n \\item $k_{prot}=0.0088$\n \\item states = 2 (67.2, 93.9 nm);\n \\end{itemize}\n\\end{minipage}\n\n\\begin{figure}\n \\centering\n \\includegraphics[width=\\linewidth]{5wyr_cb_contour_lengths_1.png}\n \\caption{All 5wyr TrmD experimental traces ($C\\alpha$ map, $T=0.6\\epsilon$).}\n \\label{fig:5wyr-cb-cl1}\n\\end{figure}\n\n\\begin{figure}\n \\centering\n \\includegraphics[width=\\linewidth]{5wyr_cc_contour_lengths_2.png}\n \\caption{All 5wyr TrmD experimental traces ($C\\alpha$ map, $T=0.6\\epsilon$).}\n \\label{fig:5wyr-cb-cl2}\n\\end{figure}\n\n\\begin{table}\n \\tiny\n \\centering\n \\caption{Parameters of 5wyr TrmD fitting in simulations ($C\\alpha$ map, $T=0.6\\epsilon$)}\n \\label{tab:5wyr-cb-parameters}\n \\begin{tabular}{c|c|c|c}\n \\textbf{Trace} & \\textbf{$p_{prot}$} & \\textbf{$k_{prot}$} & \\textbf{States [nm]}\\\\\\hline\n 1 & 0.586 & 0.008 & 25.0, 30.5, 33.7, 35.8, 37.9, 40.1, 41.8, 44.4, 48.2, 50.7, 53.3, 56.1, 59.4, 63.5, 66.5, 69.5, 79.7, 93.9\\\\\n 2 & 0.609 & 0.009 & 24.5, 26.7, 29.5, 32.9, 36.1, 38.0, 40.2, 42.9, 46.6, 49.0, 51.5, 57.7, 65.5, 68.6, 71.4, 88.5, 94.0, 103.1\\\\\n 3 & 0.593 & 0.009 & 54.0, 56.0, 58.9, 60.5, 64.9, 72.2, 75.3, 83.9, 90.4, 93.2, 94.0\\\\\n 4 & 0.624 & 0.009 & 32.9, 42.2, 58.0, 63.4, 64.6, 69.9, 87.7, 92.8, 94.0\\\\\n 5 & 0.576 & 0.008 & 32.1, 35.8, 39.2, 42.0, 45.3, 50.9, 59.2, 65.5, 70.2, 80.0, 81.9, 89.7, 93.9\\\\\n 6 & 0.581 & 0.008 & 36.4, 42.9, 46.0, 48.1, 50.8, 54.6, 60.0, 69.1, 89.4, 93.9\\\\\n 7 & 0.589 & 0.008 & 31.8, 34.4, 37.7, 40.6, 46.6, 52.0, 56.0, 66.4, 69.8, 72.3, 80.4, 81.1, 90.0, 93.9\\\\\n 8 & 0.613 & 0.009 & 42.3, 44.8, 46.8, 52.2, 56.1, 58.4, 60.1, 62.1, 64.8, 69.6, 85.2, 92.3, 94.0\\\\\n 9 & 0.583 & 0.008 & 24.8, 29.2, 34.0, 37.2, 39.4, 43.6, 48.3, 51.7, 63.0, 63.0, 66.8, 70.0, 71.8, 72.4, 86.2, 92.3, 93.9\\\\\n 10 & 0.578 & 0.008 & 31.1, 34.4, 37.2, 39.1, 41.1, 45.4, 48.4, 50.3, 52.1, 58.2, 62.2, 67.4, 71.4, 86.8, 92.5, 94.0\\\\\n 11 & 0.428 & 0.013 & 23.2, 30.2, 33.5, 35.8, 39.4, 46.4, 46.6, 49.4, 53.1, 57.5, 61.9, 66.4, 69.7, 84.1, 92.0, 94.0\\\\\n 12 & 0.583 & 0.008 & 24.2, 29.0, 35.7, 41.9, 45.4, 49.1, 56.1, 63.7, 67.8, 71.8, 89.1, 93.9\\\\\n 13 & 0.608 & 0.009 & 32.4, 36.5, 41.2, 43.7, 46.4, 49.1, 51.4, 53.4, 56.2, 59.8, 62.8, 68.7, 69.2, 84.9, 92.0, 94.0\\\\\n 14 & 0.587 & 0.008 & 26.3, 29.1, 31.4, 35.1, 46.8, 53.9, 66.4, 68.4, 72.2, 87.6, 92.5, 94.0\\\\\n 15 & 0.576 & 0.008 & 30.8, 37.6, 40.2, 42.9, 45.7, 48.3, 49.9, 53.4, 60.8, 63.6, 68.5, 83.3, 91.5, 93.9\\\\\n \\end{tabular}\n\\end{table}\n\n\\subsection{Tsai map, $T=0.4\\epsilon$}\n\\label{subsec:5wyr-pc}\n\\begin{minipage}[c]{0.7\\textwidth}\n \\includegraphics[width=\\textwidth]{5wyr_pc_histograms.png}\n\\end{minipage}\n\\hfill\n\\begin{minipage}[c]{0.45\\textwidth}\n \\begin{itemize}\n \\item method = 'stretch-adjust';\n \\item $p_{prot}=0.3745$\n \\item $k_{prot}=0.0043$\n \\item states = 9 (8.1, 11.0, 27.6, 33.5, 47.9, 68.1, 76.4, 81.4, 93.9 nm);\n \\end{itemize}\n\\end{minipage}\n\n\\begin{figure}\n \\centering\n \\includegraphics[width=\\linewidth]{5wyr_pc_contour_lengths_1.png}\n \\caption{All 5wyr TrmD experimental traces (Tsai map, $T=0.4\\epsilon$).}\n \\label{fig:5wyr-pc-cl1}\n\\end{figure}\n\n\\begin{figure}\n \\centering\n \\includegraphics[width=\\linewidth]{5wyr_pc_contour_lengths_2.png}\n \\caption{All 5wyr TrmD experimental traces (Tsai map, $T=0.4\\epsilon$).}\n \\label{fig:5wyr-pc-cl2}\n\\end{figure}\n\n\\begin{table}\n \\tiny\n \\centering\n \\caption{Parameters of 5wyr TrmD fitting in simulations (Tsai map, $T=0.4\\epsilon$)}\n \\label{tab:5wyr-pc-parameters}\n \\begin{tabular}{c|c|c|c}\n \\textbf{Trace} & \\textbf{$p_{prot}$} & \\textbf{$k_{prot}$} & \\textbf{States [nm]}\\\\\\hline\n 1 & 0.383 & 0.004 & 8.0, 10.4, 14.1, 27.8, 34.4, 48.1, 68.2, 76.5, 81.6, 93.9\\\\\n 2 & 0.377 & 0.004 & 8.2, 12.2, 28.1, 31.1, 33.6, 44.3, 48.3, 67.8, 76.5, 81.4, 93.9\\\\\n 3 & 0.367 & 0.004 & 8.0, 10.7, 13.7, 26.9, 30.7, 34.1, 46.7, 64.9, 68.3, 76.2, 81.3, 93.8\\\\\n 4 & 0.371 & 0.004 & 8.0, 10.5, 14.2, 27.5, 33.2, 37.5, 47.5, 67.6, 76.5, 81.3, 93.8\\\\\n 5 & 0.325 & 0.006 & 7.9, 10.7, 26.1, 28.0, 29.4, 31.5, 34.0, 46.8, 66.4, 75.1, 79.3, 93.9\\\\\n 6 & 0.387 & 0.004 & 8.0, 10.5, 14.3, 27.6, 33.5, 35.7, 37.7, 48.1, 67.9, 80.7, 90.9, 93.9\\\\\n 7 & 0.375 & 0.004 & 8.2, 11.5, 26.5, 31.7, 36.7, 48.0, 68.0, 76.6, 81.5, 93.9\\\\\n 8 & 0.377 & 0.004 & 8.3, 12.7, 27.9, 30.0, 32.3, 34.9, 37.5, 47.9, 68.0, 76.4, 81.4, 93.9\\\\\n 9 & 0.391 & 0.005 & 8.0, 10.5, 13.8, 25.1, 28.5, 32.0, 37.2, 48.3, 68.5, 76.6, 81.0, 93.9\\\\\n 10 & 0.379 & 0.004 & 8.4, 11.6, 28.3, 32.0, 34.1, 37.4, 47.5, 66.9, 76.2, 81.4, 93.9\\\\\n 11 & 0.382 & 0.004 & 8.2, 11.7, 27.2, 29.7, 31.0, 32.7, 36.4, 45.2, 48.6, 68.1, 81.0, 93.9\\\\\n 12 & 0.374 & 0.004 & 8.0, 10.5, 13.8, 25.2, 31.1, 34.0, 36.6, 47.0, 64.8, 68.6, 76.4, 81.4, 93.9\\\\\n 13 & 0.374 & 0.004 & 8.0, 10.6, 14.0, 27.6, 30.8, 33.7, 37.5, 47.5, 67.5, 76.6, 88.3, 93.9\\\\\n 14 & 0.381 & 0.004 & 8.2, 11.0, 27.9, 33.5, 37.1, 45.6, 48.1, 64.5, 68.5, 76.3, 81.5, 93.9\\\\\n 15 & 0.375 & 0.004 & 8.8, 13.7, 27.3, 30.0, 33.1, 38.3, 47.9, 67.3, 76.2, 81.4, 93.9\\\\\n \\end{tabular}\n\\end{table}\n\n\\subsection{Tsai map, $T=0.5\\epsilon$}\n\\label{subsec:5wyr-pa}\n\\begin{minipage}[c]{0.7\\textwidth}\n \\includegraphics[width=\\textwidth]{5wyr_pa_histograms.png}\n\\end{minipage}\n\\hfill\n\\begin{minipage}[c]{0.45\\textwidth}\n \\begin{itemize}\n \\item method = 'stretch-adjust';\n \\item $p_{prot}=0.4938$\n \\item $k_{prot}=0.0069$\n \\item states = 7 (9.5, 26.3, 31.3, 41.5, 59.8, 74.1, 93.9 nm);\n \\end{itemize}\n\\end{minipage}\n\n\\begin{figure}\n \\centering\n \\includegraphics[width=\\linewidth]{5wyr_pa_contour_lengths_1.png}\n \\caption{All 5wyr TrmD experimental traces (Tsai map, $T=0.5\\epsilon$).}\n \\label{fig:5wyr-pa-cl1}\n\\end{figure}\n\n\\begin{figure}\n \\centering\n \\includegraphics[width=\\linewidth]{5wyr_pa_contour_lengths_2.png}\n \\caption{All 5wyr TrmD experimental traces (Tsai map, $T=0.5\\epsilon$).}\n \\label{fig:5wyr-pa-cl2}\n\\end{figure}\n\n\\begin{table}\n \\tiny\n \\centering\n \\caption{Parameters of 5wyr TrmD fitting in simulations (Tsai map, $T=0.5\\epsilon$)}\n \\label{tab:5wyr-pa-parameters}\n \\begin{tabular}{c|c|c|c}\n \\textbf{Trace} & \\textbf{$p_{prot}$} & \\textbf{$k_{prot}$} & \\textbf{States [nm]}\\\\\\hline\n 1 & 0.459 & 0.008 & 9.4, 25.2, 29.8, 32.6, 41.6, 55.0, 67.7, 74.6, 76.6, 90.0, 93.9\\\\\n 2 & 0.457 & 0.008 & 9.5, 24.9, 28.6, 32.4, 40.6, 54.3, 65.2, 68.6, 70.5, 73.1, 87.4, 93.9\\\\\n 3 & 0.463 & 0.008 & 8.9, 10.9, 24.4, 27.2, 29.0, 32.0, 40.1, 43.6, 58.0, 61.2, 73.9, 93.9\\\\\n 4 & 0.527 & 0.006 & 10.0, 19.0, 26.5, 28.6, 31.7, 40.1, 44.1, 59.6, 69.6, 71.6, 72.9, 74.6, 77.3, 93.9\\\\\n 5 & 0.529 & 0.006 & 9.4, 19.3, 26.1, 31.9, 41.3, 55.2, 71.2, 71.7, 75.5, 78.5, 93.9\\\\\n 6 & 0.457 & 0.008 & 8.9, 10.2, 18.4, 23.3, 26.9, 28.1, 31.5, 41.0, 59.6, 71.1, 76.2, 93.9\\\\\n 7 & 0.533 & 0.006 & 9.8, 17.4, 25.8, 31.1, 33.6, 42.8, 61.8, 75.8, 91.2, 93.9\\\\\n 8 & 0.545 & 0.006 & 9.7, 12.3, 26.8, 32.3, 41.0, 44.0, 60.7, 64.9, 76.6, 79.7, 92.4, 93.9\\\\\n 9 & 0.553 & 0.007 & 9.1, 10.4, 12.7, 25.6, 27.4, 32.1, 41.0, 45.2, 61.9, 73.1, 78.0, 91.8, 94.0\\\\\n 10 & 0.465 & 0.008 & 9.4, 11.8, 22.8, 26.8, 31.2, 41.5, 58.0, 61.5, 63.6, 71.6, 87.8, 92.2, 94.0\\\\\n 11 & 0.537 & 0.006 & 9.6, 11.9, 26.7, 32.5, 39.7, 43.4, 59.1, 73.0, 76.0, 78.3, 91.9, 94.0\\\\\n 12 & 0.446 & 0.007 & 9.2, 25.9, 30.4, 31.8, 40.7, 56.6, 67.4, 70.5, 75.1, 93.9\\\\\n 13 & 0.442 & 0.007 & 8.5, 9.8, 15.1, 25.4, 31.6, 39.9, 43.7, 59.2, 73.8, 93.8\\\\\n 14 & 0.552 & 0.007 & 9.4, 13.9, 18.8, 25.8, 28.3, 29.7, 32.4, 41.2, 57.7, 67.9, 71.9, 74.8, 77.3, 85.6, 93.9\\\\\n 15 & 0.443 & 0.007 & 9.3, 11.9, 23.7, 25.5, 31.0, 41.1, 55.6, 58.6, 68.0, 71.2, 73.8, 90.7, 93.9\\\\\n \\end{tabular}\n\\end{table}\n\n\\subsection{Tsai map, $T=0.6\\epsilon$}\n\\label{subsec:5wyr-pb}\n\\begin{minipage}[c]{0.7\\textwidth}\n \\includegraphics[width=\\textwidth]{5wyr_pb_histograms.png}\n\\end{minipage}\n\\hfill\n\\begin{minipage}[c]{0.45\\textwidth}\n \\begin{itemize}\n \\item method = 'stretch-adjust';\n \\item $p_{prot}=0.6131$\n \\item $k_{prot}=0.0088$\n \\item states = 4 (26.4, 38.0, 67.3, 93.9 nm);\n \\end{itemize}\n\\end{minipage}\n\n\\begin{figure}\n \\centering\n \\includegraphics[width=\\linewidth]{5wyr_pb_contour_lengths_1.png}\n \\caption{All 5wyr TrmD experimental traces (Tsai map, $T=0.6\\epsilon$).}\n \\label{fig:5wyr-pb-cl1}\n\\end{figure}\n\n\\begin{figure}\n \\centering\n \\includegraphics[width=\\linewidth]{5wyr_pb_contour_lengths_2.png}\n \\caption{All 5wyr TrmD experimental traces (Tsai map, $T=0.6\\epsilon$).}\n \\label{fig:5wyr-pb-cl2}\n\\end{figure}\n\n\\begin{table}\n \\tiny\n \\centering\n \\caption{Parameters of 5wyr TrmD fitting in simulations (Tsai map, $T=0.6\\epsilon$)}\n \\label{tab:5wyr-pb-parameters}\n \\begin{tabular}{c|c|c|c}\n \\textbf{Trace} & \\textbf{$p_{prot}$} & \\textbf{$k_{prot}$} & \\textbf{States [nm]}\\\\\\hline\n 1 & 0.590 & 0.008 & 9.6, 11.8, 17.4, 25.1, 26.2, 32.4, 35.2, 38.5, 55.4, 64.2, 66.6, 69.6, 77.0, 83.7, 88.7, 93.0, 94.0\\\\\n 2 & 0.575 & 0.008 & 10.4, 14.0, 18.2, 21.8, 25.8, 31.2, 37.0, 50.0, 51.7, 66.4, 67.7, 86.9, 91.6, 94.0\\\\\n 3 & 0.578 & 0.008 & 10.8, 13.9, 16.4, 21.1, 24.4, 26.3, 28.6, 36.5, 37.7, 39.0, 53.0, 57.7, 62.2, 68.4, 89.0, 93.9\\\\\n 4 & 0.623 & 0.009 & 11.2, 14.9, 16.9, 20.0, 24.7, 27.8, 30.0, 36.1, 39.2, 42.5, 66.3, 67.6, 70.5, 90.1, 94.0\\\\\n 5 & 0.633 & 0.010 & 11.0, 16.3, 24.4, 28.4, 38.1, 41.6, 66.6, 67.2, 69.9, 72.3, 77.6, 80.2, 83.0, 88.8, 93.8, 94.0\\\\\n 6 & 0.607 & 0.009 & 9.8, 12.3, 17.8, 26.2, 30.1, 32.0, 33.8, 35.5, 37.5, 41.7, 46.9, 49.8, 59.7, 62.8, 67.8, 72.8, 85.5, 91.7, 94.0\\\\\n 7 & 0.595 & 0.009 & 11.6, 16.7, 18.8, 21.0, 24.0, 26.2, 28.7, 32.8, 38.5, 59.5, 63.4, 67.0, 69.8, 88.8, 94.0\\\\\n 8 & 0.636 & 0.010 & 10.9, 20.0, 26.6, 27.8, 30.7, 31.7, 37.7, 46.4, 53.2, 65.1, 65.1, 67.4, 71.2, 75.9, 84.5, 91.7, 94.0\\\\\n 9 & 0.625 & 0.010 & 11.1, 18.0, 29.0, 30.8, 38.6, 42.6, 56.0, 59.7, 66.5, 69.3, 72.4, 77.9, 88.8, 93.9\\\\\n 10 & 0.584 & 0.008 & 11.2, 17.6, 26.6, 37.5, 38.5, 53.8, 54.5, 60.5, 65.7, 67.8, 70.3, 71.5, 76.0, 77.2, 88.3, 92.4, 94.0\\\\\n 11 & 0.610 & 0.009 & 11.4, 18.1, 22.2, 26.1, 37.7, 37.9, 46.6, 49.4, 52.5, 54.7, 58.0, 61.1, 63.6, 68.6, 77.8, 80.2, 86.1, 92.6, 94.0\\\\\n 12 & 0.697 & 0.008 & 12.2, 21.1, 26.7, 29.4, 31.6, 40.1, 48.0, 56.8, 68.1, 75.8, 78.2, 80.2, 83.6, 89.1, 93.9\\\\\n 13 & 0.600 & 0.009 & 11.0, 14.3, 16.2, 23.9, 26.5, 27.3, 29.9, 37.2, 39.7, 56.7, 61.0, 62.9, 64.3, 66.4, 66.9, 68.8, 84.8, 88.6, 92.3, 94.0\\\\\n 14 & 0.617 & 0.009 & 11.2, 16.2, 21.4, 23.9, 25.7, 28.8, 32.8, 38.5, 40.8, 50.8, 58.1, 66.9, 69.9, 78.1, 86.4, 92.1, 94.0\\\\\n 15 & 0.627 & 0.010 & 10.6, 13.0, 15.9, 22.9, 24.6, 27.6, 30.6, 36.3, 38.8, 52.8, 58.2, 61.0, 64.5, 66.9, 70.4, 73.5, 75.1, 90.6, 94.0\\\\\n \\end{tabular}\n\\end{table}\n\n\\subsection{SMOG map, $T=0.4\\epsilon$}\n\\label{subsec:5wyr-sc}\n\\begin{minipage}[c]{0.7\\textwidth}\n \\includegraphics[width=\\textwidth]{5wyr_sc_histograms.png}\n\\end{minipage}\n\\hfill\n\\begin{minipage}[c]{0.45\\textwidth}\n \\begin{itemize}\n \\item method = 'stretch-adjust';\n \\item $p_{prot}=0.1961$\n \\item $k_{prot}=0.0078$\n \\item states = 3 (7.1, 48.5, 93.4 nm);\n \\end{itemize}\n\\end{minipage}\n\n\\begin{figure}\n \\centering\n \\includegraphics[width=\\linewidth]{5wyr_sc_contour_lengths_1.png}\n \\caption{All 5wyr TrmD experimental traces (SMOG map, $T=0.4\\epsilon$).}\n \\label{fig:5wyr-sc-cl1}\n\\end{figure}\n\n\\begin{figure}\n \\centering\n \\includegraphics[width=\\linewidth]{5wyr_sc_contour_lengths_2.png}\n \\caption{All 5wyr TrmD experimental traces (SMOG map, $T=0.4\\epsilon$).}\n \\label{fig:5wyr-sc-cl2}\n\\end{figure}\n\n\\begin{table}\n \\tiny\n \\centering\n \\caption{Parameters of 5wyr TrmD fitting in simulations (SMOG map, $T=0.4\\epsilon$)}\n \\label{tab:5wyr-sc-parameters}\n \\begin{tabular}{c|c|c|c}\n \\textbf{Trace} & \\textbf{$p_{prot}$} & \\textbf{$k_{prot}$} & \\textbf{States [nm]}\\\\\\hline\n 1 & 0.337 & 0.004 & 7.7, 11.2, 15.5, 30.2, 35.3, 39.8, 48.9, 69.0, 81.0, 88.7, 93.4\\\\\n 2 & 0.037 & 0.012 & 6.4, 10.1, 24.7, 29.1, 31.1, 35.5, 43.9, 55.9, 62.2, 73.3, 84.8\\\\\n 3 & 0.049 & 0.012 & 6.4, 10.1, 25.7, 31.0, 35.6, 44.2, 56.6, 62.7, 73.8, 85.1\\\\\n 4 & 0.354 & 0.003 & 7.8, 10.5, 11.9, 30.9, 35.6, 40.0, 49.0, 62.4, 69.4, 81.5, 89.1, 93.9\\\\\n 5 & 0.262 & 0.005 & 7.5, 11.2, 29.6, 34.7, 39.0, 46.4, 48.0, 61.1, 67.8, 79.6, 87.0, 91.8\\\\\n 6 & 0.011 & 0.014 & 6.1, 10.0, 27.3, 30.3, 34.5, 43.0, 54.9, 61.0, 71.8, 78.6, 83.0\\\\\n 7 & 0.013 & 0.014 & 6.0, 9.7, 12.3, 26.0, 30.1, 34.3, 42.9, 55.1, 61.0, 71.8, 78.8, 83.1\\\\\n 8 & 0.335 & 0.004 & 7.7, 10.6, 11.6, 30.3, 35.2, 39.8, 48.8, 62.0, 69.0, 81.0, 88.8, 93.5\\\\\n 9 & 0.358 & 0.004 & 0.0, 7.8, 11.6, 30.7, 35.6, 39.7, 49.0, 62.6, 69.4, 81.5, 89.0, 93.9\\\\\n 10 & 0.337 & 0.003 & 7.7, 10.4, 11.6, 29.5, 32.6, 34.1, 35.6, 39.7, 46.3, 48.9, 69.2, 81.2, 93.6\\\\\n 11 & 0.232 & 0.006 & 7.3, 11.0, 28.4, 34.0, 38.6, 47.4, 60.2, 67.2, 78.9, 86.3, 91.0\\\\\n 12 & 0.153 & 0.008 & 7.0, 10.9, 28.5, 33.0, 37.4, 46.2, 59.2, 65.6, 77.1, 90.0\\\\\n 13 & 0.038 & 0.013 & 6.3, 10.1, 25.6, 30.7, 35.3, 43.9, 56.1, 62.2, 73.2, 80.2, 84.6\\\\\n 14 & 0.141 & 0.009 & 7.0, 10.7, 27.3, 32.9, 37.2, 46.0, 58.7, 65.2, 76.8, 88.6\\\\\n 15 & 0.285 & 0.005 & 7.5, 11.2, 31.3, 34.7, 39.2, 48.2, 61.6, 68.2, 80.1, 87.8, 92.3\\\\\n \\end{tabular}\n\\end{table}\n\n\\subsection{SMOG map, $T=0.5\\epsilon$}\n\\label{subsec:5wyr-sa}\n\\begin{minipage}[c]{0.7\\textwidth}\n \\includegraphics[width=\\textwidth]{5wyr_sa_histograms.png}\n\\end{minipage}\n\\hfill\n\\begin{minipage}[c]{0.45\\textwidth}\n \\begin{itemize}\n \\item method = 'stretch-adjust';\n \\item $p_{prot}=0.4525$\n \\item $k_{prot}=0.0057$\n \\item states = 3 (8.3, 48.5, 93.7 nm);\n \\end{itemize}\n\\end{minipage}\n\n\\begin{figure}\n \\centering\n \\includegraphics[width=\\linewidth]{5wyr_sa_contour_lengths_1.png}\n \\caption{All 5wyr TrmD experimental traces (SMOG map, $T=0.5\\epsilon$).}\n \\label{fig:5wyr-sa-cl1}\n\\end{figure}\n\n\\begin{figure}\n \\centering\n \\includegraphics[width=\\linewidth]{5wyr_sa_contour_lengths_2.png}\n \\caption{All 5wyr TrmD experimental traces (SMOG map, $T=0.5\\epsilon$).}\n \\label{fig:5wyr-sa-cl2}\n\\end{figure}\n\n\\begin{table}\n \\tiny\n \\centering\n \\caption{Parameters of 5wyr TrmD fitting in simulations (SMOG map, $T=0.5\\epsilon$)}\n \\label{tab:5wyr-sa-parameters}\n \\begin{tabular}{c|c|c|c}\n \\textbf{Trace} & \\textbf{$p_{prot}$} & \\textbf{$k_{prot}$} & \\textbf{States [nm]}\\\\\\hline\n 1 & 0.428 & 0.006 & 8.1, 10.7, 15.9, 27.7, 33.7, 38.8, 48.1, 67.6, 80.0, 93.9\\\\\n 2 & 0.488 & 0.005 & 8.2, 10.2, 14.7, 28.6, 34.4, 39.3, 49.0, 81.2, 93.9\\\\\n 3 & 0.376 & 0.007 & 7.9, 10.3, 25.9, 28.4, 32.6, 38.4, 47.7, 78.9, 91.7\\\\\n 4 & 0.492 & 0.005 & 8.3, 10.3, 28.9, 31.1, 34.9, 39.4, 49.0, 69.0, 81.2, 93.7, 93.9\\\\\n 5 & 0.408 & 0.006 & 8.2, 25.8, 29.1, 33.1, 38.8, 48.1, 79.5, 93.9\\\\\n 6 & 0.497 & 0.005 & 8.2, 9.9, 28.5, 34.9, 39.6, 49.1, 69.2, 81.4, 92.5, 93.9\\\\\n 7 & 0.401 & 0.006 & 7.9, 10.0, 27.6, 33.7, 38.2, 47.7, 67.0, 79.6, 92.2\\\\\n 8 & 0.420 & 0.006 & 8.0, 10.3, 26.9, 33.1, 38.8, 48.1, 67.8, 79.9, 87.8, 92.4\\\\\n 9 & 0.490 & 0.005 & 8.2, 10.7, 14.7, 28.6, 34.8, 39.4, 48.8, 62.2, 79.8, 81.3, 93.9\\\\\n 10 & 0.487 & 0.005 & 8.2, 10.7, 27.1, 30.2, 33.9, 39.4, 48.9, 68.8, 81.3, 93.9\\\\\n 11 & 0.444 & 0.007 & 8.1, 10.2, 27.5, 29.7, 33.8, 39.0, 48.2, 61.4, 67.9, 80.2, 93.9\\\\\n 12 & 0.497 & 0.005 & 8.6, 27.3, 29.9, 34.1, 39.6, 49.0, 68.6, 81.2, 93.9, 94.2\\\\\n 13 & 0.435 & 0.007 & 8.1, 10.7, 27.1, 28.8, 34.3, 38.9, 48.1, 78.0, 80.0, 93.9\\\\\n 14 & 0.470 & 0.005 & 8.2, 10.8, 15.2, 28.4, 34.1, 39.3, 48.8, 68.8, 80.8, 88.7, 93.5\\\\\n 15 & 0.454 & 0.006 & 8.2, 11.2, 26.6, 29.5, 33.9, 38.7, 48.5, 61.9, 68.8, 80.6, 93.2\\\\\n \\end{tabular}\n\\end{table}\n\n\\subsection{SMOG map, $T=0.6\\epsilon$}\n\\label{subsec:5wyr-sb}\n\\begin{minipage}[c]{0.7\\textwidth}\n \\includegraphics[width=\\textwidth]{5wyr_sb_histograms.png}\n\\end{minipage}\n\\hfill\n\\begin{minipage}[c]{0.45\\textwidth}\n \\begin{itemize}\n \\item method = 'stretch-adjust';\n \\item $p_{prot}=0.6156$\n \\item $k_{prot}=0.0058$\n \\item states = 3 (47.9, 79.5, 93.8 nm);\n \\end{itemize}\n\\end{minipage}\n\n\\begin{figure}\n \\centering\n \\includegraphics[width=\\linewidth]{5wyr_sb_contour_lengths_1.png}\n \\caption{All 5wyr TrmD experimental traces (SMOG map, $T=0.4\\epsilon$).}\n \\label{fig:5wyr-sb-cl1}\n\\end{figure}\n\n\\begin{figure}\n \\centering\n \\includegraphics[width=\\linewidth]{5wyr_sb_contour_lengths_2.png}\n \\caption{All 5wyr TrmD experimental traces (SMOG map, $T=0.4\\epsilon$).}\n \\label{fig:5wyr-sb-cl2}\n\\end{figure}\n\n\\begin{table}\n \\tiny\n \\centering\n \\caption{Parameters of 5wyr TrmD fitting in simulations (SMOG map, $T=0.4\\epsilon$)}\n \\label{tab:5wyr-sb-parameters}\n \\begin{tabular}{c|c|c|c}\n \\textbf{Trace} & \\textbf{$p_{prot}$} & \\textbf{$k_{prot}$} & \\textbf{States [nm]}\\\\\\hline\n 1 & 0.583 & 0.004 & 9.5, 22.9, 26.4, 31.7, 37.7, 47.8, 66.8, 79.0, 93.7\\\\\n 2 & 0.596 & 0.004 & 9.3, 21.2, 26.7, 29.5, 31.8, 34.5, 37.8, 48.1, 79.6, 93.3, 93.8\\\\\n 3 & 0.588 & 0.004 & 9.5, 15.4, 28.3, 37.2, 47.4, 65.4, 79.2, 93.7\\\\\n 4 & 0.548 & 0.007 & 8.9, 14.0, 26.4, 28.4, 30.5, 32.9, 36.3, 47.1, 76.1, 79.1, 93.9\\\\\n 5 & 0.640 & 0.006 & 9.4, 16.3, 28.6, 31.9, 34.5, 37.9, 48.2, 67.0, 79.9, 86.5, 93.8\\\\\n 6 & 0.587 & 0.004 & 9.4, 18.3, 26.3, 30.2, 37.3, 47.0, 65.1, 76.8, 78.9, 92.0, 93.9\\\\\n 7 & 0.665 & 0.007 & 9.6, 12.0, 28.7, 31.4, 33.8, 37.6, 48.0, 80.0, 93.9\\\\\n 8 & 0.571 & 0.008 & 9.3, 27.1, 28.9, 30.3, 33.4, 37.3, 47.4, 65.3, 78.1, 93.9\\\\\n 9 & 0.671 & 0.007 & 9.5, 11.7, 18.0, 29.1, 37.7, 48.3, 75.6, 80.2, 93.1, 94.0\\\\\n 10 & 0.640 & 0.006 & 9.7, 10.9, 27.5, 33.3, 37.6, 47.9, 79.9, 93.9\\\\\n 11 & 0.648 & 0.006 & 9.0, 10.2, 12.7, 23.8, 27.3, 30.4, 32.4, 34.9, 37.6, 47.5, 65.3, 79.8, 93.9\\\\\n 12 & 0.663 & 0.007 & 9.3, 11.0, 28.8, 31.8, 34.3, 38.1, 48.2, 78.2, 80.9, 93.9\\\\\n 13 & 0.650 & 0.006 & 9.4, 10.9, 16.5, 28.2, 33.2, 38.2, 48.6, 80.1, 93.9\\\\\n 14 & 0.587 & 0.004 & 9.2, 10.6, 25.0, 27.7, 30.3, 30.7, 32.2, 36.9, 38.7, 47.8, 66.5, 79.1, 93.8\\\\\n 15 & 0.597 & 0.005 & 9.5, 19.8, 28.5, 36.1, 47.0, 78.8, 80.2, 93.8\\\\\n \\end{tabular}\n\\end{table}\n\n\\section{Analysis of TrmD in experiment}\n\\label{sec:fit-details-trmd-experiment}\n\\subsection{Regular fit (result - unknotted)}\n\\label{subsec:fit-details-trmd-experiment-unknotted}\n\\begin{minipage}[c]{0.7\\textwidth}\n \\includegraphics[width=\\textwidth]{results-experiment-trmd-histo.png}\n\\end{minipage}\n\\hfill\n\\begin{minipage}[c]{0.45\\textwidth}\n \\begin{itemize}\n \\item method = 'stretch-adjust';\n \\item $p_{prot}=5.9360$\n \\item $k_{prot}=0.0000$\n \\item $p_{dna}=0.1591$\n \\item $k_{dna}=0.0090$\n \\item $l_{dna}=339.438$\n \\item states = 3 (45.2, 51.9, 86.9 nm);\n \\end{itemize}\n\\end{minipage}\n\n\\begin{figure}\n \\centering\n \\includegraphics[width=\\linewidth]{unknotted_trmd_exp_contour_lengths_1.png}\n \\caption{All TrmD experimental traces.}\n \\label{fig:unkotted-trmd-exp-cl1}\n\\end{figure}\n\n\\begin{figure}\n \\centering\n \\includegraphics[width=\\linewidth]{unknotted_trmd_exp_contour_lengths_2.png}\n \\caption{All TrmD experimental traces (continued).}\n \\label{fig:unkotted-trmd-exp-cl2}\n\\end{figure}\n\n\\begin{figure}\n \\centering\n \\includegraphics[width=\\linewidth]{unknotted_trmd_exp_contour_lengths_3.png}\n \\caption{All TrmD experimental traces (continued).}\n \\label{fig:unkotted-trmd-exp-cl3}\n\\end{figure}\n\n\\begin{figure}\n \\centering\n \\includegraphics[width=\\linewidth]{unknotted_trmd_exp_contour_lengths_4.png}\n \\caption{All TrmD experimental traces (continued).}\n \\label{fig:unkotted-trmd-exp-cl4}\n\\end{figure}\n\n\\begin{table}\n \\tiny\n \\centering\n \\caption{The fit parameters for TrmD (experiment, assumed unknotted).}\n \\label{tab:trmd-fit-parameters-exp-unknotted}\n \\begin{tabular}{c|c|c|c|c}\n \\textbf{Trace} & $p_{dna}$ & $l_{dna}$ & $l_{prot}$ & states [nm]\\\\\\hline\n 1 & 0.143 & 340.127 & 5.936 & 46.4, 53.2, 87.1\\\\\n 2 & 0.210 & 342.254 & 5.936 & 43.6, 47.3, 51.7, 53.2, 87.1\\\\\n 3 & 0.210 & 343.767 & 5.936 & 40.2, 43.4, 47.8, 85.1, 89.2\\\\\n 4 & 0.210 & 345.437 & 5.936 & 39.8, 42.3, 50.5, 86.6\\\\\n 5 & 0.191 & 344.764 & 5.936 & 34.0, 48.5, 53.0, 56.2, 87.1\\\\\n 6 & 0.155 & 342.986 & 5.936 & 46.7, 53.7, 56.4, 87.1\\\\\n 7 & 0.137 & 342.045 & 5.936 & 45.8, 54.7, 87.0\\\\\n 8 & 0.156 & 343.190 & 5.936 & 45.0, 53.0, 87.0\\\\\n 9 & 0.130 & 345.102 & 5.936 & 42.5, 51.5, 85.3\\\\\n 10 & 0.210 & 345.664 & 5.936 & 43.1, 46.4, 51.2, 86.6\\\\\n 11 & 0.210 & 345.620 & 5.936 & 49.7, 83.9\\\\\n 12 & 0.168 & 343.993 & 5.936 & 38.4, 43.0, 48.7, 84.7\\\\\n 13 & 0.150 & 342.776 & 5.936 & 45.3, 52.3, 86.8\\\\\n 14 & 0.210 & 344.203 & 5.936 & 53.0, 87.0\\\\\n 15 & 0.188 & 343.914 & 5.936 & 45.7, 52.4, 87.0\\\\\n 16 & 0.169 & 344.101 & 5.936 & 43.3, 45.6, 51.8, 87.1\\\\\n 17 & 0.161 & 345.726 & 5.936 & 41.4, 50.0, 83.9, 87.4\\\\\n 18 & 0.130 & 342.381 & 5.936 & 45.0, 52.1, 86.9\\\\\n 19 & 0.130 & 340.034 & 5.936 & 45.1, 52.0, 87.2\\\\\n 20 & 0.160 & 338.727 & 5.936 & 47.8, 50.1, 52.2, 87.4\\\\\n 21 & 0.159 & 338.527 & 5.936 & 43.7, 47.8, 52.4, 87.0\\\\\n 22 & 0.163 & 337.772 & 5.936 & 52.8, 86.9\\\\\n 23 & 0.130 & 337.142 & 5.936 & 45.3, 49.7, 52.5, 79.1, 87.7\\\\\n 24 & 0.163 & 332.855 & 5.936 & 48.5, 88.3\\\\\n 25 & 0.130 & 331.275 & 5.936 & 48.0, 56.4, 87.1\\\\\n 26 & 0.161 & 335.616 & 5.936 & 18.7, 43.7, 46.8, 54.5, 84.7\\\\\n 27 & 0.130 & 334.444 & 5.936 & 45.4, 48.4, 49.0, 87.4\\\\\n 28 & 0.163 & 334.098 & 5.936 & 52.9, 87.2, 91.9\\\\\n 29 & 0.130 & 335.503 & 5.936 & 50.1, 85.2, 90.7\\\\\n 30 & 0.155 & 336.108 & 5.936 & 46.9, 53.2, 87.3\\\\\n 31 & 0.160 & 336.153 & 5.936 & 40.8, 47.2, 50.8, 54.9, 87.6\\\\\n 32 & 0.130 & 335.449 & 5.936 & 38.5, 52.0, 58.7, 87.3\\\\\n 33 & 0.160 & 335.847 & 5.936 & 50.9, 53.5, 87.2\\\\\n 34 & 0.130 & 335.473 & 5.936 & 47.2, 53.9, 87.3\\\\\n 35 & 0.130 & 335.570 & 5.936 & 47.0, 53.8, 86.6\\\\\n 36 & 0.162 & 335.398 & 5.936 & 54.8, 59.8, 85.5, 88.0\\\\\n 37 & 0.130 & 334.586 & 5.936 & 47.7, 55.2, 86.8\\\\\n 38 & 0.130 & 334.962 & 5.936 & 48.0, 56.8, 87.6\\\\\n 39 & 0.162 & 334.493 & 5.936 & 55.6, 87.2\\\\\n \\end{tabular}\n\\end{table}\n\n\n\\subsection{Assumed knotted state}\n\\label{subsec:fit-details-trmd-experiment-knotted}\n\\begin{minipage}[c]{0.7\\textwidth}\n \\includegraphics[width=\\textwidth]{results-experiment-trmd-histo-knotted.png}\n\\end{minipage}\n\\hfill\n\\begin{minipage}[c]{0.45\\textwidth}\n \\begin{itemize}\n \\item method = 'stretch-adjust';\n \\item $p_{prot}=5.9360$\n \\item $k_{prot}=0.0000$\n \\item $p_{dna}=0.1565$\n \\item $k_{dna}=0.0090$\n \\item $l_{dna}=342.374$\n \\item states = 3 (40.3, 47.1, 81.9 nm);\n \\end{itemize}\n\\end{minipage}\n\n\\begin{figure}\n \\centering\n \\includegraphics[width=\\linewidth]{knotted_trmd_exp_contour_lengths_1.png}\n \\caption{All TrmD experimental traces assuming knotted protein.}\n \\label{fig:knotted-trmd-exp-cl1}\n\\end{figure}\n\n\\begin{figure}\n \\centering\n \\includegraphics[width=\\linewidth]{knotted_trmd_exp_contour_lengths_2.png}\n \\caption{All TrmD experimental traces assuming knotted protein (continued).}\n \\label{fig:knotted-trmd-exp-cl2}\n\\end{figure}\n\n\\begin{figure}\n \\centering\n \\includegraphics[width=\\linewidth]{knotted_trmd_exp_contour_lengths_3.png}\n \\caption{All TrmD experimental traces assuming knotted protein (continued).}\n \\label{fig:knotted-trmd-exp-cl3}\n\\end{figure}\n\n\\begin{figure}\n \\centering\n \\includegraphics[width=\\linewidth]{knotted_trmd_exp_contour_lengths_4.png}\n \\caption{All TrmD experimental traces assuming knotted protein (continued).}\n \\label{fig:knotted-trmd-exp-cl4}\n\\end{figure}\n\n\\begin{table}\n \\tiny\n \\centering\n \\caption{The fit parameters for TrmD (experiment, assumed knotted).}\n \\label{tab:trmd-fit-parameters-exp-knotted}\n \\begin{tabular}{c|c|c|c|c}\n \\textbf{Trace} & $p_{dna}$ & $l_{dna}$ & $l_{prot}$ & states [nm]\\\\\\hline\n 1 & 0.143 & 340.127 & 82.125 & 46.4, 53.2, 87.1\\\\\n 2 & 0.210 & 345.925 & 82.125 & 38.7, 42.0, 46.4, 82.0\\\\\n 3 & 0.210 & 347.494 & 82.125 & 35.0, 38.3, 43.0, 79.9, 84.0\\\\\n 4 & 0.210 & 349.143 & 82.125 & 34.3, 36.8, 45.3, 81.5\\\\\n 5 & 0.195 & 348.582 & 82.125 & 42.6, 47.8, 50.8, 81.9\\\\\n 6 & 0.163 & 346.929 & 82.125 & 40.9, 50.4, 52.2, 82.0\\\\\n 7 & 0.144 & 345.992 & 82.125 & 40.3, 49.5, 81.8\\\\\n 8 & 0.171 & 347.406 & 82.125 & 39.9, 47.9, 81.9\\\\\n 9 & 0.130 & 347.434 & 82.125 & 38.9, 48.1, 82.1\\\\\n 10 & 0.210 & 349.114 & 82.125 & 39.3, 46.5, 81.8\\\\\n 11 & 0.210 & 347.435 & 82.125 & 47.0, 81.3\\\\\n 12 & 0.168 & 327.750 & 82.125 & 62.0, 66.6, 69.1, 71.9, 75.1, 92.0, 106.6\\\\\n 13 & 0.189 & 347.900 & 82.125 & 40.9, 44.3, 48.0, 81.8\\\\\n 14 & 0.177 & 346.774 & 82.125 & 46.9, 81.9\\\\\n 15 & 0.194 & 347.800 & 82.125 & 40.6, 46.7, 50.1, 81.9\\\\\n 16 & 0.190 & 348.537 & 82.125 & 38.3, 40.6, 46.9, 82.0\\\\\n 17 & 0.130 & 348.195 & 82.125 & 35.4, 44.9, 82.0\\\\\n 18 & 0.130 & 346.037 & 82.125 & 39.5, 47.0, 81.8\\\\\n 19 & 0.130 & 343.693 & 82.125 & 39.6, 46.9, 82.0\\\\\n 20 & 0.130 & 341.196 & 82.125 & 42.6, 82.1\\\\\n 21 & 0.169 & 342.572 & 82.125 & 38.6, 42.8, 47.4, 81.9\\\\\n 22 & 0.210 & 343.058 & 82.125 & 48.6, 81.9\\\\\n 23 & 0.130 & 340.845 & 82.125 & 40.0, 44.5, 47.4, 74.0, 82.5\\\\\n 24 & 0.130 & 335.372 & 82.125 & 41.5, 82.9\\\\\n 25 & 0.130 & 334.930 & 82.125 & 42.2, 51.2, 82.0\\\\\n 26 & 0.130 & 338.177 & 82.125 & 27.5, 39.3, 48.2, 79.2\\\\\n 27 & 0.130 & 337.881 & 82.125 & 30.4, 43.2, 82.5\\\\\n 28 & 0.210 & 339.235 & 82.125 & 45.0, 49.4, 52.4, 82.0, 87.4\\\\\n 29 & 0.130 & 339.217 & 82.125 & 44.2, 80.0, 85.4\\\\\n 30 & 0.130 & 338.777 & 82.125 & 42.5, 48.1, 82.2\\\\\n 31 & 0.130 & 338.788 & 82.125 & 30.4, 40.4, 43.6, 50.9, 82.2\\\\\n 32 & 0.130 & 339.110 & 82.125 & 30.8, 46.0, 53.3, 82.2\\\\\n 33 & 0.130 & 338.424 & 82.125 & 45.9, 50.8, 82.0\\\\\n 34 & 0.130 & 339.139 & 82.125 & 41.9, 48.8, 82.2\\\\\n 35 & 0.130 & 338.592 & 82.125 & 42.6, 82.3\\\\\n 36 & 0.130 & 337.836 & 82.125 & 45.0, 49.1, 53.1, 80.5, 82.9\\\\\n 37 & 0.130 & 337.934 & 82.125 & 42.4, 50.5, 82.1\\\\\n 38 & 0.130 & 338.628 & 82.125 & 42.2, 51.5, 82.5\\\\\n 39 & 0.130 & 336.930 & 82.125 & 45.6, 49.8, 82.1\\\\\n \\end{tabular}\n\\end{table}\n\n\\section{Analysis of Tm1570 in experiment}\n\\label{sec:fit-details-tm1570-experiment}\n\n\\subsection{Assumed unknotted state}\n\\label{subsec:fit-details-tm1570-experiment-unknotted}\n\\begin{minipage}[c]{0.7\\textwidth}\n \\includegraphics[width=\\textwidth]{tm1570_exp_histograms.png}\n\\end{minipage}\n\\hfill\n\\begin{minipage}[c]{0.45\\textwidth}\n \\begin{itemize}\n \\item method = 'stretch-adjust';\n \\item $p_{prot}=5.9360$\n \\item $k_{prot}=0.0000$\n \\item $p_{dna}=0.1691$\n \\item $k_{dna}=0.0090$\n \\item $l_{dna}=333.878$\n \\item states = 11 (10.5, 16.4, 20.3, 27.0, 33.5, 40.0, 44.2, 52.6, 57.7, 62.0, 69.2 nm);\n \\end{itemize}\n\\end{minipage}\n\n\\begin{figure}\n \\centering\n \\includegraphics[width=\\linewidth]{tm1570_exp_contour_lengths_1.png}\n \\caption{All Tm1570 experimental traces assuming unknotted protein.}\n \\label{fig:unknotted-tm1570-exp-cl1}\n\\end{figure}\n\n\\begin{figure}\n \\centering\n \\includegraphics[width=\\linewidth]{tm1570_exp_contour_lengths_2.png}\n \\caption{All Tm1570 experimental traces assuming unknotted protein (continued).}\n \\label{fig:unknotted-tm1570-exp-cl2}\n\\end{figure}\n\n\\begin{table}\n \\tiny\n \\centering\n \\caption{The fit parameters for Tm1570 (experiment, assumed unknotted).}\n \\label{tab:tm1570-fit-parameters-exp-unknotted}\n \\begin{tabular}{c|c|c|c|c}\n \\textbf{Trace} & $p_{dna}$ & $l_{dna}$ & $l_{prot}$ & states [nm]\\\\\\hline\n 1 & 0.130 & 339.650 & 70.080 & 20.9, 27.8, 50.8, 59.5, 62.2, 68.1\\\\\n 2 & 0.130 & 338.952 & 70.080 & 17.2, 24.0, 40.3, 44.4, 62.2, 69.3\\\\\n 3 & 0.131 & 339.289 & 70.080 & 22.6, 26.4, 30.4, 40.6, 42.2, 44.1, 47.1, 51.0, 61.2, 69.4\\\\\n 4 & 0.130 & 338.819 & 70.080 & 15.9, 18.8, 26.7, 40.2, 44.1, 57.5, 61.8, 69.3\\\\\n 5 & 0.133 & 338.419 & 70.080 & 12.2, 20.6, 33.8, 49.6, 52.6, 57.3, 60.9, 69.2\\\\\n 6 & 0.131 & 343.863 & 70.080 & 10.4, 15.4, 53.3, 69.7\\\\\n 7 & 0.130 & 344.082 & 68.716 & 26.2, 32.2, 37.4, 43.4, 49.6, 52.8, 67.5\\\\\n 8 & 0.132 & 343.189 & 70.080 & 16.2, 26.6, 53.4, 60.4, 67.6, 69.9\\\\\n 9 & 0.199 & 345.120 & 70.080 & 19.8, 29.4, 53.7, 69.2\\\\\n 10 & 0.141 & 343.094 & 70.080 & 28.2, 33.7, 43.5, 51.3, 60.9, 68.9\\\\\n 11 & 0.210 & 344.156 & 69.958 & 29.6, 35.7, 37.7, 52.4, 63.0, 69.6\\\\\n 12 & 0.130 & 336.336 & 70.080 & 23.3, 25.6, 29.5, 33.6, 39.3, 45.6, 69.9, 73.4, 75.9\\\\\n 13 & 0.130 & 339.378 & 70.080 & 32.6, 41.1, 50.6, 64.8, 70.9\\\\\n 14 & 0.131 & 335.895 & 70.080 & 33.7, 36.1, 36.6, 43.9, 48.4, 54.9, 70.0\\\\\n \\end{tabular}\n\\end{table}\n\n\\subsection{Assumed knotted state}\n\\label{subsec:fit-details-tm1570-experiment-knotted}\n\\begin{minipage}[c]{0.7\\textwidth}\n \\includegraphics[width=\\textwidth]{tm1570_kexp_histograms.png}\n\\end{minipage}\n\\hfill\n\\begin{minipage}[c]{0.45\\textwidth}\n \\begin{itemize}\n \\item method = 'stretch-adjust';\n \\item $p_{prot}=5.9360$\n \\item $k_{prot}=0.0000$\n \\item $p_{dna}=0.1929$\n \\item $k_{dna}=0.0090$\n \\item $l_{dna}=345.998$\n \\item states = 9 (16.9, 24.9, 29.6, 35.2, 39.9, 48.0, 57.1, 57.4, 64.3 nm);\n \\end{itemize}\n\\end{minipage}\n\n\\begin{figure}\n \\centering\n \\includegraphics[width=\\linewidth]{tm1570_kexp_contour_lengths_1.png}\n \\caption{All Tm1570 experimental traces assuming knotted protein.}\n \\label{fig:knotted-tm1570-exp-cl1}\n\\end{figure}\n\n\\begin{figure}\n \\centering\n \\includegraphics[width=\\linewidth]{tm1570_kexp_contour_lengths_2.png}\n \\caption{All Tm1570 experimental traces assuming knotted protein (continued).}\n \\label{fig:knotted-tm1570-exp-cl2}\n\\end{figure}\n\n\\begin{table}\n \\tiny\n \\centering\n \\caption{The fit parameters for Tm1570 (experiment, assumed knotted).}\n \\label{tab:tm1570-fit-parameters-exp-knotted}\n \\begin{tabular}{c|c|c|c|c}\n \\textbf{Trace} & $p_{dna}$ & $l_{dna}$ & $l_{prot}$ & states [nm]\\\\\\hline\n 1 & 0.210 & 345.909 & 64.970 & 17.2, 24.0, 46.1, 56.4, 63.5\\\\\n 2 & 0.210 & 345.235 & 64.970 & 13.8, 20.9, 29.6, 36.3, 40.0, 57.4, 64.3\\\\\n 3 & 0.210 & 345.562 & 64.970 & 20.2, 26.5, 38.9, 46.5, 56.4, 64.3\\\\\n 4 & 0.210 & 345.052 & 64.970 & 11.9, 14.5, 17.6, 27.2, 35.9, 39.8, 47.3, 52.8, 56.9, 64.3\\\\\n 5 & 0.210 & 344.555 & 64.970 & 10.6, 16.7, 30.6, 45.6, 52.5, 56.2, 64.1\\\\\n 6 & 0.210 & 350.207 & 64.970 & 6.1, 11.0, 17.5, 48.5, 64.6\\\\\n 7 & 0.210 & 349.459 & 64.970 & 24.0, 27.4, 30.9, 34.5, 39.8, 46.3, 49.5, 64.0\\\\\n 8 & 0.210 & 349.525 & 64.970 & 13.1, 17.4, 23.6, 40.8, 47.3, 49.5, 55.6, 64.0\\\\\n 9 & 0.210 & 349.142 & 64.970 & 12.3, 15.8, 24.2, 48.6, 64.0\\\\\n 10 & 0.210 & 349.077 & 64.970 & 24.1, 29.2, 36.2, 46.7, 51.6, 56.2, 63.9\\\\\n 11 & 0.210 & 347.762 & 64.970 & 24.1, 29.9, 31.9, 47.2, 58.0, 64.6\\\\\n 12 & 0.130 & 339.980 & 64.970 & 20.2, 25.4, 32.4, 34.0, 38.5, 64.8, 70.7\\\\\n 13 & 0.130 & 343.075 & 64.970 & 26.3, 33.0, 37.1, 59.4, 65.7\\\\\n 14 & 0.130 & 339.437 & 64.970 & 30.0, 36.9, 40.8, 42.8, 44.4, 49.7, 64.8\\\\\n \\end{tabular}\n\\end{table}\n\n\\section{Analysis of fusion TrmD-Tm1570 in experiment}\n\\label{sec:fit-details-fusion-experiment}\n\n\\subsection{Assumed unknotted state}\n\\label{subsec:fit-details-fusion-experiment-unknotted}\n\\begin{minipage}[c]{0.7\\textwidth}\n \\includegraphics[width=\\textwidth]{fuzja_exp_histograms.png}\n\\end{minipage}\n\\hfill\n\\begin{minipage}[c]{0.45\\textwidth}\n \\begin{itemize}\n \\item method = 'stretch-adjust';\n \\item $p_{prot}=5.9360$\n \\item $k_{prot}=0.0000$\n \\item $p_{dna}=0.1724$\n \\item $k_{dna}=0.0090$\n \\item $l_{dna}=335.848$\n \\item states = 12 (33.3, 41.2, 46.1, 56.5, 73.5, 88.6, 91.9, 96.9, 102.6, 125.5, 134.1, 138.1 nm);\n \\end{itemize}\n\\end{minipage}\n\n\\begin{figure}\n \\centering\n \\includegraphics[width=\\linewidth]{fuzja_exp_contour_lengths_1.png}\n \\caption{All fusion experimental traces assuming unknotted protein.}\n \\label{fig:unknotted-fusion-exp-cl1}\n\\end{figure}\n\n\\begin{figure}\n \\centering\n \\includegraphics[width=\\linewidth]{fuzja_exp_contour_lengths_2.png}\n \\caption{All fusion experimental traces assuming unknotted protein (continued).}\n \\label{fig:unknotted-fusion-exp-cl2}\n\\end{figure}\n\n\\begin{table}\n \\tiny\n \\centering\n \\caption{The fit parameters for fusion (experiment, assumed unknotted).}\n \\label{tab:fusion-fit-parameters-exp-unknotted}\n \\begin{tabular}{c|c|c|c|c}\n \\textbf{Trace} & $p_{dna}$ & $l_{dna}$ & $l_{prot}$ & states [nm]\\\\\\hline\n 1 & 0.132 & 332.318 & 157.315 & 60.8, 72.1, 74.2, 87.5, 96.0, 97.6, 109.3, 133.8, 157.3\\\\\n 2 & 0.210 & 340.781 & 157.315 & 59.1, 67.1, 82.4, 90.9, 94.7, 96.6, 125.2, 158.1, 177.0\\\\\n 3 & 0.210 & 340.469 & 157.242 & 57.4, 62.4, 79.8, 89.7, 120.7, 127.0, 156.5, 158.1\\\\\n 4 & 0.148 & 330.000 & 133.593 & 55.6, 72.8, 91.3, 134.3\\\\\n 5 & 0.153 & 339.926 & 157.315 & 33.4, 37.4, 41.7, 53.9, 157.4\\\\\n 6 & 0.141 & 339.726 & 157.315 & 26.5, 29.8, 33.0, 36.3, 40.6, 42.5, 87.9, 157.4\\\\\n 7 & 0.210 & 337.714 & 157.250 & 41.4, 43.3, 49.7, 58.8, 95.9, 162.5\\\\\n 8 & 0.166 & 338.961 & 157.315 & 29.1, 44.7, 54.3, 90.2\\\\\n 9 & 0.130 & 337.210 & 157.315 & 27.1, 29.9, 32.9, 37.1, 41.0, 46.8, 56.2, 92.3, 157.6\\\\\n 10 & 0.130 & 330.021 & 138.206 & 82.1, 82.7, 97.1, 103.8, 138.0\\\\\n 11 & 0.144 & 331.173 & 128.726 & 47.6, 52.1, 93.5, 96.1, 103.9\\\\\n 12 & 0.147 & 330.000 & 127.728 & 101.3, 110.8, 123.2, 125.8, 129.2\\\\\n 13 & 0.210 & 330.954 & 129.087 & 104.2, 113.4, 126.5, 131.4\\\\\n 14 & 0.210 & 338.259 & 156.753 & 90.5, 95.3, 100.8, 101.0, 149.7, 154.3, 159.1\\\\\n 15 & 0.133 & 335.604 & 157.315 & 86.2, 99.2, 112.8, 116.0, 152.1, 154.8, 157.0, 159.2\\\\\n 16 & 0.210 & 338.322 & 157.315 & 90.4, 95.6, 100.8, 112.5, 151.1, 152.7, 157.7\\\\\n 17 & 0.210 & 337.113 & 157.267 & 92.2, 97.9, 101.5, 112.9, 150.5, 153.2, 157.5\\\\\n 19 & 0.210 & 336.720 & 156.560 & 90.8, 99.1, 113.1, 151.1, 155.8, 158.0, 159.5\\\\\n \\end{tabular}\n\\end{table}\n\n\n\\subsection{Assumed singly knotted state}\n\\label{subsec:fit-details-fusion-experiment-singly}\n\\begin{minipage}[c]{0.7\\textwidth}\n \\includegraphics[width=\\textwidth]{fuzja_pexp_histograms.png}\n\\end{minipage}\n\\hfill\n\\begin{minipage}[c]{0.45\\textwidth}\n \\begin{itemize}\n \\item method = 'stretch-adjust';\n \\item $p_{prot}=5.9360$\n \\item $k_{prot}=0.0000$\n \\item $p_{dna}=0.2011$\n \\item $k_{dna}=0.0090$\n \\item $l_{dna}=338.832$\n \\item states = 11 (29.1, 36.2, 40.1, 85.9, 95.5, 108.2, 114.9, 128.2, 142.5, 146.4, 152.8 nm);\n \\end{itemize}\n\\end{minipage}\n\n\\begin{figure}\n \\centering\n \\includegraphics[width=\\linewidth]{fuzja_pexp_contour_lengths_1.png}\n \\caption{All fusion experimental traces assuming singly knotted protein.}\n \\label{fig:unknotted-fusion-pexp-cl1}\n\\end{figure}\n\n\\begin{figure}\n \\centering\n \\includegraphics[width=\\linewidth]{fuzja_pexp_contour_lengths_2.png}\n \\caption{All fusion experimental traces assuming singly knotted protein (continued).}\n \\label{fig:unknotted-fusion-pexp-cl2}\n\\end{figure}\n\n\\begin{table}\n \\tiny\n \\centering\n \\caption{The fit parameters for fusion (experiment, assumed singly knotted).}\n \\label{tab:fusion-fit-parameters-pexp-unknotted}\n \\begin{tabular}{c|c|c|c|c}\n \\textbf{Trace} & $p_{dna}$ & $l_{dna}$ & $l_{prot}$ & states [nm]\\\\\\hline\n 1 & 0.130 & 335.909 & 152.205 & 55.3, 68.7, 82.0, 90.9, 92.2, 102.5, 105.0, 128.7, 152.2\\\\\n 2 & 0.210 & 344.509 & 152.205 & 54.0, 59.0, 61.3, 76.6, 85.8, 89.4, 91.5, 120.0, 152.9\\\\\n 3 & 0.210 & 344.108 & 152.205 & 52.7, 74.3, 84.6, 115.7, 121.9, 151.4, 153.0\\\\\n 4 & 0.210 & 330.026 & 152.205 & 61.7, 77.8, 79.8, 81.7, 82.7, 95.6, 137.6\\\\\n 5 & 0.210 & 345.552 & 152.205 & 29.2, 36.3, 48.6, 152.3\\\\\n 6 & 0.210 & 345.828 & 152.205 & 25.4, 25.9, 30.1, 35.9, 37.7, 83.0, 152.3\\\\\n 7 & 0.210 & 341.545 & 152.205 & 37.0, 42.4, 44.5, 53.5, 90.6, 157.2\\\\\n 8 & 0.210 & 344.126 & 152.205 & 23.0, 25.3, 29.4, 40.1, 49.3, 85.3\\\\\n 9 & 0.130 & 340.890 & 152.205 & 24.9, 29.3, 31.3, 35.3, 41.4, 51.0, 87.1, 152.4\\\\\n 10 & 0.210 & 330.026 & 152.205 & 89.6, 104.6, 109.2, 142.1\\\\\n 11 & 0.210 & 330.026 & 152.205 & 52.5, 57.0, 98.4, 100.9, 108.6\\\\\n 12 & 0.210 & 330.026 & 152.205 & 108.1, 112.2, 115.3, 127.9, 132.4\\\\\n 13 & 0.210 & 330.026 & 152.205 & 105.6, 114.7, 118.0, 127.8, 132.6\\\\\n 14 & 0.210 & 341.573 & 152.205 & 86.0, 96.2, 107.4, 144.4, 145.3, 154.6\\\\\n 15 & 0.210 & 342.106 & 152.205 & 84.1, 95.4, 109.4, 147.3, 149.8, 151.9, 153.9\\\\\n 16 & 0.210 & 342.027 & 152.205 & 84.4, 95.1, 107.2, 145.9, 147.6, 152.6\\\\\n 17 & 0.210 & 340.791 & 152.205 & 85.6, 96.0, 107.7, 145.3, 148.1, 152.5\\\\\n 19 & 0.210 & 339.877 & 152.205 & 85.8, 94.1, 108.6, 146.7, 151.5, 153.6, 155.2\\\\\n \\end{tabular}\n\\end{table}\n\n\\subsection{Assumed doubly knotted state}\n\\label{subsec:fit-details-fusion-experiment-doubly}\n\\begin{minipage}[c]{0.7\\textwidth}\n \\includegraphics[width=\\textwidth]{fuzja_kexp_histograms.png}\n\\end{minipage}\n\\hfill\n\\begin{minipage}[c]{0.45\\textwidth}\n \\begin{itemize}\n \\item method = 'stretch-adjust';\n \\item $p_{prot}=5.9360$\n \\item $k_{prot}=0.0000$\n \\item $p_{dna}=0.2016$\n \\item $k_{dna}=0.0090$\n \\item $l_{dna}=341.713$\n \\item states = 12 (33.9, 36.8, 40.8, 80.5, 86.8, 90.1, 103.2, 108.2, 114.9, 137.5, 142.0, 147.4 nm);\n \\end{itemize}\n\\end{minipage}\n\n\\begin{figure}\n \\centering\n \\includegraphics[width=\\linewidth]{fuzja_kexp_contour_lengths_1.png}\n \\caption{All fusion experimental traces assuming doubly knotted protein.}\n \\label{fig:doubly-fusion-kexp-cl1}\n\\end{figure}\n\n\\begin{figure}\n \\centering\n \\includegraphics[width=\\linewidth]{fuzja_kexp_contour_lengths_2.png}\n \\caption{All fusion experimental traces assuming doubly knotted protein (continued).}\n \\label{fig:doubly-fusion-exp-cl2}\n\\end{figure}\n\n\\begin{table}\n \\tiny\n \\centering\n \\caption{The fit parameters for fusion (experiment, assumed doubly knotted).}\n \\label{tab:fusion-fit-parameters-exp-doubly}\n \\begin{tabular}{c|c|c|c|c}\n \\textbf{Trace} & $p_{dna}$ & $l_{dna}$ & $l_{prot}$ & states [nm]\\\\\\hline\n 1 & 0.130 & 339.565 & 147.095 & 48.8, 63.1, 76.8, 85.7, 87.8, 97.3, 99.8, 123.5, 147.1\\\\\n 2 & 0.210 & 348.236 & 147.095 & 46.5, 52.2, 54.2, 70.9, 80.5, 84.0, 86.3, 114.8, 147.7\\\\\n 3 & 0.210 & 347.801 & 147.095 & 46.6, 51.3, 69.5, 79.4, 110.6, 116.8, 146.3, 147.9\\\\\n 4 & 0.210 & 330.026 & 147.095 & 61.7, 77.8, 79.8, 81.7, 82.7, 95.6, 137.6\\\\\n 5 & 0.210 & 349.240 & 147.095 & 23.8, 27.7, 31.8, 43.6, 147.2\\\\\n 6 & 0.210 & 349.518 & 147.095 & 18.3, 24.2, 30.6, 32.2, 37.1, 77.9, 147.2\\\\\n 7 & 0.210 & 345.432 & 147.095 & 31.2, 38.9, 48.1, 85.2, 151.8, 0.0, 0.0, 31.2, 38.9, 48.1, 85.2, 151.8\\\\\n 8 & 0.210 & 347.819 & 147.095 & 19.3, 34.8, 44.2, 80.1\\\\\n 9 & 0.130 & 344.549 & 147.095 & 18.9, 22.8, 24.6, 26.0, 29.8, 36.2, 45.7, 81.9, 147.3\\\\\n 10 & 0.210 & 330.026 & 147.095 & 89.6, 104.6, 109.2, 142.1\\\\\n 11 & 0.210 & 330.026 & 147.095 & 52.5, 57.0, 98.4, 100.9, 108.6\\\\\n 12 & 0.210 & 330.026 & 147.095 & 108.1, 112.2, 115.3, 127.9, 132.4\\\\\n 13 & 0.210 & 330.026 & 147.095 & 105.6, 114.7, 118.0, 127.8, 132.6\\\\\n 14 & 0.210 & 345.204 & 147.095 & 79.9, 90.7, 139.1, 140.2, 149.5\\\\\n 15 & 0.210 & 345.810 & 147.095 & 78.0, 90.0, 104.3, 142.2, 144.7, 146.8, 148.8\\\\\n 16 & 0.210 & 345.733 & 147.095 & 78.2, 89.4, 101.9, 140.7, 142.5, 147.5\\\\\n 17 & 0.210 & 344.503 & 147.095 & 79.0, 90.5, 102.4, 140.1, 142.9, 147.3\\\\\n 19 & 0.210 & 343.581 & 147.095 & 79.9, 89.0, 103.2, 141.4, 143.7, 146.3, 148.4, 150.0\\\\\n \\end{tabular}\n\\end{table}", "meta": {"hexsha": "9d2580f85cebdf5be27f55dcf659b7c03e4918e8", "size": 94423, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Report/Chapters/Fit_details.tex", "max_stars_repo_name": "ilbsm/protein_stretching", "max_stars_repo_head_hexsha": "11dc9e2971111dea1185d43c7d0b978831331653", "max_stars_repo_licenses": ["MIT"], "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/Fit_details.tex", "max_issues_repo_name": "ilbsm/protein_stretching", "max_issues_repo_head_hexsha": "11dc9e2971111dea1185d43c7d0b978831331653", "max_issues_repo_licenses": ["MIT"], "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/Fit_details.tex", "max_forks_repo_name": "ilbsm/protein_stretching", "max_forks_repo_head_hexsha": "11dc9e2971111dea1185d43c7d0b978831331653", "max_forks_repo_licenses": ["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.546529563, "max_line_length": 208, "alphanum_fraction": 0.550819186, "num_tokens": 52306, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.1935878186402452}}
{"text": "%\n% $Id$ \n%\n\\label{sec:dft}\n\nThe NWChem density functional theory (DFT) module uses the\nGaussian basis set approach to compute\nclosed shell and open shell densities and Kohn-Sham orbitals\nin the: \n\\begin{itemize}\n\\item local density approximation (LDA), \n\\item non-local density approximation (NLDA), \n\\item local spin-density approximation (LSD), \n\\item non-local spin-density approximation (NLSD),\n\\item non-local meta-GGA approximation (metaGGA),\n\\item any empirical mixture of local and non-local approximations\n(including exact exchange), and\n\\item asymptotically corrected exchange-correlation potentials.\n\\end{itemize}\n\nThe formal scaling of the DFT computation can be reduced by choosing\nto use auxiliary Gaussian basis sets to fit the charge density (CD) and/or \nfit the exchange-correlation (XC) potential.\n\nDFT input is provided using the compound \\verb+DFT+ directive\n\\begin{verbatim}\n DFT\n ...\n END\n\\end{verbatim}\nThe actual DFT calculation will be performed when the input module\nencounters the \\verb+TASK+ directive (Section \\ref{sec:task}). \n\\begin{verbatim}\n TASK DFT\n\\end{verbatim}\n\nOnce a user has specified a geometry and a Kohn-Sham orbital basis set\nthe DFT module can be invoked with no input directives (defaults \ninvoked throughout). There are sub-directives which allow for \ncustomized application; those currently provided as options for \nthe DFT module are:\n\\begin{verbatim}\n VECTORS [[input] () || \\\n (project )] \\\n [swap [alpha||beta] ...] \\\n [output ] \\\n\n\n XC [[acm] [b3lyp] [beckehandh] [pbe0]\\\n [becke97] [becke97-1] [becke97-2] [becke97-3] [becke97-d] [becke98] \\\n [hcth] [hcth120] [hcth147]\\\n [hcth407] [becke97gga1] [hcth407p]\\\n [mpw91] [mpw1k] [xft97] [cft97] [ft97] [op] [bop] [pbeop]\\\n [xpkzb99] [cpkzb99] [xtpss03] [ctpss03] [xctpssh]\\\n [b1b95] [bb1k] [mpw1b95] [mpwb1k] [pw6b95] [pwb6k] [m05] [m05-2x] [vs98] \\\n [m06] [m06-hf] [m06-L] [m06-2x] \\\n [HFexch ] \\\n [becke88 [nonlocal] ] \\\n [xperdew91 [nonlocal] ] \\\n [xpbe96 [nonlocal] ] \\\n [gill96 [nonlocal] ] \\\n [lyp ] \\\n [perdew81 ] \\\n [perdew86 [nonlocal] ] \\\n [perdew91 [nonlocal] ] \\\n [cpbe96 [nonlocal] ] \\\n [pw91lda ] \\\n [slater ] \\\n [vwn_1 ] \\\n [vwn_2 ] \\\n [vwn_3 ] \\\n [vwn_4 ] \\\n [vwn_5 ] \\\n [vwn_1_rpa ] \\\n [xtpss03 [nonlocal] ] \\\n [ctpss03 [nonlocal] ] \\\n [bc95 [nonlocal] ] \\\n [xpw6b95 [nonlocal] ] \\\n [xpwb6k [nonlocal] ] \\\n [xm05 [nonlocal] ] \\\n [xm05-2x [nonlocal] ] \\\n [cpw6b95 [nonlocal] ] \\\n [cpwb6k [nonlocal] ] \\\n [cm05 [nonlocal] ] \\\n [cm05-2x [nonlocal] ]] \\\n [xvs98 [nonlocal] ]] \\\n [cvs98 [nonlocal] ]] \\\n [xm06-L [nonlocal] ]] \\\n [xm06-hf [nonlocal] ]] \\\n [xm06 [nonlocal] ]] \\\n [xm06-2x [nonlocal] ]] \\\n [cm06-L [nonlocal] ]] \\\n [cm06-hf [nonlocal] ]] \\\n [cm06 [nonlocal] ]] \\\n [cm06-2x [nonlocal] ]] \n\n\n\n CONVERGENCE [[energy ] \\\n [density ] \\\n [gradient ] \\\n [dampon ] \\\n [dampoff ] \\\n [diison ] \\\n [diisoff ] \\\n [levlon ] \\\n [levloff ] \\\n [ncydp ] \\\n [ncyds ] \\\n [ncysh ] \\\n [damp ] [nodamping] \\\n [diis [nfock ]] \\\n [nodiis] [lshift ] \\\n [nolevelshifting] \\\n [hl_tol ] \\\n [rabuck [n_rabuck ]]\n\n\n GRID [(xcoarse||coarse||medium||fine||xfine) default medium] \\\n [(gausleg||lebedev ) default lebedev ] \\\n [(becke||erf1||erf2||ssf) default erf1] \\\n [(euler||mura||treutler) default mura] \\\n [rm ] \\\n [nodisk]\n \n\n TOLERANCES [[tight] [tol_rho ] \\\n [accCoul ] \\\n [radius ]]\n\n\n [(LB94||CS00 )]\n\n DECOMP\n ODFT\n DIRECT\n SEMIDIRECT [filesize ]\n [memsize ]\n [filename ]\n INCORE\n ITERATIONS \n MAX_OVL\n MULLIKEN\n DISP\n MULT \n NOIO\n PRINT||NOPRINT\n\\end{verbatim}\n% [accCDfunc ] \\\n% [store_wght] [nquad_task ] \\\n\nThe following \nsections describe these keywords and\noptional sub-directives that can be specified for a \\verb+DFT+ calculation\nin NWChem.\n\n\\section{Specification of Basis Sets for the DFT Module}\n\nThe DFT module requires at a minimum the basis set for the Kohn-Sham \nmolecular orbitals. This basis set must be in the default basis set named\n{\\tt \"ao basis\"}, or it must be assigned to this default name using the\n\\verb+SET+ directive (see Section \\ref{sec:set}).\n\nIn addition to the basis set for the Kohn-Sham orbitals, \nthe charge density fitting basis set can also be specified in the \ninput directives for the DFT module. This basis set is used for the \nevaluation of the Coulomb potential in the Dunlap scheme\\footnote{B.I.~Dunlap, \nJ.W.D.~Connolly and J.R.~Sabin, J.~Chem.~Phys.~{\\bf 71}, 4993 (1979)}.\nThe charge density fitting basis set must have the name {\\tt \"cd basis\"}.\nThis can be the actual name of a basis set, or a basis set can be \nassigned this name using the \\verb+SET+ directive, as described in\nSection \\ref{sec:set}. If this basis set is not defined by input,\nthe $O(N^4)$ exact Coulomb contribution is computed.\n\nThe user also has the option of specifying a third basis set for the \nevaluation of the exchange-correlation potential. This basis set must\nhave the name {\\tt \"xc basis\"}. If this basis set is not specified\nby input, the exchange contribution (XC) is evaluated by numerical\nquadrature. In most applications, this approach is efficient enough,\nso the {\\tt \"xc basis\"} basis set is not generally required.\n\nFor the DFT module, the input options for defining the basis sets in a given\ncalculation can be summarized as follows;\n\\begin{itemize}\n\\item {\\tt \"ao basis\"} -- Kohn-Sham molecular orbitals; required for all \ncalculations\n\\item {\\tt \"cd basis\"} -- charge density fitting basis set; optional, but\nrecommended for evaluation of the Coulomb potential\n\\item {\\tt \"xc basis\"} -- exchange-correlation (XC) fitting basis set; \noptional, and usually not recommended\n\\end{itemize}\n\n\n\\section{{\\tt VECTORS} and {\\tt MAX\\_OVL} --- KS-MO Vectors}\n\nThe \\verb+VECTORS+ directive is the same as that in the SCF module\n(Section \\ref{sec:vectors}). Currently, the \\verb+LOCK+ keyword\nis not supported by the DFT module, however the directive\n\\begin{verbatim}\n MAX_OVL\n\\end{verbatim}\nhas the same effect.\n\n\\section{{\\tt XC} and {\\tt DECOMP} --- Exchange-Correlation Potentials}\n\\label{sec:xc}\n\\begin{verbatim}\n XC [[acm] [b3lyp] [beckehandh] [pbe0]\\\n [becke97] [becke97-1] [becke97-2] [becke97-3] [becke98] [hcth] [hcth120] [hcth147] \\\n [hcth407] [becke97gga1] [hcth407p] \\\n [optx] [hcthp14] [mpw91] [mpw1k] [xft97] [cft97] [ft97] [op] [bop] [pbeop]\\\n [HFexch ] \\\n [becke88 [nonlocal] ] \\\n [xperdew91 [nonlocal] ] \\\n [xpbe96 [nonlocal] ] \\\n [gill96 [nonlocal] ] \\\n [lyp ] \\\n [perdew81 ] \\\n [perdew86 [nonlocal] ] \\\n [perdew91 [nonlocal] ] \\\n [cpbe96 [nonlocal] ] \\\n [pw91lda ] \\\n [slater ] \\\n [vwn_1 ] \\\n [vwn_2 ] \\\n [vwn_3 ] \\\n [vwn_4 ] \\\n [vwn_5 ] \\\n [vwn_1_rpa ]]\n\\end{verbatim}\n\nThe user has the option of specifying the exchange-correlation\ntreatment in the DFT Module (see table \\ref{tablexc}).\n The default exchange-correlation\nfunctional is defined as the local density approximation (LDA) for\nclosed shell systems and its counterpart the local spin-density (LSD)\napproximation for open shell systems. Within this approximation the\nexchange functional is the Slater $\\rho^{1/3}$ functional (from\nJ.C.~Slater, {\\sl Quantum Theory of Molecules and Solids, Vol.~4: The\n Self-Consistent Field for Molecules and Solids} (McGraw-Hill, New\nYork, 1974)), and the correlation functional is the Vosko-Wilk-Nusair\n(VWN) functional (functional V) (S.J.~Vosko, L.~Wilk and M.~Nusair,\nCan.~J.~Phys.~{\\bf 58}, 1200 (1980)). The parameters used in this\nformula are obtained by fitting to the Ceperley and\nAlder\\footnote{D.M.~Ceperley and B.J.~Alder, Phys. Rev. Lett. {\\bf\n 45}, 566 (1980).}\nQuantum Monte-Carlo solution of the {\\em\n homogeneous electron gas}.\n\nThese defaults can be invoked explicitly by specifying the following\nkeywords within the DFT module input directive, \\verb+XC slater vwn_5+.\n\n\nThat is, this statement in the input file\n\\begin{verbatim}\ndft\n XC slater vwn_5\nend\ntask dft\n\\end{verbatim}\n\nis equivalent to the simple line\n\\begin{verbatim}\ntask dft\n\\end{verbatim}\n\n\nThe \\verb+DECOMP+ directive causes the components of the energy\ncorresponding to each functional to be printed, rather than just the\ntotal exchange-correlation energy which is the default. You can see\nan example of this directive in the sample input in \nSection \\ref{sec:DFTsample}.\n\n\nMany alternative exchange and correlation functionals are available to\nthe user as listed in table \\ref{tablexc}. The following sections describe \nhow to use these options.\n\n\\subsection{Exchange-Correlation Functionals}\n\nThere are several Exchange and Correlation functionals in addition to the \ndefault {\\tt slater} and {\\tt vwn\\_5}\nfunctionals. These are either local or gradient-corrected functionals (GCA);\na full list can be found in table \\ref{tablexc}. \n\n%\\begin{itemize}\n%\n%\\item the Becke 1998 gradient-corrected functional (see A.D.~Becke, \n% Phys. Rev. A {\\bf 38}, 3098 (1988)), is invoked by specifying\n%\n%\\begin{verbatim}\n% XC becke88\n%\\end{verbatim}\n%\n%\\item the Perdew 1991 gradient-corrected exchange functional (J.P. Perdew,\n% J.A.~Chevary, S.H.~Vosko, K.A.~Jackson, M.R.~Pederson, D.J.~Singh\n% and C.~Fiolhais, Phys. Rev. B {\\bf 46}, 6671 (1992)), is invoked by specifying\n%\n%\\begin{verbatim}\n% XC xperdew91\n%\\end{verbatim}\n%\n%\\item the Perdew-Burke-Ernzerhof gradient-corrected exchange functional \\\\\n% (J.P.~Perdew, K.~Burke and M.~Ernzerhof, Physical Review Letters\n%{\\bf 77}, 3865 (1996); {\\bf 78}, 1396 (1997))), is invoked by specifying\n%\n%\\begin{verbatim}\n% XC xpbe96\n%\\end{verbatim}\n%\n%\\item the Gill 1996 gradient-corrected exchange functional (P.W.Gill , Mol. Phys. {\\bf 89}, 433 (1996)), is invoked by specifying\n%\n%\\begin{verbatim}\n% XC gill96\n%\\end{verbatim}\n\n\n%\\item \nThe Hartree-Fock exact exchange functional, (which has $O(N^4)$\ncomputation expense), is invoked by specifying\n\\begin{verbatim}\n XC HFexch\n\\end{verbatim}\n%\\end{itemize}\n\nNote that the user also has the ability to include only the local or\nnonlocal contributions of a given functional. In addition the user\ncan specify a multiplicative prefactor (the variable\n\\verb++ in the input) for the local/nonlocal component or\ntotal. An example of this might be,\n\\begin{verbatim}\n XC becke88 nonlocal 0.72\n\\end{verbatim}\nThe user should be aware that the Becke88 local component is simply\nthe Slater exchange and should be input as such.\n\nAny combination of the supported exchange functional options can be\nused. For example the popular Gaussian B3 exchange could be specified\nas:\n\\begin{verbatim}\n XC slater 0.8 becke88 nonlocal 0.72 HFexch 0.2\n\\end{verbatim}\n\n \n%\\subsection{Correlation Functionals}\n\n%In addition to the default \\verb+vwn_5+ correlation functional, the user has\n%alternative correlation functionals as listed in table \\ref{tablexc}.\n%to choose from: lyp, perdew81,\n%perdew86, perdew91, pw91lda, \\verb+vwn_1+, \\verb+vwn_2+, \\verb+vwn_3+,\n%\\verb+vwn_4+, and \\verb+vwn_1_rpa+.\n\n%As in the exchange functional input, individual local/nonlocal\n%components as well as multiplicative prefactors can be invoked where\n%appropriate. Each of the correlation functionals is listed below along with\n%appropriate citation in table \\ref{tablexc}. \n\n\\sloppy\n\n%\\begin{itemize}\n%\\item VWN local density functionals; S.J.~Vosko, L.~Wilk and M.~Nusair, \n% Can.~J.~Phys.~{\\bf 58}, 1200 (1980); all five (5) functionals as\n% described in this paper (addressed in the paper as I - V) have been\n% implemented. These functionals can be invoked with the keywords:\n%\\begin{verbatim}\n% XC vwn_1\n% XC vwn_2\n% XC vwn_3\n% XC vwn_4\n% XC vwn_5\n%\\end{verbatim}\n%\n% Note that functionals; \\verb+vwn_2+, \\verb+vwn_3+, and \\verb+vwn_4+\n% require both sets of parameters (the Monte Carlo parameters of\n% Ceperley and Alder and VWN's RPA parameters) used in fitting the\n% homogeneous electron gas correlation energy. Functionals\n% \\verb+vwn_1+ and \\verb+vwn_5+ require only the Monte Carlo fitting\n% parameters. In order to reproduce results in the literature another\n% functional was added; the \\verb+vwn_1_rpa+. This is the original\n% \\verb+vwn_1+ functional with RPA parameters as opposed to the\n% prescribed Monte Carlo parameters. This functional can be invoked\n% with the keyword,\n%\\begin{verbatim}\n% XC vwn_1_rpa\n%\\end{verbatim}\n%\n%\\item Perdew81 local density functional; J.~P.~Perdew and A.~Zunger,\n% Phys.~Rev.~B {\\bf23}, 5048 (1981). This functional can be invoked with the\n% keyword,\n%\\begin{verbatim}\n% XC perdew81\n%\\end{verbatim}\n%\n%\\item Perdew \\& Wang 1991 local density functional; J.P.~Perdew\n% and Y.~Wang, Phys. Rev. B {\\bf 45}, 13244 (1992). The parameters\n% used in this formula are obtained by fitting to the Ceperley and\n% Alder Quantum Monte Carlo solution of the {\\em\n% homogeneous electron gas}. This functional can be invoked with the\n% keyword,\n%\\begin{verbatim}\n% XC pw91lda\n%\\end{verbatim}\n%\n%\\item Perdew86 gradient-corrected functional; J.~P.~Perdew, Phys.~Rev.~B \n% {\\bf33}, 8822 (1986). Note that this is a nonlocal functional and\n% in the absence of any local functional specification the local\n% component is defaulted to the perdew81 local correlation\n% functional. This functional can be invoked with the\n% keyword,\n%\\begin{verbatim}\n% XC perdew86\n%\\end{verbatim}\n%\n%\\item Perdew91 gradient-corrected functional; J.P.~Perdew,\n% J.A.~Chevary, S.H.~Vosko, K.A.~Jackson, M.R.~Pederson, D.J.~Singh\n% and C.~Fiolhais, Phys. Rev. B {\\bf 46}, 6671 (1992). Note that this\n% is a nonlocal functional and in the absence of any local functional \n% specification the local component is defaulted to the \\verb+pw91lda+ local \n% correlation functional. This functional can be invoked with the keyword,\n%\\begin{verbatim}\n% XC perdew91\n%\\end{verbatim}\n%\n%\\item the Perdew-Burke-Ernzerhof gradient-corrected correlation functional \\\\\n% (J.P.~Perdew, K.~Burke and M.~Ernzerhof, Physical Review Letters\n%{\\bf 77}, 3865 (1996); {\\bf 78}, 1396 (1997))), is invoked by specifying\n%\n%\\begin{verbatim}\n% XC cpbe96\n%\\end{verbatim}\n\n%\\item LYP gradient-corrected functional; C.~Lee, W.~Yang and\n% R.~G.~Parr, Phys.~Rev.~B {\\bf 37}, 785 (1988). Note that this\n% is a local and nonlocal functional but cannot be conveniently split\n% into the individual components. The option to scale the total remains.\n% This functional can be invoked with the keyword,\n%\\begin{verbatim}\n% XC lyp\n%\\end{verbatim}\n%\n%\\end{itemize}\n\n\\fussy\n\nAny combination of the supported correlation functional options can be\nused. For example B3LYP could be specified as:\n\\begin{verbatim}\nXC vwn_1_rpa 0.19 lyp 0.81 HFexch 0.20 slater 0.80 becke88 nonlocal 0.72\n\\end{verbatim}\nand X3LYP as:\n\\begin{verbatim}\nxc vwn_1_rpa 0.129 lyp 0.871 hfexch 0.218 slater 0.782 \\\nbecke88 nonlocal 0.542 xperdew91 nonlocal 0.167 \n\\end{verbatim}\n\n \n\\subsection{Combined Exchange and Correlation Functionals}\n\nIn addition to the options listed above for the exchange and correlation\nfunctionals, the user has the alternative of specifying combined exchange and \ncorrelation functionals. A complete list of the available functionals\nappears in table \\ref{tablexc}.\n\n The available hybrid functionals \n(where a Hartree-Fock Exchange component is present) consist of the Becke\n``{\\it half and half}'' (see A.D.~Becke, J.~Chem.~Phys.~98, 1372 (1992)), the\nadiabatic connection method (see A.D.~Becke, J.~Chem.~Phys.~98, 5648\n(1993)), B3LYP (popularized by Gaussian9X), Becke 1997 \n(``Becke V'' paper: A.D.Becke, J. Chem. Phys., {\\bf 107}, 8554 (1997)).\n\n%These options can be invoked by specifying any of the following input lines,\n%\\begin{verbatim}\n% XC beckehandh\n% XC acm\n% XC b3lyp\n% XC becke97\n% Xc becke97-1\n% xc becke98\n% xc pbe0\n% xc hcth\n% xc hcth120\n% xc hcth147\n% xc hcth407\n% xc hcthp14\n% xc becke97gga1\n%\\end{verbatim}\n\nThe keyword \\verb+beckehandh+ specifies that the exchange-correlation energy will be\ncomputed as \n\\begin{eqnarray*}\nE_{XC} \\ \\approx \\ \\frac{1}{2} E^{\\rm HF}_X + \\frac{1}{2} E^{\\rm\n Slater}_{X} + \\frac{1}{2} E^{\\rm PW91LDA}_{C}\n\\end{eqnarray*}\nWe know this is NOT the correct Becke prescribed implementation which\nrequires the XC potential in the energy expression. But this is what\nis currently implemented as an approximation to it.\n\n%\\clearpage\n%\n\nThe keyword \\verb+acm+ specifies that the exchange-correlation energy\nis computed as\n\\begin{eqnarray*}\nE_{XC} \\ &=& \\ a_0 E^{\\rm HF}_X + (1-a_0) E^{\\rm Slater}_{X} +\na_X \\Delta E^{\\rm Becke88}_{X} + E^{\\rm VWN}_C + a_C \\Delta E^{Perdew91}_C \\\\\n& &{\\rm where } \\\\\na_0 &=& 0.20, \\ a_X = 0.72, \\ a_C = 0.81\n\\end{eqnarray*}\nand $\\Delta$ stands for a non-local component.\n\n\nThe keyword \\verb+b3lyp+ specifies that the exchange-correlation energy\nis computed as\n\\begin{eqnarray*}\nE_{XC} \\ &=& \\ a_0 E^{\\rm HF}_X + (1-a_0) E^{\\rm Slater}_{X} +\na_X \\Delta E^{\\rm Becke88}_{X} + (1-a_C)E^{\\rm VWN\\_1\\_RPA}_C + a_C E^{LYP}_C \\\\\n& &{\\rm where } \\\\\na_0 &=& 0.20, \\ a_X = 0.72, \\ a_C = 0.81\n\\end{eqnarray*}\n\n\n%The keyword \\verb+becke97-1+ specifies the hybrid exchange-correlation energy\n%derived by Handy et al by re-fitting the Becke 1997 functional\n%(F.A.Hamprecht, A.J.Cohen, D.J.Tozer and N.C.Handy, \n% J. Chem. Phys. {\\bf 109}, 6264 (1998))\n%\n%The keyword \\verb+hcth+ specifies the exchange-correlation energy \n%functional derived by Hamprecht-Cohen-Tozer-Handy \n%(this is not a hybrid functional)\n%(F.A.Hamprecht, A.J.Cohen, D.J.Tozer and N.C.Handy, \n% J. Chem. Phys. {\\bf 109}, 6264 (1998))\n\n\n\n\\subsection{Meta-GGA Functionals}\n\n\nOne way to calculate meta-GGA energies is to use\n orbitals and densities \nfrom fully self-consistent GGA or LDA calculations\nand run them in one iteration in the meta-GGA functional.\nIt is expected that meta-GGA energies obtained\nthis way will be close to fully self consistent\nmeta-GGA calculations. \n\nIt is possible to calculate metaGGA energies both ways\nin NWChem, that is, self-consistently or with\nGGA/LDA orbitals and densities. However, since second derivatives\nare not available for metaGGAs, in order to\ncalculate frequencies, one must use\n\\verb+ task dft freq numerical+.\nA sample file with this is shown below,\nin \\ref{sec:DFTsample}. In this instance, the\nenergy is calculated self-consistently and geometry is optimized using the analytical gradients.\n\n\n(For more information on metaGGAs, see\nS. Kurth, J. Perdew, P. Blaha, Int. J. Quant. Chem 75, 889 (1999)\nfor a brief description of meta-GGAs, and citations 14-27\ntherein for thorough background )\n\nNote: both TPSS and PKZB correlation\nrequire the PBE GGA CORRELATION (which is itself dependent on an LDA). \nThe decision has been made to\nuse these functionals with the accompanying local\nPW91LDA. The user does not have the ability to set\nthe local part of these metaGGA functionals.\n\n\n\\section{{\\tt LB94} and {\\tt CS00} --- Asymptotic correction}\n\nThe keyword \\verb+LB94+ will correct the asymptotic region of \nthe \\verb+XC+ definition of exchange-correlation {\\it potential} by \nthe van-Leeuwen--Baerends exchange-correlation {\\it potential} that\nhas the correct $-1/r$ asymptotic behavior. The total energy will be computed by the \n\\verb+XC+ definition of exchange-correlation functional. This scheme is known to\ntend to overcorrect the deficiency of most uncorrected exchange-correlation potentials.\n\nThe keyword \\verb+CS00+, when supplied with a real value of shift (in atomic units),\nwill perform Casida--Salahub '00 asymptotic correction. This is primarily intended\nfor use in conjunction with TDDFT and the background of this method is given in more\ndetail in Chapter 14. The shift is normally positive (which means that the original\nuncorrected exchange-correlation potential must be shifted down).\n\nWhen the keyword \\verb+CS00+ is specified without the value of shift, the program will\nautomatically supply it according to the semi-empirical formula of Zhan, Nichols, and\nDixon (again, see Chapter 14 for more details and references). As the Zhan's formula \nis calibrated against B3LYP results, it is most meaningful to use this in conjunction\nwith the B3LYP functional, although the program does not prohibit (or even warn) the use\nof any other functional.\n\nSample input files of asymptotically corrected TDDFT calculations can be found in \nChapter 14.\n\n\\section{Sample input file}\n\\label{sec:DFTsample}\nA simple example calculates the geometry\n of water, using the metaGGA functionals\n\\verb+ xtpss03+ and \\verb+ctpss03+.\nThis also highlights some of\nthe print features in the DFT module. Note\nthat you must use the line\n\\verb+task dft freq numerical+ because\nanalytic hessians are not available for the metaGGAs:\n\\begin{verbatim}\ntitle \"WATER 6-311G* meta-GGA XC geometry\"\necho\ngeometry units angstroms\n O 0.0 0.0 0.0\n H 0.0 0.0 1.0\n H 0.0 1.0 0.0\nend\nbasis\n H library 6-311G*\n O library 6-311G*\nend\ndft\n iterations 50\n print kinetic_energy\n xc xtpss03 ctpss03\n decomp\nend\ntask dft optimize\n\ntask dft freq numerical\n\\end{verbatim}\n\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\twocolumn\n\\begin{table}[htp]\n\\centering\n{\\scriptsize \n\\begin{tabular}{|l|p{0.12cm}p{0.12cm}cccp{0.35cm}|c|}\n\\hline\nKeyword & X & C & GGA & Meta & Hybr. & 2nd & Ref.\\\\\n\\hline\n{\\tt slater }& $\\star$ & & & & & Y &[1] \\\\\n\\hline \n{\\tt vwn\\_1 }& & $\\star$ & & & & Y &[2] \\\\\n{\\tt vwn\\_2 }& & $\\star$ & & & & Y &[2] \\\\\n{\\tt vwn\\_3 }& & $\\star$ & & & & Y &[2] \\\\\n{\\tt vwn\\_4 }& & $\\star$ & & & & Y &[2] \\\\\n{\\tt vwn\\_5 }& & $\\star$ & & & & Y &[2] \\\\\n{\\tt vwn\\_1\\_rpa}& & $\\star$ & & & & Y &[2] \\\\\n{\\tt perdew81 }& & $\\star$ & & & & Y &[3] \\\\\n{\\tt pw91lda }& & $\\star$ & & & & Y &[4] \\\\\n\\hline \n{\\tt becke88 }& $\\star$ & & $\\star$ & & & Y &[5]\\\\\n{\\tt xperdew91}& $\\star$ & & $\\star$ & & & Y &[6]\\\\\n{\\tt xpbe96 }& $\\star$ & & $\\star$ & & & Y &[7]\\\\\n{\\tt gill96 }& $\\star$ & & $\\star$ & & & Y &[8]\\\\\n{\\tt optx }& $\\star$ & & $\\star$ & & & N &[20]\\\\\n{\\tt mpw91 }& $\\star$ & & $\\star$ & & & Y &[23]\\\\\n{\\tt xft97 }& $\\star$ & & $\\star$ & & & N &[24]\\\\\n{\\tt rpbe }& $\\star$ & & $\\star$ & & & Y &[33]\\\\\n{\\tt revpbe }& $\\star$ & & $\\star$ & & & Y &[34]\\\\\n{\\tt xpw6b95 }& $\\star$ & & $\\star$ & & & N &[36]\\\\\n{\\tt xpwb6k }& $\\star$ & & $\\star$ & & & N &[36]\\\\\n\\hline \n{\\tt perdew86 }& & $\\star$ & $\\star$ & & & Y &[9]\\\\\n{\\tt lyp }& & $\\star$ & $\\star$ & & & Y &[10]\\\\\n{\\tt perdew91 }& & $\\star$ & $\\star$ & & & Y &[6]\\\\\n{\\tt cpbe96 }& & $\\star$ & $\\star$ & & & Y &[7]\\\\\n{\\tt cft97 }& & $\\star$ & $\\star$ & & & N &[24]\\\\\n{\\tt op }& & $\\star$ & $\\star$ & & & N &[31]\\\\\n\\hline \n{\\tt hcth }& $\\star$ & $\\star$ & $\\star$ & & & N &[11]\\\\\n{\\tt hcth120 }& $\\star$ & $\\star$ & $\\star$ & & & N &[12]\\\\\n{\\tt hcth147 }& $\\star$ & $\\star$ & $\\star$ & & & N &[12]\\\\\n{\\tt hcth407 }& $\\star$ & $\\star$ & $\\star$ & & & N &[19]\\\\\n{\\tt becke97gga1}& $\\star$ & $\\star$ & $\\star$ & & & N &[18]\\\\\n{\\tt hcthp14 }& $\\star$ & $\\star$ & $\\star$ & & & N &[21]\\\\\n{\\tt ft97 }& $\\star$ & $\\star$ & $\\star$ & & & N &[24]\\\\\n{\\tt htch407p }& $\\star$ & $\\star$ & $\\star$ & & & N &[27]\\\\\n{\\tt bop }& $\\star$ & $\\star$ & $\\star$ & & & N &[31]\\\\\n{\\tt pbeop }& $\\star$ & $\\star$ & $\\star$ & & & N &[32]\\\\\n\\hline \n{\\tt xpkzb99 }& $\\star$ & & &$\\star$& & N &[26]\\\\\n{\\tt cpkzb99 }& & $\\star$ & &$\\star$& & N &[26]\\\\\n{\\tt xtpss03 }& $\\star$ & & &$\\star$& & N &[28]\\\\\n{\\tt ctpss03 }& & $\\star$ & &$\\star$& & N &[28]\\\\\n{\\tt bc95 }& & $\\star$ & &$\\star$& & N &[33]\\\\\n{\\tt cpw6b95 }& & $\\star$ & &$\\star$& & N &[36]\\\\\n{\\tt cpwb6k }& & $\\star$ & &$\\star$& & N &[36]\\\\\n{\\tt xm05 }& $\\star$ & & &$\\star$& & N &[37]\\\\\n{\\tt cm05 }& & $\\star$ & &$\\star$& & N &[37]\\\\\n{\\tt xm05-2x }& $\\star$ & & &$\\star$& & N &[38]\\\\\n{\\tt cm05-2x }& & $\\star$ & &$\\star$& & N &[38]\\\\\n{\\tt xctpssh }& & & &$\\star$&$\\star$& N &[29]\\\\\n{\\tt bb1k }& & & &$\\star$&$\\star$& N &[34]\\\\\n{\\tt mpw1b95 }& & & &$\\star$&$\\star$& N &[35]\\\\\n{\\tt mpwb1k }& & & &$\\star$&$\\star$& N &[35]\\\\\n{\\tt pw6b95 }& & & &$\\star$&$\\star$& N &[36]\\\\\n{\\tt pwb6k }& & & &$\\star$&$\\star$& N &[36]\\\\\n{\\tt m05 }& & & &$\\star$&$\\star$& N &[37]\\\\\n{\\tt vsxc }& & & &$\\star$&$\\star$& N &[39]\\\\\n{\\tt xvsxc }& $\\star$ & & &$\\star$& & N &[39]\\\\\n{\\tt cvsxc }& & $\\star$ & &$\\star$& & N &[39]\\\\\n{\\tt m06-L }& $\\star$ & $\\star$ & &$\\star$&$\\star$& N &[40]\\\\\n{\\tt xm06-L }& & & &$\\star$& & N &[40]\\\\\n{\\tt cm06-L }& & $\\star$ & &$\\star$& & N &[40]\\\\\n{\\tt m06-hf }& & & &$\\star$&$\\star$& N &[41]\\\\\n{\\tt xm06-hf }& $\\star$ & & &$\\star$& & N &[41]\\\\\n{\\tt cm06-hf }& & $\\star$ & &$\\star$& & N &[41]\\\\\n{\\tt m06 }& & & &$\\star$&$\\star$& N &[42]\\\\\n{\\tt xm06 }& $\\star$ & & &$\\star$& & N &[42]\\\\\n{\\tt cm06 }& & $\\star$ & &$\\star$& & N &[42]\\\\\n{\\tt m06-2x }& & & &$\\star$&$\\star$& N &[42]\\\\\n{\\tt xm06-2x }& $\\star$ & & &$\\star$& & N &[42]\\\\\n{\\tt cm06-2x }& & $\\star$ & &$\\star$& & N &[42]\\\\\n\\hline\n{\\tt beckehandh}& $\\star$ & $\\star$ & & & $\\star$ & Y &[13]\\\\\n{\\tt b3lyp }& $\\star$ & $\\star$ & $\\star$ & & $\\star$ & Y &[14]\\\\\n{\\tt acm }& $\\star$ & $\\star$ & $\\star$ & & $\\star$ & Y &[14]\\\\\n{\\tt becke97 }& $\\star$ & $\\star$ & $\\star$ & & $\\star$ & N &[15]\\\\\n{\\tt becke97-1}& $\\star$ & $\\star$ & $\\star$ & & $\\star$ & N &[11]\\\\\n{\\tt becke97-2}& $\\star$ & $\\star$ & $\\star$ & & $\\star$ & N &[22]\\\\\n{\\tt becke97-3}& $\\star$ & $\\star$ & $\\star$ & & $\\star$ & N &[30]\\\\\n{\\tt becke97-d}& $\\star$ & $\\star$ & $\\star$ & & $\\star$ & N &[45]\\\\\n{\\tt becke98 }& $\\star$ & $\\star$ & $\\star$ & & $\\star$ & N &[16]\\\\\n{\\tt pbe0 }& $\\star$ & $\\star$ & $\\star$ & & $\\star$ & Y &[17]\\\\\n{\\tt mpw1k }& $\\star$ & $\\star$ & $\\star$ & & $\\star$ & Y &[25]\\\\\n\\hline\n\\end{tabular}\n\\caption{Table of available Exchange (X) and Correlation (C) functionals.\nGGA is the Generalized Gradient Approximation, and Meta refers to Meta-GGAs.\nThe column {\\em 2nd} refers to second derivatives of the\nenergy with respect to nuclear position. }\n\\label{tablexc}\n}\n\\end{table}\n\n\n\n{\\footnotesize\n\\vspace{8.5cm}\n\\begin{enumerate}\\setlength{\\itemsep}{-1\\baselineskip}\n\\setlength{\\parsep}{-1\\baselineskip}\n\\item J.C.~Slater and K. H. Johnson, Phys. Rev. B {\\bf 5}, 844 (1972)\\\\\n\\item S.J.~Vosko, L.~Wilk and M.~Nusair,\nCan.~J.~Phys.~{\\bf 58}, 1200 (1980)\\\\\n\\item J.~P.~Perdew and A.~Zunger, Phys.~Rev.~B {\\bf23}, 5048\n(1981). \\\\\n\\item J.P.~Perdew and Y.~Wang, Phys. Rev. B {\\bf 45},\n13244 (1992)\\\\\n\\item A.D.~Becke, Phys. Rev. A {\\bf 88}, 3098 (1988)\\\\ \n\\item J.P. Perdew, J.A.~Chevary, S.H.~Vosko, K.A.~Jackson, \nM.R.~Pederson, D.J.~Singh and C.~Fiolhais, Phys. Rev. B {\\bf 46}, 6671\n(1992)\\\\\n\\item J.P.~Perdew, K.~Burke and M.~Ernzerhof, \nPhys. Rev. Lett. {\\bf 77}, 3865 (1996); {\\bf 78 }, 1396 (1997)\\\\\n\\item P.W.Gill , Mol. Phys. {\\bf 89}, 433 (1996)\\\\\n\\item J.~P.~Perdew, Phys.~Rev.~B {\\bf33}, 8822 (1986)\\\\\n\\item C.~Lee, W.~Yang and R.~G.~Parr, Phys.~Rev.~B {\\bf 37}, 785\n(1988)\\\\\n\\item F.A.Hamprecht, A.J.Cohen, D.J.Tozer and N.C\\\\ Handy, \n J. Chem. Phys. {\\bf 109}, 6264 (1998)\\\\\n\\item A.D.Boese, N.L.Doltsinis, N.C.Handy and\nM.Sprik. J. Chem. Phys. {\\bf 112}, 1670 (2000)\\\\\n\\item A.D.~Becke, J.~Chem.~Phys. {\\bf 98}, 1372 (1992)\\\\\n\\item A.D.~Becke, J.~Chem.~Phys.~{\\bf 98}, 5648 (1993)\\\\\n\\item A.D.Becke, J. Chem. Phys. {\\bf 107}, 8554 (1997)\\\\\n\\item H.L.Schmider and A.D.~Becke, J.~Chem.~Phys.~{\\bf 108},\n9624 (1998)\\\\\n\\item C.Adamo and V.Barone, J.~Chem.~Phys. {\\bf 110}, 6158 (1998)\\\\\n\\item A.J.Cohen and N.C. Handy, Chem. Phys. Lett. {\\bf 316}, 160 (2000)\\\\\n\\item A.D.Boese, N.C.Handy, J. Chem. Phys. {\\bf 114}, 5497\n(2001)\\\\\n\\item N.C.Handy, A.J. Cohen, Mol. Phys. {\\bf 99}, 403 (2001)\\\\\n\\item G. Menconi, P.J. Wilson, D.J. Tozer, \nJ. Chem. Phys {\\bf 114}, 3958 (2001)\\\\\n\\item P.J. Wilson, T.J. Bradley, D.J. Tozer, J. Chem. Phys {\\bf 115}, \n9233 (2001)\\\\\n\\item C. Adamo and V. Barone, J.~Chem.~Phys. {\\bf 108}, 664 (1998); Y. Zhao and D.G. Truhlar, J. Phys. Chem. A {\\bf 109}, 5656 (2005)\\\\\n\\item M.Filatov and W.Thiel, Mol.Phys. {\\bf 91}, 847 (1997).\n M.Filatov and W.Thiel, Int.J.Quantum Chem. {\\bf 62}, 603 (1997)\\\\\n\\item B.J. Lynch, P.L. Fast, M. Harris and D.G. Truhlar, J. Phys. Chem. A\n{\\bf 104}, 4811(2000)\\\\\n\\item J.P.~Perdew, S.~Kurth, A.~Zupan and P.~Blaha, \nPhys. Rev. Lett. {\\bf 82}, 2544 (1999)\\\\\n\\item A.~D.~Boese, A.~Chandra, J.~M.~L.~Martin and D.~Marx,\n J. Chem. Phys. {\\bf 119}, 5965 (2003)\\\\\n\\item J. Tao,J.Perdew, V. Staroverov and G. Scuseria,\nPhys. Rev. Let. {\\bf 91}, 146401-1 (2003)\\\\\n\\item V. Staroverov, G. Scuseria,\nJ. Tao and J.Perdew, J. Chem.Phys. {\\bf 119}, 12129 (2003)\\\\\n\\item T.W. Keal, D.J. Tozer, J. Chem. Phys {\\bf 123}, \n121103 (2005)\\\\\n\\item T. Tsuneda, T. Suzumura and K. Hirao,\nJ. Chem Phys. {\\bf 110}, 10664 (1999)\\\\\n\\item T. Tsuneda, T. Suzumura and K. Hirao,\nJ. Chem Phys. {\\bf 111}, 5656 (1999) \\\\\n\\item B. Hammer, L. B. Hansen and J. N{\\o}rskov , Phys. Rev. B {\\bf 58}, 7413 (1999)\\\\\n\\item Y. Zhang and W. Yang, Phys. Rev. Letters {\\bf 80}, 890 (1998)\\\\\n\\item A. D. Becke, J. Chem. Phys. {\\bf 104}, 1040 (1996)\\\\\n\\item Y. Zhao and D. G. Truhlar, J. Phys. Chem. A {\\bf 108}, 2715 (2004)\\\\\n\\item Y. Zhao and D. G. Truhlar, J. Phys. Chem. A {\\bf 108}, 6908 (2004)\\\\\n\\item Y. Zhao and D. G. Truhlar, J. Phys. Chem. A {\\bf 109}, 5656 (2005)\\\\\n\\item Y. Zhao, N. E. Schultz and D. G. Truhlar, J. Chem. Phys. {\\bf 123}, 161103 (2005)\\\\\n\\item Y. Zhao, N. E. Schultz and D. G. Truhlar, J. Chem. Theory Comput. {\\bf 2}, 364 (2006)\\\\\n\\item T. Van Voorhis, G. E. Scuseria, J. Chem. Phys. {\\bf 109}, 400 (1998)\\\\\n\\item Y. Zhao, D. G. Truhlar, J. Chem. Phys. {\\bf 125}, 194101 (2006)\\\\\n\\item Y. Zhao, D. G. Truhlar, J. Phys. Chem. A. {\\bf 110}, 13126 (2006)\\\\\n\\item Y. Zhao, D. G. Truhlar, Theor. Chem. Acc. (2006)\\\\\n\\item S. Grimme, J. Comp. Chem. \\bf{27}, 1787 (2006).\n\n\\end{enumerate}\n}\n%\\end{table}\n\\onecolumn\n\n\\section{{\\tt ITERATIONS} --- Number of SCF iterations}\n\n\\begin{verbatim}\n ITERATIONS \n\\end{verbatim}\n\nThe default optimization in the DFT module is to iterate on the \nKohn-Sham (SCF) equations for a specified number of iterations\n(default 30). The keyword that controls this optimization \nis \\verb+ITERATIONS+, and has the following general form,\n\n\\begin{verbatim}\n iterations \n\\end{verbatim}\n\nThe optimization procedure will stop when the specified number of\niterations is reached or convergence is met. See an example\nthat uses this directive in section \\ref{sec:DFTsample}.\n\n\\section{{\\tt CONVERGENCE} --- SCF Convergence Control}\n\\label{sec:dftconv}\n\n\\begin{verbatim}\n CONVERGENCE [energy ] \\\n [density ] \\\n [gradient ] \\\n [hl_tol ]\n [dampon ] \\\n [dampoff ] \\\n [ncydp ] \\\n [ncyds ] \\\n [ncysh ] \\\n [damp ] [nodamping] \\\n [diison ] \\\n [diisoff ] \\\n [(diis [nfock ]) || nodiis] \\\n [levlon ] \\\n [levloff ] \\\n [(lshift ) || nolevelshifting] \\\n [rabuck [n_rabuck ]]\n\\end{verbatim}\n\nConvergence is satisfied by meeting any or all of three criteria;\n\\begin{itemize}\n\\item convergence of the total energy; this is defined to be when the\n total DFT energy at iteration N and at iteration N-1 differ by a value less\n than some value (the default is 1e-6). This value can be modified\n using the key word,\n\\begin{verbatim}\n CONVERGENCE energy \n\\end{verbatim}\n\n\\item convergence of the total density; this is defined to be when the\n total DFT density matrix at iteration N and at iteration N-1 have a\n RMS difference less than some value (the default is 1e-5). This value can be modified\n using the key word,\n\\begin{verbatim}\n CONVERGENCE density \n\\end{verbatim}\n\n\\item convergence of the orbital gradient; this is defined to be when the\n DIIS error vector becomes less than some value (the default is\n 5e-4). This value can be modified using the key word,\n\\begin{verbatim}\n CONVERGENCE gradient \n\\end{verbatim}\n\\end{itemize}\n\nThe default optimization strategy is to immediately begin direct\ninversion of the iterative subspace\\footnote {P.~Pulay, Chem.\\ Phys.\\ \n Lett.\\ {\\bf 73}, 393 (1980) and P.~Pulay, J.~Comp.~Chem.~{\\bf 3},\n 566 (1982)}. Damping is also initiated (using 70\\% of the previous\ndensity) for the first 2 iteration. In addition, if the HOMO - LUMO\ngap is small and the Fock matrix somewhat diagonally dominant, then\nlevel-shifting is automatically initiated. There are a variety of ways\nto customize this procedure to whatever is desired.\n\nAn alternative optimization strategy is to specify, by using the change \nin total energy (from iterations when N and N-1), when to turn\ndamping, level-shifting, and/or DIIS on/off. Start and stop keywords for\neach of these is available as,\n\\begin{verbatim}\n CONVERGENCE [dampon ] \\\n [dampoff ] \\\n [diison ] \\\n [diisoff ] \\\n [levlon ] \\\n [levloff ]\n\\end{verbatim}\n\nSo, for example, damping, DIIS, and/or level-shifting can be turned\non/off as desired.\n\nAnother strategy can be to simply specify how many iterations (cycles) you wish\neach type of procedure to be used. The necessary keywords to control\nthe number of damping cycles (ncydp), the number of DIIS cycles\n(ncyds), and the number of level-shifting cycles (ncysh) are input as,\n\\begin{verbatim}\n CONVERGENCE [ncydp ] \\\n [ncyds ] \\\n [ncysh ]\n\\end{verbatim}\n\nThe amount of damping, level-shifting, time at which level-shifting is\nautomatically imposed, and Fock matrices used in the DIIS\nextrapolation can be modified by the following keywords\n\\begin{verbatim}\n CONVERGENCE [damp ] \\\n [diis [nfock ]] \\\n [lshift ] \\\n [hl_tol ]]\n\\end{verbatim}\n\nDamping is defined to be the percentage of the previous iterations\ndensity mixed with the current iterations density. So, for example \n\\begin{verbatim}\n CONVERGENCE damp 70\n\\end{verbatim}\nwould mix 30\\% of the current iteration density with 70\\% of the\nprevious iteration density.\n\nLevel-Shifting\\footnote {M.F.~Guest and \nV.R.~Saunders, Mol.~Phys.~{\\bf 28}, 819 (1974)} is defined as the\namount of shift applied to the diagonal elements of the unoccupied\nblock of the Fock matrix. The shift is specified by the\nkeyword \\verb+lshift+. For example the directive,\n\\begin{verbatim}\n CONVERGENCE lshift 0.5\n\\end{verbatim}\ncauses the diagonal elements of the Fock matrix\ncorresponding to the virtual orbitals to be shifted by 0.5 a.u.\nBy default, this level-shifting procedure is switched on whenever the\nHOMO-LUMO gap is small. Small is defined by default to be 0.05 au but\ncan be modified by the directive \\verb+hl_tol+. An example of\nchanging the HOMO-LUMO gap tolerance to 0.01 would be,\n\\begin{verbatim}\n CONVERGENCE hl_tol 0.01\n\\end{verbatim}\n\nDirect inversion of the iterative subspace with extrapolation of up to\n10 Fock matrices is a default optimization procedure. For large\nmolecular systems the amount of available memory may preclude the ability to\nstore this number of N**2 arrays in global memory. The user may then\nspecify the number of Fock matrices to be used in the extrapolation\n(must be greater than three (3) to be effective). To set the number of\nFock matrices stored and used in the extrapolation procedure to 3\nwould take the form,\n\\begin{verbatim}\n CONVERGENCE diis 3\n\\end{verbatim}\n\nThe user has the ability to simply turn off any optimization\nprocedures deemed undesirable with the obvious keywords,\n\\begin{verbatim}\n CONVERGENCE [nodamping] [nodiis] [nolevelshifting]\n\\end{verbatim}\n\n\nFor systems where the initial guess is very poor, the user can try the\nmethod described in\n\\footnote{A.~D.~Rabuck and G.~E.~Scuseria, J.~Chem.~Phys {\\bf 110},695\n(1999)}\nthat makes use of {\\bf fractional occupation} of the orbital levels during\nthe initial cycles of the SCF convergence. The input has the following form\n\n\\begin{verbatim}\n CONVERGENCE rabuck [n_rabuck ]]\n\\end{verbatim}\n\nwhere the optional value {\\tt n\\_rabuck} determines the number of SCF\ncycles during which the method will be active. For example, to\nset equal to 30 the number of cycles where the Rabuck method is\nactive, you need to use the following line\n\\begin{verbatim}\n CONVERGENCE rabuck 30\n\\end{verbatim}\n\n\\section{{\\tt CDFT} --- Constrained DFT}\n\\label{cdft}\n\nThis option enables the constrained DFT formalism by Wu and Van Voorhis described \nin the paper: Q. Wu, T. Van Voorhis, Phys. Rev. A {\\bf 72}, 024502 (2005). \n\n\\begin{verbatim}\n CDFT [] (charge||spin ) \\\n [pop (becke||mulliken||lowdin) default lowdin]\n\\end{verbatim}\n\nVariables fatom1 and latom1 define the first and last atom of the group of atoms to which\nthe constaint will be applied. Therefore the atoms in the same group should be placed \ncontinuously in the geometry input. If fatom2 and latom2 are specified, the difference between\ngroup 1 and 2 (i.e. 1-2) is constrained. \n\nThe constraint can be either on the charge or the spin density (\\# of alpha - beta electrons) with\na user specified constaint\\_value. Note: No gradients have been implemented for the spin constaints \ncase. Geometry optimizations can only be performed using the charge constaint.\n\nTo calculate the charge or spin density, the Becke, Mulliken, and Lowdin population schemes can be \nused. The Lowdin scheme is default while the Mulliken scheme is not recommended. If basis sets with \nmany diffuse functions are used, the Becke population scheme is recommended.\n\nMultiple constaints can be defined simultaniously by defining multiple {\\tt cdft} lines in the input. \nThe same population scheme will be used for all constaints and only needs to be specified once. If \nmultiple population options are defined, the last one will be used. When there are convergence\nproblems with multiple constaints, the user is advised to do one constraint first and to use the\nresulting orbitals for the next step of the constained calculations.\n\nIt is best to put \"convergence nolevelshifting\" in the dft directive to avoid issues with gradient \ncalculations and convergence in CDFT. Use orbital swap to get a broken-symmetry solution.\n\nAn input example is given below.\n\n\\begin{verbatim}\ngeometry\nsymmetry\nC 0.0 0.0 0.0\nO 1.2 0.0 0.0\nC 0.0 0.0 2.0\nO 1.2 0.0 2.0\nend\n\nbasis\n* library 6-31G*\nend\n\ndft\n xc b3lyp\n convergence nolevelshifting\n odft\n mult 1\n vectors swap beta 14 15\n cdft 1 2 charge 1.0\nend\ntask dft\n\\end{verbatim}\n\n\\section{{\\tt SMEAR} --- Fractional Occupation of the Molecular Orbitals}\n\\label{smear}\n\nThe {\\tt \\bf SMEAR} keyword is useful in cases with many degenerate states\nnear the HOMO (eg metallic clusters)\n\n\\begin{verbatim}\n SMEAR \n\\end{verbatim}\n\nThis option allows fractional occupation of the molecular orbitals.\nA Gaussian broadening function of exponent {\\tt smear} is used as described in \nthe paper:\nR.W. Warren and B.I. Dunlap, Chem. Phys. Letters {\\bf 262}, 384 (1996).\\\\\nThe user must be aware that an additional energy term is added to the total\nenergy in order to have\nenergies and gradients consistent.\n\n\n\\section{{\\tt GRID} --- Numerical Integration of the XC Potential}\n\\label{grgrid}\n\\begin{verbatim}\n GRID [(xcoarse||coarse||medium||fine||xfine) default medium] \\\n [(gausleg||lebedev ) default lebedev ] \\\n [(becke||erf1||erf2||ssf) default erf1] \\\n [(euler||mura||treutler) default mura] \\\n [rm ] \\\n [nodisk]\n\\end{verbatim}\n\nA numerical integration is necessary for the evaluation of the\nexchange-correlation contribution to the density functional. The\ndefault quadrature used for the numerical integration is an\nEuler-MacLaurin scheme for the radial components (with a modified\nMura-Knowles transformation)\nand a Lebedev\nscheme for the angular components. Within this numerical\nintegration procedure various levels of accuracy have been defined and\nare available to the user. The user can specify the level of accuracy\nwith the keywords; xcoarse, coarse, medium, fine, and xfine. The\ndefault is medium.\n\n\\begin{verbatim}\n GRID [xcoarse||coarse||medium||fine||xfine]\n\\end{verbatim}\n\nOur intent is to have a numerical integration scheme which would give\nus approximately the accuracy defined below regardless of molecular\ncomposition. \n\\begin{center}\n \\begin{tabular}[right]{|c|c|} \\hline\nKeyword & {\\tt Total Energy Target Accuracy} \\\\ \\hline\n{\\tt xcoarse} & $1x10^{-4}$ \\\\ \\hline\n{\\tt coarse} & $1x10^{-5}$ \\\\ \\hline\n{\\tt medium} & $1x10^{-6}$ \\\\ \\hline\n{\\tt fine} & $1x10^{-7}$ \\\\ \\hline\n{\\tt xfine} & $1x10^{-8}$ \\\\ \\hline\n \\end{tabular} \\\\\n\\end{center}\n\nIn order to determine the level of radial and angular quadrature needed\nto give us the target accuracy we computed total DFT energies \nat the LDA level of theory for many\nhomonuclear atomic, diatomic and triatomic systems in rows 1-4 of the\nperiodic table. In each case all bond lengths were set to twice the\nBragg-Slater radius. The total DFT energy of the system was computed\nusing the converged SCF density with atoms having radial shells\nranging from 35-235 (at fixed 48/96 angular quadratures) and angular\nquadratures of 12/24-48/96 (at fixed 235 radial shells). The error of\nthe numerical integration was determined by comparison to a ``best''\nor most accurate calculation in which a grid of 235 radial points 48\ntheta and 96 phi angular points on each atom was used. This\ncorresponds to approximately 1 million points per atom. The following\ntables were empirically determined to give the desired target accuracy\nfor DFT total energies. These tables below show the number of radial and\nangular shells which the DFT module will use for for a given atom\ndepending on the row it is in (in the periodic table) and the desired\naccuracy. Note, differing atom types in a given molecular system will\nmost likely have differing associated numerical grids. The intent is\nto generate the desired energy accuracy (with utter disregard for speed).\n\n%{\\bf Important note to users.} We clearly understand that the default\n%(Euler-MacLaurin/Gauss-Legendre) grids are large and result in slow\n%%construction of the numerical components of the Kohn-Sham equations.\n%%Alternatively, we have provided access to two-dimensional Lebedev\n%%angular quadratures which can be used in many cases to substantially\n%%reduce the number of grid points per atom while keeping good accuracy.\n%%We have not yet had the opportunity to benchmark the Lebedev angular\n%%quadratures to the same extent that we have for the Gauss-Legendre.\n%%We therefore do not have default Lebedev quadratures for specific\n%%target accuracy for all elements of the periodic table. If the user\n%%wants to significantly decrease CPU time to solution it is suggested\n%%that a few prototype benchmark calculations be done using various\n%%Lebedev quadratures (which we describe below) while monitoring the\n%%numerically integrated density and total energies for the molecular\n%%systems of interest. For many examples we have observed speed-ups of\n%%two or more for the same numerical accuracy when using Lebedev rather\n%%than the default Gauss-Legendre quadrature. In addition, we have\n%%observed that with Lebedev angular quadratures a reduction in the\n%%number of radial shells (perhaps by as much as 30\\%) might be possible\n%%while continuing to provide the same level of accuracy.\n%%% g94/Sg-1 grid ssf lebedev gausleg 50 8\n%%% g98/fine grid ssf lebedev gausleg 75 11\n\n\n\\begin{table}[h]\n\\begin{center}\n\\caption{Program default number of radial and angular shells empirically determined for Row 1 atoms\n (Li $\\rightarrow$ F) to reach the desired accuracies.}\n\n\\vspace{.2in}\n\n \\begin{tabular}[right]{|c|c|c|} \\hline\nKeyword & {\\tt Radial} & {\\tt Angular} \\\\ \\hline\n{\\tt xcoarse} & 21 & 194 \\\\ \\hline\n{\\tt coarse} & 35 & 302 \\\\ \\hline\n{\\tt medium} & 49 & 434 \\\\ \\hline\n{\\tt fine} & 70 & 590 \\\\ \\hline\n{\\tt xfine} &100 &1202 \\\\ \\hline\n \\end{tabular} \\\\\n\\end{center}\n\\end{table}\n\n\\begin{table}[h]\n\\begin{center}\n\\caption{Program default number of radial and angular shells empirically determined for Row 2 atoms\n (Na $\\rightarrow$ Cl) to reach the desired accuracies.}\n\n\\vspace{.2in}\n\n \\begin{tabular}[right]{|c|c|c|} \\hline\nKeyword & {\\tt Radial} & {\\tt Angular} \\\\ \\hline\n{\\tt xcoarse} & 42 & 194 \\\\ \\hline\n{\\tt coarse} & 70 & 302 \\\\ \\hline\n{\\tt medium} & 88 & 434 \\\\ \\hline\n{\\tt fine} &123 & 770 \\\\ \\hline\n{\\tt xfine} &125 &1454 \\\\ \\hline\n \\end{tabular} \\\\\n\\end{center}\n\\end{table}\n\n\\begin{table}[h]\n\\begin{center}\n\\caption{Program default number of radial and angular shells empirically determined for Row 3 atoms\n (K $\\rightarrow$ Br) to reach the desired accuracies.}\n\n\\vspace{.2in}\n\n \\begin{tabular}[right]{|c|c|c|} \\hline\nKeyword & {\\tt Radial} & {\\tt Angular} \\\\ \\hline\n{\\tt xcoarse} & 75 & 194 \\\\ \\hline\n{\\tt coarse} & 95 & 302 \\\\ \\hline\n{\\tt medium} &112 & 590 \\\\ \\hline\n{\\tt fine} &130 & 974 \\\\ \\hline\n{\\tt xfine} &160 &1454 \\\\ \\hline\n \\end{tabular} \\\\\n\\end{center}\n\\end{table}\n\n\\begin{table}[h]\n\\begin{center}\n\\caption{Program default number of radial and angular shells empirically determined for Row 4 atoms\n (Rb $\\rightarrow$ I) to reach the desired accuracies.}\n\n\\vspace{.2in}\n\n \\begin{tabular}[right]{|c|c|c|} \\hline\nKeyword & {\\tt Radial} & {\\tt Angular} \\\\ \\hline\n{\\tt xcoarse} & 84 &194 \\\\ \\hline\n{\\tt coarse} &104 &302 \\\\ \\hline\n{\\tt medium} &123 &590 \\\\ \\hline\n{\\tt fine} &141 &974 \\\\ \\hline\n{\\tt xfine} &205 &1454 \\\\ \\hline\n \\end{tabular} \\\\\n\\end{center}\n\\end{table}\n\n\\clearpage\n\n\\subsection{Angular grids}\n\nIn addition to the simple keyword specifying the desired accuracy as\ndescribed above, the user has the option of specifying a custom\nquadrature of this type in which ALL atoms have the same grid\nspecification. This is accomplished by using the \\verb+gausleg+ keyword.\n\n\\paragraph{Gauss-Legendre angular grid}\n\n\\begin{verbatim}\n GRID gausleg \n\\end{verbatim}\n\nIn this type of grid, the number of phi points is twice the number of\ntheta points. So, for example, a specification of,\n\\begin{verbatim}\n GRID gausleg 80 20\n\\end{verbatim}\nwould be interpreted as 80 radial points, 20 theta points, and 40\nphi points per center (or 64000 points per center before pruning).\n\n\\paragraph{Lebedev angular grid}\n\nA second quadrature is the Lebedev\nscheme for the angular components\\footnote{The subroutine \nfor the Lebedev grid was derived from a routine supplied by M.~Caus\\`a\nof the University of Torino and from the grid points supplied by\nD.N.~Laikov from Moscow State University.}. \nWithin this numerical integration procedure various levels \nof accuracy have also been defined and are available to the user. \nThe input for this type of grid takes the form,\n\\begin{verbatim}\n GRID lebedev \n\\end{verbatim}\nIn this context the variable iangquad specifies a certain number of\nangular points as indicated by the table below.\\footnote{\nV.I. Lebedev and D.N. Laikov, Doklady Mathematics {\\bf 366}, 741\n(1999).\n}\n\\begin{table}[htp]\n\\begin{center}\n\\begin{tabular}[right]{|c|rr|} \\hline\n$IANGQUAD$ & $N_{angular}$ & $l$\\\\\n\\hline\n 1& 38& 9 \\\\\n 2& 50& 11 \\\\\n 3& 74 & 13 \\\\\n 4& 86 & 15 \\\\\n 5& 110 & 17 \\\\\n 6& 146 & 19 \\\\\n 7& 170 & 21 \\\\\n 8& 194 & 23 \\\\\n 9& 230 & 25 \\\\\n10& 266& 27 \\\\\n11& 302& 29 \\\\\n12& 350& 31 \\\\\n13& 434& 35 \\\\\n14& 590& 41 \\\\\n15& 770& 47 \\\\\n16& 974& 53 \\\\\n17& 1202& 59 \\\\\n18& 1454& 65 \\\\\n19& 1730& 71 \\\\\n20& 2030& 77 \\\\\n21& 2354& 83 \\\\\n22& 2702& 89 \\\\ \n23& 3074& 95 \\\\\n24& 3470& 101 \\\\\n25& 3890& 107 \\\\\n26& 4334& 113 \\\\\n27& 4802& 119 \\\\\n28& 5294& 125 \\\\\n29& 5810& 131 \\\\\n\\hline\n\\end{tabular}\n\\end{center}\n\\caption{List of Lebedev quadratures}\n\\end{table}\nTherefore the user can specify any number of radial points along with\nthe level of angular quadrature (1-29).\n\nThe user can also specify grid parameters specific for a given atom type: \nparameters that must be supplied are: atom tag and number of radial points.\nAs an example, here is a grid input line for the water molecule\n\\begin{verbatim}\ngrid lebedev 80 11 H 70 8 O 90 11 \n\\end{verbatim}\n\n\n% Delley weights do not work .. need to replace with SSWs after input is\n%changed \n%The user also has the option of choosing one of two types of spatial weights\n%implemented in the numerical integration of the XC terms; Delley and Becke.\n\n\\clearpage\n\\subsection{Partitioning functions}\n\n\\begin{verbatim}\n GRID [(becke||erf1||erf2||ssf) default erf1]\n\\end{verbatim}\n\n\n\\begin{description}\n\\item[\\tt becke] A. D. Becke, J. Chem. Phys. {\\bf 88}, 1053 (1988).\n\\item[\\tt ssf] R.E.Stratmann, G.Scuseria and M.J.Frisch,\nChem. Phys. Lett. {\\bf 257}, 213 (1996).\n\\item[\\tt erf1] modified ssf\n\\item[\\tt erf2] modified ssf\n\\end{description}\n\nErf$n$ partioning functions\n\n\\begin{eqnarray*}\n w_A(r) & = & \\prod_{B\\neq A}\\frac{1}{2} \\left[1 \\ - \\\nerf(\\mu^\\prime_{AB})\\right] \\\\\n \\mu^\\prime_{AB} & = & \\frac{1}{\\alpha} \\ \\frac{\\mu_{AB}}{(1-\\mu_{AB}^2)^n}\\\\\n \\mu_{AB} & = & \\frac{{\\mathbf r}_A - {\\mathbf r}_B}\n{\\left|{\\mathbf r}_A - {\\mathbf r}_B \\right|}\n\\end{eqnarray*}\n\n\n\n\n\\subsection{Radial grids}\n\n\\begin{verbatim}\n GRID [[euler||mura||treutler] default mura]\n\\end{verbatim}\n\n\\begin{description}\n\\item[\\tt euler] Euler-McLaurin quadrature wih the transformation\n devised by\nC.W. Murray, N.C. Handy, and G.L. Laming,\nMol. Phys.{\\bf 78}, 997 (1993).\n \\\\\n\\item[\\tt mura] Modification of the Murray-Handy-Laming scheme by \nM.E.Mura and P.J.Knowles, J Chem Phys {\\bf 104}, 9848\n(1996) (we are not using the scaling factors proposed\nin this paper).\\\\\n\\item[\\tt treutler] Gauss-Chebyshev using the transformation suggested\n by O.Treutler and R.Alrhichs, J.Chem.Phys {\\bf 102}, 346 (1995).\\\\\n\\end{description}\n\n\\subsection{Disk usage for Grid}\n\n\\begin{verbatim}\n NODISK\n\\end{verbatim}\n\nThis keyword turns off storage of grid points and weights on disk.\n\n\n\\section{{\\tt TOLERANCES} --- Screening tolerances}\n\n\\begin{verbatim}\n TOLERANCES [[tight] [tol_rho ] \\\n [accCoul ] \\\n [radius ]]\n\\end{verbatim}\n% [accQrad ] \\\n% [accAOfunc ] \\\n% [accXCfunc ] \\\n% [accCDfunc ] \\\n%\n%{\\bf JEFF: tight needs explanation}\n%\nThe user has the option of controlling screening for the tolerances in\nthe integral evaluations for the DFT module. In most applications,\nthe default values will be adequate for the calculation, but different\nvalues can be specified in the input for the DFT module using the\nkeywords described below.\n\n%The input to define a screening tolerance for evaluation of the AO \n%Gaussian functions is specified with the keyword \\verb+accAOfunc+, as\n%follows,\n%\\begin{verbatim}\n% TOLERANCES accAOfunc \n%\\end{verbatim}\n%A Gaussian Type Function of the Orbital basis set is \n%evaluated at a point $r_i$ if its value it is greater than \n%$exp(-${\\tt accAOfunc}$)$ ;\n%the default value is set to $-ln(\\Delta E)$, where $\\Delta E$ is the desired \n%accuracy on energy.\n%A Gaussian orbital basis (AO) function with exponent $\\zeta$\n%and radial factor $e^{-\\zeta\\cdot r_i^2}$ is \n%evaluated at a point $r_i$ only if \n%$\\zeta\\cdot r_i^2$ is less than the value specified for ${\\tt accAOfunc}$.\n\n%The input to define a screening tolerance for evaluation of the exchange-\n%correlation (XC) Gaussian fitting functions is specified with the\n%keyword \\verb+accXCfunc+, as follows,\n%\\begin{verbatim}\n% TOLERANCES accXCfunc \n%\\end{verbatim}\n%An exchange-correlation (XC) fitting function with exponent $\\zeta$\n%and radial factor $e^{-\\zeta\\cdot r_i^2}$ is \n%evaluated at a point $r_i$ only if \n%$\\zeta\\cdot r_i^2$ is less than the value specified for ${\\tt accXCfunc}$.\n%\n%The input to define a screening tolerance for evaluation of the\n%charge-density (CD) Gaussian fitting functions is specified with the\n%keyword \\verb+accCDfunc+, as follows,\n%\\begin{verbatim}\n% TOLERANCES accCDfunc \n%\\end{verbatim}\n%A charge-density (CD) fitting function with exponent $\\zeta$\n%and radial factor $e^{-\\zeta\\cdot r_i^2}$ is evaluated at a \n%point $r_i$ only if $\\zeta\\cdot r_i^2$ is less than the value \n%specified for ${\\tt accCDfunc}$.\n\nThe input\nparameter {\\tt accCoul} is used to define the tolerance in Schwarz \nscreening for the Coulomb integrals. Only integrals with estimated\nvalues greater than $10^{(-{\\tt accCoul})}$ are evaluated.\n\n\\begin{verbatim}\n TOLERANCES accCoul \n\\end{verbatim}\n\n%The user also has the option of specifying the radial quadrature \n%grid cut-off for the DFT calculation, using the keyword\n%\\verb+accQrad+. The input line for this option is as follows,\n%\\begin{verbatim}\n% TOLERANCES accQrad \n%\\end{verbatim}\n\n%The value entered for \\verb+accQrad+ is the cutoff distance, in bohr, for grid\n%points around a given center or atom. Grid points that lie more than \n%\\verb+accQrad+ bohr from the center or atom are neglected. \n\nScreening away needless computation of the XC functional (on the grid)\ndue to negligible density is also possible with the use of,\n\\begin{verbatim}\n TOLERANCES tol_rho \n\\end{verbatim}\nXC functional computation is bypassed if the corresponding density\nelements are less than \\verb+tol_rho+.\n\nA screening parameter, \\verb+radius+, used in the screening of the\nBecke or Delley spatial weights is also available as,\n\\begin{verbatim}\n TOLERANCES radius \n\\end{verbatim}\nwhere radius is the cutoff value in bohr.\n\nThe tolerances as discussed previously are insured at convergence.\nMore sleazy tolerances are invoked early in the iterative process\nwhich can speed things up a bit. This can also be problematic at\ntimes because it introduces a discontinuity in the convergence\nprocess. To avoid use of initial sleazy tolerances the user can\ninvoke the \\verb+tight+ option:\n\n\\begin{verbatim}\n TOLERANCES tight \n\\end{verbatim}\n\nThis option sets all tolerances to their\ndefault/user specified values at the very first iteration.\n\n\n\\section{{\\tt DIRECT}, {\\tt SEMIDIRECT} and {\\tt NOIO} --- Hardware Resource Control}\n\\begin{verbatim}\n DIRECT||INCORE\n SEMIDIRECT [filesize ]\n [memsize ]\n [filename ]\n NOIO\n\\end{verbatim}\n\n\\sloppy\n\nThe inverted charge-density and exchange-correlation matrices\nfor a DFT calculation are normally written to disk storage. The user\ncan prevent this by specifying the keyword \\verb+noio+ within the\ninput for the DFT directive. The input to exercise this option is\nas follows,\n\\begin{verbatim}\n noio\n\\end{verbatim}\nIf this keyword is encountered, then the two matrices (inverted\ncharge-density and exchange-correlation) are computed ``on-the-fly''\nwhenever needed. \n\nThe \\verb+INCORE+ option is always assumed to be true but can be\noverridden with the option \\verb+DIRECT+ in which case all integrals\nare computed ``on-the-fly''.\n\nThe \\verb+SEMIDIRECT+ option controls caching of integrals. A full \ndescription of this option is described in User Manual~\\ref{sec:max}.\nSome functionality which is only compatible with the \\verb+DIRECT+\noption will not, at present, work when using \\verb+SEMIDIRECT+.\n\n\\fussy\n\n\\section{{\\tt ODFT} and {\\tt MULT} --- Open shell systems}\n\\begin{verbatim}\n ODFT\n MULT \n\\end{verbatim}\n\nBoth {\\sl closed-shell} and {\\sl open-shell} systems can be studied using\nthe DFT module. Specifying the keyword \\verb+MULT+ within the \\verb+DFT+\ndirective allows the user to define the spin multiplicity of the system.\nThe form of the input line is as follows;\n\\begin{verbatim}\n MULT \n\\end{verbatim}\nWhen the keyword \\verb+MULT+ is specified, the user can define the integer\nvariable \\verb+mult+, where \\verb+mult+ is equal to the number of alpha \nelectrons minus beta electrons, plus 1.\n\nThe keyword \\verb+ODFT+ is unnecessary except in the context\nof forcing a singlet system to be computed as an open shell\nsystem (i.e., using a spin-unrestricted wavefunction).\n\n\\section{{\\tt SIC} --- Self-Interaction Correction}\n\n\\begin{verbatim}\nsic [perturbative || oep || oep-loc ]\n\\end{verbatim}\n\nThe Perdew and Zunger (see J. P. Perdew and A. Zunger, Phys. Rev. B 23,\n5048 (1981)) method to remove the self-interaction contained in many\nexchange-correlation functionals has been implemented with the\nOptimized Effective Potential method \n(see R. T. Sharp and G. K. Horton, Phys. Rev. {\\bf 90}, 317 (1953),\nJ. D. Talman and W. F. Shadwick, Phys. Rev. A {\\bf 14}, 36 (1976))\nwithin the Krieger-Li-Iafrate approximation (J. B. Krieger, Y. Li, \nand G. J. Iafrate, Phys. Rev. A {\\bf 45}, 101 (1992); {\\bf 46}, 5453 (1992); \n47, 165 (1993))\nThree variants of these methods are included in NWChem:\n\\begin{itemize}\n\\item{\\tt sic perturbative} This is the default option for the sic\ndirective. After a self-consistent calculation, the Kohn-Sham\norbitals are localized with the Foster-Boys algorithm (see section\n\\ref{orbloc}) and the self-interaction energy is added to the total energy. \nAll exchange-correlation functionals implemented in the NWChem can be\nused with this option.\n\\item{\\tt sic oep} With this option the optimized effective potential is\nbuilt in each step of the self-consistent process. Because the electrostatic\npotential generated for each orbital involves a numerical\nintegration, this method can be expensive.\n\\item{\\tt sic oep-loc} \nThis option is similar to the oep option with the\naddition of localization of the Kohn-Sham orbitals in each step of the \nself-consistent process.\n\\end{itemize}\nWith oep and oep-loc options a {\\bf xfine grid} (see section \\ref{grgrid})\nmust be used in order to avoid numerical noise, furthermore the hybrid \nfunctionals can not be used with these options. More details of the\nimplementation of this method can be found in \nJ. Garza, J. A. Nichols and D. A. Dixon, J. Chem. Phys. 112, 7880 (2000). \nThe components of the sic energy can be printed out using:\n\n\\begin{verbatim}\nprint \"SIC information\"\n\\end{verbatim}\n\n\n\\section{{\\tt MULLIKEN} --- Mulliken analysis}\nMulliken analysis of the charge distribution is invoked by the keyword:\n\\begin{verbatim}\n MULLIKEN\n\\end{verbatim}\nWhen this keyword is encountered, Mulliken analysis of both the input \ndensity as well as the output density will occur.\nFor example, to perform a mulliken analysis and print the\nexplicit population analysis of the basis functions, use\nthe following\n\\begin{verbatim}\ndft\n mulliken\n print \"mulliken ao\"\nend\ntask dft\n\\end{verbatim}\n\n\n\\section{{\\tt BSSE} --- Basis Set Superposition Error}\n\nParticular care is required to compute BSSE by the counter-poise\nmethod for the DFT module. In order to include terms deriving from\nthe numerical grid used in the XC integration, the user must label\nthe ghost atoms not just {\\tt bq}, but {\\tt bq} followed by the given\natomic symbol. For example, the first component needed to compute the\nBSSE for the water dimer, should be written as follows\n\n\\begin{verbatim}\ngeometry h2o autosym units au\n O 0.00000000 0.00000000 0.22143139\n H 1.43042868 0.00000000 -0.88572555\n H -1.43042868 0.00000000 -0.88572555\n bqH 0.71521434 0.00000000 -0.33214708\n bqH -0.71521434 0.00000000 -0.33214708\n bqO 0.00000000 0.00000000 -0.88572555\nend\n\nbasis\n H library aug-cc-pvdz\n O library aug-cc-pvdz\n bqH library H aug-cc-pvdz\n bqO library O aug-cc-pvdz\nend\n\\end{verbatim}\n\nPlease note that the ``ghost'' oxygen atom has been labeled {\\tt bqO},\nand not just {\\tt bq}.\n\n\\section{{\\tt DISP} --- Empirical Long-range Contribution (vdW)}\n\n\\begin{verbatim}\n DISP \n [ vdw ] \\\n [ alpha 0$, up if $r < 0$)---tested for $r > 0$, speculation otherwise;\n \\item $\\Exp $ modifiers are applied to groups rather than individual units, and are rounded toward zero (down if $r > 0$, up if $r < 0$)---tested for $r > 0$, speculation otherwise;\n \\item $\\DLow $ and $\\DHigh $ modifiers are rounded away from zero (up if $r > 0$, down if $r < 0$)---tested for $r < 0$, speculation otherwise;\n \\item $\\Acc $ is not rounded---pure speculation;\n \\item $\\Spl $ is not rounded---pure speculation.\n\\end{itemize}\n\nWhen there is more than one modifier, they stack as follows \\cite{dev-halloween:2018}. If a base attribute $\\A $ is being modified by two modifier pairs, $(x, r)$ and $(y, s)$, then\n\\[\n \\A + \\round{(r + s) \\A } + (x + y)\n\\]\nwill be the effective value of the attribute.\n\nThe governing feature of the entire combat system is:\n\\begin{assumption}\n Units within an army attack sequentially, one at a time. \n\\end{assumption}\n\\begin{assumption}\n Opposing armies attack each other simultaneously: if a unit has survived to a stage when they are supposed to attack, they are guaranteed the opportunity to attack regardless of whether or not they are killed in this stage. \n\\end{assumption}\n\n\\begin{example}\n Two defending units---first with $4$ hit points, second with $6$ hit points---are attacked by a group with $\\DHigh = 5$, $\\DLow = 3$ and $\\Spl = 0$.\n We will illustrate the consequences of changing the order of attack. To that end, consider two scenarios: the attacker deals \\begin{inparaenum}[(i)]\\item high, low, low; and \\item low, low, high \\end{inparaenum}.\n\n In the first case the defender's hit points will be $(4, 6) \\to (0, 6) \\to (0, 3) \\to (0, 0)$.\n\n In the second case the defender's hit points will be $(4, 6) \\to (1, 6) \\to (0, 6) \\to (0, 1)$.\n\\end{example}\n\n\\begin{example}\n Three units, $u_1$, $u_2$, and $u_2$, attack an enemy unit $v$. Let the attacker have $10\\%$ damage bonus; let $v$ have $25$ hit points and damage reduction of $30\\%$.\n \n Suppose first two attackers deal base high damage of $13$ each, and the last attacker deals base low damage of $6$. The inflicted damage from $u_1$ and $u_2$ will then be\n \\[\n 13 + \\round{(0.1 - 0.3) \\cdot 13} = 13 - \\ceil{2.6} = 13 - 3 = 10\n \\]\n each. Similarly, the inflicted damage from $u_3$ will be\n \\[\n 6 - \\ceil{(0.2) \\cdot 6} = 4.\n \\]\n Thus the total damage will be $(10 + 10 + 4) = 24$, and $v$ will survive with $1$ hit point left.\n\n Note that if one dropped the assumption that units attacked sequentially, the inflicted damage would have been\n \\[\n (13 + 13 + 6) - \\ceil{(0.2) \\cdot (13 + 13 + 6)} = 32 - 7 = 25\n \\]\n instead, and $v$ would have died.\n\\end{example}\n\n\\section{To Splash or Not To Splash}\\label{sec:splash}\n\nSplash damage (as opposed to truncated---usual---damage) is the case when overshoot damage is spilled over to the next defending unit.\n%\n\\begin{example}\n Suppose there are no damage modifiers, and $u$ attacks $v$---which has only $20$ hit points left---with $100$ damage. In either case $v$ will be killed. If this was a \\emph{splash damage} attack, the remaining $80$ damage will be inflicted onto the next unit. If this was a \\emph{truncated damage} attack, the remaining $80$ damage will be lost (discarded).\n\\end{example}\n\n\n\nWhile this works nicely when damage modifiers are equal between groups, the moment damage modifiers are no longer homogeneous a big question arises: how does this difference affect overshoot damage?\n\nThe answer to this question is, perhaps, the weakest point of this work: not only is it not documented officially (according to the authors' knowledge), but it has not been tested either (partly because watchtower damage reduction has been removed from the game, and coming up with a conclusive setup seemed too challenging). In short, the following is merely a description of how the authors chose to implement it, and may have little to no relevance to the game.\n\nSuppose a unit $u$ attacks group $G$ followed by group $H$. Let $(\\underline{d}_G, \\overline{d}_G)$ and $(\\underline{d}_H, \\overline{d}_H)$ denote the effective (after all bonuses have been applied) damage of $u$ vs.\\ $G$ and $H$, respectively.\nDenote the damage ratios with\n\\[\n \\underline{r} = \\frac{\\underline{d}_H}{\\underline{d}_G}\n \\qquad \\text{and} \\qquad\n \\overline{r} = \\frac{\\overline{d}_H}{\\overline{d}_G}.\n\\]\nLet $\\o $ be the overshoot damage when $G$ is killed. If $G$ was killed with a low damage splash hit, then the damage spilled onto $H$ will be $\\floor{\\underline{r} \\, \\cdot \\o }$. If the damage was high, the corresponding value will be $\\floor{\\overline{r} \\, \\cdot \\o }$ instead.\n\n\n\\section{Special Abilities and Battle Structure}\nIn this section we briefly discuss battle or unit characteristics, modifiers, and abilities, that affect the normal course of the battle.\n\nAll modifiers to $\\He $, $\\Exp $, $\\DLow $, and $\\DHigh $ are stored separately from the base values. Effective values for $\\He $ are calculated before the battle begins. Effective values for $\\DLow $ and $\\DHigh $ are calculated prior to each combat round.\nModifiers to $\\Acc $ and $\\Spl $, on the other hand, are applied before the battle directly to the base value which is then clipped to the interval $[0, 1]$.\n\nBefore the battle starts, there are two stages:\n\\begin{enumerate}[(i)]\n \\item Pre-battle bonus stage: each army's bonuses are applied.\n \\item Pre-battle penalty stage: each army's penalties are applied.\n\\end{enumerate}\nThis ordering ensures, for example, that if one army has explosive ammunition (granting friendly ranged units \\emph{attack weakest target} ability) and the other has intercept (stripping enemy units of \\emph{attack weakest target} ability), intercept will take precedence, and all of the units in the first army will \\emph{not} have \\emph{attack weakest target}.\n\n\n\\section{Combat Sequence}\n\nIn this section let $\\He ^*$, $\\DLow ^*$, $\\DHigh ^*$, $\\Acc ^*$, and $\\Spl ^*$ denote the modified attributes (base values after the modifiers have been applied).\n\nWhile the base damage dealt by any unit is independent of any other unit, the effective damage is not. \nHowever, if the defending unit has $h$ hit points, it will take at least $k = \\ceil{h / \\DHigh ^*}$ units to eliminate it, implying that the first $k$ attacks \\emph{will} be independent.\n%\nHaving said that, the course of attack is outlined in the following algorithm.\n\\begin{algorithm}\n Consider a group $G = (u_1, u_2, \\cdots , u_n)$ attacking an army $\\cA = (v_1, v_2, \\cdots , v_m)$.\n %\n Set $i = 1$ and $j = 1$, the (one-based) index of the attacking and defending units, respectively. Let $h = \\He ^* (v_1)$ be the health of the first defending unit.\n %\n \\begin{enumerate}\n \\item \\label{step:first_conservative} Let $\\DHigh _j ^*$ and $\\DLow _j ^*$ be the effective high and low damage against the current defending unit, and let $k = \\ceil{h / \\DHigh _j ^*}$ be the least number of attacking units required to kill the defender.\n\n \\item If $k$ is greater than $(n - i + 1)$---the remaining units in the attacking group---update $k \\overwr (n - i + 1)$.\n\n \\item Generate $X \\sim \\mathrm{Bin} \\left(k, \\Acc ^* \\right)$, the number of units dealing high damage, and let $d = \\DHigh _j ^* \\cdot \\, X + \\DLow _j ^* \\cdot \\, (k - X)$.\n\n \\item Update $i \\overwr i + k$ (point to the next attacking unit).\n\n \\item Update $(h, d) \\overwr (h - d, d - h)$ (damage the current defending unit, and store potential overshoot damage).\n\n \\item If $h < 0$ (the current defending unit has been killed and there is still leftover damage), generate $Y \\sim \\mathrm{Bin} \\left(1, \\Spl _u \\right)$, the chance of splash damage (note that it is not necessary if $h = 0$). Otherwise set $Y = 0$.\n \n \\item If $Y = 0$ (no splash), update $d \\overwr 0$ (no overshoot damage).\n\n \\item While $h \\leq 0$:\n \\begin{enumerate}\n \\item update $j \\overwr j + 1$ (proceed to the next defending unit);\n \\item if $j = m + 1$, terminate: the entire army $\\cA $ has been eliminated;\n \\item let $r$ denote the splash ratio factor between $v_j$ and $v_{j - 1}$ as explained in section \\ref{sec:splash};\n \\item update $h \\overwr \\He ^* (v_j)$ and $d \\overwr \\floor{r \\cdot d}$;\n \\item update $(h, d) \\overwr (h - d, d - h)$ (damage the next defending unit, and store potential overshoot damage).\n \\end{enumerate}\n\n \\item \\label{step:last_conservative} If $i = n + 1$, terminate: the entire group $G$ has attacked, and exactly $(j - 1)$ units from $\\cA $ have been killed; the $j$-th unit in $\\cA $ has only $h$ hit points left.\n\n \\item Otherwise repeat steps \\ref{step:first_conservative}--\\ref{step:last_conservative}.\n \\end{enumerate}\n\\end{algorithm}\n\n\n\\begin{thebibliography}{9}\n \\bibitem{dev-halloween:2018} Official forums. \\textit{[Dev Diary] Halloween 2018}, {https://forum.thesettlersonline.net/threads/25261\\#post287808}.\n\\end{thebibliography}\n\n\n\\end{document}\n\n\n", "meta": {"hexsha": "1568707fc471d003c5ef766d1bd7c83c7256d559", "size": 14299, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "documentation/settlers_online.tex", "max_stars_repo_name": "ropufu/settlers_online", "max_stars_repo_head_hexsha": "a6e90567c87734375d8f099130238901f0860ce5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-04-09T12:10:44.000Z", "max_stars_repo_stars_event_max_datetime": "2018-04-09T12:10:44.000Z", "max_issues_repo_path": "documentation/settlers_online.tex", "max_issues_repo_name": "ropufu/settlers_online", "max_issues_repo_head_hexsha": "a6e90567c87734375d8f099130238901f0860ce5", "max_issues_repo_licenses": ["MIT"], "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/settlers_online.tex", "max_forks_repo_name": "ropufu/settlers_online", "max_forks_repo_head_hexsha": "a6e90567c87734375d8f099130238901f0860ce5", "max_forks_repo_licenses": ["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.3688212928, "max_line_length": 464, "alphanum_fraction": 0.6924959787, "num_tokens": 4165, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.36658973632215985, "lm_q1q2_score": 0.19330882526403356}}
{"text": "%\\documentclass[aps,showpacs,prb,floatfix,twocolumn]{revtex4}\n\\documentclass[aps,prb,floatfix,epsfig,singlecolumn,showpacs,preprintnumbers]{revtex4}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\usepackage{amsmath,amssymb,graphicx,bm,epsfig}\n\\usepackage{color}\n\\usepackage{braket}\n\n\\newcommand{\\eps}{\\epsilon}\n\\newcommand{\\vR}{{\\mathbf{R}}}\n\\newcommand{\\vF}{{\\mathbf{F}}}\n\\renewcommand{\\vr}{{\\mathbf{r}}}\n\\newcommand{\\hr}{{\\hat{\\textbf{r}}}}\n\\newcommand{\\vk}{{\\mathbf{k}}}\n\\newcommand{\\vdelta}{{\\mathbf{\\delta}}}\n\\newcommand{\\vK}{{\\mathbf{K}}}\n\\newcommand{\\vG}{{\\mathbf{G}}}\n\\newcommand{\\vq}{{\\mathbf{q}}}\n\\newcommand{\\vQ}{{\\mathbf{Q}}}\n\\newcommand{\\vPhi}{{\\mathbf{\\Phi}}}\n\\newcommand{\\vS}{{\\mathbf{S}}}\n\\newcommand{\\cG}{{\\cal G}}\n\\newcommand{\\cR}{{\\cal R}}\n\\newcommand{\\cF}{{\\cal F}}\n\\newcommand{\\cT}{{\\cal T}}\n\\newcommand{\\cO}{{\\cal O}}\n\\newcommand{\\cH}{{\\cal H}}\n\\newcommand{\\cJ}{{\\cal J}}\n\\newcommand{\\cD}{{\\cal D}}\n\\newcommand{\\cU}{{\\cal U}}\n\\newcommand{\\cL}{{\\cal L}}\n\\newcommand{\\Tr}{\\mathrm{Tr}}\n\\renewcommand{\\a}{\\alpha}\n\\renewcommand{\\b}{\\beta}\n\\newcommand{\\g}{\\gamma}\n\\renewcommand{\\d}{\\delta}\n\\newcommand{\\npsi}{\\underline{\\psi}}\n\\renewcommand{\\Im}{\\textrm{Im}}\n\\renewcommand{\\Re}{\\textrm{Re}}\n\\newcommand{\\cA}{{\\cal A}}\n\\newcommand{\\vcA}{\\vec{\\cal A}}\n\\newcommand{\\vcB}{\\vec{\\cal B}}\n\\newcommand{\\vcC}{\\vec{\\cal C}}\n\\newcommand{\\cB}{{\\cal B}}\n\\newcommand{\\cC}{{\\cal C}}\n\\usepackage{hyperref}\n\n\\begin{document}\n\n\\title{Some notes on the Free Energy in DFT+DMFT}\n\\author{Kristjan Haule}\n\\affiliation{Department of Physics, Rutgers University, Piscataway, NJ 08854, USA}\n\\date{\\today}\n\n%\\begin{abstract}\n%\\end{abstract}\n\\pacs{71.27.+a,71.30.+h}\n\\date{\\today}\n\\maketitle\n\n\\section{How is Free energy implemented?}\n\nThe details of the algorithm are published in \n\\href{http://journals.aps.org/prl/abstract/10.1103/PhysRevLett.115.256402}{Phys. Rev. Lett. 115, 256402 (2015)}. \nHere we just mention some implementation details, which are not\ncompletely detailed there.\n\nThe total energy is printed in column six of \\textit{info.iterate}. We\ncompute it by\n\\begin{eqnarray}\nE_6=E^H[\\rho]+E^{XC}[\\rho]+E_{nuc}-\\Tr((V_H+V_{XC})\\rho)+\n\\textcolor{red}{\\Tr(\\varepsilon^{DFT}_\\vk \\rho)}+\n\\textcolor{blue}{E_{imp}^{pot}-\\Phi^{DC}[n_{imp}]}\n\\end{eqnarray}\nThe blue terms are computed from the impurity quantities, and the\nblack and red\nare computed from the lattice quantities. The black are evaluated in \\textit{lapw0} and \\textit{lapwc}. The red\nterms are evaluated in \\textit{dmft2}.\n\nThe free energy is printed in column seven and eight of\n\\textit{info.iterate}. The seventh column is computed by\n\\begin{eqnarray}\nF_7=E^H[\\rho]+E^{XC}[\\rho]+E_{nuc}-\\Tr((V_H+V_{XC})\\rho)\n+\\textcolor{red}{\\Tr\\log( G)+\\mu N-\\Tr\\log(G_{loc})+\\Tr((\\varepsilon_{imp}+V_{DC})n_{loc})}\n\\\\\n+\\textcolor{blue}{E_{imp}^{pot}\n+\\Tr\\left((\\Delta-\\omega_n\\frac{d\\Delta}{d\\omega_n})G_{imp}\\right)\n-\\Phi^{DC}[n_{imp}]}\n-\\textcolor{green}{T S_{imp}}\n\\end{eqnarray}\nThe blue terms are computed from the impurity quantities, and the\nblack and red\nare computed from the lattice quantities. The black are evaluated in \\textit{lapw0} and \\textit{lapwc}. The red\nterms are evaluated in \\textit{dmft2}. The green term is missing in\n\\textit{info.iterate} and needs to be computed at postprocessing as\nexplained in the above PRL.\n\nThe eight column is computed by\n\\begin{eqnarray}\nF_8=E^H[\\rho]+E^{XC}[\\rho]+E_{nuc}-\\Tr((V_H+V_{XC})\\rho)\n+\\textcolor{red}{\\Tr\\log( G)+\\mu N-\\Tr((\\Sigma-V_{DC})G_{loc})}\n\\\\\n+\\textcolor{blue}{E_{imp}^{pot}\n+\\Tr\\left((\\Delta-\\omega_n\\frac{d\\Delta}{d\\omega_n})G_{imp}\\right)\n-\\Tr\\log(G_{imp})+\\Tr(\\varepsilon_{imp}n_{imp})+\\Tr(\\Sigma_{imp}G_{imp})\n-\\Phi^{DC}[n_{imp}]}\n-\\textcolor{green}{T S_{imp}}\n\\end{eqnarray}\n\nThe difference between the seventh and eight column is then\n\\begin{eqnarray}\nF_8-F_7 = \n\\textcolor{red}{\\Tr\\log(G_{loc})-\\Tr(\\Sigma G_{loc})-\\Tr(\\varepsilon_{imp}n_{loc})}\n-\\textcolor{blue}{\\Tr\\log(G_{imp})+\\Tr(\\Sigma G_{imp})+\\Tr(\\varepsilon_{imp}n_{imp})}\n\\end{eqnarray}\n\n\\end{document}", "meta": {"hexsha": "329f1f3508c1e0173ee51752506427182055c436", "size": 4069, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "src/doc/FreeEnergy2.tex", "max_stars_repo_name": "dmft-wien2k/dmft-wien2k-v2", "max_stars_repo_head_hexsha": "83481be27e8a9ff14b9635d6cc1cd9d96f053487", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-05-13T13:04:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-18T10:08:09.000Z", "max_issues_repo_path": "src/doc/FreeEnergy2.tex", "max_issues_repo_name": "dmft-wien2k/dmft-wien2k-v2", "max_issues_repo_head_hexsha": "83481be27e8a9ff14b9635d6cc1cd9d96f053487", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2016-07-12T21:37:53.000Z", "max_issues_repo_issues_event_max_datetime": "2016-07-12T21:42:01.000Z", "max_forks_repo_path": "src/doc/FreeEnergy2.tex", "max_forks_repo_name": "dmft-wien2k/dmft-wien2k", "max_forks_repo_head_hexsha": "83481be27e8a9ff14b9635d6cc1cd9d96f053487", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2016-07-22T15:46:56.000Z", "max_forks_repo_forks_event_max_datetime": "2016-08-02T15:05:12.000Z", "avg_line_length": 35.0775862069, "max_line_length": 124, "alphanum_fraction": 0.6763332514, "num_tokens": 1489, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166195971441, "lm_q2_score": 0.3775406687981454, "lm_q1q2_score": 0.19319383479783195}}
{"text": "\n\\section{Tendermint consensus algorithm} \\label{sec:tendermint}\n\n\\newcommand\\Disseminate{\\textbf{Disseminate}}\n\n\\newcommand\\Proposal{\\mathsf{PROPOSAL}}\n\\newcommand\\ProposalPart{\\mathsf{PROPOSAL\\mbox{-}PART}}\n\\newcommand\\PrePrepare{\\mathsf{INIT}} \\newcommand\\Prevote{\\mathsf{PREVOTE}}\n\\newcommand\\Precommit{\\mathsf{PRECOMMIT}}\n\\newcommand\\Decision{\\mathsf{DECISION}}\n\n\\newcommand\\ViewChange{\\mathsf{VC}}\n\\newcommand\\ViewChangeAck{\\mathsf{VC\\mbox{-}ACK}}\n\\newcommand\\NewPrePrepare{\\mathsf{VC\\mbox{-}INIT}}\n\\newcommand\\coord{\\mathsf{proposer}}\n\n\\newcommand\\newHeight{newHeight} \\newcommand\\newRound{newRound}\n\\newcommand\\nil{nil} \\newcommand\\id{id} \\newcommand{\\propose}{propose}\n\\newcommand\\prevote{prevote} \\newcommand\\prevoteWait{prevoteWait}\n\\newcommand\\precommit{precommit} \\newcommand\\precommitWait{precommitWait}\n\\newcommand\\commit{commit}\n\n\\newcommand\\timeoutPropose{timeoutPropose}\n\\newcommand\\timeoutPrevote{timeoutPrevote}\n\\newcommand\\timeoutPrecommit{timeoutPrecommit}\n\\newcommand\\proofOfLocking{proof\\mbox{-}of\\mbox{-}locking}\n\n\\begin{algorithm}[htb!] \\def\\baselinestretch{1} \\scriptsize\\raggedright\n\t\\begin{algorithmic}[1] \n\t\t\\SHORTSPACE \n\t\t\\INIT{} \n\t\t\\STATE $h_p := 0$ \n\t\t\\COMMENT{current height, or consensus instance we are currently executing} \n\t\t\\STATE $round_p := 0$ \\COMMENT{current round number}\n\t\t\\STATE $step_p \\in \\set{\\propose, \\prevote, \\precommit}$\n\t\t\\STATE $decision_p[] := nil$ \n\t\t\\STATE $lockedValue_p := nil$ \n\t\t\\STATE $lockedRound_p := -1$ \n\t\t\\STATE $validValue_p := nil$ \n\t\t\\STATE $validRound_p := -1$ \n\t\t\\ENDINIT \n\t\t\\SHORTSPACE \n\t\t\\STATE \\textbf{upon} start \\textbf{do} $StartRound(0)$ \n\t\t\\SHORTSPACE \n\t\t\\FUNCTION{$StartRound(round)$} \\label{line:tab:startRound} \n\t\t\\STATE $round_p \\assign round$ \n\t\t\\STATE $step_p \\assign \\propose$ \n\t\t\\IF{$\\coord(h_p, round_p) = p$}\n\t\t\\IF{$validValue_p \\neq \\nil$} \\label{line:tab:isThereLockedValue}\n\t\t\\STATE $proposal \\assign validValue_p$ \\ELSE \\STATE $proposal \\assign\n\t\tgetValue()$ \n\t\t\\label{line:tab:getValidValue} \n\t\t\\ENDIF \t \n\t\t\\STATE \\Broadcast\\ $\\li{\\Proposal,h_p, round_p, proposal, validRound_p}$\n\t\t\\label{line:tab:send-proposal} \n\t\t\\ELSE \n\t\t\\STATE \\textbf{schedule} $OnTimeoutPropose(h_p,\n\t\tround_p)$ to be executed \\textbf{after} $\\timeoutPropose(round_p)$ \n\t\t\\ENDIF\n\t\t\\ENDFUNCTION\n\t\t\n\t\t\\SPACE \n\t\t\\UPON{$\\li{\\Proposal,h_p,round_p, v, -1}$ \\From\\ $\\coord(h_p,round_p)$\n\t\t\t\\With\\ $step_p = \\propose$} \\label{line:tab:recvProposal}\n\t\t\t\\IF{$valid(v) \\wedge (lockedRound_p = -1 \\vee lockedValue_p = v$)}\n\t\t\t\\label{line:tab:accept-proposal-2} \n\t\t\t\t\\STATE \\Broadcast \\ $\\li{\\Prevote,h_p,round_p,id(v)}$ \n\t\t\t\t\\label{line:tab:prevote-proposal}\t\n\t\t\t\\ELSE\n\t\t\t\\label{line:tab:acceptProposal1}\t\t\n\t\t\t\t\\STATE \\Broadcast \\ $\\li{\\Prevote,h_p,round_p,\\nil}$ \n\t\t\t\t\\label{line:tab:prevote-nil}\t\n\t\t\t\\ENDIF\n\t\t\t\t\\STATE $step_p \\assign \\prevote$ \\label{line:tab:setStateToPrevote1} \n\t\t\\ENDUPON\n\t\t\n\t\t\\SPACE \n\t\t\\UPON{$\\li{\\Proposal,h_p,round_p, v, vr}$ \\From\\ $\\coord(h_p,round_p)$\n\t\t\t\\textbf{AND} $2f+1$ $\\li{\\Prevote,h_p, vr,id(v)}$ \\With\\ $step_p = \\propose \\wedge (vr \\ge 0 \\wedge vr < round_p)$}\n\t\t\\label{line:tab:acceptProposal} \n\t\t\\IF{$valid(v) \\wedge (lockedRound_p \\le vr\n\t\t\t\\vee lockedValue_p = v)$} \\label{line:tab:cond-prevote-higher-proposal}\t\n\t\t\t\\STATE \\Broadcast \\ $\\li{\\Prevote,h_p,round_p,id(v)}$\n\t\t\t\\label{line:tab:prevote-higher-proposal}\t\t \n\t\t\\ELSE\n\t\t\t\\label{line:tab:acceptProposal2}\t\t\n\t\t\t\\STATE \\Broadcast \\ $\\li{\\Prevote,h_p,round_p,\\nil}$ \n\t\t\t\\label{line:tab:prevote-nil2}\t\n\t\t\\ENDIF\n\t\t\\STATE $step_p \\assign \\prevote$ \\label{line:tab:setStateToPrevote3} \t \n\t\t\\ENDUPON\n\t\t\n\t\t\\SPACE \n\t\t\\UPON{$2f+1$ $\\li{\\Prevote,h_p, round_p,*}$ \\With\\ $step_p = \\prevote$ for the first time}\n\t\t\\label{line:tab:recvAny2/3Prevote} \n\t\t\\STATE \\textbf{schedule} $OnTimeoutPrevote(h_p, round_p)$ to be executed \\textbf{after} $\\timeoutPrevote(round_p)$ \\label{line:tab:timeoutPrevote} \n\t\t\\ENDUPON\n\t\t\n\t\t\\SPACE \n\t\t\\UPON{$\\li{\\Proposal,h_p,round_p, v, *}$ \\From\\ $\\coord(h_p,round_p)$\n\t\t\t\\textbf{AND} $2f+1$ $\\li{\\Prevote,h_p, round_p,id(v)}$ \\With\\ $valid(v) \\wedge step_p \\ge \\prevote$ for the first time}\n\t\t\\label{line:tab:recvPrevote} \n\t\t\\IF{$step_p = \\prevote$}\t\n\t\t\t\\STATE $lockedValue_p \\assign v$ \\label{line:tab:setLockedValue} \n\t\t\t\\STATE $lockedRound_p \\assign round_p$ \\label{line:tab:setLockedRound} \n\t\t\t\\STATE \\Broadcast \\ $\\li{\\Precommit,h_p,round_p,id(v))}$ \n\t\t\t\\label{line:tab:precommit-v}\t\n\t\t\t\\STATE $step_p \\assign \\precommit$ \\label{line:tab:setStateToCommit} \n\t\t\\ENDIF \n\t\t\\STATE $validValue_p \\assign v$ \\label{line:tab:setValidRound} \n\t\t\\STATE $validRound_p \\assign round_p$ \\label{line:tab:setValidValue} \n\t\t\\ENDUPON\n\t\t\n\t\t\\SHORTSPACE \n\t\t\\UPON{$2f+1$ $\\li{\\Prevote,h_p,round_p, \\nil}$ \n\t\t\t\\With\\ $step_p = \\prevote$} \n\t\t\t\\STATE \\Broadcast \\ $\\li{\\Precommit,h_p,round_p, \\nil}$\n\t\t\t\\label{line:tab:precommit-v-1} \n\t\t\t\\STATE $step_p \\assign \\precommit$ \n\t\t\\ENDUPON\n\t\t\n\t\t\\SPACE \n\t\t\\UPON{$2f+1$ $\\li{\\Precommit,h_p,round_p,*}$ for the first time}\n\t\t\\label{line:tab:startTimeoutPrecommit} \n\t\t\t\\STATE \\textbf{schedule} $OnTimeoutPrecommit(h_p, round_p)$ to be executed \\textbf{after} $\\timeoutPrecommit(round_p)$ \n\t\t\t \n\t\t\\ENDUPON \n\t\t\n\t\t\\SPACE \n\t\t\\UPON{$\\li{\\Proposal,h_p,r, v, *}$ \\From\\ $\\coord(h_p,r)$ \\textbf{AND}\n\t\t\t$2f+1$ $\\li{\\Precommit,h_p,r,id(v)}$ \\With\\ $decision_p[h_p] = \\nil$}\n\t\t\\label{line:tab:onDecideRule} \n\t\t\t\\IF{$valid(v)$} \\label{line:tab:validDecisionValue} \n\t\t\t\t\\STATE $decision_p[h_p] = v$ \\label{line:tab:decide} \n\t\t\t\t\\STATE$h_p \\assign h_p + 1$ \\label{line:tab:increaseHeight} \n\t\t\t\t\\STATE reset $lockedRound_p$, $lockedValue_p$, $validRound_p$ and $validValue_p$ to initial values \n\t\t\t\tand empty message log \n\t\t\t\t\\STATE $StartRound(0)$ \t\n\t\t\t\\ENDIF \n\t\t\\ENDUPON\n\t\t\n\t\t\\SHORTSPACE \n\t\t\\UPON{$f+1$ $\\li{*,h_p,round, *, *}$ \\textbf{with} $round > round_p$} \n\t\t\\label{line:tab:skipRounds} \n\t\t\t\\STATE $StartRound(round)$ \\label{line:tab:nextRound2} \n\t\t\\ENDUPON\n\t\t\n\t\t\\SHORTSPACE \n\t\t\\FUNCTION{$OnTimeoutPropose(height,round)$} \\label{line:tab:onTimeoutPropose} \n\t\t\\IF{$height = h_p \\wedge round = round_p \\wedge step_p = \\propose$} \n\t\t\t\\STATE \\Broadcast \\ $\\li{\\Prevote,h_p,round_p, \\nil}$ \n\t\t \t\\label{line:tab:prevote-nil-on-timeout}\t\n\t\t \t\\STATE $step_p \\assign \\prevote$ \n\t\t \\ENDIF\t\n\t\t \\ENDFUNCTION\n\t\t\n\t\t\\SHORTSPACE \n\t\t\\FUNCTION{$OnTimeoutPrevote(height,round)$} \\label{line:tab:onTimeoutPrevote} \n\t\t\\IF{$height = h_p \\wedge round = round_p \\wedge step_p = \\prevote$} \n\t\t\t\\STATE \\Broadcast \\ $\\li{\\Precommit,h_p,round_p,\\nil}$ \n\t\t\t\\label{line:tab:precommit-nil-onTimeout}\n\t\t\t\\STATE $step_p \\assign \\precommit$ \n\t\t\\ENDIF\t\n\t\t\\ENDFUNCTION\n\t\t\n\t\t\\SHORTSPACE \n\t\t\\FUNCTION{$OnTimeoutPrecommit(height,round)$} \\label{line:tab:onTimeoutPrecommit} \n\t\t\\IF{$height = h_p \\wedge round = round_p$}\n\t\t\t\\STATE $StartRound(round_p + 1)$ \\label{line:tab:nextRound} \n\t\t\\ENDIF\n\t\t\\ENDFUNCTION\t\n\t\\end{algorithmic} \\caption{Tendermint consensus algorithm}\n\t\\label{alg:tendermint} \n\\end{algorithm}\n\nIn this section we present the Tendermint Byzantine fault-tolerant consensus\nalgorithm. The algorithm is specified by the pseudo-code shown in\nAlgorithm~\\ref{alg:tendermint}. We present the algorithm as a set of \\emph{upon\nrules} that are executed atomically\\footnote{In case several rules are active\nat the same time, the first rule to be executed is picked randomly. The\ncorrectness of the algorithm does not depend on the order in which rules are\nexecuted.}. We assume that processes exchange protocol messages using a gossip\nprotocol and that both sent and received messages are stored in a local message\nlog for every process. An upon rule is triggered once the message log contains\nmessages such that the corresponding condition evaluates to $\\tt{true}$. The\ncondition that assumes reception of $X$ messages of a particular type and\ncontent denotes reception of messages whose senders have aggregate voting power at\nleast equal to $X$. For example, the condition $2f+1$ $\\li{\\Precommit,h_p,r,id(v)}$, \nevaluates to true upon reception of $\\Precommit$ messages for height $h_p$, \na round $r$ and with value equal to $id(v)$ whose senders have aggregate voting \npower at least equal to $2f+1$. Some of the rules ends with \"for the first time\" constraint \nto denote that it is triggered only the first time a corresponding condition evaluates \nto $\\tt{true}$. This is because those rules do not always change the state of algorithm \nvariables so without this constraint, the algorithm could keep \nexecuting those rules forever. The variables with index $p$ are process local state\nvariables, while variables without index $p$ are value placeholders. The sign\n$*$ denotes any value. \n\nWe denote with $n$ the total voting power of processes in the system, and we\nassume that the total voting power of faulty processes in the system is bounded\nwith a system parameter $f$. The algorithm assumes that $n > 3f$, i.e., it\nrequires that the total voting power of faulty processes is smaller than one\nthird of the total voting power. For simplicity we present the algorithm for\nthe case $n = 3f + 1$.\n\nThe algorithm proceeds in rounds, where each round has a dedicated\n\\emph{proposer}. The mapping of rounds to proposers is known to all processes\nand is given as a function $\\coord(h, round)$, returning the proposer for\nthe round $round$ in the consensus instance $h$. We\nassume that the proposer selection function is weighted round-robin, where\nprocesses are rotated proportional to their voting power\\footnote{A validator\nwith more voting power is selected more frequently, proportional to its power.\nMore precisely, during a sequence of rounds of size $n$, every process is\nproposer in a number of rounds equal to its voting power.}. \nThe internal protocol state transitions are triggered by message reception and \nby expiration of timeouts. There are three timeouts in Algorithm \\ref{alg:tendermint}:\n$\\timeoutPropose$, $\\timeoutPrevote$ and $\\timeoutPrecommit$.\nThe timeouts prevent the algorithm from blocking and\nwaiting forever for some condition to be true, ensure that processes continuously \ntransition between rounds, and guarantee that eventually (after GST) communication \nbetween correct processes is timely and reliable so they can decide. \nThe last role is achieved by increasing the timeouts with every new round $r$, \ni.e, $timeoutX(r) = initTimeoutX + r*timeoutDelta$; \nthey are reset for every new height (consensus\ninstance). \n\nProcesses exchange the following messages in Tendermint: $\\Proposal$,\n$\\Prevote$ and $\\Precommit$. The $\\Proposal$ message is used by the proposer of\nthe current round to suggest a potential decision value, while $\\Prevote$ and\n$\\Precommit$ are votes for a proposed value. According to the classification of\nconsensus algorithms from \\cite{RMS10:dsn}, Tendermint, like PBFT\n\\cite{CL02:tcs} and DLS \\cite{DLS88:jacm}, belongs to class 3, so it requires\ntwo voting steps (three communication exchanges in total) to decide a value.\nThe Tendermint consensus algorithm is designed for the blockchain context where\nthe value to decide is a block of transactions (ie. it is potentially quite\nlarge, consisting of many transactions). Therefore, in the Algorithm\n\\ref{alg:tendermint} (similar as in \\cite{CL02:tcs}) we are explicit about\nsending a value (block of transactions) and a small, constant size value id (a\nunique value identifier, normally a hash of the value, i.e., if $\\id(v) =\n\\id(v')$, then $v=v'$). The $\\Proposal$ message is the only one carrying the\nvalue; $\\Prevote$ and $\\Precommit$ messages carry the value id. A correct\nprocess decides on a value $v$ in Tendermint upon receiving the $\\Proposal$ for\n$v$ and $2f+1$ voting-power equivalent $\\Precommit$ messages for $\\id(v)$ in\nsome round $r$. In order to send $\\Precommit$ message for $v$ in a round $r$, a\ncorrect process waits to receive the $\\Proposal$ and $2f+1$ of the\ncorresponding $\\Prevote$ messages in the round $r$. Otherwise, \nit sends $\\Precommit$ message with a special $\\nil$ value. \nThis ensures that correct processes can $\\Precommit$ only a \nsingle value (or $\\nil$) in a round. As\nproposers may be faulty, the proposed value is treated by correct processes as\na suggestion (it is not blindly accepted), and a correct process tells others\nif it accepted the $\\Proposal$ for value $v$ by sending $\\Prevote$ message for\n$\\id(v)$; otherwise it sends $\\Prevote$ message with the special $\\nil$ value. \n\nEvery process maintains the following variables in the Algorithm\n\\ref{alg:tendermint}: $step$, $lockedValue$, $lockedRound$, $validValue$ and\n$validRound$. The $step$ denotes the current state of the internal Tendermint\nstate machine, i.e., it reflects the stage of the algorithm execution in the\ncurrent round. The $lockedValue$ stores the most recent value (with respect to\na round number) for which a $\\Precommit$ message has been sent. The\n$lockedRound$ is the last round in which the process sent a $\\Precommit$\nmessage that is not $\\nil$. We also say that a correct process locks a value\n$v$ in a round $r$ by setting $lockedValue = v$ and $lockedRound = r$ before\nsending $\\Precommit$ message for $\\id(v)$. As a correct process can decide a\nvalue $v$ only if $2f+1$ $\\Precommit$ messages for $\\id(v)$ are received, this\nimplies that a possible decision value is a value that is locked by at least\n$f+1$ voting power equivalent of correct processes. Therefore, any value $v$\nfor which $\\Proposal$ and $2f+1$ of the corresponding $\\Prevote$ messages are\nreceived in some round $r$ is a \\emph{possible decision} value. The role of the\n$validValue$ variable is to store the most recent possible decision value; the\n$validRound$ is the last round in which $validValue$ is updated. Apart from\nthose variables, a process also stores the current consensus instance ($h_p$,\ncalled \\emph{height} in Tendermint), and the current round number ($round_p$)\nand attaches them to every message. Finally, a process also stores an array of\ndecisions, $decision_p$ (Tendermint assumes a sequence of consensus instances,\none for each height).\n\nEvery round starts by a proposer suggesting a value with the $\\Proposal$\nmessage (see line \\ref{line:tab:send-proposal}). In the initial round of each\nheight, the proposer is free to chose the value to suggest. In the\nAlgorithm~\\ref{alg:tendermint}, a correct process obtains a value to propose\nusing an external function $getValue()$ that returns a valid value to\npropose. In the following rounds, a correct proposer will suggest a new value\nonly if $validValue = \\nil$; otherwise $validValue$ is proposed (see\nlines~\\ref{line:tab:isThereLockedValue}-\\ref{line:tab:getValidValue}). \nIn addition to the value proposed, the $\\Proposal$ message also\ncontains the $validRound$ so other processes are informed about the last round\nin which the proposer observed $validValue$ as a possible decision value.\nNote that if a correct proposer $p$ sends $validValue$ with the $validRound$ in the\n$\\Proposal$, this implies that the process $p$ received $\\Proposal$ and the\ncorresponding $2f+1$ $\\Prevote$ messages for $validValue$ in the round\n$validRound$. \nIf a correct process sends $\\Proposal$ message with $validValue$ ($validRound > -1$)\nat time $t > GST$, by the \\emph{Gossip communication} property, the\ncorresponding $\\Proposal$ and the $\\Prevote$ messages will be received by all\ncorrect processes before time $t+\\Delta$. Therefore, all correct processes will\nbe able to verify the correctness of the suggested value as it is supported by\nthe $\\Proposal$ and the corresponding $2f+1$ voting power equivalent $\\Prevote$\nmessages. \n\nA correct process $p$ accepts the proposal for a value $v$ (send $\\Prevote$\nfor $id(v)$) if an external \\emph{valid} function returns $true$ for the value\n$v$, and if $p$ hasn't locked any value ($lockedRound = -1$) or $p$ has locked\nthe value $v$ ($lockedValue = v$); see the line\n\\ref{line:tab:accept-proposal-2}. In case the proposed pair is $(v,vr \\ge 0)$ and a\ncorrect process $p$ has locked some value, it will accept\n$v$ if it is a more recent possible decision value\\footnote{As\nexplained above, the possible decision value in a round $r$ is the one for\nwhich $\\Proposal$ and the corresponding $2f+1$ $\\Prevote$ messages are received\nfor the round $r$.}, $vr > lockedRound_p$, or if $lockedValue = v$ \n(see line~\\ref{line:tab:cond-prevote-higher-proposal}). Otherwise, a correct\nprocess will reject the proposal by sending $\\Prevote$ message with $\\nil$\nvalue. A correct process will send $\\Prevote$ message with $\\nil$ value also in\ncase $\\timeoutPropose$ expired (it is triggered when a correct process starts a\nnew round) and a process has not sent $\\Prevote$ message in the current round\nyet (see the line \\ref{line:tab:onTimeoutPropose}). \n\nIf a correct process receives $\\Proposal$ message for some value $v$ and $2f+1$\n$\\Prevote$ messages for $\\id(v)$, then it sends $\\Precommit$ message with\n$\\id(v)$. Otherwise, it sends $\\Precommit$ $\\nil$. A correct process will send\n$\\Precommit$ message with $\\nil$ value also in case $\\timeoutPrevote$ expired\n(it is started when a correct process sent $\\Prevote$ message and received any\n$2f+1$ $\\Prevote$ messages) and a process has not sent $\\Precommit$ message in\nthe current round yet (see the line \\ref{line:tab:onTimeoutPrecommit}). A\ncorrect process decides on some value $v$ if it receives in some round $r$\n$\\Proposal$ message for $v$ and $2f+1$ $\\Precommit$ messages with $\\id(v)$ (see\nthe line \\ref{line:tab:decide}). To prevent the algorithm from blocking and\nwaiting forever for this condition to be true, the Algorithm\n\\ref{alg:tendermint} relies on $\\timeoutPrecommit$. It is triggered after a\nprocess receives any set of $2f+1$ $\\Precommit$ messages for the current round.\nIf the $\\timeoutPrecommit$ expires and a process has not decided yet, the\nprocess starts the next round (see the line \\ref{line:tab:onTimeoutPrecommit}).\nWhen a correct process $p$ decides, it starts the next consensus instance \n(for the next height). The \\emph{Gossip communication} property ensures \nthat $\\Proposal$ and $2f+1$ $\\Prevote$ messages that led $p$ to decide \nare eventually received by all correct processes, so they will also decide. \n\n\\subsection{Termination mechanism}\n\nTendermint ensures termination by a novel mechanism that benefits from the\ngossip based nature of communication (see \\emph{Gossip communication}\nproperty). It requires managing two additional variables, $validValue$ and\n$validRound$ that are then used by the proposer during the propose step as\nexplained above. The $validValue$ and $validRound$ are updated to $v$ and $r$\nby a correct process in a round $r$ when the process receives valid $\\Proposal$\nmessage for the value $v$ and the corresponding $2f+1$ $\\Prevote$ messages for\n$id(v)$ in the round $r$ (see the rule at line~\\ref{line:tab:recvPrevote}).\n\nWe now give briefly the intuition how managing and proposing $validValue$\nand $validRound$ ensures termination. Formal treatment is left for\nSection~\\ref{sec:proof}. \n\nThe first thing to note is that during good period, because of the\n\\emph{Gossip communication} property, if a correct process $p$ locks a value\n$v$ in some round $r$, all correct processes will update $validValue$ to $v$\nand $validRound$ to $r$ before the end of the round $r$ (we prove this formally\nin the Section~\\ref{sec:proof}). The intuition is that messages that led to $p$\nlocking a value $v$ in the round $r$ will be gossiped to all correct processes\nbefore the end of the round $r$, so it will update $validValue$ and\n$validRound$ (the line~\\ref{line:tab:recvPrevote}). Therefore, if a correct\nprocess locks some value during good period, $validValue$ and $validRound$ are\nupdated by all correct processes so that the value proposed in the following\nrounds will be acceptable by all correct processes. Note \nthat it could happen that during good period, no correct process locks a value,\nbut some correct process $q$ updates $validValue$ and $validRound$ during some\nround. As no correct process locks a value in this case, $validValue_q$ and\n$validRound_q$ will also be acceptable by all correct processes as\n$validRound_q > lockedRound_c$ for every correct process $c$ and as the\n\\emph{Gossip communication} property ensures that the corresponding $\\Prevote$\nmessages that $q$ received in the round $validRound_q$ are received by all\ncorrect processes $\\Delta$ time later. \n\nFinally, it could happen that after GST, there is a long sequence of rounds in which \nno correct process neither locks a value nor update $validValue$ and $validRound$. \nIn this case, during this sequence of rounds, the proposed value suggested by correct\nprocesses was not accepted by all correct processes. Note that this sequence of rounds \nis always finite as at the beginning of every\nround there is at least a single correct process $c$ such that $validValue_c$\nand $validRound_c$ are acceptable by every correct process. This is true as\nthere exists a correct process $c$ such that for every other correct process\n$p$, $validRound_c > lockedRound_p$ or $validValue_c = lockedValue_p$. This is\ntrue as $c$ is the process that has locked a value in the most recent round\namong all correct processes (or no correct process locked any value). Therefore,\neventually $c$ will be the proper in some round and the proposed value will be accepted\nby all correct processes, terminating therefore this sequence of \nrounds. \n\nTherefore, updating $validValue$ and $validRound$ variables, and the\n\\emph{Gossip communication} property, together ensures that eventually, during\nthe good period, there exists a round with a correct proposer whose proposed\nvalue will be accepted by all correct processes, and all correct processes will\nterminate in that round. Note that this mechanism, contrary to the common\ntermination mechanism illustrated in the\nFigure~\\ref{ch3:fig:coordinator-change}, does not require exchanging any\nadditional information in addition to messages already sent as part of what is\nnormally being called \"normal\" case. \n\n", "meta": {"hexsha": "3265b61c753ecd33122973588ea9fc9ae059d1f7", "size": 21933, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "spec/consensus/consensus-paper/consensus.tex", "max_stars_repo_name": "hongyuefan/tendermint", "max_stars_repo_head_hexsha": "851c0dc4f3088723c724cb01c4877ee78c3d6ffc", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-31T01:11:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-31T01:11:06.000Z", "max_issues_repo_path": "spec/consensus/consensus-paper/consensus.tex", "max_issues_repo_name": "hongyuefan/tendermint", "max_issues_repo_head_hexsha": "851c0dc4f3088723c724cb01c4877ee78c3d6ffc", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 39, "max_issues_repo_issues_event_min_datetime": "2021-10-07T23:24:48.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T11:20:01.000Z", "max_forks_repo_path": "spec/consensus/consensus-paper/consensus.tex", "max_forks_repo_name": "hongyuefan/tendermint", "max_forks_repo_head_hexsha": "851c0dc4f3088723c724cb01c4877ee78c3d6ffc", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-10-18T04:41:33.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-18T04:41:33.000Z", "avg_line_length": 55.108040201, "max_line_length": 150, "alphanum_fraction": 0.7452240916, "num_tokens": 6269, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3775406687981454, "lm_q1q2_score": 0.19319382917512679}}
{"text": "\\documentclass{beamer}\n\\usepackage{csquotes}\n\\usepackage{tikz}\n\\usetikzlibrary{arrows,positioning,shapes.geometric, calc}\n\\usepackage{amsmath}\n\\usepackage{listings, xcolor}\n\\usepackage{lmodern}\n\\usepackage{adjustbox}\n\\usepackage{booktabs}\n\\usepackage{colortbl}\n\\usepackage{caption}\n\\usepackage{icomma}\n\\usepackage{bigstrut}\n\\usepackage{geometry}\n\\usepackage{subfigure}\n\\usepackage{algorithmic}\n\n\n\\DeclareMathOperator*{\\argmin}{argmin}\n\\captionsetup[figure]{labelformat=empty}\n\n\\usetheme{metropolis} % Use metropolis theme\n\\title{Update: NN project}\n\\date{\\today}\n\\author{Robert M. Porsch}\n\\institute{Center for Genomic Science}\n\\begin{document}\n\\maketitle\n\n\\begin{frame}[t]{Training, Development, Testing}\n \\begin{columns}[t]\n \\begin{column}{0.5\\textwidth}\n Simulation Data 1:\\\\\n \\begin{itemize}\n \\item $\\sim2,000$ samples\n \\item 40 different simulated phenotypes\n \\item based on 1000 Genome project\n \\item $MAF\\geq1\\%$\n \\end{itemize}\n \\end{column}\n \\begin{column}{0.5\\textwidth}\n Simulation Data 2: \n \\begin{itemize}\n \\item $\\sim300,000$ samples\n \\item 4 different simulated phenotypes\n \\item based on UKB\n \\item $MAF\\geq1\\%$\n \\end{itemize}\n \\end{column}\n \\end{columns}\n Issues: sample size limitations for development/testing dataset \n\\end{frame}\n\n\\begin{frame}[t]{On the issue of clumping}\n \\begin{itemize}\n \\item Clumping can be seen as a variable selection methods (with the parameter p1, p2, r2 and window size)\n \\item Tests for a linear relationship between SNP and phenotype\n \\end{itemize}\n So when is this becoming a problem?\n \\begin{itemize}\n \\item nonlinearity\n \\item interactions\n \\item additional hypterparameter to optimize\n \\end{itemize}\n\\end{frame}\n\n\\begin{frame}[t]{On the sucess of clumping}\n \\begin{columns}\n \\begin{column}{0.5\\textwidth}\n \\begin{figure}[htpb]\n \\centering\n \\includegraphics[width=0.8\\linewidth]{./clumped_1kg_lasso.png}\n \\caption{Clumped Lassosum}\n \\end{figure}\n \\end{column}\n \\begin{column}{0.5\\textwidth}\n \\begin{figure}[htpb]\n \\centering\n \\includegraphics[width=0.8\\linewidth]{./not_clumped_1kg_lasso.png}\n \\caption{NOT Clumped Lassosum}\n \\end{figure}\n \\end{column}\n \\end{columns}\n\\end{frame}\n\n\\begin{frame}[t]{NN are difficult to fit}\n \\begin{columns}\n \\begin{column}{0.5\\textwidth}\n \\begin{figure}[htpb]\n \\centering\n \\includegraphics[width=0.8\\linewidth]{keras_model_ukb_nn}\n \\caption{Complex model (85,60,60,60)}\n \\end{figure}\n \\end{column}\n \\begin{column}{0.5\\textwidth}\n \\begin{figure}[htpb]\n \\centering\n \\includegraphics[width=0.8\\linewidth]{keras_model_ukb_nn_small}\n \\caption{Simple model (60)}\n \\end{figure}\n \\end{column}\n \\end{columns}\n \\begin{itemize}\n \\item Complexity becomes difficult to train (learning rate)\n \\item The phenotype is linear\n \\end{itemize}\n\\end{frame}\n\n\\begin{frame}[t]{Sometimes you need to think}\n \\begin{columns}\n \\begin{column}{0.5\\textwidth}\n \\begin{figure}[htpb]\n \\centering\n \\includegraphics[width=0.8\\linewidth]{keras_model_ukb_linear.png}\n \\caption{Linear Model on the UKB}\n \\end{figure}\n \\end{column}\n \\begin{column}{0.5\\textwidth}\n \\begin{figure}[htpb]\n \\centering\n \\includegraphics[width=0.8\\linewidth]{./keras_model_ukb_nn_small.png}\n \\caption{Small NN model on the UKB}\n \\end{figure}\n \\end{column}\n \\end{columns}\n \\begin{itemize}\n \\item Drop out layer regularizes efficiently\n \\item During validation dropout is deactivated\n \\end{itemize}\n\\end{frame}\n\n\\begin{frame}[t]{On Sample Size}\n \\begin{columns}\n \\begin{column}{0.5\\textwidth}\n \\begin{figure}[htpb]\n \\centering\n \\includegraphics[width=0.8\\linewidth]{./keras_model_ukb_nn_small.png}\n \\caption{Small NN model on the UKB}\n \\end{figure}\n \\end{column}\n \\begin{column}{0.5\\textwidth}\n \\begin{figure}[htpb]\n \\centering\n \\includegraphics[width=0.8\\linewidth]{./keras_model_1kg_nn_small.png}\n \\caption{Small NN model on the 1KG}\n \\end{figure}\n \\end{column}\n \\end{columns}\n \\begin{itemize}\n \\item less overfitting\n \\item results remain accurate despite low sample size\n \\end{itemize}\n\\end{frame}\n\n\\begin{frame}[t]{Evaluation}\n \\begin{itemize}\n \\item Trivial problem given a linear simulated phenotype\n \\item Now-complexity\n \\end{itemize}\n\\end{frame}\n\n% \\begin{frame}[t]{UKB Data}\n% I also made use of the UKB with the following phenotypes:\n% \\begin{itemize}\n% \\item height\n% \\item IQ\n% \\end{itemize}\n% Data was split into training and dev set using caucsian samples only.\n% Dev set was set to be at least $10,000$ samples.\n% \n% Some potential problems with the data structure:\n% \\begin{itemize}\n% \\item data was not shuffled \n% \\item currently data was not adjusted for potential confounders (unclear how important)\n% \\end{itemize}\n% \\end{frame}\n% \n% \\section{Fully connected LD Layer: FullDa}\n% \n% \\begin{frame}[t]{Architecture}\n% \\begin{columns}[t]\n% \\begin{column}{0.5\\textwidth}\n% Layer 1:\n% \\begin{algorithmic}\n% \\STATE initialize $Z$\n% \\FOR{v = LD-Blocks} \n% \\STATE $z_v = W^{[1]}_vX_v$\n% \\STATE $a_v = g(z_v)$\n% \\STATE $APPEND(Z, z_v)$\n% \\ENDFOR\n% \\end{algorithmic}\n% Layer $2$:\\\\\n% \\begin{itemize}\n% \\item fully connected layers to output\n% \\item $L_1$ regularization in $l=1,2$\n% \\item dropout with $p=0.8$\n% \\end{itemize}\n% \\end{column}\n% \\begin{column}{0.5\\textwidth}\n% Optimization:\n% \\begin{itemize}\n% \\item AdaGrad\n% \\item Mini-Batch gradient decent with $m=100$\n% \\item no early stopping ($epochs=100$)\n% \\end{itemize}\n% \\end{column}\n% \\end{columns}\n% \\end{frame}\n% \n% \\begin{frame}[t]{Model Overview}\n% \\begin{figure}[htpb]\n% \\centering\n% \\includegraphics[width=0.8\\linewidth]{./tensormodel.png}\n% \\end{figure}\n% \\end{frame}\n% \n% \\begin{frame}[t]{Some results}\n% \\begin{figure}[htpb]\n% \\centering\n% \\includegraphics[width=0.8\\linewidth]{performance.png}\n% \\caption{Example performance on phenotype 1}\n% \\end{figure}\n% \\begin{itemize}\n% \\item high variance problem\n% \\item disappointing performance in development set\n% \\item performance similar to LassoSum\n% \\end{itemize}\n% \\end{frame}\n% \n% \\section{Clumped NN}\n% \n% \\begin{frame}[t]{Architecture}\n% Similar architecture but with additional clumping step\n% \n% \\begin{enumerate}[(i)]\n% \\item run GWAS on training set\n% \\item perform clumping ($r^2=0.5, p_1 = 0.01, p_2 = 0.1$) \n% \\begin{itemize}\n% \\item Results in 72 SNPs\n% \\end{itemize}\n% \\item feed clumped genotype matrix into fully connected NN $L=3$\n% \\begin{itemize}\n% \\item $n^{[1]}_h=60, n^{[2]}_h=60, n^{[3]}_h=1$\n% \\item dropout layer after $l=1$ and $l=2$\n% \\end{itemize}\n% \\end{enumerate}\n% No early stopping, ($epochs=100$), mini-batch with $m=100$\n% \\end{frame}\n% \n% \\begin{frame}[t]{Results}\n% \\begin{figure}[htpb]\n% \\centering\n% \\includegraphics[width=0.8\\linewidth]{./keras_model.png}\n% \\end{figure}\n% \\begin{itemize}\n% \\item Similar performance to the LD-connected NN\n% \\item high variance problem\n% \\end{itemize}\n% \\end{frame}\n% \n% \\begin{frame}[t]{Conclusions}\n% \\begin{itemize}\n% \\item Stronger regularization is required\n% \\item Currently there is no hyper-parameter optimization\n% \\item Larger dataset should be used (requires some re-write of the data import)\n% \\item Current literature: More and more paper on penalized regression for genetic risk prediction (mostly Lasso)\n% \\end{itemize}\n% \\end{frame}\n\\end{document}\n", "meta": {"hexsha": "c525ce4920b9fff6002cb76f7f51cad75d4d9791", "size": 7909, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/presentation/nn_prediction_linear/nn_prediction_linear.tex", "max_stars_repo_name": "rmporsch/ML_genetic_risk", "max_stars_repo_head_hexsha": "4e1a0510c94260e69f93639ff4104c5f85080d9f", "max_stars_repo_licenses": ["MIT"], "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/presentation/nn_prediction_linear/nn_prediction_linear.tex", "max_issues_repo_name": "rmporsch/ML_genetic_risk", "max_issues_repo_head_hexsha": "4e1a0510c94260e69f93639ff4104c5f85080d9f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-11-13T18:04:51.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-10T19:40:45.000Z", "max_forks_repo_path": "doc/presentation/nn_prediction_linear/nn_prediction_linear.tex", "max_forks_repo_name": "rmporsch/ML_genetic_risk", "max_forks_repo_head_hexsha": "4e1a0510c94260e69f93639ff4104c5f85080d9f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-11-23T05:57:04.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-23T05:57:04.000Z", "avg_line_length": 29.2925925926, "max_line_length": 118, "alphanum_fraction": 0.6507775951, "num_tokens": 2475, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117165898111866, "lm_q2_score": 0.37754065479083276, "lm_q1q2_score": 0.1931938163846474}}
{"text": "%!TEX root = morusAC.tex\n\n\\section{Introduction}\n\\label{sec/Introduction}\n\nAuthenticated Encryption (AE) schemes combine the functionality of symmetric encryption schemes and message authentication codes.\nBased on a shared secret key $K$, they encrypt a plaintext message $M$ to a ciphertext $C$ and authentication tag $T$ in order to protect both the confidentiality and the authenticity of $M$.\nMost modern authenticated encryption algorithms are nonce-based schemes with associated data (AEAD),\nwhere $(C, T)$ additionally depends on a unique nonce $N$ (or initialization value IV) and optional associated metadata $A$.\nOne of the most prominent standardized AEAD designs is \\cipher{AES-GCM} \\cite{indocryptMcGrewV04,nistDworkin07},\nwhich is widely deployed in protocols such as \\cipher{TLS} (since v1.2).\n\nTo address the growing need for modern authenticated encryption designs for different application scenarios, \nthe CAESAR competition was launched in 2013 \\cite{CAESAR}.\nThe goal of this competition is to select a final portfolio of AEAD designs for three different use-cases:\n(1) lightweight hardware characteristics,\n(2) high-speed software performance, and\n(3) robustness.\nThe competition attracted 57 first-round submissions, 7 of which were recently selected as finalists in the fourth selection round.\n\n\\MORUS is one of the three finalists for use-case (2), together with \\cipher{OCB} and \\cipher{AEGIS}.\nThis family of authenticated ciphers by Wu and Huang \\cite{MORUS} provides three main variants:\n\\MORUS[640] with a 128-bit key and \\MORUS[1280] with either a 128-bit or a 256-bit key.\nThe design approach is reminiscent of classical stream cipher designs and\ncontinuously updates a relatively large state with a few fast operations.\n\\MORUS can be efficiently implemented in both software and hardware;\nin particular, the designers claim that the software performance even surpasses\n\\cipher{AES-GCM} implementations using Intel's \\cipher{AES-NI} instructions,\nand that \\MORUS is the fastest authenticated cipher not using \\cipher{AES-NI} \\cite{MORUS}.\n\n\\subsubsection*{Related Work.}\nIn the \\MORUS submission document, the designers discuss the security of \\MORUS against\nseveral attacks, including algebraic, differential, and guess-and-determine attacks.\nThe main focus is on differential properties, and not many details are given for other attack vectors.\nIn third-party analysis,\nMileva et~al.~\\cite{balkancryptsecMilevaDV15} propose a distinguisher in the nonce-reuse setting and practically evaluate the differential behaviour of toy variants of \\MORUS.\nShi et~al.~\\cite{aiieShiGLZ16} analyze the differential properties of the finalization reduced to 2 out of 10 steps, but find no attacks.\nDwivedi et~al.~\\cite{cryptoeprint:2016:1053} discuss the applicability of SAT solvers for state recovery, but the resulting complexity of $2^{370}$ for \\MORUS[640] is well beyond the security claim.\nDwivedi et~al.~\\cite{secryptDwivediMW17} also propose key-recovery attacks for \\MORUS[1280] if initialization is reduced to 3.6 out of 16 steps, and discuss the security of \\MORUS against internal differentials and rotational cryptanalysis.\nSalam et~al.~\\cite{trustcomSalamSBDPW17} apply cube attacks to obtain distinguishers for up to 5 out of 16 steps of the initialization of \\MORUS[1280] with negligible complexity.\nAdditionally, \nKales et~al.~\\cite{cryptoeprint:2017:1137} and\nVaudenay and Viz\\'{a}r \\cite{cryptoeprint:2017:1147}\nindependently propose state-recovery and forgery attacks on \\MORUS in a nonce-misuse setting with negligible data and time complexities.\n\nFinally, a keystream correlation similar in nature to our main attack was uncovered by Minaud \\cite{sacryptMinaud14} on the authenticated cipher \\cipher{AEGIS} \\cite{AEGIS,sacryptWuP13}, another CAESAR finalist.\n\\cipher{AEGIS} shares the same overall structure as \\MORUS, but uses a very different state update function,\nbased on the parallel application of \\cipher{AES} rounds, rather than the shift/AND/XOR operations used in \\MORUS.\nSimilar to our attack, the approach in \\cite{sacryptMinaud14} is to build a linear trail linking ciphertext bits, while canceling the\ncontribution of inner state bits.\nHow the trail is built depends primarily on the state update function, and how it lends itself to linear cryptanalysis.\nBecause the state update function differs significantly between AEGIS and MORUS, the process used to build the trail is also quite different.\n\n\\subsubsection*{Our Contributions.}\nOur main contribution is a keystream distinguisher on full \\MORUS[1280], built from linear approximations of its core \\StateUpdate{} function.\nIn addition, we provide results for round-reduced \\MORUS, targeting both the initialization or finalization phases of the cipher.\n\nIn more detail, our main result is a linear approximation \\cite{eurocryptMatsui93,eurocryptMatsuiY92} linking plaintext and ciphertext bits spanning five consecutive encryption blocks.\n%As a consequence of this trail, we exhibit a biased linear combination of ciphertext bits, which holds across any given sequence of five consecutive encryption steps.\n%Technically, this assumes that the inner state of the cipher at the start of the trail is uniformly random, but this is a fair assumption since the inner state should be indistinguishable from uniform randomness by design.\n%Moreover, that is the only assumption required; in particular, the secret key or the nonce used to initialize the inner state of MORUS are irrelevant: the bias is independent of their value.\n%As a consequence, when encrypting a fixed plaintext segment multiple times, a linear correlation exists between some output bits of the cipher.\nMoreover, the correlation does not depend on the secret key of the cipher.\nIn principle, this property could be used as a known-plaintext distinguisher, or to recover unknown bits of a plaintext encrypted a large number of times.\nFor \\MORUS[1280] with 256-bit keys, the linear correlation is $2^{-76}$\nand can be exploited using about $2^{152}$ encrypted blocks.\n\nTo the best of our knowledge, this is the first attack on full \\MORUS in the nonce-respecting setting.\nWe note that rekeying does not prevent the attack: the biases are independent of the secret encryption key and nonce, and can be exploited for plaintext recovery as long as a given plaintext segment is encrypted sufficiently often, regardless of whether each encryption uses a different key.\nA notable feature of the linear trail underpinning our attack is also that it does not depend on the values of rotation constants: a very similar trail would exist for most choices of round constants.\n\nTo obtain this result, we propose a simplified abstraction of \\MORUS, called \\MiniMORUS. \\MiniMORUS takes advantage of certain rotational invariants in \\MORUS and simplifies the description and analysis of the attack. We then show how the attack can be extended from \\MiniMORUS to the real \\MORUS.\n%We observe that the actual bias of the approximation is better than suggested by the construction of the characteristics.\nTo confirm the validity of our analysis,\nwe practically verified the correlation of the full linear trail for \\MiniMORUS, as well as the correlation of trail fragments for the full \\MORUS.\nOur analysis is also backed by a symbolic evaluation of the full trail equation and its correlation on all variants of \\MORUS.\n\nIn addition to the previous attack on full \\MORUS, we provide two secondary results: (1) we analyze the security of \\MORUS against forgery attacks with round-reduced finalization; and (2) we analyze its security against key recovery in a nonce-misuse setting, with round-reduced initialization.\nWhile this extra analysis does not threaten full \\MORUS, it complements the main result to provide a better overall understanding of the security of \\MORUS.\nMore precisely, we present a forgery attack for round-reduced \\MORUS[1280] with success probability $2^{-88}$ for a 128-bit tag if the finalization is reduced to 3 out of 10 steps. This nonce-respecting attack is based on a differential analysis of the padding rule.\nThe second result targets round-reduced initialization with 10 out of 16 steps, and extends a state-recovery attack (which can be mounted e.g. in a nonce-misuse setting) into a key-recovery attack.\n\n\\subsubsection*{Outline.}\nThis paper is organized as follows.\nWe first provide a brief description of \\MORUS in \\Cref{sec/Preliminaries}.\nIn \\Cref{sec/introminimorus}, we introduce \\MiniMORUS, an abstraction of \\MORUS based on a certain class of rotational invariants.\nWe analyze this simplified scheme in \\Cref{sec/minitrails} and provide a ciphertext-only linear approximation with a weight of 16.\nWe then extend our result to the full scheme in \\Cref{sec/fulltrails}, showing a correlation in the keystream over 5 steps,\nand discuss the implications of our observation for the security of \\MORUS in \\Cref{sec/Discussion}.\nIn \\Cref{sec/IniFin}, we present our results on the security of \\MORUS with round-reduced initialization (in a nonce-misuse setting) or finalization.\nWe conclude in \\Cref{sec/Conclusion}.\n\n%%% Local Variables:\n%%% TeX-master: \"morusAC\"\n%%% End:\n", "meta": {"hexsha": "64d9e70e57e4872f757cd4ded889cfc9b50bd119", "size": 9167, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "AC2018_camera_ready/morusAC_01_Introduction.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_01_Introduction.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_01_Introduction.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": 95.4895833333, "max_line_length": 297, "alphanum_fraction": 0.8047343733, "num_tokens": 2154, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.3557749003442964, "lm_q1q2_score": 0.1931371304712756}}
{"text": "% !TEX root = main.tex\n\nTo establish an authenticated security context for \\mOscore,\n\\mEdhoc{} uses a three-message protocol structure\nshown in Figure~\\ref{fig:edhocFramework}.\n%\nIn the first message \\mMsgone{}, the initiator (\\mT{I}) sends to the responder (\\mT{R}) an\nephemeral DH half-key \\mGx{}, an ordered list of supported cipher suites, and, in the \\mMethod{} element, suggests\nauthentication methods to be used.\n%\n\\mT{R} may reject the choice of cipher suite, leading to a negotiation across multiple \\mEdhoc{} sessions (see Section~\\ref{sec:ciphersuiteNegotiation}), or that of the authentication methods.\n%\nIn the second message \\mMsgtwo{}, \\mT{R} provides its ephemeral\nDH half-key \\mGy{} and authenticates itself to \\mT{I} by\nproviding authentication data \\mAuthr{}.\n%\nFinally, in the third message \\mMsgthree{}, \\mT{I} authenticates itself\nto \\mT{R} by providing authentication data \\mAuthi{}.\n%\nThe authentication data consists of a MAC for all authentication methods.\n%\nThis MAC is also signed when authentication is based on public key signatures.\n%\nIn addition to the exchange of DH half-keys and authentication data, the\nmessages also include parameters for the \\mOscore{} security context, such as\nencryption algorithm identifiers (\\mSuites{}) and \\mOscore{} security context\nidentifiers \\mCi{} and \\mCr{}.\n%\nOptionally, messages may also include application layer data \\mAD{}, which\nenjoys differing levels of protection depending on which message it is part of.\n%\nWe do not include \\mCi, \\mCr, and \\mAD{} in our modelling here.\n%\nWhen authentication is based on\na pre-shared key, the \\mCredi{} and \\mCredr{} credential identifiers are not\nused.\n%\nInstead, a single identifier for the pre-shared key is transmitted in \\mMsgone{}.\n%\n\\begin{figure}\n\\centering\n\\linespread{1}\n\\tikzset{>=latex, every msg/.style={draw=thick}, every node/.style={fill=none,text=black}}\n\\begin{tikzpicture}\n \\node (ini) at (0, 0) {Initiator (\\mT{I})};\n \\draw [very thick] (0, -0.25) -- (0,-2.2);\n \\draw [very thick] (7, -0.25) -- (7,-2.2);\n \\node (res) at (7,0) {Responder (\\mT{R})};\n \\msg{1em}{ini}{res}{\\mMsgone: \\mMethod, \\mSuites, \\mGx, \\mCi, \\mADone};\n\\msg{3em}{res}{ini}{\\mMsgtwo: \\mCi, \\mGy, \\mCr, [\\mIdcredr, \\mAuthr, \\mADtwo]};\n \\msg{5em}{ini}{res}{\\mMsgthree: \\mCr, [\\mIdcredi, \\mAuthi, \\mADthree]};\n \\draw [line width=1mm] (-0.75,-2.2) -- (0.75,-2.2);\n \\draw [line width=1mm] (7-0.75,-2.2) -- (7+0.75,-2.2);\n \\end{tikzpicture}\n\\caption{Structure of \\mEdhoc{}: $[t]$ means $t$ is encrypted and integrity protected}\n\\label{fig:edhocFramework}\n\\end{figure}\n\n\\knote{note that the version we look at has private keys, but the current spec\n in IETF does not. OTOH, they aim to add that later, and I can't see how they\n could avoid doing so. That is why I write \"aims to...\"\n}\n\\mEdhoc{} aims to accommodate three credential types\na party may use for authentication -- certificates, private keys\nand static long-term DH keys.\n%\nDepending on the types used, the authentication methods differ,\nand \\mAuthi{} and \\mAuthr{} need to be constructed accordingly.\n%\nThe three authentication methods are based on digital signatures (\\mSig),\nchallenge-response signatures based on static long-term DH keys (\\mStat) and\npre-shared symmetric keys (\\mPsk).\n%\nThe two parties may use different authentication methods in an \\mEdhoc{} run.\n%\nWhile any combination of the \\mSig{} and \\mStat{} methods is possible,\nwhen \\mPsk{} is used, both parties must use \\mPsk{}.\n%\nWe refer to these \\emph{combinations} of authentication methods as\n\\emph{methods} to follow the terminology in the\n\\mSpec{}~\\cite{selander-lake-edhoc-01}.\n%\nThus, we have five methods: \\mSigSig, \\mSigStat, \\mStatStat, \\mStatSig{} and\n\\mPskPsk.\n%\nThe first method in a name denotes the\nauthentication method used by the initiator of the protocol run and the second denotes the\none used by the responder.\n%\nWe refer to a method where at least one party uses \\mSig{} as a \\mSig-based\nmethod, and similarly for \\mStat{} and \\mPsk.\n%\n\nWe first briefly discuss \\mEdhoc's relations to the protocols on which it is\nbased before providing details about the methods.\n%\n\n%-----------------------------------------------------------------------------\n\\subsection{Relation to \\mSigma, \\mOptls{}, and \\mNoise{}}\n\\label{sec:relationsToOtherProtocols}\nWe now present how \\mEdhoc{} uses \\mSigma, \\mOptls{}, and \\mNoise{} as\ncryptographic cores for various methods, and the ways in which it differs from them.\n\\\\\n%\nBeing designed as an industrial standard, \\mEdhoc{} specifies more details\non top of these cores, e.g., connection identifiers for message multiplexing,\nencoding and application specific parameters to be negotiated.\n%\n\n%-----------------------------------------------------------------------------\n%\\runhead{\\mSigma{}}\n\\subsubsection{\\mSigma{}}\n\\label{sec:sigma}\nThe \\mSigSig{} method of \\mEdhoc{} is closely modeled on the \\mSigma{}\nvariant that provides identity protection for the initiator~\\cite{sigma}.\n%\nSome aspects differ though, e.g., \\mSigSig{} uses Mac-then-Sign like\n\\mTls{} instead of Sign-then-Mac. \n%\n\n%----------------------------------------------------------------------------- \n\\subsubsection{\\mOptls{}}\n\\label{sec:optls}\nThe \\mStat-based methods use challenge-response signatures based on static\nlong-term DH keys, and proceed along the lines of\n\\mOptls~\\cite{DBLP:conf/eurosp/KrawczykW16}.\n%\nThe challenge-response works as follows.\nParty $A$ sends a random challenge $r$\nand an ephemeral DH half-key $e$ to a party $B$.\n%\n$B$ mixes $e$ and $r$ with its secret static\nlong-term DH key $s$ to obtain a temporary key, which\n%\nis used to compute a MAC that is returned to $A$.\n%\nThis authenticates $B$ to $A$, which is sufficient for \\mOptls, \nbecause it only considers server authentication, where the server acts as $B$\nand the client as $A$.\n%\nThe temporary key also affects the final session key.\n%\n\nIn \\mEdhoc, a party using the \\mStat{} authentication method\nessentially acts as an \\mOptls{} client and the peer as an \\mOptls{}\nserver.\n%\nHowever, unlike \\mOptls{}, \\mEdhoc{} requires mutual\nauthentication~\\cite{ietf-lake-reqs-04}.\n%\n\\mStatStat{} can be thought of as interleaving two \\mOptls{}\nruns, one initiated by each party, and then combining the resulting session key\nmaterial.\n%\nAlso, \\mOptls{} uses the conservative security approach where $e$ and $r$\nare distinct elements, whereas \\mEdhoc{} reuses the $e$ as the challenge $r$.\n%\nThe latter can only weaken security.\n%\n\n%------------------------------------------------------------------------- sub\n\\subsubsection{\\mNoise{}}\nThe \\mStatStat{} and \\mPskPsk{} methods follow the \\mNoise{}\nframework~\\cite{perrin2016noise}.\n%\n\\mNoise{} defines how to construct AKE protocols, using static long-term DH\nkeys or pre-shared keys as credentials.\n%\nIts goal is to use so-called patterns to harmonize the many static long-term\nkey DH-based AKE protocols, of which \\mOptls{} is one.\n%\n\\mNoise{} specifies how to derive keys, use transcript hashes to ensure\nauthentication of the message flow etc.\n%\nThe \\mNoise{} pattern closest to the \\mStatStat{} method is called XX.\n%\nHowever, \\mEdhoc{} does not use the functions of \\mNoise{} exactly as\nprescribed.\n%\nIt is thus not obvious that \\mEdhoc{} automatically inherits\nthe properties enjoyed by XX.\n%\nFor example, according to \\mNoise{}, the mixHash function is called on\npre-message public keys during the initialization.\n%\nThis would correspond to \\mEdhoc{} computing a first intermediate transcript\nhash over those keys, which \\mEdhoc{} does not do.\n%\n\n%------------------------------------------------------------------------- sub\n\\subsection{Methods of \\mEdhoc{}}\n\\label{sec:methods}\nAlthough \\mCbor{} and \\mCose{}~\\cite{rfc8152} are important building blocks of\n\\mEdhoc{}, and we use their terminology in our \\mTamarin{} model to better\nreflect the \\mSpec{}, our model does not cover the details of encoding and\n\\mCose{} interfaces.\n%\nThus, we omit details about \\mCbor{} and \\mCose{}. Similarly, we refer the reader to~\\cite{aead} for details about authenticated encryption with associated data (AEAD).\n%\nAll methods make use of a common key hierarchy, which we describe first.\n%\n\n%------------------------------------------------------------------------- sub\n\\subsubsection{Key Hierarchy}\n%\\runhead{Key Hierarchy}\n\\label{sec:keyHierarchy}\n\\mEdhoc{} derives keys using \\mHkdf{}~\\cite{rfc5869}.\n%\nThe \\mHkdf{} interface provides two functions -- \\mHkdfExtract{}, which\nconstructs uniformly distributed key material from random input and a seed,\nand \\mHkdfExpand{}, which generates keys from key material and a seed.\n%\nThe seeds are used to bind the key material and keys to certain parameters.\n%\nDerived keys (\\mKtwoe, \\mKtwom{}, \\mKthreeae, and \\mKthreem) are then used as\ninput to encryption and integrity protection algorithms.\n%\n\nThe key hierarchy is rooted in the ephemeral DH key \\mGxy{}, the combination\nof the two half-keys \\mGx{} and \\mGy{}.\n%\nFrom this, keys are successively constructed with each transmitted message,\nweaving in information parties learn as the protocol progresses, culminating\nin the established session key material.\n%\nFrom the session key material, a key exporter (\\mEdhoc-Exporter) based on\n\\mHkdf{} can be used to extract the encryption and integrity keys required\nfor \\mOscore{}.\n%\nFigure~\\ref{fig:kdfdiagram} shows an abstract description of the key hierarchy.\n%\n\nFrom \\mGxy{}, three intermediate keys \\mPRKtwo, \\mPRKthree{} and\n\\mPRKthree{} are derived.\n%\nEach one of them corresponds to a specific message in the protocol, and from\nthese intermediate keys, encryption and integrity keys for that message are\nderived.\n%\nFor \\mPskPsk{}, the pre-shared key is used as seed for \\mPRKtwo.\n%\nFor all other methods the seed for \\mPRKtwo{} is empty.\n%\nIn the \\mPskPsk{} and \\mSigSig{} methods, all three intermediate keys\nare the same, i.e., $\\mPRKtwo{} = \\mPRKthree{} = \\mPRKfour$.\n%\nFor the three \\mStat-based methods, however, they differ.\n%\nThis is because the intermediate key \\mPRKthree{} is dependent on the static\nlong-term key of the party (or parties, if both) using \\mStat{}-based\nauthentication.\n%\n\n\\begin{figure}[!h]\n\\centering\n\\scalebox{.75}{\n\\linespread{1}\n\\input{kdfdiagram.tex}\n}\n\\caption{Joint key hierarchy for all methods}\n\\label{fig:kdfdiagram}\n\\end{figure}\n\nWe now describe the \\mEdhoc{} methods.\n%\n%Since the \\mSigSig{} method has been analyzed earlier, we do not focus on\n%it here.\n%\n\n\\subsubsection{\\mPskPsk{}}\nIn this method, the initiator and responder are assumed to share a pre-shared\nkey (\\mPsk) identified by \\mIDPsk.\n%\nThe message sequence is shown in Figure~\\ref{fig:edhocpsk}.\n%\nThe first message contains the \\mIDPsk{} identifier.\n%\nThe responder obtains the corresponding \\mPsk{} and uses that to construct the\nauthentication data, i.e., the MAC in the \\mAead{} transform), included in\nthe second message.\n%\nn the third message, the initiator uses this same technique to authenticate\nto the responder.\n%\nThe transcript hash \\mTH{} keeps track of the data sent in the messages.\n%\nOne unconventional feature is that the transcript hash lags behind by one\nmessage.\n%\nThat is, the second transcript hash \\mTHtwo{}, does not cover the content of\nthe second message (similarly for \\mTHthree).\n%\nThe reason for this is that \\mTHtwo{} cannot cover the output of the\n\\mAead{} transform, since \\mTHtwo{} is itself an input to it.\n%\nThis is the same for all methods, but it does not cause any problems with\nauthentication, since the data not covered by the transcript hash is\ninstead MACed or signed.\n%\n\n\\begin{figure}\n\\centering\n\\linespread{1}\n\\scalebox{.69}{\n\\tikzset{>=latex, every msg/.style={draw=thick}, every node/.style={fill=none,text=black}}\n\\begin{tikzpicture}\n \\node (ini) at (0, 0) {Initiator};\n \\draw [very thick] (0, -0.5) -- (0,-11);\n \\draw [very thick] (11.5, -0.5) -- (11.5,-11);\n \\node[below=0.5em of ini,fill=white] () {Knows $g,\\ \\mPsk,\\ \\mIDPsk,\\ \\mADone,\\ \\mADthree$};\n \\node (res) at (11.5,0) {Responder};\n \\node[below=0.5em of res,fill=white] () {Knows $g,\\ \\mPsk,\\ \\mIDPsk,\\ \\mADtwo$};\n \\action{3em}{ini}{Generates \\mMethod,\\ \\mSuites,\\ \\mCi,\\ $x$\\\\$\\mGx = g^{x}$};\n \\msg{6.5em}{ini}{res}{\\mMsgone: \\mMethod, \\mSuites, \\mGx, \\mCi, \\mIDPsk, \\mADone};\n \\action{7em}{res}{$\n \\begin{array}{c}\n \\text{Generates } \\mCr,\\ $y$\\\\\n \\mGy = g^{y}\\\\\n \\mTHtwo = \\mHash(\\mMsgone, g^{y})\\\\\n \\mPRKtwo = \\mHkdfExtract(\\mPsk, g^{xy}) \\\\\n \\mKtwoae = \\mHkdfExpand(\\mPRKtwo, \\mTHtwo)\n \\end{array}$};\n \\msg{15.5em}{res}{ini}{\\mMsgtwo: \\mCi, \\mGy, \\mCr, $\\overbrace{\\mAead(\\mKtwoae; \\mTHtwo, \\mADtwo)}^{\\mCipher}$};\n \\action{16.5em}{ini}{$\n \\begin{array}{c}\n \\mTHtwo = \\mHash(\\mMsgone, \\mGy)\\\\\n \\mPRKtwo = \\mHkdfExtract(\\mPsk, g^{xy}) \\\\\n \\mKtwoae = \\mHkdf(\\mPRKtwo, \\mTHtwo)\\\\\n \\mTHthree = \\mHash(\\mTHtwo, \\mCipher)\\\\\n \\mPRKthree = \\mPRKtwo \\\\\n \\mKthreeae = \\mHkdfExpand(\\mPRKthree, \\mTHthree)\n \\end{array}$};\n \n \\msg{25.5em}{ini}{res}{\\mMsgthree: \\mCr, \\mAead(\\mKthreeae; \\mTHthree; \\mADthree)};\n \\action{26em}{res}{$\n \\begin{array}{c}\n \t\\mPRKthree = \\mPRKtwo \\\\\n \\mKthreeae = \\mHkdfExpand(\\mPRKthree, \\mTHthree)\n \\end{array}$};\n \\draw [line width=1mm] (-2,-11) -- (2,-11);\n \\draw [line width=1mm] (9.5,-11) -- (13.5,-11);\n \\end{tikzpicture}}\n\\caption{The \\mPskPsk{} method; $\\mAead(k; x; y)$ is used to denote\n\\mAead{} encryption where $k$ is the key, $x$ is associated data to be integrity\nprotected, and $y$ is the plaintext}\n\\label{fig:edhocpsk}\n\\end{figure}\n%\n\n%------------------------------------------------------------------------- sub\n\\subsubsection{\\mStat-based Methods.}\n\\mEdhoc{} provides three \\mStat-based methods -- \\mSigStat{}, \\mStatStat{} and\n\\mStatSig{}.\n%\nOne or both of the initiator and responder authenticate to their peer using\ntheir secret static long-term DH key, \\mLtki{} or \\mLtkr{} respectively.\n%\nAuthentication of the party using the \\mStat{} method follows the\nchallenge-response signature pattern from \\mOptls.\n%\nIn the same terms as Section~\\ref{sec:optls}, the ephemeral DH half-key of the\npeer takes the place of both $r$ and $e$, i.e., $r=e$, and $s$ is the secret\nstatic long-term DH key of the party to be authenticated.\n%\nAssuming the discrete log problem is hard in the underlying DH group,\nonly the initiator and responder will be able to compute $e^s$.\n%\nThat value is then affecting the computation of \\mAuthr{} or \\mAuthi{}\n(depending on who is the authenticator), and it is also\nwoven in to the key hierarchy, see\nFigures~\\ref{fig:kdfdiagram} and \\ref{fig:edhocsigstat}.\n%\nThe receiver of \\mAuthi{}/\\mAuthr{} assumes that only the responder knows\nthe corresponding $e^s$, and therefore considers the peer authenticated if\nthe \\mAead{} transform completes successfully.\\\\\n%\nIn contrast to the \\mPskPsk{} method, in \\mStat{}-based methods, each party provides an identifier, \\mIdcredi{} and \\mIdcredr{} respectively, for the credentials they use.\n%\n\n%------------------------------------------------------------------------- sub\n%\\subsubsection{\\mSigStat.}\n\\paragraph{\\mSigStat}\nThe initiator uses the \\mSig{} method, authenticating with a signature,\nwhile the responder uses the \\mStat{} method, authenticating with a\nchallenge-response signature.\n%\nThe detailed message sequence chart is shown in Figure~\\ref{fig:edhocsigstat}.\n%\n\\mCredi{} and \\mLtki{} must be signature keys since the initiator is using the\n\\mSig{} method.\n%\n\n\\begin{figure}[h]\n\\centering\n\\linespread{1}\n\\scalebox{.7}{\n\\tikzset{>=latex, every msg/.style={draw=thick}, every node/.style={fill=none,text=black}}\n\\begin{tikzpicture}\n \\node (ini) at (0, 0) {Initiator};\n \\draw [very thick] (0, -0.5) -- (0,-15.5);\n \\draw [very thick] (9, -0.5) -- (9,-15.5);\n \\node[below=0.5em of ini,fill=white] {$\n \\begin{array}{c}\n \\text{Knows}\\ $g$,\\ \\mCredi,\\ \\mLtki,\\ \\mIdcredi,\\\\\n \\mIdcredr, \\mADone,\\ \\mADthree\n \\end{array}\n $};\n \\node (res) at (9,0) {Responder};\n \\node[below=0.5em of res,fill=white] {$\n \\begin{array}{c}\n \\text{Knows}\\ $g$,\\ \\mCredr,\\ \\mLtkr, \\ \\mIdcredr,\\\\\n \\mIdcredi, \\mADtwo\n \\end{array}$};\n \\action{4.5em}{ini}{Generates \\mMethod,\\ \\mSuites,\\ \\mCi,\\ $x$\\\\$\\mGx = g^{x}$};\n \\msg{9em}{ini}{res}{\\mMsgone: \\mMethod, \\mSuites, \\mGx, \\mCi, \\mADone};\n \\action{9.5em}{res}{$\n \\begin{array}{c}\n \\text{Generates } \\mCr,\\ $y$\\\\\n \\mGy = g^{y}\\\\\n \\mTHtwo = \\mHash(\\mMsgone, \\langle \\mCi, \\mGy, \\mCr \\rangle)\\\\\n \\mPRKtwo = \\mHkdfExtract(\\textrm{``\\phantom{}''}, g^{xy}) \\\\\n \\mGrx = \\mGx^{\\mLtkr} \\\\\n \\mPRKthree = \\mHkdfExtract(\\mPRKtwo, \\mGrx) \\\\\n \\mKtwom = \\mHkdfExpand(\\mPRKthree, \\mTHtwo) \\\\\n \\mMactwo = \\mAead(\\mKtwom; \\langle \\mIdcredr, \\mTHtwo, \\mCredr, \\mADtwo \\rangle; \\textrm{``\\phantom{}''}) \\\\\n \\mKtwoe = \\mHkdfExpand(\\mPRKtwo, \\mTHtwo)\n \\end{array}$};\n \\msg{24em}{res}{ini}{\\mMsgtwo: \\mCi, \\mGy, \\mCr, $\\overbrace{\\mKtwoe\\ \\mXor\\ \\langle \\mIdcredr, \\mMactwo, \\mADtwo \\rangle}^{\\mCipher}$};\n \\action{25em}{ini}{$\n \\begin{array}{c}\n %\\mTHtwo = \\mHash(\\mMsgone, \\langle \\mCi, \\mGy, \\mCr \\rangle) \\\n \\mPRKtwo = \\mHkdfExtract(\\textrm{``\\phantom{}''}, g^{xy}) \\\\\n %\\mKtwoe = \\mHkdfExpand(\\mPRKtwo,\\mTHtwo)\\\\\n \\mGrx = \\mCredr^{x} \\\\\n \\mPRKfour = \\mPRKthree = \\mHkdfExtract(\\mPRKtwo, \\mGrx) \\\\\n %\\mKtwom = \\mHkdfExpand(\\mPRKthree, \\mTHtwo) \\\\\n \\mKthreeae = \\mHkdfExpand(\\mPRKthree, \\mTHtwo) \\\\\n \\mTHthree = \\mHash(\\mTHtwo, \\mCipher, \\mCr)\\\\\n \\mKthreem = \\mHkdfExpand(\\mPRKfour, \\mTHthree) \\\\\n \\mMacthree = \\mAead(\\mKthreem; \\langle \\mIdcredi, \\mTHthree, \\mCredi, \\mADthree \\rangle; \\textrm{``\\phantom{}''}) \\\\\n \\mSigthree = \\mSign(\\mLtki; \\langle \\mIdcredi, \\mTHthree, \\mCredi, \\mADthree \\rangle, \\mMacthree \\rangle)\n \\end{array}$};\n \\msg{37em}{ini}{res}{$\\mMsgthree: \\mCr, \\mAead(\\mKthreeae; \\mTHthree; \\langle \\mIdcredi, \\mSigthree, \\mADthree \\rangle$)};\n \\action{37.5em}{res}{$\n \\begin{array}{c}\n \\mTHthree = \\mHash(\\mTHtwo, \\mCipher, \\mCr)\\\\\n \\mKthreem = \\mHkdfExpand(\\mPRKthree, \\mTHthree) \\\\\n \\mKthreeae = \\mHkdfExpand(\\mPRKthree, \\mTHthree)\n \\end{array}$};\n \\draw [line width=1mm] (-2,-15.5) -- (2,-15.5);\n \\draw [line width=1mm] (7,-15.5) -- (11,-15.5);\n \\end{tikzpicture}}\n \\caption{The \\mSigStat{} method; (\\mCredi{}, \\mLtki), and\n (\\mCredr{}, \\mLtkr{}) are public-private key pairs; $\\mSign(k; x)$ is\n used to denote the signing of message $x$ using key $k$}\n\\label{fig:edhocsigstat}\n\\end{figure}\n%\n\n%------------------------------------------------------------------------- sub\n\\paragraph{\\mStatSig}\nThis method mirrors the \\mSigStat{} method.\n%\nThe responder runs \\mSig{} and creates \\mAuthr{} as a signature over MAC,\nwhile the initiator runs \\mStat{}.\n%\nThis is illustrated in Figure~\\ref{fig:edhocstatsig}. \\mCredr{} and \\mLtkr{}\nmust be signature keys.\n%\n\n\\begin{figure}[h]\n\\centering\n\\linespread{1}\n\\scalebox{.7}{\n\\tikzset{>=latex, every msg/.style={draw=thick}, every node/.style={fill=none,text=black}}\n\\begin{tikzpicture}\n \\node (ini) at (0, 0) {Initiator};\n \\draw [very thick] (0, -0.5) -- (0,-15.5);\n \\draw [very thick] (9, -0.5) -- (9,-15.5);\n \\node[below=0.5em of ini,fill=white,text=black] {$\n \\begin{array}{c}\n \\text{Knows}\\ $g$,\\ \\mCredi,\\ \\mLtki,\\ \\mIdcredi,\\\\\n \\mIdcredr, \\mADone,\\ \\mADthree\n \\end{array}\n $};\n \\node (res) at (9,0) {Responder};\n \\node[below=0.5em of res,fill=white] {$\n \\begin{array}{c}\n \\text{Knows}\\ $g$,\\ \\mCredr,\\ \\mLtkr,\\ \\mIdcredr,\\\\\n \\mIdcredi, \\mADtwo\n \\end{array}$};\n \\action{4.5em}{ini}{Generates \\mMethod,\\ \\mSuites,\\ \\mCi,\\ $x$\\\\$\\mGx = g^{x}$};\n \\msg{8.5em}{ini}{res}{\\mMsgone: \\mMethod, \\mSuites, \\mGx, \\mCi, \\mADone};\n \\action{9.5em}{res}{$\n \\begin{array}{c}\n \\text{Generates } \\mCr,\\ $y$\\\\\n \\mGy = g^{y}\\\\\n \\mTHtwo = \\mHash(\\mMsgone, \\langle \\mCi, \\mGy, \\mCr \\rangle)\\\\\n \\mPRKthree = \\mPRKtwo = \\mHkdfExtract(\\textrm{``\\phantom{}''}, g^{xy}) \\\\\n \\mKtwom = \\mHkdfExpand(\\mPRKthree, \\mTHtwo) \\\\\n \\mMactwo = \\mAead(\\mKtwom; \\langle \\mIdcredr, \\mTHtwo, \\mCredr, \\mADtwo \\rangle; \\textrm{``\\phantom{}''}) \\\\\n \\mSigtwo = \\mSign(\\mLtkr; \\langle \\langle \\mIdcredr, \\mTHtwo, \\mCredr, \\mADtwo \\rangle, \\mMactwo \\rangle)\\\\\n \\mKtwoe = \\mHkdfExpand(\\mPRKtwo, \\mTHtwo)\n \\end{array}$};\n \\msg{23em}{res}{ini}{\\mMsgtwo: \\mCi, \\mGy, \\mCr, $\\overbrace{\\mKtwoe\\ \\mXor\\ \\langle \\mIdcredr, \\mSigtwo, \\mADtwo \\rangle}^{\\mCipher}$};\n \\action{24em}{ini}{$\n \\begin{array}{c}\n \\mPRKthree = \\mPRKtwo = \\mHkdfExtract(\\textrm{``\\phantom{}''}, g^{xy}) \\\\\n \\mGiy = \\mGy^{\\mLtki} \\\\\n \\mPRKfour = \\mHkdfExtract(\\mPRKthree, \\mGiy) \\\\\n \\mTHthree = \\mHash(\\mTHtwo, \\mCipher, \\mCr)\\\\\n \\mKthreem = \\mHkdfExpand(\\mPRKfour, \\mTHthree) \\\\\n \\mMacthree = \\mAead(\\mKthreem; \\langle \\mIdcredi, \\mTHthree, \\mCredi, \\mADthree \\rangle; \\textrm{``\\phantom{}''}) \\\\\n \\mKthreeae = \\mHkdfExpand(\\mPRKthree, \\mTHthree) \\\\\n \\end{array}$};\n \\msg{34.7em}{ini}{res}{$\\mMsgthree: \\mCr, \\mAead(\\mKthreeae; \\mTHthree; \\langle \\mIdcredi, \\mMacthree, \\mADthree \\rangle$)};\n \\action{35.2em}{res}{$\n \\begin{array}{c}\n \\mGiy = \\mCredi^{y} \\\\\n \\mPRKfour = \\mHkdfExtract(\\mPRKthree, \\mGiy) \\\\\n \\mTHthree = \\mHash(\\mTHtwo, \\mCipher, \\mCr)\\\\\n \\mKthreem = \\mHkdfExpand(\\mPRKfour, \\mTHthree) \\\\\n \\mKthreeae = \\mHkdfExpand(\\mPRKthree, \\mTHthree)\n \\end{array}$};\n \\draw [line width=1mm] (-2,-15.5) -- (2,-15.5);\n \\draw [line width=1mm] (7,-15.5) -- (11,-15.5);\n \\end{tikzpicture}}\n\\caption{The \\mStatSig{} method of \\mEdhoc}\n\\label{fig:edhocstatsig}\n\\end{figure}\n%\n\n\\paragraph{\\mStatStat}\nBoth the initiator and the responder use the \\mStat{}\nauthentication method.\n%\nBoth parties' secret static long-term DH keys feed into the key hierarchy.\n%\nThe initiator computes authentication data using the \\mAead{} transform\nand includes that in the third message for the responder to verify.\n%\n\n%------------------------------------------------------------------------- sub\n\\subsubsection{\\mSigSig}\nBoth parties run \\mSig{} and authenticate with signatures.\n%\nAs mentioned earlier, \\mSigSig{} is very closely modeled on \\mSigmaI{}, but\nthere are some notable differences.\n%\nFor example, \\mEdhoc{} aims to provide some degree of identity protection for\nresponders, and therefore uses the idea from \\mSigmaI{} of encrypting the\nresponder identifier \\mIdcredr{} (and other items) in the second message.\n%\nThe designers of \\mEdhoc{} consider it wasteful adding a second MAC in addition\nto the already included \\mMactwo{}, to limit bandwidth consumption.\n%\n\\mEdhoc{} applies XOR encryption, with \\mHkdf{} being used to generate the\nkey stream, whereas \\mSigma{} assumes authenticated encryption for this\npurpose (see Section 5.2 of~\\cite{sigma}).\n%\nBecause \\mSigSig{} has been analyzed in~\\cite{DBLP:conf/secsr/BruniJPS18}, we\ndo not focus on it here.\n%\nHowever, we model it and verify its properties as carefully as for the other methods.\n\n\n%------------------------------------------------------------------------- sub\n\\subsection{Negotiating a cipher suite and method and correlation parameters}\n\\label{sec:ciphersuite}\nRecall that we mentioned that the first message contains a list of cipher suites, ranked according to the preference of the initiator. What does a cipher suite actually contain? An \\mEdhoc{} cipher suite consists of an ordered set of \\mCose{} algorithms: an \\mAead{} algorithm, a hash algorithm, an ECDH curve, a signature algorithm, a signature algorithm curve, an application \\mAead{} algorithm, and an application hash algorithm from the \\mCose{} Algorithms and Elliptic Curves registries. \n\nThere are four supported cipher suites in \\mEdhoc{} -- we refer the reader to Section 3.4 of~\\cite{selander-lake-edhoc-01} for the specifics of the algorithms allowed therein. Each cipher suite is identified by one of four predefined integer labels (0--3). Some algorithms are not used in some methods. The signature algorithm and the signature algorithm curve are not used in methods without signature authentication (i.e. in \\mPskPsk{} and \\mStatStat).\n\nIn order to keep the presentation clean, we have omitted the cipher suite negotiation process from the description of the methods. However, this process happens as follows, at the beginning of every method, once the responder receives the first message. The initiator proposes an ordered list of cipher suites they support. This list presented in descending order to the responder who either accepts the topmost entry in this list (if they also support that suite) or makes a counter-proposal, namely the topmost entry which they support from the remaining part of the list. If there is no such entry the responder can reject, and the protocol does not continue. Similarly, the responder can reject the initiator's choices for the method and correlation parameters as well -- in the case of a reject for either of these values, the protocol aborts.\n\n%------------------------------------------------------------------------- sub\n\\subsection{Claimed Security Properties}\n\\label{sec:claimedProperties}\n \nWe present the security properties that the authors\nof the \\mSpec{}~\\cite{selander-lake-edhoc-01} claim \\mEdhoc{} satisfies.\n%\nMany of the claims are imprecisely expressed.\n%\nWe will revisit these claims when we discuss the formal modeling and\nverification of \\mEdhoc{} in Section~\\ref{sec:formalization} and in the\ndiscussions in Section~\\ref{sec:discussion}.\n%\nThese are our interpretations of the claimed security properties described in\nthe \\mSpec~\\cite{selander-lake-edhoc-01}, Section~8.1:\n\\begin{itemize}\n \\item Perfect Forward Secrecy (\\textbf{PFS}) for the session key material\n \\item Mutual authentication (this presumably refers to entity authentication\n because it is followed by claims of\n \\textbf{consistency} (defined in~\\cite{sigma}),\n \\textbf{aliveness}, and\n \\textbf{peer awareness} to the responder, but not to the initiator)\n \\item \\textbf{Identity protection} (the initiator against active attacks\n and the responder against passive attacks, except for \\mPskPsk{})\n \\item Key Compromise Impersonation (\\textbf{KCI}) resistance\n \\item A single session of \\mEdhoc{} enables the responder to verify\n that the selected cipher suite is the most preferred of the\n initiator which is supported by both parties, even though there is\n no negotiation of cipher suites per se.\n \\item \\textbf{Session key independence}\n\\end{itemize}\n\n", "meta": {"hexsha": "bc93a0eb08840723d3d66118cf64ccf77620090d", "size": 26744, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "models/edhoc/draftedhoc-20200301/report/techreport/edhocProtocol.tex", "max_stars_repo_name": "hoheinzollern/EDHOC-Verification", "max_stars_repo_head_hexsha": "b62bb5192021b9cee52845943ba0c1999cb84119", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "models/edhoc/draftedhoc-20200301/report/techreport/edhocProtocol.tex", "max_issues_repo_name": "hoheinzollern/EDHOC-Verification", "max_issues_repo_head_hexsha": "b62bb5192021b9cee52845943ba0c1999cb84119", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "models/edhoc/draftedhoc-20200301/report/techreport/edhocProtocol.tex", "max_forks_repo_name": "hoheinzollern/EDHOC-Verification", "max_forks_repo_head_hexsha": "b62bb5192021b9cee52845943ba0c1999cb84119", "max_forks_repo_licenses": ["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.9868421053, "max_line_length": 848, "alphanum_fraction": 0.6736090338, "num_tokens": 8306, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.3276683008207139, "lm_q1q2_score": 0.1929603008504827}}
{"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% GEANT manual in LaTeX form %\n% %\n% Version 1.00 %\n% %\n% Last Mod. 12 June 1993 18:20 MG %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\Origin{G.N.Patrick}\n\\Version{Geant 3.16}\\Routid{PHYS400}\n\\Submitted {30.03.82} \\Revised{16.12.93}\n\\Makehead{Simulation of particle decays in flight}\n\\section{Subroutines}\n\\Shubr{GDECAY}{}\n \n\\Rind{GDECAY} is the control routine for the simulation of particle\ndecays in flight. For a given parent particle it selects from a list a\ntwo- or three-body decay mode using the known branching ratios and calls the\nroutines needed to generate the vertex and secondary tracks.\nIt used the following input and output:\n\\begin{DLtt}{MMMMMMM}\n\\item[input:] via common blocks \\FCind{/GCTRAK/} and \\FCind{/GCKINE/}\n\\item[output:] via common block \\FCind{/GCKING/}\n\\end{DLtt}\n\\Rind{GDECAY} is called by the tracking routines.\nIt calls the subroutines \n\\Rind{GDECA2} for two-body decay, \\Rind{GDECA3} for three-body decay,\n\\Rind{GLOREN} for Lorentz transformation and \\Rind{GDROT} for rotation.\nFor the documentation of \\Rind{GLOREN} and \\Rind{GDROT}, see {\\tt [PHYS410]}.\n\\Shubr{GDECA2}{(XM0,XM1,XM2,PCM)}\n\\begin{DLtt}{MMMMMMMM}\n\\item[XM0] ({\\tt REAL}) mass of the parent particle\n\\item[XM1] ({\\tt REAL}) mass of the first decay product\n\\item[XM2] ({\\tt REAL}) mass of the second decay product\n\\item[PCM(3,4)] ({\\tt REAL}) array containing the four-vectors of\nthe decay products\n\\end{DLtt}\n{\\tt GDECA2} simulates the two-body decay with isotropic angular\ndistribution in the center-of-mass system. It is called from\n{\\tt GDECAY}.\n\\Shubr{GDECA3}{(XM0,XM1,XM2,XM3,PCM)}\n\\begin{DLtt}{MMMMMMMM}\n\\item[XM0] ({\\tt REAL}) mass of the parent particle\n\\item[XM1] ({\\tt REAL}) mass of the first decay product\n\\item[XM2] ({\\tt REAL}) mass of the second decay product\n\\item[XM3] ({\\tt REAL}) mass of the third decay product\n\\item[PCM(3,4)] ({\\tt REAL}) array containing the four-vectors of\nthe decay products\n\\end{DLtt}\n{\\tt GDECA3} simulates the three-body decay \nwith isotropic angular distribution in the center-of-mass system.\nIt is called from {\\tt GDECAY}.\n\n\\section{Method}\n\\begin{itemize}\n\\item\nUpon entry to \\Rind{GDECAY} a binary search is made in a list of\nparent particles. This list is stored in the {\\tt JPART} structure\nand currently contains the particles defined in \\Rind{GPART}\n{\\tt [CONS300]}. If the current particle cannot be found in the list,\ncontrol is returned {\\it without} any decay generation.\nUp to six decay modes and their corresponding branching ratios are then\nextracted from the {\\tt JPART} data banks (see {\\tt [CONS310]}).\n\\item\nA decay channel is selected according to the branching ratios.\nIf the sum\nof the branching ratios for a particle is not equal 100\\%, it is\npossible that {\\it no} decay is selected.\n\\item\nDepending on whether the two- or three-body decay is selected, either\n\\Rind{GDECA2} or \\Rind{GDECA3} is called to generate the\nfour-momenta of the decay products with isotropic angular\ndistribution in the center-of-mass system.\n\\item\nThe momentum vectors of the decay products \nare transformed into the laboratory \nsystem and rotated back into the {\\tt GEANT} coordinate frame.\nThe kinematics of the products is stored in the common \\FCind{/GCKING/}.\n\\item\nWhen a particle decays and no branching ratio is defined, then\n\\Rind{GDECAY}\ncalls the user routine \\Rind{GUDCAY}.\n\\end{itemize}\n", "meta": {"hexsha": "ea8be3820765bc8722ee23e7e4257b4114bccc7c", "size": 3824, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "geant/phys400.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": "geant/phys400.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": "geant/phys400.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.9882352941, "max_line_length": 77, "alphanum_fraction": 0.64958159, "num_tokens": 1021, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7090191337850933, "lm_q2_score": 0.2720245569956929, "lm_q1q2_score": 0.1928706157693599}}
{"text": "\\documentclass[modern]{aastex61}\n\\usepackage{graphicx}\n\\usepackage{grffile}\n\\usepackage{xcolor}\n\\usepackage[sort&compress]{natbib}\n\\usepackage[hang,flushmargin]{footmisc}\n\\usepackage{amsmath}\n\n% units macros\n\\newcommand{\\unit}[1]{\\mathrm{#1}}\n\\newcommand{\\km}{\\unit{km}}\n\\newcommand{\\m}{\\unit{m}}\n\\newcommand{\\s}{\\unit{s}}\n\\newcommand{\\kms}{\\km\\,\\s^{-1}}\n\\newcommand{\\ms}{\\m\\,\\s^{-1}}\n\\newcommand{\\ang}{\\text{\\normalfont\\AA}}\n\n% math macros\n\\newcommand{\\dd}{\\mathrm{d}}\n\\newcommand{\\T}{^{\\mathsf{T}}}\n\n% text macros\n\\newcommand{\\todo}[1]{\\textcolor{red}{#1}} % gotta have \\usepackage{xcolor} in main doc or this won't work\n\\newcommand{\\acronym}[1]{{\\small{#1}}}\n\\newcommand{\\project}[1]{\\textsl{#1}}\n\\newcommand{\\RV}{\\acronym{RV}}\n\\newcommand{\\CRLB}{\\acronym{CRLB}}\n\n\\setlength{\\parindent}{1.4em} % trust in Hogg\n\n\\shorttitle{is spectro-perfectionism perfect?}\n\\shortauthors{smartasses}\n\n\\begin{document}\\sloppy\\sloppypar\\raggedbottom\\frenchspacing % trust in Hogg\n\\graphicspath{ {figures/} }\n\\DeclareGraphicsExtensions{.pdf,.eps,.png}\n\n\\title{How perfect is spectro-perfectionism, really?}\n\n\\begin{abstract}\\noindent\nCurrent spectrograph performance requirements are increasing dramatically with pressure from the exoplanet community for precise radial velocity (\\RV) measurements, the stellar community for detailed chemical abundances, and the cosmology community for intergalactic absorption mapping. \n%Within the exoplanet community, spectrographs and their data reduction pipelines are designed with a primary goal in mind: obtaining the most precise possible. \nIn some cases, design decisions are made at the instrument level to prioritize the capability of obtaining a reliably calibrated one-dimensional extracted spectrum from the two-dimensional raw data without losing much of the encoded information. \nThe concept of \\textsl{spectro-perfectionism} outlines a way to extract spectra with minimal information loss \\todo{(check that they claim this)} from any reasonable spectrograph design, at least in principle. \nIn this work we use \\RV\\ precision as a proxy for the accuracy and information content of an extracted spectrum. \nWe test the performances of traditional optimal extraction and of spectro-perfectionism on simulated spectra under a variety of spectrograph conditions. \nWe find that under [x] conditions, spectro-perfectionism is able to extract precise \\RV s [at/near the Cram\\'er--Rao bound], outperforming optimal extraction [by a factor of...]. \nHowever, both methods begin to fail when [x], suggesting a future need for performing spectroscopic inferences directly in the two-dimensional raw data space.\n\\end{abstract}\n\n\\section{Introduction}\n\nBackground on EPRV instruments and assumptions they make.\n\nBackground on optimal extraction and spectro-perfectionism\n\nWhat we set out to do\n\n\\section{Data Generation}\nGeneral concept is a `photon-based' approach, meaning that a 2D spectrum is generated by repeating the following steps many times:\n\\begin{enumerate}\n \\item select a random position in the input slit/fiber using a PDF that reflects the slit/fiber format.\n \\item select a random wavelength (using the spectral source that we want to simulate as a PDF)\n \\item transformation of the input position to a detector position via a (wavelength-dependent) affine transformation matrix.\nThe matrix represents (part of) the spectrograph optics and adjusting the matrix elements allows to define linear dispersion, the spatial format of the 2D spectrum as well as slit rotation ($\\Theta$), shear and scaling (sx, sy) in dispersion and cross-dispersion direction.\n \\item select a random xy distortion using a Gaussian (for now!) distribution to represent the spectrographs PSF\n \\item bin the resulting detector position into detector pixels\n\\end{enumerate}\nIn equations:\\\\\nUsing\n\n \t\\[\n\tM_{\\lambda} = \\begin{pmatrix} m_{00} & m_{01} & m_{02} \\\\ m_{10} & m_{11} & m_{12} \\\\ m_{20} & m_{21} & m_{22} \\end{pmatrix} \\stackrel{\\text{(affine)}}{=} \\begin{pmatrix} sx \\cdot \\cos(\\Theta) & -sy \\cdot \\sin(\\Theta+shear) & tx \\\\ sx \\cdot \\sin(\\Theta) & sy \\cdot \\cos(\\Theta+shear) & ty \\\\ 0 & 0 & 1 \\end{pmatrix}\n\t\\]\n\nas an affine transformation matrix, we are calculating\n\\begin{equation}\n \\begin{pmatrix} X \\\\ Y \\\\ 1 \\end{pmatrix}_{\\text{detector}} =\n \\begin{pmatrix} m_{00} & m_{01} & tx \\\\ m_{10} & m_{11} & ty \\\\ 0 & 0 & 0 \\end{pmatrix} \\cdot\n \\begin{pmatrix} X \\\\ Y \\\\ 1 \\end{pmatrix}_{\\text{slit}} +\n \\begin{pmatrix} \\Delta X \\\\ \\Delta Y \\\\ 1 \\end{pmatrix}_{\\text{psf}}\n\\end{equation}\nThe simplest case is to have all matrix elements to be constant with wavelength except tx. That is equivalent to having pure linear dispersion and the detector rows\nare perfectly aligned with the echelle orders.\\\\\nIn case a pure analytic function for the slit image is wanted, the slit input vector is replaced by $\\begin{pmatrix} 0 & 0 & 1 \\end{pmatrix}$. \nThen, the matrix multiplication is simply a (wavelength dependent) shift but all spatial slit information come solely from the PSF.\\\\\nThe generated 2D data naturally comes with photon noise, detector readout noise can be added by adding appropriate noise on the binned detector data.\n\\begin{figure}\n \\includegraphics[width=0.49\\textwidth]{img/maroonx_data.png}\n \\includegraphics[width=0.49\\textwidth]{img/simulator_data.png}\n \\caption{Comparison between part of a recorded MaroonX etalon spectrum (left) and simulation data with a similar spectral format and source (right).}\n\\end{figure}\n\nhow the data are generated, what the tunable knobs are, maybe a figure comparing fake data to e.g. MAROON-X test data or HARPS?\n\n\n\n\ndetails on the time-series spectra we generate\n\n\\subsection{Theoretical Information Content}\nsince we're generating the data ourselves, it's possible to calculate the \\CRLB\\ on how much \\RV\\ information is encoded in the spectrograph images.\n\n\\section{Methods}\n\\subsection{Optimal Extraction}\nimplementation details\n\n\\subsection{Spectro-perfectionism}\nimplementation details, with some discussion of the trickiest parts (e.g. getting the A matrix right)\n\n\n\\section{Results \\& Discussion}\nHere's what we get when we run our two methods on data generated under a variety of conditions.\n\nFirst we show that under a variety of spectrograph configurations, even ones where optimal extraction fails, spectro-perfectionism performs well.\n\nThen we address the issues with implementing spectro-perfectionism in the real world: insert reasonable levels of noise into the algorithm and see where/how it breaks.\n\n\\section{Conclusions}\n\nsummarize results: conditions under which spectro-perfectionism is a good option, conditions under which optimal extraction will do, and conditions under which they both break\n\nemphasize that even if both algorithms break, the \\RV\\ content is still in the 2D spectrograph images! future outlook on 2D modeling to get \\RV s WITHOUT extracting a spectrum.\n\n\n\n\\bibliographystyle{apj}\n\\bibliography{}%general,myref,inprep}\n\n\\end{document}", "meta": {"hexsha": "c04c9677d070eab3c839f8d50a09dfb4646828b6", "size": 6987, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "paper/paper.tex", "max_stars_repo_name": "megbedell/spectro-pessimism", "max_stars_repo_head_hexsha": "e3d549287b1023f9790a156afab50551be93222a", "max_stars_repo_licenses": ["MIT"], "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/paper.tex", "max_issues_repo_name": "megbedell/spectro-pessimism", "max_issues_repo_head_hexsha": "e3d549287b1023f9790a156afab50551be93222a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2017-12-09T17:01:34.000Z", "max_issues_repo_issues_event_max_datetime": "2017-12-16T16:59:05.000Z", "max_forks_repo_path": "paper/paper.tex", "max_forks_repo_name": "megbedell/spectro-pessimism", "max_forks_repo_head_hexsha": "e3d549287b1023f9790a156afab50551be93222a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2017-12-10T23:34:32.000Z", "max_forks_repo_forks_event_max_datetime": "2017-12-10T23:34:32.000Z", "avg_line_length": 53.7461538462, "max_line_length": 317, "alphanum_fraction": 0.7665664806, "num_tokens": 1780, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.36296920551961676, "lm_q1q2_score": 0.19281264421804578}}
{"text": "\\documentclass{article}\n\\usepackage[utf8]{inputenc}\n\\usepackage{amsmath}\n\\usepackage{graphicx}\n\n\\usepackage{titling}\n\\usepackage{hyperref}\n\n\\predate{\\par\\large\\centering}\n\\postdate{\\par}\n\n\\title{Gambleswap}\n\\author{Gambleswap Team}\n\\date{March 2022}\n\n\\begin{document}\n\n\\maketitle\n\n\\begin{abstract}\n\nGambleswap is a gambling powered Constant Product Automated Market Making protocol. Liquidity providers will be given \\$GMB as a form of passive income and may enter into a gambling game to bet with their \\$GMBs. Liquidity providers also can lend their LP tokens to those who do not have enough LP tokens for participating in the gambling game, thus, unlocking leveraging the value locked in liquidity pools even more. \nThe chance of winning in the game is proportional to the \\$GMBs each user has put in the game. Also, it's designed to have the ability to control the total supply and price of \\$GMB.\n\n\\end{abstract}\n\n\\section{Decentralized Exchange}\nAs a fork of Uniswap, Gambleswap is, in its core, a decentralized liquidity pool based exchange. Liquidity pools contain a huge amounts of two different assets like $aToken$ and $bToken$. \nUsers can use these pools to swap their $aTokens$ with $bTokens$ or vice versa. The ratio between the amount of token a user deposits and the amount of the token they take out is calculated through an Automated Market Maker (AMM) which will be discussed more later (For more details, see Appendix~\\ref{app:amm}).\nIn Gambleswap, in addition to LP tokens, they also receive \\$GMB. These tokens can be used to participate in the gambling and later moderating the Gambleswap ecosystem.\n\n\\section{Tokenomics}\n\nGambleswap has introduced GMB as the main token for particpation to empower its underlying automated market maker. \nLP token holders will receive \\$GMB as rewards. Later, they can use them to participate in the gambling.\n\n\\subsection{Mint GMB}\n\nA fixed number of \\$GMB is minted in each block. Each liquidity provider will receive a fraction of these tokens which is proportional to the amount of their LP tokens. In order to get these \\$GMBs, the user needs to claim them. When a user $u$ claims that they should receive GMB tokens, the contract calculates the effective number of LP tokens that the user has and then find out their available number of GMB tokens to be minted. Effective LP tokens includes the amount of LP tokens that user holds at the time of calling claim, plus what he already has locked in the gambling game of the last recent 10 rounds, plus what he has lent:\n\n$$\n\\text{ number of GMB tokens } u \\text{ gets in a claim} =\n$$\n$$\n\\text{ GMB to mint per LP token }\n$$\n$$\n\\times \\text{ effective number of LP tokens for the user} u\n$$\n$$\n- \\text{ number of all the GMB tokens that } u \\text{ minted so far}\n$$\n\n% $$\\times (\\frac{\\text{number of } u \\text{'s LP tokens}}{\\text{total LP tokens}})\n% $$\n\nTo make it easier for the users to receive their \\$GMB, the pool contract automatically claims these tokens for them whenever they update their LP token value, i.e. when they deposit liquidity to or withdraw liquidity from the pool.\n\n\n\\subsection{Burn GMB}\nTo be able to control the supply of \\$GMB, the gambling game designed to burns some of the minted tokens on a regularly basis. We will discuss it in more details in the following sections.\n\n\\section{Gambling Game}\nThe gambling game is the powerful core of the enhancements added to Gambleswap's AMM logic. The rules of the game can be basically listed as follows:\n\\begin{itemize}\n \\item Participants send their GMB tokens into the gambling contract. These tokens are accumulated to form our jackpot. They also send their bet values, which is a number they have guessed within a particular interval.\n \\item Participants need to either own some LP tokens of the certain set of liquidity pools (called authorised pools) or borrow them from the LP lending pool to be able to play the game. Their LP tokens are locked during the game, and afterward, they can unlock them regardless of whether they win or lose. This rule intends to motivate users to provide liquidity in our pools.\n \\item A random number is generated using some properties of the block like block number, block difficulty, and block timestamp.\n \\item If the number a user has bet on falls inside a certain distance from the randomly generated number, that user is one of the winners of the game. This distance gets larger depending on the amount of GMB tokens they have deposited into the jackpot.\n \\item 25\\% of the jackpot of each round, and all the accumulated GMBs after every fourth game will be burnt. This is done in order to control the GMB total supply. \n \\item If a game doesn't have any winners, the jackpot's contents remain in the jackpot and will be used in the next round. This motivates users to participate in the game if they see there is a non-empty jackpot before they start the game. Therefore, the number of participants can grow substantially.\n \\item The maximum chance of winning is 50\\%. It means if a player owns all the \\$GMBs in the jackpot, they have a maximum 50\\% chance of winning. \n\\end{itemize}\n\n\\subsection{Determining winners}\nWe introduce a variable as $coveragePerGMB$. This value demonstrates the length of the interval that each GMB token covers. Participants can increase their coverage by having more GMBs in the game. User's coverage shows the maximum distance the user's bet value can have with the correct random number for the user to win. The greater this value, the more chance the user has for winning. This value is calculated as follows. \n\n\\begin{align*}\n \\text{user's coverage} &= min( \\frac{1}{4} \\times \\text{maximum random number}, \\\\\n &coveragePerGMB \\times \\text{user's GMB tokens})\n\\end{align*}\n\nthe $\\frac{1}{4} \\times \\text{maximum random number}$ is there to bound the maximum chance of winning to 50 percent.\n\nUsers have more chance to win by putting more GMB in the jackpot; each user wins if their bet value falls inside this interval:\n$$\n(\\text{correct random number} - \\text{user's coverage},$$\n$$\n\\text{correct random number} + \\text{user's coverage})\n$$\n\nThe $coveragePerGMB$ value in each round is calculated based on the value of the jackpot in the previous game. For the first game, we assume the coveragePerGMB value is 10, and for games after that, we have:\n$$\ncoveragePerGMB = \\frac{\\text{maximum random number}}{\\text{4}\n\\times \\text{total jackpot of the previous game}}\n$$\n\n\nIn the other words the coveragePerGMB is a dynamic value depending on the previous game. In each game, this value is the same for all users. \nIf the number of participants in one game is small, the chance of winning in the next game goes higher; Consequently, more users are encouraged to participate in the next round. Figure \\ref{fig:coverage} illustrates the process of determining the winners.\n\n\n\\begin{figure}\n \\centering\n \\includegraphics[width=\\textwidth]{coverage.png}\n \\caption{The blue interval shows the entire interval the random number can fall into. If the random number falls into the user's coverage, user will be one of the winners.}\n \\label{fig:coverage}\n\\end{figure}\n\n\\subsection{LP Lending}\nGambleswap introduces users a LP lending protocol to participate in gambling game without the need to provide liquidity. There are two user's types in this lending protocol:\n\\begin{itemize}\n \\item Lenders: Users who have LPs can lend their tokens from different pools; In return, after each round of the game, they will be given interest per borrow in form of GMB tokens.\n \\item Borrowers: Users who do not have any LP tokens and can participate in each round of the game by borrowing lenders LP tokens. In return, they have to pay the interest to the lenders.\n\\end{itemize}\n\nEach round of the game has its own capacity on the lending contract, and after each round, the capacity will be released for the upcoming round of the game. Every authorised liquidity pool has a separate lending pool and interest per borrow. Whenever a user attempts to borrow LP token, the lending contract finds the cheapest available pool which has enough capacity, and lends the needed amount of LP token to the user.\nLenders share the accumulated interest of their corresponding pool proportional to their share of the lending pool.\n\n\\subsection{Overflow/Underflow in the interval}\nThe generated interval for each user may exceed the $Maximum Random Number$ or may become less than $zero$. There are three scenarios for an interval:\n\\begin{itemize}\n \\item Overflow: It happens when\n $$CorrectRandomNumber + UserCoverage > MaximumRandomNumber$$ In this scenario, the remaining amount of the user's coverage will be considered from 0 to the OverflowValue. \n \n \\begin{align*}\n \\text{OverflowValue} &= \\text{UserCoverage} \\\\ &+ \\text{CorrectRandomNumber} \\\\ &- \\text{MaxRandomNumber}\n \\end{align*}\n \n Users will win when the below condition holds:\n $$(\\text{betValue} > (\\text{correctRandomNumber} - \\text{UserCoverage})$$\n $$\\lor$$\n $$\n \\text{betValue} < \\text{overflowValue}\n $$\n \n \\item Underflow: This happens when \n $$UnderflowValue = UserInterval - CorrectRandomNumber$$\n Users will win when the below condition holds:\n $$\n (\\text{betValue} > (\\text{maxRandomNumber} - \\text{UnderflowValue}))\n $$\n $$\\lor$$\n $$\n (\\text{betValue} < (\\text{CorrectRandomNumber} + \\text{UserCoverage}))\n $$\n \n Figure \\ref{fig:overflow} shows the coverage of the user in cases of underflow and overflow.\n \n \\item Normal: In this scenario users will win when their $betValue$ is in the below interval:\n $$\n {CorrectRandomNumber \\pm{UserInterval}}\n $$\n\\end{itemize}\n\n\\begin{figure}\n \\centering\n \\includegraphics[width=\\textwidth]{coverage2.png}\n \\caption{User's coverage in underflow and overflow cases.}\n \\label{fig:overflow}\n\\end{figure}\n\n\\subsection{Expected value of net profit}\n\nLet's assume user $u_i$ deposits $a_i$ GBM tokens in the gambling contract. The random number can be between zero and the maximum. Let's assume the maximum is $M$ and the number of participants is $n$ and number of winners is $W$. Also, $\\frac{1}{4}$ of the tokens are burnt.\nTherefore, the probability of $u_i$ being one of the winners is:\n\\begin{equation*}\n p_i = a_i \\times \\frac{1}{4\\times (\\sum_{i = 0}^{n} a_i)_{lastRound}}\n\\end{equation*}\nHence, the expected value of $u_i$'s profit in one round of gambling is:\n\\begin{align*}\n E[profit(u_i)] &= p_i \\times \\frac{3\\sum_{i=0}^{n}a_i}{4W} \\\\\n &=\n a_i \\times \\frac{1}{4\\times (\\sum_{i = 0}^{n} a_i)_{lastRound}} \\times \n \\frac{3\\sum_{i=0}^{n}a_i}{4W} \\\\\n &= \n \\frac{a_i}{16 W} \\times \\frac{3\\sum_{i=0}^{n} a_i}{(\\sum_{i=0}^{n} a_i)_{lastRound}}\n\\end{align*}\n\nAs we see, when the number of players increases in one round in respect to the last round, the probability of winning increases. If we assume the \n$\\frac{\\sum_{i=0}^{n} a_i}{(\\sum_{i=0}^{n} a_i)_{lastRound}}$ factor to be close to one, we can see that \n\n$$\nE[profit(u_i)] \\approx \\frac{3a_i}{16W}\n$$\nSo, the expected net profit of the the $u_i$ is approximately\n$\n\\frac{3a_i}{16W} - a_i\n$.\n\n\\section{Conclusion}\nGambleswap seeks to unlock the hundreds of millions of dollars in value locked in a decentralized exchange. Up until now, the community has shown great enthusiasm toward gambling and lottery games. The economic dynamics behind Gambleswap's gambling game also incentivizes people to provide even more liquidity.\n\n\\pagebreak\n\\appendix\n\\label{app:amm}\n\\section{Automated Market Maker}\nAs mentioned before there are two tokens in each liquidity pool in an AMM-based exchange. The ratio between the amount of one token a user takes out and the amount of the other token the user endows, are calculated using a constant product equation. \nAssume the amounts of the tokens are $R_a$ and $R_b$ before the swap. A user can deposit $x$ tokens of $R_a$ in the pool and take $y$ tokens of $R_b$ out. \nA small portion of $x$ is taken as a fee. This fee is divided between all liquidity providers proportional to their share in the pool. The fee ratio is shown by $\\mu$. Now, because the product of the two tokens amounts should remain equal to $k$, we can calculate $y$ like this:\n\n\\begin{align*}\n R_a R_b &= (R_a + (1 - \\mu)x)(R_b - y) \\\\\n \\to (1 - \\mu)xR_b &= (1 - \\mu)xy + yR_1 \\\\\n \\to y &= R_b - \\frac{R_aR_b}{R_a + (1 - \\mu)x}\n\\end{align*}\n\n\\end{document}\n\n", "meta": {"hexsha": "a3fb1a2b9177029036530b2d0d0c0e1cd94c5fb0", "size": 12456, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "whitepaper/main.tex", "max_stars_repo_name": "Gambleswap/docs", "max_stars_repo_head_hexsha": "a0180e963dd1d1e07e104e414414b1ea17ce5ba2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "whitepaper/main.tex", "max_issues_repo_name": "Gambleswap/docs", "max_issues_repo_head_hexsha": "a0180e963dd1d1e07e104e414414b1ea17ce5ba2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "whitepaper/main.tex", "max_forks_repo_name": "Gambleswap/docs", "max_forks_repo_head_hexsha": "a0180e963dd1d1e07e104e414414b1ea17ce5ba2", "max_forks_repo_licenses": ["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.3142857143, "max_line_length": 638, "alphanum_fraction": 0.747430957, "num_tokens": 3154, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.3738758297482025, "lm_q1q2_score": 0.19277782382564068}}
{"text": "%!TEX root = ../../common/main.tex\n\n\\chapter[\n head={Supplementary material to the measurement of \\sintwobetait},\n tocentry={Supplementary material to the measurement of \\sintwobetabfsfHyperref}\n]\n{Supplementary material to the measurement of \\sintwobetabfsf}\n\\label{ch:app:measurement_of_sin2beta}\n\n% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Decay time resolution and acceptance}\n\\label{sec:app:measurement_of_sin2beta:resolution_and_acceptance}\n\n% ------------------------------------------------------------------------------\n\\subsection{Resolution}\n\\label{sec:app:measurement_of_sin2beta:resolution_and_acceptance:resolution}\n\nFor the \\catDD candidates \n\\cref{tab:app:measurement_of_sin2beta:resolution_and_acceptance:resolution:calibration:dd} \nshows the fit results of the $\\chisq$-fit of the decay time error estimate\ncalibration parameters for a linear function and a parabolic function with\noffset parameter, while\n\\cref{tab:app:measurement_of_sin2beta:resolution_and_acceptance:resolution:calibration:ll} \nincludes fit results for the \\catLL subsample where a linear function and a\nparabolic function without offset parameter are fitted.\n%\n\\begin{table}[h]\n\\centering\n\\caption{Fit parameters of the decay time resolution calibration functions for the \\catDD subsample.}\n\\label{tab:app:measurement_of_sin2beta:resolution_and_acceptance:resolution:calibration:dd}\n \\begin{tabular}{lllr@{$\\,\\pm\\,$}lr@{$\\,\\pm\\,$}l}\n \\toprule\n Model & \\multicolumn{2}{c}{Parameter} & \\multicolumn{2}{c}{narrow width ($i = 1$)} & \\multicolumn{2}{c}{wider width ($i = 2$)}\\\\\n \\midrule\n \\multirow{2}{*}{linear} & $b_{i}$ & & 0.89 & 0.10 & 1.34 & 0.29 \\\\\n & $c_{i}$ & (\\si{\\pico\\second}) & 0.008 & 0.004 & 0.018 & 0.011 \\\\\n \\midrule\n \\multirow{3}{*}{parabolic} & $a_{i}$ & (\\si{\\per\\pico\\second}) & -3 & 6 & -1 & 17 \\\\\n & $b_{i}$ & & 1.2 & 0.5 & 1.4 & 1.4 \\\\\n & $c_{i}$ & (\\si{\\pico\\second}) & 0.003 & 0.010 & 0.016 & 0.028 \\\\\n \\bottomrule\n \\end{tabular}\n\\end{table}\n%\n\\begin{table}[h]\n\\centering\n\\caption{Fit parameters of the decay time resolution calibration functions for the \\catLL subsample.}\n\\label{tab:app:measurement_of_sin2beta:resolution_and_acceptance:resolution:calibration:ll}\n \\begin{tabular}{lllr@{$\\,\\pm\\,$}lr@{$\\,\\pm\\,$}l}\n \\toprule\n Model & \\multicolumn{2}{c}{Parameter} & \\multicolumn{2}{c}{narrow width ($i = 1$)} & \\multicolumn{2}{c}{wider width ($i = 2$)}\\\\\n \\midrule\n \\multirow{2}{*}{linear} & $b_{i}$ & & 1.10 & 0.07 & 1.81 & 0.26 \\\\\n & $c_{i}$ & (\\si{\\pico\\second}) & 0.0034 & 0.0019 & 0.009 & 0.008 \\\\\n \\midrule\n \\multirow{2}{*}{parabolic} & $a_{i}$ & (\\si{\\per\\pico\\second}) & -4.7 & 2.1 & -6 & 8 \\\\\n & $b_{i}$ & & 1.36 & 0.07 & 2.27 & 0.26 \\\\\n \\bottomrule \n \\end{tabular}\n\\end{table}\n\n\\newpage\n% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section[\n head={Measurement of \\CP violation},\n tocentry={Measurement of \\CPHyperref violation}\n]\n{Measurement of \\CPbfsf violation}\n\\label{sec:app:measurement_of_sin2beta:cpv_measurement}\n\n% ------------------------------------------------------------------------------\n\\subsection{Tables of fixed parameters}\n\\label{sec:app:measurement_of_sin2beta:cpv_measurement:fixed_parameters}\n\n\\begin{table}[h]\n\\caption{Fixed mass parameters.}\n\\label{tab:app:measurement_of_sin2beta:cpv_measurement:fixed_parameters:mass}\n\\centering\n\\begin{tabular}{lr@{$\\,\\pm\\,$}l}\n \\toprule\n Parameter & \\multicolumn{2}{c}{Fixed Value} \\\\\n \\midrule\n $\\alpha_{1,m}^\\text{\\catDD}$ & \\multicolumn{2}{c}{$2.28$}\\\\\n $\\alpha_{1,m}^\\text{\\catLL}$ & \\multicolumn{2}{c}{$2.1$}\\\\\n $\\alpha_{2,m}^\\text{\\catDD}$ & \\multicolumn{2}{c}{$2.08$}\\\\\n $\\alpha_{2,m}^\\text{\\catLL}$ & \\multicolumn{2}{c}{$2.43$}\\\\\n $\\lambda_m^\\text{\\catDD}$ & \\multicolumn{2}{c}{$-2.8$}\\\\\n $\\lambda_m^\\text{\\catLL}$ & \\multicolumn{2}{c}{$-3.6$}\\\\\n $\\zeta_m^\\text{\\catDD}$ & \\multicolumn{2}{c}{$0.0$}\\\\\n $\\zeta_m^\\text{\\catLL}$ & \\multicolumn{2}{c}{$0.0$}\\\\\n $n_1^\\text{\\catDD}$ & \\multicolumn{2}{c}{$3.18$}\\\\\n $n_1^\\text{\\catLL}$ & \\multicolumn{2}{c}{$3.2$}\\\\\n $n_2^\\text{\\catDD}$ & \\multicolumn{2}{c}{$6.8$}\\\\\n $n_2^\\text{\\catLL}$ & \\multicolumn{2}{c}{$4.1$}\\\\\n \\bottomrule\n\\end{tabular}\n\\end{table}\n%\n\\begin{table}[h]\n\\caption{Fixed decay time error parameters of the (left) signal and (right)\nbackground parametrisation.}\n\\label{tab:app:measurement_of_sin2beta:cpv_measurement:fixed_parameters:decay_time_error}\n\\centering\n\\begin{tabular}[t]{llr@{$\\,\\pm\\,$}l}\n \\toprule\n \\multicolumn{2}{c}{Parameter} & \\multicolumn{2}{c}{Fixed Value} \\\\\n \\midrule\n $f_{\\sigma_t}^\\text{\\catDD,\\catOS,\\catAU}$ & & \\multicolumn{2}{c}{$0.069461$}\\\\\n $f_{\\sigma_t}^\\text{\\catDD,\\catOS,\\catEB}$ & & \\multicolumn{2}{c}{$0.09431$}\\\\\n $f_{\\sigma_t}^\\text{\\catDD,\\catSS}$ & & \\multicolumn{2}{c}{$0.088404$}\\\\\n $f_{\\sigma_t}^\\text{\\catLL,\\catOS}$ & & \\multicolumn{2}{c}{$0.55165$}\\\\\n $M_1^\\text{\\catDD,\\catOS,\\catAU}$ & ($\\si{\\pico\\second}$) & \\multicolumn{2}{c}{$0.037506$}\\\\\n $M_1^\\text{\\catDD,\\catOS,\\catEB}$ & ($\\si{\\pico\\second}$) & \\multicolumn{2}{c}{$0.034481$}\\\\\n $M_1^\\text{\\catDD,\\catSS}$ & ($\\si{\\pico\\second}$) & \\multicolumn{2}{c}{$0.032577$}\\\\\n $M_2^\\text{\\catDD,\\catOS,\\catAU}$ & ($\\si{\\pico\\second}$) & \\multicolumn{2}{c}{$0.077666$}\\\\\n $M_2^\\text{\\catDD,\\catOS,\\catEB}$ & ($\\si{\\pico\\second}$) & \\multicolumn{2}{c}{$0.072158$}\\\\\n $M_2^\\text{\\catDD,\\catSS}$ & ($\\si{\\pico\\second}$) & \\multicolumn{2}{c}{$0.059685$}\\\\\n $M^\\text{\\catLL,\\catOS}$ & ($\\si{\\pico\\second}$) & \\multicolumn{2}{c}{$0.033253$}\\\\\n $M^\\text{\\catLL,\\catSS}$ & ($\\si{\\pico\\second}$) & \\multicolumn{2}{c}{$0.029475$}\\\\\n $k_1^\\text{\\catDD,\\catOS,\\catAU}$ & & \\multicolumn{2}{c}{$0.721$}\\\\\n $k_1^\\text{\\catDD,\\catOS,\\catEB}$ & & \\multicolumn{2}{c}{$0.73243$}\\\\\n $k_1^\\text{\\catDD,\\catSS}$ & & \\multicolumn{2}{c}{$0.72851$}\\\\\n $k_1^\\text{\\catLL,\\catOS}$ & & \\multicolumn{2}{c}{$0.80445$}\\\\\n $k_2^\\text{\\catDD,\\catOS,\\catAU}$ & & \\multicolumn{2}{c}{$0.73407$}\\\\\n $k_2^\\text{\\catDD,\\catOS,\\catEB}$ & & \\multicolumn{2}{c}{$0.65444$}\\\\\n $k_2^\\text{\\catDD,\\catSS}$ & & \\multicolumn{2}{c}{$0.70283$}\\\\\n $k_2^\\text{\\catLL,\\catOS}$ & & \\multicolumn{2}{c}{$0.70335$}\\\\\n $k^\\text{\\catLL,\\catSS}$ & & \\multicolumn{2}{c}{$0.75457$}\\\\\n \\bottomrule\n\\end{tabular}\n%\n\\quad\n%\n\\begin{tabular}[t]{llr@{$\\,\\pm\\,$}l}\n \\toprule\n \\multicolumn{2}{c}{Parameter} & \\multicolumn{2}{c}{Fixed Value} \\\\\n \\midrule\n $f_{\\sigma_t}^\\text{\\catDD,!(\\catOS,\\catAU)}$ & & \\multicolumn{2}{c}{$0.11432$}\\\\\n $f_{\\sigma_t}^\\text{\\catDD,\\catOS,\\catAU}$ & & \\multicolumn{2}{c}{$0.29076$}\\\\\n $f_{\\sigma_t}^\\text{\\catLL,\\catAU}$ & & \\multicolumn{2}{c}{$0.85159$}\\\\\n $f_{\\sigma_t}^\\text{\\catLL,\\catEB}$ & & \\multicolumn{2}{c}{$0.93631$}\\\\\n $M_1^\\text{\\catDD,!(\\catOS,\\catAU)}$ & ($\\si{\\pico\\second}$) & \\multicolumn{2}{c}{$0.03674$}\\\\\n $M_1^\\text{\\catDD,\\catOS,\\catAU}$ & ($\\si{\\pico\\second}$) & \\multicolumn{2}{c}{$0.037739$}\\\\\n $M_1^\\text{\\catLL,\\catAU}$ & ($\\si{\\pico\\second}$) & \\multicolumn{2}{c}{$0.042243$}\\\\\n $M_1^\\text{\\catLL,\\catEB}$ & ($\\si{\\pico\\second}$) & \\multicolumn{2}{c}{$0.047283$}\\\\\n $M_2^\\text{\\catDD,!(\\catOS,\\catAU)}$ & ($\\si{\\pico\\second}$) & \\multicolumn{2}{c}{$0.072757$}\\\\\n $M_2^\\text{\\catDD,\\catOS,\\catAU}$ & ($\\si{\\pico\\second}$) & \\multicolumn{2}{c}{$0.064157$}\\\\\n $M_2^\\text{\\catLL,\\catAU}$ & ($\\si{\\pico\\second}$) & \\multicolumn{2}{c}{$0.030178$}\\\\\n $M_2^\\text{\\catLL,\\catEB}$ & ($\\si{\\pico\\second}$) & \\multicolumn{2}{c}{$0.029563$}\\\\\n $k_1^\\text{\\catDD,!(\\catOS,\\catAU)}$ & & \\multicolumn{2}{c}{$0.73464$}\\\\\n $k_1^\\text{\\catDD,\\catOS,\\catAU}$ & & \\multicolumn{2}{c}{$0.72987$}\\\\\n $k_1^\\text{\\catLL,\\catAU}$ & & \\multicolumn{2}{c}{$0.69218$}\\\\\n $k_1^\\text{\\catLL,\\catEB}$ & & \\multicolumn{2}{c}{$0.59111$}\\\\\n $k_2^\\text{\\catDD,!(\\catOS,\\catAU)}$ & & \\multicolumn{2}{c}{$0.68463$}\\\\\n $k_2^\\text{\\catDD,\\catOS,\\catAU}$ & & \\multicolumn{2}{c}{$0.67792$}\\\\\n $k_2^\\text{\\catLL,\\catAU}$ & & \\multicolumn{2}{c}{$0.77259$}\\\\\n $k_2^\\text{\\catLL,\\catEB}$ & & \\multicolumn{2}{c}{$0.78276$}\\\\\n \\bottomrule\n\\end{tabular}\n\\end{table}\n%\n\\begin{table}[h]\n\\caption{Fixed \\OS mistag spline parameters for the (left) signal and (right)\nbackground parametrisation.}\n\\label{tab:app:measurement_of_sin2beta:cpv_measurement:fixed_parameters:eta:os}\n\\centering\n\\begin{tabular}[t]{lr@{$\\,\\pm\\,$}l}\n \\toprule\n Parameter & \\multicolumn{2}{c}{Fixed Value} \\\\\n \\midrule\n $u_{S,1}^\\text{\\catOS}$ & \\multicolumn{2}{c}{$0.0$}\\\\\n $u_{S,2}^\\text{\\catOS}$ & \\multicolumn{2}{c}{$0.50758$}\\\\\n $u_{S,3}^\\text{\\catOS}$ & \\multicolumn{2}{c}{$3.0879$}\\\\\n $u_{S,4}^\\text{\\catOS}$ & \\multicolumn{2}{c}{$3.7690$}\\\\\n $u_{S,5}^\\text{\\catOS}$ & \\multicolumn{2}{c}{$12.776$}\\\\\n $u_{S,6}^\\text{\\catOS}$ & \\multicolumn{2}{c}{$9.2243$}\\\\\n $u_{S,7}^\\text{\\catOS}$ & \\multicolumn{2}{c}{$26.375$}\\\\\n $u_{S,8}^\\text{\\catOS}$ & \\multicolumn{2}{c}{$29.490$}\\\\\n $u_{S,9}^\\text{\\catOS}$ & \\multicolumn{2}{c}{$39.154$}\\\\\n $u_{S,10}^\\text{\\catOS}$ & \\multicolumn{2}{c}{$39.090$}\\\\\n $u_{S,11}^\\text{\\catOS}$ & \\multicolumn{2}{c}{$34.295$}\\\\\n \\bottomrule\n\\end{tabular}\n%\n\\qquad\n%\n\\begin{tabular}[t]{lr@{$\\,\\pm\\,$}l}\n \\toprule\n Parameter & \\multicolumn{2}{c}{Fixed Value} \\\\\n \\midrule\n $u_{B,1}^\\text{\\catDD,\\catOS}$ & \\multicolumn{2}{c}{$0.0$}\\\\\n $u_{B,2}^\\text{\\catDD,\\catOS}$ & \\multicolumn{2}{c}{$0.25646$}\\\\\n $u_{B,3}^\\text{\\catDD,\\catOS}$ & \\multicolumn{2}{c}{$2.8381$}\\\\\n $u_{B,4}^\\text{\\catDD,\\catOS}$ & \\multicolumn{2}{c}{$5.0101$}\\\\\n $u_{B,5}^\\text{\\catDD,\\catOS}$ & \\multicolumn{2}{c}{$19.184$}\\\\\n $u_{B,6}^\\text{\\catDD,\\catOS}$ & \\multicolumn{2}{c}{$12.047$}\\\\\n $u_{B,7}^\\text{\\catDD,\\catOS}$ & \\multicolumn{2}{c}{$42.811$}\\\\\n $u_{B,8}^\\text{\\catDD,\\catOS}$ & \\multicolumn{2}{c}{$53.376$}\\\\\n $u_{B,9}^\\text{\\catDD,\\catOS}$ & \\multicolumn{2}{c}{$59.998$}\\\\\n $u_{B,10}^\\text{\\catDD,\\catOS}$ & \\multicolumn{2}{c}{$67.425$}\\\\\n $u_{B,11}^\\text{\\catDD,\\catOS}$ & \\multicolumn{2}{c}{$64.236$}\\\\\n $u_{B,1}^\\text{\\catLL,\\catOS}$ & \\multicolumn{2}{c}{$0.0$}\\\\ \n $u_{B,2}^\\text{\\catLL,\\catOS}$ & \\multicolumn{2}{c}{$0.96109$}\\\\ \n $u_{B,3}^\\text{\\catLL,\\catOS}$ & \\multicolumn{2}{c}{$10.005$}\\\\ \n $u_{B,4}^\\text{\\catLL,\\catOS}$ & \\multicolumn{2}{c}{$13.055$}\\\\ \n $u_{B,5}^\\text{\\catLL,\\catOS}$ & \\multicolumn{2}{c}{$65.181$}\\\\ \n $u_{B,6}^\\text{\\catLL,\\catOS}$ & \\multicolumn{2}{c}{$33.077$}\\\\ \n $u_{B,7}^\\text{\\catLL,\\catOS}$ & \\multicolumn{2}{c}{$161.56$}\\\\ \n $u_{B,8}^\\text{\\catLL,\\catOS}$ & \\multicolumn{2}{c}{$163.82$}\\\\ \n $u_{B,9}^\\text{\\catLL,\\catOS}$ & \\multicolumn{2}{c}{$244.14$}\\\\ \n $u_{B,10}^\\text{\\catLL,\\catOS}$ & \\multicolumn{2}{c}{$238.57$}\\\\ \n $u_{B,11}^\\text{\\catLL,\\catOS}$ & \\multicolumn{2}{c}{$259.16$}\\\\ \n \\bottomrule\n\\end{tabular}\n\\end{table}\n%\n\\begin{table}[h]\n\\caption{Fixed \\SSpi mistag spline parameters for the (left) signal and (right)\nbackground parametrisation.}\n\\label{tab:app:measurement_of_sin2beta:cpv_measurement:fixed_parameters:eta:ss}\n\\centering\n\\begin{tabular}[t]{lr@{$\\,\\pm\\,$}l}\n \\toprule\n Parameter & \\multicolumn{2}{c}{Fixed Value} \\\\\n \\midrule\n $u_{S,1}^\\text{\\catDD,\\catSS}$ & \\multicolumn{2}{c}{$0.0$}\\\\\n $u_{S,2}^\\text{\\catDD,\\catSS}$ & \\multicolumn{2}{c}{$0.0$}\\\\\n $u_{S,3}^\\text{\\catDD,\\catSS}$ & \\multicolumn{2}{c}{$0.0402$}\\\\\n $u_{S,4}^\\text{\\catDD,\\catSS}$ & \\multicolumn{2}{c}{$0.2597$}\\\\\n $u_{S,5}^\\text{\\catDD,\\catSS}$ & \\multicolumn{2}{c}{$0.4804$}\\\\\n $u_{S,6}^\\text{\\catDD,\\catSS}$ & \\multicolumn{2}{c}{$0.6534$}\\\\\n $u_{S,1}^\\text{\\catLL,\\catSS}$ & \\multicolumn{2}{c}{$0.0$}\\\\\n $u_{S,2}^\\text{\\catLL,\\catSS}$ & \\multicolumn{2}{c}{$0.0$}\\\\\n $u_{S,3}^\\text{\\catLL,\\catSS}$ & \\multicolumn{2}{c}{$0.013$}\\\\\n $u_{S,4}^\\text{\\catLL,\\catSS}$ & \\multicolumn{2}{c}{$0.1183$}\\\\\n $u_{S,5}^\\text{\\catLL,\\catSS}$ & \\multicolumn{2}{c}{$0.2695$}\\\\\n $u_{S,6}^\\text{\\catLL,\\catSS}$ & \\multicolumn{2}{c}{$0.4455$}\\\\\n \\bottomrule\n\\end{tabular}\n%\n\\qquad\n%\n\\begin{tabular}[t]{lr@{$\\,\\pm\\,$}l}\n \\toprule\n Parameter & \\multicolumn{2}{c}{Fixed Value} \\\\\n \\midrule\n $u_{B,1}^\\text{\\catDD,\\catSS}$ & \\multicolumn{2}{c}{$0.0$}\\\\\n $u_{B,2}^\\text{\\catDD,\\catSS}$ & \\multicolumn{2}{c}{$0.0$}\\\\\n $u_{B,3}^\\text{\\catDD,\\catSS}$ & \\multicolumn{2}{c}{$0.1498$}\\\\\n $u_{B,4}^\\text{\\catDD,\\catSS}$ & \\multicolumn{2}{c}{$0.8688$}\\\\\n $u_{B,5}^\\text{\\catDD,\\catSS}$ & \\multicolumn{2}{c}{$1.9698$}\\\\\n $u_{B,6}^\\text{\\catDD,\\catSS}$ & \\multicolumn{2}{c}{$5.3155$}\\\\\n $u_{B,1}^\\text{\\catLL,\\catSS}$ & \\multicolumn{2}{c}{$0.0$}\\\\\n $u_{B,2}^\\text{\\catLL,\\catSS}$ & \\multicolumn{2}{c}{$0.0$}\\\\\n $u_{B,3}^\\text{\\catLL,\\catSS}$ & \\multicolumn{2}{c}{$0.0022$}\\\\\n $u_{B,4}^\\text{\\catLL,\\catSS}$ & \\multicolumn{2}{c}{$0.1173$}\\\\\n $u_{B,5}^\\text{\\catLL,\\catSS}$ & \\multicolumn{2}{c}{$0.4442$}\\\\\n $u_{B,6}^\\text{\\catLL,\\catSS}$ & \\multicolumn{2}{c}{$1.2042$}\\\\\n \\bottomrule\n\\end{tabular}\n\\end{table}\n%\n\\begin{table}[h]\n\\caption{Fixed decay time resolution parameters}\n\\label{tab:app:measurement_of_sin2beta:cpv_measurement:fixed_parameters:decay_time_resolution}\n\\centering\n\\begin{tabular}[t]{lr@{$\\,\\pm\\,$}l}\n \\toprule\n Parameter & \\multicolumn{2}{c}{Fixed Value} \\\\\n \\midrule\n $c_1^\\text{\\catDD}$ & \\multicolumn{2}{c}{$0.0077$}\\\\\n $c_1^\\text{\\catLL}$ & \\multicolumn{2}{c}{$0.0045$}\\\\\n $c_2^\\text{\\catDD}$ & \\multicolumn{2}{c}{$0.019$}\\\\\n $c_2^\\text{\\catLL}$ & \\multicolumn{2}{c}{$0.007$}\\\\\n $g_2^\\text{\\catDD}$ & \\multicolumn{2}{c}{$0.251$}\\\\\n $g_2^\\text{\\catLL}$ & \\multicolumn{2}{c}{$0.24$}\\\\\n $\\mu_t^\\text{\\catDD}$ & \\multicolumn{2}{c}{$0.0$}\\\\\n $\\mu_t^\\text{\\catLL}$ & \\multicolumn{2}{c}{$0.0$}\\\\\n $b_1^\\text{\\catDD}$ & \\multicolumn{2}{c}{$0.88$}\\\\\n $b_1^\\text{\\catLL}$ & \\multicolumn{2}{c}{$1.04$}\\\\\n $b_2^\\text{\\catDD}$ & \\multicolumn{2}{c}{$1.33$}\\\\\n $b_2^\\text{\\catLL}$ & \\multicolumn{2}{c}{$1.8$}\\\\\n $\\sigma_\\text{\\acs*{PV}}^\\text{\\catDD}$ & \\multicolumn{2}{c}{$1.6$}\\\\\n $\\sigma_\\text{\\acs*{PV}}^\\text{\\catLL}$ & \\multicolumn{2}{c}{$1.40$}\\\\\n $f_\\text{\\acs*{PV}}^\\text{\\catDD}$ & \\multicolumn{2}{c}{$0.048$}\\\\\n $f_\\text{\\acs*{PV}}^\\text{\\catLL}$ & \\multicolumn{2}{c}{$0.0488$}\\\\\n \\bottomrule\n\\end{tabular}\n\\end{table}\n%\n\\begin{table}[h]\n\\caption{Fixed \\catAU acceptance spline parameters for (left) \\catAU and (right)\n\\catEB candidates.}\n\\label{tab:app:measurement_of_sin2beta:cpv_measurement:fixed_parameters:acc}\n\\centering\n\\begin{tabular}[t]{lr@{$\\,\\pm\\,$}l}\n \\toprule\n Parameter & \\multicolumn{2}{c}{Fixed Value} \\\\\n \\midrule\n $h_1^\\text{\\catAU}$ & \\multicolumn{2}{c}{$0.93057$}\\\\\n $h_2^\\text{\\catAU}$ & \\multicolumn{2}{c}{$0.93485$}\\\\\n $h_3^\\text{\\catAU}$ & \\multicolumn{2}{c}{$0.96383$}\\\\\n $h_4^\\text{\\catAU}$ & \\multicolumn{2}{c}{$0.96521$}\\\\\n $h_5^\\text{\\catAU}$ & \\multicolumn{2}{c}{$0.99547$}\\\\\n $h_6^\\text{\\catAU}$ & \\multicolumn{2}{c}{$0.97126$}\\\\\n $h_7^\\text{\\catAU}$ & \\multicolumn{2}{c}{$0.96399$}\\\\\n $h_8^\\text{\\catAU}$ & \\multicolumn{2}{c}{$0.9725$}\\\\\n $h_9^\\text{\\catAU}$ & \\multicolumn{2}{c}{$0.98045$}\\\\\n $h_{10}^\\text{\\catAU}$ & \\multicolumn{2}{c}{$0.97533$}\\\\\n \\bottomrule\n\\end{tabular}\n%\n\\qquad\n%\n\\begin{tabular}[t]{lr@{$\\,\\pm\\,$}l}\n \\toprule\n Parameter & \\multicolumn{2}{c}{Fixed Value} \\\\\n \\midrule \n $h_1^\\text{\\catEB}$ & \\multicolumn{2}{c}{$0.1481$}\\\\\n $h_2^\\text{\\catEB}$ & \\multicolumn{2}{c}{$0.27167$}\\\\\n $h_3^\\text{\\catEB}$ & \\multicolumn{2}{c}{$0.29418$}\\\\\n $h_4^\\text{\\catEB}$ & \\multicolumn{2}{c}{$0.35902$}\\\\\n $h_5^\\text{\\catEB}$ & \\multicolumn{2}{c}{$0.40022$}\\\\\n $h_6^\\text{\\catEB}$ & \\multicolumn{2}{c}{$0.4262$}\\\\\n $h_7^\\text{\\catEB}$ & \\multicolumn{2}{c}{$0.44465$}\\\\\n $h_8^\\text{\\catEB}$ & \\multicolumn{2}{c}{$0.47084$}\\\\\n $h_9^\\text{\\catEB}$ & \\multicolumn{2}{c}{$0.49859$}\\\\\n $h_{10}^\\text{\\catEB}$ & \\multicolumn{2}{c}{$0.52957$}\\\\\n \\bottomrule\n\\end{tabular}\n\\end{table}\n\n\\FloatBarrier\n% ------------------------------------------------------------------------------\n\\subsection{Fit results of subordinate parameters}\n\\label{sec:app:measurement_of_sin2beta:cpv_measurement:results}\n\n\\begin{table}[!h]\n \\caption{Results for the estimated signal and background candidate numbers\n from the nominal fit.}\n \\label{tab:app:measurement_of_sin2beta:cpv_measurement:results:yields}\n \\centering\n \\footnotesize\n \\resizebox{0.49\\textwidth}{!}{\n \\begin{tabular}{lllllr@{$\\,\\pm\\,$}l}\n \\toprule\n \\multicolumn{4}{l}{Sample} & Parameter & \\multicolumn{2}{c}{Fitted Value} \\\\ \n \\midrule\n \\multirow{24}{*}{2011} & \\multirow{12}{*}{\\catDD} & \\multirow{4}{*}{\\catOS} & \\multirow{2}{*}{\\catAU} & $N_{\\Sig}$ & $5134$ & $103$ \\\\\n & & & & $N_{\\Bkg}$ & $9352$ & $122$ \\\\\n & & & \\multirow{2}{*}{\\catEB} & $N_{\\Sig}$ & $856$ & $39$ \\\\\n & & & & $N_{\\Bkg}$ & $1413$ & $46$ \\\\\n & & \\multirow{4}{*}{\\catSS} & \\multirow{2}{*}{\\catAU} & $N_{\\Sig}$ & $2028$ & $54$ \\\\\n & & & & $N_{\\Bkg}$ & $1251$ & $46$ \\\\\n & & & \\multirow{2}{*}{\\catEB} & $N_{\\Sig}$ & $324$ & $20$ \\\\\n & & & & $N_{\\Bkg}$ & $153$ & $16$ \\\\\n & & \\multirow{4}{*}{\\catBS} & \\multirow{2}{*}{\\catAU} & $N_{\\Sig}$ & $941$ & $38$ \\\\\n & & & & $N_{\\Bkg}$ & $913$ & $38$ \\\\\n & & & \\multirow{2}{*}{\\catEB} & $N_{\\Sig}$ & $138$ & $14$ \\\\\n & & & & $N_{\\Bkg}$ & $121$ & $13$ \\\\\n & \\multirow{12}{*}{\\catLL} & \\multirow{4}{*}{\\catOS} & \\multirow{2}{*}{\\catAU} & $N_{\\Sig}$ & $2263$ & $54$ \\\\\n & & & & $N_{\\Bkg}$ & $1504$ & $47$ \\\\\n & & & \\multirow{2}{*}{\\catEB} & $N_{\\Sig}$ & $333$ & $20$ \\\\\n & & & & $N_{\\Bkg}$ & $304$ & $19$ \\\\\n & & \\multirow{4}{*}{\\catSS} & \\multirow{2}{*}{\\catAU} & $N_{\\Sig}$ & $744$ & $29$ \\\\\n & & & & $N_{\\Bkg}$ & $119$ & $14$ \\\\\n & & & \\multirow{2}{*}{\\catEB} & $N_{\\Sig}$ & $89$ & $9$ \\\\\n & & & & $N_{\\Bkg}$ & $13$ & $4$ \\\\\n & & \\multirow{4}{*}{\\catBS} & \\multirow{2}{*}{\\catAU} & $N_{\\Sig}$ & $321$ & $19$ \\\\\n & & & & $N_{\\Bkg}$ & $119$ & $13$ \\\\\n & & & \\multirow{2}{*}{\\catEB} & $N_{\\Sig}$ & $46$ & $7$ \\\\\n & & & & $N_{\\Bkg}$ & $11$ & $4$ \\\\\n \\midrule \n \\multirow{24}{*}{2012} & \\multirow{12}{*}{\\catDD} & \\multirow{4}{*}{\\catOS} & \\multirow{2}{*}{\\catAU} & $N_{\\Sig}$ & $10378$ & $156$ \\\\\n & & & & $N_{\\Bkg}$ & $20569$ & $185$ \\\\\n & & & \\multirow{2}{*}{\\catEB} & $N_{\\Sig}$ & $2188$ & $66$ \\\\\n & & & & $N_{\\Bkg}$ & $4724$ & $83$ \\\\\n & & \\multirow{4}{*}{\\catSS} & \\multirow{2}{*}{\\catAU} & $N_{\\Sig}$ & $4246$ & $80$ \\\\\n & & & & $N_{\\Bkg}$ & $3199$ & $74$ \\\\\n & & & \\multirow{2}{*}{\\catEB} & $N_{\\Sig}$ & $979$ & $35$ \\\\\n & & & & $N_{\\Bkg}$ & $468$ & $27$ \\\\\n & & \\multirow{4}{*}{\\catBS} & \\multirow{2}{*}{\\catAU} & $N_{\\Sig}$ & $1962$ & $57$ \\\\\n & & & & $N_{\\Bkg}$ & $2251$ & $59$ \\\\\n & & & \\multirow{2}{*}{\\catEB} & $N_{\\Sig}$ & $403$ & $24$ \\\\\n & & & & $N_{\\Bkg}$ & $343$ & $23$ \\\\\n & \\multirow{12}{*}{\\catLL} & \\multirow{4}{*}{\\catOS} & \\multirow{2}{*}{\\catAU} & $N_{\\Sig}$ & $4599$ & $79$ \\\\\n & & & & $N_{\\Bkg}$ & $3245$ & $70$ \\\\\n & & & \\multirow{2}{*}{\\catEB} & $N_{\\Sig}$ & $971$ & $35$ \\\\\n & & & & $N_{\\Bkg}$ & $939$ & $35$ \\\\\n & & \\multirow{4}{*}{\\catSS} & \\multirow{2}{*}{\\catAU} & $N_{\\Sig}$ & $1550$ & $41$ \\\\\n & & & & $N_{\\Bkg}$ & $298$ & $22$ \\\\\n & & & \\multirow{2}{*}{\\catEB} & $N_{\\Sig}$ & $281$ & $17$ \\\\\n & & & & $N_{\\Bkg}$ & $55$ & $9$ \\\\\n & & \\multirow{4}{*}{\\catBS} & \\multirow{2}{*}{\\catAU} & $N_{\\Sig}$ & $658$ & $27$ \\\\\n & & & & $N_{\\Bkg}$ & $177$ & $17$ \\\\\n & & & \\multirow{2}{*}{\\catEB} & $N_{\\Sig}$ & $118$ & $11$ \\\\\n & & & & $N_{\\Bkg}$ & $34$ & $7$ \\\\\n \\bottomrule\n\\end{tabular}\n}\n\\end{table}\n%\n\\begin{table}\n \\caption{Results for the mass parameters in the nominal fit}\n \\label{tab:app:measurement_of_sin2beta:cpv_measurement:results:mass}\n \\centering\n \\begin{tabular}{llr@{$\\,\\pm\\,$}l}\n \\toprule\n \\multicolumn{2}{c}{Parameter} & \\multicolumn{2}{c}{Value} \\\\\n \\midrule\n $m^{DD}_{}$ & ($\\si{\\MeVcc}$) & $5281.80$ & $0.28$ \\\\\n $\\sigma^{DD}_{m}$ & ($\\si{\\MeVcc}$) & $9.9$ & $0.1$ \\\\\n $\\beta^{DD}_{m}$ & & $-0.004$ & $0.004$ \\\\\n $\\alpha^{DD}_{m}$ & ($\\si{(\\MeVcc)^{-1}}$) & $-0.00091$ & $0.00019$ \\\\\n \\midrule\n $m^{LL}_{}$ & ($\\si{\\MeVcc}$) & $5281.20$ & $0.30$ \\\\\n $\\sigma^{LL}_{m}$ & ($\\si{\\MeVcc}$) & $8.33$ & $0.09$ \\\\\n $\\beta^{LL}_{m}$ & & $-0.009$ & $0.005$ \\\\\n $\\alpha^{LL}_{m}$ & ($\\si{(\\MeVcc)^{-1}}$) & $-0.0004$ & $0.0004$ \\\\\n \\bottomrule\n \\end{tabular}\n\\end{table}\n%\n\\begin{table}\n \\caption{Results for the background decay time parameters in the nominal fit}\n \\label{tab:app:measurement_of_sin2beta:cpv_measurement:results:time:bkg}\n \\centering\n \\begin{tabular}{llr@{$\\,\\pm\\,$}l}\n \\toprule\n \\multicolumn{2}{c}{Parameter} & \\multicolumn{2}{c}{Value} \\\\\n \\midrule\n $f^{\\catDD,\\catOS}_{2,t}$ & & $0.34$ & $0.06$ \\\\\n $f^{\\catDD,\\catOS}_{3,t}$ & & $0.049$ & $0.018$ \\\\\n $\\tau^{\\catDD,\\catOS}_{1}$ & ($\\si{\\pico\\second}$) & $0.579$ & $0.028$ \\\\\n $\\tau^{\\catDD,\\catOS}_{2}$ & ($\\si{\\pico\\second}$) & $1.41$ & $0.17$ \\\\\n $\\tau^{\\catDD,\\catOS}_{3}$ & ($\\si{\\pico\\second}$) & $4.2$ & $0.7$ \\\\\n \\midrule\n $f^{\\catDD,\\catSS}_{2,t}$ & & $0.15$ & $0.06$ \\\\\n $\\tau^{\\catDD,\\catSS}_{1}$ & ($\\si{\\pico\\second}$) & $0.703$ & $0.032$ \\\\\n $\\tau^{\\catDD,\\catSS}_{2}$ & ($\\si{\\pico\\second}$) & $1.72$ & $0.23$ \\\\\n \\midrule\n $f^{\\catLL}_{2,t}$ & & $0.48$ & $0.21$ \\\\\n $f^{\\catLL}_{3,t}$ & & $0.043$ & $0.027$ \\\\\n $\\tau^{\\catLL}_{1}$ & ($\\si{\\pico\\second}$) & $0.22$ & $0.04$ \\\\\n $\\tau^{\\catLL}_{2}$ & ($\\si{\\pico\\second}$) & $0.40$ & $0.07$ \\\\\n $\\tau^{\\catLL}_{3}$ & ($\\si{\\pico\\second}$) & $4.2$ & $0.5$ \\\\\n \\bottomrule\n \\end{tabular}\n\\end{table}\n\n\\clearpage\n% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Studies of systematic effects}\n\\label{sec:app:measurement_of_sin2beta:systematics}\n\n% ..............................................................................\n\\subsubsection{Fit model}\n\\label{sec:app:measurement_of_sin2beta:systematics:systematics:fit_model}\n\n\\begin{figure}[h]\n\\centering\n \\includegraphics[width=0.49\\textwidth]{private/content/appendices/figs/systematics_fitmodel_bkttaggingasym_s_pull.pdf}\\hfill\n \\includegraphics[width=0.49\\textwidth]{private/content/appendices/figs/systematics_fitmodel_bkttaggingasym_s_res.pdf}\\\\\n \\includegraphics[width=0.49\\textwidth]{private/content/appendices/figs/systematics_fitmodel_bkttaggingasym_c_pull.pdf}\\hfill\n \\includegraphics[width=0.49\\textwidth]{private/content/appendices/figs/systematics_fitmodel_bkttaggingasym_c_res.pdf}\n\\caption{Shown are (left) pull and (right) residual distributions of the\nparameters (top) \\SJpsiKS and (bottom) \\CJpsiKS from a \\ToyMC study of the\ninfluence of an asymmetry in the background tagging estimates on the measurement\nof the \\CP parameters.}\n\\label{fig:app:measurement_of_sin2beta:systematics:systematics:fit_model:bkg_tagging_asymmetry}\n\\end{figure}\n\n\\begin{figure}[h]\n\\centering\n \\includegraphics[width=0.49\\textwidth]{private/content/appendices/figs/systematics_fitmodel_mtcorr_s_pull.pdf}\\hfill\n \\includegraphics[width=0.49\\textwidth]{private/content/appendices/figs/systematics_fitmodel_mtcorr_s_res.pdf}\\\\\n \\includegraphics[width=0.49\\textwidth]{private/content/appendices/figs/systematics_fitmodel_mtcorr_c_pull.pdf}\\hfill\n \\includegraphics[width=0.49\\textwidth]{private/content/appendices/figs/systematics_fitmodel_mtcorr_c_res.pdf}\n\\caption{Shown are (left) pull and (right) residual distributions of the\nparameters (top) \\SJpsiKS and (bottom) \\CJpsiKS from a \\ToyMC study of the\ninfluence of a small mass and decay time correlation on the measurement of the\n\\CP parameters.}\n\\label{fig:app:measurement_of_sin2beta:systematics:systematics:fit_model:mass_time_correlations}\n\\end{figure}\n\n\\clearpage\n% ..............................................................................\n\\subsubsection{Flavour Tagging}\n\\label{sec:app:measurement_of_sin2beta:systematics:systematics:tagging}\n\n\\begin{figure}[h]\n \\includegraphics[width=0.49\\textwidth]{private/content/appendices/figs/systematics_ft_calibration_s_pull.pdf}\\hfill\n \\includegraphics[width=0.49\\textwidth]{private/content/appendices/figs/systematics_ft_calibration_s_res.pdf}\n \\includegraphics[width=0.49\\textwidth]{private/content/appendices/figs/systematics_ft_calibration_c_pull.pdf}\\hfill\n \\includegraphics[width=0.49\\textwidth]{private/content/appendices/figs/systematics_ft_calibration_c_res.pdf}\n\\caption{Shown are (left) pull and (right) residual distributions of the\nparameters (top) \\SJpsiKS and (bottom) \\CJpsiKS from a \\ToyMC study of the\ninfluence of the systematic uncertainties on the flavour tagging calibration\nparameters on the measurement of the \\CP parameters.}\n\\label{fig:app:measurement_of_sin2beta:systematics:systematics:tagging}\n\\end{figure}\n\n\\clearpage\n% ..............................................................................\n\\subsubsection{Decay time resolution}\n\\label{sec:app:measurement_of_sin2beta:systematics:systematics:resolution}\n\n\\begin{figure}[h]\n \\includegraphics[width=0.49\\textwidth]{private/content/appendices/figs/systematics_resolution_calibration_s_pull.pdf}\\hfill\n \\includegraphics[width=0.49\\textwidth]{private/content/appendices/figs/systematics_resolution_calibration_s_res.pdf}\n \\includegraphics[width=0.49\\textwidth]{private/content/appendices/figs/systematics_resolution_calibration_c_pull.pdf}\\hfill\n \\includegraphics[width=0.49\\textwidth]{private/content/appendices/figs/systematics_resolution_calibration_c_res.pdf}\n\\caption{Shown are (left) pull and (right) residual distributions of the\nparameters (top) \\SJpsiKS and (bottom) \\CJpsiKS from a \\ToyMC study of the\ninfluence of the decay time resolution calibration model on the measurement of\nthe \\CP parameters.}\n\\label{fig:app:measurement_of_sin2beta:systematics:systematics:resolution:calibration}\n\\end{figure}\n\n\\begin{figure}[h]\n \\includegraphics[width=0.49\\textwidth]{private/content/appendices/figs/systematics_resolution_offset_s_pull.pdf}\\hfill\n \\includegraphics[width=0.49\\textwidth]{private/content/appendices/figs/systematics_resolution_offset_s_res.pdf}\n \\includegraphics[width=0.49\\textwidth]{private/content/appendices/figs/systematics_resolution_offset_c_pull.pdf}\\hfill\n \\includegraphics[width=0.49\\textwidth]{private/content/appendices/figs/systematics_resolution_offset_c_res.pdf}\n\\caption{Shown are (left) pull and (right) residual distributions of the\nparameters (top) \\SJpsiKS and (bottom) \\CJpsiKS from a \\ToyMC study of the\ninfluence of neglecting a non-zero offset in the decay time resolution\ncalibration model on the measurement of the \\CP parameters.}\n\\label{fig:app:measurement_of_sin2beta:systematics:systematics:resolution:offset}\n\\end{figure}\n\n\\begin{figure}[h]\n \\includegraphics[width=0.49\\textwidth]{private/content/appendices/figs/systematics_resolution_wrongpv_s_pull.pdf}\\hfill\n \\includegraphics[width=0.49\\textwidth]{private/content/appendices/figs/systematics_resolution_wrongpv_s_res.pdf}\n \\includegraphics[width=0.49\\textwidth]{private/content/appendices/figs/systematics_resolution_wrongpv_c_pull.pdf}\\hfill\n \\includegraphics[width=0.49\\textwidth]{private/content/appendices/figs/systematics_resolution_wrongpv_c_res.pdf}\n\\caption{Shown are (left) pull and (right) residual distributions of the\nparameters (top) \\SJpsiKS and (bottom) \\CJpsiKS from a \\ToyMC study of the\ninfluence of the fraction of candidates with a wrong \\PV association on the\nmeasurement of the \\CP parameters.}\n\\label{fig:app:measurement_of_sin2beta:systematics:systematics:resolution:wrong_pv}\n\\end{figure}\n\n\\clearpage\n% ..............................................................................\n\\subsubsection{Decay time acceptance}\n\\label{sec:app:measurement_of_sin2beta:systematics:systematics:acceptance}\n\n\\begin{figure}[h]\n \\includegraphics[width=0.49\\textwidth]{private/content/appendices/figs/systematics_acc_lower_s_pull.pdf}\\hfill\n \\includegraphics[width=0.49\\textwidth]{private/content/appendices/figs/systematics_acc_lower_s_res.pdf}\n \\includegraphics[width=0.49\\textwidth]{private/content/appendices/figs/systematics_acc_lower_c_pull.pdf}\\hfill\n \\includegraphics[width=0.49\\textwidth]{private/content/appendices/figs/systematics_acc_lower_c_res.pdf}\n\\caption{Shown are (left) pull and (right) residual distributions of the\nparameters (top) \\SJpsiKS and (bottom) \\CJpsiKS from a \\ToyMC study of the\ninfluence of the low decay time acceptance model on the measurement of the \\CP\nparameters.}\n\\label{fig:app:measurement_of_sin2beta:systematics:systematics:acceptance:lower}\n\\end{figure}\n\n\\begin{figure}[h]\n \\includegraphics[width=0.49\\textwidth]{private/content/appendices/figs/systematics_acc_upper_s_pull.pdf}\\hfill\n \\includegraphics[width=0.49\\textwidth]{private/content/appendices/figs/systematics_acc_upper_s_res.pdf}\n \\includegraphics[width=0.49\\textwidth]{private/content/appendices/figs/systematics_acc_upper_c_pull.pdf}\\hfill\n \\includegraphics[width=0.49\\textwidth]{private/content/appendices/figs/systematics_acc_upper_c_res.pdf}\n\\caption{Shown are (left) pull and (right) residual distributions of the\nparameters (top) \\SJpsiKS and (bottom) \\CJpsiKS from a \\ToyMC study of the\ninfluence of the upper decay time acceptance correction function on the\nmeasurement of the \\CP parameters.}\n\\label{fig:app:measurement_of_sin2beta:systematics:systematics:acceptance:upper}\n\\end{figure}\n\n\\clearpage\n% ..............................................................................\n\\subsubsection[Production asymmetry, $z$-scale, \\DMd, and \\DGd]{Production asymmetry, $\\mathbfsfit{z}$-scale, $\\mathbfsfit{\\DMd}$, and $\\mathbfsfit{\\DGd}$}\n\\label{sec:app:measurement_of_sin2beta:systematics:systematics:further_studies}\n\n\\begin{figure}[h]\n \\includegraphics[width=0.49\\textwidth]{private/content/appendices/figs/systematics_fs_zscale_s_pull.pdf}\\hfill\n \\includegraphics[width=0.49\\textwidth]{private/content/appendices/figs/systematics_fs_zscale_s_res.pdf}\n \\includegraphics[width=0.49\\textwidth]{private/content/appendices/figs/systematics_fs_zscale_c_pull.pdf}\\hfill\n \\includegraphics[width=0.49\\textwidth]{private/content/appendices/figs/systematics_fs_zscale_c_res.pdf}\n\\caption{Shown are (left) pull and (right) residual distributions of the\nparameters (top) \\SJpsiKS and (bottom) \\CJpsiKS from a \\ToyMC study of the\ninfluence of the relative $z$-scale uncertainty on the measurement of the \\CP\nparameters.}\n\\label{fig:app:measurement_of_sin2beta:systematics:systematics:further_studies:zscale}\n\\end{figure}\n\n\\begin{figure}[h]\n \\includegraphics[width=0.49\\textwidth]{private/content/appendices/figs/systematics_fs_prodasym_s_pull.pdf}\\hfill\n \\includegraphics[width=0.49\\textwidth]{private/content/appendices/figs/systematics_fs_prodasym_s_res.pdf}\n \\includegraphics[width=0.49\\textwidth]{private/content/appendices/figs/systematics_fs_prodasym_c_pull.pdf}\\hfill\n \\includegraphics[width=0.49\\textwidth]{private/content/appendices/figs/systematics_fs_prodasym_c_res.pdf}\n\\caption{Shown are (left) pull and (right) residual distributions of the\nparameters (top) \\SJpsiKS and (bottom) \\CJpsiKS from a \\ToyMC study of the\ninfluence of an enlarged production asymmetry $A_P^{\\catOO}$ on the measurement\nof the \\CP parameters.}\n\\label{fig:app:measurement_of_sin2beta:systematics:systematics:further_studies:production_asymmetry}\n\\end{figure}\n\n\\begin{figure}[h]\n \\includegraphics[width=0.49\\textwidth]{private/content/appendices/figs/systematics_fs_dgd_s_pull.pdf}\\hfill\n \\includegraphics[width=0.49\\textwidth]{private/content/appendices/figs/systematics_fs_dgd_s_res.pdf}\n \\includegraphics[width=0.49\\textwidth]{private/content/appendices/figs/systematics_fs_dgd_c_pull.pdf}\\hfill\n \\includegraphics[width=0.49\\textwidth]{private/content/appendices/figs/systematics_fs_dgd_c_res.pdf}\n\\caption{Shown are (left) pull and (right) residual distributions of the\nparameters (top) \\SJpsiKS and (bottom) \\CJpsiKS from a \\ToyMC study of the\ninfluence of a non-zero decay width difference $\\DGd$ on the measurement\nof the \\CP parameters.}\n\\label{fig:app:measurement_of_sin2beta:systematics:systematics:further_studies:decay_width_difference}\n\\end{figure}\n\n\\begin{figure}[h]\n \\includegraphics[width=0.49\\textwidth]{private/content/appendices/figs/systematics_fs_dmd_s_pull.pdf}\\hfill\n \\includegraphics[width=0.49\\textwidth]{private/content/appendices/figs/systematics_fs_dmd_s_res.pdf}\n \\includegraphics[width=0.49\\textwidth]{private/content/appendices/figs/systematics_fs_dmd_c_pull.pdf}\\hfill\n \\includegraphics[width=0.49\\textwidth]{private/content/appendices/figs/systematics_fs_dmd_c_res.pdf}\n\\caption{Shown are (left) pull and (right) residual distributions of the\nparameters (top) \\SJpsiKS and (bottom) \\CJpsiKS from a \\ToyMC study of the\ninfluence of an enlarged mass difference $\\DMd$ on the measurement\nof the \\CP parameters.}\n\\label{fig:app:measurement_of_sin2beta:systematics:systematics:further_studies:mass_difference}\n\\end{figure}\n", "meta": {"hexsha": "c947b5f438f09f75007763594e6ec4c730e99bf8", "size": 40190, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "content/appendices/measurement-of-sin2beta.tex", "max_stars_repo_name": "ccauet/thesis", "max_stars_repo_head_hexsha": "96d26639af0c4aa4badc6a55be952edc72a5eebd", "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": "content/appendices/measurement-of-sin2beta.tex", "max_issues_repo_name": "ccauet/thesis", "max_issues_repo_head_hexsha": "96d26639af0c4aa4badc6a55be952edc72a5eebd", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2016-05-25T15:49:05.000Z", "max_issues_repo_issues_event_max_datetime": "2017-06-12T07:42:52.000Z", "max_forks_repo_path": "content/appendices/measurement-of-sin2beta.tex", "max_forks_repo_name": "ccauet/thesis", "max_forks_repo_head_hexsha": "96d26639af0c4aa4badc6a55be952edc72a5eebd", "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.304, "max_line_length": 171, "alphanum_fraction": 0.5146056233, "num_tokens": 13161, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.19277782022841536}}
{"text": "\\section{Overview} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:over}\n\nA \\emph{class hierarchy} is a partially ordered set $(H,\\subtype)$ where $H$ is a potentially open set \nof classes and $\\subtype$ is a reflexive, transitive and anti-symmetric \n\\emph{subtyping relation} on $H$. We use \\emph{class} and \\emph{type} \ninterchangeably.\n% as the exact distinction is not important for this discussion. \nWhen two classes are in a subtyping relation $D \\subtype B$, the class $D$\nis said to be a (possibly indirect) \\emph{derived class} (or subtype) of $B$;\nthe class $B$ is called a (possibly indirect) \\emph{base class}\n(or supertype) of $D$.\n %When the transitive reduction \n%$\\subtypeD$ of $\\subtype$ is a function, $H$ is usually referred to as \n%\\emph{hierarchy} to indicate single inheritance.\n\nThe %\\emph{most-derived type of an object} also known as the \n\\emph{dynamic type of an object} is the type used to create it.\nThe \\emph{static type of an expression} is the type of that expression\nas given by the static semantics.%, i.e. the typing rules of expressions.\n% By \n% \\emph{dynamic type} of an object we call any base class of the most-derived type.\n\n\\subsection{Type Switch}\n\n%This section generalizes pattern matching of closed algebraic datatype values\n%to case analysis of hierarchical and extensible datatype values.\nIn general, a \\emph{type switch} or \\emph{typecase} is a multiway branch statement \nthat distinguishes values based on their type. In a multi-paradigm programming \nlanguage like \\Cpp{}, which supports parametric, ad-hoc, and \nsubtyping polymorphisms, such a broad definition subsumes numerous different\ntypecase constructs studied in the literature~\\cite{Intensional95,Glew99,OpenShutTypecase05}. \nIn this work, we only look at typecasing scenarios based on the class inheritance \nof \\Cpp{}, similar to those studied by Glew~\\cite{Glew99}. \n% It is possible to generalize type switch\n% (the notion, not our implementation) to static polymorphism of \\Cpp{} (ad-hoc and \n% parametric polymorphism enabled by overloading and templates) along the line of \n% work introduced by Harper and Morrisett~\\cite{Intensional95} and studied in the\n% context of closed and extensible solutions by Vytiniotis et \n% al~\\cite{OpenShutTypecase05}, but we do not address such a generalization here.\nWe use the term \\emph{type switch} instead of a broader \\emph{typecase} to \nstress the run-time nature of the type analysis similar to how regular \n\\code{switch}-statement of \\Cpp{} performs case analysis of values at run time.\n\nThe term \\emph{object descriptor} means either a pointer or a reference to \nan object.\nGiven an object descriptor, called \\emph{subject}, of static type \\code{S} \nreferred to as the \\emph{subject type}, and a list of \n\\emph{target types} \\code{Ti} associated with the branches, a type switch \nstatement needs to identify a suitable clause $m$ based on \nthe dynamic type \\code{D <: S} of the subject as well as a suitable \nconversion that coerces the subject to the target type \\code{Tm}. \nDue to multiple inheritance, types \\code{Ti} may not all directly\nderive from the static type \\code{S}. However,\n%because of the strong static type safety requirement, \nthe type of the applicable clause \\code{Tm} will necessarily have to be a \nsupertype of the subject's dynamic type \\code{D <: Tm}. \nA hypothetical type switch \nstatement, not currently supported by \\Cpp{}, may look as following:\n%\n\\begin{lstlisting}[keepspaces]\nswitch (subject) { case T1: s1; ... case Tn: sn; }\n\\end{lstlisting}\n%\n\\noindent\nThere is no need for an explicit \\emph{default clause} in our setting because \nit is semantically equivalent to a case clause guarded by the \nsubject type: \\code{case S: s}. The only semantic difference such a choice \nmakes is in the treatment of null pointers.\nOne may naively think that null pointers should be handled by\nthe default clause. However, not distinguishing between \ninvalid object and valid object of a known static but unknown dynamic type may \nlead to nasty run-time errors.\n\n%\\noindent\nSimilar control structures exist in many programming languages, e.g. \n\\emph{match} in Scala~\\cite{Scala2nd}, \\emph{case} in Haskell~\\cite{Haskell98Book} and \nML~\\cite{ML90}, \\emph{typecase} in Modula-3~\\cite{Modula3TS} and CLOS (as a \nmacro), \\emph{tagcase} in CLU~\\cite{CLURefMan}, \\emph{union case} in Algol 68, \nand date back to at least Simula's \\emph{Inspect} statement~\\cite{Simula67}. \nThe statement can, in general, be given numerous plausible semantics:\n%\n\\begin{itemize}\n\\setlength{\\itemsep}{0pt}\n\\setlength{\\parskip}{0pt}\n\\item \\emph{First-fit} semantics will evaluate the first statement $s_i$ such \n that $T_i$ is a base class of $D$.\n\\item \\emph{Best-fit} semantics will evaluate the statement corresponding to the \n most-specialized base class $T_i$ of $D$ if it is unique (subject to \n ambiguity).\n\\item \\emph{Exact-fit} semantics will evaluate statement $s_i$ if $T_i=D$.\n\\item \\emph{All-fit} semantics will evaluate all statements $s_i$ whose guard \n type $T_i$ is a supertype of $D$ (order of execution has to be defined).\n\\item \\emph{Any-fit} semantics might choose non-deterministically one of the \n statements enabled by the all-fit semantics.\n\\end{itemize}\n%\nThe list is not exhaustive and depending on a language, any of them\nis a plausible choice. Functional languages, for example, often prefer \nfirst-fit semantics because it is similar to case analysis in mathematics. \nObject-oriented languages are typically inclined to best-fit semantics due \nto its similarity to overload resolution and run-time dispatch; however, some \ndo opt for first-fit semantics to mimic the functional style: e.g. Scala~\\cite{Scala2nd}. \nExact-fit semantics can often be seen in languages supporting discriminated \nunion types (sum types): e.g. \\emph{variant records} in Pascal, Ada and Modula-2, \n\\emph{oneof} and \\emph{variant objects} in CLU, \\emph{unions} in C and \\Cpp{}, etc. \nAll-fit and any-fit semantics might be seen in languages based on predicate \ndispatching~\\cite{ErnstKC98} or guarded commands~\\cite{EWD:EWD472}, where a \npredicate can be seen as a characteristic function of a type, while logical \nimplication -- as subtyping.\n\n\\subsection{The Expression Problem}\n\nType switching is related to a more general problem manifesting the differences \nin functional and object-oriented programming styles.\nConventional algebraic datatypes, as found in most functional languages, allow \nfor easy addition of new functions on existing data types. However, they fall short \nin extending data types themselves (e.g. with new constructors), which requires \nmodifying the source code. Object-oriented languages make \ndata type extension trivial through inheritance, but the addition of new \nfunctions operating on these classes typically requires changes to the class \ndefinition. This dilemma is known as the \\emph{expression problem}~\\cite{Cook90,exprproblem}.\n\n\\noindent\nClasses differ from algebraic data types in two important ways. Firstly, they\nare \\emph{extensible}, for new variants can be added later by inheriting from\nthe base class. Secondly, they are \\emph{hierarchical} and thus typically \n\\emph{non-disjoint} since variants can be inherited from other variants and form \na subtyping relation between themselves~\\cite{Glew99}. In contrast, variants in \nconventional algebraic data types are \\emph{disjoint} and \\emph{closed}.\nSome functional languages e.g. ML2000~\\cite{ML2000} and its predecessor, Moby, \nwere experimenting with \\emph{hierarchical extensible sum types}, which are \ncloser to object-oriented classes then algebraic data types are, but, \ninterestingly, they provided no %neither traditional nor efficient \nfacilities for performing case analysis on them.\n\nZenger and Odersky refined the expression problem in the context of \nindependently extensible solutions~\\cite{fool12} as a challenge to find an \nimplementation technique that satisfies the following requirements:\n%\n\\begin{itemize}\n\\setlength{\\itemsep}{0pt}\n\\setlength{\\parskip}{0pt}\n\\item \\emph{Extensibility in both dimensions}: It should be possible to add new \n data variants, while adapting the existing operations accordingly. It \n should also be possible to introduce new functions. \n\\item \\emph{Strong static type safety}: It should be impossible to apply a \n function to a data variant, which it cannot handle. \n\\item \\emph{No modification or duplication}: Existing code should neither be \n modified nor duplicated.\n\\item \\emph{Separate compilation}: Neither datatype extensions nor addition of \n new functions should require re-typechecking the original datatype or \n existing functions. No safety checks should be deferred until link or \n runtime.\n\\item \\emph{Independent extensibility}: It should be possible to combine \n independently developed extensions so that they can be used jointly.\n\\end{itemize}\n%\nWhile these requirements were formulated for extensible data types with \ndisjoint variants, object-oriented languages primarily deal with \nhierarchical data types. We thus found it important to state explicitly an \nadditional requirement based on the Liskov substitution principle~\\cite{Lis87}:\n%\n\\begin{itemize}\n\\setlength{\\itemsep}{0pt}\n\\setlength{\\parskip}{0pt}\n\\item \\emph{Substitutability}: Operations expressed on more general data variants\n should be applicable to ones that are more specific.\n %(the latter being in a subtyping relation with the former).\n\\end{itemize}\n\n%Depending on the semantics of the language's subtyping relation, \n%substitutability requirement may turn pattern matching into an expensive \n%operation. OCaml, for example, that uses structural subtyping on its object \n%types, does not offer pattern \n\n\\noindent\nWe will refer to a solution that satisfies all of the above requirements as \\emph{open}. \nNumerous solutions have been proposed to dealing with the expression problem in both \nfunctional~\\cite{garrigue-98,LohHinze2006} and object-oriented \ncamps~\\cite{Palsberg98,Krishnamurthi98,Zenger:2001,runabout}, but very few have \nmade their way into one of the mainstream languages. We refer the reader to Zenger \nand Odersky's original manuscript for a discussion of the approaches~\\cite{fool12}.\nMost of the discussed object-oriented solutions focused on the visitor design pattern and its extensions, \nwhich even today seem to be the most commonly used approach to dealing with the \nexpression problem in object-oriented languages.\n\nA lot has been written about the visitor design pattern~\\cite{DesignPatterns1993,Palsberg98,Zenger:2001,Oliveira08}. \nIts advantages include \\emph{extensibility of functions}, \\emph{speed}, and \n\\emph{being a library solution}. Nevertheless, the solution is \\emph{intrusive}, \n\\emph{specific to hierarchy}, and requires a lot of \\emph{boilerplate code} to \nbe written. It also introduces \\emph{control inversion}, but, most importantly, \n-- \\emph{hinders extensibility} of classes.\n\n%In this work we are not trying to solve the expression problem in its full \n%generality. Instead, we concentrate on deficiencies of the visitor design \n%pattern independently of its relation to the expression problem and advocate for \n%a solution that suits object-oriented paradigm better than visitors do.\n\n\\subsection{An Open Type Switch}\n\nType switch alone does not solve the expression problem in the context\nof an object-oriented language, for the existing code may have to be \nmodified to consider new variants. Relying on a default clause is not \nan acceptable solution in this situation, because often the \nonly reasonable default behavior is to raise an exception. \nZenger and Odersky observed that defaults transform type errors that should\nmanifest statically into runtime exceptions~\\cite{fool12}.\nIn our experience, newly added variants were more often extending an existing \nvariant than creating an entirely disjoint one. In a compiler, for \nexample, a new kind of type expression will typically extend a \n\\code{TypeExpression} variant, while a new form of annotation will extend an \n\\code{Annotation} variant, thus not extending the root \\code{ASTNode} directly. \nDue to the substitutability requirement, this new variant will be treated as a \nvariant it extends in all the existing code. The functions that will be affected \nby its addition and thus have to be modified will be limited to functions \ndirectly analyzing the variant it extends and not providing a default behavior.\n\nTo account for this subtlety of extensible hierarchical data types, we use a \nterm \\emph{open type switch} to refer to a type switch that satisfies all the \nrequirements of an \\emph{open solution to the expression problem} stated above \nexcept for the \\emph{no modification or duplication} requirement. We loosen it \nto allow modification of functions for which the newly added variant becomes a \ndisjoint (orthogonal) case not handled by a default clause. We believe that the \nloosened requirement allows us to express pragmatically interesting restrictions \nthat developers are willing to live with. Furthermore, \nopen type switch overcomes \nall the major shortcomings of the visitor design pattern:\n%\n\\begin{itemize}\n\\setlength{\\itemsep}{0pt}\n\\setlength{\\parskip}{0pt}\n\\item Case analysis with an open type switch is non-intrusive as it \n inspects the hierarchy externally and can be applied retroactively. \n\\item New variants can be accounted for in the newly written code and will be \n seen as a base class or default in the existing code.\n\\item The affected functions are limited to those for which the newly added \n variant is a disjoint case.\n\\item The code avoids the control inversion and the need for boilerplate code \n that visitors introduce, and is thus a more direct expression of the \n intent.\n\\end{itemize}\n\n\\subsection{\\Cpp{} Specifics: Subobjects}\n\\label{sec:specifics}\n\n\\Cpp{} supports two kinds of multiple inheritance: \n\\emph{non-virtual} inheritance and \\emph{virtual} inheritance~\\cite{CPPARM90}. \nThe difference between the two only arises in situations where a \nclass indirectly inherits from the same base class via more than one path\nin its class hierarchy. Rigorous accounts of \\Cpp{} multiple inheritance\nsemantics use the notion of \\emph{subobject}~\\cite{RF95}.\n\n\\begin{figure}[htbp]\n \\centering\n \\includegraphics[width=0.47\\textwidth]{Inheritance.pdf}\n \\caption{Multiple Inheritance in \\Cpp{}}\n \\label{fig:inheritance}\n\\end{figure}\n\n\\noindent\nConsider the simple class hierarchy in Figure~\\ref{fig:inheritance}(1). Class \n\\code{D} indirectly inherits from class \\code{A} through its \\code{B} and \n\\code{C} base classes. In this case, the user may opt to keep distinct \nsubobjects of class \\code{A} (repeated inheritance) or a shared one (virtual \ninheritance) by specifying how \\code{B} and \\code{C} inherit from \n\\code{A}. The kind of inheritance is thus not a property of a given class, but a \nproperty of an inheritance relation between classes and it is possible to mix the two. \n\nA class hierarchy gives rise to a \\emph{subobject graph}, where a given class \nnode may be replicated when inherited repeatedly or left shared when inherited \nvirtually. The edges in such a graph represent \\emph{subobject containment} and \nindicate whether such containment is shared or exclusive. \nEvery class $C$ in the class hierarchy will have its own subobject \ngraph representing the subobjects of an object of dynamic type $C$.\nFigure~\\ref{fig:inheritance}(2) shows subobject graph for class \\code{D} \nobtained for the class hierarchy in Figure~\\ref{fig:inheritance}(1) under repeated (a) and virtual (b) \ninheritance of class \\code{A} by classes \\code{B} and \\code{C}. The shared \ncontainment is indicated with the dashed arrows, while exclusive -- with the solid \nones.\n\n\\Cpp{}'s notion of multiple inheritance is fundamentally about \nsubobjects, not just types. Virtual inheritance is about\nsharing the base-class subobjects, whereas non-virtual inheritance\nreflects distinction in base-class subobjects from distinct class inheritance paths~\\cite{CPPARM90}.\n\nAn object descriptor of static type $A$ referencing an object of the dynamic \ntype $C$ can be understood as any $C$\\code{::*::}$A$-node in the subobject graph of $C$. \nCasts can be understood as a change from one subobject to another.\nWe use the terms \\emph{source subobject} and \\emph{target \nsubobject} to refer to the argument and result of the cast, respectively. Their \nstatic types will be referred to as \\emph{source type} and \\emph{target type} \nrespectively. \\Cpp{} distinguishes three kinds of casts: upcasts, downcasts, and \ncrosscasts.\n\nAn \\emph{upcast} is a cast from a derived class to one of its bases. When the \nbase class is unambiguous, such casts are implicit and require no additional \nannotations. When the base class is ambiguous, cast failure is manifested \nstatically in the form of a compile-time error. For example, this is the case with \ncasting \\code{D} to \\code{A} under repeated multiple inheritance of \\code{A}, \nin which case the user needs to explicitly cast the object to \\code{B} or \n\\code{C} first in order to indicate the desired subobject and resolve the ambiguity. \nIn some cases, however, introduction of such an explicit cast is not possible: \ne.g. in implicit conversions generated by the compiler to implement covariant \nreturn types, crosscasts or conversions in generic code. This does not mean \nthat in such cases we violate the Liskov substitution principle: the \nclasses are still in a subtyping relation, but an implicit conversion is not \navailable.\n\nA \\emph{downcast} is a cast from a base class to one of its derived classes. The \ncast has to determine at run-time whether the source subobject is contained by a \nsubobject of the target type in the dynamic type's subobject graph. Failure \nof such a cast is manifested dynamically at run-time.\n\nA \\emph{crosscast} is a cast between classes that are not necessarily related by \ninheritance except by sharing a common derived class (subclass).\nAccordingly to the \\Cpp{} semantics such cast is defined to be a \ncomposition of upcast to target type and downcast to the dynamic type. \nWhile the downcast to the dynamic type is always guaranteed to succeed \nregardless of the source subobject, the upcast to the target type may be \nambiguous, in which case the cast will fail at runtime. A cast from \\code{Y} to \n\\code{B} inside an object of dynamic type \\code{D} in \nFigure~\\ref{fig:inheritance}(2a,2b) is an example of a successful crosscast. A \nsimilar cast from \\code{Y} to \\code{A} inside \\code{D} under the repeated \ninheritance in Figure~\\ref{fig:inheritance}(2a) will fail because of the ambiguous \nupcast from \\code{D} to \\code{A}.\n\nAn interesting artifact of these distinctions can be seen in an example of \ncasting a subobject of type \\code{Z} to a subobject of type \\code{A} in \nFigure~\\ref{fig:inheritance}(2a). The subobject \\code{D::B::A::Z} will be \nsuccessfully cast to \\code{D::B::A}, while the \\code{D::C::A::Z} will be \nsuccessfully cast to \\code{D::C::A}. These casts do not involve downcasting to \n\\code{D} followed by an upcast to \\code{A}, which would be ambiguous, but \ninstead take the dynamic type of a larger subobject (\\code{D::B} or \\code{D::C}) \nthat the source subobject is contained in into account in order to resolve the \nambiguity. A similar cast from \\code{Y} to \\code{A} will fail; should \n\\code{Y} have also been non-virtually derived from \\code{Z}, the cast from \n\\code{D::C::Y::Z} to \\code{A} would have failed. This shows that the distinction \nbetween crosscast and downcast is not based solely on the presence of a \nsubtyping relation between the source and target types, but also on the actual \nposition of the source subobject in the dynamic type's subobject graph.\n\nThe \\Cpp{} inheritance model, presented here informally, further complicates the definition and\nimplementation of a type switch compared to simpler models. We have to define the\ntype switch so that only unambiguous casting between a source and a target within an object is possible.\nThat is, the implementation of the cast between source and target subobjects must take into account the\nlocation of the source subobject in the subobject graph, rather than\njust the dynamic and target types, which would suffice for a simple subtype testing.\nOf course, every use of dynamic casting and every implicit cast are type safe~\\cite{WNST06}.\n\n%\\section{Problem Description} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\\label{sec:probl}\n\n\\subsection{Existing Approaches to Type Case Analysis}\n\\label{sec:prev}\n\nThe closed nature of algebraic data types allows for their efficient \nimplementation. The traditional compilation scheme assigns unique (and often \nsmall and sequential) tags to every variant of the algebraic data type and type \nswitching is then simply implemented with a multi-way branch~\\cite{Spuler94} \n(usually a jump table) over all the tags~\\cite{Augustsson85}. Dealing with \nextensible hierarchical data types makes this %extremely efficient \napproach infeasible:\n\n\\begin{itemize}\n\\setlength{\\itemsep}{0pt}\n\\setlength{\\parskip}{0pt}\n\\item \\emph{Extensibility} implies that the compiler may not know the exact set \n of all the derived classes until link-time (due to \\emph{separate compilation}) \n or even run-time (due to \\emph{dynamic linking}).\n\\item \\emph{Substitutability} implies that we should be able to \n match tags of derived classes against case labels representing tags of \n base classes.\n\\item The presence of \\emph{multiple inheritance} might require pointer adjustments \n that are not known at compile time (e.g. due to virtual base classes, \n ambiguous base classes or crosscasting).\n\\end{itemize}\n\n%\\noindent\n%In some cases the substitutability requirement can be satisfied by obtaining \n%the base class' tag from a derived one first and then performing the jump. \n%This will work as long as we have only base classes in the case clauses.\n%Derived classes that have to be treated separately from the rest of their \n%siblings will essentially be indistinguishable from them.\n%\n%When tags are not chosen arbitrarily but to reflect the subtyping relation of the \n%underlying hierarchy (e.g. certain bit set for certain base class), the assumed \n%structure of tags is likely to make the set of tags sparse. On one hand this \n%decreases the number of representable hierarchies and thus hinders openness, \n%while on the other it forces the compiler to use a decision tree instead of a jump \n%table to implement the switch. The former was consistently slower than the \n%latter one in our experience, even though the opposite was noted on some \n%architectures for small number of case clauses~\\cite[\\textsection 4]{garrigue-98}.\n\n\\noindent\nThere are two main approaches to implementing case analysis on extensible \nhierarchical data types discussed in the literature.\n\nThe first approach is based on either explicit or implicit sealing of the class \nhierarchy on which type switching can be performed. \\Cpp{}11, for example, allows \nthe user to prohibit further derivation by specifying a class to be ``final''~\\cite{C++11}, \nsimilar to Scala and Java. The compiler then may use the above tag \nallocation over all variants to implement type analysis~\\cite[\\textsection \n4.3.2]{EmirThesis}. \nIn some cases, the sealing may happen implicitly. For example, languages %that allow names \nwith both internal and external linkage may employ the fact that classes \nwith internal linkage will not be externally accessible and are thus effectively \nsealed. While clearly efficient, the approach is not open as it avoids the \nquestion rather than answers it. \n\nThe broader problem with this approach is that techniques that rely on unique or\nsequential compile or link-time constants violate independent extensibility \nsince without a centralized authority there is no guarantee same constant will \nnot be chosen in a type-unsafe manner by independent extensions. Updating such \nconstants at load time may be too costly even when possible. %More often than \n%not, however such updates may require code regeneration since decision trees, \n%lookup tables etc. may have been generated by compiler for given values.\n\nAn important practical solution that follows this approach is the visitor design \npattern~\\cite{DesignPatterns1993}. The set of \\code{visit} methods in a visitor's \ninterface essentially seals the class hierarchy. Extensions have been proposed \nin the literature~\\cite{Zenger:2001}, but they have problems of their own, \nas discussed in \\textsection\\ref{sec:rw}.\n\nThe second approach employs type inclusion tests combined with decision \ntrees~\\cite{Cardelli84} to avoid unnecessary checks. Its efficiency is then \nentirely focused on the efficiency of type inclusion \ntests~\\cite{Schubert83,Wirth88,Cohen91,Caseau93,Vortex96,Krall97nearoptimal,Vitek97,PQEncoding,FastDynCast,Ducournau08}. \n\n%\"A couple of years later, Nikolaus With published an approach based on type \n%inclusion. However, that approach does not work well in the presence of multiple \n%inheritance and separates the single logical operation of gaining type-safe \n%access to an object into two, implying the possibility of a programmer error.\" \n\n\\Cpp{} has handled general dynamic casting since 1987, when multiple inheritance \nwas added to the language~\\cite{Str87}. Wirth later presented a technique that \ncan be used to implement subtype tests by traversing a linked list of \ntypes~\\cite{Wirth88}. His encoding required little space, but ran in time \nproportional to the distance between the two types in the class hierarchy. \nA trivial constant-time type inclusion test can be implemented with a \n\\emph{binary matrix}, encoding the subtyping relation on the class \nhierarchy~\\cite{Vortex96}. While efficient in time, it has quadratic space \nrequirements, which makes it expensive for use on large class hierarchies. Cohen \nproposed the first space-efficient constant-time algorithm, but it can\nonly deal with single inheritance~\\cite{Cohen91}. \\emph{Hierarchical encoding} \nis another constant-time test that maps subtype queries into subset queries on \nbit-vectors~\\cite{Caseau93,Krall97nearoptimal}. The approach can handle multiple\ninheritance, but the space and time required for a subtype test in this encoding \nincreases with the size of the class hierarchy; also, Caseau's approach~\\cite{Caseau93} is \nlimited to class hierarchies that are lattices. Schubert's \\emph{relative \nnumbering}~\\cite{Schubert83} encodes each type with an interval $[l,r]$, \neffectively making type inclusion tests isomorphic to a simple range checking. \nThe encoding is optimal in space and time, but it is limited to single \ninheritance. \\emph{PQ-Encoding} of Zibin and Gil employs PQ-trees to improve \nfurther space and time efficiency of the constant-time inclusion \ntesting~\\cite{PQEncoding}. While capable of handling type inclusion queries on \nhierarchies with multiple inheritance, the approach makes the closed world assumption and can be costly \nfor use with dynamic linking because it is not incremental.\nThe approach of Gibbs and Stroustrup~\\cite{FastDynCast} employs divisibility of \nnumbers to obtain a constant-time type inclusion test. The approach can handle \nmultiple inheritance and was the first constant-time technique to addresses the \nproblem of casts between subobjects. Unfortunately, the approach limits the size \nof the class hierarchies that can be encoded with this technique. \nDucournau proposed a constant-time inclusion test based on the fact that, in an \nopen solution, a class has a known number of base classes, and thus perfect hashes \ncan be used to map them to this-pointer offsets typically used to implement \nsubobject casts \\cite{Ducournau08}. Unfortunately, the approach addresses only \nvirtual multiple inheritance and (similarly to other approaches) relies on \nload-time computations. An excellent introduction to and detailed \nanalysis of existing constant-time type inclusion tests can be found in \n\\cite{Vitek97,PQEncoding}.\n\nWith the exception of work by Gibbs and Stroustrup~\\cite{FastDynCast}, all the \napproaches to efficient type-inclusion testing we found in the literature were \nbased on the assumption that \\emph{the outcome of a subtyping test as well as \nthe subsequent cast depend only on the target type and the dynamic type of \nthe object}. Although that assumption is sound for subtyping tests and subtype \ncasts for shared inheritance (including single), it does not reflect the \nrelationship between subobjects in the general case of multiple inheritance \nas found in \\Cpp{}.\n\n\\subsection{The Source of Inefficiency}\n\nWhile constant-time type inclusion tests are invaluable in optimizing subtype \ntests in programming languages, their use in implementing a type switch is \ninferior to some workaround techniques. This may prevent wide adoption of a \nlanguage implementation of such a feature due to its inferior performance. \nWe implemented 3 constant-time type inclusion tests: binary \nmatrix~\\cite{Vitek97}, Cohen's algorithm~\\cite{Cohen91}, and fast dynamic \ncast~\\cite{FastDynCast} and combined them with a decision tree to implement a \ntype switch on a class hierarchy ideally suited for such scenarios: a perfect binary tree with \nclasses number $2i$ and $2i+1$ derived from a class number $i$. Our workaround \ntechniques included the visitor design pattern and a switch on the sealed sequential \nset of tags.\n\n\\begin{figure}[htbp]\n \\centering\n \\includegraphics[width=0.47\\textwidth]{DCast-vs-Visitors.pdf}\n \\caption{Type switch based on constant-time subtype tests}\n \\label{fig:DCastVis2}\n\\end{figure}\n\nThe chart in Figure~\\ref{fig:DCastVis2} shows the number of cycles (Y-axis) each \ntechnique took to recognize an object of the dynamic type $i$ (X-axis). \nDespite known limitations, binary matrix and Cohen's algorithm are some of the \nfastest known type inclusion tests for single inheritance~\\cite{Vitek97}. It \nis nonetheless easy to see that the logarithmic cost associated with the \ndecision tree very quickly surpasses the constant overhead of double dispatch \n(20 cycles) present in the visitor design pattern or the jump-table \nimplementation of the switch on all tags (11 cycles). We expect the cost of \ntechniques capable of handling multiple inheritance to be even higher, especially \nthose addressing casting between subobjects (e.g. fast dynamic cast). The edgy \nshape of timing results reflects the shape of the class hierarchy used for this \nexperiment.\n%We show in \\textsection{sec:viscmp} that \n%our open solution is capable of delivering an amortized constant-time type \n%switching wi\n", "meta": {"hexsha": "5ab5bebdae207c2341023cebc9fd2a5c97d195e1", "size": 30727, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "media/papers/TypeSwitch/sec-problem.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/TypeSwitch/sec-problem.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/TypeSwitch/sec-problem.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": 59.3185328185, "max_line_length": 121, "alphanum_fraction": 0.7833826927, "num_tokens": 7284, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.1920988917628936}}
{"text": "% !TeX root = ./ms.tex\n\\documentclass[modern,linenumbers]{aastex62}\n\n% Load the corTeX style definitions\n\\input{cortex}\n\n% Load custom style\n\\input{style}\n\n% Force line numbers\n\\usepackage{lineno}\n\\linenumbers\n\n% Bibliography\n\\bibliographystyle{aasjournal}\n\n\\usepackage{etoolbox}\n\\makeatletter % we need to patch \\env@cases that has @ in its name\n\\patchcmd{\\env@cases}{\\quad}{\\qquad\\qquad}{}{}\n\\makeatother\n\n\\defcitealias{PaperII}{Paper II}\n\n\\usepackage{enumitem}\n\n\\newcommand{\\dfm}[1]{{\\color{blue}#1}}\n\n\\newcommand{\\shrinkage}{{variance reduction\\,}}\n\n% Begin!\n\\begin{document}\n\n% Title\n\\title{%\n \\vspace{-3em}\n \\textbf{\n Mapping stellar surfaces\\\\\n I: Degeneracies in the rotational light curve problem\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-9328-5652]{Daniel Foreman-Mackey}\n\\affil{Center~for~Computational~Astrophysics,~Flatiron~Institute,~New~York,~NY}\n%\n\\author[0000-0002-3385-8391]{Christina Hedges}\n\\affil{Bay~Area~Environmental~Research~Institute,~Moffett~Field,~CA}\n\\affil{NASA~Ames~Research~Center,~Moffett~Field,~CA}\n%\n\\author[0000-0003-2866-9403]{David W. Hogg}\n\\affil{Center~for~Computational~Astrophysics,~Flatiron~Institute,~New~York,~NY}\n\\affil{Center~for~Cosmology~and~Particle~Physics,~New~York~University,~New~York,~NY}\n\\affil{Center~for~Data~Science,~New~York~University,~New~York,~NY}\n\\affil{Max-Planck-Institut~f\\\"ur~Astronomie,~Heidelberg,~Germany}\n%\n\n\n\\keywords{time series analysis --- light curves --- stellar surfaces --- starspots}\n\n\\features{open-source figures \\codeicon; equation unit tests: \\input{tests/tally}}\n\n\\begin{abstract}\n %\n Thanks to missions like \\emph{Kepler} and \\emph{TESS}, we now\n have access to tens of thousands of high precision, fast\n cadence, and long baseline stellar photometric observations.\n %\n In principle, these light curves encode a vast amount of information about\n stellar variability and, in particular, about the distribution of\n starspots and other features on their surfaces.\n %\n Unfortunately, the problem of inferring stellar surface properties\n from a rotational light curve is famously ill-posed,\n as it often does not admit a unique solution.\n %\n Inference about the number, size, contrast, and location of spots\n can therefore depend very strongly on the assumptions of the model,\n the regularization scheme, or the prior.\n %\n The goal of this paper is twofold:\n (1) to explore the various degeneracies affecting the stellar\n light curve ``inversion'' problem and their effect on\n what can and cannot be learned from a stellar surface\n given unresolved photometric measurements; and\n (2) to motivate ensemble analyses of the light curves of\n many stars at once as a powerful data-driven alternative to common\n priors adopted in the literature.\n %\n We further derive novel results on the dependence of the null space\n on stellar inclination and limb darkening and\n show that single-band photometric measurements cannot uniquely\n constrain quantities like the total\n spot coverage without the use of strong priors.\n %\n This is the first in a series of papers devoted to the development\n of novel algorithms and tools for the analysis of\n stellar light curves and spectral time series, with the\n explicit goal of enabling statistically robust inference\n about their surface properties.\n\\end{abstract}\n\n\\section{Introduction}\n\\label{sec:intro}\n\nThe advent of space-based precision photometry with missions such as\n\\emph{Kepler} \\citep{Borucki2010} and \\emph{TESS} \\citep{Ricker2015}\nhas led to a renewed interest in the modeling of stellar light curves,\nand, in particular, in understanding what these light curves can tell\nus about the surfaces of stars across the HR diagram. One of the dominant\nsources of stellar light curve variability is the modulation caused\nby starspots rotating in and out of view.\nDark spots arise due to the suppression of convection in regions of\nintense magnetic field, resulting in a locally cooler (and hence darker)\nphotosphere. Bright spots can similarly\narise in the photosphere as faculae or in the chromosphere as plages, and\nare also magnetically driven \\citep[e.g.,][]{Berdyugina2005}.\n%\nConstraining the sizes,\ncontrasts, locations, and number of spots on stars can therefore reveal\ninformation about stellar magnetic activity, stellar interior structure,\nand how these quantities vary across spectral type and over time\n\\citep[e.g.,][]{Garraffo2018}.\nA detailed understanding of the stellar surface is also crucial to\nmitigating systematics in the radial velocity search for exoplanets\n\\citep[e.g.,][]{Lanza2011} and in the spectroscopic characterization of their\natmospheres \\citep[e.g.,][]{Rackham2018}.\n\nTo date, most studies aimed at inferring stellar surface\nproperties from light curves follow one of two broad approaches. The\nfirst is to model the stellar surface as a collection of one or more\ndiscrete, circular, uniform contrast dark or bright spots on a uniform\nintensity photosphere.\nThe advantage of this approach is that\nthe light curve can be computed efficiently and in some cases even\nanalytically \\citep[e.g.,][]{Davenport2015,Morris2017,Morris2020b}.\n%\nThe second approach is to discretize the surface at some resolution\nand compute the emergent flux as a weighted sum of the visible pixel intensities.\nThis approach is more flexible, since it is not limited to surfaces\ncomposed of distinct circular spots \\citep[e.g.,][]{Harmon2000,Roettenbacher2017}.\n%\nBoth approaches rely on an explicit \\emph{forward model}, a prescription for\nhow to generate data given a set of parameters. In most cases, however, we are interested\nin the inverse problem: constraining the parameters given data.\n%\nUnfortunately, the inverse problem is not only difficult---as it requires\na large number of forward model evaluations to find the parameter values\nthat are most consistent with the\ndata---but also formally \\emph{ill-posed}.\n%\nWhile the mapping from a stellar surface to a light curve (the forward\nproblem) is unique, the mapping from a light curve to a surface\n(the inverse problem) is not:\ngiven any light curve, there exist an infinite number of surfaces that\ncould have generated it. These degeneracies are illustrated in\nFigure~\\ref{fig:degeneracies}, where six synthetic stellar surfaces\nare shown (rows) at twelve different phases (columns), all at an\ninclination $I=60^\\circ$.%\n\\footnote{\n In this paper, we adopt the common convention where $I$ is the angle\n between the stellar spin axis and the line of sight,\n spanning $-90^\\circ \\leq I \\leq 90^\\circ$. An inclination $I=0^\\circ$ therefore\n corresponds to a pole-on orientation.\n}\nEach surface\nconsists of a different number of dark spots on a brighter, heterogeneous\nbackground.\n\n\\begin{figure}[t!]\n \\begin{centering}\n \\includegraphics[width=\\linewidth]{figures/degeneracies.pdf}\n \\oscaption{degeneracies}{%\n The fundamental limitations of the mapping problem. Each row\n corresponds to a stellar surface with a different number of\n dark spots seen at various phases at an inclination $I=60^\\circ$;\n all images are shown on the same color scale.\n The bottom panel shows the light curves of each of these stars.\n All six light curves are indistinguishable from each other, even\n at infinite signal to noise. See text for details.\n \\label{fig:degeneracies}\n }\n \\end{centering}\n\\end{figure}\n\nWhile the stellar surfaces are all distinct, containing between one (top)\nand six (bottom) large dark spots,\n\\textbf{their rotational light curves are identical}\n(lower panel). This is true even in the absence of measurement\nerror: the mapping from a stellar surface\nto its rotational light curve is so degenerate that there exist an infinite number of solutions\nto the inverse problem. This fact has been pointed out recently in different contexts\n\\citep[e.g.,][]{Cowan2013,Rauscher2018,Sandford2019,Luger2019,Basri2020}, but it dates back at least to\n\\citet{Russell1906}, who demonstrated it by expanding the surface\nintensity of a celestial body in terms of spherical harmonics\n(see Figure~\\ref{fig:ylms}). \\citet{Russell1906} showed\nthat many of the modes comprising the intensity profile of a spherical\nobject are in the \\emph{null space}, the set of surface features that have identically\nzero effect on the light curve. In fact, as we will show in \\S\\ref{sec:nullspace},\nthe \\emph{vast majority} of the modes are in the null space for rotational\nlight curves of stars. This is what allows us to construct pathological\nscenarios like that shown in Figure~\\ref{fig:degeneracies}, where the light curve\ncould be explained by any number of spots atop a heterogeneous bright background.\n\nStellar mapping studies tackle these degeneracies in different ways, but\nit usually comes down to a choice of prior: when the data is not\nsufficiently informative, assumptions---either implicit or explicit---are needed to discriminate\nbetween competing solutions. In discrete spot models like the ones\ndiscussed above, the degeneracy-breaking prior is (typically) the assumption that the\nspots must be circular, have uniform contrast, and sit atop an otherwise\nuniform photosphere. In gridded stellar surface models, it is common to\nassume a regularization prior such as the maximum entropy penalty\n\\citep[e.g.,][]{Vogt1987}, which typically favors solutions with the fewest\nnumber of dark pixels (usually referred to as the ``simplest'' solution).\n\nWhile these assumptions may be approximately valid in some cases, it is\nimportant to bear in mind that because of the light curve degeneracies discussed above,\n\\textbf{most of the information about the stellar surface usually comes from the modeling assumptions},\nso it is very important to get these assumptions right. In general, starspots are not circular and do not have uniform\ncontrast throughout; nor do spots always arrange themselves in the highest\nentropy configuration. The amount of bias introduced by these assumptions\nwill in general vary, but in principle it could be quite significant.\n\n% Add to this photometric noise, the generally unknown stellar inclination,\n% the poorly constrained limb darkening parameters, and you get ... a mess.\n\nThe goal of this paper is to explore the degeneracies at play in the\nstellar surface mapping problem from a theoretical standpoint.\nWe will focus in particular on two sources of degeneracies: the\nnull space intrinsic to the mapping from a two-dimensional surface to\na one-dimensional light curve (\\S\\ref{sec:nullspace})\nand the degeneracy due to the unknowability of the true normalization in\nsingle-band photometry (\\S\\ref{sec:normalization}). Within each section we\nwill discuss ways to either break these degeneracies or marginalize\nover unknowable quantities.\nWe will focus in particular on the power of ensemble analyses: the\njoint analysis of many light curves of statistically ``similar''\nstars. We will show that even though individual light curves are not very\nconstraining, light curves of many stars\nobserved at different inclinations can uniquely constrain certain\nproperties of the surfaces of those stars.\n%\nThis idea was recently explored to some extent\nin \\citet{Morris2020}, who used ensemble analyses to derive constraints on\nspot coverage areas as a function of stellar age. However, one of\nthe main conclusions of the present paper is that\nquantities like \\textbf{the\n total spot coverage and the total number of\n spots are not direct observables in single-band photometry.} Instead,\nany constraints placed on these quantities, even in the context of\nensemble analyses, are usually driven by the choice of prior and other assumptions.\n\nThe present paper is also similar to \\citet{Walkowicz2013} and\n\\citet{Basri2020}, who explored the information content of\nstellar light curves from a large set of simulated spotted stellar\nsurfaces. While our paper is largely complementary to\nthat work, we instead approach the information content problem from\na theoretical---as opposed to empirical---point of view.\n%\nThe present paper is the first in a series dedicated to the development of\ntechniques to perform robust inference about stellar surfaces from\nunresolved photometric and spectroscopic measurements. The results\nof this paper serve as the starting point for the development of\nan interpretable Gaussian process for the ensemble analysis of\nstellar light curves, which is the subject of\n\\citepalias[\\citealt{PaperII}, hereafter][]{PaperII}.\n\n\\vspace{1em}\n\nAll of the figures in this paper were auto-generated\nusing the Azure Pipelines continuous integration (CI) service.\nIcons next to each of the figures \\codeicon \\,\nlink to the exact script used to generate them to ensure the reproducibility\nof our results. In this paper we also introduce the concept of equation\n``unit tests'': \\textsf{pytest}-compatible test scripts associated\nwith the principal equations that pass (fail) if the equation is correct (wrong),\nin which case a clickable \\testpassicon \\, (\\testfailicon) is shown next to the equation\nlabel.\nIn most cases, the validity of an equation is gauged by comparison to\na numerical solution. Like the figure scripts, the equation unit tests are\nrun on Azure Pipelines upon every commit of the code.%\n\\footnote{\n These unit tests are certainly not foolproof: in particular, there is\n no guarantee against a mismatch in the \\LaTeX \\, version of an equation\n and its \\Python implementation (e.g., due to an uncaught typo). However, they\n \\emph{do} ensure that the linked \\Python implementation is correct to\n within the accuracy of the numerical solution, providing readers with a\n valid implementation of the equation for purposes of reproducibility.\n}\n\n\\section{The null space}\n\\label{sec:nullspace}\n\nIn this section, we define the concept of the \\emph{null space}\nand present some demonstrations showing how it can affect inferences\nabout stellar surfaces.\nFor simplicity, we assume we know quantities like the stellar\ninclination, rotation period, and limb darkening coefficients\nexactly, and we assume the stellar surface does not vary in time\n(i.e., spots do not evolve and the star rotates as a rigid body).\nBecause of these assumptions, our constraints on the information\ncontent of light curves should be viewed as strict \\emph{upper limits}.\n\nWe also present some examples of how the degeneracies due to\nthe null space can be tackled.\nWhile our examples below may appear somewhat idealized, at the end\nof this section we discuss how our ideas generalize to more\nrealistic scenario; we also revisit these assumptions in \\S\\ref{sec:caveats}.\nThis is also a topic that we discuss in much more detail in \\citetalias{PaperII}.\n\n\\begin{figure}[t!]\n \\begin{centering}\n \\includegraphics[width=\\linewidth]{figures/ylms.pdf}\n \\oscaption{ylms}{%\n The real spherical harmonics in the polar frame\n ($\\hat{\\mathbf{x}}$ points to the right,\n $\\hat{\\mathbf{y}}$ points up, and $\\hat{\\mathbf{z}}$\n points out of the page)\n up to $l = 5$. Dark colors correspond to negative intensity\n and bright colors to positive intensity;\n rows correspond to the degree $l$ and columns to\n the order $m$. The set of all spherical harmonics forms a\n complete, orthogonal basis on the sphere.\n \\label{fig:ylms}\n }\n \\end{centering}\n\\end{figure}\n\n\\subsection{Rank of the flux operator}\n%\nIn general, inferring all of the properties of a stellar surface from its light curve alone\nis not\nonly difficult, but \\emph{formally impossible}. To understand why, consider\nan expansion of the stellar surface intensity in the spherical\nharmonic basis out to arbitrary order%\n\\footnote{%\n We note that this expansion is fully general, since spherical harmonics\n constitute a complete basis on the sphere.\n} (see Figure~\\ref{fig:ylms}).\nAssuming (for the moment) that the\nstar rotates about an axis that points up along the page, the observed\nlight curve may be expressed as a weighted sum of the disk-integrated intensity\nof each of the spherical harmonics as they rotate about that same axis \\citep{Luger2019}.\nHowever, not all spherical harmonics will contribute to the full light curve,\nas many (in fact, most) of the spherical harmonics are perfectly antisymmetric\nabout the equator. This is the case for\nthe $l = 1$, $m = -1$ harmonic, which integrates to zero regardless of\nthe phase at which it is viewed. The same is true, in fact, for all other harmonics\nof order $m = -1$ and (perhaps less obviously) for all harmonics with odd\n$l = 3, 5, 7, ...$ Furthermore, there exist many linear combinations of\nspherical harmonics that similarly integrate to zero at all rotational\nphases. Together, these modes constitute the \\emph{null space} of the problem:\nthe set of modes on the surface that do not contribute to the observed\nlight curve and therefore cannot be probed from photometry.\n\nFor rotational light curves,\nthe vast majority of the surface modes lie in the null\nspace. To show this, we will make use of the fact that we can express\nthe vector of $K$ observed fluxes $\\mathbf{f}$ (i.e., the light curve)\nas a linear operation on the vector of $N$\nspherical harmonic coefficients $\\mathbf{y}$ \\citep{Luger2019}:\n%\n\\begin{linenomath}\\begin{align}\n \\label{eq:fAy}\n \\mathbf{f} = \\mathbf{1} + \\pmb{\\mathcal{A}} \\, \\mathbf{y}\n \\quad,\n \\end{align}\\end{linenomath}\n%\nwhere $\\pmb{\\mathcal{A}}$ is the $(K \\times N)$ \\emph{design matrix} of the transformation, whose columns\ndescribe how each of the $N$ components in the spherical harmonic basis contribute\nto each of the $K$ points in the light curve.%\n\\footnote{%\n For rotational light curves, the rows of $\\pmb{\\mathcal{A}}$ are given by the\n quantity $\\mathbf{r}^\\top \\pmb{\\mathcal{A}}_1 \\mathbf{R}$ in Equation~(18) of\n \\citet{Luger2019}, where $\\mathbf{r}^\\top$ is a vector of disk-integrated\n intensities, $\\pmb{\\mathcal{A}}_1$ is a change of basis matrix, and $\\mathbf{R}$\n is a spherical harmonic rotation matrix that depends on the stellar inclination\n and the rotational phase of the star. In Equation~(\\ref{eq:fAy}) we explicitly\n add a vector of ones to enforce a unit baseline for spotless stars.\n Refer to \\citet{Luger2019} for more details.\n}\n%\nEven though we are explicitly choosing the spherical harmonics as the basis in which\nwe describe the stellar surface, Equation~(\\ref{eq:fAy}) is quite general and applies to\n\\emph{any} basis that is linearly related to the flux. For instance, $\\mathbf{y}$\ncould instead describe the intensity deficits in each of the $N$ pixels of a gridded stellar\nsurface, in which case $\\pmb{\\mathcal{A}}$ would be the matrix of pixel visibilities that describe\nhow to sum each of the pixels to obtain the observed light curve.\n\nThe size of the null space is called the \\emph{nullity}, and it is equal to\n$N - R$, where $N$ is once again the number of coefficients describing the\nstellar surface and $R$ is the \\emph{rank} of the flux operator $\\pmb{\\mathcal{A}}$.\nThe rank $R$ is the number of linearly independent columns in $\\pmb{\\mathcal{A}}$, which\ncan be computed numerically using any standard linear algebra package. It is equal\nto the number of independent components that can be measured given\nan observation of $\\mathbf{f}$.\n\n\\begin{figure}[t!]\n \\begin{centering}\n \\includegraphics[width=\\linewidth]{figures/rank.pdf}\n \\oscaption{rank}{%\n Rank and nullity of the flux operator. The orange curve\n shows the number of spherical harmonic coefficients required\n to fully describe a stellar surface up to a given spherical\n harmonic degree (bottom axis) or, equivalently, up to an\n effective surface resolution (top axis). The blue curve shows\n the rank of the flux operator, corresponding to the maximum\n number of independent degrees of freedom that can be constrained from a\n light curve. The size of the null space (the nullity) is\n the difference between the two curves.\n \\label{fig:rank}\n }\n \\end{centering}\n\\end{figure}\n\nFigure~\\ref{fig:rank} shows the rank and nullity of the flux operator\nas a function of the resolution of the surface map (quantified as the\nspherical harmonic degree $l$ of the expansion). The orange\ncurve is the number of spherical harmonic coefficients needed to\nrepresent a surface map up to degree $l$, and is equal to $N = (l + 1)^2$.\nThe blue line shows the rank of the flux operator $\\pmb{\\mathcal{A}}$ as a function\nof $l$, which scales as $R \\approx 2l + 1$. The nullity is\nsimply the difference between $N$ and $R$.\n\nThe most striking feature in Figure~\\ref{fig:rank} is how quickly the two\ncurves diverge as $l$ increases. What this means for the mapping problem\nis that the number of surface modes---the total information needed to\nrepresent a surface map at some resolution---grows much more quickly than the\nnumber of independent degrees of freedom in the light curve.\n%\nAt all but the lowest resolutions, there are always more features in the\nnull space than components one can measure in the light curve, a difference\nthat grows \\emph{quadratically} with $l$.\n%\nThis means that although a light curve can tell us some information about\na stellar surface on very large scales, the amount of information it tells\nus quickly decreases for smaller scales and all but vanishes for the smallest\nsurface features.\n\nIt is also worth noting the piecewise nature of the rank as a function of\n$l$: increasing the degree of the expansion from even $l$ to odd $l$ does not\nincrease the rank of the flux operator. Put another way, odd spherical\nharmonic modes with $l > 1$ are always in the null space of the light curve.\nWe will return to this point below.\n\n\\subsection{Decomposition of the flux operator}\n%\n\\label{sec:svd}\n%\nIn Appendix~\\ref{sec:app-svd} we show that it is straightforward to\nconstruct linear operators $\\mathbf{P}$ and $\\mathbf{N}$ from the\ndesign matrix $\\pmb{\\mathcal{A}}$ such that\n%\n\\begin{linenomath}\\begin{align}\n \\mathbf{y}_\\bullet & = \\mathbf{P} \\, \\mathbf{y}\n \\end{align}\\end{linenomath}\n%\nis the component of the surface map in the \\emph{preimage} and\n%\n\\begin{linenomath}\\begin{align}\n \\mathbf{y}_\\circ & = \\mathbf{N} \\, \\mathbf{y}\n \\end{align}\\end{linenomath}\n%\nis the component of the map in the \\emph{null space}.\n%\nThe \\emph{preimage operator} $\\mathbf{P}$\ntransforms a vector $\\mathbf{y}$ in the surface map basis in such a way\nthat it preserves the information in $\\mathbf{y}$ that gets mapped\nonto the light curve $\\mathbf{f}$ via $\\pmb{\\mathcal{A}}$ (the \\emph{preimage}) and discards the rest. The\n\\emph{null space operator} $\\mathbf{N}$ does the opposite: it preserves only\nthe information in $\\mathbf{y}$ that gets mapped onto the zero\nvector via $\\pmb{\\mathcal{A}}$ (the \\emph{null space}).\n%\nIn other words,\nthe $\\mathbf{P}$ and $\\mathbf{N}$ operators reveal the\ncomponents of the surface map that contribute to the\nlight curve ($\\mathbf{y}_\\bullet$) and the components that don't ($\\mathbf{y}_\\circ$).\nThe vector $\\mathbf{y}_\\bullet$ represents all the information that can be\nlearned from a stellar light curve, while $\\mathbf{y}_\\circ$ represents all the\ninformation that cannot.\n\n\\begin{figure}[p!]\n \\begin{centering}\n %\n \\vspace{-4em}\n \\includegraphics[width=1in]{figures/wireframe_60.pdf}\n \\\\[0.5em]\n \\includegraphics[width=\\linewidth]{figures/nullspace_preimage_60a.pdf}\n \\\\[1em]\n \\includegraphics[width=\\linewidth]{figures/nullspace_preimage_60b.pdf}\n \\\\[1em]\n \\includegraphics[width=\\linewidth]{figures/nullspace_preimage_60c.pdf}\n \\\\[1em]\n \\includegraphics[width=\\linewidth]{figures/nullspace_preimage_60d.pdf}\n \\oscaption{nullspace_preimage}{%\n Decomposition of a surface map (left column) into its\n preimage (center) and null space (right) components\n for different surfaces, and their corresponding contributions\n to the rotational light curve. The preimage is the\n set of surfaces modes that map onto the light curve;\n the null space is the set of modes that do not.\n An inclination of $60^\\circ$ is assumed when computing the flux.\n The vast majority of surface modes are in the null space\n of the light curve problem and therefore do not contribute\n to the observed flux.\n \\label{fig:nullspace_preimage}\n }\n \\end{centering}\n\\end{figure}\n\n\\begin{figure}[p!]\n \\begin{centering}\n %\n \\vspace{-4em}\n \\includegraphics[width=1in]{figures/wireframe_85.pdf}\n \\\\[0.5em]\n \\includegraphics[width=\\linewidth]{figures/nullspace_preimage_85a.pdf}\n \\\\[1em]\n \\includegraphics[width=\\linewidth]{figures/nullspace_preimage_85b.pdf}\n \\\\[1em]\n \\includegraphics[width=\\linewidth]{figures/nullspace_preimage_85c.pdf}\n \\\\[1em]\n \\includegraphics[width=\\linewidth]{figures/nullspace_preimage_85d.pdf}\n \\oscaption{nullspace_preimage}{%\n Same as Figure~\\ref{fig:nullspace_preimage}, but for\n a stellar inclination of $85^\\circ$. As the stellar rotation vector\n becomes perpendicular to the line of sight, it becomes\n more difficult to constrain latitudinal information.\n \\label{fig:nullspace_preimage_85}\n }\n \\end{centering}\n\\end{figure}\n\nIt is instructive to visualize these components in\nan actual surface mapping exercise. Figure~\\ref{fig:nullspace_preimage}\nshows the decomposition of four hypothetical surfaces (left\ncolumn) into preimage (center) and null space (right)\ncomponents under the flux operator $\\pmb{\\mathcal{A}}$, which we compute for\ndefiniteness at an inclination of $I = 60^\\circ$ over a full rotation.\nSurfaces are shown in an equal-area Mollweide projection alongside\nthe corresponding light curves.\nNote that both the true map and its associated light curve are simply equal to\nthe sum of the preimage and null space components (Appendix~\\ref{sec:app-svd}).\n%\nAs expected, all of the information in the light curve comes\nfrom the preimage, and the null space contributes exactly zero\nflux at all phases. However, most of the information about the\n\\emph{surface} is stuck in the null space!\n\nIn the top row of the figure, corresponding to a surface with\na single large spot, it is clear that the light curve\ncontains information about the presence of the spot at roughly the\ncorrect longitude and latitude. There are additional artefacts\nacross the stellar surface, and the exact shape of the spot is\nnot well constrained by the data; these issues, however, can\neasily be resolved with a circular spot prior.\n\nThe degeneracies of the mapping problem are much more apparent\nin the second and third rows, corresponding to surfaces with\nmany, smaller spots. The locations, sizes, and the very existence\nof most of the spots are simply not encoded in the light curve.\nEven with an extremely restrictive prior, it may be difficult---if\nnot impossible---to learn the properties of the spots\nfrom the individual light curves.\n\nThe final row corresponds to a surface with much higher resolution\nfeatures; this example highlights how the information content of\nlight curves all but vanishes at small scales. Virtually all of the\nspatial information at the scales of interest is in the null space.\n\n\\subsection{Implications for inference}\n%\nThe model mapping spherical harmonic coefficients to observed fluxes described\nin the preceding sections is linear, so we might expect that we could fit\nfor the spherical harmonics using linear least-squares\n%\n\\begin{linenomath}\\begin{align}\n \\label{eq:linlstsq}\n \\hat{\\mathbf{y}} & \\stackrel{?}{=}\n \\left(\\pmb{\\mathcal{A}}^\\top\\,\\pmb{\\mathcal{A}}\\right)^{-1}\\,\\pmb{\\mathcal{A}}^\\top\\,\\left(\\mathbf{f} - \\mathbf{1}\\right)\n \\quad.\n \\end{align}\\end{linenomath}\n%\nBut, since the flux operator $\\pmb{\\mathcal{A}}$ is low-rank, the model is\nunderdetermined, so the above operation is not defined and, equivalently,\nthe Fisher information matrix\n%\n\\begin{linenomath}\\begin{align}\n \\label{eq:fisher-info}\n \\pmb{\\mathcal{I}}(\\mathbf{y}) & = \\frac{1}{\\sigma_f^2} \\, \\pmb{\\mathcal{A}}^\\top\\,\\pmb{\\mathcal{A}}\n \\end{align}\\end{linenomath}\n%\nis singular.\nIn Equation~(\\ref{eq:fisher-info}), $\\sigma_f$ is the flux measurement uncertainty.\nThere exist many methods and procedures for linear regression for underdetermined\nmodels, but all solutions amount to imposing stronger assumptions about the\nmodel in order to break the degeneracies.\n\nOne standard method is regularized least squares, in which\nEquation~(\\ref{eq:linlstsq}) becomes\n%\n\\begin{linenomath}\\begin{align}\n \\hat{\\mathbf{y}}_\\lambda & \\equiv\n \\left(\\pmb{\\mathcal{A}}^\\top\\,\\pmb{\\mathcal{A}} + \\lambda\\,\\mathbf{I}\\right)^{-1}\\,\\pmb{\\mathcal{A}}^\\top\\,\\left(\\mathbf{f} - \\mathbf{1}\\right)\n \\end{align}\\end{linenomath}\n%\nwhere $\\mathbf{I}$ is the identity matrix and $\\lambda$ is a parameter\ncontrolling the strength of the regularization.\nIn a Bayesian context, this can be interpreted as placing a Gaussian prior\nwith variance $\\sigma_0^{2} = \\nicefrac{\\sigma_f^2}{\\lambda}$ on the spherical harmonic coefficients.\n\nIn the limit of infinitesimal regularization, it can be demonstrated\n\\citep[see][for example]{Hogg2021} that\n%\n\\begin{linenomath}\\begin{proof}{test_svd_lstsq}\n \\label{eq:inference}\n \\lim_{\\lambda \\rightarrow 0_+} \\hat{\\mathbf{y}}_\\lambda\n % &=\n % \\lim_{\\lambda \\rightarrow 0} \\left( \\pmb{\\mathcal{A}}^\\top \\pmb{\\mathcal{A}} + \\lambda \\mathbf{I}\\right)^{-1} \\pmb{\\mathcal{A}}^\\top (\\mathbf{f} - \\mathbf{1})\n % \\nonumber\\\\\n &= \\mathbf{y}_\\bullet\n \\quad.\n \\end{proof}\\end{linenomath}\n%\nIn this sense, $\\mathbf{y}_\\bullet$ represents our knowledge about the\nsurface of a star after an observation if we have no prior information\nwhatsoever on $\\mathbf{y}$.\n\\emph{Any other information about the surface is entirely driven by our assumptions.}%\n\n% It is interesting to quantify the information content of a light curve as a\n% function of spherical harmonic coefficients.\n% While Equation~(\\ref{eq:fisher-info}) provides a compact expression for the\n% Fisher information matrix, the most important feature that we want to quantify\n% is the covariance between coefficients.\n% This is most naturally captured by the covariance matrix of the likelihood\n% function for the spherical harmonic coefficients:\n% %\n% \\begin{linenomath}\\begin{align}\n% \\pmb{\\Sigma}_\\lambda & =\n% \\sigma^2\\,\\left(\\pmb{\\mathcal{A}}^\\top\\,\\pmb{\\mathcal{A}} + \\lambda\\,\\mathbf{I}\\right)^{-1} \\quad.\n% \\end{align}\\end{linenomath}\n% %\n% Below, we use this to quantify the width of the likelihood for each spherical\n% harmonic coefficient by plotting the ``relative variance'' $S$, which we define\n% as the diagonal of the matrix $\\pmb{\\Sigma}_\\lambda$ in units of\n% $\\lambda / \\sigma^2$ in the limit where $\\lambda \\to 0_+$.\n% This choice of units constrains $0 \\le S \\le 1$ and allows easy comparisons\n% between the information content of different datasets without being sensitive\n% to the specific modeling assumptions.\n% Under this definition, when $S$ approaches one for a particular coefficient,\n% this means that the likelihood function provides no information about that\n% coefficient, while $S = 0$ indicates that that coefficient can be perfectly measured.\n\n% This relative variance $S$ can be interpreted either as the Cram\\'er--Rao\n% lower bound on the variance of an estimator for a spherical harmonic\n% \\citep[e.g.,][]{Li2012}, although our specific choice of units are somewhat\n% non-standard.\n% Similarly, in a Bayesian context, this is the ``posterior shrinkage'', the\n% ratio of the posterior variance to the prior variance in the limit of\n% infinite prior variance \\citep[e.g.,][]{Betancourt2018}.\n\nEquation~(\\ref{eq:inference}) is the solution to the surface map\nwe would obtain if we knew \\emph{nothing} about the stellar surface\nbefore analyzing the light curve. In practice, this is never really\nthe case. For instance, we know that stellar surfaces\nmust have non-negative intensities everywhere. While this may seem\nlike a trivial prior, non-negativity can be a powerful degeneracy-breaking\nconstraint \\citep[e.g.,][]{Fienup1982}. Moreover, we know that\nstellar surfaces usually consist of localized features; under an\nappropriate compactness prior, solutions\nlike the preimage in the bottom row of\nFigure~\\ref{fig:nullspace_preimage} (for example) could be\nconfidently ruled out.\n\nThe effect of different modeling assumptions on the structure and size of the null\nspace is beyond the scope of this paper. In general, this is a particularly\ndifficult question to address because non-Gaussian priors on the\nsurface map break the linearity of the problem. While compactness constraints\n(like the assumption of a small number of discrete circular spots) can\nbreak many of the degeneracies discussed here, simulation-based\narguments show that it is still not possible to uniquely constrain\ntheir number, locations, or sizes from individual light curves\n\\citep{Basri2020}.\n\n% TODO:\n% In principle, the decomposition into preimage and nullspace could\n% depend on the basis we're using to represent the surface map. If\n% I do this in the pixel basis, I typically get a different result,\n% BUT the result converges to the plots in Figure 4 as the number of\n% pixels in the basis increases!\n% So I suspect that as long as the basis is complete and has certain\n% properties -- orthogonality perhaps? -- the preimage/nullspace\n% decomposition is unique.\n% Another interesting thing is that the preimage/nullspace is the SAME\n% even when the \"true\" map is generated at much higher spherical\n% harmonic degree. So the thing I'm showing seems to actually be\n% robust to all these things!\n% Perhaps Hogg has some insight?\n\n\\subsection{Dependence on inclination}\n\\label{sec:inclination}\n\nFigure~\\ref{fig:nullspace_preimage_85} shows the same decomposition\nof stellar surfaces into what can be learned (the preimage) and what\ncannot be learned (the null space) from a light cuve, but this time\nfor stars viewed at an inclination $I = 85^\\circ$. Interestingly,\nthe structure of the null space is somewhat different; in particular,\nfeatures in the preimage are latitudinally smeared. This\nissue is well known \\citep[e.g.,][]{Cowan2009,Basri2020}, and any\ninformation about which hemisphere a feature is in formally vanishes\nas $I \\rightarrow 90^\\circ$.\n\nInstead of lamenting the difficulties of constraining stellar surface features\nat near-edge-on orientations, let us focus on the fact that the\nnull space is a function of inclination.\n%\nA useful property of\nthe spherical harmonics is that a rotation operation on any\ncomponent in the basis can only change the order $m$ of the\nharmonic; the degree $l$ is constant under rotation. In other\nwords, rotating any of the spherical harmonics in Figure~\\ref{fig:ylms}\nabout an arbitrary axis simply yields a weighted sum of the spherical\nharmonics along its row.%\n\\footnote{For instance, rotation of $Y_{1,-1}$ by $90^\\circ$ about\n $\\hat{\\mathbf{x}}$ yields $Y_{1,1}$; other rotations will in general\n yield a weighted combination of $Y_{1,-1}$, $Y_{1,0}$, and $Y_{1,1}$.}\nThis means that changing the inclination of the star---which changes\nthe axis of rotation in the observer's frame---simply changes the weighting\nof modes that give rise to certain signals in the light curve.\nThis, in turn, results in the dependence of the null space on inclination.\n\nTo better understand this effect, let us define the quantity\n%\n\\begin{linenomath}\\begin{align}\n S \\equiv\n 1 -\n \\lim_{\\lambda \\rightarrow 0_+}\n \\mathrm{diag}\n \\left(\n \\lambda\n \\left(\\pmb{\\mathcal{A}}^\\top\\,\\pmb{\\mathcal{A}} + \\lambda\\,\\mathbf{I}\\right)^{-1}\n \\right)\n \\quad,\n \\end{align}\\end{linenomath}\n%\nwhich we will refer to as the \\emph{\\shrinkage}\nof the coefficients $\\mathbf{y}$ characterizing the stellar surface.\nNote that in a Bayesian context, this is\nequivalent to the \\emph{posterior shrinkage}\n%\n\\begin{linenomath}\\begin{align}\n \\label{eq:shrinkage}\n S = 1 - \\lim\\limits_{\\sigma_0^2 \\rightarrow \\infty}\n \\frac{\\sigma^2}{\\sigma_0^2}\n \\quad,\n \\end{align}\\end{linenomath}\n%\nwhere $\\sigma_0^2$ is the prior variance\nand $\\sigma^2$ is the posterior variance\non a particular surface mode we are trying to constrain\n\\citep[see, e.g.,][]{Betancourt2018}.\n\nThe \\shrinkage is a dimensionless quantity describing how informative a measurement is about a\ngiven mode on the surface in the limit of infinite signal-to-noise ratio (SNR)\nand is independent of what the stellar surface actually looks like.\nIf, at infinite SNR and with no regularization\n(or, in a Bayesian context, a completely uninformative prior),\na particular mode can be learned exactly from a dataset, the \\shrinkage\nis defined to be unity. Conversely, if the data is completely\nunconstraining of that mode (i.e., it is entirely in the null space),\n$S$ will tend to zero.\n\n\\begin{figure}[t!]\n \\begin{centering}\n \\includegraphics[width=\\linewidth]{figures/nullspace_ensemble_single.pdf}\n \\oscaption{nullspace_ensemble}{%\n The \\shrinkage as a function of spherical harmonic\n degree $l$ given a single observation of a star at a random\n inclination (thin blue curves). The mean \\shrinkage is shown\n as the thicker curve. The information content of light curves\n tends to zero as $l$ increases, and odd $l > 1$ modes are in the\n null space at all inclinations.\n \\label{fig:nullspace_ensemble_single}\n }\n \\end{centering}\n\\end{figure}\n\nFigure~\\ref{fig:nullspace_ensemble_single} shows the \\shrinkage $S$\ngiven a single observation of a star at a random inclination.\nEach thin blue curve corresponds to a particular draw from an isotropic\ninclination distribution; the thick blue curve is the average over 300 trials.\nFor some of the low-degree modes, $S$ is relatively high: it is\nfairly easy to constrain the dipole moment from a light curve, as this is\nusually the dominant sinusoidal signal. However, as the degree $l$\nincreases, $S$ decreases dramatically: at $l = 14$, corresponding\nto features on scales of roughly $13^\\circ$, the light curve\ncan only tell us about $\\sim 10\\%$ of the total information about what the\nsurface looks like. As $l$ increases further, $S$ tends to zero.\nAnother important feature of $S$, which we hinted at above,\nis that it is exactly zero for\nall odd-degree modes above $l = 1$. This is a well-known fact: all odd spherical\nharmonics other than the dipole are in the null space \\emph{regardless of\n inclination} \\citep[e.g.,][]{Luger2019}. In other words, these spherical\nharmonics are perfectly antisymmetric in projection over the unit disk\nwhen viewed from any orientation. Absent structure to break these symmetries\n(see below), we simply cannot learn anything about these modes from\nstellar light curves. If we average over $S$ for all modes up to $l=15$,\nwe find that a single light curve measurement can only tell us $\\sim 9\\%$\nof the information about the surface on those scales.\n\nFortunately, however, there is quite a bit of scatter in $S$\nfor different values of the stellar inclination.\nAs we will see, we can use this dependence of the null space on inclination to our\nadvantage. If we could observe a star from many different vantage points,\nwe would be able to break many of the degeneracies at play, since we\nwould get different constraints on the amplitude of each mode when viewed\nat different inclinations. This, of course, is not possible (at least not\nyet!). But what we \\emph{can} do is observe many similar stars, each viewed\nat a different (random) inclination, and attempt to learn something about\nthe properties of the ensemble of stars as a whole.\nIn the\nfollowing section, we explore the role of ensemble analyses in breaking\nthe degeneracies of the mapping problem in more detail.\n\n\n\\subsection{Ensemble analyses}\n\\label{sec:ensemble}\n\nIn an ensemble analysis, we assume we observe the lightcurves of many stars\nthat are ``similar'' in some statistical sense. As a thought experiment,\nlet us consider an extreme version of ensemble analysis in which all the\nstars in our sample happen to have \\emph{identical} surfaces. We will\nstill assume they are oriented at random inclinations, as we would expect for\nfield stars.\n%\nFigure~\\ref{fig:nullspace_ensemble} shows the \\shrinkage\ncurves for this hypothetical scenario, assuming we have access to\nlight curves of 1 (blue), 3 (orange), 10 (green) and 30 (red)\nidentical stars viewed at random inclinations.\n\n\\begin{figure}[t!]\n \\begin{centering}\n \\includegraphics[width=\\linewidth]{figures/nullspace_ensemble.pdf}\n \\oscaption{nullspace_ensemble}{%\n Similar to Figure~\\ref{fig:nullspace_ensemble_single}, but\n assuming the observer can measure the light curves\n of 1 (blue), 3 (orange), 10 (green), and 30 (red) \\emph{identical}\n stars--(same surface map, same rotational phase--but viewed at random orientations.\n As we saw in Figure~\\ref{fig:nullspace_ensemble_single},\n the information content in the light curve of a star observed\n from a single vantage point approaches zero as $l$\n increases. However, observing many identical stars from different vantage points\n allows one to recover nearly all of the information in the\n even spherical harmonic modes. This is why ensemble analyses of\n many similar stars at different inclinations allows us to infer\n their surface properties.\n \\label{fig:nullspace_ensemble}\n }\n \\end{centering}\n\\end{figure}\n\nThe addition of light curve measurements at different orientations\nincreases the \\shrinkage at all even spherical harmonic degrees\n(the odd degrees, as we mentioned above, are always invisible).\nNote that since we are in the limit of infinite SNR, the fact that we have\nmore light curves (i.e., more data) is irrelevant: the\nincrease in the \\shrinkage is instead due to the fact that our observations\nfrom different vantage points broke some degeneracies in the problem.\nThis is a consequence of the fact we mentioned in the previous section:\nthe null space (for the even modes)\nis a strong function of the inclination.\n\nIf we average over all modes, we obtain an average $S$ of $\\sim 24\\%$\nfor $l\\leq15$ when our sample size is 3 (orange curves): we have more than doubled the\ninformation content of our observations. If we further increase our sample size\nto 10 (green curves), the \\shrinkage approaches $100\\%$ for all even $l\\leq15$\nmodes, effectively saturating for a sample size of 30 (red curves).\nThus, if we were able to measure light curves of identical stars\nfrom many different inclinations, the null space would consist \\emph{only}\nof the odd modes. In the limit of a large number of light curves,\nand assuming all stars in the sample have identical surfaces,\n\\textbf{ensemble analyses can tell us up to\n half of all the information about the stellar surfaces.}\n\n\\begin{figure}[p!]\n \\begin{centering}\n %\n %\n \\vspace{-4em}\n \\includegraphics[width=1in]{figures/wireframe_30.pdf}\n \\includegraphics[width=1in]{figures/wireframe_45.pdf}\n \\includegraphics[width=1in]{figures/wireframe_60.pdf}\n \\includegraphics[width=1in]{figures/wireframe_75.pdf}\n \\\\[0.5em]\n \\includegraphics[width=\\linewidth]{figures/nullspace_preimage_a.pdf}\n \\\\[1em]\n \\includegraphics[width=\\linewidth]{figures/nullspace_preimage_b.pdf}\n \\\\[1em]\n \\includegraphics[width=\\linewidth]{figures/nullspace_preimage_c.pdf}\n \\\\[1em]\n \\includegraphics[width=\\linewidth]{figures/nullspace_preimage_d.pdf}\n \\oscaption{nullspace_preimage}{%\n Same as Figures~\\ref{fig:nullspace_preimage} and \\ref{fig:nullspace_preimage_85}, \\\n but assuming we can measure the light curves of these stars from many\n different inclinations. In this limit, the information content of our\n data approaches $50\\%$ of the spatial information about the surface.\n \\label{fig:nullspace_preimage_ensemble}\n }\n \\end{centering}\n\\end{figure}\n\nTo understand what we can learn about the surfaces in this limit, let us\nreturn to the stellar surfaces we considered in Figures~\\ref{fig:nullspace_preimage}\nand \\ref{fig:nullspace_preimage_85}.\nFigure~\\ref{fig:nullspace_preimage_ensemble} shows the same decomposition of\nthese surfaces into preimage and null space, but this time assuming we measure\nthe light curves of these stars from many different random inclinations.\nAs expected, the partition of information between the preimage and the nullspace\nis about $50{-}50$.\nBecause spots are compact features, they\nare necessarily made up of a continuum of spherical harmonic modes spanning\nmany different values of $l$: they can therefore be seen in both the even\nmodes (the preimage) and the odd modes (the null space). The absence of\ninformation about the odd modes therefore does not affect our ability to\ninfer the shape and location of the features on the surface.%\n\\footnote{\n There is even some hope of deciphering complex alien messages\n (last row in the figure) in this limit!\n}\nInterestingly, however,\nthe symmetries at play require spots to be paired with antipodal dark mirror\nimages in the preimage, and with \\emph{bright} ones in the null space\n(which sum to perfectly cancel out in the true map). Thus, there are still\ndegeneracies in this very idealized ensemble problem, but they are much easier to break\nwith a suitable choice of prior. For instance, in the single spot case\n(top row), the ``ghost'' image in the southern hemisphere is surrounded by\na bright ring (whose effect is to cancel out its contribution to the flux);\neither a compactness prior or a prior that enforces uniformity in the\nbackground could easily penalize that feature in the fit. This may be\nmuch harder to do for surfaces like that shown in the second row, but\nwe can still (in principle) learn about the size, shape, and latitude\n(if not the number) of starspots from the light curves.\n\nThere are several practical reasons why this kind of ensemble analysis\nmay be very difficult (but not impossible!) in practice. Before\nwe address those, let us consider an important effect that we have not\naddressed thus far in this paper: limb darkening.\n\n\\subsection{The effect of limb darkening}\n\\label{sec:limbdark}\n\n\\begin{figure}[t!]\n \\begin{centering}\n \\includegraphics[width=\\linewidth]{figures/nullspace_ensemble_ld.pdf}\n \\oscaption{nullspace_ensemble_ld}{%\n Same as Figure~\\ref{fig:nullspace_ensemble},\n but for limb-darkened\n stars with quadratic coefficients $u_1 = 0.5$ and $u_2 = 0.25$. Odd\n modes can now be probed, at the expense of the even modes.\n \\label{fig:nullspace_ensemble_ld}\n }\n \\end{centering}\n\\end{figure}\n\nTypically, the shallower the angle between the line of sight\nand the stellar surface normal, the higher up in the stellar\natmosphere optical depth unity is reached. At optical wavelengths,\nlines of sight directed toward the limb of the star therefore\nprobe cooler temperatures, resulting in the well-known effect of\n\\emph{limb darkening}. Features close to the limb of the star therefore\ncontribute less to the total outgoing flux, and this must be\naccounted for when computing the effect of a rotating starspot\non the light curve. Limb darkening is often parametrized\nas a low-order polynomial in the cosine of the line of sight angle\n\\citep{Kopal1950}.\n\nTo understand how limb darkening affects our ability to infer\nsurface properties from stellar light curves,\nlet us repeat the experiment from the previous section,\nthis time with moderate quadratic limb darkening (with coefficients\n$u_1 = 0.5$ and $u_2 = 0.25$, although our conclusions do not\nqualitatively change for different values).\nThe top panel of Figure~\\ref{fig:nullspace_ensemble_ld} shows the\n\\shrinkage plot (same as Figure~\\ref{fig:nullspace_ensemble}, but\nthis time accounting for limb darkening). Interestingly, there is no longer a clean division of\nthe null space between even and odd modes in the limit of a large number\nof light curves.\nThis is because limb darkening effectively lifts odd modes out of the null space, \\emph{at the\n expense of the even modes}. While no coefficient lies entirely in the\nnull space ($S = 0$) when limb darkening is present, no coefficient\ncan be uniquely inferred ($S = 1$), either. This can be understood by noting that\na polynomial limb darkening law can be written\nexactly as a linear combination of the $m=0$ spherical harmonics\nup to a degree equal to the order of the limb darkening\n\\citep[in this case, $l = 2$;]{Luger2019,Agol2020}.\nSince the limb darkening operation is a (multiplicative) downweighting of\nthe surface intensity, the map seen by the observer is just the product\nof the spherical harmonic representation of the surface ($\\mathbf{y}$)\nand the spherical harmonic representation of the limb darkening profile.\nAnd since spherical harmonics are just polynomials on the surface of the sphere,\nthe product of spherical harmonics of degree $l_1$ and $l_2$ is a spherical\nharmonic of degree $l_1 + l_2$. This means that the linear limb darkening\ncomponent ($l = 1$) effectively raises the degree of all spherical harmonic\ncoefficients of the surface map by one. This has the effect of reversing\nthe null space: under \\emph{only} linear limb darkening, it is the \\emph{even}\nmodes that would be in the null space. However, the quadratic\nlimb darkening term ($l = 2$) raises the degree of all spherical harmonics by two,\nso its presence ensures that the even modes can still be probed to some extent.\nIn reality, the true limb darkening profile of a stellar surface is more\ncomplicated than a two-parameter quadratic model can capture; but one may still\nexpand it as an arbitrary order polynomial, in which case the argument still\napplies---limb darkening mixes the null space and the preimage in a nontrivial\nway.\n%\nThe fact that no coefficient can be determined uniquely---i.e., there are\nperfect degeneracies involving \\emph{all} modes on the surface---could make it more\ndifficult in practice to perform ensemble analyses on limb-darkened stars.\n\n\\begin{figure}[t!]\n \\begin{centering}\n \\includegraphics[width=\\linewidth]{figures/nullspace_ensemble_ld_var.pdf}\n \\oscaption{nullspace_ensemble_ld_var}{%\n Same as Figure~\\ref{fig:nullspace_ensemble_ld}, but allowing for\n a 10\\% variation in the limb darkening coefficients $u_1$ and $u_2$\n across different observations. For $\\gtrsim 30$ light curves,\n there is virtually no null space up to at least $l_\\mathrm{max} = 15$.\n \\label{fig:nullspace_ensemble_ld_var}\n }\n \\end{centering}\n\\end{figure}\n\nIn reality, it is unlikely that all stars in a given ensemble will have exactly\nthe same limb darkening coefficients, however ``similar'' the stars may be.\nFigure~\\ref{fig:nullspace_ensemble_ld_var} shows the same\n\\shrinkage plot as Figure~\\ref{fig:nullspace_ensemble_ld},\nbut for the case where each star has coefficients\n$u_1 = 0.5 \\pm 0.05$ and $u_2 = 0.25 \\pm 0.025$; i.e., we add a scatter of\n10\\% in the value of these coefficients. The plot shows the \\shrinkage\nin the hypothetical case where we know the coefficients for\neach star exactly. Now, as the size of the ensemble increases, the \\shrinkage\napproaches unity \\emph{for all spherical harmonic modes}.\nIn the same way that the null space is a strong function of the inclination,\nallowing us to chip away at it with observations at different inclinations,\nthe null space is also a strong function of the limb darkening law. Even a\nsmall amount of variance in the coefficients is sufficient to constrain all surface\nmodes exactly (in the limit of infinite SNR and a large number of light curves).\n\nIn practice, of course, we will never know the limb darkening coefficients\nexactly. In the next section, we will revisit this and other assumptions we\nmade above in a more sober light.\n\n\\subsection{A reality check}\n\\label{sec:reality-check}\n\nThere are three major points that make the kind of ensemble\nanalyses discussed above difficult in practice. First, and perhaps\nmost obviously, stars are\nnot identical, no matter how ``similar'' we think they may be.\nEven stars of the same spectral type, age, and metallicity will\nin general have different configurations of spots on their surfaces.\nWhen we perform an ensemble analysis on the light curves of a\nheterogeneous group of stars, we are learning something about the\n\\emph{distribution} of surface properties across all the stars in\nthe sample---not the surface properties of any individual star.\nWhat exactly we can learn in this case is not immediately obvious,\nand requires a detailed investigation. This is the subject of\nthe next paper in this series \\citepalias{PaperII}, where we show that,\narmed with a good model,\nwe can learn \\emph{a lot} about the distribution of starspot\nproperties of a heterogenous group of stellar light curves.\n\nThe second point is that while observing many similar stars at different\ninclinations can greatly help us learn about their surfaces from a\nstatistical standpoint, our analysis\nabove assumed we knew what the values of the individual inclinations were.\nIn practice, this will usually not be the case. While we may have\ngood priors for some stars (from spectroscopic $v\\sin I$ measurements,\nor from the assumption that transiting exoplanet hosts are likely\nto have inclinations close to $I=90^\\circ$), for the vast majority\nof field stars we won't know much a priori. Since the inclination\nis typically degenerate with the spot latitude \\citep[e.g.,][]{Walkowicz2013},\nthis decreases the constraining power of ensemble analyses.\nHowever, as we show in \\citetalias{PaperII}, there is still enough\ninformation in ensembles of $\\gtrsim 50$ light curves\nto independently constrain the spot latitudes\nand the \\emph{individual} stellar inclinations.\n\nThe final point concerns limb darkening, which also has a strong\neffect on the structure of the null space. While limb darkening can\nhelp us in the same way as the inclination, in practice it is likely to be more\nof a problem, since the use of incorrect limb darkening coefficients can lead\nto bias in the spot properties when doing inference.\nIt is therefore extremely important to use reliable limb darkening models\nwhen doing ensemble analyses; we also explore this in \\citetalias{PaperII}.\n\n\\section{The normalization degeneracy}\n\\label{sec:normalization}\n\nThus far we have focused our discussion on theoretical aspects concerning\nwhat can and cannot be learned from disk-integrated photometric measurements\nof stellar surfaces. In this section, we discuss an important degeneracy\nintroduced by how we actually measure stellar light curves, which we\nwill refer to as the \\emph{normalization degeneracy}. This degeneracy has been\npointed out before \\citep[e.g.,][]{Basri2018}, but it is useful to revisit and\nbuild on it here.\n\n\\subsection{A fundamental issue of units}\n%\nTo understand the normalization degeneracy, consider how we might go about simulating\na stellar surface.\n%\nWe might add a dark spot somewhere on the surface, either by expanding\nit in spherical harmonics or by gridding up the stellar surface and\nsetting the intensity of pixels within the spot to a low value. To compute\nthe light curve, we integrate over the\nprojected disk at each point in time.\n% , either analytically (if we're\n% in the spherical harmonic basis) or numerically by computing a weighted\n% sum of the visible pixels (if we're in the pixel basis).\nThe resulting\nlight curve will have strange units, so we might then divide by the\nintegral of the background intensity over the unit disk, so that we are\nnow in what we will call \\emph{fractional units}: the flux as a\nfraction of the flux we would measure if the star had no spots on it.\n\n\\begin{figure}[t!]\n \\begin{centering}\n \\includegraphics[width=\\linewidth]{figures/mean_normalization.pdf}\n \\oscaption{mean_normalization}{%\n An example of the normalization problem.\n \\emph{Top:} Consider a star with a single\n equatorial spot of contrast $c$ viewed at a certain inclination.\n The total flux (in some units) as a function of time is shown as\n the blue curve. Now, consider a second star,\n identical in all respects to the first, except that (1) the equatorial spot\n has half the contrast (i.e., $\\nicefrac{c}{2}$); and (2) there is\n a second, large spot centered on the pole. The corresponding light\n curve is shown as the dashed orange curve.\n The orange light curve is different from the blue one in two ways:\n (1) since the equatorial spot has half the contrast, the amplitude of the associated\n dips in the light curve is half that of the first star; and\n (2) since the polar spot is azimuthally symmetric, its only\n contribution is a net darkening at all phases.\n \\emph{Bottom:} The true baseline level of a stellar\n light curve, which corresponds to the flux one would measure in the\n absence of any spots, is almost always unknown. Photometric measurements\n are therefore meaningful only in a relative sense, i.e., as deviations from\n the mean, median, or maximum level of the light curve.\n The bottom panel shows the same two light curves, this time plotted as\n deviations in parts per thousand (ppt) from their respective maxima.\n To the observer, the two light curves are \\emph{indistinguishable}.\n In the absence of baseline information, there\n exists a perfect degeneracy between the total spot coverage\n and the contrast of any individual feature on the surface.\n As a consequence, the total spot coverage of a star cannot be\n uniquely inferred from single-band photometry.\n \\label{fig:mean_normalization}\n }\n \\end{centering}\n\\end{figure}\n\nThe top panel of Figure~\\ref{fig:mean_normalization} shows two mock\nlight curves we might compute following the procedure above. The solid blue\ncurve corresponds to the light curve of a star with a single large\nequatorial spot of contrast $c$ viewed at an inclination $I = 60^\\circ$.\nThe dashed orange curve corresponds to a star with a spot at the same\nlocation but half the contrast, plus a large polar spot of comparable\ncontrast. Because the equatorial spot on this star has half the contrast of that on\nthe first star, the peak-to-trough amplitude of the orange light curve is half that of\nthe blue light curve. Moreover, since the polar spot is always in view on\nthis star, the peak flux is itself only about half that of the first star.\nIf we were given these two light curves \\emph{in these fractional units},\nwe might be able to infer these basic differences between the two stars\n(setting aside for the moment all the issues with the null space discussed\nin the previous section).\n\nHowever, \\textbf{we do not observe stellar light curves in fractional units.}\nInstead, we typically observe in units of counts on\nthe detector, which depend (among other things) on various properties of the telescope.\nBut even if we knew all these things, as well as the true luminosity\nof the star and the precise distance to it, and we could truly\nperform \\emph{absolute photometry}, that \\emph{still would not be enough}\nto correctly calibrate the light curve into the units we need.\n\\textbf{To convert to fractional units, we would need to know the brightness we would\n measure if the star had no spots on it.} This depends on the brightness\nof the unspotted photosphere, which cannot be measured directly unless\nwe actually resolve the star (i.e., interferometrically)!\n\nUsually, this isn't much of an issue. Astronomers typically circumvent\nthis by self-normalizing the data: i.e., dividing the flux by the mean,\nmedian, maximum, or some similar statistic of the light curve.\n%\nThis operation folds the unknowability of\nthe true units under the rug and transforms the light curve into a \\emph{relative}\nmeasurement of the star's temporal variability. While relative measurements\nare typically what we are interested in anyways, this normalization procedure\ncan sometimes fool us into thinking we have access to information that\nis simply not observable in single-band photometry. To understand why,\nconsider the lower panel of Figure~\\ref{fig:mean_normalization}, which shows the\nsame two light curves in what we will call \\emph{relative units}. To\nget the light curves in these units, we followed the common procedure of\ndividing each by the observed ``continuum'' level (the maximum flux in the\nlight curve), subtracting unity, and multiplying by $1{,}000$, yielding\nrelative fluxes in units of parts per thousand (ppt).\n\nThe two light curves, which were distinct in the fractional units we used\nto generate them, are \\textbf{indistinguishable in the relative units\n in which we observe them}. There is absolutely no information in the\nrelative light curves that can differentiate between the two stellar\nsurfaces shown in the figure. The depth of each of the dips cannot tell\nus about either the contrast of individual spots or the total number of spots;\nin fact, in single-band photometry, these two quantities are perfectly\ndegenerate with each other.\n\n\\subsection{Ensemble analyses don't necessarily help}\n\\label{sec:basic-gp}\n%\nTo explore this point in a bit more detail, let us consider the normalization\ndegeneracy in the context of ensemble analyses. Even though we can't\nuniquely infer contrasts or numbers of spots from individual light curves,\nperhaps we could harness the power of the ensemble.\n%\nLet us therefore go\nback to our thought experiment in which we added spots to a stellar\nsurface. Assuming for simplicity that all spots have the same contrast $c$,\nevery time we add a spot the flux (in fractional units)\ndecreases by an amount proportional to $c$, so to first order we can approximate an\nindividual light curve as\n%\n\\begin{linenomath}\\begin{align}\n \\label{eq:fapprox}\n \\mathbf{f}(c, n) = \\mathbf{1} - c \\sum_{i=0}^{n-1} \\mathbf{g}(\\pmb{\\theta}_i)\n \\end{align}\\end{linenomath}\n%\nwhere $\\mathbf{g}(\\pmb{\\theta}_i)$ is some (complicated) function of the properties\nof the $i^\\mathrm{th}$ spot\nas well as the stellar inclination, rotation period, etc., which we\ndenote by $\\pmb{\\theta}_i$.\nNow, consider many stellar light curves drawn from some distribution\ncontrolling the stellar and starspot properties with probability density\n$p(\\pmb{\\theta})$.\n%\nThe mean of the distribution of\nlight curves (still in fractional units) is then given by\n%\n\\begin{linenomath}\\begin{align}\n \\mu(c, n) & = \\mathrm{E} \\Big[ \\mathbf{f} (c, n) \\Big] \\nonumber \\\\\n & = 1 - c \\, \\mathrm{E} \\bigg[ \\sum_{i=0}^{n-1} \\mathbf{g}(\\pmb{\\theta}_i) \\bigg] \\nonumber \\\\\n & = 1 - c \\, n \\, \\alpha\n \\quad,\n \\end{align}\\end{linenomath}\n%\nwhere $\\mathrm{E}\\big[\\cdots\\big]$ denotes the expected value and\n%\n\\begin{linenomath}\\begin{align}\n \\alpha \\equiv \\int \\mathbf{g} (\\pmb{\\theta}) p(\\pmb{\\theta}) \\mathrm{d} \\pmb{\\theta}\n \\end{align}\\end{linenomath}\n%\nis the expected value of $\\mathbf{g}$.\n%\nSimilarly, the variance of the distribution may be computed as\n%\n\\begin{linenomath}\\begin{align}\n \\sigma^2(c, n) & = \\mathrm{Var} \\Big[ \\mathbf{f}(c, n) \\Big] \\nonumber \\nonumber \\\\\n & = \\mathrm{Var} \\Big[ c \\, \\sum_{i=0}^{n-1} \\mathbf{g}(\\pmb{\\theta}_i) \\Big] \\nonumber \\\\\n & = c^2 \\, \\mathrm{Var} \\Big[ \\sum_{i=0}^{n-1} \\mathbf{g}(\\pmb{\\theta}_i) \\Big] \\nonumber \\\\\n & = c^2 \\sum_{i=0}^{n-1} \\mathrm{Var} \\Big[ \\mathbf{g}(\\pmb{\\theta}_i) \\Big] \\nonumber \\\\\n & = c^2 \\, n \\, (\\beta^2 - \\alpha^2)\n \\quad,\n \\end{align}\\end{linenomath}\n%\nwhere $\\mathrm{Var}\\big[\\cdots\\big]$ denotes the variance,\n%\n\\begin{linenomath}\\begin{align}\n \\beta^2 \\equiv \\int \\mathbf{g}^2 (\\pmb{\\theta}) p(\\pmb{\\theta}) \\mathrm{d} \\pmb{\\theta}\n \\end{align}\\end{linenomath}\n%\nis the expected value of $\\mathbf{g}^2$, and we used the fact that the variance\nof the sum of independent random variables is equal to the sum of their variances.\n\n%\n\nTo summarize, the mean and variance of the ensemble of stellar light curves\nin fractional units is\n%\n\\begin{linenomath}\\begin{align}\n \\mu & = 1 - c \\, n \\, \\alpha\n \\nonumber \\\\\n \\sigma^2 & = c^2 \\, n \\, (\\beta^2 - \\alpha^2)\n \\quad,\n \\end{align}\\end{linenomath}\n%\nfor some complicated functions $\\alpha$ and $\\beta$ of the distribution of\nstellar inclinations,\nrotation periods, and starspot properties.\n%\nIf our observations were collected in these fractional units,\nwe could uniquely infer the spot contrast $c$ and the number of spots $n$,\nsince these enter as $c \\, n$ and $c^2 n$ in the expressions for the mean\nand variance, respectively, and these are straightforward statistics to\ncompute from the ensemble.\n%\nHowever, because of observations are made in \\emph{relative} units, in which\nwe typically normalize to the mean, the amplitudes of features in light curves\ncan only tell us about the \\emph{ratio}\n%\n\\begin{linenomath}\\begin{align}\n \\label{eq:ratio}\n \\frac{\\sigma}{\\mu}\n & \\propto \\frac{c \\sqrt{n}}{1 - c n \\alpha}\n \\end{align}\\end{linenomath}\n%\nfor some value of $\\alpha$.\nIn other words, even photometric ensemble analyses may not be able to tell\nus about the values of the contrast and the number of spots independently.\n\nA direct consequence of this normalization degeneracy is that it may not be\npossible to uniquely constrain the total spot coverage of a star from\nsingle-band photometry without strong prior assumptions.\nThe total spot coverage $f_S$\nis simply the (average) area of a spot\ntimes the total number of spots divided by the total area of the sphere, which\nmay be expressed as\n%\n\\begin{linenomath}\\begin{proof}{test_fS}\n \\label{eq:fS}\n f_S = \\frac{1}{2}\\left(1 - \\left<\\cos r\\right>\\right)n\n \\quad,\n \\end{proof}\\end{linenomath}\n%\ngiven an angular spot radius $r$.\nWhile $r$ may be uniquely constrained from the covariance structure of the data\n\\citepalias{PaperII}, $n$ cannot.\n\nThe arguments above are heuristic and based on only the first two moments\nof the distribution of light curves in an ensemble.\nIt is possible, at least in principle, that higher order moments of the data\ncould encode information to\nbreak the $c-n$ degeneracy, but these are in general more difficult\nto constrain from the data. It is also possible that we could place a\n\\emph{lower limit} on the spot contrast based on the normalized light\ncurve. In Equation~(\\ref{eq:fapprox}) we implicitly assumed that\nspots are allowed to overlap; under this assumption, it is possible to\ndouble the contrast of a spot by simply adding another spot on top\nof it. We could therefore generate light curves with arbitrarily\nlarge dips by choosing a small value for $c$ and a very large value for $n$.\nIn reality, spots do not behave in this way: many overlapping spots\nlikely still have the same effective temperature! Therefore,\nassuming there are no bright spots,\nthe maximum depth of a feature in the light curve (even in relative units)\ncould be used to place a lower limit on the spot contrast.\nMoreover, in \\citetalias{PaperII} we empirically show that, depending on the choice\nof prior, ensemble analyses may be able to place stronger constraints on\nthe contrast $c$ than on the number of spots $n$.\n\nNevertheless, even with these caveats in mind, the fact remains\nthat degeneracies like the polar spot effect are fundamental: recall\nFigure~\\ref{fig:mean_normalization}, in which the two stars\nhave identical relative light curves, but very different spot coverage\nfractions. In general, any azimuthally-symmetric mode on the surface\nis in the null space of the \\emph{normalized} light curve problem. These\ncomponents contribute a constant value to the flux at all phases, which\neffectively gets normalized away when we measure the light curve. A\npolar spot is just one manifestation of this degeneracy. Bands, or\nband-like arrangements of spots, will be at least partly in the null\nspace of normalized light curves. These features change the total ``spot coverage''\nof the surface but do not affect the light curve in a uniquely measurable\nway.\n\n\\subsection{Effect on the covariance structure}\n\\label{sec:covariance}\n\nThere is one final subtle point concerning the normalization degeneracy that merits discussion.\nThe common procedure of normalizing light curves to their mean, median, or\nmaximum level does not only change the \\emph{units} of the data: it changes\nthe very covariance structure of the light curves.\n\nTo understand why, let us consider the procedure of normalizing a light curve\nto its mean value. Whenever we scale our data, we must always be sure to\nscale the errorbars accordingly. Since in this case we are dividing the\nflux by the mean, one might imagine that we could simply divide each of\nthe measurement uncertainties by the same amount. However,\nthis is technically incorrect!\n\n\\begin{figure}[t!]\n \\begin{centering}\n \\includegraphics[width=\\linewidth]{figures/nonstationarity.pdf}\n \\oscaption{nonstationarity}{%\n An example of why normalized light curves are non-stationary.\n The top panel shows $1{,}000$ samples from a unit-mean sinusoid with\n an amplitude of 10\\% and a period of 10 days, much longer than the\n 1 day observation baseline. The bottom panel shows the same light curves,\n each normalized to its own mean. Because the mean tends to be near\n the center of the observation window, points near $t=0.5$ are driven\n to values very close to unity, while points near the edges have much\n larger scatter.\n \\label{fig:nonstationarity}\n }\n \\end{centering}\n\\end{figure}\n\nConsider the example in Figure~\\ref{fig:nonstationarity}. The top panel\nshows $1{,}000$ samples from a sinusoid with random phases and a period\nequal to ten times the observational window.\n%\nIn this limit, each light curve is approximately\nlinear, which causes its mean value to roughly coincide with the midpoint of the\nobservation window.\n%\nDivision by the mean value (lower panel) results in points near the\nmidpoint being driven to unity and points near the edges (whose values differ\nthe most from the mean) to be driven to both large and small values.\n%\nIf our error bars in the original data were uniform (homoscedastic),\nthe error bars in the normalized light curves are\nnot: the standard deviation (or variance) of the data is now\ndistinctly dependent on the phase.\n\nWhile the example shown in the figure is fairly extreme, the idea here\nis quite general: the normalization procedure changes the covariance\nstructure of the data. In most cases, the non-stationarity (i.e., the\nphase dependence) of the variance will be quite small. The effect is primarily\nimportant for light curves with periods much longer than\nthe observation window. In these cases, not accounting for this effect\ncould introduce bias in light curve analyses. A detailed investigation of\nthis effect is beyond the scope of this paper, but we do present a\nmethod to correct the covariance matrix of normalized light curves for\nthis issue in \\citetalias{PaperII}.\n\n\\section{Discussion and conclusions}\n\n\\subsection{Degeneracies stemming from the null space}\n\nIn this paper we explored various degeneracies in the problem of\ninferring a stellar surface map from its rotational light curve.\nWe discussed the idea behind the null space, the set of surface modes that\nhave exactly zero effect on the observed light curve (\\S\\ref{sec:nullspace}).\nFor rotational light curves, we showed that the vast majority of the information\nabout the surface intensity is in the null space and therefore cannot\nbe inferred from unresolved photometric measurements. We showed, in particular,\nthat the size of the null space grows \\emph{quadratically} with increasing spatial\nresolution, while the number of independent degrees of freedom in the light curve\nonly grow \\emph{linearly}. Consequently, the information content of light\ncurves is small for large scale surface features and \\emph{vanishingly small}\nfor small scale features.\n\nA direct consequence of this fact is that \\textbf{results based on analyses\n of individual light curves are often extremely sensitive to\n the particular assumptions of one's model.} We therefore urge lots of care\nin these kinds of analyses, where assumptions of uniform-contrast, discrete, and\ncircular spots, or alternatively of maximum entropy or ``simplicity'' may\nresult in significant bias. In this respect, we agree with the recent\npaper by \\citet{Basri2020}, which cautions against the association of\ninvidual dips in light curves with individual, discrete spots.\n\nOne of the main results in this paper concerning the null space is its\ndependence on stellar inclination (\\S\\ref{sec:inclination}).\nBecause the modes that lie in the null\nspace change depending on the viewing angle, observations of a star at many\ninclinations would break many of the degeneracies in the mapping problem. While\nthis is obviously infeasible in practice, the dependence of the null\nspace on inclination motivates ensemble analyses of many similar stars\nas a way of circumventing the mapping degeneracies by\nproviding a strong data-driven prior. As we show in\n\\citetalias{PaperII} in this series, the joint analysis of tens to hundreds\nof light curves can uniquely constrain the distribution of starspot\nsizes and latitudes among the stars in the sample. In that paper,\nwe show that ensemble analyses can\neven break the latitude-inclination degeneracy \\citep[e.g.,][]{Walkowicz2013},\nallowing one to infer individual stellar inclinations, typically to within\nabout $10^\\circ$.\n\nWe also showed how the null space is a strong function of the stellar limb\ndarkening. While this can again be used to our advantage---by harnessing the\nvariance in the limb darkening parameters across an ensemble of stellar\nlight curves---in practice it is likely to complicate inference, since\nany bias in the assumed limb darkening coefficients will likely result in\nbias in the inferred surface properties. We revisit this point in\n\\citetalias{PaperII}.\n\nOne final point that we did not address thus far concerns occultations.\nOur results regarding the null space apply strictly to rotational light curves,\nin which all points on the projected disk contribute to the measured flux.\nDuring an occultation by a transiting planet or a binary companion, the\nweighting of surface modes giving rise to the light curve changes\nsubstantially. In fact, the presence of an occultor breaks many of the perfect\nsymmetries that give rise to a null space in the first place\n\\citep[e.g.,][]{Luger2019}. This fact can be used to infer the properties\nof spots in the path of the occultor, as was done (for example)\nby \\citet[e.g.,][]{Morris2017}. A detailed investigation of the null space\nfor the occultation problem is beyond the scope of this work.\n\n\\subsection{Degeneracies due to the unknown normalization}\n\nThe second major source of degeneracies is the fundamental\nunknowability of the true normalization in single-band\nphotometry (\\S\\ref{sec:normalization}), which is summarized in\nFigure~\\ref{fig:mean_normalization}. In a nutshell, the relationship\nbetween the amplitude of a feature in the light curve and the contrast\nof the feature that gave rise to it depends on quantities like the\nunspotted photospheric brightness, which is not an observable in\nsingle-band photometry. This leads to the possibility of distinctly\ndifferent stellar surfaces having identical \\emph{relative}\nlight curves, as demonstrated in the figure.\n\nIn practice, this degeneracy usually manifests as a nonlinear correlation\nbetween the contrast $c$ of a spot and the total number $n$\nof spots on the surface of the star. Even in ensemble analyses,\none cannot in general learn these two quantities independently from\nthe data alone,\nonly a (complicated) function of the two (Equation~\\ref{eq:ratio}).\nIn \\citetalias{PaperII} we show empirically that\ncareful analysis of the covariance structure of ensembles of light curves\nmay shed some light on $c$ but cannot uniquely constrain $n$.\n%\nA direct consequence of this degeneracy is that \\textbf{constraints on\n the total number of spots or on the spot coverage of a star from single-band light curves\n depend strongly on the model assumptions.}\n\nRecently, \\citet{Morris2020} performed an ensemble analysis of\n\\emph{Kepler}, \\emph{K2}, and \\emph{TESS}\nlight curves to derive a relationship between the fractional spot\ncoverage $f_S$ and stellar age.\n%\n% That work inferred a power-law\n% scaling between the fractional\n% ``smoothed amplitude'',\n% the peak-to-trough difference of the (normalized, de-trended) light curve,\n% and the fractional spot coverage $f_S$\n% This distribution was then compared to the distribution of observed\n% smoothed amplitude values among stellar clusters of different ages\n% within an ABC algorithm, yielding approximate\n% posterior distributions for the hyperparameters as a function of\n% stellar age.\nThat work found that the spot coverage $f_S$ as a\nfunction of age is well modeled by a simple power law, decreasing from\n${\\sim}10\\%$ for the youngest (${\\sim}10$ Myr) stars\nto less than $1\\%$ for the oldest (${\\sim}5$ Gyr) stars.\n%\nWhile this broadly agrees with the expectation that stellar\nmagnetic activity decreases over time, our work strongly suggests\nthat these results depend heavily on the prior.\n%\nThis is because the expression for $f_S$ (Equation~\\ref{eq:fS}) depends on\ntwo quantities: the average spot radius $r$, which can be\nconstrained \\citep[see][]{PaperII}, and the total number of spots $n$, which\nwe showed \\emph{cannot} be uniquely constrained from single-band light curves.\n%\nIn fact, \\citet{Morris2020} assumed $n=3$ for simplicity when doing\nposterior inference. We therefore urge care in interpreting those results,\nas it is possible this assumption does not hold across the large\nrange of spectral types and stellar ages considered in that study.\n%\nNevertheless, the other central result of that paper, the relationship\nbetween the ``smoothed amplitude'' of a light curve and the stellar age,\n\\emph{is} valid.\n%\nMoreover, the core idea in \\citet{Morris2020}\n\\citep[and in related studies such as][]{Jackson2013}\nis very similar\nto that advocated here: the use of ensemble analyses to constrain population-level\nparameters when invidual datasets are not sufficiently constraining.\n\nAnother recent paper relevant to our work is that of \\citet{Basri2020}, who\ninvestigated the information content of stellar light curves, exploring what\ncan and cannot be learned about star spot configurations from individual\nlight curves. That paper strongly urges against the common practice\nof interpreting\nlight curves with one or two dips as originating from one or two spots,\nrespectively, a point we strongly agree with (see our Figure~\\ref{fig:degeneracies}).\nIt also reinforces our point about the additional degeneracies introduced\nby the unknown normalization inherent to single-band photometry.\n%\n\n% SOLUTIONS TO normalization degeneracy\n\nAs with the degeneracies due to the null space, there are potential ways\nto break the normalization degeneracy.\n%\nIn principle, the maximum level of a light curve could set a lower limit on\nthe brightness of the\nunspotted photosphere, particularly for long-baseline, time-variable\nsurfaces \\citep{Basri2018}. However, this would work only if the surface is\nknown to be made up \\emph{exclusively} of dark spots. The presence of bright\nspots (faculae), which are common on the Sun, make it difficult\nfor one to infer this quantity (and hence the correct normalization)\nfrom single-band photometry in practice.\n\nA better approach may be to collect photometric data in\nmultiple wavelength bands, an idea that has\nbeen explored recently \\citep[e.g.,][]{Gully2017,Guo2018}. Assuming the\nlocations and sizes of a star's spots are constant in wavelength, the amplitude\nof the light curve in different bands (and in particular its slope as a function\nof wavelength) can be used to directly constrain the\ntemperature, and hence the contrast, of the spots. This effectively breaks the\n$c-n$ degeneracy. In practice, the effective size of spots may be different\nat different wavelengths, which could complicate this picture somewhat, but\nthe point still stands that light curves collected in multiple bands\ncontain at least \\emph{partial} information about the correct normalization.\n%\nA more detailed analysis of the information content of multi-band light curves,\nand, by extension, spectroscopic timeseries, is deferred to a future paper\nin this series.\n\n\\subsection{Caveats}\n\\label{sec:caveats}\n\nThere are several simplifying assumptions we made in this paper that\nare worth discussing. First, in our characterization of the null space\nwe assumed we knew the stellar inclination, the stellar rotation period,\nand the limb darkening coefficients\nexactly, and we computed the information content of stellar light curves\nin the limit of infinite SNR. None of these assumptions are valid in\npractice. In realistic scenarios, the \\shrinkage will be\nnecessarily \\emph{lower} than what we presented here: the curves in\nFigure~\\ref{fig:nullspace_ensemble}, for instance, are therefore\nstrict upper bounds on the amount of information that can be learned about\nthe surface. In some cases, it may be possible to infer the inclination\nfrom spectroscopic $v \\sin I$ measurements, or the limb darkening coefficients\nfrom the shape of transiting exoplanet light curves; but any uncertainty\nin these quantities will degrade our ability to constrain\ninformation about the surface.\n\nMoreover, our constraints on the information content of ensembles of light curves are\nalso strict upper limits, since we assumed all stars in the ensemble\nare identical. Variance in the surface maps of stars in\na population makes it effectively impossible to infer detailed\nproperties of the individual stellar surfaces in the ensemble.\nWe argued without proof that what we can learn instead are properties of the\n\\emph{distribution} of stellar surfaces among the population, such as\nthe distribution of spot sizes and active latitudes.\nDemonstrating this point is more difficult, so we defer it to\n\\citetalias{PaperII}, where we construct a custom Gaussian process model\nand show that it can be used to infer such population-level parameters\nfrom ensembles of light curves.\n\nFinally, we limited our discussion to static stellar surfaces.\nReal stellar surfaces vary\nwith time as individual spots form, evolve, and dissipate, or as a star progresses\nthrough its activity cycle. This, too, makes it more difficult to constrain\nthe stellar surface at a particular point in time, since the amount of\ndata corresponding to a particular surface configuration is more limited.\nOn the other hand, a time-variable surface could be used to our advantage\nfrom an ensemble standpoint. Although we are unable to uniquely infer\ninvididual spot properties, we could treat each point in the light curve\nas a realization of a random process (i.e., a draw from some distribution)\ndescribing the stellar surface at a high level. In this sense, we could\nharness the fact that we can measure the light curves of many ``similar''\nsurfaces to learn something about their statistical properties.\nDemonstrating this is beyond the scope of the present work, but we\nreturn to this point in \\citetalias{PaperII}.\n\n\\subsection{Future work}\n\nThis paper is the first in a series dedicated to developing\nmethodology to infer stellar surface properties from\nunresolved measurements. It sets the stage for \\citet{PaperII},\nin which we develop an interpretable Gaussian process (GP) model for\nstarspot-induced light curve variability. This GP is aimed specifically\nat the difficult problem of jointly modeling many light curves\nin an ensemble analysis. Although we hinted at this here, we will show\nin that paper that ensemble analyses can uniquely constrain several\nstatistical properties of starspots, including their distribution\nof radii and latitudes across stars in the ensemble. In that work\nwe also consider temporally evolving surfaces, which we neglected\nin our discussion thus far.\n\nFinally, while this paper explicitly dealt with the problem of\nphotometric rotational light curves, the degeneracies outlined\nhere and the methodology developed in this series of papers\napply more broadly in other contexts.\nThese including applications where the stellar\nsurface is a nuisance (exoplanet detection and characterization using\ntransit light curves or radial velocities) and spectral time series\ndatasets (such as transmission spectroscopy and Doppler imaging).\n\n\n\\vspace{2em}\n\nIn keeping with other papers in the \\starry series, all figures in this\npaper are generated automatically from open-source scripts linked to in\neach of the captions \\codeicon, and the principal equations link to associated\nunit tests that ensure the accuracy and reproducibility of the algorithm\npresented here \\testpassicon/\\testfailicon.\n\n%\n%\n%\n%\n%\n%\n%\n%\n\n\\vspace{2em}\n\nWe would like to thank Michael Gully-Santiago, Fran Bartoli\\'c, and the\nAstronomical Data Group at the Center for Computational Astrophysics for\nmany thought-provoking discussions that helped shape this paper.\n\n\\bibliography{bib}\n\n\\appendix\n\n\\section{Decomposition of the flux operator}\n\\label{sec:app-svd}\n%\nIn this section we show how to use singular value decomposition (SVD)\nto decompose a surface map\ninto its preimage and its null space (see \\S\\ref{sec:svd}). By performing SVD, we\nmay express the flux design matrix as\n%\n\\begin{linenomath}\\begin{align}\n \\label{eq:svd}\n \\pmb{\\mathcal{A}} = \\mathbf{U} \\, \\mathbf{S} \\, \\mathbf{V}^\\top\n \\quad,\n \\end{align}\\end{linenomath}\n%\nwhere $\\mathbf{U}$ is a $(K \\times K)$ orthogonal matrix,\n$\\mathbf{V}$ is a $(N \\times N)$ orthogonal matrix,\nand $\\mathbf{S}$ is a $(K \\times N)$ diagonal matrix.\n%\nThe columns of $\\mathbf{U}$ and the rows of $\\mathbf{V}^\\top$ are the left and right\n\\emph{singular vectors} of $\\pmb{\\mathcal{A}}$, and the entries along the\ndiagonal of $\\mathbf{S}$ are the corresponding \\emph{singular values}, arranged\nin descending order. If $\\pmb{\\mathcal{A}}$\nhas rank $R$, the first $R$ singular values will be nonzero, while the\nremaining $N - R$ will be identically zero.\n%\nIf we assume for definitess that $K > N$ (i.e., we have more flux observations\nthan surface map coefficients we're trying to constrain), we can express the\nmatrices in Equation~(\\ref{eq:svd}) as\n%\n\\begin{linenomath}\\begin{align}\n \\mathbf{U}\n & =\n \\left(\n \\begin{array}{ccc|ccc}\n \\mathbf{U}_{0,0} & \\cdots & \\mathbf{U}_{0,R\\text{-}1} & \\mathbf{U}_{0,R} & \\cdots & \\mathbf{U}_{0,K\\text{-}1} \\\\\n \\vdots & \\cdots & \\vdots & \\vdots & \\cdots & \\vdots \\\\\n \\mathbf{U}_{K\\text{-}1,0} & \\cdots & \\mathbf{U}_{K\\text{-}1,R\\text{-}1} & \\mathbf{U}_{K\\text{-}1,R} & \\cdots & \\mathbf{U}_{K\\text{-}1,K\\text{-}1}\n \\end{array}\n \\right)\n \\equiv\n \\left(\n \\begin{array}{c|c}\n \\mathbf{U}_\\bullet & \\mathbf{U}_\\circ\n \\end{array}\n \\right)\n %\n \\\\[1.5em]\n %\n \\label{eq:S}\n \\mathbf{S}\n & =\n \\left(\n \\begin{array}{ccc|ccc}\n \\mathbf{S}_{0,0}\\phantom{y} & & & & & \\\\\n & \\ddots & & & \\mbox{\\normalfont\\Large\\bfseries 0} & \\\\\n & & \\mathbf{S}_{R\\text{-}1,R\\text{-}1} & & & \\\\\n \\hline\n & & & \\mathbf{S}_{R,R}\\phantom{y} & & \\\\\n & \\mbox{\\normalfont\\Large\\bfseries 0} & & & \\ddots & \\\\\n & & & & & \\mathbf{S}_{N\\text{-}1,N\\text{-}1} \\\\\n & & & & & \\\\\n & \\mbox{\\normalfont\\Large\\bfseries 0} & & & \\mbox{\\normalfont\\Large\\bfseries 0} & \\\\\n & & & & &\n \\end{array}\n \\right)\n \\equiv\n \\left(\n \\begin{array}{c|c}\n \\mathbf{S}_\\bullet & \\mathbf{0} \\\\\n \\hline\n \\mathbf{0} & \\mathbf{S}_\\circ\n \\end{array}\n \\right)\n %\n \\\\[1.5em]\n %\n \\mathbf{V}^\\top\n & =\n \\left(\n \\begin{array}{cccccc}\n \\mathbf{V}_{0,0}^\\top & \\cdots & \\mathbf{V}_{0,N\\text{-}1}^\\top \\\\\n \\vdots & \\cdots & \\vdots \\\\\n \\mathbf{V}_{R\\text{-}1,0}^\\top & \\cdots & \\mathbf{V}_{R\\text{-}1,N\\text{-}1}^\\top \\\\[0.5em]\n \\hline \\\\[-0.85em]\n \\mathbf{V}_{R,0}^\\top & \\cdots & \\mathbf{V}_{R,N\\text{-}1}^\\top \\\\\n \\vdots & \\cdots & \\vdots \\\\\n \\mathbf{V}_{N\\text{-}1,0}^\\top & \\cdots & \\mathbf{V}_{N\\text{-}1,N\\text{-}1}^\\top\n \\end{array}\n \\right)\n \\equiv\n \\left(\n \\begin{array}{cc}\n \\mathbf{V}_\\bullet^\\top \\\\\n \\hline\n \\mathbf{V}_\\circ^\\top\n \\end{array}\n \\right)\n \\end{align}\\end{linenomath}\n%\nwhere\n$\\mathbf{U}_\\bullet$ is $(K \\times R)$,\n$\\mathbf{U}_\\circ$ is $(K \\times K - R)$,\n$\\mathbf{S}_\\bullet$ is $(R \\times R)$,\n$\\mathbf{S}_\\circ$ is $(K - R \\times N - R)$,\n$\\mathbf{V}_\\bullet^\\top$ is $(R \\times N)$,\nand\n$\\mathbf{V}_\\circ^\\top$ is $(N - R \\times N)$.\n%\nWe may then express the decomposition of $\\pmb{\\mathcal{A}}$ as\n%\n\\begin{linenomath}\\begin{align}\n \\label{eq:A}\n \\pmb{\\mathcal{A}} =\n \\left(\n \\begin{array}{c|c}\n \\mathbf{U}_\\bullet & \\mathbf{U}_\\circ\n \\end{array}\n \\right)\n \\left(\n \\begin{array}{c|c}\n \\mathbf{S}_\\bullet & \\mathbf{0} \\\\\n \\hline\n \\mathbf{0} & \\mathbf{S}_\\circ\n \\end{array}\n \\right)\n \\left(\n \\begin{array}{cc}\n \\mathbf{V}_\\bullet^\\top \\\\\n \\hline\n \\mathbf{V}_\\circ^\\top\n \\end{array}\n \\right)\n \\quad.\n \\end{align}\\end{linenomath}\n%\nInserting this into Equation~(\\ref{eq:fAy}), we have\n%\n\\begin{linenomath}\\begin{proof}{test_decomposition}\n \\label{eq:ydecomp}\n \\mathbf{f} - \\mathbf{1} & = \\pmb{\\mathcal{A}} \\, \\mathbf{y}\n \\nonumber \\\\\n & =\n \\left(\n \\begin{array}{c|c}\n \\mathbf{U}_\\bullet & \\mathbf{U}_\\circ\n \\end{array}\n \\right)\n \\left(\n \\begin{array}{c|c}\n \\mathbf{S}_\\bullet & \\mathbf{0} \\\\\n \\hline\n \\mathbf{0} & \\mathbf{S}_\\circ\n \\end{array}\n \\right)\n \\left(\n \\begin{array}{cc}\n \\mathbf{V}_\\bullet^\\top \\\\\n \\hline\n \\mathbf{V}_\\circ^\\top\n \\end{array}\n \\right) \\mathbf{y}\n \\nonumber \\\\[0.5em]\n & =\n \\mathbf{U}_\\bullet \\, \\mathbf{S}_\\bullet \\, \\mathbf{V}_\\bullet^\\top \\, \\mathbf{y}\n +\n \\mathbf{U}_\\circ \\, \\mathbf{S}_\\circ \\, \\mathbf{V}_\\circ^\\top \\, \\mathbf{y}\n \\nonumber \\\\[0.5em]\n & =\n \\mathbf{U}_\\bullet \\, \\mathbf{S}_\\bullet (\\,\\mathbf{I}\\,) \\mathbf{V}_\\bullet^\\top \\, \\mathbf{y}\n +\n \\mathbf{U}_\\circ \\, \\mathbf{S}_\\circ (\\,\\mathbf{I}\\,) \\mathbf{V}_\\circ^\\top \\, \\mathbf{y}\n \\nonumber \\\\[0.5em]\n & =\n \\mathbf{U}_\\bullet \\, \\mathbf{S}_\\bullet (\\mathbf{V}_\\bullet^\\top \\mathbf{V}_\\bullet) \\mathbf{V}_\\bullet^\\top \\, \\mathbf{y}\n +\n \\mathbf{U}_\\circ \\, \\mathbf{S}_\\circ (\\mathbf{V}_\\circ^\\top \\mathbf{V}_\\circ) \\mathbf{V}_\\circ^\\top \\, \\mathbf{y}\n \\nonumber \\\\[0.5em]\n & =\n (\\mathbf{U}_\\bullet \\, \\mathbf{S}_\\bullet \\, \\mathbf{V}_\\bullet^\\top) \\mathbf{V}_\\bullet \\mathbf{V}_\\bullet^\\top \\, \\mathbf{y}\n +\n (\\mathbf{U}_\\circ \\, \\mathbf{S}_\\circ \\, \\mathbf{V}_\\circ^\\top) \\mathbf{V}_\\circ \\mathbf{V}_\\circ^\\top \\, \\mathbf{y}\n \\nonumber \\\\[0.5em]\n & =\n (\\mathbf{U}_\\bullet \\, \\mathbf{S}_\\bullet \\, \\mathbf{V}_\\bullet^\\top) \\, \\mathbf{y}_\\bullet\n +\n (\\mathbf{U}_\\circ \\, \\mathbf{S}_\\circ \\, \\mathbf{V}_\\circ^\\top) \\, \\mathbf{y}_\\circ\n \\end{proof}\\end{linenomath}\n%\nwhere we define\n%\n\\begin{linenomath}\\begin{proof}{test_PN}\n \\label{eq:yrow}\n \\mathbf{y}_\\bullet & \\equiv \\mathbf{P} \\, \\mathbf{y}\n \\\\\n \\label{eq:ynull}\n \\mathbf{y}_\\circ & \\equiv \\mathbf{N} \\, \\mathbf{y}\n \\\\[0.5em]\n \\mathbf{P} & \\equiv \\mathbf{V}_\\bullet \\mathbf{V}_\\bullet^\\top\n \\\\\n \\mathbf{N} & \\equiv \\mathbf{V}_\\circ \\mathbf{V}_\\circ^\\top\n \\quad,\n \\end{proof}\\end{linenomath}\n%\nand we used the fact that since $\\mathbf{V}^\\top$ is orthogonal,\n%\n\\begin{linenomath}\\begin{proof}{test_orthogonality}\n \\mathbf{V}_\\bullet^\\top \\mathbf{V}_\\bullet & = \\mathbf{I}\n \\nonumber \\\\\n \\mathbf{V}_\\circ^\\top \\mathbf{V}_\\circ & = \\mathbf{I}\n \\quad,\n \\end{proof}\\end{linenomath}\n%\nwhere $\\mathbf{I}$ is the identity matrix.\n%\nNow, recalling that $R$ is the number of nonzero singular values in\n$\\mathbf{S}$, it is evident from Equation~(\\ref{eq:S}) that\n%\n\\begin{linenomath}\\begin{align}\n \\label{eq:S0}\n \\mathbf{S}_\\circ = \\mathbf{0}\n \\quad.\n \\end{align}\\end{linenomath}\n%\nTherefore we may write Equation~(\\ref{eq:ydecomp}) as\n%\n\\begin{linenomath}\\begin{proof}{test_decomposition}\n \\boxed{\n \\mathbf{f} = \\mathbf{1} + \\pmb{\\mathcal{A}} \\, \\mathbf{y}_\\bullet\n +\n \\mathbf{0} \\, \\mathbf{y}_\\circ\n }\n \\end{proof}\\end{linenomath}\n%\nwhere the fact that $\\mathbf{U}_\\bullet \\, \\mathbf{S}_\\bullet \\, \\mathbf{V}_\\bullet^\\top = \\pmb{\\mathcal{A}}$\nfollows directly from Equations~(\\ref{eq:A}) and (\\ref{eq:S0}).\n%\nThis is the decomposition of the surface map $\\mathbf{y}$ into\nits preimage $\\mathbf{y}_\\bullet$ and null space\n$\\mathbf{y}_\\circ$ components.\n%\n\nTwo things should be noted concerning this derivation. First,\nbecause of the orthogonality of $\\mathbf{V}$,\n%\n\\begin{linenomath}\\begin{proof}{test_PN}\n \\mathbf{V} \\mathbf{V}^\\top &= \\mathbf{I}\n \\nonumber \\\\\n \\mathbf{V}_\\bullet \\mathbf{V}_\\bullet^\\top + \\mathbf{V}_\\circ \\mathbf{V}_\\circ^\\top &= \\mathbf{I}\n \\nonumber \\\\\n \\mathbf{P} + \\mathbf{N} &= \\mathbf{I}\n \\quad,\n \\end{proof}\\end{linenomath}\n%\nso it follows from Equations~(\\ref{eq:yrow}) and (\\ref{eq:ynull})\nthat $\\mathbf{y} = \\mathbf{y}_\\bullet + \\mathbf{y}_\\circ$.\n\nSecond, the singular value decomposition is not always unique. The\nmatrix of singular values $\\mathbf{S}$ is unique provided we arrange\nthem in decreasing order, but if there are degenerate or zero-valued\nsingular values (as is the case here), the matrices $\\mathbf{U}$ and\n$\\mathbf{V}^\\top$ (and thus $\\mathbf{V}^\\top_\\bullet$ and $\\mathbf{V}^\\top_\\circ$)\nare only well-defined up to arbitrary unitary\ntransformations. However, the quantities\n$\\mathbf{V}_\\bullet\\mathbf{V}^\\top_\\bullet$\nand\n$\\mathbf{V}_\\circ\\mathbf{V}^\\top_\\circ$\n(which define the operators $\\mathbf{P}$ and $\\mathbf{N}$ above) \\emph{are}\nunique, so the decomposition into null space and preimage is always well-defined.\n\n\\end{document}\n", "meta": {"hexsha": "261e68dd84c26f820564314e176fc9737fd5abdb", "size": 98741, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "paper1/ms.tex", "max_stars_repo_name": "rodluger/mapping_stellar_surfaces", "max_stars_repo_head_hexsha": "638e07e3264cfa0a1795e3eb34660e91117f8edd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2021-01-21T17:03:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-19T17:49:28.000Z", "max_issues_repo_path": "paper1/ms.tex", "max_issues_repo_name": "rodluger/mapping_stellar_surfaces", "max_issues_repo_head_hexsha": "638e07e3264cfa0a1795e3eb34660e91117f8edd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2021-01-21T15:55:53.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-30T14:35:16.000Z", "max_forks_repo_path": "paper1/ms.tex", "max_forks_repo_name": "rodluger/mapping_stellar_surfaces", "max_forks_repo_head_hexsha": "638e07e3264cfa0a1795e3eb34660e91117f8edd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-01-21T15:41:58.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-25T16:26:15.000Z", "avg_line_length": 49.8943911066, "max_line_length": 226, "alphanum_fraction": 0.7201061363, "num_tokens": 24421, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3812195662561499, "lm_q1q2_score": 0.19209889176289358}}
{"text": "\\chapter{De-Entanglement of Content - Case study with Acoustic Unit Discovery}\n\n\\section{Problem Introduction}\nA major bottleneck in the progress of many data-intensive language processing tasks such as speech recognition and synthesis is scalability to new languages and domains. \nBuilding such technologies for unwritten or under-resourced languages is often not feasible due to lack of annotated data or other expensive resources. \nA fundamental resource required to build such a stack is a phonetic lexicon - something that translates acoustic input to textual representation. Having such a lexicon, even if noisy, can help bootstrap speech recognition models, synthesis, and other technologies. Typical approaches may involve a pivot language or bootstrapping or adapting from a closely related high-resource language.\nBut, this can be a deceptively non-trivial task due to linguistic differences which can pose inherent difficulties. \nFor instance, it may be unreasonable to analyze a Sino-Tibetan language using English as a source. Moreover, using an additional language might make the model learn unintended surface level associations or biases between the participating languages that prevent them from generalizing across languages. Associations between these languages over a set of units that may better generalize to other languages. Therefore, in this paper we are interested in discovering the appropriate acoustic phonetic units. \n\n\\begin{figure}[t]\n\\centering\n\\includegraphics[width=80mm,scale=0.5]{images/vaconda_architecture_zerospeech2019.png}\n\\caption{Illustration of our procedure for automatically discovering acoustic units from a speech utterance. We pass the speech utterance through a downsampling encoder. The encoded representation is hashed to a latent code based on a discrete articulatory prior bank. The code is passed to the decoder, a WaveNet using speaker embeddings as global conditioning that regenerates audio. } \n\\label{frame_replacement_overview}\n\\end{figure} \n\n\nIn ZeroSpeech Challenge\\citep{zerospeech2019} resynthesis is considered a good proxy task to evaluate the performance of systems when training using unsupervised approaches. To accomplish this we use neural generative models. %Resynthesis might be a good proxy. \nDeep Neural Generative models have seen a tremendous amount of progress in the recent past. These models aim to model the joint probability of the data distribution and the conditioning information as a product of conditional distributions. Typical implementations of such models follow an autoregressive framework, although other formulations have been suggested as well. Such models have been shown very effective in addressing one of the major challenges with conventional vocoding techniques - fidelity. \nNeural generative models has been shown to generate speech that rivals natural speech when conditioned on predicted mel spectrum \\citep{shen2017natural}. Speech has a lot of natural variations in terms of content, speaker, channel information, speaking style, prosodic variations, etc. Accordingly, we are interested in models which have flexibility to marginalize such variations but preserve the phonetic content and distinguish meaningful differences between phonetic units.To accomplish this, we employ sequence to sequence models with latent random variables (referred to as latent stochastic models hereafter). These models provide a mechanism to jointly train both the latent representations as well as the downstream inference network. They are expected to both discover and disentangle causal factors of variation present in the distribution of original data, so as to generalize at inference time. While training latent stochastic models, optimizing the exact log likelihood can be intractable. To address this, a recognition network is employed to approximate the posterior probability using reparameterization \\citep{vae}. When deployed in encoder-decoder models, this approach is often subject to an optimization challenge referred to as KL-collapse \\citep{bowman_continuous}, wherein the generator (usually an RNN) marginalizes the learnt latent representation. Typical approaches to dealing this issue involve annealing the KL divergence loss~\\citep{bowman_continuous,zhou2017multi}, weakening the generator \\citep{zhao2017learning} and ensuring the recall using bag of words loss. In our work, we present an approach to deal with the KL-collapse problem by vector quantization in the latent space. Building on \\citep{vq-vae, chorowski2019unsupervised}, we add additional constraints in the prior space forcing the latent representations to follow articulatory dimensions: The encoded representation is hashed to a latent code based on a articulatory prior bank designed using a discrete codebook. Our decoder is a conditional WaveNet using speaker embedding as global embedding trained to regenerate input audio using the code sequence as local information. \n\n\n\\section{Background - Acoustic Unit Discovery}\n\nLet us consider a speech corpus X which consists of speakers $\\{ s_1, s_2...,s_n \\}$. The goal of acoustic unit discovery is to come up with a set of units \\textbf{U} that represent a speech utterance \\textit{x} $\\subset$ X allowing robust resynthesis. %comprehensively. \nThe elements of such a set also might conform to desirable characteristics such as being injective, consistent and compact, i.e. that different inputs should have discriminant acoustic units, but expected variance such as speaker or dialect should produce the same acoustic units. %, and the set of units should be \n% We aim to discover a minimal set of units to fit these goals.\n%must be well corresponding to the acoustic vectors(predictable)\n\n\nThere have been numerous attempts to discover such acoustic units in an unsupervised fashion. In \\citep{subword_diarization}, authors presented an approach to modify the speaker diarization system to detect speaker-dependent acoustic units. \\citep{unsupervised_AMtraining_ArenJansen} proposed a GMM-based approach to discover speaker-independent subword units. However, their system requires a separate Spoken Term Detector. Recently, due to the surge of deep generative model, using unsupervised method such as auto-encoder and variational auto-encoder (VAE). \\citep{badino_autoencoder} designed a stacked AutoEncoder using backpropagation and then cluster the representations at the bottleneck layer. To avoid quick transitions leading to repeated units, they employed a smoothing function based on transition probabilities of the individual states. \\citep{hmm-vae_bhiksha} extended the structured VAE to incorporate the Hidden Markov Models as latent model. \\citep{vq-vae, chorowski2019unsupervised} proposed VQ-VAE and argue that by vector quantization the ``“posterior collapse\" problem could be circumvented.\n\n\n\\section{\\textit{VACONDA}}\n\\label{proposed_approach}\n\n\n\\subsection{Analysis of optimization and de-entanglement}\n\\label{analysis}\n\nWaveNet \\citep{van2016WaveNet} is an autoregressive neural model with a stack of 1D convolutional layers that is capable of directly generating audio signal. It has been shown to produce generated speech that rivals natural speech when conditioned on predicted mel spectrum \\citep{shen2017natural}. The input to WaveNet is subjected to corresponding gated activations while passing through each dilated convolutional layer and is classified by the final softmax layer into a $\\mu$ law encoding. The concrete form of the residual gated activation function is given by following equation:\n\n\n\\begin{equation} \\label{WaveNet_Eqn}\n\\begin{split}\n r_d(x) = tanh(W_{f} * x) \\odot \\sigma (W_{g} * x) \\\\ \n\\end{split}\n\\end{equation}\n\n\\noindent where $x$ and $r_d(x)$ are the input and output with dilation $d$, respectively. The symbol $*$ is a convolution operator with dilation $d$ and the symbol $\\odot$ is an element-wise product operator. $W$ represents a convolution weight. The subscripts $f$ and $g$ represent a filter and a gate, respectively. The joint probability of a waveform \\textbf{X} can be written as:\n\n\n\\begin{equation} \\label{WaveNet_gen_Eqn}\n\\begin{split}\n P(X | \\theta) = \\prod_{t=1}^{T} P(x_t | x_1, x_2 .. x_{t-1}, \\theta) \\\\\n\\end{split}\n\\end{equation} \n\n\\noindent given model parameters $\\theta$. During implementation of WaveNet, the autoregressive process is realized by a stack of dilated convolutions. The final output $y_t$ at time step $t$ can be expressed mathematically as:\n\n\\begin{equation} \n\\begin{split}\n \\hat{y_t} \\sim \\sum_{d=0}^{D} h_d * r_d(x) \\\\\n\\end{split}\n\\label{WaveNet_Eqn}\n\\end{equation} \n\n\\noindent where $x$, $y$ represent input and output vectors; $D$ is the number of different dilation used and $d$ is the dilation factor; $h_d$ is the convolution weights. This stack of convolutions is repeated multiple times in the original WaveNet. Optimization in WaveNet is performed based on the error between predicted sample and the ground truth sample conditioned on previous samples in the receptive field alongside the local conditioning. Expressing the loss function being optimized mathematically the error at sample $t$ is:\n\n\n\\begin{equation} \\label{discrete_Eqn}\n\\begin{split}\n l_t = Div(\\hat{y_t} || y_t)\n\\end{split}\n\\end{equation} \n\nHere, we define the divergence similar to the \\citep{salimans2017pixelcnn++}, To optimize this loss, the contribution from the individual convolution layers towards this global error function must be nullified. Now let us consider the expression for intermediate output for a single filter in Eqn~\\ref{WaveNet_Eqn}:\n\n\\begin{equation}\n\\begin{split}\n x_{out}(t) = \\sum_{\\tau=0}^{t} h(\\tau)x(t-\\tau)\n\\end{split}\n\\end{equation} \n\n\\noindent where $\\tau$ is the receptive field covered by the model and $h(\\tau)$ represents the discrete state representation at time $t$. Without loss of generality and dropping the term $\\tau$ for brevity, the spectral representation generated by the model can be expressed as:\n\n\\begin{equation} \\label{transfer_function_representation}\n Y(z) = H(z) X(z) \n\\end{equation} \n\n\nConsidering the discrete nature of input from Eqn \\ref{discrete_Eqn}, an interpretation of Eqn \\ref{transfer_function_representation} is that the neural autoregressive model acts as the transfer function and is discretized by convolving with the samples from original signal. It has to be noted that this is similar to the formulation of source filter model of speech, specifically the periodic components aka voiced sounds. Voiced sounds typically represented as impulse train are convolved with the transfer function to generate spectral envelope. As a corollary, from Eqn \\ref{discrete_Eqn} and \\ref{transfer_function_representation}, we posit that the optimization in WaveNet model is performed by minimizing the divergence between true and approximate spectral envelope. Note that latent stochastic models such as VAEs are aimed to minimize the divergence between true and approximate posterior distributions of input data. The advantage with such models is the presence of stochastic random variables that capture the causal factors of variation in input based on some prior information about the distributional characteristics of data. Techniques aimed at this \\citep{beta_vae} have shown that it is possible to effectively disentangle the factors of variation using stochastic variables. Hence, we postulate that it should be possible to augment WaveNet decoder with a suitable encoder and an appropriate prior distribution to disentangle the acoustic phonetic units from a given utterance. \n\n\nHowever, this is a deceptively non-trivial task. If the prior is too simplistic, such as unit normal distribution, the model is trivially incentivized to force the posterior distribution to closely follow the Gaussian prior distribution \\citep{lossy_vae}, particularly early in training. This results in the decoder marginalizing out the latent variable completely, manifesting in poor reconstruction ability. On the other hand, making the prior distribution arbitrarily complex also leads to unreasonable constraints on the decoder. For instance, in scenarios that have categorical distributions as their output (tasks such as language modeling, machine translation, and 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. We make an observation that dealing with speech presents a characteristic advantage - speech has both continuous as well as discrete priors. The generative process of speech assumes a Gaussian prior distribution which is continuous in nature. However, the language which is also present in the utterance can be approximated to be sampled from a discrete prior distribution. Exact manifestation of this in the linguistics can be at different levels: phonemes, words, syllables, subword units, etc. From the analysis presented in the previous section, we hypothesize that if we use background knowledge about the data distribution while designing the priors, we can help the encoder effectively disentangle the latent causal factors of variation in the data. In other words, this presents us with an opportunity to control what gets disentangled in the latent space by appropriately choosing a prior distribution. Therefore, we engineer our prior space to account for the phonetic information in the utterance by representing the prior as a discrete latent variable bank, similar to the filterbanks used for feature extraction from speech. Each discrete latent variable has a different set of states reflecting one of the articulatory dimensions. The specific design of our latent space is highlighted in Table \\ref{articulatory features}.\n\n\n\\renewcommand{\\arraystretch}{1.0}\n\\begin{table}[t]\n\\caption{Articulatory Features\\label{tab:arti}}\n\\centering\n\\begin{tabular}{l | c | c}\\toprule[\\heavyrulewidth] \\textbf{Feature name} & \\textbf{Value} & \\textbf{Details} \\\\\n\\toprule[\\heavyrulewidth]\nvc & + - 0 & vowel or consonant \\\\\nvlng & s l d a 0 & vowel length\\\\\nvheight & 1 2 3 0 - & vowel height \\\\\nvfront & 1 2 3 0 - & vowel frontness\\\\\nvrnd & + - 0 & lip rounding\\\\\nctype & s f a n l r 0 & consonant type \\\\\ncplace & l a p b d v g 0 & place of articulation \\\\\ncvox & + - 0 & consonant voicing\\\\\nasp & + - 0 & consonant voicing\\\\\nnuk & + - 0 & consonant voicing\\\\\n\\bottomrule[\\heavyrulewidth]\n\\end{tabular}\n\\label{articulatory features}\n\\end{table}\n\n\n\n\\section{Experiments}\n\\label{expts}\n\n\n\\subsection{ZeroSpeech 2019 dataset}\n% The goal of ZeroSpeech dataset is to learn the Phonetic representation of the audio without any supervision, discover the symbolic representation of the audio, and resynthesize the audio using these unit. The evaluation metric look at both the quality of sub-unit and the resynthesized audio.\n\nZeroSpeech Challenge 2019: TTS without T is to propose to build a speech synthesizer without any text or phonetic labels~\\citep{sakti2008development1, sakti2008development2, zerospeech2019}. The systems are required to extract the symbolic representation of the raw audio, and then re-synthesize the audio using these discovered units. There are three datasets in total: (1) \\textit{Unit Discovery Dataset} provides audio from a variety of speakers and is used to unsupervised acoustic modeling, (2) \\textit{Voice Dataset} provides audio from the targeted speaker and is used for synthesizer modeling and (3) \\textit{Parallel Dataset} is intended for finetuning both the sub-systems. We have not utilized the parallel dataset for our observations in this study. The development language is English and the test language is Standard Indonesian. The system is constrained to not use any pre-existing resource or models. To ensure that the model generalizes out of the box, the hyperparameter will be fine-tuned only on the development dataset, and the model will be trained in test language under the same parameters. \n\n\\iffalse\n\\begin{enumerate}\n \\item \\textit{Unit Discovery Dataset} provides audio from a variety of speakers and is used to unsupervised acoustic modeling\n \\item \\textit{Voice Dataset} provides audio from the targeted speaker and is used for synthesizer modeling\n \\item \\textbit{Parallel Dataset} is used for finetuning the both sub-systems\n\\end{enumerate}\n\nThe development language is English and the test language is Standard Indonesian. The system is refrained from using any pre-existing resource or models. To ensure that the model generalizes out of the box, the hyper-parameter will be fine-tuned only on the development dataset, and the model will be trained in test language under the same parameters. \n\\fi\n\n% \\subsubsection{CSTR VCTK Corpus}\n\n% CSTR VCTK is an English speech dataset, which contains 109 native speakers with various accents. Each speaker is required to record 400 sentences from newspaper, plus Rainbow Passage and an elicitation paragraph intended to identify the speaker's accent.\n\n%\\subsection{Implementation Details}\n\n% CSTR VCTK Corpus includes speech data uttered by 109 native speakers of English with various accents. Each speaker reads out about 400 sentences, most of which were selected from a newspaper plus the Rainbow Passage and an elicitation paragraph intended to identify the speaker's accent\n% \n% newspaper sentences,\n\n\\iffalse\nOur voice building process employs the phone sharing approach as outlined in \\citep{rallabandi_mixedlingual_IS2017} - where the combined phoneset is formed by the union of phones from both the languages - to build acoustic models. In this section, we present our approaches to generate the required bilingual acoustic data using just monolingual recordings. Specifically, in each of the subsections, we introduce the approaches we follow to artificially generate spectral content in English. We then follow the outlined procedure to build a bilingual voice using the native (L1) recordings and `pseudo English' (L2) recordings. \n\nIn this section, present our approaches for ZeroSpeech 2019. Specifically, our aim is to build robust models capable of accomplishing (1) Discovering acoustic units given a speech utterance. and (2) Generating novel utterances conditioned on the discovered acoustic units. For this, we have built two systems: (1) System A which is a pipeline based approach and (2) System B which is an end-to-end approach. \n\\fi \n\n\\section{Baseline System}\n\nWe have a three-stage pipeline: (1) \\textit{Unit Discovery}: We hypothesize acoustic units given a speech utterance using latent Stochastic Models; (2) \\textit{Unit Alignment}: We fine-tune the alignment between the utterance and the proposed acoustic units ; (3) \\textit{Unit Synthesis}: We build a speech synthesizer using the acoustic units and the target voice.\n\n\n%In this section, we will elaborate on each of the three stages.\n\n%\\subsubsection{Acoustic Unit Discovery}\n%\\subsubsection{Acoustic Unit Alignment}\n\nAs proposed in \\citep{sitaram2013bootstrapping}, we take the initially discovered transcription of the acoustic units for our speech corpus and train an ASR model on it. Then we re-encode the corpus using the ASR model, and train a TTS system on it. Here we using Bi-LSTM with CTC loss as our ASR model, and tacotron \\citep{tacotron_transferlearning2multispeaker} as TTS system. \n\n% At each iteration, an acoustic model is trained from the parallel speech-transcription data. This acoustic model is then used to re-decode the speech data, and so on for 10 iterations. At the end of each iteration, we have produced a rebuilt acoustic model and a re-decoded transcript. These two are used to build a synthetic CLUSTERGEN \\citep{black2006clustergen} voice (given the noise in the generated data, statistical parametric synthesis is appropriate) using Festvox for the purpose of evaluation on a held out test set on the basis of MCD scores. The best-aligned transcription is taken as the one producing the synthetic voice with the lowest distortion score.\n\n%\\subsubsection{Acoustic Unit Synthesis}\n\n\n\n\n\n\\begin{figure}[t]\n \\centering \n \\subfigure[Original speech]{ \n \\includegraphics[width=0.95\\linewidth]{images/target4.png}}\n\\subfigure[Generated speech]{\n \\includegraphics[width=0.95\\linewidth]{images/generated4.png}}\n\\subfigure[Converted speech]{\n \\includegraphics[width=0.95\\linewidth]{images/transferred4.png}}\n \\caption{Spectrograms of original, generated, and converted speech. The source speaker is female while the target speaker is male.\\label{fig:waveform}}\n\\end{figure}\n\n\n\\subsection{VACONDA}\n\nThe architecture of our model is built on top of VQ-VAE. It consists of three modules: an encoder, quantizer and a decoder. As our encoder, we use a dilated convolution stack of layers which downsamples the input audio by 64. The speech signal was power normalized and squashed to the range (-1,1) before feeding to the downsampling encoder. To make the training faster, we have used chunks of 2000 time steps. This means we get 31 timesteps at the output of the encoder. The quantizer acts as a bottleneck and performs vector quantization to generate the appropriate code from a parameterized codebook. We define the latent space $e \\in \\mathbmm{R}^{k\\times d}$ to contain $k$ $d$-dim continuous vector. Quantization is implemented using minimum distance in the embedding space. The number of classes was chosen to be 64, approximating 64 universal phonemes. We use a linear mapping to first project the 128 dimensional vector to 160 dimensions. We then perform comparisons with respect to individual articulatory dimensions each of which is 16 in size. Assuming $z_e(x)$ denotes the encoder output in the latent space, then the input of decoder $z_d(x)$ will be obtained by $\\argmin_{j}d(e_j, z_e(x))$, where $d$ is a similarity function of two vectors. In this paper, we consider Euclidean distance as the similarity metric. Our decoder is an iterated dilated convolution-based WaveNet that uses a 256-level quantized raw signal as the input and the output from vector quantization module as the conditioning. Although using a Mixture of Logistics loss function might yield a better output, we have only used a 256 class softmax in this study. The decoder takes the output from the quantizer along with the speaker label as global conditioning and aims to reconstruct the input in an autoregressive fashion. Following IDCNNs, we have shared the parameters of all the stacks.\n\n\n\n% In this subsection we describe our end-to-end approach for the task. We extend the framework proposed in \\citep{vq-vae} to accomplish subword unit discovery. Although a structure such as HMM \\citep{hmm-vae_bhiksha} might be intuitively better at capturing the transitions, we have limited ourselves to a vector quantization based approach as we observed it to be better at handling the posterior collapse problem in VAEs. We have used 3 stacks of 10 layers each in the decoder and residual blocks with similar dilation factors in each of the stacks shared their parameters \\citep{strubell2017fast}.\n\n% Our voice building process employs the VQ-VAE approach as outlined in \\citep{rallabandi_mixedlingual_IS2017}, where the raw audio is first fed to a downsampling encoder which reduces the time resolution by 64. This encoded representation is then hashed into a latent representation that is forced to follow articulatory constraints. Specifically, we employ a set of discrete embeddings of cardinality 5, where each is a multi-dimensional array in itself associated with a continuous vector. The output from this hash function is fed to the decoder, which is a conditional WaveNet implemented using iterated dilated convolutions. In this section, we first present our analysis of the optimization that happens in our models. We then present a case for controlling the disentanglement that happens in such models to accomplish voice conversion. This is followed by an explanation of each component in our model in detail.\n\n% Aside from the architecture discussed in Section~\\ref{proposed_approach}, we argue that adding meaningful inductive bias can help the model learn better. We first normalize the vector representation to ensure the same scale in the latent space. Compared to VQ-VAE, we incorporate the articulatory features information in Table~\\ref{tab:arti}. The above articulatory features apply to all human languages. To incorporate them, we first transpose the embedding from 128-dimension to 160-dimension by a linear layer. Then, we equally divide the latent embedding into 10 parts, and perform the vector quantization separately. Finally we concatenate all vectors, and feed into the linear layer to map it back to 128-dimension. In each class, the number of latent embedding is the number of possible values.\n\n\n\\subsection{Analysis}\n\nIn this section, we will discuss different design choices in the architecture, including input features and latent space constraints. \n\n% \\subsubsection{Input Feature}\n\n% We first compare the performance gap between different features as our model's input. The feature used along with its performance is shown in Table~\\ref{tab:input}.\n\n\\subsubsection{Acoustic Unit Discovery}\n\nHere we analyze the AUD performance of three different models in ZeroSpeech dataset as shown in Table~\\ref{tab:aud}. We only show the results in English since we don't have ground truth for the Indonesian language.\n\n% Now all is baseline \n\n\\renewcommand{\\arraystretch}{1.1}\n\\begin{table}[!htbp]\n\\caption{Performance of different systems in ZeroSpeech}\n\\centering\n\\begin{tabular}{l c c}\\toprule[\\heavyrulewidth]\n& \\multicolumn{2}{c}{English}\\\\\nModel & ABX score & bitrate \\\\\n\\toprule[\\heavyrulewidth]\nBaseline & \\textbf{27.46} & 74.5\\\\\nThree-stage Model & 34.86 & 68.54 \\\\\nVACONDA & 38 & \\textbf{58.19} \\\\\n\n\\bottomrule[\\heavyrulewidth]\n\\end{tabular}\n\\label{tab:aud}\n\\end{table}\n\nAs in Table~\\ref{tab:aud}, the VACONDA achieves the best bit rate among three models. With such small number of unit, we could resynthesize and even convert the speech in a very high quality.\n\n\\subsubsection{Speech Resynthesis and Conversion}\n\nThe proposed model supports synthesizing the same speech in both the same speaker and a different speaker. Here we show a sample in the test dataset of Indonesian language in Figure~\\ref{fig:waveform}. When we feed the decoder with the same speaker identification, the decoder will generate the original audio. Otherwise, it will perform speech convertion. The three audio shares similar structure. However, the converted audio has denser waveform, suggesting it's a different speaker. For the sampled audio, please visit the \\href{http://tts.speech.cs.cmu.edu/rsk/campaigns/interspeech2019/submissions/acoustic_unit_discovery/}{our website}.\n\n\n\n%The results are shown in Table~\\ref{tab:constraints}. We use \n\n% \\renewcommand{\\arraystretch}{1.1}\n% \\begin{table}[htbp]\n% \\caption{System performance with latent space constraints}\n% \\centering\n% \\begin{tabular}{l | c}\\toprule[\\heavyrulewidth] \\textbf{Model} & \\textbf{ABX score}\\\\\n% \\toprule[\\heavyrulewidth]\n% Baseline model & 12\\\\\n% \\bottomrule[\\heavyrulewidth]\n% \\end{tabular}\n% \\label{tab:constraints}\n% \\end{table}\n\n\\label{analysis}\n\n\n\\subsection{Conclusion}\n\nIn this case study, we present an approach to automatically discover acoustic-phonetic units from a speech utterance in an unsupervised fashion. We first present an analysis to show that incorporating latent random variables into neural generative models using suitable priors allows us to control what gets encoded into the latent space. Based on this, we employ articulatory features as a discrete prior bank in the latent space and obtain acoustic units that are speaker and language independent. To validate effectiveness of the discovered units, we perform discriminability tests as part of ZeroSpeech Challenge 2019. \n\n\n\\section{De-Entanglement of Content - Application to Source Separation}\n\n\n\n\\noindent Speech synthesis has taken some major strides in past few years especially in the form of text-2-speech synthesis (TTS) models. However, most of the work that has been carried out involves carefully recorded speech data. Generation of such vast amount of data for every application is a daunting task. On the other hand, there is a plethora of speech data that is available on the internet such as news broadcasts, press conferences, audio books etc - also referred to as \\textit{Found Data}. The only hindrance in utilizing such data for speech based machine learning models is that this found data is characterized by noise or music in the background. Presence of noise / music degrades the performance of such models. One of the solutions to this problem is source separation - separating out speech from music in the audio. There have been several attempts to accomplish this task using both classical speech processing techniques as well as deep learning models.\\\\\n\n\\cite{6287816} proposed a matrix factorization of the magnitude spectrogram of audio that utilizes the periodicity in music and sparseness in speech to separate the two. However, this technique requires a lot of hyperparameter tuning depending on the type of background music and also degrades the quality of separated speech to some extent. REPET \\cite{6269059} also involves music separation by exploiting its periodic nature but on occasions still leaves a residual music in the background. Most of the work in source separation using deep learning has been supervised \\cite{SVSGAN}, \\cite{Disc}, \\cite{TFGAN}, \\cite{spen}, i.e. they had both noisy and clean versions of the data. However most of the times, especially with found data, we don't have the clean version of the data. \\\\\n\nThere has also been some focus on source separation using unsupervised models. \\cite{Hsu2018DisentanglingCS} takes the approach of data augmentation by adding different background noise to the clean data and then training an adversarial classifier to make these augmented versions of data indistinguishable from the original speech. However, this method again requires a clean version of data first and additional data augmentation that is representative of the noise in the background. Therefore essentially, this is a semi-supervised approach that requires labels for clean and noisy data. One other semi-supervised approach is using domain adaptation \\cite{domadp} where output is made to follow the clean data domain while making the encoding for clean and noisy data domain indistinguishable using a adversarial classifier. However, this approach requires speech content in both clean and noisy version of data to be very similar for domain adaptation to occur. \\\\\n\nWe propose a completely unsupervised approach using multinode variational autoencoders (VAE) combined with robust principal component analysis (RPCA) \\cite{6287816} as a post-processing step. Our goal is to enable the use of found data for downstream TTS applications. Therefore, the data we target is predominantly speech with music in the background. We apply this approach on two datasets:- Wilderness\\cite{wildernessdataset} and Hub4. Wilderness consists of Bible recordings in 699 languages while Hub4 is a news broadcast dataset in English. Both of these datasets contain music/noise in the background. We show that the proposed approach separates out the dominant mode, speech, from a noisy audio and improves the performance of the downstream tasks irrespective of the language of the speech. \\\\\n\nThis paper is organized as follows: section 1 discusses the variational autoencoder framework, section 2 talks about source separation using VAE, section 3 addresses the extension to multinode VAE architeture and section 4 discusses post-processing using robust principal component analysis (RPCA). Section 5 analyses the source separation capacity and architectural requirements of the proposed model. Section 6 reports the performance of the proposed model for source separation and for downstream TTS applications. We conclude in section 7.\n\n\\section{Variational Autoencoder}\nVariational autoencoder model in this paper follows the standard formulation consisting of an inference network with a speech encoder $p(z|x)$ and a latent space decoder $p(x|z)$, where $x$ and $z$ represent the input and the latent space random variables respectively. \n\n\\begin{figure}[h!]\n \\centering\n \\includegraphics[scale=0.4]{LatexDiss/Dissertation/images/vae_graph.png}\n \\caption{Latent Variable Model - Variational Autoencoder}\n \\label{fig:vae_graph}\n\\end{figure}\n\n\nThe figure \\ref{fig:vae_graph} depicts the latent variable model for variational autoencoder. The true posterior density is intractable.\n\n\\begin{equation}\n p(z|x) = \\frac{p(x|z)p(z)}{p(x)}\n\\end{equation}\n% Intractable true posterior and marginals\n% ELBO formulation\n\n\nWe then approximate the true posterior $p(z|x)$ with a variational distribution $q(z|x)$ that has a prior $p(z)$. The objective can be represented by the evidence lower bound (ELBO) or variational lower bound on the likelihood of the data. \n\\begin{equation}\n \\log{p(x)} \\geq \\mathcal{L}(x)\n\\end{equation}\n\n\\begin{equation}\n\\mathcal{L}(x) = \\mathbb{E}_q[\\log(p(x|z))] - D_{KL}(q(z|x) || p(z)) \n\\label{Likelihood}\n\\end{equation}\n\nwhere $\\mathcal{L}(x)$ denotes the variational lower bound on the likelihood of the data and $D_{KL}$ is the Kullback-Leibler divergence. We write the first term as a mean squared error (MSE) between the reconstructed and the original data and the prior p(z) follows a standard normal distribution $\\mathcal{N}(0,I)$.\n\n\\section{VAE for Source Separation}\nAs shown in the previous section, a variational autoencoder reconstructs the input data conditioned on the latent space. The latent space is constrained to follow a certain prior distribution, such as Gaussian distribution. \\cite{JMLR:v19:17-704} shows that this formulation is equivalent to minimizing the alternative lower bound function \n\n\\begin{equation}\n\\begin{aligned}\nminimize \\;\\; & n \\cdot rank[\\, L \\,] \\,+ \\parallel S \\parallel_0 \\\\\nM & = L + S \\\\\n\\end{aligned}\n\\end{equation}\n\n\nwhere M is the original data matrix, L is a low-rank matrix and S is a sparse matrix and $\\parallel.\\parallel_0$ denotes the $l_0$ norm. This is shown to be equivalent to an RPCA problem if an optimum solution exists otherwise it's known to smooth out undesirable erratic peaks from the energy curve. \\cite{JMLR:v19:17-704} also presents some interesting results on VAE and it's separation properties. We rewrite some of the results what it means in our context here.\n\n\n\\begin{itemize}\n \\item This formulation of variational autoencoders is shown to perform robust outlier removal in the context of learning inlier points constrained to a manifold of unknown dimension. In simple terms this means, VAE has the property to remove sparse components in the input data distribution and accordingly reduces the latent space to a required (unknown) dimension.\n \\item VAE also help smooth out undesirable minima from the energy landscape of the optimization problem which differentiates it from traditional deterministic autoencoders.\n\\end{itemize}\n \nSince our goal is to enhance speech synthesis and speech recognition performances on the 'found' data, we target audio data that is predominantly speech with some music (almost uniform) in the background, for instance, news broadcasts and audio books. We will later show that the presence of the background music can effect the speech synthesis performance drastically. It's been shown that speech and music distributions in audio are quite distinct \\cite{SM_diff} \\cite{SM_diff1}. As a result VAE has the tendency to remove the sparse outlier - music from the audio. \\\\ \n\nIn case of multiple speakers in the input audio there can be multiple modes in the speech distribution as well. This can be solved by have multiple nodes in the latent space. This is possible because all latent variables are initialized at random and pick multiple speech modes from the distribution. Later in the results section, we are going to analyze this and the requirement on the number of nodes in the latent space depending on the input data distribution. We also talk about how the performance of the output speech changes based on the intensity/loudness of the music in the background.\n\n\\section{Multi-node VAE Model Architecture}\n\n\n\\begin{figure}\n \\centering\n \\includegraphics[scale=0.31]{LatexDiss/Dissertation/images/Multinode_VAE.jpg}\n \\caption{Multi-node VAE model. Dashed lines represent sampling using reparametrization. Encoder and Decoder are Bi-LSTM networks. Purple blocks are fully connected layers.}\n \\label{fig:VAE}\n\\end{figure}\n\nThe Figure \\ref{fig:VAE} depicts the multi-node variational autoencoder architecture. It consists of an Bi-LSTM encoder ($LSTM_E$) for the inference network that captures latent space distributions $p(z_1|x), p(z_2|x), \\dots, p(z_k|x)$ where $x$ is the magnitude spectrogram of the input audio, $z_1, z_2, \\dots, z_k$ are the latent variables and $k$ is the number of latent variables. The reconstruction network is a Bi-LSTM decoder ($LSTM_D$) which generates the reconstructed input distribution at each time-step $p(x_r^t|x_r^{t-1},z_1,z_2,\\dots,z_k)$ conditioned on the reconstructed input from the previous time-step and the latent space. \n\n\\begin{equation}\nh_e^t, c_e^t = LSTM_E(x^t,h_e^{t-1},c_e^{t-1})\n\\end{equation}\n\\begin{equation}\n\\mu_i^t = MLP_{\\mu_i}(h_e^t) \\; \\forall i \\in {0,\\dots,k}\n\\end{equation}\n\\begin{equation}\nlogvar_i^t = MLP_{\\sigma_i}(h_e^t) \\; \\forall i \\in {0,\\dots,k}\n\\end{equation}\n\\begin{equation}\nq(z_i|x) = \\mathcal{N}(\\mu_i,\\exp(logvar_i))\n\\end{equation}\n\\begin{equation}\nh_{d}^t, c_{d}^t = LSTM_D(\\phi^t, z_1^t, \\dots, z_k^t,h_d^{t-1},c_d^{t-1})\n\\end{equation}\n\\begin{equation}\n\\phi^t = MLP_{\\phi}(h_d^{t-1})\n\\end{equation}\n\\begin{equation}\nx_r^t = MLP_{x_r}(h_d^t)\n\\end{equation}\n\nwhere Bi-LSTM refers to bidirectional long short term memory recurrent neural network, MLP refers to a multi-layer perceptron network, $h_e, c_e$ represent hidden and cell states of the encoder LSTM, $h_d, c_d$ represent hidden and cell states of the decoder LSTM and $\\phi$ represents the context from the previous time-step of the decoder. The initial hidden state and the cell state of the decoder LSTM are learnable parameters. The latent variable model for the multinode variational autoencoder is shown in figure \\ref{fig:multinodevae_graph}\\\\\n\n\\begin{figure}[h!]\n \\centering\n \\includegraphics[scale=0.4]{LatexDiss/Dissertation/images/multinode_vae_graph.png}\n \\caption{Latent Variable Model - Multinode Variational Autoencoder}\n \\label{fig:multinodevae_graph}\n\\end{figure}\n\nThe modified learning objective for a multinode VAE can be represented as an extension of equation \\ref{Likelihood} as:\n\n\\begin{equation}\n\\begin{aligned}\n\\mathcal{L}(x) \\ge & \\; \\mathbb{E}_q[\\log(p(x|z_1,z_2,\\dots,z_k))] \\\\& -\\sum_{i=1}^k D_{KL}(q(z_i|x) || p(z_i)) \n\\end{aligned}\n\\end{equation}\n\n\n\n\\section{Speech Enhancement}\n\nThe output of the VAE network from the above formulation removes the music from the audio however, replaces the music content with random noise instead of silence. There can be multiple post processing or speech enhancement techniques used to eliminate this residual noise such as speech enhancement neural networks or classical speech processing methods. Here in this paper we use robust principal component analysis (RPCA) \\cite{6287816} to eliminate the background noise as it gives control over the quality of speech versus the amount of background noise. We follow the original formulation from the paper by expressing the speech separation as a matrix factorization problem. It represents the magnitude spectrogram of the audio signal as a sum of low rank matrix and a sparse matrix. The assumption here is that non-speech component (background noise) is low rank while the speech component is sparse. \n\n\\begin{equation}\n\\begin{aligned}\nminimize & \\parallel L \\parallel_* + \\lambda \\parallel S \\parallel_1 \\\\\nM & = L + S\n\\end{aligned}\n\\end{equation}\n\nwhere $M \\in \\mathbb{R}^{n_1 \\times n_2}$ is the magnitude spectrogram of the VAE output, $L \\in \\mathbb{R}^{n_1 \\times n_2}$ is a low rank matrix, $S \\in \\mathbb{R}^{n_1 \\times n_2}$ is a sparse matrix, $\\parallel . \\parallel_*$ is the nuclear norm and $\\parallel . \\parallel_1$ is the $L_1$ norm. $\\lambda > 0$ is a hyperparameter that controls the rank and sparsity of $L$ and $S$ respectively. It is recommended in \\cite{6287816} to use $\\lambda = 1/\\sqrt{max(n_1,n_2)}$ to obtain the best result. However, we only need to enhance the audio a little while retaining the speech quality so we use $\\lambda = 0.3/\\sqrt{max(n_1,n_2)}$. Instead of the hard mask in \\cite{6287816} we used a soft mask as it resulted in a better quality and a smoother speech. The idea is to have a high value for the speech mask where the magnitude of the speech component is much greater the magnitude of the non-speech component.\n\n\\begin{equation}\n|S| > g|L|\n\\end{equation}\n\n\\begin{equation}\n|S|^2 > g^2 |L|^2\n\\end{equation}\n\n\\begin{equation}\n|M|^2 = |S|^2 + |L|^2\n\\end{equation}\n\n\\begin{equation}\n|S|^2 > g^2 |M|^2 - g^2|S|^2\n\\end{equation}\n\n\\begin{equation}\n|S|^2 > \\frac{g^2}{1 + g^2} |M|^2 \n\\end{equation}\n\n\\begin{equation}\n|S| > \\sqrt{\\frac{g^2}{1 + g^2}} |M|\n\\end{equation}\n\n\\begin{equation}\n\\frac{|S|}{|M|} - \\sqrt{\\frac{g^2}{1 + g^2}} > 0 \n\\end{equation}\n\nwhere $g \\ge 0$ is the gain factor. We came up with a Sigmoid looking threshold for the mask which is still close to the hard mask but results in smoother speech transitions. \n\n\\begin{equation}\nW = \\frac{1}{1 + \\exp{(-\\alpha(\\frac{|S|}{|M|} - \\sqrt{\\frac{g^2}{1 + g^2}}))}}\n\\end{equation}\n\nwhere $W \\in \\mathbb{R}^{n_1 \\times n_2}$ represents the speech mask and the obtained speech spectrogram is\n\n\\begin{equation}\nX_{speech}(i,j) = W(i,j)M(i,j) \\; \\forall i,j\n\\end{equation}\n\n\\section{Experiments}\nWe applied the multinode VAE model on two datasets:- Wilderness and Hub4. Wilderness dataset consists of Bible recordings in 699 languages with music in the background. We carried out full experiments on two languages:- Dhopadhola (an African language) and Marathi (an Indian language). The results presented here are based on the model that was trained on languages different than the ones that are reported/tested. Hub4 consists of news broadcast recordings in English with various forms of noise in the background, such as music, clapping, roaring etc. We used about 2 hrs of training data for both datasets consisting 1 hr of speech only data and 1 hr of speech-music data. \\\\\n\nFor these experiments, the VAE model consists of input magnitude spectrogram of dimension 512, Bi-LSTM encoder and decoder with hidden size of 512, each of the fully connected layers for latent variables and decoder context from the previous time-step of dimension 64 and the final output layer with a dimension same as the input dimension. We trained for 50 epochs with annealing weight for KL-Divergence loss, this is explained in detail below. For both datasets, we used an ADAM optimizer with a learning rate of 1e-3. \\\\ \n\n\n\\begin{figure}[h!]\n \\centering\n \\begin{subfigure}{0.2\\textwidth}\n \\includegraphics[scale=0.55]{LatexDiss/Dissertation/images/wilderness_hist.png}\n \\caption{Wilderness}\n \\end{subfigure}\n \\hspace*{\\fill}\n \\begin{subfigure}{0.2\\textwidth}\n \\includegraphics[scale=0.55]{LatexDiss/Dissertation/images/hub4_hist.png}\n \\caption{Hub4}\n \\end{subfigure}\n \\caption{Input Data Distributions for (a) Wilderness (b) Hub4. The red dots show the high density regions in each distribution.}\n \\label{fig:distributions}\n\\end{figure}\n\nThe input data distributions for the two dataset are shown in Figure \\ref{fig:distributions}. These 2-dimensional distributions are obtained after applying PCA to the magnitude spectrogram and plotting the histogram of the first two components. This figure shows the high density regions of the two distributions. As we can observe, the wilderness distribution has one significant high density region while the hub4 distribution consists of multiple high density regions. Hence, Hub4 data will have more dominant speech modes than the wilderness data. This is probably because there are multiple speakers in Hub4 as well as news broadcast speech has more variance as compared to bible recordings. This gives us an approximate idea that Hub4 multinode VAE model will require more nodes in the latent space than the model for Wilderness dataset. \\\\\n\n\\begin{figure}[h!]\n \\centering\n \\includegraphics[scale=0.37]{LatexDiss/Dissertation/images/score1.png}\n \\caption{Gaussian Mixture Fit for Wilderness and Hub4}\n \\label{fig:GMM}\n\\end{figure}\n\nFigure \\ref{fig:GMM} shows the likelihood of fitting Gaussian Mixture Models as a function of the number of cluster centers. As discussed earlier, speech modes are dominant in the target data so fitting $n$ clusters in the curve can be thought of as having $n-1$ nodes/clusters in the VAE for the speech and $1$ cluster as the residual non-speech data. The multinode VAE model for the wilderness data obtained good results with just $1$ VAE node or $2$ clusters as can be confirmed from the graph where likelihood values are high for just $2$ clusters. On the other hand, multinode VAE model for Hub4 gave good results with $3$ nodes or $4$ clusters. Now, as we increase the number of nodes, the peak performance does not change much, however, we attain the same peak performance for more model states:- MSE loss vs KL loss. This will be explained using training loss curves. It would have been better to use some validation parameter but since model performance for human hearing can only be analyzed by listening to the speech, we use the training metrics. \\\\\n\n\n\\begin{figure}[h!]\n %\\centering\n \\begin{subfigure}{0.4\\textwidth}\n \\centering\n \\includegraphics[scale=0.31]{LatexDiss/Dissertation/images/unsupervised1_w.png}\n \\caption{1-Node VAE: Wilderness}\n \\end{subfigure}\n \\vspace{0pt} \\newline\n \\begin{subfigure}{0.4\\textwidth}\n \\centering\n \\includegraphics[scale=0.31]{LatexDiss/Dissertation/images/unsupervised3_w.png}\n \\caption{3-Node VAE: Wilderness}\n \\end{subfigure}\n \\caption{Training Loss (a) 1-Node VAE: Wilderness (b) 3-Node VAE: Wilderness. The left shaded blue region and the right shaded orange region show the required MSE loss and KL loss threshold respectively to obtain good speech. Overlap region represents the model parameters where speech separation occurs.}\n \\label{fig:lossw}\n\\end{figure}\n\n\n\n\nThe Figure \\ref{fig:lossw} and \\ref{fig:lossh} give an idea of speech separation capacity of the model as we increase the number of latent variables. During training of the multinode VAE model, we anneal the KL divergence loss for latent space exponentially. We do the annealing for latent variables simultaneously. Initially, KL divergence loss is assigned a very small weight and then increased exponentially. So, it first increases (not shown in the plot as it's out of the range of the plot) and then decreases eventually while the MSE reconstruction loss first decreases and then increases slightly. During this process there is a small window where both the losses are low enough and we are able to extract out speech from the audio. This window is determined by the threshold values for both losses. If both loss values are below their respective thresholds, we observe speech at the output.\\\\\n\n\n\\begin{figure}[h!]\n %\\centering\n \\begin{subfigure}{0.4\\textwidth}\n \\centering\n \\includegraphics[scale=0.31]{LatexDiss/Dissertation/images/unsupervised1_h.png}\n \\caption{1-Node VAE: Hub4}\n \\end{subfigure}\n \\vspace{0pt} \\newline\n \\begin{subfigure}{0.4\\textwidth}\n \\centering\n \\includegraphics[scale=0.31]{LatexDiss/Dissertation/images/unsupervised3_h.png}\n \\caption{3-Node VAE: Hub4}\n \\end{subfigure}\n \\vspace{0pt} \\newline\n \\begin{subfigure}{0.4\\textwidth}\n \\centering\n \\includegraphics[scale=0.31]{LatexDiss/Dissertation/images/unsupervised8_h.png}\n \\caption{8-Node VAE: Hub4}\n \\end{subfigure}\n \\caption{Training Loss (a) 1-Node VAE: Hub4 (b) 3-Node VAE: Hub4 (c) 8-Node VAE: Hub4. The left shaded blue region and the right shaded orange region show the required MSE loss and KL loss threshold respectively to obtain good speech. Overlap region represents the model parameters where speech separation occurs.}\n \\label{fig:lossh}\n\\end{figure}\n\nThe blue and orange shaded regions in figures \\ref{fig:lossw} and \\ref{fig:lossh} depict the loss values below the threshold for MSE loss and KL divergence loss respectively. Therefore, their intersection as indicated by the overlap region represents the model parameters that result in speech and music separation. For visualization, the MSE loss in the figure is averaged over all the samples as well as in the time dimension of the audio while the KL divergence loss is averaged over all the latent variables as well as across all samples. Using these loss definitions results in a threshold value of 250 for MSE loss and a threshold value of 60 for KL divergence loss for both datasets. These are just soft experimental values and may change for other datasets as well as a different loss definition. The key idea is that there exists a window where speech separation occurs. \\\\\n\n\n\nAs shown in the figure, for Wilderness data we obtain this window with just one node in the latent space. As we increase the number of nodes in the latent space, we don't see any significant improvement in the quality of the output speech, however, we do obtain a wider window where this separation occurs. As for the Hub4 dataset, we don't observe any such window with one latent node, however, we do obtain a separation window with three latent nodes and an even wider window with eight latent nodes. Observe that, these results align with the results derived using input data distribution and GMM fitting analysis. Therefore, to be totally certain about the existence of a separation window, we can always add a few more latent variables than what we obtain from our analysis of input distribution. \\\\\n\nLet's explore the nature of the output on either side of the separation window. On the blue/left side of the window MSE loss is very low while the KL divergence loss is high, this results in the output that is close to the original input that consists of both speech and music. On the orange/right side of the window, MSE loss is high while the KL divergence loss is low. This causes the network output to be a really noisy version of the speech component of the audio. \\\\\n\nWe also observed that, as the intensity/loudness of music in the background increases in an audio or for a part of the audio, the speech separation performance for that part of the audio begins to deteriorate slightly. For example, in case of advertisement segments between news broadcasts where music tends to dominate the segment. In such cases, we can still hear some traces of music in the background when we use the same VAE model as we do for the rest of the data. However, this is not a concern as the downstream applications we target don't generally depend on data with such high intensity music. \\\\\n\nAs mentioned in \\cite{JMLR:v19:17-704}, a traditional autoencoder is not able to perform the outlier removal. We verified this fact experimentally. We removed any constraint on the latent space and trained the model to minimize the reconstruction loss. We observed that the model was able to reconstruct the audio completely including both speech and music. Therefore, a traditional autoencoder is not able to smooth out the energy contour and fails to remove any outliers. We also tried to experiment with this model on songs and movie clips. As the background music in songs and movies very dense and varies significantly, we observed that our model wasn't able to separate out speech completely. The output speech contained some music in the background and the quality of speech itself was compromised. \n\n% Songs\n% TV shows/ Movies\n\n\\section{Results}\n%The separated speech samples for both Wilderness and Hub4 datasets can be found in the supplemental material\nThe separated speech samples for both Wilderness and Hub4 datasets can be found at \\footnote[1]{https://github.com/nishantgurunath/Separabl/tree/master/samples}\nunder folders \"Wilderness\" and \"Hub4\" respectively. We present Wilderness samples for two languages - Dhopadhola and Marathi both having different but somewhat uniform music in the background. These samples can be found inside their respective folders within the wilderness folder. We also present samples for when we removed the KL-divergence term from the loss function and trained an autoencoder instead. It can be observed from the samples that the model reconstructs the whole audio without outlier/music removal. Hub4 data samples have a lot more variation in both speech and music. All the samples come from news broadcast in English. We also ran experiments on mixed signals where a background music was added to a clean sample from the wilderness data. We performed this experiment with drums, flute, guitar and piano music in the background. \n%The mixed audio and the separated speech samples can be found in the supplemental material.\\\\ \nThe mixed audio and the separated speech samples can be found at \\textsuperscript{\\rm 1}.\\\\ \n% Do on some standard dataset\n\\begin{table}[h!]\n \\centering\n \\begin{tabular}{|c|c|c|}\n \\hline\n \\textbf{Input Audio} & \\textbf{SegSNR} & \\textbf{MOS} \\\\\n \\hline\n Noisy & 4.91 & 1.5 \\\\\n \\hline\n Clean & 7.5 & 1.2\\\\\n \\hline\n \\end{tabular}\n \\caption{Segmented Signal to Noise Ratio (SegSNR) and Mean Opinion Score (MOS) for Mixed Signals}\n \\label{tab:my_label}\n\\end{table}\n\n\\begin{table}[h!]\n \\centering\n \\begin{tabular}{|c|c|c|}\n \\hline\n \\textbf{Audio} & \\textbf{WER Mono Voxforge} & \\textbf{WER Tri2b Librispeech}\\\\\n \\hline\n Noisy & 100.53 & 103.72 \\\\\n \\hline\n Clean & 102.84 & 104.33 \\\\\n \\hline\n \\end{tabular}\n \\caption{Word Error Rate (WER) for Noisy and Cleaned Audio on Pretrained Kaldi ASR Models}\n \\label{tab:my_label}\n\\end{table}\n\nOne other way to asses the proficiency of the proposed method is to evaluate its performance on downstream tasks, for instance, Text-2-Speech Synthesis (TTS). We performed Text-2-Speech synthesis on original and cleaned version of Marathi language from the wilderness dataset. \n%The TTS samples can be found with the supplemental material as well. \nThe TTS samples can be found at \\textsuperscript{\\rm 1} as well.\nWe observe that Text-2-Speech synthesis performance improves significantly after music is removed from the background. In TTS samples generated from the original (noisy) version of the audio, one can clearly see the distortion in the speech and presence of music in the background. Whereas, TTS samples that were generated from cleaned samples had a very clear speech quality with no music in the background. \n\n\n\n\n% TTS with noisy - speech breaks and music in the background\n\n\\section{Conclusion}\nWe show that Multinode VAE model helps to remove the background noise/music in the 'found data' irrespective of the language of the speech. Extensive studies on different type of speech and music data verify the effectiveness and robustness of the proposed approach. Performance of this model on Text-2-Speech synthesis applications shows the potential of such an approach that can be further extended to other speech based machine learning models such as Automatic Speech Recognition (ASR). Such an efficient source separation technique can help overcome a major cause for under utilization of 'found data'. This could mean that acoustic based machine learning models can be drastically improved by leveraging the data found on the internet. Since this approach works in a unsupervised fashion, it eliminates the need to obtain labeled data which has been major hindrance to effective utilization of 'found data'. Since 'found data' is abundant, this could also possibly further accelerate the research in this area. \n\n", "meta": {"hexsha": "115ff1f305d0bb2c95c0e0aa3367cb1f5d0cb7c6", "size": 56179, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "quarterly_stuff/2020Q2/chapters/de-entanglement_of_content.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/de-entanglement_of_content.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/de-entanglement_of_content.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": 96.6936316695, "max_line_length": 2195, "alphanum_fraction": 0.7894764948, "num_tokens": 13055, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.3486451488696663, "lm_q1q2_score": 0.19196658692576865}}
{"text": "\nIn embedded IoT class devices to which an attacker may have\nphysical access,\nDifferential Power Analysis (DPA) attacks on cryptographic implementations\n\\cite{KJJ:99} can be devastating.\nWhile ISEs give a notable increase in efficiency, they can also create\nattractive targets for DPA attacks.\nThis stems from there being only one way to sensibly implement\nAES using the ISE and the ISE having very well defined behaviour.\nThis reduces the number of target variables or\nimplementation styles an attacker needs to consider.\nIt is then important to consider how an implementer might\nfurther extend a cryptographic ISE to secure it against DPA attacks.\nWhile our focus here is on DPA attacks, we note that Differential\nElectro-Magnetic Analysis attacks are exploited and countered using\nsimilar techniques to DPA.\n\nHaving identified ISE \\ISE{3} as a strong standardisation candidate\nfor embedded $32$-bit RISC-V cores, we take a hardware/software co-design\napproach to extending the ISE, adding $1$st order DPA side-channel\nresistance.\n\n\\subsection{Design}\n\nWe based our design on boolean masking, and represent the secret\nkey as two Boolean masked shares.\n\nAn implementation of the AES block encrypt/decrypt function \nusing \\ISE{3} requires eight $\\GPR$s:\nfour for the current round state and\nfour to load the next round key\nand\nthen accumulate the next round state.\nSee \\REFFIG{fig:v3:round} for an AES round function implementation\nusing \\ISE{3}.\nStoring shares of each secret variable\nin the General Purpose Register (GPR) file is unreasonable,\nrequiring drastic modifications to the instruction definitions and\nregister file to read four registers (two sources, of two shares each) and\nwrite two registers.\nThis would break the RISC-V $2$-read-$1$-write principle.\nStoring corresponding shares in the GPRs is also a security\nrisk, as they may be accidentally combined due to\ncareless instruction use, or implicit register accesses by the\nCPU micro-architecture.\n\nInstead, we define a new, $8$-element ``Mask Register File'' (MRF).\nEach mask register $M_i$ is $R=32$-bits wide, and stores the mask for\none of the GPRs.\nWe use a fixed mapping between GPRs and mask registers;\nnot all GPRs have a corresponding mask register.\nWe use the mapping $\\{a0..a3,t0..t4\\} \\Rightarrow \\{m0..m7\\}$.\n\nShare $0$ of each secret value is loaded into the GPRs using the\nstandard RISC-V Load Word ({\\tt lw}) instruction.\nWe define a new Load Mask instruction {\\tt lm rd, offset(rs1)} which\nloads {\\em the mask for GPR {\\tt rd}}\n(i.e. Share $1$)\nfrom memory into the corresponding MRF entry.\nA corresponding Store Mask instruction {\\tt sm rs2, offset(rs1)} writes\nthe mask corresponding to GPR {\\tt rs2} to memory.\nThe {\\tt sm} instruction is only used for context switches, and\ndestructively reads the MRF register value to prevent it being\nleaked to other applications running on the same core.\\footnote{\n In this case, destructive could mean set to zero (which could\n leak the hamming weight of the mask) or randomising its value.}\nWe require the secret values be stored in shared form in memory\n(rather than splitting them into shares upon being loaded)\nto extend the SCA protection boundary outside the CPU.\nOtherwise, the hamming weight of unmasked secret values would be\nleaked by memory-hierarchy registers outside the CPU.\nExecuting an {\\tt lm} instruction such that {\\tt rd} does not map to\na mask register raises an illegal opcode exception.\nLikewise for {\\tt sm} and {\\tt rs2}.\n\nWhen an ISE instruction is executed and its $\\GPR$ source\nregisters map to an MRF register, both the $\\GPR$s and MRF are\nread simultaneously and fed to the AES functional unit.\nIf any $\\GPR$ source does not map to an MRF register, we assume that\noperand is unmasked and represent the other share as $0$.\n\nWithin the AES-FU the instruction result is computed entirely in a\nmasked representation.\nThe result shares are then re-masked before being written back to the\n$\\GPR$s and MRF.\nThis is necessary, because \\ISE{3} instructions are designed\nsuch that {\\tt rs1=rd} for all use cases.\nWithout re-masking, overwriting a source with the result could cause \n$1$'st order hamming-distance leakage.\n\nIf the destination $\\GPR$ has a corresponding\nmask register, share $0$ is stored in the $\\GPR$s and share $1$ in the MRF.\nIf the destination $\\GPR$ does not map to a mask register, the result is\nwritten to the GPR unmasked.\nThis means that in the final encrypt/decrypt round, we can optionally obtain\nthe unmasked results without having to store the shares to memory,\nload them back and unmask them.\n\n\\subsection{Implementation}\n\nWe used the \\CORE{2} core as the basis for our side-channel secure\nimplementation of \\ISE{3}.\n\\REFFIG{fig:core:2:secure} shows a block diagram of the modifications\nmade to the core, and which data-paths carry masked data.\nTo avoid accidental unmasking of the two shares,\nShare $1$ is stored in {\\em bit-reversed} form in the MRF and pipeline\nregisters.\nThis means that any accidental multiplexing between pipeline operand\nregisters causes toggles between non-corresponding bits of each share.\nShare $1$ is only un-reversed immediately prior to entering the\nAES functional unit, and is re-reversed before exiting it.\nBit-reversal has zero logic gate cost and some minor routing complexity.\n\nWhile the architectural state stores a $2$-share representation\nof the secret material, we use a $3$-share implementation of the\nAES S-box.\nThis was driven by experiments showing \nleakage from a $2$-share design in our FPGA platform.\nThe additional share is generated by a simple $32$-bit LFSR and added\ndynamically by the hardware, and is never visible to the programmer.\nThis is suitable for a proof of concept (evident in the experimental\nresults) but would need to be used in conjunction with a true random\nnumber source (e.g., a set of ring-oscillators) in a deployed system.\nOnly the S-box is implemented using $3$-shares.\nSubsequent \\AESFUNC{MixColumns} logic is only implemented using $2$ shares.\n\n\\subsection{Evaluation}\n\nThe modified \\CORE{2} core was implemented on a\nSasebo GIII \\cite{HKSS:12}\nside-channel analysis platform, containing two Xilinx FPGAs:\na Kintex-7 \n(model {\\tt xc7k160tfbg676})\ntarget\nand\na supporting Spartan-6\n(model {\\tt xc6slx45}).\nOnly the Kintex-7 was used.\nThe design was synthesised using Xilinx Vivado 2019.2 with\ndefault synthesis and implementation strategies.\nThe Kintex-7 FPGA uses a 200MHz differential external clock source, which is\ntransformed into a 50MHz internal clock used by the entire design.\n\nTrace capture uses a standard pipeline of components:\na MiniCircuits BLK+89 D/C blocker,\nan Agilent 8447D amplifier (with a $\\SI{100}{\\kilo\\hertz}$ to $\\SI{1.3}{\\giga\\hertz}$ range, and $\\SI{25}{\\decibel}$ gain),\nand\na PicoScope 5000 series oscilloscope using a\n250 MHz sample rate, with a 12-bit resolution.\n\nWe performed a generic randomised plaintext\nTest Vector Leakage Assessment (TVLA) \\cite{TVLA:13}\nflow to evaluate the effectiveness of the side-channel hardened implementation,\nusing the AES-128 block encrypt function as the target operation.\nThe unprotected and protected implementation results are shown in\n\\REFFIG{fig:sca:unprotected} and\n\\REFFIG{fig:sca:protected} respectively.\nThe protected implementation is effective at removing $1$st\norder side-channel leakage up to $100$K traces.\nThe peaks at the beginning and end of \\REFFIG{fig:sca:protected}\nare caused by the unmasked block input and output data being loaded/stored.\n\n\\REFTAB{tab:sca:sw-hw} shows the hardware and software overheads.\nThe ISE Size/Circuit Depth rows are inclusive of the S-box Size/Circuit\nDepth rows.\nLikewise, the CPU Size rows are inclusive of the ISE Size rows.\nThe static code size and instruction count overheads are\n$\\approx 20\\%$: considerably less than a non-ISE-based software masking\napproach.\nThe hardware overheads are dominated by the increased size of the\nS-box (owing to the 3-share design), and the MRF.\nAlthough the overhead to the dedicated\nISE logic is $~4x$, this drops to $~1.2x$ when the entire\nCPU sub-system is considered.\nMeasured against an entire SoC, the overheads are modest.\n\n\\begin{table}[]\n\\centering\n\\begin{tabular}{|l|r|r|r|}\n\\hline\nMetric & Unprotected & Protected & Overhead \\\\\n\\hline\n\\hline\nStatic Code Size (Bytes) & 290 & 358 & $1.23\\times$ \\\\\nInstructions Executed & 238 & 287 & $1.21\\times$ \\\\\nCPU Clock Cycles & 291 & 331 & $1.14\\times$ \\\\\n\\hline\nS-box Size (NAND2 Equivalent) & 554 & 3245 & $5.86\\times$ \\\\\nS-box Circuit Depth & 19 & 22 & $1.16\\times$ \\\\\nISE Size (NAND2 Equivalent) & 1157 & 4616 & $3.99\\times$ \\\\\nISE Circuit Depth & 30 & 37 & $1.23\\times$ \\\\\nCPU Size (NAND2 Equivalent) & 38610 & 45141 & $1.16\\times$ \\\\\nCPU Size LUTs & 4017 & 4956 & $1.23\\times$ \\\\\nCPU Size FFs & 2078 & 2420 & $1.16\\times$ \\\\\nFPGA Timing Slack @50MHz & 8.12ns & 7.05ns & $0.87\\times$ \\\\\n\\hline\n\\end{tabular}\n\\caption{\nSoftware and hardware overheads for the protected ISE implementation\nof AES-128 block encryption.\nThe ``ISE Size'' row does not include the cost of the mask register file\nfor the protected implementation;\nthis is included in the CPU size measurements, since the exact method\nof mask delivery and storage is an implementation option.\n}\n\\label{tab:sca:sw-hw}\n\\end{table}\n\n\\begin{figure}\n\\centering\n\\begin{subfigure}[t]{0.95\\textwidth}\n\\centering\n\\includegraphics[width=\\textwidth]{graphs/aes-vanilla-enc-default-ttest.png}\n\\caption{\n Un-protected implementation TVLA results after $10$K traces.\n}\n\\label{fig:sca:unprotected}\n\\end{subfigure}\n\\begin{subfigure}[t]{0.95\\textwidth}\n\\centering\n\\includegraphics[width=\\textwidth]{graphs/aes-secure-enc-default-ttest.png}\n\\caption{\n Side-channel protected implementation TVLA results after $100$K traces.\n}\n\\label{fig:sca:protected}\n\\end{subfigure}\n\\caption{\nTVLA results for the baseline and protected implementations.\nThe blue trace is the absolute result of the TVLA evaluation, the green\ntrace is the average power consumption for each TVLA trace set.\n}\n\\end{figure}\n", "meta": {"hexsha": "b9aff678ed56c82df0b5ee48b45e185d4b748c97", "size": 10245, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/tex/body-sca.tex", "max_stars_repo_name": "mfkiwl/aes-risc-pipeline", "max_stars_repo_head_hexsha": "9ebf788db1465cd5959fb23fbbcefdd60a5e0a34", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-11-12T15:41:59.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-12T15:41:59.000Z", "max_issues_repo_path": "doc/tex/body-sca.tex", "max_issues_repo_name": "mfkiwl/aes-risc-pipeline", "max_issues_repo_head_hexsha": "9ebf788db1465cd5959fb23fbbcefdd60a5e0a34", "max_issues_repo_licenses": ["MIT"], "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/body-sca.tex", "max_forks_repo_name": "mfkiwl/aes-risc-pipeline", "max_forks_repo_head_hexsha": "9ebf788db1465cd5959fb23fbbcefdd60a5e0a34", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-08-26T17:16:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-05T05:07:42.000Z", "avg_line_length": 43.9699570815, "max_line_length": 123, "alphanum_fraction": 0.756954612, "num_tokens": 2646, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3665897363221599, "lm_q1q2_score": 0.19188052770221997}}
{"text": "\\section{Correctness} \\label{correctness}\n\nIt is useful to think about correctness in the following manner. Each round in the chain represents a slot in a sequence of consensus decisions.\nOnce a decision is committed, it takes effect immediately in the next slot. For normal transactions, this means that the state of the ledger is\nupdated by each slot, starting with the state of the previous slot. For control actions like reconfiguration, it changes the algorithm itself.\nThis again, takes effect in the immediate slot following the control transaction.\nGenerally, note that reconfiguration transactions can change any aspect of the algorithm, not just the validator set.\n\nNow, imagine that an entire consensus algorithm is done separately for each round/slot. Clearly, to agree on the commit output of the algorithm\nwe must have agreement on the algorithm itself. Initially, the system is bootstrapped with an algorithm (and in particular, the\nvalidator-configuration) responsible for slot 1 pre-determined and known to all via genesis transaction. Thereafter, if a slot commits an algorithm (configuration) change,\nit takes effect in the succeeding slot.\n\nIt is fairly obvious to see inductively that in this manner, we maintain agreement on the algorithm for each slot.\n\n\\paragraph{Enters pipelining}\n\nAs depicted above under “Pipelined reconfiguration”, the DijetsBFT consensus algorithm “spreads” the phases of the protocol (for every slot) over\n3 rounds. More specifically, every phase is carried in a single round and contains a new proposal. For example, the leader of round k drives only\na single phase of certification of its proposal. In the next round, k+1, a leader again drives a single phase of certification. Interestingly,\nthis phase has multiple purposes:\n\\begin{itemize}\n\\item The k+1 leader sends its own k+1 proposal.\n\\item It also piggybacks the QC for the k proposal. In this way, certifying at round k+1 generates a QC for k+1, but also a QC-of-QC for k.\n\\item In the third round, k+2, the k proposal can become committed, the k+1 proposal can obtain a QC-of-QC, and the k+2 can obtain a QC.\n\\end{itemize}\n\nImportantly, it should be understood that spreading phases of the k-protocol into rounds k+1 and k+2 does not shift the responsibility away from the k-algorithm.\n\nTo complicate matters, if any phase aborts due to a timeout, the k-protocol remains undecided. It can become committed only via a transaction that extends the k branch. If the k command is a reconfiguration command, the reconfiguration takes effect only upon the next commit.\n\nFor example, say that round k+1 aborts (no QC(k+1) obtained). The leader for k+2 extends k, and if three consecutive rounds (k+2, k+3, k+4) complete, then the prefix of the branch up to and include k+2 becomes committed, including k. Importantly, in this case, the reconfiguration transaction takes effect at round k+2.\n\nA correctness “meta argument” reduction is the follows:\n\nIf the algorithm for a slot k is A, then it is necessary and sufficient for the quorums used for three slots succeeding the first commit on a branch extending A to contain quorums of A. If there is no gap, then rounds k, k+1 and k+2 use algorithm A. If there is a gap and k’ is the next commit, then rounds from k all the way to k’, k’+1, k’+2 use algorithm A.\n\nIf round k* (once committed) changes the configuration to A’, then similarly, it is necessary and sufficient for slots succeeding k* to contain quorums for A’ but also A until k* becomes committed.\n\n\\paragraph{Reconfiguration condition with pipelining}\nConsider a round-k proposal such that:\n\\begin{itemize}\n\\item the last committed reconfiguration transaction on the branch which the k proposal extends is A (hence, A is “in effect”)\n\\item the k proposal changes (once committed) the algorithm from A to A’\n\\item k becomes committed by a round k* transaction which extends the k-branch\n\\end{itemize}\nThen the following is necessary and sufficient for reconfiguration to not fork:\n\\begin{itemize}\n\\item A’ should take effect at round k+1\n\\item rounds k+1 thru k*+2 must use QC’s that contains quorums of both A and A’.\n\\end{itemize}\n\nThis “meta argument” suffices to show that the above proposals all work. The proposals differ in other properties they provide, such as ease of implementation, building state-transfer transition into reconfiguration, etc.\n", "meta": {"hexsha": "536fef30b8f538b9e76bb0a97de8cb7fdd647710", "size": 4370, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "documentation/tech-papers/lbft-reconfig/correctness.tex", "max_stars_repo_name": "lasthyphen/dijets", "max_stars_repo_head_hexsha": "35fc1295628bd3316f2923e677e062770949698b", "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": "documentation/tech-papers/lbft-reconfig/correctness.tex", "max_issues_repo_name": "lasthyphen/dijets", "max_issues_repo_head_hexsha": "35fc1295628bd3316f2923e677e062770949698b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 123, "max_issues_repo_issues_event_min_datetime": "2021-08-31T19:16:05.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T19:35:09.000Z", "max_forks_repo_path": "documentation/tech-papers/lbft-reconfig/correctness.tex", "max_forks_repo_name": "lasthyphen/dijets", "max_forks_repo_head_hexsha": "35fc1295628bd3316f2923e677e062770949698b", "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": 80.9259259259, "max_line_length": 360, "alphanum_fraction": 0.7890160183, "num_tokens": 1011, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832058771035, "lm_q2_score": 0.35577489351363034, "lm_q1q2_score": 0.1917566926765616}}
{"text": "\\subsection{Enumeration field values}\n\\label{subsec:library_of_transformations:instance_level_transformations:enum_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/07_enum_field_values/enum_field_value.pdf}\n \\caption{$Im_{EnumField}$ with one object and its field referencing enumeration option $OPTION\\!\\_B$}\n \\label{fig:library_of_transformations:instance_level_transformations:enum_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/07_enum_field_values/enum_as_node_types_field_as_edge_type_value.tikz}\n \\caption{$IG_{EnumFieldNodes}$ with one node and and its edge referencing enumeration option $OPTION\\!\\_B$}\n \\label{fig:library_of_transformations:instance_level_transformations:enum_field_values:visualisation:groove_nodes}\n \\end{subfigure}\n \\\\\n \\begin{subfigure}{0.95\\textwidth}\n \\centering\n \\input{images/05_library_of_transformations/03_instance_level_transformations/07_enum_field_values/enum_as_flags_field_as_edge_type_value.tikz}\n \\caption{$IG_{EnumFieldFlags}$ with one node and its edge referencing enumeration option $OPTION\\!\\_B$}\n \\label{fig:library_of_transformations:instance_level_transformations:enum_field_values:visualisation:groove_flags}\n \\end{subfigure}\n \\caption{Visualisation of the transformation of field values from fields typed by enumeration types}\n \\label{fig:library_of_transformations:instance_level_transformations:enum_field_values:visualisation}\n\\end{figure}\n\nIn this section, the instance level transformation belonging to the transformation of an enumeration field is discussed. The type level transformation for enumeration fields can be found in \\cref{subsec:library_of_transformations:type_level_transformations:enum_fields}. On the instance level, values for the enumeration fields are introduced.\n\n\\begin{defin}[Instance model $Im_{EnumField}$]\n\\label{defin:library_of_transformations:instance_level_transformations:enum_field_values:imod_enum_field}\nLet $Im_{EnumField}$ be an instance model typed by $Tm_{EnumField}$ (\\cref{defin:library_of_transformations:type_level_transformations:enum_fields:tmod_enum_field}). Define a set $objects$, which represent the objects that will get a value for the field introduced by $Tm_{EnumField}$. 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_{EnumField}$. $Im_{EnumField}$ is defined as:\n\\begin{align*}\nObject =\\ &objects \\\\\n\\mathrm{ObjectClass} =\\ & \\begin{cases}\n (ob, classtype) & \\mathrm{if }\\ ob \\in objects\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{enum}, (enumid, values(ob))\\big]\\Big) & \\mathrm{if }\\ ob \\in objects\n\\end{cases} \\\\\n\\mathrm{DefaultValue} =\\ & \\{\\}\n\\end{align*}\n\\isabellelref{imod_enum_field}{Ecore-GROOVE-Mapping-Library.EnumFieldValue}\n\\end{defin}\n\n\\begin{thm}[Correctness of $Im_{EnumField}$]\n\\label{defin:library_of_transformations:instance_level_transformations:enum_field_values:imod_enum_field_correct}\n$Im_{EnumField}$ (\\cref{defin:library_of_transformations:instance_level_transformations:enum_field_values:imod_enum_field}) is a valid instance model in the sense of \\cref{defin:formalisations:ecore_formalisation:instance_models:model_validity}.\n\\isabellelref{imod_enum_field_correct}{Ecore-GROOVE-Mapping-Library.EnumFieldValue}\n\\end{thm}\n\nA visual representation of $Im_{EnumField}$ with $objects = \\{ob\\}$ and $obids(ob) = someId$ can be seen in \\cref{fig:library_of_transformations:instance_level_transformations:enum_field_values:visualisation:ecore}. In this visualisation, the field value for $ob$ is defined as $values(ob) = OPTION\\!\\_B$. Although this visualisation only shows one object, it is required to define a value for all objects that contain 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_{EnumField}$ only is 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_{EnumField}$ should be compatible with the instance model it is combined with.\n\n\\begin{thm}[Correctness of $\\mathrm{combine}(Im, Im_{EnumField})$]\n\\label{defin:library_of_transformations:instance_level_transformations:enum_field_values:imod_enum_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_{EnumField}$ (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:enum_fields:tmod_enum_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_{EnumField}$ may not be extended by another class type in the type model corresponding to $Im$;\n \\item All of the objects in the set $objects$ must already be objects in $Im$;\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_{EnumField}$;\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 For all objects in set $objects$, the value set by the $values$ function must be valid.\n\\end{itemize}\n\\isabellelref{imod_enum_field_combine_correct}{Ecore-GROOVE-Mapping-Library.EnumFieldValue}\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_{EnumField})$ is consistent in the sense of \\cref{defin:formalisations:ecore_formalisation:instance_models:model_validity}.\n\\end{proof}\n\nAs explained earlier, $Im_{EnumField}$ needs to introduce values for all objects that are typed by the class type on which the field is defined. This is enforced by the requirements of \\cref{defin:library_of_transformations:instance_level_transformations:enum_field_values:imod_enum_field_combine_correct}. 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 with a node type encoded enumeration type}\n\nAs discussed in \\cref{subsec:library_of_transformations:type_level_transformations:enum_fields}, there are two different encodings for a field typed by an enumeration type. These correspond to the two different encodings of the enumeration type itself. On the instance level, these encodings also need to be distinguished. The first encoding of the values assumes that the enumeration is encoded using node types. The encoding corresponding to $Im_{EnumField}$ is then represented as $IG_{EnumFieldNodes}$, defined in the following definition:\n\n\\begin{defin}[Instance graph $IG_{EnumFieldNodes}$]\n\\label{defin:library_of_transformations:instance_level_transformations:enum_field_values:ig_enum_as_node_types_field_as_edge_type}\nLet $IG_{EnumFieldNodes}$ be the instance graph typed by type graph $TG_{EnumFieldNodes}$ (\\cref{defin:library_of_transformations:type_level_transformations:enum_fields:tg_enum_as_node_types_field_as_edge_type}). Reuse the set $objects$ from $Im_{EnumField}$. Moreover, reuse the functions $obids$ and $values$ from $Im_{EnumField}$. Furthermore, define $enumob$ to be the function that maps an enumeration value to an internal node identity. Similarly, define $enumids$ as the function that maps an enumeration value to its explicit node id.\n\nWithin $IG_{EnumFieldNodes}$, the objects in the set $objects$ are converted to nodes in $Im_{EnumField}$. For each of these objects, an edge of the encoded field is created. This edge targets a node that corresponds to the value set by $values$ for the corresponding object. Furthermore, the identity of the objects is defined using $obids$. Finally, ensure that the instances of the enumeration values exist and encode them in the same way as $IG_{EnumNodes}$ (\\cref{defin:library_of_transformations:instance_level_transformations:enumeration_values:ig_enum_as_node_types}). $IG_{EnumFieldNodes}$ is defined as:\n\\begin{align*}\nN =\\ & objects \\cup \\{enumob(v) \\mid v \\in enumvalues \\} \\\\\nE =\\ & \\big\\{\\big(ob, (\\mathrm{ns\\_\\!to\\_\\!list}(classtype), \\langle name \\rangle, \\mathrm{ns\\_\\!to\\_\\!list}(enumid)), enumob(values(ob))\\big) \\mid ob \\in objects \\big\\} \\\\\n\\mathrm{ident} =\\ & \\begin{cases}\n (obids(ob), ob) & \\mathrm{if }\\ ob \\in objects\\\\\n (enumids(v), enumob(v)) & \\mathrm{if }\\ v \\in enumvalues\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 (enumob(v), \\mathrm{ns\\_\\!to\\_\\!list}(enumid) \\append \\langle v \\rangle) & \\mathrm{if }\\ v \\in enumvalues\n\\end{cases}\n\\end{align*}\n\\isabellelref{ig_enum_as_node_types_field_as_edge_type}{Ecore-GROOVE-Mapping-Library.EnumFieldValue}\n\\end{defin}\n\n\\begin{thm}[Correctness of $IG_{EnumFieldNodes}$]\n\\label{defin:library_of_transformations:instance_level_transformations:enum_field_values:ig_enum_as_node_types_field_as_edge_type_correct}\n$IG_{EnumFieldNodes}$ (\\cref{defin:library_of_transformations:instance_level_transformations:enum_field_values:ig_enum_as_node_types_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_enum_as_node_types_field_as_edge_type_correct}{Ecore-GROOVE-Mapping-Library.EnumFieldValue}\n\\end{thm}\n\nA visual representation of $IG_{EnumFieldNodes}$ with $objects = \\{ob\\}$ and $obids(ob) = someId$ can be seen in \\cref{fig:library_of_transformations:instance_level_transformations:enum_field_values:visualisation:groove_nodes}. Like the previous visualisation, the field value for $ob$ is defined as $values(ob) = OPTION\\!\\_B$. Although this visualisation only shows one node, it is required to define a value for all nodes that are typed by the node type corresponding to the field. 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_{EnumFieldNodes}$ only is 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_{EnumFieldNodes}$ should be compatible with the instance graph it is combined with.\n\n\\begin{thm}[Correctness of $\\mathrm{combine}(IG, IG_{EnumFieldNodes})$]\n\\label{defin:library_of_transformations:instance_level_transformations:enum_field_values:ig_enum_as_node_types_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_{EnumFieldNodes}$ (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:enum_fields:tg_enum_as_node_types_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 All nodes in $IG$ that are typed by the node type on which the field is defined are also nodes in $IG_{EnumFieldNodes}$;\n \\item All nodes in $IG_{EnumFieldNodes}$ that encode the values of the corresponding enumeration type are also nodes in $IG$;\n \\item For all nodes shared between $IG$ and $IG_{EnumFieldNodes}$, each node must have the same identifier in both $IG$ and $IG_{EnumFieldNodes}$;\n \\item For all nodes for which the field is set, the $values$ function must define a valid value.\n\\end{itemize}\n\\isabellelref{ig_enum_as_node_types_field_as_edge_type_combine_correct}{Ecore-GROOVE-Mapping-Library.EnumFieldValue}\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_{EnumFieldNodes})$ is valid in the sense of \\cref{defin:formalisations:groove_formalisation:instance_graphs:instance_graph_validity}.\n\\end{proof}\n\nLike the definition for the combination of instance models, the combination of instance graphs also requires the user to set a value for all nodes that are typed by the node type that corresponds to the field type. This is to keep the graph valid.\n\nThe next definitions define the transformation function from $Im_{EnumField}$ to $IG_{EnumFieldNodes}$:\n\n\\begin{defin}[Transformation function $f_{EnumFieldNodes}$]\n\\label{defin:library_of_transformations:instance_level_transformations:enum_field_values:imod_enum_field_to_ig_enum_as_node_types_field_as_edge_type}\nThe transformation function $f_{EnumFieldNodes}(Im)$ is defined as:\n\\begin{align*}\nN =\\ & Object_{Im} \\cup \\{enumob(ob) \\mid v \\in enumvalues\\} \\\\\nE =\\ & \\big\\{\\big(ob, (\\mathrm{ns\\_\\!to\\_\\!list}(classtype), \\langle name \\rangle, \\mathrm{ns\\_\\!to\\_\\!list}(enumid)), enumob(values(ob))\\big) \\mid \\\\&ob \\in Object_{Im} \\big\\} \\\\\n\\mathrm{ident} =\\ & \\begin{cases}\n (obids(ob), ob) & \\mathrm{if }\\ ob \\in Object_{Im}\\\\\n (enumids(v), enumob(v)) & \\mathrm{if }\\ v \\in enumvalues\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}\\\\\n (enumob(v), \\mathrm{ns\\_\\!to\\_\\!list}(enumid) \\append \\langle v \\rangle) & \\mathrm{if }\\ v \\in enumvalues\n\\end{cases}\n\\end{align*}\n\\isabellelref{imod_enum_field_to_ig_enum_as_node_types_field_as_edge_type}{Ecore-GROOVE-Mapping-Library.EnumFieldValue}\n\\end{defin}\n\n\\begin{thm}[Correctness of $f_{EnumFieldNodes}$]\n\\label{defin:library_of_transformations:instance_level_transformations:enum_field_values:imod_enum_field_to_ig_enum_as_node_types_field_as_edge_type_func}\n$f_{EnumFieldNodes}(Im)$ (\\cref{defin:library_of_transformations:instance_level_transformations:enum_field_values:imod_enum_field_to_ig_enum_as_node_types_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_{EnumField}$ into $IG_{EnumFieldNodes}$.\n\\isabellelref{imod_enum_field_to_ig_enum_as_node_types_field_as_edge_type_func}{Ecore-GROOVE-Mapping-Library.EnumFieldValue}\n\\end{thm}\n\nThe proof of the correctness of $f_{EnumFieldNodes}$ 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_{EnumFieldNodes}$ into $Im_{EnumField}$ is defined:\n\n\\begin{defin}[Transformation function $f'_{EnumFieldNodes}$]\n\\label{defin:library_of_transformations:instance_level_transformations:enum_field_values:ig_enum_as_node_types_field_as_edge_type_to_imod_enum_field}\nThe transformation function $f'_{EnumFieldNodes}(IG)$ is defined as:\n\\begin{align*}\nObject =\\ &\\{\\mathrm{src}(e) \\mid e \\in E_{IG}\\} \\\\\n\\mathrm{ObjectClass} =\\ & \\begin{cases}\n (ob, name) & \\mathrm{if }\\ ob \\in \\{\\mathrm{src}(e) \\mid e \\in E_{IG}\\}\n\\end{cases}\\\\\n\\mathrm{ObjectId} =\\ & \\begin{cases}\n (ob, obids(ob)) & \\mathrm{if }\\ ob \\in \\{\\mathrm{src}(e) \\mid e \\in E_{IG}\\}\n\\end{cases}\\\\\n\\mathrm{FieldValue} =\\ & \\begin{cases}\n \\Big((ob, (classtype, name)), \\big(\\type{enum}, (enumid, values(ob))\\big)\\Big) & \\mathrm{if }\\ ob \\in \\{\\mathrm{src}(e) \\mid e \\in E_{IG}\\}\n\\end{cases} \\\\\n\\mathrm{DefaultValue} =\\ & \\{\\}\n\\end{align*}\n\\isabellelref{ig_enum_as_node_types_field_as_edge_type_to_imod_enum_field}{Ecore-GROOVE-Mapping-Library.EnumFieldValue}\n\\end{defin}\n\n\\begin{thm}[Correctness of $f'_{EnumFieldNodes}$]\n\\label{defin:library_of_transformations:instance_level_transformations:enum_field_values:ig_enum_as_node_types_field_as_edge_type_to_tmod_class_func}\n$f'_{EnumFieldNodes}(IG)$ (\\cref{defin:library_of_transformations:instance_level_transformations:enum_field_values:ig_enum_as_node_types_field_as_edge_type_to_imod_enum_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_{EnumFieldNodes}$ into $Im_{EnumField}$.\n\\isabellelref{ig_enum_as_node_types_field_as_edge_type_to_imod_enum_field_func}{Ecore-GROOVE-Mapping-Library.EnumFieldValue}\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 edges and nodes with a flag encoded enumeration type}\n\nThe second possible encoding of the values assumes that the enumeration is encoded using flags. The encoding corresponding to $Im_{EnumField}$ is then represented as $IG_{EnumFieldFlags}$, defined in the following definition:\n\n\\begin{defin}[Instance graph $IG_{EnumFieldFlags}$]\n\\label{defin:library_of_transformations:instance_level_transformations:enum_field_values:ig_enum_as_flags_field_as_edge_type}\nLet $IG_{EnumFieldFlags}$ be the instance graph typed by type graph $TG_{EnumFieldFlags}$ (\\cref{defin:library_of_transformations:type_level_transformations:enum_fields:tg_enum_as_flags_field_as_edge_type}). Reuse the set $objects$ from $Im_{EnumField}$. Moreover, reuse the functions $obids$ and $values$ from $Im_{EnumField}$. Furthermore, define $enumob$ to be the function that maps an enumeration value to an internal node identity. Similarly, define $enumids$ as the function that maps an enumeration value to its explicit node id.\n\nWithin $IG_{EnumFieldFlags}$, the objects in the set $objects$ are converted to nodes in $Im_{EnumField}$. For each of these objects, an edge of the encoded field is created. This edge targets a node that corresponds to the value set by $values$ for the corresponding object. Furthermore, the identity of the objects is defined using $obids$. Finally, ensure that the instances of the enumeration values exist and encode them in the same way as $IG_{EnumFlags}$ (\\cref{defin:library_of_transformations:instance_level_transformations:enumeration_values:ig_enum_as_flags}). $IG_{EnumFieldFlags}$ is defined as:\n\\begin{align*}\nN =\\ & objects \\cup \\{enumob(v) \\mid v \\in enumvalues \\} \\\\\nE =\\ & \\big\\{\\big(ob, (\\mathrm{ns\\_\\!to\\_\\!list}(classtype), \\langle name \\rangle, \\mathrm{ns\\_\\!to\\_\\!list}(enumid)), enumob(values(ob))\\big) \\mid ob \\in objects \\big\\} \\\\\n\\mathrm{ident} =\\ & \\begin{cases}\n (obids(ob), ob) & \\mathrm{if }\\ ob \\in objects\\\\\n (enumids(v), enumob(v)) & \\mathrm{if }\\ v \\in enumvalues\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 (enumob(v), \\mathrm{ns\\_\\!to\\_\\!list}(enumid)) & \\mathrm{if }\\ v \\in enumvalues\n\\end{cases}\n\\end{align*}\n\\isabellelref{ig_enum_as_flags_field_as_edge_type}{Ecore-GROOVE-Mapping-Library.EnumFieldValue}\n\\end{defin}\n\n\\begin{thm}[Correctness of $IG_{EnumFieldFlags}$]\n\\label{defin:library_of_transformations:instance_level_transformations:enum_field_values:ig_enum_as_flags_field_as_edge_type_correct}\n$IG_{EnumFieldFlags}$ (\\cref{defin:library_of_transformations:instance_level_transformations:enum_field_values:ig_enum_as_flags_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_enum_as_flags_field_as_edge_type_correct}{Ecore-GROOVE-Mapping-Library.EnumFieldValue}\n\\end{thm}\n\nA visual representation of $IG_{EnumFieldFlags}$ with $objects = \\{ob\\}$ and $obids(ob) = someId$ can be seen in \\cref{fig:library_of_transformations:instance_level_transformations:enum_field_values:visualisation:groove_flags}. It does not differ much from the previous encoding, except that the values of the enumeration type are shown as flags on the nodes instead of using seperate types. The formal definition is therefore very similar, except for the definition of $\\mathrm{type}_n$. Although this visualisation only shows one node, it is required to define a value for all nodes that are typed by the node type corresponding to the field. Failing to do so would, once more, result in an invalid instance graph after it is combined with another graph. The correctness proof of $IG_{EnumFieldFlags}$ only is 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_{EnumFieldFlags}$ should be compatible with the instance graph it is combined with.\n\n\\begin{thm}[Correctness of $\\mathrm{combine}(IG, IG_{EnumFieldFlags})$]\n\\label{defin:library_of_transformations:instance_level_transformations:enum_field_values:ig_enum_as_flags_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_{EnumFieldFlags}$ (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:enum_fields:tg_enum_as_flags_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 All nodes in $IG$ that are typed by the node type on which the field is defined are also nodes in $IG_{EnumFieldFlags}$;\n \\item All nodes in $IG_{EnumFieldFlags}$ that encode the values of the corresponding enumeration type are also nodes in $IG$;\n \\item For all nodes shared between $IG$ and $IG_{EnumFieldFlags}$, each node must have the same identifier in both $IG$ and $IG_{EnumFieldFlags}$;\n \\item For all nodes for which the field is set, the $values$ function must define a valid value.\n\\end{itemize}\n\\isabellelref{ig_enum_as_flags_field_as_edge_type_combine_correct}{Ecore-GROOVE-Mapping-Library.EnumFieldValue}\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_{EnumFieldFlags})$ 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_{EnumField}$ to $IG_{EnumFieldFlags}$:\n\n\\begin{defin}[Transformation function $f_{EnumFieldFlags}$]\n\\label{defin:library_of_transformations:instance_level_transformations:enum_field_values:imod_enum_field_to_ig_enum_as_flags_field_as_edge_type}\nThe transformation function $f_{EnumFieldFlags}(Im)$ is defined as:\n\\begin{align*}\nN =\\ & Object_{Im} \\cup \\{enumob(ob) \\mid v \\in enumvalues\\} \\\\\nE =\\ & \\big\\{\\big(ob, (\\mathrm{ns\\_\\!to\\_\\!list}(classtype), \\langle name \\rangle, \\mathrm{ns\\_\\!to\\_\\!list}(enumid)), enumob(values(ob))\\big) \\mid \\\\&ob \\in Object_{Im} \\big\\} \\\\\n\\mathrm{ident} =\\ & \\begin{cases}\n (obids(ob), ob) & \\mathrm{if }\\ ob \\in Object_{Im}\\\\\n (enumids(v), enumob(v)) & \\mathrm{if }\\ v \\in enumvalues\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}\\\\\n (enumob(v), \\mathrm{ns\\_\\!to\\_\\!list}(enumid)) & \\mathrm{if }\\ v \\in enumvalues\n\\end{cases}\n\\end{align*}\n\\isabellelref{imod_enum_field_to_ig_enum_as_flags_field_as_edge_type}{Ecore-GROOVE-Mapping-Library.EnumFieldValue}\n\\end{defin}\n\n\\begin{thm}[Correctness of $f_{EnumFieldFlags}$]\n\\label{defin:library_of_transformations:instance_level_transformations:enum_field_values:imod_enum_field_to_ig_enum_as_flags_field_as_edge_type_func}\n$f_{EnumFieldFlags}(Im)$ (\\cref{defin:library_of_transformations:instance_level_transformations:enum_field_values:imod_enum_field_to_ig_enum_as_flags_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_{EnumField}$ into $IG_{EnumFieldFlags}$.\n\\isabellelref{imod_enum_field_to_ig_enum_as_flags_field_as_edge_type_func}{Ecore-GROOVE-Mapping-Library.EnumFieldValue}\n\\end{thm}\n\nThe proof of the correctness of $f_{EnumFieldFlags}$ 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_{EnumFieldFlags}$ into $Im_{EnumField}$ is defined:\n\n\\begin{defin}[Transformation function $f'_{EnumFieldFlags}$]\n\\label{defin:library_of_transformations:instance_level_transformations:enum_field_values:ig_enum_as_flags_field_as_edge_type_to_imod_enum_field}\nThe transformation function $f'_{EnumFieldFlags}(IG)$ is defined as:\n\\begin{align*}\nObject =\\ &\\{\\mathrm{src}(e) \\mid e \\in E_{IG}\\} \\\\\n\\mathrm{ObjectClass} =\\ & \\begin{cases}\n (ob, classtype) & \\mathrm{if }\\ ob \\in \\{\\mathrm{src}(e) \\mid e \\in E_{IG}\\}\n\\end{cases}\\\\\n\\mathrm{ObjectId} =\\ & \\begin{cases}\n (ob, obids(ob)) & \\mathrm{if }\\ ob \\in \\{\\mathrm{src}(e) \\mid e \\in E_{IG}\\}\n\\end{cases}\\\\\n\\mathrm{FieldValue} =\\ & \\begin{cases}\n \\Big((ob, (classtype, name)), \\big[\\type{enum}, (enumid, values(ob))\\big]\\Big) & \\mathrm{if }\\ ob \\in \\{\\mathrm{src}(e) \\mid e \\in E_{IG}\\}\n\\end{cases} \\\\\n\\mathrm{DefaultValue} =\\ & \\{\\}\n\\end{align*}\n\\isabellelref{ig_enum_as_flags_field_as_edge_type_to_imod_enum_field}{Ecore-GROOVE-Mapping-Library.EnumFieldValue}\n\\end{defin}\n\n\\begin{thm}[Correctness of $f'_{EnumFieldFlags}$]\n\\label{defin:library_of_transformations:instance_level_transformations:enum_field_values:ig_enum_as_flags_field_as_edge_type_to_tmod_class_func}\n$f'_{EnumFieldFlags}(IG)$ (\\cref{defin:library_of_transformations:instance_level_transformations:enum_field_values:ig_enum_as_flags_field_as_edge_type_to_imod_enum_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_{EnumFieldFlags}$ into $Im_{EnumField}$.\n\\isabellelref{ig_enum_as_flags_field_as_edge_type_to_imod_enum_field_func}{Ecore-GROOVE-Mapping-Library.EnumFieldValue}\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": "e764fa037e6cf093c8ef3500cd2433724dd5fbd3", "size": 28089, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "thesis/tex/05_library_of_transformations/03_instance_level_transformations/07_enum_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/07_enum_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/07_enum_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": 89.7412140575, "max_line_length": 927, "alphanum_fraction": 0.7950799245, "num_tokens": 7450, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3775406758018019, "lm_q1q2_score": 0.19171963442014375}}
{"text": "\\documentclass[main.tex]{subfiles}\r\n\\begin{document}\r\n\\chapter{Logic}\r\n\\label{chapter:logic}\r\n\r\n\\epigraph{All opinions are not equal. Some are a very great deal more robust, sophisticated and well supported in logic and argument than others.}{Douglas Adams}\r\n\r\n\\minitoc\r\n\r\n\\section{Introduction}\r\n\r\nLet's spell out two logic puzzles:\r\n\r\n\\begin{center}\r\n\t\\textit{Sam has 1 cow. If Sam has at least 2 cows, then Sam can breed the cows to make one more cow. Assuming Sam has access to infinite resources and time, how many cows can Sam make?}\r\n\\end{center}\r\n\r\n\\begin{center}\r\n\t\\textit{Two givens: knights always tell the truth, and knaves always lie. On the island of knights and knaves, you are approached by two people. The first one says to you, ``we are both knaves.\" What are they actually?} (from Popular Mechanic's Riddle of the Week \\#43: Knights and Knaves, Part 1 \\cite{pop-mech})\r\n\\end{center}\r\n\r\nThinking logically about these puzzles will help you -- think about what can and cannot happen; what can and cannot be true. Solving these problems is left as an exercise. There are only two possibilities for Boolean\\index{Boolean} statements -- True or False. Here's a formal definition of logic, from Merriam-Webster:\r\n\r\n\\begin{defn}[Logic\\index{Logic}]\r\n\tA science that deals with the principles and criteria of validity of inference and demonstration : the science of the formal principles of reasoning \\cite{logic}\r\n\\end{defn}\r\n\r\nThis chapter includes a wealth of topics. We will touch on propositional logic and its corollaries, as well as predicate logic and it's applications to the rest of this course. Thinking logically should be a natural process, so we hope this section is relatively straightforward.\r\n\r\n\\section{Propositional Logic}\r\n\r\nPropositional logic is a branch of logic that deals with simple propositions and logical connectives. Sometimes propositional logic is referred to as \\textbf{zeroth-order logic}, as it lays the foundations for \\textit{predicate logic}, also known as \\textit{first-order logic}.\r\n\r\n\\begin{defn}[Proposition]\r\n\t\\index{Proposition}\r\n\tA statement that is exclusively either true or false. A proposition must \\textit{have} a true or false value, and it cannot have \\textit{both}. Propositions are usually represented as variables. These variables can represent a single statement, or large compound statements. We will see examples later\r\n\\end{defn}\r\n\r\n\\begin{defn}[Logical Connective]\r\n\tAn operation that connects two propositions. We study these below\r\n\\end{defn}\r\n\r\nThe motivation behind propositional logic is that we want to represent basic logical statements as an expression of variables and operators.\r\nPropositional logic also lays the groundwork for higher-order logic.\r\n\r\nBefore we start, let us motivate propositional logic and Boolean algebra by recalling the fundamental ideas of mathematical concepts we are already familiar with.\r\nFor standard arithmetic, we utilize real numbers \\(\\R\\), binary (two inputs) operators \\(+\\),\\(-\\),\\(\\times\\),\\(\\div\\),\\(\\cdots\\), and unary (one input) operators \\(\\exp(\\cdot)\\), \\(\\log(\\cdot)\\), \\(\\sqrt{\\cdot}\\), \\(\\text{abs}(\\cdot)\\), \\((-1)(\\cdot)\\),\\(\\cdots\\).\r\nNote that our operators here take elements from our main set, and return an element back inside that set.\r\nFor example, \\(4.01 + 3.99\\) gives us 8.\r\nWe have a way to signal that those two quantities above are the same, namely the equals sign \\(=\\).\r\nFinally, we have a way to abstract out elements as \\textit{variables}, for example \\(x+y=z\\).\r\nAnd if we fill in some of the variables, we can solve for the other ones.\r\nFor example \\(x+3.99=8\\) implies \\(x=4.01\\).\r\nIn a similar way, this whole mathematical system can be completely abstracted, and we can reason about those abstract structures.\r\nThen, any specific example that holds the same inherent properties of our structures will also have any reasoned theorem apply.\r\nThis is quite an important idea in mathematics -- we can abstract concepts and reason about abstract structures that can apply to a variety of specific examples.\r\n\r\n\\begin{figure}[h]\r\n\t\\centering\r\n\t\\[(\\hspace{2mm} \\rule{0.5cm}{0.5pt} \\hspace{2mm} \\mathbin{\\square} \\hspace{2mm} \\rule{0.5cm}{0.5pt} \\hspace{2mm}) \\mapsto \\hspace{1mm} \\rule{0.5cm}{0.5pt}\\]\r\n\t\\caption{\r\n\t\tIn abstract mathematics, we care about \\textit{operators} that \\textit{map} elements from a set into another element in the same set.\r\n\t\tFor addition in the reals, this would look like \\((4.01+3.99) \\mapsto 8\\).\r\n\t}\r\n\\end{figure}\r\n\r\nWhy does this apply here?\r\nWell, for propositional logic, we are, essentially, going to \\textit{define} a new \\textit{structure}.\r\nOur new ``number set'' becomes \\(\\B = \\{\\mathbf{T},\\mathbf{F}\\}\\) (analogous to \\(\\R\\)).\r\nOur new ``unary operators'' become \\(\\lnot\\) (analogous to multiplying by \\(-1\\), etc).\r\nOur new ``binary operators'' become \\(\\land,\\lor,\\Rightarrow,\\cdots\\) (analogous to \\(+,-,\\times,\\div,\\cdots\\)).\r\nOur new ``equality'' becomes \\textit{logical equivalence} (\\(\\equiv\\) versus \\(=\\)).\r\nOur idea of \\textit{variables} stays the same.\r\nBut, interestingly, because our input set \\(\\B\\) is \\textit{finite} (which is different from the countably infinite \\(\\Z\\) and the uncountable \\(\\R\\)).\r\nThis gives us nice ways to actually \\textit{write out all possibilities} for inputs and outputs of our operators.\r\nWith this in mind, let us push onward to propositional logic.\r\n\r\n\\subsection{Truth Tables and Logical Connectives}\r\n\r\nBefore we dive into the logical connectives, let's study the notion of a truth table. This will help us fully understand the logical connectives.\r\n\r\n\\begin{defn}[Truth Table]\r\n\t\\index{Truth Table}\r\n\tA table that shows us all truth-value possibilities. For example, with two propositions \\(p\\) and \\(q\\):\r\n\t\r\n\t\\begin{center}\r\n\t\t\\begin{tabular}{c|c|c}\r\n\t\t\t\\(p\\) & \\(q\\) & \\textit{some compound proposition} \\\\\r\n\t\t\t\\hline\r\n\t\t\tF & F & T/F \\\\\r\n\t\t\tF & T & T/F \\\\\r\n\t\t\tT & F & T/F \\\\\r\n\t\t\tT & T & T/F\r\n\t\t\\end{tabular}\r\n\t\\end{center}\r\n\\end{defn}\r\n\r\nNow we can begin our study of the logical connectives. The following definitions explain the intuition behind the logical connectives, and present their associated truth tables.\r\n\r\n\\begin{defn}[And \\(\\land\\)]\r\n\tAlso known as the \\textit{conjunction}. Logical connective that evaluates to true when the propositions that it connects are both true. If either proposition is false, then \\textit{and} evaluates to false. To remember: \\textit{prop 1} \\textbf{and} \\textit{prop 2} must \\textit{both} be true. Truth table:\r\n\t\\begin{center}\r\n\t\t\\begin{tabular}{c|c|c}\r\n\t\t\t\\(p\\) & \\(q\\) & \\(p \\land q\\) \\\\\r\n\t\t\t\\hline\r\n\t\t\tF & F & F \\\\\r\n\t\t\tF & T & F \\\\\r\n\t\t\tT & F & F \\\\\r\n\t\t\tT & T & T\r\n\t\t\\end{tabular}\r\n\t\\end{center}\r\n\t\r\n\t\\textit{Notice the only row that evaluates to true is when both propositions are true}\r\n\\end{defn}\r\n\r\n\\begin{defn}[Or \\(\\lor\\)]\r\n\tAlso known as the \\textit{disjunction}. Logical connective that evaluates to true when either of the propositions that it connects are true (at least 1 of the connected propositions is true). If both propositions are false, then \\textit{or} evaluates to false. \\textbf{Note}: if both propositions are true, then \\textit{or} still evaluates to true. To remember: either \\textit{prop 1} \\textbf{or} \\textit{prop 2} must be true. Truth table:\r\n\t\\begin{center}\r\n\t\t\\begin{tabular}{c|c|c}\r\n\t\t\t\\(p\\) & \\(q\\) & \\(p \\lor q\\) \\\\\r\n\t\t\t\\hline\r\n\t\t\tF & F & F \\\\\r\n\t\t\tF & T & T \\\\\r\n\t\t\tT & F & T \\\\\r\n\t\t\tT & T & T\r\n\t\t\\end{tabular}\r\n\t\\end{center}\r\n\t\r\n\t\\textit{Notice the only row that evaluates to false is when both propositions are false}\r\n\\end{defn}\r\n\r\n\\begin{defn}[Not \\(\\lnot\\), \\(\\sim\\)]\r\n\tAlso known as the \\textit{negation}. Logical connective that flips the truth value of the proposition to which it is connected. Unlike \\textit{and} and \\textit{or}, \\textit{not} only affects 1 proposition. Truth table:\r\n\t\\begin{center}\r\n\t\t\\begin{tabular}{c|c}\r\n\t\t\t\\(p\\) & \\(\\lnot p\\) \\\\\r\n\t\t\t\\hline\r\n\t\t\tF & T \\\\\r\n\t\t\tT & F \\\\\r\n\t\t\\end{tabular}\r\n\t\\end{center}\r\n\\end{defn}\r\n\r\n\\begin{defn}[Implication/Conditional \\(\\Rightarrow\\), \\(\\rightarrow\\)]\r\n\tLogical connective that reads as an \\textit{if-then} statement. The implication must be false if the first proposition is true and the implied (connected/second) proposition is false. Otherwise it is true. Truth table:\r\n\t\\begin{center}\r\n\t\t\\begin{tabular}{c|c|c}\r\n\t\t\t\\(p\\) & \\(q\\) & \\(p \\Rightarrow q\\) \\\\\r\n\t\t\t\\hline\r\n\t\t\tF & F & T \\\\\r\n\t\t\tF & T & T \\\\\r\n\t\t\tT & F & F \\\\\r\n\t\t\tT & T & T\r\n\t\t\\end{tabular}\r\n\t\\end{center}\r\n\tNote: the direction of an implication can be flipped: \\(p \\Leftarrow q\\) is the same as \\(q \\Rightarrow p\\)\r\n\\end{defn}\r\n\r\nLet's try to understand the truth table for the implication statement before we continue. We present two examples that attempt to form an intuitive analogy to the implication.\r\n\r\n\\begin{example}\r\n\tThink of the implication as a vending machine. \\(p\\) is the statement \\textit{we put money into the vending machine}, and \\(q\\) is the statement \\textit{we received a snack from the vending machine}. Notice that the statements do not necessarily depend on each other. We examine the four cases and see when we are \\textit{unhappy}:\r\n\t\r\n\t\\begin{enumerate}\r\n\t\t\\item \\(p\\) is \\textbf{false} and \\(q\\) is \\textbf{false} -- we did not put in money, and we did not get a snack, so we remain happy (normal operations)\r\n\t\t\\item \\(p\\) is \\textbf{false} and \\(q\\) is \\textbf{true} -- we did not put in money, and we did get a snack, so we are very very happy (free snack!)\r\n\t\t\\item \\(p\\) is \\textbf{true} and \\(q\\) is \\textbf{false} -- we did put in money, and we did not get a snack, so we are very very unhappy (we got robbed!)\r\n\t\t\\item \\(p\\) is \\textbf{true} and \\(q\\) is \\textbf{true} -- we did put in money, and we did get a snack, so we are happy (normal operations)\r\n\t\\end{enumerate}\r\n\t\r\n\tWhen we are unhappy, then the implication statement is false. Otherwise it is true (we are not \\textit{unhappy}).\r\n\\end{example}\r\n\r\n\\begin{example}\r\n\tThink of the implication in the lens of a program. You want to evaluate whether your program \\textit{makes sense}. Here is the example program from the statement \\(p \\Rightarrow q\\):\r\n\t\r\n\t\\begin{lstlisting}\r\n\t(...)\r\n\tif (p is true) {\r\n\t\t\r\n\t}\r\n\t(...)\r\n\t\\end{lstlisting}\r\n\t\r\n\tThe body code is run only if \\(q\\) is true. Now let's examine the 4 cases and see whether the program makes sense:\r\n\t\\begin{enumerate}\r\n\t\t\\item \\(p\\) is \\textbf{false} and \\(q\\) is \\textbf{false} -- the program does not go into the body of the if-statement and hence makes sense\r\n\t\t\\item \\(p\\) is \\textbf{false} and \\(q\\) is \\textbf{true} -- the program again does not go into the body of the if-statement and hence makes sense (regardless of the value of \\(q\\))\r\n\t\t\\item \\(p\\) is \\textbf{true} and \\(q\\) is \\textbf{false} -- the program goes into the body of the if-statement but since \\(q\\) is false the program does not evaluate the body code. This does not make sense\r\n\t\t\\item \\(p\\) is \\textbf{true} and \\(q\\) is \\textbf{true} -- the program goes into the body of the if-statement and evaluates the body code. This makes sense\r\n\t\\end{enumerate}\r\n\t\r\n\tWhen the code evaluator makes sense, then the implication statement is true.\r\n\\end{example}\r\n\r\n% todo add the 'promise' example?\r\n\r\n\\begin{defn}[Bi-conditional \\(\\Leftrightarrow\\), \\(\\leftrightarrow\\)]\r\n\tLogical connective that reads as an \\textit{if and only if} statement. This means that both propositions must imply each other. For the bi-conditional to be true, both propositions must either be true or false. Truth table:\r\n\t\\begin{center}\r\n\t\t\\begin{tabular}{c|c|c}\r\n\t\t\t\\(p\\) & \\(q\\) & \\(p \\Leftrightarrow q\\) \\\\\r\n\t\t\t\\hline\r\n\t\t\tF & F & T \\\\\r\n\t\t\tF & T & F \\\\\r\n\t\t\tT & F & F \\\\\r\n\t\t\tT & T & T\r\n\t\t\\end{tabular}\r\n\t\\end{center}\r\n\\end{defn}\r\n\r\nSome more complicated ones:\r\n\r\n\\begin{defn}[Exclusive Or (\\textit{Xor}) \\(\\oplus\\)]\r\n\tLogical connective that evaluates to true when \\textit{only} one of the two propositions that it connects is true. If both propositions are true or false, then \\textit{xor} evaluates to false. The exclusive part means we \\textit{exclude} the \\textit{or} case when both propositions are true. Truth table:\r\n\t\\begin{center}\r\n\t\t\\begin{tabular}{c|c|c}\r\n\t\t\t\\(p\\) & \\(q\\) & \\(p \\oplus q\\) \\\\\r\n\t\t\t\\hline\r\n\t\t\tF & F & F \\\\\r\n\t\t\tF & T & T \\\\\r\n\t\t\tT & F & T \\\\\r\n\t\t\tT & T & F\r\n\t\t\\end{tabular}\r\n\t\\end{center}\r\n\\end{defn}\r\n\r\n\\begin{defn}[Exclusive Nor (\\textit{Xnor}) \\(\\otimes\\)]\r\n\tLogical connective that negates the \\textit{xor}. It is just an \\textit{xor} connective appended with a \\textit{not} connective. Truth table:\r\n\t\\begin{center}\r\n\t\t\\begin{tabular}{c|c|c}\r\n\t\t\t\\(p\\) & \\(q\\) & \\(\\lnot (p \\oplus q) \\equiv (p \\otimes q)\\) \\\\\r\n\t\t\t\\hline\r\n\t\t\tF & F & T \\\\\r\n\t\t\tF & T & F \\\\\r\n\t\t\tT & F & F \\\\\r\n\t\t\tT & T & T\r\n\t\t\\end{tabular}\r\n\t\\end{center}\r\n\\end{defn}\r\n\r\nNow an example:\r\n\r\n\\exsol{\r\n\tTranslate the following statement into a propositional logic statement: \\textit{exclusively either the weather rains or students wear rain jackets}.\r\n}{\r\n\tLet \\(r\\) be the proposition \\textit{the weather rains} and \\(j\\) be the proposition \\textit{students wear rain jackets}. Then the statement becomes \\(r \\oplus j\\)\r\n}\r\n\r\n\\subsection{Boolean Algebra}\r\n\r\nThe motivation behind Boolean algebra is that we want to take complicated compound propositional statements and simplify them. If we notice that a variable does not affect the final output, then getting rid of that variable cuts the amount of truth-value possibilities (truth-table rows) in half.\r\n\r\n\\begin{defn}[Boolean Statement]\r\n\t\\index{Boolean Statement}\r\n\tA statement that is exclusively either true or false\r\n\\end{defn}\r\n\r\nSome handy notations:\r\n\r\n\\begin{defn}[Equivalence \\(\\equiv\\)]\r\n\tLogical equivalence says that the two connected statements are logically the same. You can think of this notation as the \\textit{equals} sign. Equality is poorly defined for Boolean expressions, so we use the equivalence notation instead\r\n\\end{defn}\r\n\r\n\\begin{defn}[Tautology \\(t\\) \\textit{or} \\(\\mathbf{T}\\)]\r\n\tA proposition that is always true\r\n\\end{defn}\r\n\r\n\\begin{defn}[Contradiction \\(c\\) \\textit{or} \\(\\mathbf{F}\\)]\r\n\tA proposition that is always false\r\n\\end{defn}\r\n\r\nWe provide a handful of helpful theorems to aid in your Boolean algebra simplifications. You do not need to memorize these theorems -- they will be given to you as a table.\r\n\\marginpar{See appendix \\ref{appendix:tables}}\r\n\r\n\\begin{thm}[Commutativity]\r\n\tFor any propositions \\(p\\) and \\(q\\) the \\textbf{and} and \\textbf{or} operations are commutative: \\[p \\lor q \\equiv q \\lor p\\] \\[p \\land q \\equiv q \\land p\\]\r\n\\end{thm}\r\n\r\n\\begin{thm}[Associativity]\r\n\tFor any propositions \\(p\\), \\(q\\), and \\(r\\) the \\textbf{and} and \\textbf{or} operations are associative: \\[(p \\lor q) \\lor r \\equiv p \\lor (q \\lor r)\\] \\[(p \\land q) \\land r \\equiv p \\land (q \\land r)\\]\r\n\\end{thm}\r\n\r\n\\begin{thm}[Distributivity]\r\n\tFor any propositions \\(p\\), \\(q\\), and \\(r\\) the \\textbf{and} and \\textbf{or} operations are distributive: \\[p \\land (q \\lor r) \\equiv (p \\land q) \\lor (p \\land r)\\] \\[p \\lor (q \\land r) \\equiv (p \\lor q) \\land (p \\lor r)\\]\r\n\\end{thm}\r\n\r\n\\begin{thm}[Identity]\r\n\tFor any proposition \\(p\\) the following hold: \\[p \\lor c \\equiv p\\] \\[p \\land t \\equiv p\\]\r\n\\end{thm}\r\n\r\n\\begin{thm}[Negation]\r\n\tFor any proposition \\(p\\) the following hold: \\[p \\lor \\lnot p \\equiv t\\] \\[p \\land \\lnot p \\equiv c\\]\r\n\\end{thm}\r\n\r\n\\begin{thm}[Double Negation]\r\n\tFor any proposition \\(p\\) the following holds: \\[\\lnot (\\lnot p) \\equiv p\\]\r\n\\end{thm}\r\n\r\n\\begin{thm}[Idempotence]\r\n\tFor any proposition \\(p\\) the following hold: \\[p \\lor p = p\\] \\[p \\land p = p\\]\r\n\\end{thm}\r\n\r\n\\begin{thm}[De Morgan's]\r\n\tFor any propositions \\(p\\) and \\(q\\) the following hold: \\[\\lnot (p \\lor q) = \\lnot p \\land \\lnot q\\] \\[\\lnot (p \\land q) = \\lnot p \\lor \\lnot q\\]\r\n\\end{thm}\r\n\r\n\\begin{thm}[Universal Bound]\r\n\tFor any proposition \\(p\\) the following hold: \\[p \\lor t \\equiv t\\] \\[p \\land c \\equiv c\\]\r\n\\end{thm}\r\n\r\n\\begin{thm}[Absorption]\r\n\tFor any propositions \\(p\\) and \\(q\\) the following hold: \\[p \\lor (p \\land q) \\equiv p\\] \\[p \\land (p \\lor q) \\equiv p\\]\r\n\\end{thm}\r\n\r\n\\begin{thm}[Negation of Tautology and Contradiction]\r\n\tThe following hold: \\[\\lnot t \\equiv c\\] \\[\\lnot c \\equiv t\\]\r\n\\end{thm}\r\n\r\nHere are two important theorems that you will use throughout your proofs in this course. The first theorem says that for a bi-conditional both propositions must imply each other. The second theorem gives an equivalence between the implication and \\textit{or} connective. The proofs of these theorems are left as an exercise to the reader.\r\n\r\n\\begin{thm}[Bi-conditional to Implication]\r\n\t\\label{bicond-to-imp}\r\n\tFor any propositions \\(p\\) and \\(q\\) the following hold: \\[p \\Leftrightarrow q \\equiv (p \\Rightarrow q) \\land (q \\Rightarrow p)\\]\r\n\\end{thm}\r\n\r\n\\begin{thm}[Implication to Disjunction]\r\n\t\\label{imp-to-disj}\r\n\tFor any propositions \\(p\\) and \\(q\\) the following holds: \\[p \\Rightarrow q \\equiv \\lnot p \\lor q\\]\r\n\\end{thm}\r\n\r\nNow some examples of Boolean statement simplification.\r\n\r\n% todo\r\n\\exsol{\r\n\tSimplify the following expression: \\((p \\Rightarrow q) \\Rightarrow r\\)\r\n}{\r\n\t\\begin{align*}\r\n\t(p \\Rightarrow q) \\Rightarrow r &\\equiv \\big(\\lnot (p \\Rightarrow q)\\big) \\lor r & \\text{Implication to Disjunction} \\\\\r\n\t&\\equiv \\big(\\lnot ((\\lnot p) \\lor q)\\big) \\lor r & \\text{Implication to Disjunction} \\\\\r\n\t&\\equiv ((\\lnot (\\lnot p)) \\land (\\lnot q)) \\lor r & \\text{De Morgan's} \\\\\r\n\t&\\equiv (p \\land (\\lnot q)) \\lor r & \\text{Double Negation}\r\n\t\\end{align*}\r\n}\r\n\r\nNotice how we reference a theorem in each step. This allows us to fully explain our equivalence, keeps us from making mistakes, and ensures our equivalence is valid.\r\n\r\n\\exsol{\r\n\tSimplify the following expression: \\((p \\otimes q) \\land p\\)\r\n}{\r\n\t\\begin{align*}\r\n\t(p \\otimes q) \\land p &\\equiv \\lnot (p \\oplus q) \\land p & \\text{XNOR equivalence} \\\\\r\n\t&\\equiv \\lnot \\big((p \\land (\\lnot q)) \\lor ((\\lnot p) \\land q)\\big) \\land p & \\text{XOR equivalence} \\\\\r\n\t&\\equiv \\big( \\lnot (p \\land (\\lnot q)) \\land \\lnot ((\\lnot p) \\land q)\\big) \\land p & \\text{De Morgan's} \\\\\r\n\t&\\equiv \\big( ((\\lnot p) \\lor \\lnot(\\lnot q)) \\land (\\lnot (\\lnot p) \\lor (\\lnot q))\\big) \\land p & \\text{De Morgan's} \\\\\r\n\t&\\equiv \\big( ((\\lnot p) \\lor q) \\land (p \\lor (\\lnot q)) \\big) \\land p & \\text{Double Negation} \\\\\r\n\t%\r\n\t&\\equiv ((\\lnot p) \\lor q) \\land \\big( (p \\lor (\\lnot q)) \\land p \\big) & \\text{Associativity} \\\\\r\n\t&\\equiv ((\\lnot p) \\lor q) \\land \\big(p \\land (p \\lor (\\lnot q)) \\big) & \\text{Commutativity} \\\\\r\n\t&\\equiv ((\\lnot p) \\lor q) \\land p & \\text{Absorption} \\\\\r\n\t%\r\n\t&\\equiv p \\land ((\\lnot p) \\lor q) & \\text{Commutativity} \\\\\r\n\t&\\equiv (p \\land (\\lnot p)) \\lor (p \\land q) & \\text{Distributivity} \\\\\r\n\t&\\equiv c \\lor (p \\land q) & \\text{Negation} \\\\\r\n\t&\\equiv p \\land q & \\text{Identity}\r\n\t\\end{align*}\r\n}\r\n\r\nNote in the preceding example that we used equivalences between the \\textit{xnor} to the \\textit{xor}, and the \\textit{xor} to the \\textit{or}. We will discuss later exactly how we deduced these equivalences.\r\n\r\nNow that we understand some equivalences, we can motivate some definitions relating to the implication.\r\n\r\n\\begin{defn}[Converse]\r\n\tThe converse of \\(p \\Rightarrow q\\) is \\(q \\Rightarrow p\\). Obtain this by reversing the arrow direction.\r\n\\end{defn}\r\n\r\n\\begin{defn}[Inverse]\r\n\tThe inverse of \\(p \\Rightarrow q\\) is \\((\\lnot p) \\Rightarrow (\\lnot q)\\). Obtain this by negating both propositions.\r\n\\end{defn}\r\n\r\n\\begin{defn}[Contrapositive]\r\n\tThe contrapositive of \\(p \\Rightarrow q\\) is \\((\\lnot q) \\Rightarrow (\\lnot p)\\). Obtain this by reversing the arrow direction, and negating both propositions. Or, take both the converse and inverse.\r\n\\end{defn}\r\n\r\n\\begin{defn}[Negation]\r\n\tThe negation of \\(p \\Rightarrow q\\) is \\(\\lnot (p \\Rightarrow q)\\). Obtain this by negating the entire implication.\r\n\\end{defn}\r\n\r\nNow we can use our equivalencies to show some important facts about these definitions.\r\n\r\n\\begin{thm}[Contraposition Equivalence]\r\n\t\\[p \\Rightarrow q \\equiv (\\lnot q) \\Rightarrow (\\lnot p)\\]\r\n\\end{thm}\r\n\r\nWe leave the proof as an exercise. This theorem will serve us well in our study of Number Theory. The contrapositive indirect proof technique relies on this fact.\r\n\r\n\\begin{thm}[The Converse Error]\r\n\t\\[(p \\Rightarrow q) \\not\\Rightarrow (q \\Rightarrow p)\\]\r\n\\end{thm}\r\n\r\n\\begin{proof}\r\n\tWe want to show that if you have \\(p \\Rightarrow q\\), then you do not necessarily have \\(q \\Rightarrow p\\). There are many ways to show this, but we will start by simply examining cases of \\(p\\) and \\(q\\).\r\n\t\r\n\tConsider \\(p \\equiv \\mathbf{F}\\) and \\(q \\equiv \\mathbf{T}\\). Then\r\n\t\\(p \\Rightarrow q \\equiv \\mathbf{F} \\Rightarrow \\mathbf{T} \\equiv \\mathbf{T}\\). But then\r\n\t\\(q \\Rightarrow p \\equiv \\mathbf{T} \\Rightarrow \\mathbf{F} \\equiv \\mathbf{F}\\). Then overall we have\r\n\t\\((p \\Rightarrow q) \\Rightarrow (q \\Rightarrow p) \\equiv \\mathbf{T} \\Rightarrow \\mathbf{F} \\equiv \\mathbf{F}\\).\r\n\tSo we've shown that if you have \\(p \\Rightarrow q\\), then you do not necessarily have \\(q \\Rightarrow p\\).\r\n\\end{proof}\r\n\r\n\\begin{thm}[The Inverse Error]\r\n\t\\[(p \\Rightarrow q) \\not\\Rightarrow ((\\lnot p) \\Rightarrow (\\lnot q))\\]\r\n\\end{thm}\r\n\r\n\\begin{rem}\r\n\tA similar proof can be made for this theorem. Find one truth-value pairings for \\(p\\) and \\(q\\) such that \\(p \\Rightarrow q\\) is true, but \\((\\lnot p) \\Rightarrow (\\lnot q)\\) is false.\r\n\\end{rem}\r\n\r\n\\subsection{Circuits} %todo make better\r\n\r\nPropositions have two possible values: true and false. If we set true to mean \\textit{on} and false to mean \\textit{off}, then we can translate our Boolean statements into logical circuits. To do this, think of each logical connective as a \\textit{gate}. Similar to the logical connectives, a gate takes 2 (or more) inputs and returns some output. The inputs and outputs are all 1s and 0s (\\textit{on}s and \\textit{off}s -- true and false). Circuits are the bare-bones to computers, so it is necessary you understand the basics. For computer engineers, you must know circuits by heart.\r\n\r\n\\begin{defn}[Circuit]\r\n\tRepresentations of Boolean statements into electronic components\r\n\\end{defn}\r\n\r\nBoolean variables can be exclusively either true or false; this is analogous to electric wires being exclusively either on or off. We let a tautology be equivalent to a \\textit{power source}, which is a wire that is always \\textbf{on}. Similarly we let a contradiction be equivalent to \\textbf{off}, or a wire receiving no power.\r\n\r\nThe following gates are exactly equivalent to their logic counterparts. We thus only include the gate picture.\r\n\r\n\\begin{defn}[And Gate -- \\textit{conjunction}]\r\n\tPicture:\r\n\t\r\n\t\\begin{center}\r\n\t\t\\begin{circuitikz}\r\n\t\t\t\\draw\r\n\t\t\t(0,0) node[and port] () {};\r\n\t\t\\end{circuitikz}\r\n\t\\end{center}\r\n\t\r\n\tTo remember the \\textit{and} gate, note that the picture looks like a \\textbf{D}, which corresponds to the D in AN\\textbf{D}\r\n\\end{defn}\r\n\r\n\\begin{defn}[Or Gate -- \\textit{Disjunction}]\r\n\tPicture:\r\n\t\r\n\t\\begin{center}\r\n\t\t\\begin{circuitikz}\r\n\t\t\t\\draw\r\n\t\t\t(0,0) node[or port] () {};\r\n\t\t\\end{circuitikz}\r\n\t\\end{center}\r\n\\end{defn}\r\n\r\n\\begin{defn}[Not Gate -- \\textit{Negation}]\r\n\tPicture:\r\n\t\r\n\t\\begin{center}\r\n\t\t\\begin{circuitikz}\r\n\t\t\t\\draw\r\n\t\t\t(0,0) node[not port] () {};\r\n\t\t\\end{circuitikz}\r\n\t\\end{center}\r\n\\end{defn}\r\n\r\n\\begin{rem}\r\n\tWhen we have a gate that has a \\textit{not} after it, we can simplify the gate by just adding a circle to the output. Example (the \\textit{nand} gate is the negation of the \\textit{and} gate):\r\n\t\r\n\t\\begin{multicols}{3}\r\n\t\t\\begin{center}\r\n\t\t\t\\begin{circuitikz}\r\n\t\t\t\t\\draw\r\n\t\t\t\t(0,0) node[and port] (and1) {}\r\n\t\t\t\t(1,0) node[not port] (not1) {}\r\n\t\t\t\t(and1.out) -- (not1.in);\r\n\t\t\t\\end{circuitikz}\r\n\t\t\\end{center}\r\n\t\t\\begin{center}\r\n\t\t\tbecomes\r\n\t\t\\end{center}\r\n\t\t\\begin{center}\r\n\t\t\t\\begin{circuitikz}\r\n\t\t\t\t\\draw\r\n\t\t\t\t(0,0) node[nand port] (and1) {};\r\n\t\t\t\\end{circuitikz}\r\n\t\t\\end{center}\r\n\t\\end{multicols}\r\n\\end{rem}\r\n\r\n\\begin{defn}[Xor Gate (\\textit{eXclusive Or gate})]\r\n\tPicture:\r\n\t\r\n\t\\begin{center}\r\n\t\t\\begin{circuitikz}\r\n\t\t\t\\draw\r\n\t\t\t(0,0) node[xor port] () {};\r\n\t\t\\end{circuitikz}\r\n\t\\end{center}\r\n\\end{defn}\r\n\r\nWe can think of truth tables in an equivalent fashion, where 1 is true and 0 is false.\r\n\r\n\\exsol{\r\n\tWrite the truth table for the \\textit{nand} gate.\r\n}{\r\n\t\\mbox{}\r\n\t\r\n\t\\begin{center}\r\n\t\t\\begin{tabular}{c|c|c}\r\n\t\t\t\\(p\\) & \\(q\\) & \\(\\lnot (p \\land q)\\) \\\\\r\n\t\t\t\\hline\r\n\t\t\t0 & 0 & 1 \\\\\r\n\t\t\t0 & 1 & 1 \\\\\r\n\t\t\t1 & 0 & 1 \\\\\r\n\t\t\t1 & 1 & 0\r\n\t\t\\end{tabular}\r\n\t\\end{center}\r\n}\r\n\r\nYou can use 1/0 or T/F, whichever you prefer. If an assignment specifies you use a specific key, then use the one specified. Later when we discuss different number systems, you will notice a correlation between binary numbers and truth tables with 1/0s. This makes it easy to construct a truth table very quickly with a given amount of inputs.\r\n\r\n\r\n\r\n\\subsubsection{Circuit Addition}\r\n\r\nWe can also create circuits that add numbers.\r\nFor a discussion of different number bases, see section \\ref{diff-num-bases}.\r\n\r\nWe can build a circuit that adds two single-digit binary numbers? There are only 4 possibilities for adding single-digit numbers, so let's examine what a truth table for this process might look like (all numbers are in base-2):\r\n\r\n\\begin{center}\r\n\t\\begin{tabular}{cc|c}\r\n\t\tinput \\(a\\) & input \\(b\\) & output \\(a + b\\) \\\\\r\n\t\t\\midrule\r\n\t\t0 & 0 & 0 \\\\\r\n\t\t0 & 1 & 1 \\\\\r\n\t\t1 & 0 & 1 \\\\\r\n\t\t1 & 1 & 10 \\\\\r\n\t\\end{tabular}\r\n\\end{center}\r\n\r\nIn the output, we can always append zeros to the beginning of the binary number without changing the actual number:\r\n\r\n\\begin{center}\r\n\t\\begin{tabular}{cc|c}\r\n\t\tinput \\(a\\) & input \\(b\\) & output \\(a + b\\) \\\\\r\n\t\t\\midrule\r\n\t\t0 & 0 & 00 \\\\\r\n\t\t0 & 1 & 01 \\\\\r\n\t\t1 & 0 & 01 \\\\\r\n\t\t1 & 1 & 10 \\\\\r\n\t\\end{tabular}\r\n\\end{center}\r\n\r\nNow let's separate our output column into two columns -- the sum-bit (right) and the carry-bit (left):\r\n\r\n\\begin{center}\r\n\t\\begin{tabular}{cc|cc}\r\n\t\tinput \\(a\\) & input \\(b\\) & carry & sum \\\\\r\n\t\t\\midrule\r\n\t\t0 & 0 & 0 & 0 \\\\\r\n\t\t0 & 1 & 0 & 1 \\\\\r\n\t\t1 & 0 & 0 & 1 \\\\\r\n\t\t1 & 1 & 1 & 0 \\\\\r\n\t\\end{tabular}\r\n\\end{center}\r\n\r\nWe know how to generate Boolean expressions for the output columns: \r\n\\begin{align*}\r\n\t\\text{sum} &\\equiv a \\oplus b \\\\\r\n\t\\text{carry} &\\equiv a \\land b\r\n\\end{align*}\r\n\r\nWhich gives us the \\textbf{half adder}:\r\n\r\n\\begin{boxx}\r\n\tAdding two bits \\(a+b = cs\\) is equivalent to the circuit\r\n\t\\begin{center}\r\n\t\t\\begin{circuitikz}\r\n\t\t\t\\draw\r\n\t\t\t(0,0) node (xor1) [xor port] {}\r\n\t\t\t(0,1.5) node (and1) [and port] {}\r\n\t\t\t(and1.in 1) node (a) [anchor=east,xshift=-1cm] {\\(a\\)}\r\n\t\t\t(xor1.in 2) node (b) [anchor=east,xshift=-1cm] {\\(b\\)};\r\n\t\t\t\r\n\t\t\t\\draw (and1.in 1) -- (a);\r\n\t\t\t\\draw (and1.in 2) -- (b);\r\n\t\t\t\\draw (xor1.in 1) -- (a);\r\n\t\t\t\\draw (xor1.in 2) -- (b);\r\n\t\t\t\r\n\t\t\t\\draw\r\n\t\t\t(and1.out) node (c) [anchor=west,xshift=1cm] {carry}\r\n\t\t\t(xor1.out) node (s) [anchor=west,xshift=1cm] {sum};\r\n\t\t\t\r\n\t\t\t\\draw (and1.out) -- (c);\r\n\t\t\t\\draw (xor1.out) -- (s);\r\n\t\t\t\r\n\t\t\t\\node [xshift=.2cm] at (a) {\\textbullet};\r\n\t\t\t\\node [xshift=.2cm] at (b) {\\textbullet};\r\n\t\t\t\\node [xshift=-.5cm] at (c) {\\textbullet};\r\n\t\t\t\\node [xshift=-.5cm] at (s) {\\textbullet};\r\n\t\t\\end{circuitikz}\r\n\t\\end{center}\r\n\\end{boxx}\r\n\r\nNow we can add two 1-bit numbers together. What if we want to add multiple-bit numbers together? Consider adding two 2-bit numbers:\r\n\\begin{center}\r\n\t\\begin{tabular}{ccc}\r\n\t\t& \\(c\\) & \\\\\r\n\t\t& \\(x\\) & \\(y\\) \\\\\r\n\t\t\\(+\\) & \\(z\\) & \\(w\\) \\\\\r\n\t\t\\midrule\r\n\t\t\\(o_2\\) & \\(o_1\\) & \\(s\\)\r\n\t\\end{tabular}\r\n\\end{center}\r\n\r\nWe see here that after adding \\(y+w\\) we are left with a carry bit \\(c\\) for our addition \\(x+z\\). How do we add three bits \\(c+x+z\\)? Well, we can separate it into two 1-bit additions: \\(c+x\\) which, via a half-adder, yields a sum bit \\(s_1\\) and carry bit \\(c_1\\), then \\(s_1 + z\\) which, via another half-adder, yields a sum bit \\(s_2\\) and carry bit \\(c_2\\). Then, we can let \\(o_1 = s_2\\). Unfortunately this leaves us two carry bits that somehow need to be combined into a final carry bit.\r\n\r\nConsider now the truth-table for adding three bits:\r\n\\begin{center}\r\n\t\\begin{tabular}{ccc|c|ccc}\r\n\t\t\\(c\\) & \\(x\\) & \\(z\\) & \\(c+x+z\\) & carry\\((c+x)\\) & sum\\((c+x) = s_1\\) & carry\\((s_1+z)\\) \\\\\r\n\t\t\\midrule\r\n\t\t0 & 0 & 0 & 00 & 0 & 0 & 0 \\\\\r\n\t\t0 & 0 & 1 & 01 & 0 & 0 & 0 \\\\\r\n\t\t0 & 1 & 0 & 01 & 0 & 1 & 0 \\\\\r\n\t\t0 & 1 & 1 & 10 & 0 & 1 & 1 \\\\\r\n\t\t1 & 0 & 0 & 01 & 0 & 1 & 0 \\\\\r\n\t\t1 & 0 & 1 & 10 & 0 & 1 & 1 \\\\\r\n\t\t1 & 1 & 0 & 10 & 1 & 0 & 0 \\\\\r\n\t\t1 & 1 & 1 & 11 & 1 & 0 & 0 \\\\\r\n\t\\end{tabular}\r\n\\end{center}\r\n\r\nNow notice the carry bit in the output column \\(c+x+z\\) is the same as OR-ing the two carry bits from \\(c+x\\) and \\(s_1+z\\). This completes our circuit for adding three bits. We call this the \\textbf{full adder}:\r\n\r\n\\begin{boxx}\r\n\tAdding three bits \\(a+b+c = os\\) is equivalent to the circuit\r\n\t\\begin{center}\r\n\t\t\\begin{circuitikz}\r\n\t\t\t\\draw\r\n\t\t\t(0,0.75) node[draw,minimum width=2cm,minimum height=1cm] (HA1) {Half Adder}\r\n\t\t\t(3.5,0) node[draw,minimum width=2cm,minimum height=1cm] (HA2) {Half Adder}\r\n\t\t\t($(HA1.west)!0.75!(HA1.north west)$) coordinate (ha1in1)\r\n\t\t\t($(HA1.west)!0.75!(HA1.south west)$) coordinate (ha1in2);\r\n\t\t\t\\draw\r\n\t\t\t(ha1in1) node (a) [anchor=east,xshift=-0.5cm] {\\(a\\)}\r\n\t\t\t(ha1in2) node (b) [anchor=east,xshift=-0.5cm] {\\(b\\)}\r\n\t\t\t(ha1in1) -- (a)\r\n\t\t\t(ha1in2) -- (b);\r\n\t\t\t\\node [xshift=.2cm] at (a) {\\textbullet};\r\n\t\t\t\\node [xshift=.2cm] at (b) {\\textbullet};\r\n\t\t\t\r\n\t\t\t\\draw\r\n\t\t\t($(HA1.east)!0.75!(HA1.north east)$) coordinate (ha1out1)\r\n\t\t\t($(HA1.east)!0.75!(HA1.south east)$) coordinate (ha1out2);\r\n\t\t\t\\draw\r\n\t\t\t(ha1out1) node (c1) [anchor=west,xshift=4cm] {c\\(_1\\)}\r\n\t\t\t(ha1out2) node (s1) [anchor=west,xshift=0.35cm] {sum}\r\n\t\t\t(ha1out1) -- (c1)\r\n\t\t\t(ha1out2) -- (s1);\r\n\t\t\t%\\node [xshift=-.2cm] at (c1) {\\textbullet};\r\n\t\t\t\r\n\t\t\t\\draw\r\n\t\t\t($(HA2.west)!0.75!(HA2.north west)$) coordinate (ha2in1)\r\n\t\t\t($(HA2.west)!0.75!(HA2.south west)$) coordinate (ha2in2);\r\n\t\t\t\\draw\r\n\t\t\t(s1) -- (ha2in1)\r\n\t\t\t(ha2in2) node (c) [anchor=east,xshift=-4cm] {\\(c\\)}\r\n\t\t\t(ha2in2) -- (c);\r\n\t\t\t\\node [xshift=.2cm] at (c) {\\textbullet};\r\n\t\t\t\r\n\t\t\t\\draw\r\n\t\t\t($(HA2.east)!0.75!(HA2.north east)$) coordinate (ha2out1)\r\n\t\t\t($(HA2.east)!0.75!(HA2.south east)$) coordinate (ha2out2);\r\n\t\t\t\\draw\r\n\t\t\t(ha2out1) node (c2) [anchor=west,xshift=0.5cm] {c\\(_2\\)}\r\n\t\t\t(ha2out2) node (s) [anchor=west,xshift=2.65cm] {\\(s\\)}\r\n\t\t\t(ha2out1) -- (c2)\r\n\t\t\t(ha2out2) -- (s);\r\n\t\t\t\\node [xshift=-.2cm] at (s) {\\textbullet};\r\n\t\t\t\r\n\t\t\t\\draw\r\n\t\t\t(7,0.75) node (or1) [or port] {}\r\n\t\t\t(or1.in 1) -- (c1)\r\n\t\t\t(or1.in 2) -- (c2)\r\n\t\t\t(or1.out) node (o) [anchor=west] {\\(o\\)};\r\n\t\t\t\\node [xshift=-.2cm] at (o) {\\textbullet};\r\n\t\t\\end{circuitikz}\r\n\t\\end{center}\r\n\\end{boxx}\r\n\r\nPutting these two structures, the half adder and full adder, together, we can construct a 2-bit adder, which solves our previous problem of doing \\(xy + zw = o_2o_1s\\):\r\n\r\n\\begin{boxx}\r\n\tAdding three bits \\(a+b+c = os\\) is equivalent to the circuit\r\n\t\\begin{center}\r\n\t\t\\begin{circuitikz}\r\n\t\t\t\\draw\r\n\t\t\t(0,0.75) node[draw,minimum width=2cm,minimum height=1cm] (HA1) {Half Adder}\r\n\t\t\t(3.75,-0.2) node[draw,minimum width=2cm,minimum height=1.5cm] (FA1) {Full Adder}\r\n\t\t\t($(HA1.west)!0.75!(HA1.north west)$) coordinate (ha1in1)\r\n\t\t\t($(HA1.west)!0.75!(HA1.south west)$) coordinate (ha1in2);\r\n\t\t\t\\draw\r\n\t\t\t(ha1in1) node (y) [anchor=east,xshift=-0.5cm] {\\(y\\)}\r\n\t\t\t(ha1in2) node (w) [anchor=east,xshift=-0.5cm] {\\(w\\)}\r\n\t\t\t(ha1in1) -- (y)\r\n\t\t\t(ha1in2) -- (w);\r\n\t\t\t\\node [xshift=.2cm] at (y) {\\textbullet};\r\n\t\t\t\\node [xshift=.2cm] at (w) {\\textbullet};\r\n\t\t\t\r\n\t\t\t\\draw\r\n\t\t\t($(HA1.east)!0.75!(HA1.north east)$) coordinate (ha1out1)\r\n\t\t\t($(HA1.east)!0.75!(HA1.south east)$) coordinate (ha1out2);\r\n\t\t\t\\draw\r\n\t\t\t(ha1out1) node (s) [anchor=west,xshift=4.5cm] {\\(s\\)}\r\n\t\t\t(ha1out2) node (c1) [anchor=west,xshift=0.35cm] {carry}\r\n\t\t\t(ha1out1) -- (s)\r\n\t\t\t(ha1out2) -- (c1);\r\n\t\t\t\\node [xshift=-.2cm] at (s) {\\textbullet};\r\n\t\t\t\r\n\t\t\t\\draw\r\n\t\t\t($(FA1.west)!0.75!(FA1.north west)$) coordinate (fa1in1)\r\n\t\t\t($(FA1.west)!0.75!(FA1.south west)$) coordinate (fa1in2)\r\n\t\t\t($(FA1.west)!0!(FA1.south west)$) coordinate (fa1in3);\r\n\t\t\t\\draw\r\n\t\t\t(c1) -- (fa1in1)\r\n\t\t\t(fa1in2) node (x) [anchor=east,xshift=-4.25cm] {\\(x\\)}\r\n\t\t\t(fa1in2) -- (x)\r\n\t\t\t(fa1in3) node (z) [anchor=east,xshift=-4.25cm] {\\(z\\)}\r\n\t\t\t(fa1in3) -- (z);\r\n\t\t\t\\node [xshift=.2cm] at (x) {\\textbullet};\r\n\t\t\t\\node [xshift=.2cm] at (z) {\\textbullet};\r\n\t\t\t\r\n\t\t\t\\draw\r\n\t\t\t($(FA1.east)!0.75!(FA1.north east)$) coordinate (fa1out1)\r\n\t\t\t($(FA1.east)!0.75!(FA1.south east)$) coordinate (fa1out2);\r\n\t\t\t\\draw\r\n\t\t\t(fa1out1) node (o1) [anchor=west,xshift=0.75cm] { \\(o_1\\)}\r\n\t\t\t(fa1out2) node (o2) [anchor=west,xshift=0.75cm] { \\(o_2\\)}\r\n\t\t\t(fa1out1) -- (o1)\r\n\t\t\t(fa1out2) -- (o2);\r\n\t\t\t\\node [xshift=-.3cm] at (o1) {\\textbullet};\r\n\t\t\t\\node [xshift=-.3cm] at (o2) {\\textbullet};\r\n\t\t\\end{circuitikz}\r\n\t\\end{center}\r\n\\end{boxx}\r\n\r\nThis solves our 2-bit addition problem. What if we want to add 3-bit numbers? 4-bit numbers? \\(n\\)-bit numbers? Well, after the first bit column (adding two bits) we must add three bits. After this second column, we get a sum bit and a carry bit. If we tack on another column, which would make a 3-bit adder, then we add in the previous carry to the two new bits. This same process repeats for all further columns. So, tacking on another bit solely entails tacking on another full adder! \\textit{Picture omitted}.\r\n\r\n\\exsol{\r\n\tHow many half adders are required for an \\(n\\)-bit adder?\r\n}{\r\n\tNote, here we implicitly assumed \\(n > 0\\).\r\n\t\r\n\tWe need 1 half adder to start, and we need \\(n-1\\) full adders which each contain 2 half adders. This totals to \\(2(n-1) + 1 = 2n-1\\) half adders.\r\n}\r\n\r\n\r\n\r\n\\subsection{Translations}\r\n\r\nYou must know how to translate between circuits, Boolean statements, and truth tables.\r\n\r\nWe start by motivating the translation between truth tables and Boolean statements. First, notice that we have already discussed how to make a truth table from a Boolean statement -- simply draw the truth table and fill in each row. Now we can focus on the reverse.\r\n\r\nWe attempt to first motivate a process for this translation by showing a few examples.\r\n\r\n\\begin{example}\r\n\tFirst recall the truth table for the conjunction:\r\n\t\r\n\t\\begin{center}\r\n\t\t\\begin{tabular}{cc|c}\r\n\t\t\t\\(p\\) & \\(q\\) & \\(p \\land q\\) \\\\\r\n\t\t\t\\hline\r\n\t\t\tF & F & F \\\\\r\n\t\t\tF & T & F \\\\\r\n\t\t\tT & F & F \\\\\r\n\t\t\tT & T & T\r\n\t\t\\end{tabular}\r\n\t\\end{center}\r\n\t\r\n\tRecall that we can extend the conjunction to take multiple inputs -- in this case, \\textit{each} input \\textit{must} be \\textbf{True} for the output to be \\textbf{True}.\r\n\t\r\n\tNow consider the following unknown table:\r\n\t\r\n\t\\begin{center}\r\n\t\t\\begin{tabular}{cc|c}\r\n\t\t\t\\(p\\) & \\(q\\) & unknown \\\\\r\n\t\t\t\\hline\r\n\t\t\tF & F & F \\\\\r\n\t\t\tF & T & T \\\\\r\n\t\t\tT & F & F \\\\\r\n\t\t\tT & T & F\r\n\t\t\\end{tabular}\r\n\t\\end{center}\r\n\t\r\n\tThis table is similar to the conjunction table in that it has \\textit{one row} that outputs \\textbf{True}. In the conjunction case, the assignments to \\(p\\) and \\(q\\) were both \\textbf{True}. What are the assignments to the previous truth table? Well, the \\(p\\) input is \\textbf{False} and the \\(q\\) input is \\textbf{True}, as per the table. If we apply the conjunction to this row we have, we get the following table:\r\n\t\r\n\t\\begin{center}\r\n\t\t\\begin{tabular}{c|c|c|c}\r\n\t\t\t\\(p\\) & \\(\\lnot p\\) & \\(q\\) & \\((\\lnot p) \\land q\\) \\\\\r\n\t\t\t\\hline\r\n\t\t\tF & T & F & F \\\\\r\n\t\t\tF & T & T & T \\\\\r\n\t\t\tT & F & F & F \\\\\r\n\t\t\tT & F & T & F\r\n\t\t\\end{tabular}\r\n\t\\end{center}\r\n\t\r\n\tIn the previous table, if we look at the middle two columns, we recover the conjunction with the \\(p\\) variable negated.\r\n\\end{example}\r\n\r\nThis is only half the story though.\r\n\r\n\\begin{example}\r\n\tFirst recall the truth table for the disjunction:\r\n\t\r\n\t\\begin{center}\r\n\t\t\\begin{tabular}{cc|c}\r\n\t\t\t\\(p\\) & \\(q\\) & \\(p \\lor q\\) \\\\\r\n\t\t\t\\hline\r\n\t\t\tF & F & F \\\\\r\n\t\t\tF & T & T \\\\\r\n\t\t\tT & F & T \\\\\r\n\t\t\tT & T & T\r\n\t\t\\end{tabular}\r\n\t\\end{center}\r\n\t\r\n\tFor this example, we only care about the middle two rows where \\textit{either} variable is \\textbf{True}.\r\n\t\r\n\t\r\n\\end{example}\r\n\r\nThese bring light to a simple 3-step process to translate from truth tables to Boolean statements:\r\n\r\n\\begin{enumerate}\r\n\t\\item Collect the rows whose \\textit{output} is \\textbf{True}\r\n\t\\item For each of those rows\r\n\t\\begin{enumerate}\r\n\t\t\\item Look at the truth value assigned to the \\textit{input}\r\n\t\t\\item Construct a Boolean statement where, for each input\r\n\t\t\\begin{itemize}\r\n\t\t\t\\item If the assignment is \\textbf{True} then use the variable itself\r\n\t\t\t\\item If the assignment is \\textbf{False} then use the \\textit{negation} of the variable\r\n\t\t\\end{itemize}\r\n\t\t\\item Chain each input with \\textbf{And} (\\(\\land\\)) connectives\r\n\t\\end{enumerate}\r\n\t\\item Chain each row's statement with \\textbf{Or} (\\(\\lor\\)) connectives\r\n\\end{enumerate}\r\n\r\n\\exsol{\r\n\tFind the unknown Boolean formula corresponding to the following truth table:\r\n\r\n\t\\begin{center}\r\n\t\t\\begin{tabular}{cc|c}\r\n\t\t\t\\(p\\) & \\(q\\) & unknown \\\\\r\n\t\t\t\\hline\r\n\t\t\tF & F & T \\\\\r\n\t\t\tF & T & F \\\\\r\n\t\t\tT & F & T \\\\\r\n\t\t\tT & T & F\r\n\t\t\\end{tabular}\r\n\t\\end{center}\r\n}{\r\n\tWe follow the algorithm as before. The first and third rows return true in the output. In the first row, we see neither input is true, so we AND the negation of each input: \\((\\lnot p) \\land (\\lnot q)\\). In the third row, we see the first input is true, while the second input is false, thus we get: \\(p \\land (\\lnot q)\\). OR-ing each statement together thus yields our unknown formula: \\[((\\lnot p) \\land (\\lnot q)) \\lor (p \\land (\\lnot q))\\]\r\n}\r\n\r\n\\begin{rem}\r\n\tIn our Boolean formula algorithm, we only focus on the true rows. If we wanted to also include the false rows, then we would need the statement in each false row to return false. We know how to get a statement that returns true, so we can simply take that statement and negate it! What happens, though, if we include the false rows then?\r\n\\end{rem}\r\n\r\n\\exsol{\r\n\tInclude the false rows in the Boolean formula from the previous example.\r\n}{\r\n\tWe negate the second and fourth row returned by the algorithm: \\(\\lnot ((\\lnot p) \\land q)\\) and \\(\\lnot (p \\land q)\\)\r\n\t\r\n\tSo our entire statement is now \\[((\\lnot p) \\land (\\lnot q)) \\lor (p \\land (\\lnot q)) \\lor (\\lnot ((\\lnot p) \\land q)) \\lor (\\lnot (p \\land q))\\]\r\n\t\r\n\tLet's simplify this statement (rules omitted):\r\n\t\\begin{align*}\r\n\t&\\equiv ((\\lnot p) \\land (\\lnot q)) \\lor (p \\land (\\lnot q)) \\lor (\\lnot ((\\lnot p) \\land q)) \\lor (\\lnot (p \\land q)) \\\\\r\n\t&\\equiv ((\\lnot p) \\land (\\lnot q)) \\lor (p \\land (\\lnot q)) \\lor (p \\lor (\\lnot q)) \\lor ((\\lnot p) \\lor q) \\\\\r\n\t&\\equiv ((\\lnot p) \\land (\\lnot q)) \\lor (p \\land (\\lnot q)) \\lor (p \\lor (\\lnot p)) \\lor ((\\lnot q) \\lor q) \\\\\r\n\t&\\equiv ((\\lnot p) \\land (\\lnot q)) \\lor (p \\land (\\lnot q)) \\lor t \\lor t \\\\\r\n\t&\\equiv ((\\lnot p) \\land (\\lnot q)) \\lor (p \\land (\\lnot q))\r\n\t\\end{align*}\r\n\t\r\n\tNice, we have recovered the original statement!\r\n}\r\n\r\n\\begin{rem}\r\n\tIncluding each false row in the Boolean statement generated by the algorithm -- so long as their true versions are negated -- does not logically change the Boolean statement\r\n\\end{rem}\r\n\r\nWe have a name for the type of statement generated from our algorithm above:\r\n\r\n\\begin{defn}[Disjunctive Normal Form\\index{Disjunctive Normal Form}]\r\n\tDescribes a Boolean statement that is a conjunction of disjunctions -- abbreviated DNF\r\n\\end{defn}\r\n\r\nIf we flip each gate (AND goes to OR, OR goes to AND), then we get another important type of statement:\r\n\r\n\\begin{defn}[Conjunctive Normal Form\\index{Conjunctive Normal Form}]\r\n\tDescribes a Boolean statement that is a disjunction of conjunctions -- abbreviated CNF\r\n\\end{defn}\r\n\r\nInterestingly, any Boolean statement can be translated to an equivalent statement in CNF. Namely, statements in DNF, which are easy to generate, can be translated into CNF. This is important for computational complexity theory -- specifically NP-completeness. There exists a problem in computer science which entails finding a set of truth-value assignments for \\(n\\) different Boolean variables which makes a Boolean statement in CNF return true (or, become \\textit{satisfiable}).\r\n\r\n\\subsection{Reasoning/Deductions}\r\n\\label{section:reasoning}\r\n\r\nPropositional logic also allows us to \\textit{reason} about things.\r\n\r\n\\begin{defn}[Knowledge Base]\r\n\tA group of information that you know is true\r\n\\end{defn}\r\n\r\n\\begin{defn}[Reasoning]\r\n\tThe process of deriving new information from a given knowledge base\r\n\\end{defn}\r\n\r\nSee the introduction of this chapter for an example.\r\n\r\n\\subsubsection{Classical Rules of Deduction}\r\n\r\nWe may refer to \\textit{deductions} as \\textit{inferences}. They are the same.\r\n\r\n\\begin{defn}[Deductions]\r\n\tUsing previously-known knowledge in your knowledge base to obtain/create new knowledge\r\n\\end{defn}\r\n\r\nWe have a whole list of useful deductions that are provably valid. As with our Boolean algebra theorems, you do not need to memorize these theorems -- they will be given to you as a table.\r\n\r\n\\begin{thm}[Modus Ponens]\r\n\t\\mbox{}\r\n\t\\begin{center}\r\n\t\t\\begin{tabular}{c@{\\,}l@{}}\r\n\t\t\t& \\(p\\) \\\\\r\n\t\t\t& \\(p \\Rightarrow q\\) \\\\\r\n\t\t\t\\cline{2-2}\r\n\t\t\t\\(\\therefore\\) & \\(q\\)\r\n\t\t\\end{tabular}\r\n\t\\end{center}\r\n\\end{thm}\r\n\r\n\\begin{thm}[Modus Tollens]\r\n\t\\mbox{}\r\n\t\\begin{center}\r\n\t\t\\begin{tabular}{c@{\\,}l@{}}\r\n\t\t\t& \\(\\lnot q\\) \\\\\r\n\t\t\t& \\(p \\Rightarrow q\\) \\\\\r\n\t\t\t\\cline{2-2}\r\n\t\t\t\\(\\therefore\\) & \\(\\lnot p\\)\r\n\t\t\\end{tabular}\r\n\t\\end{center}\r\n\\end{thm}\r\n\r\n\\begin{thm}[Disjunctive Addition]\r\n\t\\mbox{}\r\n\t\\begin{center}\r\n\t\t\\begin{tabular}{c@{\\,}l@{}}\r\n\t\t\t& \\(p\\) \\\\\r\n\t\t\t\\cline{2-2}\r\n\t\t\t\\(\\therefore\\) & \\(p \\lor q\\)\r\n\t\t\\end{tabular}\r\n\t\\end{center}\r\n\\end{thm}\r\n\r\n\\begin{thm}[Conjunctive Addition]\r\n\t\\mbox{}\r\n\t\\begin{center}\r\n\t\t\\begin{tabular}{c@{\\,}l@{}}\r\n\t\t\t& \\(p,q\\) \\\\\r\n\t\t\t\\cline{2-2}\r\n\t\t\t\\(\\therefore\\) & \\(p \\land q\\)\r\n\t\t\\end{tabular}\r\n\t\\end{center}\r\n\\end{thm}\r\n\r\n\\begin{thm}[Conjunctive Simplification]\r\n\t\\mbox{}\r\n\t\\begin{center}\r\n\t\t\\begin{tabular}{c@{\\,}l@{}}\r\n\t\t\t& \\(p \\land q\\) \\\\\r\n\t\t\t\\cline{2-2}\r\n\t\t\t\\(\\therefore\\) & \\(p,q\\)\r\n\t\t\\end{tabular}\r\n\t\\end{center}\r\n\\end{thm}\r\n\r\n\\begin{thm}[Disjunctive Syllogism]\r\n\t\\mbox{}\r\n\t\\begin{center}\r\n\t\t\\begin{tabular}{c@{\\,}l@{}}\r\n\t\t\t& \\(p \\lor q\\) \\\\\r\n\t\t\t& \\(\\lnot p\\) \\\\\r\n\t\t\t\\cline{2-2}\r\n\t\t\t\\(\\therefore\\) & \\(q\\)\r\n\t\t\\end{tabular}\r\n\t\\end{center}\r\n\\end{thm}\r\n\r\n\\begin{thm}[Hypothetical Syllogism]\r\n\t\\mbox{}\r\n\t\\begin{center}\r\n\t\t\\begin{tabular}{c@{\\,}l@{}}\r\n\t\t\t& \\(p \\Rightarrow q\\) \\\\\r\n\t\t\t& \\(q \\Rightarrow r\\) \\\\\r\n\t\t\t\\cline{2-2}\r\n\t\t\t\\(\\therefore\\) & \\(p \\Rightarrow r\\)\r\n\t\t\\end{tabular}\r\n\t\\end{center}\r\n\\end{thm}\r\n\r\n\\begin{thm}[Resolution]\r\n\t\\mbox{}\r\n\t\\begin{center}\r\n\t\t\\begin{tabular}{c@{\\,}l@{}}\r\n\t\t\t& \\(p \\lor q\\) \\\\\r\n\t\t\t& \\((\\lnot q) \\lor r\\) \\\\\r\n\t\t\t\\cline{2-2}\r\n\t\t\t\\(\\therefore\\) & \\(p \\lor r\\)\r\n\t\t\\end{tabular}\r\n\t\\end{center}\r\n\\end{thm}\r\n\r\n\\begin{thm}[Division Into Cases]\r\n\t\\mbox{}\r\n\t\\begin{center}\r\n\t\t\\begin{tabular}{c@{\\,}l@{}}\r\n\t\t\t& \\(p \\lor q\\) \\\\\r\n\t\t\t& \\(p \\Rightarrow r\\) \\\\\r\n\t\t\t& \\(q \\Rightarrow r\\) \\\\\r\n\t\t\t\\cline{2-2}\r\n\t\t\t\\(\\therefore\\) & \\(r\\)\r\n\t\t\\end{tabular}\r\n\t\\end{center}\r\n\\end{thm}\r\n\r\n\\begin{thm}[Law of Contradiction]\r\n\t\\mbox{}\r\n\t\\begin{center}\r\n\t\t\\begin{tabular}{c@{\\,}l@{}}\r\n\t\t\t& \\((\\lnot p) \\Rightarrow \\mathbf{c}\\) \\\\\r\n\t\t\t\\cline{2-2}\r\n\t\t\t\\(\\therefore\\) & \\(p\\)\r\n\t\t\\end{tabular}\r\n\t\\end{center}\r\n\\end{thm}\r\n\r\nYou may be wondering how to prove these deductions are \\textit{valid}. We have two equivalent methods:\r\n\\begin{enumerate}\r\n\t\\item Tautological implication\r\n\t\\item Critical-row identification\r\n\\end{enumerate}\r\n\r\nConsider an arbitrary deduction:\r\n\\begin{center}\r\n\t\\begin{tabular}{c@{\\,}l@{}}\r\n\t\t& \\(P_1\\) \\\\\r\n\t\t& \\(P_2\\) \\\\\r\n\t\t& \\(\\cdots \\cdots \\cdots\\) \\\\\r\n\t\t& \\(P_n\\) \\\\\r\n\t\t\\cline{2-2}\r\n\t\t\\(\\therefore\\) & \\(Q\\)\r\n\t\\end{tabular}\r\n\\end{center}\r\n\r\nTo prove it valid,\r\n\r\n\\textbf{Tautological implication}\r\n\\begin{enumerate}\r\n\t\\item Construct a new proposition \\(A \\Rightarrow B\\) where \\(A\\) is a \\textbf{conjunction of the premises} and \\(B\\) is the conclusion. For our arbitrary deduction, we would have \\[\\big( P_1 \\land P_2 \\land \\cdots \\land P_n \\big) \\Rightarrow Q\\]\r\n\t\\item Inspect this proposition in a truth-table. If the proposition is a tautology, then the deduction is valid. Otherwise, the deduction is invalid. So, to be valid we must have \\[(A \\Rightarrow B) \\equiv \\big( P_1 \\land P_2 \\land \\cdots \\land P_n \\big) \\Rightarrow Q \\equiv t\\]\r\n\\end{enumerate}\r\n\r\n\\textbf{Critical-row identification}\r\n\\begin{enumerate}\r\n\t\\item Construct a truth-table with columns for each proposition and for the conclusion. \\textit{You may need extra columns, that is fine}. For our arbitrary deduction, we would have\r\n\t\\begin{center}\r\n\t\t\\begin{tabular}{cccc|c}\r\n\t\t\t\\(P_1\\) & \\(P_2\\) & \\(\\cdots\\) & \\(P_n\\) & \\(Q\\) \\\\\r\n\t\t\t\\midrule\r\n\t\t\tF/T & F/T & \\(\\cdots\\) & F/T & F/T \\\\\r\n\t\t\t&& \\(\\vdots\\) && \\\\\r\n\t\t\tT/T & F/T & \\(\\cdots\\) & F/T & F/T \\\\\r\n\t\t\\end{tabular}\r\n\t\\end{center}\r\n\t\\item Identify the rows in which each \\textbf{premise} is true. We call these rows \\textbf{critical-rows}.\r\n\t\\item For each critical-row, inspect the conclusion. If the conclusion is true in \\textbf{every} critical-row, then the deduction is valid. Otherwise, the deduction is invalid.\r\n\\end{enumerate}\r\n\r\nExamples following the above steps.\r\n\r\n\\exsol{\r\n\tShow that Modus Ponens is a valid rule of inference.\r\n}{\r\n\t\\textit{method 1 -- tautological implication}\r\n\t\r\n\tOur proposition we care about is \\((p \\land (p \\Rightarrow q)) \\Rightarrow q\\), so we build the following truth-table with extraneous rows:\r\n\t\\begin{center}\r\n\t\t\\begin{tabular}{cc|cc|cc|c}\r\n\t\t\t\\(p\\) & \\(q\\) & \\(p\\) & \\(p \\Rightarrow q\\) & \\(p \\land (p \\Rightarrow q)\\) & \\(q\\) & \\((p \\land (p \\Rightarrow q)) \\Rightarrow q\\) \\\\\r\n\t\t\t\\midrule\r\n\t\t\tF & F & F & T & F & F & T \\\\\r\n\t\t\tF & T & F & T & F & T & T \\\\\r\n\t\t\tT & F & T & F & F & F & T \\\\\r\n\t\t\tT & T & T & T & T & T & T \\\\\r\n\t\t\\end{tabular}\r\n\t\\end{center}\r\n\t\r\n\tInspect the last column.\r\n\t\\begin{center}\r\n\t\t\\begin{tabular}{cc|cc|cc|c}\r\n\t\t\t\\(p\\) & \\(q\\) & \\(p\\) & \\(p \\Rightarrow q\\) & \\(p \\land (p \\Rightarrow q)\\) & \\(q\\) & \\((p \\land (p \\Rightarrow q)) \\Rightarrow q\\) \\\\\r\n\t\t\t\\midrule\r\n\t\t\tF & F & F & T & F & F & \\cellcolor{Melon}\\color{green} \\textbf{T} \\\\\r\n\t\t\tF & T & F & T & F & T & \\cellcolor{Melon}\\color{green} \\textbf{T} \\\\\r\n\t\t\tT & F & T & F & F & F & \\cellcolor{Melon}\\color{green} \\textbf{T} \\\\\r\n\t\t\tT & T & T & T & T & T & \\cellcolor{Melon}\\color{green} \\textbf{T} \\\\\r\n\t\t\\end{tabular}\r\n\t\\end{center}\r\n\t\r\n\tIn the case of Modus Ponens, the final column is a tautology, hence the deduction is valid.\r\n}\r\n\r\n\\exsol{\r\n\tShow that Modus Ponens is a valid rule of inference.\r\n}{\r\n\t\\textit{method 2 -- critical-row identification}\r\n\t\r\n\tConstruct a truth table with each premise and conclusion:\r\n\t\\begin{center}\r\n\t\t\\begin{tabular}{cc|cc|c}\r\n\t\t\t\\(p\\) & \\(q\\) & \\(p\\) & \\(p \\Rightarrow q\\) & \\(q\\) \\\\\r\n\t\t\t\\midrule\r\n\t\t\tF & F & F & T & F \\\\\r\n\t\t\tF & T & F & T & T \\\\\r\n\t\t\tT & F & T & F & F \\\\\r\n\t\t\tT & T & T & T & T \\\\\r\n\t\t\\end{tabular}\r\n\t\\end{center}\r\n\t\r\n\tIdentify the critical-rows.\r\n\t\\begin{center}\r\n\t\t\\begin{tabular}{cc|cc|c}\r\n\t\t\t\\(p\\) & \\(q\\) & \\(p\\) & \\(p \\Rightarrow q\\) & \\(q\\) \\\\\r\n\t\t\t\\midrule\r\n\t\t\tF & F & F & T & F \\\\\r\n\t\t\tF & T & F & T & T \\\\\r\n\t\t\tT & F & T & F & F \\\\\r\n\t\t\t\\rowcolor{Melon}\r\n\t\t\tT & T & \\textbf{T} & \\textbf{T} & T \\\\\r\n\t\t\\end{tabular}\r\n\t\\end{center}\r\n\t\r\n\tInspect the conclusion in each critical-row.\r\n\t\\begin{center}\r\n\t\t\\begin{tabular}{cc|cc|c}\r\n\t\t\t\\(p\\) & \\(q\\) & \\(p\\) & \\(p \\Rightarrow q\\) & \\(q\\) \\\\\r\n\t\t\t\\midrule\r\n\t\t\tF & F & F & T & F \\\\\r\n\t\t\tF & T & F & T & T \\\\\r\n\t\t\tT & F & T & F & F \\\\\r\n\t\t\t\\rowcolor{Melon}\r\n\t\t\tT & T & \\textbf{T} & \\textbf{T} & \\textbf{\\color{green} T} \\\\\r\n\t\t\\end{tabular}\r\n\t\\end{center}\r\n\t\r\n\tIn the case of Modus Ponens, the conclusion is true in each critical row, hence the deduction is valid.\r\n}\r\n\r\nWe leave it to the reader to understand why the two methods are equivalent.\r\n\r\n\\subsubsection{Deducing Things}\r\n\r\nIn a later section, we will see that this order of logic is not powerful enough to prove mathematical statements. For now, we can still do interesting things with a given knowledge base.\r\n\r\n\\exsol{\r\n\tGiven the following knowledge base, deduce as much new information as possible using the following rules of inference: Modus Ponens, Modus Tollens, Hypothetical Syllogism, and Disjunctive Syllogism.\r\n\t\r\n\t\\begin{center}\r\n\t\t\\hfill \\(a \\Rightarrow b\\) \\hfill \\(b \\Rightarrow (\\lnot d)\\) \\hfill \\(e\\) \\hfill \\(d \\lor (\\lnot e)\\) \\hfill \\mbox{}\r\n\t\\end{center}\r\n}{\r\n\\\\\r\n\tBy Hypothetical Syllogism \\(a \\Rightarrow b\\), \\(b \\Rightarrow (\\lnot d)\\), \\hfill \\(\\therefore a \\Rightarrow (\\lnot d)\\)\r\n\t\r\n\tBy Disjunctive Syllogism \\(d \\lor (\\lnot e)\\), \\(e\\), \\hfill \\(\\therefore d\\)\r\n\t\r\n\tBy Modus Tollens \\(d\\), \\(a \\Rightarrow (\\lnot d)\\), \\hfill \\(\\therefore \\lnot a\\)\r\n\t\r\n\tBy Modus Tollens \\(d\\), \\(b \\Rightarrow (\\lnot d)\\), \\hfill \\(\\therefore \\lnot b\\)\r\n\t\r\n\t% todo is this finished?\r\n}\r\n\r\n\\begin{rem}\r\n\tFrom the above example, we restricted the rules you could have used. We did this mainly because Disjunctive Addition can allow you to generate any new knowledge you like -- so long as you have one thing that is true, then you can add in a disjunction infinitely-many times.\r\n\\end{rem}\r\n\r\n\\begin{rem}\r\n\tIn the above example, we could have translated \\(d \\lor (\\lnot e) \\equiv e \\Rightarrow d\\) and concluded \\(d\\) by Modus Ponens. This somewhat tells you that Disjunctive Syllogism and Modus Ponens are equivalent.\r\n\\end{rem}\r\n\r\n\\begin{rem}\r\n\tFrom an inconsistent database, anything follows.\r\n\t\r\n\tThis is due to the law of contradiction. An \\textit{inconsistent database} is one that contains a contradiction. Recall from the law of contradiction that \\((\\lnot p) \\Rightarrow c \\equiv (\\lnot (\\lnot p)) \\lor c \\equiv p\\) using the Identity Boolean algebra theorem. Using Disjunctive Addition, we have the contradiction \\(c\\), \\(\\therefore A \\lor c\\), and by Identity, \\(\\therefore A\\). \\(A\\) can be \\textit{Anything}.\r\n\\end{rem}\r\n\r\nIn Artificial Intelligence, there exists an algorithm called \\textbf{The Resolution Algorithm}. Essentially, it says to take a given knowledge base, translate each statement into disjunctive normal form, then apply the Resolution rule of inference as many times as possible.\r\n\r\n\\section{Predicate Logic}\r\n\r\nSometimes basic propositions are not enough to do what you want. In programming we can have functions that return true or false. We can do the same thing with logic -- we call this \\textit{first-order} logic, or \\textit{predicate} logic. Predicate logic includes all of propositional logic, however it adds predicates and quantifiers.\r\n\r\n\\begin{defn}[Predicate\\index{Predicate}]\r\n\tA property that the subject of a statement can have. In logic, we represent this sort-of like a function. A predicate takes, as input, some element, and returns whether the inputted element has the specific property.\r\n\\end{defn}\r\n\r\n\\begin{example}\r\n\tWe could use the predicate \\(EVEN(x)\\) to mean \\(x\\) is an even number. In this case, the predicate is \\(EVEN(\\cdot)\\)\r\n\\end{example}\r\n\r\n\\begin{example}\r\n\tWe could use the predicate \\(P(y)\\) to mean \\(y\\) is an integer multiple of 3. In this case, the predicate is \\(P(\\cdot)\\)\r\n\\end{example}\r\n\r\n\\begin{rem}\r\n\tPredicates take \\textbf{elements}. They do \\textbf{not} take in other predicates. This is because predicates say whether the input element \\textit{has} the property specified by the predicate -- true and false cannot have properties.\r\n\t\r\n\tIn terms of programming, you can think of a predicate as a program method. For example, the \\(EVEN(x)\\) predicate might be implemented as follows:\r\n\t\r\n\t\\begin{lstlisting}\r\nfunc EVEN(Entity x) -> bool {\r\n\tif IS_INTEGER(x) {\r\n\t\treturn x % 2 == 0\r\n\t}\r\n\treturn false\r\n}\r\n\t\\end{lstlisting}\r\n\t\r\n\tIn this case, entities are \\textit{objects} and true/false are \\textit{Boolean primitives} (or, propositional statements, which can only be true or false). In contrast to, say, Java, a compiler for this code would not allow \\textit{true/false} to be an object.\r\n\t\r\n\tA better example,\r\n\t\r\n\t\\begin{lstlisting}\r\nclass Foo extends Entity {\r\n\tbool isInteger\r\n\tbool isOdd\r\n\t\r\n\tFoo(Integer i) {\r\n\t\tthis.isInteger = true\r\n\t\tthis.isOdd = i % 2 == 1\r\n\t}\r\n}\r\n\r\nfunc ODD(Entity x) -> bool {\r\n\tif x has type Foo {\r\n\t\treturn x.isOdd\r\n\t}\r\n\tif IS_INTEGER(x) {\r\n\t\treturn x % 2 == 1\r\n\t}\r\n\treturn false\r\n}\r\n\t\\end{lstlisting}\r\n\\end{rem}\r\n\r\n\\begin{defn}[Quantifier\\index{Quantifier}]\r\n\tA way to select a specific range of elements that get inputted to a predicate. We have two quantifiers:\r\n\t\r\n\t\\begin{itemize}\r\n\t\t\\item The Universal quantifier \\(\\forall\\)\r\n\t\t\\item The Existential quantifier \\(\\exists\\)\r\n\t\\end{itemize}\r\n\r\n\tThe universal quantifier says to select \\textbf{all} elements, and the existential quantifier says to select \\textbf{at least one} element.\r\n\\end{defn}\r\n\r\n\\begin{defn}[Quantified Statement]\r\n\tA logical statement involving predicates and quantifiers. Syntax: \\[(\\text{quantifier } var \\in D)[\\text{statement involving predicates}]\\]\r\n\\end{defn}\r\n\r\nAnd now we can define:\r\n\r\n\\begin{defn}[Predicate Logic]\r\n\tAlso called \\textit{first-order logic}, is a logic made up of quantified statements.\r\n\\end{defn}\r\n\r\n\\exsol{\r\n\tTranslate the following statements to predicate logic:\r\n\t\\begin{enumerate}\r\n\t\t\\item All people are mortal\r\n\t\t\\item Even integers exist\r\n\t\t\\item If an integer is prime then it is not even\r\n\t\\end{enumerate}\r\n}{\r\n\t\\begin{enumerate}\r\n\t\t\\item Denote \\(P\\) as the domain of people, and the predicate \\(M(x)\\) to mean \\(x\\) is mortal. Then the statement translates to \\[(\\forall p \\in P)[M(p)]\\]\r\n\t\t\\item Denote \\(\\Z\\) as the domain of integers, and the predicate \\(EVEN(x)\\) to mean \\(x\\) is even. Then the statement translates to \\[(\\exists x \\in \\Z)[EVEN(x)]\\]\r\n\t\t\\item Denote the predicate \\(PRIME(y)\\) to mean \\(y\\) is prime. Then the statement translates to \\[(\\forall a \\in \\Z)[PRIME(a) \\Rightarrow \\lnot EVEN(a)]\\]\r\n\t\\end{enumerate}\r\n}\r\n\r\n\\subsection{Negating Quantified Statements}\r\n\r\nOne may find useful to negate a given quantified statement. We present here how to do this, first with an English example, followed by a quantified example, followed by an algorithm.\r\n\r\n\\begin{example}\r\n\tThe following statement\r\n\t\\begin{center}\r\n\t\t\\textit{There is no student who has taken calculus.}\r\n\t\\end{center}\r\n\tis equivalent to\r\n\t\\begin{center}\r\n\t\t\\textit{All students have not taken calculus.}\r\n\t\\end{center}\r\n\\end{example}\r\n\r\n\\begin{example}\r\n\tThe following statement\r\n\t\\begin{center}\r\n\t\t\\textit{Not all students have taken calculus.}\r\n\t\\end{center}\r\n\tis equivalent to\r\n\t\\begin{center}\r\n\t\t\\textit{There is a student who has not taken calculus.}\r\n\t\\end{center}\r\n\\end{example}\r\n\r\n\\begin{example}\r\n\tThe following statement \\[\\lnot(\\exists x \\in D)[C(x)]\\] is equivalent to \\[(\\forall x \\in D)[\\lnot C(x)]\\]\r\n\\end{example}\r\n\r\n\\begin{example}\r\n\tThe following statement \\[\\lnot(\\forall x \\in D)[C(x)]\\] is equivalent to \\[(\\exists x \\in D)[\\lnot C(x)]\\]\r\n\\end{example}\r\n\r\nThe generic algorithm for pushing the negation into a quantified statement:\r\n\r\n\\begin{enumerate}\r\n\t\\item Flip each quantifier \\(\\forall \\rightarrow \\exists\\) and \\(\\exists \\rightarrow \\forall\\)\r\n\t\\item Apply the negation to the propositional part of the quantified statement, and simplify\r\n\t\\begin{enumerate}\r\n\t\t\\item If the inside contains another quantified statement, then recursively apply this algorithm\r\n\t\\end{enumerate}\r\n\\end{enumerate}\r\n\r\n\\begin{rem}\r\n\tThe domain and variable attached to any quantifier are \\textbf{not} changed.\r\n\\end{rem}\r\n\r\n\\exsol{\r\n\tPush the negation in as far as possible: \\[\\lnot (\\forall x,y \\in \\Z)[(x < y) \\Rightarrow (\\exists m \\in \\Q)[x < m < y]]\\]\r\n}{\r\n\t\\begin{align*}\r\n\t& \\lnot (\\forall x,y \\in \\Z)[(x < y) \\Rightarrow (\\exists m \\in \\Q)[x < m < y]] \\\\\r\n\t\\equiv & (\\exists x,y \\in \\Z) \\lnot [(x < y) \\Rightarrow (\\exists m \\in \\Q)[x < m < y]] \\\\\r\n\t\\equiv & (\\exists x,y \\in \\Z) \\lnot [\\lnot (x < y) \\lor (\\exists m \\in \\Q)[x < m < y]] \\\\\r\n\t\\equiv & (\\exists x,y \\in \\Z) [\\lnot \\lnot (x < y) \\land \\lnot (\\exists m \\in \\Q)[x < m < y]] \\\\\r\n\t\\equiv & (\\exists x,y \\in \\Z) [(x < y) \\land (\\forall m \\in \\Q) \\lnot [x < m < y]] \\\\\r\n\t\\equiv & (\\exists x,y \\in \\Z) [(x < y) \\land (\\forall m \\in \\Q) \\lnot [x < m \\land m < y]] \\\\\r\n\t\\equiv & (\\exists x,y \\in \\Z) [(x < y) \\land (\\forall m \\in \\Q) [x \\geq m \\lor m \\geq y]]\r\n\t\\end{align*}\r\n}\r\n\r\n\\begin{rem}\r\n\tWe typically expect the final statement to contain no \\(\\lnot\\) operators.\r\n\\end{rem}\r\n\r\n\\subsection{Quantified Rules of Inference}\r\n\r\nAgain, \\textit{deductions} and \\textit{inferences} are the same. We present a handful of important \\textit{quantified} rules of inference.\r\n\r\n\\begin{thm}[Universal Instantiation]\r\n\tFor a predicate \\(P(\\cdot)\\) and some domain \\(D\\) with \\(c \\in D\\),\r\n\t\\begin{center}\r\n\t\t\\begin{tabular}{c@{\\,}l@{}}\r\n\t\t\t& \\((\\forall x \\in D)[P(x)]\\) \\\\\r\n\t\t\t\\cline{2-2}\r\n\t\t\t\\(\\therefore\\) & \\(P(c)\\)\r\n\t\t\\end{tabular}\r\n\t\\end{center}\r\n\r\n\tAs an example, if our domain consists of all dogs and Fido is a dog, then the above rule can be read as\r\n\t\\begin{center}\r\n\t\t``All dogs are cuddly''\r\n\t\t\r\n\t\t``Therefore Fido is cuddly''\r\n\t\\end{center}\r\n\\end{thm}\r\n\r\n\\begin{thm}[Universal Generalization]\r\n\tFor a predicate \\(P(\\cdot)\\) and some domain \\(D\\) for an arbitrary \\(c \\in D\\),\r\n\t\\begin{center}\r\n\t\t\\begin{tabular}{c@{\\,}l@{}}\r\n\t\t\t& \\(P(c)\\) \\\\\r\n\t\t\t\\cline{2-2}\r\n\t\t\t\\(\\therefore\\) & \\((\\forall x \\in D)[P(x)]\\)\r\n\t\t\\end{tabular}\r\n\t\\end{center}\r\n\r\n\tThis is most-often used in mathematics. As an example, if our domain consists of all dogs, then the above rule can be read as\r\n\t\\begin{center}\r\n\t\t``An arbitrary dog is cuddly'' (which in-turn applies to all dogs)\r\n\t\t\r\n\t\t``Therefore all dogs are cuddly''\r\n\t\\end{center}\r\n\\end{thm}\r\n\r\n\\begin{thm}[Existential Instantiation]\r\n\tFor a predicate \\(P(\\cdot)\\) and some domain \\(D\\) for some element \\(c \\in D\\),\r\n\t\\begin{center}\r\n\t\t\\begin{tabular}{c@{\\,}l@{}}\r\n\t\t\t& \\((\\exists x \\in D)[P(x)]\\) \\\\\r\n\t\t\t\\cline{2-2}\r\n\t\t\t\\(\\therefore\\) & \\(P(c)\\)\r\n\t\t\\end{tabular}\r\n\t\\end{center}\r\n\r\n\tAs an example, if our domain consists of all dogs, then the above rule can be read as\r\n\t\\begin{center}\r\n\t\t``There is a dog who is cuddly''\r\n\t\t\r\n\t\t``Let's call that dog \\(c\\), and so \\(c\\) is cuddly''\r\n\t\\end{center}\r\n\\end{thm}\r\n\r\n\\begin{thm}[Existential Generalization]\r\n\tFor a predicate \\(P(\\cdot)\\) and some domain \\(D\\) for some element \\(c \\in D\\),\r\n\t\\begin{center}\r\n\t\t\\begin{tabular}{c@{\\,}l@{}}\r\n\t\t\t& \\(P(c)\\) \\\\\r\n\t\t\t\\cline{2-2}\r\n\t\t\t\\(\\therefore\\) & \\((\\exists x \\in D)[P(x)]\\)\r\n\t\t\\end{tabular}\r\n\t\\end{center}\r\n\r\n\tAs an example, if our domain consists of all dogs and Fido is a dog, then the above rule can be read as\r\n\t\\begin{center}\r\n\t\t``Fido is cuddly''\r\n\t\t\r\n\t\t``Therefore there is a dog who is cuddly''\r\n\t\\end{center}\r\n\\end{thm}\r\n\r\n\\begin{thm}[Universal Modus Ponens]\r\n\tFor two predicates \\(P(\\cdot)\\) and \\(Q(\\cdot)\\), and some domain \\(D\\) with \\(a \\in D\\),\r\n\t\\begin{center}\r\n\t\t\\begin{tabular}{c@{\\,}l@{}}\r\n\t\t\t& \\(P(a)\\) \\\\\r\n\t\t\t& \\((\\forall x \\in D)[P(x) \\Rightarrow Q(x)]\\) \\\\\r\n\t\t\t\\cline{2-2}\r\n\t\t\t\\(\\therefore\\) & \\(Q(a)\\)\r\n\t\t\\end{tabular}\r\n\t\\end{center}\r\n\\end{thm}\r\n\r\n\\begin{thm}[Universal Modus Tollens]\r\n\tFor two predicates \\(P(\\cdot)\\) and \\(Q(\\cdot)\\), and some domain \\(D\\) with \\(a \\in D\\),\r\n\t\\begin{center}\r\n\t\t\\begin{tabular}{c@{\\,}l@{}}\r\n\t\t\t& \\(\\lnot Q(a)\\) \\\\\r\n\t\t\t& \\((\\forall x \\in D)[P(x) \\Rightarrow Q(x)]\\) \\\\\r\n\t\t\t\\cline{2-2}\r\n\t\t\t\\(\\therefore\\) & \\(\\lnot P(a)\\)\r\n\t\t\\end{tabular}\r\n\t\\end{center}\r\n\\end{thm}\r\n\r\n\\subsection{Proving Things}\r\n\r\nOur familiar rules of inference are not strong enough to prove abstract mathematical statements. Typically we want our proof to apply to a whole \\textit{set} of things (numbers). Now that we know about \\textit{predicate logic}, we can apply our more powerful \\textit{quantified} rules of inference to prove real mathematical statements.\r\n\r\n\\exsol{\r\n\tUsing Universal Modus Ponens, verify the validity of the following proof:\r\n\t\\begin{proof}\r\n\t\tLet \\(m,n \\in \\Z\\), and let \\(m\\) be even. Then \\(m = 2p\\) for some integer \\(p\\).\\textsuperscript{\\color{blue} (1)} Now, \r\n\t\t\\begin{align*}\r\n\t\tm \\cdot n &= (2p)n & \\text{by substitution} \\\\\r\n\t\t&= 2(pn)^{\\text{\\color{blue} (2)}} & \\text{by associativity}\r\n\t\t\\end{align*}\r\n\t\t\r\n\t\tNow, \\(pn \\in \\Z\\),\\textsuperscript{\\color{blue} (3)} so by definition of even \\(2(pn)\\) is even.\\textsuperscript{\\color{blue} (4)} Thus \\(mn\\) is even.\r\n\t\\end{proof}\r\n}{\r\n\t\\\\\r\n\t\\makebox[4mm]{\\color{blue} (1)} \\makebox[6mm]{} If an integer is even, then it equals twice some integer.\\\\\r\n\t\\makebox[4mm]{} \\makebox[6mm]{} \\(m\\) is a particular integer, and it is even.\\\\\r\n\t\\makebox[4mm]{} \\makebox[6mm]{\\(\\therefore\\)} \\(m\\) equals twice some integer \\(p\\).\\\\\r\n\t\r\n\t\\makebox[4mm]{\\color{blue} (2)} \\makebox[6mm]{} If a quantity is an integer, then it is a real number.\\\\\r\n\t\\makebox[4mm]{} \\makebox[6mm]{} \\(p\\) and \\(n\\) are both particular integers.\\\\\r\n\t\\makebox[4mm]{} \\makebox[6mm]{\\(\\therefore\\)} \\(p\\) and \\(n\\) are both real numbers.\\\\\r\n\t\r\n\t\\makebox[4mm]{} \\makebox[6mm]{} For all \\(a,b,c\\), if \\(a,b,c \\in \\R\\) then \\((ab)c = a(bc)\\).\\\\\r\n\t\\makebox[4mm]{} \\makebox[6mm]{} \\(2\\), \\(p\\), and \\(n\\) are all particular real numbers.\\\\\r\n\t\\makebox[4mm]{} \\makebox[6mm]{\\(\\therefore\\)} \\((2p)n = 2(pn)\\).\\\\\r\n\t\r\n\t\\makebox[4mm]{\\color{blue} (3)} \\makebox[6mm]{} For all \\(u,v\\), if \\(u,v \\in \\Z\\) then \\(uv \\in \\Z\\).\\\\\r\n\t\\makebox[4mm]{} \\makebox[6mm]{} \\(p\\) and \\(n\\) are both particular integers.\\\\\r\n\t\\makebox[4mm]{} \\makebox[6mm]{\\(\\therefore\\)} \\(pn \\in \\Z\\).\\\\\r\n\t\r\n\t\\makebox[4mm]{\\color{blue} (4)} \\makebox[6mm]{} If a number equals twice some integer, then that number is even.\\\\\r\n\t\\makebox[4mm]{} \\makebox[6mm]{} \\(2(pn)\\) equals twice the integer \\(pn\\).\\\\\r\n\t\\makebox[4mm]{} \\makebox[6mm]{\\(\\therefore\\)} \\(2(pn)\\) is even.\\\\\r\n}\r\n\r\nOf course, we would never do a mathematical proof like this. In reality, you do this in your head automatically. Seeing this form, however, allows you to easily verify the \\textbf{validity} of the proof.\r\n\r\n\\section{Summary}\r\n\r\n\\begin{itemize}\r\n\t\\item Propositional logic contains the entirety of Boolean algebra and logic connectives, with True and False as the only inputs/outputs\r\n\t\\item Predicate logic contains the entirety of propositional logic and uses functions along with entities\r\n\t\\item Deriving knowledge from familiar rules entails mathematical proof\r\n\\end{itemize}\r\n\r\n\\section{Practice}\r\n\r\n\\begin{enumerate}\r\n\t\\item Answer the two logic puzzles presented in the introduction of this chapter.\r\n\t\\item Translate the following statement into propositional logic: \\textit{turn right then turn left}.\r\n\t\\item Translate the following statement into propositional logic: \\textit{if it is raining then everyone has an umbrella}.\r\n\t\\item How can you quickly construct a truth table with all row possibilities? Use your technique to construct a truth table with 4 variables.\r\n\t\\item How many rows does a truth table with \\(n\\) variables have?\r\n\t\\item Prove theorem \\ref{bicond-to-imp}.\r\n\t\\item Prove theorem \\ref{imp-to-disj}.\r\n\t\\item Draw the circuit representation of theorem \\ref{bicond-to-imp}.\r\n\t\\item Prove the following rule valid or invalid:\r\n\t\\begin{center}\r\n\t\t\\begin{tabular}{c@{\\,}l@{}}\r\n\t\t\t& \\((a \\land d) \\Rightarrow b\\) \\\\\r\n\t\t\t& \\(e\\) \\\\\r\n\t\t\t& \\(b \\Rightarrow (\\lnot e)\\) \\\\\r\n\t\t\t& \\((\\lnot a) \\Rightarrow f\\) \\\\\r\n\t\t\t& \\((\\lnot d) \\Rightarrow f\\) \\\\\r\n\t\t\t\\cline{2-2}\r\n\t\t\t\\(\\therefore\\) & \\(f\\)\r\n\t\t\\end{tabular}\r\n\t\\end{center}\r\n\t\\item Prove the following rule valid or invalid:\r\n\t\\begin{center}\r\n\t\t\\begin{tabular}{c@{\\,}l@{}}\r\n\t\t\t& \\((a \\land d) \\Rightarrow b\\) \\\\\r\n\t\t\t& \\(e\\) \\\\\r\n\t\t\t& \\(b \\Rightarrow (\\lnot e)\\) \\\\\r\n\t\t\t& \\((\\lnot a) \\Rightarrow f\\) \\\\\r\n\t\t\t& \\((\\lnot d) \\Rightarrow f\\) \\\\\r\n\t\t\t\\cline{2-2}\r\n\t\t\t\\(\\therefore\\) & \\(b \\Rightarrow e\\)\r\n\t\t\\end{tabular}\r\n\t\\end{center}\r\n\t\\item Push the negation inside the following statement as far as possible: \\[\\lnot (\\forall x \\in \\R)(\\exists m \\in \\Z)[(0 \\leq x - m < 1) \\Leftrightarrow (m = \\floor{x})]\\]\r\n\\end{enumerate}\r\n\r\n%\\section{Solutions}\r\n%\r\n%\\begin{enumerate}\r\n%\t\\item (1) Sam cannot make any cows, because Sam only starts with 1 cow. (2) We know knights always tell the truth. If we assume the speaker is a knight, then he will have lied about whom he is. Therefore, the speaker is a knave. Since knaves always lie, then we know the speaker lied, so the two people cannot both be knaves. Therefore, the second person is a knight.\r\n%\t\\item This is a trick question since the statement does not have any true or false value! If you answered something like \\(r \\Rightarrow l\\), good thinking, however this is incorrect.\r\n%\t\\item One possibility: let \\(r\\) be the proposition \\textit{it is raining} and \\(u\\) be the proposition \\textit{everyone has an umbrella}, then the statement becomes \\(r \\Rightarrow u\\).\r\n%\t\\item \\(2^n\\) rows.\r\n%\t\\item Examine the rows from right to left. In the first column, alternate T/F by 1 step. In the second column, alternate T/F by 2 steps. In the third column, alternate T/F by 4 steps. In the \\(n\\)th column, alternate T/F by \\(2^{n-1}\\) steps. The following example uses 1/0, however you should be able to translate it to T/F.\r\n%\t\r\n%\t\\begin{center}\r\n%\t\t\\begin{tabular}{cccc}\r\n%\t\t\t\\(p\\) & \\(q\\) & \\(r\\) & \\(s\\) \\\\\r\n%\t\t\t\\hline\r\n%\t\t\t0 & 0 & 0 & 0 \\\\\r\n%\t\t\t0 & 0 & 0 & 1 \\\\\r\n%\t\t\t0 & 0 & 1 & 0 \\\\\r\n%\t\t\t0 & 0 & 1 & 1 \\\\\r\n%\t\t\t0 & 1 & 0 & 0 \\\\\r\n%\t\t\t0 & 1 & 0 & 1 \\\\\r\n%\t\t\t0 & 1 & 1 & 0 \\\\\r\n%\t\t\t0 & 1 & 1 & 1 \\\\\r\n%\t\t\t1 & 0 & 0 & 0 \\\\\r\n%\t\t\t1 & 0 & 0 & 1 \\\\\r\n%\t\t\t1 & 0 & 1 & 0 \\\\\r\n%\t\t\t1 & 0 & 1 & 1 \\\\\r\n%\t\t\t1 & 1 & 0 & 0 \\\\\r\n%\t\t\t1 & 1 & 0 & 1 \\\\\r\n%\t\t\t1 & 1 & 1 & 0 \\\\\r\n%\t\t\t1 & 1 & 1 & 1\r\n%\t\t\\end{tabular}\r\n%\t\\end{center}\r\n%\t\\item \r\n%\t\\item \r\n%\\end{enumerate}\r\n\\end{document}\r\n", "meta": {"hexsha": "17d68398af61586f1a429dbc2fb1c19c90bcae7e", "size": 65093, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "ch-logic.tex", "max_stars_repo_name": "jugoodma/250-textbook", "max_stars_repo_head_hexsha": "ebfcd8e9d15079fe8924bf562a194ed057aed302", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2020-04-22T03:33:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-27T14:39:11.000Z", "max_issues_repo_path": "ch-logic.tex", "max_issues_repo_name": "jugoodma/250-textbook", "max_issues_repo_head_hexsha": "ebfcd8e9d15079fe8924bf562a194ed057aed302", "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": "ch-logic.tex", "max_forks_repo_name": "jugoodma/250-textbook", "max_forks_repo_head_hexsha": "ebfcd8e9d15079fe8924bf562a194ed057aed302", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-06-19T22:24:49.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-19T22:24:49.000Z", "avg_line_length": 40.8106583072, "max_line_length": 586, "alphanum_fraction": 0.6478576805, "num_tokens": 21318, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4532618480153862, "lm_q2_score": 0.4225046348141882, "lm_q1q2_score": 0.19150523157094482}}
{"text": "%\\documentclass[12pt]{article}\n\\documentclass[12pt,landscape]{article}\n\n\\usepackage{wrapfig}\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 241 Fall \\the\\year{} \\\\ Midterm Examination Two}\n\\author{Professor Adam Kapelner}\n\n\\date{Thursday, November 11, \\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}\nThis exam is 70 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. Within each problem, I recommend considering the questions that are easy first and then circling back to evaluate the harder ones. 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\\problem\\timedsection{12} Consider an apartment building with three floors. Each apartment has a floor number and an apartment letter. The first floor has 5 apartments denoted 1A, 1B, 1C, 1D, 1E; the second floor has 3 apartments denoted 2A, 2B, 2C; the third floor has only a penthouse denoted 3A. Bob walks into this apartment building and selects a floor uniformly (i.e. each floor is equally likely). He then enters an apartment on that floor uniformly.\n\n\\vspace{-0.2cm}\\benum\\truefalsesubquestionwithpoints{15} \n\\begin{enumerate}[(a)]\n\\item The probability Bob picks floor 3 is less than the probability Bob picks floor 1.\n\\item The probability Bob picks floor 3 is more than the probability Bob picks floor 1.\n\\item The probability of selecting each apartment in the entire building is uniform.\n\\item The probability of selecting each apartment on floor 2 is uniform if you are told Bob is on floor 2.\n\\item The probability Bob enters the penthouse is 1/3.\n\\item The probability Bob enters a C apartment is 2/3.\n\\item Given that Bob is in a C apartment, the probability he is on the first floor is zero.\n\\item Given that Bob is in a C apartment, the probability he is on the first floor is 1/3.\n\\item Given that Bob is in a C apartment, the probability he is on the first floor is 9/24.\n\\item Given that Bob is in a C apartment, the probability he is on the first floor is 15/24.\n\\item Given that Bob is in a C apartment, the probability he is on the third floor is zero.\n\\item Given that Bob is in a C apartment, the probability he is on the third floor is 1/3.\n\\item Given that Bob is in a C apartment, the probability he is on the third floor is 9/24.\n\\item Given that Bob is in a C apartment, the probability he is on the third floor is 15/24.\n\\item The floor selection is independent of the apartment letter selection\n\\end{enumerate}\n\\eenum\\instr\\pagebreak\n\n%%%%%%%%%%%%%%%%%%\n\\vspace{-0.4cm}\n\\begin{wrapfigure}{R}{2in}\n\\includegraphics[width=1.5in]{spinner.png}\n\\end{wrapfigure} \\problem\\timedsection{12} Consider a game where someone spins the spinner pictured on the right. The numbers represent payouts in \\$. The spinner has four colors: red, blue, green, yellow with payouts 2,4, or 8; 5 or 7; 3 or 6; 1 respectively. Let $X$ be the rv whose realization values are the payouts. Assume the spinner is fair.\n\n\\benum\\truefalsesubquestionwithpoints{18} \n\\begin{enumerate}[(a)]\n\n\\vspace{-0.2cm}\n\\item $X$ is a discrete rv\n\\item $X$ is a uniform discrete rv\n\\item $X$ could be a binomial rv where $n = 8$\n\\item $X$ could be a hypergeometric rv where $N = 8$\n\\item $\\support{X} = \\braces{1, 2,..., 8}$\n\\item $\\support{X} = \\bracks{1, 8}$\n%\\item $|\\support{X}| = 8$\n\\item $|\\support{X}| = |\\naturals|$\n\\item If we let $\\Omega$ = \\{Red, blue, green, yellow\\} then we can construct a rv $X$ that maps $\\omega \\in \\Omega$ to the support values of $X$.\n\\item If we let $\\Omega = \\bracks{0, 2\\pi}$ where $\\omega$ represents the angle of the spinner from the right horizontal level between states 2 and 3, then we can construct a rv $X$ that maps $\\omega \\in \\Omega$ to the support values of $X$.\n\\item $\\expe{X} = 4$\n\\item $\\expe{X} = 4.5$\n\\item $\\expe{X} = 5$\n\\item Med$\\bracks{X}$ = 4\n\\item Med$\\bracks{X}$ = 4.5\n\\item Med$\\bracks{X}$ = 5\n\\item Q$\\bracks{X, 0.1}$ = 1\n\\item Q$\\bracks{X, 0.1}$ = 2\n\\item Range$\\bracks{X}$ = 8\n\\end{enumerate}\n\\eenum\\instr\\pagebreak\n\n%%%%%%%%%%%%%%%%%%\n\\begin{wrapfigure}{R}{2in}\n\\includegraphics[width=1.5in]{spinner.png}\n\\end{wrapfigure} \\problem\\timedsection{8} \\ingray{Consider a game where someone spins the spinner pictured on the right. The numbers represent payouts in dollars. The spinner has four colors: red, blue, green, yellow. Red payouts are 2,4, or 8; blue payouts are 5 or 7; green payouts are 3 or 6; yellow only pays out 1. Let $X$ be the rv whose realization values are the payouts. Assume the spinner is fair.} In this rv, $\\mu = 4.5$ and $\\support{X} = \\braces{1, 2,..., 8}$.\n\n\\vspace{-0.2cm}\\benum\\truefalsesubquestionwithpoints{14} \n\\begin{enumerate}[(a)]\n\\item $p(x)$ is monotonically increasing\n\\item $F(x)$ is monotonically increasing\n\\item $p(x) < 1$ for all $x \\in \\support{X}$\n\\item $F(x) < 1$ for all $x \\in \\support{X}$\n\\item $F(4) = 0$\n\\item $F(4) = 0.5$\n\\item $F(4) = 1$\n\\item $p(4) = 0.5$\n\\item $\\sigsq := \\var{X} = (1/8) (1^2 + 2^2 + 3^2 + \\ldots + 8^2)$\n\\item $\\sigsq := \\var{X} = (1/4)(0.5^2 + 1.5^2 + 2.5^2 + 3.5^2)$\n\\item $\\expe{X^2} = 4.5^2$\n\\item $\\sigma := \\sd{X} = \\expe{X} - 4.5$\n\\item The unit of the value of the variance of $X$ is dollars\n\\item The unit of the value of the standard deviation of $X$ is dollars\n\\end{enumerate}\n\\eenum\\instr\\pagebreak\n\n%%%%%%%%%%%%%%%%%%\n\\begin{wrapfigure}{R}{2in}\n\\includegraphics[width=1.3in]{spinner.png}\n\\end{wrapfigure} \\problem\\timedsection{10} \\ingray{Consider a game where someone spins the spinner pictured on the right. The numbers represent payouts in dollars. The spinner has four colors: red, blue, green, yellow. Red payouts are 2,4, or 8; blue payouts are 5 or 7; green payouts are 3 or 6; yellow only pays out 1. Let $X$ be the rv whose realization values are the payouts. Assume the spinner is fair. In this rv, $\\mu = 4.5$ and $\\support{X} = \\braces{1, 2,..., 8}$.} The variance is $\\sigsq := \\var{X} = 5.25$ and $\\sigma := \\sd{X} = 2.29$ rounded to the nearest two digits.\n\n\\vspace{-0.2cm}\\benum\\truefalsesubquestionwithpoints{13} \n\\begin{enumerate}[(a)]\n\\item Another way to define variance (i.e. mean \\qu{distance} from the mean) could be $\\expe{\\abss{X - \\mu}}$\n\\item Another way to define variance (i.e. mean \\qu{distance} from the mean) could be $\\expe{X - \\mu}$\n\\item Another way to define variance (i.e. mean \\qu{distance} from the mean) could be $\\expe{(X - \\mu)^{100}}$\n\\item $\\expe{X^2} = 5.25 + 4.25^2 = 23.3125$\n\\item $\\expe{X^2} = 5.25 - 4.25^2 = -12.8125$\n\\item $\\expe{X^2} = 5.25^2 - 4.25^2 = 9.5$\\\\\n\nFor the rest of these questions let $Y$ denote the rv for the following game. You play the game $X$ but you have to pay a 20\\% of the winnings to the casino, then after the tax is taken, you have to pay \\$4 to the casino.\n\n\\item $X \\equalsindist Y$\n\\item $X, Y$ are independent rv's\n\\item $Y$ is a \\qu{fair game} for you (the player)\n\\item $\\var{Y} = 0.8\\sigsq$\n\\item $\\sd{Y} = 0.8\\sigma$\n\\item The probability of winning money if you play the game $Y$ is 3/8\n\\item $\\var{X + Y}$ would have a non-zero covariance term in its expression\n\\end{enumerate}\n\\eenum\\instr\\pagebreak\n\n%%%%%%%%%%%%%%%%%%\n\\begin{wrapfigure}{R}{2in}\n\\includegraphics[width=1.5in]{spinner.png}\n\\end{wrapfigure} \\problem\\timedsection{9} \\ingray{Consider a game where someone spins the spinner pictured on the right. The numbers represent payouts in dollars. The spinner has four colors: red, blue, green, yellow. Red payouts are 2,4, or 8; blue payouts are 5 or 7; green payouts are 3 or 6; yellow only pays out 1. Let $X$ be the rv whose realization values are the payouts. Assume the spinner is fair. In this rv, $\\mu = 4.5$ and $\\support{X} = \\braces{1, 2,..., 8}$. The variance is $\\sigsq := \\var{X} = 5.25$ and $\\sigma := \\sd{X} = 2.29$ rounded to the nearest two digits.} Also consider playing this game $n = 1000$ times where the spinner is reset to the same position and you flick it with approximately the same force each time. The payouts for these $n$ games are denoted by rv's $\\Xoneton$.\n\n\\vspace{-0.2cm}\\benum\\truefalsesubquestionwithpoints{11} \n\\begin{enumerate}[(a)]\n\\item $\\Xoneton \\iid$\n\\item $\\Xoneton \\inddist$\n\n\\item The total winnings after all $n$ games is expected to be $4500$\n\\item The variance in the total winnings after all $n$ games is 5250\n\\item The standard deviation in the total winnings after all $n$ games is 72.46 rounded to the nearest two digits.\n\\item The standard deviation in the total winnings after all $n$ games is 2290\n\n\\item The average winnings per game after all $n$ games is expected to be $4.5$\n\\item The variance in the average winnings per game after all $n$ games is 0.00525\n\\item The standard deviation in the average winnings per game after all $n$ games is 0.00229 rounded to the nearest 3 digits.\n\\item The standard deviation in the average winnings per game after all $n$ games is 0.0724 rounded to the nearest 3 digits.\n\\item As $n$ gets larger, the average winnings per game after all $n$ games approaches a rv centered at $4.5$ with variance shrinking to zero.\n\\end{enumerate}\n\\eenum\\instr\\pagebreak\n\n\n%%%%%%%%%%%%%%%%%%\n\\problem\\timedsection{9} In the previous game, the probability of winning is $p := 3/8$ and you played $n = 1000$ times. Each game was $\\iid$. Let $\\Xoneton$ now denote whether each game was won or not (1 = win and 0 = lose). These are different rv's than the previous problem! Let $T$ denote the total number of wins out over the $n$ games.\n\n\\vspace{-0.2cm}\\benum\\truefalsesubquestionwithpoints{17} \n\\begin{enumerate}[(a)]\n\\item $\\Xoneton \\iid$\n\\item $X_{17} \\sim \\bernoulli{3/8}$\n\\item $X_{17} \\sim \\bernoulli{5/8}$\n\\item $T \\sim \\binomial{n}{p}$\n\\item $T \\sim \\hypergeom{n}{np}{n}$ \n\\item $T$ is independent of $X_{17}$\n\\item $\\prob{T = 17} = 3/8$\n\\item $\\prob{T = 17} = \\binom{1000}{17} (3/8)^{17} (5/8)^{983}$\n\\item $\\prob{X_{17} = 17} = 3/8$\n\\item $\\prob{X_{17} = 17} = (3/8)^{17}$\n\\item $\\prob{X_{17} = 17} = \\binom{1000}{17} (3/8)^{17} (5/8)^{983}$\n\\item $\\expe{T} = (3/8)^{17}$\n\\item $\\expe{T} = 1000 \\times 3/8$\n\\item $\\var{T} = 1000 \\times 3/8 \\times 5/8$\n\\item $\\var{T} = \\sum_{t=1}^{1000} \\binom{1000}{t} (3/8)^{t} (5/8)^{1000 - t}$\n\\item $\\var{T} = \\sum_{t=1}^{1000} t \\binom{1000}{t} (3/8)^{t} (5/8)^{1000 - t}$\n\\item If you kept playing this game until you won (i.e. no limit on $n$, the number of games), then the number of games total played would be a memoryless rv.\n\\end{enumerate}\n\\eenum\\instr\\pagebreak\n\n\n%%%%%%%%%%%%%%%%%%\n\\problem\\timedsection{10} Consider a cup with $N = 8$ coins inside and $K = 3$ coins are marked with a permanent marker. Let $p := 3/8$ denote the proportion of marked coins of the total number of coins. You shake the cup and then reach in and pull out $n = 6$ coins so 6 are in your hand and 2 are left in the cup. Let $X_1, X_2, \\ldots, X_6$ denote the rv that models if each of the 6 coins in your hand are marked or unmarked ($X_i = 1$ if marked and $X_i = 0$ if unmarked). Let $T$ denote the number of coins in your hand that are marked with the permanent marker. Thus, $T$ is the sum of $X_1, X_2, \\ldots, X_6$.\n\n\\vspace{-0.2cm}\\benum\\truefalsesubquestionwithpoints{16} \n\\begin{enumerate}[(a)]\n\\item $X_1, X_2, \\ldots, X_6 \\iid$\n\\item $X_{3} \\equalsindist X_6$\n\\item $X_{3} \\sim \\bernoulli{p}$\n\\item $X_{3} \\sim \\bernoulli{K/N}$\n\\item $T \\sim \\binomial{n}{p}$\n\\item $T \\sim \\binomial{N}{p}$\n\\item $T \\sim \\hypergeom{n}{K}{N}$ \n\\item $T \\sim \\hypergeom{n}{np}{N}$ \n\\item $T$ is independent of $X_{3}$\n\\item $\\support{T} = \\braces{1, 2, 3, 4, 5, 6, 7, 8}$\n\\item $\\support{T} = \\braces{1, 2, 3, 4, 5, 6}$\n\\item $\\support{T} = \\braces{1, 2, 3}$\n\\item $\\prob{T = t} = \\displaystyle \\frac{\\binom{3}{t}\\binom{5}{6 - t}}{\\binom{8}{6}}$\n\\item $\\expe{T} = np$\n\\item $\\expe{T} = n\\frac{K}{N}$\n\\item Given a calculator and enough time, $\\var{T}$ can be computed given the information on this page\n\\end{enumerate}\n\\eenum\\instr\\pagebreak\n\n\\end{document}\n\n\n", "meta": {"hexsha": "0e139511598030aab711415b3ba706d3d5452b3c", "size": 14176, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "exams/midterm2/midterm2.tex", "max_stars_repo_name": "kapelner/QC_MATH_241_Fall_2021", "max_stars_repo_head_hexsha": "576398d1429317ce7e38c1e6c39c377d18f7cd9e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-08-30T03:05:47.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-30T03:05:47.000Z", "max_issues_repo_path": "exams/midterm2/midterm2.tex", "max_issues_repo_name": "kapelner/QC_MATH_241_Fall_2021", "max_issues_repo_head_hexsha": "576398d1429317ce7e38c1e6c39c377d18f7cd9e", "max_issues_repo_licenses": ["MIT"], "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/midterm2/midterm2.tex", "max_forks_repo_name": "kapelner/QC_MATH_241_Fall_2021", "max_forks_repo_head_hexsha": "576398d1429317ce7e38c1e6c39c377d18f7cd9e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-08-29T05:45:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-29T06:49:47.000Z", "avg_line_length": 62.449339207, "max_line_length": 1004, "alphanum_fraction": 0.7053470655, "num_tokens": 4487, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41869690935568665, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.19140173048867778}}
{"text": "%\\renewcommand*{\\descriptionlabel}[1]{\\hspace\\labelsep\\normalfont\\sffamily #1}\n\\newenvironment{features}{%\n\\firmlists\\begin{description}}%\n{\\end{description}}\n\\newcommand\\feat[1]{\\item[-- \\normalfont\\itshape #1]}\n\n\n\\chapter{Features supported by \\pharmml}\n\\label{chap:scope}\n\n\n\\section{Introduction}\n\nThe scope of pharmacometric models is very wide, as such models can be empirical as well as\nmechanistic; describe continuous as well as discrete data types; and be deterministic, stochastic\nor a mixture of both. It is a challenging endeavour to accommodate this variety of possibilities\nunder one computational standard, therefore it is indispensable to split the task into multiple\nsteps of subsequent specifications and to define precisely the scope of every release.\n\nIn this chapter we define the scope of the functionality in\n\\pharmml. In particular what information a \\pharmml document can\nrepresent and what it cannot. As is common practise in software\nengineering we have described the functionality as a set of\n``features''. These features are said to be \\emph{current} if they are\nprovided by this release of \\pharmml, \\emph{planned} if they are not\nin the current version, but planned for a future release.\n% and \\emph{not include} if we wish to highlight the fact that we believe \\pharmml\n%will not include this feature. \nIt is important to remember that this\nspecification is just the beginning of \\pharmml and over time we\nexpect many of the features currently out of scope to be provided by\nfuture releases of the language.\n\nThe language is organised into three sections, which we believe naturally\ndescribe the logical organisation of a pharmacometric model and its\nassociated tasks. Consequently we have grouped the features to match this\norganisation. The sections are:\n\\begin{description}\n\\item[Model Definition] A description of the model, incl.\\ the structural model, the model\n parameters, relevant covariates, the variability components, and the observations.\n\\item[Trial Design] A description of the design of a clinical trial associated with the model\n (for example a trial from which data is available to estimate the parameters of the model or\n a trial to be simulated with the model).\n\\item[Modelling Steps] A description of steps or tasks performed with\n the model. Typically this describes how the model has been used, for\n example to estimate its parameters or to perform a simulation.\n\\end{description}\n\n\n\\section{Current Features}\n\n\\subsection{General}\n\n\\begin{features}\n\\feat{Metadata annotation} Provides support to enable metadata\ndescriptions of the \\pharmml document.\n\\feat{Extension mechanism} Provides support to enable the extension of\nthe \\pharmml document.\n\\end{features}\n\n\\subsection{Model Definition}\n\n\\subsubsection{Structural Model}\n\n\\pharmml can encode:\n\\begin{features}\n\\feat{A structural model defined by a set of algebraic equations.} Typically the explicit solution to a simple PK model, or a dose-response model.\n\\feat{A structural model defined by a system of ODEs with initial conditions.} Such systems of ODEs can include algebraic equations as well.\n\\feat{A structural model defined in \\sbml format.}\n\\feat{A structural model from an external resource or library.}\n\\feat{Standard PK models} Including those encoded by Monolix \\cite{Bertrand:2008} or PREDPP in NONMEM \\cite{PREDPP:2011}.\n\\feat{Standard PD models.} Including those defined by Monolix \\cite{Bertrand:2008}.\n\\end{features}\n\n\\subsubsection{Covariate Model}\n\n\\pharmml can encode:\n\\begin{features}\n\\feat{Continuous covariates.} These can be sampled from a probability distribution and used with an applied transformation.\n\\feat{Categorical covariates.} These can also be sampled from a probability distribution.\n\\end{features}\n\n\\subsubsection{Parameter Model}\n\n%\\footnote{As described in detail in section \\ref{maths:parameter-model}, the current specification allows encoding of models that are linear in the transformed parameter, which covers the majority of cases in practical applications. This approach is\n%flexible in that one can encode any type of parameter with a distribution that is normal up to a transformation, i.e.\n%normal (identity transformation), log-normal (natural logarithm) or logit-normal (logit tranformation).}\n\n\\pharmml can encode:\n\\begin{features}\n\\feat{The population mean/typical value for a parameter.}\n\\feat{Linear covariate model.}\n\\feat{Random effects at arbitrary levels of variability.}\n\\feat{Correlation of the random effects, described by a correlation or covariance matrix.}\n\\feat{Non-linear parameter models, such as those described in \\cite{Keizer:2011aa}.}\n\\end{features}\n\n\\subsubsection{Variability Model}\n\n\\pharmml supports the following levels of variability:\n\\begin{features}\n\\feat{Between-Subject Variability (BSV).} Aka inter-individual variability (IIV).\n\\feat{Inter-Occasion Variability (IOV).} Such as within-subject variability.\n\\feat{Higher levels of variability above BSV.} Such as variability between countries or centres.\n\\feat{Lower levels of variability below IOV.} Such as variability between sub-occasions within occasions.\n\\end{features}\n\n\\subsubsection{Observations Model}\n\n\\pharmml currently only supports the following observation model:\n\\begin{features}\n\\feat{Continuous observation model.} A residual error model applied to one or more variables in the structural model.\n\\feat{Autocorrelation of the residual errors in a continuous observation model.}\n\\end{features}\n\n\\subsection{Trial Design}\n\n\\pharmml can encode the following features of a trial design \\emph{explicitly}\\footnote{As\nopposed to the implicit trial design definition present within a data file.}:\n\\begin{features}\n\\feat{Bolus dosing.}\n\\feat{Infusion dosing.}\n\\feat{Multiple dosing regimens including mixed bolus and infusion.}\n\\feat{Repeated dosing.}\n\\feat{Dosing at arbitrary time points.}\n\\feat{Steady state dosing.}\n\\feat{Dosing to more than one compartment.}\n\\feat{Cross-over designs.}\n\\feat{Parallel designs.}\n\\feat{Washout periods.}\n\\feat{Run-in periods.}\n\\feat{Occasions -- defined by time interval within a treatment epoch.}\n\\feat{Trials with different centres or other levels of organisation above study groups (aka arms)}\n\\end{features}\n\n\\subsection{Modelling Steps}\n\n\\pharmml can encode the following features related to the task(s) associated with a model:\n\\begin{features}\n\\feat{Estimation utilising the maximum likelihood principle.}\n\\feat{Simulation of the model}\n\\end{features}\n\n\n\\section{Planned Features}\n\n\\subsection{General}\n\n\\begin{features}\n\\feat{Units} Support for unit definitions and unit consistency\nchecking.\n\\end{features}\n\n\\subsection{Model Definition}\n\n\\subsubsection{Covariate Model}\n\n\\pharmml does not support the following covariate related features:\n\\begin{features}\n\\feat{Conditional distributions of continuous covariates.}\n\\feat{Clusters of categorical covariates.}\n\\feat{Selection/exclusion criteria for covariates.}\n\\end{features}\n\n\\subsubsection{Structural Model}\n\n\\pharmml does not support the following model types:\n\\begin{features}\n\\feat{(Hidden) Markov models.}\n\\feat{Delay Differential Equations (DDEs).}\n\\feat{Partial Differential Equations (PDEs).}\n\\feat{Stochastic Differential Equations (SDEs).}\n\\end{features}\n\n\\subsubsection{Observations Model}\n\n\\pharmml does not support the following types of observation models:\n\\begin{features}\n\\feat{Count data models.} Poisson, negative binomial, zero-inflated Poisson models etc.\n\\feat{Nominal and ordered categorical models.} Logistic regression, proportional odds models etc.\n\\feat{Time-to-event models.} Parametric (e.g.\\ exponential, Gompertz, Weibull) or semi-parametric Cox models.\n\\end{features}\n\n\\subsection{Trial Design}\n\n\\pharmml cannot encode the following features in a trial design:\n\\begin{features}\n\\feat{Reset of all or single compartments.}\n\\end{features}\n\n\\subsection{Modelling Steps}\n\n\\pharmml cannot encode the following features related to the task(s) associated with a model:\n\\begin{features}\n\\feat{Bayesian inference methods.}\n%Methods such as Maximum a posteriori (MAP) or Bayesian inference sing Gibbs sampling methods used in tools of the BUGS-family (winBUGS \\cite{Lunn:2002aa}, openBUGS \\cite{Lunn:2009fk}) or JAGS \\cite{JAGS:2003aa}.\n\\feat{Writing estimation results to a file or other external resource.}\n\\feat{Writing simulation results to a file or other external resource.}\n\\feat{Exchange of results from one modelling step to another.} Currently it is not possible to pass on the results of an estimation task to a subsequent estimation step.\n\\feat{Model exploration} Tasks such as sensitivity analysis are not\nsupported.\n\\feat{Optimal design}\n\\end{features}\n\n%\\section{Features not Included}\n%\n%\\subsection{Model Definition}\n%\n%\\subsubsection{Structural Model}\n%\n%\\pharmml cannot encode:\n%\\begin{features}\n%\\feat{Higher order differential equations.}\n%\\feat{Delay Differential Equations (DDEs).}\n%\\feat{Partial Differential Equations (PDEs).}\n%\\feat{Stochastic Differential Equations (SDEs).}\n%\\feat{(Hidden) Markov models.}\n%\\end{features}\n\n%\\subsubsection{Covariate Model}\n%\n%\\pharmml cannot encode:\n%\\begin{features}\n%\\feat{Conditional distributions of continuous covariates.}\n%\\feat{Clusters of categorical covariates.}\n%\\feat{Selection/exclusion criteria for covariates.}\n%\\end{features}\n\n\n\n% \\begin{itemize}\n% \\item\n% ODE based, standard 1-, 2- or 3-compartmental or physiology based PK (PBPK) models\n% \\begin{itemize}\n% \\item\n% defined explicitly as a system of ODE's\n% \\item\n% defined as an SBML model\n% \\end{itemize}\n% \\item\n% algebraic expressions, if analytic solutions are available, e.g. one-compartmental oral model, see section \\ref{sec:structuralModel}\n% \\item\n% using library models, e.g. Monolix \\cite{Bertrand:2008} or PREDPP \\cite{PREDPP:2011}\n% \\end{itemize}\n\n% \\paragraph{Continuous PD models}\n% \\begin{itemize}\n% \\item\n% ODE based -- e.g. turnover models\n% \\item\n% algebraic -- e.g. Emax-models\n% \\item\n% using library models, e.g. Monolix \\cite{Bertrand:2008}\n% \\end{itemize}\n\n\n% \\section{MS Intro}\n\n% Any part of human and animal anatomy and physiology can be subject to pathological changes and eventually diseases. The scope of pharmacometric models, dealing with virtually any type of such cases, is therefore almost without precedence in science. The models can be\n% \\begin{itemize}\n% \\item\n% phenomenological or mechanistic\n% \\item\n% they have to cope both with continuous and discrete data types\n% \\item\n% they are deterministic, stochastic or mixture of both\n% \\item\n% they cover all levels of complexity from the molecular to organ and whole body level\n% \\end{itemize}\n% It is a challenging endeavour to accommodate this variety of possibilities under one computational standard but thanks excellent use cases and other documents created and provided by our DDMoRe partners it seams possible. However it is indispensable to split the task into multiple steps of subsequent specifications and to define precisely the scope of every release. This is exactly the goal of this chapter.\n\n\n% \\section{Components of a pharmacometric model}\n% In the context of PharmML a typical pharmacometric model can be decomposed into the following components\n% \\begin{itemize}\n% \\item\n% Data model\n% \\item\n% Trial design model\n% \\item\n% Structural model\n% \\item\n% Parameter model\n% \\begin{itemize}\n% \\item\n% Covariate model\n% \\item\n% Variability model\n% \\item\n% Correlation of random effects\n% \\end{itemize}\n% \\item\n% Residual error model\n% \\item\n% Observation model\n% \\item\n% Task model\n% \\end{itemize}\n% In the following sections we describe each of these components briefly and list features which are implemented in the current specification and those which will be included in future releases (the latter listed in the subsections \\textit{\\textbf{Out of scope}}).\n\n% \\section{Features in and outside of current scope}\n\n% \\subsection{Data model}\n\n% Coming soon...\n\n\n% \\subparagraph{Out of scope}\n% \\begin{itemize}\n% \\item\n% trials with different centres or other levels of organisation above study groups (aka arms)\n% \\item\n% levels of variability below one level of inter-occasion variability\n% \\item\n% dose escalation methods, e.g. accelerated titration designs or pharmacologically guided dose escalation\n% \\item\n% complex dosing models, e.g. Higuchi or Weibull release models\n% \\item\n% reset of all or single compartments\n% \\item\n% output compartment definition\n% \\end{itemize}\n\n% \\subsection{Structural model}\n% In the current specification only continuous models are considered and any model which can be formulated using\n% as system of ordinary differential equations (ODE) or algebraic equations can be implemented. More precisely, the following options are available\n% \\paragraph{PK models}\n\n% \\begin{itemize}\n% \\item\n% ODE based, standard 1-, 2- or 3-compartmental or physiology based PK (PBPK) models\n% \\begin{itemize}\n% \\item\n% defined explicitly as a system of ODE's\n% \\item\n% defined as an SBML model\n% \\end{itemize}\n% \\item\n% algebraic expressions, if analytic solutions are available, e.g. one-compartmental oral model, see section \\ref{sec:structuralModel}\n% \\item\n% using library models, e.g. Monolix \\cite{Bertrand:2008} or PREDPP \\cite{PREDPP:2011}\n% \\end{itemize}\n\n% \\paragraph{Continuous PD models}\n% \\begin{itemize}\n% \\item\n% ODE based -- e.g. turnover models\n% \\item\n% algebraic -- e.g. Emax-models\n% \\item\n% using library models, e.g. Monolix \\cite{Bertrand:2008}\n% \\end{itemize}\n\n% \\subparagraph{Out of scope}\n% The following model types or approaches are planned for a subsequent release\n% \\begin{itemize}\n% \\item\n% Discrete data models\n% \\begin{itemize}\n% \\item\n% nominal and ordered categorical models e.g. logistic regression, proportional odds models etc.\n% \\item\n% count data models, e.g. Poisson, negative binomial, zero-inflated Poisson models etc.\n% \\item\n% time-to-event models, e.g. parametric (e.g. exponential, Gompertz, Weibull) or semi-parametric Cox model\n% \\end{itemize}\n% \\item\n% (Hidden) Markov models\n% \\item\n% stochastic differential equations (SDE)\n% \\item\n% delay differential equations (SDE)\n% \\item\n% partial differential equations (PDE)\n% \\end{itemize}\n\n\n% \\subsection{Parameter model}\n% As described in detail in section \\ref{sec:parameterModel}, the current specification allows for encoding of\n% models which are linear in the transformed parameter which covers a majority of cases in practical applications.\n% This approach is flexible in that one can encode any type of parameter which distribution is normal up to a transformation,\n% i.e. normal (identity transformation), log-normal (natural logarithm) or logit-normal (logit tranformation).\\\\\n% The parameter model consists of the following elements\n% \\begin{itemize}\n% \\item\n% population/typical value for the parameter\n% \\item\n% continuous and categorical covariate model (covariates can be sampled from probability distributions)\n% %---- estimating categorical distribution from external data file \\\\\n% %---- sampling from known categorical distribution \\\\\n% \\item\n% random effects of arbitrary level, see section \\ref{sec:variabilityModel} for details\n% \\item\n% correlation of random effects, described by a correlation or covariance matrix\n% \\end{itemize}\n\n% \\subparagraph{Out of scope}\n% The following features are planned for a subsequent release:\n% \\begin{itemize}\n% \\item\n% non-linear parameter models, such as those described in \\cite{Keizer:2011aa}\n% \\item\n% autocorrelation of residual errors\n% \\item\n% clusters of categorical covariates\n% \\item\n% conditional distributions of continuous covariates\n% \\item\n% selection/exclusion criteria for covariates\n% \\end{itemize}\n\n\n% \\subsection{Residual error model}\n% PharmML is flexible with respect to defining residual error models. Currently this can be done\n% only explicitly as there is no external library, see section \\ref{sec:residualErrorModel}.\n% For a future release the creation of an external library is planned.\n\n% \\subsection{Observation model}\n% The following information can be stored in PharmML\n% \\begin{itemize}\n% \\item\n% model variable to be observed, both for continuous PK or PD models\n% \\item\n% time points for every model varaiable at which predictions are to be estimated\n% \\end{itemize}\n\n% \\subsection{Task model}\n% This model describes a combination of the operations one can perform on the model, such as:\n% \\begin{itemize}\n% \\item\n% simulation of a trial design, defined explicitly in PharmML or encoded in a data file\n% \\item\n% estimation of population or individual parameters\n% \\begin{itemize}\n% \\item\n% using the trial design designed in PharmML and objective data encoded in a data file\n% \\item\n% using the trial design and objective data encoded in a data file\n% \\end{itemize}\n% \\item\n% model exploration, e.g. sensitivity analysis\n% \\end{itemize}\n\n% \\subparagraph{Out of scope}\n% \\begin{itemize}\n% \\item\n% export of simulation results to an external file\n% \\item\n% export of estimation results to an external file\n% \\item\n% transfer of results from one modelling step to another, for example transferring estimation results to a simulation step\n% \\end{itemize}\n\n\n% \\paragraph{Inference methods supported in PharmML}\n% In general the current specification is restricted to estimation methods utilising the maximum likelihood principle. Not in the scope are Bayesian inference methods such as Maximum a posteriori (MAP) or Bayesian inference sing Gibbs sampling methods used in tools of the BUGS-family (winBUGS \\cite{Lunn:2002aa}, openBUGS \\cite{Lunn:2009fk}) or JAGS \\cite{JAGS:2003aa}.\n\n\n\n% %\\paragraph{Covariate model}\n% %Covariate model is barely covered so far. See also \\cite{Keizer:2011aa}. Missing are following features:\\\\\n% %For categorical covariates:\\\\\n% %-- categorical distribution of categorical covariates \\\\\n% %---- estimating categorical distribution from external data file \\\\\n% %---- sampling from known categorical distribution \\\\\n% %---- clusters of categorical covariates \\\\\n% %For continuous covariates:\\\\\n% %-- power-normal distribution for continuous covariates \\\\\n% %---- estimating parameters $\\lambda$,$\\mu$,$\\sigma$ from external data file \\\\\n% %---- sampling from known power-normal distribution \\\\\n% %---- conditional distribution of continuous covariates \\\\\n% %------ none \\\\\n% %------ defined \\\\\n% %------ to be estimated \\\\\n% %---- selecting criteria for continuous covariates \\\\\n% %---- dependent distribution of continuous covariates \\\\\n% %---- correlated continuous covariates \\\\\n% %For both types: \\\\\n% %-- selection/exclusion criteria missing \\\\\n% %\n% %\\subsection{Observation model}\n% %- Name\\\\\n% %- Units\\\\\n% %- Observation types - continuous/discrete\\\\\n% %- Symbol of predicted output\\\\\n% %\n% %\\subsection{Task model}\n% %-- Combination of tasks, e.g.\\\\\n% %1. estimate distribution of covariate from experimental data\\\\\n% %2. Simulation task using the estimated PDF\n% %\n% %\n% %\\subsection{Not covered so far}\n% %- correlation of residual errors \\\\\n% %---- number models of relevant models identified and described in Use Case document\\\\\n% %\n\n\n% \\input{input/features.tex}\n", "meta": {"hexsha": "45bb5cbe8f75dc5c6eb99ec2caba04c95c0260a6", "size": 19013, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "input/Scope.tex", "max_stars_repo_name": "pharmml/pharmml-spec", "max_stars_repo_head_hexsha": "b102aedd082e3114df26a072ba9fad2d1520e25f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-01-26T13:17:54.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-26T13:17:54.000Z", "max_issues_repo_path": "input/Scope.tex", "max_issues_repo_name": "pharmml/pharmml-spec", "max_issues_repo_head_hexsha": "b102aedd082e3114df26a072ba9fad2d1520e25f", "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": "input/Scope.tex", "max_forks_repo_name": "pharmml/pharmml-spec", "max_forks_repo_head_hexsha": "b102aedd082e3114df26a072ba9fad2d1520e25f", "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.026, "max_line_length": 412, "alphanum_fraction": 0.7732078052, "num_tokens": 4651, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.37387583672470853, "lm_q1q2_score": 0.19131847374969674}}
{"text": "% $Id: aboutcryptool.tex 3714 2016-04-08 18:34:16Z esslinger $\n% ............................................................................\n% TEXT OF THE 2nd PAGE (Overview)\n%\n% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n\\clearpage\\phantomsection\n\n\\addcontentsline{toc}{chapter}{Overview about the Content of the CrypTool Book}\n\\chapter*{Overview about the Content of the CrypTool Book} \n\n\\parskip 4pt\n%\\vskip +12 pt\nThe rapid spread of the Internet has led to intensified research in the\ntechnologies involved, especially within the area of cryptography where a good\ndeal of new knowledge has arisen.\n\nIn this {\\em book accompanying the CrypTool programs} \\index{CrypTool}\nyou will find predominantly mathematically oriented information on using\ncryptographic procedures. Also included are many sample code pieces written in the\ncomputer algebra system {\\bf SageMath}\\index{SageMath} (see appendix~\\ref{s:appendix-using-sage}).\nThe main chapters have been written by various {\\bf authors}\n(see appendix~\\ref{s:appendix-authors}) %\\hyperlink{appendix-authors}{authors}\nand are therefore independent from one another. At the end of most chapters\nyou will find references and web links.\nThe sections have been enriched with many {\\em footnotes}. Within the footnotes\nyou can see where the described functions can be called in the different CrypTool\nversions.\n\nThe \\hyperlink{Kapitel_1}{first chapter} explains the principles of symmetric\nand asymmetric {\\bf encryption} and definitions for their resistibility.\n\nBecause of didactic reasons the \\hyperlink{Kapitel_PaperandPencil}\n{second chapter} gives an exhaustive overview\nabout {\\bf paper and pencil encryption methods}.\n\nBig parts of this book are dedicated to the fascinating topic of \n{\\bf prime numbers} (chap. \\ref{Label_Kapitel_Primes}).\n%\\hyperlink{Kapitel_2}{{\\bf prime numbers}}. \nUsing numerous examples, {\\bf modular arithmetic} and \n{\\bf elementary number theory} (chap. \\ref{Chapter_ElementaryNT})\nare introduced. The features of the {\\bf RSA procedure} are a key aspect.\n\nBy reading chapter \\ref{Chapter_ModernCryptography}\nyou'll gain an insight into the mathematical ideas and concepts behind \n{\\bf modern cryptography}.\n\nChapter \\ref{Chapter_Hashes-and-Digital-Signatures} gives\nan overview about the status of attacks against modern {\\bf hash algorithms}\nand is then shortly devoted to {\\bf digital signatures}, \nwhich are an essential component of e-business applications.\n\nChapter \\ref{Chapter_EllipticCurves} describes {\\bf elliptic curves}:\nThey could be used as an alternative to RSA and in addition are extremely\nwell suited for implementation on smartcards.\n\nChapter \\ref{Chapter_BitCiphers} introduces {\\bf Boolean algebra}.\nBoolean algebra is the foundation for most modern, symmetric encryption algorithms\nas these operate on bit streams and bit groups. Principal construction\nmethods are described and implemented in SageMath.\n\nChapter \\ref{Chapter_HomomorphicCiphers} describes {\\bf homomorphic crypto\nfunctions}: They are a modern research topic which got especial attention\nin the course of cloud computing.\n\nThe \\hyperlink{Chapter_Crypto2020}{last chapter} {\\bf Crypto2020}\ndiscusses threats for currently used cryptographic methods and introduces\nalternative research approaches to achieve long-term security\nof cryptographic schemes.\n\nWhereas the CrypTool \\textit{e-learning programs}\\index{e-learning} motivate\nand teach you how to use cryptography in practice, the \\textit{book} provides\nthose interested in the subject with a deeper understanding of the mathematical\nalgorithms used -- trying to do it in an instructive way.\n\nWithin the {\\bf appendices}\n\\ref{s:appendix-menu-overview-CT1},\n\\ref{s:appendix-template-overview-CT2},\n\\ref{s:appendix-function-overview-JCT}, and\n\\ref{s:appendix-function-overview-CTO}\nyou can gain a fast overview about the functions delivered by the different\nCrypTool variants\\index{CrypTool 1}\\index{CrypTool 2}\\index{JCrypTool} via:\n\\begin{itemize}\n \\item the function list and\n the \\hyperlink{appendix-menu-overview-CT1}\n {menu tree of CrypTool 1 (CT1)},\n \\item the function list and\n the \\hyperlink{appendix-template-overview-CT2}\n {templates in CrypTool 2 (CT2)},\n \\item the \\hyperlink{appendix-function-overview-JCT}\n {function list of JCrypTool (JCT)}, and\n \\item the \\hyperlink{appendix-function-overview-CTO}\n {function list of CrypTool-Online (CTO)}.\n\\end{itemize}\n\n% Bernhard Esslinger, Matthias B\\\"uger, Bartol Filipovic, Henrik Koy, \n% Roger Oyono and J\\\"org Cornelius Schneider\nThe authors would like to take this opportunity to thank their colleagues \nin the particular companies and at the universities of Bochum, Darmstadt,\nFrankfurt, Gie\\ss en, Karlsruhe and Siegen.\n\n\\enlargethispage{12pt}\nAs with the e-learning program CrypTool\\index{CrypTool}, the quality of the \nbook is enhanced by your suggestions and ideas for improvement. \nWe look forward to your feedback.\n\n\n% Local Variables:\n% TeX-master: \"../script-en.tex\"\n% End:\n", "meta": {"hexsha": "d532863c57238129e2c4103307ccdf9a15a5a802", "size": 5121, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "trunk/script/en/chapters/aboutcryptool.tex", "max_stars_repo_name": "flomar/CrypTool-VS2015", "max_stars_repo_head_hexsha": "6468257af2e1002418882f22a9ed9fabddde096d", "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": "trunk/script/en/chapters/aboutcryptool.tex", "max_issues_repo_name": "flomar/CrypTool-VS2015", "max_issues_repo_head_hexsha": "6468257af2e1002418882f22a9ed9fabddde096d", "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": "trunk/script/en/chapters/aboutcryptool.tex", "max_forks_repo_name": "flomar/CrypTool-VS2015", "max_forks_repo_head_hexsha": "6468257af2e1002418882f22a9ed9fabddde096d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2016-07-02T12:59:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-02T14:58:30.000Z", "avg_line_length": 46.1351351351, "max_line_length": 98, "alphanum_fraction": 0.7535637571, "num_tokens": 1211, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46101677931231594, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.19127532962962357}}
{"text": "%\\documentclass[12pt]{article}\n\\documentclass[12pt,landscape]{article}\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 / 650 Fall \\the\\year{} \\\\ Midterm Examination One}\n\\author{Professor Adam Kapelner}\n\n\\date{Thursday, October 7, \\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}\nThis exam is 70 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. Within each problem, I recommend considering the questions that are easy first and then circling back to evaluate the harder ones. 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{10} These are questions about indicator functions. Let $a,b \\in \\reals$ and $b > a$. And let $X$ be a discrete rv.\n\n\\vspace{-0.2cm}\\benum\\truefalsesubquestionwithpoints{18} \n\n\\begin{enumerate}[(a)]\n\\item $\\sum_{x \\in \\reals} \\indic{x \\in \\braces{a}} = a$\n\\item $\\sum_{x \\in \\reals} \\indic{x \\in \\braces{a}} = 1$\n\\item $\\sum_{x \\in \\reals} a\\indic{x \\in \\braces{a}} = a$\n\\item $\\sum_{x \\in \\reals} a\\indic{x \\in \\braces{a}} = 1$\n\\item $\\prod_{x \\in \\reals} a\\indic{x \\in \\braces{a}} = a$\n\\item $\\prod_{x \\in \\reals} a\\indic{x \\in \\braces{a}} = 1$ \n\n\\item $\\int_{\\reals} a\\indic{x \\in [a,b]} = a$ \n\\item $\\int_{\\reals} a\\indic{x \\in [a,b]} = b$ \n\\item $\\int_{\\reals} a\\indic{x \\in [a,b]} = b-a$\n\\item $\\int_0^1 \\indic{x \\in [a,b]} = b-a$\n\n\n\n\\item $p(x) = p^{old}(x)\\indic{x \\in \\support{X}}$\n\\item $\\sum_{x \\in \\reals} p^{old}(x) = 1$\n\\item $\\sum_{x \\in \\support{X}} p^{old}(x) = 1$\n\n\\item $\\sum_{x \\in \\naturals} p(x) = 1$\n\\item $\\sum_{x \\in \\integers} p(x) = 1$\n\n\\item $\\int_{\\reals} p^{old}(x) = 1$\n\\item $\\int_{\\support{X}} p^{old}(x) = 1$\n\n\\item $\\sum_{x \\in \\support{X}} p^{old}(x)^2 = 1$\n\n\\end{enumerate}\n\\eenum\\instr\\pagebreak\n\n\n%%%%%%%%%%%%%%%%%%\n\\problem\\timedsection{11} Let $X \\sim U(\\braces{1,2,3})$ and $Y \\sim U(\\braces{-1,-2,-3})$ and $T = X + Y$.\n\n\\vspace{-0.2cm}\\benum\\truefalsesubquestionwithpoints{19} \n\n\\begin{enumerate}[(a)]\n\\item $\\sum_{x \\in \\reals} p_{X,Y}(x,y) = 1$\n\\item $p_{X,Y}$ has at most 9 $x,y$ input pairs that produce nonzero values\n\\item $p_X^{old}(x) = 1/3$\n\\item $p_Y^{old}(y) = 1/3$\n\\item $p_T^{old}(t) = 1/9$ if $X,Y$ are independent.\n\\item $p_T^{old}(2) = 1/9$ if $X,Y$ are independent.\n\\item $p_T(t) = p_{X,Y}(x,y) \\star p_{X,Y}(x,y)$\n\\item $p_T(t) = \\sum_{x \\in \\reals} \\sum_{y \\in \\reals} p_{X,Y}(x,y)$\n\\item The expectation of $T$ is 0 if $X,Y$ are independent.\n\\item The expectation of $T$ is 0 regardless of the dependence relationship of $X, Y$.\n\\item $\\support{T} = \\braces{-2, -1, 0, 1, 2}$ if $X,Y$ are independent.\n\\item $\\support{T} = \\braces{-2, -1, 0, 1, 2}$ regardless of the dependence relationship of $X, Y$.\n\\item $T$ could be a degenerate rv.\n\\item You can compute $p_T(t)$ for all $t \\in \\reals$ if $X,Y$ are independent given the information provided.\n\\item You can compute $p_T(t)$ for all $t \\in \\reals$ if $X,Y$ are dependent given the information provided.\n\\item $\\cov{X}{Y} = 0$ if $X,Y$ are independent.\n\\item $\\cov{X}{T} = 0$ if $X,Y$ are independent.\n\\item $\\cov{Y}{T} = \\expe{YT} - \\expe{Y}\\expe{T}$ if $X,Y$ are independent.\n\\item $\\cov{X}{Y} = \\cov{Y}{X}$ if $X,Y$ are dependent.\n\\end{enumerate}\n\\eenum\\instr\\pagebreak\n\n%%%%%%%%%%%%%%%%%%\n\\problem\\timedsection{10} Let $X \\sim \\geometric{p_x}$ independent of $Y \\sim \\geometric{p_y}$ and $T = X + Y$.\n\n\\vspace{-0.2cm}\\benum\\truefalsesubquestionwithpoints{15} \n\n\\begin{enumerate}[(a)]\n\\item The PMF of $T$ can be derived using one of the discrete convolution formulas\n\\item $\\support{X} = \\support{T}$\n\\item If $p_x > p_y$ it is likely that $X > Y$\n\\item $T \\sim \\geometric{p_x+p_y}$\n\\item $T \\sim \\negbin{2}{p_x+p_y}$\n\\item If $p_x = p_y = 1$, $T$ is a degenerate rv\n\\item If $p_x = p_y = 0$, $T$ is a degenerate rv\n\\item If $p_x = p_y = \\half$ then $T \\sim \\negbin{2}{\\half}$\n\\item If $p_x = p_y = \\half$ then $\\prob{X = Y} > 0$\n\\item If $p_x = p_y = \\half$ then $\\prob{X = Y} = \\frac{3}{4}$\n\\item If $p_x = p_y = \\half$ then $\\prob{X = Y} = \\oneover{3}$\n\\item If $p_x = p_y = \\half$ then $\\prob{X = Y} = \\half$\n\\item If $p_x = p_y = \\half$ then $\\prob{X = Y} = \\oneover{4}$\n\\item If $p_x = p_y = \\half$ then $\\prob{X = Y} = \\oneover{8}$\n\\item If $p_x = p_y = \\half$ then $\\prob{X = Y} = \\oneover{16}$\n\\end{enumerate}\n\\eenum\\instr\\pagebreak\n\n%%%%%%%%%%%%%%%%%%\n\\problem\\timedsection{10} Let $X \\sim \\geometric{p}$ independent of $Y \\sim \\geometric{p}$ and $T = X + Y$.\n\n\\vspace{-0.2cm}\\benum\\truefalsesubquestionwithpoints{13} \n\n\\begin{enumerate}[(a)]\n%\\item $\\prob{T = 6} = 7(1-p)^7 p^2$\n%\\item $\\prob{T = 6} = 7(1-p)^6 p^2$\n%\\item $\\prob{T = 6} = 6(1-p)^7 p^2$\n%\\item $\\prob{T = 6} = 6(1-p)^6 p^2$\n\\item $p_{X\\,|\\,T}(x,t) = p_{X,T}(x,t)$\n\\item $p_{X\\,|\\,T}(x,t) = p_{X,Y}(x,t) / p_T(t)$\n\\item $p_{X\\,|\\,T}(x,t) = p_{X,Y}(x,t-x) / p_T(t)$\n\\item $p_{X\\,|\\,T}(x,t) = \\displaystyle \\frac{(1-p)^x (1-p)^{t-x}}{(t+1) (1-p)^t}$\n\\item $p_{X\\,|\\,T}(x,t) = \\displaystyle \\frac{(1-p)^x (1-p)^{t-x}}{(t+1) (1-p)^t p^2}$\n\\item $p_{X\\,|\\,T}(x,t) = \\displaystyle \\frac{(1-p)^x (1-p)^{t-x}}{t (1-p)^{t+1}}$\n\\item $p_{X\\,|\\,T}(x,t) = \\displaystyle \\frac{(1-p)^x (1-p)^{t-x}}{t (1-p)^{t+1} p^2}$\n\\item $p_{X\\,|\\,T}(x,t)$ is a geometric rv\n\\item $p_{X\\,|\\,T}(x,t)$ is a negative binomial rv\n\\item $p_{X\\,|\\,T}(x,t)$ is a binomial rv\n\\item $p_{X\\,|\\,T}(x,t)$ is a poisson rv\n\\item $p_{X\\,|\\,T}(x,t)$ is a uniform discrete rv\n\\item $p_{X\\,|\\,T}(x,t)$ is a degenerate rv\n\\end{enumerate}\n\\eenum\\instr\\pagebreak\n\n\n\n\n\n%%%%%%%%%%%%%%%%%%\n\\problem\\timedsection{7} Let $\\X = \\bracks{\\Xoneton}^\\top \\sim p(\\x)$ and $\\expe{\\X} = \\zerovec_n$.\n\n\\vspace{-0.2cm}\\benum\\truefalsesubquestionwithpoints{10} \n\n\\begin{enumerate}[(a)]\n\\item If $\\A$ be an $m \\times n$ matrix of constants, then $\\expe{\\A\\X} = \\zerovec_m$\n\\item $\\var{\\X}$ is an $n \\times n$ matrix with entries $\\expe{X_i X_j}$ at row $i$ and column $j$\n\\item $\\var{\\X}$ can be written as a quadratic form\n\\item $\\var{\\X}$ can be written as the expectation of an inner product \n\\item $\\var{\\X}$ can be written as the expectation of an outer product \n\\item If $\\Xoneton \\inddist$ then $\\var{\\X} = \\I_n$\n\\item There exists a $p(\\x)$ where $\\var{\\X}$ is \\emph{not} symmetric\n\\item There exists a $p(\\x)$ where $\\var{\\onevec^\\top \\X} > \\sum_{i=1}^n \\var{X_i}$\n\\item There exists a $p(\\x)$ where $\\var{\\onevec^\\top \\X} = \\sum_{i=1}^n \\var{X_i}$\n\\item There exists a $p(\\x)$ where $\\var{\\onevec^\\top \\X} < \\sum_{i=1}^n \\var{X_i}$\n\\end{enumerate}\n\\eenum\\instr\\pagebreak\n\n%%%%%%%%%%%%%%%%%%\n\\problem\\timedsection{10} Let $X_1 \\sim \\binomial{n_1}{p_1}$ independent of $X_2 \\sim \\binomial{n_2}{p_2}$ and consider the difference $D = X_1 - X_2 \\sim p_D(d)$. Let $Y = -X_2$.\n\n\\vspace{-0.2cm}\\benum\\truefalsesubquestionwithpoints{10} \n\n\\begin{enumerate}[(a)]\n\\item If $n_1$ was large and $p_1 \\approx 0$, then the PMF of $X_1$ can be approximated with low error by $\\poisson{n_1 p_1}$\n\\item $X_1 \\sim \\displaystyle \\binom{n_1}{x} p_1^x (1-p_1)^{n_1 - x} \\indic{x \\in \\braces{0, 1, \\ldots, n_1}}$\n\\item $X_2 \\sim \\displaystyle \\binom{n_2}{x} p_2^x (1-p_2)^{n_2 - x} \\indic{x \\in \\braces{0, 1, \\ldots, n_2}}$\n\\item $Y \\sim \\displaystyle \\binom{n_2}{-y} p_2^{-y} (1-p_2)^{n_2 + y} \\indic{y \\in \\braces{0, 1, \\ldots, n_2}}$\n\\item $p_D(d) = \\displaystyle\\sum_{x \\in \\reals} p_{X_1}(x) p_{X_2}(d - x)$\n\\item $p_D(d) = \\displaystyle\\sum_{x \\in \\support{X_1}} p_{X_1}^{old}(x) p_{X_2}^{old}(d - x) \\indic{d-x \\in \\braces{0, 1, \\ldots, n_2}}$\n\\item $p_D(d) = \\displaystyle\\sum_{x = 0}^{n_1} \\binom{n_1}{x} p_1^x (1-p_1)^{n_1 - x} \\binom{n_2}{x-d} p_2^{x-d} (1-p_2)^{n_2 + d - x} \\indic{x-d \\in \\braces{0, 1, \\ldots, n_2}}$\n\\item $p_D(d) = \\displaystyle\\sum_{x = d}^{n_1} \\binom{n_1}{x} p_1^x (1-p_1)^{n_1 - x} \\binom{n_2}{x-d} p_2^{x-d} (1-p_2)^{n_2 + d - x}$\n\\item $D$ is a binomial rv\n\\item $D$ is a poisson rv\n\\end{enumerate}\n\\eenum\\instr\\pagebreak\n\n\n%%%%%%%%%%%%%%%%%%\n\\problem\\timedsection{12} A large factory produces marbles with the following color distribution:\n\n\\begin{table}[h]\n\\centering\n\\begin{tabular}{l|lllll}\nColor \t\t\t& Blue & Red & Green & Yellow & Orange \\\\ \\hline\nPercentage\t & 20 & 20 & 30 & 5 & 25\n\\end{tabular}\n\\end{table}\n\n\\noindent You sample 100 marbles randomly from the assembly line. Let $X_b, X_r, X_g, X_y, X_o$ denote the rv's modeling the counts of Blue, Red, Green, Yellow and Orange marbles respectively in your sample and let $\\X$ denote the column vector of those rv's stacked.\n\n\\vspace{-0.2cm}\\benum\\truefalsesubquestionwithpoints{15} \n\n\\begin{enumerate}[(a)]\n\\item $X_b \\sim \\binomial{100}{0.2}$ and $X_r \\sim \\binomial{100}{0.2}$\n\\item $X_b + X_r \\sim \\binomial{200}{0.2}$\n\\item $\\expe{X_b + X_r} = 40$.\n\\item $\\x \\in \\reals$ \n\\item $\\x^\\top \\onevec = 100$ for all $\\x \\in \\support{\\X}$\n\\item $|\\corr{X_b}{X_r}| = |\\cov{X_b}{X_r}|$\n\\item $|\\corr{X_b}{X_r}| > |\\corr{X_y}{X_g}|$\n\\item $p_{X_b\\,|\\,X_r}(x, y)$ is undefined for $y > 100$\n\\item Generally speaking, the more blue marbles in the sample, the less yellow marbles in the sample.\n\\item If it is known that there are 8 blue marbles in the sample, then the number of yellow marbles is expected to be lower as compared to if you have no information about the number of blue marbles in the sample.\\\\\n\nFor the remaining questions, assume that we are told there are 8 blue marbles in the sample.\n\\item The number of yellow marbles will be a drawn from a $\\binomial{92}{0.05}$ rv.\n\\item The number of yellow marbles will be a drawn from a $\\binomial{92}{0.0625}$ rv.\n\\item The number of yellow marbles will be a drawn from a $\\binomial{75}{0.05}$ rv.\n\\item The number of yellow marbles will be a drawn from a $\\binomial{75}{0.0625}$ rv.\n\\item $\\bracks{X_r\\, X_g\\, X_y\\, X_o}^\\top \\sim \\multinomial{4}{92}{\\bv{p}}$ where the vector $\\bv{p}$ can be computed using information provided in this problem.\n\\end{enumerate}\n\\eenum\\instr\\pagebreak\n\n\\end{document}\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n\\problem\\timedsection{5} These are conceptual questions ...\n\n\\vspace{-0.2cm}\\benum\\truefalsesubquestionwithpoints{14} \n\n\\begin{enumerate}[(a)]\n\\item \n\\end{enumerate}\n\\eenum\\instr\\pagebreak\n", "meta": {"hexsha": "0242633f22aa10641c8fb63d8ca3c87351d2b044", "size": 12396, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "exams/midterm1/midterm1.tex", "max_stars_repo_name": "kapelner/QC_MATH_368_Fall_2021", "max_stars_repo_head_hexsha": "08e9ebb9ed83276f4da33f1a9d6169604489a193", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "exams/midterm1/midterm1.tex", "max_issues_repo_name": "kapelner/QC_MATH_368_Fall_2021", "max_issues_repo_head_hexsha": "08e9ebb9ed83276f4da33f1a9d6169604489a193", "max_issues_repo_licenses": ["MIT"], "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_368_Fall_2021", "max_forks_repo_head_hexsha": "08e9ebb9ed83276f4da33f1a9d6169604489a193", "max_forks_repo_licenses": ["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.584, "max_line_length": 1004, "alphanum_fraction": 0.6523878671, "num_tokens": 4527, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46490157137338844, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.19112608911471451}}
{"text": "\\section{Optimization Overview}\n\nMost intermediate representations are organised as \\textit{control flow graphs (CFG)} over \\textit{basic blocks}.\n\n\\subsection{Basic Blocks}\n\nA basic block is a single entry, single exit, straight line code segment. More formally, it is a maximal sequence of instructions with no labels (except at the first instruction) and no jumps (except at the last instruction).\n\nIn the following figure, (a) is a basic block. (b) is not a basic block because it has multiple exits; (c) is not a basic block because it has multiple entries; (d) is not a basic block because it does not represent a straight line code. \n\n\\begin{figure}[htp]\n\\centering\n\\includegraphics[height=6cm]{images/1.png}\n\\caption{Examples and Counterexamples for basic block}\n\\end{figure}\n\nConsider the following example of a single basic block:\n\n\\begin{enumerate}\n \\item L:\n \\item \\(t := 2 * x\\)\n \\item \\(w := t + x\\)\n \\item if w \\(>\\) 3 goto L'\n\\end{enumerate}\n\n\\begin{itemize}\n \\item Is it ok to change (3) to \\(w := 3 * x\\) ?\n It is ok. If addition of two numbers is more expensive as compared to multiplication of a number with a constant, the above change can be considered an optimization.\n \\item Is it ok to change (4) to if x \\(>\\) 1 goto L' ? It is not ok. Because here x is a finite bounded integer and due to overflow, it is possible to have \\(3 * x > 3\\) and not x \\(>\\) 1.\n \\item Is it ok to remove (2) ? Depends on whether variable t is used later in the code or not.\n\\end{itemize}\n\n\\subsection{Control Flow Graph}\n\nA control flow graph is a directed graph with\n\\begin{itemize}\n \\item basic blocks as nodes\n \\item edge from block A to block B if the execution can pass from the last instruction in A to the first instruction in B, for example\n \\begin{itemize}\n \\item the last instruction in A is: jump Lb\n \\item the last instruction in A is: if id1 = id2 then goto Lb\n \\item execution can fall-through from block A to block B\n \\end{itemize}\n\\end{itemize}\n\nConsider the following example of a CFG:\n\n\\begin{figure}[htp]\n\\centering\n\\includegraphics[height=6cm]{images/CFG Example.png}\n\\caption{CFG Example}\n\\end{figure}\n\nThe body of a method (or procedure) can be represented as a control-flow graph. There is one initial node (entry node). All \"return\" nodes are terminal.\n\n\\subsection{Optimization}\nThe optimizations are performed on the control flow graph of the intermediate representation of the code to improve program's resource utilization:\n\n\\begin{itemize}\n \\item Execution Time\n \\item Code Size\n \\item Memory Usage\n \\item Frequency of Disk I/O operations (or network operations)\n \\item Power Consumption (Not same as energy)\n\\end{itemize}\n\nIt is important to remember that optimization should not alter the meaning of the program. It should not alter what the program computes.\n\nFor example, the following optimization changes the meaning of the program and thus, it is not a valid optimization.\n\nw := 3 * x\nif w \\(>\\) 3 goto L \n\ncannot be converted to: if x \\(>\\) 1 goto L\n\n\\subsection{Typical Granularity of Optimization}\n\n\\begin{enumerate}\n \\item \\textbf{Local Optimizations}\n \\begin{itemize}\n \\item applied to a basic block in isolation\n \\item easiest to implement\n \\end{itemize}\n \n \\item \\textbf{Global Optimizations}\n \\begin{itemize}\n \\item applied to a CFG (method body) in isolation while crossing the boundaries of basic blocks\n \\end{itemize}\n \n \\item \\textbf{Inter-Procedural Optimizations}\n \\begin{itemize}\n \\item applied across method (CFG) boundaries\n \\item difficult to implement but usually most effective\n \\end{itemize}\n\\end{enumerate}\n\n\\subsection{Economics of the Optimization}\n\nOptimizations are more of an art rather than science. The current state of the art methods are based on the concept of \"Maximum benefit for minimum cost\" where cost can denote the development and integration costs of the optimization.\n\n\\begin{itemize}\n \\item Some optimizations are hard to implement\n \\item Some optimizations require large compilation time\n \\item Some optimizations have low payoff (the benefits) and it is often difficult to quantify payoff.\n\\end{itemize}\n", "meta": {"hexsha": "03ce40e11461a3e9a9ce79f2e6ee188cd93d44db", "size": 4242, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "module72.tex", "max_stars_repo_name": "arpit-saxena/compiler-notes", "max_stars_repo_head_hexsha": "af3788cde815a5b1d19f206ec8605c0e372c1833", "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": "module72.tex", "max_issues_repo_name": "arpit-saxena/compiler-notes", "max_issues_repo_head_hexsha": "af3788cde815a5b1d19f206ec8605c0e372c1833", "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": "module72.tex", "max_forks_repo_name": "arpit-saxena/compiler-notes", "max_forks_repo_head_hexsha": "af3788cde815a5b1d19f206ec8605c0e372c1833", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2021-02-16T08:32:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-12T19:11:33.000Z", "avg_line_length": 40.0188679245, "max_line_length": 238, "alphanum_fraction": 0.7291371994, "num_tokens": 1045, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49609382947091946, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.19095253976689844}}
{"text": "%% FINAL PROJECT FOR ANALYTICAL MODELS\r\n%% last modifed 05/08/06\r\n\\documentclass[times,12pt,fullpage]{article}\r\n\r\n\\usepackage{hyperref}\r\n\\usepackage{times}\r\n\\usepackage{amsmath,amssymb,amsfonts} % Typical maths resource packages\r\n\r\n\\topmargin 0.0in \\oddsidemargin -0.2in \\evensidemargin 0.8in\r\n\\textwidth 6.80in \\textheight 8.6in\r\n\\parskip 7.6pt\r\n\\parindent 0.25in\r\n\r\n\\makeindex\r\n\\usepackage{fancyhdr}\r\n\\thispagestyle{fancy} \\pagestyle{fancy} \\fancyhf{}\r\n\\lhead{Multiprocessor Modeling Guide} \\chead{} \\rhead{Bennett\r\n\\thepage} \\lfoot{} \\cfoot{} \\rfoot{}\r\n\r\n\\title{Modeling Guide for Multiprocessing Systems}\r\n\\author{Matthew Bennett \\\\\r\n{\\small School of Computing, University of Southern Mississippi} \\\\\r\n{\\small {\\em matthew.bennett@usm.edu} \\ Typeset in \\LaTeX on \\\r\n\\today{} } }\r\n\\date{ }\r\n\r\n\\begin{document}\r\n\\maketitle\r\n\\begin{abstract}\\noindent A tremendous variety of techniques exist for the modeling and\r\nsubsequent simulation of multiprocessor systems. This paper presents\r\nseveral of the approaches of Marsan et al. \\cite{marsan}, in a\r\ncondensed format suitable to practical systems engineer or computer\r\nscientist. Most of these techniques are based upon Generalized\r\nStochastic Petri Nets. The guide covers Bucci's Preemptive Time Nets\r\n\\cite{bucci} to fill in gaps where continuous-time models fail.\r\n\\end{abstract}\r\n\r\n\\section*{Preliminaries}\r\nA working knowledge of multiprocessor architecture, statistical\r\ndistributions, and the modeling technique of General Stochastic\r\nPetri Nets is required. For the latter, Murata \\cite{murata}\r\nprovides a succinct and quick introduction. Markov chains are\r\nmentioned, but the results presented do not require thorough\r\nunderstanding of the device, since the work has already been\r\ncompleted and proven by others.\r\n\r\nMany of the graphs or numerical results in Marsan \\cite{marsan}, and\r\n\\cite{murata} are similar enough to be asymptotically bound for some\r\nconstant. The purpose of this guide is to provide a straightforward\r\nand efficient means of guiding the systems architect through the\r\nmodeling process and on into either simulation or analysis. The\r\nreader may check those sources cited for more in-depth coverage of\r\nvery detailed models, since only the simplest models are presented\r\nwithin.\r\n\r\nA few taxonomic niceties will save the designer some time. The\r\nmodeling phase has been split into five categories (as in\r\n\\cite{marsan}). After the model is developed, the developer may move\r\non to modeling fault tolerance (\\ref{fault tolerance}) or\r\nverification (\\ref{analysis}).\r\n\r\n\\section{Bus-Contention Free Architectures}\r\nThe most trivial multiprocessor system to model is one that\r\nexperiences no contention whatsoever. The canonical example in\r\nacademia (as in \\cite{marsan}) is a crossbar-connected switch\r\nbetween $n$ processor elements and $m$ memory elements. An analog of\r\ncrossbar switch is the Plain Old Telephone System (POTS) exchange.\r\nThese are rarely seen in practice, since the number of switches and\r\ninterconnections increases by a factor of $\\Theta(mn)$, making the\r\ninterconnection network extremely expensive for even small numbers\r\nof processors and memories.\r\n\r\nMarsan \\cite{marsan} mentions that most time spent in any\r\nmultiprocessing time is idle time due to contention for a common\r\nresource such as a bus. It is therefore no surprise that modeling\r\ncontention-free systems is strait-forward in terms of waiting. The\r\nanalysis instead concentrates on statistical modeling of random\r\nactivity within the system. This is easily accomplished using\r\nqueueing networks, where processors are nodes without queues, and\r\nmemory modules are nodes with finite queues \\cite{marsan}. For a\r\ncrossbar architecture, there is an edge from every processor element\r\nto every memory element, since any processor may read any memory\r\nelement regardless of other processors. Some simplification occurs\r\nwhen two or more processors try to access the same memory node in a\r\ngiven time step: only one is served. Simulation can be performed\r\nusing the Monte Carlo method, with memory accesses being produced\r\nusing a random variable (``Markovian process'' is exponential) on\r\nall producers (processors) and consumers (memories) in the net.\r\n\r\nAs more becomes known about the system under analysis, more can be\r\nincluded in the modeling queueing network. Marsan \\cite{marsan}\r\nprovides a useful ontology by asking if the devices are synchronous,\r\nor asynchronous, and also whether memory accesses are uniform or\r\nnon-uniform between processors.\r\n\r\nMarsan gives a number of case studies. The simplest one is\r\nattributed to Bhandarkar \\cite{bhan}, who assumes that memory\r\naccesses are uniform across processors, with lost requests in the\r\ncase of memory contention. Bandarkar creates a vector of states that\r\nthe queueing network can take on, and then further simplifies the\r\namount of information at hand by creating super-states, or {\\em\r\nequivalence classes} of mutually indistinguishable states (since\r\nprocessors and memories are assumed identical). He derives a formula\r\n(Marsan fig 6.2) which can be used to algorithmically calculate\r\nsuper-state transition probabilities in a Markov process, and Marsan\r\n(p. 124, 136) gives further approximation formulas from others' work\r\nwhich can be calculated in better time on a computer. These\r\napproximations are not as important as they once were, because\r\ncomputers are substantially more capable today than they were in\r\n1986, at the time of publication. They are all valid, as they are\r\nequivalent to the exact result obtained by Bandarkar \\cite{bhan}. A\r\ngood approximation closed-form for the number of busy memory modules\r\n$ \\beta $ is given by Rau \\cite{rau} , using binomial approximations\r\nfor all events (equation \\ref{raus}). In this formula, $m$ counts\r\nmemories, and $p$ counts processors.\r\n\\begin{equation}\\label{raus}\r\n\\frac{\\sum_{i=0}^{\\text{min}(m,p)-1} 2^i \\binom {m-1}{i} \\binom\r\n{p-1}{i}}\r\n{\\sum_{i=0}^{\\text{min}(m,p)-1}\\frac{2^i}{i+1}\\binom{m-1}{i}\\binom{p-1}{i}}\r\n\\end{equation}\r\nDelay models, in which memory contention requests are queued instead\r\nof dropped, were also considered my multiple authors. Many of the\r\nresults were similar, with memory utilization expectedly being\r\nbetter with the addition of queues to memory \\cite{marsan} (136).\r\nRau's formula given above is an excellent minimum bound for back of\r\nthe envelope calculations for networks without bus contention.\r\n\r\n\\section{Shared Memory Systems}\r\n\r\nMost real systems are not free of bus contention, because of the\r\nnonlinear overhead cost of building complete connection networks.\r\nWhen bus contention is introduced, the location of the bus with\r\nrespect to the memory elements and processors plays a vital role in\r\nthe performance and contention of the system as a whole. In this\r\nsection, we investigate the subset of systems for which a number of\r\nprocessors each have a private local memory, connected by a local\r\nbus, and must contend for access to a shared memory, which requires\r\ncontrol of one of one or more global buses. This multiprocessor\r\narchitecture is common to many multiprocessor, multi-core\r\nworkstations as well as supercomputers such as the classic Cray\r\nseries. Classical multi-threading problems, including deadlock\r\nprevention and avoidance, starvation, and mutual exclusion must all\r\nbe taken into account for any shared memory systems. Marsan\r\n\\cite{marsan} lays out a number of simplifying assumptions for\r\nmodeling shared memory systems. Namely, they are: no delay when\r\ncapturing the bus (other than normal bus contention), CSMA/CA bus\r\ndiscipline, and immediate release of the bus upon completion (as\r\nwith capture). Marsan uses the term ``active state'' to mean that a\r\nprocessor is not currently accessing memory, ``waiting state'' to\r\nmean that a processor is waiting for the bus or memory, and ``access\r\nstate'' to mean that the processor is currently in memory.\r\n\r\n\\subsection{Single-Bus Shared Memory Systems}\r\nThe architecture is defined by Marsan to be a single global bus\r\nconnecting a number of local buses to the shared memory resource.\r\nEach local bus serves a single processor and its private memory.\r\n\r\nHe chooses three values to take into consideration: access times,\r\nactive times, and\r\n\r\n\\subsubsection{Exponential Distribution}\r\nThe Exponential Distribution represents . In a generalized\r\nstochastic petri net, a single exponentially distributed random\r\nevent can be represented by a place connected to a timed transition,\r\nwhere the firing rate of that transition takes on the parameter\r\n$\\lambda$ of the exponential distribution, and determines the\r\nlikelihood of that even firing depending on a continuous time\r\nvariable \\cite{marsan}. An example of an Exponentially distributed\r\nrandom variable is likelihood of a webserver receiving a packet at a\r\nparticular time.\r\n\r\n\\subsubsection{Erlang-k Distribution}\r\nAn Erlang-K distribution models k Exponentially distributed random\r\nevents which depend upon one another. They must occur in {\\em\r\nserial}. In the Petri Net representation, Erlang-K events should be\r\nrepresented by a k-chain of exponential General Stochastic\r\nContinuous-Timed Petri events \\cite{marsan}. An example of an Erlang\r\ndistributed random variable is the number of packets to a web server\r\nat a particular instant of time.\r\n\r\n\\subsubsection{Hyper-Exponential Distribution}\r\nA hyper-exponentially distributed random variable counts the number\r\nof simultaneous occurrences of an exponentially distributed random\r\nevent, such as processors trying to access the same piece of memory\r\nsimultaneously.\r\n\r\n\\subsubsection{Queueing disciplines}\r\n\r\nMarsan \\cite{marsan} defines three queueing disciplines for dealing\r\nwith memory access contention, and mutual exclusion assurance. Fixed\r\npriority means that the processors have some preordained priority\r\nfor which can preempt one another for memory access. Process sharing\r\nis like round-robin in that processors take their turn accessing\r\nmemory in the order they attempt to get in, but they are guaranteed\r\naccess because of some global device, like in time sharing. First\r\ncome first serve simply operated like a FIFO queue, but provides no\r\nguarantee that a process will give up the bus to allow others in.\r\n\r\nAll of the combinations of these ideas can be analyzed, and have\r\nbeen in several different papers. Again, see Marsan p. 157 for a\r\nfull bibliography of works. A simplified queuing network model or\r\nMarkov chain was successfully employed to deal with simple cases in\r\nwhich access times and/or active times were equally exponentially\r\ndistributed, but Petri nets were used by Marsan to get results for\r\nthe more complex models where distribution was hyper-exponential,\r\nErlang, or more complicated.\r\n\r\nIn all cases, the numerical results of Marsan seem to indicate that\r\nmodeling with a generalized stochastic Petri net can produce\r\napproximate simulation results fairly close to the analytical\r\nresults for simpler single-bus shared memory systems. The numerical\r\nresults show that the queueing discipline is not an important\r\nconsideration when modeling small systems. Since Petri nets are more\r\ngraphical and more intuitive than analytical methods, and because\r\nthe mathematics become complicated for very complex systems, the\r\nrecommended method for modeling anything complex is Generalized\r\nStochastic Petri nets as described in the 2nd half of Marsan\r\n\\cite{marsan} (Chapter 7 and the beginning of Chapter 8).\r\n\r\n\\subsection{Multi-Bus Shared Memory Systems}\r\nMulti-bus Shared Memory systems can be modeled with Petri nets using\r\nthe same techniques as single-bus shared memory systems. Generally,\r\nthe number of buses are represented as tokens in a resource pool,\r\nwhich is a place. Depending upon the architecture of the system, and\r\nbecause of Marsan's simplifying assumptions for shared memory\r\nsystems, immediate transitions usually follow the global bus\r\nresource pool (capturing and releasing being instantaneous, but\r\nactive, access times being exponential).\r\n\r\nMarsan gives a full analytical treatment to many complicated\r\nmulti-bus systems, but that is unnecessary since most systems can be\r\neasily intuitively modeled with Petri nets. Marsan et al. first\r\nobtains upper and lower bounds limiting the gain or loss of\r\nprocessing power, so any numerical results given by Petri net\r\nmodeling should fall within the domain on \\cite{marsan} (p.\r\n186-189). This is generally a good methodology, since most\r\nbottlenecks in this configuration are assumed to stem from global\r\nbus contention.\r\n\r\n\\section{Distributed Memory Systems}\r\nShared memory systems are not the only type of distributed system. A\r\ntrue distributed system uses a paradigm more like message passing.\r\nThis architecture consists of one or more global buses connecting\r\nlocal buses. Each local bus contains a processor and at least one\r\nmemory element. Unlike previous shared memory systems, there is no\r\nmemory connected to the global bus(es). Instead, the memory at each\r\nlocal bus is used by any processor in the system, and both local and\r\nglobal buses must be secured at each access step. An example of this\r\ntype of system is a computer network utilizing file sharing. Because\r\nof the high dynamism of such networks, analysis of any but the\r\nsimplest distributed memory systems is impossible with queueing\r\nnets. Marsan \\cite{marsan} proposes tens of architectures that are\r\nboth single global bus and multiple global bus and also incorporate\r\ndistributed memory, but does not give any indication of extending\r\nthis methodology to generalized distributed systems.\r\n\r\nTo model any distributed memory systems, a Petri net should be\r\nemployed, and numerical results obtained. The reachability tree of\r\nthe Petri net can then be used to discover some analytical artifacts\r\nof the system, such as whether it is live, as described in\r\n\\cite{murata}.\r\n\r\n\\section{Extended Petri Nets}\r\n\r\nBucci \\cite{bucci} describes an extended version of Petri nets where\r\nthe continuous time model is replaced with discrete time events. A\r\nglobal clock of some sort . A ``firing event'' occurs whenever the\r\nrandom variable distribution coincides {\\em as well as} the time has\r\ncome for that transition to fire. The idea of this extension is that\r\na Petri net can operate within a discrete time domain, following a\r\nglobal clock, while keeping the ability to induce transitions from\r\nstate-to-state concurrently (ie using threads or a similar\r\nmechanism). This dramatically increases the simulation uses of GSPN\r\nmodels, but does not really add much to their descriptive power.\r\nBucci's method should be taken into account any time that a\r\nsimulation must occur, especially in a simulation with lots of\r\nsimultaneity.\r\n\r\n\\section{Fault Tolerance Modeling}\\label{fault tolerance}\r\nIf systems include repairable components, a GSPN event (place /\r\ntimed transition) can represent the break and rapair of any\r\ncomponent in the system, just as\r\n\r\n\\section{Analysis and Verification}\\label{analysis}\r\nGenerally, any sort of Petri Net model is good for modeling a\r\nspecific system, but can only provide numerical results. In order to\r\nassure that those results are statistically significant, many runs\r\n(at least 30) should be performed in simulation, and every variable\r\nmust be checked for consistency with a real system. One technique\r\nwhich is liberally applied by many \\cite{murata} \\cite{marsan} is to\r\nuse a verifiable Markovian process or queueing network to provide\r\nupper and lower analytical bounds. At this point, the system can\r\nsimply be built and run. Analysis can be extremely difficult, so\r\nmost of the time the Petri net approach will be more useful for the\r\nbudding system developer, without rigorous mathematical background.\r\n\r\n\\begin{thebibliography}{5}\r\n\r\n\\bibitem{marsan} Marsan, N. Balbo, G. Conte, G. \"Stochastic Petri Nets.\" Performance Models of Multiprocessor Systems. Cambridge: MIT Press. 1986. pp. 72 - 98.\r\n\r\n\\bibitem{bucci} Bucci, G. Correctness Verification and Performance Analysis Using Stochastic Preemptive Time Petri Nets. IEEE Transactions on Software Engineering. Vol 23, No 11. November 2005. pp. 913 - 937.\r\n\r\n\\bibitem{murata} Murata, T. Petri Nets: Properties, Analysis, and Applications. Invited Paper. Proceedings of the IEEE. Vol 77. No 4. April 1989. pp. 541 - 579.\r\n\r\n\\bibitem{bhan} Bhandarkar, D. Analysis of Memory Interference in\r\nMultiprocessors. IEEE Transactions on Computers Vol 24. No 9.\r\nSeptember 1975. 897-908.\r\n\r\n\\bibitem{rau} Rau, B. Interleaved Memory Bandwidth in a Model of a Multiprocessor Computer System. IEEE Transactions on Computers Vol 28. No 9.\r\nSeptember 1979. 678 - 681.\r\n\r\n\r\n\\end{thebibliography}\r\n\r\n\\end{document}\r\n", "meta": {"hexsha": "99d994b062553bb88492e839f37b0442f023822c", "size": 16685, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "analysis and modeling final.tex", "max_stars_repo_name": "twinbee/analModels", "max_stars_repo_head_hexsha": "c011561fc0bf3101766ff86380a33b36d19dedfb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "analysis and modeling final.tex", "max_issues_repo_name": "twinbee/analModels", "max_issues_repo_head_hexsha": "c011561fc0bf3101766ff86380a33b36d19dedfb", "max_issues_repo_licenses": ["MIT"], "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 and modeling final.tex", "max_forks_repo_name": "twinbee/analModels", "max_forks_repo_head_hexsha": "c011561fc0bf3101766ff86380a33b36d19dedfb", "max_forks_repo_licenses": ["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.8006329114, "max_line_length": 210, "alphanum_fraction": 0.7918489661, "num_tokens": 3767, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.3415824860330003, "lm_q1q2_score": 0.1907147227444101}}
{"text": "% Template for PLoS (Adapted for Frontiers, MdK))\n% Version 1.0 January 2009\n%\n% To compile to pdf, run:\n% latex plos.template\n% bibtex plos.template\n% latex plos.template\n% latex plos.template\n% dvipdf plos.template\n\n\\documentclass[12pt]{article}\n\n% amsmath package, useful for mathematical formulas\n\\usepackage{amsmath}\n% amssymb package, useful for mathematical symbols\n\\usepackage{amssymb}\n\n% graphicx package, useful for including eps and pdf graphics\n% include graphics with the command \\includegraphics\n\\usepackage{graphicx}\n\n% cite package, to clean up citations in the main text. Do not remove.\n\\usepackage{natbib}\n\\usepackage{cite}\n\\usepackage{lineno}\n\\usepackage{color} \n\n% Use doublespacing - comment out for single spacing\n%\\usepackage{setspace} \n%\\doublespacing\n\n% Text layout\n\\topmargin 0.0cm\n\\oddsidemargin 0.5cm\n\\evensidemargin 0.5cm\n\\textwidth 16cm \n\\textheight 21cm\n\n% Bold the 'Figure #' in the caption and separate it with a period\n% Captions will be left justified\n\\usepackage[labelfont=bf,labelsep=period,justification=raggedright]{caption}\n\n% Use the Frontiers provided bibtex style\n\n% Remove brackets from numbering in List of References\n%\\makeatletter\n%\\renewcommand{\\@biblabel}[1]{\\quad#1.}\n%\\makeatother\n\n\n% Leave date blank\n\\date{}\n\n\\pagestyle{myheadings}\n%% ** EDIT HERE **\n\n% the subfigure package\n\\usepackage{caption}\n\\usepackage{subcaption}\n\n\\DeclareCaptionFormat{subfig}{\\figurename~#1#2#3}\n\\DeclareCaptionSubType*{figure}\n\\captionsetup[subfigure]{format=subfig,labelsep=colon,labelformat=simple}\n\n% the listings package\n\\usepackage{listings}\n\\lstset{\nlanguage=C++,\nbasicstyle=\\footnotesize,\nnumbers=right,\nnumberstyle=\\tiny,\nframe=tb,\ncolumns=fullflexible,\nshowstringspaces=false\n}\n\n\n%% ** EDIT HERE **\n%% PLEASE INCLUDE ALL MACROS BELOW\n\n%% END MACROS SECTION\n\n\\begin{document}\n\n% Title must be 150 characters or less\n\\begin{center}\n\\thispagestyle{empty}\n{\\Large\n\\textbf{Parallel MIIND: a Parallel Framework for Populations of Spiking Neurons Using Population Density Techniques}\n}\n\\vspace{1.0cm}\n% Insert Author names, affiliations and corresponding author email.\n\\\\\nMarc de Kamps$^{1,\\ast}$, \nDavid Sichau$^{2}$\n\\vspace{0.5cm}\n\\\\\n\\bf{1} School of Computing, University of Leeds, Leeds, West Yorkshire, UK\n\\\\\n\\bf{2} LAV, Institute of Energy Technology, ETH Zurich, 8092 Zurich, Switzerland\n\\\\\n\\vspace{0.5cm}\n$\\ast$ E-mail: m.dekamps@leeds.ac.uk\n\\end{center}\n\n% Please keep the abstract between 250 and 300 words\n\\section*{Abstract}\n\n\n%\\section*{Author Summary}\n\\newpage \n\\setcounter{page}{1}\n\\linenumbers\n\n\\section{Introduction}\nMultiple Interacting Instantiations of Neural Dynamics \\citep{dekamps2008} (MIIND) is a simulation framework designed for modeling large networks of \nneuronal populations. It is written in C++ and employs MPI \\citep{gropp1998} for parallelisation. Python extensions can be provided on request. \nDue to its design philosophy it can be easily applied to modeling \nbiological processes outside computational neuroscience. MIIND abstracts the interaction between neuronal populations into an interaction \nbetween nodes on a directed graph. The neuronal processes describing the activity of the population live on these nodes as objects and evolve \nthe population’s state. In general we aim to support network processes that use CPU-intensive computations to model nodes, but\nrequire little bandwidth in the internode communication. Neuronal networks where individual spikes are less important than the transmission\nof population firing rates are well supported by this paradigm. As such, the processes that are supported by this framework are trivially\nparallelizable. Unfortunately, the word trivial does not apply to the actual implementation: we found that in the original code base of MIIND there\nwere too many obstacles to parallelisation and we decided to start from a fresh code based. \n\nAs with any framework, MIIND comes with a number of predefined algorithms, some allowing sophisticated simulations of neuronal \ndynamics. The simplest algorithms implement Wilson-Cowan dynamics \\citep{wilson1972}, but, uniquely, \nMIIND provides an implementation of population density techniques (e.g.) \\citep{stein1965,knight1972,knight1996}. They provide efficient simulations \nof large populations of neurons by means of a density function over the state variables of a given neuron. Such techniques have undergone rapid \ndevelopment over the last decade \\citep{omurtag2000}. In practice these techniques have been mainly used for leaky-integrate-and-fire (LIF) neurons,\nin the so-called diffusion limit: small synaptic efficacies and high firing rate. In this limit the distribution of membrane potentials of the\npopulation can be modeled by a diffusion process, using Fokker-Planck equations. \n\nRecent progress has extended the usefulness of these technique considerably. First, the techniques are no longer restricted to the diffusion limit \n\\citep{omurtag2000,dekamps2003,dekamps2006}, indeed arbitrary large efficacies can be used. Second, they are no longer restricted to LIF neurons: \na method to model any one-dimensional neuronal model was described recently \\citep{dekamps2013}, and will soon be part of the code base.\nOthers have described density approaches based on 2D neuronal models, including synaptic kinetics, and have established that networks\nof 2D populations are computationally still competitive, compared to direct simulation.\n \nThe methods described here are at least an order of magnitude more efficient than direct simulation (a real second for a population of LIF neurons\ncan be modeled in well under 0.5 s simulated time \\citep{dekamps2006}). Nevertheless, the computational load is such that a network of hundreds of such \npopulations would lead to lengthy simulation runs on a serial machine. Therefore investigating the performance of such a network provides a good\nbenchmark for the scalability of the parallelisation approach.\n\n\n\n% Results and Discussion can be combined.\n\\section{Results}\n\\subsection{The Framework}\nIn \\citep{dekamps2008} we have outlined the general design ideas of the framework: populations can be modeled by nodes on a directed graph, \nwhich interact via the edges. The evolution of a population is determined by an Algorithm object which lives on the node and which maintains an \nAlgorithmGrid. A central simulation loop visits each node in term, collects the contributions from every other node connected to this node and calculates \nits input contribution weighted by the link value of the connection. Thus an instantaneous weighted input contribution from the entire network to node will \nbe calculated, and this will be used by the algorithm to evolve its node state a small moment in time. This will result into an update of the AlgorithmGrid. \nBy repeating this process for all nodes in the network for a desired period of time, a simulation of the network process is implemented. \nThe central idea is represented in Figure 1. In the next section we will illustrate how network creation and configuring a simulation is done \nfrom the user's perspective.\n\\subsection{Simulating Networks as a Use Case}\nHere we present a small program that performs a simulation of two neuronal populations: one excitatory and one inhibitory, driven by a common external input.\nIn listing \\ref{code:twopopnet} the shortened code of this simulation is provided.\nTo increase the readability parameters are not provided. \nAs a placeholder for the parameters the word PARAM is used.\nAdditional namespaces are ignored. \nFor the whole program the reader is refered to the source code where this example is provided as \\texttt{two-population.cpp}.\nIn the next section the setup of an simulation is explained step by step with the two population network.\n\\begin{lstlisting}[caption=Simulation of a two neuronal population network.,label=code:twopopnet]\nint main(int argc, char* argv[]) {\n#ifdef ENABLE_MPI\n\tboost::mpi::environment env(argc, argv);\n#endif\n\ttry {\n\t\tNodeId id_cortical_background;\n\t\tNodeId id_excitatory_main;\n\t\tNodeId id_inhibitory_main;\n\t\tMPINetwork network;\n\n\t\t// Create cortical background, and add to network\n\t\tpopulist::RateFunctor cortical_background(PARAM);\n\t\tid_cortical_background = network.addNode(cortical_background, EXCITATORY);\n\t\t// Create excitatory main population\n\t\tPopulationAlgorithm_ algorithm_excitatory(PARAM);\n\t\tid_excitatory_main = network.addNode(algorithm_excitatory, EXCITATORY);\n\t\t// Create inhibitory main population\n\t\tPopulationAlgorithm_ algorithm_inhibitory(PARAM);\n\t\tid_inhibitory_main = network.addNode(algorithm_inhibitory, INHIBITORY);\n\n\t\t// Background and excitatory connection only differ in x, 1- x\n\t\tnetwork.makeFirstInputOfSecond(id_cortical_background, id_excitatory_main, PARAM);\n\t\t// Excitatory connection to itself\n\t\tnetwork.makeFirstInputOfSecond(id_excitatory_main, id_excitatory_main, PARAM);\n\t\t// Background connection to I\n\t\tnetwork.makeFirstInputOfSecond(id_cortical_background, id_inhibitory_main, PARAM);\n\t\t// E to I\n\t\tnetwork.makeFirstInputOfSecond(id_excitatory_main, id_inhibitory_main, PARAM);\n\t\t// I to E\n\t\tnetwork.makeFirstInputOfSecond(id_inhibitory_main, id_excitatory_main, PARAM);\n\t\t// I to I\n\t\tnetwork.makeFirstInputOfSecond(id_inhibitory_main, id_inhibitory_main, PARAM);\n\n\t\tnetwork.configureSimulation(PARAM);\n\t\tnetwork.evolve();\n\t} catch (std::exception&e) {\n\t\tstd::cout << e.what() << std::endl;\n\t\treturn 1;\n\t}\n\treturn 0;\n}\n\\end{lstlisting}\n\nFor parallel MIIND it is important to initialise the mpi environment (see line 3 in listing \\ref{code:twopopnet}).\nTo allow that the code is compilable without an mpi compiler the preprocessor is used to remove the code if mpi is not enabled.\nThese 3 lines are the only one where actually the user is forced to handle the mpi environment direct.\nAll other mpi related code is hidden from the user.\n\nAfter the mpi environment is initialised one can start with setting up an simulation.\nThe network is created by instantiating a network object (line 9).\nThe network gets two template parameters.\nThe first parameter defines the connection type of the network.\nIn the example above this is a Ornstein Uhlenbeck type of connection.\nThe second parameter is the distribution of the nodes.\nThese parameter controls the distribution of the nodes in an mpi environment.\nMore details will be provided in the next section.\n\nSo far only the type of the network is defined.\nTo define the structure of the network two methods are needed.\n\n\nThe first method \\texttt{addNode} adds a new nodes to the network (see line 13, 16 and 19).\nThis method expects the algorithm executed on this node and the type of the node.\nIn the example above 3 nodes are generated.\nThe cortical background driving the simulation with a constant firing rate (line 13).\nAnd an excitatory and inhibitory node where leaky-integrate-and-fire neurons are simulated (line 16 and 19). %what reference for that\n\nThe method \\texttt{addNode} returns the node id of the generated node.\nThe node ids start from 0 and are incremented by one for each additional nodes.\nThe order of the node ids correspond to the chronological order of the calls to \\texttt{addNode}.\nThese ids are needed to identify the individual nodes and are needed for the second method to generate the network structure.\n\nAfter the creation of the nodes the interactions of the network needs to be created.\nTherefore directed connections between two nodes are generated.\nDirected Connections between two nodes are generated by calling the method \\texttt{makeFirstInputOfSecond}.\nThe method expects as parameters the node id of the first and the second node in the connection and the parameters of the connection (see line 22 - 32).\nIn the case of the two population network six connections are generated.\nThe background node is connected to the exhibitory and the inhibitory node.\nThe exhibitory and inhibitory nodes are connected to itself and to each other.\nWith these two methods the structure of the network is constructed.\nThe structure of the generated network can be seen in figure \\ref{fig:twoPopNetwork}.\n\nWith these two methods all kind of networks can be generated.\nTo execute a simulation on that network the simulation needs to be configured.\nThe configuration is done by providing the simulation parameters to the method \\texttt{configureSimulation} (see line 34 in listing \\ref{code:twopopnet}).\nWhen the simulation is configured the main simulation loop can be executed with the method \\texttt{evolve}.\n\nWith the example provided above one can see that the generation of a simulation is straightforward.\nIt does not need any knowledge about the underlying parallelisation. More details about the parallelisation is provided in the next section.\n\n\\subsection{The Simulation Engine: An MPI-enabled Simulation Loop}%TODO(MdK) it is not only the simulation loop which is parallised. Maybe another title would be more suitable\nIn this section we will describe the mpi-based infrastructure that forms the heart of the framework.\n\nTo start with an illustration will be used.\nA person wants to solve a large equation consiting of lot of different smaller equations.\nIn the beginning the person solved the equation on its own.\nHowever it took a large amount of time for one person to solve the equations.\nTherefore the management decided to hire additonal people to speed up the process.\nTo solve the equations faster each person needs to know what equation it should solve and sometimes the extension of another person equation is needed.\nTo share results and work they need to communicate with each other.\nWhen people communicate with each other they cannot solve equations on the same time.\nAdditional the they might need lot of extensions of other people so they need to wait until the other people are finished with their calculation.\nThese two problems show some of the largest issues with parallelisation.\nOne is the overhead for communication.\nAnd the other the latency.\nThe illustration above allegorize the message passing interface.\n\nThe Message passing interface mpi is a standard to develop applications aimed at large scale parallel applications.\nAn mpi program resembles an ordinary program written for a serial processor.\nThis similarity is deceptive, however.\nIn reallity the code is executed in parallel on different mpi processes.\nA mpi process can be either executed on a single core of a multi core processor or on a different CPU.\nThese execution in different processes results that each process has its own memory space and not a shared memory space like a serial program.\nThat increases the amount of work to share data between the mpi processes.\nFor sharing data messages are sent between the individual mpi processes.\nTo send messages conncetions between the individual processes are needed.\nThe connections between the individual processes can be either a internal bus or a simple network connection.\nHowever mpi is normally executed on super clusters with a very fast network connection (e.g. InfiniBand).\n\nTo speed-up a serial program with mpi the serial program is decomposed in parts that can be executed in parallel.\nA serial program that is not embarrasing parallel results in data that needs to be shared between the mpi processes.\nTherefore the individual mpi processes needs to communicate with each other to share the data.\nTo share the data between the mpi processes messages are sent from one mpi process to another with the data.\nCompared to computation a message is very slow.\nTo reduce the overhead of parallelisation it is very important to reduce the number of messages to the minimum.\n\n\nFor the parallelisation of MIIND the idea was to distribute the nodes to MPI processes.\nEach node can locally envole one time step without any communication.\nThe evolve step is responsible for most of the run time of an simulation the run time should be reduced by parallising these method.\nTo distribute the nodes to the mpi processes a distibution function is used.\nAs a default distribution function the circular distribution (\\texttt{CircularDistribution}) is provided.\nThe circular distribution assignes the nodes in a circular manar to the mpi processes by using the modulor operator.\nFor example the network \\ref{fig-realNetwork} would be represented internaly like \\ref{fig-internalNetwork} when 4 mpi processes are available.\nAs the default distribution is not always the best choice it can be easily exchanged.\nA new distribution can be implemented by implementing the virtual methods of the base class \\texttt{NodeDistributionInterface}.\nThe implementation of a new distribution might be useful if another distribution would decrease the number of messages across the MPI processes (the dotted arrows in figure \\ref{fig-internalNetwork}).\nTo implement a new distribution one might make use of additional knowledge of the network to decrease the messages over MPI process boarders.\n\nWith the distribution function the nodes are assigned to distinct mpi processes.\nAs the nodes are distributed over several mpi processes major changes inside the library where needed.\n\nThe parallelisation starts during the creation of the network.\nWhen a node is added to the network the node is only generated on its responsible mpi process.\nThe method \\texttt{addNode} is responsible for creating nodes.\n\n\\begin{lstlisting}[caption=The \\texttt{addNode} method of the network.,label=code:addNode]\naddNode(const AlgorithmInterface& alg, NodeType nodeType) {\n\tNodeId tempNodeId = getMaxNodeId();\n\tif (nodeDistribution.isLocalNode(tempNodeId)) {\n\t\tMPINode node = MPINode(...);\n\t\tlocalNodes.insert(std::make_pair(tempNodeId, node));\n\t}\n\tincrementMaxNodeId();\n\tutilities::MPIProxy().barrier();\n\treturn tempNodeId;\n}\n\\end{lstlisting}\n\nIn listing \\ref{code:addNode} the simplified method is provided.\nThe method starts with getting the next node id (see line 2 in listing \\ref{code:addNode}.\nThe node id needs to be synchonised between the mpi processes to make sure that each nodes gets an unique id.\nThe ids of the nodes starts with 0 and increasing numbers are assigned to each node depending on the time of their initialization.\nAt this moment all mpi processes have the same node id.\nTo generate a node only on the responsibel mpi process the check on line 3 is carried out.\nThe \\texttt{nodeDistribution} is the choosen distribution class, which checks if the node should be assigned to this mpi process.\nIf the node should generate on this node the node is generated and stored in the map \\texttt{localNodes}, where the nodes on this mpi process are stored with their id as an key.\nAfter the node is generated, or not the node id needs to be increased by calling the method \\texttt{incrementMaxNodeId()}.\nTo avoid side effects the \\texttt{addNode} method is synchronised.\nFor synchronous code mpi barriers are used which make sure that the function is only finished if all processes have executed all code.\nAs the generation of nodes happen only during the initialization this synchronous code has no impact on the performance.\n\n\n\n\nAs the mpi processes have different memory spaces the connections between the nodes cannot be stored anymore by connecting the nodes direct (via pointers or references).\nThe connections are generated by calls to the \\texttt{makeFirstInputOfSecond} method.\n\n\n\\begin{lstlisting}[caption=The simplified \\texttt{makeFirstInputOfSecond} method of the network.,label=code:makeFirstInputOfSecond]\nmakeFirstInputOfSecond(NodeId first, NodeId second, const WeightValue& weight) {\n\t//Make sure that the node exists and then add the successor\n\tif (nodeDistribution.isLocalNode(first)) {\n\t\tlocalNodes.find(first)->second.addSuccessor(second);\n\t}\n\t// Make sure that the second node exist and then set the precursor\n\tif (nodeDistribution.isLocalNode(second)) {\n\t\tlocalNodes.find(second)->second.addPrecursor(first, weight, nodeIdsType_[second]);\n\t}\n}\n\\end{lstlisting}\n\nIn listing \\ref{code:makeFirstInputOfSecond} the simplified method is provided.\nAs the connections cannot be stored with pointers or references it is stored by saving the node ids of the precursors respective the successor of a node.\nDuring the \\texttt{makeFirstInputOfSecond} method on the local nodes either the successor (line 4) or precursor (line 8) of a node is stored.\n\n\nAfter the network has been generated the simulation is initialized.\nTo avoid to much communication between the nodes each mpi process has its own log and output file.\nIn the output file the activities of the local nodes are stored.\nThe advantage of several output files is that the node activities had not to be collected on one mpi process, which would require lot of communication.\nThis performance gain is paid for by a more difficult post processing. \nAs the activites of the nodes are distributed into several files and are not stored all in one file.\n\nWhen the simulation is configured the main simulation loop is started.\nThe main simulation loop iterates over the local nodes and envoles them one step.\nTo make sure that all node have recieved and sended their activity at the beginning of each \\texttt{evolve} step an barrier is introduced.\nAt this barrier all nodes waits until all mpi messages are successfully finished.\nThis barrier increased the performance as the latency of the mpi messages was hidded.\nThe mpi messages where sent ascynchronus such that the mpi process could continue with other computation and does not need to wait for each to be finished.\n\nThe evolve of a node does require that all nodes have the activity of their precursors.\nEach node has a temporary storage (\\texttt{\\_precursorActivity}) of the activity of their precursors.\nDuring the \\texttt{evolve} method each node calls his corresponding algorithm and passes the activity of the precursors the weights of the connection and the type of the precursor (see line 3 in listing \\ref{code:evolve}).\n\n\n\\begin{lstlisting}[caption=The simplified \\texttt{evolve} method of the nodes.,label=code:evolve]\nevolve(Time time) {\n\twhile (_pAlgorithm->getCurrentTime() < time) {\n\t\t_pAlgorithm->evolveNodeState(_precursorActivity, _weights, time,_precursorTypes);\n\t}\n\tthis->setActivity(_pAlgorithm->getCurrentRate());\n\tsendOwnActivity();\n\treceiveData();\n}\n\\end{lstlisting}\n\nAfter the algorithm had evolved the state of the node the new rate of the node is stored (line 5).\nWhen the new activity of the node is available the node sends its new activity to all its successors (line 6).\nThe details of the \\texttt{sendOwnActivity} method is explained below.\nAdditonal the node prepares itself to receive data from his precursors (line 7).\nThe details of the method \\texttt{receiveData} is explained below.\nAs the \\texttt{sendOwnActivity} and \\texttt{receiveData} are asynchronous they return immediately such that the next node can be envolved without waiting for the data transmission.\n\n\nThe activity of a node is sent to the successors with the help of the \\texttt{sendOwnActivity} method.\nIn listing \\ref{code:sending} the simplified method is provided.\n\\begin{lstlisting}[caption=The simplified \\texttt{sendOwnActivity} method of the nodes.,label=code:sending]\nsendOwnActivity() {\n for (auto& it : _successors) {\n\tif (!_rNodeDistribution.isLocalNode(it)) {\n\t MPIProxy().isend(_rNodeDistribution.getResponsibleProcessor(it), _nodeId, _activity);\n\t}\n }\n}\n\\end{lstlisting}\nThe method \\texttt{sendOwnActivity} iterates ofter the ids of the successors of a node (see line 2 in listing \\ref{code:sending}.\nFor each successor it is checked if the successor is on the same mpi process or not (line 3).\nIf not the activity of the code needs to be send with mpi to the corresponding processor (line 4).\nThe \\texttt{MPIProxy} class is a simple wrapper over the mpi environment to avoid any bare mpi code in library.\n\\texttt{MPIPoroxy} is explained later into more detail.\nThe method \\texttt{isend} sends an asynchronous mpi message to a processor with some data.\nThe first parameter \\texttt{isend} is the identifier of the mpi process which is responsible for the successor.\nThe second parameter is a message identifer.\nTogether with the mpi process these need to be unique.\nThe last parameter is the actual data that is send to the other node.\n\nAfter the own data sending was started each node prepares itself to recieve the activities of the other nodes.\nTherefore the \\texttt{receiveData} method is used.\n\n\\begin{lstlisting}[caption=The simplified \\texttt{receiveData} method of the nodes.,label=code:receive]\nreceiveData() {\n int i = 0;\n for (auto it = _precursors.begin(); it != _precursors.end(); it++, i++) {\n\tif (_rNodeDistribution.isLocalNode(*it)) {\n \t _precursorActivity[i] = _rLocalNodes.find(*it)->second.getActivity();\n\t} else {\n\t MPIProxy().irecv(_rNodeDistribution.getResponsibleProcessor(*it), *it, _precursorActivity[i]);\n\t}\n }\n}\n\\end{lstlisting}\n\nThe \\texttt{receiveData} method iterates over all precursors of a node (see line 3 in listing \\ref{code:receive}).\nFor each precursor it is checked if it is local to this mpi process (line 4).\nIf a node is local the activity is received without any communication with a lookup in the map of the local nodes (line 5).\nWhen a node is not local to this mpi process the method opens an asynchronous receive (line 7).\nThe first parameter the method \\texttt{irecv} is the identifier of the mpi process which is responsible for the precursor.\nThe second parmeter is the identfier of the message. \nEach \\texttt{isend} and \\texttt{irecv} method must pair depending on responsible processors and the message identifier.\nThe last parameter is the storage location where the location where the received activity should be stored.\nIt is the temporary storage of the activities of the precursors which are used during the next \\texttt{evolve} step.\n\n\nThese are where all the magic of the parallelisation of MIIND is done. \nThe algorithms of Parallel MIIND have not changed significantly compared to MIIND. \nFor an algorithm developer only the way the data is provided has changed.\nAdditional he does not need to care about concurrency issues as the parallelisation is encapsuled from the algorithm.\nThis simplifies the development of new algorithms significantly as developers does not need to gain internal knowledge of pmiind.\n\nThe most visible change of Parallel MIIND for an application developer is the output.\nAs explained above each mpi process writes to its own output file.\nInstead of one root file with all results for each MPI process a root file with the corresponding local nodes is generated.\nTherefore the activity of the nodes are distributed to several files and need to be collected from different files for postprocessing.\n\nTo reduce the impact of pmiind all mpi related code is encapsulated in the class \\texttt{MPIProxy} and can be turned off.\nTo improve the readability of the code the mpi related code is wrapped by the class \\texttt{MPIProxy}.\nTherefore when MPI methods are used boost mpi is not called direct instead the class \\texttt{MPIProxy} forwards the calls to boost mpi.\nAdditional this class stores all open mpi requests of the asynchronous calls.\nReducing the code to handle all open communications as all mpi request are stored in one place and not scattered around the code of the library.\nAs all mpi related code is encapsulated in one class it can be easily turned off.\nWhen MPI is turned off parallel MIIND can be builded and executed without mpi available on the computer.\nThis reduces the impact of the development of new algorithms further as the development computer does not need to have mpi installed.\nAfter the testing the parallelisation can be turned on and one can benefit of the speed ups achieved by parallel execution on clusters.\n\nAs a parallel environment is very hard to debug a new logging class had been developed.\nThe class \\texttt{Log} provides methods to print logging and debugging messages.\nAdditional it provides additional information about the mpi environment allowing to identify the mpi process which might have an error.\nThe generation of a huge number of debug logs is very time consuming. Therefore the logging can be turned off completely for release builds.\nInstead off a simple on or off the class provides several log levels allowing a fine granularity of log messages.\nThis allows the usage of this class not only for debugging purposed but additional for error messages or important information during a simulation run.\n\n\\subsection{A Scalable Model of Waves in a Large Network of Leaky-Integrate-and-Fire Neurons}\nConsider the local circuit displayed in Figure \\ref{fig-network} (A). It consists if an excitatory and inhibitory population, which are fully connected\nand driven by a common input. It is possible to predict the firing rate of the populations in the circuit using a number of simple equations\ncite{amit199a}, which can be solved with the algorithms provided in MIIND (see section \\ref{sec-methods}). A population density-based simulation\nshows that the network indeed converges to the predicted rates.\n\nIn Figure \\ref{fig-network} (C), a hexagonal network is created, whose populations should converge to the same rates. To achieve this, the efficacy\nof the local EE connections are halved and each excitatory population is connected laterally with an efficacy that makes up for the reduced\nefficacy in the self-connection (section \\ref{sec-methods}). Such a network can be easily expanded into an overall hexagonal structure that consists\nof a number of rings, and the number of local circuits in the network scales quadratically with the number of rings. By simply expanding the number\nof rings, we can investigate the scalability of the network. Finally, a burst from an external input is introduced to the central population.\n\nWhen no delays are introduced in the lateral connections, the network quickly converges to the same firing rate as for the single local circuit. When\nthe burst occurs, it is transmitted without delays to the outer populations, which respond immediately. Although this may seem odd, large population\nof neurons can respond considerably faster that the time membrane constant of the comprising neurons would suggest. Indeed, population density methods\nthat model infinitely large populations responds immediately.\n \nWhen delays are introduced the dynamics of the network becomes very interesting: the network never quite settles in its equilibrium mode as\ndelayed contributions from further away keep causing local disturbances (Figure \\ref{fig-sim}. The burst is now clearly delayed and\nripples from inside to outside. The outside nodes, however functions as a secondary source, and a rebound on more central populations can\nalso be discerned (see Figure \\ref{fig-sim}).\n\n\\section{Discussion}\n\n\\section*{Methods}\n\\label{sec-methods}\n\\subsection{Network Model}\n\\subsubsection{Finding Steady State Firing Rate}\n\\label{sec-steady}\nThe architecture of the network has been described in Figure \\ref{fig-bb}. It consists of a local circuit comprised of an excitatory and an inhibitory\npopulation that are fully connected. We will first describe how this local circuit the local circuit is simulated. \nIn section \\ref{sec-hexagon} we will then describe how this circuit is embedded in an overall hexagonal structure.\nEach population\nis assumed to be comprised of a large number of spiking LIF neurons. It is assumed that both the populations input and output spike trains\nare Poisson distributed and that populations are connected sparsely but by a large number of connections. Under these assumptions an expression\ncan be found that expresses the population's output firing rate as a function of the input contributions: the so-called gain functions.\nAssume a population of LIF neurons with time constant $\\tau$, threshold $V_{th}$, reset potential $V_{reset}$ and reversal potential $V_{rev}$\nreceives Poisson distributed spike trains from another external population, which has a population firing rate of $\\nu_{ext}$. \nFurthermore, assume that each such input spike raises the membrane potential\ninstantaneously by a magnitude $h$ (delta peak synapses), that $N_{input}\\epsilon$ external neurons connect to a neuron in the population on average, \nwhere $N_{input}$ is the average number of input neurons and $\\epsilon$ is a sparseness parameter. The average contribution to the\nmembrane potential per time unit $\\tau$ is then given by:\n\\begin{equation}\n \\mu = \\tau \\epsilon \\nu_{ext} J, \n\\end{equation}\nthe variability by:\n\\begin{equation}\n \\sigma^2 = \\tau \\epsilon \\nu_{ext} J^2,\n\\end{equation}\n\nThe population's own firing rate is then given by:\n\\begin{equation}\n\\nu = \\phi( \\mu, \\sigma)\n\\label{eq-transduc}\n\\end{equation}\nwith $\\phi$ given by:\n\\begin{equation}\n\\phi(\\mu, \\sigma) = \\int^{bla}_{ble}du \\exp(u^2)(1 + )\n\\end{equation}\nIf the population is large, Equation \\ref{eq-transduc} is a very good approximation of the firing rate that would be found in a simulation\nof LIF neurons indeed. In a network of LIF neuron populations this leads to self-consistency relationships in term of gain functions, that describe\nthe steady state firing rates that eventually may emerge \\footnote{This is not necessarily the case. See section \\ref{sec-Fokker-Planck}.} if external contributions to the network are kept constant. For each population $i$ one has:\n\\begin{equation}\n \\nu_i = \\phi_i( \\mu_i, \\sigma_i), i = 0 \\cdots N-1\n \\label{eq-steady}\n\\end{equation}\nwith:\n\\begin{equation}\n \\mu_i = \\tau_i (\\sum^{N-1}_{j=0} J_{ij}\\epsilon_{ij} N_j\\nu_j + \\sum^{N_{ext}-1}_{k=0} J_{ik} \\epsilon_{ik}N_k \\nu_k)\n \\label{eq-mui}\n\\end{equation}\n\\begin{equation}\n \\sigma^2_i = \\tau (\\sum^{N-1}_{j=0} J^2_{ij}\\epsilon_{ij} N_j\\nu_j + \\sum^{N_{ext}-1}_{k=0} J_{ik} \\epsilon_{ik}N_k \\nu_k)\n \\label{eq-sigi}\n\\end{equation}\nThe $J_{ij}$ are now the (average) efficacy of population $j$ onto $i$, which can be positive (excitatory) or negative (inhibitory)\nwith the understanding that ... Dale's law.\n\nHere $N$ is the number of populations in the network, and the existence of a number of $N_{k}$ external sources is assumed\nwhose activation drive the dynamics of the network. If a steady state exists where the external populations fire at a constant rate,\nthen also the network will settle into a steady state where each population $i$ fires with a constant rate. These rates can be found\nwith Equations \\ref{eq-mui} and \\ref{eq-sigi}. Although this is an elaborate process, computationally it is much faster than\nsimulating a network of large populations, waiting until the network relaxates and then finally collating population statistics.\n\nOne can find solutions to this set of equations by postulating a state $E_i$ for each node $i$, which evolves according to:\n\\begin{equation}\n \\frac{dE_i}{dt} = -E_i + \\phi_i (\\mu_i, \\sigma_i) \n \\label{eq-wc}\n\\end{equation}\nOne can pick 'sensible' values $E_i(0)$ and numerically solve Equation \\ref{eq-wc}. After some time, the values $E_i$ will start to approximate\nthose of the $\\nu_i$, given by Equation \\ref{eq-steady}. \n\nAlthough this seems a roundabout way of doing things, in practice it is convenient since the solution of sets of Equations such\nas \\ref{eq-wc} are precisely what MIIND is designed to do. There is an algorithm provided with MIIND that evolves a node's state\n$E_i$ according to Equation \\ref{eq-wc}. This allows one to play with the values of connectivities, synaptic efficacies, etc.\nand observe their effect on the steady state firing rates of the network.\n\n\\subsubsection{Modeling the Network Dynamics}\n\\label{sec-Fokker-Planck}\nThe methods described in the last section are well established techniques to find the steady state firing rates\nof networks of LIF neuron populations, but there are sitautions where Equation \\ref{eq-wc} provides a poor \nmodel for the transient dynamics of the network, or indeed the stability of the steady state solution. It may well be possible\nthat the network never settles into a steady state. A much better description of the firing rate of neurons is given\nby population density methods. Population density methods do not resort to the simulation of large groups of neuronal models,\nbut instead they define a density function over the neuronal population. Assume the existence of some minimum potential, that\nany neuron in the population is likely to cross with vanishing probaility.\nOne can then define a density function $\\rho(V,t)$, defined as the fraction of neurons in the population that have\ntheir membrane potential in interval $[V, v+ dv)$. Clearly:\n\\begin{equation}\n \\int^{V_{th}}_{V_{min}} \\rho(V,t) dv = 1\n\\end{equation}\nIt can be demonstrated that all relevant quantities that exist at the population level, such as its firing rate, can be calculated\nfrom thsi function. Although mathematically more complex, this method is an order of magnitude more efficient than large\nscale neuronal simulations. \n\nAssume the same situation as in the previous section where we defined the gain function of a population, and consider another\npopulation connecting onto this population with all parameters defined in the same way as before.\n\nIt can be demonstrated (see \\citet{omurtag2000} for a lucid demonstration) that:\n\\begin{equation}\n \\frac{\\partial}{\\partial t} \\rho(V,t) + \\frac{1}{\\tau}\\frac{\\partial \\rho(V,t)}{\\partial V} = \\nu_{ext}( \\rho(V-h,t) - \\rho(V,t)) +\\nu(t) \\delta(V -V_{reset})\n \\label{eq-balance}\n\\end{equation}\nwhere $\\nu(t)$ is given by:\n\\begin{equation}\n \\nu(t) = \\int^{V_{th}}_{V_{th} - h} rho(v,t) dv)\n\\end{equation}\nMoreover, one must impose:\n\\begin{equation}\n \\rho(V_{th},t) = 0\n\\end{equation}\nas a boundary condition. Note that in the limit where $h \\rightarrow 0$, but $\\nu_{ext} h $ is constant, one can Taylor expand the right hand side of\nEquation \\ref{eq-balance} to obtain the form:\n\\begin{equation}\n\\frac{\\partial \\rho(V,t)}{\\partial t} + \\frac{1}{\\tau}\\frac{\\partial}{\\partial}\\left\\{(V - \\mu)\\rho)\\right\\} + \\frac{sigma^2}{2 \\tau}\\frac{\\partial^2}{\\partial v^2} \\rho(V,t) = \\nu_{ext} \\delta (V - V_{reset}),\n\\label{eq-fp}\n\\end{equation}\nwhich is a Fokker-Planck equation.\nIntroducing $\\mathcal{L}_{FP}(\\mu, \\sigma)$ as a shorthand for the second order differential operator defined by Equation \\ref{eq-fp}.\nThe network can now be described by the following set of coupled Fokker-Planck equations:\n\\begin{equation}\n \\mathcal{L}_{FP,i}(\\mu_{i},\\sigma_{i})\\rho_i(V,t) = nu_{i} \\delta(V - V_{reset}),\n\\end{equation}\nwith:\n\\begin{equation}\n \\nu_i = \\int^{V_{th}}_{V_{th}-h} \\rho_i(V,t)\n\\end{equation}\nand $\\mu_i$, $\\sigma_i$ given by Equations \\ref{eq-mui} and \\ref{eq-sigi}. \n\nAlthough the state of each individual node is much more complex than for the simulation described in the previous section. The network structure\nof the simulation is identical. Again, MIIND provides algorithms that can evolve the state $\\rho_i$ of node $i$ numerically, and in this way\nan accurate simulation of transient network dynamics and stability can be simulated without having to model thousands of nodes individually, and then\ncollating their population statistics. The gain in overall efficiency is still large enough to warrant the added complexity of the poulation\ndensity approach.\n\n\\subsubsection{A Hexagonal Network of Populations}\n\\label{sec-hexagon}\nUsing parameters described as biologically plausible elsewhere \\citet{amit1997}, and tinkering with them to obtain\nsteady state firing rates of 2 Hz for the excitatory population and 5 Hz for the inhibitory population, we arrive at the\nconnectivity parameters described in Table \\ref{tab-con}\n\\begin{table}[h]\n\\label{tab-con}\nFor these parameters the network is stable, although not far away from instability: a mere change of $x$ in $J_{EE}$ brings the network\nin a permanent oscillatory state. The convergence of the firing rates and the steady state density distributions are given in Fig \\ref{fig-bingo}.\nThe network can maintain its low level firing rates due a balance of excitation and inhibition and individual neurons in this regime\nwould fire irregularly.\n\n\nWe now reduce take one such local circuit at the centre of a hexagon, and place six others at the cornes of the hexagon. We\nreduce all intra-circuit parameters $J_{EE}$ by a factor half. We connect all excitatory populations laterally by with an efficacy\n$\\frac{1}{2N_{neigh}}$ where $N_{neigh}$ is the number of neighbours. For the centre node $N_{neigh}= 6$ for the outside nodes $N_{neigh} = 3$.\nThis ensures that when all excitatory nodes fire with a firing rate of 2 Hz, the neighbour nodes make up for the lost connectivity,\nthe previous self-stable. Clearly, hexagonal networks with more rings can be created by taking following this procedure, always taking\nthe correct number of neighbours of a node into account. In general the number of populations in the network $N_{pop}$ is given\nby:\n\\begin{equation}\nN_{pop} = 2 ...,\n\\end{equation}\nwhere the factor of two accounts for there being two populations in the circuit. Finally, it is possible to provide a delay\n\\caption{Connectivity parameters for the local cortical circuit.}\n\\end{table}\n\\section*{Acknowledgments}\nThis parallelization of MIIND was carried out as a Google Summer of Code 2012 project. We gratefully acknowledge Google's support. \n\n% The bibtex filename\n\\bibliographystyle{front}\n\\bibliography{pmiind}\n\n\\section*{Figure Legends}\n\\begin{figure}[tbp]\n\t\\includegraphics[width=0.99\\textwidth]{twoPopNetwork.eps}\n \\label{fig:twoPopNetwork}\n \\caption{The network of the two population network simulation.}\n\\end{figure}\n\n\\begin{figure}[tbp]\n\t\\begin{subfigure}[b]{0.48\\linewidth}\n\t\t\\includegraphics[width=0.99\\textwidth]{realNetwork.eps}\n \\caption{An example network representation. The circles correspond to the neurons and the arrows between them to directed connection between them.}\n\t\t\\label{fig-realNetwork}\n\t\\end{subfigure} \n\t\\quad\n\t\\begin{subfigure}[b]{0.48\\linewidth}\n\t\t\\includegraphics[width=0.99\\textwidth]{internalNetwork.eps}\n \\subcaption{The internal representation of the network. The circles correspond to the neurons. The rounded boxes represent the individual MPI Nodes. For the distribution the default circular distribution was used. The dashed arrows correspond to asynchronous MPI messages. The normal arrows correspond to internal messages.}\n\t\t\\label{fig-internalNetwork}\n\t\\end{subfigure}\n \\caption{The real and internal representation of a small network.}\n\\end{figure}\n\n\n\\end{document}\n\n", "meta": {"hexsha": "f49989e499b93562c5be129e2606bb82a876a5d6", "size": 42483, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Publication/pmiind.tex", "max_stars_repo_name": "dekamps/miind", "max_stars_repo_head_hexsha": "4b321c62c2bd27eb0d5d8336a16a9e840ba63856", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2015-09-15T17:28:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T20:26:47.000Z", "max_issues_repo_path": "Publication/pmiind.tex", "max_issues_repo_name": "dekamps/miind", "max_issues_repo_head_hexsha": "4b321c62c2bd27eb0d5d8336a16a9e840ba63856", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 41, "max_issues_repo_issues_event_min_datetime": "2015-08-25T07:50:55.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-21T16:20:37.000Z", "max_forks_repo_path": "Publication/pmiind.tex", "max_forks_repo_name": "dekamps/miind", "max_forks_repo_head_hexsha": "4b321c62c2bd27eb0d5d8336a16a9e840ba63856", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2015-09-14T20:52:07.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T12:18:18.000Z", "avg_line_length": 61.303030303, "max_line_length": 332, "alphanum_fraction": 0.7936821788, "num_tokens": 9794, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.34864513533394575, "lm_q1q2_score": 0.1906175969909071}}
{"text": "\\section{Comparison to DNS - Application to Slope Stability Analysis}\n\nTo validate the up-scaling methodology used, a simple 2-D slope problem is presented and loaded from the top until failure using both DEM and the up-scaled CDM model. Here, the resultant stress distribution are compared just as failure occurs. \n\nIn the DEM model, failure can be assessed based on the unbalanced forces in the model. Since the joints in the model have a stiffness and cohesion, when the slope fails, the explicit quasi-static solution becomes dynamic because of a sudden release of elastic energy and the inability of the applied damping to suppress it all. At this point, the total unbalanced forces in the model increase and the slope can be said to have failed. \n\nFor the CDM model, failure can be assessed based on non-convergence of the model when run as an implicit static simulation, which does not converge when the slope fails. The load step in which the CDM model fails to converge because the slope fails dynamically is considered the point of failure.\n", "meta": {"hexsha": "5c6ad31791a9d25e8b12b0c7d2c36f88048499ff", "size": 1051, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "section_applicationToCAES.tex", "max_stars_repo_name": "yetisir/up-scaling-dem-simulations", "max_stars_repo_head_hexsha": "9c9043effdb72a608ffec11726af97154751722e", "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": "section_applicationToCAES.tex", "max_issues_repo_name": "yetisir/up-scaling-dem-simulations", "max_issues_repo_head_hexsha": "9c9043effdb72a608ffec11726af97154751722e", "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": "section_applicationToCAES.tex", "max_forks_repo_name": "yetisir/up-scaling-dem-simulations", "max_forks_repo_head_hexsha": "9c9043effdb72a608ffec11726af97154751722e", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-06-29T23:14:09.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-29T23:14:09.000Z", "avg_line_length": 131.375, "max_line_length": 435, "alphanum_fraction": 0.8058991437, "num_tokens": 211, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.3486451217982255, "lm_q1q2_score": 0.19061758959041242}}
{"text": "%% ------------------------------------------------------------------------- %%\n\\chapter{Introduction and Motivation} \\label{Chap:Intro}\n\\lettrine[findent=2pt]{\\textbf{T}}{}he parallel and distributed platforms available today become more and more \\textit{heterogeneous}.\nSuch heterogeneous architectures, composed of several kinds of computing units, have had a growing impact on performance in high-performance computing.\nHardware accelerators, such as General Purpose Graphical Processing Units (in short GPUs), are often used in conjunction with multiple computing units (CPUs) on the same chip sharing the same common memory.\nAs an instance of this, the number of platforms of the ~\\cite{TOP500} equipped with accelerators has significantly increased during the last years. In the future it is expected that the nodes of such platforms will be even more diverse than today: they will be composed of fast computing nodes, hybrid computing nodes mixing general purpose units with accelerators, I/O nodes, nodes specialized in data analytics, etc. In order to use all the computational power available, applications should be composed of multiple tasks that allow the usage of the available resources as efficiently as possible. \n\nThe Job Management System (JMS) is the middleware responsible for distributing computing power to applications. A JMS must allocate resources to tasks in order to optimize the use of the available resources while guaranteeing good performance for all applications running in parallel. A promising way to achieve this is using performance prediction. However, in a scenario with millions of processors and a large number of tasks it is very difficult to predict the performance of applications.\n\nJob management systems require that users provide an upper bound of the execution times of their jobs (wall time). Usually, if the execution goes beyond this upper bound, the job is killed. According to~\\cite{Gaj:Trystram:2002}, this leads to very bad estimations, with an obvious bias that tends to overestimate this duration. Moreover, those jobs are subject to uncertainties that depend on the context and other running jobs. The uncertain information is generated by communications and executions that depends on the specific context.\n\nThe GPUs were initially conceived with the purpose to accelerate the 2D and 3D graphics tasks. However, the evolution of the GPU architectures has gone from a single core to a set of dense arrays of highly parallel cores for more general purpose computation. Not surprisingly, the use of this hardware for parallel computing is a very attractive and it is used in several scientific areas. Moreover, nowadays GPUs can be found in a wide number of electronic devices, just to mention a few: desktops, laptops, smartphones, cars and supercomputers~\\citep[chap. 10]{verber2014future}. \n\nGPUs are integrated with multi-core CPUs with the goal to boost more computational processing power. In this way, the regular users have access to a massively parallel environment when acquiring any kind of these devices. Figure \\ref{fig:gflops} shows the theoretical performance and bandwidth reached for those devices, this figure shows a comparison between NVIDIA GPUs and current x86 CPUs. The predominant manufacturer of CPUs are Intel and AMD, and of GPUs are NVIDIA and AMD.\n\n\\begin{figure}[htpb]\n\\centering\n\\includegraphics[width=\\linewidth]{./images/Volta-GPU.png}\n\\caption{Theoretical performance and bandwidth reached for recent GPUs. Copied from~\\cite{CUDAGuide}}\n\\label{fig:gflops}\n\\end{figure}\n\nIn GPU applications the computation is done with a large amount of data, which expose restrictions on the storage space available in the devices and the latency of data transfers~\\citep{Gregg:2011}. GPUs are composed of hundreds and even thousands of simple cores. Figure~\\ref{fig:gpuComp} shows a generic scheme of a heterogeneous system composed of a CPU and a GPU. In this figure we can see that CPUs have much more transistors for control and cache, on other hand GPUs have much more ALUs and few transistors for cache and control. \n\n\n\\begin{figure}[htpb]\n\\centering\n\\includegraphics[scale=.85]{./images/gpu-computing.png}\n\\caption{Multiples Cores CPU + Hundreds or Thousands Cores GPU. Copied from~\\cite{CUDAGuide}}\n\\label{fig:gpuComp}\n\\end{figure}\n\nLast decade with the development of application programming interfaces for GPUs emerged the concept of General Purpose Computing on GPU or GPGPU. GPGPU has evidenced outstanding results in many scientific areas, however, tools to further capitalize these parallel devices and more refined implementations are still emerging~\\citep{CUDAGuide,bsgp}. Researchers in this area can create applications with a concept of parallelism that are able to run on both CPU and GPU architectures. Nevertheless, the implementation of an algorithm, for parallel execution on CPU or GPU, does not guarantee that will execute with the same efficiency in the two architectures. In particular, algorithms with parallelism in large blocks of data, i.e. applications with intensity in array arithmetic and linear data structures, can obtain great benefits when they are implemented for execution exclusively on a GPU~\\citep{zhong2012data, Benedict:12}. \n\nNowadays, GPUs are general purpose parallel processing units with accessible programming interfaces, including standard languages such as C, Java, and Python. In particular, the Compute Unified Device Architecture (CUDA) is a parallel computing platform that facilitates the development of applications which execute in GPU~\\citep{CUDAGuide}. CUDA was introduced by NVIDIA in 2006 for their GPU hardware line. CUDA is a SIMT programming model, it is an extension of SIMD according to Flynn architecture. MIMD is the model used to characterize a machine in an exchange of messages. CUDA is an extension that developers of different languages can use, there is a phase to preprocess the code and extract the CUDA functions. After, CUDA functions are translated into a pseudo-assembly language named PTX (Parallel Threads eXecution), and the graphics driver contains a compiler which translates the PTX into a binary code which can be run on the processing cores.\n\nCUDA applications are organized in kernels, which are functions executed in GPUs. Kernels are compounded of thread blocks of execution and each one of these blocks can have hundreds or even thousands of threads. Each kernel is executed asynchronously, and various kernels can execute concurrently. The programming model allows directive of synchronization in different levels of the memory hierarchy.\n\nThe software development process and performance modeling of GPU applications require a high degree of understanding and knowledge~\\citep{Baghsorkhi:2010:APM}. Performance prediction is often just ignored in a development process, this is due to the in-depth analysis that must be done. Models with specific properties to these problems have been created ~\\citep{Skillicorn:1998:MLP} to facilitate programming on parallel machines. Properties such as synchronization and division of work between computing and communication improve the way developers can solve a problem and how the performance of applications running on parallel machines can be modeled.\n\nThe accuracy of a GPU performance model is subject to low-level elements such as instruction pipeline usage and cache hierarchy. GPU performance approaches its peak when the instruction pipeline is saturated but becomes unpredictable when the pipeline is under-utilized~\\citep{Baghsorkhi:2010:APM}. Effects of cache hierarchy and memory-access divergence are also critical to GPU performance models. Some parallel programs can be efficiently executed on some architectures, but not on others. \n\nPerformance prediction over these devices is a great challenge because hardware characteristics can impact their performance in different ways. There are different approaches to do this, such as analytical modeling and machine learning techniques. Analytic predictive models are useful, but require the manual inclusion of interactions between architecture and software, and may not capture the complex interactions in GPU architectures. Machine learning techniques can learn to capture these interactions without manual intervention but can require large training sets. \n\nThere are different models of parallel machines that help to deal with these problems. Among these models, we have the Parallel Random Access Memory (PRAM), Bulk Synchronous Parallel (BSP) and Coarse Grained Multicomputer (CGM). The main objective of a parallel computing model is to provide a set of parameters that have an impact on the performance of applications in parallel architectures, and thus to be able to simulate the behavior of these applications in their respective architectures.\n\nThe Bulk Synchronous Parallel is a computing model for parallel computing introduced for~\\cite{Valiant:1990}, BSP model provides a simple but accurate characterization of all parallel machines-past, present, and future. There are other parallel models parameterized, almost all of them using or extending the focus of the BSP model. \\cite{Dehne:2002} studied the problem to design scalable parallel geometric algorithms for the Coarse Grained Multicomputer model which are optimal or at least efficient for a wide range of the ratio $\\frac{n}{p}$, with $n$ the size of the problem and $p$ the number of processors.\n\nThe BSP model allows developers to design algorithms and software that can run on any standard parallel architecture with very high performance~\\citep{goldchleger2005implementation}. This model may potentially serve as a unified programming model for both coarse-grained and fine-grained. The model BSP has been implemented as API libraries and programming languages \\citep{BSPLib} and API libraries have been developed to use BSP on GPU architectures~\\citep{bsgp}, these developments are to create scientific applications in massively parallel environments computing in an easy and better way. Recently, ~\\cite{Valiant:2011} has implemented the BSP model over multicore architectures. The implementation of BSP model for multicore architecture incorporates the memory size shared as a further parameter in the computer. The BSP model is a good alternative to tackle parallel problems in massively parallel architectures. \n\n%Data are produced either by the Job management systems, to effectively leverage these platforms, and by the user's applications that are executed. These applications could be in execution, awaiting execution, monitoring the machine, so forth. While this happens, a lot of information is registered in traces. There are several recent works on using this information~\\citep{Tsafrir:Backfilling:2007,Lublin01theworkload,Ernemann:2003}, in other cases these data are ignored by the job management systems~\\citep{andreetto2008glite}. \n\nThe developed methods in the area of \\textbf{big data} (especially machine learning) can be used for the scheduling of jobs in new computing platforms to large scale. Information about profiling and traces of heterogeneous applications can be used to improve current JMS, which require a better knowledge of the applications~\\citep{JMR:Ruiz:2014}. To predict execution or communication times in heterogeneous applications is a great challenge, for this reason, it always is meritorious to research more effective mechanisms to obtain a better performance prediction.\n\nThis thesis is related to the modeling and performance prediction of applications executed in GPUs using approaches of analytical model and machine learning techniques. Considering that the market has been taken by NVIDIA graphics cards, our models and experimentation are done on GPUs manufactured by NVIDIA. We evaluated our model using 9 developed kernels and other kernels from Rodinia Benchmark suite~\\citep{Rodinia:Che:2009}, Rodinia has been used and accepted by the GPGPU community~\\citep{che:2010:Rodinia, nagasaka:2010:Rodinia}, and is used in various GPU simulators~\\citep{power:2014:gem5-gpu}.\n\nThese CUDA kernels were executed over GPUs with different architectures among these architectures are Kepler, Maxwell, and Pascal. We showed by using profile information for a single board, that the models are general enough to predict the execution time of an application with different input sizes and on different boards.\n\nThis thesis also presents the creation of a benchmark, which is freely available in Standard Workload Format (SWF), consisting of five applications of dense linear algebra from the Chameleon software~\\citep{agullo2012morse} and a \\emph{fork-join} application generated using GGen~\\citep{GGen:simutools10}, this benchmark was used for ~\\cite{mommessin:2017, mommesin:2017:CCPE} in the experimental evaluation of on-line and off-line scheduling algorithms in machines with heterogeneous resources. \n\nThis benchmark is available online in a web-based hosting service for version control using git, inside the repository, there are a set of application workloads with their respective execution times and dependencies, researchers can use it to test scheduler algorithms of task-based applications over CPU and GPUs. \n\n%Our model predictions were within $XXXX$ to $XXXX$ times the measured execution times, which are reasonable for such a simple model. These results indicate that the model is good enough to generalize the predictions for different problem sizes and GPU configurations.\n\n\\section{Objectives and Thesis Contributions}\nThe main propose of this work is to present an analysis and design of techniques to predict the performance of applications executed on General-purpose Graphic Processing Units.\n\nIn this thesis, we first present an analysis and design of an easy and simple BSP-based model to predict the performance of GPU applications~\\citep{amaris:2015:HiPC}. The model is based on the number of computations and memory accesses of the GPU, with additional information on cache usage obtained from profiling. Scalability, divergence, the effect of optimizations and differences of architectures are adjusted by a single parameter.\n\nWe also evaluate the use of different machine learning techniques to reach the same objective. We compare three different machine learning approaches: linear regression, support vector machines and random forests with our BSP-based analytical model~\\citep{amaris:2016:NCA}. Our main contribution was showing that machine learning techniques provided acceptable predictions for all the applications over all the GPUs. Although the analytical model provided better predictions for some applications, it requires a deep analysis and knowledge of the applications and hardware structure. Consequently, machine learning techniques can be useful for deploying automated on-line performance prediction for scheduling applications on heterogeneous architectures with GPUs, whenever a large data set with information about similar applications is available.\n\nFinally, we developed a benchmark of task-based applications executed on heterogeneous machines. These files are saved in format SWF (Standard Workload Format). This format was defined in order to use a pattern accepted and well used for the community in scheduling research. The benchmark is collected of six parallel applications. Five of them have been created from Chameleon, a dense linear algebra software which is part of the MORSE project~\\citep{agullo2012morse}, while the sixth is a fork-join application generated automatically with GGen, a library for generating directed acyclic graphs~\\citep{GGen:simutools10}. This benchmark has been tested for \\citep{mommessin:2017, mommesin:2017:CCPE}. \n\nThis work was presented in the Doctoral Showcase of the International Conference for High Performance Computing, Networking, Storage and Analysis of 2017. In this conference, a summary of the thesis was presented in a short talk and poster. \n\nWe list the publications directly related to this thesis. %Each one of these papers can be found in the appendix~\\ref{app:papers} in the same order as they are presented below.\n\n\\begin{itemize}\n\n\\bibitem[Amaris {\\rm{\\em et~al.}} (2015)Amaris, Cordeiro, Goldman, e\n Camargo]{amaris:2015:HiPC}\n{\\bf Marcos Amaris}, Daniel Cordeiro, Alfredo Goldman e Raphael~Y.de Camargo.\n\\newblock A simple bsp-based model to predict execution time in gpu\n applications.\n\\newblock In \\emph{High Performance Computing (HiPC), 2015 IEEE 22nd\n International Conference on}, p\\'{a}ginas 285--294.\n \n\\bibitem[Amaris {\\rm{\\em et~al.}} (2016)Amaris, de~Camargo, Dyab, Goldman, e\n Trystram]{Amaris:2016:NCA}\n{\\bf Marcos~Amaris}, Raphael~Y.de Camargo, Mohammed~Dyab, Alfredo~Goldman e Denis~Trystram.\n\\newblock A comparison of GPU execution time prediction using machine learning\n and analytical modeling.\n\\newblock In \\emph{2016 IEEE 15th International Symposium on Network Computing\n and Applications (NCA)}, pages 326--333.\n\n \\bibitem[Mommessin {\\rm{\\em et~al.}} (2017)Mommessin, Amaris, Lucarelli, e\n Trystram]{Mommessin:2017}\nClement~Mommessin, {\\bf Marcos~Amaris}, Giorgio~Lucarelli and Denis~Trystram.\n\\newblock Generic algorithms for scheduling applications on hybrid multi-core\n machines.\n\\newblock In \\emph{2017 Euro-Par: International Conference on Parallel and\n Distributed Computing}, pages 220--231. \n \n \\bibitem[Mommessin {\\rm{\\em et~al.}} (2018)Mommessin, Amaris, Lucarelli, e\n Trystram]{mommesin:2017:CCPE}\nClement~Mommessin, {\\bf Marcos~Amaris}, Giorgio~Lucarelli and Denis~Trystram.\n\\newblock Generic algorithms for scheduling applications on heterogeneous multi-core platforms\n\\newblock \\emph{arXiv preprint arXiv:1711.06433} in revision. Submmited in \n\\emph{Concurrency and Computation: Practice and Experience}\n\\end{itemize} \n\nThere are other works which were published during the Doctorate of the candidate and are indirectly related to this thesis:\n%\\cite{bruel:2015:WSCAD}\\cite{gonccalves:2016:HICSS}\\cite{okada:2015:WSCAD}\\cite{bruel:2017:CCPE}\n\n\n\\begin{itemize}\n \\bibitem[Okada {\\rm{\\em et~al.}} (2015)Okada, Amar{\\'\\i}s, e vel\n Lejbman]{okada:2015:WSCAD} \nThiago~Kenji Okada, {\\bf Marcos Amar{\\'\\i}s} e Alfredo~Goldman vel Lejbman.\n\\newblock Scheduling moldable bsp tasks on clouds.\n\\newblock In \\emph{WSCAD'15 - XVI Simp{\\'o}sio em Sistemas Computacionais de\n Alto Desempenho},\n \n \\bibitem[Bruel {\\rm{\\em et~al.}} (2015)Bruel, Amar{\\'\\i}s, e\n Goldman]{bruel:2015:WSCAD}\nPedro Bruel, {\\bf Marcos Amar{\\'\\i}s} and Alfredo Goldman.\n\\newblock Autotuning gpu compiler parameters using opentuner.\n\\newblock In \\emph{WSCAD'15 - XVI Simp{\\'o}sio em Sistemas Computacionais de\n Alto Desempenho}, pages\\'{a}ginas 13--23.\n \n \n \\bibitem[Gon{\\c{c}}alves {\\rm{\\em et~al.}} (2016)Gon{\\c{c}}alves, Amar{\\'\\i}s,\n Okada, Bruel, e Goldman]{gonccalves:2016:HICSS}\nRog{\\'e}rio Gon{\\c{c}}alves, {\\bf Marcos Amar{\\'\\i}s}, Thiago Okada, Pedro Bruel and\n Alfredo Goldman.\n\\newblock Openmp is not as easy as it appears.\n\\newblock In \\emph{49th Hawaii International Conference on System Sciences}, January-2016,\n pages 5742--5751.\n\n\\bibitem[Bruel {\\rm{\\em et~al.}} (2017)Bruel, Amar{\\'\\i}s, e\n Goldman]{bruel:2017:CCPE}\nPedro Bruel, {\\bf Marcos Amar{\\'\\i}s} and Alfredo Goldman.\n\\newblock Autotuning cuda compiler parameters for heterogeneous applications\n using the opentuner framework.\n\\newblock \\emph{Concurrency and Computation: Practice and Experience}\n 29\\penalty0 (22). 2017\n\\end{itemize} \n\n\\section{Thesis Outline}\nThis document is organized into 6 chapters. In Chapter~\\ref{chap:characterization}, we show a detailed analysis and characterizations of GPU applications, Chapter~\\ref{chap:BSPmodel} shows our proposed BSP-based model used to predict execution times of GPU applications. Chapter~\\ref{Chap:ML} presents a machine learning approach for predicting execution times and compare the predictions with those of the analytical model. Chapter~\\ref{Chap:Bench} describes the creation of a benchmark of task-based applications executed over heterogeneous resources, CPU and GPUs. Finally we present the conclusions and future works in the Chapter~\\ref{chap:conclusion}", "meta": {"hexsha": "bb34bc6e775fc9548b57d06328db6fb198dd0848", "size": 20150, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "docs/thesis/chapters/introduction.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/chapters/introduction.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/chapters/introduction.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": 134.3333333333, "max_line_length": 961, "alphanum_fraction": 0.8060545906, "num_tokens": 4475, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.36658974324230986, "lm_q1q2_score": 0.19045118802332314}}
{"text": "% !TeX spellcheck = en_GB\n\\section{Optimal Estimation Retrieval Algorithm} %Section - 1.2\n\\label{sec:retrieval}\nThe purpose of this study is to apply an optimal-estimation snowfall retrieval on ground based measurements to estimate the surface accumulation and vertical snow water content for an extreme event during Christmas 2016. These will later be used to compare to \\SI{48}{\\hour} MEPS model forecasts to see if the model was able to predict synoptical features and precipitation related to the extreme event 'Urd' in 2016. \n% maybe start out by saying that you are trying to estimate atmospheric parameters (SWC in our case) from a set of measurements. The optimal-estimation approach provides a flexible retrieval framework that can incorporate multiple measurements/ pieces of information into a common retrieval framework. In this way, we can use measurements from MRR, PIP, and MASC to estimate vertical profiles of snowfall. You could then discuss the reindeer -> tracks thing to illustrate the general principle. \n% literally taken from paper until Skofronick, Noh\nThe quantitative estimation of snowfall at the global scale from spaceborne measurements has been available only recently. Initial retrieval approaches were based on passive microwave measurements \\citep{skofronick-jackson_physical_2004,noh_development_2006}. But since these passive measurements can only assess total integrated snow water path for a given column, such efforts were unable to provide much information on the profiles of snow water content. \nThe launch of the CloudSat \\SI{94}{\\giga\\hertz} Cloud Profiling Radar (CPR) in 2006, however, provided the first opportunity to examine such vertical structure at a global scale. \n%Several studies, such as \\citet{matrosov_modeling_2007} and \\citet{kulie_utilizing_2009}, have shown that the CPR can be used to estimate snofall rate but that estimated snowfall values depend heavily upon assumed snowflake microphysical properties. \nSeveral studies have shown, that estimated snow rate depends upon retrieval assumptions such as snowflake habit and particle size distribution (PSD) and can give large differences for a given radar reflectivity.\n\\\\\nFor the operational CloudSat snowfall retrieval scheme (2C-SNOW-PROFILE), \\citet{wood_microphysical_2015} developed snowflake particle models based upon video snow disdrometer observations from the Canadian CloudSat-CALIPSO Validation Project \\citep[C3VP,][]{hudak_canadian_2006}. Scattering properties for these snow particle models were based upon the Discrete Dipole Approximation (DDA) method. \n%It was hoped that the use of realistic snow properties in the retrievals would lead to reasonable estimates of snowfall in the retrieval. \nIn addition, they derived an a priori relationship between particle size distribution and temperature that they could use as an additional constraint for the snowfall scheme. Use of the flexible optimal-estimation retrieval framework allowed to develop a best estimate of snow properties that are consistent with both the CPR reflectivities and the a priori constraint. \n\\\\\nThey have also been used to estimate snowfall in remote locations such as the Antarctic and Arctic \\citep{palerme_how_2014,kulie_shallow_2016} that in turn have been used to evaluate the representation of snowfall in climate models \\citep{palerme_evaluation_2017,christensen_arctic_2016}. \nThese estimates have been used to assess the performance of ground-based radar schemes such as those based upon the operational weather radar system in Sweden \\citep{norin_intercomparison_2015}. Despite such progress, however, the CloudSat scheme can still lead to uncertainties in the retrievals of up to \\SIrange{140}{200}{\\percent} \\citep{wood_estimation_2011} for individual storms.\n\\\\\nAgain, these uncertainties arise from the large variance in snowflake microphysical properties as observed in nature. In response, \\citet{cooper_variational_2017} explored the use of in-situ, event specific observations of snowflake microphysical properties to improve radar-based retrievals of snowfall. This work was based upon observations from the Ka-band ARM (The Atmospheric Radiation Measurement) Zenith Radar (KAZR) and Multi-Angle Snow Camera (MASC) deployed at the ARM Climate Facility Site at Barrow, Alaska in Spring 2014. This ground-based \\SI{35}{\\giga\\hertz} retrieval scheme was modified from the space-borne \\SI{94}{\\giga\\hertz} CloudSat retrieval scheme developed by \\citet{wood_estimation_2011}. But instead of using a temperature dependent a priori characterisation of PSD, \\citeauthor{cooper_variational_2017} introduced the in-situ observations of particle size distribution through the a priori terms of the optimal-estimation framework. \n\\\\\n%\nPreliminary analyses suggested good performance for this retrieval scheme at Barrow, Alaska. Estimates of snowfall from the \\citet{cooper_variational_2017} approach differed by \\SI{18}{\\percent} relative to nearby National Weather Service snow gauge measurements for total accumulation over multiple snow events. However, given limited snowfall observed at Barrow during the deployment of the MASC, it was difficult to come to any definitive conclusions about retrieval performance. The NSF (National Science Foundation) funded field campaign with MRR, MASC, and PIP (Precipitation Imaging Package) deployment at Haukeliseter provides an ideal opportunity to further explore the \\citet{cooper_variational_2017} retrieval approach. This thesis will continue to examine the sensitivity of retrieval surface snowfall rate to assumptions of habit, fall speed, and particle size distribution as in \\citet{cooper_variational_2017}. In addition, this study here will will examine the vertical profiles of snowfall profiles in the atmospheric column.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%\\newpage\n%%%% OE scheme %%%%%%%\n\\subsection{Snowfall Retrieval Scheme}\\label{sec:ret_scheme}\n%%% image forward problem %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\input{./images_tex/retrieval_dragon_track}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nThe optimal-estimation snowfall retrieval scheme was modified for the Barrow instrumentation described in \\citet{cooper_variational_2017} to the \\SI{24}{\\giga\\hertz} MRR, MASC, and PIP located at Haukeliseter. This scheme was then used to derive surface snowfall rates and vertical profiles of snow water content using different combinations of retrieval assumptions based upon in-situ observations.\nHere a discussion of the optimal-estimation framework is presented so that the reader can understand exactly how the different measurements in the retrieval scheme were incorporated. The differences in the forward and inverse problem are reviewed in the beginning. Both, forward and inverse problem underlie the basic methodologies of remote sensing.\n\\par\\medskip\\noindent\nThe general concepts of forward and inverse problems are illustrated in \\Cref{fig:dragon}. The forward problem describes the relationship between the physical parameters of interest and the measurements (\\Cref{fig:dragon:forward}). In \\Cref{fig:dragon:inverse}, the physical parameter is the reindeer and the measurements are its tracks. In the here presented thesis snowfall scheme, the physical parameters are the vertical profiles of snow water content (SWC) and the measurements are the MRR reflectivities. The inverse problem represents the opposite goal. The physical entity (reindeer and SWC) must be inferred from the measurements (reindeer tracks or MRR reflectivities).\n\\\\\nThe optimal-estimation framework is used to solve the inverse problem for the thesis work. But it is more complex than the direct inversion as represented in \\Cref{fig:dragon:inverse}. Instead of inverting directly for the parameter of interest (SWC) from the measurements [\\SI{}{\\decibel ze}], the scheme includes additional information based upon an 'a priori' understanding of the physics of the retrieval problem. Thus, it represents a weighted balance between what the data can tell about the state and what is already known about it. For the CloudSat retrieval scheme, this a priori information came from a parametrisation relating particle size distribution (PSD) to temperature. For the Barrow and Haukeliseter schemes, the a priori information could also come from the in-situ observations of snowflake microphysics. These constraints also add numerical stability to the inversion process when there are either calibration errors in the measurements or uncertainties in the forward model that relates the physical parameter to measurement space. Details of the radar forward model are discussed at the end of this section.\n\\\\\nThe optimal estimation method is based on Gaussian statistics. It solves for snowfall properties of interest or retrieval vector, $\\mathbf{x}$, by minimizing the scalar cost function, $\\Phi$ , as in \\Cref{eq:scalar_cost_fct}.\n\\begin{equation}\n\\begin{split}\n\\Phi(\\mathbf{x},y,a) = & (y- F(\\mathbf{x}))^T \\mathbf{S}_y^{-1} \t\t\t(y-F(\\mathbf{x})) \\\\\n&+(\\mathbf{x}-a)^T \\mathbf{S}_{a}^{-1} (\\mathbf{x}-a)\n\\end{split} \\label{eq:scalar_cost_fct}\n\\end{equation}\nSpecifically, or this thesis retrieval scheme, $\\mathbf{x}$ represents the PSD parameters of slope and number intercept of an assumed exponential size distribution for each radar range bin as in \\Cref{eq:num_dens}. $y$ is the vector of MRR reflectivites. The vector $a$ is the a priori guess for slope parameter and number in each range bin. $F(\\mathbf{x})$ represents the forward model that translates snow properties into reflectivity space. Minimizing the cost function therefore seeks to reduce the difference between the observations, $y$, and simulated observations, $F(x)$ and between the a priori guess ($a$) and the retrieval vector ($x$).\n\\begin{align}\n\tn(r) & = N_{0} \\exp\\left(-\\lambda r\\right) \\qquad [ \\SI{}{\\per\\cubic\\metre\\per\\mm} ] \\label{eq:num_dens}\n\\end{align}\nThe $\\mathbf{S}_y$ and $\\mathbf{S}_{a}$ terms, in \\Cref{eq:scalar_cost_fct}, represent the forward model and measurement error covariance matrix and the a priori error covariance matrix, respectively. The relative differences between $\\mathbf{S}_{a}$ and $\\mathbf{S}_y$ weight the importance of the observations and the a priori considerations in determining our best estimate of PSD properties. \n\\\\\nNewtonian iteration is used until the value of the cost function converges and our best estimate of snowfall properties are found. The optimal-estimation scheme also provides error diagnostics through the retrieval error covariance matrix, $\\mathbf{S}_x$, as in \\Cref{eq:Sx}.\n\\begin{align}\n\t\\mathbf{S}_x & = \\left( \\mathbf{S}_a^{-1} + \\mathbf{K}^T \\mathbf{S}_y^{-1} \\mathbf{K} \\right)^{-1}\\label{eq:Sx}\n\\end{align}\nThe Jacobian matrix, $\\mathbf{K}$, represents the sensitivity matrix of the perturbed result of the forward model. The true state $\\mathbf{x}$ is perturbed by \\SI{0.2}{\\percent} and thus $\\mathbf{K}$ represents the relation between simulated values to the true state and how sensitive the simulated values are to small changes when starting a new retrieval cycle. The closer $\\mathbf{K}$ is diagonal, the more is $\\mathbf{x}$ determined by the real observed and a priori values. If the limit of the partial derivative is close to unity, the retrieved value $\\mathbf{x}$ is its true state \\citep{wood_estimation_2011}.\n\\\\\nIn practical application for this multiple layer retrieval scheme, log-transformed particle size distribution parameters of slope and number intercept were used due to the large expected range of these variables. The state vector, $\\mathbf{x}$, is defined in \\Cref{eq:snow_prop}.\n\\begin{align}\n\t\\mathbf{x} & = \\begin{bmatrix}\n\t\tlog(\\lambda)_0 \t\\\\\n\t\t\\vdots \t\t\t\\\\\n\t\tlog(\\lambda)_{\\text{nlayer}} \t\\\\\n\t\tlog(N_0)_0\t\t\\\\\n\t\t\\vdots\t\t\t\\\\\n\t\tlog(N_0)_{\\text{nlayer}}\t\t\n\t\\end{bmatrix} \\qquad \\text{nlayer} = 14\n\t\\label{eq:snow_prop}\n\\end{align}\nThe usage of a priori terms were explored both from in-situ microphysical observations and from the PSD-temperature relationship developed for the CloudSat scheme as in \\Cref{eq:lambda,eq:N0}. Temperatures in \\SI{}{\\celsius} at Haukeliseter were taken from site measurements with an assumption of a moist adiabatic lapse rate for the observed snow events. The log transformed slope and number intercept values were taken from \\citet{wood_estimation_2011}. \n\\begin{align}\n\t\\log(\\lambda) & = -0.03053 \\cdot T_{ap} - 0.08258 \\label{eq:lambda} \\qquad [ \\log(\\SI{}{\\per\\mm}) ] \\\\\n\t\\log(N_0) & = -0.07193 \\cdot T_{ap} +2.665 \\qquad [ \\log(\\SI{}{\\per\\cubic\\metre\\per\\mm})]\n\t\\label{eq:N0}\n\\end{align}\nThe log-transformed equations are useful, since the results from C3VP were similar to other observations. The study showed, that $N_0$ ranges over several order of magnitude as well as $\\lambda$ was non-Gaussian for the snow events \\citet{wood_estimation_2011}. The diagonal matrix elements in $\\mathbf{S}_a$ (\\Cref{eq:scalar_cost_fct,eq:Sx}) are equal to \\numlist{0.133;0.95} for the particle slope parameter and the number intercept, respectively, as from Eq. 7.35 and 7.36 in \\citet{wood_estimation_2011}. The diagonal matrix elements for $\\mathbf{S}_y$ are $2.5^2$ in \\Cref{eq:scalar_cost_fct,eq:Sx}.\n\\\\\nAfter the best estimate of PSD parameters are found, the snow water content in each layer is calculated using the snow particle mass-dimension relationships as in \\Cref{app:scat_scheme}. \n%\n\\begin{align}\n\t\\text{SWC} & = \\int_{r_{min}}^{r_{max}} m(r) n(r) dr \\qquad [\\SI{}{\\gram\\per\\cubic\\metre}] \\label{eq:SWC}\n\\end{align}\n$r$ is the particle maximum dimension and $m(r)$ the related mass. \n\\par\\medskip\\noindent\nThis thesis work considered the database of particle models developed for the CloudSat mission, e.g. different types of aggregates, sector plates, and columns. Scattering properties for these snowflakes were calculated for the \\SI{24}{\\giga\\hertz} frequency using discrete dipole approximation (DDA). Observations from the MASC of snowflake habit were used to guide particle selection. Snow water content, in turn, was translated into a snowfall rate using fall speed observations (MASC, PIP, or MRR Doppler velocity) or climatological analyses ($V = \\SI{0.85}{\\mPs}$). Surface snowfall rate is estimated using the SWC from the lowest non-noise reflectivity and radar bin. \n\\\\\nThe forward model that calculates simulated \\SI{24}{\\giga\\hertz} MRR reflectivities from PSD parameters was modified from that used in the CloudSat \\SI{94}{\\giga\\hertz} operational snowfall product (2C-SNOW-PROFILE). Backscatter from frozen hydrometeors in each radar bin is summed up as in \\Cref{eq:backscatter} form which reflectivity factor, Z, can be found (\\Cref{eq:singleZ}). \n% singly-scattered non-attenuated reflectivity\n\\begin{align}\n\t\\eta_{bk} & = \\int_{r_{min}}^{r_{max}} n(r) \\sigma_{bk} dr \\qquad [\\SI{}{\\per\\metre}] \\label{eq:backscatter} \\\\\n\tZe^{ss,na} & = \\frac{\\Lambda^4}{\\left\\| K_w \\right\\|^2 \\pi^5} \\eta_{bk} \\qquad [\\SI{}{\\mm^6\\metre^{-3}}] \\label{eq:singleZ}\n\\end{align}\nWhere, $\\Lambda$ is the wavelength of the radar; $\\left\\| K_w \\right\\|^2$ is the complex refractive index of water. Radar backscatter values were estimated using discrete dipole approximation for the CloudSat particle models at \\SI{24}{\\giga\\hertz}. Unlike the \\SI{94}{\\giga\\hertz} spaceborne CloudSat mission, multiple scattering and attenuation can be neglected for \\SI{24}{\\giga\\hertz} MRR and the short path length retrievals as viewed from the ground perspective. \n\n%\\newpage\n\\subsection{Environmental Masks for the Optimal Estimation Retrieval}\\label{sec:pre_snow}\nDifferent steps and assumptions are done in the here presented snowfall retrieval, to achieve vertical profiles of snowfall from MRR. The snowfall rate at the surface can be estimated from one of the lower levels. The optimal estimation retrieval is only performed for profiles, which are likely to have observed snow. \n%Relationships between reflectivity and snowfall have been developed in previous studies. Different crystal shapes led to different results, even if the PSD of ice particles is known. Snow densities vary significantly from storm to storm, where small particles are still Rayleigh scattered, and larger particles non-Rayleigh scattered \\citep{gunn_microwave_1954}. \n%%%% image surface temperature and MRR %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\input{./images_tex/retrieval_MRR_sfcT}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\noindent\n\\\\\nThis value was chosen as sensitivity studies \\citep[e.g.][]{wood_level_2013} that a days worth of such reflectivities would produce only a trace of snow. Such a value therefore guarantees that a significant snow event is not missed and that any storms with lower \\SI{}{\\decibel Z} values would not produce meaningful precipitation.\n%A reflectivity threshold of \\SI{- 15}{\\decibel Z} was selected for the scheme. The threshold is similar to the one used in \\citet{wood_level_2013}. Light liquid precipitation is related to \\SI{- 10}{\\decibel Z} \\citep{stephens_properties_2007}. \\citet{wood_estimation_2011} found, that the reflectivity above \\SI{-15}{\\dB Z} are not influenced by ground clutter, when the reflectivity in the lowest bin and adjacent bin is compared.\nThe Haukeliseter measurement site is equipped with a weather mast, measuring the air temperature every minute at two-meter height (compare \\Cref{fig:MRR_sfcT}, upper panel). \nSince the MRR measures above \\SI{300}{\\metre} and temperature measurements exists only at the surface, a priori temperature ($T_{ap}$) at the surface is assumed to be similar to the observed near-surface air temperature. The use of a moist adiabatic lapse rate of $dT/dz = \\SI{5}{\\kelvin\\per\\km}$ gives $T_{ap}$ in each layer. \nSnow existence at temperature measurements up to a threshold of +\\SI{2}{\\celsius} are assumed. \\citet{liu_g._deriving_2008} validated this threshold, by analysing present weather reports to find the distinction between liquid and solid precipitation.\\\\\nThe purple line in the lower panel of \\Cref{fig:MRR_sfcT} represents the time frame during \\SI{25}{\\dec}, where the MRR reflectivity is less than \\SI{- 15}{\\decibel Z}, and a priori temperature passes the \\SI{2}{\\celsius} limit at the surface. \n", "meta": {"hexsha": "5c2bb5f1466a533ec31c1001008cf8368d48c20b", "size": 18284, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "thesis_full/Data_Instrument_Methods/Retrieval.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/Retrieval.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/Retrieval.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": 167.7431192661, "max_line_length": 1131, "alphanum_fraction": 0.7762524612, "num_tokens": 4474, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.36658973632215985, "lm_q1q2_score": 0.19045118442815764}}
{"text": "\\subsection{Datasets}\n\\begin{frame}\n \\frametitle{Modeling the University of Illinois}\n \\begin{itemize}\n \\item All data is from the University of Illinois\n \\item UIUC is a good model for thinking about hybrid energy systems.\n \\begin{itemize}\n \\item Solar Power\n \\item Wind Power\n \\item Natural Gas\n \\item District Heating\n \\end{itemize}\n \\end{itemize}\n\\end{frame}\n\n\\subsection{Echo State Networks}\n\\begin{frame}\n \\frametitle{Echo State Networks}\n \\begin{figure}\n \\includegraphics[width=\\textwidth]{reservoir_network.jpg}\n \\caption{A conceptual diagram of an echo state network. The reservoir is a large sparse matrix with randomly assigned entries \\cite{pathak_model-free_2018, lukosevicius_practical_2012}.}\n \\label{fig:resnet}\n \\end{figure}\n\\end{frame}\n\n\\begin{frame}\n \\frametitle{Hyper-parameter Optimization}\n \\begin{columns}\n \\column[t]{5cm}\n \\begin{figure}\n \\includegraphics[width=\\columnwidth]{solar-angle-gridsearchNP.png}\n \\caption{A grid search for the set of noise and spectral radius, $\\rho$, that minimizes the mean squared error.}\n \\label{fig:gridsearch}\n \\end{figure}\n \\column[t]{5cm}\n \\vspace{1cm}\n \\begin{align}\n MSE = \\frac{1}{N}\\sum_i^N(\\hat y - y_i)^2\n \\end{align}\n\n \\begin{itemize}\n \\item The optimal set of parameters is ``reservoir specific''\n \\item Several other parameters need to be optimized such as:\n \\begin{itemize}\n \\item Reservoir Size\n \\item Sparsity\n \\item Training Length\n \\end{itemize}\n \\end{itemize}\n \\end{columns}\n\\end{frame}\n\n\\begin{frame}\n \\frametitle{Uncertainty Analysis}\n \\begin{figure}\n \\centering\n \\includegraphics[width=0.85\\textwidth]{demsol-bars01.png}\n \\caption{Total demand prediction with error bars. The 60\\% confidence is $\\pm 1\\sigma$ and the 95\\% confidence interval is $\\pm 2\\sigma$. Mean is generated from predictions made by several different reservoirs.}\n \\label{fig:uncertainty}\n \\end{figure}\n\\end{frame}\n", "meta": {"hexsha": "6f44a242c4eecec4de9032fb5a98e52ddde6c301", "size": 2062, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "publications/forecasting-pres/methods.tex", "max_stars_repo_name": "samgdotson/CAIRO", "max_stars_repo_head_hexsha": "dadc59c5f3ae42b78147ffc4e54e95fb5421ca91", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-09-11T18:27:30.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-11T18:27:30.000Z", "max_issues_repo_path": "publications/forecasting-pres/methods.tex", "max_issues_repo_name": "samgdotson/CAIRO", "max_issues_repo_head_hexsha": "dadc59c5f3ae42b78147ffc4e54e95fb5421ca91", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 68, "max_issues_repo_issues_event_min_datetime": "2019-09-19T19:40:13.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-25T20:03:06.000Z", "max_forks_repo_path": "publications/forecasting-pres/methods.tex", "max_forks_repo_name": "samgdotson/CAIRO", "max_forks_repo_head_hexsha": "dadc59c5f3ae42b78147ffc4e54e95fb5421ca91", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-10-01T18:27:43.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-11T07:37:44.000Z", "avg_line_length": 33.2580645161, "max_line_length": 215, "alphanum_fraction": 0.6823472357, "num_tokens": 572, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.1902450726330614}}
{"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%% tW %%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Single-top \\texorpdfstring{$tW$}{tW} associated production}\n\\label{subsec:tW}\n\nThis section describes the MC samples used for the modelling of single-top $tW$ associated production.\nSection~\\ref{subsubsec:tW_PP8} describes the \\POWPY[8] samples -- both for the diagram removal (DR) set-ups,\nwhich are used for the nominal prediction as well as uncertainties due to additional radiation and PDFs, \nand for the diagram subtraction (DS) set-ups, which are used for the uncertainty due to the treatment \nof the overlap with \\ttbar production. \nSection~\\ref{subsubsec:tW_PH7} describes the \\POWHER[7] samples used for the uncertainty \ndue to parton showering and hadronisation modelling, and Section~\\ref{subsubsec:tW_aMCP8} describes the \n\\MGNLOPY[8] samples used for the uncertainty due to the choice of matching scheme.\n\nThe reference cross-section values are extracted from Ref.~\\cite{LHCTopWGsgtopXsec}.\n\n\\subsubsection[Powheg+Pythia8]{\\POWPY[8]}\n\\label{subsubsec:tW_PP8}\n\n\\paragraph{Samples}\n%\\label{par:tW_PP8_samples}\n\nTable~\\ref{tab:tW_PP8} gives the DSIDs of the $tW$ \\POWPY[8] samples, for both the DR and DS schemes.\nSingle-top and single-anti-top ($tW^-$ and $\\bar{t}W^+$) events were generated in different samples.\nThe dileptonic samples overlap with the inclusive ones.\n\\begin{table}[htbp]\n\\begin{center}\n\\caption{Single-top $tW$ associated production samples produced with \\POWPY[8].} \n\\label{tab:tW_PP8}\n\\begin{tabular}{ l | l }\n\\hline\nDSID & Description \\\\\n\\hline\n410646 & $tW^-$ (DR) inclusive \\\\\n410647 & $\\bar{t}W^+$ (DR) inclusive \\\\\n410648 & $tW^-$ (DR) dileptonic \\\\\n410649 & $\\bar{t}W^+$ (DR) dileptonic \\\\\n\\hline\n410654 & $tW^-$ (DS) inclusive \\\\\n410655 & $\\bar{t}W^+$ (DS) inclusive \\\\\n410656 & $tW^-$ (DS) dileptonic \\\\\n410657 & $\\bar{t}W^+$ (DS) dileptonic \\\\\n\\hline\n\\end{tabular}\n\\end{center}\n\\end{table}\n\n\\paragraph{Short description:}\n\nThe associated production of top quarks with $W$ bosons ($tW$) was\nmodelled by the\n\\POWHEGBOX[v2]~\\cite{Re:2010bp,Nason:2004rx,Frixione:2007vw,Alioli:2010xd}\ngenerator at NLO in QCD using the five-flavour scheme and the\n\\NNPDF[3.0nlo] set of PDFs~\\cite{Ball:2014uwa}.\nThe diagram removal scheme~\\cite{Frixione:2008yi} was used to\nremove interference and overlap with \\ttbar production. \nThe related uncertainty was estimated by comparison with an alternative sample\ngenerated using the diagram subtraction scheme~\\cite{Frixione:2008yi,ATL-PHYS-PUB-2016-020}.\\footnote{Analyses which do not use this approach \nshould obviously not use this sentence in their description.} \nThe events were interfaced to \\PYTHIA[8.230]~\\cite{Sjostrand:2014zea} using the A14\ntune~\\cite{ATL-PHYS-PUB-2014-021} and the \\NNPDF[2.3lo] set of\nPDFs~\\cite{Ball:2012cx}.\n\n\\input{top_isrfsr_powpy_short}\n\n\\paragraph{Long description:}\n\nSingle-top $tW$ associated production was modelled using the\n\\POWHEGBOX[v2]~\\cite{Re:2010bp,Nason:2004rx,Frixione:2007vw,Alioli:2010xd}\ngenerator, which provided matrix elements at next-to-leading\norder~(NLO) in the strong coupling constant \\alphas\\ in the five-flavour \nscheme with the \\NNPDF[3.0nlo]~\\cite{Ball:2014uwa} parton\ndistribution function~(PDF) set. The functional form of the\nrenormalisation and factorisation scales was set to the default scale,\nwhich is equal to the top-quark mass ($\\mtop = 172.5\\,\\GeV$). \nThe diagram removal scheme~\\cite{Frixione:2008yi} was employed to handle the interference\nwith \\ttbar production~\\cite{ATL-PHYS-PUB-2016-020}. The events were\ninterfaced with \\PYTHIA[8.230]~\\cite{Sjostrand:2014zea} using the A14\ntune~\\cite{ATL-PHYS-PUB-2014-021} and the \\NNPDF[2.3lo] PDF set. The\ndecays of bottom and charm hadrons were simulated using the\n\\EVTGEN[1.6.0] program~\\cite{Lange:2001uf}.\n\nThe inclusive cross-section was corrected to the theory prediction\ncalculated at NLO in QCD with NNLL soft-gluon\ncorrections~\\cite{Kidonakis:2010ux,Kidonakis:2013zqa}. For proton--proton\ncollisions at a centre-of-mass energy of \\rts~=~\\SI{13}{\\TeV}, this\ncross-section corresponds to $\\sigma(tW)_\\text{NLO+NNLL}= 71.7\\pm3.8$\\,pb,\nusing a top-quark mass of $\\mtop = 172.5\\,\\GeV$. The uncertainty in\nthe cross-section due to the PDF was calculated using the \\MSTW[nnlo] 90\\%\nCL~\\cite{Martin:2009iq,Martin:2009bu} PDF set, and was added in\nquadrature to the effect of the scale uncertainty.\n\n\\input{top_isrfsr_powpy_long}\n\nThe nominal \\POWPY[8] sample was compared with an alternative\nsample generated using the diagram subtraction\nscheme~\\cite{Frixione:2008yi,ATL-PHYS-PUB-2016-020} to estimate the\nuncertainty arising from the interference with \\ttbar production.\n\nTo evaluate the PDF uncertainties for the nominal PDF, the 100\nvariations for \\NNPDF[3.0nlo] were taken into account. \nIn addition, the central value of this PDF was compared with the \ncentral values of the \\CT[14nnlo]~\\cite{Dulat:2015mca} and\n\\MMHT[nnlo]~\\cite{Harland-Lang:2014zoa} PDF sets.\n\n\\subsubsection[Powheg+Herwig7]{\\POWHER[7]}\n\\label{subsubsec:tW_PH7}\n\n\\paragraph{Samples}\n%\\label{par:tW_PH7_samples}\n\nTable~\\ref{tab:tW_PH7} gives the DSIDs of the $tW$ \\POWHER[7] DR samples.\nSingle-top and single-anti-top ($tW^-$ and $\\bar{t}W^+$) events were generated in different samples.\nThe dileptonic samples overlap with the inclusive ones.\n\\begin{table}[htbp]\n\\begin{center}\n\\caption{Single-top $tW$ associated production samples produced with \\POWHER[7].} \n\\label{tab:tW_PH7}\n\\begin{tabular}{ l | l }\n\\hline\nDSID & Description \\\\\n\\hline\n411036 & $tW^-$ (DR) inclusive \\\\\n411037 & $\\bar{t}W^+$ (DR) inclusive \\\\\n411038 & $tW^-$ (DR) dileptonic \\\\\n411039 & $\\bar{t}W^+$ (DR) dileptonic \\\\\n\\hline\n\\end{tabular}\n\\end{center}\n\\end{table}\n\n\\paragraph{Short description:}\n\nThe uncertainty due to the parton shower and hadronisation model was\nevaluated by comparing the nominal sample of events with a sample where\nevents generated with the\n\\POWHEGBOX[v2]~\\cite{Re:2010bp,Nason:2004rx,Frixione:2007vw,Alioli:2010xd}\ngenerator were interfaced to\n\\HERWIG[7.04]~\\cite{Bahr:2008pv,Bellm:2015jjp}, using the H7UE set\nof tuned parameters~\\cite{Bellm:2015jjp} and the \\MMHT[lo] PDF set~\\cite{Harland-Lang:2014zoa}.\n\n\\paragraph{Long description:}\n\nThe impact of using a different parton shower and hadronisation model was evaluated\nby comparing the nominal $tW$ sample with another sample produced with the\n\\POWHEGBOX[v2]~\\cite{Re:2010bp,Nason:2004rx,Frixione:2007vw,Alioli:2010xd}\ngenerator but interfaced with \\HERWIG[7.04]~\\cite{Bahr:2008pv,Bellm:2015jjp},\nusing the H7UE set of tuned parameters~\\cite{Bellm:2015jjp} and the\n\\MMHT[lo] PDF set \\cite{Harland-Lang:2014zoa}.\n\\POWHEGBOX provided matrix elements at next-to-leading order~(NLO) in the \nstrong coupling constant \\alphas in the five-flavour scheme with the \n\\NNPDF[3.0nlo]~\\cite{Ball:2014uwa} parton distribution function~(PDF). \nThe functional form of the renormalisation and factorisation scales was set to \nthe default scale, which is equal to the top-quark mass. The diagram removal\nscheme~\\cite{Frixione:2008yi} was employed to handle the interference\nwith \\ttbar production~\\cite{ATL-PHYS-PUB-2016-020}. The decays of bottom\nand charm hadrons are simulated using the \\EVTGEN[1.6.0]\nprogram~\\cite{Lange:2001uf}.\n\n\\subsubsection[MadGraph5\\_aMC@NLO+Pythia8]{\\MGNLOPY[8]}\n\\label{subsubsec:tW_aMCP8}\n\n\\paragraph{Samples}\n%\\label{par:tW_aMCP8_samples}\n\nTable~\\ref{tab:tW_aMCP8} gives the DSIDs of the $tW$ \\MGNLOPY[8] samples.\nThe dileptonic sample overlaps with the inclusive one.\n\\begin{table}[htbp]\n\\begin{center}\n\\caption{Single-top $tW$ associated production samples produced with \\MGNLOPY[8].} \n\\label{tab:tW_aMCP8}\n\\begin{tabular}{ l | l }\n\\hline\nDSID & Description \\\\\n\\hline\n412002 & $tW$ inclusive \\\\\n412003 & $tW$ dileptonic \\\\\n\\hline\n\\end{tabular}\n\\end{center}\n\\end{table}\n\n\\paragraph{Short description:}\n\nTo assess the uncertainty in the matching of NLO matrix elements to the\nparton shower, the nominal $tW$ sample was compared with a sample generated\nwith the \\MGNLO[2.6.2] generator at NLO in QCD using the five-flavour\nscheme and the \\NNPDF[2.3nlo]~\\cite{Ball:2014uwa} PDF set. The events were\ninterfaced with \\PYTHIA[8.230]~\\cite{Sjostrand:2014zea}, using the A14\nset of tuned parameters~\\cite{ATL-PHYS-PUB-2014-021} and the \\NNPDF[2.3lo]\nPDF.\n\n\\paragraph{Long description:}\n\nTo assess the uncertainty due to the choice of matching scheme, the nominal $tW$ sample was compared with a sample generated\nwith the \\MGNLO[2.6.2] generator, which provided matrix elements at next-to-leading order~(NLO) in the strong coupling constant \\alphas\nin the five-flavour scheme, using the \\NNPDF[2.3nlo]~\\cite{Ball:2014uwa} PDF set.\nThe functional form of the renormalisation and factorisation scale was set to the default scale, which is equal to the top-quark mass.\nThe parton-shower starting scale had the functional form $\\muQ = H_{\\mathrm T}/2$~\\cite{ATL-PHYS-PUB-2017-007}, \nwhere $H_{\\mathrm T}$ is defined as the scalar sum of the \\pT of all outgoing partons.\nThe diagram removal scheme~\\cite{Frixione:2008yi} was employed to handle the interference with \\ttbar production~\\cite{ATL-PHYS-PUB-2016-020}.\nThe events were interfaced with \\PYTHIA[8.230]~\\cite{Sjostrand:2014zea}, using the A14 set of tuned parameters~\\cite{ATL-PHYS-PUB-2014-021} \nand the \\NNPDF[2.3lo] PDF.\nThe decays of bottom and charm hadrons were simulated using the \\EVTGEN[1.6.0] program~\\cite{Lange:2001uf}.\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%% t-channel %%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Single-top \\texorpdfstring{$t$}{t}-channel production}\n\\label{subsec:tchan}\n\nThis section describes the MC samples used for the modelling of single-top $t$-channel production.\nSection~\\ref{subsubsec:tchan_PP8} describes the \\POWPY[8] samples used for the nominal prediction\nand for the uncertainty from additional radiation and due to PDFs.\nSection~\\ref{subsubsec:tchan_PH7} describes the \\POWHER[7] samples used for the uncertainty due to the choice of parton shower and hadronisation model,\nand Section~\\ref{subsubsec:tchan_aMCP8} describes the \\MGNLOPY[8] samples used for the uncertainty due to the choice of matching scheme.\n\nThe reference cross-section values are extracted from Ref.~\\cite{LHCTopWGsgtopXsec}.\n\n\n\\subsubsection[Powheg+Pythia8]{\\POWPY[8]}\n\\label{subsubsec:tchan_PP8}\n\n\\paragraph{Samples}\n%\\label{par:tchan_PP8_samples}\n\nTable~\\ref{tab:tchan_PP8} gives the DSIDs of the $t$-channel \\POWPY[8] samples.\nSingle-top and single-anti-top events were generated in distinct samples.\n\\begin{table}[!htbp]\n\\begin{center}\n\\caption{Single-top $t$-channel event samples produced with \\POWPY[8].} \n\\label{tab:tchan_PP8}\n\\begin{tabular}{ l | l }\n\\hline\nDSID & Description \\\\\n\\hline\n410658 & $t$-channel $t$ leptonic \\\\\n410659 & $t$-channel $\\bar{t}$ leptonic \\\\\n\\hline\n\\end{tabular}\n\\end{center}\n\\end{table}\n\n\\paragraph{Short description:}\n\nSingle-top $t$-channel production was modelled using the\n\\POWHEGBOX[v2]~\\cite{Frederix:2012dh,Nason:2004rx,Frixione:2007vw,Alioli:2010xd}\ngenerator at NLO in QCD using the four-flavour scheme and the\ncorresponding \\NNPDF[3.0nlo] set of PDFs~\\cite{Ball:2014uwa}. The events were\ninterfaced with \\PYTHIA[8.230]~\\cite{Sjostrand:2014zea} using the A14\ntune~\\cite{ATL-PHYS-PUB-2014-021} and the \\NNPDF[2.3lo] set of\nPDFs~\\cite{Ball:2012cx}.\n\n\\input{top_isrfsr_powpy_short}\n\n\\paragraph{Long description:}\n\nSingle-top $t$-channel production was modelled using the\n\\POWHEGBOX[v2]~\\cite{Frederix:2012dh,Nason:2004rx,Frixione:2007vw,Alioli:2010xd}\ngenerator, which provided matrix elements at next-to-leading-order~(NLO) \naccuracy in the strong coupling constant \\alphas\\ in the four-flavour \nscheme with the corresponding \\NNPDF[3.0nlo]~\\cite{Ball:2014uwa} parton\ndistribution function~(PDF) set. The functional form of the\nrenormalisation and factorisation scales was set to\n$\\sqrt{m_b^2 + p_{\\text{T},b}^2}$ following the\nrecommendation of Ref.~\\cite{Frederix:2012dh}. Top quarks were decayed at\nLO using \\MADSPIN~\\cite{Frixione:2007zp,Artoisenet:2012st} to preserve\nall spin correlations. The events were interfaced with\n\\PYTHIA[8.230]~\\cite{Sjostrand:2014zea} using the A14\ntune~\\cite{ATL-PHYS-PUB-2014-021} and the \\NNPDF[2.3lo] PDF set. \nThe decays of bottom and charm hadrons were simulated using the\n\\EVTGEN[1.6.0] program~\\cite{Lange:2001uf}.\n\nThe inclusive cross-section was corrected to the theory prediction calculated at NLO in QCD with \n\\HATHOR[2.1]~\\cite{Aliev:2010zk,Kant:2014oha}.\nFor proton--proton collisions at a centre-of-mass energy of \\rts~=~\\SI{13}{\\TeV}, this cross-section corresponds to\n$\\sigma(t,t\\text{-chan})_\\text{NLO}= 136.02^{+5.40}_{-4.57}$\\,pb ($\\sigma(\\bar{t},t\\text{-chan})_\\text{NLO}=80.95^{+4.06}_{-3.61}$\\,pb)\nfor single-top (single-anti-top) production, using a top-quark mass of $\\mtop = 172.5\\,\\GeV$.\nThe uncertainties in the cross-section due to the PDF and \\alphas were calculated using the \\PDFforLHC prescription~\\cite{Butterworth:2015oua}\nwith the \\MSTW[nlo] 68\\% CL~\\cite{Martin:2009iq,Martin:2009bu}, \\CT[10nlo]~\\cite{Lai:2010vv} \nand \\NNPDF[2.3nlo]~\\cite{Ball:2012cx} PDF sets,\nand were added in quadrature to the effect of the scale uncertainty.\n\n\\input{top_isrfsr_powpy_long}\n\nTo evaluate the PDF uncertainties for the nominal PDF, the 100 variations for \\NNPDF[3.0nlo] were taken into account. \nIn addition, the central value of this PDF was compared with the central values of the \\CT[14nnlo]~\\cite{Dulat:2015mca} \nand \\MMHT[nnlo]~\\cite{Harland-Lang:2014zoa} PDF sets.\n\n\\subsubsection[Powheg+Herwig7]{\\POWHER[7]}\n\\label{subsubsec:tchan_PH7}\n\n\\paragraph{Samples}\n%\\label{par:tchan_PH7_samples}\n\nTable~\\ref{tab:tchan_PH7} gives the DSIDs of the $t$-channel \\POWHER[7] samples.\nSingle-top and single-anti-top events were generated in distinct samples.\n\\begin{table}[htbp]\n\\begin{center}\n\\caption{Single-top $t$-channel event samples produced with \\POWHER[7].} \n\\label{tab:tchan_PH7}\n\\begin{tabular}{ l | l }\n\\hline\nDSID & Description \\\\\n\\hline\n411032 & $t$-channel $\\bar t$ leptonic \\\\\n411033 & $t$-channel $t$ leptonic \\\\\n\\hline\n\\end{tabular}\n\\end{center}\n\\end{table}\n\n\\paragraph{Short description:}\n\nThe uncertainty due to the parton shower and hadronisation model was\nevaluated by comparing the nominal sample of events with a sample where\nthe events generated with the\n\\POWHEGBOX[v2]~\\cite{Frederix:2012dh,Nason:2004rx,Frixione:2007vw,Alioli:2010xd}\ngenerator were interfaced to\n\\HERWIG[7.04]~\\cite{Bahr:2008pv,Bellm:2015jjp}, using the H7UE set\nof tuned parameters~\\cite{Bellm:2015jjp} and the \\MMHT[lo] PDF set\n\\cite{Harland-Lang:2014zoa}.\n\n\\paragraph{Long description:}\n\nThe impact of using a different parton shower and hadronisation model was evaluated by comparing the nominal sample\nwith another sample produced with the \\POWHEGBOX[v2]~\\cite{Frederix:2012dh,Nason:2004rx,Frixione:2007vw,Alioli:2010xd}\ngenerator but interfaced with \\HERWIG[7.04]~\\cite{Bahr:2008pv,Bellm:2015jjp}, using the H7UE set of\ntuned parameters~\\cite{Bellm:2015jjp} and the \\MMHT[lo] PDF set \\cite{Harland-Lang:2014zoa}.\n\\POWHEGBOX provided matrix elements at next-to-leading order~(NLO) in the strong coupling constant \\alphas\nin the four-flavour scheme with the corresponding \\NNPDF[3.0nlo]~\\cite{Ball:2014uwa} parton distribution function~(PDF).\nThe functional form of the renormalisation and factorisation scales was set to $\\sqrt{m_b^2 + p_{\\text{T},b}^2}$\nfollowing the recommendation of Ref.~\\cite{Frederix:2012dh}.\nTop quarks were decayed at LO using \\MADSPIN~\\cite{Frixione:2007zp,Artoisenet:2012st} to preserve all spin correlations.\nThe decays of bottom and charm hadrons were simulated using the \\EVTGEN[1.6.0] program~\\cite{Lange:2001uf}.\n\n\\subsubsection[MadGraph5\\_aMC@NLO+Pythia8]{\\MGNLOPY[8]}\n\\label{subsubsec:tchan_aMCP8}\n\n\\paragraph{Samples}\n%\\label{par:tchan_aMCP8_samples}\n\nTable~\\ref{tab:tchan_aMCP8} gives the DSIDs of the $t$-channel \\MGNLOPY[8] samples.\n\\begin{table}[htbp]\n\\begin{center}\n\\caption{Single-top $t$-channel event samples produced with \\MGNLOPY[8].} \n\\label{tab:tchan_aMCP8}\n\\begin{tabular}{ l | l }\n\\hline\nDSID & Description \\\\\n\\hline\n412004 & $t$-channel leptonic \\\\\n\\hline\n\\end{tabular}\n\\end{center}\n\\end{table}\n\n\\paragraph{Short description:}\n\nTo assess the uncertainty in the matching of NLO matrix elements to the\nparton shower, the nominal sample was compared with a sample generated\nwith the \\MGNLO[2.6.2] generator at NLO in QCD using the five-flavour\nscheme and the \\NNPDF[2.3nlo]~\\cite{Ball:2014uwa} PDF set. The events were\ninterfaced with \\PYTHIA[8.230]~\\cite{Sjostrand:2014zea}, using the A14\nset of tuned parameters~\\cite{ATL-PHYS-PUB-2014-021} and the \\NNPDF[2.3lo] PDF set.\n\n\\paragraph{Long description:}\n\nTo assess the uncertainty due to the choice of matching scheme, the nominal sample was compared with a sample generated\nwith the \\MGNLO[2.6.2] generator, which provided matrix elements at next-to-leading order~(NLO) in the strong coupling constant \\alphas\nin the four-flavour scheme, using the corresponding \\NNPDF[3.0nlo]~\\cite{Ball:2014uwa} PDF set.\nThe functional form of the renormalisation and factorisation scales was set to $\\sqrt{m_b^2 + p_{\\text{T},b}^2}$\nfollowing the recommendation of Ref.~\\cite{Frederix:2012dh}.\nThe parton-shower starting scale had the functional form $\\muQ = H_\\text{T}/2$~\\cite{ATL-PHYS-PUB-2017-007}, \nwhere $H_\\text{T}$ is defined as the scalar sum of the \\pT of all outgoing partons.\nTop quarks were decayed at LO using \\MADSPIN~\\cite{Frixione:2007zp,Artoisenet:2012st} to preserve all spin correlations.\nThe events were interfaced with \\PYTHIA[8.230]~\\cite{Sjostrand:2014zea}, using the A14 set of tuned parameters~\\cite{ATL-PHYS-PUB-2014-021} \nand the \\NNPDF[2.3lo] PDF set.\nThe decays of bottom and charm hadrons were simulated using the \\EVTGEN[1.6.0] program~\\cite{Lange:2001uf}.\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%% s-channel %%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsubsection{Single-top \\texorpdfstring{$s$}{s}-channel production}\n\\label{subsec:schan}\n\nThis section describes the MC samples used for the modelling of single-top $s$-channel production.\nSection~\\ref{subsubsec:schan_PP8} describes the \\POWPY[8] samples used for the nominal prediction\nand for the uncertainty from additional radiation and due to PDFs.\nSection~\\ref{subsubsec:schan_PH7} describes the \\POWHER[7] samples used for the uncertainty due to the parton shower and hadronisation model,\nand Section~\\ref{subsubsec:schan_aMCP8} describes the \\MGNLOPY[8] samples used for the uncertainty due to the choice of matching scheme.\n\nThe reference cross-section values are extracted from Ref.~\\cite{LHCTopWGsgtopXsec}.\n\n\\subsubsection[Powheg+Pythia8]{\\POWPY[8]}\n\\label{subsubsec:schan_PP8}\n\n\\paragraph{Samples}\n%\\label{par:schan_PP8_samples}\n\nTable~\\ref{tab:schan_PP8} gives the DSIDs of the $s$-channel \\POWPY[8] samples.\nSingle-top and single-anti-top events were generated in distinct samples.\n\\begin{table}[htbp]\n\\begin{center}\n\\caption{Single-top $s$-channel event samples produced with \\POWPY[8].} \n\\label{tab:schan_PP8}\n\\begin{tabular}{ l | l }\n\\hline\nDSID & Description \\\\\n\\hline\n410644 & $s$-channel $t$ leptonic \\\\\n410645 & $s$-channel $\\bar{t}$ leptonic \\\\\n\\hline\n\\end{tabular}\n\\end{center}\n\\end{table}\n\n\\paragraph{Short description:}\n\nSingle-top $s$-channel production was modelled using the \\POWHEGBOX[v2]~\\cite{Alioli:2009je,Nason:2004rx,Frixione:2007vw,Alioli:2010xd}\ngenerator at NLO in QCD in the five-flavour scheme with the \\NNPDF[3.0nlo]~\\cite{Ball:2014uwa} parton distribution function~(PDF) set.\nThe events were interfaced with \\PYTHIA[8.230]~\\cite{Sjostrand:2014zea} using the A14 tune~\\cite{ATL-PHYS-PUB-2014-021} and the\n\\NNPDF[2.3lo] PDF set.\n\n\\input{top_isrfsr_powpy_short}\n\n\\paragraph{Long description:}\n\nSingle-top $s$-channel production was modelled using the \\POWHEGBOX[v2]~\\cite{Alioli:2009je,Nason:2004rx,Frixione:2007vw,Alioli:2010xd}\ngenerator, which provided matrix elements at next-to-leading order~(NLO) in the strong coupling constant \\alphas in the \nfive-flavour scheme with the \\NNPDF[3.0nlo]~\\cite{Ball:2014uwa} parton distribution function~(PDF) set.\nThe functional form of the renormalisation and factorisation scales was set to the default scale, which was equal to the top-quark mass.\nThe events were interfaced with \\PYTHIA[8.230]~\\cite{Sjostrand:2014zea} using the A14 tune~\\cite{ATL-PHYS-PUB-2014-021} and the\n\\NNPDF[2.3lo] PDF set.\nThe decays of bottom and charm hadrons were simulated using the \\EVTGEN[1.6.0] program~\\cite{Lange:2001uf}.\n\nThe inclusive cross-section was corrected to the theory prediction calculated at NLO in QCD with \n\\HATHOR[2.1]~\\cite{Aliev:2010zk,Kant:2014oha}.\nFor proton--proton collisions at a centre-of-mass energy of \\rts~=~\\SI{13}{\\TeV}, this cross-section corresponds to\n$\\sigma(t,s\\text{-chan})_\\text{NLO}= 6.35^{+0.23}_{-0.20}$\\,pb ($\\sigma(\\bar{t},s\\text{-chan})_\\text{NLO}=3.97^{+0.19}_{-0.17}$\\,pb)\nfor single-top (single-anti-top) production, using a top-quark mass of $\\mtop = 172.5\\,\\GeV$.\nThe uncertainties in the cross-section due to the PDF and \\alphas were calculated using the \\PDFforLHC prescription~\\cite{Butterworth:2015oua}\nwith the \\MSTW[nlo] 68\\% CL~\\cite{Martin:2009iq,Martin:2009bu}, \\CT[10nlo]~\\cite{Lai:2010vv} and \\NNPDF[2.3nlo]~\\cite{Ball:2012cx} PDF sets,\nand were added in quadrature to the effect of the scale uncertainty.\n\n\\input{top_isrfsr_powpy_long}\n\nTo evaluate the PDF uncertainties for the nominal PDF, the 100 variations for \\NNPDF[3.0nlo] were taken into account. \nIn addition, the central value of this PDF was compared with the central values of the \n\\CT[14nnlo]~\\cite{Dulat:2015mca} and \\MMHT[nnlo]~\\cite{Harland-Lang:2014zoa} PDF sets.\n\n\\subsubsection[Powheg+Herwig7]{\\POWHER[7]}\n\\label{subsubsec:schan_PH7}\n\n\\paragraph{Samples}\n%\\label{par:schan_PH7_samples}\n\nTable~\\ref{tab:schan_PH7} gives the DSIDs of the $s$-channel \\POWHER[7] samples.\nSingle-top and single-anti-top events were generated in distinct samples.\n\\begin{table}[htbp]\n\\begin{center}\n\\caption{Single-top $s$-channel event samples produced with \\POWHER[7].} \n\\label{tab:schan_PH7}\n\\begin{tabular}{ l | l }\n\\hline\nDSID & Description \\\\\n\\hline\n411034 & $s$-channel $t$ leptonic \\\\\n411035 & $s$-channel $\\bar{t}$ leptonic \\\\\n\\hline\n\\end{tabular}\n\\end{center}\n\\end{table}\n\n\\paragraph{Short description:}\n\nThe impact of using a different parton shower and hadronisation model was evaluated by comparing the nominal sample\nwith another sample produced with the \\POWHEGBOX[v2]~\\cite{Alioli:2009je,Nason:2004rx,Frixione:2007vw,Alioli:2010xd}\ngenerator at NLO in the strong coupling constant \\alphas in the five-flavour scheme using the \n\\NNPDF[3.0nlo]~\\cite{Ball:2014uwa} parton distribution function~(PDF).\nEvents in the latter sample were interfaced with \\HERWIG[7.04]~\\cite{Bahr:2008pv,Bellm:2015jjp}, using the H7UE set of\ntuned parameters~\\cite{Bellm:2015jjp} and the \\MMHT[lo] PDF set \\cite{Harland-Lang:2014zoa}.\n\n\\paragraph{Long description:}\n\nThe impact of using a different parton shower and hadronisation model was evaluated by comparing the nominal sample\nwith another sample produced with the \\POWHEGBOX[v2]~\\cite{Alioli:2009je,Nason:2004rx,Frixione:2007vw,Alioli:2010xd}\ngenerator but interfaced with \\HERWIG[7.04]~\\cite{Bahr:2008pv,Bellm:2015jjp}, using the H7UE set of\ntuned parameters~\\cite{Bellm:2015jjp} and the \\MMHT[lo] PDF set \\cite{Harland-Lang:2014zoa}.\n\\POWHEGBOX provided matrix elements at next-to-leading order~(NLO) in the strong coupling constant \\alphas\nin the five-flavour scheme with the \\NNPDF[3.0nlo]~\\cite{Ball:2014uwa} parton distribution function~(PDF).\nThe functional form of the renormalisation and factorisation scales was set to the default scale, which is equal to the top-quark mass.\nThe decays of bottom and charm hadrons were simulated using the \\EVTGEN[1.6.0] program~\\cite{Lange:2001uf}.\n\n\\subsubsection[MadGraph5\\_aMC@NLO+Pythia8]{\\MGNLOPY[8]}\n\\label{subsubsec:schan_aMCP8}\n\n\\paragraph{Samples}\n%\\label{par:schan_aMCP8_samples}\n\nTable~\\ref{tab:schan_aMCP8} gives the DSIDs of the $s$-channel \\MGNLOPY[8] samples.\n\\begin{table}[htbp]\n\\begin{center}\n\\caption{Single-top $s$-channel event samples produced with \\MGNLOPY[8].} \n\\label{tab:schan_aMCP8}\n\\begin{tabular}{ l | l }\n\\hline\nDSID & Description \\\\\n\\hline\n412005 & $s$-channel leptonic \\\\\n\\hline\n\\end{tabular}\n\\end{center}\n\\end{table}\n\n\\paragraph{Short description:}\n\n%% the MG5_aMC@NLO version was doulble checked in the tag collector\nTo assess the uncertainty due to the choice of matching scheme, the nominal sample was compared with a sample generated\nwith the \\MGNLO[2.6.2] generator at NLO in the strong coupling constant \\alphas in the five-flavour scheme, \nusing the \\NNPDF[3.0nlo]~\\cite{Ball:2014uwa} PDF set.\nThe events were interfaced with \\PYTHIA[8.230]~\\cite{Sjostrand:2014zea}, using the A14 set of tuned parameters~\\cite{ATL-PHYS-PUB-2014-021} \nand the \\NNPDF[2.3lo] PDF set.\n\n\\paragraph{Long description:}\n\nTo assess the uncertainty due to the choice of matching scheme, the nominal sample was compared with a sample generated\nwith the \\MGNLO[2.6.2] generator, which provided matrix elements at next-to-leading order~(NLO) in the strong coupling constant \\alphas\nin the five-flavour scheme with the \\NNPDF[3.0nlo]~\\cite{Ball:2014uwa} parton distribution function~(PDF).\nThe functional form of the renormalisation and factorisation scales was set to the default scale, which is equal to the top-quark mass.\nThe parton-shower starting scale had the functional form $\\muQ = H_{\\mathrm T}/2$~\\cite{ATL-PHYS-PUB-2017-007}, \nwhere $H_{\\mathrm T}$ is defined as the scalar sum of the \\pT of all outgoing partons.\nTop quarks were decayed at LO using \\MADSPIN~\\cite{Frixione:2007zp,Artoisenet:2012st} to preserve all spin correlations.\nThe events were interfaced with \\PYTHIA[8.230]~\\cite{Sjostrand:2014zea}, using the A14 set of tuned parameters~\\cite{ATL-PHYS-PUB-2014-021} \nand the \\NNPDF[2.3lo] PDF set.\nThe decays of bottom and charm hadrons were simulated using the \\EVTGEN[1.6.0] program~\\cite{Lange:2001uf}.\n", "meta": {"hexsha": "81dd27b7bf9ed5315fe86578477be5d40dfdb574", "size": 26104, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "template/MC_snippets/sgtop.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": "template/MC_snippets/sgtop.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": "template/MC_snippets/sgtop.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": 48.1623616236, "max_line_length": 151, "alphanum_fraction": 0.7570487282, "num_tokens": 8554, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.1898585785706167}}
{"text": "\\begin{figure}\n\\begin{center}\n \\includegraphics[width=0.9\\textwidth]{figs/abc_slope_AV_starforming.pdf}\n \\caption{\\label{fig:slope}\n The attenuation-slope relation of star-forming galaxies ($\\ssfr >\n 10^{-11}yr^{-1}$), using the attenuation curves predicted by our \n \\eda~prescription for the median posterior parameter values of SIMBA\n (left), TNG (center) and EAGLE (right). \n For comparison, we include the observed attenuation-slope relation\n from GSWLC2~\\citep{salim2020}. \n We use $A_V$ and $S = A(1500\\AA)/A_V$ as measurements of attenuation and\n slope, respectively. \n \\emph{The \\eda~does not predict $A_V < 0.3$ because star-forming galaxies in\n the simulations are intrinsically too lumnious and require significant attenuation to\n match observations.}\n Beyond $A_V > 0.3$, however, there is good agreement between the\n attenuation-slope relation predicted by the \\eda~and observations. \n }\n\\end{center}\n\\end{figure}\n\n\\subsection{Comparison to Dust Observations} \\label{sec:reproduce}\nIn addition to reproducing observations, the \\eda~assigns dust attenuation\ncurves to each simulated galaxy so we can compare the \\eda~attenuation curves\nto dust attenuation measured from observations. \nWe begin with the well-established attenuation-slope relation: star-forming\ngalaxies with higher dust attenuation have shallower attenuation curves. \nThis relation is a consequence of dust scattering dominating absorption at\nlow attenuation while dust absorption dominates at high\nattenuation~\\citep{gordon1994, witt2000, draine2003, chevallard2013}. \nIn Figure~\\ref{fig:slope}, we present the attenuation-slope relation of\nstar-forming galaxies with $\\ssfr > 10^{-11}yr^{-1}$ using the\ndust attenuation curves predicted by the \\eda~for the median posteriors of\nSIMBA (left), TNG (center) and EAGLE (right).\nFor comparison, we include the observed attenuation-slope relations of\nGSWLC2 galaxies~\\citep[grey shaded;][]{salim2020}.\nFor attenuation, we use $A_V$; for slope, we use the UV-optical slope, $S\n= A(1500\\AA)/A_V$. \nThe contours mark the 68 and 95 percentiles. \n\nMost noticably, we find that the \\eda~does not predict $A_V < 0.3$ for\nstar-forming galaxies.\n%\\chedit{\n% This is not due to the selection function imposed by our forward model. \n% The attenuation-slope relation of star-forming galaxies in GSWLC2 does not\n% change significantly if we impose similar selection cuts as our\n% observational sample.\n% Instead, the lack of star-forming galaxies with $A_V < 0.3$ is a\nThis is a consequence of SIMBA, TNG, and EAGLE predicting star-forming galaxies\nthat are intrinsically more luminous than observations. \nAll of the simulations have star-forming galaxies with intrinsic $M_r <\n-21$ and $\\gr < 0.5$ (Figure~\\ref{fig:obs}). \nThis is further corroborated by the $\\sfr-M*$ relations in\nFigure~\\ref{fig:smf_msfr}, where the simulations all have star-forming\ngalaxies with $M_* > 10^{11}M_\\odot$, not found in SDSS. \nTo reproduce the SDSS optical color-magnitude relation these galaxies would\nneed to be significantly reddened and attenuated so any dust prescription would\nneed to assign high $A_V$ to star-forming galaxies.\nNevertheless, for $A_V > 0.3$, we find good agreement between the \nattenuation-slope relation predicted by the \\eda~and observations. \nWe refrain from further scrutinizing on $A_V$ values, since they can vary {\\em\nsignificantly} between different observational measurements --- even for the\nsame galaxy. \nSDSS star-forming galaxies, for instance, have significantly higher \n$A_V > 0.3$ according to the \\cite{brinchmann2004} measurements\n(Appendix~\\ref{sec:slab}).\n\n\n%We note that the difference in the $A_V$ ranges is due to the $M_r$\n%completeness limit imposed by our forward model (Section~\\ref{sec:fm}).\n%The GSWLC2 sample in \\cite{salim2020} extends down to $M_* \\sim\n%10^{8.5}M_\\odot$; however, the TNG and EAGLE samples do not extend below\n%$M_* \\sim10^{10}M_\\odot$.\n%\\emph{The \\eda~predicts attenuation-slope relations for TNG and EAGLE that\n%are in excellent agreement with observations.} \n\n\\begin{figure}\n\\begin{center}\n \\includegraphics[width=0.5\\textwidth]{figs/abc_sf_attenuation.pdf}\n \\caption{\\label{fig:sfatten}\n The normalized attenuation curves of star-forming galaxies predicted by\n the \\eda~for median posterior parameter values of SIMBA (orange), TNG\n (blue), and EAGLE (green). \n We classify galaxies with $\\log \\ssfr > -11~yr^{-1}$ as star-forming. \n The attenuation curves are normalized at $3000\\AA$ and we mark the\n 68 percentile of the attenuation curves with the shaded region.\n For comparison, we include $A(\\lambda)/A(3000\\AA)$ measurements from\n the~\\cite{narayanan2018} radiative transfer simulation (dashed) and\n \\cite{salim2018} observations (dotted).\n %The \\cite{calzetti2000} and \\cite{battisti2017} attenuation curves are shallower than the \\eda~attenuation curves; however, they probe lower $M_*$ galaxies than our forward modeled TNG and EAGLE samples. For attenuation curve from \\cite{salim2018}, which probe a similar $M_*$ range, we find goood agreement. \n {\\em The \\eda~predict attenuation curves of star-forming galaxies\n are in good agreement with the attenuation curves measured from\n the simulation and observations in the literature.}\n %We also find good agreement with median attenuation curve of star-forming galaxies in the radiative transfer simulations of \\cite{narayanan2018}.\n }\n\\end{center}\n\\end{figure}\n\nIn addition to the attenuation-slope relation, we can also directly compare\nthe attenuation curves predicted by the \\eda~to measurements from\nobservations for star-forming galaxies. \nIn Figure~\\ref{fig:sfatten}, we present the normalized attenuation curves\nof star-forming galaxies predicted by the \\eda~for the median posterior\nparameter values of SIMBA(orange), TNG (blue), and EAGLE (green).\nWe again define galaxies with $\\ssfr > 10^{-11}{yr}^{-1}$ as star-forming.\nThe attenuation curves are normalized at $3000\\AA$ and we present the\nvariation in the attenuation curves in the shaded region, 68 percentile. \nFor comparison, we include $A(\\lambda)/A(3000\\AA)$ from the\n\\cite{narayanan2018} radiative transfer simulation (dashed) and \nobservations~\\citep[][dotted]{salim2018}. \nThe attenuation curve from \\cite{salim2018} corresponds to star-forming\ngalaxies with $M_* > 10^{10.5}M_\\odot$, a similar $M_*$ range as our\nforward modeled samples. \nSince we do not vary the UV bump in our \\eda~prescription, we ignore any\ndiscrepancies in the amplitudes of the bump. \n\\emph{Overall, we find good agreement between the \\eda~attenuation curves for\nstar-forming galaxies and the attenuation curves from observations and\nsimulations.}\n\n%Again, the fact that we reproduce the detailed dust attenuation curves of star-forming galaxies in observations and simulations with the \\eda~without fitting for them, highlights the advantages of a forward modeling approach. \n\n%The \\eda~attenuation curves are slightly steeper than the \\cite{calzetti2000} and \\cite{battisti2017} curves. \n%These attenuation curves, however, are derived from $M_* < 10^{9.9}M_\\odot$\n%star-forming galaxies, which lie below the $M_*$ limit of our forward\n%modeled TNG and EAGLE samples. \n%Meanwhile, the TNG and EAGLE \\eda~attenuation curves are in good agreement\n%with the \\cite{salim2018} attenuation curve for $M_* > 10^{10.5}M_\\odot$ star-forming galaxies. \n%They are also consistent with the median curve of \\cite{narayanan2018}. \n\n%The \\eda~attenuation curves are noticeably steeper than the \\cite{calzetti2000} and \\cite{battisti2017} curves. These attenuation curves, however, are derived from $M_* < 10^{9.9}M_\\odot$ star-forming galaxies --- below our $M_*$ range. \n%Since we find $\\mdeltam < 0$ for both the TNG and EAGLE posteriors, the \\eda~attenuation curves are consistent with \\cite{calzetti2000} and \\cite{battisti2017}. \n\n\n%\\chedit{ \n% The \\eda~predicts higher dust attenuation at lower wavelenghts for\n% star-forming galaxies.\n% Without dust attenuation, both TNG and EAGLE predict star-forming galaxies\n% that are bluer in the optical and UV than observations\n% (Figure~\\ref{fig:obs}).\n% To reproduce the SDSS, the \\eda~significantly reddens star-forming galaxies.\n%}\n%In Figure~\\ref{fig:raw_atten}, we also find that more massive star-forming\n%galaxies have higher attenuation. This is because the simulations overpredict \n%luminous blue star-forming galaxies, which must be attenuated to reproduce\n%observations. \n\n\n%At low attenuation, dust scattering dominates absoprtion so the \n%attenuation curve steepens because red light scatters isotropically while blue light\n%scatters forward~\\citep{gordon1994, witt2000, draine2003}. %, which causes more optical-to-IR light to escape the galaxy than UV light\n%At high attenuation dust absorption is dominant and the attenuation curve is\n%shallower~\\citep{chevallard2013}. For the $A_V$ range probed by the DEM, the\n%$A_V$--slope relation is in good agreement with GSWLC2 galaxies~\\citep[black shaded][]{salim2020}.\n%They are also consistent with \\cite{leja2017}. We also compare our results to\n%theoretical predictions from radiative transfer models, \\cite{inoue2005}\n%(dotted), the radiative transfer models considered in \\cite{chevallard2013}\n%(dot dashed), and \\cite{trayford2020} (light shaded), which all predict shallower \n%attenuation curves than observations. This is also the case for the\n%\\cite{narayanan2018} attenuation curves (not included). \n%\\emph{The attenuation curve slopes from the DEM for are in excellent\n%agreement with observations and better reproduces the observed\n%attenuation--slope relation than radiative transfer models.}\n", "meta": {"hexsha": "6711aa7681172076a89b7e2793949e0453f35d47", "size": 9717, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/paper/reproduce.tex", "max_stars_repo_name": "IQcollaboratory/galpopFM", "max_stars_repo_head_hexsha": "1b30abc1cc2fd1119d0f34a237b0c1112d7afc9d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-02-08T17:36:06.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-08T17:36:06.000Z", "max_issues_repo_path": "doc/paper/reproduce.tex", "max_issues_repo_name": "IQcollaboratory/galpopFM", "max_issues_repo_head_hexsha": "1b30abc1cc2fd1119d0f34a237b0c1112d7afc9d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 35, "max_issues_repo_issues_event_min_datetime": "2020-02-07T19:02:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-04T14:28:05.000Z", "max_forks_repo_path": "doc/paper/reproduce.tex", "max_forks_repo_name": "IQcollaboratory/galpopFM", "max_forks_repo_head_hexsha": "1b30abc1cc2fd1119d0f34a237b0c1112d7afc9d", "max_forks_repo_licenses": ["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.6134969325, "max_line_length": 315, "alphanum_fraction": 0.7693732634, "num_tokens": 2633, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.1898585785706167}}
{"text": "%-------------------------------------------------------------------------------\n\\section{Event reconstruction}\n\\label{sec:objects}\n%-------------------------------------------------------------------------------\n\nThe event reconstruction is affected by multiple $pp$ collisions in a single bunch crossing and by collisions\nin neighbouring bunch crossings, referred to as pile-up. \nInteraction vertices from the $pp$ collisions are reconstructed from at least two tracks \nwith transverse momentum ($\\pt$) larger than $400~\\mev$ that are consistent with originating from the \nbeam collision region in the $x$--$y$ plane. If more than one primary vertex candidate is found, the\ncandidate whose associated tracks form the largest sum of squared $\\pt$~\\cite{ATL-PHYS-PUB-2015-026}\nis selected as the hard-scatter primary vertex.\n\nElectron candidates~\\cite{ATLAS-CONF-2016-024,Aaboud:2018ugz} are reconstructed from energy \nclusters in the EM calorimeter that are matched to reconstructed tracks in the inner detector;\nelectron candidates in the transition region between the EM barrel and endcap calorimeters \n($1.37 < |\\eta_{\\textrm{cluster}}| < 1.52$) are excluded.\nElectron candidates are required to have $|\\eta_{\\textrm{cluster}}| < 2.47$, and to satisfy tight likelihood-based identification \ncriteria~\\cite{ATLAS-CONF-2016-024} based on calorimeter, tracking and combined variables that provide \nseparation between electrons and jets. \n\nMuon candidates~\\cite{Aad:2016jkr} are reconstructed by matching track segments in %the various\ndifferent layers of the muon spectrometer to tracks found in the inner detector;\nthe resulting muon candidates are re-fitted using the complete track information from both detector systems.\nMuon candidates are required to satisfy medium identification criteria~\\cite{Aad:2016jkr}. \n\nElectron (muon) candidates are matched to the primary vertex by requiring that the significance of their transverse impact parameter, $d_0$, \nsatisfies $|d_0/\\sigma(d_0)|<5\\,(3)$, where $\\sigma(d_0)$ is the measured uncertainty in $d_0$,\nand by requiring that their longitudinal impact parameter, $z_0$, satisfies $|z_0 \\sin\\theta|<0.5$~mm. To reduce the impact of the trigger efficiency uncertainty around the threshold, the leptons are required to have \\pt 1~GeV above the threshold.\nTo further reduce the background from non-prompt leptons, photon conversions and hadrons, lepton candidates are also required to be isolated \nin the tracker and in the calorimeter.\nA track-based lepton isolation criterion is defined by calculating the quantity $I_R = \\sum \\pt^{\\textrm{trk}}$ and $E_R = \\sum E^{\\textrm{clst}}$, where\nthe scalar sum includes all tracks and energy deposit (excluding the lepton candidate itself) within the cone defined by $\\Delta R<0.2 (0.3)$ around the %axis\ndirection of the electron (muon). The electron (muon) candidates are required satisfy both $I_R/\\pt^\\ell < 0.2~(0.3)$ and $E_R/\\pt^\\ell < 0.2~(0.3)$.\n\nTight isolation working points are also applied in some channels to reduce fake and non-prompt lepton contributions based a trained isolation boosted decision tree \\texttt{PromptLeptonVeto}(PLIV), which is to identify non-prompt light leptons using lifetime information associated with a track jet that matches the selected light lepton~\\cite{ATLAS-CONF-2019-045}. These additional reconstructed charged particle tracks inside the jet can be\nused to increase the precision of identifying the displaced decay vertex of heavy flavor (b, c) hadrons that produced non-prompt leptons.\nThe tight working points are used for high $\\pt$ lepton.\nThe scale factors for the efficiencies of the tight \\texttt{PLIV} working points are measured using the tag and probe method\nwith $Z\\rightarrow l^+l^-$ events. These scale factors are also checked applicable to the electron or muon from the tau decay\nusing $Z\\rightarrow\\tau\\tau\\rightarrow e\\mu$ samples, which is consistent with 1 at 2\\% level. To be conservative, we assign\nadditional $\\pm 2\\%$ systematic uncertainty for the PLIV efficiency for the tau-lepton in the lepton+$\\thad$ channels.\n%Additionally, the $\\Htautau$ search requires leptons to\n%satisfy a calorimeter-based isolation criterion; a requirement is made on the sum of the transverse energy of\n%topological clusters within the cone defined by $\\Delta R<0.2$ around the lepton, after subtracting the contribution\n%from the energy deposit of the lepton itself and correcting for pile-up effects, to be less than a $\\pt$-dependent \n%percentage of the lepton energy. \n%The combined efficiency of track-based and calorimeter-based isolation requirements made by the $\\Htautau$ \n%search is 90\\% (99\\%) at $\\pt=25\\;(60)~\\gev$.\n\n%a Gradient isolation working points are used for both electrons and muons. The working points are based on cut maps derived from the $Z\\to l^+l^-$ Monte Carlo samples. The efficiency maps are simply derived from the sum of transverse energy of the clusters deposited in the calorimeter in the given cone. The efficiency for the leptons with a certain $\\pt$ is $(0.1143*\\pt[\\GeV]+92.14)\\%*(0.1143*\\pt[\\GeV]+92.14)\\%$.\n%draft 1 version\n%Candidate jets are reconstructed with the anti-$k_t$ algorithm~\\cite{Cacciari:2008gp,Cacciari:2005hq,Cacciari:2011ma} with a\n%radius parameter $R=0.4$, using topological clusters~\\cite{Aad:2016upy} \n%built from energy deposits in the calorimeters calibrated to the electromagnetic scale. \nCandidate jets are reconstructed using the anti-$k_t$ algorithm~\\cite{Cacciari:2008gp,Cacciari:2005hq} with a\nradius parameter $R=0.4$ applied to topological energy clusters~\\cite{Aad:2016upy} and charged-particle tracks, processed using\na particle-flow algorithm~\\cite{Aad:2017epj77}. %newref Eur. Phys. J. C 77 (2017) 466\n%as implemented in the \\fastjet\\ package~\\cite{Cacciari:2011ma}. \n%Jet reconstruction in the calorimeter starts from topological clustering~\\cite{Aad:2016upy} of individual calorimeter cells calibrated to the electromagnetic energy scale. \nThe reconstructed jets are then calibrated to the particle level by the application of a jet energy scale \nderived from simulation and in situ corrections based on $\\sqrt{s}=13~\\tev$ data~\\cite{Aaboud:2017jcu}. %(TBD: check PFlow jets description)\nThe calibrated jets used are required to have $\\pt > 25~\\gev$ and $|\\eta| < 2.5$.\nJet four-momenta are corrected for pile-up effects using the jet-area method~\\cite{Cacciari:2008gn}.\n\nQuality criteria are imposed to reject events that contain any jets arising from non-collision sources\nor detector noise~\\cite{ATLAS-CONF-2015-029}. To reduce the contamination due to jets originating from pile-up interactions,\nadditional requirements are imposed on the jet vertex tagger (JVT)~\\cite{Aad:2015ina} output for jets with $\\pt<60~\\gev$ and $|\\eta| < 2.4$.\n\nJets containing $b$-hadrons are identified ($b$-tagged) via the DL1r tagger~\\cite{Aad:2019epj79,ATL-PHYS-PUB-2017-013} %newref\n%\\cite{Aad:2015ydr,ATL-PHYS-PUB-2016-012} \nthat uses multivariate techniques to combine information about the impact parameters of displaced tracks and the topological properties \nof secondary and tertiary decay vertices reconstructed within the jet. For each jet, a value for the multivariate $b$-tagging discriminant is \ncalculated. A jet is considered $b$-tagged if this value is above the threshold corresponding to\nan average 70\\% efficiency to tag a $b$-quark jet, with a light-jet\\footnote{Light-jet refers to a jet originating from the hadronisation of a light quark ($u$, $d$, $s$) or a gluon.} rejection factor of about 385 and a charm-jet rejection factor of about 12, as determined for jets with\n$\\pt >20~\\gev$ and $|\\eta|<2.5$ in simulated $\\ttbar$ events.\n\nHadronically decaying $\\tau$-lepton ($\\had$) candidates are reconstructed from energy clusters in the calorimeters and\nassociated inner-detector tracks~\\cite{ATL-PHYS-PUB-2019-033}. %newref\n%~\\cite{ATL-PHYS-PUB-2015-045}.\nCandidates are required to have either one or three associated tracks,\nwith a total charge of $\\pm 1$. Candidates are required to have \\pt 5 GeV higher than the trigger threshold, and $|\\eta|<2.5$,\nexcluding the EM calorimeter's transition region.\nA Recurrent Neural Network (RNN)~\\cite{Graves:2012SCI}\n%~\\cite{Breiman:1984jka,Friedman:2002we,Freund:1997xna}\n%A. Graves, Supervised Sequence Labelling with Recurrent Neural Networks, Studies in Computational Intelligence 385, Springer, 2012.\nusing calorimeter- and tracking-based variables is used to identify $\\had$ candidates and reject jet backgrounds.\nThree working points labelled loose, medium and tight are defined, and correspond to different $\\had$ identification efficiency values, with the efficiency designed to be independent of $\\pt$. The $\\Htautau$ search uses the medium\nworking point for the nominal selection.\n%, while the loose working point is used for background estimation.\nThe medium working point has a combined reconstruction and identification efficiency of 75\\% (60\\%) for one-prong (three-prong) $\\had$ \ndecays, and an expected rejection factor against light-jets of 35 (240)~\\cite{ATL-PHYS-PUB-2019-033}. \nElectrons that are reconstructed as one-prong $\\had$ candidates are removed via a BDT trained to reject electrons.\nEvents with$\\had$ candidate that is $b$-tagged are rejected.\n%(TBD: check RNN description and update then numbers)\n\n%Overlaps between candidate objects are removed sequentially, following this order: muons, electrons,\n%$\\tauhad$ (only for the $\\Htautau$ search), and jets. In the $\\Hbb$ search, firstly, electron candidates that lie \n%within $\\Delta R = 0.01$ of a muon candidate are removed to suppress contributions from muon bremsstrahlung. \n%Overlaps between electron and jet candidates are resolved next, and finally, overlaps between remaining jet candidates \n%and muon candidates are removed. Clusters from identified electrons are not excluded during jet reconstruction. \n%In order to avoid double-counting of electrons as jets, the closest jet whose axis is within ${\\Delta}R = 0.2$ of an electron \n%is discarded. If the electron is within ${\\Delta}R = 0.4$ of the axis of any jet after this initial removal, the jet is retained and the electron is removed.\n%The overlap removal procedure between the remaining jet candidates and muon candidates is designed to remove those muons \n%that are likely to have arisen in the decay chain of hadrons and to retain the overlapping jet instead. \n%Jets and muons may also appear in close proximity when the jet results from high-$\\pt$ muon bremsstrahlung, \n%and in such cases the jet should be removed and the muon retained. Such jets are characterised by having very \n%few matching inner-detector tracks. Selected muons that satisfy $\\Delta R(\\mu,{\\textrm{jet}}) < 0.04+10~\\gev/\\pt^\\mu$ are rejected\n%if the jet has at least three tracks originating from the primary vertex; otherwise the jet is removed and the muon is kept.\n%In the $\\Htautau$ search, a fixed cone size of $\\Delta R=0.2$ is used to determine the overlap between\n%candidate objects, and only the highest-$\\pt$ (leading) or the two leading $\\tauhad$ candidates (depending on the\n%analysis channel, see Section~\\ref{sec:data_presel}) are considered to resolve their overlap with jets.\n\nOverlaps between reconstructed objects are removed sequentially. Firstly, electron candidates that lie \nwithin $\\Delta R = 0.01$ of a muon candidate are removed to suppress contributions from muon bremsstrahlung. \nOverlaps between electron and jet candidates are resolved next, and finally, overlaps between remaining jet candidates \nand muon candidates are removed. Energy clusters from identified electrons are not excluded during jet reconstruction. \nIn order to avoid double-counting of electrons as jets, the closest jet whose axis is within ${\\Delta}R = 0.2$ of an electron \nis discarded if the jet is not $b$-tagged, otherwise the electron is removed.\nIf the electron is within ${\\Delta}R = 0.4$ of the axis of any jet after this initial removal, the jet is retained and the electron is removed.\nThe overlap removal procedure between the remaining jet candidates and muon candidates is designed to remove those muons \nthat are likely to have arisen in the decay of hadrons and to retain the overlapping jet instead. \nJets and muons may also appear in close proximity when the jet results from high-$\\pt$ muon bremsstrahlung, \nand in such cases the jet should be removed and the muon retained. Such jets are characterised by having very \nfew matching inner-detector tracks. Selected muons that satisfy $\\Delta R(\\mu,{\\textrm{jet}}) < 0.2$ are rejected\nif the jet is either $b$-tagged or has at least three tracks originating from the primary vertex; otherwise the jet is removed and the muon is kept.\nThe $\\tauhad$ within a $\\Delta R=0.2$ cone of an electron or muon are removed.\nIn order to avoid double-counting of $\\tauhad$ as jets, the closest jet whose axis is\nwithin ${\\Delta}R = 0.2$ of a $\\tauhad$ is discarded if the jet is not $b$-tagged, otherwise the $\\tauhad$ is removed. \n% TEXT FROM BOYANG. NEED TO RECHECK WHAT WE HAVE ABOVE IS ACCURATE\n%In the $\\Htautau$ search, the objects are removed with the following sequence: if two electrons have overlapping second-layer cluster, or shared tracks, the electron with lower $\\pt$ is removed; $\\tauhad$ within a $\\Delta R=0.2$ cone of an electron or muon are removed; if a muon sharing an ID track with an electron and the muon is calo-tagged, the muon is removed, otherwise the electron is removed; jets within a $\\Delta R=0.2$ cone of an electron are removed; electrons within a $\\Delta R=0.4$ cone of a jet are removed; when a muon ID track is ghost associated to a jet or within a $\\Delta R=0.2$ cone of a jet, the jet is removed if it has less than 3 tracks with $\\pt>500$ MeV or has a relative small $\\pt$ ($\\pt^{\\mu}>0.5\\pt^{\\text{jet}} \\text{ and } \\pt^{\\mu}>0.7[\\text{the scalar sum of the } \\pt \\text{'s of the jet tracks with } \\pt>500$ MeV]); muons within a $\\Delta R=0.4$ cone of a jet are removed; jets within a $\\Delta R=0.2$ cone of the leading $\\tauhad$ ($\\lephad$), or with the two leading $\\tauhad$'s ($\\hadhad$), are removed.\n\n%firstly, the electron within a ${\\Delta}R = 0.2$ cone of muons are excluded, then the $\\tau_{had}$'s or jets within a ${\\Delta}R = 0.2$ cone of an electron or muon are excluded. Finally, the jets within a ${\\Delta}R = 0.2$ cone of the leading $\\had$ ($\\lephad$), or with the two leading $\\had$’s ($\\hadhad$) are excluded.\n\nThe missing transverse momentum $\\mpt$ (with magnitude $\\met$) is defined as the negative vector sum of the \n$\\pt$ of all selected and calibrated objects in the event, including a term to account for momentum from soft particles \nin the event which are not associated with any of the selected objects. \nThis soft term is calculated from inner-detector tracks matched to the selected primary vertex to make it more resilient to\ncontamination from pile-up interactions~\\cite{Aaboud:2018tkc}.\n\n\n", "meta": {"hexsha": "21ba5b6ac2e16081c9de4ee002d0268662319632", "size": 14919, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "sections/objects.tex", "max_stars_repo_name": "liboyang0112/fcnc-paper", "max_stars_repo_head_hexsha": "08cb3a976aa4274b7bf414401b627ed84f50d926", "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": "sections/objects.tex", "max_issues_repo_name": "liboyang0112/fcnc-paper", "max_issues_repo_head_hexsha": "08cb3a976aa4274b7bf414401b627ed84f50d926", "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": "sections/objects.tex", "max_forks_repo_name": "liboyang0112/fcnc-paper", "max_forks_repo_head_hexsha": "08cb3a976aa4274b7bf414401b627ed84f50d926", "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.0633802817, "max_line_length": 1048, "alphanum_fraction": 0.7672766271, "num_tokens": 3857, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.3522017684487511, "lm_q1q2_score": 0.18983084349040585}}
{"text": "\\section{Hadron propagation.}\n\n\\hspace{1.0em}\nSo far the hadrons are transported along the straight line paths (cascade \napproach), i. e. particle coordinates ${\\bf r}$ for time \"shift\" \nbetween $t_0$ and \n$t_1$ are updated according to\n\\begin{equation}\n\\label{HP1} {\\bf r}(t_1) = {\\bf r}(t_0) + \\frac{ {\\bf p}(t_0)}{E(t_0)},\n\\end{equation}\nwhere ${\\bf p}$ and $E$ denote particles momenta and energies. \nThe intranuclear nucleons are assumed to be \"frozen\" before collision,\ni. e. they are allowed to move only with the c. m. nucleus velocity.\nHowever, their Fermi momenta are taken into account to find interaction\ncross sections or characteristics of secondary particles produced in the\ncourse of an intranuclear collision. \n", "meta": {"hexsha": "6c1a99d52a4276f5e8ee60482f3d75f283299420", "size": 730, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "geant4/hadronic/theory_driven/HadronKinetic/HadronPropagation.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/HadronPropagation.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/HadronPropagation.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": 42.9411764706, "max_line_length": 74, "alphanum_fraction": 0.7410958904, "num_tokens": 212, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6442251201477016, "lm_q2_score": 0.2942149659744614, "lm_q1q2_score": 0.18954067180414932}}
{"text": "\\hypertarget{performance-metrics-for-parallel-systems}{%\n\\section{Performance Metrics for Parallel\nSystems}\\label{performance-metrics-for-parallel-systems}}\n\n\\hypertarget{analytical-modeling}{%\n\\subsection{Analytical Modeling}\\label{analytical-modeling}}\n\n\\begin{itemize}\n\\tightlist\n\\item\n Sequential Runtime\n\n \\begin{itemize}\n \\tightlist\n \\item\n A sequential algorithm is evaluated by its runtime\n \\end{itemize}\n\\item\n Parallel Runtime\n\n \\begin{itemize}\n \\tightlist\n \\item\n The parallel runtime of a program depends on\n\n \\begin{itemize}\n \\tightlist\n \\item\n the input size n,\n \\item\n the number of processors p,\n \\item\n and the communication parameters of the machine.\n \\end{itemize}\n \\item\n An algorithm must therefore be analyzed in the context of the\n underlying platform.\n \\end{itemize}\n\\item\n Parallel System\n\n \\begin{itemize}\n \\tightlist\n \\item\n A parallel system is a combination of a parallel algorithm and an\n underlying parallel platform.\n \\end{itemize}\n\\item\n Wall-clock time\n\n \\begin{itemize}\n \\tightlist\n \\item\n the time from the start of the first processor to the end of the\n last processor in a parallel ensemble\n \\item\n in other words: the operation time of the processor which needs the\n most time\n \\end{itemize}\n\\end{itemize}\n\n\\hypertarget{metrics}{%\n\\subsubsection{Metrics}\\label{metrics}}\n\n\\begin{itemize}\n\\tightlist\n\\item\n $T_s(n)$: Zeitkomplexität des besten sequentiellen Vergleichalgorithmus\n\\item\n $T_p(p,n)$: Zeitkomplexität des besten parallelen Algorithmus\n\\item\n n: eindimensionale Inputgrösse\n\\item\n $p$: Anzahl ``Prozessoren'' (evtl. auch Threads, Cores, etc.)\n\\item\n Total Parallel Overhead $T_O = pT_P - T_S$\n\\item\n Speedup $S = T_S / T_P$\n\\item\n Speedup per processor = Efficiency $E = S / p = T_S / pT_P$\n\\end{itemize}\n\n\\hypertarget{speedup}{%\n\\subsubsection{Speedup}\\label{speedup}}\n\n\\begin{itemize}\n\\tightlist\n\\item\n The lower bound of the speedup can be 0 (for parallel programs that\n never terminate)\n\\item\n The upper bound of the speedup should in theory be p, but in practice\n it is often lower than p.\n\\end{itemize}\n\n\\begin{figure}[H]\n\\centering\n\\includegraphics[width=0.7\\textwidth]{figures/metricExample.png}\n\\caption{Metric Example}\n\\end{figure}\n\n\\hypertarget{big-o-landau-notation}{%\n\\subsubsection{Big-O / Landau Notation}\\label{big-o-landau-notation}}\n\n\\begin{itemize}\n\\tightlist\n\\item\n $\\mathcal{O}$ (Big O): Obergrenze, maximal so viele Schritte\n\\item\n $\\Omega$ (Omega): Untergrenze, mindestens so viele Schritte\n\\item\n $\\Theta$ (Theta): Obergrenze = Untergrenze, genau so viel\n\\end{itemize}\n\n\\hypertarget{cost-of-a-parallel-system}{%\n\\subsection{Cost of a Parallel System}\\label{cost-of-a-parallel-system}}\n\n\\begin{itemize}\n\\tightlist\n\\item\n Cost (amount of total work)\n\n \\begin{itemize}\n \\tightlist\n \\item\n is the product of parallel runtime and the number of processing\n elements used\n \\item\n Cost $= p * T_P$\n \\end{itemize}\n\\item\n Cost-Optimal System\n\n \\begin{itemize}\n \\tightlist\n \\item\n a parallel system is said to be cost-optimal if the cost of solving\n a problem on a parallel computer is asymptotically identical to\n serial cost since $E = T_S / pT_P$, for cost-optimal systems: $E = \\mathcal{O}(1)$\n \\end{itemize}\n\\end{itemize}\n\n\\hypertarget{impact-of-non-cost-optimality}{%\n\\subsection{Impact of\nNon-Cost-Optimality}\\label{impact-of-non-cost-optimality}}\n\n\\begin{itemize}\n\\tightlist\n\\item\n The efficiency is calculated from the speedup over the number of\n processors (S/P)\n\\item\n Increasing the processors doesn't always solve the problem. Even if\n the speedup is increasing, the efficiency can shrink\n\\item\n speedup goes down as the problem size n is increased for a given p\n\\item\n efficiency doesn't depend on p, but goes down as the problem size is\n increased\n\\end{itemize}\n\n\\hypertarget{effect-of-granularity-on-performance}{%\n\\subsection{Effect of Granularity on\nPerformance}\\label{effect-of-granularity-on-performance}}\n\n\\begin{figure}[H]\n\\centering\n\\includegraphics[width=0.7\\textwidth]{figures/granularityOnPerformance.png}\n\\caption{Effect of Granularity on Performance}\n\\end{figure}\n\n\\begin{itemize}\n\\tightlist\n\\item\n Scaling-Down a parallel system is using fewer than the maximum\n possible number of processing elements to execute a parallel algorithm\n\\item\n This often improves the efficiency\n\\item\n One way of scaling down could be\n\n \\begin{itemize}\n \\tightlist\n \\item\n think of each processor in the original case as a virtual processor\n and to assign virtual processors equally to scaled down processors\n \\item\n since the number of processing elements decreases by a factor of\n $n/p$, the computation at each processing element increases by a\n factor of $n/p$\n \\end{itemize}\n\\end{itemize}\n\n\\clearpage", "meta": {"hexsha": "07acb9fd631dfaa9c0d75f7261d6d128c13a171e", "size": 4836, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "TSM_ProgAlg/03_PerformanceMetrics.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_ProgAlg/03_PerformanceMetrics.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_ProgAlg/03_PerformanceMetrics.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": 24.9278350515, "max_line_length": 86, "alphanum_fraction": 0.7388337469, "num_tokens": 1390, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4610167793123159, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.18952900887370075}}
{"text": "% !TEX root = ./busty_transcription.tex\n\\section{Discussion and future work}\n\nThe study of gene expression is one of the dominant themes of modern biology,\nmade all the more urgent by the dizzying pace at which genomes are being\nsequenced. But there is a troubling Achilles heel buried in all of that genomic\ndata, which is our inability to find and interpret regulatory sequence. In\nmany cases, this is not possible even qualitatively, let alone the possibility\nof quantitative dissection of the regulatory parts of genomes in a predictive\nfashion. Other recent work has tackled the challenge of finding and annotating\nthe regulatory part of genomes \\cite{Belliveau2018, Ireland2020}. Once we have\ndetermined the architecture of the regulatory part of the genome, we are then\nfaced with the next class of questions which are sharpened by formulating them\nin mathematical terms, namely, what are the input-output properties of these\nregulatory circuits and what knobs control them?\n\nThe present work has tackled that question in the context of the first\nregulatory architecture hypothesized in the molecular biology era, namely, the\nrepressor-operator model of Jacob and Monod~\\cite{Jacob1961}. Regulation in that\narchitecture is the result of a competition between a repressor which inhibits\ntranscription and RNAP polymerase which undertakes it. Through the labors of\ngenerations of geneticists, molecular biologists and biochemists, an\noverwhelming amount of information and insight has been garnered into this\nsimple regulatory motif, licensing it as what one might call the ``hydrogen\natom'' of regulatory biology. It is from that perspective that the present paper\nexplores the extent to which some of the different models that have been\narticulated to describe that motif allow us to understand both the average level\nof gene expression found in a population of cells, the intrinsic cell-to-cell\nvariability, and the full gene expression distribution found in such a population\nas would be reported in a single molecule mRNA Fluorescence \\textit{in situ}\nHybridization experiment, for example.\nWe do so by contrasting two theoretical frameworks to think about the problem.\nOn the one hand, thermodynamic models are convenient ways to describe the\nproblem of gene regulation because of the relatively small number of parameters\ncompared with kinetic models, and the agnostic nature with respect to the full\nreaction topology that leads to a transcription event. In addition, either\nimplicitly or explicitly, many approaches to gene regulation focus strictly on\noccupancy and ideas such as $K_d$s, and thus is of great interest to test these\nmodels. This comes with the limitation that thermodynamic models are only able\nto make statements about mean gene expression of a quasi-steady state process.\nOn the other hand, kinetic models break those limitations, being able to make\nexplicit predictions about higher moments of the gene expression distribution,\nand the transient states towards steady state, at the cost of propagating the\nnumber of parameters, and demanding the full set of reactions\n\nOur key insights can be summarized as follows. First, as shown in\nFigure~\\ref{fig1:means_cartoons}, the mean expression in the simple repression\narchitecture is captured by a master curve in which the action of repressor and\nthe details of the RNAP interaction with the promoter appear separately and\nadditively in an effective free energy. Interestingly, as has been shown\nelsewhere in the context of the Monod-Wyman-Changeux model, these kinds of\ncoarse-graining results are an exact mathematical result and do not constitute\nhopeful approximations or biological naivete \\cite{Razo-Mejia2018, Chure2019}.\nThe fact that thermodynamic and kinetic models for the simple repression motif\ncan not only be reconciled, but are indistinguishable from each other at the\nlevel of mean mRNA count is a consequence of the possible transitions between\npromoter microstates. The promoter microstates in all models shown in Figure~1\ncan explicitly be separated into two groups: 1) promoters with repressor bound,\nand 2) all other promoters states. The single path between these two groups of\nstates guarantees detailed-balance between the groups. We can therefore separate\n\\textit{expression} related transitions, which by definition must be out of\nequilibrium, with \\textit{regulation} transitions that can in principle be in\nequilibrium. This implies that the probability distribution of the promoter\nmicrostates not involving the repressor take the same functional form, allowing\nus to write the fold-change as an effective free energy involving a regulation\nterm, $\\Delta F_R$, and a promoter details term, $\\rho$. We offer this argument\nas a conjecture, and we suspect that a careful argument using the\ngraph-theoretic framework based on the Matrix-Tree\nTheorem~\\cite{Gunawardena2012}, might furnish a ``proof'' not with some\nchallenges as this theoretical framework applies, at the present, to finite\ngraphs.\n\nTo further dissect the relative merits of the different models, we must appeal\nto higher moments of the gene expression probability distribution. To that end,\nour second set of insights focus on gene expression noise, where it is seen that\na treatment of the constitutive promoter already reveals that some models have\nFano factors (variance/mean) that are less than one, at odds with any and all\nexperimental data that we are aware of~\\cite{So2011, Jones2014}. This\ntheoretical result allows us to directly discard a subset of the models (models\n1-3 in Figure~\\ref{fig2:constit_cartoons}(A)) since they cannot be reconciled\nwith experimental observations. The two remaining models (models 4 and 5 in\nFigure~\\ref{fig2:constit_cartoons}) appear to contain enough microscopic realism\nto be able to reproduce the data. A previous exploration of model 4 demonstrated\nthe ``sloppy''~\\cite{Transtrum2015} nature of the model in which data on\nsingle-cell mRNA counts alone cannot constrain the value of all parameters\nsimultaneously \\cite{Razo-Mejia2020}. Here we demonstrate that the proposed\none-state bursty promoter model (model 5 in\nFigure~\\ref{fig2:constit_cartoons}(A)) emerges as a limit of the commonly used\ntwo-state promoter model \\cite{Peccoud1995, Shahrezaei2008, So2011, Sanchez2013,\nJones2014}. We put the idea to the test that this level of coarse-graining is\nrich enough to reproduce previous experimental observations. In particular we\nperform Bayesian inference to determine the two parameters describing the full\nsteady-state mRNA distribution, finding that the model is able to provide a\nquantitative description of a plethora of promoter sequences with different mean\nlevels of expression and noise.\n\nWith the results of the constitutive promoter in hand, we then fix the\nparameters associated with this class of promoters and use them as input for\nevaluating the noise in gene expression for the simple repression motif itself.\nThis allows us to provide a single overarching analysis of both the constitutive\nand simple repression architectures using one simple model and corresponding set\nof self-consistent parameters, demonstrating not only a predictive framework,\nbut also reconciling the thermodynamic and kinetic views of the same simple\nrepression constructs. More specifically, we obtained values for the\ntranscription factor association and dissociation rates by performing Bayesian\ninference on the full mRNA distribution for data obtained from simple-repression\npromoters with varying number of transcription factors per cell and affinity of\nsuch transcription factors for the binding site. The free energy value obtained\nfrom these kinetic rates --computed as the log ratio of the rates-- agrees with\nprevious inferences performed only from mean gene expression measurements, that\nassumed a thermodynamic rather than a kinetic\nframework~\\cite{Garcia2011a,Razo-Mejia2018}. Interestingly, to constrain the\nbinding and unbinding rates inferred for Figure~\\ref{fig4:repressed_post_full},\nall of the rates need to be simultaneously fit. This is because a single\ncombination of operator (repressor binding site) and aTc concentration\n(repressor copy number) cannot constraint both rates independently, but only\ntheir ratio (See Appendix~\\ref{sec:bayesian} for further details).\n\nIt is important to be clear on the nature of the assumptions present in all\nmodels, including model 5 from Figure~\\ref{fig2:constit_cartoons}(A). First, as\nwith many of the models used routinely in the analysis of transcription, the\nmodels considered here imagine the promoter as existing in a series of discrete\nstates. This assumption is clearly an oversimplification due to effects such as\nDNA supercoiling~\\cite{Chong2014,Sevier2016} or DNA\nlooping~\\cite{Boedicker2013a} which are both parameterized by continuous\nvariables describing DNA shape; although there are formal and very interesting\nways of integrating out such degrees of freedom. Another facet of the models\nused here is that they can feature irreversible processes characterized by only\na single rate process with no corresponding return pathway at odds with\nthermodynamics. Such models are mathematically convenient and serve only as an\napproximation to the more realistic situation in which the forward rates are\nmuch larger than the backward rates. One consequence is that the inferred rates\nfor the transcription burst rate and burst size can only be thought of as\neffective rate constants. Another idealization of the models considered here is\nthat when computing the fold-change in gene expression (Section 2) we assume\nthat the translation efficiency of an mRNA transcript is the same in cells with\nand without regulation. There might be some known biological effects that could\nlimit the applicability of this assumption such as cooperation between the\ntranscription and translation machinery~\\cite{Proshkin2010}, or coupling of mRNA\ntranscription and degradation~\\cite{Chen2015} among other potential effects.\nAnother implicit assumption in all of the models discussed here is that the\neffects due to changes in gene copy number during the cell cycle have no effects\non the expression profile. For moderate growth rates such as those used\nin~\\cite{Jones2014} from which we obtained the data, at all points during the\ncell cycle there are at most two copies of the gene of interest. In a recent\npublication, we explored the effects that this change in gene dosage can have in\ngene expression, finding that the effects are much more drastic at the protein\nlevel~\\cite{Razo-Mejia2020}.\n\nMore specifically, for model 5 from Figure~\\ref{fig2:constit_cartoons}(A), it is\ninteresting to speculate what microscopic details are being coarse-grained by\nour burst rate and burst size in Figure~\\ref{fig2:constit_cartoons}(A), model 5.\nChromosomal locus is one possible influence we have not addressed in this work,\nas all the single-molecule mRNA data from~\\cite{Jones2014} that we considered\nwas from a construct integrated at the \\textit{galK} locus. The results\nof~\\cite{Chong2014} indicate that transcription-induced supercoiling contributes\nsubstantially in driving transcriptional bursting, and furthermore, their\nFigure~7 suggests that the parameters describing the rate, duration, and size of\nbursts vary substantially for transcription from different genomic loci.\nAlthough the authors of~\\cite{Englaender2017} do not address noise, they note\nenormous differences in mean expression levels when an identical construct is\nintegrated at different genomic loci. The authors of~\\cite{Engl2020} attribute\nnoise and burstiness in their single-molecule mRNA data to the influence of\ndifferent sigma factors, which is a reasonable conclusion from their data. Could\nthe difference also be due to the different chromosomal locations of the two\noperons? What features of different loci are and are not important? Could our\npreferred coarse-grained model capture the variability across different loci? If\nso, and we were to repeat the parameter inference as done in this work, is there\na simple theoretical model we could build to understand the resulting\nparameters?\n\nIn summary, this work took up the challenge of exploring the extent to which a\nsingle specific mechanistic model of the simple-repression regulatory\narchitecture suffices to explain the broad sweep of experimental data for this\nsystem. Pioneering early experimental efforts from the M\\\"{u}ller-Hill lab\nestablished the simple-repression motif as an arena for the quantitative\ndissection of regulatory response in bacteria, with similar work emerging in\nexamples such as the \\textit{ara} and \\textit{gal} operons as\nwell~\\cite{Dunn1984b, Oehler1990, Weickert1993, Oehler1994, Schleif2000,\nSemsey2002, SwintKruse2009}. In light of a new generation of precision\nmeasurements on these systems, the definition of what it means to understand\nthem can now be formulated as a rigorous quantitative question. In particular,\nwe believe understanding of the simple repression motif has advanced\nsufficiently that the design of new versions of the architecture is now\npossible, based upon predictions about how repressor copy number and DNA binding\nsite strength control expression. In our view, the next step in the progression\nis to first perform similar rigorous analyses of the fundamental ``basis set''\nof regulatory architectures. Natural follow-ups to this work are explorations of\nmotifs such as simple activation that is regulated by a single activator binding\nsite, and the repressor-activator architecture, mediated by the binding of both\na single activator and a single repressor, and beyond. With the individual\ninput-output functions in hand, similar quantitative dissections including the\nrigorous analysis of their tuning parameters can be undertaken for the ``basis\nset'' of full gene-regulatory networks such as switches, feed-forward\narchitectures and oscillators for example, building upon the recent impressive\nefforts from systems biologists and synthetic biologists~\\cite{Milo2002,\nAlon2007}.", "meta": {"hexsha": "c88b3bfdbabe285f1f994d76c8592129dfc6a484", "size": 14044, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/resubmission/section_05_discussion.tex", "max_stars_repo_name": "RPGroup-PBoC/bursty_transcription", "max_stars_repo_head_hexsha": "cd3082c567168dfad12c08621976ea49d6706f89", "max_stars_repo_licenses": ["MIT"], "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/resubmission/section_05_discussion.tex", "max_issues_repo_name": "RPGroup-PBoC/bursty_transcription", "max_issues_repo_head_hexsha": "cd3082c567168dfad12c08621976ea49d6706f89", "max_issues_repo_licenses": ["MIT"], "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/resubmission/section_05_discussion.tex", "max_forks_repo_name": "RPGroup-PBoC/bursty_transcription", "max_forks_repo_head_hexsha": "cd3082c567168dfad12c08621976ea49d6706f89", "max_forks_repo_licenses": ["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.2893401015, "max_line_length": 81, "alphanum_fraction": 0.8240529764, "num_tokens": 3024, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.359364152021239, "lm_q1q2_score": 0.189498655271086}}
{"text": "\\subsection{Ranged}\n\\subsubsection{Bow-type}\n\\begin{longtable}{|C{2cm} L{2cm} L{2cm} L{8cm}|}\n\\hline\n\\large{\\textbf{Name}} &\n\\large{\\textbf{Cost}} &\n\\large{\\textbf{Handedness}} &\n\\large{\\textbf{Damage}}\n\\\\ \\hline\n\\WeaponRow{Shortbow}{60 m}{Two}{\nDepends on the ammunition, $\\frac{AmmoDamage}{10}*Strength$\n}{Shortbows are simple bows usually made for practice, sportsmanship or hunting rather than serious military use. They have a short range, and don't offer any bonuses to the damage caused by the arrows used. While the caused damage depends on the specific type of arrow used, such bows typically fail at penetrating armour.}\n\\WeaponRow{Longbow}{120 m}{Two}{\nDepends on the ammunition, $\\frac{AmmoDamage*1.5}{10}*Strength$\n}{Longbows are sturdier bows roughly the height of their users. Typically used as weapons of war, they require quite a bit of strength to use, and thus, longbowmen are usually trained from a rather young age. They are famous for their long range, and their extra strength gives them some armour-penetrating ability, especially when used with bodkin arrows.}\n\\WeaponRow{Recurve Bow}{160 m}{Two}{\nDepends on the ammunition, $\\frac{AmmoDamage*1.5}{10}*Strength$\n}{Bows where the limbs curve away from the archer when unstrung, typically made from composites of multiple materials, these weapons store and deliver energy more effectively than regular bows, but also require more strength to use. They are effectively shorter bows, but with the effectiveness of a longbow - though, they are also costlier to manufacture.}\n\\end{longtable}\n\\subsubsection{Crossbow}\n\\begin{longtable}{|C{2cm} L{2cm} L{2cm} L{8cm}|}\n\\hline\n\\large{\\textbf{Name}} &\n\\large{\\textbf{Cost}} &\n\\large{\\textbf{Handedness}} &\n\\large{\\textbf{Damage}}\n\\\\ \\hline\n\\WeaponRow{Stirrup Crossbow}{100 m}{Two}{\nDepends on the ammunition\n}{The earliest type of crossbow, it has a draw weight low enough to allow crossbowmen to draw the string back with their bare hands, but this also limits the maximum amount of draw weight such a crossbow can have, which in turn puts a limit on the strength of such a crossbow. With mundane ammunition, such crossbows are typically too weak to penetrate plate armour, merely causing dents.}\n\\WeaponRow{Goatsfoot Crossbow}{150 m}{Two}{\nDepends on the ammunition, $AmmoDamage*1.5$\n}{A variation of the stirrup crossbow - when draw weight is increased to the point that a crossbowman cannot pull the string back by their bare hands, some utilities are needed to do the job. The first of such utilities was the goat's foot lever, which slightly reduces rate of fire, but greatly increases the maximum draw weight - therefore maximum firepower - a crossbow can potentially have.}\n\\WeaponRow{Windlass Crossbow}{200 m}{Two}{\nDepends on the ammunition, $AmmoDamage*2$\n}{A further evolution of the crossbow - at one point, not even the goat's foot could lever could pull back the strings of the increasingly heavier crossbows, requiring a new utility to do the job: the windlass. Greatly increasing draw weight - potential firepower - at the expense of rate of fire, the windlass crossbow is only slighter faster to reload than a muzzle-loaded firearm, but compensates by penetrating platemail.}\n\\WeaponRow{Repeating Crossbow}{150 m}{Two}{\nDepends on the ammunition, $\\frac{AmmoDamage}{4}$ per shot\n}{Effectively pump-action repeating crossbow, the repeating crossbow has low firepower and short range, but compensates by having quite a high rate of fire, making it effective at crowd-control against larger number of unarmoured opponents.}\n\\WeaponRow{Hand Crossbow}{80 m}{One}{\nDepends on the ammunition, $\\frac{AmmoDamage}{3}$\n}{A pistol-shaped handheld crossbow small enough to be held in a single hand, it has a low firepower, short range and a rate of fire comparable to that of a stirrup crossbow, but compensates by being a lightweight hanheld weapon that can be held in a single hand.}\n\\end{longtable}\n\\subsubsection{Other}\n\\begin{longtable}{|C{2cm} L{2cm} L{2cm} L{8cm}|}\n\\hline\n\\large{\\textbf{Name}} &\n\\large{\\textbf{Cost}} &\n\\large{\\textbf{Handedness}} &\n\\large{\\textbf{Damage}}\n\\\\ \\hline\n\\WeaponRow{Sling}{50 m}{One}{\nDepends on the ammunition\n}{Ancient weapons that are used to hurl projectiles at the enemy - thus causing crushing damage -, short-ranged and inaccurate, they pack quite a punch when they actually hit their intended target.}\n\\WeaponRow{Javelin}{80 m}{One}{\n\\textit{Piercing:} $\\frac{2d8 \\pm modifiers}{5}*Strength$\\hfill \\break\n\\textit{Crushing:} $\\frac{1d4 \\pm modifiers}{5}*Strength$\n}{Shorter spears that are made for throwing. Not much else can be said about them.}\n\\WeaponRow{Blowgun}{50 m}{Two}{\nDepends on the ammunition, $\\frac{AmmoDamage}{10}*Strength$\n}{Primitive weapons where the projectiles are expelled from a narrow tube via the user's exhalation. Typically used with poisonous darts.}\n\\WeaponRow{Hand Cannon}{300 m}{Two}{\nDepends on the ammunition\n}{Primitive firearms powered by either gunpowder or a magical substance that fufills a similar function, hand cannons have an abysmally low rate of fire and a pathetically short range - even shorter than that of a shortbow, comparable to the pathetic range of repeating crossbows and hand crossbows - but compensate for all of this by having a devastating amount of firepower, and by making a loud noise that strikes fear into the hearts of uninitiated. At the weapon's effective range, no known armour can offer meaningful resistance to the bullets this weapon fires. The intended target's only hope for salvation is the weapon's infamously comical inaccuracy.}\n\\end{longtable}\n", "meta": {"hexsha": "d1f7db8718a88e41eddf6e62bd2016cd7954fc01", "size": 5585, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "chapters.d.tex/06-items.d.tex/02-weapons.d.tex/04-ranged.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/06-items.d.tex/02-weapons.d.tex/04-ranged.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/06-items.d.tex/02-weapons.d.tex/04-ranged.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": 84.6212121212, "max_line_length": 662, "alphanum_fraction": 0.7774395703, "num_tokens": 1428, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.658417487156366, "lm_q2_score": 0.2877678157610531, "lm_q1q2_score": 0.1894713621378687}}
{"text": "\\chapter{Parameterization of Human Knee Joints}\n\\label{sec:KneeParams}\n\nThe proposed and prototyped knee joint requires a specific input of patient parameters to achieve its goal of matching a person's knee movement. Therefore, a system must be developed to non-invasively identify a relationship between the flexion of the patient's knee joint and the linear movement of the shank away from the knee's joint center. There have been several attempts to parameterize the human knee joint using many different methods, including \\cite{3DKinKneeJointOldStabby}, \\cite{MRIKneeShape_Unloaded}, \\cite{MRIKneeShape_Loaded}, and \\cite{ModelAnalysisDeepKneeFlexion}. All of these studies focus on the tibiofemoral relationship, i.e. the bone movement within the lower limbs. However, rehabilitation exoskeletons connect to the skin of its user. Other studies have identified a difference between identifying knee kinematics through skin markers and bone pins \\cite{reinschmidt1997effect}, suggesting there is in fact a distinct difference between tibiofemoral movement and skin movement around the knee. Therefore, an imaging workflow and software processing program needs to be developed to be able to parameterize a patient's knee movement with consideration to skin movement.\n\nTo identify the knee relationship, an imaging workflow as well as an accompanying software analysis tool is proposed and tested with pilot data. This imaging method uses a motion capture system to identify movement of specific markers attached to a person's skin. This will all be processed using a custom software workflow consisting of both Vicon image processing and custom Python scripts that will extract the parameters from the data. To test this workflow, an experiment is proposed using medical MR imaging to identify the kinematics of the knee joint, compare the developed knee joint to a traditional pin joint, and determine the relationship between the knee joint kinematics and the skin movement surrounding the knee.\n\n\\section{Proposed Method of Imaging}\n\\label{sec:ImaginKneeProcedure}\n\n\\begin{figure}[ht!]\n \\centering\n \\includegraphics[width=0.65\\textwidth]{Figures/Param/StudyPatientPositioning.jpg}\n \\caption{Depicts the patient position during motion capture. The patient will then flex and extend their knee while keeping the heel on the table.}\n \\label{fig:ParamPatientPosition}\n\\end{figure}\n\nThe proposed imaging workflow can be split up into two major parts: the imaging session and the software processing. For flexibility and speed, the usage of a motion capture system is proposed, which can develop accurately track the position of motion dots. In this study, the motion capture system used was a 10-camera Vicon Vantage 5 \\footnote{See Vicon system here: \\url{https://www.vicon.com/hardware/cameras/vantage/}}, but any motion capture system is usable given enough precision. \n\nTo measure the knee flexion, a patient is placed on their back, shown in \\autoref{fig:ParamPatientPosition}.Motion capture dots are then placed on the patient using double-sided tape to track the positions where the exoskeleton will attach to the skin. Two additional points can be placed on the knee for extra feedback and the final joint position, but are not necessary for the software system. Then, the patient will flex and extend their knee joint while keeping the heel on the table to stabilize the knee and prevent shanking. The placement of the patient should allow for a technician to help the patient bend their knee if their condition does not allow them to do so themselves. Once the data is collected, it can be processed by the parameterization software system.\n\n\\section{Parameterization Software}\n% TODO: Add software flowchart\nThe collected data first goes through a Vicon workflow for processing. This will properly format the data, create virtual joints, and determine joint centers. This is done using the built-in tools called SCoRE (Symmetrical Center of Rotation Estimation) and SARA (Symmetrical Axis of Rotation Analysis). Additionally, a built-in tool will determine the angle of the knee joint using the four dots on each section of the patient's leg. This Vicon specific workflow can be exported, shared, and reused for others who are using a similar system. The output of the workflow is a CSV file which can be parsed by a custom script.\n\nTo finish the parameterization of the knee, custom software was developed and written in Python. This software utilizes the AiM Vicon Python module \\footnote{The AiM Vicon Python module is an open-source project found here: \\url{https://github.com/WPI-AIM/AIM_Vicon}} which parses the CSV file from above. The joint angle, SARA, SCoRE, and marker positions are extracted from the data and placed in their specified datatypes. Since the AiM Vicon module did not have all the tools needed for this project, I developed and contributed to the Python module. Additional features added include SARA and SCoRE support, a new 3D visualizer, and stability improvements when importing different workflows.\n\n\\begin{figure}[ht!]\n \\centering\n \\includegraphics[width=\\textwidth]{Figures/Param/3D_Marker_Animation.png}\n \\caption{An example of a possible output from the Parameterization Software System shown in a visualizer}\n \\label{fig:SoftwareSampleData}\n\\end{figure}\n\nWith the data parsed and imported, the final step is to calculate the final joint angles and determine the linear extension between the thigh and shank. The axis of rotation from SCoRE and all marker positions are projected onto a plane, which is calculated to be approximately the same as the plane of the manufactured joint. Then the final distance and angle are calculated by drawing two virtual lines as shown in \\autoref{fig:SoftwareSampleData}: 1. from the projected primary thigh marker to the projected SCoRE location and 2. from the projected SCoRE location to the projected primary shank marker. The lengths of these lines then become the calculated linear extension and the angle between these two lines become the flexion. These two metrics are then combined into a dataset, and a best fit quartic curve is selected to become the patient's knee parameters.\n\n\\section{Testing with Pilot Data}\nDue to time constraints, IRB (Internal Review Board) approval was not obtained to run a full study. However, some data was used to develop the software platform that will analyze the data. The graphs in \\autoref{fig:Subj1KneeParams} and \\autoref{fig:Subj2KneeParams} show the relationships between the knee joint flexion (angle of the knee) and the linear extension (distance of the shank to the joint center).\n\n\\begin{figure}[ht!]\n \\centering\n \\includegraphics[width=\\textwidth]{Figures/Param/Subj1_KneeProfile.png}\n \\caption{A visualization of the angular flexion and linear extension of the shank from the joint center of the first dataset with subject 1. Subject bent and extended their knee joint 4 times.}\n \\label{fig:Subj1KneeParams}\n\\end{figure}\n\n\\begin{figure}[ht!]\n \\centering\n \\includegraphics[width=\\textwidth]{Figures/Param/Subj2_KneeProfile.png}\n \\caption{A visualization of the angular flexion and linear extension of the shank from the joint center of the second dataset with subject 2. Subject bent and extended their knee joint 3 times.}\n \\label{fig:Subj2KneeParams}\n\\end{figure}\n\nThe data displayed in \\autoref{fig:Subj1KneeParams} has a variation of up to \\(7mm\\) for any given angle. However, what is most interesting is the difference in the direction of the flexion. When the knee joint angle is increasing (knee is being bent), the markers are closer together, compared to when the knee joint is decreasing. In any given direction of movement, variation is less than \\(2mm\\), suggesting that this seemingly cyclical trajectory is not due to measurement variations or inaccuracies.\n\n\\autoref{fig:Subj2KneeParams}'s data is seemingly less dependent on the knee joint angular velocity direction. All data is within a \\(3mm\\) variation at any given angle. The notable exception is the \\(7mm\\) spike that can be seen at roughly \\(25^\\circ\\) mark. This can likely be explained by either an accidental shift in the markers or a slight measurement error in the motion capture system. However, there is not sufficient data to make a conclusion as to the reasoning.\n\nThe data analyzed both show that the maximum variation in skin movement through the flexion of the knee never exceeded \\(7mm\\), even with the outlier event from \\autoref{fig:Subj2KneeParams}. In comparison, studies presented in \\autoref{sec:KneeModel} describe a tibio\\-femoral relationship that varies over \\(40mm\\) throughout the joint flexion. While these two data points are not statistically significant enough to make a conclusion for all human knees, the preliminary pilot data suggests that the skin movement is different than the tibiofemoral movement. An in-depth study is needed to make a definitive conclusion.\n\n\\section{Study Outline}\n\nAs a part of this thesis, an study was designed to test the developed parameterization software as well as the knee joint's capability to be customized to a specific person. However, due to time constraints, IRB (Internal Review Board) approval to run the human study was not obtained, and therefore the study was not run. The study's methodology is outlined below, and the IRB proposal documents are attached in \\autoref{apx:ParamStudyDocs}.\n\nUp to 6 subjects are to be selected to partake in this study. Each subject should not have any prior severe knee injury, and should be cleared to be imaged with an MRI. The study will start with imaging the knee using the motion capture procedures outlined in \\autoref{sec:ImaginKneeProcedure}, and parameters will be selected using the parameterization software developed. These parameters will be used to manufacture an MRI safe personalized knee joint. Additionally, a second non-personalized pin joint will be manufactured and used as a control.\n\nThe second stage of the study will compare the fit of the two joints. The subject will undergo MR scans at up to 3 different knee angles, first with no joint and then subsequently with each type of joint. The movement (if any) of the joint in reference to the subjects body will be measured. A successful experiment should demonstrate that the customized knee joint moves less than a non-customized pin joint. Additionally, the tibiofemoral movement can be compared to the measured parameters to determine how much the skin moves relative to the knee joint.\n", "meta": {"hexsha": "c2ba9d83f75d973db11cb1ab0768745ed27386a0", "size": 10538, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "sections/knee_params.tex", "max_stars_repo_name": "alextac98/KneeJointThesis", "max_stars_repo_head_hexsha": "db48c8df95657fab1a8c56a8906f997dfd5241a4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-04-25T04:44:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-25T04:44:08.000Z", "max_issues_repo_path": "sections/knee_params.tex", "max_issues_repo_name": "alextac98/KneeJointThesis", "max_issues_repo_head_hexsha": "db48c8df95657fab1a8c56a8906f997dfd5241a4", "max_issues_repo_licenses": ["MIT"], "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/knee_params.tex", "max_forks_repo_name": "alextac98/KneeJointThesis", "max_forks_repo_head_hexsha": "db48c8df95657fab1a8c56a8906f997dfd5241a4", "max_forks_repo_licenses": ["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.2835820896, "max_line_length": 1197, "alphanum_fraction": 0.8067944582, "num_tokens": 2287, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.37022540649291935, "lm_q1q2_score": 0.18945048798577616}}
{"text": "% 13 pages of text and up to 5 pages for references and appendices, totalling no more than 18 pages\n\n\\documentclass[conference]{IEEEtran}\n\n\\usepackage[numbers]{natbib}\n\\usepackage{amsmath}\n\\usepackage{amssymb}\n\\usepackage{stmaryrd}\n% For a version without hyperlinks, use the [draft] option.\n\\usepackage{hyperref}\n\\newcommand{\\email}[1]{\\href{mailto:#1}{{\\UrlFont #1}}}\n\\usepackage{amsthm}\n\\theoremstyle{plain}\n\\newtheorem{theorem}{Theorem}[section]\n\\newtheorem{proposition}[theorem]{Proposition}\n\\theoremstyle{definition}\n\\newtheorem{definition}[theorem]{Definition}\n% \\usepackage{verbatim}\n% \\makeatletter\n% \\def\\verbatim@font{\\sffamily\\upshape}\n% \\makeatother\n\n\\bibliographystyle{plainnat}\n\\usepackage{macros}\n\\newcommand{\\ignore}[1]{}\n\\newcommand{\\todo}[1]{{\\color{red}\\textbf{\\{#1\\}}}}\n\n\\pagestyle{plain}\n\n\\begin{document}\n\n\\title{The Code That Never Ran:\\\\Modeling Attacks on Speculative Evaluation}\n\n\\author{\n\\IEEEauthorblockN{Craig Disselkoen}\n\\IEEEauthorblockA{\\textit{University of California San Diego}\\\\\n \\textit{Mozilla Research Internship}\\\\\n \\email{cdisselk@cs.ucsd.edu}}\n\\and\n\\IEEEauthorblockN{Radha Jagadeesan}\n\\IEEEauthorblockA{\\textit{DePaul University}\\\\\n \\email{rjagadeesan@cs.depaul.edu}}\n\\and\n\\IEEEauthorblockN{Alan Jeffrey}\n\\IEEEauthorblockA{\\textit{Mozilla Research}\\\\\n \\email{ajeffrey@mozilla.com}}\n\\and\n\\IEEEauthorblockN{James Riely}\n\\IEEEauthorblockA{\\textit{DePaul University}\\\\\n \\email{jriely@cs.depaul.edu}}\n}\n\n\n\\maketitle\n\n\\begin{abstract}\n This paper studies information flow caused by speculation mechanisms\n in hardware and software. The Spectre attack shows that there are\n practical information flow attacks which use an interaction of\n dynamic security checks, speculative evaluation and cache timing.\n Previous formal models of program execution are designed to capture\n computer architecture, rather than micro-architecture, \n % have not been designed to model speculative evaluation,\n and so do not capture attacks such\n as Spectre. In this paper, we propose a model based on pomsets which\n is designed to model speculative evaluation. \n % The model provides a\n % compositional semantics for a simple shared-memory concurrent\n % language, which captures features such as data and control\n % dependencies, relaxed memory and transactions.\n The model is abstract with respect to specific micro-architectural\n features, such as caches and pipelines, yet is powerful enough to express\n known attacks such as Spectre and \\textsc{Prime+Abort},\n and verify their countermeasures.\n The model also allows for\n the prediction of new information flow attacks. We derive two such\n attacks, which exploit compiler optimizations, and validate these\n experimentally against gcc and clang.\n % We provide models for \n % existing information flow attacks based on speculative evaluation\n % and transactions. We also model new information flow attacks based on compiler\n % optimizations, which are experimentally validated against\n % gcc and clang.\n\\end{abstract}\n\n\\section{Introduction}\n\nThis paper is about some of the lies we tell when we talk about programs.\n\nAn example lie (or to be more formal, a ``leaky abstraction'') is the order\nof reads and writes in a program. We pretend that these happen in the\norder specified by the program text, for example\nwe think of the program\n\\(( \\aLoc\\GETS0 \\SEMI \\aLoc\\GETS1 \\SEMI \\bLoc\\GETS2 )\\)\nas having three sequentially ordered write events:\n\\begin{tikzdisplay}[node distance=1em]\n \\event{wx0}{\\DW{\\aLoc}{0}}{}\n \\event{wx1}{\\DW{\\aLoc}{1}}{right=of wx0}\n \\event{wy2}{\\DW{\\bLoc}{2}}{right=of wx1}\n \\po{wx0}{wx1}\n \\po{wx1}{wy2}\n\\end{tikzdisplay}\nHowever, due to optimizations in hardware or compilers, instructions\nmay be reordered, resulting in executions where the accesses of\n$\\aLoc$ and $\\bLoc$ are independent, and the hardware\nor compiler is free to reorder them:\n\\begin{tikzdisplay}[node distance=1em]\n \\event{wx0}{\\DW{\\aLoc}{0}}{}\n \\event{wx1}{\\DW{\\aLoc}{1}}{right=of wx0}\n \\event{wy2}{\\DW{\\bLoc}{2}}{right=of wx1}\n \\po{wx0}{wx1}\n\\end{tikzdisplay}\nInstruction reordering optimizations are not problematic as long\nas they are not visible to user code, that is if programs\nare sequentially consistent. Unfortunately, multi-threaded\nprograms can often observe reorderings. For example\nrunning the above writing thread concurrently with\nan observing thread \\((\\IF{\\bLoc}\\THEN \\cLoc\\GETS\\aLoc \\FI)\\)\ncan result in a sequentially inconsistent execution\n(where we highlight the matching write for each read):\n\\begin{tikzdisplay}[node distance=1em]\n \\node(th1){Writing thread:};\n \\event{wx0}{\\DW{\\aLoc}{0}}{right=of th1}\n \\event{wx1}{\\DW{\\aLoc}{1}}{right=of wx0}\n \\event{wy2}{\\DW{\\bLoc}{2}}{right=of wx1}\n \\po{wx0}{wx1}\n \\node(th2)[below=2.5ex of th1]{Observing thread:};\n \\event{ry2}{\\DR{\\bLoc}{2}}{below=of wx0}\n \\event{rx0}{\\DR{\\aLoc}{0}}{below=of wx1}\n \\event{wz0}{\\DW{\\cLoc}{0}}{below=of wy2}\n \\po{ry2}{rx0}\n \\po{rx0}{wz0}\n \\rf{wx0}{rx0}\n \\rf[out=210,in=35]{wy2}{ry2}\n\\end{tikzdisplay}\n\nThis leaky abstraction has resulted in a literature\nof \\emph{relaxed memory models}~\\cite{Manson:2005:JMM:1047659.1040336,SevcikThesis,Jagadeesan:2010:GOS:2175486.2175503,DBLP:journals/toplas/Lochbihler13,DBLP:conf/esop/BattyMNPS15,DBLP:conf/lics/JeffreyR16,Kang-promising-2017},\nwhich try to state precisely the memory guarantees\na compiler is expected to provide, without requiring the use of\nexpensive memory barriers to ensure sequential consistency.\n\nRelaxed memory is an example of how simple models can become\ncomplex. Instruction reordering was originally intended to be\nvisible only to the microarchitecture or compiler,\nnot to the architecture or user code.\nReordering optimizations are so important to the performance\nof modern systems that hardware and programming language designers\nhave now accepted the complexity of relaxed memory models as the price\nthat has to be paid for acceptable performance.\n\nThis paper looks at another leaky abstraction:\n\\emph{speculative evaluation}. This is similar to reordering,\nin that it is an optimization that was intended to be visible only to the microarchitecture,\nbut the arrival of Spectre~\\cite{DBLP:journals/corr/abs-1801-01203}\nshows that not only is speculation visible, it has serious\nsecurity implications.\n\nThe simplest example of speculative evaluation\nis branch prediction. The expected observable behavior of\na conditional such as\n\\(( \\IF{\\aLoc} \\THEN \\bLoc\\GETS1 \\ELSE \\cLoc\\GETS1 \\FI )\\)\nis that just one branch will execute, for example:\n\\begin{tikzdisplay}[node distance=1em]\n \\event{rx0}{\\DR{\\aLoc}{0}}{}\n \\event{wz1}{\\DW{\\cLoc}{1}}{right=of rx0}\n \\po{rx0}{wz1}\n\\end{tikzdisplay}\nTo improve instruction throughput, hardware will often evaluate\nbranches speculatively, and roll back any failed speculations. For example,\nhardware might incorrectly speculate that $\\aLoc$ is\nnonzero, speculatively execute a write to $\\bLoc$,\nbut then roll it back and execute a write to $\\cLoc$:\n\\begin{tikzdisplay}[node distance=1em]\n \\event{rx0}{\\DR{\\aLoc}{0}}{}\n \\nonevent{nwy1}{\\DW{\\bLoc}{1}}{right=of rx0}\n \\event{wz1}{\\DW{\\cLoc}{1}}{right=of nwy1}\n \\po{rx0}{nwy1}\n \\po[out=30,in=150]{rx0}{wz1}\n\\end{tikzdisplay}\nSpeculation is intended only to be visible at the microarchitectural\nlevel, but as Spectre shows, this abstraction is leaky, and in a way\nthat allows side-channel attacks to be mounted.\n\nInstruction reordering and speculative evaluation are similar leaky abstractions.\nBoth were intended originally not to\nbe visible to user code, but both abstractions have leaked.\nThis opens some possible areas of investigation:\n\\begin{itemize}\n\n\\item \\emph{Using ideas from relaxed memory for speculation}. There is a\n significant literature showing how to build models of relaxed memory, for\n use in validating compilers, or proving correctness of programs. Less\n formally, they provide programmers with a way to visualize and communicate\n the behavior of their systems. Inspired by these models, we give a\n compositional model of program execution that includes speculation\n (\\S\\ref{sec:model} and \\S\\ref{sec:semantics}) and show how it can be used\n to model known attacks (\\S\\ref{sec:examples}) on branch prediction\n \\cite{DBLP:journals/corr/abs-1801-01203} and transactional memory\n \\cite{ChongSW18,DBLP:conf/uss/DisselkoenKPT17}.\n\n\\item \\emph{Mounting attacks against speculation on relaxed memory}.\n Spectre shows how a leaky abstraction allows for the construction of\n side-channels which bypass dynamic security checks.\n %% Since defenses\n %% against buffer overflows are often dynamic checks, these attacks\n %% allow all memory in a process to be read.\n Inspired by these\n attacks, we show how to mount information flow attacks against\n compiler optimizations, both against the model (\\S\\ref{sec:compiler})\n and against existing compilers (\\S\\ref{sec:experiments}).\n Fortunately, we were only able to mount the attacks against\n ahead-of-time compilers (where optimizations require secrets\n to be known at compile-time) and not just-in-time compilers\n (which can optimize based on run-time secrets).\n With the addition of shared-memory concurrency\n to JavaScript~\\cite[\\S24.2]{ecma-262}, the attacks described in this paper might\n become feasible.\n %% We hope that compiler designers become as\n %% aware of information flow attacks against optimizations as their\n %% hardware designing colleagues.\n\n\\end{itemize}\nReaders who wish to focus on the impact of the model can skip to \\S\\ref{sec:examples}\non first reading, referring to prior sections as needed.\n\n\\paragraph*{Acknowledgments}\n\nWe would like to thank the anonymous referees,\nand the paper shepherd Frank Piessens, whose\ncomments helped greatly improve this paper.\nJagadeesan and Riely are supported by National Science Foundation CCR-1617175.\n\n\\section{Related work}\n\nInformation flow provides a formal\nfoundation for end-to-end security. Informally, a program is secure\nif there is no observable dependency of low-security outputs on high-security inputs.\nThe precise formalization of this intuitive idea has been the topic of\nextensive research \\cite{Sabelfeld:2006:LIS:2312191.2314769}, encompassing a variety of language\nfeatures such as non-determinism~\\cite{Wittbold1990InformationFI},\nconcurrency~\\cite{Smith:1998:SIF:268946.268975}, reactivity~\\cite{O'Neill:2006:ISI:1155442.1155677}, and\nprobability~\\cite{Gray:1992:TMF:2699806.2699811}. The static and dynamic enforcement\nof these definitions in general purpose languages~\\cite{myers-popl99} has % also\n% been studied extensively and has\ninfluenced language design and implementation.\n\nA key parameter in defining information flow is the \\emph{observational power} of the attacker model. Whereas the classical\ninput-output behavior is often an adequate foundation,\nit has long been known~\\cite{Lampson:1973:NCP:362375.362389,Biswas:2017:STC:3058791.3023872} that side-channels that leak\ninformation arise from other observables such as execution time and\npower consumption.\nRecently, the Spectre family of attacks~\\cite{DBLP:journals/corr/abs-1801-01203} has\nshown that branch prediction, in conjunction with cache-timing side-channels,\nallows adversaries to bypass dynamic security checks.\n\n\\citet{Chien:2018} argues that Spectre-like attacks ``extend the functional\nspecification of the architecture to include its detailed performance'' and\nthus ``making strong assurances of application security on a computing system\nrequires detailed performance information.''\nThis approach has been pursued in the information flow literature, by\nenriching language semantics with observables such as execution time and power consumption\n\\cite{Zhang:2012:LCM:2345156.2254078,hyperflow}. This approach\nhas also been pursued to develop model-checking techniques for Spectre-like\nattacks \\cite{DBLP:conf/micro/TrippelLM18}. Like our work,\n\\cite{DBLP:conf/micro/TrippelLM18} recognizes the role played by adapting\ntechniques from relaxed memory.\n\nIn this paper, we adopt the opposite approach, attempting to understand\nSpectre-like attacks as \\emph{abstractly} as possible and thus to reveal the\n``essence'' of Spectre. We develop a novel model of speculative\nevaluation and show that it is sufficient to both capture known attacks and\npredict new attacks. Our model is defined at the \\emph{language} level,\nrather than the hardware level; thus, we do not model micro-architectural\ndetails such as caches or timing.\n\nRelaxed memory models\n\\cite{SparcV9,Manson:2005:JMM:1047659.1040336,Boehm:2008:FCC:1375581.1375591,DBLP:conf/popl/ZhaoNMZ12,\n Jagadeesan:2010:GOS:2175486.2175503,Kang-promising-2017} allow\nspeculative execution to varying degrees. Relaxed execution is known to\naffect the validity of information flow analyses\n\\cite{6957104,Vaughan:2012:SIF}.\nIn these models, a valid execution is defined\nwith reference to other possible executions of the program. These\nmodels are not, however, designed for modeling Spectre-style attacks\non speculation. For example all of these models will consider the\nstraight-line code:\n\\[\n r\\GETS x\\SEMI s\\GETS\\SEC \\SEMI\n a[r]\\GETS 1\n\\]\nto be the same as the conditional code:\n\\[\\begin{array}{ll}\n r\\GETS x\\SEMI s\\GETS\\SEC \\SEMI \\\\[\\jot]\n \\IF{r\\EQ s} \\THEN a[s]\\GETS 1 \\ELSE a[r]\\GETS 1 \\FI\n\\end{array}\\]\nand indeed an optimizing compiler might choose to rewrite\neither of these programs to be the other.\n\nAn attacker can mount a Spectre-style attack on the\nconditional code, for example by setting $x$ to be~$0$,\nflushing the cache,\nexecuting the program, then using timing effects to\ndetermine if $a[1]$ is in the cache. If it is, then $\\SEC$\nmust have been~$1$. This attack is not possible against\nthe straight-line code, and so any model trying to\ncapture Spectre must distinguish them.\n\nMost definitions of non-interference will say that in both\nprograms, there is no observable dependency of the low-security\noutputs ($a$) on the high-security inputs ($\\SEC$) and so both programs\nare safe.\n The only existing models of\nnon-interference which capture this information flow are ones such\nas~\\cite{Zhang:2012:LCM:2345156.2254078} which model\nmicro-architectural features such as caching and timing.\n\nIn our model, the straight-line and conditional programs are not equated, since the conditional code has the execution:\n\\begin{tikzdisplay}[node distance=1em]\n \\event{rx0}{\\DR{\\aLoc}{0}}{}\n \\event{rs1}{\\DR{\\SEC}{1}}{below=of rx0}\n \\event{wa01}{\\DW{a[0]}{1}}{right=3em of rx0}\n \\nonevent{wa11}{\\DW{a[1]}{1}}{below=of wa01}\n \\po{rx0}{wa01}\n \\po{rs1}{wa01}\n \\po{rx0}{wa11}\n \\po{rs1}{wa11}\n\\end{tikzdisplay}\nwhich is not matched in the straight-line code.\nIndeed, from an information-flow perspective,\nthis refined treatment of dependencies in conditionals identifies a novel\ndistinguishing feature of our model, namely that the traditional conditional\nis a self-composition operator in the sense\nof~\\cite{Barthe:2004:SIF:1009380.1009669}.\n\nStatic analyses such as the Smith-Volpano type\nsystem~\\cite{Smith:1998:SIF:268946.268975} will reject the conditional\nprogram, due to $a[s]\\GETS 1$, in which a low-security assignment depends on\na high-security variable. We show how to circumvent such analyses in\n\\S\\ref{sec:spectre}.\n\n\\section{UNUSED: Old intro}\nInformation flow provides a formal\nfoundation for end-to-end security. Informally, a program is secure\nif there is no observable dependency of low-security outputs on high-security inputs.\nThe precise formalization of this intuitive idea has been the topic of\nextensive research \\cite{Sabelfeld:2006:LIS:2312191.2314769}, encompassing a variety of language\nfeatures such as non-determinism~\\cite{Wittbold1990InformationFI},\nconcurrency~\\cite{Smith:1998:SIF:268946.268975}, reactivity~\\cite{O'Neill:2006:ISI:1155442.1155677}, and\nprobability~\\cite{Gray:1992:TMF:2699806.2699811}. The static and dynamic enforcement\nof these definitions in general purpose languages~\\cite{myers-popl99} has % also\n% been studied extensively and has\ninfluenced language design and implementation.\n\nA key parameter in defining information flow is the \\emph{observational power} of the attacker model. Whereas the classical\ninput-output behavior is often an adequate foundation,\nit has long been known~\\cite{Lampson:1973:NCP:362375.362389,Biswas:2017:STC:3058791.3023872} that side-channels that leak\ninformation arise from other observables such as execution time and\npower consumption.\nRecently, the Spectre family of attacks~\\cite{DBLP:journals/corr/abs-1801-01203} has\nshown that branch prediction, in conjunction with cache-timing side-channels,\nallows adversaries to bypass dynamic security checks.\n\n\\citet{Chien:2018} argues that Spectre-like attacks ``extend the functional\nspecification of the architecture to include its detailed performance'' and\nthus ``making strong assurances of application security on a computing system\nrequires detailed performance information.''\nThis approach has been pursued in the information flow literature, by\nenriching language semantics with observables such as execution time and power consumption\n\\cite{Zhang:2012:LCM:2345156.2254078,hyperflow}.\n\nIn this paper, we adopt the opposite approach, attempting to understand\nSpectre-like attacks as \\emph{abstractly} as possible and thus to reveal the\n``essence'' of Spectre. We develop a novel model of \\emph{speculative\n evaluation} and show that it is sufficient to both capture known attacks and\npredict new attacks. Our model is defined at the \\emph{language} level,\nrather than the hardware level; thus, we do not model micro-architectural\ndetails such as caches or timing, as in\n\\cite{Zhang:2012:LCM:2345156.2254078,hyperflow}.\n% We try to give as\n% simple a model as possible, while still capturing shared-memory concurrency\n% and speculation.\n\n\nThere are several sources of speculative evaluation in modern computer\nsystems, intended to improve performance without affecting the observable\nbehavior of the program: Failed speculations are meant to be\nundetectable. Yet, Spectre-like attacks show that failed speculations are not\nalways undetectable. Our model provides a unifying mechanism to understand\nthese sources of speculation. Because failed speculations are part of the\nmodel, it is easily enriched with operators to detect operations that occur\nin failed speculations.\n% In the spirit of \\citet{Chien:2018}, our model ``extends the functional\n% specification of the programming language to include its detailed performance''.\n% so that failed speculation does not affect the input-output behavior\n% of the program, but may affect other observable behavior, opening an opportunity\n% for side-channels:\n\\begin{itemize}\n\\item Relaxed memory models\n \\cite{SparcV9,Manson:2005:JMM:1047659.1040336,Boehm:2008:FCC:1375581.1375591,DBLP:conf/popl/ZhaoNMZ12}\n allow speculative execution to varying degrees. Relaxed execution\n is known to affect the validity of information flow analyses\n \\cite{6957104,Vaughan:2012:SIF}. More troubling, relaxed memory models\n allow for the observation of control and data dependencies. This creates an\n opportunity for information flows caused by optimizing compilers, whose\n behavior is driven by dependency analysis. Our basic model captures this\n dependency analysis.\n %% For example,\n %% $(\\IF{\\aReg}\\THEN \\aLoc\\GETS1 \\ELSE \\aLoc\\GETS1 \\FI)$ can be optimized to\n %% $(\\aLoc\\GETS1)$, whereas %% $(\\IF{\\aReg}\\THEN \\aLoc\\GETS1 \\ELSE \\aLoc\\GETS2 \\FI)$ cannot be so\n %% optimized.\n\\item Pipelined micro-architectures use \\emph{branch prediction}\n to speculatively execute the result of\n a conditional jump or indirect jump instruction.\n Spectre \\cite{DBLP:journals/corr/abs-1801-01203} exploits\n cache timing to detect the operations performed in a mispredicted branch\n before being flushed from the pipeline. We capture Spectre by enriching\n our language with a single operation that allows one to test whether a\n location has been touched. %, even in a failed speculation.\n %% This means,\n %% for example, that a single execution of\n %% $(\\IF{\\aExp}\\THEN \\aCmd \\ELSE \\bCmd \\FI)$ may depend on both $\\aCmd$ and\n %% $\\bCmd$. This differs from the standard semantics of the conditional, in\n %% which executions of $\\aCmd$ and $\\bCmd$ are disjoint.\n\\item Some microprocessors support transactional\n memory~\\cite{ChongSW18}, where aborted transactions are meant to be\n unobservable. \\textsc{Prime+Abort}\n \\cite{DBLP:conf/uss/DisselkoenKPT17} uses cache timing to detect the\n operations performed in an aborted transaction. We capture \\textsc{Prime+Abort} by enriching\n our language with transactions that abort when a location used by the\n transaction is touched outside the transaction.\n\\end{itemize}\n\n%% This line of research was initiated by~\\citet{Zhang:2012:LCM:2345156.2254078}.\n%% Whereas they explore static annotations to address side channels in the context of hardware description languages, we explore a model of programs\n%% that captures enough detail to reveal and analyze the presence of side\n%% channels revealed by speculative execution.\n%\n\nOur model is based on \\emph{partially ordered multisets}~\\cite{GISCHER1988199,Plotkin:1997:TSP:266557.266600}\n(``pomsets''), whose labels are given by read and write actions. These can be\nvisualized as a graph where the edges indicate dependencies, for example\n$(\\aReg\\GETS\\aLoc\\SEMI \\bLoc\\GETS1\\SEMI \\cLoc\\GETS\\aReg+1)$\nhas an execution modeled by the pomset:\n\\begin{tikzdisplay}[node distance=1em]\n \\event{rx1}{\\DR{\\aLoc}{1}}{}\n \\event{wy1}{\\DW{\\bLoc}{1}}{right=of rx1}\n \\event{wz2}{\\DW{\\cLoc}{2}}{right=of wy1}\n \\po[out=25,in=155]{rx1}{wz2}\n\\end{tikzdisplay}\nThe edge from $(\\DR{\\aLoc}{1})$ to $(\\DW{\\cLoc}{2})$ indicates a\ndata dependency. Since there is no dependency between\n$(\\DW{\\bLoc}{1})$ and $(\\DW{\\cLoc}{2})$, the write actions may\ntake place in either order. Such reorderings may arise in\nhardware (for example, caching) or in the compiler (for example,\ninstruction reordering).\n\nThe novel aspect of the model is that events have\n\\emph{preconditions} which may be false. These are used in giving the\nsemantics of conditionals and transactions, modeling failed branch\nprediction and aborted transactions. For example the program\n$(\\IF{\\aLoc}\\THEN \\bLoc\\GETS1\\SEMI\\cLoc\\GETS1 \\ELSE \\bLoc\\GETS2\\SEMI\\cLoc\\GETS1\\FI)$\nhas an execution:\n\\begin{tikzdisplay}[node distance=1em]\n \\event{rx1}{\\DR{\\aLoc}{1}}{}\n \\event{wy1}{\\DW{\\bLoc}{1}}{right=of rx1}\n \\nonevent{wy2}{\\DW{\\bLoc}{2}}{below=of wy1}\n \\event{wz1}{\\DW{\\cLoc}{1}}{right=of wy1}\n \\po{rx1}{wy1}\n \\po{rx1}{wy2}\n\\end{tikzdisplay}\nThe edges from $(\\DR{\\aLoc}{1})$ to $(\\DW{\\bLoc}{1})$ and\n$(\\DW{\\bLoc}{2})$ indicate control dependencies. The presence of\na crossed out $(\\DW{\\bLoc}{2})$ indicates an event with an unsatisfiable precondition,\nmodeling an unsuccessful speculation.\nSince the $(\\DW{\\cLoc}{1})$ action is performed on both branches of the conditional,\nthere is no control dependency from $(\\DR{\\aLoc}{1})$. Indeed, from an information-flow perspective,\nthis refined treatment of dependencies in conditionals identifies a novel distinguishing feature of our model, namely that the traditional conditional is a self-composition operator in the sense of~\\cite{Barthe:2004:SIF:1009380.1009669}.\n\nThere do exist models of programs which include speculation, notably\nthe Java Memory Model~\\cite{Manson:2005:JMM:1047659.1040336}, and the\ngenerative~\\cite{Jagadeesan:2010:GOS:2175486.2175503} and\npromising~\\cite{Kang-promising-2017} operational semantics for\nrelaxed memory. In all of these models a valid execution is defined\nwith reference to other possible executions of the program. These\nmodels are not, however, designed for modeling Spectre-style attacks\non speculation. For example all of these models will consider the\nstraight-line code:\n\\[\n r\\GETS x\\SEMI s\\GETS\\SEC \\SEMI\n a[r]\\GETS 1\n\\]\nto be the same as the conditional code:\n\\[\\begin{array}{ll}\n r\\GETS x\\SEMI s\\GETS\\SEC \\SEMI \\\\[\\jot]\n \\IF{r\\EQ s} \\THEN a[s]\\GETS 1 \\ELSE a[r]\\GETS 1 \\FI\n\\end{array}\\]\nand indeed an optimizing compiler might choose to rewrite\neither of these programs to be the other.\n\nAn attacker can mount a Spectre-style attack on the\nconditional code, for example by setting $x$ to be~$0$,\nflushing the cache,\nexecuting the program, then using timing effects to\ndetermine if $a[1]$ is in the cache. If it is, then $\\SEC$\nmust have been~$1$. This attack is not possible against\nthe straight-line code, and so any model trying to\ncapture Spectre must distinguish them.\n\nMost definitions of non-interference will say that in both\nprograms, there is no observable dependency of the low-security\noutputs ($a$) on the high-security inputs ($\\SEC$) and so both programs\nare safe.\n The only existing models of\nnon-interference which capture this information flow are ones such\nas~\\cite{Zhang:2012:LCM:2345156.2254078} which model\nmicro-architectural features such as caching and timing.\n\nIn our model, the straight-line and conditional programs are not equated, since the conditional code has the execution:\n\\begin{tikzdisplay}[node distance=1em]\n \\event{rx0}{\\DR{\\aLoc}{0}}{}\n \\event{rs1}{\\DR{\\SEC}{1}}{below=of rx0}\n \\event{wa01}{\\DW{a[0]}{1}}{right=3em of rx0}\n \\nonevent{wa11}{\\DW{a[1]}{1}}{below=of wa01}\n \\po{rx0}{wa01}\n \\po{rs1}{wa01}\n \\po{rx0}{wa11}\n \\po{rs1}{wa11}\n\\end{tikzdisplay}\nwhich is not matched in the straight-line code.\n\nStatic analyses such as the Smith-Volpano type\nsystem~\\cite{Smith:1998:SIF:268946.268975} will reject the conditional\nprogram, due to $a[s]\\GETS 1$, in which a low-security assignment depends on\na high-security variable. We show how to circumvent such analyses in\n\\S\\ref{sec:spectre}.\n\n\nThe model in this paper leads to new attacks on optimizing\ncompilers~(\\S\\ref{sec:info-flow-attack} and~\\S\\ref{sec:dse}) which\nwere discovered as a consequence of building the model. A natural\nquestion is whether these attacks are an artifact of the model, or if\nthey can be mounted in practice? We mounted the attacks on gcc and\nclang, where they succeeded in leaking a $\\SEC$ as long as the secret\nwas a constant known at compile time. By itself this is not too\nworrying, since secrets are not normally static constants. If the same\nattacks could be mounted against Just-In-Time~(JIT) compilers, this\nis potentially significant, as secrets are often known at JIT-compile\ntime.\n\nFortunately, our attempts to mount the attacks against SpiderMonkey,\nV8 and HotSpot did not succeed. We speculate that this is because\nJIT compilers do not perform as aggressive optimizations as\nahead-of-time compilers, and not because of mitigations against\ninformation flows. With the addition of shared-memory concurrency\nto JavaScript~\\cite[\\S24.2]{ecma-262}, the attacks described in this paper might\nbecome feasible. We hope that compiler designers become as\naware of information flow attacks against optimizations as their\nhardware designing colleagues.\n\nThe novel contributions of this paper are:\n\\begin{itemize}\n\n\\item a compositional model of program execution that includes speculation\n (\\S\\ref{sec:model} and \\S\\ref{sec:semantics}),\n\n\\item examples showing how the model can be applied,\n including existing information flow attacks on\n hardware and transactional memory, and new attacks on optimizing compilers (\\S\\ref{sec:examples}), and\n\n\\item experimental evidence about how practical it is to mount\n the new class of attacks (\\S\\ref{sec:experiments}).\n\n\\end{itemize}\nReaders who wish to focus on the impact of the model can skip to \\S\\ref{sec:examples}\non first reading, referring to prior sections as needed.\n\n\n\\section{Model}\n\\label{sec:model}\n\nOur model is based on \\emph{partially ordered multisets}~\\cite{GISCHER1988199,Plotkin:1997:TSP:266557.266600}\n(``pomsets''), whose labels are given by read and write actions. These can be\nvisualized as a graph where the edges indicate dependencies, for example\n$(\\aReg\\GETS\\aLoc\\SEMI \\bLoc\\GETS1\\SEMI \\cLoc\\GETS\\aReg+1)$\nhas an execution modeled by the pomset:\n\\begin{tikzdisplay}[node distance=1em]\n \\event{rx1}{\\DR{\\aLoc}{1}}{}\n \\event{wy1}{\\DW{\\bLoc}{1}}{right=of rx1}\n \\event{wz2}{\\DW{\\cLoc}{2}}{right=of wy1}\n \\po[out=25,in=155]{rx1}{wz2}\n\\end{tikzdisplay}\nThe edge from $(\\DR{\\aLoc}{1})$ to $(\\DW{\\cLoc}{2})$ indicates a\ndata dependency. Since there is no dependency between\n$(\\DW{\\bLoc}{1})$ and $(\\DW{\\cLoc}{2})$, the write actions may\ntake place in either order. Such reorderings may arise in\nhardware (for example, caching) or in the compiler (for example,\ninstruction reordering).\n\nThe novel aspect of the model is that events have\n\\emph{preconditions}, which give the thread-local view of memory. These are used in giving the\nsemantics of conditionals and transactions, modeling failed branch\nprediction and aborted transactions. For example the program\n$(\\IF{\\aLoc}\\THEN \\bLoc\\GETS1\\SEMI\\cLoc\\GETS1 \\ELSE \\bLoc\\GETS2\\SEMI\\cLoc\\GETS1\\FI)$\nhas an execution:\n\\begin{tikzdisplay}[node distance=1em]\n \\event{rx1}{\\DR{\\aLoc}{1}}{}\n \\event{wy1}{\\DW{\\bLoc}{1}}{right=of rx1}\n \\nonevent{wy2}{\\DW{\\bLoc}{2}}{below=of wy1}\n \\event{wz1}{\\DW{\\cLoc}{1}}{right=of wy1}\n \\po{rx1}{wy1}\n \\po{rx1}{wy2}\n\\end{tikzdisplay}\nThe edges from $(\\DR{\\aLoc}{1})$ to $(\\DW{\\bLoc}{1})$ and\n$(\\DW{\\bLoc}{2})$ indicate control dependencies. The presence of\na crossed out $(\\DW{\\bLoc}{2})$ indicates an event with an unsatisfiable precondition,\nmodeling an unsuccessful speculation.\nSince the $(\\DW{\\cLoc}{1})$ action is performed on both branches of the conditional,\nthere is no control dependency from $(\\DR{\\aLoc}{1})$. \n\nWe give the semantics of a program as a set of pomsets with event labels of the form\n$(\\aForm \\mid \\aAct)$, where $\\aForm$ is the event's precondition\n(such as $\\aExp=\\aVal$) and $\\aAct$ is the event's action (such as $\\DW\\aLoc\\aVal$).\nFor example the semantics of the program $(\\aLoc\\GETS\\aExp)$ includes the case\nwhere $\\aExp$ is $\\aVal$, which is written to $\\aLoc$, and is captured\nby the one-event pomset:\n\\begin{tikzdisplay}[node distance=1em]\n \\event{wxv}{\\aExp=\\aVal \\mid \\DW{\\aLoc}{\\aVal}}{}\n\\end{tikzdisplay}\nWe make few requirements of the logic of preconditions, save that it\nincludes equalities between expressions, is closed under substitution,\nand supports a notion of implication.\n\n% For example, the set of pomsets $\\sem{\\aReg\\GETS\\bLoc\\SEMI \\aLoc\\GETS\\aReg+1}$ contains:\n% \\begin{tikzdisplay}[node distance=1em]\n% \\event{ry1}{\\DR{\\bLoc}{1}}{}\n% \\event{wx2}{\\DW{\\aLoc}{2}}{right=of ry1}\n% \\po{ry1}{wx2}\n% \\end{tikzdisplay}\nThe semantics is defined compositionally. As an example, we show how to \nconstruct one of the pomsets in\n$\\sem{\\aReg\\GETS\\bLoc\\SEMI \\aLoc\\GETS\\aReg+1}$.\nFirst, $\\sem{\\aLoc\\GETS\\aReg+1}$\ncontains the pomset:\n\\begin{tikzdisplay}[node distance=1em]\n \\event{wx2}{\\aReg=1 \\mid \\DW{\\aLoc}{2}}{}\n\\end{tikzdisplay}\nNext, we perform the substitution of $\\aReg$ with $1$ in every precondition,\nto get that $\\sem{\\aLoc\\GETS\\aReg+1}[1/\\aReg]$\ncontains the pomset:\n\\begin{tikzdisplay}[node distance=1em]\n \\event{wx2}{1=1 \\mid \\DW{\\aLoc}{2}}{}\n\\end{tikzdisplay}\nand since $(1=1)$ is a tautology, we elide it:\n\\begin{tikzdisplay}[node distance=1em]\n \\event{wx2}{\\DW{\\aLoc}{2}}{}\n\\end{tikzdisplay}\nThis substitution is performed in defining\n$\\sem{\\aReg\\GETS\\bLoc\\SEMI \\aLoc\\GETS\\aReg+1}$, which contains\nthe pomset:\n\\begin{tikzdisplay}[node distance=1em]\n \\event{ry1}{\\DR{\\bLoc}{1}}{}\n \\event{wx2}{\\DW{\\aLoc}{2}}{right=of ry1}\n \\po{ry1}{wx2}\n\\end{tikzdisplay}\nThere is an ordering $(\\DR{\\bLoc}{1}) \\lt (\\DW{\\aLoc}{2})$ (represented pictorially as an arrow)\nbecause the precondition $(\\aReg=1)$ depends on $\\aReg$. If the precondition\nwas independent of $\\aReg$ then there would be no ordering, for example\n$\\sem{\\aReg\\GETS\\bLoc\\SEMI \\aLoc\\GETS\\aReg+1-\\aReg}$ contains\nthe pomset:\n\\begin{tikzdisplay}[node distance=1em]\n \\event{ry1}{\\DR{\\bLoc}{1}}{}\n \\event{wx1}{\\DW{\\aLoc}{1}}{right=of ry1}\n\\end{tikzdisplay}\nsince the precondition $(\\aReg+1-\\aReg=1)$ is independent of $\\aReg$.\n\nThe main novelty of our semantics is the use of preconditions, which allow us\nto provide an unusual model of conditionals. In most\nmodels, an execution of\n$\\sem{\\IF{\\aExp}\\THEN \\aCmd \\ELSE \\bCmd \\FI}$ would either be\ngiven by an execution from $\\sem{\\aCmd}$ or from $\\sem{\\bCmd}$, but not both.\nIn our semantics, a pomset\nin $\\sem{\\IF{\\aExp}\\THEN \\aCmd \\ELSE \\bCmd \\FI}$ may include\nboth a pomset from $\\sem{\\aCmd}$ \\emph{and} a pomset from $\\sem{\\bCmd}$.\nFor example, $\\sem{\\IF{\\aExp}\\THEN \\aLoc\\GETS1 \\ELSE \\aLoc\\GETS2 \\FI}$\ncontains:\n\\begin{tikzdisplay}[node distance=1em]\n \\event{wx1}{\\aExp\\neq0 \\mid \\DW{\\aLoc}{1}}{}\n \\event{wx2}{\\aExp=0 \\mid \\DW{\\aLoc}{2}}{right=of wx1}\n\\end{tikzdisplay}\nthat is we have behavior from both branches of execution.\n\nMoreover, two events representing the same action on both sides of a\nconditional can be merged, producing a single event.\nThe precondition of the merged event is the disjunction of the preconditions\nof the original events.\nFor example\n$\\sem{\\IF{\\aExp}\\THEN \\aLoc\\GETS1\\SEMI \\bLoc\\GETS3 \\ELSE \\aLoc\\GETS2\\SEMI \\bLoc\\GETS3 \\FI}$\ncontains:\n\\begin{tikzdisplay}[node distance=1em]\n \\event{wx1}{\\aExp\\neq0 \\mid \\DW{\\aLoc}{1}}{}\n \\event{wx2}{\\aExp=0 \\mid \\DW{\\aLoc}{2}}{right=of wx1}\n \\event{wy3}{(\\aExp\\neq0) \\lor (\\aExp=0) \\mid \\DW{\\bLoc}{3}}{below=3ex of $(wx1)!0.5!(wx2)$}\n\\end{tikzdisplay}\nand since $(\\aExp\\neq0) \\lor (\\aExp=0)$ is a tautology, this is:\n\\begin{tikzdisplay}[node distance=1em]1\n \\event{wx1}{\\aExp\\neq0 \\mid \\DW{\\aLoc}{1}}{}\n \\event{wx2}{\\aExp=0 \\mid \\DW{\\aLoc}{2}}{right=of wx1}\n \\event{wy3}{\\DW{\\bLoc}{3}}{right=of wx2}\n\\end{tikzdisplay}\n\nCombining this model of conditionals with the previously discussed model of memory using substitutions\ngives that\n$\\sem{\\IF{\\cLoc}\\THEN \\aLoc\\GETS1\\SEMI \\bLoc\\GETS3 \\ELSE \\aLoc\\GETS2\\SEMI \\bLoc\\GETS3 \\FI}$\ncontains:\n\\begin{tikzdisplay}[node distance=1em]\n \\event{rz1}{\\DR{\\cLoc}{1}}{}\n \\event{wx1}{1\\neq0 \\mid \\DW{\\aLoc}{1}}{right=of rz1}\n \\event{wx2}{1=0 \\mid \\DW{\\aLoc}{2}}{right=of wx1}\n \\event{wy3}{\\DW{\\bLoc}{3}}{right=of wx2}\n \\po{rz1}{wx1}\n \\po[out=25,in=155]{rz1}{wx2}\n\\end{tikzdisplay}\nand we visualize unsatisfiable preconditions as crossed out:\n\\begin{tikzdisplay}[node distance=1em]\n \\event{rz1}{\\DR{\\cLoc}{1}}{}\n \\event{wx1}{\\DW{\\aLoc}{1}}{right=of rz1}\n \\nonevent{wx2}{\\DW{\\aLoc}{2}}{right=of wx1}\n \\event{wy3}{\\DW{\\bLoc}{3}}{right=of wx2}\n \\po{rz1}{wx1}\n \\po[out=25,in=155]{rz1}{wx2}\n\\end{tikzdisplay}\nNote that this semantics captures control dependencies\nsuch as $(\\DR\\cLoc1)\\lt(\\DW\\aLoc1)$, independencies\nsuch as $(\\DR\\cLoc1)\\not\\lt(\\DW\\bLoc3)$, and failed\nspeculations such as the crossed out $(\\DW\\aLoc2)$.\n\nIn summary, the features we need of the underlying data model are:\n\\begin{itemize}\n\\item \\emph{actions}, which may read or write memory locations, and\n\\item \\emph{preconditions}, which are closed under substitution.\n\\end{itemize}\nIn rest of this section we make data models precise %in~\\S\\ref{sec:preliminaries},\nand define pomsets. In the next section we give the semantics of a simple\nimperative language as sets of pomsets.\n% in \\S\\ref{sec:pomsets}.\n% In \\refapp{sets-of-pomsets}, we define\n% operations on sets of pomsets, which are used in~\\S\\ref{sec:semantics}\n% to give a compositional semantics for\n% a simple imperative language.\n\n\\subsection{Data models}\n\\label{sec:preliminaries}\n\nA \\emph{data model} consists of:\n\\begin{itemize}\n\\item a set of \\emph{memory locations} $\\Loc$, ranged over by\n $\\aLoc$ and $\\bLoc$,\n\\item a set of \\emph{registers} $\\Reg$, ranged over by\n $\\aReg$ and $\\bReg$,\n\\item a set of \\emph{values} $\\Val$, ranged over by\n $\\aVal$ and $\\bVal$,\n\\item a set of \\emph{expressions} $\\Exp$, ranged over by\n $\\aExp$ and $\\bExp$,\n\\item a set of \\emph{logical formulae} $\\Formulae$, ranged over by\n $\\aForm$ and $\\bForm$, and\n\\item a set of \\emph{actions} $\\Act$, ranged over by $\\aAct$ and $\\bAct$,\n\\end{itemize}\nsuch that:\n\\begin{itemize}\n\\item values include at least the constants $0$ and $1$,\n\\item expressions include at least registers and values,\n\\item expressions are closed under substitutions of the form $\\aExp[\\bExp/\\aReg]$,\n\\item formulae include at least $\\TRUE$, $\\FALSE$, and equalities of the form $(\\aExp=\\bExp)$ and $(\\aLoc=\\bExp)$,\n\\item formulae are closed under negation, conjunction, disjunction,\n\\item formulae are closed under substitutions of the form $\\aForm[\\aLoc/\\aReg]$ or $\\aForm[\\bExp/\\aLoc]$,\n\\item there is a relation $\\vDash$ between formulae, and\n\\item there are partial functions $\\rreads$ and $\\rwrites: \\Act \\fun (\\Loc \\times \\Val)$.\n\\end{itemize}\nWe shall say $\\aAct$ \\emph{reads} $\\aVal$ \\emph{from} $\\aLoc$ whenever\n$\\rreads(\\aAct) = (\\aLoc,\\aVal)$, and\n$\\aAct$ \\emph{writes} $\\aVal$ \\emph{to} $\\aLoc$ whenever\n$\\rwrites(\\aAct) = (\\aLoc,\\aVal)$.\nWe shall say $\\aForm$ \\emph{implies} $\\bForm$ whenever $\\aForm\\vDash\\bForm$,\n$\\aForm$ is a \\emph{tautology} whenever $\\TRUE\\vDash\\aForm$,\n$\\aForm$ is \\emph{unsatisfiable} whenever $\\aForm\\vDash\\FALSE$, and\n$\\aForm$ is \\emph{independent of $\\aLoc$} whenever $\\aForm \\vDash \\aForm[\\aVal/\\aLoc] \\vDash \\aForm$ for every $\\aVal$.\nIn examples, the actions are of the form $(\\DR{\\aLoc}{\\aVal})$, which reads $\\aVal$ from $\\aLoc$,\nand $(\\DW{\\aLoc}{\\aVal})$, which writes $\\aVal$ to $\\aLoc$.\n\n\\subsection{3-valued pomsets}\n\\label{sec:pomsets}\n\nRecall the definition of a pomset from~\\cite{GISCHER1988199}:\n\\begin{definition}\n A \\emph{pomset} $(\\Event, {\\le}, \\labeling)$ with alphabet $\\Alphabet$\n is a partial order $(\\Event, {\\le})$ together with\n $\\labeling: \\Event \\fun \\Alphabet$.\n\\end{definition}\nGoing forward, we fix the alphabet $\\Alphabet=(\\Formulae\\times\\Act)$.\nWe will write $(\\aForm \\mid \\aAct)$ for the pair $(\\aForm,\\aAct)$,\nelide $\\aForm$ when $\\aForm$ is a tautology, and write $\\aAct$ crossed-out ($\\NEVER\\aAct$)\nwhen $\\aForm$ is unsatisfiable.\nWe lift terminology from logical formulae and actions to events,\nfor example if $\\labeling(\\aEv)=(\\aForm\\mid\\aAct)$\nthen we say\n$\\aEv$ is unsatisfiable whenever $\\aForm$ is unsatisfiable,\n$\\aEv$ writes $\\aVal$ to $\\aLoc$ whenever $\\aAct$ writes $\\aVal$ to $\\aLoc$, and\nso forth.\nWe visualize a pomset as a graph where the nodes are drawn from\n$\\Event$, each node $\\aEv$ is labeled with $\\labeling(\\aEv)$,\nand an edge $\\bEv \\rightarrow \\aEv$ corresponds to an ordering\n$\\bEv\\le\\aEv$. For example:\n\\begin{tikzdisplay}[node distance=1em]\n \\event{rx1}{\\DR{\\aLoc}{1}}{}\n \\nonevent{wy0}{\\DW{\\bLoc}{0}}{right=of rx1}\n \\event{wy1}{\\DW{\\bLoc}{1}}{right=of wy0}\n \\po{rx1}{wy0}\n \\po[out=30,in=150]{rx1}{wy1}\n\\end{tikzdisplay}\nis a visualization of the pomset where:\n\\[\\begin{array}{c}\n E = \\{ 0,1,2 \\} \\quad\n 0 \\le 1 \\quad\n 0 \\le 2 \\quad\n \\labeling(0) = (\\TRUE, \\DR{\\aLoc}{1}) \\\\\n \\labeling(1) = (\\FALSE, \\DW{\\bLoc}{0}) \\quad\n \\labeling(2) = (\\TRUE, \\DW{\\bLoc}{1}) \\quad\n\\end{array}\\]\n\nWe are building a compositional semantics of shared memory\nconcurrency, which means we require a notion of when\na read has a matching write. This is a property we require\nof closed programs, but \\emph{not} of open programs.\nFor example a program whose semantics includes:\n\\begin{tikzdisplay}[node distance=1em]\n \\event{wx1}{\\DW{\\aLoc}{1}}{}\n \\event{rx0}{\\DR{\\aLoc}{0}}{right=2.5em of wx1}\n \\event{wy0}{\\DW{\\bLoc}{0}}{right=of rx0}\n \\nonevent{wy1}{\\DW{\\bLoc}{1}}{right=of wy0}\n \\po{rx0}{wy0}\n \\po[out=30,in=150]{rx0}{wy1}\n\\end{tikzdisplay}\nmay be put in parallel\nwith another program which writes $0$ to $\\aLoc$.\nIf the program is closed with respect to $\\aLoc$ though, such an execution cannot exist,\nso we need each read of $\\aLoc$ to have a matching write.\nThis is captured by defining when $\\aEv$ \\emph{reads $\\aLoc$ from} $\\bEv$~\\cite{alglave}.\nA preliminary definition (which, as we shall see, needs to be strengthened) is:\n\\begin{itemize}\n\\item $\\bEv \\lt \\aEv$,\n\\item $\\aEv$ implies $\\bEv$,\n\\item $\\bEv$ writes $\\aVal$ to $\\aLoc$,\n and $\\aEv$ reads $\\aVal$ from $\\aLoc$, and\n\\item there is no $\\bEv \\lt \\cEv \\lt \\aEv$ such that\n $\\cEv$ writes to $\\aLoc$.\n\\end{itemize}\n% In diagrams, for readability we often highlight the reads-from edges,\n% for example:\n%% We visualize rf-pomsets by drawing a dashed edge between nodes in $\\RF$,\n%% labeled with the memory location,\n%% for example:\n%% \\begin{tikzdisplay}[node distance=1em]\n%% \\event{wx1}{\\DW{\\aLoc}{1}}{}\n%% \\event{x1}{\\DR{\\aLoc}{1}}{right=5em of wx1}\n%% \\nonevent{y0}{\\DW{\\bLoc}{0}}{below left=of x1}\n%% \\event{y1}{\\DW{\\bLoc}{1}}{below right=of x1}\n%% \\rfx{wx1}{x}{x1}\n%% \\po{x1}{y0}\n%% \\po{x1}{y1}\n%% \\end{tikzdisplay}\n%% In most cases, the memory location is obvious from context,\n%% so we elide it:\n% \\begin{tikzdisplay}[node distance=1em]\n% \\event{wx1}{\\DW{\\aLoc}{1}}{}\n% \\event{x1}{\\DR{\\aLoc}{1}}{right=2.5em of wx1}\n% \\nonevent{y0}{\\DW{\\bLoc}{0}}{right=of x1}\n% \\event{y1}{\\DW{\\bLoc}{1}}{right=of y0}\n% \\rf{wx1}{x1}\n% \\po{x1}{y0}\n% \\po[out=30,in=150]{x1}{y1}\n% \\end{tikzdisplay}\nUnfortunately by itself, this is not enough. The problem is the final\nclause saying that there does not exist an $\\aLoc$-\\emph{blocking}\nevent $\\cEv$ between $\\bEv$ and $\\aEv$. Unfortunately, concurrency can\nturn events that were not $\\aLoc$-blockers into an $\\aLoc$-blocker,\n\\emph{even if the new thread does not mention $\\aLoc$.}\nWe give an example to show this in \\refapp{blockers}.\nThis is a problem in that it means the preliminary model violates\n\\emph{scope extrusion}~\\cite{Milner:1999:CMS:329902},\nin that we can find programs $\\aCmd$ and $\\bCmd$ such that\n$\\sem{\\VAR\\aLoc\\SEMI(\\aCmd\\PAR\\bCmd)}$ is not the same as\n$\\sem{(\\VAR\\aLoc\\SEMI\\aCmd)\\PAR\\bCmd}$, even if $\\bCmd$ does not mention~$\\aLoc$.\n\nThere are a number of ways this can be addressed; for example,\nin models such as~\\cite{Batty:2011:MCC:1926385.1926394} the reads-from relation is taken\nas a primitive. In this paper, we propose \\emph{3-valued pomsets}\nas a solution. These are pomsets in which, in addition to positive statements\n$(\\bEv \\lt \\aEv)$ (interpreted as $\\aEv$ depends on $\\bEv$),\nwe also have negative statements $(\\aEv \\gtN \\bEv)$\n(interpreted as $\\aEv$ cannot depend on $\\bEv$).\n\n\\begin{definition}\n A \\emph{3-valued pomset} $(\\Event, {\\le}, {\\gtN}, \\labeling)$ \n is a \\emph{pomset} $(\\Event, {\\le}, \\labeling)$\n together with ${\\gtN} \\subseteq (\\Event\\times\\Event)$ such that:\n \\begin{itemize}\n \\item if $\\bEv \\le \\aEv$ then $\\bEv \\gtN \\aEv$,\n \\item if $\\bEv \\le \\aEv$ and $\\aEv \\gtN \\bEv$ then $\\bEv = \\aEv$,\n \\item if $\\cEv \\ge \\aEv \\gtN \\bEv$ or $\\bEv \\gtN \\cEv \\ge \\aEv$ then $\\aEv \\gtN \\cEv$.\n \\end{itemize}\n\\end{definition}\n\n% \\begin{definition}\n% A \\emph{3-valued poset} $(\\Event,{\\le},{\\gtN})$ is a poset $(\\Event,{\\le})$\n% together with ${\\gtN} \\subseteq (\\Event\\times\\Event)$ such that:\n% \\begin{itemize}\n% \\item if $\\bEv \\le \\aEv$ then $\\bEv \\gtN \\aEv$,\n% \\item if $\\bEv \\le \\aEv$ and $\\aEv \\gtN \\bEv$ then $\\bEv = \\aEv$,\n% \\item if $\\cEv \\ge \\aEv \\gtN \\bEv$ or $\\bEv \\gtN \\cEv \\ge \\aEv$ then $\\aEv \\gtN \\cEv$.\n% \\end{itemize}\n% \\end{definition}\n\n% \\begin{definition}\n% A \\emph{3-valued pomset} $(\\Event, {\\le}, {\\gtN}, \\labeling)$\n% is a 3-valued poset $(\\Event, {\\le}, {\\gtN})$ and\n% a pomset $(\\Event, {\\le}, \\labeling)$.\n% \\end{definition}\n\nStructures similar to 3-valued pomsets have come up in many guises, for example\nrough sets~\\cite{Pawlak1982} or ultrametrics over\n$\\{0,{}^1\\!/_2,1\\}$. They correspond to axioms A1--A3 of Lamport's\n\\emph{system executions}~\\cite{DBLP:journals/dc/Lamport86}.\nThey are the notion of pomset given by interpreting\n$\\bEv\\le\\aEv$ in a 3-valued logic~\\cite{Urquhart1986}. \n\nIn diagrams, we visualize $(\\bEv \\gtN \\aEv)$ as a dashed\narrow from $\\bEv$ to $\\aEv$ (note the change of direction).\nWe refer to edges introduced by $(\\bEv \\lt \\aEv)$ as\n\\emph{strong edges} and by $(\\bEv \\gtN \\aEv)$\nas \\emph{weak edges}.\nFor readability, we often highlight the reads-from edges as well.\n% for example:\nFor example one execution of\n\\(\n (\\aLoc\\GETS0\\SEMI\\aLoc\\GETS1) \\PAR (\\aLoc\\GETS\\aLoc+1)\n\\)\nis:\n\\begin{tikzdisplay}[node distance=1em]\n \\event{wx0}{\\DW{\\aLoc}{0}}{}\n \\event{wx1}{\\DW{\\aLoc}{1}}{right=of wx0}\n \\event{rx1}{\\DR{\\aLoc}{1}}{right=2.5 em of wx1}\n \\event{wx2}{\\DW{\\aLoc}{2}}{right=of rx1}\n \\rf{wx1}{rx1}\n \\wk{wx0}{wx1}\n \\wk{rx1}{wx2}\n\\end{tikzdisplay}\nWe strengthen the definition of reads-from to require not just that\nno blocker exists, but that any candidate blocker must either\nhave $\\cEv \\gtN \\bEv$ or $\\aEv \\gtN \\cEv$. This ensures that any\nfurther concurrency cannot turn a non-blocker into a blocker.\n\\begin{definition}\\label{def:rf}\n In a 3-valued pomset, $\\aEv$ \\emph{can read $\\aLoc$ from} $\\bEv$ whenever: \n \\begin{itemize}\n \\item $\\bEv \\lt \\aEv$,\n \\item $\\aEv$ implies $\\bEv$,\n \\item $\\bEv$ writes $\\aVal$ to $\\aLoc$,\n and $\\aEv$ reads $\\aVal$ from $\\aLoc$, and\n \\item if $\\cEv$ writes to $\\aLoc$\n then either $\\cEv \\gtN \\bEv$ or $\\aEv \\gtN \\cEv$.\n \\end{itemize}\n\\end{definition}\nOne of the requirements of closed programs is that\nevery read event reads from a write event.\n\nIn the remainder of the paper, we drop the prefix ``3-valued'', referring to\n3-valued pomsets simply as \\emph{pomsets}.\n\n\\section{Semantics of programs}\n\\label{sec:semantics}\n\n\\begin{figure*}\n\\begin{eqnarray*}\n \\sem{\\SKIP} & = & \\{ \\emptyset \\} \\\\\n \\sem{\\aLoc\\GETS\\aExp\\SEMI \\aCmd} & = & \\textstyle\\bigcup_\\aVal\\; \\bigl((\\aExp=\\aVal) \\guard (\\DW\\aLoc\\aVal) \\prefix \\sem{\\aCmd}[\\aExp/\\aLoc]\\bigr) \\\\\n \\sem{\\aReg\\GETS\\aLoc\\SEMI \\aCmd} & = & \\sem{\\aCmd}[\\aLoc/\\aReg] \\cup \\textstyle\\bigcup_\\aVal\\; (\\DR\\aLoc\\aVal) \\prefix \\sem{\\aCmd}[\\aLoc/\\aReg] \\\\\n \\sem{\\IF{\\aExp} \\THEN \\aCmd \\ELSE \\bCmd \\FI} & = & \\bigl((\\aExp \\neq 0) \\guard \\sem{\\aCmd}\\bigr) \\parallel \\bigl((\\aExp=0) \\guard \\sem{\\bCmd}\\bigr) \\\\\n \\sem{\\aCmd \\PAR \\bCmd} & = & \\sem{\\aCmd} \\parallel \\sem{\\bCmd} \\\\\n \\sem{\\VAR\\aLoc\\SEMI \\aCmd} & = & \\nu \\aLoc \\DOT \\sem{\\aCmd}\n\\end{eqnarray*}\n\\caption{Semantics of a concurrent shared-memory language}\n\\label{fig:programs}\n\\end{figure*}\n\nIn Figure~\\ref{fig:programs}, we give the semantics of a simple shared-memory\nconcurrent language as sets of pomsets. \nEach pomset\n$\\aPS\\in\\sem{\\aCmd}$ represents a single execution of $\\aCmd$. We do not\nexpect $\\sem{\\aCmd}$ to be prefixed closed; thus, one may view each\n$\\aPS\\in\\sem{\\aCmd}$ as a \\emph{completed} execution. However, the sets of\npomsets given by our semantics \\emph{are} closed with respect to\naugmentation, which may create additional order and strengthening\npreconditions:\n\\begin{definition}\n $\\aPS'$ is an augmentation of $\\aPS$ if $\\Event'=\\Event$, $\\aEv\\le\\bEv$\n implies $\\aEv\\le'\\bEv$, $\\aEv\\gtN\\bEv$ implies $\\aEv\\gtN'\\bEv$, and\n % $\\labeling'(\\aEv)=\\labeling(\\aEv)$\n if $\\labeling(\\aEv) = (\\bForm \\mid \\bAct)$ then\n $\\labeling'(\\aEv) = (\\bForm' \\mid \\bAct)$ where $\\bForm'$ implies\n $\\bForm$.\n\\end{definition}\n\nWe give the semantics using combinators over sets of pomsets, defined in\n\\refapp{sets-of-pomsets}. Using $\\aPSS$ to range over sets of pomsets, these\nare:\n\\begin{itemize}\n\\item \\emph{restriction} $\\nu\\aLoc\\DOT\\aPSS$, which filters $\\aPSS$ to include\n only pomsets where every event $\\aEv$ that reads from $\\aLoc$ \\emph{can read} from some\n $\\bEv$, following Definition~\\ref{def:rf},\n and where no precondition can depend on $\\aLoc$,\n\n\\item \\emph{guarding} $\\aForm\\guard\\aPSS$, which filters $\\aPSS$,\n keeping pomsets whose events have preconditions that imply $\\aForm$,\n\\item \\emph{substitution} $\\aPSS[\\aExp/\\aLoc]$, which replaces $\\aLoc$ with\n $\\aExp$ in every precondition of $\\aPSS$,\n\\item \\emph{composition} $\\aPSS_1\\parallel\\aPSS_2$, which unions pomsets from\n $\\aPSS_1$ and $\\aPSS_2$, allowing events to be merged, and\n\\item \\emph{prefixing} $\\aAct\\prefix\\aPSS$, which adds an event with action\n $\\aAct$ to pomsets in $\\aPSS$, ordering $\\aAct$ before any $\\aEv$ whose predicate\n depends on the value read by $\\aAct$.\n\\end{itemize}\nThese operations are similar to those from models of concurrency such\nas~\\cite{Brookes:1984:TCS:828.833}, but adapted here to the setting of\nspeculative evaluation.\n\nRestriction and guarding filter the set of pomsets; we have\n$(\\nu\\aLoc\\DOT\\aPSS)\\subseteq\\aPSS$ and $(\\aForm\\guard\\aPSS)\\subseteq\\aPSS$.\nSubstitution updates the preconditions in a pomset, thus we expect the number\nof pomsets to be unchanged; in addition, the number of events in each of the\npomsets is unchanged.\n% : $|\\aPSS[\\aExp/\\aLoc]|=|\\aPSS|$\nThe most interesting operators are composition and prefixing, which create\nlarger pomsets from smaller ones.\n\n\nComposition is used in giving the semantics for conditionals and concurrency.\n$\\aPSS_1 \\parallel \\aPSS_2$ contains the union of pomsets from $\\aPSS_1$ and\n$\\aPSS_2$, allowing overlap as long as they agree on actions. For example, if\n$\\aPSS_1$ and $\\aPSS_2$ contain:\n\\begin{tikzdisplay}[node distance=1em]\n \\event{a}{\\aForm \\mid \\aAct}{}\n \\event{b}{\\bForm_1 \\mid \\bAct}{right=of a}\n \\po{a}{b}\n\\end{tikzpicture}\\qquad\\qquad\\begin{tikzpicture}[node distance=1em]\n \\event{b}{\\bForm_2 \\mid \\bAct}{}\n \\event{c}{\\cForm \\mid \\cAct}{right=of b}\n \\wk{b}{c}\n\\end{tikzdisplay}\nthen $\\aPSS_1 \\parallel \\aPSS_2$ contains:\n\\begin{tikzdisplay}[node distance=1em]\n \\event{a}{\\aForm \\mid \\aAct}{}\n \\event{b}{\\bForm_1 \\lor \\bForm_2 \\mid \\bAct}{right=of a}\n \\event{c}{\\cForm \\mid \\cAct}{right=of b}\n \\po{a}{b}\n \\wk{b}{c}\n\\end{tikzdisplay}\n\nPrefixing is used in giving the semantics of reads and writes.\n$\\aAct\\prefix\\aPSS$ adds a new event $\\cEv$ with action $\\aAct$ to each\npomset in $\\aPSS$. As in the definition of parallel composition, the\ndefinition allows the new event to overlap with events in $\\aPSS$ as long as\nthey agree on the action.\n\nIf $\\cEv$ writes to a location that is also written by $\\aEv$ in $\\aPSS$,\nthen prefixing introduces weak order between them: $\\aEv \\gtN \\cEv$. This\nensures that these writes cannot be given the reverse order in an augmentation.\n\nIf $\\cEv$ reads from a location that occurs in the predicate of $\\aEv$, then\nprefixing introduces order from $\\cEv$ to any $\\aEv$\nwhose predicate depends on $\\aLoc$. \nFor example, if $\\aAct$ and $\\bAct$ write to the same location, $\\aAct$ reads\n$\\aVal$ from $\\aLoc$, $\\bForm$ is independent of $\\aLoc$, and $\\aPSS$\ncontains:\n\\begin{tikzdisplay}[node distance=1em]\n \\event{b}{\\bForm \\mid \\bAct}{}\n \\event{c}{\\cForm \\mid \\cAct}{right=of b}\n \\po{b}{c}\n\\end{tikzdisplay}\nthen $\\aAct\\prefix\\aPSS$ contains:\n\\begin{tikzdisplay}[node distance=1em]\n \\event{a}{\\aForm \\mid \\aAct}{}\n \\event{b}{\\bForm \\mid \\bAct}{right=of a}\n \\event{c}{\\cForm[\\vec\\aVal/\\vec\\aLoc] \\mid \\cAct}{right=of b}\n \\po[out=25,in=155]{a}{c}\n \\wk{a}{b}\n \\po{b}{c}\n\\end{tikzdisplay}\n\n%% A write generates a write event that may be visible\n%% to other threads. A read may see a\n%% thread-local value, or it may generate a read event that must be justified by\n%% another thread. In the latter case, occurrences of $\\aReg$ are replaced with\n%% $\\aLoc$ (rather than $\\aVal$) to ensure that dependencies are tracked\n%% properly. The subsequent substitution of $\\aVal$ for $\\aLoc$ occurs in\n%% Definition~\\ref{def:prefix} of prefixing.\n\n\n\n% We have completed the formal definition of our model of speculative\n% evaluation, and now turn to examples.\n\nIn the remainder of this section, we give examples to explain the semantics,\nconcentrating on reads and conditionals. Security-relevant examples begin in\n\\S\\ref{sec:examples}.\n\n\\subsection{Sequential memory accesses}\n\\label{sec:sequential-memory}\n\nIn the semantics of memory, there are two very different ways memory can be\naccessed: sequentially or concurrently. These are modeled differently, since\nhardware and compilers give very different guarantees about their behavior.\nIn the semantics of $\\sem{\\aReg\\GETS\\aLoc\\SEMI \\aCmd}$, given in\nFigure~\\ref{fig:programs}, these are found on left and right sides of the\nunion operation. In this section, we discuss the sequential semantics,\n$\\sem{\\aCmd}[\\aLoc/\\aReg]$, leaving the concurrent semantics to\n\\S\\ref{sec:concurrent-memory}.\n\nConsider the program $(\\aLoc\\GETS0\\SEMI \\bLoc\\GETS\\aLoc+1)$. One execution of\nthis program is where the write to $y$ uses the sequential value of\n$x$, which is $0$:\n\\begin{tikzdisplay}[node distance=1em]\n \\event{wx0}{\\DW{x}{0}}{}\n \\event{wy1}{\\DW{y}{1}}{right=of wx0}\n\\end{tikzdisplay}\nTo see how this execution is modeled, we first\nexpand out the syntax sugar to get the program\n$(\\aLoc\\GETS0\\SEMI \\aReg\\GETS\\aLoc\\SEMI \\bLoc\\GETS\\aReg+1\\SEMI\\SKIP).$\nNow $\\sem{\\SKIP}$ is just $\\{\\emptyset\\}$, and\n$\\sem{y \\GETS r+1\\SEMI \\SKIP}$ includes:\n\\[\n (r+1=1) \\guard (\\DW y1) \\prefix \\sem{\\SKIP}[1/y]\n\\]\nwhich contains the pomset:\n\\begin{tikzdisplay}[node distance=1em]\n \\event{wy1}{r+1=1 \\mid \\DW{y}{1}}{}\n\\end{tikzdisplay}\nexpressing that this program can write $1$ to $y$,\nas long as the precondition $(r+1=1)$ is satisfied.\nNow $\\sem{r \\GETS x\\SEMI y \\GETS r+1\\SEMI \\SKIP}$\nhas two cases, the sequential case\n(which does not introduce a read action)\nand the concurrent case (which does).\nFor the moment, we are interested in the sequential case:\n\\[\n \\sem{y \\GETS r+1\\SEMI \\SKIP}[x/r]\n\\]\nwhich contains the pomset:\n\\begin{tikzdisplay}[node distance=1em]\n \\event{wy1}{x+1=1 \\mid \\DW{y}{1}}{}\n\\end{tikzdisplay}\nIn this pomset, the precondition is $(x+1=1)$, which specifies a property\nof the thread-local value of $x$.\nFinally $\\sem{x \\GETS 0\\SEMI r \\GETS x\\SEMI y \\GETS r+1\\SEMI \\SKIP}$ includes:\n\\[\n (0=0) \\guard (\\DW x0) \\prefix \\sem{r \\GETS x\\SEMI y \\GETS r+1\\SEMI \\SKIP}[0/x]\n\\]\nwhich contains the pomset:\n\\begin{tikzdisplay}[node distance=1em]\n \\event{wx0}{0=0 \\mid \\DW{x}{0}}{}\n \\event{wy1}{0=0\\land0+1=1 \\mid \\DW{y}{1}}{right=of wx0}\n\\end{tikzdisplay}\nall of whose preconditions are tautologies, so this has the expected behavior:\n\\begin{tikzdisplay}[node distance=1em]\n \\event{wx0}{\\DW{x}{0}}{}\n \\event{wy1}{\\DW{y}{1}}{right=of wx0}\n\\end{tikzdisplay}\nThere is no dependency between $(\\DW x0)$ and $(\\DW y1)$,\nsince $(0=0\\land0+1=1)$ is independent of $\\aLoc$.\n\nThis example demonstrates how preconditions\ncapture the sequential semantics of memory.\nIn an execution containing an event with label\n$(\\aForm \\mid \\aAct)$, one way the precondition $\\aForm$\ncan be discharged is by an assignment $\\aLoc\\GETS\\aExp$,\nwhich performs a substitution $[\\aExp/\\aLoc]$.\nThis is a variant of the Hoare semantics of\nassignment \\cite{Hoare:1969:ABC:363235.363259}, where if $\\aCmd$ has precondition $\\aForm$\nthen $\\aLoc\\GETS\\aExp\\SEMI\\aCmd$ has precondition\n$\\aForm[\\aExp/\\aLoc]$.\n\n\\subsection{Concurrent memory accesses}\n\\label{sec:concurrent-memory}\n\nWe now turn to the case of concurrent accesses to memory.\nConsider the program %a concurrent version of the program from \\S\\ref{sec:sequential-memory}:\n$(\\aLoc\\GETS1 \\PAR \\bLoc\\GETS\\aLoc+1)$.\nIn executions of this program, it is possible for the second thread to \nperform a concurrent read of $x$:\n\\begin{tikzdisplay}[node distance=1em]\n \\event{wx1}{\\DW{x}{1}}{}\n \\event{rx1}{\\DR{x}{1}}{right=2.5em of wx1}\n \\event{wy2}{\\DW{y}{2}}{right=of rx1}\n \\rf{wx1}{rx1}\n \\po{rx1}{wy2}\n\\end{tikzdisplay}\nTo see how this execution is modeled, we first\nexpand out the syntax sugar to get the program\n$(\\aLoc\\GETS1\\SEMI\\SKIP \\PAR \\aReg\\GETS\\aLoc\\SEMI \\bLoc\\GETS\\aReg+1\\SEMI\\SKIP).$\nAs before, $\\sem{y \\GETS r+1\\SEMI \\SKIP}$ includes:\n\\[\n (r+1=2) \\guard (\\DW y2) \\prefix \\sem{\\SKIP}[2/y]\n\\]\nwhich contains the pomset:\n\\begin{tikzdisplay}[node distance=1em]\n \\event{wy2}{r+1=2 \\mid \\DW{y}{2}}{}\n\\end{tikzdisplay}\nAs before, $\\sem{r \\GETS x\\SEMI y \\GETS r+1\\SEMI \\SKIP}$ has two cases.\nWe are now interested in the concurrent case, which includes:\n\\[\n (\\DR x1) \\prefix \\sem{y \\GETS r+1\\SEMI \\SKIP}[x/r]\n\\]\nwhich contains the pomset:\n\\begin{tikzdisplay}[node distance=1em]\n \\event{rx1}{\\DR{x}{1}}{}\n \\event{wy2}{\\DW{y}{2}}{right=of rx1}\n \\po{rx1}{wy2}\n\\end{tikzdisplay}\nNote that $(\\DR x1)$ reads $1$ from $x$, and while\n$(x+1=2)[1/x]$ is a tautology,\n$(x+1=2)$ is not,\nand so there is a dependency\n$(\\DR x1) \\lt (\\DW y2)$.\n\nNow, $\\sem{x \\GETS 1\\SEMI \\SKIP}$ includes the pomset:\n\\begin{tikzdisplay}[node distance=1em]\n \\event{wx1}{\\DW{x}{1}}{}\n\\end{tikzdisplay}\nand so $\\sem{x \\GETS 1\\SEMI \\SKIP \\PAR r \\GETS x\\SEMI y \\GETS r+1\\SEMI \\SKIP}$ includes:\n\\begin{tikzdisplay}[node distance=1em]\n \\event{wx1}{\\DW{x}{1}}{}\n \\event{rx1}{\\DR{x}{1}}{right=2.5em of wx1}\n \\event{wy2}{\\DW{y}{2}}{right=of rx1}\n \\rf{wx1}{rx1}\n \\po{rx1}{wy2}\n\\end{tikzdisplay}\nas expected, including a reads-from dependency\n$(\\DW x1) \\lt (\\DR x1)$.\n\nThis example demonstrates how read and write events\ncapture the concurrent semantics of memory.\nIn an execution containing an event with label\n$(\\DR \\aLoc\\aVal)$, if the execution is\n$\\aLoc$-closed, then there must be an event\nit reads from, for example one labeled\n$(\\DW \\aLoc\\aVal)$.\n\n\\subsection{Control dependencies}\n\\label{sec:control-dep}\n\nConditionals introduce control dependencies, for example consider the program:\n\\[\n \\aReg\\GETS\\cLoc\\SEMI\n \\IF{\\aReg}\\THEN \\aLoc\\GETS1 \\ELSE \\bLoc\\GETS2 \\FI\n\\]\nThis includes executions in which the false branch is taken:\n\\begin{tikzdisplay}[node distance=1em]\n \\event{rz0}{\\DR{z}{0}}{}\n \\nonevent{wx1}{\\DW{x}{1}}{right=of rz0}\n \\event{wy2}{\\DW{y}{2}}{right=of wx1}\n \\po{rz0}{wx1}\n \\po[out=30,in=150]{rz0}{wy2}\n\\end{tikzdisplay}\nand ones where the true branch is taken:\n\\begin{tikzdisplay}[node distance=1em]\n \\event{rz1}{\\DR{z}{1}}{}\n \\event{wx1}{\\DW{x}{1}}{right=of rz1}\n \\nonevent{wy2}{\\DW{y}{2}}{right=of wx1}\n \\po{rz1}{wx1}\n \\po[out=30,in=150]{rz1}{wy2}\n\\end{tikzdisplay}\nIn both cases, we record the actions in the branch that was\nnot taken. This is a novel feature of this model, and is\nintended to capture speculative evaluation. In \\S\\ref{sec:spectre}\nwe will show how this model captures Spectre-like information\nflow attacks, once the attacker is provided with the ability to\nobserve such speculations.\n\nTo see how these executions are modeled, consider the semantics of\n$\\sem{x\\GETS 1\\SEMI\\SKIP}$, which contains any pomset of the form:\n\\begin{tikzdisplay}[node distance=1em]\n \\event{wx1}{\\aForm \\mid \\DW{x}{1}}{}\n\\end{tikzdisplay}\nin particular it contains:\n\\begin{tikzdisplay}[node distance=1em]\n \\event{wx1}{r\\neq0 \\mid \\DW{x}{1}}{}\n\\end{tikzdisplay}\nSimilarly $\\sem{y\\GETS 2\\SEMI\\SKIP}$ contains:\n\\begin{tikzdisplay}[node distance=1em]\n \\event{wy2}{r=0 \\mid \\DW{y}{2}}{}\n\\end{tikzdisplay}\nand so $\\sem{\\IF{r}\\THEN x\\GETS 1\\SEMI\\SKIP \\ELSE y\\GETS 2\\SEMI\\SKIP \\FI}$\ncontains:\n\\begin{tikzdisplay}[node distance=1em]\n \\event{wx1}{r\\neq0 \\mid \\DW{x}{1}}{}\n \\event{wy2}{r=0 \\mid \\DW{y}{2}}{right=of wx1}\n\\end{tikzdisplay}\nNow, the semantics of concurrent read performs substitutions, for example:\n\\begin{tikzdisplay}[node distance=1em]\n \\event{rz0}{\\DR{z}{0}}{}\n \\event{wx1}{0\\neq0 \\mid \\DW{x}{1}}{right=of rz0}\n \\event{wy2}{0=0 \\mid \\DW{y}{2}}{right=of wx1}\n \\po{rz0}{wx1}\n \\po[out=25,in=155]{rz0}{wy2}\n\\end{tikzdisplay}\nwhich gives the required pomset:\n\\begin{tikzdisplay}[node distance=1em]\n \\event{rz0}{\\DR{z}{0}}{}\n \\nonevent{wx1}{\\DW{x}{1}}{right=of rz0}\n \\event{wy2}{\\DW{y}{2}}{right=of wx1}\n \\po{rz0}{wx1}\n \\po[out=30,in=150]{rz0}{wy2}\n\\end{tikzdisplay}\nNote that the precondition $r=0$ is dependent on $r$,\nand so there is a dependency $(\\DR z0) \\lt (\\DW y2)$,\nmodeling the control dependency introduced by the conditional.\n\n\\subsection{Control independencies}\n\nIn most models of control dependencies, the dependency relation\nis syntactic, based on whether the action occurs syntactically\ninside a conditional. In contrast, the notion in this model is\nsemantic: if an action can occur on both sides of a conditional,\nthere is no control dependency. Consider a variant of the example\nfrom \\S\\ref{sec:control-dep}:\n\\[\n \\aReg\\GETS\\cLoc\\SEMI\n \\IF{\\aReg}\\THEN \\aLoc\\GETS1 \\ELSE \\aLoc\\GETS1 \\FI\n\\]\nThis has the expected execution in which the control\ndependencies exist:\n\\begin{tikzdisplay}[node distance=1em]\n \\event{rz0}{\\DR{z}{0}}{}\n \\nonevent{nwx1}{\\DW{x}{1}}{right=of rz0}\n \\event{wx1}{\\DW{x}{1}}{right=of nwx1}\n \\po{rz0}{nwx1}\n \\po[out=30,in=150]{rz0}{wx1}\n\\end{tikzdisplay}\nbut it also has an execution in which the two writes\nof $1$ to $x$ are merged, resulting in no dependency:\n\\begin{tikzdisplay}[node distance=1em]\n \\event{rz0}{\\DR{z}{0}}{}\n \\event{wx1}{\\DW{x}{1}}{right=of rz0}\n\\end{tikzdisplay}\nTo see how this arises,\nconsider the definition of $\\sem{\\IF{r}\\THEN x\\GETS1\\SEMI\\SKIP \\ELSE x\\GETS1\\SEMI\\SKIP \\FI}$:\n\\[\\begin{array}{rl}\n \\aPSS_1 \\parallel \\aPSS_2 \\quad\\mbox{where}\\quad&\n \\aPSS_1 = (r\\neq 0) \\guard \\sem{x\\GETS1\\SEMI\\SKIP} \\\\&\n \\aPSS_2 = (r=0) \\guard \\sem{x\\GETS1\\SEMI\\SKIP}\n\\end{array}\\]\nNow, one pomset in $\\aPSS_1$ is:\n\\begin{tikzdisplay}[node distance=1em]\n \\event{wx1}{r\\neq0 \\mid \\DW{x}{1}}{}\n\\end{tikzdisplay}\nthat is $\\aPS_1$ where:\n\\[\n \\Event_1 = \\{\\aEv\\} \\quad\n \\labeling_1(\\aEv) = (r\\neq 0, \\DW x1)\n\\]\nand similarly, one pomset in $\\aPSS_2$ is:\n\\begin{tikzdisplay}[node distance=1em]\n \\event{wx1}{r=0 \\mid \\DW{x}{1}}{}\n\\end{tikzdisplay}\nthat is $\\aPS_2$ where:\n\\[\n \\Event_2 = \\{\\aEv\\} \\quad\n \\labeling_2(\\aEv) = (r= 0, \\DW x1)\n\\]\nCrucially, in the definition of $\\aPSS_1 \\parallel \\aPSS_2$\nthere is \\emph{no} requirement that $\\Event_1$ and $\\Event_2$ are disjoint,\nand in this case they overlap at $\\aEv$. As a result, one pomset in\n$\\aPSS_1\\parallel\\aPSS_2$ is $\\aPS_0$ where:\n\\[\n \\Event_0 = \\{\\aEv\\} \\quad\n \\labeling_0(\\aEv) = (r\\neq0 \\lor r=0, \\DW x1)\n\\]\nthat is:\n\\begin{tikzdisplay}[node distance=1em]\n \\event{wx1}{\\DW{x}{1}}{}\n\\end{tikzdisplay}\nNote that this pomset has no precondition dependent on $r$,\nsince $(r\\neq0 \\lor r=0)$ does not depend on $r$, which is why\nwe end up with an execution without a control dependency:\n\\begin{tikzdisplay}[node distance=1em]\n \\event{rz0}{\\DR{z}{0}}{}\n \\event{wx1}{\\DW{x}{1}}{right=of rz0}\n\\end{tikzdisplay}\nThis semantics captures compiler optimizations which may, for example,\nmerge code executed on both branches of a conditional, or hoist\nconstant assignments out of loops.\n\nWe can now see the counterintuitive behavior of conditionals\nin the presence of control dependencies.\nThere are programs such as\n\\(\n (\\IF{\\cLoc}\\THEN \\aLoc\\GETS1 \\ELSE \\aLoc\\GETS1 \\FI)\n\\)\nwith executions in which $(\\DW x1)$ is independent of $(\\DR z1)$:\n\\begin{tikzdisplay}[node distance=1em]\n \\event{rz1}{\\DR{z}{1}}{}\n \\event{wx1}{\\DW{x}{1}}{right=of rz1}\n\\end{tikzdisplay}\nwhile programs such as\n\\(\n (\\IF{\\cLoc}\\THEN \\aLoc\\GETS1 \\ELSE \\bLoc\\GETS2 \\FI)\n\\)\nonly have executions in which $(\\DW x1)$ is dependent on $(\\DR z1)$:\n\\begin{tikzdisplay}[node distance=1em]\n \\event{rz1}{\\DR{z}{1}}{}\n \\event{wx1}{\\DW{x}{1}}{right=of rz1}\n \\nonevent{wy2}{\\DW{y}{2}}{right=of wx1}\n \\po{rz1}{wx1}\n \\po[out=30,in=150]{rz1}{wy2}\n\\end{tikzdisplay}\nThese programs have executions with different dependency relations, depending only\non conditional branches that were \\emph{not} taken. In \\S\\ref{sec:info-flow-attack}\nwe shall see that this has security implications, since relaxed\nmemory can observe dependency.\n% The attack is similar to Spectre, so\n% we shall take a detour to see how Spectre can be modeled in this\n% setting.\n\n\\subsection{UNUSED: Relaxed memory}\n\\label{sec:relaxed-memory}\n\nIn \\S\\ref{sec:info-flow-attack} we present an information flow attack\non relaxed memory, similar to Spectre in that it relies on speculative\nevaluation. Unlike Spectre it does not depend on timing attacks,\nbut instead is based on the sensitivity of relaxed memory to data\ndependencies. % For this reason, we present a simple model of relaxed\n% memory, which is strong enough to capture this attack.\n\nOur model includes concurrent memory accesses, which can introduce concurrent\nreads-from. \nSince we are allowing events to be partially ordered, this gives a simple\nmodel of relaxed memory. For example an independent read independent write\n(IRIW) example is:\n\\[\\begin{array}{l}\n x\\GETS0\\SEMI x\\GETS x+1\n \\PAR\n y\\GETS0\\SEMI y\\GETS y+1\n\\\\{}\n \\PAR\n r_1\\GETS x\\SEMI r_2\\GETS y\n \\PAR\n s_1\\GETS y\\SEMI s_2\\GETS x\n\\end{array}\\]\nwhich includes the execution:\n\\begin{tikzdisplay}[node distance=1em]\n \\event{wx0}{\\DW{x}{0}}{}\n \\event{wx1}{\\DW{x}{1}}{right=of wx0}\n \\event{wy0}{\\DW{y}{0}}{right=2.5em of wx1}\n \\event{wy1}{\\DW{y}{1}}{right=of wy0}\n \\event{ry1}{\\DR{y}{1}}{below=4ex of wx0}\n \\event{rx0}{\\DR{x}{0}}{right=of ry1}\n \\event{rx1}{\\DR{x}{1}}{right=2.5 em of rx0}\n \\event{ry0}{\\DR{y}{0}}{right=of rx1}\n \\rf{wx1}{rx1}\n \\rf{wy0}{ry0}\n \\rf[out=210,in=30]{wy1}{ry1}\n \\rf{wx0}{rx0}\n \\wk{rx0}{wx1}\n \\wk{ry0}{wy1}\n\\end{tikzdisplay}\nThis model does not introduce thin-air reads (TAR).\nFor example the TAR pit\n\\((\n x\\GETS y \\PAR y \\GETS x\n)\\)\nfails to produce a value for $x$ from thin air\nsince this produces a cycle in $\\le$, as shown on the left below:\n\\begin{align*}\n\\begin{tikzpicture}[node distance=1em]\n \\event{ry42}{\\DR{y}{42}}{}\n \\event{wx42}{\\DW{x}{42}}{below=of ry42}\n \\event{rx42}{\\DR{x}{42}}{right=2.5em of ry42}\n \\event{wy42}{\\DW{y}{42}}{below=of rx42}\n \\po{ry42}{wx42}\n \\po{rx42}{wy42}\n \\rf{wx42}{rx42}\n \\rf{wy42}{ry42}\n\\end{tikzpicture}\n&&\n\\begin{tikzpicture}[node distance=1em]\n \\event{ry1}{\\DR{y}{1}}{}\n \\event{wx1}{\\DW{x}{1}}{below=of ry1}\n \\event{rx1}{\\DR{x}{1}}{right=2.5em of ry1}\n \\event{wy1}{\\DW{y}{1}}{below=of rx1}\n \\po{ry1}{wx1}\n \\rf{wx1}{rx1}\n \\rf{wy1}{ry1}\n\\end{tikzpicture}\n\\end{align*}\nThis cycle can be broken by removing a dependency. For example\n\\((\n x\\GETS y \\PAR r\\GETS x\\SEMI y \\GETS r+1-r\n)\\)\nhas the execution on the right above.\n% \\begin{tikzdisplay}[node distance=1em]\n% \\event{ry1}{\\DR{y}{1}}{}\n% \\event{wx1}{\\DW{x}{1}}{below=of ry1}\n% \\event{rx1}{\\DR{x}{1}}{right=2.5em of ry1}\n% \\event{wy1}{\\DW{y}{1}}{below=of rx1}\n% \\po{ry1}{wx1}\n% \\rf{wx1}{rx1}\n% \\rf{wy1}{ry1}\n% \\end{tikzdisplay}\nNote that $(\\DR x1) \\not\\le (\\DW y1)$, so this does not introduce a cycle.\n\nAlthough it is not the primary focus of this paper, our model may be an\nattractive model of relaxed memory. Many prior models either permit\nthin-air executions that our model forbids or forbid desirable executions\nthat our model permits.\n%% In \\S\\ref{sec:logic}, we develop a logic which allows us to prove that our\n%% semantics forbids thin air examples that are permitted by prior speculative\n%% models\n%% \\cite{Manson:2005:JMM:1047659.1040336,Jagadeesan:2010:GOS:2175486.2175503,DBLP:conf/popl/KangHLVD17}.\n% Our model passes all of the causality test cases\n% \\cite{PughWebsite}.\n%% Significantly, this\n%% includes test case 9, which is forbidden by \\cite{DBLP:conf/lics/JeffreyR16},\n%% one of the few models that disallows the thin air example from\n%% \\S\\ref{sec:logic}. We present this test case in the appendix, where we also\n%% discuss the thread inlining examples from\n%% \\cite{Manson:2005:JMM:1047659.1040336}.\n\n% In \\refapp{logic}, we present a variant of the TAR-pit\n% example %from \\S\\ref{sec:relaxed-memory}\n% that is allowed under prior speculative semantics\n% \\cite{Manson:2005:JMM:1047659.1040336,Jagadeesan:2010:GOS:2175486.2175503,DBLP:conf/popl/KangHLVD17}.\n% We develop a logic that allows us to prove that the problematic execution is\n% forbidden in our model. \\citet{DBLP:conf/esop/BattyMNPS15} showed that the\n% thin-air problem has no per-candidate-execution solution for C++. This\n% result does not apply to our model, which has a different notion of\n% dependency.\n\n% as the semantics of a conditional can depend on the semantics\n% of both branches.\n\n\\citet{PughWebsite} developed a set of twenty {causality test cases} in the\nprocess of revising the Java Memory Model (JMM)\n\\cite{Manson:2005:JMM:1047659.1040336}. Using hand calculation, we have\nconfirmed that our model gives the desired result for all twenty cases,\nunrolling loops as necessary. Our model also gives the desired results for\nall of the examples in \\citet[\\textsection 4]{DBLP:conf/esop/BattyMNPS15} and\nall but one in \\citet[\\textsection 5.3]{SevcikThesis}:\nredundant-write-after-read-elimination fails for any\nsensible non-coherent semantics. Our model agrees with the JMM on the\n``surprising and controversial behaviors'' of \\citet[\\textsection\n8]{Manson:2005:JMM:1047659.1040336}, and thus fails to validate thread\ninlining.\nIn \\refapp{tc}, we discuss three of the causality test cases and the thread\ninlining example from \\cite{Manson:2005:JMM:1047659.1040336}.% In presenting the\n% examples, we unroll loops, correct typos and simplify the code. \n\n\n\\section{Attacks on speculative execution}\n\\label{sec:examples}\n\nIn this section, we show how known attacks on speculative execution can be\nmodeled. In \\S\\ref{sec:spectre}, we discuss Spectre. In\n\\S\\ref{sec:spec-barriers}, we describe \\emph{speculation barriers} for\ndefense against Spectre. In \\S\\ref{sec:transactions}, we discuss attacks on\ntransactions.\n\nIn each attack, there is a high-security variable $\\SEC$,\nand the goal of the attacker is to learn one bit of information\nfrom $\\SEC$. The Spectre and \\textsc{Prime+Abort}\nattacks exploit optimizations in hardware, and so can be mounted\nagainst a dynamic $\\SEC$.\n\n\\subsection{Spectre}\n\\label{sec:spectre}\n\nWe give a simplified model of Spectre attacks, ignoring the details of\ncache timing. In this model, we extend programs with the ability to tell\nwhether a memory location has been touched (in practice this is\nimplemented using timing attacks on the cache). For example,\nwe can model Spectre by:\n\\[\\begin{array}{l}\n \\VAR a\\SEMI \\IF{\\CANREAD(\\SEC})\\THEN a[\\SEC]\\GETS1\n \\brELIF{\\TOUCHED a[0]}\\THEN x\\GETS0\n \\brELIF{\\TOUCHED a[1]}\\THEN x\\GETS1 \\FI\n\\end{array}\\]\nThis is a low-security program, which is attempting to discover the\nvalue of a high-security variable $\\SEC$. The low-security program\nis allowed to attempt to escalate its privileges by checking that it is\nallowed to read a high-security variable:\n\\[\\begin{array}{l}\n \\IF{\\CANREAD(\\SEC})\\THEN \\mbox{code allowed to read $\\SEC$}\n \\brELSE \\mbox{code not allowed to read $\\SEC$} \\FI\n\\end{array}\\]\nIn this case, $\\CANREAD(\\SEC)$ is false, so the fallback code\nis executed. Unfortunately, the escalated code is speculatively\nevaluated, which allows information to leak by testing for which\nmemory locations have been touched.\n\nAttacks may realize the abstract notions in various ways. For example, in\nvariant 1 of Spectre, the dynamic security check is implemented as an array\nbounds check.\n\nWe model the $\\TOUCHED$ test by introducing a new action\n$(\\DT{\\aLoc})$, and defining:\n\\[\\begin{array}{l}\n \\sem{\\IF{\\TOUCHED\\aLoc} \\THEN \\aCmd \\ELSE \\bCmd \\FI} \\\\[\\jot]\\quad = ((\\DT\\aLoc) \\prefix \\sem{\\aCmd}) \\cup \\sem{\\bCmd}\n\\end{array}\\]\nImplementations of $\\TOUCHED$ use cache timing, but their success can be modeled\nwithout needing to be precise about such microarchitectural details:\n\\begin{itemize}\n\\item if $\\labeling(\\aEv)=(\\aForm \\mid \\DT{\\aLoc})$\n then there is $\\bEv\\gtN\\aEv$\n where $\\bEv$ reads or writes $\\aLoc$.\n\\end{itemize}\nNote that there is no requirement that $\\bEv$ be satisfiable,\nand indeed Spectre has the execution:\n\\begin{tikzdisplay}[node distance=1em]\n \\nonevent{rs}{\\DR{\\SEC}{1}}{}\n \\nonevent{wa}{\\DW{a[1]}{1}}{right=of rs}\n \\event{ta}{\\DT{a[1]}}{right=of wa}\n \\event{wx}{\\DW{x}{1}}{right=of ta}\n \\po{rs}{wa}\n \\wk{wa}{ta}\n \\po{ta}{wx}\n\\end{tikzdisplay}\nbut (assuming a successful implementation of $\\TOUCHED$) \\emph{not}:\n\\begin{tikzdisplay}[node distance=1em]\n \\nonevent{rs}{\\DR{\\SEC}{0}}{}\n \\nonevent{wa}{\\DW{a[0]}{1}}{right=of rs}\n \\event{ta}{\\DT{a[1]}}{right=of wa}\n \\event{wx}{\\DW{x}{1}}{right=of ta}\n \\po{rs}{wa}\n \\wk{wa}{ta}\n \\po{ta}{wx}\n\\end{tikzdisplay}\nThus, the attacker has managed to leak the value of a high-security\nlocation to a low-security one: if $(\\DW x1)$ is observed, the \\verb|SECRET|\nmust have been 1.\n\nThis shows how our model of speculation can express\nthe way in which Spectre-like attacks bypass dynamic security checks,\nwithout giving a treatment of microarchitecture.\n\n\\subsection{Speculation barriers}\n\\label{sec:spec-barriers}\n\nThe ability to model Spectre is useful, but really we would\nlike to model defenses against such attacks, and provide some\nconfidence in the correctness of the defense. One such defense\nwhich fits naturally in our model is \\emph{speculation barriers},\nwhich prevent code from being speculatively executed. For example,\nwe could introduce such a $\\BARRIER$, and require that\na barrier is introduced on each security check:\n\\[\\begin{array}{l}\n\\IF{\\CANREAD(\\SEC})\\THEN \\BARRIER\\SEMI\\cdots\n \\ELSE \\cdots \\FI\n\\end{array}\\]\nTo model barriers, we introduce a new action $\\DSB$\nand define:\n\\[\\begin{array}{l}\n \\sem{\\BARRIER\\SEMI\\aCmd} = \\{\\emptyset\\} \\cup ((\\DSB) \\prefix \\sem{\\aCmd})\n\\end{array}\\]\nImplementations of $\\BARRIER$ make use of hardware barriers which\nhalt speculative execution until all instructions up to the barrier\nhave been retired. Such barriers are successful when:\n\\begin{itemize}\n\\item if $\\labeling(\\aEv)=(\\aForm \\mid \\DSB)$\n then $\\aForm$ is satisfiable.\n\\end{itemize}\nFor example, a successful implementation of barriers disallows\nthe execution of Spectre:\n\\begin{tikzdisplay}[node distance=1em]\n \\nonevent{sb}{\\DSB}{}\n \\nonevent{rs}{\\DR{\\SEC}{1}}{right=of sb}\n \\nonevent{wa}{\\DW{a[1]}{1}}{right=of rs}\n \\event{ta}{\\DT{a[1]}}{right=of wa}\n \\event{wx}{\\DW{x}{1}}{right=of ta}\n \\po{rs}{wa}\n \\wk{wa}{ta}\n \\po{ta}{wx}\n\\end{tikzdisplay}\nOne might expect that this is a successful (albeit expensive) defense\nagainst Spectre, but it is not, unless the compiler is aware that\n$\\BARRIER$ cannot be lifted out of a conditional. An unaware compiler\nmight perform common subexpression elimination on barriers, allowing\nthe attacker to introduce a barrier to fool a compiler into optimizing\nthe safe:\n\\[\\begin{array}{l}\n \\IF{\\CANREAD(\\SEC})\\THEN \\BARRIER\\SEMI \\cdots\n \\ELSE \\BARRIER\\SEMI \\cdots \\FI\n\\end{array}\\]\ninto the unsafe:\n\\[\\begin{array}{l}\n \\BARRIER\\SEMI \\IF{\\CANREAD(\\SEC})\\THEN \\cdots\n \\ELSE \\cdots \\FI\n\\end{array}\\]\nTo model the requirement that barriers are not moved past\nconditionals, we make them \\emph{unmergeable}: $\\DSB$ events\non different arms of a conditional cannot be merged.\nWith this requirement, we can show that barriers act as a\ndefense against Spectre by first showing that $\\sem\\bCmd$ has\nthe same successful executions as:\n\\[\n \\sem{\\IF{\\CANREAD(\\SEC}) \\THEN \\BARRIER\\SEMI\\aCmd \\ELSE \\bCmd \\FI}\n\\]\nand then showing that the semantics which only looks at successful\nexecutions is \\emph{compositional}: if $\\sem\\bCmd$ has the same\nsuccessful executions as $\\sem{\\bCmd'}$ then $\\sem{\\aCmd[\\bCmd]}$ has\nthe same successful executions as $\\sem{\\aCmd[\\bCmd']}$ for any\n``program with a hole'' $\\aCmd[{\\bullet}]$. Compositional reasoning\nis what fails when $\\DSB$ is mergeable, as shown by the\nattack against a compiler which blindly performs common subexpression\nelimination.\n\nTo realize a speculation barrier in microarchitecture, it is likely\nsufficient for the barrier to stop any further speculation until the barrier\nis known to succeed. There is experimental evidence that Intel's\n\\texttt{mfence} instruction has the effect of a speculation barrier in some contexts\n\\cite[\\S{VII-\\textit{D}}]{DBLP:conf/micro/TrippelLM18}.\n\n\\subsection{Transactions}\n\\label{sec:transactions}\n\nWe present a model of transactional memory~\\cite{Larus:2007:TM:1207012} that is sufficient to capture\n\\textsc{Prime+Abort} attacks~\\cite{DBLP:conf/uss/DisselkoenKPT17}. We make\nseveral simplifying assumptions: transactions are serializable, strongly\nisolated, and only abort due to cache conflicts.\n\nThe action $(\\DB{\\aVal})$ %\\in\\Acq$\nrepresents the begin of a transaction with\nid $\\aVal$, and $(\\DC{\\aVal})$ %\\in \\Rel$\nrepresents the corresponding commit.\nWe model a language in which transactions have explicit identifiers (which we\nelide in examples) and abort handlers (which we elide when they are empty):\n\\[\\begin{array}{l}\n \\sem{\\BEGINVAL\\SEMI \\eCmd\\SEMI \\RECOVERYVAL \\bCmd \\ENDREC} \\\\\\quad\n = (\\DB{\\aVal}) \\prefix \\bigl(\\sem{\\eCmd} \\cup \\bigl((\\FALSE \\guard \\sem{\\eCmd}) \\parallel \\sem{\\bCmd}\\bigr)\\bigr)\n \\\\[\\jot]\n \\sem{\\COMMITVAL\\SEMI \\bCmd} \\\\\\quad\n = (\\DC{\\aVal}) \\prefix \\sem{\\bCmd}\n \\end{array}\\]\nThe semantics of a transaction has two cases: a committed case\n(executing only the transaction body) and an aborted case (executing both the body and the\nrecovery code, where the body is marked unsatisfiable). For example, two executions of\n\\begin{math}\n (\\BEGIN\\SEMI \\aLoc\\GETS1\\SEMI \\aLoc\\GETS2\\SEMI \\COMMIT\\SEMI \\RECOVERY \\bLoc\\GETS1\\ENDREC)\n\\end{math}\nare:\n\\[\\begin{array}{c}\\begin{tikzpicture}[node distance=1em]\n \\event{b0}{\\DB{}}{}\n \\event{wx0}{\\DW{x}{1}}{right=of b0}\n \\event{wx1}{\\DW{x}{2}}{right=of wx0}\n \\event{c0}{\\DC{}}{right=of wx1}\n \\po{b0}{wx0}\n \\po[out=30,in=150]{b0}{wx1}\n \\po[out=30,in=150]{wx0}{c0}\n \\po{wx1}{c0}\n \\wk{wx0}{wx1}\n\\end{tikzpicture}\n\\\\\n\\begin{tikzpicture}[node distance=1em]\n \\event{b0}{\\DB{}}{}\n \\nonevent{wx0}{\\DW{x}{1}}{right=of b0}\n \\nonevent{wx1}{\\DW{x}{2}}{right=of wx0}\n \\nonevent{c0}{\\DC{}}{right=of wx1}\n \\event{wy1}{\\DW{y}{1}}{right=of c0}\n \\po{b0}{wx0}\n \\po[out=30,in=150]{b0}{wx1}\n \\po[out=30,in=160]{b0}{wy1}\n \\po[out=30,in=150]{wx0}{c0}\n \\po{wx1}{c0}\n \\wk{wx0}{wx1}\n\\end{tikzpicture}\\end{array}\\]\nAt top level, we require that pomsets be \\emph{serializable}, as defined below.\n\\begin{definition}\n We say that event $\\comEv$ \\emph{matches} $\\begEv$ if\n $\\labeling(\\comEv)=(\\DC{\\aVal})$ and\n $\\labeling(\\begEv)=(\\DB{\\aVal})$. %, for some $\\aVal$.\n % We say that a begin event \\emph{aborts} if every matching commit is\n % unsatisfiable.\n We say that begin event $\\begEv$ \\emph{begins} $\\aEv$ if\n $\\begEv\\le\\aEv$ and there is no intervening matching commit; in this case\n $\\aEv$ \\emph{belongs to} $\\begEv$.\n % event $\\comEv$ such that $\\begEv\\le\\comEv\\le\\aEv$\n We say that commit event $\\comEv$ \\emph{commits} $\\aEv$ if $\\aEv\\le\\comEv$\n and there is no intervening matching begin.\n % event $\\begEv$ such that $\\aEv\\le\\begEv\\le\\comEv$.\n\\end{definition}\n\\begin{definition}\n A pomset is \\emph{serializable} if:\n \\begin{enumerate}\n \\item\\label{tx:1} no two begins have the same id,\n \\item\\label{tx:2} every commit follows the matching begin,\n \\item\\label{tx:3} $\\le$ totally orders tautological begins and commits,\n \\item\\label{tx:4} if $\\begEv$ begins $\\aEv$, but not $\\bEv$, and $\\bEv\\le\\aEv$ then $\\bEv\\le\\begEv$,\n \\item\\label{tx:5} if $\\comEv$ ends $\\aEv$, but not $\\bEv$, and $\\aEv\\le\\bEv$ then $\\comEv\\le\\bEv$,\n % \\item\\label{tx:4} if $\\begEv$ begins $\\aEv$, but not $\\bEv$, then\n % $\\bEv\\le\\aEv$ implies $\\bEv\\le\\begEv$ and $\\bEv\\gtN\\aEv$ implies $\\bEv\\gtN\\begEv$\n % \\item\\label{tx:5} if $\\comEv$ ends $\\aEv$, but not $\\bEv$, then\n % $\\aEv\\le\\bEv$ implies $\\comEv\\le\\bEv$ and $\\aEv\\gtN\\bEv$ implies $\\comEv\\gtN\\bEv$,\n \\item\\label{tx:6} if $\\aEv$ and $\\bEv$ belong to $\\begEv$ and read the same\n location, then both read the same value, and\n % note that read events are optional, so we can assume they come from\n % outside the transaction.\n %\n % \\item\\label{tx:6} if $\\begEv$ begins $\\aEv$ then some matching $\\comEv$ both implies and ends $\\aEv$,\n % \\item\\label{tx:6} if $\\begEv$ begins $\\aEv$ then some matching $\\comEv$\n % ends $\\aEv$ such that both $\\aEv$ implies $\\comEv$ and $\\comEv$ implies $\\aEv$,\n \\item\\label{tx:7} if $\\aEv$ belongs to $\\begEv$, then $\\aEv$ implies some\n matching $\\comEv$ that ends $\\aEv$.\n \\end{enumerate}\n\\end{definition}\n%In discussion, we identify transactions by their unique begin event.\n%A transaction that does not abort is \\emph{successful}.\n%\nConditions \\ref{tx:1}-\\ref{tx:5} ensure serializability of committed\ntransactions. Conditions \\ref{tx:4}-\\ref{tx:6} also ensure strong isolation\nfor non-transactional events\n\\cite{DBLP:journals/pacmpl/DongolJR18}. Condition \\ref{tx:7} ensures that all\nevents in aborted transactions are unsatisfiable.\n%\nFor example Conditions \\ref{tx:5} and \\ref{tx:7} rule out\nexecutions (which violate strong isolation and atomicity):\n\\[\\begin{array}{c}\\begin{tikzpicture}[node distance=1em]\n \\event{b0}{\\DB{}}{}\n \\event{wx0}{\\DW{x}{0}}{right=of b0}\n \\event{wx1}{\\DW{x}{1}}{right=of wx0}\n \\event{c0}{\\DC{}}{right=of wx1}\n \\event{rx0}{\\DR{x}{0}}{right=of c0}\n \\po{b0}{wx0}\n \\po[out=30,in=150]{b0}{wx1}\n \\po[out=30,in=150]{wx0}{c0}\n \\po{wx1}{c0}\n \\wk{wx0}{wx1}\n \\rf[out=30,in=150]{wx0}{rx0}\n\\end{tikzpicture}\n\\\\\n\\begin{tikzpicture}[node distance=1em]\n \\event{b0}{\\DB{}}{}\n \\event{wx0}{\\DW{x}{0}}{right=of b0}\n \\nonevent{wx1}{\\DW{x}{1}}{right=of wx0}\n \\nonevent{c0}{\\DC{}}{right=of wx1}\n \\event{wy1}{\\DW{y}{1}}{right=of c0}\n \\po{b0}{wx0}\n \\po[out=30,in=150]{b0}{wx1}\n \\po[out=30,in=160]{b0}{wy1}\n \\po[out=30,in=150]{wx0}{c0}\n \\po{wx1}{c0}\n \\wk{wx0}{wx1}\n\\end{tikzpicture}\\end{array}\\]\n\nIn order to model \\textsc{Prime+Abort}, we need a mechanism for modeling\n\\emph{why} a transaction aborts, as this can be used as a back channel.\nWe model a simple form of concurrent transaction, which aborts when it\nencounters a memory conflict---this is similar to\nthe treatment of $\\TOUCHED$ in \\S\\ref{sec:spectre}.\n\n\\begin{definition}\n \\label{def:abort}\n A commit event $\\comEv$ matching $\\begEv$ \\emph{aborts due to memory conflict}\n if there is some $\\aEv$ ended by $\\comEv$, and some tautologous $\\begEv\\gtN\\bEv\\gtN\\comEv$ that does not\n belong to $\\begEv$ such that $\\aEv$ and $\\bEv$ touch the same location.\n\\end{definition}\n\nThe attack requires an honest agent whose %cache-set\naccess pattern depends upon a secret.\n% If $a[0]$ and $a[1]$ belong to separate cache sets, then\nSuch an honest agent is:\n\\[\n a[\\SEC]\\,\\GETS\\,1\n\\]\n% \\ignore{\n% \\begin{verbatim}\n% a[SECRET] := 1\n% \\end{verbatim}\n% }\n%The attack relies on discovery of some $y$ which belongs to the cache-set of $a[1]$.\nThen the attacker program\n\\[\n\\BEGIN\\SEMI a[1]\\GETS0\\SEMI r\\GETS\\COMMIT\\SEMI \\RECOVERY x\\GETS1\\ENDREC\n\\]\n% \\ignore{\n% \\begin{verbatim}\n% begin; y:=0; commit; onabort; x:=1;\n% \\end{verbatim}\n% }\ncan write $1$ to $x$ if the \\texttt{SECRET} is $1$, in which case the\nfollowing execution is possible.\n\\begin{tikzdisplay}[node distance=1em,baselinecenter]\n \\event{wa1}{\\DW{a[1]}{1}}{}\n \\event{b}{\\DB{}}{right=2.5em of wa1}\n \\nonevent{e}{\\DW{a[1]}{0}}{right=of b}\n \\nonevent{c}{\\DC{}}{right=of e}\n \\event{wx1}{\\DW{x}{1}}{right=of c}\n \\po{b}{e}\n \\po{e}{c}\n \\po[out=30,in=155]{b}{wx1}\n \\wk{b}{wa1}\n \\wk[out=25,in=155]{wa1}{c}\n\\end{tikzdisplay}\nIf the attacker knows that commits only abort due to memory conflicts,\nthen this attack is an information flow, since the memory conflict only happens\nwhen the \\texttt{SECRET} is $1$.\n\nThe attacker code here must have write access to the high security variable\n$a$. Such a ``write up'' is allowed by secrecy analyses such as the\nSmith-Volpano type system \\cite{Smith:1998:SIF:268946.268975}, which\nis meant to guarantee noninterference.\n\nIf we require that the attacker and honest agent access disjoint locations in\nmemory, then we must include a bit of microarchitecture to model the attack.\nSuppose that the set of locations $\\Loc$ is partitioned into \\emph{cache\n sets} and update Definition~\\ref{def:abort} so that the commit event\n{aborts due to memory conflict} if $\\aEv$ and $\\bEv$ touch locations \\emph{in\n the same cache set}.\n\n\\textsc{Prime+Abort} exploits an honest agent whose cache-set\naccess pattern depends upon a secret.\nIf $a[0]$ and $a[1]$ belong to separate cache sets, then\nsuch an honest agent is, as before:\n\\[\n a[\\SEC]\\,\\GETS\\,1\n\\]\nThe attack relies on discovery of some $y$ which belongs to the cache-set of\n$a[1]$.\nThen the attack can be written as:\n\\[\n \\BEGIN\\SEMI y\\GETS0\\SEMI r\\GETS\\COMMIT\\SEMI \\RECOVERY x\\GETS1\\ENDREC\n\\]\nAs before, if the attacker knows that commits only abort due to memory\nconflicts, then there is an information flow, since the memory conflict\nonly happens when the \\texttt{SECRET} is $1$.\n\nThis style of attack can be thwarted by requiring that the honest agent and\nattack code access disjoint cache sets. This approach is pursued in \\cite{dawg}.\n\nAnother defense is to require a speculation barrier at the beginning of each\ntransaction. This would have the effect, however, of undermining any\noptimistic execution strategy for transactions: the transaction would only be\nable to begin when it is known that its commit will succeed.\n\n% \\ignore{\n% \\begin{verbatim}\n% begin; y:=0; commit; onabort; x:=1;\n% \\end{verbatim}\n% }\n\n% The definition handles simple examples:\n% \\begin{itemize}\n% \\item Single threaded example: $\\DB_1 \\DC_1 \\DB_2 \\DC_2$. Because\n% $\\DC_2$ is a release, we know that $\\DC_1\\lt\\DC_2$. Because\n% $\\DB_1$ is an acquire, we know that $\\DB_1\\lt\\DB_2$ By lifting, either of\n% these is sufficient to require that $\\DC_1\\lt\\DB_2$.\n% \\begin{tikzdisplay}[node distance=1em,baselinecenter]\n% \\event{b1}{\\DB_1}{}\n% \\event{c1}{\\DC_1}{right=of b1}\n% \\event{b2}{\\DB_2}{below right=of b1}\n% \\event{c2}{\\DC_2}{right=of b2}\n% \\po{b1}{c1}\n% \\po{b1}{b2}\n% \\po{b2}{c2}\n% \\po{c1}{c2}\n% \\end{tikzpicture}\n% \\;\\text{implies}\\;\n% \\begin{tikzpicture}[node distance=1em,baselinecenter]\n% \\event{b1}{\\DB_1}{}\n% \\event{c1}{\\DC_1}{right=of b1}\n% \\event{b2}{\\DB_2}{below right=of b1}\n% \\event{c2}{\\DC_2}{right=of b2}\n% \\po{b1}{c1}\n% \\po{c1}{b2}\n% \\po{b2}{c2}\n% \\end{tikzdisplay}\n% \\item Abort example:\n% \\begin{tikzdisplay}[node distance=1em,baselinecenter]\n% \\event{b1}{\\DB}{}\n% \\event{wx1}{\\DW{x}{1}}{right=of b1}\n% \\event{c1}{\\DC_1}{above right=of wx1}\n% \\nonevent{c2}{\\DC_2}{below right=of wx1}\n% \\event{rx1}{\\DR{x}{1}}{right=2.5 em of wx1}\n% \\po{b1}{wx1}\n% \\po{wx1}{c1}\n% \\po{wx1}{c2}\n% \\rf{wx1}{rx1}\n% \\end{tikzpicture}\n% \\;\\text{implies}\\;\n% \\begin{tikzpicture}[node distance=1em,baselinecenter]\n% \\event{b1}{\\DB}{}\n% \\event{wx1}{\\DW{x}{1}}{right=of b1}\n% \\event{c1}{\\DC_1}{above right=of wx1}\n% \\nonevent{c2}{\\DC_2}{below right=of wx1}\n% \\event{rx1}{\\DR{x}{1}}{right=2.5 em of wx1}\n% \\po{b1}{wx1}\n% \\po{wx1}{c1}\n% \\po{wx1}{c2}\n% \\rf{wx1}{rx1}\n% \\po{c1}{rx1}\n% \\end{tikzdisplay}\n\n% % \\item Clause \\eqref{xrf} stops transaction from reading two different values\n% % for the same variable from transactions (it is possible with no\n% % transactional writes).\n% % \\item Clause \\eqref{xrf} also stops transactional IRIW.\n% \\end{itemize}\n% % \\begin{definition}\n% % An rf-pomset is transaction-closed if the $\\DB$ and $\\DC$ actions with\n% % satisfiable preconditions are totally ordered by $\\lt$.\n% % \\end{definition}\n\n% Let ``$\\END\\SEMI \\bCmd$'' be syntax sugar for\n% ``$\\IF{\\COMMIT\\vec\\aLoc}\\THEN\\bCmd \\ELSE \\bCmd$'', where $\\vec\\aLoc$ are the\n% free variables of $\\bCmd$.\n\n% The semantics of\n% \\begin{alltt}\n% x:=1; begin; x:=2; end; y:=x;\n% \\end{alltt}\n% includes\n% \\begin{tikzdisplay}[node distance=1em]\n% \\event{wx1}{\\DW{x}{1}}{}\n% \\event{b}{\\DB}{right=of wx1}\n% \\event{wx2}{\\DW{x}{2}}{right=of b}\n% \\event{c}{\\DC}{right=of wx2}\n% \\event{wy2}{\\DW{y}{2}}{right=of c}\n% \\nonevent{wy1}{\\DW{y}{1}}{below=of wy2}\n% \\po{b}{wx2}\n% \\po[bend right]{b}{wy1}\n% \\po[bend left]{b}{wy2}\n% \\po{wx2}{c}\n% \\po[bend left]{wx1}{c}\n% %\\po{rz0}{wy2}\n% \\end{tikzdisplay}\n% and\n% \\begin{tikzdisplay}[node distance=1em]\n% \\event{wx1}{\\DW{x}{1}}{}\n% \\event{b}{\\DB}{right=of wx1}\n% \\nonevent{wx2}{\\DW{x}{2}}{right=of b}\n% \\nonevent{c}{\\DC}{right=of wx2}\n% \\nonevent{wy2}{\\DW{y}{2}}{right=of c}\n% \\event{wy1}{\\DW{y}{1}}{below=of wy2}\n% \\po{b}{wx2}\n% \\po[bend right]{b}{wy1}\n% \\po[bend left]{b}{wy2}\n% \\po{wx2}{c}\n% \\po[bend left]{wx1}{c}\n% %\\po{rz0}{wy2}\n% \\end{tikzdisplay}\n\n% Publication example:\n% \\begin{alltt}\n% var x; var f; x:=0; f:=0;\n% x:=1; (begin; f:=1; end;) || (begin; r:=f; end; s:=x;)\n% \\end{alltt}\n\n% Note: we could also include a transaction factory, and close the factory.\n% \\begin{alltt}\n% TransactionFactory T; var x; var f; x:=0; f:=0; fence;\n% x:=1; (begin T; f:=1; f:=2; end T;) || (begin T; r:=f; end T; s:=x;)\n% \\end{alltt}\n\n% Before defining atomicity, we provide some auxiliary notation.\n%\n% We say that $\\aEv$ is a \\emph{begin event} if\n% $\\labeling(\\aEv)=(\\aForm\\mid\\DB)$ and a \\emph{commit event} if\n% $\\labeling(\\aEv)=(\\aForm\\mid\\DC)$.\n%\n% We write $\\aForm_\\aEv$ for the formula and $\\aAct_\\aEv$ for the\n% action of $\\aEv$; that is, when $\\labeling(\\aEv)=(\\aForm_\\aEv\\mid\\aAct_\\aEv)$.\n%\n% We say that $\\aEv$ is \\emph{compatible with} $\\bEv$ when\n% $\\aForm_\\aEv\\land\\aForm_\\bEv$ is satisfiable.\n%\n% \\begin{definition}\n% A pomset is \\emph{atomic} when for any $\\aEv$ that belongs to $(\\begEv,\\vec\\comEv)$:\n% \\begin{enumerate}\n% \\item\\label{xcommitform} $\\aForm_{\\aEv}$ implies $\\textstyle\\bigvee_i\\aForm_{\\comEv_i}$,\n% \\item\\label{xliftb} if $\\bEv\\lt\\aEv$ then $\\bEv\\lt\\begEv$,\n% \\item\\label{xliftc} if $\\aEv\\lt\\bEv$ and $\\bEv$ is compatible with\n% $\\comEv_i$ then $\\comEv_i\\lt\\bEv$,\n% \\item\\label{xtotal} if $\\aEv'\\neq\\aEv$ belongs to $(\\begEv',\\vec\\comEv')$ but not\n% $(\\begEv,\\dontcare)$ and\n% \\begin{itemize}\n% \\item $\\comEv'_j$ is compatible with $\\aEv$, and\n% \\item $\\comEv_i$ is compatible with $\\aEv'$\n% \\end{itemize}\n% then either\n% $\\comEv'_j\\lt\\begEv$ or\n% $\\comEv_i\\lt\\begEv'$,\n% % \\item\\label{xrf} if $\\aEv'\\neq\\aEv$ belongs to $(\\begEv,\\dontcare)$ but not\n% % $(\\begEv,\\dontcare)$ and\n% % \\begin{itemize}\n% % \\item $\\aEv$ reads from $\\bEv'$ that belongs to $(\\begEv',\\vec\\comEv')$,\n% % \\item $\\aEv'$ reads from $\\bEv''\\neq\\beV'$ that belongs to $(\\begEv'',\\vec\\comEv'')$,\n% % \\item $\\comEv''_j$ is compatible with $\\bEv'$, and\n% % \\item $\\comEv'_i$ is compatible with $\\bEv''$\n% % \\end{itemize}\n% % then either\n% % $\\comEv''_j\\lt\\begEv'$ or\n% % $\\comEv'_i\\lt\\begEv''$ .\n% \\item\\label{xcommitvars} if $\\aEv$ writes $\\aLoc$ and $\\comEv_i$ writes\n% $\\vec\\aLoc$ then $\\aLoc=\\aLoc_i$, for some $i$, and\n% \\item\\label{xreadunique} if $\\aEv$ reads $\\aLoc$ and $\\aEv'\\neq\\aEv$ reads\n% $\\aLoc$, belongs to $(\\begEv,\\dontcare)$ and is compatible with $\\aEv$\n% then $\\aAct_{\\aEv}=\\aAct_{\\aEv'}$.\n% \\end{enumerate}\n% \\end{definition}\n% Clause \\eqref{xcommitform} requires that the precondition on $\\aEv$ is false on an\n% aborted transaction.\n% The \\emph{lifting clauses}, \\eqref{xliftb} and \\eqref{xliftc}, require order\n% come in or out of $\\aEv$ is lifted to the corresponding begin or commit event.\n% % Clause \\eqref{xrf} requires that whenever a transaction reads from two other\n% % transactions, the other transactions must be ordered.\n% Clause \\eqref{xtotal} requires that transactions be totally ordered.\n% Clause \\eqref{xcommitvars} requires that all writes be committed.\n% Clause \\eqref{xreadunique} requires that multiple reads of a location in a\n% single transaction must see the same value.\n%\n% The definition of atomicity guarantees strong isolation. For weak isolation,\n% clauses \\eqref{xcommitvars} and \\eqref{xreadunique} are unnecessary,\n% \\eqref{xliftb} only applies when $\\bEv$ is a commit, and \\eqref{xliftc} only\n% applies when $\\bEv$ is a begin.\n\n\n\\section{Attacks on compiler optimizations}\n\\label{sec:compiler}\n\nIn this section, we model two attacks on compiler optimizations. The first\nattack exploits reordering allowed by relaxed memory models\n(\\S\\ref{sec:info-flow-attack}). The second exploits dead store elimination\n(\\S\\ref{sec:dse}).\n\nAs in the previous section, the goal of the attacker is to learn one bit of\ninformation from the high-security $\\SEC$. The attacks on compiler\noptimizations require the $\\SEC$ to be known to the compiler, for example a\nstatic $\\SEC$ or a JIT compiler.\n\nTo defend against these attacks it is sufficient to require a traditional\nmemory fence after each security check: compilers do not reorder instructions\nover fences.\n\n\\subsection{Relaxed memory orders}\n\\label{sec:info-flow-attack}\n\nConsider an attacker program, again using dynamic security checks to\ntry to learn a \\verb|SECRET|. Whereas \\verb|Spectre| uses\nhardware capabilities, which have to be modeled by adding\nextra capabilities to the language, this new attacker works\nby exploiting relaxed memory which can result in\nunexpected information flows. The attacker program is:\n\\[\\begin{array}[t]{@{}l}\n \\VAR x\\GETS0\\SEMI \\VAR y\\GETS0\\SEMI\\\\\\quad\n y\\GETS x\n \\PAR\\begin{array}[t]{@{}l}\n \\IF{y\\EQ0}\\THEN x\\GETS1\n \\brELIF{\\CANREAD(\\SEC)}\\THEN x\\GETS\\SEC\n \\brELSE x\\GETS1\\SEMI z\\GETS1 \\FI\n\\end{array}\\end{array}\\]\nIn the case where $\\SEC$ is $2$, this has many executions,\none of which is:\n\\begin{tikzdisplay}[node distance=1em]\n \\event{ix}{\\DW{x}{0}}{}\n \\event{iy}{\\DW{y}{0}}{right=of ix}\n \\event{rx0}{\\DR{x}{0}}{below=of wx0}\n \\event{wy0}{\\DW{y}{0}}{right=of rx0}\n \\event{ry0}{\\DR{y}{0}}{below=of wy0}\n \\event{wx1}{\\DW{x}{1}}{right=of ry0}\n \\nonevent{wx2}{\\DW{x}{2}}{right=of wx1}\n \\nonevent{wz1}{\\DW{z}{1}}{right=of wx2}\n \\po{rx0}{wy0}\n \\po{ry0}{wx1}\n \\po[out=30,in=150]{ry0}{wz1}\n \\po[out=25,in=155]{ry0}{wx2}\n \\rf{ix}{rx0}\n \\rf{wy0}{ry0}\n \\wk{iy}{wy0}\n\\end{tikzdisplay}\nbut there are no executions which exhibit\n$(\\DW{z}{1})$, since any attempt to do so\nproduces a cycle, since the value written\nto $x$ has a control dependency on the value\nread from $y$:\n\\begin{tikzdisplay}[node distance=1em]\n \\event{ix}{\\DW{x}{0}}{}\n \\event{iy}{\\DW{y}{0}}{right=of ix}\n \\event{rx1}{\\DR{x}{1}}{below=of ix}\n \\event{wy1}{\\DW{y}{1}}{right=of rx1}\n \\event{ry1}{\\DR{y}{1}}{below=of wy1}\n \\event{wx1}{\\DW{x}{1}}{right=of ry0}\n \\nonevent{wx2}{\\DW{x}{2}}{right=of wx1}\n \\event{wz1}{\\DW{z}{1}}{right=of wx2}\n \\po{rx1}{wy1}\n \\po{ry1}{wx1}\n \\po[out=30,in=150]{ry1}{wz1}\n \\po[out=25,in=155]{ry1}{wx2}\n \\rf[in=-90,out=-150]{wx1}{rx1}\n \\rf{wy1}{ry1}\n \\wk[out=-20,in=90]{ix}{wx1}\n \\wk[out=-20,in=120]{ix}{wx2}\n \\wk{iy}{wy1}\n\\end{tikzdisplay}\\vskip-\\bigskipamount\\noindent\nIn the case where \\verb|SECRET| is $1$, there is an execution:\n\\begin{tikzdisplay}[node distance=1em]\n \\event{ix}{\\DW{x}{0}}{}\n \\event{iy}{\\DW{y}{0}}{right=of ix}\n \\event{rx1}{\\DR{x}{1}}{below=of ix}\n \\event{wy1}{\\DW{y}{1}}{right=of rx1}\n \\event{ry1}{\\DR{y}{1}}{below=of wy1}\n \\event{wx1}{\\DW{x}{1}}{right=of ry0}\n \\event{wz1}{\\DW{z}{1}}{right=of wx1}\n \\po{rx1}{wy1}\n \\po[out=30,in=150]{ry1}{wz1}\n \\rf[in=-90,out=-150]{wx1}{rx1}\n \\rf{wy1}{ry1}\n \\wk[out=-20,in=90]{ix}{wx1}\n \\wk[out=-20,in=120]{ix}{wx2}\n \\wk{iy}{wy1}\n\\end{tikzdisplay}\\vskip-\\bigskipamount\\noindent\nNote that in this case, there is no dependency from\n$(\\DR{y}{1})$ to $(\\DW{x}{1})$. This lack of dependency makes the\nexecution possible. Thus, if the attacker sees\nan execution with $(\\DW{z}{1})$, they can conclude\nthat \\verb|SECRET| is $1$, which is an information flow\nattack.\n\nThis attack is not just an artifact of the model,\nsince the same behavior can be exhibited by\ncompiler optimizations. Consider the program fragment:\n\\[\\begin{array}{l}\n \\IF{y = 0}\\THEN x\\GETS1\n \\brELIF{\\CANREAD(\\SEC)}\\THEN x\\GETS\\SEC\n \\brELSE x\\GETS1\\SEMI z\\GETS1 \\FI\n\\end{array}\\]\nIn the case where \\verb|SECRET| is a constant \\verb|1|,\nthe compiler can inline it\nand lift the assignment to $x$ out of the $\\IF{}$ statement:\n\\[\\begin{array}{l}\n x\\GETS1\\SEMI\n \\IF{y = 0}\\THEN\n \\brELIF{\\CANREAD(\\SEC)}\\THEN\n \\brELSE z\\GETS1 \\FI\n\\end{array}\\]\nAfter this optimization, a sequentially consistent execution\nexhibits $(\\DW{z}{1})$. We discuss the practicality of this attack\nfurther in \\S\\ref{sec:experiments}.\n\n\\subsection{Dead store elimination}\n\\label{sec:dse}\n\nA common compiler optimization is \\emph{dead store elimination},\nin which writes are omitted if they will be overwritten by a subsequent\nwrite later in the same thread. We can model eliminated writes\nby ones with an unsatisfiable precondition. For example,\none execution of $(x \\GETS 1\\SEMI x \\GETS 2) \\PAR (r \\GETS x)$ is:\n\\begin{tikzdisplay}[node distance=1em]\n \\nonevent{wx1}{\\DW{x}{1}}{}\n \\event{wx2}{\\DW{x}{2}}{right=of wx1}\n \\event{rx2}{\\DR{x}{2}}{right=2.5em of wx2}\n \\wk{wx1}{wx2}\n \\rf{wx2}{rx2}\n\\end{tikzdisplay}\nRecall that for any satisfiable $\\aEv$, if $\\aEv$ reads $\\aLoc$ from $\\bEv$\nthen $\\bEv$ is satisfiable. This means that, although we can eliminate\n$(\\DW{x}{1})$ we cannot eliminate $(\\DW{x}{2})$.\n\nOne heuristic that a compiler might adopt is to only eliminate\nwrites that are guaranteed to be followed by another write\nto the same variable. This can be formalized by saying that\na write event $\\bEv$ is eliminable if\nthere is a tautology $\\bEv \\gtN \\aEv$\nwhich writes to the same location.\nA model of dead store elimination is one where,\nin every pomset, every eliminable event is unsatisfiable.\nThis model includes the example above.\n\nNote that if dead store\nelimination is \\emph{always} performed, then there is an information\nflow attack similar to the one in \\S\\ref{sec:info-flow-attack}. Consider\nthe program:\n\\[\\begin{array}[t]{@{}l}\n y\\GETS x\n \\PAR\\begin{array}[t]{@{}l}\n x\\GETS 1\\SEMI\\\\\n \\IF{\\CANREAD(\\SEC})\\THEN \\IF{\\SEC}\\THEN x\\GETS 2\\FI\n \\brELSE x\\GETS 2\\FI\n\\end{array}\\end{array}\\]\nIn the case that \\verb|SECRET| is $0$, there is an execution:\n\\begin{tikzdisplay}[node distance=1em]\n \\event{rx1}{\\DR{x}{1}}{}\n \\event{wy1}{\\DW{y}{1}}{right=of rx1}\n \\event{wx1}{\\DW{x}{1}}{right=2.5em of wy1}\n \\event{wx2}{\\aForm \\mid \\DW{x}{2}}{right=of wx1}\n \\rf[out=160,in=20]{wx1}{rx1}\n \\po{rx1}{wy1}\n \\wk{wx1}{wx2}\n\\end{tikzdisplay}\nwhere $\\aForm$ is ($\\lnot$\\verb|canRead(SECRET)|),\nwhich is not a tautology, and so the $(\\DW{x}{1})$ event is not eliminated.\nIn the case that \\verb|SECRET| is not $0$, the matching execution\nis:\n\\begin{tikzdisplay}[node distance=1em]\n \\event{rx2}{\\DR{x}{2}}{}\n \\event{wy2}{\\DW{y}{2}}{right=of rx2}\n \\nonevent{wx1}{\\DW{x}{1}}{right=2.5em of wy2}\n \\event{wx2}{\\DW{x}{2}}{right=of wx1}\n \\rf[out=160,in=20]{wx2}{rx2}\n \\po{rx2}{wy2}\n \\wk{wx1}{wx2}\n\\end{tikzdisplay}\nNow the $(\\DW{x}{2})$ event is a guaranteed write, so the $(\\DW{x}{1})$\nis eliminated, and so cannot be read.\nIn the case that the attacker can rely on dead store\nelimination taking place, this is an information flow: if the attacker observes\n$x$ to be $1$, then they know \\verb|SECRET| is $0$. We return to this attack\nin \\S\\ref{sec:experiments}.\n\n\\section{Experiments}\n\\label{sec:experiments}\n\nOne theme of this paper is that optimizations not typically part of formal\nabstractions can result in information flow leaks.\nThis is typified by the Spectre attack, which leverages speculative execution,\na hardware optimization.\n\\S\\ref{sec:info-flow-attack} and~\\S\\ref{sec:dse} presented other attacks\nalong the same line, which leverage compiler optimizations.\nThese attacks also, unlike Spectre, do not rely on timing side channels, or\nindeed timers of any kind, bypassing many common Spectre\nmitigations~\\cite{KohlbrennerShacham2016, FirefoxPerformanceNow}.\n\nIn this section we present implementations of the attacks described\nin~\\S\\ref{sec:info-flow-attack} and~\\S\\ref{sec:dse}, in both cases\nexploiting compiler optimizations to construct an information flow attack.\n\\ignore{\nThe attacker model (detailed in~\\S\\ref{subsec:attacker-model})\nis currently unrealistic, as we attack C compilers rather than scripting\nlanguages, and we require the secret to be a compile-time constant which\nthe compiler can optimize on.\nThis renders these attacks proof-of-concepts rather than\nimmediately exploitable vulnerabilities.\nHowever, we believe their novelty may lead to\ninteresting discussion, and with much more development, these attacks may\nevolve into genuine threats against targets such as JIT compilers.\n}\nWe demonstrate the efficacy of our proof-of-concept attacks against\nthe {\\CLANG} and {\\GCC} C compilers.\nAll of our experiments are performed on a Debian 9 machine with an Intel\ni7-6500U processor and 8 GB RAM;\nwe test against {\\GCC}~6.3.0 and {\\CLANG}~3.8.\n\n\\subsection{Attacker model}\n\\label{subsec:attacker-model}\n\nAs explained in Section~\\ref{sec:examples}, our model expresses a variety\nof attacks with differing attacker models.\nThe Spectre~(\\S\\ref{sec:spectre}) and\n\\textsc{Prime+Abort}~(\\S\\ref{sec:transactions}) attacks exploit optimizations\nin hardware, and so can be mounted against a dynamic \\SEC.\nOur model captures this appropriately.\nIn contrast, the attacks from~\\S\\ref{sec:info-flow-attack}\nand~\\S\\ref{sec:dse} leverage compiler optimizations and require the \\SEC to\nbe known to the compiler, for example a static \\SEC or a JIT compiler.\nAs our experimental section is devoted to these latter (novel) attacks, we\ndiscuss the attacker model for these attacks in more detail.\n\nIn the attacker model for the compiler-optimization attacks, we assume that\nthere is a {\\SEC} hardcoded into an application; for instance, {\\SEC} may be\nan API key.\nThis {\\SEC} is known at compile time, but may not be\naccessed except behind a security check.\nSince the attacker is running with low security privileges,\nthe security check always fails,\nso the attacker can only access the {\\SEC} in dead code.\n\\ignore{\nThe attacker has no capabilities other than writing and executing code --- in\nparticular the attacker may not disassemble the compiler or libraries to learn\nthe {\\SEC} directly; may not examine the internal state of the compiler;\nmay not access timers of any kind; and may not leverage hardware side channels.\n}\nThe attacker's goal is to learn the value of the {\\SEC}.\n\nAs a running hypothetical example, suppose there is a library that contains\na hardcoded {\\SEC}: % such as an API key: --- API key mentioned just above\n\\begin{verbatim}\n static const uint SECRET = 0x1234;\n static volatile bool canReadSecret = false;\n\\end{verbatim}\nThe attacker is not allowed to write to \\verb|canReadSecret| or read from {\\SEC}\nexcept after performing an \\verb|if(canReadSecret)| check.\n\nThis is not necessarily a realistic attacker model,\nsince in most cases secrets are only known at run time rather than compile time,\nwhich means that the attacks presented in this section\nare more proof-of-concepts rather than immediately exploitable vulnerabilities.\nHowever, the mechanisms we use are novel and could potentially be applied\nin other contexts.\nFor instance, many real-world contexts allow untrusted or\nthird-party entities to write code in a scripting language which is then\ncompiled alongside and integrated into a larger application, often\nusing a just-in-time (JIT) compiler.\nJavaScript code from third-party websites running in a browser is a common\nexample of this.\n% We give an attacker similar capabilities against a\n% compiler, except that we consider the simpler setting of using C code against a C\n% compiler.\nAlthough we consider only attacks using C code against a C compiler,\none could imagine a similar attack using JavaScript against browser JIT\ncompilers, where the compiler may have access to interesting secrets such as the\nbrowser's cookie store, and may be able to optimize based on those secrets.\nWe plan to explore JavaScript attacks of this type as future work.\n\n\\subsection{Load-store reordering attack}\n\\label{subsec:exp-rel-mem}\n\nWe begin by examining the attack in~\\S\\ref{sec:info-flow-attack} in\nmore detail.\nWe show that by exploiting compiler optimizations which perform\nload-store reordering, an attacker can learn the value of a compile-time\n{\\SEC} despite only being allowed to use it inside dead code.\n%This attack was tested and works against {\\GCC} version 6.3.0.\nWe verified that this attack succeeds against {\\GCC} version 6.3.0.\n\nThe form of the attack presented in~\\S\\ref{sec:info-flow-attack} works in\ntheory, but in practice, just because a compiler is \\emph{allowed} to perform a\nload-store reordering doesn't mean that it \\emph{will}.\nWe found that {\\GCC} and {\\CLANG} chose to read $y$ into a\nregister first (before writing to $x$), regardless of the value of\n{\\SEC}.\n% However, we did find a related pattern in which {\\GCC} will emit a\nHowever, using a similar program we were able to coax {\\GCC} to emit a\ndifferent ordering of the read of $y$ and the write of $x$ depending\non the value of a {\\SEC}:\n\\[\\begin{array}[t]{@{}l}\n \\VAR x\\GETS0\\SEMI \\VAR y\\GETS0\\SEMI\\\\\\quad\n y\\GETS x\n \\PAR\\begin{array}[t]{@{}l}\n x\\GETS 1\\SEMI\\\\\n \\IF{\\texttt{canReadSecret}}\\THEN x\\GETS\\SEC\\FI\\\\\n \\IF{y > 0}\\THEN z\\GETS 0 \\ELSE z\\GETS 1\\FI\n\\end{array}\\end{array}\\]\n\\ignore{\n\\begin{verbatim}\n x := 0; y := 0;\n (\n y := x;\n ) || (\n x := 1;\n if(canReadSecret) { x = SECRET; }\n if (y) { return 0; }\n else { return 1; }\n )\n\\end{verbatim}\n}\n\nFigure~\\ref{fig:lsr-asm} shows the assembly output of {\\GCC} on this program in the cases\nwhere {\\SEC} is 0 and 1 respectively.\nIn the case that {\\SEC} is $1$, {\\GCC} removes the $\\IF{}$\nstatement entirely, and moves the read of $y$ above the write of $x$.\nHowever, when {\\SEC} is $0$, the $\\IF{}$ statement must remain\nintact, and {\\GCC} does not move the read of $y$.\nThis means that if {\\SEC} is $1$, the second thread will always\nread $y\\EQ0$ and always assign $z\\GETS1$.\nHowever, if {\\SEC} is $0$, it is possible that the first thread\nmay observe $x\\EQ1$ and write $y\\GETS1$ in time for the second thread\nto observe $y\\EQ1$ and thus assign $z\\GETS0$.\nIn this way, we leverage compiler load-store reordering to learn the value of\na compile-time {\\SEC}.\n\n\\begin{figure}\n \\begin{tabular}{p{3.4cm} @{\\quad} | p{3.4cm}}\n \\texttt{SECRET == 0} & \\texttt{SECRET == 1} \\\\ \\hline\n\\begin{verbatim}\n mov s(%rip), %eax\n mov $1, x(%rip)\n test %eax, %eax\n je label1\n mov $0, x(%rip)\nlabel1:\n mov y(%rip), %eax\n test %eax, %eax\n sete %eax\n\\end{verbatim}\n &\n\\begin{verbatim}\n mov s(%rip), %eax\n mov y(%rip), %eax\n mov $1, x(%rip)\n test %eax, %eax\n sete %eax\n\\end{verbatim}\n \\end{tabular}\n \\caption{\n Simplified x86 assembly output from \\texttt{gcc} for the main thread of\n the load-store reordering attack.\n In particular, note that the order between (\\texttt{mov \\$1, x(\\%rip)})\n and (\\texttt{mov y(\\%rip), \\%eax}) is different in the two cases.\n References to the \\texttt{canReadSecret} variable have been shortened to\n \\texttt{s} for the figure.\n }\n \\label{fig:lsr-asm}\n\\end{figure}\n\nWe extend this attack to leak a secret consisting of an arbitrary number\n\\verb|N| of bits.\nTo do this, we compile \\verb|N| copies of the test function, each\nperforming a boolean test on a single bit of {\\SEC}.\nSo that the bit value is\nconstant at compile time, we must compile a separate function for each bit, rather than execute the same\ncode repeatedly in a loop.\n\\ignore{\nThe function used for reading the \\verb|k|th bit is as follows (for\n\\verb|N <= 64|):\n\\[\\begin{array}[t]{@{}l}\n \\VAR x\\GETS0\\SEMI \\VAR y\\GETS0\\SEMI\\\\\\quad\n y\\GETS x\n \\PAR\\begin{array}[t]{@{}l}\n x\\GETS 1\\SEMI\\\\\n \\IF{\\texttt{canReadSecret}}\\THEN x\\GETS\\texttt{(\\SEC\\, \\& (1 << k)) ? 1 : 0}\\SEMI\\FI\\\\\n \\IF{y > 0}\\THEN \\RETURN 0\n \\brELSE \\RETURN 1\\FI\n\\end{array}\\end{array}\\]\nFollowing the same analysis as above, this function will always return $1$\nif {\\SEC} is $1$, but may return $0$ if {\\SEC} is $0$.\nThe extension of the attack to the general case with truly arbitrary \\verb|N|\nis straightforward; {\\SEC} becomes an array of 64-bit values, and we use\n\\verb|k / 64| and \\verb|1 << (k & 63)| as the array index and bitmask\nrespectively.\n}\n\nWe make three additional tweaks to improve the reliability, so that the attacker\ncan confidently infer the value of {\\SEC} based on the observed value of $z$.\n First, rather than performing $y\\GETS x$ only once in the forwarding thread,\nwe perform $y\\GETS x$ continuously in a loop.\nThis maximizes the probability that, once $x\\GETS 1$ occurs in the main\nthread, $y$ will be immediately assigned $1$ by the forwarding thread\nand the main thread will be able to read $y\\EQ 1$.\n\nSecond, we wish to lengthen the timing window between $x\\GETS 1$ and the\nread of $y$ in the main thread (in the case where\n{\\SEC} is $0$ and the read of $y$ remains below $x\\GETS 1$).\nHowever, we wish to do this in a way that does not block the reordering of the\nread of $y$ upwards in the case where {\\SEC} is $1$.\nWe do this by inserting many copies of the line\n\\[\n \\IF{\\texttt{canReadSecret}} \\THEN x\\GETS\\SEC\\FI\n\\]\ninstead of just one.\nIn the case where {\\SEC} is $0$, this\nresults in many reads of \\verb|canReadSecret| and many conditional jumps,\nwhich in practice creates a timing window for the forwarding thread to perform\n$y\\GETS x$.\nHowever, in the case where {\\SEC} is $1$,\nall of these inserted lines can be removed just as a single copy could be.\nIn practice, we found that inserting too many copies of the line prevents\n{\\GCC} from reordering the read of $y$ above the write to $x$ as\ndesired; inserting $30$ copies was sufficient to create a timing window\nwhile still allowing the desired reordering.\n\nFinally, we redundantly execute the entire attack several times, noting the\nvalue of $z$ in each case.\nWe note that if \\emph{any} of the redundant runs produces a value of\n$z\\EQ0$ for a particular bit position, then we can be certain that the\ncorresponding bit of {\\SEC} \\emph{must} be $0$, as it implies the\nread of $y$ was not reordered upwards in that particular function.\nOn the other hand, the more runs that produce a value of $z\\EQ1$ for a\nparticular bit position, the more certain we can be that the read of $y$\nwas reordered above the $x\\GETS 1$ assignment, and {\\SEC} is $1$.\n\n\\begin{figure}\n \\small\n \\begin{tabular}{ r | l | l | l }\n Redundancy & Bandwidth (bits/s) & Bitwise Acc & Per-run Acc \\\\ \\hline\n 1 & 3.14 million & 90.89\\% & 1.9\\% \\\\\n 2 & 1.56 million & 96.04\\% & 8.1\\% \\\\\n 3 & 1.04 million & 98.09\\% & 10.0\\% \\\\\n 4 & 783 thousand & 98.98\\% & 24.3\\% \\\\\n 5 & 626 thousand & 99.71\\% & 50.2\\% \\\\\n 7 & 447 thousand & 99.91\\% & 70.6\\% \\\\\n 10 & 314 thousand & 99.991\\% & 93.8\\% \\\\\n 15 & 208 thousand & 99.994\\% & 95.5\\% \\\\\n 20 & 157 thousand & 99.9995\\% & 99.2\\% \\\\\n 30 & 105 thousand & 99.99995\\% & 99.9\\% \\\\\n \\end{tabular}\n \\caption{\n Performance results for the load-store reordering attack when leaking a\n 2048-bit secret.\n `Redundancy' is the number of redundant runs performed for error\n correction; more redundant runs improves accuracy but reduces bandwidth.\n `Bandwidth' is the number of bits leaked per second after accounting for\n any error correction.\n `Bitwise Accuracy' is the percentage of bits that were correct, while\n `Per-run Accuracy' is the percentage of full 2048-bit secrets that were\n correct in all bit positions.\n }\n \\label{fig:load-store-perf}\n\\end{figure}\n\nFigure~\\ref{fig:load-store-perf} gives the performance results for this attack\nagainst {\\GCC} version 6.3.0.\nThe attack can sustain hundreds of thousands of bits per second leaked with\nnear-perfect accuracy, or millions of bits per second with error rates of a\nfew percent.\nThis means that an attacker can leak a 2048-bit secret with near-perfect\naccuracy in under $10$ ms.\nNote that this bandwidth assumes that all copies of the attack function are\nalready compiled; the cost of compilation is not included here.\n\n\\subsection{Dead store elimination attack}\n\\label{subsec:exp-dse}\n\nIn this section we return to the attack in~\\S\\ref{sec:dse} based on\ndead store elimination.\nWe show that in our attacker model (given in~\\S\\ref{subsec:attacker-model}),\nthe attacker is able to exploit dead\nstore elimination to again learn the value of a compile-time {\\SEC}\ndespite only being allowed to use it inside dead code.\nThis attack is even more efficient than the attack on load-store reordering,\nand further, we were able to demonstrate its effectiveness against both\n{\\GCC} and {\\CLANG}.\n\nWe start from the simple form of the attack presented in~\\S\\ref{sec:dse},\nand extend it to leak a secret consisting of an\narbitrary number of bits, in the same way that we extended the load-store\nreordering attack.\n\\ignore{\nAs we did in the load-store reordering attack, we again compile \\verb|N| copies\nof the test function, each performing a boolean test on a single bit of the\nsecret.\nThe function used for reading the \\verb|k|th bit is as follows (for\n\\verb|N <= 64|):\n\\[\\begin{array}[t]{@{}l}\n \\VAR x\\GETS0\\SEMI\\\\\\quad\n r\\GETS x\n \\PAR\\begin{array}[t]{@{}l}\n x\\GETS 1\\SEMI\\\\\n \\IF{\\CANREAD(\\SEC})\\THEN \\IF{\\SEC\\,\\texttt{ \\& (1 << k}}\\NOTEQ0)\\THEN x\\GETS 2\\FI\n \\brELSE x\\GETS 2\\FI\n\\end{array}\\end{array}\\]\n\\ignore{\n\\begin{verbatim}\n (\n r := x;\n ) || (\n x := 1;\n if (canRead(SECRET)) {\n if (SECRET & (1 << k)) { x := 2; }\n } else {\n x := 2;\n }\n )\n\\end{verbatim}\n}\nThen, we test each function in turn, each time noting the value of $y$\nobserved by the `listening' thread.\nIf {\\SEC} is 1, the $x\\GETS 2$ assignment is\nguaranteed to happen, so the compiler can eliminate the $x \\GETS 1$\nassignment as a dead store and we will observe $y\\EQ 2$; however, if\n{\\SEC} is 0, the $x\\GETS 1$ assignment cannot be\neliminated, and we will observe $y\\EQ 1$ with some probability.\nThe extension of the attack to the general case with truly arbitrary \\verb|N|\nis straightforward and proceeds exactly as it did for the attack on\nload-store reordering.\n}\nWe make three additional tweaks to improve the reliability so that the attacker\ncan confidently infer the value of {\\SEC}.\nTwo of them follow exactly the same pattern as the reliability tweaks\nfor the load-store reordering attack in~\\S\\ref{subsec:exp-rel-mem} ---\ncontinuously forwarding $x$ to $y$ in the forwarding thread, and running the\nentire attack multiple times.\nThe remaining tweak is again motivated by increasing the timing window in\nwhich the forwarding can happen, but differs in some details from the\nimplementation in~\\S\\ref{subsec:exp-rel-mem}.\n\n\\ignore{\nFirst, rather than simply observing $x$ with $y\\GETS x$ in the\n`listening' thread, we continuously load $x$ in a loop until a\nnonzero value is observed --- i.e., we perform\n$\\DO{r\\GETS x} \\WHILE(r\\EQ0)$.\n\\ignore{\n\\begin{verbatim}\n do {\n r := x;\n } while(r == 0);\n\\end{verbatim}\n}\nThis remedies the case where $y\\GETS x$ could observe a value of $x$\nfrom `before' either of the two possible writes performed by the other thread.\n}\n\nTo increase the timing window, we insert additional time-consuming\ncomputation immediately following\nthe $x\\GETS 1$ operation in the main thread.\nThis increases the likelihood that the listening thread will be able to observe\n$x\\EQ 1$ (unless the $x\\GETS 1$ write was eliminated).\nInserting this computation should be done without interfering with the dead store\nelimination process itself, so that the compiler will continue to eliminate\nthe $x\\GETS 1$ write if and only if {\\SEC} was 1.\nFor {\\GCC}, we have a fair amount of freedom with the time-consuming\ncomputation --- for instance, we can use an arbitrarily long loop.\nIn fact, we can perform a further optimization by monitoring the value of the\nvariable $y$ (written to by the listening thread) and breaking out of the\nloop early if we see that the listening thread has already observed $x\\EQ 1$.\nHowever, with {\\CLANG}, we cannot use a loop at all --- the time-consuming\ncomputation must be branch-free and, furthermore, must not consist of too many\ninstructions.\n\\ignore{\nThis is because {\\CLANG}'s dead store elimination pass operates only\nwithin basic blocks, and uses a heuristic to stop scanning the basic block\nearly if it is too large.\n}\nNonetheless, we find that even with these restrictions, we are able to\nconstruct a reliable and fast attack against both {\\CLANG} and {\\GCC}.\n\n\\ignore{\nFinally, we redundantly execute the entire attack several times, noting the\nfinal value of $y$ (the first observed nonzero value of $x$) in each\ncase.\nWe note that if \\emph{any} of the redundant runs produces $y\\EQ 1$ for a\nparticular bit position, we can be certain that the corresponding bit of\n{\\SEC} \\emph{must} be $0$, as it implies that the $x\\GETS 1$ write\nwas not eliminated in that particular function.\nOn the other hand, the more runs that observe $y\\EQ 2$ in a particular bit\nposition despite our other reliability-increasing measures taken above, the\nmore certain we can be that the $x\\GETS 1$ write was eliminated in that\nfunction, and {\\SEC} is $1$.\n}\n\n\\begin{figure}\n \\small\n \\begin{tabular}{ r | l | l | l }\n Redundancy & Bandwidth (bits/s) & Bitwise Acc & Per-run Acc \\\\ \\hline\n 1 & 1.19 million & 99.991\\% & 95.6\\% \\\\\n 2 & 597 thousand & 99.99986\\% & 99.7\\% \\\\\n 3 & 397 thousand & 100.0\\% & 100.0\\% \\\\\n \\end{tabular}\n \\caption{\n Performance results for the dead store elimination attack on {\\CLANG} when\n leaking a 2048-bit secret.\n Terms are the same as defined in the caption for Figure~\\ref{fig:load-store-perf}.\n }\n \\label{fig:clang-dse-perf}\n\\end{figure}\n\n\\begin{figure}\n \\small\n \\begin{tabular}{ r | c | c | c }%| c | c | c }\n Stall amount & 10 &\n% 20 &\n% 50 &\n 100 &\n% 200 &\n 500 \\\\ \\hline\n Redundancy 1 & \\makecell{2.54 million\\\\98.15\\%} &\n% \\makecell{2.36 million\\\\99.80\\%} &\n% \\makecell{1.95 million\\\\99.987\\%} &\n \\makecell{1.54 million\\\\99.996\\%} &\n% \\makecell{1.12 million\\\\99.993\\%} &\n \\makecell{584 thousand\\\\99.998\\%} \\\\ \\hline\n Redundancy 2 & \\makecell{1.24 million\\\\99.73\\%} &\n% \\makecell{1.17 million\\\\99.993\\%} &\n% \\makecell{989 thousand\\\\100.0\\%} &\n \\makecell{774 thousand\\\\100.0\\%} &\n% \\makecell{553 thousand\\\\100.0\\%} &\n \\makecell{295 thousand\\\\100.0\\%} \\\\ \\hline\n Redundancy 3 & \\makecell{841 thousand\\\\99.94\\%} &\n% \\makecell{784 thousand\\\\100.0\\%} &\n% \\makecell{666 thousand\\\\100.0\\%} &\n \\makecell{521 thousand\\\\100.0\\%} &\n% \\makecell{370 thousand\\\\100.0\\%} &\n \\makecell{201 thousand\\\\100.0\\%} \\\\ \\hline\n Redundancy 4 & \\makecell{620 thousand\\\\99.992\\%} &\n% \\makecell{585 thousand\\\\100.0\\%} &\n% \\makecell{499 thousand\\\\100.0\\%} &\n \\makecell{387 thousand\\\\100.0\\%} &\n% \\makecell{285 thousand\\\\100.0\\%} &\n \\makecell{145 thousand\\\\100.0\\%} \\\\\n \\end{tabular}\n \\caption{\n Performance results for the dead store elimination attack on {\\GCC} when\n leaking a 2048-bit secret.\n Rows give different values of `redundancy' (as defined in previous figures),\n while columns give amounts of stall time immediately following the\n $x\\GETS 1$ write (as measured in loop iterations).\n Each table cell gives the leak bandwidth in bits/sec, followed by the\n bitwise accuracy.\n }\n \\label{fig:gcc-dse-perf}\n\\end{figure}\n% \\begin{figure*}\n% \\small\n% \\begin{tabular}{ r | c | c | c | c | c | c }\n% Stall amount & 10 & 20 & 50 & 100 & 200 & 500 \\\\ \\hline\n% Redundancy 1 & \\makecell{2.54 million\\\\98.15\\%} &\n% \\makecell{2.36 million\\\\99.80\\%} &\n% \\makecell{1.95 million\\\\99.987\\%} &\n% \\makecell{1.54 million\\\\99.996\\%} &\n% \\makecell{1.12 million\\\\99.993\\%} &\n% \\makecell{584 thousand\\\\99.998\\%} \\\\ \\hline\n% Redundancy 2 & \\makecell{1.24 million\\\\99.73\\%} &\n% \\makecell{1.17 million\\\\99.993\\%} &\n% \\makecell{989 thousand\\\\100.0\\%} &\n% \\makecell{774 thousand\\\\100.0\\%} &\n% \\makecell{553 thousand\\\\100.0\\%} &\n% \\makecell{295 thousand\\\\100.0\\%} \\\\ \\hline\n% Redundancy 3 & \\makecell{841 thousand\\\\99.94\\%} &\n% \\makecell{784 thousand\\\\100.0\\%} &\n% \\makecell{666 thousand\\\\100.0\\%} &\n% \\makecell{521 thousand\\\\100.0\\%} &\n% \\makecell{370 thousand\\\\100.0\\%} &\n% \\makecell{201 thousand\\\\100.0\\%} \\\\ \\hline\n% Redundancy 4 & \\makecell{620 thousand\\\\99.992\\%} &\n% \\makecell{585 thousand\\\\100.0\\%} &\n% \\makecell{499 thousand\\\\100.0\\%} &\n% \\makecell{387 thousand\\\\100.0\\%} &\n% \\makecell{285 thousand\\\\100.0\\%} &\n% \\makecell{145 thousand\\\\100.0\\%} \\\\\n% \\end{tabular}\n% \\caption{\n% Performance results for the dead store elimination attack on {\\GCC} when\n% leaking a 2048-bit secret.\n% Rows give different values of `redundancy' (as defined in previous figures),\n% while columns give amounts of stall time immediately following the\n% $x\\GETS 1$ write (as measured in loop iterations).\n% Each table cell gives the leak bandwidth in bits/sec, followed by the\n% bitwise accuracy.\n% }\n% \\label{fig:gcc-dse-perf}\n% \\end{figure*}\n\nPerformance results for the dead store elimination attack against {\\CLANG}\nare given in Figure~\\ref{fig:clang-dse-perf}, and against {\\GCC} are given in\nFigure~\\ref{fig:gcc-dse-perf}.\nBoth attacks are faster than the load-store-reordering attack from\n\\S\\ref{subsec:exp-rel-mem} when comparing settings which give the same\naccuracy.\nIn particular, the attack on {\\GCC} can leak a 2048-bit cryptographic\nkey with perfect accuracy (in our tests) in about $2$ ms.\n\n\\section{Conclusions and future work}\n\nIn this paper, we have presented a model of speculative evaluation and\nshown that it captures non-trivial properties of speculations produced\nby hardware, compiler optimizations, and transactions. These properties\ninclude information flow attacks: in the case of hardware and transactions\nthis is modeling known attacks~\\cite{DBLP:journals/corr/abs-1801-01203,DBLP:conf/uss/DisselkoenKPT17},\nbut in the case of compiler optimizations the attacks are new, and were\ndiscovered as a direct result of developing the model. We have experimentally\nvalidated that the attacks can be carried out against \\verb|gcc| and \\verb|clang|,\nthough only against secrets known at compile time.\n\nWe have tried where possible to abstract away from the\nmicro-architectural details that enable attackers to exploit\nspeculation, while still trying to capture the ``essence'' of\nSpectre. There are trade-offs with any such abstraction, as\nhigher-level abstractions make program behavior easier to understand\nand reason about, but at the cost of ignoring potential attacks. One\nsoftware developer's useful abstraction is another's ignoring the\ndifficult issues.\n\nAs a concrete instance, one feature of Spectre we have glossed over is\nthe ability of the attacker to influence speculation, for example by\ntraining the branch predictor or influencing the contents of caches.\nWe expect that such attacker influence could be modeled using a\nmechanism similar to the speculation barriers of \\S\\ref{sec:spec-barriers},\nbut under the control of the attacker rather than the honest agents.\n\nThe paper's primary focus is not weak memory, and the model of relaxed\nmemory used in this paper is deliberately simplified, compared for\nexample to\nC11~\\cite{Boehm:2008:FCC:1375581.1375591,Batty:2011:MCC:1926385.1926394}. Nonetheless,\nwe believe that the model developed in the paper has promise as a\nsemantics for relaxed memory. Our model appears to be the first in the\nliterature that both validates all of the JMM causality test cases and\nalso forbids thin air behavior; the most prominent existing models are\neither too permissive~\\cite{Manson:2005:JMM:1047659.1040336,\n Jagadeesan:2010:GOS:2175486.2175503,Kang-promising-2017} or\ntoo conservative~\\cite{DBLP:conf/lics/JeffreyR16}. In separate work,\nwe are exploring the usual properties of weak memory, such as\ncomparisons with sequentially consistent models,\noptimization soundness, or compilation soundness. While our model of\ntransactions shows the flexibility of our model, in this future work,\nwe will include known features of hardware, including locks, fences,\nand read-modify-write instructions. This development is not core to\nthe basic findings of this paper.\n\n\n\nUNUSED: In particular our model of reads-from is strong, and could be weakened\nby replacing the requirement $\\bEv\\lt\\aEv$ in Definition~\\ref{def:rf} by $\\bEv\\gtN\\aEv$. It remains to be seen how this impacts the model.\n%% in particular the logical formulation of $\\aLoc$-closure in\n%% \\S\\ref{sec:logic} as\n%% $((\\DR{\\aLoc}{\\aVal}) \\Rightarrow \\once(\\DW{\\aLoc}{\\aVal}))$\n%% would no longer be sound.\n% The model is also not considering coherence, though we speculate it\n% can be added by requiring that for each $\\aLoc$, $\\gtN$ form a total\n% order when restricted to events that write to $\\aLoc$.\n\nThe design space for transactions is very rich~\\cite{DBLP:journals/pacmpl/DongolJR18}.\nWe have only presented one design choice, and it remains to be seen how other\ndesign choices could be adopted. For example, we have chosen not to distinguish\ncommits that are aborted due to transaction failure from commits which are aborted\nfor other reasons, such as failed speculation.\n\nIn future work, it would be interesting to see if full-abstraction\nresults for pomsets \\cite{Plotkin:1997:TSP:266557.266600} can be extended to\n3-valued pomsets.\n\nOne interesting feature of this model is that (in the language\nof~\\cite{Pichon-Pharabod:2016:CSR:2837614.2837616}) it is a\n\\emph{per-candidate execution model}, in that the correctness of an\nexecution only requires looking at that one execution, not at\nothers. This is explicit in memory models such\nas~\\cite{Jagadeesan:2010:GOS:2175486.2175503,Kang-promising-2017} in which\n``alternative futures'' are explored, in a style reminiscent of\nAbramsky's bisimulation as a testing equivalence~\\cite{ABRAMSKY1987225}. Models of\ninformation flow are similar, in that they require comparing different\nruns to test for the presence of dependencies~\\cite{Clarkson:2010:HYP:1891823.1891830}. In contrast, the model\npresented here explicitly captures dependency in the pomset order, and\nmodels multiple runs by giving the semantics of $\\IF{}$ in terms of a\nconcurrent semantics of both branches.\nIn the parlance of information flow~\\cite{Barthe:2004:SIF:1009380.1009669},\nthe humble conditional suffices to construct a composition operator to detect information flow in the presence of speculation.\n\n\\begin{small}\n\\bibliography{bib}\n\\end{small}\n\n\\appendix\n\\subsection{Operations on sets of pomsets}\n\\label{app:sets-of-pomsets}\n\nHere we give the formal definitions for the operations described at the\nbeginning of \\S\\ref{sec:semantics}.\n\nIn order to model speculation barriers in \\S\\ref{sec:spec-barriers},\nwe partition the actions into \\emph{mergeable} and \\emph{unmergeable}.\n\nIn transactional memory, begin and commit actions are memory fences: that is,\nthey are a barrier to reordering memory accesses. To capture this (and other\nmemory barriers), we identify sets $\\Rel$ and $\\Acq \\subseteq\\Act$. For\ntransactions, we have $(\\DB{\\aVal})\\in\\Acq$ for begins,\n$(\\DC{\\aVal})\\in \\Rel$ for commits. We say that $\\aAct$ is a \\emph{release}\nif $\\aAct\\in\\Rel$ and $\\aAct$ is an \\emph{acquire} if $\\aAct\\in\\Acq$.\n% In a pomset, a release event is one\n% labeled with a release action, and an acquire event is one labeled by an\n% acquire action. \n\n\\begin{definition}\n \\label{def:prefix}\nLet $\\aAct \\prefix \\aPSS$ be the set $\\aPSS'$ where $\\aPS'\\in\\aPSS'$ whenever\nthere is $\\aPS\\in\\aPSS$ such that:\n\\begin{itemize}\n\\item $\\Event' = \\Event \\cup \\{\\cEv\\}$,\n\\item if $\\bEv \\le \\aEv$ then $\\bEv \\le' \\aEv$,\n\\item if $\\aEv \\gtN \\bEv$ then $\\aEv \\gtN' \\bEv$,\n\\item if $\\cEv\\in\\Event$ then $\\cEv$ is mergeable,\n\\item $\\labeling'(\\cEv) = (\\aForm, \\aAct)$, and\n\\item if $\\labeling(\\aEv) = (\\bForm \\mid \\bAct)$ then $\\labeling'(\\aEv) =\n (\\bForm' \\mid \\bAct)$, where:\n \\begin{itemize}\n \\item $\\cEv \\lt' \\aEv$ whenever $\\aAct$ is an acquire or $\\bAct$ is a release, \n \\item if $\\aAct$ is an acquire then $\\bForm$ is independent of every $\\bLoc$,\n \\item if $\\aAct$ and $\\bAct$ both touch the same location and one is a write,\n then $\\cEv \\gtN' \\aEv$, and\n \\item $\\bForm'$ implies \\(\\left\\{\\begin{array}{l@{~}ll}\n % \\bForm[\\aVal/\\aLoc] & \\mbox{if $\\aAct$ reads $\\aVal$ from $\\aLoc$ and $\\cEv\\lt'\\aEv$} & \\textsc{[dependent read]} \\\\\n % \\bForm[\\aVal/\\aLoc] \\text{ and } \\bForm & \\mbox{if $\\aAct$ reads $\\aVal$ from $\\aLoc$} & \\textsc{[independent read]} \\\\\n % \\bForm & \\mbox{otherwise} & \\textsc{[non-read]} \\\\ \n \\bForm[\\aVal/\\aLoc] \\\\\\quad \\mbox{if $\\aAct$ reads $\\aVal$ from $\\aLoc$ and $\\cEv\\lt'\\aEv$} \\\\\\qquad \\textsc{[dependent read]} \\\\[\\jot]\n \\bForm[\\aVal/\\aLoc] \\text{ and } \\bForm \\\\\\quad \\mbox{if $\\aAct$ reads $\\aVal$ from $\\aLoc$} \\\\\\qquad \\textsc{[independent read]} \\\\[\\jot]\n \\bForm \\\\\\quad \\mbox{otherwise} \\\\\\qquad \\textsc{[non-read]} \\\\\n \\end{array}\\right.\\)\n \\end{itemize}\n\\end{itemize}\n\\end{definition}\nThe first constraint ensures that events are ordered before a release and\nafter an acquire. The second constraint ensures that thread-local reads do\nnot cross acquire fences.\n\n% Prefixing is used to define the semantics of reads and writes, and\n% adds a new event $\\cEv$ with action $\\aAct$. As in the definition\n% of parallel composition, the definition allows the new event to overlap with\n% events in $\\aPSS$ as long as they agree on the action.\n\nThe tricky parts of the\ndefinition are the named cases, which place requirements on read\ndependencies. If $\\aAct$ reads $\\aVal$ from $\\aLoc$, we have to\ndecide whether $\\aEv$ depends on $\\cEv$ for some $\\aEv$ with old\nprecondition $\\bForm$ and new precondition $\\bForm'$. The first case\n\\textsc{[dependent read]} is that the dependency exists, in which case\n$\\bForm'$ just has to imply $\\bForm[\\aVal/\\aLoc]$. The more interesting \ncase is \\textsc{[independent read]}, in which case $\\bForm'$ has to imply\n$\\bForm[\\aVal/\\aLoc]$ and $\\bForm$. This corresponds to a case where\n$\\aEv$ can be performed with or without $\\cEv$.\nIn particular, if $\\bForm$ is independent of $\\aLoc$ then we can pick\n$\\bForm'$ to be $\\bForm$, and the independent read case will apply.\n% For example,\n% if $\\aAct$ and $\\bAct$ write to the same location, $\\aAct$ reads $\\aVal$ from $\\aLoc$, $\\bForm$ is independent of $\\aLoc$,\n% and\n% $\\aPSS$ contains:\n% \\begin{tikzdisplay}[node distance=1em]\n% \\event{b}{\\bForm \\mid \\bAct}{}\n% \\event{c}{\\cForm \\mid \\cAct}{right=of b}\n% \\po{b}{c}\n% \\end{tikzdisplay}\n% then $\\aAct\\prefix\\aPSS$ contains:\n% \\begin{tikzdisplay}[node distance=1em]\n% \\event{a}{\\aForm \\mid \\aAct}{}\n% \\event{b}{\\bForm \\mid \\bAct}{right=of a}\n% \\event{c}{\\cForm[\\vec\\aVal/\\vec\\aLoc] \\mid \\cAct}{right=of b}\n% \\po[out=25,in=155]{a}{c}\n% \\wk{a}{b}\n% \\po{b}{c}\n% \\end{tikzdisplay}\n\n\n\\begin{definition}\nLet $\\aPS_0 \\in (\\aPSS_1 \\parallel \\aPSS_2)$\nwhenever there are $\\aPS_1 \\in \\aPSS_1$ and $\\aPS_2 \\in \\aPSS_2$ such that:\n\\begin{itemize}\n\\item $\\Event_0 = \\Event_1 \\cup \\Event_2$,\n\\item if $\\aEv \\le_1 \\bEv$ or $\\aEv \\le_2 \\bEv$ then $\\aEv \\le_0 \\bEv$,\n\\item if $\\aEv \\gtN_1 \\bEv$ or $\\aEv \\gtN_2 \\bEv$ then $\\aEv \\gtN_0 \\bEv$,\n\\item if $\\aEv\\in\\Event_1\\cap\\Event_2$ then $\\aEv$ is mergeable,\n\\item if $\\labeling_0(\\aEv) = (\\aForm_0 \\mid \\aAct)$ then either:\n \\begin{itemize}\n \\item $\\labeling_1(\\aEv) = (\\aForm_1 \\mid \\aAct)$ and $\\labeling_2(\\aEv) = (\\aForm_2 \\mid \\aAct)$\n and $\\aForm_0$ implies $\\aForm_1 \\lor \\aForm_2$,\n \\item $\\labeling_1(\\aEv) = (\\aForm_1 \\mid \\aAct)$ and $\\aEv \\not\\in \\Event_2$\n and $\\aForm_0$ implies $\\aForm_1$, or\n \\item $\\labeling_2(\\aEv) = (\\aForm_2 \\mid \\aAct)$ and $\\aEv \\not\\in \\Event_1$\n and $\\aForm_0$ implies $\\aForm_2$.\n \\end{itemize}\n\\end{itemize}\n\\end{definition}\n% We use $\\aPSS_1 \\parallel \\aPSS_2$ in defining the semantics of conditionals\n% and concurrency.\n% It contains the union of pomsets from $\\aPSS_1$ and $\\aPSS_2$,\n% allowing overlap as long as they agree on actions. For example, if\n% $\\aPSS_1$ and $\\aPSS_2$ contain:\n% \\begin{tikzdisplay}[node distance=1em]\n% \\event{a}{\\aForm \\mid \\aAct}{}\n% \\event{b}{\\bForm_1 \\mid \\bAct}{right=of a}\n% \\po{a}{b}\n% \\end{tikzpicture}\\qquad\\qquad\\begin{tikzpicture}[node distance=1em]\n% \\event{b}{\\bForm_2 \\mid \\bAct}{}\n% \\event{c}{\\cForm \\mid \\cAct}{right=of b}\n% \\wk{b}{c}\n% \\end{tikzdisplay}\n% then $\\aPSS_1 \\parallel \\aPSS_2$ contains:\n% \\begin{tikzdisplay}[node distance=1em]\n% \\event{a}{\\aForm \\mid \\aAct}{}\n% \\event{b}{\\bForm_1 \\lor \\bForm_2 \\mid \\bAct}{right=of a}\n% \\event{c}{\\cForm \\mid \\cAct}{right=of b}\n% \\po{a}{b}\n% \\wk{b}{c}\n% \\end{tikzdisplay}\n\n\\begin{definition}\nLet $\\aPSS[\\aExp/\\aLoc]$ be the set $\\aPSS'$ where $\\aPS'\\in\\aPSS'$ whenever\nthere is $\\aPS\\in\\aPSS$ such that:\n\\begin{itemize}\n\\item $\\Event' = \\Event$,\n\\item if $\\bEv \\le \\aEv$ then $\\bEv \\le' \\aEv$, and\n\\item if $\\aEv \\gtN \\bEv$ then $\\aEv \\gtN' \\bEv$, and\n\\item if $\\labeling(\\aEv) = (\\bForm \\mid \\aAct)$ then $\\labeling'(\\aEv) = (\\bForm[\\aExp/\\aLoc] \\mid \\aAct)$.\n\\end{itemize}\nand similarly for $\\aPSS[\\aLoc/\\aReg]$.\n\\end{definition}\n\n\\begin{definition}\nLet $(\\aForm \\guard \\aPSS)$ be the subset of $\\aPSS$ such that $\\aPS\\in\\aPSS$ whenever:\n\\begin{itemize}\n\\item if $\\labeling(\\aEv) = (\\bForm \\mid \\aAct)$ then $\\aForm$ implies $\\bForm$.\n\\end{itemize}\n\\end{definition}\n\n\n\n\\begin{definition}\n\\label{def:x-closed}\n A 3-valued pomset is $\\aLoc$-closed if,\n for every $\\aEv\\in\\Event$:\n \\begin{itemize}\n \\item $\\aEv$ is independent of $\\aLoc$, and\n \\item if $\\aEv$ reads from $\\aLoc$, then there is a $\\bEv$ such that $\\aEv$ can read $\\aLoc$ from $\\bEv$.\n \\end{itemize}\n\\end{definition}\n\nThe definitions as they stand allow cycles in weak edges. This is necessary for examples such\nas $(\\aLoc\\GETS\\bLoc-1\\SEMI \\aLoc\\GETS1 \\PAR \\bLoc\\GETS\\aLoc-1\\SEMI\\bLoc\\GETS1)$\nwhich has execution:\n\\begin{tikzdisplay}[node distance=1em]\n \\event{ry1}{\\DR{\\bLoc}{1}}{}\n \\event{wx0}{\\DW{\\aLoc}{0}}{right=of ry1}\n \\event{wx1}{\\DW{\\aLoc}{1}}{right=of wx0}\n \\event{rx1}{\\DR{\\aLoc}{1}}{right=2.5em of wx1}\n \\event{wy0}{\\DW{\\bLoc}{0}}{right=of rx1}\n \\event{wy1}{\\DW{\\bLoc}{1}}{right=of wy0}\n \\wk{wx0}{wx1}\n \\wk{wy0}{wy1}\n \\po{ry1}{wx0}\n \\po{rx1}{wy0}\n \\rf{wx1}{rx1}\n \\rf[in=20,out=160]{wy1}{ry1}\n\\end{tikzdisplay}\nHowever, in order to model release/acquire fencing in transactions, we need to ban\nexecutions such as:\n\\begin{tikzdisplay}[node distance=1em]\n \\event{wx0}{\\DW{\\aLoc}{0}}{}\n \\event{wx1}{\\DW{\\aLoc}{1}}{below=7ex of wx0}\n \\event{wy1}{\\DC{}}{below right=of wx0}\n \\event{ry1}{\\DB{}}{right=2.5em of wy1}\n % \\event{wy1}{\\DWRel{\\bLoc}{1}}{below right=of wx0}\n % \\event{ry1}{\\DRAcq{\\bLoc}{1}}{right=2.5em of wy1}\n \\event{rx0}{\\DR{\\aLoc}{0}}{above right=of ry1}\n \\event{rx1}{\\DR{\\aLoc}{1}}{below=7ex of rx0}\n \\wk[out=-75,in=75]{wx0}{wx1}\n \\wk[out=105,in=-105]{wx1}{wx0}\n \\po{wx0}{wy1}\n \\po{wx1}{wy1}\n \\po{ry1}{rx0}\n \\po{ry1}{rx1}\n \\rf{wy1}{ry1}\n \\rf{wx0}{rx0}\n \\rf{wx1}{rx1}\n\\end{tikzdisplay}\nThe problem here is the weak cycle between $(\\DW\\aLoc0)$ and $(\\DW\\aLoc1)$,\nwhich according to Definition~\\ref{def:rf}, allows both $(\\DR\\aLoc0)$ and\n$(\\DR\\aLoc1)$, even though one of them must be a stale value. This can be addressed by\nrequiring $\\gtN$ to form a \\emph{per-location} partial order. This is a form\nof partial coherence, and can be strengthened to total coherence by requiring\n$\\gtN$ to be a per-location total order.\n\n\\begin{definition}\n A 3-valued pomset is \\emph{partially} (resp.~\\emph{totally}) $\\aLoc$-\\emph{coherent}\n if, when restricted to events which touch $\\aLoc$,\n $\\gtN$ forms a partial (resp.~total) order.\n\\end{definition}\n\n\\begin{definition}\nLet $(\\nu\\aLoc\\DOT\\aPSS)$ be the subset of $\\aPSS$ such that $\\aPS\\in\\aPSS$ whenever\n$\\aPS$ is $\\aLoc$-closed and partially $\\aLoc$-coherent.\n\\end{definition}\n\n\\subsection{Blockers}\n\\label{app:blockers}\n\nRecall the preliminary definition of reads-from in \\S\\ref{sec:pomsets}, which\ndefined an $\\aLoc$-blocker to be and event $\\cEv$ that writes to $\\aLoc$ such that\n$\\bEv \\lt \\cEv \\lt \\aEv$. Were we to adopt this definition, then concurrent\nthreads could turn events that were not $\\aLoc$-blockers into an\n$\\aLoc$-blocker, even if the new thread does not mention $\\aLoc$.\n\nTo see this, consider the program\n\\begin{math}\n (\n \\aLoc\\GETS1\\SEMI\n \\bLoc\\GETS\\aLoc\n \\PAR\n \\aLoc\\GETS\\cLoc+1\\SEMI\n \\bLoc\\GETS\\aLoc\n \\PAR\n \\IF{z=2}\\THEN\\aReg\\GETS\\aLoc\\FI\n )\n\\end{math}\nwith execution:\n\\begin{tikzdisplay}[node distance=1em]\n \\event{wx1}{\\DW{\\aLoc}{1}}{}\n \\event{rz1}{\\DR{\\cLoc}{1}}{right=of wx1}\n \\event{wx2}{\\DW{\\aLoc}{2}}{right=of rz1}\n \\event{rz2}{\\DR{\\cLoc}{2}}{right=of wx2}\n \\event{rx1}{\\DR{\\aLoc}{1}}{right=of rz2}\n \\event{rx1a}{\\DR{\\aLoc}{1}}{below=of wx1}\n \\event{wy1}{\\DW{\\bLoc}{1}}{below=of rx1a}\n \\event{rx2a}{\\DR{\\aLoc}{2}}{below=of wx2}\n \\event{wy2}{\\DW{\\bLoc}{2}}{below=of rx2a}\n \\rf{wx1}{rx1a}\n \\po{rx1a}{wy1}\n \\rf{wx2}{rx2a}\n \\po{rx2a}{wy2}\n \\po{rz1}{wx2}\n \\po{rz2}{rx1}\n \\rf[out=20,in=160]{wx1}{rx1}\n\\end{tikzdisplay}\nand the program\n\\begin{math}\n (\n \\cLoc\\GETS\\bLoc\\SEMI\n \\cLoc\\GETS\\bLoc\n )\n\\end{math}\nwith execution:\n\\begin{tikzdisplay}[node distance=1em]\n \\event{ry1}{\\DR{\\bLoc}{1}}{}\n \\event{wz1}{\\DW{\\cLoc}{1}}{right=of ry1}\n \\event{ry2}{\\DR{\\bLoc}{2}}{right=of wz1}\n \\event{wz2}{\\DW{\\cLoc}{2}}{right=of ry2}\n \\po{ry1}{wz1}\n \\po{ry2}{wz2}\n\\end{tikzdisplay}\nIf these are placed in parallel, then a possible execution is:\n\\begin{tikzdisplay}[node distance=1em]\n \\event{wx1}{\\DW{\\aLoc}{1}}{}\n \\event{rz1}{\\DR{\\cLoc}{1}}{right=of wx1}\n \\event{wx2}{\\DW{\\aLoc}{2}}{right=of rz1}\n \\event{rz2}{\\DR{\\cLoc}{2}}{right=of wx2}\n \\event{rx1}{\\DR{\\aLoc}{1}}{right=of rz2}\n \\event{rx1a}{\\DR{\\aLoc}{1}}{below=of wx1}\n \\event{wy1}{\\DW{\\bLoc}{1}}{below=of rx1a}\n \\event{rx2a}{\\DR{\\aLoc}{2}}{below=of wx2}\n \\event{wy2}{\\DW{\\bLoc}{2}}{below=of rx2a}\n \\rf{wx1}{rx1a}\n \\po{rx1a}{wy1}\n \\rf{wx2}{rx2a}\n \\po{rx2a}{wy2}\n \\po{rz1}{wx2}\n \\po{rz2}{rx1}\n \\event{ry1}{\\DR{\\bLoc}{1}}{below=of wy1}\n \\event{wz1}{\\DW{\\cLoc}{1}}{right=of ry1}\n \\event{ry2}{\\DR{\\bLoc}{2}}{below=of wy2}\n \\event{wz2}{\\DW{\\cLoc}{2}}{right=of ry2}\n \\po{ry1}{wz1}\n \\po{ry2}{wz2}\n \\rf{wy1}{ry1}\n \\rf{wz1}{rz1}\n \\rf{wy2}{ry2}\n \\rf{wz2}{rz2}\n\\end{tikzdisplay}\nand now the $(\\DW{\\aLoc}{2})$ event is an $\\aLoc$-blocker,\nso $(\\DR{\\aLoc}{1})$ cannot\nread from $(\\DW{\\aLoc}{1})$.\n\nIn the final definition of reads-from in \\S\\ref{sec:pomsets} we\nruled out $\\aLoc$-blockers by requiring that any\nevent $\\cEv$ that writes to $\\aLoc$ has\neither $\\cEv \\gtN \\bEv$ or $\\aEv \\gtN \\cEv$.\nWith this definition, in order for $(\\DR{\\aLoc}{1})$ to read from\n$(\\DW{\\aLoc}{1})$, we either need $(\\DW{\\aLoc}{2}) \\gtN (\\DW{\\aLoc}{1})$\nor $(\\DR{\\aLoc}{1}) \\gtN (\\DW{\\aLoc}{2})$, for example:\n\\begin{tikzdisplay}[node distance=1em]\n \\event{wx1}{\\DW{\\aLoc}{1}}{}\n \\event{rz1}{\\DR{\\cLoc}{1}}{right=of wx1}\n \\event{wx2}{\\DW{\\aLoc}{2}}{right=of rz1}\n \\event{rz2}{\\DR{\\cLoc}{2}}{right=of wx2}\n \\event{rx1}{\\DR{\\aLoc}{1}}{right=of rz2}\n \\event{rx1a}{\\DR{\\aLoc}{1}}{below=of wx1}\n \\event{wy1}{\\DW{\\bLoc}{1}}{below=of rx1a}\n \\event{rx2a}{\\DR{\\aLoc}{2}}{below=of wx2}\n \\event{wy2}{\\DW{\\bLoc}{2}}{below=of rx2a}\n \\rf{wx1}{rx1a}\n \\po{rx1a}{wy1}\n \\rf{wx2}{rx2a}\n \\po{rx2a}{wy2}\n \\po{rz1}{wx2}\n \\po{rz2}{rx1}\n \\rf[out=20,in=160]{wx1}{rx1}\n \\wk[out=-150,in=-30]{rx1}{wx2}\n \\wk{wy1}{wy2}\n\\end{tikzdisplay}\nthen putting this in parallel as before results in:\n\\begin{tikzdisplay}[node distance=1em]\n \\event{wx1}{\\DW{\\aLoc}{1}}{}\n \\event{rz1}{\\DR{\\cLoc}{1}}{right=of wx1}\n \\event{wx2}{\\DW{\\aLoc}{2}}{right=of rz1}\n \\event{rz2}{\\DR{\\cLoc}{2}}{right=of wx2}\n \\event{rx1}{\\DR{\\aLoc}{1}}{right=of rz2}\n \\event{rx1a}{\\DR{\\aLoc}{1}}{below=of wx1}\n \\event{wy1}{\\DW{\\bLoc}{1}}{below=of rx1a}\n \\event{rx2a}{\\DR{\\aLoc}{2}}{below=of wx2}\n \\event{wy2}{\\DW{\\bLoc}{2}}{below=of rx2a}\n \\rf{wx1}{rx1a}\n \\po{rx1a}{wy1}\n \\rf{wx2}{rx2a}\n \\po{rx2a}{wy2}\n \\po{rz1}{wx2}\n \\po{rz2}{rx1}\n \\rf[out=20,in=160]{wx1}{rx1}\n \\wk[out=-150,in=-30]{rx1}{wx2}\n \\wk{wy1}{wy2}\n \\event{ry1}{\\DR{\\bLoc}{1}}{below=of wy1}\n \\event{wz1}{\\DW{\\cLoc}{1}}{right=of ry1}\n \\event{ry2}{\\DR{\\bLoc}{2}}{below=of wy2}\n \\event{wz2}{\\DW{\\cLoc}{2}}{right=of ry2}\n \\po{ry1}{wz1}\n \\po{ry2}{wz2}\n \\rf{wy1}{ry1}\n \\rf{wz1}{rz1}\n \\rf{wy2}{ry2}\n \\rf{wz2}{rz2}\n \\wk[out=30,in=150]{wz1}{wz2}\n\\end{tikzdisplay}\nbut this is \\emph{not} a valid 3-valued pomset,\nsince $(\\DW{\\aLoc}{2}) \\lt (\\DR{\\aLoc}{1})$ but also $(\\DR{\\aLoc}{1}) \\gtN (\\DW{\\aLoc}{2})$,\nwhich is a contradiction.\n\n\n%\\input{logic}\n\n\n\\subsection{Release/acquire synchronization}\n\\label{app:ra}\n\n% In relaxed memory models, synchronization actions act as memory fences: that\n% is, they are a barrier to reordering memory accesses. In this section, we\n% present a simple model of release/acquire fencing. In\n% \\S\\ref{sec:transactions}, we show that this can be scaled up to a model of\n% transactional memory.\n\n% We assume there are sets $\\Rel$ and $\\Acq \\subseteq\\Act$. We say that\n% $\\aAct$ is a \\emph{release action} if $\\aAct\\in\\Rel$ and $\\aAct$ is an\n% \\emph{acquire action} if $\\aAct\\in\\Acq$.\n% In a pomset, a release event is one labeled with a release action,\n% and an acquire event is one labeled by an acquire action.\n% To give the semantics of fences, we add extra constraints\n% to Definition~\\ref{def:prefix} of prefixing %$\\aAct\\prefix\\aPSS$\n% (recalling that $\\cEv$ is the %$\\aAct$-labeled\n% event being introduced):\n% \\begin{itemize}\n% \\item $\\cEv \\le \\aEv$ whenever $\\cEv$ is an acquire event or $\\aEv$ is a release event, and\n% \\item if $\\cEv$ is an acquire event then $\\aEv$ is independent of $\\aLoc$,\n% for every $\\aLoc$.\n% \\end{itemize}\n% The first constraint ensures that events are ordered before a release and\n% after an acquire. The second constraint ensures that thread-local reads do\n% not cross acquire fences.\n\nWe can develop a simple model of release/acquire synchronization using the\nfollowing actions: % we will use\n% releasing writes and acquiring reads:\n\\begin{itemize}\n\\item $(\\DWRel{\\aLoc}{\\aVal})$, a release action that writes $\\aVal$ to $\\aLoc$, and\n\\item $(\\DRAcq{\\aLoc}{\\aVal})$, an acquire action that reads $\\aVal$ from $\\aLoc$.\n\\end{itemize}\nThe semantics of programs with releasing write and acquiring read are similar\nto regular write and read, with $\\DWRel\\aLoc\\aVal$ replacing\n$\\DW\\aLoc\\aVal$ and $\\DRAcq\\aLoc\\aVal$ replacing $\\DR\\aLoc\\aVal$:\n\\begin{eqnarray*}\n \\sem{\\aLoc^\\mRA\\GETS\\aExp\\SEMI \\aCmd} & = & \\textstyle\\bigcup_\\aVal\\; \\bigl((\\aExp=\\aVal) \\guard (\\DWRel\\aLoc\\aVal) \\prefix \\sem{\\aCmd}[\\aExp/\\aLoc]\\bigr) \\\\\n \\sem{\\aReg\\GETS\\aLoc^\\mRA\\SEMI \\aCmd} & = & \\textstyle\\bigcup_\\aVal\\; (\\DRAcq\\aLoc\\aVal) \\prefix \\sem{\\aCmd}[\\aLoc/\\aReg]\n\\end{eqnarray*}\n\nTo see the need for the first constraint on prefixing, consider the program:\n\\[\n \\VAR x\\GETS0\\SEMI \\VAR f\\GETS0\\SEMI\n (x\\GETS 1\\SEMI f^\\mRA\\GETS1 \\PAR r\\GETS f^\\mRA \\SEMI s\\GETS x)\n\\]\nThis has an execution:\n\\begin{tikzdisplay}[node distance=1em]\n \\event{wx0}{\\DW{x}{0}}{}\n \\event{wf0}{\\DW{f}{0}}{right=of wx0}\n \\event{wx1}{\\DW{x}{1}}{below=of wx0}\n \\event{wf1}{\\DWRel{f}{1}}{right=of wx1}\n \\event{rf1}{\\DRAcq{f}{1}}{right=2.5em of wf1}\n \\event{rx1}{\\DR{x}{1}}{right=of rf1}\n \\po{wx0}{wf1}\n \\po{wf0}{wf1}\n \\po{wx1}{wf1}\n \\po{rf1}{rx1}\n \\rf{wf1}{rf1}\n \\rf[out=20,in=160]{wx1}{rx1}\n \\wk{wx0}{wx1}\n\\end{tikzdisplay}\nbut \\emph{not}:\n\\begin{tikzdisplay}[node distance=1em]\n \\event{wx0}{\\DW{x}{0}}{}\n \\event{wf0}{\\DW{f}{0}}{right=of wx0}\n \\event{wx1}{\\DW{x}{1}}{below=of wx0}\n \\event{wf1}{\\DWRel{f}{1}}{right=of wx1}\n \\event{rf1}{\\DRAcq{f}{1}}{right=2.5em of wf1}\n \\event{rx0}{\\DR{x}{0}}{right=of rf1}\n \\po{wx0}{wf1}\n \\po{wf0}{wf1}\n \\po{wx1}{wf1}\n \\po{rf1}{rx1}\n \\rf{wf1}{rf1}\n \\rf[out=-20,in=160]{wx0}{rx0}\n \\wk{wx0}{wx1}\n\\end{tikzdisplay}\nsince $(\\DW x0) \\gtN (\\DW x1) \\lt (\\DR x0)$, so this pomset does not satisfy the\nrequirements to be $x$-closed.\nIf we replace the release\nwith a plain write, then the outcome $(\\DRAcq f1)$ and $(\\DR x0)$ is possible:\n\\begin{tikzdisplay}[node distance=1em]\n \\event{wx0}{\\DW{x}{0}}{}\n \\event{wf0}{\\DW{f}{0}}{right=of wx0}\n \\event{wx1}{\\DW{x}{1}}{below=of wx0}\n \\event{wf1}{\\DW{f}{1}}{right=of wx1}\n \\event{rf1}{\\DRAcq{f}{1}}{right=2.5em of wf1}\n \\event{rx0}{\\DR{x}{0}}{right=of rf1}\n \\wk{wf0}{wf1}\n \\po{rf1}{rx0}\n \\rf{wf1}{rf1}\n \\rf[out=-20,in=160]{wx0}{rx0}\n \\wk{wx0}{wx1}\n\\end{tikzdisplay}\nsince no order is required between $(\\DW x1)$ and $(\\DW f1)$. \nSymmetrically, if we replace the acquire of the original program\nwith a plain read, then the outcome $(\\DR f1)$ and $(\\DR x0)$ is possible.\n% \\begin{verbatim}\n% x := 0; rel f := 0; ||\n% acq r := f; if (r == 0) { x := x+1; rel f := 1; } ||\n% acq s := f; if (r == 1) { x := x+1; rel f := 2; }\n% \\end{verbatim}\n% This has an execution:\n% \\begin{tikzdisplay}[node distance=1em]\n% \\event{wx0}{\\DW{x}{0}}{}\n% \\event{wf0}{\\DWRel{f}{0}}{below=of wx0}\n% \\event{rf0}{\\DRAcq{f}{0}}{right=2.5 em of wx0}\n% \\event{rx0}{\\DR{x}{0}}{below=of rf0}\n% \\event{wx1}{\\DW{x}{1}}{below=of rx0}\n% \\event{wf1}{\\DWRel{f}{1}}{below=of wx1}\n% \\event{rf1}{\\DRAcq{f}{1}}{right=2.5 em of rf0}\n% \\event{rx1}{\\DR{x}{1}}{below=of rf1}\n% \\event{wx2}{\\DW{x}{2}}{below=of rx1}\n% \\event{wf2}{\\DWRel{f}{2}}{below=of wx2}\n% \\po{wx0}{wf0}\n% \\po{rf0}{rx0}\n% \\po{rx0}{wx1}\n% \\po{wx1}{wf1}\n% \\po{rf1}{rx1}\n% \\po{rx1}{wx2}\n% \\po{wx2}{wf2}\n% \\rf{wf0}{rf0}\n% \\rf{wx0}{rx0}\n% \\rf{wf1}{rf1}\n% \\rf{wx1}{rx1}\n% \\end{tikzdisplay}\n% but \\emph{not}:\n% \\begin{tikzdisplay}[node distance=1em]\n% \\event{wx0}{\\DW{x}{0}}{}\n% \\event{wf0}{\\DWRel{f}{0}}{below=of wx0}\n% \\event{rf0}{\\DRAcq{f}{0}}{right=2.5 em of wx0}\n% \\event{rx0}{\\DR{x}{0}}{below=of rf0}\n% \\event{wx1}{\\DW{x}{1}}{below=of rx0}\n% \\event{wf1}{\\DWRel{f}{1}}{below=of wx1}\n% \\event{rf1}{\\DRAcq{f}{1}}{right=2.5 em of rf0}\n% \\event{rx0b}{\\DR{x}{0}}{below=of rf1}\n% \\event{wx1b}{\\DW{x}{1}}{below=of rx0b}\n% \\event{wf2}{\\DWRel{f}{2}}{below=of wx1b}\n% \\po{wx0}{wf0}\n% \\po{rf0}{rx0}\n% \\po{rx0}{wx1}\n% \\po{wx1}{wf1}\n% \\po{rf1}{rx0b}\n% \\po{rx0b}{wx1b}\n% \\po{wx1b}{wf2}\n% \\rf{wf0}{rf0}\n% \\rf{wx0}{rx0}\n% \\rf{wf1}{rf1}\n% \\rf{wx0}{rx0b}\n% \\end{tikzdisplay}\n% since $(\\DW x0) \\lt (\\DW x1) \\lt (\\DR x0)$, so this pomset does not satisfy the\n% requirements to be an rf-pomset.\n\n% The notion rf-pomset is sufficient to capture hardware models and\n% release/acquire access in C++, where reads-from implies happens-before\n% \\cite{alglave}. To model C++ relaxed access, it\n% would be necessary to use a more general notion of rf-pomset, where\n% $(\\bEv,\\aLoc,\\aEv) \\in \\RF$ does not necessarily imply $\\bEv \\lt \\aEv$, instead\n% requiring that $(\\mathord\\lt \\cup \\mathord\\RF)$ be acyclic.\n\n%% To see the need for the second constraint on prefixing, consider the program:\n%% \\begin{displaymath}\n%% (\n%% x\\GETS1\\SEMI\n%%^\\mRA f\\GETS 1\\SEMI\n%%^\\mRA r\\GETS f\\SEMI\n%% y\\GETS x\n%% )\n%% \\PAR\n%% (\n%%^\\mRA s\\GETS f\\SEMI\n%% x\\GETS2\\SEMI\n%%^\\mRA f\\GETS 2\\SEMI\n%% )\n%% \\end{displaymath}\n%% whose semantics includes execution:\n%% \\begin{displaymath}\n%% \\begin{tikzpicture}[node distance=1em]\n%% \\event{wx1}{\\DW{x}{1}}{}\n%% \\event{wf1}{\\DWRel{f}{1}}{right=of wx1}\n%% \\event{rf1}{\\DRAcq{f}{2}}{below=of wf1}\n%% \\event{wx2}{\\DW{x}{2}}{right=of rf1}\n%% \\event{wf2}{\\DWRel{f}{1}}{right=of wx2}\n%% \\event{rf2}{\\DRAcq{f}{2}}{above=of wf2}\n%% \\event{wy1}{\\DW{y}{1}}{right=of rf2}\n%% \\po{wx1}{wf1}\n%% \\rf{wf1}{rf1}\n%% \\po{rf1}{wx2}\n%% \\po{wx2}{wf2}\n%% \\rf{wf2}{rf2}\n%% \\po{rf2}{wy1}\n%% \\end{tikzpicture}\n%% \\end{displaymath}\n%% This execution exists because\n%% \\begin{math}\n%% \\sem{y\\GETS x}\n%% \\end{math}\n%% includes\n%% \\begin{math}\n%% (x=1\\mid \\DW{y}{1})\n%% \\end{math}\n%% and the precondition $x=1$ is fulfilled by the preceding write $x\\GETS1$. In\n%% implementation term, this execution is reading $1$ from $x$ in a ``stale\n%% cache.'' The alternative execution that attempts to read $1$ from the $x$ in\n%% ``main memory,'' has an explicit $(\\DR{x}{1})$ between $(\\DRAcq{f}{2})$ and\n%% $(\\DW{y}{1})$, and thus will fail to be $x$-closed.\n\n%% To prevent thread-local writes from crossing release/acquire pairs, we\n%% require that pomsets in the semantics of acquire have no free locations.\n%% This corresponds to the idea that acquires flush the read cache, and\n%% therefore reads must reload values from main memory after an acquire.\n\n% In addition, we must change the semantics of write from\n% \\S\\ref{sec:sets-of-pomsets} to ensure that an action is generated for every\n% write that might be published by a subsequent release action.\n% Formally, $\\sem{\\aLoc\\GETS\\aExp\\SEMI \\aCmd}$ only includes pomsets\n% from $\\sem{\\aCmd}[\\aExp/\\aLoc]$ that contain a write to\n% $\\aLoc$ that is not preceded by a release.\n\n\n\\subsection{Relaxed memory}\n\\label{sec:relaxed-memory}\n\nIn \\S\\ref{sec:info-flow-attack} we presented an information flow attack\non relaxed memory, similar to Spectre in that it relies on speculative\nevaluation. Unlike Spectre it does not depend on timing attacks,\nbut instead is based on the sensitivity of relaxed memory to data\ndependencies. % For this reason, we present a simple model of relaxed\n% memory, which is strong enough to capture this attack.\n\nOur model includes concurrent memory accesses, which can introduce concurrent\nreads-from. \nSince we are allowing events to be partially ordered, this gives a simple\nmodel of relaxed memory. For example an independent read independent write\n(IRIW) example is:\n\\[\\begin{array}{l}\n x\\GETS0\\SEMI x\\GETS x+1\n \\PAR\n y\\GETS0\\SEMI y\\GETS y+1\n\\\\{}\n \\PAR\n r_1\\GETS x\\SEMI r_2\\GETS y\n \\PAR\n s_1\\GETS y\\SEMI s_2\\GETS x\n\\end{array}\\]\nwhich includes the execution:\n\\begin{tikzdisplay}[node distance=1em]\n \\event{wx0}{\\DW{x}{0}}{}\n \\event{wx1}{\\DW{x}{1}}{right=of wx0}\n \\event{wy0}{\\DW{y}{0}}{right=2.5em of wx1}\n \\event{wy1}{\\DW{y}{1}}{right=of wy0}\n \\event{ry1}{\\DR{y}{1}}{below=4ex of wx0}\n \\event{rx0}{\\DR{x}{0}}{right=of ry1}\n \\event{rx1}{\\DR{x}{1}}{right=2.5 em of rx0}\n \\event{ry0}{\\DR{y}{0}}{right=of rx1}\n \\rf{wx1}{rx1}\n \\rf{wy0}{ry0}\n \\rf[out=210,in=30]{wy1}{ry1}\n \\rf{wx0}{rx0}\n \\wk{rx0}{wx1}\n \\wk{ry0}{wy1}\n\\end{tikzdisplay}\nThis model does not introduce thin-air reads (TAR).\nFor example the TAR pit\n\\((\n x\\GETS y \\PAR y \\GETS x\n)\\)\nfails to produce a value for $x$ from thin air\nsince this produces a cycle in $\\le$, as shown on the left below:\n\\begin{align*}\n\\begin{tikzpicture}[node distance=1em]\n \\event{ry42}{\\DR{y}{42}}{}\n \\event{wx42}{\\DW{x}{42}}{below=of ry42}\n \\event{rx42}{\\DR{x}{42}}{right=2.5em of ry42}\n \\event{wy42}{\\DW{y}{42}}{below=of rx42}\n \\po{ry42}{wx42}\n \\po{rx42}{wy42}\n \\rf{wx42}{rx42}\n \\rf{wy42}{ry42}\n\\end{tikzpicture}\n&&\n\\begin{tikzpicture}[node distance=1em]\n \\event{ry1}{\\DR{y}{1}}{}\n \\event{wx1}{\\DW{x}{1}}{below=of ry1}\n \\event{rx1}{\\DR{x}{1}}{right=2.5em of ry1}\n \\event{wy1}{\\DW{y}{1}}{below=of rx1}\n \\po{ry1}{wx1}\n \\rf{wx1}{rx1}\n \\rf{wy1}{ry1}\n\\end{tikzpicture}\n\\end{align*}\nThis cycle can be broken by removing a dependency. For example\n\\((\n x\\GETS y \\PAR r\\GETS x\\SEMI y \\GETS r+1-r\n)\\)\nhas the execution on the right above.\n% \\begin{tikzdisplay}[node distance=1em]\n% \\event{ry1}{\\DR{y}{1}}{}\n% \\event{wx1}{\\DW{x}{1}}{below=of ry1}\n% \\event{rx1}{\\DR{x}{1}}{right=2.5em of ry1}\n% \\event{wy1}{\\DW{y}{1}}{below=of rx1}\n% \\po{ry1}{wx1}\n% \\rf{wx1}{rx1}\n% \\rf{wy1}{ry1}\n% \\end{tikzdisplay}\nNote that $(\\DR x1) \\not\\le (\\DW y1)$, so this does not introduce a cycle.\n\nAlthough it is not the primary focus of this paper, our model may be an\nattractive model of relaxed memory. Many prior models either permit\nthin-air executions that our model forbids or forbid desirable executions\nthat our model permits.\n%% In \\S\\ref{sec:logic}, we develop a logic which allows us to prove that our\n%% semantics forbids thin air examples that are permitted by prior speculative\n%% models\n%% \\cite{Manson:2005:JMM:1047659.1040336,Jagadeesan:2010:GOS:2175486.2175503,DBLP:conf/popl/KangHLVD17}.\n% Our model passes all of the causality test cases\n% \\cite{PughWebsite}.\n%% Significantly, this\n%% includes test case 9, which is forbidden by \\cite{DBLP:conf/lics/JeffreyR16},\n%% one of the few models that disallows the thin air example from\n%% \\S\\ref{sec:logic}. We present this test case in the appendix, where we also\n%% discuss the thread inlining examples from\n%% \\cite{Manson:2005:JMM:1047659.1040336}.\n\n% In \\refapp{logic}, we present a variant of the TAR-pit\n% example %from \\S\\ref{sec:relaxed-memory}\n% that is allowed under prior speculative semantics\n% \\cite{Manson:2005:JMM:1047659.1040336,Jagadeesan:2010:GOS:2175486.2175503,DBLP:conf/popl/KangHLVD17}.\n% We develop a logic that allows us to prove that the problematic execution is\n% forbidden in our model. \\citet{DBLP:conf/esop/BattyMNPS15} showed that the\n% thin-air problem has no per-candidate-execution solution for C++. This\n% result does not apply to our model, which has a different notion of\n% dependency.\n\n% as the semantics of a conditional can depend on the semantics\n% of both branches.\n\n\\citet{PughWebsite} developed a set of twenty {causality test cases} in the\nprocess of revising the Java Memory Model (JMM)\n\\cite{Manson:2005:JMM:1047659.1040336}. Using hand calculation, we have\nconfirmed that our model gives the desired result for all twenty cases,\nunrolling loops as necessary. Our model also gives the desired results for\nall of the examples in \\citet[\\textsection 4]{DBLP:conf/esop/BattyMNPS15} and\nall but one in \\citet[\\textsection 5.3]{SevcikThesis}:\nredundant-write-after-read-elimination fails for any\nsensible non-coherent semantics. Our model agrees with the JMM on the\n``surprising and controversial behaviors'' of \\citet[\\textsection\n8]{Manson:2005:JMM:1047659.1040336}, and thus fails to validate thread\ninlining.\n% In \\refapp{tc}, we discuss three of the causality test cases and the thread\n% inlining example from \\cite{Manson:2005:JMM:1047659.1040336}.% In presenting the\n% examples, we unroll loops, correct typos and simplify the code. \n\n% \\subsection{Causality test cases}\n% \\label{app:tc}\n\n% \\citet{PughWebsite} developed a set of twenty {causality test cases} in the\n% process of revising the Java Memory Model (JMM)\n% \\cite{Manson:2005:JMM:1047659.1040336}. Using hand calculation, we have\n% confirmed that our model gives the desired result for all twenty cases,\n% unrolling loops as necessary. Our model also gives the desired results for\n% all of the examples in \\citet[\\textsection 4]{DBLP:conf/esop/BattyMNPS15} and\n% all but one in \\citet[\\textsection 5.3]{SevcikThesis}:\n% redundant-write-after-read-elimination fails for any\n% sensible non-coherent semantics. Our model agrees with the JMM on the\n% ``surprising and controversial behaviors'' of \\citet[\\textsection\n% 8]{Manson:2005:JMM:1047659.1040336}, and thus fails to validate thread\n% inlining.\n\n\\section{UNUSED: appendix stuff}\n\n%In this section,\nWe now discuss three of the causality test cases, as well as the thread\ninlining from \\cite{Manson:2005:JMM:1047659.1040336}. In presenting the\nexamples, we unroll loops, correct typos and simplify the code. \n\n\\subsubsection{Causality test case 8}\n\nTest case 8 asks whether:\n\\begin{displaymath}\n \\VAR x\\GETS 0\\SEMI\n \\VAR y\\GETS 0\\SEMI\n (\\IF{x<2}\\THEN y\\GETS 1\\FI \n \\PAR\n x\\GETS y)\n\\end{displaymath}\nmay read $1$ for both $x$ and $y$. This behavior is allowed, since\n``interthread analysis could determine that $x$ and $y$ are always either $0$\nor $1$.'' This breaks the dependency between the read of $x$ and the write\nto $y$ in the first thread, allowing the write to be moved earlier.\n\nThe semantics of TC8 includes\n\\begin{tikzdisplay}[node distance=1em]\n \\event{ix}{\\DW{x}{0}}{}\n \\event{iy}{\\DW{y}{0}}{right=of ix}\n \\event{rx1}{\\DR{x}{1}}{right=2.1em of iy}\n \\event{wy1}{\\DW{y}{1}}{right=of rx1}\n \\event{ry1}{\\DR{y}{1}}{right=2.1em of wy1}\n \\event{wx1}{\\DW{x}{1}}{right=of ry1}\n \\po{ry1}{wx1}\n \\po[out=30,in=150]{ix}{rx1}\n \\rf[in=-25,out=-160]{wx1}{rx1}\n \\rf[out=20,in=160]{wy1}{ry1}\n \\wk[out=-25,in=-150]{ix}{wx1}\n \\wk[out=25,in=155]{iy}{wy1}\n\\end{tikzdisplay}\nWhere we require $(\\DW{x}{0})\\lt(\\DR{x}{1})$ but not $(\\DR{x}{1})\\lt(\\DW{y}{1})$.\nTo see why this execution exists, consider the left thread with syntax sugar\nremoved:\n\\begin{displaymath}\n r\\GETS x\\SEMI \\IF{r<2}\\THEN y\\GETS 1\\FI\n\\end{displaymath}\n\\begin{math}\n \\sem{\\IF{r<2}\\THEN y\\GETS 1\\FI}\n\\end{math}\nincludes\n\\begin{math}\n (r<2\\mid\\DW{y}{1}).\n\\end{math}\n% \\begin{tikzdisplay}[node distance=1em]\n% \\event{wy1}{r<2\\mid\\DW{y}{1}}{}\n% \\end{tikzdisplay}\nThus, by Figure~\\ref{fig:programs}, \n\\begin{math}\n \\sem{r\\GETS x\\SEMI \\IF{r<2}\\THEN y\\GETS 1\\FI}\n\\end{math}\nincludes\n\\begin{math}\n (\\DR{x}{1}) \\prefix (r<2\\mid\\DW{y}{1})[x/r]\n\\end{math}\nwhich simplifies to\n\\begin{math}\n (\\DR{x}{1}) \\prefix (x<2\\mid\\DW{y}{1}),\n\\end{math}\nwhich, by Definition~\\ref{def:prefix}, includes:\n\\begin{tikzdisplay}[node distance=1em,baselinecenter]\n \\event{rx1}{\\DR{x}{1}}{}\n \\event{wy1}{x<2\\mid\\DW{y}{1}}{right=of rx1}\n \\end{tikzdisplay}\nHere we have used the \\textsc{[non-ordering read]} clause of Definition~\\ref{def:prefix}:\n``$\\bForm'$ implies $\\bForm[\\aVal/\\aLoc] \\land \\bForm$, if $\\aAct$ reads $\\aVal$ from $\\aLoc$,''\nwhere $a=(\\DR{x}{1})$, $\\bForm=\\bForm'=(x<2)$. We can use this case since\n$x<2$ implies $1<2\\land x<2$.\n\nPrefixing with $(\\DW{x}{0})$ allows us to discharge the assumption $x<2$,\narriving at:\n\\begin{tikzdisplay}[node distance=1em,baselinecenter]\n \\event{ix}{\\DW{x}{0}}{}\n \\event{rx1}{\\DR{x}{1}}{right=2.5 em of ix}\n \\event{wy1}{\\DW{y}{1}}{right=of rx1}\n \\po{ix}{rx1}\n \\end{tikzdisplay}\nHere we have used the \\textsc{[ordering read]}\nclause of \\ref{def:prefix}:\n``$\\bForm'$ implies $\\bForm[\\aVal/\\aLoc]$, if $\\aAct$ reads $\\aVal$ from $\\aLoc$ and $\\cEv\\lt'\\aEv$,''\nwhere $a=(\\DW{x}{0})$, $\\bForm=(x<2)$ and $\\bForm'=\\TRUE$. As long as\nrequire\n\\begin{math}\n (\\DW{x}{0})\\lt\n (\\DR{x}{1}),\n\\end{math}\nwe can use this case since $\\TRUE$ implies $0<2$.\n\n\\subsubsection{Causality test case 9}\n\nTest case 9 asks whether:\n\\begin{displaymath}\n \\VAR x\\GETS 0\\SEMI\n \\VAR y\\GETS 0\\SEMI\n (\\IF{x<2}\\THEN y\\GETS 1\\FI \n \\PAR\n x\\GETS y\n \\PAR\n y\\GETS 2\\SEMI)\n\\end{displaymath}\nmay read $1$ for both $x$ and $y$. This behavior is also allowed. This is\n``similar to test case $8$, except that $x$ is not always $0$ or\n$1$. However, a compiler might determine that the read of $x$ by thread $1$\nwill never see the write by thread $3$ (perhaps because thread $3$ will be\nscheduled after thread $1$)''\n\nReasoning as for test case 8, the semantics of test case 9 includes:\n\\begin{tikzdisplay}[node distance=1em]\n \\event{ix}{\\DW{x}{0}}{}\n \\event{iy}{\\DW{y}{0}}{right=of ix}\n \\event{rx1}{\\DR{x}{1}}{right=2.2 em of iy}\n \\event{wy1}{\\DW{y}{1}}{right=of rx1}\n \\event{ry1}{\\DR{y}{1}}{right=2.2em of wy1}\n \\event{wx1}{\\DW{x}{1}}{right=of ry1}\n \\event{wx2}{\\DW{x}{2}}{below=3ex of $(ix)!0.5!(iy)$}%{right=2.5em of wx1}\n \\po{ry1}{wx1}\n \\po[out=30,in=150]{ix}{rx1}\n \\rf[in=-25,out=-160]{wx1}{rx1}\n \\rf[out=20,in=160]{wy1}{ry1}\n \\wk[out=-25,in=-150]{ix}{wx1}\n \\wk[out=25,in=155]{iy}{wy1}\n \\wk{ix}{wx2}\n % \\wk[out=-25,in=-150]{ix}{wx2}\n\\end{tikzdisplay}\n\nThus, with respect to the introduction of new threads, our model appears to\nbe more robust than the event structures semantics of\n\\cite{DBLP:conf/lics/JeffreyR16}, which fails on this test case.\n\n\\subsubsection{Causality test case 14}\n\nTest case 14 asks whether:\n\\begin{multline*}\n \\VAR a\\GETS 0\\SEMI\n \\VAR b\\GETS 0\\SEMI\n \\VAR y\\GETS 0\\SEMI\\\\[-.5ex]\n (\\IF{a}\\THEN b\\GETS 1\\ELSE y\\GETS 1\\FI \n \\PAR\\\\[-.5ex]\n \\WHILE(y+b==0) \\THEN\\SKIP\\FI\\; a\\GETS1)\n\\end{multline*}\nmay read $1$ for $a$ and $b$, yet $0$ for $y$. Here $a$ and $b$ are regular\nvariables and $y$ is volatile, which is equivalent to release/acquire in this\nexample. This behavior is also disallowed, since ``in all sequentially\nconsistent executions, [the read of $a$ gets $0$] and the program is\ncorrectly synchronized. Since the program is correctly synchronized in all SC\nexecutions, no non-SC behaviors are allowed.''\n\nUnrolling the loop once, we have:\n\\begin{multline*}\n \\VAR a\\GETS 0\\SEMI\n \\VAR b\\GETS 0\\SEMI\n \\VAR y\\GETS 0\\SEMI\\\\[-.5ex]\n (\\IF{a}\\THEN b\\GETS 1\\ELSE y\\GETS 1\\FI \n \\PAR\\\\[-.5ex]\n \\IF{y\\lor b}\\THEN a\\GETS 1\\FI)\n\\end{multline*}\nWe argue that any execution with $(\\DR{a}{1})$, $(\\DR{b}{1})$, and\n$(\\DR{y}{0})$ must be cyclic. The closure requirements require that\n\\begin{math}\n (\\DW{a}{1})\\lt(\\DR{a}{1})\n \\;\\text{and}\\;\n (\\DR{b}{1})\\lt(\\DR{b}{1}).\n\\end{math}\nIgnoring initialization, least ordered execution that includes all of these\nactions is:\n\\begin{tikzdisplay}[node distance=1em]\n \\event{ra1}{\\DR{a}{1}}{}\n \\event{wb1}{\\DW{b}{1}}{below=of ra1}\n \\nonevent{wy1}{\\DW{y}{1}}{left=of wb1}\n \\event{rb1}{\\DR{b}{1}}{right=4.5em of ra1}\n \\event{ry0}{\\DR{y}{0}}{right=of rb1}\n \\event{wa1}{\\DW{a}{1}}{below=of rb1}\n \\po{ra1}{wb1}\n \\po{rb1}{wa1}\n \\rf{wa1}{ra1}\n \\rf{wb1}{rb1}\n\\end{tikzdisplay}\nwhere the read of $a$ is ordering for $(\\DW{b}{1})$ but\nnot $(\\DW{y}{1})$, and the read of $b$ is ordering for $(\\DW{a}{1})$ but the\nread of $y$ is not. $(\\DW{y}{1})$ is crossed out, since its\nprecondition must imply $(\\lnot a)[1/a]$, which is equivalent to $\\FALSE$.\nTo avoid order from $(\\DR{y}{0})$ to $(\\DW{a}{1})$, we\nhave strengthened the predicate on $(\\DW{a}{1})$ from $(y\\lor b)$ to\n$(y=0\\land b=1)$. Note that we cannot use this trick symmetrically to remove\nthe order from $(\\DR{b}{1})$ to $(\\DW{a}{1})$, since $b=1$ does not follow\nfrom the initialization of $b$.\n\n\n\\subsubsection{Thread inlining}\n\nOne property one could ask of a model of shared memory is thread\ninlining: any execution of $\\sem{P\\SEMI Q}$ is an execution of $\\sem{P\n \\PAR Q}$. This is \\emph{not} a goal of our model, and indeed is not\nsatisfied, due to the different semantics of concurrent and sequential\nmemory accesses. We demonstrate this by considering an example from\nthe Java Memory Model~\\cite{Manson:2005:JMM:1047659.1040336}, which shows that Java does not\nsatisfy thread inlining either.\n\nThe lack of thread inlining is related to the different dependency\nrelations introduced by sequential and concurrent access.\nRecall from \\S\\ref{sec:sequential-memory} that the program\n\\verb`(x := 0; y := x+1;)` has execution:\n\\begin{tikzdisplay}[node distance=1em]\n \\event{wx0}{\\DW{x}{0}}{}\n \\event{wy1}{\\DW{y}{1}}{right=of wx0}\n\\end{tikzdisplay}\nbut that \\verb`(x := 1; || y := x+1;)` has:\n\\begin{tikzdisplay}[node distance=1em]\n \\event{wx1}{\\DW{x}{1}}{}\n \\event{rx1}{\\DR{x}{1}}{right=2.5em of wx1}\n \\event{wy2}{\\DW{y}{2}}{right=of rx1}\n \\rf{wx1}{rx1}\n \\po{rx1}{wy2}\n\\end{tikzdisplay}\nThat is, in the sequential case there is no dependency from the\nwrite of $x$ to the write of $y$, but in the concurrent case there\nis such a dependency.\n\nThis can be used to construct a counter-example to thread inlining, based on~\\cite[Ex~11]{Manson:2005:JMM:1047659.1040336}:\n\\begin{verbatim}\n x := 0; if (x == 1) { z := 1; } else { x := 1; } || y := x; || x := y;\n\\end{verbatim}\nThis has no execution containing $(\\DW z1)$. Any attempt to build such an execution\nresults in a cycle:\n\\begin{tikzdisplay}[node distance=1em]\n \\event{rx1a}{\\DR{x}{1}}{}\n \\event{wz1}{\\DW{z}{1}}{right=of rx1a}\n \\nonevent{wx1a}{\\DW{x}{1}}{right=of wz1}\n \\event{rx1b}{\\DR{x}{1}}{below=of wx1a}%{right=2.5em of wx1a}\n \\event{wy1}{\\DW{y}{1}}{right=of rx1b}\n \\event{ry1}{\\DR{y}{1}}{right=2.5em of wy1}\n \\event{wx1b}{\\DW{x}{1}}{right=of ry1}\n \\po{rx1a}{wz1}\n \\po[out=25, in=150]{rx1a}{wx1a}\n \\po{rx1b}{wy1}\n \\po{ry1}{wx1b}\n \\rf{wy1}{ry1}\n \\rf[out=160, in=30]{wx1b}{rx1a}\n \\rf[out=160, in=30]{wx1b}{rx1b}\n\\end{tikzdisplay}\nInlining the thread \\verb|(y := x)| gives~\\cite[Ex~12]{Manson:2005:JMM:1047659.1040336}:\n\\begin{verbatim}\n x := 0; if (x == 1) { z := 1; } else { x := 1; } y := x; || x := y;\n\\end{verbatim}\nwith execution:\n\\begin{tikzdisplay}[node distance=1em]\n \\event{rx1a}{\\DR{x}{1}}{}\n \\event{wz1}{\\DW{z}{1}}{right=of rx1a}\n \\nonevent{wx1a}{\\DW{x}{1}}{right=of wz1}\n \\event{wy1}{\\DW{y}{1}}{right=of wx1a}\n \\event{ry1}{\\DR{y}{1}}{right=2.5em of wy1}\n \\event{wx1b}{\\DW{x}{1}}{right=of ry1}\n \\po{rx1a}{wz1}\n \\po[out=25, in=150]{rx1a}{wx1a}\n \\po{ry1}{wx1b}\n \\rf{wy1}{ry1}\n \\rf[out=160, in=30]{wx1b}{rx1a}\n\\end{tikzdisplay}\nTo see why this execution exists, consider the program fragment:\n\\begin{verbatim}\n if (x == 1) { z := 1; } else { x := 1; } y := x;\n\\end{verbatim}\nRemoving the syntax sugar, this is:\n\\begin{verbatim}\n r1 := x; if (r1 == 1) {\n z := 1; r2 := x; y := r2; skip\n } else {\n x := 1; r3 := x; y := r3; skip\n }\n\\end{verbatim}\nNow, $\\sem{z := 1\\SEMI r_2 := x\\SEMI y := r_2\\SEMI \\SKIP}$\nincludes pomset:\n\\begin{tikzdisplay}[node distance=1em]\n \\event{wz1}{r_1=1 \\mid \\DW{z}{1}}{}\n \\event{wy1}{r_1=x=1 \\mid \\DW{y}{1}}{right=of wz1}\n\\end{tikzdisplay}\nand $\\sem{x := 1\\SEMI r_3 := x\\SEMI y := r_3\\SEMI \\SKIP}$\nincludes pomset:\n\\begin{tikzdisplay}[node distance=1em]\n \\event{wx1a}{r_1\\neq 1 \\mid \\DW{x}{1}}{}\n \\event{wy1}{r_1\\neq 1 \\mid \\DW{y}{1}}{right=of wx1a}\n\\end{tikzdisplay}\nso $\\sem{\\IF{r_1 = 1} \\THEN z := 1\\SEMI r_2 := x\\SEMI y := r_2\\SEMI \\SKIP \\ELSE x := 1\\SEMI r_3 := x\\SEMI y := r_3\\SEMI \\SKIP \\FI}$ includes:\n\\begin{tikzdisplay}[node distance=1em]\n \\event{wz1}{r_1=1 \\mid \\DW{z}{1}}{}\n \\event{wx1a}{r_1\\neq1 \\mid \\DW{x}{1}}{right=of wz1}\n \\event{wy1}{(r_1=x=1) \\lor (r_1\\neq1) \\mid \\DW{y}{1}}{below=3ex of $(wz1)!0.5!(wx1a)$}\n\\end{tikzdisplay}\nwhich means $\\sem{\\IF{r_1 = 1} \\THEN z := 1\\SEMI r_2 := x\\SEMI y := r_2\\SEMI \\SKIP \\ELSE x := 1\\SEMI r_3 := x\\SEMI y := r_3\\SEMI \\SKIP \\FI}[x/r_1]$ includes:\n\\begin{tikzdisplay}[node distance=1em]\n \\event{wz1}{x=1 \\mid \\DW{z}{1}}{}\n \\event{wx1a}{x\\neq1 \\mid \\DW{x}{1}}{right=of wz1}\n \\event{wy1}{(x=x=1) \\lor (x\\neq1)) \\mid \\DW{y}{1}}{below=3ex of $(wz1)!0.5!(wx1a)$}%{right=of wx1a}\n\\end{tikzdisplay}\nNow $(x=x=1) \\lor (x\\neq1)$ is a tautology, so this is just:\n\\begin{tikzdisplay}[node distance=1em]\n \\event{wz1}{x=1 \\mid \\DW{z}{1}}{}\n \\event{wx1a}{x\\neq1 \\mid \\DW{x}{1}}{right=of wz1}\n \\event{wy1}{\\DW{y}{1}}{right=of wx1a}\n\\end{tikzdisplay}\nand so $\\sem{r_1 \\GETS x\\SEMI \\IF{r_1 = 1} \\THEN z := 1\\SEMI r_2 := x\\SEMI y := r_2\\SEMI \\SKIP \\ELSE x := 1\\SEMI r_3 := x\\SEMI y := r_3\\SEMI \\SKIP \\FI}$ includes:\n\\begin{tikzdisplay}[node distance=1em]\n \\event{rx1a}{\\DR{x}{1}}{}\n \\event{wz1}{1=1 \\mid \\DW{z}{1}}{right=of rx1a}\n \\event{wx1a}{1\\neq1 \\mid \\DW{x}{1}}{right=of wz1}\n \\event{wy1}{\\DW{y}{1}}{right=of wx1a}\n \\po{rx1a}{wz1}\n \\po[out=25, in=150]{rx1a}{wx1a}\n\\end{tikzdisplay}\nwhich simplifies to:\n\\begin{tikzdisplay}[node distance=1em]\n \\event{rx1a}{\\DR{x}{1}}{}\n \\event{wz1}{\\DW{z}{1}}{right=of rx1a}\n \\nonevent{wx1a}{\\DW{x}{1}}{right=of wz1}\n \\event{wy1}{\\DW{y}{1}}{right=of wx1a}\n \\po{rx1a}{wz1}\n \\po[out=25, in=150]{rx1a}{wx1a}\n\\end{tikzdisplay}\nas required. The rest of the example is straightforward, and shows that our semantics\nagrees with the JMM in not supporting thread inlining.\n\n\n\n% \\subsection{Word tearing}\n\n% \\todo{Remove this section, since it's not needed for transactions?}\n\n% In \\S\\ref{sec:transactions}, we shall be considering transactional memory,\n% and in \\S\\ref{sec:transactions} show that we can model a simplified version\n% of an information flow attack on transactions. In order to model transactions,\n% we need to consider actions that can write many memory locations at once,\n% since this is part of the semantics of commitment. To lead up to this, we first\n% consider a simpler scenario of many-location writes and reads, which is word\n% tearing.\n\n% In word tearing, a program contains a write instruction with data larger\n% than the hardware word size, for example copying a byte array, or assigning\n% a 64-bit float on a 32-bit architecture. For example, consider the program:\n% \\begin{verbatim}\n% (x := [0, 0];) || (x := [1, 1];) || (r := x;)\n% \\end{verbatim}\n% This has executions in which the read of $x$ only reads from one of the writes,\n% for example:\n% \\begin{tikzdisplay}[node distance=1em]\n% \\event{wx00}{\\DW{x}{[0,0]}}{}\n% \\event{wx11}{\\DW{x}{[1,1]}}{right=2.5em of wx00}\n% \\event{rx00}{\\DR{x}{[0,0]}}{right=2.5em of wx11}\n% \\rf[out=20, in=160]{wx00}{rx00}\n% \\end{tikzdisplay}\n% but also has executions in which the read of $x$ reads from both writes,\n% for example:\n% \\begin{tikzdisplay}[node distance=1em]\n% \\event{wx00}{\\DW{x}{[0,0]}}{}\n% \\event{wx11}{\\DW{x}{[1,1]}}{right=2.5em of wx00}\n% \\event{rx01}{\\DR{x}{[0,1]}}{right=2.5em of wx11}\n% \\rfx[out=20, in=160]{wx00}{x[0]}{rx01}\n% \\rfx[out=-20, in=-160]{wx11}{x[1]}{rx01}\n% \\end{tikzdisplay}\n% Word tearing can occur, for example, in Java extended floating point~\\cite{jmm},\n% LLVM 64-bit instructions on 32-bit hardware~\\cite{llvm}, or in\n% JavaScript SharedArrayBuffers~\\cite{js-sab}.\n\n% \\newcommand{\\rfControl}[4][]{\\draw[rf,#1](#2) .. controls (#3) .. (#4);}\n% \\begin{tikzdisplay}[node distance=1em]\n% \\event{wx0}{\\DW{x}{0}}{}\n% \\event{wx1}{\\DW{x}{1}}{right=of wx0}\n% \\event{wy0}{\\DW{y}{0}}{right=2.5em of wx1}\n% \\event{wy1}{\\DW{y}{1}}{right=of wy0}\n% \\event{rx1}{\\DR{x}{1}}{right=2.5 em of wy1}\n% \\event{ry0}{\\DR{y}{0}}{right=of rx1}\n% \\event{ry1}{\\DR{y}{1}}{right=2.5 em of ry0}\n% \\event{rx0}{\\DR{x}{0}}{right=of ry1}\n% \\rf[out=20,in=160]{wx1}{rx1}\n% \\rf[out=20,in=160]{wy0}{ry0}\n% \\rf[out=340,in=200]{wy1}{ry1}\n% \\coordinate (a) [below=of wy1];\n% \\rfControl[out=340,in=200]{wx0}{a}{rx0}\n% \\wk{wx0}{wx1}\n% \\wk{wy0}{wy1}\n% \\po{rx1}{ry0}\n% \\po{ry1}{rx0}\n% \\end{tikzdisplay}\n\n\n% Batty section 4:\n% \\cite[\\S4]{DBLP:conf/esop/BattyMNPS15},\n% Example LB+ctrldata+ctrl-double (language must allow)\n% r1=loadrlx(x) //reads 42\n% if (r1 == 42)\n% storerlx(y,r1)\n\n% r2=loadrlx(y) //reads 42\n% if (r2 == 42)\n% storerlx (x,42)\n% else\n% storerlx (x,42)\n\n% a:RRLX x=42 sb,dd,cd\n% c:RRLX y=42 sb,cd\n% This is forbidden on hardware if compiled naively, as the architectures respect read-to-write control dependencies, but in practice compilers will collapse conditionals like that of the second thread, removing the control dependencies from the read of y to the writes of x and making the code identical to the previous example. As that example is allowed and observable on hardware (and we pre- sume that it would be impractical to outlaw such optimization for C or C++), the language must also allow this execution. But this execution has a cycle in the union of reads-from and dependency, so we cannot simply exclude all those.\n% Then one might hope for some other adaptation of the C/C++11 model, but the following example shows at least that there is no per-candidate-execution solution.\n% Example LB+ctrldata+ctrl-single (language can and should forbid)\n% r1=loadrlx(x) //reads 42 if (r1 == 42)\n% storerlx (y,r1) r2=loadrlx (y) //reads 42 if (r2 == 42)\n% a:RRLX x=42 sb,dd,cd\n% rf\n% b:WRLX y=42\n% c:RRLX y=42 sb,cd\n% rf\n% d:WRLX x=42\n% rf rf\n% b:WRLX y=42 d:WRLX x=42\n% storerlx (x,42)\n\n\\subsection{UNUSED: Logic}\n\\label{app:logic}\n\n\\newcommand{\\closed}{\\textsf{closed}}\n\\newcommand{\\pLTL}{\\textsf{PLTL}}\n\\newcommand{\\once}{\\Diamond^{-1}}\n\\newcommand{\\always}{\\Box^{-1}}\n\\newcommand{\\afo}{\\phi}\n\\newcommand{\\bfo}{\\psi}\n\\newcommand{\\mods}{\\textsf{Models}}\n\nIn this section, we develop sufficient logical infrastructure to prove that\nour semantics disallows thin air executions. We present a variant of the\nTAR-pit example from \\S\\ref{sec:relaxed-memory} which poses difficulties\nunder many speculative semantics.\n\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.\n% \\begin{displaymath}\n% \\afo \\QUAD::=\\QUAD\n% \\DR{\\aLoc}{\\aVal}\n% \\mid\n% \\DW\\aLoc\\aVal\n% \\afo \\wedge\\bfo\n% \\mid \\lnot \\afo\n% \\once\\afo\n% \\mid \\always\\afo\n% \\end{displaymath}\n%\\begin{definition} %[Satisfaction]\n Given an pomset $\\aPS$ and event $\\aEv$, define:\n \\begin{displaymath}\n \\begin{array}{lrl}\n \\aPS,\\aEv &\\models& \\DW{\\aLoc}{\\aVal}, \\text{ if } \\labeling(\\aEv) = (\\TRUE, \\DW{\\aLoc}{\\aVal}) \\\\\n \\aPS,\\aEv &\\models& \\DR{\\aLoc}{\\aVal}, \\text{ if } \\labeling(\\aEv) = (\\TRUE, \\DR{\\aLoc}{\\aVal}) \\\\\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& \\once\\afo, \\text{if } (\\exists \\bEv \\le \\aEv, \\bEv\\not=\\aEv) \\aPS,\\bEv \\models \\afo \\\\\n \\aPS,\\aEv &\\models& \\always\\afo, \\text{ if } (\\forall \\bEv \\le \\aEv,\\, \\bEv\\not=\\aEv)\\; \\aPS,\\bEv \\models \\afo\n \\end{array} \n \\end{displaymath}\n Define $\\aPS \\models \\afo$ if\n $(\\forall \\aEv \\in \\Event) \\;\\aPS,\\aEv \\models\\afo$ and $\\aPSS\\models \\afo$\n if $(\\forall \\aPS \\in \\aPSS)\\; \\aPS \\models\\afo$.\n%\\end{definition}\n\nLet $\\once\\afo$ be defined as $\\lnot(\\always\\lnot\\afo)$. \nIn addition, let $\\FALSE$, $\\lor$ and $\\Rightarrow$ be defined in the\nstandard way.\n% $\\afo\\lor\\bfo$ for $\\lnot(\\lnot \\afo \\land \\lnot \\bfo)$,\n% and $\\afo \\Rightarrow \\bfo$ for $\\lnot \\afo \\lor \\bfo$.\n\nThe past operators do not include the current instant, and thus \nthey do \\emph{not} satisfy the rule\n\\begin{math}\n \\always\\afo\\Rightarrow\\once\\afo.\n\\end{math}\nHowever, they do satisfy:\n% \\begin{align*} \n% \\frac{\\aPS \\models \\afo \\Rightarrow\\once{\\afo}}{\\aPS \\models \\lnot \\afo}\\text{(Coinduction)}\n% &&\n% \\frac{\\aPS \\models \\always\\afo \\Rightarrow\\afo}{\\aPS \\models \\afo}\\text{(Induction)}\n% \\end{align*}\n\\begin{gather*}\n \\tag{Coinduction}\n (\\afo \\Rightarrow\\once{\\afo}) \\Rightarrow\\lnot \\afo\n \\\\\n \\tag{Induction}\n (\\always\\afo \\Rightarrow\\afo) \\Rightarrow\\afo\n\\end{gather*}\n% \\begin{description}\n% \\item[Coinduction.]\n% \\begin{math}\n% (\\afo \\Rightarrow\\once{\\afo}) \\Rightarrow\\lnot \\afo\n% \\end{math}\n% \\item[Induction.] \n% \\begin{math}\n% (\\always\\afo \\Rightarrow\\afo) \\Rightarrow\\afo\n% \\end{math}\n% \\end{description}\nNote that $\\aPS \\models \\afo \\land \\always\\afo$ whenever $\\aPS \\models \\afo$.\n\nWe now present two proof rules. The first rule captures the semantics of\nlocal variables. Define\n\\begin{math}\n \\closed(\\aLoc) = (\\DR{\\aLoc}{\\aVal} \\Rightarrow \\once \\DW{\\aLoc}{\\aVal}).\n\\end{math}\nAlthough this definition does not mention intervening writes, it is\nsufficient for our example. It is straightforward to establish that\nfollowing rule is sound:\n\\begin{displaymath}\n \\tag{Closing $\\aLoc$}\n \\frac{\n \\afo \\text{ is independent of } \\aLoc\n \\qquad\n \\aPS \\models \\closed(\\aLoc) \\Rightarrow \\afo\n }{\n \\nu \\aLoc \\DOT \\aPS \\models \\afo\n }\n\\end{displaymath}\n\nThe second rule describes composition, in the style of Abadi and\nLamport~\\cite{Abadi:1993:CS:151646.151649}. To simplify the presentation, we\nconsider the special case with a single invariant.\n% We view the\n% composition result as capturing key aspects of no-ThinAirRead, as will become\n% clearer in the examples below.\nIn order to state the theorem, we generalize the satisfaction relation to\ninclude environment assumptions. Let\n\\begin{math}\n \\mods{(\\afo)} = \\{ \\aPSS \\mid \\aPSS \\models \\afo \\}\n\\end{math}\nbe the set of pomsets that satisfy $\\afo$. We say that $\\afo$ is prefix\nclosed if $\\mods{(\\afo)}$ is prefix-closed\\footnote{$\\aPS'$ is a prefix of\n $\\aPS$ if $\\Event'\\subseteq\\Event$, $\\aEv\\in\\Event'$ and $ \\bEv\\le\\aEv$\n imply $\\bEv\\in\\Event'$, and $(\\labeling',\\le',\\gtN')$ coincide with\n $(\\labeling,\\le,\\gtN)$ for elements of $\\Event'$.}.\n % when $\\aEv,\\,\\bEv\\in\\Event'$: $\\labeling'(\\aEv)=\\labeling(\\aEv)$,\n % $\\aEv\\le'\\bEv$ iff $\\aEv\\le\\bEv$, and $\\aEv\\gtN'\\bEv$ iff\n % $\\aEv\\gtN\\bEv$. \n\\begin{noenv}\n Define\n \\begin{math}\n \\afo, \\aPSS \\models \\bfo \\text{ if } \\mods{(\\afo)} \\parallel \\aPSS \\models \\bfo.\n \\end{math}\n\\end{noenv}\n\\begin{proposition}%[Composition]\n Let $\\afo$ be prefix-closed. Let $\\aPSS_1, \\aPSS_2$ be\n augmentation-closed.%\\footnote{$\\aPS'$ is an augmentation of $\\aPS$ if\n % $\\Event'=\\Event$, $\\aEv\\le\\bEv$ implies $\\aEv\\le'\\bEv$, $\\aEv\\gtN\\bEv$\n % implies $\\aEv\\gtN'\\bEv$, and\n % % $\\labeling'(\\aEv)=\\labeling(\\aEv)$\n % if $\\labeling(\\aEv) = (\\bForm \\mid \\bAct)$ then\n % $\\labeling'(\\aEv) = (\\bForm' \\mid \\bAct)$ where $\\bForm'$ implies\n % $\\bForm$.}\n Then:\n \\begin{displaymath}\n \\tag{Composition}\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 prefixes in the prefix closures of\n $\\aPSS_1 \\parallel \\aPSS_2$ satisfy the required property. Proof proceeds\n by induction on prefixes of $\\aPS \\in \\aPSS_1 \\parallel \\aPSS_2$.\n\n The case for empty prefix follows from assumption that $\\afo$ is prefix closed. \n\n For the inductive case, consider %$\\aPS$ in the prefix 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 %\n Consider a prefix $\\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 prefix of $\\aPS'$ and $\\aPS' \\models \\afo$\n by induction hypothesis, we deduce that $\\aPS_2 \\models \\afo$.\n % Thus, $\\aPS_2 \\in \\mods{(\\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\nWe now turn the conditional TAR-pit program, which is a variant of \\cite[Figure 8]{DBLP:journals/toplas/Lochbihler13}:\n\\begin{multline*}\n \\VAR x\\GETS0\\SEMI \\VAR y\\GETS0\\SEMI \\VAR z\\GETS0\\SEMI \\\\[-.5ex] (\n y\\GETS x\n \\PAR\n \\IF{z}\\THEN x\\GETS1 \\ELSE x\\GETS y\\SEMI a\\GETS y \\FI\n \\PAR\n z\\GETS1\n )\n\\end{multline*}\nThis program is allowed to write $1$ to $a$ under many speculative\nmemory models\n\\cite{Manson:2005:JMM:1047659.1040336,Jagadeesan:2010:GOS:2175486.2175503,DBLP:conf/popl/KangHLVD17},\neven though the read of $1$ from $y$ in the else branch of the second\nthread arises out of thin air. In contrast, we prove the formula\n\\begin{math}\n \\lnot\\once(\\DW{a}{1})\n\\end{math}\nholds for the models of this program in our semantics. We start with the following invariant,\nwhich holds for each of the three threads, and thus, by composition, for the\naggregate program:\n\\begin{align*}\n &[\\once(\\DW{y}{1}) \\Rightarrow \\once(\\DR{x}{1})]\n \\land\\\\[-.5ex]\n &[\\once(\\DW{a}{1}) \\Rightarrow (\\once(\\DR{y}{1}) \\land \\always(\\DW{x}{1} \\Rightarrow \\once(\\DR{y}{1})))]\n\\end{align*}\nClosing $y$, we have,\n\\begin{math}\n \\once(\\DR{y}{1}) \\Rightarrow \\once(\\DW{y}{1}) % \\Rightarrow \\once(\\DR{x}{1})\n\\end{math}\nwhich we substitute into the left conjunct to get:\n\\begin{displaymath}\n \\once(\\DR{y}{1}) \\Rightarrow \\once(\\DR{x}{1})\n\\end{displaymath}\nwhich in turn we substitute into the right conjunct to get:\n\\begin{displaymath}\n \\once(\\DW{a}{1}) \\Rightarrow (\\once(\\DR{x}{1}) \\land \\always(\\DW{x}{1} \\Rightarrow \\once(\\DR{x}{1})))\n\\end{displaymath}\nClosing $x$, we can replace $\\once(\\DR{x}{1})$ with $\\once(\\DW{x}{1})$:\n\\begin{displaymath}\n \\once(\\DW{a}{1}) \\Rightarrow (\\once(\\DW{x}{1}) \\land \\always(\\DW{x}{1} \\Rightarrow \\once(\\DW{x}{1})))\n\\end{displaymath}\nApplying coinduction to the right conjunct, we have:\n\\begin{displaymath}\n \\once(\\DW{a}{1}) \\Rightarrow (\\once(\\DW{x}{1}) \\land \\always(\\lnot \\DW{x}{1}))\n\\end{displaymath}\nSimplifying, we have, as required: \n\\begin{displaymath}\n \\once(\\DW{a}{1}) \\Rightarrow \\FALSE\n\\end{displaymath}\n\n\\end{document}\n", "meta": {"hexsha": "8623d65e820e0f09047196bd2f68414d9fa09aba", "size": 179385, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "sp.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": "sp.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": "sp.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": 41.5243055556, "max_line_length": 633, "alphanum_fraction": 0.6959277532, "num_tokens": 61216, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3702253786982541, "lm_q1q2_score": 0.18945047376278443}}
{"text": "\\documentclass[english, twocolumn, 10pt, aps, superscriptaddress, floatfix, prb, citeautoscript]{revtex4-1}\n\\pdfoutput=1\n\\usepackage{xr}\n\\externaldocument{zigzag}\n\\usepackage[utf8]{inputenc}\n\\usepackage[T1]{fontenc}\n\\usepackage{verbatim}\n\\usepackage{units}\n\\usepackage{mathtools}\n\\usepackage{amsmath}\n\\usepackage{amssymb}\n\\usepackage{graphicx}\n\\usepackage{wasysym}\n\\usepackage{layouts}\n\\usepackage{siunitx}\n\\usepackage{bm}\n\\usepackage{xcolor}\n\\usepackage[colorlinks, citecolor={blue!50!black}, urlcolor={blue!50!black}, linkcolor={red!50!black}]{hyperref}\n\\usepackage{bookmark}\n\\usepackage{tabularx}\n\\usepackage{microtype}\n\\usepackage{babel}\n\\hypersetup{pdfauthor={Quantum Tinkerer},pdftitle={Enhanced proximity effect in zigzag-shaped Majorana Josephson junctions.}}\n\n\\setcounter{secnumdepth}{4}\n\\setcounter{tocdepth}{4}\n\n\\DeclareMathOperator{\\e}{e}\n\\DeclareMathOperator{\\de}{d\\!}\n\\DeclareMathOperator{\\Tr}{Tr}\n\\DeclareMathOperator{\\diag}{diag}\n\\DeclareMathOperator{\\Res}{Res}\n\\DeclareMathOperator{\\sgn}{sgn}\n\\DeclareMathOperator{\\Pf}{Pf}\n\\DeclareMathOperator{\\Det}{Det}\n\\DeclareMathOperator{\\rank}{rank}\n\\DeclareMathOperator{\\im}{Im}\n\\DeclareMathOperator{\\re}{Re}\n\n\\renewcommand{\\comment}[2]{#2}\n% Uncomment the following line for paragraph descriptions to appear in the file.\n% \\renewcommand{\\comment}{\\paragraph}\n\n\\DeclarePairedDelimiter\\abs{\\lvert}{\\rvert}\n\\DeclarePairedDelimiter\\norm{\\lVert}{\\rVert}\n\n\\makeatletter\n\\let\\oldabs\\abs\n\\def\\abs{\\@ifstar{\\oldabs}{\\oldabs*}}\n\\let\\oldnorm\\norm\n\\def\\norm{\\@ifstar{\\oldnorm}{\\oldnorm*}}\n\\makeatother\n\n\\newcommand{\\ev}[1]{\\langle#1\\rangle}\n\\newcommand{\\bra}[1]{\\langle#1|}\n\\newcommand{\\ket}[1]{|#1\\rangle}\n\\newcommand{\\bracket}[2]{\\langle#1|#2\\rangle}\n\n\\newcolumntype{L}[1]{>{\\raggedright\\arraybackslash}p{#1}}\n\\newcolumntype{C}[1]{>{\\centering\\arraybackslash}p{#1}}\n\\newcolumntype{R}[1]{>{\\raggedleft\\arraybackslash}p{#1}}\n\n\n\\begin{document}\n\n\n\\appendix\n\n\\section{Zigzag devices and disorder}\\label{appendix:mfp_vs_gap}\n\n\\comment{We compare $E_\\textrm{gap}(l_e)$ for zigzag and straight systems at $\\phi=0$ and $\\phi=\\pi$; and confirm that the zigzag and disorder both increase $E_\\textrm{gap}$ through a similar mechanism.}\nThe right amount of disorder improves the Majorana properties~\\cite{Haim2019} and scatters long trajectories in a similar fashion to the zigzag geometry cutting off long trajectories.\nWe simulate devices with disorder---parameterized by its mean free path $l_e$---and calculate $E_\\textrm{gap}(l_e)$ for straight and zigzag devices at different phases and magnetic fields, see Fig.~\\ref{fig:mfp_vs_gap}.\nFor the parameters we chose, at $\\phi=0$ we observe that an optimal value of $l_e$ results in an enhancement that is at best equal to that of the zigzag device.\nAt $\\phi=\\pi$ we observe that zigzag geometry outperforms disorder.\n\n\\begin{figure}[!htb]\n\\centering\n\\includegraphics[width=0.9\\columnwidth]{figures/mfp_vs_gap.pdf}\n\\caption{Comparison of the gap of zigzag devices (dashed lines) and straight devices (solid lines) as function of mean free path $l_e$.\nEach $E_\\textrm{gap}$ value is averaged over 40 disorder realizations and is calculated using a translationally invariant system where the unit-cell is $L_x=3z_x$, with $z_x=\\SI{1300}{\\nm}$.\n\\label{fig:mfp_vs_gap}}\n\\end{figure}\n\n\\section{Zigzag device with a single superconductor}\\label{appendix:NS_junction}\n\n\\comment{We run the simulation and observe that the phase diagrams are the same but the zigzag device is still better.}\nA zigzag-shaped device with a single superconductor shows a similar enhancement of the superconducting gap as the Josephson junction devices.\nWe demonstrate this by simulating a straight and a zigzag device and computing $E_\\textrm{gap}(B_x, \\; \\mu)$ in Fig.~\\ref{fig:ns_junction}.\nWe observe that the order of magnitude increase of $E_\\textrm{gap}$ also occurs upon the introduction of a zigzag geometry.\n\n\\begin{figure}[!htb]\n\\centering\n\\includegraphics[width=0.9\\columnwidth]{figures/phasediagrams_NS.pdf}\n\\caption{Same as Fig.~\\ref{fig:phasediagrams} (c) and (d) but with one superconductor instead of two.\nWe observe that the zigzag geometry also increases the gap in this case.\n\\label{fig:ns_junction}}\n\\end{figure}\n\n\\section{Direction of the magnetic field}\\label{appendix:direction_B}\n\n\\comment{Zigzag geometry removes the need for precise field alignment.}\nBecause the zigzag geometry cuts off long trajectories---leaving only short trajectories---this device requires a less precise alignment of the magnetic field.\nTo show this, we perform a simulation of a straight and zigzag device with a rotated field (see Fig.~\\ref{fig:tilted_angle_phase_diagram}).\nWe observe that the zigzag device still has a sizeable gap with a $10^\\circ$ misaligned magnetic field, wherea a $1^\\circ$ misalignment makes a straight device gapless.\n\n\\comment{Likewise a inhomogeneous magnetic field does not matter.}\nStrong screening of the magnetic field by the superconductors may distort the magnetic field pattern.\nTo determine whether this effect degrades the device quality, we simulate a device with the magnetic field parallel to the NS interface, shown in Fig.~\\ref{fig:syst_snaking_magnetic_field}.\nWe find that the resulting gap is comparable to that of a device with the magnetic field purely in the $x$-direction, as shown in Fig.~\\ref{fig:snaking_magnetic_field}.\n\n\\begin{figure}[!htb]\n\\centering\n\\includegraphics[width=0.9\\columnwidth]{figures/tilted_angle_phase_diagram.pdf}\n\\caption{The topological gap as a function of the magnetic field magnitude $B$ and its angle $\\theta=\\arctan{B_y/B_x}$ for a straight device (a) and a zigzag device (b).\nNote that the colormaps and the $\\theta$-axes differ between panels: the zigzag-shaped device becomes gapless at $\\theta$ an order of magnitude larger compared to the straight device.\n\\label{fig:tilted_angle_phase_diagram}}\n\\end{figure}\n\n\\begin{figure}[!htb]\n\\centering\n\\includegraphics{figures/syst_snaking_magnetic_field.pdf}\n\\caption{\nThe magnetic field pattern emulating strong screening by the superconductors.\n\\label{fig:syst_snaking_magnetic_field}}\n\\end{figure}\n\n\\begin{figure}[!htb]\n\\centering\n\\includegraphics{figures/snaking_magnetic_field.pdf}\n\\caption{\nComparison of the zigzag device's band structures with the magnetic field following the shape of the junction (orange) (see Fig.~\\ref{fig:syst_snaking_magnetic_field}) and a magnetic field in the $x$-direction (blue) for different values of $z_y$.\n\\label{fig:snaking_magnetic_field}}\n\\end{figure}\n\n\\section{Interface transparency vs.~path length cut-off}\n\nThe zigzag geometry both increases the interface transparency (because particles typically hit the superconductor\ncloser to normal incidence) as well as sets an upper limit to the trajectory length.\nThe change in the interface transparency alone is not sufficient to explain the increase of the topological gap.\nTo verify this, we compute the dispersion of a system with $z_x = z_y = \\SI{80}{\\nm}$ comparable to the Fermi wavelength $\\lambda_\\textrm{F}$ and $W=\\SI{400}{\\nm}$, so that the angle of the boundaries is sufficiently large, but the boundary modulation is much smaller than the width.\nWe observe that $E_\\textrm{gap}$ becomes $\\SI{6.1}{\\mu \\eV}$, a two-fold increase compared to the straight system, not the order of magnitude increase resulting from the cutting off of long trajectories.\n\n\\bibliographystyle{apsrev4-1}\n\\bibliography{zigzag}\n\n\\end{document}\n", "meta": {"hexsha": "a5164a54f47bd1990bccbf12c98f76019d0b3668", "size": 7408, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "paper/appendix.tex", "max_stars_repo_name": "basnijholt/zigzag-majoranas", "max_stars_repo_head_hexsha": "012e1ad347959690b7d25597ef8f1af34c43ac8d", "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/appendix.tex", "max_issues_repo_name": "basnijholt/zigzag-majoranas", "max_issues_repo_head_hexsha": "012e1ad347959690b7d25597ef8f1af34c43ac8d", "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/appendix.tex", "max_forks_repo_name": "basnijholt/zigzag-majoranas", "max_forks_repo_head_hexsha": "012e1ad347959690b7d25597ef8f1af34c43ac8d", "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.0540540541, "max_line_length": 283, "alphanum_fraction": 0.7844222462, "num_tokens": 2054, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.37022537869825406, "lm_q1q2_score": 0.1894504737627844}}
{"text": "%\\index{M7!history}\r\nThe documented aerosol modules (Sulphate, BCOC, DUST, SALT) produce\r\naerosols independent of each other. Nitrate is somewhat special since\r\nit depends on SALT and sulphate, and sulphate depends on the\r\ntropospheric chemistry.\r\n\r\nM7 tries to put the aerosol packages together. The inclusion of M7\r\nbuilds on this approach in the following way:\r\n\\begin{enumerate}\r\n \\item All the separate modules are left untouched.\r\n \\item If M7 is activated the emissions of the components which \r\n are concerned by M7 are transferred to a new array and the \r\n original emission arrays become irrelevant.\r\n \\item All the M7 tracers have their own loss terms depending\r\n on the microphysics.\r\n\\end{enumerate}\r\n\r\nYou turn on the M7 application by setting \\verb#M7 := Y# in\r\n\\makefile. Running the aerosol modules separately is of coarse good if\r\nyou want to save CPU time and only want to run 8 carbon tracers\r\ninstead of full chemistry/sulfate/M7 run.\r\n\r\n\r\n% Physics\r\n\\subsection{Physics}\r\n\\index{M7!physics}\r\nM7 is a microphysical model. This means that it's purpose is to\r\ncalculate interaction between different types of aerosols. The output\r\nis the size of the aerosols and their mixing state (i.e. water soluble\r\nor insoluble). M7 splits the aerosol size distribution into the\r\nfollowing size distributed modes\r\n\\begin{itemize2}\r\n \\item Nucleation mode, water soluble, size: $\\sim 1 nm$\r\n \\item Aitken mode, water soluble, size: $\\sim 0.01 {\\mu}m$\r\n \\item Accumulation mode, water soluble, size: $\\sim 0.1 {\\mu}m$\r\n \\item Coarse mode, water soluble, size: $\\sim 1 {\\mu}m$\r\n \\item Aitken mode, insoluble, size: $\\sim 0.01 {\\mu}m$\r\n \\item Accumulation insoluble, size: $\\sim 0.1 {\\mu}m$\r\n \\item Coarse mode, insoluble, size: $\\sim 1 {\\mu}m$\r\n\\end{itemize2}\r\n\r\n{\\bf Important}\\\\\r\n{\\bf M7 does not treat semivolatile aerosol species} like nitrate or\r\nsecondary organics. This is both a good thing and a bad thing. It is\r\ngood because it greatly reduces the complexity of the problem, and it\r\nis bad because.. well... you can not calculate the effect these\r\ntracers would have on aerosol microphysics.\r\n\r\n% M7 tracers\r\n\\subsection{M7 tracers}\r\n\\index{M7!tracers}\r\nThe M7 tracers are listed in Table \\ref{tbl:m7tracers}.\r\n\r\n\\begin{table*}\r\n\\caption{Tracers included in the M7 model. All the aerosol species\r\n (250--274) have lifetimes of days-weeks and they all need to be\r\n transported. Water species (275--278) are in equilibrium (see below)\r\n and should not be transported. Soluble species (except water) are\r\n washed out in convection. There are 17 soluble species in M7.}\r\n\\label{tbl:m7tracers}\r\n\\begin{minipage}{\\linewidth}\r\n\\begin{tabular}{|c|l|l|c|c|}\r\n\\hline\r\nNr & Component name & Remarks & Soluble & Transport \\\\\r\n\\hline \\hline\r\n80 & SO4GAS & Gas phase sulf. acid & N/A (No) & No\\\\\r\n\\hline\r\n250 & SO4NUC & nucleation mode sulphate & Yes & Yes\\\\\r\n\\hline\r\n251 & SO4AT & aitken mode sulphate & Yes & Yes\\\\\r\n\\hline\r\n252 & SO4AC & accumulation mode sulphate & Yes & Yes\\\\\r\n\\hline\r\n253 & SO4CRS & coarse mode sulphate & Yes & Yes\\\\\r\n\\hline\r\n254 & BCKS & aitken mode soluble BC & Yes & Yes\\\\\r\n\\hline\r\n255 & BCAS & accumulation mode BC & Yes & Yes\\\\\r\n\\hline\r\n256 & BCCS & coarse mode BC & Yes & Yes\\\\\r\n\\hline\r\n257 & BCKI & aitken mode BC & No & Yes\\\\\r\n\\hline\r\n258 & OCKS & aitken mode OC & Yes & Yes\\\\\r\n\\hline\r\n259 & OCAS & accumulation mode OC & Yes & Yes\\\\\r\n\\hline\r\n260 & OCCS & coarse mode OC & Yes & Yes\\\\\r\n\\hline\r\n261 & OCKI & aitken mode OC & No & Yes\\\\\r\n\\hline\r\n262 & SSAS & accumulation mode Seasalt & Yes & Yes\\\\\r\n\\hline\r\n263 & SSCS & coarse mode seasalt & Yes & Yes\\\\\r\n\\hline\r\n264 & DUAS & accumulation mode dust & Yes & Yes\\\\\r\n\\hline\r\n265 & DUCS & coarse mode dust & Yes & Yes\\\\\r\n\\hline\r\n266 & DUAI & accumulation mode dust & No & Yes\\\\\r\n\\hline\r\n267 & DUCI & coarse mode dust & No & Yes\\\\\r\n\\hline\r\n268 & NNUC & Nucleation mode number & Yes & Yes\\\\\r\n\\hline\r\n269 & NKS & Aitken mode number & Yes & Yes\\\\\r\n\\hline\r\n270 & NAS & Accumulation mode number & Yes & Yes\\\\\r\n\\hline \r\n271 & NCS & coarse mode number & Yes & Yes\\\\\r\n\\hline\r\n272 & NKI & aikten mode number & No & Yes\\\\\r\n\\hline\r\n273 & NAI & accumulation mode number & No & Yes\\\\\r\n\\hline\r\n274 & NCI & Coarse mode number & No & Yes\\\\\r\n\\hline\r\n275 & H2ONUC & nucleation mode water & Yes & No\\\\\r\n\\hline\r\n276 & H2OKS & aitken mode water & Yes & No \\\\\r\n\\hline\r\n277 & H2OAS & accumulation mode water & Yes & No\\\\\r\n\\hline\r\n278 & H2OCS & coarse mode water & Yes & No \\\\\r\n\\hline\r\n\\end{tabular}\r\n\\end{minipage}\r\n\\end{table*}\r\n\r\nThus, when running M7, you need 51 tracers from tropospheric\r\nchemistry, 7 from sulfate and one extra (\\verb#SO4GAS#), and further\r\nyou need the 8 BC/OC species, which are not transported or washed\r\nout. The tracers washed out in convection are all the\r\nwater-soluble. Table \\ref{tbl:tracerm7} shows in more detail the\r\ntracers need for running M7.\r\n\r\n\\begin{table}\r\n\\caption{Explanation of the number of tracers needed for running\r\n M7. Note that several tracers are dummy tracers (the 8 of BCOC, the\r\n 2 of dust, the 2 of salt). These tracers are handled by the 25 M7\r\n tracers when running M7. The sulphate species are converted\r\n immediately to M7 species. The number in parenthesis for\r\n Transport indicates the number of tracers if you exclude the\r\n tracers labeled \\textcolor{red}{\\it Maybe} in Table\r\n \\ref{tbl:tropcomp}.}\r\n \\label{tbl:tracerm7}\r\n\\begin{minipage}{\\linewidth}\r\n\\begin{tabular}{|l|c|c|c|}\r\n\\hline\r\nApplication & Tracers & Transport & Washout \\\\\r\n\\hline\r\nTROPCHEM & 51 & 40 (35) & 8 \\\\\r\n\\hline\r\nSALT & 2\\footnote{dummy tracers} & 0 & 0 \\\\\r\n\\hline\r\nDUST & 2\\footnote{dummy tracers} & 0 & 0 \\\\\r\n\\hline\r\nSULPHATE\\footnote{no transport or washout of old $SO_4$} \r\n & 7 & 4 & 3 \\\\ \r\n\\hline\r\nSO4GAS & 1 & 0 & 0 \\\\\r\n\\hline\r\nBCOC & 8\\footnote{dummy tracers} & 0 & 0 \\\\\r\n\\hline\r\nM7 & 25 & 25 & 17 \\\\\r\n\\hline\r\nM7(water) & 4 & 0 & 0 \\\\\r\n\\hline\r\n\\hline\r\nSUM & 100 & 69 (64) & 28 \\\\\r\n\\hline\r\n\\end{tabular}\r\n\\end{minipage}\r\n\\end{table}\r\n\r\n\r\n\\subsection{Technical information}\r\n\\index{M7!technical information}\r\n\r\nThe M7 model is activated by the logical switch LM7. This logical\r\nvariable currently has to be set in the main program. When this\r\nlogical switch is activated, the emissions calculated for the\r\nM7-relevant components are removed from the \\verb#POLLX# array and put\r\nin the \\verb#PRODM7# array. \r\n\r\nThe idea is that the old aerosols tracers still exist in the\r\nmodel. However, they are in a way irrelevant if M7 is used and there\r\nis no need for transporting them.\r\n\r\n\r\n\\subsection{Interaction with other parts of aerosol codes}\r\n\\index{M7!aerosol code interaction}\r\n\r\n\\subsubsection{Carbon particles}\r\n\\index{M7!carbon particles}\r\nThe carbon particles in their old form should not be transported if M7\r\nis used. However, they should be included as tracers in the \\inptrctm\\\r\nfile.\r\n\r\nIf the logical LM7 is recognized by the model, the emissions of BC\r\nand OC are put into the \\verb#prodm7# array and enters the M7 tracer\r\nlist. They are not put into the places they have as BC/OC tracers as\r\ndescribed in section \\ref{sxn:bcoc}.\r\n\r\n\\subsubsection{Sulphate model}\r\n\\index{M7!sulphate model}\r\nM7 needs explicit input about how much sulphate is formed in gas phase\r\nand how much is formed in the aqueous phase. Therefore, another\r\ntracer, number 80, \\verb#SO4gas# is used when M7 is used.\r\nThe tracer which represents sulphate in the sulphate application (see\r\nchapter \\ref{sxn:sulphate}) which is tracer number 73 is only\r\nrepresenting aqueous phase sulphate when M7 is used.\r\n\r\nThere is no need for transporting the sulphate tracers since the mass\r\nproduced in the sulphate tracers are moved to the M7-tracers in the\r\nsame timestep. These tracers are later the ones being transported and\r\nbeing lost by dry- and wet deposition.\r\n\r\n\\subsubsection{Dust and Seasalt models}\r\n\\index{M7!dust and seasalt models}\r\n\r\nThe dust and seasalt models are activated when it finds tracers\r\nnamed \\verb#SALTXX# or \\verb#DUSTXX# (where \\verb#XX# is bin number)\r\nin the standard version (see more description in section\r\n\\ref{sxn:dust} and \\ref{sxn:salt}. To not re-organize the code too\r\nmuch, this feature is kept, and you still need tracers called\r\n\\verb#DUST01# and \\verb#SALT01# to be able to run these modules.\r\n\r\nHowever, when running M7, the standard versions of these codes are\r\nno longer relevant. Therefore, you need 2 dust species and 2 salt\r\nspecies to activate the model. These species have to be listed in\r\n\\inptrctm\\ {\\bf but they do not need to be transported}.\r\n\r\n\\subsubsection{Salt model}\r\n\\label{sxn:salt2m7}\\index{M7!seasalt model}\r\n\r\nThe logical variable LM7 is sent directly into the salt model.\r\nIf the salt model recognizes this variable as TRUE, it will\r\nnot care about fall speeds and dry deposition, but only output\r\nthe emissions into the \\verb#prodm7# array.\r\n\r\nIn the case of LM7 being true in the seasalt application, a production\r\nroutine giving modal emissions are being activated. This is different\r\nfrom the standard model in the way that in the standard model,\r\nthe production routines distributes the production to size bins.\r\n\r\n\\subsubsection{Dust model}\r\n\\index{M7!dust model}\r\n\r\nWhen using M7, the whole DUST model (DEAD) is still run. This is \r\nstrictly not necessary since M7 does not really care about what\r\nhappens in DEAD except for one thing: It wants the emissions.\r\n\r\nIt would have been possible to send the logical LM7 to the dust model \r\nand only output the emissions if M7 is used, and not call the\r\ndeposition routines in a similar way to what is done for the salt\r\nmodel (section \\ref{sxn:salt2m7}. However: In the case of dust, \r\nthe complete call to DEAD kept because of the following reasons\r\n\\begin{itemize}\r\n \\item The dust code is more complicated than the salt code and\r\n sending around the logical LM7 in it could be messy.\r\n \\item DEAD is not developed at UiO, and if anyone wants to upgrade\r\n to a more recent version of DEAD, it would be easier not having to\r\n re-code it using the variable LM7 also.\r\n\\end{itemize}\r\n\r\nThe code to DEAD will update the concentrations of the tracer\r\n\\verb#DUST01# which should not transported in CTM2. However, DEAD also\r\nputs the emissions in a 2D field which can be accessed with the\r\nsubroutine \\verb#dustfield2main#.\r\n\r\nAll that is needed to include dust in M7 is the call to\r\n\\verb#dustfield2main# and fetch the emissions. These are then\r\nprocessed in the \\verb#prodm7# variable.\r\n\r\n", "meta": {"hexsha": "8bb8f791423458c66baf3ebbc27063fa3f81a511", "size": 11218, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "maybe_later/m7.tex", "max_stars_repo_name": "NordicESMhub/OsloCTM3-docs", "max_stars_repo_head_hexsha": "8e76cd9561a94eff4d96818c3518a112111aef72", "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": "maybe_later/m7.tex", "max_issues_repo_name": "NordicESMhub/OsloCTM3-docs", "max_issues_repo_head_hexsha": "8e76cd9561a94eff4d96818c3518a112111aef72", "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": "maybe_later/m7.tex", "max_forks_repo_name": "NordicESMhub/OsloCTM3-docs", "max_forks_repo_head_hexsha": "8e76cd9561a94eff4d96818c3518a112111aef72", "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.6449275362, "max_line_length": 75, "alphanum_fraction": 0.6719557853, "num_tokens": 3264, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.596433160611502, "lm_q2_score": 0.3174262591305011, "lm_q1q2_score": 0.1893235469942904}}
{"text": "\\subsection{Excitation laser power optimization}\n\\label{subsec:power_optim}\n\nFirstly, we tried to establish the optimal laser power for excitation in\nright-angle geometry using a spinning cell.\nWe used commercial samples of polyU (Sigma) dissolved in 80\\,mM cacodylate\nbuffer with ph 6.4 to the concentration of 500\\,\\g{m}M per nucleobase.\nWe chose 244\\,nm excitation laser wavelength with 10, 2, and 1 mW at samples.\nThe 150\\,\\g{m}L of the sample was rotated at 9600\\,rpm during the measurement.\nThe spectral series were measured with 30\\,s (10 and 2\\,mW excitation) and\n60\\,s (1\\,mW excitation) accumulation time per spectrum.\nThe beginning of each measurement was slightly delayed from the start of\nthe exposure to the laser because the samples needed to be adjusted for\noptimal signal.\nThe adjustment took 26\\,s for 10\\,mW excitation, 90\\,s for 2\\,mW, and 69\\,s\nfor 1\\,mW excitation.\n\nFurther analysis was performed on the integral intensity of measured Raman\nbands.\nThe band shapes were modeled as described in\n\\cref{band_intensities}\nwith the experimentally estimated Lorentzian curve fraction coefficient\n$c_\\text{L} = 0.5$, which visually gave the best band shape fit.\nThe linear function $a_0 + a_1\\wn$ was added to the shape function\n\\eqnref{band_intensities:shape}\nas the model of the spectral background.\n\nThe analysis was performed on the polyU integral intensity represented by\nits band at 1231\\,\\icm{} compared to the intensity of the cacodylate band at\n607\\,\\icm{} to account for the excitation laser power and sample adjustment\nvariations during the measurement.\n\\Figref{power_optim:triplexes_pU}\nclearly shows that the polyU band also contains a shoulder at 1248\\,\\icm{}, and\nis overlapping with the cacodylate band at 1276\\,\\icm.\nTherefore, the band was modeled by the shape function\n(\\eqnref{band_intensities:shape})\nwith three components, but its intensity was calculated as a sum of the pulyU\nbands without the cacodylate one.\nThe cacodylate band was modeled as having two components, at 607 and 640\\,\\icm,\nbut only the first one was used for the integral intensity calculation.\n\n\\begin{figure}\n\t\\centering\n\t\\input{results_and_discussion/assets/power_optimization_triplexes/%\n\t\tpower_optimization_triplexes_pU}\n\t\\caption[%\n\t\tExample UV RR spectrum of polyU dissolved in cacodylate buffer.%\n\t]{%\n\t\t\\captiontitle{%\n\t\t\tExample UV RR spectrum of polyU dissolved in cacodylate buffer.%\n\t\t}\n\t\tThe fits of shape functions\n\t\t(\\eqnref{band_intensities:shape})\n\t\tto the bands of polyU and cacodylate used in intensity estimation fit are\n\t\tmarked by green, and red lines, respectively, and the areas used for\n\t\tintensity calculation are filled with the corresponding colors.\n\t}\n\t\\label{\\figlabel{power_optim:triplexes_pU}}\n\\end{figure}\n\nThe time dependence of the intensity of polyU band at 1231\\,\\icm{} (normalized\nto the intensity of cacodylate band at 607\\,\\icm) was modeled by the\nexponential decay curve\n\\begin{equation}\n\tI = I_0 \\text{e}^{-\\lambda t} + b,\n\t\\label{\\eqnlabel{power_optim:decay}}\n\\end{equation}\nwhere $I_0$ is initial intensity, $\\lambda$ is the decay constant, and $b$ is\nthe baseline constant.\nThe normalized results (subtracted by $b$) can be seen in\n\\figref{power_optim:triplexes}.\n\n\\begin{figure}\n\t\\centering\n\t\\input{results_and_discussion/assets/power_optimization_triplexes/%\n\t\tpower_optimization_triplexes}\n\t\\caption[%\n\t\tDecrease of the integral intensity of polyU band at 1231\\,\\icm{} for\n\t\tdifferent excitation laser powers in raw spectra.%\n\t]{%\n\t\t\\captiontitle{%\n\t\t\tDecrease of the integral intensity of polyU band at 1231\\,\\icm{} for\n\t\t\tdifferent excitation laser powers in raw spectra.%\n\t\t}\n\t\tIt was normalized to the integral intensity of the cacodylate band at\n\t\t607\\,\\icm{}, which was used as the internal intensity standard.\n\t\tThe values were fitted by exponential decay curves\n\t\t\\eqnref{power_optim:decay}\n\t\tand the baseline constant $b$ from the fit was subtracted from the plots.\n\t}\n\t\\label{\\figlabel{power_optim:triplexes}}\n\\end{figure}\n\nWe can see, that the lines intersect almost at the same point, which is\nexpected outcome, but this point is not at 0\\,s.\nThis is caused by the fact that the time axis denotes the ends of the spectrum\naccumulation, whereas the intensity comes from the whole time period of the\nspectrum acquisition, which is even more enhanced by the fact that band's\nintensity lowers during the measurement.\nThe lifetimes $\\tau$ can be calculated from decay constants $\\lambda$ from\n\\eqnref{power_optim:decay}\n\\begin{equation}\n\t\\tau = \\frac{1}{\\lambda}.\n\t\\label{\\eqnlabel{power_optim:lifetime}}\n\\end{equation}\nWe can also calculate total accumulated relative energy from the decay curve\nby\n\\begin{equation*}\n\tE_{0,\\text{r}}\n\t\t= \\int_0^{\\infty}{I_0 \\text{e}^{-\\lambda t}\\text{d}t}\n\t\t= \\frac{I_0}{\\lambda}\n\\end{equation*}\nand energy accumulated from time $T_0$ by\n\\begin{equation*}\n\tE_r\t= \\int_{T_0}^{\\infty}{I_0 \\text{e}^{-\\lambda t}\\text{d}t}\n\t\t= \\frac{I_0}{\\lambda} \\text{e}^{-\\lambda T_0}.\n\\end{equation*}\nEnergy fractions can then be calculated by dividing the relative energies by\nthe maximal total relative energy. The resulting lifetimes, total accumulated\nenergy fractions $E_0$, and energy fractions $E$ accumulated from time\n$T = 60\\pm20$\\,s, which was regarded as reasonable approximate for the time\nneeded for adjustment of the sample before measurement could start, can be\nseen in\n\\tabref{power_optim:lifetimes_triplexes}.\n\n\\begin{table}\n\t\\centering\n\t\\input{results_and_discussion/assets/power_lifetimes_triplexes}\n\t\\caption[%\n\t\tLifetimes of polyU in dependence on excitation power estimated from raw\n\t\tspectra.%\n\t]{%\n\t\t\\captiontitle{%\n\t\t\tLifetimes $\\tau$ of the polyU in dependence on excitation power $P$\n\t\t\testimated from raw spectra.%\n\t\t}\n\t\t$E_0$ are total energies accumulated by detector divided by maximal value\n\t\tacross all the excitation powers $P$, and $E$ are energies accumulated from\n\t\ttime $T = 60\\pm20$\\,s, which was needed for the adjustment of the\n\t\tsamples before the acquisition can even start, but the sample needs to be\n\t\tirradiated by the excitation laser.\n\t\tThe last column contains fractions of the samples $r$ which were not\n\t\tdestroyed by photodecomposition after the time $T$.\n\t}\n\t\\label{\\tablabel{power_optim:lifetimes_triplexes}}\n\\end{table}\n\nThe results show that the 10\\,mW power gave the best results if we do not take\ninto account adjustment of the samples, but as you can see in\n\\figref{power_optim:triplexes},\nthe signal intensity quickly lowers with time.\nThe lifetimes can also vary significantly in dependence on a sample which can\nlower the reliability of the band intensity estimations.\nThe table shows that, after 1-minute adjustment of the sample, the 10\\,mW\nexcitation photodecomposes about 35\\% of the sample, whereas, with the 1\\,mW\nexcitation, only around 6\\% of the sample is destroyed.\nThe accumulated energies are calculated as integral to infinity, but we can\neffectively measure only smaller portions of the decay with lower powers,\nfavoring measurements with higher powers.\n\nFurther investigation of the spectral decay behavior shows that this simple\napproach does not reveal that a single decay curve cannot model such a complex\nsystem.\nThis effect is clearly visible if we subtract the cacodylate buffer background\nfrom the spectra.\nThe resulting spectrum can be seen in\n\\figref{power_optim:triplexes2_pU}.\n\n\\begin{figure}\n\t\\centering\n\t\\input{results_and_discussion/assets/power_optimization_triplexes2/%\n\t\tpower_optimization_triplexes2_pU}\n\t\\caption[%\n\t\tExample UV RR spectrum of polyU dissolved in cacodylate buffer with\n\t the cacodylate buffer background subtracted.%\n\t]{%\n\t\t\\captiontitle{%\n\t\t\tExample UV RR spectrum of polyU dissolved in cacodylate buffer with\n\t\t\tthe cacodylate buffer background subtracted.%\n\t\t}\n\t\tThe fit of shape function\n\t\t(\\eqnref{band_intensities:shape})\n\t\tto the band of polyU used in intensity estimation fit is marked by a green\n\t\tline together with the area used for the intensity calculation.\n\t}\n\t\\label{\\figlabel{power_optim:triplexes2_pU}}\n\\end{figure}\n\nThe polyU band at 1230\\,\\icm{} can then be modeled directly without the\ninterference of the cacodylate band at 1276\\,\\icm{}.\nIt can be seen from the polyU band intensity dependence plot in\n\\figref{power_optim:triplexes2}\nthat the background subtraction process slightly obscures the intensity\nnormalization so that the fast decay curves cannot be modeled here.\nHowever, we can also see a slower decay trend which is not evident from the fit\nto the intensities of the polyU band calculated from the spectra without\nsubtracted background.\nThis is caused by the fact that it is harder to reliably decouple\nthe contribution of the overlapping polyU and cacodylate bands with the\nlowering polyU band intensity.\n\n\\begin{figure}\n\t\\centering\n\t\\input{results_and_discussion/assets/power_optimization_triplexes2/%\n\t\tpower_optimization_triplexes2}\n\t\\caption[%\n\t\tDecrease of the integral intensity of the polyU band at 1231\\,\\icm{}\n\t\tfor different excitation powers in background-corrected spectra.%\n\t]{%\n\t\t\\captiontitle{%\n\t\t\tDecrease of the integral intensity of the polyU band at 1231\\,\\icm{}\n\t\t\tfor different excitation powers in background-corrected spectra.%\n\t\t}\n\t\tThe intensity was normalized to the subtracted spectrum of cacodylate\n\t\tbuffer, which was used as the internal intensity standard.\n\t\tThe values were fitted by exponential decay curves\n\t\t\\eqnref{power_optim:decay}.\n\t\tThe baseline constant $b$ from the fit was subtracted from the plots.\n\t}\n\t\\label{\\figlabel{power_optim:triplexes2}}\n\\end{figure}\n\nFor analysis of the optimal measurement conditions, we ignored the first 3, 3,\nand 10 spectra for excitations at 1, 2, and 10\\,mW, respectively, which visibly\ndeviated from the slow decay curves.\nWe used\n\\eqnref{power_optim:decay}\nto estimate the lifetime $\\tau$, total accumulated energy fractions $E_0$, and\nenergy fractions $E$ accumulated from time $T = 60\\pm20$\\,s the same way as\nfor the samples without subtracted background (see\n\\tabref{power_optim:lifetimes_triplexes2}).\nThe baseline constant $b$ was used only for the power of 10 mW, where it\ndecayed quickly to constant noise caused by the fit for an almost undetectable\nband.\nThe table clearly shows that the slow decay process depends linearly on\nexcitation power.\nIn other words, the total accumulated energy is the same for all the\nexcitation powers, and that the lifetime is inversely related to the excitation\npower.\n\n\\begin{table}\n\t\\centering\n\t\\input{results_and_discussion/assets/power_lifetimes_triplexes2}\n\t\\caption[%\n\t\tLifetimes of the polyU in dependence on excitation power estimated from\n\t\tthe background-corrected spectra.%\n\t]{%\n\t\t\\captiontitle{%\n\t\t\tLifetimes $\\tau$ of the polyU in dependence on excitation power $P$\n\t\t\testimated from the background-corrected spectra.%\n\t\t}\n\t\t$E_0$ are total energies accumulated by detector divided by maximal value\n\t\tacross all the excitation powers $P$, and $E$ are energies accumulated from\n\t\tthe time $T = 60\\pm20$\\,s, which was needed for the adjustment of the\n\t\tsamples before the acquisition can even start, but the sample needs to\n\t\tbe irradiated by the excitation laser.\n\t\tThe last column contains fractions of the samples $r$ that were not\n\t\tdestroyed by photodecomposition after time $T$.\n\t}\n\t\\label{\\tablabel{power_optim:lifetimes_triplexes2}}\n\\end{table}\n\nWe can see that the system is complex, and our current methods cannot correctly\nanalyze the underlying processes.\nPhotoproducts can influence the resulting spectra, and therefore we\ndecided to use relatively lower excitation powers like 1\\,mW or 0.5\\,mW even\nthough the higher excitation power could probably give higher quality spectra.\n\nWe also tried to optimize the excitation laser power for the backscattering\nmeasurements in thermostated cell holder.\nWe used 3\\,mL of 125\\,\\g{m}M polyU samples dissolved in 40\\,mM cacodylate\nbuffer with pH 6.8.\n257\\,nm was used as an excitation laser wavelength and a magnetic stirred\nstirred the samples.\nThe spectral series was measured in 20\\,s accumulation time per\nspectrum.\nThe measurements in the thermostated cell holder were easier to set up\nbecause the backscattering geometry and robust construction of the holder\nwere less sensitive to displacements which meant that the adjustments could be\nperformed on helper samples and, the real samples weren't exposed to the\nlaser power before measurement.\n\nThe analysis of the results was performed with the same steps as the analysis\nof the measurements with a spinning cell using the integral intensity of the\npolyU band at 1231\\,\\icm{} and the cacodylate band at 607\\,\\icm{}.\nAs we used 20 times\nlarger volumes of samples and 4 times lower concentrations, we should roughly\nexpect 5 times longer lifetimes, which means that we could observe only the\nfast decay components, (see\n\\figref{power_optim:hairpins}\nand\n\\tabref{power_optim:lifetimes_hairpins}).\n\n\\begin{figure}\n\t\\centering\n\t\\input{results_and_discussion/assets/power_optimization_hairpins/%\n\t\tpower_optimization_hairpins}\n\t\\caption[%\n\t\tDecrease of the integral intensity of the polyU band at 1231\\,\\icm{}\n\t\tfor different excitation laser powers in raw spectra using\n\t\tbackscattering geometry.%\n\t]{%\n\t\t\\captiontitle{%\n\t\t\tDecrease of the integral intensity of the polyU band at 1231\\,\\icm{}\n\t\t\tfor different excitation laser powers in raw spectra using\n\t\t\tbackscattering geometry.%\n\t\t}\n\t\tIt was normalized to the integral intensity of the cacodylate band at\n\t\t607\\,\\icm{}, which was used as the internal intensity standard.\n\t\tThe values were fitted by exponential decay curves\n\t\t\\eqnref{power_optim:decay}.\n\t\tThe baseline constant $b$ from the fit was subtracted from the plots.\n\t}\n\t\\label{\\figlabel{power_optim:hairpins}}\n\\end{figure}\n\n\\begin{table}\n\t\\centering\n\t\\input{results_and_discussion/assets/power_lifetimes_hairpins}\n\t\\caption[%\n\t\tLifetimes of the polyU in dependence on excitation power\n\t\testimated from raw spectra in backscattering geometry.%\n\t]{%\n\t\t\\captiontitle{%\n\t\t\tLifetimes $\\tau$ of the polyU in dependence on excitation power $P$\n\t\t\testimated from raw spectra in backscattering geometry.%\n\t\t}\n\t\t$E_0$ are total energies accumulated by detector divided by maximal value\n\t\tacross all the excitation powers $P$.\n\t}\n\t\\label{\\tablabel{power_optim:lifetimes_hairpins}}\n\\end{table}\n\nIt can be seen that the lifetimes are proportionally longer with lower\nexcitation laser power and no further special effects are observable.\nThe lifetimes are slightly lower than the expected 5 times longer lifetimes as\ncompared to the\n\\tabref{power_optim:lifetimes_triplexes}\nbut almost in the range of estimated errors.\nIt can be caused by many effects like underestimated errors, different\nexcitation laser wavelength (257\\,nm instead of 244\\,nm), less effective\nstirring in larger volumes, or longer laser path in the samples.\nWe can also see that higher intensity gives more reliable results with\nlower errors because of a better SNR.\nWe decided to perform further measurements with 4\\,mW of excitation power at\n257\\,nm and 5\\,mW at 244\\,nm.\n", "meta": {"hexsha": "28b110855f658f66b1b1937f6131e46e5bdd881a", "size": 15009, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "src/results_and_discussion/power_optimization.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/power_optimization.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/power_optimization.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": 43.2536023055, "max_line_length": 79, "alphanum_fraction": 0.7842627757, "num_tokens": 4023, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5888891163376235, "lm_q2_score": 0.32082129433083023, "lm_q1q2_score": 0.18892816852077524}}
{"text": "% !TEX root = ../zeth-protocol-specification.tex\n\n\\section{Generating the inputs of the $\\mix$ function (\\inp{\\mix})}\\label{zeth-protocol:mix-inp}\n\nIn the following section, we assume that the system is initialized. In other words, we assume that a ledger $\\ledger$ is available (i.e.~an \\ethereum~network is operated by a set of miners), the $\\mixer$ contract is deployed on $\\ledger$. Likewise, we assume that the public parameters $\\pparams_{\\zksnark} \\gets \\zksnark.\\kgen(\\secparam, \\RELCIRC)$ are available to $\\mixer$ and to all parties willing to call the $\\mix$ function of $\\mixer$. Furthermore, we assume that there exists a set of \\ethereum~and \\zeth~users, and that the \\emph{payment address} of each \\zeth~user is easily discoverable. In the rest of this section, the set of \\emph{payment addresses} discovered by a zeth user $\\zparty{U}$ is represented as a list attribute $\\zparty{U}.\\keystore$ indexed by usernames.\n\n\\medskip\n\nIn order for $\\zparty{U}$ to transact via \\zeth, $\\zparty{U}$ needs to create an object $\\inp{\\mix}$ of type $\\mixInputDType$ to pass to the $\\mix$ function of $\\mixer$:\n\\begin{enumerate}\n \\item Create an object $\\priminputs$ of type $\\primInputDType$ to represent the primary input, and an object $\\auxinputs$ of type $\\auxInputDType$ to represent the auxiliary input, where:\n \\begin{enumerate}\n \\item $\\priminputs.\\mkroot \\in \\rootset$, where $\\rootset$ is the set of \\emph{all} Merkle roots corresponding to one of the state of the Merkle tree on $\\mixer$ containing \\emph{all} the commitments to the input notes, in $\\auxinputs.\\jsins{}$, in its set of leaves.\n \\item $\\auxinputs.\\znotes{j}.\\noter \\sample \\BB^{\\noterLen}, \\forall j \\in [\\jsout]$, and $\\auxinputs.\\pphi \\sample \\BB^{\\phiLen}$\n \\item The public values $(\\auxinputs.\\vin, \\auxinputs.\\vout) \\in {(\\BB^{\\zvalueLen})}^{2}$, $\\auxinputs.\\znotes{j}.\\notev$ and $\\auxinputs.\\znotes{j}.\\apk\\ \\forall j \\in [\\jsout]$ are all set by the sender, $\\zparty{U}$, as desired as long as they satisfy the \\gls{joinsplit-eq}.\n \\item All attributes of the $\\priminputs$ and $\\auxinputs$ objects should be derived as specified in the statement (see~\\cref{zeth-protocol:statement}), alongside a signature hash ($\\auxinputs.\\hsig$) that is generated as the hash of the nullifiers and a one-time signing verification key (non-malleability, see~\\cref{appendix:trnm}), using the desired signature scheme $\\otsigscheme$ (see~\\cref{instantiation:otsig}):\n \\begin{align}\n & (\\sk_{\\otsig}, \\vk_{\\otsig}) = \\otsigscheme.\\kgen(\\secparam) \\label{zeth-protocol:otsig-generation} \\\\\n & \\auxinputs.\\hsig = \\crhhsig{\\indexedset{\\auxinputs.\\jsins{i}.\\nf{}}{i \\in [\\jsin]}, \\vk_{\\otsig}}\n \\end{align}\n \\item $\\inp{\\mix}.\\primInp \\gets \\priminputs$\n \\end{enumerate}\n \\begin{notebox}\n If one of the attributes of $\\priminputs$ and $\\auxinputs$ is not correctly generated, then the proof of computational integrity generated in the next step will be rejected on $\\mixer$, and the state of $\\mixer$ will not be modified.\n \\end{notebox}\n\\item Generate a zk-SNARK proof \\zkp~to prove, in zero-knowledge, that the relation $\\RELCIRC$ (\\cref{zeth-protocol:statement}) holds on the primary and auxiliary inputs, using the desired zk-SNARK scheme $\\zksnark$ (see~\\cref{instantiation:zksnark}):\n \\begin{enumerate}\n \\item $\\zkp \\gets \\zksnark.\\prover(\\pparams_{\\zksnark}, \\priminputs, \\auxinputs)$\n \\item $\\inp{\\mix}.\\zkproof \\gets \\zkp$\n \\end{enumerate}\n\n\\item Encrypt all the $\\auxinputs.\\znotes{}$ using the recipient's \\emph{payment address}, using the encryption scheme $\\encscheme$ (see~\\cref{instantiation:enc}).\n \\begin{enumerate}\n \\item For all $j \\in [\\jsout]$, do:\n \\begin{align*}\n & \\ct_j \\gets \\encscheme.\\enc(\\auxinputs.\\znotes{j}, \\zparty{U}.\\keystore[\\varstyle{recipient}_j].\\pubaddr.\\pkenc)\n \\end{align*}\n \\item $\\inp{\\mix}.\\ciphers \\gets \\indexedset{\\ct_j}{j \\in [\\jsout]}$\n \\end{enumerate}\n\\item Generate a signature $\\otsSigma$ on the inputs of the \\mix~function, in order to prevent any malleability attacks~(c.f.~\\cref{appendix:trnm}), using the desired signature scheme $\\otsigscheme$ (see~\\cref{instantiation:otsig}):\n \\begin{enumerate}\n \\item\\label{zeth-protocol:mix-inp:create-otsig} Using the one-time signature keypair generated in~\\cref{zeth-protocol:otsig-generation}, do:\n \\begin{align*}\n & \\datatobesigned = \\eparty{S}.\\addr \\concat \\inp{\\mix}.\\primInp \\concat \\inp{\\mix}.\\zkp \\concat \\inp{\\mix}.\\ciphers \\\\\n & \\otsSigma = \\otsigscheme.\\sig(\\sk_{\\otsig}, \\crhots{\\datatobesigned})\n \\end{align*}\n \\item $\\inp{\\mix}.\\otssig \\gets \\otsSigma$\n \\item $\\inp{\\mix}.\\otsvk \\gets \\vk_{\\otsig}$\n \\end{enumerate}\n Here, $\\eparty{S}.\\addr$ represents the address of the $\\ethereum{}$ user $\\eparty{S}$ who must sign the transaction (see~\\cref{zeth-protocol:create-tx}). In general, this is likely to be owned by the holder $\\zparty{U}$ of the $\\zeth{}$ notes to be spent, but this is not a requirement.\n\\end{enumerate}\n\n\\begin{remark}\\label{zeth-protocol:mix-inp:otsig-for-dispatch-call}\n \\cref{zeth-protocol:process-tx:dispatch-call} describes a situation in which the proof data $\\inp{\\mix}.\\zkp$ is not available (having been verified by some external mechanism). In such cases, $\\datatobesigned$ in \\cref{zeth-protocol:mix-inp:create-otsig} \\MAY{} be replaced with:\n \\[\n \\datatobesigned = \\eparty{S}.\\addr \\concat \\inp{\\mix}.\\primInp \\concat \\inp{\\mix}.\\ciphers\n \\]\n This modification, mentioned here for completeness, \\MUSTNOT{} be used except as described in \\cref{zeth-protocol:process-tx:dispatch-call}.\n\\end{remark}\n", "meta": {"hexsha": "0f0ec0bdc2082914e28105e4cbe653152aa3fd6d", "size": 5769, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "chapters/chap02-sec03.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-sec03.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-sec03.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": 96.15, "max_line_length": 783, "alphanum_fraction": 0.692841047, "num_tokens": 1737, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.2942149783515162, "lm_q1q2_score": 0.1884846641629257}}
{"text": "\\subsection{Jets}\n\\label{sec:jet}\n\nJets are another important features for many physics analyses at the LHC, and especially the key signatures for vector boson fusion/scattering (VBF/VBS) processes.\nIn ATLAS detector, jets are reconstructed as groups of topologically associated energy deposits in the calorimeters, \ntracks associated with charged particles measured in the inner tacking detector, or simulated particles.\nThis section introduces the jet reconstruction, jet energy scale (JES) calibration and the b-jet tagging techniques.\n\n\\textbf{Jet reconstruction}\n\nJets are reconstructed using anti-$k_{t}$ algorithm~\\cite{Cacciari_2008} within various radius parameter $R$,\nand usually $R = 0.4$, namely small-$R$ jets, are used in most cases.\nThe \\textsc{FastJet} software package\\cite{Cacciari2012} is utilized for jet finding and reconstruction.\nA collection of four-momentum vectors are used as inputs at each combination step in jet clustering, \nthe total four-momentum is therefore computed as the sum of four-vector of all its constituents.\nThere are three types of jets in ATLAS:\n\\begin{itemize}\n\t\\item \\textit{Truth jets:} use stable simulated particles as the inputs to jet algorithm.\n\t\\item \\textit{Track jets:} use charged tracks measured from inner detector as inputs to jet algorithm.\n\t\\item \\textit{Calorimeter jets:} make use of the energy deposits in calorimeters as inputs to jet algorithm.\n\\end{itemize}\nFigure~\\ref{fig:jet_reco_overview} shows the schematic of ATLAS jet reconstruction.\n\\begin{figure}[!htb]\n \\centering\n \\includegraphics[width=1.0\\textwidth]{figures/Simulation/threetypes_jet_reco.png}\n \\caption{A overview schematic of ATLAS jet reconstruction~\\cite{Aad:2014bia}.}\n \\label{fig:jet_reco_overview}\n\\end{figure}\n\nThe \\textit{truth jets} are reconstructed using anti-$k_{t}$ algorithm with $R = 0.4$ by using final-state, stable particles from MC simulation as inputs.\nIt requires the candidate particles with lifetime $c_{\\tau}$ > 10 mm and excludes the particles from pile-up.\nTruth jets with $p_{T} > 7 GeV$ and $|\\eta| < 4.5$ are then used for jets calibration described later.\n\nThe \\textit{track jets} are reconstructed from charged particles within the full acceptance of inner detector ($|\\eta| < 2.5$).\nThe track reconstruction has been introduced in section~\\ref{sec:track}.\nReconstructed jets with $p_{T} > 500 MeV$ and associated with primary vertex are then selected.\nTracks are assigned to jets using ghost association\\cite{CACCIARI2008119}, a procedure that treats selected tracks as four-vectors of infinitesimal magnitude during the jet reconstruction and assigns them to the jet which they are clustered with.\nIn addition, muon track segments are used as a compensation for those uncaptured jet energy carried by energetic particles passing through the calorimeters without being completely absorbed.\nSimilar to the ID track, muon segments are assigned to jets using the method of ghost association mentioned above as well.\n\nThe \\textit{calorimeter jets} are reconstructed using a set of three-dimensional, positive-energy topological clusters (topo-clusters) made of calorimeter cell energies as input to the anti-$k_{t}$ algorithm\\cite{Aaboud:2017jcu}.\nTopo-clusters are built from nearby calorimeter cells that contains a significant energy above a noise threshold,\nwhich is estimated from measurements of calorimeter electronic noise and simulated pile-up noise.\nThose calorimeter cell energies are measured at electromagnetic energy scale (EM scale) corresponding to the energy deposited by electromagnetically interacting particles. \nAnd jets passing a \\pt threshold of 7 GeV are reconstructed with the anti-$k_{t}$ algorithm.\n\n\\textbf{Jet energy scale calibration}\n\nFigure~\\ref{fig:jet_cali} elaborates an overview of ATLAS jet calibration scheme for EM-scale calorimeter jets.\nIn this procedure, the jet energies are scaled to truth jets, which is reconstructed at the particle-level.\nEach step of the calibration corrects the full four-momentum unless otherwise stated, scaling the jet \\pt, energy, and mass.\n\\begin{figure}[!htb]\n \\centering\n \\includegraphics[width=1.0\\textwidth]{figures/Simulation/jet_calibration.png}\n \\caption{A overview schematic of ATLAS jet calibration\\cite{Aaboud:2017jcu}.}\n \\label{fig:jet_cali}\n\\end{figure}\n\nFirst of all, the origin correction recompute the four-momentum of jets to point them to the hard-scatter primary vertex instead of the centre of detector, and in the meantime keep the jet energy unchanged.\nThis correction improves the $\\eta$ resolution of jets by roughly 25\\% at a jet $p_{T}$ of 20~\\gev~ and > 5 times improvement for jet with $p_{T}$ above 200~\\gev, \nas measured from the difference between reconstructed jets and truth jets in MC simulation.\nSecondly, the pile-up correction is adopted to remove the excess energy due to in-time and out-of-time pile-up,\nwhich consists of two processes: an area-based $p_{T}$ density subtraction applied on the top of each event; and a residual correction derived from the simulation.\nThirdly, the absolute JES calibration corrects the jet four-momentum to the particle-level energy scale, using truth jets in di-jet MC events.\nFurthermore, the step of global sequential calibration uses calorimeter, track and MS-based variables to reduce the flavor dependence and energy leakage effects.\nFinally, the residual in situ calibration is utilized to correct jets in data by using well-measured objects such as photons, Z bosons and calibrated jets.\n\n\\textbf{B-jet tagging}\n\nTagging of b-jets plays a important role in many physics analyses involving b- or t- quark.\nIn the meantime, lots of analyses need to apply b-jet veto to suppress \\ttbar process.\nThere are three major types of algorithms that have been developed to distinguish b-quark jets from light-quark (u,d,s) jets~\\cite{ATL-PHYS-PUB-2016-012}:\n\\begin{itemize}\n\t\\item \\textbf{Impact parameter based algorithms (IP2D and IP3D):} b-hadrons usually have long lifetime ($\\sim$1.5 ps, $c_{\\tau}\\sim450~\\mu$m), which leads to large impact parameter for tracks produced from b-hadron decay. The impact parameter taggers are developed based on these variables. The IP2D tagger makes use of the transverse impact parameter significance $d_{0}/\\sigma(d_{0})$ as discriminant, while IP3D tagger uses two-dimensional discriminant of both transverse and longitudinal impact parameter significances: $d_{0}/\\sigma(d_{0})$ and $z_{0}sin\\theta/\\sigma(z_{0})$.\n\t\\item \\textbf{Secondary vertex finding algorithm (SV1)} makes use of the secondary vertex formed by decay products of b-hadron within the jet. All track pairs within a jet are tested for a two-track vertex hypothesis, and removed if they are likely to originate from a long-live particle decay (eg. $K_{s}$ or $\\Lambda$), hadronic interactions or photon conversions. After that, a new vertex is fitted with all tracks from remaining two-track vertices, and the outliers are removed from this set of tracks.\n\t\\item \\textbf{Decay chain multi-vertex algorithm (JetFitter)}\\cite{Piacquadio_2008} exploits the topological structure of weak b- and c- hadron decays inside the jet and tries to reconstruct the full b-hadron decay chain. A Kalman filter is adopted to find a common line between primary vertex and b-/c- vertices, as well as their position in this line, which gives a approximated flight path for the b-hadron. In this approach, the b- and c-hadron vertices, whenever resolution allows, can be resolved, even when there is only a single track associated to them.\n\\end{itemize}\nThe final discrimination commonly used in many physics analyses is called \\textbf{Multivariate Algorithm (MV2)}, which is based on Boosted Decision Tree (BDT) implemented in the TMVA package\\cite{Speckmayer_2010} by combining the outputs from underlying taggers mentioned above.\nThe MV2 was trained using jets in $t\\bar{t}$ sample, where the b-jets are treated as signal while the c- and light-flavor jets are treated as backgrounds.\nThere are three kinds of MV2 depending on the fraction of c-jets in background for training: \\textit{MV2c00}, \\textit{MV2c10} and \\textit{MV2c20}.\nFigure~\\ref{fig:jet_mv2} presents the output score of MV2c10 for different flavor jets.\n\\begin{figure}[!htb]\n \\centering\n \\includegraphics[width=0.5\\textwidth]{figures/Simulation/jet_mv2c10.png}\n \\caption{MV2c10 BDT output for b- (solid blue), c- (dashed green) and light-flavour (dotted red) jets in $t\\bar{t}$ events\\cite{ATL-PHYS-PUB-2016-012}.}\n \\label{fig:jet_mv2}\n\\end{figure}\n", "meta": {"hexsha": "7cf55c399ee1f0da290d8ceaf21931a662687067", "size": 8521, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "chapters/Simulation/jet.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/Simulation/jet.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/Simulation/jet.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": 96.8295454545, "max_line_length": 582, "alphanum_fraction": 0.7929820444, "num_tokens": 2087, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.35220178884745895, "lm_q1q2_score": 0.1884626237717569}}
{"text": "\\chapter{The Transition to Planet Formation}\n\\label{ch:planets}\n\n\\marginnote{\n\\textbf{Suggested background reading:}\n\\begin{itemize}\n\\item \\href{http://adsabs.harvard.edu/abs/2014prpl.conf..547J}{Johansen, A., et al. 2014, in \"Protostars and Planets VI\", ed.~H.~Beuther et al., pp.~547-570} \\nocite{johansen14a}\n\\end{itemize}\n\\textbf{Suggested literature:}\n\\begin{itemize}\n\\item \\href{http://adsabs.harvard.edu/abs/2010ApJ...722.1437B}{Bai, X.-N., \\& Stone, J.~M. 2010, ApJ, 722, 1437} \\nocite{bai10a}\n\\end{itemize}\n}\n\nIn this final chapter, we will finish our discussion of the transition from star formation to planet formation. We have already seen in chapter \\ref{ch:late_disk} that the interstellar dust grains that are captured in a star's disk will begin to collide with one another and grow, and that they will reach macroscopic size on time scales shorter than the observed disk lifetime. We now seek to sharpen our understanding of how these solids will evolve. We will continue to make use of fiducial numbers from the minimum mass Solar nebula (MMSN) that we introduced in chapter \\ref{ch:late_disk}.\n\n\\section{Dynamics of Solid Particles in a Disk}\n\n\\subsection{Forces on Solids}\n\nWe begin our discussion by attempting to determine the dynamics of solid particles orbiting in a protoplanetary disk. Consider such a particle. Because the mass of the disk is very small compared that of the star, we can neglect the gravitational force it exerts in the radial direction, and thus the radial gravitational acceleration felt by the particle is simply $g_\\varpi = G M/\\varpi^2$, where $M$ is the star's mass and $\\varpi$ is the distance from the star. \n\nIn the vertical direction we have the gravitational pull of both the star and the disk itself, and we have to think a bit more. However, one can show fairly easily that, for material distributed with the thermal scale height of the disk, the star's vertical gravity must dominate as well. The star's vertical gravitational force is \n\\begin{equation}\ng_{z,*} = \\frac{z}{\\varpi} g_\\varpi = \\Omega^2 z,\n\\end{equation}\nwhere $z$ is the distance above the disk midplane and $\\Omega$ is the angular velocity of a Keplerian orbit. We can approximate the disk as an infinite slab of surface density $\\Sigma$; the gravitational force per unit mass exerted by such a slab is\n\\begin{equation}\ng_{z,d} = 2\\pi G \\Sigma.\n\\end{equation}\nThe ratio of the stellar force to the disk force at a distance $H$ off the midplane, the typical disk height, is\n\\begin{equation}\n\\frac{g_{z,*}}{g_{z,d}} = \\frac{\\Omega^2 H}{2\\pi G \\Sigma} = \\frac{c_g \\Omega}{2\\pi G \\Sigma} = \\frac{Q}{2},\n\\end{equation}\nwhere in the last step we substituted in the Toomre $Q=\\Omega c_g/(\\pi G \\Sigma)$ for a Keplerian disk.\n\nThus the vertical gravity of the disk is negligible as long as it is Toomre stable, $Q\\gg 1$. For our MMSN,\n\\begin{equation}\n\\label{eq:QMMSN}\nQ=55 \\varpi_0^{-1/4},\n\\end{equation}\nso unless we are {\\it very} far out, stellar gravity completely dominates. As a caveat, it is worth noting that we implicitly assumed that the scale height $H$ applies to both the gas and the dust, even though we calculated it only for the gas. In fact, the motion of the dust is more complex, and, as we will see shortly, the assumption that the dust scale height is the same as that of the gas is not a good one. Nonetheless, neglecting the self-gravity of the disk is a reasonable approximation until significant gas-dust separation has occurred.\n\nThe other force on the solids that we have to consider is drag. Aerodynamic drag is a complicated topic, but we can get an estimate of the drag force for a small, slowly moving particle that is good to order unity fairly easily. Consider a spherical particle of size $s$ moving through a gas of density $\\rho$ and sound speed $c_g$ at a velocity $v$ relative to the mean velocity of the gas. First note that for small particles the mean free path of a gas molecule is larger than the particle size -- Problem Set 5 contains a computation of the size scale up to which this remains the case.\n\nFor such small grains it is a reasonable approximation to neglect collective behavior of the gas and view it as simply a sea of particles whose velocity distribution does not change in response to the dust grain moving through it. If the particle is moving slowly compared to the molecules, which will be the case for most grains, then the rate at which molecules strike the grain surface will be\n\\begin{equation}\n\\mbox{collision rate} \\approx 4\\pi s^2 \\frac{\\rho}{\\mu m_{\\rm H}} c_g,\n\\end{equation}\nwhere $\\mu$ is the mean mass per molecule, so $\\rho/\\mu m_{\\rm H}$ is the number density. This formula simply asserts that the collision rate is roughly equal to the grain area times the number density of molecules times their mean speed.\n\nIf the grain were at rest the mean momentum transferred by these collisions would be zero. However, because it is moving, collisions on the forward face happen at a mean velocity of $\\sim c_g+v$, and those on the backward face have a mean velocity $\\sim c_g-v$. Thus, averaging over many collisions, there will be a net momentum transfer per collision of $\\mu m_{\\rm H} v$. The net rate of momentum transfer, the drag force, is therefore the product of this with the collision rate:\n\\begin{equation}\nF_D = C_D s^2 \\rho v c_g,\n\\end{equation}\nwhere $C_D$ is a constant of order unity.\n\nIntegrating over the Boltzmann distribution and assuming that all collisions are elastic and that the reflectance is in random directions (so-called diffuse reflection), appropriate for a rough surface, gives $C_D = 4\\pi/3$. With this value of $C_D$, this formula is known as the Epstein drag law. It becomes exact in the limit $s\\ll \\mbox{mean free path}$, $v \\ll c_g$, and for pure elastic, diffuse reflection. Larger bodies experience Stokes drag, in which the dependence changes from $s^2 \\rho v c_g$ to $s^2 \\rho v^2$, but we will not worry about that for now. Finally, note that solid particles will not experience significant pressure forces, since they are so much more massive than the molecules that provide pressure.\n\n\\subsection{Settling}\n\nNow let us consider what the combination of vertical gravity and drag implies. The vertical equation of motion for a particle is\n\\begin{equation}\n\\frac{d^2 z}{dt^2} = -g_z - \\frac{F_D}{\\frac{4}{3}\\pi s^3 \\rho_s} = -\\Omega^2 z - \\frac{\\rho c_g}{\\rho_s s} \\frac{dz}{dt}\n\\end{equation}\nwhere $\\rho_s$ is the density of the solid particle. This ODE represents a damped harmonic oscillator: the gravitational term is the linear restoring force, and the drag term is the damping term. Within one gas scale height of the midplane $\\rho$ is roughly constant, $\\rho \\approx \\Sigma/H = 3\\times 10^{-9} \\varpi_0^{-11/4}$ g cm$^{-3}$. For constant $\\rho$ the ODE can be solved analytically:\n\\begin{equation}\nz = z_0 e^{-t/\\tau},\n\\end{equation}\nwhere\n\\begin{equation}\n\\tau = 2\\frac{\\rho_s s}{\\rho c_g} \\left[1 - \\left(1 - \\frac{4 s^2 \\rho_s^2 \\Omega^2}{\\rho^2 c_g^2}\\right)^{1/2}\\right]^{-1}.\n\\end{equation}\n\nIf the term in the square root is negative, which is the case when $s$ is large, the damping is not strong enough to stop particles before they reach the midplane, and they instead perform a vertical oscillation of decreasing magnitude. If it is positive, they simply drift downward, approaching the midplane exponentially. The minimum time to reach the midplane occurs when the particles are critically damped, corresponding to the case where the square root term vanishes exactly. Critical damping occurs for particles of size\n\\begin{equation}\ns_c = \\frac{\\rho c_g}{2 \\rho_s \\Omega} = 850 \\varpi_0^{-3/2} \\rho_{s,0}^{-1}\\mbox{ cm},\n\\end{equation}\nwhere $\\rho_{s,0} = \\rho_s/(1\\mbox{ g cm}^{-3})$.\n\nThus all objects smaller than $\\sim 10$ m boulders will slowly drift down to the midplane without oscillating. For $s\\ll s_c$, we can expand the square root term in a series to obtain\n\\begin{equation}\n\\tau \\approx 4 \\frac{\\rho_s s}{\\rho c_g} \\left(\\frac{s}{s_c}\\right)^{-2} = \\frac{\\rho c_g}{\\rho_s \\Omega^2 s} = 270 \\varpi_0^{11/4} \\rho_{s,0}^{-1} s_0^{-1}\\mbox{ yr},\n\\end{equation}\nwhere $s_0 = s/(1\\mbox{ cm})$. \n\nThus 1 cm grains will settle to the midplane almost immediately, while interstellar grains, those $\\sim 1$ $\\mu$m in size, will take several Myr to reach the midplane. Of course these very small grains will also collide with one another and grow to larger sizes, which will let them sediment more rapidly. In practice coagulation and sedimentation occur simultaneously, and each enhances the other: growth helps particle sediment faster, and sedimentation raises the density, letting them collide more often.\n\n\\subsection{Radial Drift}\n\nWe have just considered the consequences of the forces acting on solid particles in the vertical direction. Next let us consider the radial direction. The homework includes a detailed solution to this problem for small particles, so we will not go through the calculation, just the qualitative result. The basic idea is that gas in the disk is mostly supported by rotation, but it also has some pressure support. As a result, it orbits at a slightly sub-Keplerian velocity. Solid bodies, on the other hand, do not feel gas pressure, so they can only remain in orbit at constant radius if they orbit at the Keplerian velocity. The problem is that this means that they are moving faster than the gas, and thus experience a drag force.\n\nProblem Set 5 contains a calculation showing that the difference in velocity between the Keplerian speed and the speed with which a particle orbits is\n\\begin{equation}\n\\Delta v = \\frac{n c_g^2}{2 v_K} = \\eta v_K\n\\end{equation}\nwhere the pressure in the disk is assumed to vary with distance from the star as $P\\propto \\varpi^{-n}$, $c_g$ is the gas sound speed, and the dimensionless quantity $\\eta = n c_g^2/2 v_K^2$, which depends only on the local properties of the disk, has been defined for future convenience. At 1 AU for our minimum mass solar nebula model, this velocity is about $70 n$ m s$^{-1}$.\n\nDrag takes away angular momentum, in turn causing the bodies to spiral inward. We can parameterize this effect in terms of the stopping time \n\\begin{equation}\nt_s = \\frac{mv}{F_D},\n\\end{equation}\nwhere $m$ and $v$ are the body's mass and velocity, and $F_D$ is the drag force it experiences. The stopping time is simply the characteristic time scale required for drag to stop the body.\n\nConsider a spherical solid body of size $s$. For the Epstein law, which we discussed last time, $F_D \\propto s^2$, while for Stokes drag, which describes larger bodies, $F_D \\propto s^2$ at low Reynolds and $s$ at high Reynolds number. On the other hand, for a body of fixed density the mass varies as $s^3$, so the acceleration produced by drag must be a decreasing function of $s$. The stopping time is therefore an increasing function of $s$. Intuitively, big things have a lot of inertia per unit area, so they are hard to stop. Little things have little inertia per unit area, so they are easy to stop.\n\nNow consider two limiting cases. Very small bodies will have stopping times $t_s$ much smaller then their orbital periods $t_p$, so they will always be forced into co-rotation with the gas. Since this makes their rotation sub-Keplerian, they will want to drift inward. The rate at which they can drift, however, will also be limited by gas drag, since to move inward they must also move through the gas. Thus we expect that the inward drift velocity will also decrease as the stopping time decreases, and thus as the particle size decreases. To summarize, then, for $t_s/t_p \\ll 1$, we expect $v_{\\rm drift} \\propto s^p$, where $p$ is a positive number. Small particles drift inward very slowly, and the drift speed increases with particle size for small $s$.\n\nNow consider the opposite limit, $t_s \\gg t_p$. In this case, the drag is unable to force the solid body into co-rotation on anything like the orbital period, so the body is always in a near-Keplerian orbit, and just slowly loses angular momentum to drag. Clearly in this case the rate at which this causes the particle to drift inward will decrease as the stopping time increases, and thus as the particle size increases. Summarizing this case, then, for $t_s/t_p \\gg 1$, we expect $v_{\\rm drift} \\propto s^{-q}$, where $q$ is a positive number.\n\nSince the inward drift speed rises with particle size at small sizes and decreases with particle size at large sizes, there must be some intermediate size with it reaches a maximum. Conversely, the time required for drag to take away all of a body's angular momentum, so that it spirals into the star, must reach a minimum at some intermediate size. Problem set 5 contains a calculation showing that even for 1 cm pebbles the loss time is a bit shorter than the disk lifetime, and 1 cm pebbles are in the regime where $t_s \\ll t_p$. The drift rate reaches a maximum for $\\sim 1$ m radius objects, and for them the loss time can be as short as $\\sim 100$ yr. For km-sized objects the drift rate is back down to the point where the loss time is $\\sim 10^5$ to $10^6$ yr. \n\n\\section{From Pebbles to Planetesimals}\n\nThe calculation we have just completed reveals a serious problem in how we can continue the process of growing the solids to larger sizes, forming planets and clearing away disks: it seems that once growth reaches $\\sim 1$ m sizes, all those bodies should be dragged into the star in a very short amount of time. We therefore next consider how to overcome this barrier.\n\n\\subsection{Gravitational Growth}\n\nOne solution is to skip over this size range using a mechanism that allows particles to go directly from cm to km sizes, while spending essentially no time at intermediate sizes. A natural candidate mechanism for this is gravitational instability, so we begin with a discussion of whether this might work. As noted above, the gas in the MMSN is very gravitationally stable, $Q \\sim 50$. However, we also saw that solids will tend to settle toward the midplane, and the solids have a much smaller velocity dispersion than the gas. The Toomre $Q$ for the solid material alone is\n\\begin{equation}\nQ_s = \\frac{\\Omega c_s}{\\pi G \\Sigma_s}\n\\end{equation}\nwhere $c_s$ and $\\Sigma_s$ are the velocity dispersion and surface density of the solid material. To see what velocity dispersion is required, note that this definition of $Q$ lets use write $Q_s$ in terms of $Q_g$ as\n\\begin{equation}\nQ_s = Q_g \\left(\\frac{\\Sigma_g}{\\Sigma_s}\\right) \\left(\\frac{c_s}{c_g}\\right) \\approx(240, 60) Q_g \\left(\\frac{c_s}{c_g}\\right),\n\\end{equation}\nwhere the factors of 240 or 60 are for regions without and with solid ices, respectively.\n\nUsing equation (\\ref{eq:QMMSN}) for $Q_g$ and equation (\\ref{eq:TMMSN}) for the gas temperature, we have $Q_g\\approx 55$ and $c_g\\approx 1$ km s$^{-1}$ at 1 AU. Thus, gravitational instability for the solids, $Q_s<1$, requires that $c_s \\lesssim (30, 7)$ cm s$^{-1}$, depending on whether ice is present or not. If such an instability were to occur, the characteristic mass of the resulting object would be set by the Toomre mass\n\\begin{equation}\nM_T = \\frac{4 c_s^4}{G^2 \\Sigma_s} = (2\\times 10^{19}, 3\\times 10^{17})\\mbox{ g},\n\\end{equation}\nwhere the two numbers are again for the cases with and without ices in solid form. If we adopt $\\rho_{\\rm i,r} = (1,3)$ g cm$^{-3}$ as the characteristic densities of (icy, rocky) material, the corresponding sizes of spheres with this mass are $(20, 3)$ km. This is large enough to avoid the size range where rapid loss occurs.\n\nTo see whether this condition can be met, it is more convenient to phrase the instability criterion in terms of a density. If we use $H_s=c_s/\\Omega$ in the Toomre condition, where $H_s$ is the scale height of the solids, and we take the midplane density of the solids to be $\\rho_s \\approx \\Sigma_s/H_s$, then we have\n\\begin{equation}\nQ_s = \\frac{\\Omega^2 H_s}{\\pi G \\Sigma_s} \\approx \\frac{M_*}{\\varpi^3 \\rho_s},\n\\end{equation}\nwhere $M_*$ is the mass of the star. A detailed stability analysis by \\citet{Sekiya83a} of the behavior of a stratified self-gravitating disk shows that the instability condition turns out to be\n\\begin{equation}\n\\rho > 0.62\\frac{M_*}{\\varpi^3} = 4\\times 10^{-7} M_{*,0} \\varpi_0^{-3} \\mbox{ g cm}^{-3},\n\\end{equation}\nwhere $\\rho = \\rho_s + \\rho_g$ is the total (gas plus solid) surface density and $M_{*,0}=M_*/\\msun$. For our minimum mass solar nebula, recall that the midplane density of the gas is roughly $3\\times 10^{-9}$ g cm$^{-3}$, a factor of 100 too small for instability to set in. The question then is whether the density of solids at the midplane can rise to 100 times that of the gas.\n\nThe discussion followed here closely follows that of \\citet{youdin02a}. We have seen that drag causes solid particles to drift down to the midplane, and if this were the only force acting on them, then the density could rise to arbitrarily high values. However, there is a countervailing effect that will limit how high the midplane density can rise. If the midplane density of solids is large enough so that the solid density greatly exceeds the gas density, then the solid-dominated layer will rotate at the Keplerian speed rather than the sub-Keplerian speed that results from gas pressure. It is fairly straightforward to show (and a slight extension of one of the problems in Problem Set 5) that the rotation velocity required for radial hydrostatic balance is\n\\begin{equation}\nv_{\\phi} = \\left(1-\\eta \\frac{\\rho_g}{\\rho}\\right) v_K,\n\\end{equation}\nwhere $\\rho = \\rho_g + \\rho_s$ which approaches $v_K$ for $\\rho_g \\ll \\rho_s$, and $(1-\\eta) v_K$ for $\\rho_g \\gg \\rho_s$. Since $\\rho_s / \\rho_g$ rises toward the midplane, this velocity profile has shear in it, with $v_{\\phi}$ reaching a maximum at the midplane and dropping above it.\n\nThe shear can generate Kelvin-Helmholtz instability, which will in turn create turbulence that will dredge up the dust out of the midplane, halting settling and preventing the density from continuing to rise. A useful analogy to think about, which I borrow from \\citet{youdin02a}, is a sandstorm in the desert. Since the midplane full of dust is trying to rotating faster than the gas-dominated layer above it, there is effectively a wind blowing above the dusty midplane layer, like a wind blowing over the desert. If the wind blows too fast, it will start picking up dust, preventing it from falling back to the desert floor.\n\nIn the case of a disk, this process will self-regulate, since reducing the amount of dust in the midplane brings its rotation velocity closer to that of the gas, thereby reducing the strength of the wind. This process of self-regulation can be calculated in terms of the condition required for KH instability. To understand how the criterion for KH instability is set, it is easiest to think about the case of a physical interface -- the results are not significantly different for a continuous medium. The most common example is a pond of water with wind blowing across its surface. Imagine that there is a small ripple in the water that causes the surface to rise a little. The wind will strike the bit of the water above the surface and try to push it horizontally. At the same time gravity will try to drag the water downward.\n\nIf the wind is strong, it will push the water horizontally faster than gravity can drag it downward. The moving water will displace the surface even more, creating a growing wave, the signature of KH instability. If it is weak, gravity will drag the ripple downward before the wind is able to displace it significantly. Thus we expect the critical condition for KH instability to involve a balance between the restoring force of gravity and the destabilizing force of shear. For a continuous medium, it turns out that the condition for instability can be stated in terms of the Richardson number\n\\begin{equation}\n\\mbox{Ri} = \\frac{(g_z/\\rho) (\\partial \\rho/\\partial z)}{\\left(\\partial v_\\phi/\\partial z\\right)^2} < \\mbox{Ri}_c,\n\\end{equation}\nwhere $z$ is the vertical distance, $g_z$ is the gravitational acceleration in the vertical direction, and the critical Richardson number for instability $\\mbox{Ri}_c\\approx 1/4$.\\footnote{Note that the quantity in the numerator has units of one over time squared, so it is the square of a frequency. In fact, it is a frequency that is familiar from stellar structure: $(g_z/\\rho) (\\partial \\rho/\\partial z)$ is the square of the Brunt-V\\\"{a}is\\\"{a}l\\\"{a} frequency, the characteristic oscillation frequency for vertical displacements in a stratified medium, such as stellar atmosphere.}\n\nThe numerator here represents the stabilizing effects of gravity, which depends on both the gravitational acceleration and how quickly the density drops with height. The gravitational acceleration is\n\\begin{equation}\ng_z = \\Omega^2 z + 4\\pi G \\int_0^z \\rho(z') \\, dz',\n\\end{equation}\nwhere the first term represents the gravitational pull of the star and the second represents the self-gravity of the disk. The denominator represents the amount of destabilizing velocity shear.\n\nA reasonable approximation is that the KH instability will stop any further settling once it turns on, so the density of the solids will become as centrally peaked as possible while keeping the disk marginally stable against KH. Thus, we expect the equilibrium density profile for the solids to be the one that gives $\\mbox{Ri}=1/4$. If $\\rho_g(z)$ is known at a given radius, then the condition $\\mbox{Ri} =1/4$ fully specifies the total density profile $\\rho(z)$, since both $g_z$ and $v_\\phi$ are known functions of $\\rho$ and $\\rho_g$. Given $\\rho(z)$, it is obviously trivial to deduce the density of solids $\\rho_s(z)$. The equation can be solved numerically fairly easily, but we can gain additional insight by proceeding via analytic approximations.\n\nFirst, note that we are interested in whether a self-gravitating layer of particles can develop at all, and that until one does then we can ignore the self-gravity of the disk in $g_z$. Thus, we can set $g_z\\approx \\Omega^2 z$ for our analytic approximation. If we now differentiate the velocity profile $v_{\\phi}$ with respect to $z$, we get\n\\begin{equation}\n\\frac{\\partial v_\\phi}{\\partial z} = -\\eta \\left(\\frac{1}{\\rho} \\frac{\\partial \\rho_g}{\\partial z} - \\frac{\\rho_g}{\\rho^2}\\frac{\\partial \\rho}{\\partial z}\\right) v_K.\n\\end{equation}\nSubstituting this into the condition that the Richardson number is roughly $1/4$, and noting the $v_K = \\varpi\\Omega$, we have\n\\begin{eqnarray}\n\\mbox{Ri}_c \\approx \\frac{1}{4} \n& \\approx &\n\\frac{z}{\\eta^2 \\varpi^2} \\frac{\\rho^3 (\\partial \\rho/\\partial z)}{\\left[\\rho (\\partial \\rho_g/\\partial z) - \\rho_g (\\partial \\rho/\\partial z)\\right]^2} \\\\\n& = &\n\\frac{z}{\\eta^2 \\varpi^2} \\frac{\\rho^3 (\\partial \\rho/\\partial z)}{\\left[\\rho_s (\\partial \\rho_g/ \\partial z) - \\rho_g (\\partial \\rho_s/\\partial z)\\right]^2}.\n\\end{eqnarray}\n\nNow we make our second approximation: if we focus our attention near the midplane where solids are trying to sediment out, and are being stirred up by KH instability, the density of solids should be changing much more quickly than the density of gas. In other words, we will focus our attention at heights $z$ much smaller than the gas scale height, so we can set $\\partial \\rho/\\partial z \\approx \\partial \\rho_s/\\partial z$, and drop $\\partial \\rho_g/\\partial z$ in comparison to $\\partial \\rho_s/\\partial z$. Doing so gives\n\\begin{equation}\n\\mbox{Ri}_c \\approx \\frac{z}{\\eta^2 \\varpi^2} \\frac{\\rho^3}{\\rho_g^2 (\\partial\\rho_s/\\partial z)}\n\\end{equation}\n\nTo see what this implies, consider a layer of solids with scale height $H_s$ and surface density $\\Sigma_s$ that marginally satisfies this equation. Plugging in $z\\sim H_s$ and $\\rho_s \\sim \\Sigma_s/H_s$ gives\n\\begin{equation}\n\\mbox{Ri}_c \\sim \\frac{H_s}{\\eta^2 \\varpi^2} \\frac{(\\rho_g + \\Sigma_s/H_s)^3}{\\rho_g^2 (\\Sigma_s/H_s^2)} = \\frac{(\\rho_g H_s + \\Sigma_s)^3}{(\\eta r \\rho_g)^2 \\Sigma_s}\n\\end{equation}\nClearly this equation cannot be satisfied for arbitrarily large $\\Sigma_s$, since the RHS scales as $\\Sigma_s^2$ in this case. Physically, this indicates that our assumption that the KH instability can keep the Richardson number at the critical value must break down if the surface density of solids is too high. If we think about it, it makes sense that there is a maximum amount of solid material that the gas can keep aloft. To continue the sandstorm analogy, the wind can only keep a certain amount of sand aloft in the desert. It cannot pick up the entire desert.\n\nThus, we expect there to be a critical column density $\\Sigma_p$ at which it becomes impossible to satisfy the condition that the Richardson number is $1/4$. If $\\Sigma_p$ exceeds this critical value, the surface density at the midplane will rise arbitrarily, and gravitational instability becomes inevitable. For the case $\\Sigma_s \\gg \\rho_g H_s$, this critical value is clearly given by\n\\begin{equation}\n\\Sigma_s \\sim \\sqrt{\\mbox{Ri}_c} \\eta \\varpi \\rho_g = 2 n \\sqrt{\\mbox{Ri}_c} \\left(\\frac{c_g}{v_K}\\right)^2 \\varpi \\rho_g.\n\\end{equation}\nFor the conditions of our MMSN at 1 AU, using $n=1$ and $\\mbox{Ri}_c=1/4$, this evaluates to $70$ g cm$^{-2}$. The numerical solution for the critical surface density is $\\Sigma_s=94$ g cm$^{-2}$; the increase relative to our simple analytic estimate mostly comes from the self-gravity of the dust, which increases the shear and thus strengthens the KH instability.\n\nThis is clearly larger than the surface density of solids we have available in the MMSN, even using ices. Moreover, just increasing the total mass of the disk does not help, because $\\rho_g$ will rise along with $\\Sigma_s$, and thus the condition will not be any easier to meet. We therefore conclude that gravitational instability cannot be a viable mechanism to jump from cm to km sizes unless a way can be found to enhance the solid to gas ratio in the disk by a factor of $\\sim 3$ in the icy part of the disk, or $\\sim 10$ in the rocky part. \n\n\\subsection{Hydrodynamic Concentration Mechanisms}\n\nGravitational instability by itself will not solve the problem of the meter-size barrier, but if some other mechanism can be found to increase the solid-to-gas ratio by a factor of $\\sim 3-10$, then gravitational instability will take over and manufacture planetestimals. We therefore turn for the final topic in this chapter to what mechanisms might be able increase the solid to gas ratio by the required amount.\n\n\\begin{figure}\n\\includegraphics[width=\\linewidth]{eddies_johansen14}\n\\caption[Schematic of particle concentration by eddies in a protoplanetary disk]{\n\\label{fig:eddies_johansen14a}\nSchematic diagram of three mechanisms to concentrate particles in a protoplanetary disk, taken from \\citet{johansen14a}. The left panel shows how small-scale turbulent eddies expel particles to their outskirts. The middle panel shows how zonal flows associated with large-scale pressure bumps concentrate particles. The right panel shows concentration by streaming instabilities. In each panel, black arrows show the velocity field, and the caption indicates the characteristic length scale of the structures shown, where $H$ is the disk scale height.\n}\n\\end{figure}\n\nThe first mechanism we will examine is concentration of small particles by eddies in a disk (Figure \\ref{fig:eddies_johansen14a}). Consider a rotating eddy in a disk. By an eddy here we mean a structure where the gas moves on circular trajectories in the frame co-rotating with the disk at angular velocity $\\Omega$. Suppose that the gas at some distance $r$ from the center of an eddy is rotating at some speed $v_e$. In the rotating reference frame, there are two forces acting on the gas: pressure gradients and Coriolis forces. For the eddy to remain static, the sum of these two forces must produce an acceleration per unit mass equal to the centripetal acceleration associated with the circular motion of the eddy. Specifically, we must have\n\\begin{equation}\n2\\Omega v_e - \\frac{1}{\\rho} \\frac{dP}{dr} = -\\frac{v_e^2}{r},\n\\end{equation}\nwhere the first term is the Coriolis force per unit mass, the second is the pressure force per unit mass, and the right hand side is the centripetal acceleration. For a slowly-rotating eddy, $v_e /r \\ll \\Omega$, we can ignore the right hand side, and simply approximate that the sum of the two terms on the left is zero. Thus for slow eddies, the eddy rotation speed is given by\n\\begin{equation}\nv_e = \\frac{1}{2\\rho\\Omega} \\frac{dP}{dr}.\n\\end{equation}\nWe see that if the eddy is associated with a pressure maximum, $dP/dr < 0$, then $v_e < 0$ as well, indicating that rotation is clockwise; eddies associated with pressure minima, $dP/dr > 0$, produce counter-clockwise rotation.\n\nNow let us consider the dynamics of a solid particle moving through the eddy. Returning to the inertial frame, if the eddy is rotating clockwise, $v_e < 0$, then the material that is further from the star is orbiting somewhat more slowly, while the material that is closer to the star is orbiting somewhat more rapidly. This means that the material farther from the star will have a smaller velocity difference with the sub-Keplerian solids, while the material that is closer to the star will have a somewhat larger velocity difference. The drag force is therefore smaller on the far side of the eddy, and larger on the near side. The net effect is that, as solids drift from large radii inward and encounter the eddy, their rate of drift slows down, and they tend to pile up at the location of the eddy. This is a potential mechanism to raise the local ratio of solids to gas, and thus to set off gravitational instability.\n\nThe final step in this argument is to have something that provides a pressure jump and thus can produce clockwise eddies. There are a number of possible mechanisms, including a build-up of gas at the edge of a dead zone where MRI shuts off, or simply the turbulence driven by the MRI itself. Whether this actually happens in practice is still an unsolved problem, but the mechanism is at least potentially viable.\n\nAnother possible mechanism to concentrate particles is known as the streaming instability. We will not derive this rigorously, but we can describe it qualitatively. Streaming instability operates as follows: suppose that, in some region of the disk, for whatever reason, the local density of solids relative to gas is slightly enhanced. Because we are in a mid-plane layer that is at least partly sedimented, the inertia of the solids is non-negligible. Thus while we have focused on the drag force exerted by the gas on the solids, the corresponding force on gas is not entirely negligible. This force tries to make the gas rotate faster, and thus closer to Keplerian. This in turn reduces the difference in gas and solid velocities.\n\nNow consider the implications of this: where the solid to gas ratio is enhanced, the solids force the gas to rotate closer to their velocity, which in turn reduces the drag force and thus the inward drift speed. Thus if solid particles are drifting inward, when the encounter a region of enhanced solid density, they will slow down and linger in that region. This constitutes an instability, because the slowing down of the drift enhances the solid density even further, potentially leading to a runaway instead in the gas to solid ratio. If this mechanism is able to increase the ratio enough, gravitational instability will take over and produce planetesimals.\n\n\n\n\n", "meta": {"hexsha": "5f2bfeb84da821a5f11617654d3b01fcc3c79276", "size": 31507, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "chapters/chapter21.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/chapter21.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/chapter21.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": 134.6452991453, "max_line_length": 924, "alphanum_fraction": 0.7676071984, "num_tokens": 7981, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.37387581579519075, "lm_q1q2_score": 0.18839833059079047}}
{"text": "\\chapter{Results}\n\n%\\section{Comparing the CNN to the currently used Random Forest}\nAfter the optimizing process \\num{20} CNNs were trained with the gained insights.\nA \\enquote{\\texttt{6c\\_4f}} architecture was trained with the mentioned dropout rates\nand \\num{5000} batches of pretraining for every layer.\nThe hyperparameters were set by a random grid search.\n\nFor reviewing the best, trained network, a so far unused simulated dataset has been used.\nAs a result, the separation of hadrons and gamma rays through the CNN's processing can be observed and evaluated.\nBy processing \\num{500000} events of both classes and plotting the resulting predictions,\na separation of those classes can be observed.\nAlthough many events overlap and are therefore not separable,\nboth curves are slightly skewed to their respective end of the axes.\nWith this dataset, a ROC-AUC score of \\num{0.817} can be achieved.\n\n\\begin{figure}\n \\centering\n \\includegraphics[scale=1]{Plots/CNN_MC_Evaluation.pdf}\n \\caption{Using an unseen, simulated dataset for the evaluation of the CNN's performance, a separation of the two classes is visible.}\n \\label{fig:cnn_mc_evaluation}\n\\end{figure}\n\nIn the best case a real-image dataset displays a similar distribution of the classes,\nonly distinguished from the simulated events by the ratio of hadrons to gamma rays.\nThe real-image dataset consists of data,\nwhich has been recorded between \\num{2013} and \\num{2014} and shows the activity of the Crab nebula.\nIt contains roughly \\num{20000000} events.\n\nBy comparing the histograms of the simulated and real datasets,\na distinctly smaller occurrence of gamma rays can be noted.\nThis could arise from a small ratio in the cosmic radiation\nor a poor performance of the CNN caused by a mismatch between the real and simulated datasets.\n\n\\begin{figure}\n \\centering\n \\includegraphics[scale=1]{Plots/CNN_Real_Evaluation.pdf}\n \\caption{Using a real dataset of the Crab nebula, the predictions imply a high rate of hadrons and a small rate of gamma rays in the cosmic radiation.}\n \\label{fig:cnn_real_evaluation}\n\\end{figure}\n\nSince the Crab nebula is a well surveyed source by many telescopes around the globe,\nit should be detectable with the newly predicted gamma rays at its position.\nSince every gamma ray can be retraced to its origin,\nthe gamma ray activity of six opposing positions in FACT's field of view will be compared.\nThe first position (\\enquote{On}) is the calculated position of the Crab nebula\nand contains activities of the source and the background radiation.\nThe five other positions (\\enquote{Off}) lie circular and equally spaced next to the first one\nand therefore contain only background radiation.\nIn this way a difference of activity at the Crab nebula position can be detected.\n\nThe positions will be compared using a Theta-plot.\nBoth position's centers are placed at zero on the x-axis.\nThe x-axis measures the angular distance to this position,\nwhile the y-axis depicts the activity of the cosmic region.\nThe crucial significance value summarizes this difference.\nIn this case, the Crab nebula can be detected with \\num{24.4}\\,$\\sigma$.\nSince comparable approaches with currently used Random Forest classifiers reach \\num{39.89}\\,$\\sigma$ \\cite{significance},\na poor performance of the CNN can be assumed.\n\n\\begin{figure}\n \\centering\n \\includegraphics[scale=0.8]{Plots/Theta_Plot.pdf}\n \\caption{After \\num{83.7}\\,\\si{\\hour} of observation time the Crab nebula can be seen with the CNN with a significance of \\num{24.4}\\,$\\sigma$. To optimize the significance, an angular cut at \\num{0.026} and a threshold of \\num{0.766} have been used for this plot.}\n \\label{fig:theta_plot}\n\\end{figure}\n\nThis poor performance can derive from two distinct origins:\neither the network can be optimized to overcome the performance difference\nor the simulated input data contains features which the CNN utilizes,\nthat are absent in the real images (Monte Carlo Mismatch).\nSince much effort has been put into optimizing the network,\nonly small prospective improvements can be expected from further optimization.\nTherefore, the big performance difference seems to emerge from a mismatch between the training dataset and the real images.\n\n\n\\chapter{Conclusion}\n\\section{Potential Improvements}\nTo enhance the network's performance, there are two different approaches:\non the one hand, there is the possibility of changing the input data;\non the other hand, there are further options to improve the network's structure and data handling.\nOptions to improve results will be described in the following paragraph.\nThe order follows the data's pathway through the network and its programs.\n\nFirst and foremost a simulated dataset has been used and the downside of this has been described.\nThe mismatch between simulated and real data seems to arise a malfunction when predicting real images.\nImproving this dataset would be a complex and time-consuming task without any improvement guarantees.\nAs this may not solve the problem,\na more promising approach could be to switch from generated images to real images.\nThe current classifier could predict labels for each real image, and these labels\nand images would form the training data for the network.\nIn contrast to the first approach, uncertain labels would be the main challenge to overcome.\n\nAdditionally, the flat hexagonal structure has been skewed to fit into a flat square structure.\nAlternatively, a two-dimensional hexagonal structure could be transformed to a three-dimensional cubic structure\nwithout losing any neighborhood information at all.\nFurthermore, the time series information has been lost in this thesis by summing it up.\nIn contrast to a two-dimensional convolution with loss of information, as performed in this thesis,\na four-dimensional convolution with all information could be performed for the feature generation.\nFor this, the library \\texttt{TensorFlow} will not be sufficient as such high dimensional convolutions are not yet supported.\n\nAlthough many architectures have been implemented and many hyperparameters have been independently evaluated,\nonly a small feature space could be investigated in this thesis.\nNaturally, expanding the hyperparameter optimization could yield better results.\nSince all hyperparameters form a feature space themselves, a machine learning algorithm could be designed to predict\na network's performance by using the hyperparameters as input.\nTo optimize a network's performance during the training,\na reinforcement learning algorithm (Q-Learning) could increase the network's performance.\nRewarding the reinforcement learner for increasing the best performance,\ncould achieve a more optimized network overall \\cite{q_learning}.\n\nAs the mismatch in the data will not be overcome by increasing the performance of the network itself,\nthe training data must first of all be exchanged.\nAfter that, the network proposed in this thesis could investigate the performance using the new data\ninstead to the simulated data used here.\nOnce this has been successful, the other suggestions could be implemented.\n\n\n\\section{Outlook}\nTo classify images originating from cosmic radiation, a Convolutional Neural Network has been trained on a simulated dataset.\nThis network has been optimized, evaluated and performs comparably to the currently-used Random Forest on this task.\nBy predicting real images and computing the significance of the Crab nebula, a crucial performance difference between\nthe CNN and the other classifiers emerges.\nSince CNNs have outperformed other classifiers in image classification tasks in the past,\nthis gap cannot be explained by a poorly optimized network alone.\nThe known mismatch in the simulated training dataset and the real images can be again confirmed.\nTo overcome this problem, an improved training dataset is the most promising option.\nAs simulated datasets contain the threat of mismatches every time,\ntraining the CNN on real images could be the solution.\nThis introduces the challenge of creating a dataset containing real images with reliable labels.\nAs a first step, the current classifiers could be used to label the images.\nThe most reliable images could serve as the training data for a CNN.\nThis CNN's performance could yield new insights as to whether this approach is encouraging.\n", "meta": {"hexsha": "20fc369214ec6311126d0df8b82880e610c82e05", "size": 8330, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "content/04_results.tex", "max_stars_repo_name": "JMBehnken/Bachelor_Thesis", "max_stars_repo_head_hexsha": "efc83a497e86945817e13634a310141f804939f8", "max_stars_repo_licenses": ["MIT"], "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_results.tex", "max_issues_repo_name": "JMBehnken/Bachelor_Thesis", "max_issues_repo_head_hexsha": "efc83a497e86945817e13634a310141f804939f8", "max_issues_repo_licenses": ["MIT"], "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_results.tex", "max_forks_repo_name": "JMBehnken/Bachelor_Thesis", "max_forks_repo_head_hexsha": "efc83a497e86945817e13634a310141f804939f8", "max_forks_repo_licenses": ["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.1641791045, "max_line_length": 269, "alphanum_fraction": 0.8075630252, "num_tokens": 1688, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073507867328, "lm_q2_score": 0.34158249273565866, "lm_q1q2_score": 0.18807783140030943}}
{"text": "\\nonstopmode\n\\documentclass[submission,copyright,creativecommons]{eptcs}\n\\providecommand{\\event}{LFMTP'11} % Name of the event you are submitting to\n% \\usepackage{breakurl} % Not needed if you use pdflatex only.\n\\usepackage{hyperref}\n\\usepackage{proof}\n\\usepackage[all]{xy}\n\n\\input{mymacros}\n\\newcommand{\\define}[1]{\\mbox{\\textbf{\\textit{#1}}}}\n\n\\title{A Lambda Term Representation \\\\ Inspired by Linear Ordered Logic}\n\\author{Andreas Abel\n\\institute{\nTheoretical Computer Science\\\\\nInstitut f\\\"ur Informatik\\\\\nLudwig-Maximilians-Universit\\\"at\\\\\nM\\\"unchen, Germany}\n\\email{andreas.abel@ifi.lmu.de}\n\\and\nNicolai Kraus\n\\institute{\nFunctional Programming Laboratory\\\\\nSchool of Computer Science\\\\\nUniversity of Nottingham\\\\\nNottingham, United Kingdom}\n\\email{ngk@cs.nott.ac.uk}\n}\n\\def\\titlerunning{A Lambda Term Representation Inspired by Linear Ordered Logic}\n\\def\\authorrunning{Andreas Abel and Nicolai Kraus}\n\\begin{document}\n\\maketitle\n\n\\begin{abstract}\nWe introduce a new nameless representation of lambda terms inspired by\nordered logic. At a lambda abstraction, number and relative\nposition of all occurrences of the bound variable are stored, and\napplication carries the additional information where to cut the\nvariable context into function and argument part. This way,\ncomplete information about free variable occurrence is available at each\nsubterm without requiring a traversal, and environments can\nbe kept exact such that they only assign values to variables that\nactually occur in the associated term.\nOur approach avoids space leaks in interpreters that build\nfunction closures.\n\nIn this article, we prove correctness of the new representation and\npresent an experimental evaluation of its performance in a proof\nchecker for the Edinburgh Logical Framework.\n\nKeywords:\nrepresentation of binders,\nexplicit substitutions,\nordered contexts,\nspace leaks,\nLogical Framework.\n\n% We introduce a nameless representation of lambda terms inspired by ordered logic.\n% Information about number and places of variables bound by a lambda is available without examining the whole term, thus making it possible to drop unneeded substitutions early to avoid memory leaks.\n% % We describe an implementation of this and other representations as well as suggested evaluation algorithms. These implementations were tested in Haskell by using them for typechecking large dependently typed terms of the logical framework (LF). The different needs of time and space are documented and compared.\\\\\n% We also describe our implementation experiments and present some results.\n\\end{abstract}\n\n\\section{Introduction}\n\\label{sec:intro}\n\nType checking dependent types in languages like Agda~\\cite{norell:PhD}\nand Coq~\\cite{inria:coq83} or logical frameworks like Twelf~\\cite{carsten:twelf}\nrequires a large amount of evaluation, since types may depend on\nvalues. Such type checkers incorporate\nan interpreter for purely functional programs with free variables---at least, the\n$\\lambda$-calculus---which is used to compute weak head normal forms\nof types. Efficiency of type checking is mostly identical with\nefficiency of evaluation\\footnote{Evaluation is necessary to reduce\n types to weak head normal form and compare types for equality.\n Subtracting these operations, type checking has linear complexity.\n}\n(and, in case of type reconstruction,\nefficiency of unification), and remains a challenge as of today.\nIn seminal work, Gregoire and Leroy \\cite{gregoireLeroy:icfp02} have\nsped up Coq type checking by compiling to byte-code instead of\nusing an interpreter. Boespflug \\cite{boespflug:padl10} has obtained\nfurther speed-ups by producing native code using stock-compilers.\n\nWhile compilation approaches are successful on batch type \\emph{checking}\nfully explicit programs, they have not been attempted on type\n\\emph{reconstruction} using higher-order unification or on interactive\nprogram construction such as in Agda and Epigram \\cite{mcBrideMcKinna:view}.\nThese languages are involved and constantly evolving,\nand their implementations are\nprototypes and frequently modified and extended. Implementing a\nfull compiler just to get type reconstruction going is deterring;\nfurthermore, compilation has not (yet) proven its feasibility in minor\nevaluation tasks (like weak head evaluation)\nthat dominate higher-order unification.\nAt least for language prototyping, smart\ninterpreters are, and may remain, competitive with compilation.\n\nFor instance, Twelf's interpreter is sufficiently fast; it is\ninspired by a term representation with de Bruijn indices\n\\cite{deBruijn:nameless} and explicit substitutions\n\\cite{abadiCardelliCurienLevy:jfp91}. In the context of functional\nprogramming, explicit substitutions are known as \\emph{closures},\nconsisting of the code of a function plus an environment, assigning\nvalues to the free variables appearing in the code.\nIn typical implementations of interpreters \\cite{coquand:type},\nthese environments are not\nprecise; they assign values to all variables that are statically in\nscope rather than only to those that are actually referred to in the\ncode. This bears potential for space-leaks: the environment of a\nclosure might refer to a large value that is never used, but cannot be\ngarbage collected. An obvious remedy to this threat is, when forming\na closure, to restrict the environment to the actual free variables;\nhowever, this requires a traversal of the code. We explore a\ndifferent direction: we are looking for a code representation that\nmaintains information about the free variables at each node of the\nabstract syntax tree.\n\nA principal candidate is \\emph{linear typing} in Curry-Howard\ncorrespondence with Girard's linear logic \\cite{girard:linear}; there,\neach variable in scope is actually referenced (more precisely,\nreferenced exactly once). In other words, the\nfree variables are exactly the variables in the typing context.\nDropping types, we may talk of \\emph{linear scoping}.\nYet we do not want to represent linear terms, but arbitrary\n$\\lambda$-terms. Kesner and Lengrand \\cite{kesnerLengrand:infcomp07}\nachieve this by introducing explicit term constructs for weakening and\ncontraction. We pursue a different path: we incorporate information\nabout variable use and multiplicity directly into abstraction and\napplication.\n\nIn the context of linear $\\lambda$-calculus, the free\nvariables of a function application are the disjoint union of the free\nvariables of the function and the free variables of the argument. If\nwe want to maintain the set of free variables during a term traversal,\nat an application node we need to decide which variables go into the\nfunction part and which into the argument part. Thus, we would store\nat each application a set of variables that go into the, say, function\npart, all others would go to the argument part. Less information is\nneeded if we switch to an \\emph{ordered} representation.\n\n\\emph{Ordered logic}, also called \\emph{non-commutative linear logic}\n\\cite{polakowPfenning:tlca99}, refines linear logic by removing the\nstructural rule \\emph{exchange} which restricts hypotheses to be used\n\\emph{in the order they have been declared}. Transferring this\nprinciple to ordered scoping this means that the scoping context lists\nthe free variables in the order they occur in the term, from left to\nright. This allows pushing the context into an application with very\nlittle information: we just need to know \\emph{how many} variables\nappear in the function part so we can cut the context in two at the\nright position, splitting it into function context and argument\ncontext. This constitutes the central idea of our representation: at\neach application node of the syntax tree, we store a number denoting\nthe number of free variable occurrences in the function part. During\nevaluation of an application in an environment, we can cut the\nenvironment into two, the environment needed for the evaluation of the\nfunction and the environment needed for the evaluation of the\nargument. Thus, our environments are precise and space leaks are\navoided. In particular, a variable is always evaluated in a singleton\nenvironment assigning only a value to this variable. Following this\nobservation, variables do not need a name, they are identified by\ntheir position; and environments are simply sequences of values.\n\nSince we are not interested in proof terms of ordered logic per se,\nbut only borrow the \\emph{ordered context} idea for our\nrepresentation of untyped $\\lambda$-calculus,\nwe need to allow multiple occurrences of the same\nvariable. In fact, the context shall list the variable\n\\emph{occurrences} in order. At a lambda abstraction, we bind all\noccurrences of the same variable. Thus, at an abstraction node we\nspecify at which positions the bound variable should be inserted in\nthe scoping context. This concludes the presentation of our idea.\n\nIn the rest of the paper, after an introductory example\n(Section~\\ref{sec:example}) we formally define our term representation\nin Section~\\ref{sec:syntax}. Interpreter and handling of\nenvironments are described in Section~\\ref{sec:values}, followed by\nthe translation between ordinary lambda terms and ordered terms\n(Section~\\ref{sec:parsing}). Soundness of the interpreter is formally\nproven in Section~\\ref{sec:sound}, before we conclude with an\nexperimental evaluation in Section~\\ref{sec:experiments}.\n\nThis article summarizes the B.Sc.\\ thesis of the second author\n\\cite{kraus:bachelor}.\n\n\\section{An Example}\n\\label{sec:example}\n\n% Beta reduction is an important part of evaluation in functional\n% programming languages, proof assistants and other formal\n% systems. However, implementations often involve the risk of memory\n% leaks and inefficiency. Here, we assume that all of our terms are\n% well-typed and beta reduction is therefore strongly normalizing, so\n% all we care about is efficiency.\n\n\n%To demonstrate the problem we want to deal with, we apply the term we just mentioned on the free variables $g$ and $f$, consecutively.\n%To get rid of the beta redexes, we could reduce it in the way shown below. By writing $t\\multisubs {s_1} {x_1} {s_n} {x_n}$, we want to express that in the term $t$, each occurrence of the variable $x_1$ ($x_2, \\ldots, x_n$) has to be replaced by the term $s_1$ (resp. $s_2, \\ldots, s_n$) simultaneously. Such a substitution list always applies only to the directly preceding term:\n\nTo demonstrate the discussed risk of space-leaks during evaluation, we apply the term $\\LaA x {\\LaA y {\\ApA{\\ApA a b} y}}$ in basic syntax consecutively to the free variables $g$ and $f$. A possible (and, if the mentioned closures are used, typical) sequence of reduction steps is given below.\nBy writing $t\\multisubs {s_1} {x_1} {s_n} {x_n}$, we want to express that in the term $t$, each occurrence of the variable $x_1$ ($x_2, \\ldots, x_n$) has to be replaced by the term $s_1$ (resp. $s_2, \\ldots, s_n$) simultaneously. Such a substitution list always applies only to the directly preceding term:\n\\[\n\\begin{array}{lr@{}l}\n\\shspace &(\\LaA x {\\LaA y {\\ApA{\\ApA a b} y}}) & \\sspace g \\sspace f \\\\\n\\shspace\\re &(\\LaA y {\\ApA{\\ApA a b} y}) & \\sub g x \\lspace f \\\\\n\\shspace\\re & (\\ApA{\\ApA a b} y) & \\subs g x f y \\\\\n\\shspace\\re & \\multicolumn 2 l {(a\\sspace b)\\subs g x f y \\lspace y\\subs g x f y} \\\\\n\\shspace\\re & \\multicolumn 2 l {a\\subs g x f y \\lspace b\\subs g x f y \\lspace f} \\\\\n\\shspace\\re & \\multicolumn 2 {c} {a \\sspace b \\sspace f} \\\\\n\\end{array}\n\\]\nHere, the substitution $\\sub g x$ could be dropped instantly and there is no need to apply the other substitution $\\sub f y$ to the term $\\ApA a b$.\nHowever, the term representation used above comes along with the problem that such an evaluation algorithm does not have the required information in time.\nThis is due to the fact that the binding information is always split between the $\\la$ and the actual variable occurrence, as they both carry the variable name.\nIn contrast, using de Bruijn indices would make it possible to remove the piece of information from the $\\la$.\nOur goal is to do it the other way round: We want the whole information to be available at the $\\la$, thus making it possible to know the number and places of the bound variable occurrences without looking at the whole term.\n\n\n%A term representation always has to have a way to represent that a variable is bound by a lambda.\n%For example, in the term $\\LaA x {\\LaA y {\\ApA{\\ApA a b} y}}$ in basic syntax, the information about the connection between the second $\\la$ and the last variable is split: We have to look at both the $\\la y$ and the $y$ in order to know what is going on. This may lead to some unnecessary difficulties. In contrast, the usage of de Bruijn indices makes it possible to remove the information from the $\\la$ and concentrate them on the variable. Our goal is to do it the other way round: We want the whole information to be available at the $\\la$.\n\n\n% However, the algorithm used above does not have this information in time and this is a problem that many representations come along with. Motivated by this observation, we want to describe an alternative.\n\n\\section{Syntax}\n\\label{sec:syntax}\n\n% The idea is that the information which variable is bound by which lambda should neither be split (like in the standard representation) nor carried by the variable (de Bruijn indices). Instead, it should be available as soon as the lambda becomes visible.\nIn this article, we only cover the core constructs of the lambda calculus as they are enough to make the approach clear. However, we do not see any limitations for common extensions. We first define \\define{ordered preterms}:\n\\[\n\\begin{array}{lllrll@{\\qquad}}\n\\mathsf{ordered \\ preterms} & \\ni & t,u & ::= & x & \\mbox{free variable (named $x$)} \\\\\n &&& \\mid & \\ovar & \\mbox{bound variable (nameless)} \\\\\n &&& \\mid & \\ApO t m u & \\mbox{application} \\\\\n &&& \\mid & \\LaO {\\vec k} t & \\mbox{abstraction} \\\\\n\\end{array}\n\\]\n\\emph{Free variables} are denoted by their name like in the standard syntax. \\emph{Bound variables}, however, are just denoted by a dot $\\ovar$, which does not carry any information beside the fact that it is a bound variable.\n% This, for example, means that if $\\left(\\ApO \\ovar 1 \\ovar \\right)$ is a subterm, it is not possible to tell whether we have two different variables or two times the same one without looking at the whole term.\\footnote{However, the latter possibility could not be well-typed.}\nIn the case of an \\emph{application}, there is a first term (the function part) and a second term (the argument) as usual.\nFurthermore, the application carries an integer $m$ as an additional piece of information that will be important for the evaluation process and is explained\nin a moment.\n%the number of dots $\\ovar$ in the first term which are not bound by lambdas in the first term itself should be denoted by the integer $k$. % COMMENT - there is no reason anymore to prefer the second to the first term. It might be a good idea to use the first term instead!? I have changed it now.\n%This will be important for the evaluation process.\nThe most interesting part is the \\emph{abstraction} $\\LaO {\\vec k} t$. The vector $\\vec k = \\ve{k_1, k_2, \\ldots, k_n}$ is nothing else but a list of non-negative integers of length $n$. It determines which dots $\\ovar$ are bound by the $\\la$ in the following way: Consider all $\\ovar$ in the term $t$ which are not bound in $t$ itself. Now, the first $k_1$ of these are not bound by the $\\la$, the next one is, the following $k_2$ are again not bound and so on (see examples below).\n\nWe denote the number of unbound $\\ovar$ in an ordered preterm $t$ by $\\freevars t$. Consequently, $\\freevars \\cdot$ is simply defined by:\n\\[\n\\begin{array}{cccc}\n\\freevars x = 0, & \\freevars \\ovar = 1, & \\freevars {\\ApO t m u} = \\freevars {t} + \\freevars{u}, & \\freevars {\\LaO {\\ve {k_1, \\ldots, k_n}} t} = \\freevars t - n.\n\\end{array}\n\\]\n%Note that in the case of $\\ApO t k u$, we have $k = \\freevars u$ by definition of $k$. \\\\\n% new:\nWe call an ordered preterm $u$ an \\define{ordered term} iff each sub-preterm $w$ of $u$ fulfils the following condition: If $w$ is an application $\\ApO t m u$, the equation $m = \\freevars t$ holds and if it is an abstraction $\\LaO {\\ve {k_1, \\ldots, k_n}} t$, then $n + \\sum_i k_i \\leq \\freevars t$ is satisfied. The latter condition states that if a $\\la$ in $u$ binds a variable, this variable must actually exist while the first one just gives a meaning to the integer carried by an application. Clearly, any sub-preterm of an ordered term is again an ordered term.\n%\n%Any ordered preterm $u$ is an \\define{ordered term} if each lambda abstraction $\\LaO {\\ve {k_1, \\ldots, k_n}} t$ which is a sub-preterm of $u$ satisfies the condition $n + \\sum_i k_i \\leq \\freevars t$. In other words, if a $\\la$ in $u$ binds a variable, this variable must actually exist. In addition, each sub-preterm $\\ApO t m u$ has to fulfil the condition $m = \\freevars t$.\n$u$ is called \\define{closed} if $\\freevars t = 0$.\n% From now on, we only handle terms and forget about invalid preterms.\n\nHere are some examples of closed terms.\nThe $S$ combinator\n\\[\n\\LaA x {\\LaA y {\\LaA z {\\ApA x z \\sspace \\pa {\\ApA y z}}}}\n\\]\nwould be written as\n\\[\\LaO {\\ve 0} {\\LaO {\\ve 1} {\\LaO {\\ve{1,1}} {\\ApO {\\ApO \\ovar 1 \\ovar} 2 {\\pa{\\ApO \\ovar 1 \\ovar}}}}}\n\\]\nMoreover, the term\n\\[\n(\\LaA x {\\LaA y {\\ApA{\\ApA a b} y}}) \\sspace g \\sspace f\n\\]\nfrom Section~\\ref{sec:example} would be represented as\n\\[\n\\ApO{\\left(\\ApO {\\LaO{\\emptyVec}{\\LaO{\\ve 0}{\\ApO{\\ApO{a}{0}{b}}{0}{\\ovar}}}\\right)} 0 f } 0 g\n\\]\n(note that applications are still left-associative). We can see that the first $\\la$ does not bind anything as it is annotated with the empty vector $\\emptyVec$, while this is less obvious when it is written as $\\la x$.\n\nAt this point, we hope to have clarified the intended meaning of our syntax. A formal definition will be given in Section~\\ref{sec:parsing}.\n\n\n\\section{Values and Evaluation}\n\\label{sec:values}\n\nBefore specifying values and evaluation formally, we want to give an example to demonstrate how the information carried by a lambda should be used and why we always have exactly the needed information. Suppose we have the term\n\\[\n\\left(\\LaO {\\ve 0} {\\LaO {\\ve 1} {\\LaO {\\ve{1,1}} {\\ovar \\oapp 1 \\ovar \\oapp 2 {\\pa{\\ovar \\oapp 1 \\ovar}}}}}\\right) \\sspace g \\sspace f \\sspace n\n%\\left(\\LaO {\\ve 0} {\\LaO {\\ve 1} {\\LaO {\\ve{1,1}} {\\ovar \\oapp 1 \\ovar \\oapp 2 {\\pa{\\ovar \\oapp 1 \\ovar}}}}}\\right) \\oapp 0 g \\oapp 0 f \\oapp 0 n, \\\\\n\\]\nthat is, the $S$ combinator applied to three free variables\n% i.e. the $S$ combinator which is first applied to a free variable $g$, then to $f$ and finally to $n$\n(we suppress the application indices $0$ for better readability). We want to get rid of the beta redexes, so we start by eliminating the first one. The outermost $\\la$ is decorated with the vector $\\ve 0$ of length one. Now, the single variable bound by this $\\la$ should be replaced by $g$, so we start a substitution list and insert a single $g$:\n\\[\n\\left(\\LaO {\\ve 1} {\\LaO {\\ve{1,1}} {\\ovar \\oapp 1 \\ovar \\oapp 2 {\\pa{\\ovar \\oapp 1 \\ovar}}}}\\right) \\left[ g \\right] \\lspace f \\sspace n\n\\]\nThe first remaining $\\la$ is $\\la^{\\ve 1}$, so it does not bind the first variable (thus $g$ remains first in the substitution list), but the second one. Consequently, we add an $f$ after the $g$:\n\\[\n\\left(\\LaO {\\ve{1,1}} {\\ovar \\oapp 1 \\ovar \\oapp 2 {\\pa{\\ovar \\oapp 1 \\ovar}}}\\right) \\left[ g, f \\right] \\lspace n\n\\]\nNow the situation becomes more interesting. The only remaining $\\la$ is now decorated with the vector $\\ve{1,1}$, so one $n$ has to be inserted after the first entry ($g$) and another one must be placed after the subsequent entry ($f$):\n\\[\n\\left(\\ovar \\oapp 1 \\ovar \\oapp 2 {\\pa{\\ovar \\oapp 1 \\ovar}}\\right) \\left[ g, n, f, n \\right]\n\\]\nAll $\\la$ have now been eliminated. The applications' indices tell us how the substitution list should be divided between the terms:\n\\[\n\\left(\\ovar \\oapp 1 \\ovar\\right)\\left[ g, n \\right] \\lspace \\left(\\ovar \\oapp 1 \\ovar\\right) \\left[ f, n \\right]\n% \\left(\\ovar \\oapp 1 \\ovar\\right)\\left[ g, n \\right] \\lspace \\oapp 0 \\lspace \\left(\\ovar \\oapp 1 \\ovar\\right) \\left[ f, n \\right]\n\\]\nWe do the same step once more:\n\\[\n\\ovar[g] \\lspace \\ovar[n] \\lspace \\left(\\ovar[f] \\lspace \\ovar[n]\\right)\n\\]\nThe only thing left to be done is to apply the substitutions in the obvious way:\n\\[\ng \\sspace n \\sspace (f \\sspace n)\n\\]\nHere, evaluation naturally leads to a term in beta normal form. This is not always the case: as an example, if we had tried to evaluate the above term without the $n$ (i.e. $S \\oapp 0 f \\oapp 0 g$), we would have got stuck at $\\left(\\LaO {\\ve{1,1}} {\\ovar \\oapp 1 \\ovar \\oapp 2 {\\pa{\\ovar \\oapp 1 \\ovar}}}\\right) \\left[ g, f \\right]$. However, this would have been satisfactory as it would have shown that the term's normal form is an abstraction. In other words, our evaluation results in weak head normal forms.\n\nConsequently, we define \\define{values} in the following way:\n\\[\n\\begin{array}{lllrll@{\\qquad}}\n\\mathsf{values} & \\ni & v,w & ::= & x \\sspace \\vec v & \\mbox{large application} \\\\\n% \\noalign{\\medskip}\n &&& \\mid & \\Val {\\vec k} t {\\vec v} & \\mbox{closure} \\\\\n\\end{array}\n\\]\n% \\[\n% \\mathsf{values} \\ni v, w ::= x \\, \\vec v \\ \\mid \\ \\ClosO{\\vec k}{t}{}{\\vec v}\n% \\]\nThe \\emph{large application}\\footnote{\nThe argument vector $\\vec v$ of a large application is sometimes\ncalled a \\emph{spine} \\cite{cervesatoPfenning:spineCalculus}. Large\napplications $x\\,\\vec v$ also appear in the formulation of B\\\"ohm\ntrees \\cite{barendregt:lambdacalculus}.}\n consists of a variable $x$ which is applied to a vector $\\ve{v_1, v_2, \\ldots, v_m}$ of values. It is to be read as a left-associative application, i.e. as $\\pa{\\pa{x \\, v_1} v_2 \\ldots } v_m$.\nNote that it is not necessarily ``large''. Quite the contrary, it\noften only consists of the head (and the vector of values is empty).\n\nA \\emph{closure} $\\Val {\\vec k} t {\\vec v}$ is the result of the evaluation process if the corresponding beta normal form of the term does not start with a free variable. The main part, $\\LaO {\\vec k} t$, is nothing other than a lambda abstraction in the syntax of ordered terms.\nIn addition, we need the substitution list $\\vec v$ (which is simply a list of values) that satisfies $\\length {\\vec v} = \\freevars{\\LaO {\\vec k} t}$. % as there might be unbound $\\ovar$ in $\\LaO {\\vec k} t$.\nThe idea is that the $i^{th}$ unbound $\\ovar$ is to be replaced by $v_i$. These substitution lists have already been used in the example above.\n\n\nAt this point, we want to introduce a notation for inserting a single item multiple times into a list. More precisely, if $\\vec v = [v_1, v_2, \\ldots, v_m]$ is a list,\n%(e.g. of values), % TODO neil suggests to delete this - I am not yet sure about it\n$\\vec k = [k_1, k_2, \\ldots, k_n]$ is a vector (i.e. also a list) of non-negative integers satisfying $\\sum_{i=1}^n k_i \\leq m$ and $w$ is a single item, we write $\\multiinsert {\\vec v} {\\vec k} {w}$ for the list that is constructed by inserting $w$ at each of the positions $k_1, k_1 + k_2, \\ldots, \\sum_{i=1}^n k_i$ into $\\vec v$, i.e. for the list $[v_1, v_2, \\ldots, v_{k_1}, w, v_{k_1 + 1}, \\ldots, v_{k_1 + k_2}, w, v_{k_1 + k_2 + 1}, \\ldots, v_m]$ (of course, it is possible that $\\multiinsert {\\vec v} {\\vec k} {w}$ starts or ends with $w$).\n\n\nWe are now able to define the evaluation function $\\ev {\\cdot} {\\cdot}$ which takes an ordered term $t$ as well as an ordered substitution list $\\vec v$ and returns a value. The tuple must always satisfy the condition $\\freevars t = \\length {\\vec v}$. In other words, the list carries neither too little nor redundant information.\nAt the start of the evaluation, the ordered substitution list is empty.\nAdditionally, we specify the application $\\cdot \\ap \\cdot$ of two values, which also returns a value and does not need anything else.\nOur evaluation procedure uses a call-by-value strategy:\n\n% this is not how it should be done using latex...\n\\[\n\\begin{array}{lcl@{\\qquad} r}\n \\ev x {\\emptyVec} & = & x & \\lab 1 \\\\ \\noalign{\\medskip}\n \\ev \\ovar {\\ve{v_1}} & = & v_1 & \\lab 2\\\\ \\noalign{\\medskip}\n \\ev {t \\oapp k u} {\\ve{v_1, \\ldots, v_n}} & = & {\\ev t {\\ve{v_1, \\ldots, v_k}}} \\ap {\\ev u {\\ve{v_{k+1}, \\ldots, v_n}}} & \\lab 3 \\\\ \\noalign{\\medskip}\n \\ev {\\LaO {\\vec k} t} {\\vec v} & = & \\Val {\\vec k} t {\\vec v} & \\lab 4 \\\\\n\\\\\n \\pa{x \\sspace \\vec v} \\ap w & = & x \\sspace \\ve{\\vec v, w} & \\lab 5\n\\\\ \\noalign{\\medskip}\n \\Val{\\vec k} t {\\vec v} \\ap w & = & \\ev t {\\multiinsert{\\vec v}{\\vec k}{w}} & \\lab 6\n\\end{array}\n\\]\n%\\beginalign}\n% \\ev x {\\emptyVec} &= x \\\\ %\\noalign{\\medskip}\n% \\ev \\ovar {\\ve{v_1}} &= v_1 \\\\ %\\noalign{\\medskip}\n% \\ev {t \\oapp k u} {\\ve{v_1, \\ldots, v_n}} &= {\\ev t {\\ve{v_1, \\ldots, v_k}}} \\ap {\\ev u {\\ve{v_{k+1}, \\ldots, v_n}}} \\\\ %\\noalign{\\medskip}\n% \\ev {\\LaO {\\vec k} t} {\\vec v} &= \\Val {\\vec k} t {\\vec v} \\\\\n%\\nonumber \\\\\n% \\pa{x \\sspace \\vec v} \\ap w &= x \\sspace \\ve{\\vec v, w} \\\\\n%%\\\\ \\noalign{\\medskip}\n% \\Val{\\vec k} t {\\vec v} \\ap w &= \\ev t {\\multiinsert{\\vec v}{\\vec k}{w}}\n%\\end{align}\nFirst, if we want to evaluate a free variable \\lab 1, the substitution list must be empty because of the invariant mentioned above.\nSecond, in the case of a $\\ovar$ \\lab 2, the ordered list must have exactly one entry. This entry is the result of the evaluation.\nIf we evaluate an application \\lab 3, we evaluate the left and the right term. The application's index enables us to split the substitution list at the right position. Then, we have to apply the first result to the second.\nEvaluating an abstraction \\lab 4 is easy. We just need to keep the substitutions to build a closure.\n\nIf we want to apply a large application to a value $w$ \\lab 5 , we just append $w$ to the vector of values (we write $\\ve{\\vec v, w}$ for $\\ve{v_1, \\ldots, v_n, w}$).\nThe case of a closure $\\Val {\\vec k} t {\\vec v}$ \\lab 6 is less simple, but it is still quite clear what to do: $\\vec k$ determines at which positions $w$ should be inserted in the ordered substitution list, so we just construct the list $\\multiinsert {\\vec v} {\\vec k} w$. Then, $t$ is evaluated.\n\n\nConcerning substitution lists, we talk about ``lists of values'' for\nsimplicity. More specifically, we want them to be lists of pointers to\navoid the duplication of ``real'' values during constructing lists\nlike $\\multiinsert {\\vec v} {\\vec k} {w}$.\nInstead of simple linked lists,\nwe have also implemented these lists as dynamic functional arrays\nrepresented as binary trees. This reduces the asymptotic costs of\nlist splitting---$[v_1,\\dots,v_n]$ to\n$([v_1,\\dots,v_k],[v_{k+1},\\dots,v_n])$---\nand multi-insertion $\\multiinsert {\\vec v} {\\vec k} w$\nfrom linear to logarithmic time (in terms of the length of the list\n$\\vec v$). For an\nexperimental comparison of the two implementations\nsee Section~\\ref{sec:experiments}.\n\n\n\\section{Parsing and Printing}\n\\label{sec:parsing}\n\nIn this section, we define how terms in normal syntax are translated into our ordered syntax (Parsing) and vice versa (Printing).\nTo specify this, we need some notation.\nFirst of all, we write $\\x$ for the set of variable names we want to use and $\\te$ for the set of lambda terms in basic standard syntax (i.e. $\\x \\subset \\te$, furthermore, $x \\in \\x$ together with $t, u \\in \\te$ implies $\\ApA t u \\in \\te$ and $\\LaA x t \\in \\te$). Additionally, $\\ot$ is the set of terms in our ordered syntax defined above, $\\otc$ the subset of closed ordered terms ($\\freevars t = 0$) and $\\va$ the set of values (defined in the previous section).\nMoreover, we write $\\xl$ for the set of lists of variable names and $\\vl$ for the set of lists of values.\nFor each set $\\Gamma$ of variable names ($\\Gamma \\subseteq \\x$), we denote the set of lists of elements of $\\Gamma$ by $\\gl$ and the ordered terms that do not contain any variable of $\\Gamma$ (as a free variable) by $\\otw$.\n% We will often allow $\\Gamma$ to be a finite multiset, i.e. a finite set that can contain each element more than once. The according notion of union $\\uplus$ satisfies $\\Gamma \\uplus \\{z\\} \\not= \\Gamma$.\n\nBy writing $\\ot \\otimes \\xl$ (resp. $\\ot \\otimes \\vl$, $\\otw \\otimes \\gl$, $\\ldots$), we mean the subset $\\{(t, \\vec x) \\ | \\ \\freevars t = \\length {\\vec x} \\}$ of $\\ot \\times \\xl$ (and analogous for the other cases).\n\n% \\begin{defin}\nFor a finite %multiset\nset $\\Gamma$ of variable names, we define the \\define{correspondence relation}\n% $\\parse \\cdot \\Gamma \\cdot \\ \\subset \\ \\te \\times (\\ot \\times \\xl)$.\n${\\parseb \\cdot \\Gamma \\cdot \\cdot ~ \\subset ~ \\te \\times \\ot \\times\n \\xl}$\n(pronounce: ``corresponds in context $\\Gamma$ to'').\nThe intuition is that ${\\parseb M \\Gamma u {\\vec x}}$ means:\n% The intuition is that $\\parse M \\Gamma (u, \\vec x)$ (or simply $\\parse\n% M \\Gamma {u \\, \\vec x}$) means:\n$M$ is a term that corresponds to the ordered term $u$, where unbound\n$\\ovar$ are replaced by the (\\emph{not} necessarily pairwise distinct)\nvariables in the list $\\vec x$.\n% This list $\\vec x$ of variable names may contain duplicates!\nThe set $\\Gamma$ can be seen as a filter that tells us which free variables do not occur in $u$ but in $\\vec x$ instead.\n\\[\n\\begin{array}{c@{\\qquad\\qquad} c}\n\\infnamed{\\quad (A)}{x \\in \\Gamma}{\\parseb x \\Gamma \\ovar x}\n&\n\\infnamed{\\quad (B)}{ {\\parseb M \\Gamma t {\\vec x}} \\qquad\n {\\parseb N \\Gamma u {\\vec y}} \\qquad {\\length{\\vec x} = m} }\n {\\parseb {M\\,N} {\\Gamma} {(\\ApO t m u)} {\\vec x, \\vec y} }\n\\\\ \\\\\n\\infnamed{\\quad (C)}{x \\not\\in \\Gamma}{\\parseb x \\Gamma x {}}\n&\n\\infnamed{\\quad (D)}{\n {\\parseb M { (\\Gamma \\cup \\{z\\}) } t {\\multiinsert{\\vec x}{\\vec k}{z} }}\n \\qquad\n z \\not\\in \\vec x }\n {\\parseb {\\LaA z M} {\\Gamma} {(\\LaO {\\vec{k}} t)} {\\vec x}}\n\\end{array}\n\\]\n%\\end{defin}\nIt is important to note that $\\parseb M \\Gamma u {\\vec x}$ implies that each variable occurring in $\\vec x$ is contained in $\\Gamma$ and each free variable occurring in $u$ is not contained in $\\Gamma$. This can be shown by induction on $M$ (simultaneously for all sets $\\Gamma$).\n\nBy the same argument, one can see that (for each $M$ and $\\Gamma$) there exists a unique tuple $(u, \\vec x)$ satisfying $\\parseb M \\Gamma u {\\vec x}$, so we can consider $\\parseFun \\Gamma$ a function $\\te \\rightarrow \\otw \\times \\gl$. Furthermore, we note that $\\parseb M \\Gamma u {\\vec x}$ always implies $\\freevars u = \\length {\\vec x}$.\n\nThis also works the other way round. For each $\\Gamma$ and each tuple\n$(u, \\vec x) \\in \\otw \\otimes \\gl$, there is (by induction on $u$) a\nterm $M \\in \\te$ satisfying $\\parseb M \\Gamma u {\\vec x}$. Moreover,\nthis term $M$ is unique up to $\\alpha$ equivalence. So, $\\parseFun\n\\Gamma$ is actually a bijection between $\\te / \\alpha$ (the set of\n$\\alpha$ equivalence classes of terms) and $\\otw \\otimes \\gl$. The\ninference rules above show how to apply this bijection or its inverse\nto a term or a tuple (in the last rule, any variable satisfying the\ncondition can be chosen for $z$), so we have\n% (computable) functions $\\parseFun \\Gamma : \\te / \\alpha \\rightarrow \\otw \\otimes \\gl$ and $\\parseFun \\Gamma ^{-1}$.\na computable bijection $\\te / \\alpha \\leftrightarrow \\otw \\otimes \\gl$\ndetermined by the rules for $\\parseFun \\Gamma$.\n\nChoosing $\\Gamma = \\emptySet$, we get a bijection $\\te/\\alpha\n\\leftrightarrow \\ot \\otimes {\\vec \\emptySet}$. As $\\vec \\emptySet$ is\nonly inhabited by the empty vector $\\emptyVec$, we naturally get the\n\\define{parse} function $\\parseFunE$ which maps $\\te / \\alpha$\nbijectively on $\\otc$.\n\n\n%Choosing $\\Gamma = \\emptySet$, we get the special cases $\\parseFun \\emptySet$ and $\\parseFun \\emptySet ^{-1}$, which are bijections between $\\te$ and $\\otc$. This also explaines how one representation can be transformed into the other.\n\nThe above construction also gives us a function $\\otc \\rightarrow\n\\te$, but this is not enough. We want to transform closures\n(elements of $\\ot \\otimes \\vl$) and values (elements of $\\va$)\ninto basic terms $\\te$.\nTherefore, we\n% \\begin{defin}\n% We\ndefine the two \\define{print} functions $\\prE : \\ot \\otimes \\vl \\rightarrow \\te / \\alpha$ and $\\prValE : \\va \\rightarrow \\te / \\alpha$ simultaneously by recursion on the structure:\n\\[\n\\begin{array}{lclc}\n\\medskip\n\\pr{x}{\\emptyVec} & = & x & \\lab I \\\\\n\\medskip\n\\pr{\\ovar}{[v]} & = & \\prVal v & \\lab {II} \\\\\n\\pr{t \\oapp m u}{\\vec v} & = & \\ApA {\\pr {t}{\\vstart} } {\\quad \\pr\n {u}{\\vrest}} & \\lab {III} \\\\\n\\medskip\n&& \\mbox{(split $\\vec v$ at position $m$ to get $\\vstart$ and $\\vrest$)} \\\\\n% \\pr{\\LaO {k_1, \\ldots, k_m} t}{[v_1, v_2, \\ldots, v_n]} & = & \\LaA z {\\pr {t} {v_1, \\ldots, v_{k_1}, z, v_{k_1+1}, \\ldots, }} & \\lab {IV} \\\\\n\\pr{\\LaO {\\vec k} t}{\\vec v} & = & \\LaA z {\\pr {t} { \\multiinsert{\\vec v}{\\vec k}{z} }} & \\lab {IV}\\\\\n\\medskip\n&& \\mbox{where $z$ is any variable that does not occur freely in $t$ or $\\vec v$ } \\\\\n\\prVal{x \\sspace v_1 \\sspace v_2 \\sspace \\ldots \\sspace v_n} & = & x \\ \\prVal{v_1} \\ \\prVal{v_2} \\ \\ldots \\ \\prVal{v_n} & \\lab V\\\\\n\\medskip && \\mbox{(a large application simply becomes an application of terms)} \\\\\n\\prVal{\\Val {\\vec k} t {\\vec v}} & = & \\pr{\\LaO {\\vec k} t}{\\vec v} & \\lab {VI}\\\\\n\\end{array}\n\\]\n%\\end{defin}\nFirst, note that the printing functions are well-defined (i.e., they always terminate). This is because during evaluation of $\\pr{u}{\\vec v}$, we may safely assume that $\\pr{t}{\\vec w}$ is well-defined as long as $t$ is a strict subterm of $u$ and each value $w'$ in $\\vec w$ is either only a variable (so termination of $\\prVal {w'}$ is clear) or also in $\\vec v$. Similar, during evaluation of $\\prVal {x \\sspace v_1 \\sspace \\ldots v_n}$, we may assume that $\\prVal {v_i}$ is defined for each $i$.\n\nFor all $t \\in \\otc, M \\in \\te$, we have $\\pr t \\emptyVec = M$ if and only if $\\parseb M \\emptySet t { }$ (which just means $\\parseFunE t = M$) as both judgements are defined identically in the case of closed ordered terms. This essentially (with implicit use of the bijection $\\otc \\leftrightarrow \\ot \\otimes \\vec \\emptySet$) means $\\prE \\circ \\parseFunE = id_{\\te}$, i.e. the composition of parsing and printing is the identity.\n\n\n\n\n\n\n\\section{Correctness and Termination properties}\n\\label{sec:sound}\n\n\n\nWe still have not shown that our evaluation algorithm given in Section~\\ref{sec:values} does not change the meaning of terms. The combination of parsing, evaluating and printing should never result in a term that is not beta equivalent to the original term. We also want to show a limited termination property.\nTo keep our argument simple, we just sketch the proofs and hope that the ideas become clear.\n\nFirst, we attend to the correctness question.\nWe need to convince ourselves that \\emph{rewriting} according to the rules of the functions $\\ev \\cdot \\cdot$ and $\\ap$ does not cause an error.\nBy \\emph{rewriting}, we mean one step of the \\emph{normal} or \\emph{leftmost outermost} evaluation. We have demonstrated this in the example at the beginning of Section~\\ref{sec:values}.\n%If we have, e.g., the tupel $(t, \\vec v)$, printing it should result in a term that is $\\beta$ equivalent to the term we get if we rewrite it once before printing.\nPrinting should result in a term that is $\\beta$ equivalent to the term we get if we rewrite before printing.\nThis basically means that, for each evaluation rule on the left hand\nside of the following table, we have to check that the equality on the\nright hand side holds:\n\n\\begin{center}\n\\begin{tabular}{| rcl | rcl | c }\n\\cline{1-6}\n&&&&&& \\\\\n$\\ev x {\\emptyVec} $&$=$&$ x $ & $ \\pr{x}{\\emptyVec} $&$\\, =_\\beta \\, $&$\\prVal{x}$ & \\qquad \\lab 1 \\\\\n&&&&&& \\\\\n$\\ev \\ovar {\\ve{v}} $&$=$&$ v $ & $ \\pr{\\ovar}{v} $&$\\, =_\\beta \\,$&$ \\prVal v$ & \\qquad \\lab 2 \\\\\n&&&&&& \\\\\n$\\ev {t \\oapp k u} {[\\vec v , \\vec w]} $&$=$&$ {\\ev t {\\vec v}} \\ap {\\ev u {\\vec w}} $ & $ \\pr {t \\oapp k u} {[\\vec v , \\vec w]} $&$\\, =_\\beta \\,$&$ \\ApA {\\pr{t}{\\vec v}} {\\pr{u}{\\vec w}} $ & \\qquad \\lab 3 \\\\\n&&&&&& \\\\\n$\\ev {\\LaO {\\vec k} t} {\\vec v} $&$=$&$ \\Val {\\vec k} t {\\vec v} $ & $ \\pr{\\LaO {\\vec k} t}{\\vec v}$&$ \\, =_\\beta \\,$&$ \\prVal {\\Val {\\vec k} t {\\vec v}} $ & \\qquad \\lab 4 \\\\\n&&&&&& \\\\\n$\\pa{x \\sspace \\vec v} \\ap w $&$=$&$ x \\sspace \\ve{\\vec v, w} $ & $\\ApA {\\prVal {x \\sspace \\vec v} } {\\prVal w} $&$\\, =_\\beta \\, $&$ \\prVal{x \\sspace \\ve{\\vec v, w}}$ & \\qquad \\lab 5\\\\\n&&&&&& \\\\\n$\\Val{\\vec k} t {\\vec v} \\ap w $&$=$&$ \\ev t {\\multiinsert{\\vec v}{\\vec k}{w}} $ & $ \\ApA{\\prVal{\\Val{\\vec k} t {\\vec v}}}{\\prVal w} $&$ \\, =_\\beta \\, $&$ \\pr{t}{\\multiinsert{\\vec v}{\\vec k}{w}} $ & \\qquad \\lab 6\\\\\n&&&&&& \\\\\n\\cline{1-6}\n\\end{tabular}\n\\end{center}\n\nNote that ``rewriting using the evaluation rules'' results in expressions which are, more or less, a mixture of elements of $\\ot \\otimes \\vl$ and $\\va$. To be precise, such an expression is either in $\\ot \\otimes \\vl$ or in $\\va$ or a tuple (to read as simple application) of two expressions. The $1^{st}$, $2^{nd}$ and $4^{th}$ rule turn an element of $\\ot \\otimes \\va$ into a value, the $3^{rd}$ turns it in a tuple of two such elements, and the last two rules turn a tuple of two values into one value or element.\nAlthough we do not define it formally, it should be clear how those expressions can be printed by using the printing functions for ordered terms and values (if an expression is a tuple, just print the function part and the argument part separately). In fact, while the function $\\ev \\cdot \\cdot$ is formulated as a big step evaluation, the rewriting process can be understood as the corresponding small step (or one step) evaluation.\n\nIn the first five rows of the table, we only have to look at the definitions of the printing functions to see that the printed terms are not only $\\beta$ equivalent but also equal. The very last rule $\\lab 6$ requires closer examination:\nBy rule $\\lab {IV}$, the term $\\prVal{\\Val{\\vec k} t {\\vec v}}$ is equal to $\\LaA z {\\pr {t} { \\multiinsert{\\vec v}{\\vec k}{z} }} $ for a (sufficiently) fresh variable $z$. Now, the definitions of the printing functions are ``context free'' in a way that guarantees that $z$ occurs exactly $\\length{\\vec k}$ times (free) in $\\pr {t} { \\multiinsert{\\vec v}{\\vec k}{z} }$. Furthermore, replacing those occurrences by $\\prVal{w}$ results in the term $\\pr{t}{\\multiinsert{\\vec v}{\\vec k}{w}}$. This means that, starting with\n$ \\ApA{\\prVal{\\Val{\\vec k} t {\\vec v}}}{\\prVal w} $,\nwe have to use exactly one $\\beta$ reduction step to get the term $ \\pr{t}{\\multiinsert{\\vec v}{\\vec k}{w}} $.\n\nAs we have already seen that the composition of parsing a term and printing it afterwards does not change anything (up to $\\alpha$ equivalence), we can now conclude that parsing, evaluating (a finite number of rewriting steps) and printing is equivalent to a number of $\\beta$ reduction steps.\n\nNow we discuss termination. Obviously, our evaluation function $\\ev \\cdot \\cdot$ does not always terminate as some terms do not have a weak head normal form. However, $\\ev \\cdot \\cdot$ terminates whenever it is applied to ($\\parseFunE t$) if the usual $\\beta$ reduction is strongly normalizing on $t$.\nThe main consequence of this is that evaluation terminates for all well-typed terms. % TODO \"all\" !\nTo prove this statement, assume that there is such a term $s_0 \\in \\te$ so that the evaluation of $t_0 := \\parseFunE s_0$ does not terminate.\n%\nThen, we get an infinite sequence $t_0, t_1, t_2, \\ldots$ where $t_{i+1}$ is the result of rewriting (a subexpression of) $t_i$ using one of the evaluation rules. If we print $t_0, t_1, t_2, \\ldots$, we get a sequence $s_0, s_1, s_2, \\ldots$ of terms in $\\te$, where $s_{i+1}$ is either ($\\alpha$) equal to $s_i$ or arises from $s_i$ in exactly one $\\beta$ reduction step. If $\\beta$ reduction is strongly normalizing on $s_0$, the sequence has to become constant at some point, i.e. $s_N = s_{N+1} = s_{N+2} = \\ldots$ for some $N$. This implies that, after the first $N$ rewriting steps, rule \\lab 6 is not used anymore. Define the \\emph{weight} $w(t)$ of an expression $t$ to be $1$, if the expression is just an element of $\\ot \\otimes \\va$, to be $2$, if it is a value of the \\emph{closure} type, to be %TODO\n$1 + 2^n + w(v_1) + w(v_2) + \\ldots + w(v_n)$, if it is a value of the form $x \\, v_1 v_2 \\ldots v_n$ (i.e. a \\emph{large application}) and, if it is a tuple of two expressions, as the sum of both weights. Then, each of the rewritings that are induced by the first five lines in the table increase the weight of the expression, so we get $w(t_N) < w(t_{N+1}) < w(t_{N+2}) < \\ldots$; however, as the total number of values (and tuples in $\\ot \\otimes \\va$) is bound by the length of the term we get after printing $t_N$ (or any $t_{N+i}$), the sequence is bounded, resulting in the required contradiction.\n\n\n\n% -----------------------------------\n%\n% THIS IS AN OUTDATED VERSION OF THE SECTION. IT IS MORE \"FORMALLY CORRECT\" BUT CONTAINS TOO MUCH OVERHEAD AND IS THEREFORE DIFFICULT TO READ.\n%\n%We still have to prove two important facts about the evaluation algorithm given in section \\ref{sec:values} - first, its termination properties and second, its correctness, i.e. it corresponds to beta reduction.\n%\n%Concerning correctness, we would obviously want to show that taking a term $t$, translating it to an ordered term, evaluation and printing it gives us a term which is beta equal to $t$, which is represented by the diagram\n%\\[\n%\\begin{xy}\n%\\xymatrix{\n% t \\in \\te \\ar@{-}[rrr]^{=_\\beta} \\ar@/_/[dd]_{\\parseFunE} & & & t' \\in \\te \\\\\n% \\\\\n%% u \\in \\otc \\ar@/_/[uu]_{\\pr{\\cdot}{\\emptyVec}} \\ar[rrr]^{\\ev{\\cdot}{\\emptyVec}} & & & \\ev{u}{\\emptyVec} \\in \\va \\ar[uu]_{\\prValE}\n% u \\in \\otc \\ar@/_/[uu]_{\\prE } \\ar[rrr]^{\\ev{\\cdot}{\\emptyVec}} & & & \\ev{u}{\\emptyVec} \\in \\va \\ar[uu]_{\\prValE}\n%}\n%\\end{xy}\n%\\]\n%However, the diagram does not make much sense as we do not know yet that $\\ev \\cdot \\emptyVec$ is a well-defined function.\n%What we need to do is to define a one-step-evaluation, thereby making it possible to check if each single evaluation step preserves beta equality. Unfortunately, this becomes even more complicated as we get binary trees during evaluation:\n%\\[\n%\\begin{array}{lllrll@{\\qquad}}\n%\\evTr & \\ni & \\mathsf{tree}_1, \\mathsf{tree}_2 & ::= & (t, \\vec v) & \\mbox{a tupel in $\\ot \\otimes \\vl$} \\\\\n% &&& \\mid & v & \\mbox{just a value} \\\\\n% &&& \\mid & \\tree {\\mathsf{tree}_1} {\\mathsf{tree}_2} & \\mbox{node with two subtrees}\n%\\end{array}\n%\\]\n%Our one-step reduction $\\osr$ is a relation on $\\evTr \\times \\evTr$:\n%\n%\\begin{gather*}\n%\\infnamed{^{\\ev \\cdot \\cdot \\mbox{\\small -1} }}{}{(x , \\emptyVec) \\osr x}\n%\\qquad\n%\\qquad\n%\\infnamed{^{\\ev \\cdot \\cdot \\mbox{\\small -2}}}{}{(\\ovar , \\ve v) \\osr v}\n%\\qquad\n%\\qquad\n%\\infnamed{^{\\ev \\cdot \\cdot \\mbox{\\small -3}}}{}{(t \\oapp k u , \\vec v \\vec w) \\osr \\tree {(t, \\vec v)}{(u, \\vec w)}}\n%\\\\ \\\\\n%\\infnamed{^{\\ev \\cdot \\cdot \\mbox{\\small -4}}}{}{(\\LaO {\\vec k} t , \\vec v) \\osr \\Val {\\vec k} t {\\vec v}}\n%\\qquad\n%\\qquad\n%\\infnamed{^{\\mbox{\\small (struct-1)}}}{a \\osr a'}{\\tree a b \\osr \\tree {a'} b}\n%\\qquad\n%\\qquad\n%\\infnamed{^{\\mbox{\\small (struct-2)}}}{b \\osr b'}{\\tree a b \\osr \\tree a {b'}}\n%\\\\ \\\\\n%\\infnamed{^{@\\mbox{\\small -1}}}{}{\\tree {x \\sspace v_1 \\ldots v_n} w \\osr x \\sspace v_1 \\ldots v_n \\sspace w}\n%\\qquad\n%\\qquad\n%\\infnamed{^{@\\mbox{\\small -2}}}{}{\\tree {\\Val {\\vec k} t {\\vec v}}{w} \\osr (t, \\multiinsert {\\vec v} {\\vec k} w)}\n%\\end{gather*}\n%Now it is easy to define a printing function $\\prTreeE$ to transform a tree into a term:\n%\\[\n%\\begin{array}{lclll}\n%\\prTree{(t, \\vec v)} & = & \\pr {t} {\\vec v} &&\\\\\n%\\prTree{v} & = & \\prVal v &&\\\\\n%\\prTree{\\tree a b} & = & \\ApA {\\prTree a}{\\prTree b}&& \\mbox{(simply the application in $\\te$)}\n%\\end{array}\n%\\]\n%\\begin{prop}\n% For $a, b \\in \\evTr$ satisfying $a \\osr b$, we have $\\prTree a =_\\beta \\prTree b$. More precisely, if one of the rules ${\\ev \\cdot \\cdot \\mbox{-1} }, {\\ev \\cdot \\cdot \\mbox{-2} }, {\\ev \\cdot \\cdot \\mbox{-3} }, {\\ev \\cdot \\cdot \\mbox{-4} }$ or ${@\\mbox{-1}}$ was used, even $\\prTree a = \\prTree b$ (up to $\\alpha$-equivalence) holds, if ${@\\mbox{-1}}$ was used, $\\prTree a$ can be reduced to $\\prTree b$ in exactly one $\\beta$-reduction step.\n%\\end{prop}\n%\\begin{proof}\n% For all of the $\\ev \\cdot \\cdot$-rules and $@\\mbox{-1}$, the equality $\\prTree a = \\prTree b$ is easy to check.\n%% In the case of the structure rules, we may assume that the statement holds for the premises, so it is also clear for the conclusions. The first of the $@$-rules is also simple.\n% We have to have a closer look at the second $@$-rule:\\\\\n% By definition, we have\n% \\[\n%\\begin{array}{lclr}\n% \\prTree {\\tree {\\Val {\\vec k} t {\\vec v}}{w}} & = & \\ApA { \\prVal {\\Val {\\vec k} t {\\vec v}} } \\ {\\prVal w} & \\\\\n%& = &\\ApA { \\pr{\\LaO {\\vec k} t}{\\vec v} } \\ {\\prVal w} \\\\\n%& = & \\ApA {\\left( \\LaA z {\\pr {t} {\\multiinsert {\\vec v}{\\vec k}{z}}} \\right)} \\ {\\prVal w} & \\qquad \\mbox{$z$ not free in $t$, $\\vec v$}\\\\\n%\\mbox{and} &&& \\\\\n% \\prTree { (t , \\multiinsert{\\vec v}{\\vec k}{w} ) } & = & \\pr{t}{\\multiinsert{\\vec v}{\\vec k}{w}} &\n%\\end{array}\n%\\]\n%Now, note that (again by induction on $t$) the term $\\pr {t} {\\multiinsert {\\vec v}{\\vec k}{z}}$ contains $z$ exactly $\\length {\\vec k}$ times as a free variable and, by replacing each of those free occurrences by $\\prVal w$, we get the term $\\pr{t}{\\multiinsert{\\vec v}{\\vec k}{w}}$.\n%Consequently, the term $\\prTree {\\tree {\\Val {\\vec k} t {\\vec v}}{w}}$ can be reduced to $\\prTree { (t , \\multiinsert{\\vec v}{\\vec k}{w} ) }$ in exactly one beta reduction step. \\\\\n%Note that these statements are also true if one or more of the structure rules are used in addition.\n%\n%\n%\\end{proof}\n%\n%\\begin{prop}\n%For any well-typed term $t \\in \\te$, the One-Step-Reduction terminates for $(\\parseFunE t)$.\n%\\end{prop}\n%\\begin{proof}\n%Suppose there is an infinite sequence $a_0 \\rightarrow a_1 \\rightarrow a_2 \\rightarrow \\ldots$ with $a_0 = \\parseFunE t$. According to the proposition above, we can conclude that for each $i$, either $\\prTree {a_i} = \\prTree {a_{i+1}}$ or $\\prTree {a_i} \\rightarrow_\\beta \\prTree {a_{i+1}}$ (in exactly one step). Assume the latter possibility occurs infinitely often. This contradicts the fact that $\\beta$-reduction is strongly normalizing on well-types terms. Assume it occurs only finitely often. Then there is an $N$ such that $\\prTree {a_N} = \\prTree {a_{N+1}} = \\prTree {a_{N+2}} = \\ldots$. For $a \\in \\evTr$, we define the weight $w(a)$ as the number of leafs of $a$ containing an element of $\\ot \\otimes \\vl$ plus twice the number of leafs that contain a value. % TODO: THIS HAS TO BE MODIFIED. (see newer version)\n%Each of the one-step-rules except the last one (and the structure rules) obviously increases the weight of a tree, thus we get $w(a_N) < w(a_{N+1}) < w(a_{N+2}) < \\ldots$. However, the printing function is defined in a way that forces the weight of any tree $a$ to be less or equal than twice the length of $a$ and consequently, the sequence above is bounded by $2 \\cdot \\length{ \\prTree{a_N}}$, thus giving us a contradiction again.\n%\\end{proof}\n%% TODO rename PARSINGfunction and make clear that sometimes parse: ... -> trees.\n%\n%Note that if the reduction terminates, the result is a tree that consists of exactly one leaf containing a value (as there is a reduction step for any other case). We identify this tree with the value.\n%\n%\\begin{cor}\n%For all well-typed terms, the evaluation function $\\ev \\cdot \\cdot$ is well-defined (i.e. terminates) and correct (i.e. parsing a term, evaluating and printing it results in a $\\beta$-equivalent term).\n%\\end{cor}\n%\\begin{proof}\n%It is easy to check that the evaluation $\\ev \\cdot \\cdot$ can be simulated by using a sequence of $\\rightarrow$-steps. First, this shows that it terminates as we would get an infinite sequence of steps otherwise. Second, as each small step conserves $\\beta$-equality, the whole sequence does the same. As we know that for $t \\in \\te$ the equality $\\prTree {\\parseFunE t , \\emptyVec} = t$ holds, this implies $\\prTree {\\ev{\\parseFunE t} {\\emptyVec}} = t$.\n%\\end{proof}\n%\n% -----------------------------------\n\n\n\n\n\n\n\n\n\n\n\n\\section{Experiments and Results}\n\\label{sec:experiments}\n\nThe specified term representation and evaluation have been implemented\nin Haskell. They have been used by a type checker to check large files\nof dependently\ntyped terms of the Edinburgh Logical Framework which were kindly\nprovided by Andrew W. Appel (Princeton University). To make this\npossible, an extended syntax has been used that includes $\\Pi$-types% and technical elements like\n, constants and definitions. It is straightforward to expand our\nevaluation algorithm to the extended syntax---for details consult the\nBachelor's thesis of the second author \\cite{kraus:bachelor}.\nThe substitution lists\nhave been implemented as simple Haskell lists, and also as balanced\nbinary trees (following Adams \\cite{adams:jfp93})\nfor better asymptotic complexity. Both variants were\nevaluated for performance\n[referred to as \\emph{Ordered (trees)} and \\emph{Ordered (lists)}].\n\nFor comparison, the completely analogous algorithm for terms in\nextended basic syntax (i.e. $\\te$) has been used [\\emph{Simple\n Closures}]. Furthermore, we have tested a strategy that always\nevaluates completely (i.e. produces $\\beta$ normal forms) using\nHereditary Substitution [\\emph{Beta Normal Values}]\n\\cite{watkins:concurrentlftr}.\n\nOur main test file \\textsf{w32\\_sig\\_semant.elf} with a size of\napproximately 21 megabytes contains a proof described in\n\\cite{appel:toplas10}. We also tested smaller parts of this file, more\nprecisely, the first $6000$, $10,000$ and $12,000$ lines without the\nrest (named \\textsf{6000.elf} and so on). Later terms tend to be\nlarger, so the tests with fewer lines needed much less time.\n\nAll tests were executed on the same server\n\\mbox{\\texttt{baerentatze.cip.ifi.lmu.de}}\n% (\"baerentatze\",\n% Ludwig-Maximilians-Universit\\\"at M\\\"unchen, Department of Computer\n% Science)\nworking with a CPU of type \\emph{AMD Phenom II X4 B95} (only\none core used, 3 GHz) and 8 GB system memory. The measurements\nof space and time consumption are given in the following tables (rounded\naverage values). More specifically, \\emph{time} refers to the total time, including parsing the input file and transforming (if necessary) the representation to our ordered representation or to one that uses De Bruijn terms. However, in our tests, the transformation process only took a negligible amount of time. The time value does, however, not include any printing of the terms or the values (with printing, the total time increased significantly). \\emph{Space} refers to the peak space usage of the whole process.\n\n\\begin{center}\n\\begin{tabular}{| l || c | c |}\n\\multicolumn{3}{c}{\\textsf{6000.elf} (file size: 3.8 MB)}\\\\\n\\hline\n& time (sec) & space (MB) \\\\\n\\hline\n\\hline\nOrdered (trees) & 18.9 & 1111 \\\\\n\\hline\nOrdered (lists) & 18.6 & 1114\\\\\n\\hline\nSimple Closures & 18.5 & 1152\\\\\n\\hline\nBeta Normal Values & 27.6 & 2034\\\\\n\\hline\n\\end{tabular}\n\n\\vspace{5pt}\n\n\\begin{tabular}{| l || c | c |}\n\\multicolumn{3}{c}{\\textsf{10000.elf} (file size: 12.9 MB)}\\\\\n\\hline\n& time (sec) & space (MB) \\\\\n\\hline\n\\hline\nOrdered (trees) & 61.0 & 3230\\\\\n\\hline\nOrdered (lists) & 60.6 & 3237\\\\\n\\hline\nSimple Closures & 60.0 & 3302\\\\\n\\hline\nBeta Normal Values & 98.7 & 5878\\\\\n\\hline\n\\end{tabular}\n\n\\vspace{5pt}\n\n\\begin{tabular}{| l || c | c |}\n\\multicolumn{3}{c}{\\textsf{12000.elf} (file size: 17.8 MB)}\\\\\n\\hline\n& time (sec) & space (MB) \\\\\n\\hline\n\\hline\nOrdered (trees) & 84.3 & 5096 \\\\\n\\hline\nOrdered (lists) & 83.8 & 5103 \\\\\n\\hline\nSimple Closures & 83.6 & 5226 \\\\\n\\hline\nBeta Normal Values & 137.7 & 8513 \\\\\n\\hline\n\\end{tabular}\n\\end{center}\n\nUnsurprisingly, beta normal values perform significantly worse than each of the other possibilities. However, the difference is smaller than it could have been expected. This might be due to the fact that during type checking, total evaluation of a term is often necessary anyway, thereby reducing the hereditary substitution's disadvantage.\n\nAlthough none of the other strategies exhibited any shortcomings in the comparisons above, the following results for the complete file are remarkable. Here, implementing ordered substitutions as normal Haskell lists seems to be much more efficient than using tree structures:\n\n\\begin{center}\n \\begin{tabular}{| l || c | c |}\n\\multicolumn{3}{c}{\\textsf{w32\\_sig\\_semant.elf} (file size: 20.9 MB)}\\\\\n\\hline\n& time (sec) & space (MB) \\\\\n\\hline\n\\hline\nOrdered (trees) & 108.4 & 8877\\\\\n\\hline\nOrdered (lists) & 94.8 & 4948\\\\ % average, 4 values.\n\\hline\nSimple Closures & 94.3 & 5068 \\\\ % some more tests: 92.42 , 4994 (?!); 94.17, 5068; 94.97, 5068; 93.75, 4994\n\\hline\nBeta Normal Values & 169.8 & 9044 \\\\\n\\hline\n\\end{tabular}\n\\end{center}\n\nOur Simple Closures are still on the same level as Ordered Representation with lists, but the trees are far behind.\nIn comparison, the type checker of the Twelf project, \\emph{Twelf\n r1697} (written in \\emph{Standard ML} and compiled with\n\\emph{MLton}'s whole program optimizations \\cite{fluetWeeks:icfp01})\ndoes the job nearly five\ntimes faster while using only 2720 megabytes of\nmemory. % TODO only due to an optimized compiler?\n\n%Unfortunately, the idea of ordered substitution lists does not really pay off within the context of type checking in our tests.\n%On the other hand, it can compete with the simple standard implementation. This offers hope that there might be some applications that benefit more from our suggested strategy.\n\n\n\n\n\\section{Related Work and Conclusions}\n\\label{sec:concl}\n\nOur term representation is inspired by intuitionistic implicational\nlinear logic in natural deduction style which has explicit operations\nfor weakening and contraction\n\\cite{bentonBiermanDePaivaHyland:tlca93}. With explicit weakening and\ncontraction, one easily maintains complete information about the free\nvariables of a term at each node \\cite{kesnerLengrand:infcomp07}. Our\nterm representation incorporates weakening and contraction into lambda\nabstraction. By using inspiration from ordered logic, we reduce the\nstored information at application nodes to a minimum, namely an\ninteger; further, our variable nodes need to carry no information at all.\n\nAnother means to maintain information about free variables are\n\\emph{director strings} by Sinot \\cite{sinot:jlc05}. Application\nnodes come with a map that tell for each variable whether it appears\nin the left or the right subterm or in both. Our term representation\ncan be seen as an optimized version of director strings, however, we\nhave no experimental comparison.\nSinot \\etal~\\cite{fernandezMackieSinot:aaecc05} present some\nperformance results of director strings; however, it is restricted\nto evaluation of some specific big lambda-terms. There is no study on\ntheir relative performance in a realistic application---yet that is\nour concern.\n\nAn alternative to explicit substitutions is Nadathur's suspension\ncalculus \\cite{nadathur:jflp99}, which, in a refinement, also\nmaintains information about closedness of subterms. In this\nrefinement, the suspension calculus maintains at least partial\ninformation about the free variables of a subterm.\nAs the basis of an implementation of\n$\\lambda$-Prolog \\cite{nadathur:flops01},\nNadathur has proven the efficiency of his term\nrepresentation not only for normalization and equality checking, but\nalso for higher-order unification.\n\n% Building on Nadathur's alternative to explicit substitutions, the\n% \\emph{suspension calculus} \\cite{nadathur:jflp99},\nBuilding on the suspension calculus,\nLiang, Nadathur, and Qi \\cite{liangNadathurQi:jar05} have evaluated\ndifferent term representations in the context of $\\lambda$Prolog, a\nstudy that compares to our study of term representations for the\nEdinburgh Logical Framework. They have tested different combinations\nof features, confirming our result that lazy substitution is\npreferable to eager substitution {[Beta Normal Forms]},\neven more so when several substitutions are gathered into one\ntraversal {[Closures, Ordered]}. They also test a variant where\neach term is equipped with an \\emph{annotation}, a flag telling whether\nthis term is open, \\ie, has free variables, or closed, \\ie, has no\nfree variables. In their experimental evaluation, these annotations\npay off greatly for the poorly behaving eager substitution, yet give\nnegligible advantage for explicit substitutions. It is\nhypothesized that in a combined substitution, each subterm will\nmention at least one variable with a high probability, so the\ntraversal has to run over most of the whole term---this is certainly\ndifferent in the substitution for a single variable.\n\nTo summarize, we have presented a new term representation for the\nlambda-calculus inspired by ordered linear logic, and experimentally\ncompared it with well-known representations (closures, normal forms)\nin a prototypical implementation of a type checker for the Edinburgh\nLogical Framework. The experiments were carried out on large realistic\nproof terms, constructed manually and mechanically.\n\nThe results were not significantly in favor of our new representation.\nThis might be due to the application domain, LF signature checking.\nFor one, LF-definitions are closed, which means that substitutions\nnever need to traverse a definition body when the definition is\nexpanded, and this optimization is shared by all the term\nrepresentations we compared. Secondly, we only tested type checking,\nnot type reconstruction via unification. During type checking, where\nequality tests are expected to succeed, full normal forms are always\ncomputed, and closures are very short-lived in memory. More space\nleaks are to be expected in applications such as logic programming or\ntype reconstruction, where unification is needed, which is not\nexpected to always succeed. In constraint-based unification,\nunsolvable constraints might be postponed, keeping closures alive for\nlonger. In such situations, the benefits of our representation might\nbe more noticeable, more experiments are required.\n\nIn the future, we plan to investigate further term representations\nsuch as term graphs, and perform more experiments. The literature on\nexperimentally successful term representations is sparse, our work\ncontributes to close this gap. Our long term goal is to find a\nterm representation which speeds up Agda's type reconstruction.\n\n\n\\paragraph*{Acknowledgements}\nThe idea for the here presented ordered term representation was\nplanted in a discussion with Christophe Raffalli who invited the first\nauthor to Chambery in February 2010. He mentioned to me that in his\nlibrary \\texttt{bindlib} formation of closures restricts the\nenvironment to the variables actually occurring free in the code. I\nalso benefited from discussions with Brigitte Pientka and Stefan Monnier.\n\nThanks to Gabriel Scherer for comments on a draft version of this\npaper and pointers to related work.\nThe final version of this paper was stylistically improved with the highly appreciated help of Neil Sculthorpe.\n\n\n\n\\bibliographystyle{eptcs}\n\\bibliography{nonauto-lfmtp11}\n\n\n\\end{document}\n", "meta": {"hexsha": "58a0e073d1785d9dad2759602b6d1fccf75d2e82", "size": 59440, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "notes/lfmtp11.tex", "max_stars_repo_name": "andreasabel/helf", "max_stars_repo_head_hexsha": "e8f19dbec8f9c5db303ec2e711e325644d1784b0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 21, "max_stars_repo_stars_event_min_datetime": "2017-09-15T23:21:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-06T12:15:40.000Z", "max_issues_repo_path": "notes/lfmtp11.tex", "max_issues_repo_name": "andreasabel/helf", "max_issues_repo_head_hexsha": "e8f19dbec8f9c5db303ec2e711e325644d1784b0", "max_issues_repo_licenses": ["MIT"], "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/lfmtp11.tex", "max_forks_repo_name": "andreasabel/helf", "max_forks_repo_head_hexsha": "e8f19dbec8f9c5db303ec2e711e325644d1784b0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2017-10-01T10:55:18.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-22T16:23:59.000Z", "avg_line_length": 64.7494553377, "max_line_length": 824, "alphanum_fraction": 0.713307537, "num_tokens": 17183, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.37022539954425293, "lm_q1q2_score": 0.18800485034608042}}
{"text": "\\section{Siamese Multi-Object Tracking and Embedding}\r\n\\label{sec:SiamMOTandFeatureEmb}\r\n\r\n% ##############################################################################\r\n\\subsection{Motivation}\r\n\r\nOne of our experiments involved an end-to-end training of the \\gls{siammot} together with a custom head aimed at embeddings based on \\gls{roi}-pooled features for the object \\gls{bbox}. The goal was to force the training process into extracting features that are not only satisfactory for detection and tracking but also do contain the necessary information to create embeddings for \\gls{reid} purposes during the inference. We strived for simplicity by extending the processing pipeline without altering the existing infrastructure.\r\n\r\nDuring research related to our Siamese tracking survey~\\cite{ondrasovic2021siamese}, we noticed one work where the exemplar features were projected using \\gls{gap} into an embedding space consisting of fewer dimensions~\\cite{li2020figsiam}. The embedding vector was produced using the feature tensor representing the kernel for the cross-correlation operation. More concretely, let the extracted features be represented by an $8 \\times 8 \\times 256$ tensor. Then, the \\gls{gap} along the channel dimension would produce a $1 \\times 1 \\times 256$ tensor, which could then be further flattened into a single $256$D vector. In the end, the obtained vector was $l_2$-normalized and thus projected onto a unit hypersphere. In the work of Li~\\etal{}~\\cite{li2020figsiam}, these embedding vectors were exploited for template updating and for combining multiple templates within a pool of size $n$ in an exponential fashion.\r\n\r\nThis observation led us to the following hypothesis. Given the fact the Siamese exemplar features do contain some, although probably not sufficient information for pure object \\gls{reid}, would it be possible to map them further using a non-linear function to produce embedding vectors that could serve for \\gls{reid}? Such features are just a learned template, therefore, some notion of similarity needs to be already built into it.\r\n\r\n% ##############################################################################\r\n\\subsection{Feature Embedding Head Architecture}\r\n\r\n% ------------------------------------------------------------------------------\r\n\\begin{figure}[!t]\r\n \\centering\r\n \\includegraphics[width=\\linewidth]{figures/siamese_tracking/siammot_feature_emb_training.pdf}\r\n \\caption[Embedding-enhanced \\gls{siammot} architecture]{Our extension (shown in red) to the underlying \\gls{siammot} architecture that incorporates vector embeddings to the end-to-end training. This diagram shows the pipeline that is used during the training, not inference.}\r\n \\label{fig:SiamMOTWithEmbeddings}\r\n\\end{figure}\r\n% ------------------------------------------------------------------------------\r\n\r\nAs for the vector embedding computation, we attached an \\gls{femb} head (\\tabletext{}~\\ref{tab:FeatureEmbeddingHead}) after the \\gls{roi}-pooling phase of the backbone features (\\figtext{}~\\ref{fig:SiamMOTWithEmbeddings}). This ensured fixed tensor shapes and allowed us to process the very same features that the object detector and Siamese tracker utilized, too. Simply put, for every proposal made for a particular frame, we looked at the delineated \\gls{bbox} through the lens of \\gls{roi}-pooling to extract its features. We simply reused the extracted exemplar features. Later on, we processed these features using our newly devised \\gls{femb} head to produce \\gls{femb}. The resulting embeddings were subjected to the triplet loss computation with all the necessary operations such as various types of hard negative mining.\r\n\r\n\\begin{table}[!t]\r\n \\centering\r\n \\begin{tabular}{lll}\r\n \\toprule\r\n \\textbf{layer} & \\textbf{tensor shape} & \\textbf{parameters no.} \\\\\r\n \\midrule\r\n input & $\\sbrackets{B, 128, 15, 15}$ & $0$ \\\\\r\n \\midrule\r\n conv $3 \\times 3$ & $\\sbrackets{B, 128, 13, 13}$ & $147\\ 456$ \\\\\r\n ReLU & $\\sbrackets{B, 128, 13, 13}$ & $0$ \\\\\r\n \\midrule\r\n conv $3 \\times 3$ & $\\sbrackets{B, 256, 11, 11}$ & $294\\ 912$ \\\\\r\n ReLU & $\\sbrackets{B, 256, 11, 11}$ & $0$ \\\\\r\n \\midrule\r\n flatten & $\\sbrackets{B, 30976}$ & $0$ \\\\\r\n linear & $\\sbrackets{B, 1024}$ & $31\\ 720\\ 448$ \\\\\r\n \\midrule\r\n $l_2$-normalize & $\\sbrackets{B, 1024}$ & $0$ \\\\\r\n \\bottomrule\r\n & \\textbf{total} & $32\\ 162\\ 816$ \\\\\r\n \\cline{2-3}\r\n \\end{tabular}\r\n \\caption[\\gls{femb} head]{Our custom \\gls{femb} head that we used to process backbone-extracted features to produce embedding vectors. It is built from two convolutional layers separated by a \\gls{relu} nonlinearity followed by a fully connected layer that produces a $1024$ dimensional feature embedding. The batch size dimension is given by $B$ in the tensor shape. Since each embedding vector is normalized to unit length, we avoided learning biases throughout the whole network.}\r\n \\label{tab:FeatureEmbeddingHead}\r\n\\end{table}\r\n\r\n% ##############################################################################\r\n\\subsection{Training Phase}\r\n\r\nThe training phase was altered by adding another loss function to the sum of already existing three losses from the original model. In particular, the general \\gls{siammot} loss function defined in \\eqtext{}~\\ref{eq:SiamMOTGeneralLoss} was reformulated as\r\n\\begin{equation}\r\n \\label{eq:SiamMOTFeatureEmbLoss}\r\n \\lossf = l_{rpn} + l_{detect} + l_{motion} + l_{emb}.\r\n\\end{equation}\r\nThe $l_{emb}$ loss incorporated a triplet loss (\\eqtext{}~\\ref{eq:TripletLoss},~p.~\\pageref{eq:TripletLoss}). We also experimented with a contrastive loss (\\eqtext{}~\\ref{eq:ContrastiveLoss},~p.~\\pageref{eq:ContrastiveLoss}), but the effect was detrimental in every aspect as expected, so we will not discuss it any further.\r\n\r\nAs we remarked in \\sectiontext{}~\\ref{sec:LatentSpacesAndEmbeddings},~p.~\\pageref{sec:LatentSpacesAndEmbeddings}, aimed at latent spaces and embeddings, it is crucial to adopt appropriate sample mining strategies when using the triplet loss. The rationale is that for the training to keep progressing, the model needs to encounter harder and harder triplets to generate sufficient learning signals. To this end, we went for the semi-hard triplet mining strategy (\\eqtext{}~\\ref{eq:BatchHardMining},~p.~\\pageref{eq:BatchHardMining}). However, we struggled with collapsing embeddings~\\cite{levi2021rethinking}. This phenomenon happens when the embedding training forces the model to project all the features onto a single point in the embedding space, thus incurring the loss equal to the used margin. We claim that the use of semi-hard negative mining produced triplets that were too difficult. Since we used all the \\gls{rpn} proposals to generate triplets, one may imagine that there would always be proposals covering only some small part of the object, making it problematic for the network to learn the concept of ``similarity'' and ``difference'' if it only processes very hard images. Nevertheless, these situations are very common in margin-based losses~\\cite{levi2021rethinking}. The computed loss is so high that it is more suitable for the model to map all the features onto a single point. To remedy this, we implemented a batch-all online mining strategy (\\eqtext{}~\\ref{eq:BatchAllLossFunction},~p.~\\pageref{eq:BatchAllLossFunction}), which stabilized the training.\r\n\r\nWe recommend first utilizing the batch-all mining strategy during the training, and then proceeding to a batch-hard strategy after a certain point. However, this approach would be time-consuming to find the right hyperparameters. There are many open questions, such as how to mine the \\gls{rpn} proposals in a better way or how to set the margin value. Loss functions aimed at object \\gls{reid} are notoriously cumbersome to train. We implemented the entire mining algorithm followed by the loss computation in a \\gls{gpu}-only fashion for fast execution and easy integration into the pipeline.\r\n\r\n% ##############################################################################\r\n\\subsection{Inference Phase}\r\n\r\n\\subsubsection{Feature-based Non-Maximum Suppression}\r\n\\label{sssec:FeatureNonMaximumSuppression}\r\n\r\nSalscheider~\\cite{salscheider2020featurenms} proposed an extended \\gls{nms} algorithm that incorporates a distance between feature embeddings dubbed as \\featurenms{} (\\algtext{}~\\ref{alg:FeatureNMS}). Considering our idea introduced above, we had to encompass the vector embeddings into the solver reasoning. In the beginning, we came up with a solution that exactly copied the one the mentioned author proposed. That provided further justification for attempting to implement the algorithm and test it in practice. The advantage is that this approach is restricted to the inference phase, thus experimenting with it does not require model re-training.\r\n\r\n\\def\\threshlower{\\tau_{\\text{lower}}}\r\n\\def\\threshupper{\\tau_{\\text{upper}}}\r\n\\def\\threshsim{\\delta}\r\n\r\nWe assume the reader is acquainted with the \\gls{nms} algorithm (\\sectiontext{}~\\ref{ssec:NonMaximumSuppression},~p.~\\pageref{ssec:NonMaximumSuppression}). Here we repeat the same definitions for clarity. Let $\\mset{B} = \\cbrackets{\\vect{b}_1, \\vect{b}_2, \\dots, \\vect{b}_n}$ be a set of $n$ region proposals described by $n$ \\glspl{bbox}. Scores for each detection are contained in a set $\\mset{S} = \\cbrackets{s_1, s_2, \\dots, s_n}$, where $s_i$ denotes a detection score for the $i$-th box, $\\vect{b_i}$. This time, we are also going to need the associated feature embedding vectors with each \\gls{bbox}, represented by a set $\\mset{E} = \\cbrackets{\\vect{e}_1, \\vect{e}_2, \\dots, \\vect{e}_n}$. Let $\\mset{B}_{fnms}$ be the set of filtered proposal instances from the set $\\mset{B}$ produced by the \\featurenms{} algorithm. The distinction in parameters is the following. The original algorithm requires only one threshold for the maximum allowed portion of the overlap between regions. The \\featurenms{} requires three parameters discussed below.\r\n\\begin{itemize}\r\n \\item A minimum threshold $\\threshlower$ denoting a boundary below which the two objects are deemed as different. This value should be low, for example, $0.2$, which means that if the \\gls{iou} between the two objects is less than $0.2$, then the two instances should be treated as different objects.\r\n \\item A maximum threshold $\\threshupper$ denoting a boundary above which the two objects are considered identical. Unlike the $\\threshlower$, this value should be high, \\egtext{}, $0.8$, indicating that if the \\gls{iou} of the two object instances surpasses this threshold, then it should be the same object. The \\gls{bbox} with the lower confidence is discarded.\r\n \\item A threshold $\\threshsim$ is used as a decision boundary between the embedding vectors. This threshold should reflect a measure of similarity. If the adopted measure of similarity falls below $\\threshsim$, then the two objects are different, otherwise, they are considered the same. This value of $\\threshsim$ is used only if the two conditions above do not hold.\r\n\\end{itemize}\r\n\r\n\\begin{algorithm}[t]\r\n \\caption[\\featurenms{} algorithm]{\\featurenms{} algorithm.}\r\n \\label{alg:FeatureNMS}\r\n \\begin{algorithmic}[1]\r\n \\Function{Feature-NMS}{$\\mset{B}$, $\\mset{S}$, $\\mset{E}$, $\\threshlower$, $\\threshupper$, $\\threshsim$}\r\n\r\n \\State $\\mset{B}_{fnms}$ $\\gets$ $\\emptyset$\r\n \\Comment{initialize the output (filtered) set of region proposals}\r\n\r\n \\While {$\\mset{B} \\neq \\emptyset$}\r\n \\Comment{loop until all the proposals are processed}\r\n\r\n \\State $m \\gets \\underset{i \\in \\cbrackets{1, 2, \\dots, \\msetsize{S}}}{\\argmax{}} \\mset{S}$\r\n \\Comment{find an index of a proposal with the highest score}\r\n\r\n \\State $\\mset{B} \\gets \\mset{B} - \\vect{b}_m$, $\\mset{S} \\gets \\mset{S} - s_m$, $\\mset{E} \\gets \\mset{E} - \\vect{e}_m$\r\n \\Comment{remove the proposal}\r\n\r\n \\State $\\mset{B}_{fnms} \\gets \\mset{B}_{fnms} \\cup \\vect{b}_m$\r\n \\Comment{save the proposal with the highest score}\r\n\r\n \\For{$i \\gets 1$ to $\\msetsize{B}$}\r\n \\Comment{iterate through remaining proposals}\r\n\r\n \\If{\\Call{iou}{$\\vect{b}_m$, $\\vect{b}_i$} $\\geq \\threshlower$}\r\n \\Comment{above the lower-bound threshold}\r\n\r\n \\If{\\Call{iou}{$\\vect{b}_m$, $\\vect{b}_i$} $\\geq \\threshupper$}\r\n \\Comment{above the upper-bound threshold}\r\n\r\n \\State $\\mset{B} \\gets \\mset{B} - \\vect{b}_i$, $\\mset{S} \\gets \\mset{S} - s_i$, $\\mset{E} \\gets \\mset{E} - \\vect{e}_i$\r\n \\Comment{remove the proposal}\r\n\r\n \\Else\r\n\r\n \\If{\\Call{similarity}{$\\vect{e}_m$, $\\vect{e}_i$} $\\geq \\threshsim$}\r\n \\Comment{similarity above threshold}\r\n \\State $\\mset{B} \\gets \\mset{B} - \\vect{b}_i$, $\\mset{S} \\gets \\mset{S} - s_i$, $\\mset{E} \\gets \\mset{E} - \\vect{e}_i$\r\n \\Comment{remove the proposal}\r\n \\EndIf\r\n\r\n \\EndIf\r\n \\EndIf\r\n \\EndFor\r\n \\EndWhile\r\n\r\n \\State \\Return $\\mset{B}_{fnms}$\r\n \\EndFunction\r\n \\end{algorithmic}\r\n\\end{algorithm}\r\n\r\n% ##############################################################################\r\n\\subsection{Experimental Evaluation and Discussion}\r\n\r\nThe proposed embedding-based enhancement was evaluated against the baseline model without the \\gls{femb} head. For a fair comparison, we made sure that the hyperparameters were identical to the greatest possible extent. We only had to alter the batch size and the learning rate. Since the triplet loss requires the computation of a large number of triplets, especially the batch-all strategy, we had to decrease the batch size and employ \\gls{ga} to avoid crashes due to not having enough \\gls{gpu} \\gls{vram} available.\r\n\r\nWe can tell that this experiment was also detrimental to the tracker's performance. We conjecture that it was solely caused by the introduction of the \\gls{femb} head itself. Our ablation study also demonstrated that joint training with the \\gls{femb} head harmed the tracker, even if the original solver was adopted during the evaluation. This raises the question of potential task/feature conflict between the heads. We venture to claim there is an inherent incompatibility between the detection, tracking, and \\gls{reid} tasks, despite the existence of a recently published work Lu~\\etal{}~\\cite{lu2020retinatrack}, who developed their \\retinatrack{} tracker. Their framework exploited the base visual object detector called a \\retinanet{}~\\cite{lin2018focal} and then added, in principle, a very similar head as we did to produce embeddings. However, there are obvious architectural differences between the two trackers in terms of how the inference phase is executed.\r\n\r\n\\begin{table}[!t]\r\n \\centering\r\n \\begin{tabular}{llllll}\r\n \\toprule\r\n \\textbf{\\gls{femb} head} & \\textbf{solver} & \\textbf{MOTA} & \\textbf{MOTP} & \\textbf{precision} & \\textbf{recall} \\\\\r\n \\midrule\r\n & original & $0.7416$ & $0.1478$ & $0.9454$ & $0.7896$ \\\\\r\n \\checkmark & \\featurenms{} & $0.6861$ & $0.1568$ & $0.9166$ & $0.7574$ \\\\\r\n \\checkmark & original & $0.6882$ & $0.1568$ & $0.9184$ & $0.7574$ \\\\\r\n \\bottomrule\r\n \\end{tabular}\r\n \\caption[The effect of \\gls{femb} head inclusion]{Demonstration that introduction of the \\gls{femb} head causes a feature conflict on the level of backbone before the \\gls{roi}-pooling operation. The effect is clearly visible since the \\featurenms{} algorithm is only part of the inference phase. Both the object detection and the tracking head are ``parallel'' to the \\gls{femb} head, however, training with the \\gls{femb} head and then avoiding it during the inference considerably reduces the tracker's accuracy. The last two rows are practically identical in terms of \\gls{clear} evaluation.}\r\n \\label{tab:OrigSolverVsFeatureNMS}\r\n\\end{table}\r\n\r\nTo see the aforementioned feature conflict, one of the key takeaways from this trial, \\tabletext{}~\\ref{tab:OrigSolverVsFeatureNMS} shows that training the model with the \\gls{femb} head and then evaluating it without the \\featurenms{} algorithm, \\ietext{}, using the original solver algorithm (\\figtext{}~\\ref{fig:SiamMOTOnlineSolver}), resulted in a drastically reduced tracker's accuracy. The reason is that the \\gls{roi}-pooled features were trained in a conflicting way, therefore no task was served satisfactorily. Having trained the model and then omitting the \\gls{femb} head completely during the testing should not dramatically affect ``parallel heads''. However, once the entire end-to-end model tries to accommodate for the triplet, object detection, and tracking loss functions, the conflicting nature of these tasks manifests itself in a negative fashion. This table shows the best models given by the combination of \\gls{mota} and \\gls{motp} metrics. All models were trained with \\gls{ga} using batch size of $32 = 16 \\times 2$ with $256$ object proposals. The relatively big batch size was dictated by the unstable nature of the triplet loss training.\r\n\r\nAlthough this extension is not appropriate for practical usage unless further modifications are devised, we still wanted to evaluate the impact on inference speed in terms of \\gls{fps} for comparison with the next experiment. It can be seen that the reduction in the tracker's speed is noticable. Specifically, the original model inference runs on average at $26.49$ \\gls{fps}, whilst the \\fembmodel{} version achieves $18.57$ \\gls{fps}, resulting in reduction speed of about $30$\\% (more in \\tabletext{}~\\ref{tab:InferenceSpeedComparison},~p.~\\pageref{tab:InferenceSpeedComparison}).\r\n\r\n\\subsubsection{``Unfairness'' between the detection and re-identification}\r\n\r\nThere is a recent publication~\\cite{zhang2021fairmot} by Zhang~\\etal{} that discusses the notion of ``fairness'' between detection and \\gls{reid}. According to their empirical evidence, there are multiple levels of ``unfairness''. This term was used to describe a situation in which the importance of either \\gls{reid} or the detection task is lessened. We would like to emphasize the recency of this work (the end of $2021$) since several of their remarks and conclusions coincide with ours. Had this paper been published before conducting our experiments, we would have taken a different path, or at least we would have striven to find another way to incorporate the embeddings into an end-to-end pipeline. The aforementioned work, among other things, introduces a joint tracker that effectively circumvents the obstacles related to conflicting tasks. This framework avoids the use of anchor proposals and is based on \\gls{centernet}~\\cite{zhou2019centernet} object detector.\r\n\r\nThey argue that the \\gls{reid} task may become overlooked if the embedding vectors are produced solely from the \\gls{roi}-pooled regions, as in our case. Consequently, the detection task becomes central in terms of influence upon the loss function since generating embedding vectors on incorrect \\glspl{bbox} is meaningless. Thus, the bias to produce accurate object proposals is inescapable.\r\n\r\nNext, a problem arises when one anchor corresponds to multiple identities, which is an obstacle we have already mentioned (\\sectiontext{}~\\ref{ssec:SiamMOTAndReIDDiscussion}). As a result, the extracted features are not optimal in terms of their accuracy as well as discriminative representativeness. To remedy this, features should be extracted at a single point, \\ietext{}, at the estimated object centers (hence the use of \\gls{centernet}), instead of region proposals.\r\n\r\nAn analogical problem is when multiple anchors correspond to one identity. A high overlap in terms of \\gls{iou} directs the model to estimate the same identity for nearby anchors. But, even a small perturbation may result in falling below a specific threshold and the anchors become marked as belonging to different objects. This situation is very common as proposals are generated on the feature level (a coarse representation due to downsampling), and not on the pixel level.\r\n\r\nAnother inherent problem when merging object detection and \\gls{reid} is feature conflict. We have highlighted numerous times the significance of multi-layer feature fusion. However, not all tasks benefit from this approach equally. In particular, object detection utilizes high-level features to estimate object classes and locations, whereas the \\gls{reid} is more prone to utilizing low-level features owing to their discriminative power. For that reason, it is important to balance the loss optimization.\r\n\r\nLast but not least, the feature dimension poses another source of imbalance. The authors remarked that learning lower-dimensional features for the \\gls{reid} is better than higher-dimensional. In our research, we thought the opposite is true. High-dimensional embedding vectors notably harm the object detection accuracy due to the competition between the two tasks. The number of feature dimensions for detection is usually very low (compared to $1024$D or $2048$D embedding vectors). We adopted high-dimensional vector embeddings in conjunction with the usual low-dimensional detector features, thereby further exacerbating the rivalry. The rationale behind proposing to use, \\egtext{}, $64$D embedding vectors, is that the \\gls{mot} task executes just a few one-to-one matchings between two consecutive frames. However, there is a tacit assumption of having all objects sufficiently visible, as this work did not cover occlusion handling and their benchmark evaluations were not specifically targeted at full object occlusion, which is a path worth exploring. Nonetheless, the proposed framework achieved \\gls{sota} performance among \\gls{mot} approaches, surpassing the competitive frameworks by a large margin.\r\n", "meta": {"hexsha": "36270d7a90c6162723489d08ad561a6cc92ec6d7", "size": 22296, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "tex/chapters/siamese_tracking/sections/siammot_and_featureemb.tex", "max_stars_repo_name": "mondrasovic/phd_thesis", "max_stars_repo_head_hexsha": "68a3a6d1687ea43dc6cdfafcd5e6d9ce35f424e8", "max_stars_repo_licenses": ["MIT"], "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/chapters/siamese_tracking/sections/siammot_and_featureemb.tex", "max_issues_repo_name": "mondrasovic/phd_thesis", "max_issues_repo_head_hexsha": "68a3a6d1687ea43dc6cdfafcd5e6d9ce35f424e8", "max_issues_repo_licenses": ["MIT"], "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/siamese_tracking/sections/siammot_and_featureemb.tex", "max_forks_repo_name": "mondrasovic/phd_thesis", "max_forks_repo_head_hexsha": "68a3a6d1687ea43dc6cdfafcd5e6d9ce35f424e8", "max_forks_repo_licenses": ["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.6818181818, "max_line_length": 1579, "alphanum_fraction": 0.7192321493, "num_tokens": 5379, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3702253786982541, "lm_q1q2_score": 0.18800483976023488}}
{"text": "% This is an example for a `Introduction'.\n% To generate the final document, run latex, build and quick build commands\n% on the skeleton-thesis file not this one.\n\n\\chapter{Introduction}\\label{chapters:Introduction}\n%\\vspace{-7mm}\n\nWhile seemingly small objects, nuclei and their interactions can play an enormous role across a wide swath of energy and spatial scales.\nFrom understanding the abundance of elements produced in astrophysical events to providing a general description of quantum many-body equilibration, the deceptively simple study of two colliding nuclei can be illuminating.\nEven the more traditionally aligned investigations that are associated with nuclear reactions (such as superheavy element and neutron-rich nuclei formation) acts as a foundation for other areas of physics to piece together an understanding of the physical world.\n\nLeaving aside the fact that nuclei are made of protons and neutrons, the dynamics of interacting quantum systems alone is of extreme interest to researchers from varied fields.\nThis is due to the striking fact that most quantum many-body systems (no matter the specific systems and particles that compose their structure) exhibit the same general features as atomic nuclei.\nThat is to say that studying the fusion, transfer, equilibration, vibrations, etc. of nuclear systems can provide vital insight into analogous studies in interactions between cold atoms or molecules -- systems which are several orders of magnitude larger than the few femtometers (fm) of interest to nuclear physicists.\n\n\\section{The nuclear many-body problem (in a nutshell)}\n\n\\begin{figure}[t]\n\t\\includegraphics[width=\\textwidth]{../Figures/intro_figs/ReidForce2.jpg}\n\t\\caption{An example nucleon-nucleon potential from the Reid model~\\citep{reid1968} of the nuclear force. Note the characteristic exponential decay in the attractive tail, as well as the strong repulsion that tends toward infinity at $R\\approx0.7$. Figure from~\\citep{bdushaw}.}\n\t\\label{fig:reid}\n\\end{figure}\n\nThe specific subbranch of nuclear physics this thesis focuses on is the realm of low-energy nuclear physics.\nAt this level, relativistic effects are typically neglected and the nuclei are modeled as collections of protons and neutrons interacting with each other to form a bound system.\nThe force felt by the nucleons themselves is an artifact of the strong interaction, mediated primarily by the exchange of virtual pions with an effective range of about~$1$~fm.\nThrough further contributions by vector mesons (principally rho and omega), a complicated model of interacting nucleons can be built that depends on not only a nucleon's charge and distance, but also on its spin and angular momentum as well.\nAn example channel of the Reid potential~\\citep{reid1968} is shown in Fig.~\\ref{fig:reid}.\nExtensive effort has been placed in modeling nuclei using such an interaction (see ~\\citep{wiringa1995} for another popular choice of an N-N potential), though this \\textit{ab initio} approach is not numerically feasible for large nuclei or for simulating dynamical interactions between nuclei.\nIt is for this reason that alternate approaches to modeling finite nuclei have been pursued throughout the field's history.\n\nOne such approach is that of the mean-field method which, simply stated, assumes that each nucleon moves freely through an average field made up of contributions from all the other nucleons.\nThis independent particle approximation is extremely powerful because it reduces a series of N-body self interactions to a simple sum over each individual particle.\n%in the mean-field.\n%A schematic image is shown in Fig.~\\ref{fig:meanfield}.\nWhile many takes on the mean-field idea have been pursued over time, the foundation of the current work was formulated in 1928 when Hartree developed the self-consistent field method~\\citep{hartree1928}.\nThis was further extended for antisymmetric systems by Fock to form the more complete Hartree-Fock method that has been used since~\\citep{fock1930}.\nThe term \"self-consistent\" used above refers to the fact that the effective Hamiltonian of the system depends on the single particle wave functions themselves, thus requiring the problem to be solved iteratively.\nOne common approach is to choose an initial guess of Gaussian wave packets for the first step and then a minimization procedure is followed to obtain the ground state solution for the nucleus.\nDespite having a general purpose algorithm for self-consistently solving the static many-body quantum problem, the method wasn't widely adopted until computational abilities were readily available due to the large matrices involved in larger systems paired with the iterative nature of the problem.\n\n\nWhile the Hartree-Fock method provides a general purpose, robust numerical algorithm, it is only useful for studying static properties of nuclei.\nTo obtain a time-dependent theory based on the mean-field approximation, one may proceed in several ways\\footnote{For a more complete description of the various approaches to deriving TDHF (including a path integral formulation, many-body perturbation theory, the Balian-V\\'en\\'eroni variational principle, etc) see~\\citep{simenel2018}.} though we will focus on the derivation by minimization of the Dirac action.\nAs it's vital to all chapters of this thesis and reveals much about the approximations and limitations of the theory, I will cover the derivation in detail.\nFirst, consider the Dirac action from $t_0$ to $t_1$,\n\\begin{equation}\nS\\equiv S_{t_0,t_1}[\\Psi] = \\int_{t_0}^{t_1}dt \\langle \\Psi(t) | \\left(i\\hbar\\frac{d}{dt}-\\hat{H}\\right)|\\Psi(t)\\rangle.\n\\end{equation}\nFor a generic many-body wave function, $|\\Psi(t)\\rangle$, the stationary solution of the action will simply be the Schr\\\"odinger equation, thus we impose that the many-body wave function is a Slater determinant of independent particle states $|\\phi_i(t)\\rangle$ to obtain\n\\begin{equation}\nS_{t_0,t_1}[\\Psi] = \\int_{t_0}^{t_1}dt \\left(\\sum_{i=1}^{N} \\langle\\phi_i(t)|i\\hbar\\frac{d}{dt}|\\phi_i(t)\\rangle-\\langle\\phi_i(t)|\\hat{H}|\\phi_i(t)\\rangle\\right).\n\\end{equation}\nThis can be simplified further by defining the quantity $\\sum_{i=1}^{N}\\langle\\phi_i(t)|\\hat{H}|\\phi_i(t)\\rangle$ as an energy density functional (EDF), $E[\\rho(t)]$.\nNow, by varying with respect to single particle states we may impose the stationarity of the action\n\\begin{equation}\n\\frac{\\delta S}{\\delta\\langle\\phi_i(t)|}=i\\hbar\\frac{d}{dt}|\\phi_i(t)\\rangle - \\int_{t_0}^{t_1}dt' \\frac{\\delta E[\\rho(t)]}{\\delta\\langle\\phi_i(t)|} = 0,\n\\end{equation}\nwith the final step being to utilize the chain rule in the EDF integral and define a final quantity, the single particle Hamiltonian, $h[\\rho(t)]=\\frac{\\delta E[\\rho(t)]}{\\delta\\rho(t)}$.\nCollecting all of this, we are left with our final TDHF equation\n\\begin{equation}\ni\\hbar\\frac{d}{dt}|\\phi_i(t)\\rangle = h[\\rho(t)]|\\phi_i(t)\\rangle.\n\\label{eq:tdhf}\n\\end{equation}\nBy examining the form of the TDHF equations, we see that we have a description of the time evolution for each state, $i$, in the system.\nFurthermore, the single particle Hamiltonian has a dependence on $\\rho(t)$ and thus on the wave functions themselves.\nThis is in line with the self consistency feature of static Hartree-Fock mentioned above, and thus in the time propagation procedure densities from a half time step are typically used for stability.\n\n\\begin{figure}[t]\n\t\\includegraphics[width=\\textwidth]{../Figures/intro_figs/paths.png}\n\t\\caption{A schematic depiction of the stationary path chosen for the TDHF evolution.\\hfill\\null}\n\t\\label{fig:paths}\n\\end{figure}\n\nAn extremely important feature of the TDHF method comes about by restricting ourselves to the stationary path from $t_0$ to $t_1$, namely that we recover only a single path in time.\nThis is at odds with a fully quantum picture of a many-body system evolving in time where multiple paths have some probability of occurring.\nFigure~\\ref{fig:paths} shows a schematic explanation of this choice.\nIt is for this reason that TDHF is described as a semi-classical theory and only recovers the most probable event in a time evolution.\nBeyond this, the derivation required us to consider fully independent particles, just as assumed in the Hartree-Fock method, meaning that many-body correlations will not be considered.\nAs will be seen later in this thesis, these (and other) limitations require extensions to the base theory to uncover features in nuclear reactions that are absent with the present formulation.\nDespite the theoretical shortcomings of the approach, pure TDHF calculations have been extremely successful in reproducing experimental data over its history.\n\nOne final point of interest to note from the derivation above is the appearance of a density dependent single particle Hamiltonian in Eq.~\\ref{eq:tdhf}.\nAs this Hamiltonian was derived by varying an EDF by the density, it allows one to skip a standard representation of the interaction between nucleons as a one or two-body potential and write down the EDF directly.\nThis is now the standard approach in mean-field, low-energy nuclear physics and there are various forms and fits of functionals that are in active use such as Skyrme and Gogny~\\citep{skyrme1956,decharge1980}.\nIn practice, the nuclear EDF also depends on other quantities such as the probability current, spin density, spin-current density, and so on.\nThe interaction used in the results presented in the current work are of the Skyrme type and the specific EDFs are noted in the individual chapters' method sections.\n%This approach is justified by the Hohenberg-Kohn theorems which prov~\\citep{hohenberg1964}\n\nThe specific mean-field and beyond mean-field approaches to each project presented in this work are discussed in their respective chapters, though a general, brief word should be said about the validity of the mean-field method as it applies to atomic nuclei.\nAs the nucleus is traditionally thought of as a densely packed collection of nucleons, the primary assumption that individual protons and neutrons can travel freely in the nucleus is a bit counter intuitive.\nIt turns out, however, that the Pauli exclusion principle between nucleons ensures that the particles will remain at an average distance exceeding their radius at low energies~\\citep{ring1980}.\nEven at finite collision energies, the mean free path of nucleons in the nucleus is several times that of the nuclear radius, implying that a so-called hard-core collision is unlikely.\nThis means that the average potential felt by the nucleons in the nucleus will be around the minimum of a model potential like the one shown in Fig.~\\ref{fig:reid}.\nShould one go to higher collision energies, the mean-field approximation begins to break down and may misrepresent the outcome of such reactions.\n\n\\section{Nuclear dynamics}\n\n\\begin{figure}[t]\n\t\\includegraphics[width=\\textwidth]{../Figures/intro_figs/timescale.png}\n\t\\caption{The general timescales of nuclear reactions from quasielastic scattering through fusion and subsequent decay.}\n\t\\label{fig:timescale}\n\\end{figure}\n\nOur focus is now turned to the dynamics of nuclear physics at low collision energies as predicted by TDHF.\nBroadly speaking, for two incoming nuclei with their own distinct numbers of protons and neutrons, one could expect to see a large number of possible outcomes depending on factors such as the orientation of the incoming nuclei, the distance off the collision axis, and the energy between the two fragments.\nWhat is seen experimentally will be some complex combination of initial configurations, however.\nThe typical technique employed to investigate a given system is then to perform a large number of calculations across the configuration space in an attempt to understand what is happening systematically as you change any initial quantity.\nIt is for this reason that one must take care to check the full parameter space in order to make authoritative statements on the physics at play in reactions, especially when comparing to experimental data.\n\nThe usual method of classifying nuclear reactions is by the length of time that the fragments stay in contact\\footnote{The specific definition of contact varies from work to work, though it is typically stated as when the density in the neck region between the nuclei is around half the saturation density, $\\rho=0.08$.} before coming apart again.\nOf course, if the fragments stay together indefinitely this is interpreted as a fusion event in TDHF.\nThough the timescales and definition of reaction channels are fluid, they may be roughly divided into categories as is shown in Fig.~\\ref{fig:timescale}.\nFor reasons mentioned in the previous section TDHF is capable of investigating reaction mechanisms from the far left of the chart up through compound nucleus formation (around $10^{-20}-10^{-19}$s in Fig.~\\ref{fig:timescale}).\nAny subsequent events after a fused system is formed, like fission or the evaporation of a particle, will not occur in a TDHF calculation and must be dealt with using a separate technique.\n\n\\begin{figure}[t]\n\t\\includegraphics[width=\\textwidth]{../Figures/intro_figs/48Ca249BkEvolution_tr.png}\n\t\\caption{A typical density evolution for a quasifission reaction. The system presented is $^{48}$Ca$+^{249}$Bk and the figure is taken from~\\citep{godbey2020}.}\n\t\\label{fig:qf}\n\\end{figure}\n\nAs an example case, a typical set of contours from a benchmark quasifission reaction may be seen in Fig.~\\ref{fig:qf}.\nIn this reaction, as is common in quasifission, the initially mass asymmetric system collides and begins to exchange a substantial amount of energy and mass before rotating and forming two new nuclei as they separate.\nAs mentioned before, the nuclei produced in such a reaction will depend on the initial configuration, and substantial effort has been expended to understand the production rates of nuclei via these sorts of reactions.\nFrom the image it is clear that the dynamics governing the outcome of a nuclear collisions depend on much more than the incoming number of particles, hence the sophisticated tools required to study these processes.\n\n\\section{Summary}\n\nThrough use of state-of-the-art many-body methods this thesis explores nuclear reactions through both theoretical development and extensions of the base theories, as well as through systematic, comprehensive studies of nuclei.\nEach chapter either focuses on a specific aspect of nuclear reactions or attempts to exhaustively characterize a given system.\nIn Chapter~\\ref{chapters:chapter_2}, I discuss the development of a new extension to explore the role of transfer in the initial stages of the collision on fusion.\nThe basis of the technique is described and then select applications are presented to demonstrate the applicability to generic nuclear systems.\nChapter~\\ref{chapters:chapter_3} meanwhile continues to focus on fusion, though via a more basic aspect.\nSpecifically, a method is developed to directly show the impact of the Pauli exclusion principle on heavy ion collisions at low energies.\n\n\nChapters~\\ref{chapters:chapter_4} and~\\ref{chapters:chapter_5} turn away from the development of new extensions to TDHF and instead look into the effect of the Skyrme tensor interaction on fusion for multiple systems.\nSimilar to this is Chapter~\\ref{chapters:chapter_6} which studies fusion cross sections of \\textsuperscript{12}C+\\textsuperscript{12}C both above and below the fusion barrier.\nThis study also represents an effort to make extremely precise fusion calculations be checking the effect of numerical changes on the results.\n\nFinally, the last two chapters are largely devoted to transfer studies for two systems of nuclei.\nChapter~\\ref{chapters:chapter_7} utilizes direct TDHF collisions to study fragment production in $^{48}$Ca+$^{249}$Bk reactions.\nDue to the deformed nature of $^{249}$Bk, a complete sweep of angles was performed to paint the fullest picture yet of quasifission in TDHF.\nWhile also a study of transfer, Chapter~\\ref{chapters:chapter_8} goes beyond TDHF to look at fluctuations about the mean field to uncover the correlations that are missing in the base theory.\nThis system, as did the one before, requires a large amount of computation due to the deformed initial states and the added cost of the beyond TDHF method.\n\n\n\n\n\\clearpage\n", "meta": {"hexsha": "509c22fe9ed1e0fa668d32c62ae1a1133379586f", "size": 16324, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Chapters/introduction.tex", "max_stars_repo_name": "kylegodbey/Dissertation", "max_stars_repo_head_hexsha": "63048eecc834936896cb762f7d05b3faa945af78", "max_stars_repo_licenses": ["MIT"], "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": "kylegodbey/Dissertation", "max_issues_repo_head_hexsha": "63048eecc834936896cb762f7d05b3faa945af78", "max_issues_repo_licenses": ["MIT"], "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": "kylegodbey/Dissertation", "max_forks_repo_head_hexsha": "63048eecc834936896cb762f7d05b3faa945af78", "max_forks_repo_licenses": ["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.3947368421, "max_line_length": 413, "alphanum_fraction": 0.8028669444, "num_tokens": 3636, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165085228825, "lm_q2_score": 0.35577490034429643, "lm_q1q2_score": 0.18760597826963085}}
{"text": "% !Mode:: \"TeX:UTF-8\"\n\n\\documentclass[11pt, a4paper]{article}\n%\\usepackage{xltxtra,fontspec,xunicode}\n\\usepackage{amsmath}\n\\usepackage{amssymb}\n\\usepackage{breqn}\n\\usepackage{autobreak}\n\\usepackage{braket,mleftright}\n\\usepackage{amsfonts}\n\\usepackage[section]{placeins}\n\\usepackage{float}\n\\usepackage{siunitx}\n\\usepackage{graphicx}\n\\usepackage{subcaption}\n\\usepackage{mwe}\n\\usepackage{indentfirst}\n\\usepackage{caption}\n\\usepackage{physics}\n\\usepackage{geometry}\n\\usepackage{graphicx}\n\\usepackage{algorithm}% http://ctan.org/pkg/algorithm\n\\usepackage{algpseudocode}% http://ctan.org/pkg/algorithmicx\n\n\\geometry{top=1in, bottom=1in, left=1in, right=1in}\n%\\linespread{1.5}\n\n\\DeclareMathOperator*{\\argmax}{argmax}\n\\DeclareMathOperator*{\\argmin}{argmin}\n\n\\newcommand{\\degc}{$\\,^\\circ$C}\n\n\\begin{document}\n\n\\title{Work Report}\n\\author{Zhuoran Qiao}\n\\date{\\today}\n\n\\maketitle\n\n\\section{Introduction}\n\n\\paragraph{1} Developed a genetic algorithm based approach to simulate kinetics of co-transcriptional folding.\n\\paragraph{2} Tested effect of folding rate variation on folding population dynamics and $p_{unbound}$.\n\n\n\\section{Progress}\n\\subsection{Framework}\nVarious algorithms or programs have been developed to predict RNA folding pathway ultilizing force-field based simulations and multiple coarse grained energy landscape sampling methods built on Markov state model. Those present methods have succeeded in revealing multiscale dynamic events during RNA folding, however are either designed for only predicting\nannealing dynamics or limited to RNA segments with length up to hundred bases. To quantitatively predict folding dynamics coupled with transcription,\nwe developed a genetic algorithm and chemical Master equation based approach, which is capable of capturing kilobase level kinetics.\n Our method is built on two following assumptions:\n\\paragraph{1} All populated RNA secondary structures (SS) are linkage of locally optimal or sub-optimal structures at various folding sites;\n\\paragraph{2} Global structural rearrangement of a partial RNA segment is permitted only if it's folding to the optimal SS on that segment.\n\\\\\n\nFormally, we denote a domain $D_{A,\\,B}$ as a segment between base $A$ and $B$ that all contacts on that segment are local. For simplicity, we denote \\textbf{foldon}\nas domains with optimal secondary structures: $D^{foldon}_{A,\\,B} = \\text{MFE(sequence[A,B])}$. Note that $'.'$ is a trival example of foldon.\nOur assumption 1 can be rewritten as\n\\begin{equation}\n D_{A,\\,B} = D^{foldon}_{A, i_1} \\oplus D^{foldon}_{i_1, i_2} \\oplus ... \\oplus D^{foldon}_{i_n, B}\n\\end{equation}\nWhere $\\oplus$ represents a link operation. Note that all structural information of $D_{A,\\,B}$ is encoded by the sequential representation $[A,\\, i_1,\\, ...,\\, i_n,\\, B]$;\n as a foldon is also a linkage of smaller foldons, there could be multiple way to represent $D_{A,\\,B}$. Here we introduce \\textbf{Irreducible Foldon Representation} (IFR) to be the\n sequential representations for which linkage of every adjacent foldons is not another foldon: $\\forall k,\\, D^{foldon}_{i_k, i_{k+1}} \\oplus D^{foldon}_{i_{k+1}, i_{k+2}} \\neq D^{foldon}_{i_{k}, i_{k+2}}$.\n Then the sufficient and necessary condition for structural rearrangement is\n\n\\begin{center}\n $\\langle D^{u}_{A,\\,B} | \\hat{\\mathbf{T}} | D^{v}_{A,\\,B} \\rangle \\neq 0$ if and only if $\\exists\\, i,\\,j$ satisfies\n\n $i,\\,j \\in D^{u}_{A,\\,B}$.IFR, $i,\\,j \\in D^{v}_{A,\\,B}$.IFR;\n\n $D^{u}_{A,\\,i} = D^{v}_{A,\\,i},\\, D^{u}_{j,\\,B} = D^{v}_{j,\\,B}$;\n\n $D^{u}_{i,\\,j} = D^{foldon}_{i,\\,j}$ or $D^{v}_{i,\\,j} = D^{foldon}_{i,\\,j}$.\n\n Then $\\langle D^{u}_{A,\\,B} | \\hat{\\mathbf{T}} | D^{v}_{A,\\,B} \\rangle = \\langle D^{u}_{i,\\,j} | \\hat{\\mathbf{T}} | D^{v}_{i,\\,j} \\rangle$.\n\\end{center}\n\n\\subsection{Folding pathway identification \\& Rate calculation} \\label{section:rate}\n\nGiven two domains between which rearrangement is allowed, the task is to compute forward and backward rate constant\nlinking each other. Multiple methods to rigorously calculate the maximum likelihood during RNA folding have been reported;\nhere we proposed a computationally feasible approach: the forward free energy barrier is estimated by sum up all free energy associated\nwith old stacks unzipping and new loop forming; then rate constant $k_{uv} = \\langle D^{u}_{A,\\,B} | \\hat{\\mathbf{T}} | D^{v}_{A,\\,B} \\rangle $ is calculated by Arrhenius approximation $k_{uv} = k_0 \\exp[-\\frac{1}{RT}(\\Delta G^{Stack}_{u}+\\Delta G^{Loop}_{v})]$. 'New' and 'old' helices are identified by comparing elementary domains (defined as domains that cannot be decomposed to smaller valid domains) between reactant and product domains; identical elementary domains are excluded.\n\n\\subsection{Algorithm procedure}\n\nDuring every iterative elongation step, an active species pool of strands with unique SS and diffrent population is updated. New candidate strands $D^{Candidate}_{0,\\, L+\\Delta L}$ with\nlength $L+\\Delta L$ are generated by a recombination\nprocess: for every old strand $D^{Strand}_{0, \\text{ L}}$, all indices in its IFR is identified as possible rearrangement site, then its child strands is generated by linking partial domains\n$D^{Strand}_{0, \\text{ Site}}$ with a foldon $D^{foldon}_{\\text{Site}, L+\\Delta L}$ that terminated at $L+\\Delta L$.\n\nWe assume that elongation will not change the inital population distribution\nof secondary structures: child strands with the exact parental SS on $[0, L]$ ($D^{child}_{0, L+\\Delta L} = D^{strand}_{0, L} \\oplus D^{foldon}_{L, L+\\Delta L}$) will also inherit the population of their parents.\n\nAfter structual generation the rate matrix among all candidate strands within the new active species pool is calculated (see part \\ref{section:rate}). Then the population\ndistribution of strands after elongation is computed by propagate the chemical master equation.\n\nFor the sake of computational efficiency, we introduce a cutoff $N $ as the size limit of the active species pool. After each elongation step, we impose a selection sweep on all active\nstrands; species with top $N $ fitness is reserved. In the current edition, we simply used population as the fitness function. Population of remaining strands within\nthe active pool is renormalized after selection.\n\nPseudocodes of the whole simulation procedure are as follows (Algorithm \\ref{algorithm:1}):\n\n\\begin{algorithm}\n \\begin{algorithmic}[1]\n \\State Initalize ActivePool\n \\While{$\\text{sequence length} > \\text{current length }$}\n \\State $\\text{OldPool} \\gets \\text{ActivePool }$\n \\State $\\text{renew ActivePool }$\n \\State $\\text{Current length} \\gets \\text{Current length} + dL$\n \\State $\\text{dt} \\gets dL / k_T$ \\Comment{Transcription time}\n \\For{$\\text{left boundary} \\in \\text{\\{0, dL, 2dL, ..., Current length - dL\\}}$}\\Comment{Get all new foldons}\n \\State $D^{foldon}_{\\text{left boundary}, \\text{ Current length}} \\gets \\text{numpy.mfe(sequence[left boundary, Current length]})$\n \\EndFor\n \\For{$\\text{Strand} \\in \\text{OldPool }$}\\Comment{Recombination}\n \\For{$\\text{Site} \\in \\text{Strand.IFR }$}\n \\State $D^{Candidate}_{0,\\text{Current length}} \\gets D^{Strand}_{0, \\text{ Site}} \\oplus D^{foldon}_{\\text{Site}, \\text{ Current length}}$\n \\If {$D^{Candidate}_{0,\\text{Current length}} \\in \\text{ActivePool }$}\n \\State $\\text{update $D^{Candidate}_{0,\\text{Current length}}$.IFR}$\n \\Else\n \\State $\\text{add $D^{Candidate}_{0,\\text{Current length}}$ to ActivePool}$\n \\EndIf\n \\If {$\\text{site} = \\text{Current length} - dL$}\n \\State $\\langle \\text{ActivePool}.\\textbf{population}\\,|D^{Candidate}_{0,\\text{Current length}}\\rangle \\gets \\langle \\text{OldPool}.\\textbf{population}\\,|D^{Strand}_{0, \\text{ Site}}\\rangle$\n \\EndIf\n \\EndFor\n \\EndFor\n \\For{$D^{\\text{u}}_{0,\\text{Current length}} \\neq D^{\\text{v}}_{0,\\text{Current length}} \\in \\text{ActivePool}$}\\Comment{Calculate new rate matrix}\n \\State $\\text{calculate } D^{u}_{\\text{rearrange}} ,\\ D^{v}_{\\text{rearrange}}$\\Comment{Find all helices involved in rearrangement}\n \\State $\\langle D^{u}_{\\text{rearrange}} | \\hat{\\mathbf{T}} |D^{v}_{\\text{rearrange}} \\rangle \\gets k_0 \\exp(-\\frac{1}{RT}(\\Delta G^{Stack}_{u}+\\Delta G^{Loop}_{v}) )$\n \\EndFor\n \\State $\\langle \\text{ActivePool}.\\textbf{population}\\,|\\, \\gets \\langle \\text{ActivePool}.\\textbf{population}\\,|\\, \\exp(t\\times\\hat{\\mathbf{T}}) $\\Comment{Master equation}\n \\State $\\text{reserve top $N$ populated strands in ActivePool}$\\Comment{Selection}\n \\State $\\text{renormalize }\\langle \\text{ActivePool}.\\textbf{population}\\,|$\n \\EndWhile\n \\end{algorithmic}\n\\caption{Co-transcriptional folding elongation procedure}\\label{algorithm:1}\n\\end{algorithm}\n\n\\subsection{Results}\n\nThe only remaining free parameter to be determined is $k_0/k_T$, the ratio of pre-exponential factor in Arrhenius rate formulation and trancription rate ($nt\\cdot s^{-1}$). I tuned $k_0/k_T$ from $10^{1}$ to $10^{15}$ and obtained the data for $k_0/k_T=\\infty$ by calculate stationary distribution ($\\frac{1}{Q}\\exp(-G_i)$) after every elongation step for strand i in active pool.\n \n\\paragraph{Population analysis} For folA-WT four predominant local folding motifs within SD sequence are identified. Figure \\ref{fig:local_foldings} shows exemplary secondary structures containing these motifs; figure \\ref{fig:populations} shows evolution of these structure motifs during co-transcriptional folding with different $k_0/k_T$. Identical motifs are marked by the same color as in figure \\ref{fig:local_foldings}. Surprisingly we noticed that when $k_0/k_T=\\infty$, exchange between dominant motifs is very frequent at early stage of transcription, indicating the sensitivity of local structures on long-range contacts, and dependence of motif predominance on the limited timescale for folding.\n\n\\begin{figure*}\n \\centering\n \\begin{subfigure}[b]{0.475\\textwidth}\n \t\t\\centering\n \t\\includegraphics[width=\\textwidth]{folding_example_purple}\n \t\\caption[]%\n \t\t{{\\small Motif 1}} \n \t\\label{fig:mean and std of net14}\n \\end{subfigure}\n \t\\hfill\n \\begin{subfigure}[b]{0.475\\textwidth} \n \t\t\\centering \n \t\t\\includegraphics[width=\\textwidth]{folding_example_blue}\n \t\\caption[]%\n \t{{\\small Motif 2}} \n \t\t\\label{fig:mean and std of net24}\n \t\\end{subfigure}\n \t\\vskip\\baselineskip\n \t\\begin{subfigure}[b]{0.475\\textwidth} \n \t\\centering \n \t\\includegraphics[width=\\textwidth]{folding_example_red}\n \t\t\\caption[]%\n \t\t{{\\small Motif 3}} \n \t\\label{fig:mean and std of net34}\n \\end{subfigure}\n \t\\quad\n \t\\begin{subfigure}[b]{0.475\\textwidth} \n \t\t\\centering \n \t\\includegraphics[width=\\textwidth]{folding_example_grey}\n \t\\caption[]%\n \t\t{{\\small Motif 4}} \n \t\t\\label{fig:mean and std of net44}\n \t\\end{subfigure}\n \\caption[ Exemplary ss containing folding motifs within folA-WT Shine-Dalgarno sequence ]\n \t{\\small Exemplary ss containing folding motifs within folA-WT Shine-Dalgarno sequence} \n \t\\label{fig:local_foldings}\n\\end{figure*}\n\n\\begin{figure*}[tph]\n\\centering\n\\includegraphics[width=\\textwidth]{RNA_local_population_evolution_summary}\n\\caption[Population dynamics]{\\small Population dynamics of four structrual motifs during co-transcriptional folding.}\n\\label{fig:populations}\n\\end{figure*}\n\n\\paragraph{$p_{unbound}$ analysis} We calculated $p_{unbound}$ with respect to transcription time and $k_0/k_T$ (Figure \\ref{fig:RNA_p_unbound_SD_k_tuning}-\\ref{fig:RNA_p_unbound_base[-14]_k_tuning}). Deviation of asymptotic behavior from equilibrium value (calculated by nupack.ppairs) is possiblly due to the limited set of foldons (only used mfe to obtain current results).\n\n\\begin{figure}\n\t\\centering\n\t\\includegraphics[width=\\linewidth]{p_unbound/RNA_p_unbound_SD_k_tuning}\n\t\\caption{}\n\t\\label{fig:RNA_p_unbound_SD_k_tuning}\n\\end{figure}\n\\begin{figure}\n\\centering\n\\includegraphics[width=\\linewidth]{p_unbound/RNA_p_unbound_base[-8]_k_tuning}\n\\caption{}\n\\label{fig:RNA_p_unbound_base[-8]_k_tuning}\n\\end{figure}\n\\begin{figure}\n\\centering\n\\includegraphics[width=\\linewidth]{p_unbound/RNA_p_unbound_base[-9]_k_tuning}\n\\caption{}\n\\label{fig:RNA_p_unbound_base[-9]_k_tuning}\n\\end{figure}\n\\begin{figure}\n\\centering\n\\includegraphics[width=\\linewidth]{p_unbound/RNA_p_unbound_base[-10]_k_tuning}\n\\caption{}\n\\label{fig:RNA_p_unbound_base[-10]_k_tuning}\n\\end{figure}\n\\begin{figure}\n\\centering\n\\includegraphics[width=\\linewidth]{p_unbound/RNA_p_unbound_base[-11]_k_tuning}\n\\caption{}\n\\label{fig:RNA_p_unbound_base[-11]_k_tuning}\n\\end{figure}\n\\begin{figure}\n\\centering\n\\includegraphics[width=\\linewidth]{p_unbound/RNA_p_unbound_base[-12]_k_tuning}\n\\caption{}\n\\label{fig:RNA_p_unbound_base[-12]_k_tuning}\n\\end{figure}\n\\begin{figure}\n\\centering\n\\includegraphics[width=\\linewidth]{p_unbound/RNA_p_unbound_base[-13]_k_tuning}\n\\caption{}\n\\label{fig:RNA_p_unbound_base[-13]_k_tuning}\n\\end{figure}\n\\begin{figure}\n\\centering\n\\includegraphics[width=\\linewidth]{p_unbound/RNA_p_unbound_base[-14]_k_tuning}\n\\caption{}\n\\label{fig:RNA_p_unbound_base[-14]_k_tuning}\n\\end{figure}\n\n\n%\\paragraph{a.} Using a genetic-algorithm based method and NUPACK to predict populated RNA configurations during cotranscriptional folding (in progress);\n%\\paragraph{b.} Using master equation method to simulate evolution of folding configurations and SD sequence accessibility.\n\n%In order to examine when the one-dimensional coordinate projection could be recognized as effective reaction coordinate,\n%we then examine the probability distribution of committors for transition path trajectories $p(q|TP)$, for which a single peak of probability $p(q|TP)$ have been ultilized as a indicator for 'good' reaction coordinates.\n% Firstly, We found that for harmonic toy model, the shape of $p(q|TP)$ is very sensitive to the definition of source/sink region. For illustration, $p(q|TP)$ for two different selection\n% of source/sink regions was compared: in the first case, only two free energy minimum was indentified as source or sink\\textbf{(S1)}; in the second case, only the barrier top was\n% defined as the transition path, while other two region of the free energy landscape was calssified as source/sink\\textbf{(S2)}.\n\n%\\cite{Jacobs2018,Chaudhury2010,Vanden-Eijnden2010,Metzner,Krivov}\n\n\\small\n%\\bibliographystyle{plain}\n%\\bibliography{0727}\n\n\\end{document}\n", "meta": {"hexsha": "1848f4d54fa3be311e11c828a07e6bb0bd9d719c", "size": 14421, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Reports/0815/Work_Report_Zhuoran_Qiao_0726-0815.tex", "max_stars_repo_name": "Utenaq/GenoFold", "max_stars_repo_head_hexsha": "31b626ebf3d08b16b1cdf6544c36bbea75147719", "max_stars_repo_licenses": ["MIT"], "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/0815/Work_Report_Zhuoran_Qiao_0726-0815.tex", "max_issues_repo_name": "Utenaq/GenoFold", "max_issues_repo_head_hexsha": "31b626ebf3d08b16b1cdf6544c36bbea75147719", "max_issues_repo_licenses": ["MIT"], "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/0815/Work_Report_Zhuoran_Qiao_0726-0815.tex", "max_forks_repo_name": "Utenaq/GenoFold", "max_forks_repo_head_hexsha": "31b626ebf3d08b16b1cdf6544c36bbea75147719", "max_forks_repo_licenses": ["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.2528735632, "max_line_length": 707, "alphanum_fraction": 0.7353165523, "num_tokens": 4159, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3665897432423098, "lm_q1q2_score": 0.18759005873132653}}
{"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% GEANT manual in LaTeX form %\n% %\n% Michel Goossens (for translation into LaTeX) %\n% Version 1.00 %\n% Last Mod. Jan 24 1991 1300 MG + IB %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\Origin{L.Urb\\'{a}n}\n\\Revision{J. Chwastowski}\n\\Submitted{26.10.84}\\Revised{16.12.93}\n\\Version{GEANT 3.16}\\Routid{PHYS231}\n\\Makehead{Simulation of photoelectric Effect}\n\\section{Subroutines}\n\\Shubr{GPHOT}\n{\\tt GPHOT} simulates the photoelectric effect. It uses the following\ninput and output:\n\\begin{DLtt}{MMMMMMM}\n\\item[Input]{via common \\Cind{GCTRAK}}\n\\item[Output]{via common \\Cind{GCKING}}\n\\end{DLtt}\nIt calls the functions \\Rind{GPHSG1}, \\Rind{GPHSGP}, \\Rind{GAVRL2}\nand \\Rind{GAVRL3} for the cross-section and the functions \\Rind{GHPHAK},\n\\Rind{GHPHAL1}, \\Rind{GHPHAL2}, \\Rind{GPHAL3} for the cosine distribution \nof the photoelectron. \\Rind{GPHOT} is called by the tracking routine\n\\Rind{GTGAMA}, if, and when, the photon reaches its interaction point.\n\\Sfunc{GAVRL2}{VALUE = GAVRL2(GAMAL2,BETAL2,X)}\n\\Rind{GAVRL2} calculates approximation of the cross-section for the \nphotoelectric effect from $L_{II}$ shell. {\\tt GAMAL2},\n{\\tt BETAL2} are the Lorentz gamma and beta factors of the emitted \nphotoelectron and $X = m_e/E_\\gamma$ where $m_e$ is\nthe electron mass and $E_\\gamma$ is the incident radiation energy.\n\\Rind{GAVRL2} is called by \\Rind{GHPOT}.\n\\Sfunc{GAVRL3}{VALUE = GAVRL3(GAMAL3,BETAL3,X)}\n\\Rind{GAVRL3} calculates approximation of the cross-section for the \nphotoelectric effect from $L_{III}$ shell.\n{\\tt GAMAL3}, {\\tt BETAL3} are the Lorentz gamma and beta factors of the \nemitted photoelectron and $X = m_e/E_\\gamma$ where $m_e$ is the electron \nmass and $E_\\gamma$ is the incident radiation energy.\n{\\tt GAVRL3} is called by \\Rind{GPHOT}.\n\\Sfunc{GPHAK}{VALUE = GPHAK(BETAK)}\n\\Sfunc{GPHAL1}{VALUE = GPHAL1(BETAL1)}\n{\\tt GPHAK} and its entry point {\\tt GPHAL1} poll the cosine distribution \n(w.r.t. the incident photon direction) of the photoelectron emitted from \n$K$ or $L_{I}$ shell, respectively. They are called by \\Rind{GPHOT}.\n\\Sfunc{GPHAL2}{VALUE = GPHAL2(BETAL2)}\n\\Rind{GPHAL2} polls the cosine distribution (w.r.t. the incident photon\ndirection) of the photoelectron emitted from $L_{II}$ shell.\n\\Sfunc{GPHAL3}{VALUE = GPHAL3(BETAL3)}\n{\\tt GPHAL3} polls the cosine distribution (w.r.t. the incident photon\ndirection) of the photoelectron emitted from $L_{III}$ shell.\nIt is called by \\Rind{GPHOT}.\n\\Sfunc{GPHSGP}{VALUE = GPHSGP(EGAM)}\n\\Rind{GPHSGP} calculates the photoelectric effect total cross-section for\na particular atom of a mixture taking into account weights. It is called by \n\\Rind{GPHOT} for ${\\tt Z} \\leq 100$.\n \n\\section{Method}\n \nIf the energy of the radiation incident on an atom is $E_{\\gamma}$, then\nthe quanta can be absorbed if $E_{\\gamma} > E_{shell}$.\nThe photoelectron is emitted with total energy:\n\\begin{equation}\nE_{photoelectron} = E_{\\gamma}-E_{shell}+m_e.\n\\end{equation}\nIn the above equation it is assumed that the atom has infinite mass. One should\nnote that there exists a correction term (see \\cite{bib-BETHE} and\nreferences therein) which becomes more and more important with\nincreasing $E_{\\gamma}$ \\cite{bib-HALL} \\cite{bib-PRATT} \\cite{bib-PRATT1}.\n\n\\subsection{Probability of Interaction with an Atom}\nProbability of the interaction with an atom is calculated taking into\naccount partial cross-sections of atoms of a mixture\nor a compound.\n\\subsection{Probability of Interaction with a Shell}\nTo calculate the probability of the interaction with a particular shell we use\nthe jump ratios defined as:\n\\begin{equation}\nJ_{shell} = \\frac{\\sigma(E_{shell}+\\delta E)}{\\sigma(E_{shell}-\\delta E)}\n\\label{eq:jumprat}\n\\end{equation}\nwhere $\\delta E \\rightarrow 0$.\nIn addition we assume that the jump ratio is also valid away from the edges.\\\\\nFrom (\\ref{eq:jumprat}) it follows that the probability $p_{shell}$ \nto interact with a shell is:\n\\begin{equation}\np_{shell} = 1-\\frac{1}{J_{shell}}\n\\label{eq:probrat}\n\\end{equation}\nWe use the following parametrisation of the jump ratios for $K$ and\n$L_{I}$ shells\\cite{bib-VEIGELE}:\n\\begin{equation}\nJ_K = \\frac{125}{Z} + 3.5\n\\end{equation}\n\\begin{equation}\nJ_{L_{I}} = 1.2\n\\label{eq:jumpl1}\n\\end{equation}\nFor the $L_{II}$ and $L_{III}$ shells we adopt approximation of the formulae\ncalculated by Gavrila \\cite{bib-GAVRILA-L}:\n\\begin{eqnarray}\n\\sigma_{L_{II}} &=& \\gamma \\beta \\frac{m_e}{E_\\gamma}\n \\left\\{\n \\gamma^3-5\\gamma^2+24\\gamma-16\n -(\\gamma^2+3\\gamma-8)\\frac{\\log(\\gamma(1+\\beta))}{\\gamma\\beta}\n \\right\\}\n\\label{eq:sigmal2}\n\\end{eqnarray}\nand\n\\begin{eqnarray}\n\\sigma_{L_{III}} &=& \\gamma \\beta \\frac{m_e}{E_\\gamma}\n \\left\\{\n 4\\gamma^3-6\\gamma^2+5\\gamma+3\n -(\\gamma^2-3\\gamma+4)\\frac{\\log(\\gamma(1+\\beta))}{\\gamma\\beta}\n \\right\\}\n\\label{eq:sigmal3}\n\\end{eqnarray}\nwhere\\\\\n \n\\begin{tabular}[t]{l@{\\hspace{1cm}}p{.7\\textwidth}}\n$ \\gamma, \\beta $ & are the emitted photoelectron Lorentz gamma and beta\n factors;\\\\\n$ E_\\gamma $ & is the incident radiation energy; \\\\\n$ m_e $ & is the electron mass. \\\\\n\\end{tabular}\\\\\nBelow an example of the shell interaction probability calculations for \n$E_\\gamma > E_K$ is given.\\\\\nIf\n\\begin{eqnarray*}\n \\Sigma_{II,III} & = & \\sigma_{L_{II}}+\\sigma_{L_{III}} \\\\\n r_{L_{II}} & = & \\frac{\\sigma_{L_{II}}}{\\Sigma_{II,III}} \\\\\n r_{L_{III}} & = & \\frac{\\sigma_{L_{III}}}{\\Sigma_{II,III}} \n\\end{eqnarray*}\nthen from (\\ref{eq:probrat}) one can find that\n\\begin{eqnarray*}\n p_K & = & 1-\\frac{1}{J_K} \\\\\n p_{L_1} & = & (1-p_K)\\cdot (1 - \\frac{1}{J_{L_1}}) \\\\\n p_{L_{II}} & = & (1-p_K-p_{L_I})\\cdot r_{L_{II}} \\\\\n p_{L_{III}} & = & (1-p_K-p_{L_I})\\cdot r_{L_{III}} \n\\end{eqnarray*}\nAfter simple calculations one obtains the probability distribution function\nwhich is used to select the shell.\n\\subsection{Angular distributions of photoelectrons}\n \nThe angular distributions of photoelectrons should be calculated using the\npartial wave analysis for the outgoing electron. Since this method is very time\nconsuming we use approximations of the angular distributions calculated by\nF. von Sauter \\cite{bib-SAUTER1} \\cite{bib-SAUTER2} (K shell) and Gavrila\n\\cite{bib-GAVRILA-K} \\cite{bib-GAVRILA-L} \n(K and L shells). We use the cross-section\nwhich is correct only to zero order in $\\alpha Z$. This approximation foresees\nzero scattering amplitude in the direction of incident photon while\nexperimentally the cross-section at $0$ angle is non-vanishing \\cite{bib-NAGEL}.\nIf\n\\begin{eqnarray*}\n X &=& 1-\\beta\\cos\\Theta\n\\end{eqnarray*}\nthen for $K$ and $L_I$ shells we use:\n\\begin{eqnarray}\n \\frac{d\\sigma_{K,L_{I}}}{d(\\cos\\Theta)}\n &\\sim& \\frac{\\sin^2\\Theta}{X^4}\n \\left\\{1+ \\frac{1}{2}\\gamma(\\gamma-1)(\\gamma-2)\\right\\}\n\\label{eq:angkl}\n\\end{eqnarray}\n and for $L_{II}$ and $L_{III}$ shells we have:\n\\begin{eqnarray}\n \\frac{d\\sigma_{L_{II}}}{d(\\cos\\Theta)}\n &\\sim & \\frac{(\\gamma^2-1)^{\\frac{1}{2}}}{\\gamma^5(\\gamma-1)^5}\n \\left\\{ \\frac{\\gamma(3\\gamma+1)}{2 X^4}\n -\\frac{\\gamma^2(9\\gamma^2+30\\gamma-7)}{8 X^3} \\right. \\nonumber \\\\\n \\ & \\ & +\\frac{\\gamma^3(\\gamma^3+6\\gamma^2+11\\gamma-2)}{4 X^2}\n -\\frac{\\gamma^4(\\gamma-1)(\\gamma+7)}{8 X} \\\\\n \\ & \\ & +\\sin^2\\Theta\n \\left. \\left(\n \\frac{(\\gamma+1)}{X^5}\n -\\frac{\\gamma(\\gamma+1)}{X^4}\n -\\frac{\\gamma^2(3\\gamma+1)(\\gamma^2-1)}{X^3}\n \\right)\n \\right\\} \\nonumber\n\\label{eq:angl2}\n\\end{eqnarray}\n \n\\begin{eqnarray}\n \\frac{d\\sigma_{L_{III}}}{d(\\cos\\Theta)}\n &\\sim & \\frac{(\\gamma^2-1)^{\\frac{1}{2}}}{\\gamma^5(\\gamma-1)^5}\n \\left\\{ -\\frac{\\gamma(3\\gamma-1)}{2 X^4}\n +\\frac{\\gamma^2(3\\gamma^2-1)}{X^3} \\right. \\nonumber \\\\\n \\ & \\ & \\frac{\\gamma^3(\\gamma^3-3\\gamma^2+2\\gamma+1)}{X^3}\n -\\frac{\\gamma^4(\\gamma-2)(\\gamma-1)}{2 X} \\\\\n \\ & \\ & +\\sin^2\\Theta\n \\left. \\left(\n \\frac{(\\gamma+1)}{X^5}\n -\\frac{\\gamma(\\gamma+1)(3\\gamma-1)}{X^4}\n +\\frac{\\gamma^2(\\gamma^2-1)}{X^3}\n \\right)\n \\right\\} \\nonumber\n\\label{eq:angl3}\n\\end{eqnarray}\nThe azimuthal angle distribution is uniform.\n \n\\subsection{Final State}\n \nAfter the photoelectron emission the atom is left in excited state.\nThe excitation energy equal to the binding energy $E_i$ of the shell in which the interaction took place. Subsequently the atom emits a fluorescent photon\nor Auger or Coster-Kronig electron. The selection of radiative or\nnon-radiative transition is based on compilation by Krause \\cite{bib-KRAUSE}.\\\\\nThe Auger or Coster-Kronig transitions are represented by the most probable\nline for a given vacancy \\cite{bib-CULLEN}. The emitted electron energy $E_e$ is\n\\begin{equation}\n E_e = E_i-(E_j+E_k)\n\\label{eq:augere}\n\\end{equation}\nwhere\n$E_i, E_j, E_k$ are the subshell binding energies and $E_j > E_k$.\\\\\nIn case of fluorescence we use transition rates of Scofield \\cite{bib-SCOFIELD}.\nWe use only those transitions for which the occurrence probability is not less\nthan 1\\%. The fluorescent photon is emitted with energy $E_\\gamma$\n\\begin{equation}\nE_\\gamma = E_i-E_j\n\\label{eq:fluore}\n\\end{equation}\nfor transition between the subshells $i$ and $j$.\\\\\nIn addition to the above, to fulfill the energy conservation law,\nemission of an additional photon is simulated. For non-radiative transitions \nits energy is $E_k$ (see formula \\ref{eq:augere}). In case of fluorescent\ntransition this photon has energy $E_j$ (see equation \\ref{eq:fluore}). \nThe angular distribution of the emitted particle is isotropic.\n", "meta": {"hexsha": "b10f2b759e65eb226eb63ecebf39db5c15e62147", "size": 10262, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "geant/phys231.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": "geant/phys231.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": "geant/phys231.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.8122270742, "max_line_length": 154, "alphanum_fraction": 0.6399337361, "num_tokens": 3246, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6442251201477016, "lm_q2_score": 0.2909808600663598, "lm_q1q2_score": 0.1874571795369322}}
{"text": "%%\n%% Automatically generated file from DocOnce source\n%% (https://github.com/hplgit/doconce/)\n%%\n%%\n\n\n%-------------------- begin preamble ----------------------\n\n\\documentclass[%\noneside, % oneside: electronic viewing, twoside: printing\nfinal, % draft: marks overfull hboxes, figures with paths\n10pt]{article}\n\n\\listfiles % print all files needed to compile this document\n\n\\usepackage{relsize,makeidx,color,setspace,amsmath,amsfonts,amssymb}\n\\usepackage[table]{xcolor}\n\\usepackage{bm,ltablex,microtype}\n\n\\usepackage[pdftex]{graphicx}\n\n\\usepackage[T1]{fontenc}\n%\\usepackage[latin1]{inputenc}\n\\usepackage{ucs}\n\\usepackage[utf8x]{inputenc}\n\n\\usepackage{lmodern} % Latin Modern fonts derived from Computer Modern\n\n% Hyperlinks in PDF:\n\\definecolor{linkcolor}{rgb}{0,0,0.4}\n\\usepackage{hyperref}\n\\hypersetup{\n breaklinks=true,\n colorlinks=true,\n linkcolor=linkcolor,\n urlcolor=linkcolor,\n citecolor=black,\n filecolor=black,\n %filecolor=blue,\n pdfmenubar=true,\n pdftoolbar=true,\n bookmarksdepth=3 % Uncomment (and tweak) for PDF bookmarks with more levels than the TOC\n }\n%\\hyperbaseurl{} % hyperlinks are relative to this root\n\n\\setcounter{tocdepth}{2} % levels in table of contents\n\n% --- fancyhdr package for fancy headers ---\n\\usepackage{fancyhdr}\n\\fancyhf{} % sets both header and footer to nothing\n\\renewcommand{\\headrulewidth}{0pt}\n\\fancyfoot[LE,RO]{\\thepage}\n% Ensure copyright on titlepage (article style) and chapter pages (book style)\n\\fancypagestyle{plain}{\n \\fancyhf{}\n \\fancyfoot[C]{{\\footnotesize \\copyright\\ 1999-2019, \"Computational Physics I FYS3150/FYS4150\":\"http://www.uio.no/studier/emner/matnat/fys/FYS3150/index-eng.html\". Released under CC Attribution-NonCommercial 4.0 license}}\n% \\renewcommand{\\footrulewidth}{0mm}\n \\renewcommand{\\headrulewidth}{0mm}\n}\n% Ensure copyright on titlepages with \\thispagestyle{empty}\n\\fancypagestyle{empty}{\n \\fancyhf{}\n \\fancyfoot[C]{{\\footnotesize \\copyright\\ 1999-2019, \"Computational Physics I FYS3150/FYS4150\":\"http://www.uio.no/studier/emner/matnat/fys/FYS3150/index-eng.html\". Released under CC Attribution-NonCommercial 4.0 license}}\n \\renewcommand{\\footrulewidth}{0mm}\n \\renewcommand{\\headrulewidth}{0mm}\n}\n\n\\pagestyle{fancy}\n\n\n% prevent orhpans and widows\n\\clubpenalty = 10000\n\\widowpenalty = 10000\n\n% --- end of standard preamble for documents ---\n\n\n% insert custom LaTeX commands...\n\n\\raggedbottom\n\\makeindex\n\\usepackage[totoc]{idxlayout} % for index in the toc\n\\usepackage[nottoc]{tocbibind} % for references/bibliography in the toc\n\n%-------------------- end preamble ----------------------\n\n\\begin{document}\n\n% matching end for #ifdef PREAMBLE\n\n\\newcommand{\\exercisesection}[1]{\\subsection*{#1}}\n\n\n% ------------------- main content ----------------------\n\n\n\n% ----------------- title -------------------------\n\n\\thispagestyle{empty}\n\n\\begin{center}\n{\\LARGE\\bf\n\\begin{spacing}{1.25}\nProject 2, deadline September 30\n\\end{spacing}\n}\n\\end{center}\n\n% ----------------- author(s) -------------------------\n\n\\begin{center}\n{\\bf \\href{{http://www.uio.no/studier/emner/matnat/fys/FYS3150/index-eng.html}}{Computational Physics I FYS3150/FYS4150}}\n\\end{center}\n\n \\begin{center}\n% List of all institutions:\n\\centerline{{\\small Department of Physics, University of Oslo, Norway}}\n\\end{center}\n \n% ----------------- end author(s) -------------------------\n\n% --- begin date ---\n\\begin{center}\nSep 18, 2019\n\\end{center}\n% --- end date ---\n\n\\vspace{1cm}\n\n\n\\subsection*{Eigenvalue problems, from the equations of a buckling beam to Schroedinger's equation for two electrons in a three-dimensional harmonic oscillator well}\n\n\\paragraph{Introduction.}\nThe aim of this project is to develop your own code for solving\neigenvalue problems. The matrix to diagonalize is the same as the one\nwe encountered in project one, a so-called tridiagonal Toeplitz\nmatrix. This matrix has analytical eigenpairs (eigenvalues and\neigenvectors) and gives us an excellent testing ground for our\nalgorithms. In this project we will develop an eigenvalue solver based\non Jacobi's method. The project will also introduce you to units tests\nand we will compare our results against other eigenvalue solvers (from\nLAPACK and/or numpy).\n\nThis project aims also at introducing to you the concept of \\href{{http://www.springer.com/us/book/9783319327259}}{scaling\nof equations}. This\nmeans often either making various variables dimensionless or\nintroducing units which are more convenient.\n\nWe will start with the two-point boundary value problem of a buckling\nbeam or a spring fastened at both ends. This is one of the problems\nwhich has analytical solutions. Thereafter, by simply adding a new\nvariable along the diagonal elements, we can study quantum mechanical\nproblems. In particular, we will study the harmonic oscillator problem\nin three dimensions, with one or two electrons. For the latter case we\ncan study the role of the repulsive Coulomb interaction and extract\ninteresting physics results. For selected frequencies, this\ninteracting two-electron problem exhibits analytical solutions, one of the few cases of an interacting system where wecan find analytical solutions. See\n\\href{{http://prola.aps.org/abstract/PRA/v48/i5/p3561_1}}{M. Taut, Phys. Rev. A 48, 3561\n(1993)} for the derivation of analytical expressions for the eigenpairs..\n\nElectrons confined in small areas in semiconductors, so-called quantum\ndots, form a hot research area in modern solid-state physics, with\napplications spanning from such diverse fields as quantum\nnano-medicine to the contruction of quantum gates. \nThe article on quantum computing with quantum dots by \\href{{http://journals.aps.org/pra/abstract/10.1103/PhysRevA.57.120}}{Loss and DiVincenzo} is an excellent read for those interested in this exciting topic.\n\n\n\n\\paragraph{The buckling beam problem, a classical wave function problem in one dimension.}\nWe start with the following differential equation, namely \n\\[\n\\gamma \\frac{d^2 u(x)}{dx^2} = -F u(x),\n\\]\nwhere $u(x)$ is the vertical displacement of the beam in the $y$ direction. \nThe beam has length $L$, $x\\in [0,L]$ and $F$ is a force applied at $(L,0)$ in the direction towards the origin. \nThe parameter $\\gamma$ is a constant defined by properties like the rigidity of the beam. \nWe apply again so-called Dirichlet boundary conditions and set $u(0)=u(L)=0$.\n\nIn this specific case two of the parameters $\\gamma$, $F$ and $L$ are known. As an example, assume we know $F$ and $L$. Then the eigenvalue problem we set up below will allow us to find $\\gamma$. \n\nWe define a dimensional variable\n\\[\n \\rho = \\frac{x}{L}, \n\\]\nmeaning that we have $\\rho \\in [0,1]$. By reordering the equation as \n\\[\n \\frac{d^2 u(\\rho)}{d\\rho^2} = -\\frac{FL^2}{\\gamma} u(\\rho)=-\\lambda u(\\rho),\n\\]\nwith $\\lambda= FL^2/\\gamma$ we have an equation that when discretized, becomes an eigenvalue problem.\nWe use the same \nexpression for the second derivative of a function $u$ as we did in project 1, namely\n\\begin{equation}\n u''=\\frac{u(\\rho+h) -2u(\\rho) +u(\\rho-h)}{h^2} +O(h^2),\n \\label{eq:diffoperation}\n\\end{equation}\nwhere $h$ is our step.\nNext we define minimum and maximum values for the variable $\\rho$,\n$\\rho_{\\mathrm{min}}=0$ and $\\rho_{\\mathrm{max}}=1$, respectively.\nWith a given number of mesh points, $N$, we \ndefine the step length $h$ as, with $\\rho_{\\mathrm{min}}=\\rho_0$ and $\\rho_{\\mathrm{max}}=\\rho_N$,\n\\begin{equation*}\n h=\\frac{\\rho_N-\\rho_0 }{N}.\n\\end{equation*}\nThe value of $\\rho$ at a point $i$ is then \n\\[\n \\rho_i= \\rho_0 + ih \\hspace{1cm} i=1,2,\\dots , N.\n\\]\nWe can rewrite the differential equation for a value $\\rho_i$ as\n\\[\n-\\frac{u(\\rho_i+h) -2u(\\rho_i) +u(\\rho_i-h)}{h^2} = \\lambda u(\\rho_i),\n\\]\nor in a more compact way as\n\\[\n-\\frac{u_{i+1} -2u_i +u_{i-1} }{h^2} = \\lambda u_i.\n\\]\nFollowing our approach from project 1, we can rewrite this equation in a more a general form, but now \nas an eigenvalue problem, that is\n\\begin{equation}\n \\begin{bmatrix} d& a & 0 & 0 & \\dots &0 & 0 \\\\\n a & d & a & 0 & \\dots &0 &0 \\\\\n 0 & a & d & a &0 &\\dots & 0\\\\\n \\dots & \\dots & \\dots & \\dots &\\dots &\\dots & \\dots\\\\\n 0 & \\dots & \\dots & \\dots &a &d & a\\\\\n 0 & \\dots & \\dots & \\dots &\\dots &a & d\\end{bmatrix} \n \\begin{bmatrix} u_1 \\\\ u_2 \\\\ u_3 \\\\ \\dots \\\\ u_{N-2} \\\\ u_{N-1}\\end{bmatrix} = \\lambda \\begin{bmatrix} u_1 \\\\ u_2 \\\\ u_3 \\\\ \\dots \\\\ u_{N-2} \\\\ u_{N-1}\\end{bmatrix} . \n\\label{eq:matrixse} \n\\end{equation}\nAs in project 1, we have not included the endpoints $u_0$ and $u_N$. \nWe have defined $d=2/h^2$ and the non-diagonal ones as $a=-1/h^2$. This eigenvalue problem has analytical eigenpairs, with eigenvalues given as \n\\[\n\\lambda_j = d+2a\\cos{(\\frac{j\\pi}{N+1})} \\hspace{0.1cm} j=1,2,\\dots N.\n\\]\n\n\n\\paragraph{Project 2 a): Mathematical intermezzo.}\nA unitary transformation preserves the orthogonality of the obtained eigenvectors. To see this consider first a basis of vectors $\\mathbf{v}_i$,\n\\[\n\\mathbf{v}_i = \\begin{bmatrix} v_{i1} \\\\ \\dots \\\\ \\dots \\\\v_{in} \\end{bmatrix}\n\\]\nWe assume that the basis is orthogonal, that is \n\\[\n\\mathbf{v}_j^T\\mathbf{v}_i = \\delta_{ij}.\n\\]\nShow that an orthogonal or unitary transformation\n\\[\n\\mathbf{w}_i=\\mathbf{U}\\mathbf{v}_i,\n\\]\npreserves the dot product and orthogonality. \n\n\\paragraph{Project 2 b): Setting up a code for tridiagonal Toeplitz matrix.}\nYour task now is to write a function which implements Jacobi's rotation algorithm (see Lecture notes chapter 7) in order to solve Eq. (\\ref{eq:matrixse}). \nHowever, the first simple check is to set up the matrix to diagonalize for a given $N$ and use either armadillo's or numpy's functions for diagonalizing a matrix. You can then check that you obtain the analytical eigenvalues. \n\nFor Jacobi's method,\nwe define the quantities $\\tan\\theta = t= s/c$, with $s=\\sin\\theta$ and $c=\\cos\\theta$ and\n\\begin{equation*}\\cot 2\\theta=\\tau = \\frac{a_{ll}-a_{kk}}{2a_{kl}}.\n\\end{equation*}\nWe can then define the angle $\\theta$ so that the non-diagonal matrix elements of the transformed matrix \n$a_{kl}$ become non-zero and\nwe obtain the quadratic equation (using $\\cot 2\\theta=1/2(\\cot \\theta-\\tan\\theta)$\n\n\\begin{equation*}\nt^2+2\\tau t-1= 0,\n\\end{equation*}\nresulting in\n\n\\begin{equation*}\n t = -\\tau \\pm \\sqrt{1+\\tau^2},\n\\end{equation*}\nand $c$ and $s$ are easily obtained via\n\n\\begin{equation*}\n c = \\frac{1}{\\sqrt{1+t^2}},\n\\end{equation*}\nand $s=tc$. \n\n\nHow many similarity transformations are needed before you reach a \nresult where all non-diagonal matrix elements are essentially zero?\nTry to estimate the number of transformations and extract a behavior as function\nof the dimensionality of the matrix. Compare your results with the analytical ones.\n\nYou can check your results against the Armadillo function for solving \neigenvalue problems. The armadillo function \\emph{eigsys} can be used to find eigenvalues and eigenvectors.\nA Python program which solves this part of the project is available under the \\href{{http://compphysics.github.io/ComputationalPhysics/doc/pub/projectwriting/html/projectwriting.html}}{project writing slides}. \n\n\n\nComment your results (here you could for example compute the time needed for \nboth algorithms for a given dimensionality of the matrix). \n\n\n\\paragraph{Project 2 c): Implementing tests in your code.}\nIn this project (and later ones as well) we will implement so-called\n\\textbf{unit} tests. Our unit tests are mainly meant to test mathematical\nproperties of our algorithm. During the development phase of a program\nit is useful to devise tests that your program should pass. One of\nthese is to make sure that for a given simple test matrix (say a\n$5\\times 5$ matrix) our algorithm for searching for the largest\nnon-diagonal element always returns the correct answer. Furthermore,\nfor a known simple matrix, irrespective of changes made, we should\nalways get the same and correct eigenvalues. Another test is to make\nsure that the orthogonality shown in exercise (a) is preserved. Try to\nfigure out other tests your code should pass, based either on the\nmathematical properties of the algorithms or more program specific\ntests. Implement at least two unit tests in this project.\n\n\n\n\n\n\n\\paragraph{Extending our machinery to quantum mechanics.}\nHere we will assume that these electrons move in a three-dimensional harmonic\noscillator potential (they are confined by for example quadrupole fields)\nand repel each other via the static Coulomb interaction. \nWe assume spherical symmetry. You don't need to think of quantum mechanics when solving this project, look at it as another diagonalization problem. \n\nWe are first interested in the solution of the radial part of Schroedinger's equation for one electron. This equation reads\n\n\\begin{equation*}\n -\\frac{\\hbar^2}{2 m} \\left ( \\frac{1}{r^2} \\frac{d}{dr} r^2\n \\frac{d}{dr} - \\frac{l (l + 1)}{r^2} \\right )R(r) \n + V(r) R(r) = E R(r).\n\\end{equation*}\nIn our case $V(r)$ is the harmonic oscillator potential $(1/2)kr^2$ with\n$k=m\\omega^2$ and $E$ is\nthe energy of the harmonic oscillator in three dimensions.\nThe oscillator frequency is $\\omega$ and the energies are\n\n\\begin{equation*}\nE_{nl}= \\hbar \\omega \\left(2n+l+\\frac{3}{2}\\right),\n\\end{equation*}\nwith $n=0,1,2,\\dots$ and $l=0,1,2,\\dots$.\n\nSince we have made a transformation to spherical coordinates it means that \n$r\\in [0,\\infty)$. \nThe quantum number\n$l$ is the orbital momentum of the electron. \n% \nThen we substitute $R(r) = (1/r) u(r)$ and obtain\n% \n\n\\begin{equation*}\n -\\frac{\\hbar^2}{2 m} \\frac{d^2}{dr^2} u(r) \n + \\left ( V(r) + \\frac{l (l + 1)}{r^2}\\frac{\\hbar^2}{2 m}\n \\right ) u(r) = E u(r) .\n\\end{equation*}\n% \nThe boundary conditions are $u(0)=0$ and $u(\\infty)=0$.\n\nWe introduce a dimensionless variable $\\rho = (1/\\alpha) r$\nwhere $\\alpha$ is a constant with dimension length and get\n% \n\n\\begin{equation*}\n -\\frac{\\hbar^2}{2 m \\alpha^2} \\frac{d^2}{d\\rho^2} u(\\rho) \n + \\left ( V(\\rho) + \\frac{l (l + 1)}{\\rho^2}\n \\frac{\\hbar^2}{2 m\\alpha^2} \\right ) u(\\rho) = E u(\\rho) .\n\\end{equation*}\n% \nWe will set in this project $l=0$.\nInserting $V(\\rho) = (1/2) k \\alpha^2\\rho^2$ we end up with\n\n\\begin{equation*}\n -\\frac{\\hbar^2}{2 m \\alpha^2} \\frac{d^2}{d\\rho^2} u(\\rho) \n + \\frac{k}{2} \\alpha^2\\rho^2u(\\rho) = E u(\\rho) .\n\\end{equation*}\nWe multiply thereafter with $2m\\alpha^2/\\hbar^2$ on both sides and obtain\n\n\\begin{equation*}\n -\\frac{d^2}{d\\rho^2} u(\\rho) \n + \\frac{mk}{\\hbar^2} \\alpha^4\\rho^2u(\\rho) = \\frac{2m\\alpha^2}{\\hbar^2}E u(\\rho) .\n\\end{equation*}\nThe constant $\\alpha$ can now be fixed\nso that\n\n\\begin{equation*}\n\\frac{mk}{\\hbar^2} \\alpha^4 = 1,\n\\end{equation*}\nor\n\n\\begin{equation*}\n\\alpha = \\left(\\frac{\\hbar^2}{mk}\\right)^{1/4}.\n\\end{equation*}\nDefining\n\n\\begin{equation*}\n\\lambda = \\frac{2m\\alpha^2}{\\hbar^2}E,\n\\end{equation*}\nwe can rewrite Schroedinger's equation as\n\n\\begin{equation*}\n -\\frac{d^2}{d\\rho^2} u(\\rho) + \\rho^2u(\\rho) = \\lambda u(\\rho) .\n\\end{equation*}\nThis is the first equation to solve numerically. In three dimensions \nthe eigenvalues for $l=0$ are \n$\\lambda_0=3,\\lambda_1=7,\\lambda_2=11,\\dots .$\n\nWe define minimum and maximum values for the variable $\\rho$,\n$\\rho_{\\mathrm{min}}=0$ and $\\rho_{\\mathrm{max}}$, respectively.\nYou need to check your results for the energies against different values\n$\\rho_{\\mathrm{max}}$, since we cannot set\n$\\rho_{\\mathrm{max}}=\\infty$. \n\nWith a given number of mesh points, $N$, we \ndefine the step length $h$ as, with $\\rho_{\\mathrm{min}}=\\rho_0$ and $\\rho_{\\mathrm{max}}=\\rho_N$,\n\n\\begin{equation*}\n h=\\frac{\\rho_N-\\rho_0 }{N}.\n\\end{equation*}\nThe value of $\\rho$ at a point $i$ is then \n\\[\n \\rho_i= \\rho_0 + ih \\hspace{1cm} i=1,2,\\dots , N.\n\\]\nWe can rewrite the Schroedinger equation for a value $\\rho_i$ as\n\n\\[\n-\\frac{u(\\rho_i+h) -2u(\\rho_i) +u(\\rho_i-h)}{h^2}+\\rho_i^2u(\\rho_i) = \\lambda u(\\rho_i),\n\\]\nor in a more compact way\n\n\\[\n-\\frac{u_{i+1} -2u_i +u_{i-1}}{h^2}+\\rho_i^2u_i=-\\frac{u_{i+1} -2u_i +u_{i-1} }{h^2}+V_iu_i = \\lambda u_i,\n\\]\nwhere $V_i=\\rho_i^2$ is the harmonic oscillator potential.\n\nWe define first the diagonal matrix element\n\\begin{equation*}\n d_i=\\frac{2}{h^2}+V_i,\n\\end{equation*}\nand the non-diagonal matrix element\n\\begin{equation*}\n e_i=-\\frac{1}{h^2}.\n\\end{equation*}\nIn this case the non-diagonal matrix elements are given by a mere constant.\n\\emph{All non-diagonal matrix elements are equal}.\nWith these definitions the Schroedinger equation takes the following form\n\n\\begin{equation*}\nd_iu_i+e_{i}u_{i-1}+e_{i}u_{i+1} = \\lambda u_i,\n\\end{equation*}\nwhere $u_i$ is unknown. We can write the \nlatter equation as a matrix eigenvalue problem\n\\begin{equation}\n \\begin{bmatrix}d_1 & e_1 & 0 & 0 & \\dots &0 & 0 \\\\\n e_1 & d_2 & e_2 & 0 & \\dots &0 &0 \\\\\n 0 & e_2 & d_3 & e_3 &0 &\\dots & 0\\\\\n \\dots & \\dots & \\dots & \\dots &\\dots &\\dots & \\dots\\\\\n 0 & \\dots & \\dots & \\dots &\\dots e_{N-3} &d_{N-2} & e_{N-2}\\\\\n 0 & \\dots & \\dots & \\dots &\\dots &e_{N-2} & d_{N-1}\n \\end{bmatrix} \\begin{bmatrix} u_{1} \\\\\n u_{2} \\\\\n \\dots\\\\ \\dots\\\\ \\dots\\\\\n u_{N-1}\n \\end{bmatrix}=\\lambda \\begin{bmatrix} u_{1} \\\\\n u_{2} \\\\\n \\dots\\\\ \\dots\\\\ \\dots\\\\\n u_{N-1}\n \\end{bmatrix}. \n \\label{eq:sematrix}\n\\end{equation}\n\nNote here that we have not included the endpoints since we assume that they are knowm (as we did in project 1). The matrix is also symmetric in this case.\n\n\\paragraph{Project 2 d): Quantum dots in three dimensions, one electron.}\nAdd the harmonic oscillator potential to your tridiagonal Toeplitz matrix from 2a-2c and diagonalize the matrix.\nStudy the results as functions of the number of integration points $N$ and your approximation to $\\rho_{\\mathrm{max}}$. \nThe analytical results with our scaling for the one-electron energies are $\\lambda=3,7,11,15,\\dots$. How many integration points do you need in order to reproduce the analytical results with say four leading digits after the decimal point?\n\nYou can reuse the code you wrote for part (b), \nbut you need to add the potential $\\rho^2$ to the diagonal elements. \n\n\n\n\\paragraph{Project 2 e): Quantum dots in three dimensions, two electrons.}\nNote: if you are not interested in the explicit quantum physics case here, you can replace this part with either 2g or 2h below. The latter ones are optional exercises if you do this.\n\nWe will now study two electrons in a harmonic oscillator well which\nalso interact via a repulsive Coulomb interaction.\nLet us start with the single-electron equation written as\n\n\\begin{equation*}\n -\\frac{\\hbar^2}{2 m} \\frac{d^2}{dr^2} u(r) \n + \\frac{1}{2}k r^2u(r) = E^{(1)} u(r),\n\\end{equation*}\nwhere $E^{(1)}$ stands for the energy with one electron only.\nFor two electrons with no repulsive Coulomb interaction, we have the following \nSchroedinger equation\n\n\\begin{equation*}\n\\left( -\\frac{\\hbar^2}{2 m} \\frac{d^2}{dr_1^2} -\\frac{\\hbar^2}{2 m} \\frac{d^2}{dr_2^2}+ \\frac{1}{2}k r_1^2+ \\frac{1}{2}k r_2^2\\right)u(r_1,r_2) = E^{(2)} u(r_1,r_2) .\n\\end{equation*}\n\n\nNote that we deal with a two-electron wave function $u(r_1,r_2)$ and \ntwo-electron energy $E^{(2)}$.\n\nWith no interaction this can be written out as the product of two\nsingle-electron wave functions, that is we have a solution on closed form.\n\nWe introduce the relative coordinate $\\mathbf{r} = \\mathbf{r}_1-\\mathbf{r}_2$\nand the center-of-mass coordinate $\\mathbf{R} = 1/2(\\mathbf{r}_1+\\mathbf{r}_2)$.\nWith these new coordinates, the radial Schroedinger equation reads\n\n\\begin{equation*}\n\\left( -\\frac{\\hbar^2}{m} \\frac{d^2}{dr^2} -\\frac{\\hbar^2}{4 m} \\frac{d^2}{dR^2}+ \\frac{1}{4} k r^2+ kR^2\\right)u(r,R) = E^{(2)} u(r,R).\n\\end{equation*}\n\nThe equations for $r$ and $R$ can be separated via the ansatz for the \nwave function $u(r,R) = \\psi(r)\\phi(R)$ and the energy is given by the sum\nof the relative energy $E_r$ and the center-of-mass energy $E_R$, that\nis\n\n\\begin{equation*}\nE^{(2)}=E_r+E_R.\n\\end{equation*}\n\nWe add then the repulsive Coulomb interaction between two electrons,\nnamely a term\n\n\\begin{equation*}\nV(r_1,r_2) = \\frac{\\beta e^2}{|\\mathbf{r}_1-\\mathbf{r}_2|}=\\frac{\\beta e^2}{r},\n\\end{equation*}\nwith $\\beta e^2=1.44$ eVnm.\n\nAdding this term, the $r$-dependent Schroedinger equation becomes\n\n\\begin{equation*}\n\\left( -\\frac{\\hbar^2}{m} \\frac{d^2}{dr^2}+ \\frac{1}{4}k r^2+\\frac{\\beta e^2}{r}\\right)\\psi(r) = E_r \\psi(r).\n\\end{equation*}\nThis equation is similar to the one we had previously in (b) and we introduce\nagain a dimensionless variable $\\rho = r/\\alpha$. Repeating the same\nsteps as above, we arrive at\n\n\\begin{equation*}\n -\\frac{d^2}{d\\rho^2} \\psi(\\rho) \n + \\frac{1}{4}\\frac{mk}{\\hbar^2} \\alpha^4\\rho^2\\psi(\\rho)+\\frac{m\\alpha \\beta e^2}{\\rho\\hbar^2}\\psi(\\rho) = \n\\frac{m\\alpha^2}{\\hbar^2}E_r \\psi(\\rho) .\n\\end{equation*}\nWe want to manipulate this equation further to make it as similar to that in (a)\nas possible. We define a new 'frequency'\n\n\\begin{equation*}\n\\omega_r^2=\\frac{1}{4}\\frac{mk}{\\hbar^2} \\alpha^4,\n\\end{equation*}\nand fix the constant $\\alpha$ by requiring\n\n\\begin{equation*}\n\\frac{m\\alpha \\beta e^2}{\\hbar^2}=1\n\\end{equation*}\nor\n\n\\begin{equation*}\n\\alpha = \\frac{\\hbar^2}{m\\beta e^2}.\n\\end{equation*}\nDefining\n\n\\begin{equation*}\n\\lambda = \\frac{m\\alpha^2}{\\hbar^2}E,\n\\end{equation*}\nwe can rewrite Schroedinger's equation as\n\n\\begin{equation*}\n -\\frac{d^2}{d\\rho^2} \\psi(\\rho) + \\omega_r^2\\rho^2\\psi(\\rho) +\\frac{1}{\\rho} = \\lambda \\psi(\\rho).\n\\end{equation*}\nWe treat $\\omega_r$ as a parameter which reflects the strength of the oscillator potential.\n\nHere we will study the cases $\\omega_r = 0.01$, $\\omega_r = 0.5$, $\\omega_r =1$,\nand $\\omega_r = 5$ \nfor the ground state only, that is the lowest-lying state.\n\n\nWith no repulsive Coulomb interaction \nyou should get a result which corresponds to \nthe relative energy of a non-interacting system. \nMake sure your results are \nstable as functions of $\\rho_{\\mathrm{max}}$ and the number of steps.\n\nWe are only interested in the ground state with $l=0$. We omit the \ncenter-of-mass energy.\n\nYou can reuse the code you wrote for part (b), \nbut you need to add the potential $\\omega_r^2\\rho^2+1/\\rho$ to the diagonal elements. \n\nComment the results for the lowest state (ground state) as function of\nvarying strengths of $\\omega_r$. \n\n\nFor specific oscillator frequencies, the above equation has answers in an analytical form,\nsee the article by \\href{{http://prola.aps.org/abstract/PRA/v48/i5/p3561_1}}{M. Taut, Phys. Rev. A 48, 3561 (1993)}.\n\n\n\\paragraph{Project 2 f): First optional exercise: Quantum physics analysis of the results.}\nThis exercise is a continuation of the previous and adds more quantum physics to the analysis. \nIn this exercise we want to plot the wave function \nfor two electrons as functions of the relative coordinate $r$ and different\nvalues of $\\omega_r$. With no Coulomb interaction you should have a result which corresponds to the non-interacting case. \nPlot either the function itself or the probability distribution (the function squared) with and without the repulsion between the two electrons.\nVarying $\\omega_r$, the shape of the wave function\nwill change. \n\nWe are only interested in the wave function for the ground state with $l=0$ and\nomit again the center-of-mass motion.\n\nThe eigenvectors are normalized. \nPlot then the normalized wave functions for different values of $\\omega_r$ and comment the results.\n\n\\paragraph{Project 2 g): Second optional challenge: Smarter way of finding the eigenvalues.}\nThis exercise is also optional and is an algorithmic challenge. Your matrix is already tridiagonal. \nCan you devise a more efficient way to find the eigenvalues and eigenvectors instead of the brute force application of Jacobi's method? \nHint: Use the bisection method discussed in for example \\href{{http://www.maths.ed.ac.uk/~aar/papers/bamawi.pdf}}{Barth, Martin and Wilkinson, Numerische Mathematik 9, 386 (1967)}.\n\n\n\n\\paragraph{Project 2 h): Third optional challenge: Implementing Lanczos' algorithm.}\nThis exercise is optional and is meant more as a challenge for those of you with an interest in other algorithms for solving eigenvalue problems. \nImplement the iterative Lanczos' algorithm discussed in the lecture notes and compute the lowest eigenvalues \nas done in exercise (c) or (d) above. Compare your results and discuss faults and merits of the iterative method versus\ndirect methods like Jacobi's method. \n\n\n\n\n\n\n\\subsection*{Introduction to numerical projects}\n\nHere follows a brief recipe and recommendation on how to write a report for each\nproject.\n\n\\begin{itemize}\n \\item Give a short description of the nature of the problem and the eventual numerical methods you have used.\n\n \\item Describe the algorithm you have used and/or developed. Here you may find it convenient to use pseudocoding. In many cases you can describe the algorithm in the program itself.\n\n \\item Include the source code of your program. Comment your program properly.\n\n \\item If possible, try to find analytic solutions, or known limits in order to test your program when developing the code.\n\n \\item Include your results either in figure form or in a table. Remember to label your results. All tables and figures should have relevant captions and labels on the axes.\n\n \\item Try to evaluate the reliabilty and numerical stability/precision of your results. If possible, include a qualitative and/or quantitative discussion of the numerical stability, eventual loss of precision etc.\n\n \\item Try to give an interpretation of you results in your answers to the problems.\n\n \\item Critique: if possible include your comments and reflections about the exercise, whether you felt you learnt something, ideas for improvements and other thoughts you've made when solving the exercise. We wish to keep this course at the interactive level and your comments can help us improve it.\n\n \\item Try to establish a practice where you log your work at the computerlab. You may find such a logbook very handy at later stages in your work, especially when you don't properly remember what a previous test version of your program did. Here you could also record the time spent on solving the exercise, various algorithms you may have tested or other topics which you feel worthy of mentioning.\n\\end{itemize}\n\n\\noindent\n\\subsection*{Format for electronic delivery of report and programs}\n\nThe preferred format for the report is a PDF file. You can also use DOC or postscript formats or as an ipython notebook file. As programming language we prefer that you choose between C/C++, Fortran2008 or Python. The following prescription should be followed when preparing the report:\n\n\\begin{itemize}\n \\item Use Devilry to hand in your projects, log in at \\href{{http://devilry.ifi.uio.no}}{\\nolinkurl{http://devilry.ifi.uio.no}} with your normal UiO username and password and choose either 'fys3150' or 'fys4150'. There you can load up the files within the deadline.\n\n \\item Upload \\textbf{only} the report file! For the source code file(s) you have developed please provide us with your link to your github domain. The report file should include all of your discussions and a list of the codes you have developed. Do not include library files which are available at the course homepage, unless you have made specific changes to them.\n\n \\item In your git repository, please include a folder which contains selected results. These can be in the form of output from your code for a selected set of runs and input parameters.\n\n \\item In this and all later projects, you should include tests (for example unit tests) of your code(s).\n\n \\item Comments from us on your projects, approval or not, corrections to be made etc can be found under your Devilry domain and are only visible to you and the teachers of the course.\n\\end{itemize}\n\n\\noindent\nFinally, \nwe encourage you to work two and two together. Optimal working groups consist of \n2-3 students. You can then hand in a common report. \n\n\n\n% ------------------- end of main content ---------------\n\n\\end{document}\n\n", "meta": {"hexsha": "170c820372eccc530bfdd7b3a8eaaa564e11aac9", "size": 28871, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/Projects/2019/Project2/pdf/Project2.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/2019/Project2/pdf/Project2.tex", "max_issues_repo_name": "solisius/ComputationalPhysics", "max_issues_repo_head_hexsha": "94d32d177881695d443eea34af3410e886b8cb9a", "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/2019/Project2/pdf/Project2.tex", "max_forks_repo_name": "solisius/ComputationalPhysics", "max_forks_repo_head_hexsha": "94d32d177881695d443eea34af3410e886b8cb9a", "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": 42.3328445748, "max_line_length": 405, "alphanum_fraction": 0.6946070451, "num_tokens": 8393, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.43782349911420193, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.1866536113970813}}
{"text": "\\documentclass[sttt]{svjour}\n\n% Packages LaTeX\n\\input{Packages}\n\n\\usepackage{algorithm}\n\\usepackage[noend]{algorithmic}\n\\usepackage{listings}\n\\usepackage{upgreek}\n\\usepackage{enumerate}\n\n\\usepackage{fancyvrb}\n% \\usepackage{wrapfig}\n\n\\newcommand{\\sopra}{}\n\n% Definizioni di Macro ed ambienti\n\\input{DefinizioniFrancesco.tex}\n\n%\\setlength{\\textheight}{8.6in}\n\n\\title{SubPolyhedra: A family of numerical abstract domains for the (more) scalable inference of linear inequalities} \n\\author{Vincent Laviron \\inst{1} \\and Francesco Logozzo \\inst{2}}\n\n\\institute{\n \\'Ecole Normale Sup\\'erieure, 45, rue d'Ulm, Paris (France) \\\\\n\\email{Vincent.Laviron@ens.fr}\n\\and\nMicrosoft Research, Redmond, WA (USA) \\\\\n\\email{logozzo@microsoft.com}\n}\n\n\n\\begin{document}\n\n\\pagestyle{plain}\n\n\\maketitle\n\n\\begin{abstract}\nWe introduce Subpolyhedra (\\SubPoly) a new family of numerical abstract domains to infer and propagate linear inequalities.\nThe key insight is that the reduced product of linear equalities and intervals produces powerful yet scalable analyses.\nAbstract domains in \\Subpoly\\ are as expressive as Polyhedra, but they drop some of the deductive power to achieve scalability.\nThe cost/precision ratio of abstract domains in the \\Subpoly\\ family can be fined tuned according to: (i) the precision one wants to retain at join pointsl; and (ii) the algorithm used to infer tight bounds on intervals. \n\nWe implemented \\Subpoly\\ on the top of \\Clousot, a generic abstract interpreter for \\NET.\n\\Clousot\\ with \\Subpoly\\ analyzes very large and complex code bases in few minutes. \n\\Subpoly\\ can efficiently capture linear inequalities among hundreds of variables, a result well-beyond state-of-the-art implementations of Polyhedra.\n\\end{abstract}\n\n\\newcommand\\codefamily\\sffamily\n\\lstset{language={[Sharp]C},mathescape=false,flexiblecolumns=true,morekeywords={assume},basicstyle=\\codefamily\\small,frame=lines,moredelim=[is][\\itshape]{@}{@},captionpos=b,numberstyle=\\tiny,stepnumber=1,numbersep=2pt}\n\n\\algsetup{indent=2em}\n\n\\section{Introduction}\n\nThe goal of an abstract interpretation-based static analyzer is to statically infer properties of the execution of a program that can be used to check its specification.\nThe specification usually includes the absence of runtime exceptions (division by zero, integer overflow, array index out of bounds \\dots) and programmer annotations in the form of preconditions, postconditions, object invariants and assertions (``contracts''~\\cite{meyer97,BarnettFahndrichLogozzo-SAC10}).\nProving that a piece of code satisfies its specification often requires discovering numerical invariants on program variables. \n\nThe concept of abstract domain is central in the design and the implementation of a static analyzer~\\cite{CousotCousot77}.\nAbstract domains capture the properties of interest on programs.\nIn particular \\emph{numerical} abstract domains are used to infer numerical relationships among program variables.\nCousot and Halbwachs introduced the Polyhedra numerical abstract domain (\\Polyhedra) in~\\cite{CousotHalbwachs78}.\n\\Polyhedra\\ infers all the linear equalities on the program variables.\nThe application and scalability of \\Polyhedra{} has been severely limited by its performance which is worst-case exponential (easily attained in practice).\nTo overcome this shortcoming and to achieve scalability, new numerical abstract domains have been designed moving in two orthogonal directions: either only considering inequalities of a particular shape (weakly relational domains) or fixing \\emph{ahead} of the analysis the maximum number of linear inequalities to be considered (bounded domains).\nThe first class includes Octagons (which capture properties in the form $\\pm \\code{x} \\pm \\code{y} \\leq c$)~\\cite{Mine01-2}, TVPI ($a \\cdot \\code{x} + b \\cdot \\code{y} \\leq c$)~\\cite{SimonKing02-2}, Pentagons ($\\code{x} \\leq \\code{y} \\wedge a \\leq \\code{x} \\leq b$)~\\cite{LogozzoMaf08}, Stripes ($\\code{x} + a \\cdot (\\code{y} + \\code{z}) > b$)~\\cite{FerraraLogozzoMaf08} and Octahedra ($\\pm \\code{x}_0 \\dots \\pm \\code{x}_n \\leq c$)~\\cite{ClarisoCortadella04}.\nThe latter includes constraint template matrices (which capture at most $m$ linear inequalities)~\\cite{Sankaranarayanan05,GulwaniEtAl08-2} and methods to generate polynomial invariants \\eg~\\cite{MullerSeidl04-2,CarbonellKapur07,Kovacs08}.\n\n\\begin{figure}%[t]\n{\n\\small\n\\begin{Verbatim}\nclass StringBuilder {\n int m_ChunkLength; char[] m_ChunkChars;\n // ...\n public void Append(int wb, int count) {\n Contract.Requires(wb >= 2 * count); \n if (count + m_ChunkLength > m_ChunkChars.Length) \n(*) CopyChars(wb, m_ChunkChars.Length - m_ChunkLength);\n // ... }\n \n private void CopyChars(int wb, int len) {\n Contract.Requires(wb >= 2 * len); \n // ... \n\\end{Verbatim}\n}\n\\caption{An example extracted from \\code{mscorlib.dll}. The function \\code{Contract.Requires(\\dots)} expresses method preconditions. Proving the precondition of \\code{CopyChars} requires propagating an invariant involving three variables and non-unary coefficients.}\n\\label{fig:ex_vance}\n\\end{figure}\n\nAlthough impressive results have been achieved using weakly relational and bounded abstract domains, we experienced situations where the full \\emph{expressive} power of \\Poly{} is required.\nAs an example, let us consider the code snippet of Fig.~\\ref{fig:ex_vance}, extracted from \\code{mscorlib.dll}, the main library of the \\NET\\ framework.\nChecking the precondition at the call site \\code{(*)} involves:\n\\begin{enumerate}[(i)]\n \\item \\emph{propagating} the given constraints:\n \\[\\code{wb} \\geq 2 \\cdot \\code{count}\\]\n \\[\\code{count} + \\code{m\\_ChunkLength > m\\_ChunkChars.Length}\\]\n \\item \\emph{deducing} the precondition for \\code{CopyChars}:\n \\[\\code{wb} \\geq 2 \\cdot ( \\code{m\\_ChunkChars.\\allowbreak Length}-\\code{m\\_ChunkLength})\\] \n\\end{enumerate}\nThe aforementioned weakly relational domains cannot be used to check the precondition: Octahedra do not capture the first constraint (it involves a constraint with a non-unary coefficient); TVPI do not propagate the second constraint (it involves three variables); Pentagons and Octagons cannot represent any of the constraints; Stripes can propagate both constraints, but because of the incomplete closure it cannot deduce the precondition.\nBounded domains does the job, provided we fix \\emph{before} the analysis the template for the constraints.\nThis is inadequate for our purposes: The analysis of a \\emph{single} method in \\code{mscorlib.dll} may involve hundreds of constraints, whose shape cannot be fixed ahead of the analysis, \\eg\\ by a textual inspection.\n\\Polyhedra{} easily propagates the constraints. \nHowever, in the general case the price to pay for using \\Polyhedra{} is too elevated: the analysis will be limited to few tens of variables.\n\n\\subsection{Subpolyhedra}\nWe propose a new family of numerical abstract domains, Subpolyhedra (\\Subpoly), which has the same \\emph{expressive} power as \\Polyhedra, but it drops some inference power to achieve scalability:\n\\Subpoly\\ exactly represents and propagates linear inequalities containing hundreds of variables and constraints. \n\\Subpoly\\ is based on the fundamental insight that the reduced product of linear equalities, \\LinEq~\\cite{Karr76}, and intervals, \\Intervals~\\cite{CousotCousot77}, can produce very powerful yet efficient program analyses.\n\\Subpoly\\ can represent linear inequalities using slack variables, \\eg\\ $\\code{wb} \\geq 2 \\cdot \\code{count}$ is represented in \\Subpoly\\ by $\\code{wb} - 2 \\cdot \\code{count} = \\beta \\wedge \\beta \\in [0, +\\infty]$.\nAs a consequence, \\Subpoly\\ easily proves that the precondition for \\code{CopyChars} is satisfied at the call site~\\code{(*)}.\nIn general the join of \\Subpoly\\ is less precise than the one on \\Polyhedra{}, so that it may not infer \\emph{all} the linear inequalities.\nThe reason for that is that the pairwise join on \\LinEq\\ and \\Intervals\\ is in general less precise than the join on \\Poly.\nTo mitigate this loss of precision, we introduce a technique called hints~\\cite{Lavironlogozzo09-2} which enable recovering some of the precision.\nThis technique is not limited to \\Subpoly, and indeed we show that several existing refinement techniques can be seen as a particular case of hints.\n\nThe cardinal operation for \\Subpoly\\ is the join, which computes a compact yet precise upper approximation of two incoming abstract states.\nThe join of \\Subpoly\\ is parameterized by the: (i) the reduction algorithm, which propagates the information between \\LinEq\\ and \\Intervals; and (ii) the hints, which recover information lost at join points.\nEvery instantiation of the (reduction, hints) produces a new abstract domain in the \\Subpoly\\ family, allowing the fine tuning of the cost/precision ratio.\nThe most imprecise yet fast abstract domain in the \\Subpoly\\ family is the one in which the reduction is the simple identity (no interval is refined) and the no hints are used.\nThe most precise yet expensive abstract domain is one where the reduction is a complete linear programming algorithm and the hints are the usual \\Polyhedra\\ join. \n\n\\begin{figure}%[ht]\n% \\begin{wrapfigure}{l}{0pt}\n\\small\n\\begin{minipage}{5.5cm}\n\\begin{Verbatim}\nvoid Foo(int i, int j) {\n int x = i, y = j;\n if (x <= 0) return;\n while (x > 0) { x--; y--; }\n if (y == 0) \n Assert(i == j); \n}\n\\end{Verbatim}\n\\end{minipage}\n\\caption{\\small An example from~\\cite{SankaranarayananEtAl07}. \\Subpoly\\ infers the loop invariant $\\code{x} - \\code{i} = \\code{y} - \\code{j} \\wedge \\code{x} \\geq 0$, propagates it and prove the assertion.}\n\\label{fig:ex_paperSriramNEC}\n\\end{figure}\n% \\end{wrapfigure}\n\n\\subsection{Reduction}\nLet us consider the example in Fig.~\\ref{fig:ex_paperSriramNEC}, taken from~\\cite{SankaranarayananEtAl07}.\nThe program contains operations and predicates that can be exactly represented with Octagons.\nProving that the assertion is not violated requires discovering the loop invariant $\\code{x} - \\code{y} = \\code{i} - \\code{j} \\wedge \\code{x} \\geq 0$.\nThe loop invariant cannot be fully represented in Octagons: it involves a relation on four variables.\nBounded numerical domains are unlikely to help here as there is no way to syntactically figure out the required template. \nThe \\LinEq\\ component of \\SubPoly\\ infers the relation $\\code{x} - \\code{y} = \\code{i} - \\code{j}$. \nThe \\Intervals\\ component of \\SubPoly\\ infers the loop invariant $\\code{x} \\in [0, +\\infty]$, which in conjunction with the negation of the guard implies that $\\code{x} \\in [0, 0]$.\nThe simplification of \\SubPoly\\ propagates the interval, refining the linear constraint to $\\code{y} = \\code{j} - \\code{i}$.\nThis is enough to prove the assertion (in conjunction with the if-statement guard).\nIt is worth noting that unlike~\\cite{SankaranarayananEtAl07} \\Subpoly\\ does not require any hypothesis on the order of variables to prove the assertion.\n\n\n\n\\subsection{Join and Hints} Let us consider the code in Fig.~\\ref{fig:ex_paperSriramMS}, taken from~\\cite{GulavaniEtAl08}.\nThe loop invariant required to prove that the assertion is unreached (and hence that the program is correct) is $\\code{x} \\leq \\code{y} \\leq 100 \\cdot \\code {x} \\wedge \\code{z} = \\code{10} \\cdot \\code{w}$.\nWithout hints, \\Subpoly\\ can only infer $\\code{z} = \\code{10 \\cdot w}$.\n\\emph{Template} hints, inspired by~\\cite{Sankaranarayanan05}, are used to recover linear inequalities that are dropped by the imprecision of the join: In the example the template is $\\code{x} - \\code{y} \\leq b$, and the analysis automatically figures out that $b = 0$.\n\\emph{Planar Convex hull} hints, inspired by~\\cite{SimonKing02-2}, are used to introduce at join points linear inequalities derived by a planar convex hull: In the example it helps the analysis figure out that $\\code{y} \\leq \\code{100} \\cdot \\code{x}$.\nIt is worth noting that \\Subpoly\\ does not need any of the techniques of~\\cite{GulavaniEtAl08} to infer the loop invariant.\n\n\\begin{figure}%[t]\n{\n\\small\n\\begin{verbatim}\nint x = 0, y = 0, w = 0, z = 0;\nwhile (...) {\n if (...) { x++; y += 100; }\n else if (...) { if (x >= 4) { x++; y++; } }\n else if (y > 10 * w && z >= 100 * x) { y = -y; }\n \n w++; z += 10;\n}\nif (x >= 4 && y <= 2) Assert(false); \n\\end{verbatim}\n}\n\\caption{An example from~\\cite{GulavaniEtAl08}. \\Subpoly\\ infers the loop invariant $\\code{x} \\leq \\code{y} \\leq 100 \\cdot \\code {x} \\wedge \\code{z} = \\code{10} \\cdot \\code{w}$, propagates it out of the loop, and proves that the assertion is unreached.}\n\\label{fig:ex_paperSriramMS}\n\\end{figure}\n\n\n\\section{Abstract Interpretation}\n\n\\subsection{Abstract domains}\n\nWe assume the concrete domain to be the complete Bool-ean lattice of environments, $\\adom{C} = \\tupla{\\parti{\\Sigma}, \\subseteq, \\emptyset, \\Sigma, \\cup, \\cap}$, where $\\Sigma = \\funzione{\\Vars}{\\mathbb{Z}}$.\nAn abstract domain \\adom{A} is a tuple \\tupla{\\ael{D}, \\gamma, \\aless, \\abot, \\atp, \\ajoin, \\ameet, \\awidening, \\rho, \\sigma}.\nThe set of abstract elements $\\ael{D}$ is related to the concrete domain by a \\emph{monotonic} concretization function $\\gamma \\in \\funzione{\\ael{D}}{\\ael{C}}$.\nWith an abuse of notation, we will not distinguish between an abstract domain and the set of its elements.\nThe approximation order is $\\aless$ is a sound approximation of the concrete order: \n\\[\n\\forall \\ael{d}_0, \\ael{d}_1 \\in \\adom{D}.\\ \\ael{d}_0 \\aless \\ael{d}_1 \\Longrightarrow \\gamma(\\ael{d}_0) \\subseteq \\gamma(\\ael{d}_1)\n\\]\nThe smallest element is $\\abot$, the largest element is $\\atp$.\nThe join operator $\\ajoin$ satisfies:\n\\[\n\\forall \\ael{d}_0, \\ael{d}_1 \\in \\ael{D}.\\ \\ael{d}_0 \\aless \\ael{d}_0 \\ajoin \\ael{d}_1 \\wedge \n\\ael{d}_1 \\aless \\ael{d}_0 \\ajoin \\ael{d}_1\n\\]\nThe meet operator $\\ameet$ satisfies:\n\\[\n\\forall \\ael{d}_0, \\ael{d}_1 \\in \\ael{D}.\\ \\ael{d}_0 \\ameet \\ael{d}_1 \\aless \\ael{d}_0 \\wedge \n \\ael{d}_0 \\ameet \\ael{d}_1 \\aless \\ael{d}_1\n\\]\nThe widening $\\awidening$ ensures the convergence of the fixpoint iterations, \\ie\\ it satisfies:\n\\begin{enumerate}[(i)]\n\n \\item $ \\forall \\ael{d}_0, \\ael{d}_1 \\in \\ael{D}.\\ \\ael{d}_0 \\aless \\ael{d}_0 \\awidening \\ael{d}_1 \\wedge \\ael{d}_1 \\aless \\ael{d}_0 \\awidening \\ael{d}_1$\n \\item for each sequence of abstract elements $\\ael{d}_0, \\ael{d}_1, \\dots \\ael{d}_k $ the sequence defined by: \\\\\n $\\ael{d}_0^\\awidening\\! = \\ael{d}_0, \\ael{d}_1^\\awidening = \\ael{d}^\\awidening_0 \\awidening \\ael{d}_1 \\dots \\ael{d}^\\awidening_k = \\ael{d}^\\awidening_{k-1} \\awidening \\ael{d}_{k} $ \\\\\n is ultimately stationary.\n\\end{enumerate}\nIn general, we do not require abstract elements to be in some canonical or closed form, \\ie\\ there may exist $\\ael{d}_0, \\ael{d}_1 \\in \\adom{D}$, such that $\\ael{d}_0 \\neq \\ael{d}_1$, but $\\gamma(\\ael{d}_0) = \\gamma(\\ael{d}_1)$.\nThe \\emph{reduction} operator $\\rho \\in \\funzione{\\ael{D}}{\\ael{D}}$ puts an abstract element into a (pseudo-)canonical form without adding or losing any information: $\\forall \\ael{d}.\\ \\gamma(\\rho(\\ael{d})) = \\gamma(\\ael{d}) \\wedge \\rho(\\ael{d}) \\aless \\ael{d}$. \nWe do not require $\\rho$ to be idempotent.\nThe \\emph{simplification} operator $\\sigma \\in \\funzione{\\ael{D}}{\\ael{D}}$ removes redundancies in an abstract state. \nIt may introduce some loss of precision: $\\forall \\ael{d}.\\ \\gamma(\\ael{d}) \\subseteq \\gamma(\\sigma(\\ael{d}))$.\n\nIn most of the literature, reduction and simplification are not given the status of lattice operation. However, several domains use internally some specific operations that gives a more adapted representation of the abstract state, for a given operation.\nFor instance, there is an operation on Octagons that is called \\emph{closure}, and which has the properties of a reduction operator.\nWe believe that this is general enough to warrant adding two operators to the standard abstract domain definition.\nOf course, the identity is always a reduction operator and a simplification operator, so it can be defined even for domains which have no corresponding specific operation.\nThose operators are particularly important when the abstract elements considered are representations of mathematical objects, such that some objects have multiple equivalent representations.\n\nNew abstract domains can be systematically derived by cartesian composition or functional lifting~\\cite{CousotCousot79}. \nFollowing~\\cite{Cousot98}, we use the dot-notation to denote point wise or functional extensions.\n\n\\subsection{Transfer functions}\n It is common practice for the implementation of an\n abstract domain \\dom{A} to provide three abstract transfer functions:\n one for the assignment, one for the handling of\n tests, and one to perform abstract checking. \n The abstract transfer function for assignment, \\dom{A}.\\aassign, is an\n over-approximation of the states reached after the concrete assignment ($\\semantica{E}{\\code{E}}(\\sigma)$ denotes the evaluation of the expression \\code{E} in the state $\\sigma$) :\n\\begin{small}\n \\[\n \\begin{array}{l}\n \\forall \\code{x}, \\code{E}. \\forall \\ael{e} \\in \\dom{A}. \\\\\n \\{ \\sigma[\\code{x} \\mapsto v] \\mid \\sigma\\! \\in\\! \\gamma(\\ael{e}), \\semantica{E}{\\code{E}}(\\sigma) = v \\} \\subseteq \\gamma(\\dom{A}.\\aassign(\\ael{e}, \\code{x}, \\code{E}))\n \\end{array}\n \\]\n\\end{small}\n%\\sopra\n%\\noindent \nThe test abstract transfer function, \\adom{A}.\\atest, filters the input states ($\\semantica{B}{\\code{B}}(\\sigma)$ denotes the evaluation of a Boolean expression \\code{B} in the state $\\sigma$):\n\\begin{small}\n\\begin{equation*}\n% \\(\n\\forall \\code{B}. \\forall \\ael{e} \\in \\dom{A}.\\ \\{ \\sigma \\in \\gamma(\\ael{e}) \\mid \\semantica{B}{\\code{B}}(\\sigma) = \\mathit{true} \\} \\subseteq \\gamma(\\dom{A}.\\atest(\\ael{e}, \\code{B})).\n% \\)\n\\label{for:soundnesstest}\n\\end{equation*}\n\\end{small}\n%\\sopra\n%\\noindent \nThe abstract checking $\\dom{A}.\\checkif$ verifies if an assertion \\code{A} holds in an abstract state \\ael{e}.\nIt has four possible outcomes: $\\mathit{true}$ meaning that \\code{A} holds in all the concrete states $\\gamma(\\ael{e})$; $\\mathit{false}$, meaning that \\code{!A} holds in all the concrete states $\\gamma(\\ael{e})$; $\\mathit{bottom}$, meaning that the assertion is unreached; $\\mathit{top}$, meaning that the validity of \\code{A} cannot be decided in $\\gamma(\\ael{e})$.\nFormally, $\\adom{A}.\\checkif$ satisfies $\\forall \\code{A}.\\ \\forall\n\\ael{e} \\in \\adom{A}$:\n\n\\vspace{-0.2cm}\n\\begin{small}\n \\begin{equation*}\n \\begin{array}{l}\n \\adom{A}.\\checkif(\\code{A},\\ael{e}) = \\mathit{v} \\Rightarrow \\forall \\sigma \\!\\in\\! \\gamma(\\ael{e}).\\ \\semantica{B}{\\code{A}}(\\sigma) = \\mathit{v}, \\mathit{v} \\!\\in\\! \\{\\! \\mathit{true}, \\mathit{false}\\! \\} \\\\\n \\adom{A}.\\checkif(\\code{A},\\ael{e}) = \\mathit{bot} \\Rightarrow \\gamma(\\ael{e}) = \\emptyset \\\\\n \\adom{A}.\\checkif(\\code{A},\\ael{e}) = \\mathit{top} \\Rightarrow \\exists \\sigma_0, \\sigma_1 \\in \\gamma(\\ael{e}).\\ \\semantica{B}{\\code{A}}(\\sigma_0) \\neq \\semantica{B}{\\code{A}}(\\sigma_1)\n \\end{array}\n \\label{for:soundnesscheck}\n\\end{equation*}\n\\end{small}\n\n\n% define Karr, Intervals, Octagons, Polyhedra with gammas\n\n% Domain Reduction Simplification\n% Intervals id id\n% Karr Gaussian elimination\n% Octagon Floyd Marshal (put in sparse form?)\n% Polyhedra Generators inference All the constraints not implied (look in Axel's book)\n\n\\subsection{Intervals}\nThe abstract domain of interval environments is $\\tupla{\\Intervals, \\gamma_\\Intervals,\\allowbreak \\dot\\aless_\\Intervals, \\dot\\abot_\\Intervals, \\allowbreak \\dot\\atp_\\Intervals, \\dot\\ajoin_\\Intervals, \\dot\\ameet_\\Intervals, \\dot\\awidening_\\Intervals}$.\nThe abstract elements are maps from program variables to open intervals. \nThe concretization of an interval environment \\ael{i} is \n\\[\n\\gamma_\\Intervals(\\ael{i}) = \\{ s \\in \\Sigma \\mid \\forall \\code{x} \\in \\mathrm{dom}(\\ael{i}).\\ \\ael{i}(\\code{x}) = [a, b] \\wedge a \\leq s(\\code{x}) \\leq b\\}.\n\\]\nThe lattice operations are the functional extension of those in Fig.~\\ref{tab:intervals}.\nThe reduction and the simplification for intervals are the identity function.\nAll the domain operations can be implemented in linear time. \n\n\\begin{figure}%[t]\n\\small\n\\begin{tabular}{rl}\nOrder:& $\\![a_1, b_1] \\aless_\\Intervals [a_2, b_2] \\Longleftrightarrow a_1 \\geq a_2 \\wedge b_1 \\leq b_2$ \\\\\nBottom:& $\\![a, b] = \\abot_\\Intervals \\Longleftrightarrow a > b$ \\\\\nTop:& $\\![a, b] = \\atp_\\Intervals \\Longleftrightarrow a = -\\infty \\wedge b = +\\infty$\\\\\nJoin:& $\\![a_1, b_1] \\ajoin_\\Intervals [a_2, b_2] = \\![\\mathrm{min}(a_1, a_2), \\mathrm{max}(b_1, b_2)]$ \\\\\nMeet:& $\\![a_1, b_1] \\ameet_\\Intervals [a_2, b_2] = \\![\\mathrm{max}(a_1, a_2), \\mathrm{min}(b_1, b_2)]$ \\\\\nWidening:& $\\![a_1, b_1] \\awidening_\\Intervals [a_2, b_2] =$ \\\\\n& $\\quad \\quad [\\mathtt{if}\\, a_1 > a_2 \\,\\mathtt{then}\\, a_2 \\,\\mathtt{else}\\, -\\infty,$\\\\\n& $\\quad \\quad \\phantom{[}\\mathtt{if}\\, b_1 < b_2 \\,\\mathtt{then}\\, b_2 \\,\\mathtt{else}\\, +\\infty]$\\\\\n\\end{tabular}\n\\caption{Lattice operations over single intervals}\n\\label{tab:intervals}\n\\end{figure}\n\n\\subsection{Linear Equalities}\nThe abstract domain of linear \\emph{equalities} is $\\tupla{\\LinEq, \\gamma_\\LinEq,\\allowbreak \\aless_\\LinEq, \\abot_\\LinEq, \\allowbreak \\atp_\\LinEq, \\ajoin_\\LinEq, \\ameet_\\LinEq}$.\nThe elements are sets of linear equalities, their meaning is given by the set of concrete states which satisfy the constraints, \\ie\\ \n\\[\n\\gamma_\\LinEq = \\lambda \\ael{l}.\\ \\{ s \\in \\Sigma \\mid \\forall (\\sum a_i \\cdot \\code{x}_i = b) \\in \\ael{l}.\\ \\sum a_i \\cdot s(\\code{x}_i) = b \\} \n.\n\\]\nThe order is sub-space inclusion, the bottom is the empty space, the top is the whole space, the join is the smallest space which contains the two arguments, the meet is space intersection.\n\\Karr\\ satisfies the ascending chain condition, so that the join suffices to ensure analysis termination.\nThe reduction and the simplification are just Gaussian elimination.\nThe complexity of the domain operations is subsumed by the complexity of Gaussian elimination, which is cubic.\n\n\\subsection{Polyhedra}\nThe abstract domain of linear \\emph{inequalities} is $\\tupla{\\Poly, \\gamma_\\Poly,\\allowbreak \\aless_\\Poly, \\abot_\\Poly, \\allowbreak \\atp_\\Poly, \\ajoin_\\Poly, \\ameet_\\Poly, \\awidening_\\Poly}$.\nThe elements are sets of linear inequalities, the concretization is the set of concrete states which satisfy the constraints \n \\ie\\ \n\\[\n\\gamma_\\Poly = \\lambda \\ael{p}.\\ \\{ s \\in \\Sigma \\mid \\forall (\\sum a_i \\cdot \\code{x}_i \\leq b) \\in \\ael{p}.\\ \\sum a_i \\cdot s(\\code{x}_i) \\leq b \\},\n\\]\n the order is the polyhedron inclusion, the bottom is the empty polyhedron, the top is the whole space, the join is the convex hull, the meet is just the union of the set of constraints, and the widening preserves the inequalities stable among two successive iterations.\nThe reduction and the simplification respectively infers the set of generators and removes the redundant inequalities.\nThe cost of the \\Polyhedra{} operations is subsumed by the cost of the conversion between the algebraic representation (set of inequalities) and the geometric representation (set of generators) used in the implementation~\\cite{PPL}.\nIn fact, some operations require the algebraic representation (\\eg\\ $\\ameet_\\Poly$), some require the geometrical representation (\\eg\\ $\\ajoin_\\Poly$), and some others require both (\\eg\\ $\\aless_\\Poly$).\nThe conversion between the two representations is exponential in the number of variables, and it cannot be done better~\\cite{KhachiyanBBEG06}.\n\n\\section{Subpolyhedra}\n\nWe introduce the numerical abstract domain of Subpolyhedra, \\Subpoly.\nThe main idea of \\Subpoly\\ is to combine \\Intervals\\ and \\Lineq\\ to capture complex linear \\emph{inequalities}.\nSlack variables are introduced to replace inequality constraints with equalities. \n\n\n\\subsection{Variables}\nA variable $\\var \\in \\Vars$ can either be a \\emph{program} variable ($\\progvar \\in \\VarProg$) or a \\emph{slack} variable ($\\slackvar \\in \\VarSlack$).\nA slack variable $\\slackvar$ has an associated information, denoted by $\\slackvarinfo$, which is a linear form $a_1 \\cdot \\variable{v}_1 + \\dots + a_k \\cdot \\variable{v}_k$.\n\nLet $\\kappa \\equiv \\sum a_i \\cdot \\progvariable{i} + \\sum b_j \\cdot \\slackvariable{j} = c$ be a linear equality:\n$\\code{s_\\kappa} = \\sum_{\\progvar_i \\in \\VarProg} a_i \\cdot \\progvar_i$ denotes the partial sum of the monomials involving just program variables;\n $\\VarProg(\\kappa) = \\{ \\progvariable{i} \\mid a_i \\cdot \\progvariable{i} \\in \\kappa, a_i \\neq 0 \\}$ and $\\VarSlack(\\kappa) = \\{ \\slackvariable{j} \\mid b_j \\cdot \\slackvariable{j} \\in \\kappa, b_j \\neq 0 \\}$ denote respectively the program variables and the slack variables in $\\kappa$.\nThe generalization to inequalities and sets of equalities and inequalities is straightforward.\n\n\n\\subsection{Domain structure}\n\nThe elements of \\SubPoly\\ belong to the reduced product $\\Lineq \\times \\Intervals$~~\\cite{CousotCousot79}.\nInequalities are represented in \\SubPoly{} with slack variables:\n\\[\\sum a_i \\cdot \\progvariable{i} \\leq c \\Longleftrightarrow \\sum a_i \\cdot \\progvariable{i} - c = \\slackvar \\wedge \\slackvar \\in [-\\infty, 0]\n\\] \n(\\slackvar{} is a fresh slack variable with the associated information $\\slackvarinfo = \\sum a_i \\cdot \\progvariable{i}$). \n\n\n\n\\subsection{Concretization}\nAn element of \\Subpoly\\ can be interpreted as a polyhedron by projecting out the slack variables: $\\gamma^\\Poly_{S} \\in \\funzione{\\Subpoly}{\\Poly}$ is\n\\[\n\\gamma^\\Poly_{S} = \\lambda \\subpolyPair{}{}.\\ \\pi_{\\VarSlack}(\\ael{l} \\cup \\{ a \\leq \\var \\leq b \\mid \\ael{i}(\\var) = [a, b] \\} )\n,\\]\n where $\\pi$ denotes the projection of variables in $\\Poly$.\nThe concretization $\\gamma_{S} \\in \\funzione{\\SubPoly}{\\parti{\\Sigma}}$ is then\n$\n\\gamma_{S} = \\gamma_\\Poly \\circ \\gamma^{\\Poly}_{S}.\n$\n\n\n\\subsection{Approximation Order}\nThe order on \\Subpoly\\ may be defined in terms of order over \\Polyhedra.\nGiven two subpolyhedra $\\subpoly_0, \\subpoly_1$, the most precise order relation $\\lessS^{*}$ is \n\\[\n\\subpoly_{0} \\lessS^{*} \\subpoly_{1} \\Longleftrightarrow \\gamma^\\Poly_{S}(\\subpoly_{0}) \\aless_\\Poly \\gamma^\\Poly_{S}(\\subpoly_{1}).\n\\]\nHowever, $\\lessS^{*}$ may be too expensive to compute: it involves mapping subpolyhedra in the dual representation of \\Polyhedra.\n This can easily cause an exponential blow up.\nWe define a weaker approximation order relation which first tries to find a renaming $\\theta$ for the slack variables, and then checks the pairwise order.\nFormally: \n\\begin{multline*}\n\\subpolyPair{0}{} \\lessS \\subpolyPair{1}{} \\Longleftrightarrow \\\\\n\\quad \\exists \\theta.~ \\VarSlack(\\subpolyPair{0}{}) \\stackrel{\\mathrm{inj}}{\\longrightarrow} \\VarSlack(\\subpolyPair{1}{}). \\\\\n\\qquad \\forall \\slackvar \\in \\VarSlack(\\subpolyPair{0}{}).\\ \\slackvarinfo = \\slackvariableinfo{\\theta(\\slackvar)} \\\\\n\\qquad \\wedge \\theta(\\subpolyPair{0}{}) \\dot{\\aless} \\subpolyPair{1}{}.\n\\end{multline*}\nIn general $\\lessS \\subsetneq \\lessS^{*}$.\nIn practice, \\lessS{} is used to check if a fixpoint has been reached. \nA weaker order relation means that the analysis may perform some extra widening steps, which may introduce precision loss.\nHowever, we found the definition of $\\lessS$ satisfactory in our experience.\n\nOne other important consequence of using a weak approximation order is that we are not always able to tell whether two abstract elements\nare actually equivalent representations of the same geometric shape.\nThis is why, unlike some other domains like \\Polyhedra{}, in \\Subpoly\\ the elements do not correspond to a geometrical shape, even up to equivalence; there are some elements that correspond to the same polyhedron, but are not comparable with our weak ordering.\n\n\\subsection{Bottom}\nAn element of \\Subpoly\\ is equivalent to bottom if after a reduction one of the two components is bottom:\n\\[\n\\subpoly = \\bottomS \\Longleftrightarrow \\reduction{\\ael{s}} = \\tupla{\\lineq, \\intv} \\wedge (\\intv = \\dot\\bot_\\Intervals \\vee \\lineq = \\bot_\\Lineq).\n\\]\n \n\\subsection{Top}\nAn element of \\Subpoly\\ is top if after the simplification both components are top:\n\\[\n\\subpoly = \\topS \\Longleftrightarrow \\simplify{\\ael{s}} = \\tupla{\\lineq, \\intv} \\wedge \\intv = \\dot\\top_\\Intervals \\wedge \\lineq = \\top_\\Lineq.\n\\]\n\n\\subsection{Linear form evaluation}\nLet \\code{s} be a linear form: $\\sem{s}\\in \\funzione{\\SubPoly}{\\Intervals}$ denotes the evaluation of \\code{s} in an element of \\Subpoly\\ after that the reduction has inferred the tightest bounds: \n\\(\n\\left\\sx\\sum \\mathit{a_i} \\cdot \\var_\\mathit{i} \\right\\dx\\subpolyPair{}{} = \\mathbf{let}\\ \\subpolyPair{}{*} = \\rho(\\subpolyPair{}{})\\ \\mathbf{in} \\sum a_i \\cdot \\ael{i}^*(\\var_i). \n\\)\n\n\n\n\\subsection{Join}\nAs with the order, one could define a most precise join operation by concretizing on \\Polyhedra{}, doing the convex hull, then abstracting again to \\Subpoly.\nHowever, this is a very expensive operation, and the aim of \\Subpoly\\ is to give faster, but potentially less precise, operations.\nSo we define instead a specific join algorithm \\joinS\\ in three steps.\nFirst, inject the information of the slack variables into the abstract elements.\nSecond, perform the pairwise join on the saturated arguments. \nThird, add the constraints that are implied by the two operands of the join, but that were not preserved by the previous step.\nThe join is defined by the Algorithm~\\ref{alg:join} \n(We let $\\underline{0} = 1$, $\\underline{1} = 0$).\nWe illustrate it with examples.\n\n\\begin{algorithm}[t]\n\\caption{The join $\\joinS$ on Subpolyhedra}\n\\label{alg:join}\n\\begin{algorithmic}\n\\STATE \\textbf{input} $\\subpolyPair{i}{} \\in \\Subpoly$, $i \\in \\{0, 1\\}$\n\\medskip\n\\STATE \\textbf{let} \\subpolyPair{i}{'} = \\subpolyPair{i}{}\n\\STATE\n\\smallskip\n\\COMMENT{Step 1. Propagate the information of the slack variables}\n\\FORALL{$\\slackvar \\in \\VarSlack(\\lineq_i) \\setminus \\VarSlack(\\lineq_{\\underline{i}})$}\n\\STATE \\subpolyPair{\\underline{i}}{'} := \\tupla{\\ael{l}'_{\\underline{i}} \\meet_\\LinEq\\{ \\slackvar = \\slackvarinfo \\};\\ \\ael{i}'_{\\underline{i}} } \n\\ENDFOR\n\\STATE\n\\smallskip\n\\COMMENT{Step 2. Perform the point-wise join on the saturated operands}\n\\STATE \\textbf{let} \\subpolyPair{\\sqcup}{} = $\\rho(\\subpolyPair{0}{'}) \\dot\\sqcup \\rho(\\subpolyPair{1}{'})$\n\\STATE\n\\smallskip\n\\COMMENT{Step 3. Hints: Recover the lost information }\n\\STATE \\textbf{let} $D_{i}$ be the linear equalities dropped from $\\lineq'_i$ at the previous step\n\\FORALL{$\\kappa \\in D_{i}$}\n\\IF {$\\kappa$ contains no slack variable }\n\\STATE \\textbf{let} $\\intv_{s_\\kappa} = \\sem{s_\\kappa}\\subpolyPair{\\underline{i}}{'}$\n\\IF {$\\intv_{s_\\kappa} \\neq \\top_\\Intervals$}\n\\STATE \\textbf{let} \\slackvar\\ be a fresh slack variable\n\\STATE \\subpolyPair{\\sqcup}{} := $\\tupla{\\lineq_\\sqcup \\meet_\\LinEq \\{ \\slackvar = \\kappa\\};\\ \\intv_\\sqcup \\dot \\sqcap_\\Intervals \\{ \\slackvar= \\intv_{s_\\kappa} \\sqcup_\\Intervals [0,0]\\}}$ \n\\ENDIF\n\\ELSIF {$\\kappa$ contains exactly one slack variable \\slackvar}\n\\STATE \\textbf{let} $\\intv_{s_\\kappa} = \\sem{s_\\kappa}\\subpolyPair{\\underline{i}}{'}$\n\\IF {$\\intv_{s_\\kappa} \\neq \\top_\\Intervals$}\n\\STATE \\subpolyPair{\\sqcup}{} := $\\tupla{\\lineq_\\sqcup \\meet_\\LinEq \\{ \\kappa\\};\\intv_\\sqcup \\dot\\sqcap_\\Intervals \\{ \\slackvar = \\intv_{s_\\kappa} \\sqcup_\\Intervals \\intv_i(\\slackvar)\\}}$ \n\\ENDIF\n\\ELSE[$\\kappa$ contains strictly more than one slack variable]\n\\STATE \\textbf{continue}\n\\ENDIF\n\\ENDFOR\n\\RETURN \\subpolyPair{\\sqcup}{} \n\\end{algorithmic}\n\\end{algorithm}\n\n\n\\begin{figure}%[t]\n \\begin{subfloat}\n \\begin{minipage}{4cm}\n\\begin{verbatim}\n if(...) \n { assume x - y <= 0; } \n else \n { assume x - y <= 5; }\n\\end{verbatim}\n \\end{minipage}\n\\caption{} \n \\end{subfloat} \n\\qquad\n \\begin{subfloat}\n \\begin{minipage}{6cm}\n\\begin{verbatim}\nif(...) \n { assume x == y; assume y <= z; } \nelse \n { assume x <= y; assume y == z; } \n\\end{verbatim}\n\\caption{}\n \\end{minipage}\n \\end{subfloat}\n\\caption{Examples illustrating the need for Step 1 in the join algorithm }\n\\label{fig:example-join}\n\\end{figure}\n\n\\begin{example}[Steps 1 \\& 2]\nLet us consider the code in Fig.~\\ref{fig:example-join}(a).\nAfter the assumption, the abstract states on the left branch and the right branch are respectively:\n\\(\n\\subpoly_0 = \\tupla{\\code{x} -\\code{y} = \\slackvariable{0};\\ \\slackvariable{0} \\in [-\\infty, 0]}\\) and % \\quad\n\\(\n\\subpoly_1 = \\tupla{\\code{x} -\\code{y} = \\slackvariable{1};\\ \\slackvariable{1} \\in [-\\infty, 5]}\n\\).\nThe information associated with the slack variables is $\\slackvariableinfo{ \\slackvariable{0}} = \\slackvariableinfo{ \\slackvariable{1}} = \\code{x} -\\code{y}$.\nAt the join point we apply Algorithm~\\ref{alg:join}.\nStep 1 refines the abstract states by introducing the information associated with the slack variables:\n\\(\n\\subpoly'_0 = \\tupla{\\code{x} -\\code{y} = \\slackvariable{0} = \\slackvariable{1};\\ \\slackvariable{0} \\in [-\\infty, 0]}\\) and % \\quad\n\\(\n\\subpoly'_1 = \\tupla{\\code{x} -\\code{y} = \\slackvariable{1} = \\slackvariable{0};\\ \\slackvariable{1} \\in [-\\infty, 5]}\n\\).\nStep 2 requires the reduction of the operands. \nThe interval for \\slackvariable{1} (resp. \\slackvariable{0}) in $\\subpoly'_0$ (resp. $\\subpoly'_1$) is refined:\n%\\begin{align*}\n\\(\n\\rho(\\subpoly'_0) = \\tupla{\\code{x} -\\code{y} =\\slackvariable{0} = \\slackvariable{1};\\ \\slackvariable{0} \\in [-\\infty, 0], \\slackvariable{1} \\in [-\n\\infty, 0]}\n\\)\nand\n\\(\n\\rho(\\subpoly'_1) = \\tupla{\\code{x} -\\code{y} = \\slackvariable{1} = \\slackvariable{0};\\ \\slackvariable{0} \\in [-\\infty, 5], \\slackvariable{1} \\in [-\\infty, 5]}.\n\\)\n%\\end{align*}\nThe pairwise join gets the expected invariant:\n\\(\n\\subpoly_\\sqcup = \\rho(\\subpoly'_0) \\dot\\sqcup \\rho(\\subpoly'_1) = \\tupla{\\code{x} -\\code{y} = \\slackvariable{0} = \\slackvariable{1};\\ \\slackvariable{0}\\in [-\\infty, 5], \\slackvariable{1} \\in [-\\infty, 5]}. \n\\) \\qed\n\\end{example}\n\n\\begin{example}[Non-trivial information for slack variables]\nLet us consider the code snippet in Fig.~\\ref{fig:example-join}(b).\nThe abstract states to be joined are \n\\(\n\\tupla{\\code{x} -\\code{y} = 0, \\code{y} - \\code{z} = \\slackvariable{0}; \\slackvariable{0} \\in [-\\infty, 0]} \n\\) and\n\\(\n\\tupla{\\code{y} -\\code{z} = 0, \\code{x} - \\code{y} = \\slackvariable{1}; \\slackvariable{1} \\in [-\\infty, 0]}\n\\).\nThe associated information are $\\slackvariableinfo{ \\slackvariable{0}} = \\code{y} -\\code{z}$ and $\\slackvariableinfo{ \\slackvariable{1}} = \\code{x} -\\code{y}$.\nStep 1 allows to refine the abstract states with the slack variable information, and hence to infer that after the join $\\code{x} \\leq \\code{y}$ and $\\code{y} \\leq \\code{z}$. \\qed\n\\end{example}\n\n\n\n\nThe two examples above show the importance of introducing the information associated with slack variables in Step 1 and the reduction in Step 2.\nWithout those, the relation between the slack variables and the program point where they were introduced would have been lost.\n\n\n\nThe join of \\Lineq{} is \\emph{precise} in that if a linear equality is implied by both operands, then it is implied by the result too.\nThe same for the join of \\Intervals.\nThe pairwise join in $\\Lineq \\times \\Intervals$ may drop some inequalities.\nSome of those can be recovered by the refinement step.\nThe next example illustrates it.\n\n\n\\begin{example}[Step 3]\nLet us consider the code in Fig.~\\ref{ex:joinwiden}(a).\nThe analysis of the two branches of the conditional produces the abstract states: \n\\(\n\\subpoly_0 = \\tupla{\\code{x} - 3 \\cdot \\code{y} = 0;\\ \\dot\\top_\\Intervals} \n\\) \nand\n\\(\n\\subpoly_1 =\\tupla{\\code{x} = 0, \\code{y} = 1;\\ \\code{x} \\in [0,0], \\code{y} \\in [1,1] }\n\\).\nThe reduction $\\rho$ does not refine the states (we already have the tightest bounds).\nThe point-wise join produces the abstract state \\topS.\nStep 3 identifies the dropped constraints: $D_0 = \\{\\code{x} - 3 \\cdot \\code{y} = 0\\}$ and $D_1 = \\{\\code{x} = 0, \\code{y} = 1 \\}$.\nThe algorithm inspects them to check if the corresponding linear form can be bounded by the ``other'' branch.\nThe linear form in $D_0$ is also bounded in the right branch: $\\sem{\\code{x} - \\mathrm{3} \\cdot \\code{y}}(\\subpoly_1)$ = $[-3,-3]$ ($\\neq \\dot\\top_\\Intervals$).\nTherefore it is meaningful to add a slack variable $\\slackvar$ corresponding to this linear form to the result.\nThe linear formss of $D_1$ cannot be bounded on the left branch,so they are discarded. \nThe abstract state after the join is then\n\\(\n\\subpoly_\\sqcup =\\tupla{\\code{x} - \\code{y} = \\slackvar;\\ \\slackvar \\in [-3,0] }.\n\\) \\qed\n\\end{example}\n\n\\begin{figure}%[t]\n\\centering\n \\begin{subfloat}\n \\begin{minipage}{5cm}\n\\begin{verbatim}\nif(...) { assume x == 3 * y; } \nelse { x = 0; y = 1; }\n\\end{verbatim}\n \\end{minipage}\n \\caption{}\n \\end{subfloat} \n \\qquad \n \\begin{subfloat}\n \\begin{minipage}{2.5cm}\n\\begin{verbatim}\ni := k;\nwhile(...) i++;\nassert i >= k;\n\\end{verbatim}\n \\end{minipage}\n \\caption{}\n \\end{subfloat}\n\\caption{Examples illustrating the need for the Step 3 in the join and the widening.}\n\\label{ex:joinwiden}\n\\end{figure}\n\n\\subsection{Meet} \nThe meet $\\meet_S$ is simply the pairwise meet on $\\LinEq \\times \\Intervals$.\n\n\\subsection{Widening}\nThe algorithm for the widening is similar to the join, with the main differences that: \n(i) the information associated to slack variables is propagated only in one direction; \n(ii) only the right argument is saturated; and\n(iii) the recovery step is applied only to one of the operands.\nThose hypotheses avoid the well-known problems of interaction between reduction, refinement and convergence of the iterations~\\cite{Mine04,Simon08}.\n\n\n\\begin{algorithm}[t]\n\\caption{The widening $\\wideningS$ on Subpolyhedra}\n\\label{alg:widening}\n\\begin{algorithmic}\n\\STATE \\textbf{input} $\\subpolyPair{i}{} \\in \\Subpoly$, $i \\in \\{0, 1\\}$\n\\medskip\n\\STATE \\textbf{let} \\subpolyPair{i}{'} = \\subpolyPair{i}{}\n\\STATE\n\\smallskip\n\\COMMENT{Step 1. Propagate the information of the slack variables}\n\\FORALL{$\\slackvar \\in \\VarSlack(\\lineq_0) \\setminus \\VarSlack(\\lineq_1)$}\n\\STATE \\subpolyPair{0}{'} := \\tupla{\\ael{l}'_{0} \\meet_{\\Lineq} \\{ \\slackvar = \\slackvarinfo\\};\\ \\ael{i}'_{0}} \n\\ENDFOR\n\\STATE\n\\smallskip\n\\COMMENT{Step 2. Perform the point-wise widening}\n\\STATE \\textbf{let} \\subpolyPair{\\widening}{} = $ \\subpolyPair{0}{'} \\dot\\widening \\rho(\\subpolyPair{1}{'})$\n\\STATE\n\\smallskip\n\\COMMENT{Step 3. Recover the lost information }\n\\STATE \\textbf{let} $D_{0}$ be the linear equalities dropped from $\\lineq'_0$ at the previous step\n\\FORALL{$\\kappa \\in D_{0}$}\n\\IF {$\\kappa$ contains no slack variables }\n\\STATE \\textbf{let} $\\intv_{s_\\kappa} = \\sem{s_\\kappa}\\subpolyPair{1}{'}$\n\\IF {$\\intv_{s_\\kappa} \\neq \\top_\\Intervals$}\n\\STATE \\textbf{let} \\slackvar\\ be a fresh slack variable\n\\STATE \\subpolyPair{\\widening}{} := $\\tupla{\\lineq_\\widening \\meet_\\LinEq \\{ \\slackvar = \\kappa\\};\\ \\intv_\\widening \\dot\\sqcap_\\Intervals \\{ \\slackvar = [0,0] \\widening \\intv_{s_\\kappa} \\}}$ \n\\ENDIF\n\\ELSIF {$\\kappa$ contains exactly one slack variable \\slackvar}\n\\STATE \\textbf{let} $\\intv_{s_\\kappa} = \\sem{s_\\kappa}\\subpolyPair{1}{'}$\n\\IF {$\\intv_{s_\\kappa} \\neq \\top_\\Intervals$}\n\\STATE \\subpolyPair{\\widening}{} := $\\tupla{\\lineq_\\widening \\meet_\\Lineq \\{ \\kappa\\};\\ \\intv_\\widening \\dot\\sqcap_\\Intervals \\{ \\slackvar = \\intv_0(\\code{v}) \\widening \\intv_{s_\\kappa} \\}}$ \n\\ENDIF\n\\ELSE[$\\kappa$ contains strictly more than one slack variable]\n\\STATE \\textbf{continue}\n\\ENDIF\n\\ENDFOR\n\\smallskip\n\\RETURN \\subpolyPair{\\widening}{}\n\\end{algorithmic}\n\\end{algorithm} \n\n\n\\begin{example}[Refinement step for the widening]\nLet us consider the code snippet in Fig.~\\ref{ex:joinwiden}(b).\nThe entry state to the loop is\n\\(\n\\subpoly_0 = \\tupla{ \\code{i} - \\code{k} = 0;\\ \\dot \\top_\\Intervals} \\).\nThe state after one iteration is\n\\(\\subpoly_1 = \\tupla{ \\code{i} -\\code{k} = 1;\\ \\dot \\top_\\Intervals} \\).\nWe apply the widening operator. \nStep 1 does not refine the states as there are no slack variables.\nThe pairwise widening of Step 2 lose all the information.\nStep 3 recovers the constraint $\\code{k} \\leq \\code{i}$:\n $D_0 = \\{ \\code{i} -\\code{k} = 0 \\}$ contains no slack variables and \n$\\sem{\\code{i} -\\code{k} }(\\subpoly_1) = [1, 1]$ so that \n\\(\n\\subpoly_\\widening = \\tupla{ \\code{i} -\\code{k} = \\slackvar;\\ \\slackvar \\in [0, +\\infty] }.\n\\)\n\\qed\n\\end{example}\n\n\\begin{theorem}[Fixpoint convergence]\nThe operator defined in Algorithm~\\ref{alg:widening} is a widening. Moreover, \\lessS\\ can be used to check that the fixpoint iterations eventually stabilize.\n\\end{theorem}\n\\textit{Proof sketch.}\nAlgorithm~\\ref{alg:widening} ensures that the number of linear equalities at any step is at most the number of equalities in the first step. \nSo there exists a point from which no more slack variables will be added. \nExisting slack variables may be renamed to fresh ones to avoid conflicts.\nIn the definition of \\lessS\\ the renaming $\\theta$ takes care of those.\nUp to the renaming, the widening is the pairwise widening, which is convergent and whose stability can be checked by the pairwise partial order.\n\\qed\n\n\\section{Reduction for Subpolyhedra}\nThe reduction in \\SubPolyhedra\\ infers tighter bounds on linear forms and hence on program variables.\nReduction is cardinal to fine tuning the precision/cost ratio.\nWe propose two reduction algorithms, one based on linear programming, $\\rho_{LP}$, and the other on basis exploration, $\\rho_{BE}$.\nBoth of them have been implemented in \\Clousot, our abstract interpretation-based static analyzer for \\NET~\\cite{MafLogozzo10}.\n\n\\subsection{Linear programming-based reduction}\nA linear programming problem is the problem of maximizing (or minimizing) a linear function subject to a finite number of linear constraints.\nWe consider \\emph{upper bounding} linear problems (UBLP)~\\cite{LinearProgramming}, \\ie\\ problems in the form ($n$ is the number of variables, $m$ is the number of equations):\n\\[\n% \\small\n\\begin{aligned}\n\\text{maximize} &\\quad c \\cdot \\var_k \\quad \\quad\\quad k \\in {1 \\dots n}, c \\in \\{ -1, +1 \\} \\\\\n\\text{subject to} & \\quad\\sum_{j=1}^n a_{ij} \\cdot \\var_j = b_j \\quad (i = 1, \\dots m) \\\\\n & \\quad \\text{and} \\quad l_j \\leq \\var_j \\leq u_j \\quad (j = 1, \\dots n). \n\\end{aligned}\n \\]\n\nThe Linear programming-based reduction $\\rho_{LP}$ is trivially an instance of UBLP:\nTo infer the tightest upper bound (resp. lower bound) on a variable $\\code{v}_k$ in an element of \\Subpoly\\ $\\subpolyPair{}{}$ instantiate UBLP with $c = 1$ (resp. $c = -1$) subject to the linear equalities $\\ael{l}$ and the numerical bounds $\\ael{i}$.\n\nUBLP can be solved in polynomial time~\\cite{LinearProgramming}. \nHowever, polynomial time algorithms for UBLP do not perform well in practice.\nThe Simplex method~\\cite{Dantzig48}, exponential in the worst-case, in practice performs a lot better than other known linear programming algorithms~\\cite{SpielmanTeng04}.\nThe Simplex algorithm works by visiting the \\emph{feasible bases} (informally, the vertices) of the polyhedron associated with the constraints. \nAt each step, the algorithm visits the adjacent basis (vertex) that maximizes the current value of the objective by the largest amount. \nThe iteration strategy of the Simplex guarantees the convergence to a basis which exhibits the optimal value for the objective. \n\nThe advantages of using Simplex for $\\rho_{LP}$ are that: (i) it is well-studied and optimized; (ii) it is complete in $\\mathbb{R}$, \\ie\\ it finds the best solution over real numbers; and (iii) it guarantees that all the information is propagated at once: $\\rho_{LP} \\circ \\rho_{LP} = \\rho_{LP}$.\n\nThe drawbacks of using Simplex are that (i) the computation over machine floating point may introduce imprecision or unsoundness in the result; and (ii) the reduction $\\rho_{LP}$ requires to solve $2 \\cdot n$ UBLP problems to find the lower bound and the upper bound for each of the $n$ variables in an abstract state.\nWe have observed (i) in our experiences (cf. Sect.~\\ref{sect:Experience}). \nThere exists methods to circumvent the problem at the price of extra computational cost, \\eg\\ using arbitrary precision rationals, or a combination of machine floating arithmetic and precise arithmetic.\nEven if (i) is solved, we observed that (ii) dominates the cost of the reduction, in particular in presence of abstract states with a large number of variables: the $2 \\cdot n$ UBLP problems are \\emph{disjoints} and there is no easy way to share the sequence of bases visited by the Simplex algorithm over the different runs of the algorithm for the same abstract state.\n\n\\begin{algorithm}[t]\n\\begin{algorithmic}\n\\STATE \\textbf{input} $\\subpolyPair{}{} \\in \\Subpoly$, $\\delta \\in \\parti{\\{ \\upzeta \\mid \\upzeta\\ \\text{is a basis change}\\}} $\n\\medskip\n\\STATE Put $\\lineq$ into row echelon form. Call the result $\\lineq'$\n\\STATE \\textbf{let} $\\tupla{\\lineq^*, \\intv^*} = \\tupla{\\lineq', \\intv}$\n\\FORALL{$\\upzeta \\in \\delta$}\n \\STATE $\\lineq^*$ := $\\upzeta(\\lineq^*)$\n \\FORALL{$\\var_k + a_{k+1}\\cdot \\var_{k+1} + \\dots + a_n\\cdot \\var_{n} = b \\in \\lineq^*$}\n \\STATE $\\intv^* := \\intv^*[\\var_k \\mapsto \\intv^*(\\var_k) \\meet_\\Intervals \\sx b-a_{k+1}\\cdot \\var_{k+1} + \\dots + a_n\\cdot \\var_{n}\\dx(\\intv^*)]$ \n \\ENDFOR\n\\ENDFOR\n\\smallskip\n\\RETURN \\tupla{\\lineq^*, \\intv^*}\n\\end{algorithmic}\n\\caption{The reduction algorithm $\\rho_{BE}$, para-metrized by the oracle $\\delta$}\n\\label{alg:reduction}\n\\end{algorithm}\n\n\\subsection{Basis exploration-based reduction}\nWe have developed a new reduction $\\rho_{BE}$, less subject to the drawbacks from floating point computation than $\\rho_{LP}$, which enables a better tuning of the precision/cost ratio than the Simplex. \nThe basic ideas are: (i) to fix \\emph{ahead} of time the bases we want to explore; and (ii) to refine at each step the variable bounds.\nThe reduction $\\rho_{BE}$, parametrized by a set of changes of basis $\\delta$, is formalized by Algorithm~\\ref{alg:reduction}. \nFirst, we put the initial set of linear constraints into triangular form (row echelon form). \nThen, we apply the basis changes in $\\delta$ and we refine all the variables \\emph{in the basis}.\nWith respect to $\\rho_{LP}$, $\\rho_{BE}$ is faster: (i) the number of bases to explore is statically bounded; (ii) at each step, $k$ variables may be refined at once. \n\nIn theory, $\\rho_{BE}$ is an abstraction of $\\rho_{LP}$, in that it may not infer the \\emph{optimal} bounds on variables (it depends on the choice of $\\delta$).\nIn practice, we found that $\\rho_{BE}$ is much more numerically stable and it can infer better bounds than $\\rho_{LP}$.\nThe reason is in the handling of numerical errors in the computation. \nSuppose we are seeking a (lower or upper) bound for a variable using the Simplex. \nIf we detect a numerical error (\\ie\\ a loss of precision in floating point computations or a huge coefficient in the exact arithmetic computation), the only sound solution is to stop the iterations, and return the current value of the objective function as the result.\nOn the other hand, when we detect a numerical error in $\\rho_{BE}$, we can just skip the current basis (abstraction), and move to the next one in $\\delta$.\n\n\n\\subsubsection{Linear Explorer ($\\delta_L$)} The linear bases explorer is based on the empirical observation that in most cases, to infer the tightest bounds for some variable $\\var_0$, you need to have it in the basis while some other variable $\\var_1$ is out of the basis.\nFollowing this, the linear explorer generates a sequence of bases $\\delta_L$ with the property that for each unordered pair of distinct variables $\\tupla{\\var_0, \\var_1}$, there exists $\\upzeta \\in \\delta_L$ such that $\\var_0$ is in the basis and $\\var_1$ is not.\nThe sequence $\\delta_L$ is defined as \n\\(\n\\delta_L = \\{ \\upzeta_i \\mid i \\in [0, n],\\ \\var_{i} \\dots \\var_{(i + m - 1)\\, \\mathtt{mod}\\, n} \\text{ are in basis for}\\ \\upzeta_i\\}.\n\\)\n\n\\begin{example}(Reduction with the linear explorer)\nLet the initial state be $\\subpoly= \\tupla{\\var_0 + \\var_2 + \\var_3 = 1, \\var_1 + \\var_2 - \\var_3 = 0;\\ \\var_0 \\in [0,2], \\var_1 \\in [0,3] }$, so that $\\delta_L = \\{ \\{ \\var_0, \\var_1\\},$ $\\{ \\var_1, \\var_2\\},$ $ \\{ \\var_2, \\var_3 \\},$ $\\{\\var_3, \\var_0 \\}\\}$.\nThe reduction $\\rho_{BE}(\\subpoly)$ contains the tightest bounds for $\\var_2, \\var_3$:\n\\(\n\\tupla{\\var_2 + \\frac{1}{2} \\cdot \\var_0 + \\frac{1}{2} \\cdot \\var_1 = 0, \\var_3 + \\frac{1}{2} \\cdot \\var_0 - \\frac{1}{2} \\cdot \\var_1 = 0;\n\\var_0\\in [0,2], \\var_1 \\in [0, 3], \\var_2 \\in[-\\frac{5}{2}, 0], \\var_3 \\in [-1, \\frac{3}{2}] }. \n\\)\n\\qed\n\\end{example}\nProperties of $\\delta_L$ are that: (i) each variable appears exactly $m$ times in the basis; (ii) it can be implemented efficiently as the basis change from $\\upzeta_i$ to $\\upzeta_{i+1}, i \\in [0, n-1]$ requires just one variable swap; (iii) in general it is not idempotent: it may be the case that $\\rho_L \\circ \\rho_L \\neq \\rho_L$; (iv) the result may depend on the initial order of variables, as shown by the next example.\n\n\n\\begin{example}[Incompleteness of the linear explorer]\nLet us consider an initial state $\\subpoly = \\tupla{ \\var_0 + \\var_1 + \\var_2 = 0, \\var_3 + \\var_1 = 0;\\ \\var_2 \\in [0,1], \\var_3 \\in [0,1]}$.\nThe reduced state $\\rho_{BE}(\\subpoly) = \\tupla{\\var_3 + \\var_1 = 0, \\var_2 + \\var_0 - \\var_1 = 0 ; \\var_1 \\in [-1,0], \\var_2 \\in [0,1], \\var_3 \\in [0,1] }$ does not contain the bound $\\var_0 \\in [-1, 1]$. \\qed\n\\end{example}\n\n\n\n\\subsubsection{Combinatorial Explorer ($\\delta_C$)} The combinatorial explorer $\\delta_C$ systematically visits all the bases.\nIt generates all possible combinations of $\\variable{m}$ variables trying to minimize the number of swaps at each basis change. \nIt is very costly, but it finds the best bounds for each variable: it visits all the bases, in particular the one where the optimum is reached.\nThe main advantage with respect to the Simplex is a better tolerance to numerical errors.\nHowever it is largely impractical because of (i) the huge cost; and (ii) the negligible gain of precision w.r.t. the use of $\\delta_L$ that it showed in our benchmark examples.\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%\n% Start of hints paper %\n%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\begin{figure}%[t]\n \\centering\n \\begin{subfloat}\n \\begin{minipage}{3.5cm}\n\\begin{verbatim}\nvoid AbsEl(int x) \n{ if(...) x =-1; \n else x = 1; \n\n assert x != 0; \n}\n\\end{verbatim}\n \\end{minipage}\n \\caption{}\n \\label{fig:gathering1}\n \\end{subfloat} \n \\qquad \n \\begin{subfloat}\n \\begin{minipage}{3.6cm}\n\\begin{verbatim}\nvoid Transfer(int x, y) \n{ assume 2 <= x <= 3;\n assume -1 <= y <= 1; \n \n int z = (x + y) * y;\n\n assert -2 <= z; \n}\n\\end{verbatim}\n \\end{minipage}\n\\caption{}\n\\label{fig:transfer}\n \\end{subfloat}\n% \\qquad\n% \\begin{subfloat}\n% \\begin{minipage}{4cm}\n% \\begin{verbatim}\n% void DomOp() \n% { int x = 0, y = 0;\n% while (...) \n% { if (...) { x++; y += 100; }\n% else if (...) \n% if (x >= 4) { x++; y++; } \n% }\n% (*) assert x <= y;\n% assert y <= 100 * x; \n% }\n% \\end{verbatim}\n% \\end{minipage}\n% \\caption{}\n% \\label{fig:gathering2}\n% \\end{subfloat}\n\\vspace{-0.2cm}\n\\caption{Examples of orthogonal losses of precision in abstract interpretations:\n(a) a convex domain cannot represent $\\code{x} \\neq 0$; and \n(b) a compositional transfer function does not infer the tightest\nlower bound for $\\code{z}$ \n% (c) the standard domain operations on Polyhedra are not precise enough to infer the loop invariant $\\code{x} \\leq \\code{y}$.\n}\n\\label{fig:gathering}\n\\vspace{-0.5cm}\n\\end{figure}\n\n\\section{Hints}\n\n% Journal version\nThe relative loss of precision of the join operator incited us to search some ways to recover precision on imprecise operators.\nWe discovered several of those, and they share some properties that led us to define a new concept called hints, which generalizes all of them as well as several known refining techniques.\n% End journal version\n\nHints are precision improving operators which can be used\nto systematically refine and improve the precision of domain\noperations in abstract interpretation.\nDomain operations are either \\emph{basic} domain operations (\\eg, \\cjoin\\\nor \\cmeet)\nor their compositions (\\eg, $\\lambda (\\ael{e}_0, \\ael{e}_1,\n\\ael{e}_2).\\ (\\ael{e}_0 \\cmeet \\ael{e}_1) \\cjoin (\\ael{e}_0 \\cmeet \\ael{e}_2)$).\n\n\\begin{definition}[Hint, \\hint{}]\n\\label{def:hints}\nLet $\\op \\in \\funzione{\\dom{C}^n}{\\dom{C}}$ be a concrete domain operation defined over a concrete domain \\tupla{\\dom{C}, \\less, \\join, \\meet}.\nLet $\\ael{\\op} \\in \\funzione{\\adom{A}^n}{\\adom{A}}$ be the abstract counterpart for \\op\\ defined over the abstract domain \\tupla{\\adom{A}, \\cless, \\cjoin, \\cmeet}.\nA hint $\\hint{\\ael{\\op}}\\in \\funzione{\\adom{A}^n}{\\adom{A}}$ is such that:\n\\[\n\\begin{aligned}\n\\hint{\\ael{\\op}}(\\ael{e}_0 \\dots \\ael{e}_{n-1}) \\cless \\ael{\\op}(\\ael{e}_0 \\dots \\ael{e}_{n-1}) & \\quad \\text{\\textrm{(Refinement)}} \\\\\n\\op(\\gamma( \\ael{e}_0) \\dots \\gamma(\\ael{e}_{n-1})) \\less \\gamma(\\hint{\\ael{\\op}}(\\ael{e}_0 \\dots \\ael{e}_{n-1})) & \\quad \\text(\\textrm{Soundness}).\n\\end{aligned}\n\\]\n\\end{definition}\nThe first condition states that $\\hint{\\ael{\\op}}$ is a more precise operations than $\\ael{\\op}$.\nThe second condition requires $\\hint{\\ael{\\op}}$ to be a sound approximation of \\op.\nAn important property of hints is that they can be designed separately and the combined to obtain a more precise hint.\n\\begin{lemma}[Hints combination]\nIf $\\hint{\\ael{\\op}}^1$ and $\\hint{\\ael{\\op}}^2$ are hints, then \n\\[\n\\hint{\\ael{\\op}}^\\cmeet(\\ael{e}_0 \\dots \\ael{e}_{n-1}) = \\hint{\\ael{\\op}}^1(\\ael{e}_0 \\dots \\ael{e}_{n-1}) \\cmeet \\hint{\\ael{\\op}}^2(\\ael{e}_0 \\dots \\ael{e}_{n-1})\\]\nis a hint.\n\\end{lemma}\n\\textit{Proof.}\n\\textit{(Refinement)} follows from the definition of \\cmeet.\n\\textit{(Soundness)} is because $\\op(\\gamma( \\ael{e}_0), \\dots \\gamma(\\ael{e}_{n-1}))$ $\\less \\gamma$ $(\\hint{\\ael{\\op}}^1$ \\allowbreak $(\\ael{e}_0, \\dots \\ael{e}_{n-1}))$ $\\meet \\gamma(\\hint{\\ael{\\op}}^2(\\ael{e}_0, \\dots \\ael{e}_{n-1})) \\less \\gamma(\\hint{\\ael{\\op}}^1(\\ael{e}_0, \\dots \\ael{e}_{n-1}) \\cmeet \\hint{\\ael{\\op}}^2(\\ael{e}_0, \\dots \\ael{e}_{n-1}))$.\n\\qed\n\nThe next theorem states that hints improve the precision of static analyses without introducing unsoundness and preserving termination:\n\n\\begin{theorem}[Refinement of the abstract semantics]\nLet $\\hint{\\widening}$ and $\\hint{\\cjoin}$ be two hints refining respectively the widening and the abstract union, and let $\\hint{\\widening}$ be a widening operator.\nLet \\asemRefined{\\cdot} be the abstract semantics obtained from \\asem{\\cdot} by replacing \\widening with $\\hint{\\widening}$ and \\cjoin\\ with $\\hint{\\cjoin}$.\nLet \\code{P} be a program.\nThen, $\\forall \\el{e}\\in \\parti{\\Sigma}. \\forall \\ael{e} \\in \\dom{A}.$ \n\\[\n\\begin{aligned}\n\\asemRefined{P}(\\ael{e}) \\cless \\asem{P}(\\ael{e}) & \\qquad \\text{\\textrm{(Refinement)}} \\\\\n\\el{e} \\subseteq \\gamma(\\ael{e}) \\Longrightarrow \\sem{P}(\\el{e}) \\subseteq \\gamma(\\asemRefined{P}(\\ael{e})) & \\qquad \\text{\\textrm{(Soundness)}}.\n\\end{aligned}\n\\]\n\\end{theorem}\n\\textit{Proof sketch.}\nThe cases to consider are those for the conditional and the while loop.\nThe conditional can be proven by structural induction.\nThe while loop by instantiating the abstract fixpoint transfer theorem of~\\cite{CousotCousot92-1}.\n\\qed\n\n% \\sopra\\sopra\n\\subsection{Syntactic hints}\n\\label{sec:Syntactichints}\nSyntactic hints use some part of the program text to refine the operations of the abstract domain.\nThey exploit user annotations to preserve as much information as possible in gathering operations (user-provided hints), and systematically improve the widening heuristics to find tighter loop invariants (thresholds hints).\n\n% \\vspace{-0.3cm}\n\n\\subsubsection{User-provided hints}\n\\begin{figure}%[t]\n\n\\small\n{\n\\[\n\\begin{array}{rcl}\n\\mathsf{pred}(\\code{skip};) &=& \\emptyset \\\\ \n\\mathsf{pred}(\\code{x = E};) &=& \\emptyset \\\\ \n\\mathsf{pred}(\\code{assert}\\ \\code{B};) &=& \\mathsf{atomize}(\\code{B}) \\\\\n\\mathsf{pred}(\\code{assume}\\ \\code{B};) &=& \\mathsf{atomize}(\\code{B}) \\\\\n\\mathsf{pred}(\\code{C\\ C'}) & = & \\mathsf{pred}(\\code{C}) \\cup \\mathsf{pred}(\\code{C'}) \\\\\n\\mathsf{pred}(\\If(\\code{B})~ \\{ \\code{C} \\} \\Else~\\{ \\code{C'} \\}) & = & \\mathsf{atomize}(\\code{B}) \\cup \\mathsf{pred}(\\code{C}) \\cup \\mathsf{pred}(\\code{C'}) \\\\ \n\\mathsf{pred}(\\While(\\code{B})~\\{\\code{C}\\}) & = & \\mathsf{atomize}(\\code{B}) \\cup \\mathsf{pred}(\\code{C}) \n\\end{array}\n\\]\n\\[\n\\begin{array}{rcl}\n\\mathsf{atomize}(\\code{B}_1 \\wedge\\code{B}_2)&=& \\mathsf{atomize}(\\code{B}_1) \\cup \\mathsf{atomize}(\\code{B}_2) \\\\\n\\mathsf{atomize}(\\code{B}_1 \\vee \\code{B}_2) &=& \\mathsf{atomize}(\\code{B}_1) \\cup \\mathsf{atomize}(\\code{B}_2) \\\\\n\\mathsf{atomize}(\\code{B}) &=& \\{ \\code{B} \\} \\qquad \\text{otherwise}.\n\\end{array}\n\\]\n}\n\n\\caption{The functions $\\mathsf{pred}$ and $\\mathsf{atomize}$ collect the atomic predicates in statements and Boolean expressions.}\n\\label{fig:pred}\n\\end{figure}\nThey are the easiest, and probably cheapest form of hints.\nFirst, we collect all the predicates appearing as assertions or as guards.\nThen, the gathering operations are refined by explicitly checking for each collected predicate $\\code{B}$, if it holds for \\emph{all} the operands.\nIf this is the case, $\\code{B}$ is added to the result.\nThe predicate seeker $\\mathsf{pred} \\in \\funzione{\\Stm}{\\parti{\\BExp}}$ is defined in Fig.~\\ref{fig:pred}.\nUser provided hints do not affect the termination of the widening as we can only add finitely many new predicates.\n\n\n\\begin{lemma}[User-provided hints]\n\n\nLet $\\diamond \\in \\{ \\cjoin, \\widening\\}$, and let \\code{P} be a program. \nThen: (i) $\\hint{\\diamond}^{\\mathsf{pred}}$ defined below is a hint;\nand (ii) $\\hint{\\widening}^{\\mathsf{pred}}$ is a widening operator.\n\n\n\\begin{small}\n\\[\n\\begin{array}{rcl}\n\\hint{\\diamond}^{\\mathsf{pred}}(\\ael{e}_0, \\ael{e}_1) &=&\n\\mathrm{let}\\ S = \\{ \\code{B} \\!\\in\\! \\mathsf{pred}(\\code{P}) \\mid\n\\dom{A}.\\checkif(\\code{B}, \\ael{e}_0) = \\mathit{true} \\\\\n& & \\phantom{\\mathrm{let}\\ S = \\{ \\code{B} \\!\\in\\! \\mathsf{pred}(\\code{P}) \\mid}\\wedge \\dom{A}.\\checkif(\\code{B}, \\ael{e}_1) = \\mathit{true} \\} \\\\\n& & \\mathrm{in}\\ \\dom{A}.\\guard(\\bigwedge_{\\code{B} \\in S} \\code{B}, \\diamond(\\ael{e}_0, \\ael{e}_1)).\n\\end{array}\n\\]\n\\end{small}\n\\end{lemma}\n\\textit{Proof sketch.}\nNote that (\\ref{for:soundnesstest}) implies that $\\adom{A}.\\atest(\\code{b1} \\wedge \\code{b2}, \\ael{e}) \\cless \\adom{A}.\\atest(\\code{b1}, \\ael{e})$, which is enough to prove \\textit{(Refinement)}.\nThe soundness condition (\\ref{for:soundnesscheck}) of $\\checkif$ guarantees that no inconsistent predicate is added to the result, implying \\textit{(Soundness)}.\n\\qed\n\n\\begin{figure}\n\\begin{verbatim}\nvoid DomOp() \n{ int x = 0, y = 0;\n while (...) \n { if (...) { x++; y += 100; }\n else if (...) \n if (x >= 4) { x++; y++; } \n }\n (*) assert x <= y;\n assert y <= 100 * x; \n}\n\\end{verbatim}\n\\caption{Example requiring user-provided hints}\n\\label{fig:userhints}\n\\end{figure}\n\n\\begin{example}[Refined \\SubPoly\\ operations] \nIn example of Fig.~\\ref{fig:userhints}, $\\mathsf{pred}(\\code{DomOp}) = \\{ \\code{x} \\leq \\code{y}, 4 \\leq \\code{x}, \\code{y} \\leq 100 \\cdot \\code{x} \\}$.\nThe refined domain operations keep the predicate $\\code{x} \\leq \\code{y}$, which is stable among loop iterations, and hence is a loop invariant. \\qed\n\\end{example}\n\n%\\Fsubsubsection{Discussion}\n\nWe found user-provided hints very useful in \\Clousot, our abstract interpretation based static analyzer for \\NET.\n\\Clousot\\ analyzes methods in isolation, and supports assume/guarantee\nreasoning (``contracts'' ~\\cite{meyer97}) via executable annotations~\\cite{FoxtrotClousot}.\nPrecision in propagating and checking program annotations is crucial to provide a satisfactory user experience.\nUser-provided hints help to reach this goal as the analyzer makes sure that at each joint point no user annotation is lost, if it is implied by the incoming abstract states.\nThey make the analyzer more robust w.r.t. incompleteness of $\\cjoin$ or a buggy implementation which may cause $\\cjoin$ to return a more abstract element than the one predicted by the theory.\nThe downside is that user-provided hints are syntactically based:\n\\begin{example}[Fragility of user-provided hints]\n\\label{ex:syntactic}\nLet us consider again the code in Fig.~\\ref{fig:userhints}.\nIf we replace the assertion at $\\mathtt{(*)}$ with \\code{if\\ 10 <= x \\ then\\ assert\\ 5 <= y }, then $\\mathsf{pred}(\\code{DomOp}) = \\{ 10 \\leq \\code{x} , 5 \\leq \\code{y} \\}$, so that $\\hint{\\widening_{\\Poly}}^{\\mathsf{pred}}$ cannot figure out that $\\code{x} \\leq \\code{y}$, and hence the analyzer cannot prove that the assertion is valid.\nSemantic hints (Sect.~\\ref{sec:Templatehints}) will fix it. \\qed\n\\end{example}\n\n\\subsubsection{Thresholds hints}\nWidening with threshold has been introduced in~\\cite{BlanchetCousotEtAl03} to improve the precision of standard widenings over non-relational or weakly relational domains.\nRoughly, the idea of a widening with thresholds is to stage the extrapolation process, so that before projecting a bound to the infinity, values from a set $T$ are considered as candidate bounds.\nThe set $T$ can be either provided by the user or it can be extracted from the program text.\nThe widening with thresholds is just another form of hint.\nLet $\\ael{e}_0$ and $\\ael{e}_1$ be abstract states belonging to some numerical abstract domain.\nWithout loss of generality we can assume that the basic facts in $\\ael{e}_0, \\ael{e}_1$ are in the form $\\code{p} \\leq k$, where \\code{p} is some polynomial.\nFor instance $\\code{x} \\in [-2, 4]$ is equivalent to $\\{ -\\code{x} \\leq 2, \\code{x} \\leq 4 \\}$.\nThe standard widening preserves the linear forms with stable upper bounds:\n%\\begin{small}\n\\(\n\\widening (\\ael{e}_0,\\ael{e}_1) = \\{ \\code{p} \\leq k \\mid \\code{p} \\leq k_0\\in \\ael{e}_0, \\code{p} \\leq k_1\\in \\ael{e}_1, k = \\text{if } k_1 > k_0 \\text{ then} +\\infty \\text{ else } k_0\\}.\n\\)\n%\\end{small}\n%\\sopra\n%\\noindent \nGiven a finite set of values \\code{T}, threshold hints refine the standard widening by:\n\n% \\sopra\n\\begin{small}\n \\begin{align*}\n \\hint{\\widening}^T(\\ael{e}_0,\\ael{e}_1) = \\{ \\code{p} \\leq k \\mid \\code{p} & \\leq k_0\\in \\ael{e}_0, \\code{p} \\leq k_1\\in \\ael{e}_1, \\\\\n & k = \\text{if } k_1 > k_0 \\text{ then } \\\\\n & \\qquad\\mathrm{min}\\{ t \\in T \\cup \\{ +\\infty \\} \\mid k_1 \\leq t \\} \\\\\n & \\qquad \\text{ else } k_0\\}.\n \\end{align*}\n\\end{small}\n%The next lemma states that $\\hint{\\widening}^T$ refines the standard widening, and it does not compromise the termination nor the soundness of the analysis:\n\\begin{lemma}\n$\\hint{\\widening}^T$ is: (i) a hint; and (ii) a widening.\n\\end{lemma}\n\\textit{Proof sketch.}\n\\textit{Refinement} and \\textit{Soundness} are a direct consequence of definition of $\\hint{\\widening}^T$.\nTermination follows from the fact that $T$ is finite.\n\\qed\n\n\n\\begin{figure}%[t]\n\\centering\n\\begin{subfloat}\n \\begin{minipage}{3cm}\n\\begin{verbatim}\nvoid LessThan() {\n int x = 0;\n while (x < 1000) {\n x++;\n }\n}\n\\end{verbatim}\n \\end{minipage}\n \\caption{Narrowing}\n \\label{fig:tresholds1}\n\\end{subfloat} \n\\qquad \n\\begin{subfloat}\n \\begin{minipage}{2.5cm}\n\\begin{verbatim}\nvoid NotEq() {\n int x = 0;\n while (x != 1000) {\n x++;\n }\n}\n\\end{verbatim}\n \\end{minipage}\n \\caption{Thresholds}\n \\label{fig:tresholds2}\n\\end{subfloat}\n\\vspace{-0.2cm}\n\\caption{Two programs to be analyzed with Intervals.\n The iterations with widening infer the loop invariant $\\code{x} \\in [0,+\\infty]$.\n In the first case, the narrowing step refines the loop invariant to $\\code{x} \\in [0, 1000]$.\n In the second case, the narrowing fails to refine it.}\n\\label{fig:tresholds}\n%\\vspace{-0.2cm}\n\\end{figure}\n\n\\begin{example}[Widening with thresholds]\nLet us consider the code snippets in Fig.~\\ref{fig:tresholds} to be analyzed with Intervals.\nIn the both cases, the (post-)fixpoint is reached after the first iteration $\\widening([0,0], [1,1]) = [0, +\\infty]$.\nIn the first case, the invariant can be improved by a narrowing step to $ \\narrowing([0, +\\infty], [-\\infty, 1000])= [0, 1000]$ (see \\cite{CousotCousot77} for a definition of narrowing of \\Intervals).\nIn the second case, the narrowing is of no help as $\\narrowing([0, +\\infty], $ $\\cjoin([-\\infty, 1000],$ $[1002, +\\infty]))$ $= [0, +\\infty]$.\nA widening with Thresholds $T = \\{ 1000 \\}$ helps discovering the tightest loop invariant for both examples in one step as $\\hint{\\widening}^T([0,0],[1,1]) = [0, 1000]$.\n\\qed\n\\end{example}\nPlease note that user-provided hints are of no help in the previous example, as $\\mathsf{pred}(\\code{NotEq}) = \\{ \\code{x} \\neq 1000\\}$ does not hold for all the operands of the widening. \n\nWe are left with problem of generating the set $T$ of thresholds.\nA common practice in static analyzers is to have $T = \\{ -1, 0, 1\\}$. \nA better solution is to have the user provide $T$, left as parameter of the analyzer. \nThis is the approach of~\\cite{BlanchetCousotEtAl03}.\nIn \\Clousot\\ we chose a slightly different solution, which consists in populating $T$ with the constants appearing in the program text.\nConstants are fetched from the source using a function $\\mathsf{const} \\in\n\\funzione{\\Stm}{\\parti{\\code{int}}}$ defined as one may expect.\nWe found $\\hint{\\widening}^{\\mathsf{const}}$ very satisfactory.\nThe hint $\\hint{\\widening}^{\\mathsf{const}}$: (i) helps inferring precise \\emph{numerical} loop invariants without requiring the extra iteration steps required for applying the narrowing; and (ii) improves the precision of the analysis of code involving disequalities, \\eg, Fig.~\\ref{fig:tresholds}(b).\nA drawback of threshold hints is that the set $T$ may grow too large, slowing down the convergence of the fixpoint iterations.\nIn \\Clousot, we infer thresholds on a per-method basis, which helps maintaining the cardinality of $T$ quite small.\n\n\n\\subsection{Semantic hints}\nSemantic hints provide a more refined yet more expensive form of operator refinement.\nFor instance, they exploit information in the abstract states to materialize constraints that were implied by the operands (saturation hints, die-hard hints and template hints) or they iterate the application of operators to get a more precise abstract state (reductive hints).\n\n\\subsubsection{Saturation hints}\nA common way to design abstract interpreters is to build the abstract domain as a composition of basic abstract domains, which interact through a well-defined interface~\\cite{CousotEtAl06,ChangLeino05,GulwaniEtAl08}.\nFormally, given two abstract domains $\\adom{A}_0$, $\\adom{A}_{1}$, the Cartesian product $\\adom{A}^\\times = \\adom{A}_0 \\times \\adom{A}_{1}$ is still an abstract domain, whose operations are defined as the point-wise extension of those over $\\adom{A}_0$ and $\\adom{A}_{1}$.\nLet $\\ael{\\op}_i \\in \\funzione{\\adom{A}_i^n}{\\adom{A}_i}$, $i \\in \\{ 0, 1\\}$, then \n\\[\n\\ael{\\op}^\\times\\!((\\ael{e}^0_0, \\ael{e}^0_1) \\!\\dots\\! (\\ael{e}^{n\\!-\\!1}_0, \\ael{e}^{n\\!-\\!1}_1)) \\!=\\! (\\ael{\\op}_0(\\ael{e}^0_0 \\!\\dots\\! \\ael{e}^{n\\!-\\!1}_0), \\ael{\\op}_1(\\ael{e}^{0}_1 \\!\\dots\\! \\ael{e}^{n\\!-\\!1}_1))\n\\]\nThe Cartesian product enables the modular design (and refinement) of static analyses.\nHowever, a naive design which does not consider the flow of information between the abstract elements may lead to imprecise analyses, as illustrated by the following example.\n\n\\begin{example}[Cartesian join]\n\\label{ex:cartesian}\nLet us consider the abstract domain $\\adom{Z} = \\Intervals \\times \\LT$, where $\\LT = \\funzione{\\Var}{\\parti{\\Var}}$ is an abstract domain capturing the \\emph{``less than''} relation between \\emph{variables}.\nFor instance, $\\code{x} < \\code{y} \\wedge \\code{x} < \\code{z}$ is represented in \\LT\\ by $[ \\code{x} \\mapsto \\{ \\code{y}, \\code{z}\\}]$.\nThe domain operations are defined as one may expect~\\cite{LogozzoMaf08}.\nLet $\\ael{z}_0 = ([\\code{x} \\mapsto [-\\infty, 0], \\code{y} \\mapsto [1, +\\infty]], \\emptyfun )$ and $\\ael{z}_1 = (\\emptyfun, [\\code{x} \\mapsto \\{ \\code{y}\\}] )$ be two elements of \\adom{Z} (\\emptyfun\\ denotes the empty map).\nThen the Cartesian join loses all the information: $\\cjoin^\\times(\\ael{z}_0, \\ael{z}_1) = (\\emptyfun, \\emptyfun )$. \\qed\n\\end{example}\n\nA common solution is: (i) saturate the operands; and (ii) apply the operation pairwise.\nThe saturation materializes all the constraints implicitly expressed\nby the product abstract state.\nLet $\\rho \\in \\funzione{\\adom{A}^\\times}{\\adom{A}^\\times}$ be a saturation (\\emph{a.k.a.} closure) procedure.\nThen the next lemma provides a systematic way to refine an operator $\\ael{\\op}^\\times$.\n\n\\begin{lemma}\nThe operator $\\hint{\\op^\\times}^{\\rho}$ below is a hint.\n\\begin{small}\n \\[\n \\begin{split}\n &\\hint{\\ael{\\op}^\\times}^{\\rho}((\\ael{e}^0_0, \\ael{e}^0_1) \\dots\n (\\ael{e}^{n-1}_0, \\ael{e}^{n-1}_1)) = \\\\ \n& \\quad \\mathrm{let}\\ \\ael{r}^i\n = \\rho(\\ael{e}_0^i, \\ael{e}_1^i)\\ \\mathrm{for}\\ i \\in 0 \\dots n-1\\ \n \\mathrm{in}\\ \\ael{\\op}^\\times(\\ael{r}^0 \\dots \\ael{r}^{n-1}).\n \\end{split}\n \\]\n\\end{small}\n\\end{lemma}\n\n\n\\begin{example}[Cartesian join, continued]\nThe saturation of $\\ael{z}_0$ materializes the constraint $\\code{x} < \\code{y}$ : $\\ael{r}_0 = ([\\code{x} \\mapsto [-\\infty, 0], \\code{y} \\mapsto [1, +\\infty], [\\code{x} \\mapsto \\{ \\code{y}\\}] )$, and it leaves $\\ael{z}_1$ unchanged.\nThe constraint $\\code{x} < \\code{y}$ is now present in both the operands, and it is retained by the pairwise join. \\qed\n\\end{example}\n\nIt is worth noting that in general $\\hint{\\widening}^{\\rho}$ does not\nguarantee the convergence of the iterations, as the saturation\nprocedure may re-introduce constraints which were abstracted away from\nthe widening (\\eg, Fig.~10 of~\\cite{Mine01-2}).\n\nSaturation hints can provide very precise operations for Cartesian abstract interpretations:\nThey allow the analysis to get additional precision by combining the information present in different abstract domains.\nThe quality of the result depends on the quality of the saturation procedure.\nThe main drawbacks of saturation hints are that: (i) the iteration convergence is not ensured, so that extra care should be put in the design of the widening; (ii) the systematic application of saturation may cause a dramatic slow-down of the analysis.\nIn our experience with the combination of domains implemented in \\Clousot, we found that the slow-down introduced by saturation hints was too high to be practical.\nDie-hard hints, introduced in the next section, are a better solution to achieve precision without giving up scalability.\n\n\\subsubsection{Die-hard hints}\nThese hints are based on the observation that often the constraints that one wants to keep at a gathering point often appears explicitly in one of the operands.\nFor instance in Ex.~\\ref{ex:cartesian} the constraint $\\code{x} < \\code{y}$ is explicit in $\\ael{z}_1$, and implicit in $\\ael{z}_0$ (as $\\code{x} \\leq 0 \\wedge 1 \\leq \\code{y} \\Longrightarrow \\code{x} < \\code{y}$).\nTherefore $\\code{x} < \\code{y}$ holds for all the operands of the join so it is sound to add it to its result.\nDie-hard hints generalize and formalize it.\nThey work in three steps: (i) apply the gathering operation, call the result \\ael{r}; (ii) collect the constraints $C$ that are explicit in one of the operands, but are neither present nor implied by \\ael{r}; and (iii) add to \\ael{r} all the constraints in $C$ which are implied by \\emph{all} the operands.\nFormally:\n\n% \\sopra\n\\begin{small}\n \\[\n \\begin{split}\n \\hint{(\\ael{\\op}, I)}^{d}(\\ael{e}_0, \\ael{e}_1) = \\ & \\mathrm{let}\\ \\ael{r} = \\ael{\\op}(\\ael{e}_0, \\ael{e}_1),\\\\\n & C = \\cup_{i \\in I }\\{ \\kappa \\in \\ael{e}_i \\mid \\adom{A}.\\checkif(\\kappa, \\ael{r}) = \\mathit{top} \\} \\\\\n & \\mathrm{let}\\ S = \\{ \\kappa \\in C \\mid \\adom{A}.\\checkif(\\kappa, \\ael{e}_0) = \\\\\n & \\phantom{ S = \\{ \\kappa \\in C \\mid} \\quad \\adom{A}.\\checkif(\\kappa, \\ael{e}_1) = \\mathit{true} \\} \\\\\n& \\mathrm{in}\\ \\adom{A}.\\atest\\left(\\wedge_{\\kappa \\in S} \\kappa, \\ael{r}\\right).\n\\end{split}\n\\]\n\\end{small}\n\\sopra\n\nIn defining the die-hard hint for \\widening, one should pay attention\nto avoid loops which re-introduce a constraint that as been dropped by\nthe widening. \nOne way to do it is to have an asymmetric hint, which restricts $C$\nonly to the first operand (\\eg, the candidate invariant):\n\\begin{lemma}\n$\\hint{(\\cjoin, \\{ 0, 1 \\})}^{d}$ and $\\hint{(\\widening, \\{ 0 \\})\n}^{d}$ are hints and $\\hint{(\\widening, \\{0\\})}^{d}$ is a widening.\n\\end{lemma}\n\n\n\\subsubsection{Computed hints}\n\\label{sec:Templatehints}\nHints can be inferred from the abstract states themselves. \nBy looking at some properties of the elements involved in the\noperation, one can try to guess useful hints. \n\n\\begin{lemma}[Computed hints]\nLet $\\ael{e}_0, \\ael{e}_1 \\in \\adom{A}$, $\\hintcomp \\in \\funzione{\\dom{A} \\times \\dom{A}}{\\adom{A}}$\na function which returns a set of likely bounds of $\\ael{e}_0 \\cjoin \\ael{e}_1$. \nThen $\\hint{\\cjoin}^{\\hintcomp}$ below is a hint.\n\n% \\sopra\n\\begin{small}\n \\[\n \\begin{array}{rcl}\n \\hint{\\cjoin}^{\\hintcomp}(\\ael{e}_0, \\ael{e}_1) &=& \\mathrm{let}\\ S =\n \\{ \\code{B} \\in \\hintcomp(\\ael{e}_0, \\ael{e}_1) \\mid\n \\dom{A}.\\checkif(\\code{B}, \\ael{e}_0) =\\mathit{true} \\\\\n & & \\qquad \\qquad \\qquad \\wedge\\ \\dom{A}.\\checkif(\\code{B}, \\ael{e}_1) = \\mathit{true} \\} \\\\ \n & & \\mathrm{in}\\ \\dom{A}.\\guard(\\bigwedge_{\\code{B} \\in S} \\code{B}, \\ael{e}_0 \\cjoin \\ael{e}_1).\n \\end{array}\n \\]\n\\end{small}\n\\end{lemma}\n\nComputed hints are useful when the abstract join \\cjoin\\ is not optimal.\nOtherwise, $\\hint{\\cjoin}^{\\hintcomp}$ is no more precise than \\ajoin.\nFor instance, in a Galois connections-based abstract interpretation,\n\\ajoin\\ is optimal, in that it returns the most precise\nabstract element overapproximating the concrete union.\nAs a consequence, no further information can be extracted from the operands.\nIt is worth noting that in general\n$\\hint{\\widening}^{\\hintcomp}$ is not a widening.\nHowever, one can extend the arguments of the previous section to define\nan asymmetric hint $\\hint{\\widening}^{\\hintcomp}$.\n\n% Journal version\nThe next two kinds of hints (template hints and 2D-convex hull hints) are examples of computed hints.\n\n% Journal version : should this be a subsubsubsection ?\n\\subsubsection{Template hints}\nLet $\\adom{A}.\\arange \\in\n\\funzione{\\Exp \\times \\adom{A}}{\\Intervals}$ be a function that returns\nthe range for an expression in some abstract state, \\eg,\nit satisfies:\n \\(\n \\forall \\code{E}.\\ \\forall \\ael{e} \\in \\adom{A}.\\\n \\adom{A}.\\arange(\\code{E}, \\ael{e}) = [l, u] \\Longrightarrow \\forall \\sigma \\in\n \\gamma(\\ael{e}).\\ l \\leq \\semantica{E}{\\code{E}}(\\sigma) \\leq u.\n \\)\nIf $\\adom{A}.\\arange(\\code{E}, \\ael{e}_i) = [l_i, u_i]$ for $i \\in \\{\n0, 1 \\}$, then $\\gamma(\\join_{\\Intervals}([l_0, u_0], [l_1, u_1]))$ is an upper\nbound for \\code{E} in $\\cup(\\gamma(\\ael{e}_0), \\gamma(\\ael{e}_1))$.\nAs a consequence given a set $P$ of polynomial forms, one can design\nthe guessing function $\\hintcomp^{P}$:\n\n% \\sopra\n\\begin{small}\n\\[\n\\begin{split}\n\\hintcomp^{P}(\\ael{e}_0, \\ael{e}_1) & = \\{ l \\leq \\code{p} \\leq u \\mid\n\\code{p} \\in P \\wedge [l, u] \\\\\n& = \\join_{\\Intervals}(\\adom{A}.\\arange(\\code{p}, \\ael{e}_0),\n\\adom{A}.\\arange(\\code{p}, \\ael{e}_1) \\}.\n\\end{split}\n\\] \n\\end{small}\n\n% \\sopra\nThe main difference between $\\hint{\\cjoin}^{\\hintcomp^{P}}$ and\nsyntactic hints is that the bounds for the polynomials in $P$ are \\emph{semantic},\nas they are inferred from the abstract states and not from the\nprogram text.\nFor instance, computed hints infer the right invariant in\nEx.~\\ref{ex:syntactic} using the set of templates $\\mathit{Oct} \\equiv \\{ \\code{x}_0 - \\code{x}_1\n\\mid \\code{x}_0, \\code{x}_1\\ \\text{are}$ $\\text{program}\\\n\\text{variables} \\}$.\nIn general, template hints with $\\mathit{Oct}$ refine \\SubPoly\\\nso to make it as precise as \\Octagons.\n\n% Journal version : should this be a subsubsubsection ?\n\\subsubsection{2D-Convex Hull hints}\nNew linear inequalities can be discovered at join points using the convex hull\nalgorithm.\nFor instance, the standard join on \\Polyhedra\\ is defined in that way~\\cite{CousotHalbwachs78}.\nHowever the convex hull algorithm requires an expensive conversion\nfrom a tableau of linear constraints to a set of vertices and\ngenerators, which causes the analysis time to blow up.\nA possible solution is to consider a planar convex hull, which \ncomputes possible linear relations between \\emph{pairs} of variables by: (i) projecting\nthe \\Intervals part of the abstract states on all the two-dimensional planes; and (ii) computing the\nplanar convex hull (of two rectangles, a particularly simple case) on those planes. \nPlanar convex hull, combined with a smart representation of the\nabstract elements allows us to automatically discover complex invariants\nwithout giving up performances.\n\n\n\\begin{example}[2D-Convex hull]\nLet us consider the code in Fig.~\\ref{fig:2dhints}\nfrom~\\cite{CousotHalbwachs78}.\nAt a price of exponential complexity, \\Poly\\ can infer the correct loop invariant, and prove the assertion\ncorrect.\n\\Subpoly\\ refined with 2D-Convex hull hints can prove the assertion,\nyet keeping a worst-case polynomial complexity~\\cite{LavironLogozzo09}. \\qed\n\\end{example}\n\n\\begin{figure}%[t]\n\\centering\n\\begin{verbatim}\nvoid Foo() {\n int i = 2, j = 0;\n while (...) {\n if (...) { i = i + 4; }\n else { i = i + 2; j++; } }\n assert 2 <= i - 2 * j; }\n\\end{verbatim}\n\\vspace{-2pt}\n\\caption{Example requiring the use of 2D-convex hull hints to infer the right invariant, expressed by the assertion}\n\\label{fig:2dhints}\n\\vspace{-3pt}\n\\end{figure}\n\n\n\\subsubsection{Reductive hints}\nIntuitively, one way to improve the precision of a unary operator is to iterate its application~\\cite{Granger92}.\nHowever, an unconditional iteration may be source of unsoundness, as shown by the following example.\n\\begin{example}[Unsoundness of unconditional iterations]\nLet $- \\in \\funzione{\\Intervals}{\\Intervals}$ be the operator which\napplies the unary minus to an interval.\nIn general, $\\forall n \\in \\mathbb{N}.\\ \\ael{e} = -^{2n}(\\ael{e}) \\neq\n-^{2n+1}(\\ael{e})$ so that the iterations are unstable. \\qed\n\\end{example}\nWe say that a function $f$ is \\emph{reductive} if $\\forall x. f(x) \\less x$; and \\emph{closing} if it is reductive and $\\forall x. f(f(x)) = f(x)$.\n\n\\\n\\begin{lemma}[Reductive hints]\n\\label{lem:reductive}\nLet $\\op \\in \\funzione{\\dom{C}}{\\dom{C}}$ be a unary operator and $\\ael{\\op} \\in \\funzione{\\adom{A}}{\\adom{A}}$ its abstract counterpart.\nLet $\\op$ be closing, $\\ael{\\op}$ be reductive, and $n \\geq 0$.\nThen $\\hint{\\ael{\\op}}(\\ael{e}) =\\ael{\\op}^{n}(\\ael{e})$ is a hint.\n\\end{lemma}\n\\textit{Proof. (Sketch)}\n\\textit{(Refinement)} follows from the definition.\nTo prove \\textit{(Soundness)}, it is enough to prove that $\\op(\\gamma(\\ael{e})) \\subseteq \\gamma(\\ael{\\op}^2(\\ael{e}))$.\nIt holds as $\\op(\\gamma(\\ael{e})) = \\op^2(\\gamma(\\ael{e})) \\subseteq \\op(\\gamma(\\ael{\\op}(\\ael{e}))) \\subseteq \\gamma(\\ael{\\op}^2(\\ael{e}))$.\n\\qed\n\nThe main application of reductive hints is to improve the precision in handling the guards in non-relational abstract domains.\nGiven a Boolean guard \\code{B} and an abstract domain \\adom{A}, $\\psi \\equiv \\lambda{\\ael{e}}.\\ \\adom{A}.\\atest(\\code{B}, \\ael{e})$ is an abstract operator which satisfies the hypotheses of Lemma~\\ref{lem:reductive}.\nAbstract compilation can be used to express $\\psi$ in terms of domain operations, their compositions and state update.\nLemma~\\ref{lem:reductive} justifies the use of local fixpoint iterations to refine the result of the analysis.\n\n\\begin{example}\nLet us consider the following Boolean expression :\n\\[\n \\code{b1} == \\code{b2} \\wedge \\code{b2} == \\code{b3}\n\\]\nIts abstract compilation in an abstract domain \\funzione{\\code{Var}}{\\{ \\mathsf{true}, \\mathsf{false}, \\top, \\bottom \\}} is :\n\\[\n \\begin{array}{rl}\n \\psi \\equiv & \\lambda \\el{b}. (\\el{b}[\\code{b1},\\code{b2} \\mapsto \\el{b}(\\code{b1}) \\wedge \\el{b}(\\code{b2})]) \\\\\n & \\quad \\dot\\wedge (\\el{b}[\\code{b2},\\code{b3} \\mapsto \\el{b}(\\code{b2}) \\wedge \\el{b}(\\code{b3})]) \\\\\n \\end{array}\n\\]\nwhere $\\dot\\wedge$ denotes the pointwise extension of $\\wedge$. \nIn an initial abstract state $\\el{b_0} = [\\code{b1}, \\code{b2} \\mapsto \\top; \\code{b3} \\mapsto \\mathsf{true}]$, \n$\\psi(\\el{b}_0) = [ \\code{b1} \\mapsto \\top; \\code{b2}, \\code{b3} \\mapsto \\mathsf{true} ]$, and $\\psi^2(\\el{b}_0) = [ \\code{b1}, \\code{b2}, \\code{b3} \\mapsto \\mathsf{true}] = \\psi^n(\\el{b}_0)$, $n \\geq 2$. \\qed \n\\end{example}\n\n%%%%%%%%%%%%%%%%%%%%%%%%\n% End of hints paper %\n%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\section{Refinements for Subpolyhedra}\n\n\\subsection{Precision improvement: Hints}\n\n% Journal version\nMany of the hints presented above can be used to improve the precision of \\Subpoly.\nUser-provided hints provide a simple but efficient way to deal with programs that are not too complicated,\nand the intervals part of \\Subpoly\\ can of course use the threshold hints.\n\nSaturation hints are impractical for \\Subpoly, but die-hard hints are very useful; indeed, step 3 of the join algorithm (\\ref{alg:join}) can be seen as a particular case of die-hard hints, with the difference that the constraints marked as deleted in the join of the linear equalities domain migth not have been actually present in the initial states, but have been introduced in place of an equivalent one by Karr's algorithm.\n\nBoth kinds of computed hints are useful, but in a different way : they can be used for tricky programs that require some complex reasoning, but in most cases the algorithm already returns a good enough result, and use of those hints only slows down the analysis.\nAs an example, template hints can be used to manually set the invariants to infer on a complicated program.\nThey can also be used to guarantee some minimal precision (e.g., at least the precision of octagons) if one can afford the extra time it costs.\n2D-convex hull hints are useful in the case of pointer access validation, to infer bounds with non-unary coefficients between pairs of variables.\n\nReductive hints can also be used on cases involving reduction, because our reduction is not idempotent; however, reduction is rather expensive and there is no guarantee of an actual gain of precision in this case, so we do not use it in practice. Instead, when precision matters, we use reduction with the combinatorial explorer, which does have guarantees on the precision of the result.\n% The inference power of \\Subpoly\\ can be increased using \\emph{hints}.\n% Hints are linear functionals associated with a subpolyhedra \\subpoly.\n% They represent some linear inequality that may hold in \\subpoly, but that it is not explicitly represented by a slack variable, or that it is not been checked to hold in \\subpoly\\ yet. \n% \n% Hints increase the precision of joins and widenings.\n% Let \\code{h} be an hint, let $\\subpoly_0$ and $\\subpoly_1$ two subpolyhedra, and let $\\ael{b} = \\semantica{}{h}(\\subpoly_0) \\join_\\Intervals \\semantica{}{h}(\\subpoly_1)$. \n% If $\\ael{b} \\neq \\top_\\Intervals$, then $\\code{h} \\in \\ael{b}$ holds in both $\\subpoly_0$ and $\\subpoly_1$, so that the constraint can be safely added to $\\subpoly_0 \\joinS \\subpoly_1$.\n% That helps recovering linear inequalities that may have been dropped by the Algorithm~\\ref{alg:join}.\n% The situation for widening is similar, with the main difference that the number of hints should be bounded, to ensure convergence.\n% Hints can be automatically generated during the analysis or they can be provided by the user in the form of annotations.\n% We have three ways to generate hints, inspired by existing solutions in the literature: program text, templates and planar convex hull.\n% They provide very powerful hints, but some of them may be expensive. \n% \n% \\Fsubsubsection{Program text hints} They introduce a new hint each time a guard or assume statement (user annotation) is encountered in the analysis. \n% This way, properties that are obvious when looking at the syntax of the program will be proved.\n% Also, every time a slack variable \\slackvar\\ is removed, \\slackvarinfo\\ is added to the hints. \n% This is useful in the realistic case when \\Subpoly\\ is used in conjunction with an heap analysis which may introduce unwanted renamings.\n% \n% \\Fsubsubsection{Template hints} They consider hints of fixed shape~\\cite{Sankaranarayanan05}. \n% For instance, hints in the form $\\code{x}_0 - \\code{x}_1$ guarantee a precision at least as good as difference bounds matrices~\\cite{ModelChecking,Mine01-1}, provided that the reduction is complete.\n% \n% \\Fsubsubsection{Planar convex hull hint} It materializes new hints by performing the planar convex hull of the subpolyhedra to join~\\cite{SimonKing02-2}.\n% First, it projects the interval components on every two-dimensional plane (there are a quadratic number of such planes).\n% Then performs the convex hull of the resulting pair of rectangles (in constant time, since the number of vertices is at most eight). \n% The resulting new linear constraints are a sound approximation by construction.\n% They can be safely added to the result of the join.\n\n% End journal version\n\n\\subsection{Speed Improvement: Simplification} \nThe simplification operator $\\sigma$ removes redundant information from an abstract element. \nIt is required neither for soundness nor completeness nor to improve the precision of the analysis (unlike $\\rho$), but it is cardinal to the implementation of scalable analyses.\nThe simplification $\\sigma$ of an element of \\Subpoly\\ $\\subpolyPair{}{}$ reduces the number of variables in \\ael{l}, which is the more expensive domain, without losing any precision.\nIt consists in the application of the following three rules:\n\n\\begin{enumerate}\n\\setlength{\\itemindent}{25pt}\n\\item[(Const)] If an equality $\\var = b$ is detected, \\\\\n $\\var$ is projected from $\\ael{l}$ and added to $\\ael{i}$; \n\\item[(Slack)] If a slack variable $\\slackvar$ does not appear in \\subpolyPair{}{}, \\\\\n then it should be removed; \n\\item[(Dep)] If $\\subpolyPair{}{}$ implies $\\slackvariable{0} + a \\cdot \\slackvariable{1} = b$, \\\\\n then one between $\\slackvariable{0}$ and $\\slackvariable{1}$ can be removed.\n\\end{enumerate}\n\n\n\\noindent The rationale behind (Const) is that constants are very expensive when represented in \\Karr\\ but very cheap if represented with \\Intervals;\n(Slack) performs a kind of garbage collection, by removing slack variables $\\beta$ which are in the domain of $\\subpolyPair{}{}$, but such that $\\beta$ does not appear in any of the constraints of \\ael{l} and $\\ael{i}(\\beta) = \\top_\\Intervals$; (Dep) is justified by the fact that after refining the intervals for both variables, removing one of the slack variables does not change the concretization of the abstract element.\n(Const) is useful when we introduce a new slack variable; (Slack) helps reducing the number of slack variables after joins; and (Dep) is applied as a pre-step of the reduction, to reduce the number of variables and hence make it faster.\n\n\\section{Experience}\n\\label{sect:Experience}\n\n\\begin{figure*}\n\\centering\n\\small\n\\begin{tabular}{@{}r | r r |r r r | r r r | c@{}}\n & & Bounds & \\multicolumn{3}{c|}{Simplex $\\rho_{LP}$} & \\multicolumn{3}{c|}{Linear Explorer $\\rho_{BE}$} & Max \\\\\nAssembly & Methods & Checked & Valid & \\% & Time & Valid & \\% & Time & Vars\\vspace{3pt} \\\\\n\\hline\n\\code{mscorlib.dll} & 18 084 & 17 181 & 14 432 & 84.00 & 73:48 (3) & 14 466 & 84.20 & 23:19 (0) & 373 \\\\\n\\code{System.dll} & 13 776 & 11 891 & 10 225 & 85.99 & 58:15 (2) & 10 427 & 87.69 & 14:45 (0) & 140 \\\\\n\\code{System.Web.dll} & 22 076 & 14 165 & 13 068 & 92.26 & 24:41 (0) & 13 078 & 92.33 & 6:33 (0) & 182 \\\\\n \\code{System.}\\phantom{ciaoc} & & & & & & & & &\\\\\n\\code{Design.dll} & 11 419& 10 519 & 10 119 & 96.20 & 26:07 (0) & 10 148 & 96.47 & 5:18 (0) & 73\\\\\n\\hline\nAverage & & & & 89.00 & & & 89.51 \\\\\n\\end{tabular}\n\\caption{The experimental results of checking array creation and accesses.\n \\Subpoly\\ is instantiated with two reductions $\\rho_{LP}$ and $\\rho_{BE}$. \nTime is expressed in minutes, the time-out per method is set to two minutes (in parentheses). \nThe last column reports the maximum number of variables related by an element of \\Subpoly.}\n\\label{fig:results}\n\\end{figure*}\n\nWe have implemented \\Subpoly\\ on the top of \\Clousot, our modular abstract interpretation-based static analyzer for \\NET. \n\\Clousot\\ directly analyzes MSIL, a bytecode target for more than seventy compilers (including C\\#, Managed C++, VB.NET, F\\#, \\dots).\nPrior to the numerical analysis \\Clousot\\ performs a heap analysis and an expression recovery analysis~\\cite{LogozzoMaf08-2}.\n\\Clousot\\ performs \\emph{intra-}procedural analysis and it supports assume-guarantee reasoning via \\Foxtrot\\ annotations~\\cite{FoxtrotClousot,FerraraLogozzoMaf08}.\n%\\Foxtrot\\ allows specifying contracts in \\NET\\ without requiring any language support (cf. Appendix~\\ref{sec:foxtrot}). \nContracts are expressed directly in the language as method calls and are persisted to MSIL using the normal compilation process of the source language (cf. Appendix~\\ref{sec:foxtrot}).\nClasses and methods are annotated with class invariants, preconditions and postconditions.\nPreconditions are asserted at call sites and assumed at the method entry point.\nPostconditions are assumed at call sites and asserted at the method exit point.\n\\Clousot\\ also checks the absence of specific errors, \\eg\\ out of bounds array accesses, null dereferences, buffer overruns, and divisions by zero.\n\nFigure ~\\ref{fig:results} summarizes our experience in analyzing array creations and accesses in four libraries shipped with \\NET.\nThe test machine is an ordinary 2.4Ghz dual core machine, running Windows Vista.\nThe assemblies are directly taken from the standard .NET directory of our PC.\nThe shipped versions of the assemblies do not contain contracts (We are actively working to annotate the \\NET\\ libraries). \nOn average, we were able to validate almost 89.5\\% of the proof obligations. \nWe manually inspected some of the warnings issued for \\code{mscorlib.dll}. \nMost of them are due to lack of contracts, \\eg\\ an array is accessed using a method parameter or the return value of some helper method.\nHowever, we also found real bugs (dead code and off-by-one). \nThat is remarkable considering that \\code{mscorlib.dll} has been tested \\emph{in extenso}.\nWe also tried \\Subpoly\\ on the examples of~\\cite{CousotHalbwachs78,SankaranarayananEtAl07,GulavaniEtAl08}, proving all of them.\n\n\\subsection{Reduction Algorithms}\nWe run the tests using the Simplex-based and the Linear explorer-based reduction algorithms.\nWe used the Simplex implementation shipped with the Microsoft Automatic Graph Layout tool, widely tested and optimized.\nThe results in Fig.~\\ref{fig:results} show that $\\rho_{LP}$ is significantly slower than $\\rho_{BE}$, and in particular the analysis of five methods was aborted as it reached the two minutes time-out.\nLarger time-outs did not help.\n\n\\Subpoly\\ with the reduction $\\rho_{LP}$ validates less accesses than $\\rho_{BE}$.\nTwo reasons for that.\nFirst, it is slower, so that the analysis of some methods is aborted and hence some proof obligations cannot be validated.\nSecond, our implementation of the Simplex uses floating point arithmetic which induces some loss of precision. \nIn particular we need to read back the result (a \\code{float}) into an interval of \\code{int}s containing it.\nIn general this may cause a loss of precision and even worse unsoundness.\nWe experienced both of them in our tests.\nFor instance the 39 ``missing'' proof obligations in \\code{System.Web.dll} and \\code{System.Design.dll} (validated using $\\rho_{BE}$, but not with $\\rho_{LP}$) \nare due to floating point imprecision in the Simplex.\nWe have considered replacing a floating point-based Simplex with one using exact rationals.\nHowever, the Simplex has the tendency to generate coefficients with large denominators.\nThe code we analyze contains many large constants which cause the Simplex to produce enormous denominators.\n\n\\Subpoly\\ with $\\rho_{BE}$ instantiated with the linear bases explorer perform very well in practice: it is extremely fast and precise.\nHowever, the result may depend on the variables order.\nA ``bad'' variable order may cause $\\rho_{BE}$ not to infer bounds tight enough.\nPossible solutions are: (i) to reduce the number of variables using $\\sigma$ (less bases to explore);\n(ii) to mark variables which can be safely kept in the basis at all times: In the best case, only one basis needs to be explored. \nIn the general case, it still makes the reduction more precise because the bases explored are more likely to give bounds on the variables.\n\n\\subsection{Max Variables} \nIt is worth noting, that even if \\Clousot\\ performs an intra-procedural analysis, the methods we analyze may be very complex, and they may require tracking linear inequalities among many abstract locations.\nAbstract locations are produced by the heap analysis~\\cite{Logozzo07}, and they abstract stack locations and heap locations. \nFigure~\\ref{fig:results} shows that it is not uncommon to have methods which requires the abstract state to track more than 100 variables.\nOne single method of \\code{mscorlib.dll} required to track relations among 373 distinct variables.\n\\Subpoly\\ handles it: the analysis with $\\rho_{BE}$ took a little bit more than a minute.\nTo the best of our knowledge those performances in presence of so many variables are largely beyond state-of-the-art \\Polyhedra\\ implementations.\n\n\\subsection{Hints}\n\nFigure~\\ref{tab:subpoly} focuses on the analysis of \\code{mscorlib} using \\Subpoly{} refined with hints and no-reduction.\nThe first column in the table shows the results of the analysis with no hints.\nThis is roughly equivalent to precisely propagating arbitrary linear equalities and intervals, with limited inference and no propagation of information between linear equalities and intervals. \nUser-provided hints and die-hard hints add more inference power, at the price of a still acceptable slow-down.\nComputed hints (with Octagons and 2D-Convex hull) further slow-down of the analysis, causing the analysis of various methods to time out.\nWe manually inspected the analysis logs to investigate the differences.\nIgnoring the methods that timed-out, with respect to $\\Subpoly^*$, $\\tupla{\\Subpoly^*, \\hint{\\cjoin}^{\\hintcomp^\\mathit{Oct}} }$ and $\\tupla{\\Subpoly^*, \\hint{\\cjoin}^{\\hintcomp^\\mathit{2DCH}}}$ report respectively 125 and 124 less false positives. \nOut of those, only 13 overlap.\n\nOne may wonder if computed hints are needed at all.\nWe observed that, when considering annotated code (unfortunately, just a small fraction of the overall codebase at the moment of writing), one needs to refine the operations of the abstract domains with hints in order to get a very low (and hence acceptable) false alarms ratio (around 0.5\\%) . \nIn fact, even if (relatively) rare, assertions as in Fig.~\\ref{fig:gathering}(b) and Fig.~\\ref{fig:2dhints} are present in real code.\nThanks to the incremental structure of \\Clousot, we do not need to run \\Subpoly{} with \\emph{all} the hints on \\emph{all} the analyzed methods, but we can focus the highest precision only on the few methods which require it.\n\n\n\\begin{figure*}\n\\centering\n\\small\n\\begin{tabular}{@{}r r | r r r| r r r | r r r@{}}\n \\multicolumn{2}{c|}{\\Subpoly{}} & \n \\multicolumn{2}{c}{$\\Subpoly^*$}\n & Slow &\n \\multicolumn{2}{c}{$\\Subpoly{}^*$ + $ \\hint{\\cjoin}^{\\hintcomp^\\mathit{Oct}}$}\n & Slow \n& \\multicolumn{2}{c}{$\\Subpoly{}^*$ + $ \\hint{\\cjoin}^{\\hintcomp^\\mathit{2DCH}}$} & Slow\n \\\\\nValid & Time & Valid & Time & down & Valid & Time & down & Valid & Time & down \\\\\n\n\\hline\n 14 230 & 4:29(0) & 14 432 & 20:22(0) & 4.5x & 13 948 & 81:24(20) & 18.2x & 14 396 & 36:33(7) & 8.1x\n\\end{tabular}\n\\caption{The experimental results analyzing \\code{mscorlib} with \\Subpoly{} and different semantic hints and no-reduction.\n$\\Subpoly^*$ denotes $\\Subpoly$ refined with $\\hint{\\diamond}^{\\mathsf{pred}}$ and $\\hint{\\cjoin,\\widening}^{d}$.\nComputed hints significantly slow-down the analysis, but they are needed to reach a very low false alarm ratio.}\n\\label{tab:subpoly}\n\\end{figure*}\n\n\n\\section{Conclusions}\nWe introduced \\Subpoly, a new numerical abstract domain based on the combination of linear equalities and intervals.\n\\Subpoly\\ can track linear inequalities involving hundred of variables.\nWe defined the operations of the abstract domain (order, join, meet, widening); the simplification operator (to speed up the analysis); and two reduction operators (one based on linear programming and another based on basis exploration).\nWe found Simplex-based reduction quite unsatisfactory for program analysis purposes: because of floating point errors the result may be too imprecise, or worse unsound.\nWe introduced then the basis exploration-based reduction, in practice more precise and faster.\n\n\\Subpoly\\ precisely propagates linear inequalities, but it may fail to infer some of them at join points. \nPrecision can be recovered using hints either provided by the programmer in the form of program annotations; or automatically generated (at some extra cost).\n\\Subpoly\\ worked fine on some well known examples in literature that required the use of \\Polyhedra.\nWe tried \\Subpoly\\ on shipped code, and we showed that it scales to several hundreds of variables, a result far beyond existing \\Polyhedra{} implementations.\n\n\n\n\n\\Fsubsubsection{Acknowledgments} Thanks to Lev Nachmanson for providing us the Simplex implementation.\nThanks to Manuel F\\\"ahndrich, J\\'er\\^ome Feret, Corneliu Popeea for the useful discussions.\n\n\\bibliographystyle{plain}\n{\n\\small\n\\bibliography{bib}\n}\n\n\\appendix\n\n\n\\section{Foxtrot}\n\\label{sec:foxtrot}\n% Foxtrot\n\\Foxtrot\\ is a language independent solution for contract\nspecifications in \\NET. It does not require any source language\nsupport or compiler modification. Preconditions and postconditions\nare expressed by invocations of static methods\n(\\code{Contract.Requires} and \\code{Contract.Ensures}) at the start of\nmethods. Class\ninvariants are contained in a method with an opportune name\n(\\code{ObjectInvariant}) or tagged by a special attibute\n(\\code{[ObjectInvariant]}). Dummy static methods are used to express\nmeta-variables such as \\eg\\ \\code{Contract.Old(x)} for the value in the\npre-state of \\code{x} or \\code{Contract.WritableBytes(p)} for the\nlength of the memory region associated with \\code{p}. These contracts are\npersisted to MSIL using the standard source language compiler.\n\nContracts in the \\Foxtrot{} notation (using static method calls) can\nexpress arbitrary boolean expressions as pre-conditions and\npost-conditions. We expect the expressions to be side effect free (and\nonly call side-effect free methods). We use a separate purity checker\nto optionally enforce this~\\cite{BarnettEtAl07}. \n\nA binary rewriter tool enables dynamic checking. It extracts the\nspecifications and instruments the binary with the appropriate runtime\nchecks at the applicable program points, taking contract inheritance\ninto account. Most \\Foxtrot{} contracts can be enforced at runtime.\n\nFor static checking, \\Foxtrot\\ contracts are presented\nto \\Clousot\\ as simple \\code{assert} or \\code{assume}\nstatements. E.g., a pre-condition of a method appears as an assumption\nat the method entry, whereas it appears as an assertion at every\ncall-site.\n\n\\section{Simplex algorithm}\n\\label{sec:simplex}\n\nWe recall some basic facts about the Simplex algorithm, and in particular the notion of basis.\nThe Simplex algorithm finds the best solution to the problem:\n\\[\n\\begin{aligned}\n\\text{maximize} &\\quad c^T \\code{v} \\\\\n\\text{subject to} &\\quad A\\ \\code{v} = b \n\\end{aligned}\n\\]\nThere may be also interval constraints ($l_i \\leq \\var_i \\leq u_i$), but they are not important for the notion of basis.\nThe problem above can be rewritten in matricial form as\n\\[\n\\left( \\begin{tabular}{c|c}\n $A$ & $b$\n\\end{tabular}\n \\right)\n\\left( \\begin{tabular}{c}\n \\code{v} \\\\ $-1$\n\\end{tabular}\n \\right) = 0\n\\]\nWe let $S = ( A | b)$. \nThere are infinitely many matrices $S$ with the same space of solutions as $S\\ \\code{v} = 0$, so we can make a few assumptions on $S$.\nFirst, we can use Gaussian elimination get an upper triangular matrix (row echelon form). \nGaussian elimination updates the matrix by adding to a row a linear combination of the other rows of the matrix, which does not change the space of solutions; after several of such updates, the result is triangular. \nWe can then remove all zero rows and divide each row by its leading coefficient (which is the left-most non-zero coefficient). These operations do not change the space of solutions. \nAs Gaussian elimination guarantees that the leading coefficient of each row is strictly right of the leading coefficients of the rows above it, there is at most one leading coefficient in each column. \nThe variables whose columns contain a leading coefficient are called \\emph{basic variables}, the ones whose columns do not contain a leading coefficient are called \\emph{non-basic variables}. \nThe set of basic variables is the \\emph{basis}.\nIt is also convenient to have the columns corresponding to basic variables containing only zeros except for a single one (the leading coefficient).\nThis can be achieved from the previous matrix by a way similar to Gaussian elimination.\n\nThe Simplex algorithm starts with a matrix in this form, and at each iteration changes the basis. \\emph{Changing the basis} consists in choosing a basic variable, $\\var_b$, with the associated row $r$ (the row whose leading coefficient is in the column for $\\var_b$), then choosing a non-basic variable $\\var_n$ whose coefficient $c$ in the row $r$ is non-zero, then divide the row $r$ by $c$, and use row operations to make all the other coefficients in the column for $\\var_n$ zeros. \nThe basis is now the previous basis plus $\\var_n$ minus $\\var_b$ (and so $\\var_b$ is now non-basic and $\\var_n$ is now basic).\nNote that the matrix may not be triangular anymore; this is not required for the simplex algorithm.\nThe simplex algorithm uses the cost function $c$ and the bounds $l_i$ and $u_i$ on variables to change the basis.\nFurthermore the simplex chooses the variables to ensures that $c$ will not be zero; if this is not the case, a zero coefficient means that a particular exchange is not possible.\n\n\n\\end{document}\n", "meta": {"hexsha": "3d2d68b31cdda1d044a99de247cc70cc7f2a53fe", "size": 102216, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Documentation/Papers/SubPolyhedra_Journal/Subpolyhedra.tex", "max_stars_repo_name": "jeroen-mostert/CodeContracts", "max_stars_repo_head_hexsha": "a7df47aaf1b6570abc07191a32a0afa29f9838e8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 778, "max_stars_repo_stars_event_min_datetime": "2015-01-15T21:59:13.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-04T04:14:50.000Z", "max_issues_repo_path": "Documentation/Papers/SubPolyhedra_Journal/Subpolyhedra.tex", "max_issues_repo_name": "tom-englert/CodeContracts", "max_issues_repo_head_hexsha": "7255a95ec1de1453518852030de285d0fa001c11", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 460, "max_issues_repo_issues_event_min_datetime": "2015-01-16T06:30:35.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-26T16:13:29.000Z", "max_forks_repo_path": "Documentation/Papers/SubPolyhedra_Journal/Subpolyhedra.tex", "max_forks_repo_name": "tom-englert/CodeContracts", "max_forks_repo_head_hexsha": "7255a95ec1de1453518852030de285d0fa001c11", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 198, "max_forks_repo_forks_event_min_datetime": "2015-01-15T22:02:07.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-10T14:09:57.000Z", "avg_line_length": 60.2333529758, "max_line_length": 486, "alphanum_fraction": 0.7175588949, "num_tokens": 30723, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.3486451217982255, "lm_q1q2_score": 0.18655945682256403}}
{"text": "\\chapter{Production data}\\label{appen:proddata}\r\n\r\n\\begin{table}[htbp]\r\n\\begin{center}\r\n\\resizebox{4in}{!}{\r\n\\begin{tabular}{llll}\r\n \\hline\r\n feature & grammatical & quotative & discourse particle \\\\\r\n \\hline\r\n \r\n\r\n total tokens & 198 & 217 & 305 \\\\\r\n followed by C & 143 & 77 & 176 \\\\\r\n followed by pause & 10 & 56 & 59 \\\\\r\n followed by V & 45 & 84 & 70 \\\\\r\n min EucD (Hz) & 1.5 & 0.0 & 10.9 \\\\\r\n mean EucD (Hz) & 416.3 & 304.9 & 415.4 \\\\\r\n max EucD (Hz) & 1173.0 & 1099.0 & 1498.0 \\\\\r\n min nuc F2 (Hz) & 1028 & 1040 & 1234 \\\\\r\n mean nuc F2 (Hz) & 1549 & 1599 & 1603 \\\\\r\n max nuc F2 (Hz) & 2349 & 2286 & 2057 \\\\\r\n full glott & 46 & 47 & 75 \\\\\r\n mid glott & 21 & 29 & 49 \\\\\r\n no glott & 131 & 141 & 181 \\\\\r\n min pitch & 77.0 & 84.0 & 76.5 \\\\\r\n mean pitch & 203.2 & 224.2 & 202.2 \\\\\r\n max pitch & 352.5 & 352.1 & 342.0 \\\\\r\n min duration ratio & 0.00 & 0.00 & 0.00 \\\\\r\n mean duration ratio & 0.47 & 0.32 & 0.43 \\\\\r\n max duration ratio & 1.57& 1.55 & 1.76 \\\\\r\n /k/ not realised & 64 & 96 & 98 \\\\\r\n /k/ realised & 134 & 121 & 207 \\\\\r\n\r\n \\hline\r\n \r\n \\end{tabular}\r\n}\r\n\\caption{Counts of tokens with particular phonetic features, by type.}\\label{tab:appenprodfeatures}\r\n\\end{center}\r\n\\end{table}\t", "meta": {"hexsha": "f372d12f1bdbd0ea924dbd37d606cc8f9ff02c2b", "size": 1227, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "original/appendices/appendix2-from submitted version.tex", "max_stars_repo_name": "langsci/Drager", "max_stars_repo_head_hexsha": "556ce56d71fd4a8d2e13ed5905f9517ddf8c5b84", "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": "original/appendices/appendix2-from submitted version.tex", "max_issues_repo_name": "langsci/Drager", "max_issues_repo_head_hexsha": "556ce56d71fd4a8d2e13ed5905f9517ddf8c5b84", "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": "original/appendices/appendix2-from submitted version.tex", "max_forks_repo_name": "langsci/Drager", "max_forks_repo_head_hexsha": "556ce56d71fd4a8d2e13ed5905f9517ddf8c5b84", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2016-09-29T01:31:33.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-04T12:30:19.000Z", "avg_line_length": 30.675, "max_line_length": 100, "alphanum_fraction": 0.5550122249, "num_tokens": 532, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.33111972642778714, "lm_q1q2_score": 0.1861477291774361}}
{"text": "There can be a large number of computational tools within a given field of\nstudy. They are typically developed with a single aspect of analysis in mind,\nso one must understand the simplifying assumptions the developers made for\ntheir purposes. Thus, choosing a computational tool is not always obvious. This\nsection introduces the choices for the various experimental components.\n\n\\subsection{Fuel Cycle Simulation}\n\nNuclear fuel cycle studies involve tracking the material flow of nuclear fuel.\nThis can be anywhere from mining to waste management, or focus on a process\nstep in between. Fuel cycle studies are not necessarily nuclear-specific. For\nexample, they can be used to evaluate economic predictions, environmental\nimpact, transportation planning, etc. In order to draw conclusions from these\nstudies, it is common to use a nuclear fuel cycle simulator that tracks the\nquantities of interest. These allow the comparison of different fuel types,\nreactor technologies, material processing steps, etc. \n\nThere are simplifications researchers need to make in order to experiment in a\ncontrolled way. Fuel cycle simulators, built for a specific needs, must remove\ncomplicating factors that are less relevant to the study. For example, one\ntool might be suited well to large-scale systems analysis with little nuclear\nphysics included in the models, and another might focus on detailed isotopics\nwithin a system to track plutonium.\n\nBecause a large portion of a nuclear forensics investigation relies on\nmeasuring isotopics, this work used \\gls{ORIGEN} \\cite{origen}, which is a part\nof the \\gls{SCALE} 6.2 modeling and simulation suite of computational tools\ndeveloped for nuclear design and safety \\cite{scale}. \\gls{ORIGEN} was chosen\nfor its physically detailed models of activation, depletion, and decay.\nSpecifically, the ARP module of the code was used: \\gls{ORIGEN-ARP}.\n\n\\gls{ORIGEN} calculates time-dependent nuclide concentrations (or quantities\nderived from these) that result from activation and depletion calculations. The\nphysics (i.e., neutron transport and decay) calculations are carried out in\nother \\gls{SCALE} modules that solve the depletion equations. This generates\nlibraries for \\gls{ORIGEN} that include the probabilities of reaction (i.e.,\ncross sections) for the system.\n\nTo obtain an \\gls{SNF} recipe from a reactor simulation, \\gls{ORIGEN} uses the\ndesired input power generation with the cross section library to calculate a\nflux, the resulting depletion, and the end composition (i.e., isotopic recipes\nor nuclide vectors). Another output is decay; the composition is computed\nusing decay equations with nuclear data \\cite{endf}. These compositions provide\nsource terms for other calculations, such as decay emission spectra from\nneutrons, alpha particles, beta particles, and gamma rays. Other derived\nquantities like activity, decay heat, or radiological hazard factors are also\nan option.\n\n\\gls{ORIGEN-ARP} allows users to access a wider range of simulations by\ninterpolating between the pre-calculated libraries instead of creating new\nlibraries. It is known to be validated for \\gls{LWR} \\gls{SNF}\n\\cite{lwr_valid}. Additionally, recycled \\gls{SNF} in the form of mixed oxide\nfuel has been benchmarked for the relevant reactors \\cite{mox_valid}. Through\n\\gls{ORIGEN}, given an initial material composition, some reactor operation\nparameters, and a reactor type, one can quickly perform many different nuclear\nreactor simulations and obtain \\gls{SNF} recipes.\n\n\\subsection{Statistics Toolkit}\n\nThe statistics toolkit chosen for this work is scikit-learn \\cite{scikit}, a\nmachine learning package in python. Virtually all modern \\gls{ML}\ntoolkits will have acceptably fast and reliable algorithms, but the use of\npython provides a platform for seamless integration of all the tools in the\nworkflow. \n\n\\subsection{Computational Gamma Spectra}\n\nAlthough the data modification shown later in Section \\ref{sec:inforeduc} does\nnot use any standalone tool, the code \\gls{GADRAS} \\cite{gadras} developed at\nSandia National Laboratories will provide information reduction in a physically\nvalid manner. Test studies will be carried out using the gamma energies\navailable from \\gls{ORIGEN} simulations, but the detector response will need to\nbe varied more than this tool can provide. Thus, given the gamma energies from\n\\gls{ORIGEN} and a user-chosen \\gls{DRF}, \\gls{GADRAS} computationally\ngenerates gamma spectra. This will enable a more robust study of statistical\nperformance with respect to information reduction.\n\n", "meta": {"hexsha": "18733a877ce1331922075817ef20a408a8f35a7b", "size": 4559, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "document/chapters/litrev/fcsim.tex", "max_stars_repo_name": "opotowsky/prelim", "max_stars_repo_head_hexsha": "100a27fb533beee1c985ad72ae70bdb646b04bab", "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/litrev/fcsim.tex", "max_issues_repo_name": "opotowsky/prelim", "max_issues_repo_head_hexsha": "100a27fb533beee1c985ad72ae70bdb646b04bab", "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": "document/chapters/litrev/fcsim.tex", "max_forks_repo_name": "opotowsky/prelim", "max_forks_repo_head_hexsha": "100a27fb533beee1c985ad72ae70bdb646b04bab", "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": 58.4487179487, "max_line_length": 79, "alphanum_fraction": 0.80960737, "num_tokens": 1030, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.3629691986286475, "lm_q1q2_score": 0.18573736593444326}}
{"text": "\n\\documentclass{llncs}\n\\usepackage{CJK}\n\\usepackage{algorithm} \n\\usepackage{algorithmicx} \n\\usepackage{algpseudocode} \n\\usepackage{amsmath} \n\\usepackage{multirow}\n\\begin{document}\n\t\n\n\\title{Algorithm Description}\n%\n\\titlerunning{Hamiltonian Mechanics} % abbreviated title (for running head)\n% also used for the TOC unless\n% \\toctitle is used\n%\n\\author{}\n\n%\n\\institute{HIT WI}\n\n\\maketitle % typeset the title of the contribution\n\n\\begin{abstract}\nFor this ccks named entity recognition task, we mainly use two methods.The single CRF and the LSTM-CRF neural network model.We use the gold label data \nset to do the unsupervised learning for both model,and the unlabel data set to do the embedding and supervised learning.Finally get the \\dots\n\\keywords{Name entity recognition,CRF,LSTM}\n\\end{abstract}\n%\n\\section{LSTM-CRF method}\n\\subsection{Neural Network Architecture}\nIn this section, we describe the components (layers) of our neural network architecture. We introduce the neural layers in our neural network one\nby-one from bottom to top.\n\\subsubsection{Char Embedding}\nWe use the char level vector to represent the Chinese words,by using the word2vec in the unlabeled dataset,the embedding dimension is 100.\n\\subsubsection{Bi-directional-LSTM}\nFor many sequence labeling tasks it is beneficial to have access to both past (left) and future (right) contexts.The solution whose effectiveness has been proven by previous work (Dyer et al., 2015) is bi-directional LSTM\n(BLSTM). The basic idea is to present each sequence forwards and backwards to two separate hidden states to capture past and future information, respectively. Then the two hidden states are concatenated to form the final output.\n\\subsubsection{CRF}\nFor sequence labeling (or general structured prediction) tasks, it is beneficial to consider the correlations between labels in neighborhoods and jointly decode the best chain of labels for a given input sentence.Therefore, we model\nlabel sequence jointly using a conditional random field (CRF) (Lafferty et al., 2001), instead of decoding each label independently.\nIn our code,we try to use the negative log likelihood function and the\nlabelwise function to get the loss of the CRF layer.Using the marginal decode\nand viterbi decode.\n \n\\floatname{algorithm}{Algorithm} \n\\renewcommand{\\algorithmicrequire}{\\textbf{input:}} \n\\renewcommand{\\algorithmicensure}{\\textbf{output:}} \n\t\\begin{algorithm} \n\t\t\\caption{CRF loss Negative log likelihood} \n\t\t\\begin{algorithmic}[1] \n\t\t\t\\Require feature from BiLSTM,Tags \n\t\t\t\\Ensure Loss \n\t\t\t\\Function {Likelihood loss}{$feature,self,tags$} \n\t\t\t\\State $forward score \\gets CRFlayer.forward(feature)$\n\t\t\t\\State \\# Do the forward algorithm to compute the partition function\n\t\t\t\\State $gold score \\gets CRFlayer.score_sentence(feature,tags)$\n\t\t\t\\State \\# Gives the score of a provided tag sequence\n\t\t\t\\State \\Return{$forward score - gold score$} \n\t\t\t\\EndFunction \n\t\t\\end{algorithmic} \n\t\\end{algorithm} \n\n \n\\subsubsection{BLSTM-CRF}\n\\\nThe basic train step is as fellow:\n\\begin{algorithm} \n\t\\caption{Network train step} \n\t\\begin{algorithmic}[1] \n\t\t\\Require Sequences of context C,Sequences of BIEO tags T \n\t\t\\Ensure Model \n\t\t\\State Initialize the word-embedding layer$\\gets$ Separating text by char and do Word2vec\n\t\t\\State model$\\gets$LstmCrfModel.BiLSTM CRF(Model parameters)\n\t\t\\State optimizer $\\gets$ optim.SGD(model.parameters(), lr$\\gets$0.01, weight decay$\\gets$1e-4)\n\t\t\\For {in range(epcho)}\n\t\t \\ForAll {$sentence \\in context$}\n\t\t \\State model.LSTMtrain(sentence)\n\t\t \\State Input to the CRFlayer\n\t\t \\EndFor\n\t\t \\State Get loss(T,predict tags)\n\t\t \\State SGD Optimize the loss\n\t\t \\EndFor\n\t\t\\State \\Return{$Model$} \n\t\\end{algorithmic} \n\\end{algorithm} \n\\section{Parameter Initialization}\nThe Parameter Initialization is as fellow:\n\\begin{table}[!hbp]\n\t\\begin{tabular}{|p{2cm}|p{2cm}|p{2cm}|p{2cm}|p{2cm}|p{2cm}|}\n\t\t\\hline\n\t\t Optimizer & Embedding & Dropout & Learning rate& Weight dercay&CRF loss \\\\\n\t\t\\hline\n\t\t SGD & Word2Vec & 0.5 & 0.01 & 1e-4 &lablewise\\\\\n\t\t\\hline\n\t\\end{tabular}\n\\end{table} \n\n\\section{Single CRF method}\n\\subsection{feature chose}\nChose the pos tag to be the extra feature,to do the crf in char level.\n\\subsection{Parameter Initialization}\nThe Parameter Initialization is as fellow:\n\\begin{table}[!hbp]\n\t\\begin{tabular}{|p{2cm}|p{2cm}|p{2cm}|p{2cm}|p{2cm}|p{2cm}|}\n\t\t\\hline\n\t\tOptimizer & Embedding & Dropout & Learning rate& Weight dercay&CRF loss \\\\\n\t\t\\hline\n\t\tSGD & Word2Vec & 0.5 & 0.01 & 1e-4 &lablewise\\\\\n\t\t\\hline\n\t\\end{tabular}\n\\end{table} \n\n\n\n%\n% ---- Bibliography ----\n%\n\\begin{thebibliography}{5}\n%\n\\bibitem {clar:eke}\nSchölkopf B, Platt J, Hofmann T. Training Conditional Random Fields for Maximum Labelwise Accuracy[C]// Advances in Neural Information Processing Systems 19, Proceedings of the Twentieth Conference on Neural Information Processing Systems, Vancouver, British Columbia, Canada, December. DBLP, 2006:529-536.\n\n\\bibitem {clar:eke:2}\nMa X, Hovy E. End-to-end Sequence Labeling via Bi-directional LSTM-CNNs-CRF[J]. 2016.\n\\bibitem {clar:eke:3}\nGoldberg Y, Levy O. word2vec Explained: deriving Mikolov et al.'s negative-sampling word-embedding method[J]. Eprint Arxiv, 2014.\n\n\\end{thebibliography}\n\\end{document}\n", "meta": {"hexsha": "3d2ca09f07a9d8677dc58b0fac1c16750cad45dd", "size": 5317, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/main.tex", "max_stars_repo_name": "fangwater/Medical-named-entity-recognition-for-ccks2017", "max_stars_repo_head_hexsha": "ed5e9dae78efad5a4f542a36f921f26f670e9c10", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 93, "max_stars_repo_stars_event_min_datetime": "2017-08-25T13:58:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T13:43:06.000Z", "max_issues_repo_path": "doc/main.tex", "max_issues_repo_name": "ahashisyuu/Medical-named-entity-recognition-for-ccks2017", "max_issues_repo_head_hexsha": "ed5e9dae78efad5a4f542a36f921f26f670e9c10", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2017-09-04T02:49:59.000Z", "max_issues_repo_issues_event_max_datetime": "2018-09-14T09:33:44.000Z", "max_forks_repo_path": "doc/main.tex", "max_forks_repo_name": "ahashisyuu/Medical-named-entity-recognition-for-ccks2017", "max_forks_repo_head_hexsha": "ed5e9dae78efad5a4f542a36f921f26f670e9c10", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 41, "max_forks_repo_forks_event_min_datetime": "2017-07-27T13:19:02.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-06T11:08:56.000Z", "avg_line_length": 40.2803030303, "max_line_length": 306, "alphanum_fraction": 0.7415835998, "num_tokens": 1493, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.35220178204788966, "lm_q1q2_score": 0.18572181923758121}}
{"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% GEANT manual in LaTeX form %\n% %\n% Michel Goossens (for translation into LaTeX) %\n% Version 1.00 %\n% Last Mod. Jan 24 1991 1300 MG + IB %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\Origin{L.Urb\\'{a}n}\n\\Version{Geant 3.16} \\Routid{PHYS450}\n\\Submitted{24.03.86} \\Revised{16.12.93}\n\\Makehead{Total cross-section and energy loss for e-e+ pair\nproduction by muons}\n\\section{Subroutines}\n\\Shubr{GPRELA}{}\n\\Rind{GPRELA} adds to the muon energy loss tables the contribution \ndue to $\\mu$-nucleus interactions and \\Pep\\Pem-pair production in \nwhich the energy of the pair is below threshold (see later).\nFor the contribution of pair production, it calls the function \n\\Rind{GPRELM}. The energy binning is in the array {\\tt ELOW} (common \n\\FCind{/CGMULO/}). The following pointers are used:\n\n\\begin{DLtt}{MMMMMMMMMMMMMMMMMMMM}\n\\item[JMA = LQ(JMATE-I)] pointer to the I$^{th}$ material;\n\\item[JEL2 = LQ(JMA-2)] pointer to $dE/dx$ for $\\mu^+\\mu^-$.\n\\end{DLtt}\n\n\\Rind{GPRELA} is called during initialisation by \\Rind{GPHYSI}.\n\n\\Sfunc{GPRELM}{VALUE = GPRELM(Z,T,CUT)}\n\n\\begin{DLtt}{MMMMMMMM}\n\\item[Z] ({\\tt REAL}) atomic number of the material;\n\\item[T] ({\\tt REAL}) kinetic energy of the muon;\n\\item[CUT] ({\\tt REAL}) maximum energy for the pair considered by the routine.\n\\end{DLtt}\n\\Rind{GPRELM} calculates the energy loss due to the direct\nproduction by muons of \\Pem\\Pep pairs with energy below {\\tt CUT}\n({\\tt PPCUTM} in common \\FCind{/GCCUTS/}).\nAbove this cut, the direct pairs are produced as discrete processes\n(see {\\tt [PHYS451]}). \\Rind{GPRELM} is called by \\Rind{GPRELA}.\n\\Shubr{GPRSGA}{}\n{\\tt GPRSGA} calculates the total cross-section for \nthe pair production by photons and the direct pair production by muons.\nIt tabulates the mean free path\nin cm as a function of medium and energy. \nFor the direct pair production of muons, it calls \nthe function \\Rind{GPRSGM}. The energy\nbinning is in the array {\\tt ELOW} (common \\FCind{/CGMULO/}).\nThe following pointers are used:\n\\begin{DLtt}{MMMMMMMMMMMMMMMMMMMM}\n\\item[JMA = LQ(JMATE-I)] pointer to the I$^{th}$ material;\n\\item[JPAIR = LQ(JMA-10)] pointer to photon pair production cross-sections;\n\\item[JPAIR+NEK1] pointer to muon pair production.\n\\end{DLtt}\n{\\tt GPRSGA} is called during initialisation by {\\tt GPHYSI}.\n\n\\Sfunc{GPRSGM}{VALUE = GPRSGM(Z,T,CUT)}\n\n\\begin{DLtt}{MMMMMMMM}\n\\item[Z] ({\\tt REAL}) atomic number of the medium;\n\\item[T] ({\\tt REAL}) kinetic energy of the muon;\n\\item[CUT] ({\\tt REAL}) minimum energy for the \\Pem\\Pep pair.\n\\end{DLtt}\n\\Rind{GPRSGM} calculates the total cross-section for\nmuon direct pair production where the energy of the pair is greater\nthan {\\tt CUT} ({\\tt PPCUTM} in common \\FCind{/GCCUTS/}). It is called \nby \\Rind{GPRSGA} (see {\\tt [PHYS451]}).\n\n\\section{Method}\nWhen a muon of energy $E$ moves in the field of\nan atom of charge $Z$, it can radiate a \\Pep\\Pem-pair\n($4^{th}$ order QED process) with \ndifferential cross-section \\cite{bib-LOHM}:\n\\begin{equation}\n\\frac{\\partial^2 \\sigma}{\\partial \\nu \\; \\partial \\rho}=\n\\alpha^4 \\frac {2}{3 \\pi} (Z \\lambdar)^2 \\frac{1-v}{v}\n\\left [ \\phi_e + \\left(\\frac{m_{e}} {m_{\\mu}}\\right)^2 \\phi_{\\mu} \\right ]\n\\end{equation}\nwhere\n\\[\n\\nu = \\frac{ E^+ + E^-}{E} \\mbox{\\quad and\\quad}\\rho =\n\\frac{E^+ - E^-}{E^+ + E^-}\n\\]\nand\n\\begin{DLtt}{MMMMMMMM}\n\\item[$\\alpha$] 1/137, fine structure constant;\n\\item[$\\lambdar$] $3.8616 \\times 10^{-11}$ cm, electron Compton wavelength;\n\\item[$v$] $k/E$ fraction of energy transferred to the pair;\n\\item[$T$] $E-M$ kinetic energy of the muon.\n\\item[$E^{\\pm}$] the energy of the $e^{\\pm}$.\n\\end{DLtt}\n\nThe explicit form of the terms $\\phi_e$ and $\\phi_{\\mu}$\ncan be found in \\cite{bib-LOHM}. The kinematic ranges of $\\nu$ and $\\rho $ are:\n\\begin{equation}\n\\begin{array}{RCCCCCL}\n\\frac{4m_{e}}{E}=\\nu_{min} & \\leq & \\nu & \\leq & \\nu_{max} & = &\n1 -0.75 \\sqrt{e}\\frac{m_{\\mu}}{E} Z^{1/3} \\\\ [0.7cm]\n0=\\rho_{min} & \\leq & |\\rho (\\nu) | & \\leq & \\rho_{max} (\\nu) &\n= & \\left [1-\\frac{6m_{\\mu}^2}{E^2 (1-\\nu)}\\right]\n \\sqrt{1- \\frac{4m_{e}}{\\nu E}} \n\\end{array}\n\\end{equation}\n \nwhere $e = 2.718\\dots$.\n \n$E_c$ ({\\tt PPCUTM} in the program) is the energy cut-off; below this \nenergy \\Pep\\Pem-pair are treated as continuous energy loss,\nand above they are explicitly\ngenerated and $v_c = E_c/E$.\nThe mean value of the energy lost by the incident muon due to\n\\Pep\\Pem-pair with energy below $E_{c}$ is:\n\\begin{equation}\n\\label{eq:phys450-1}\n E_{loss}^{pair}(Z,T,E_c ) =\n 2E \\int_{\\nu_{min}}^{\\nu_c}{ d\\nu\\;\\nu \\int_{0}^{\\rho_{max}(\\nu)}{\n d\\rho \\;\n\\frac{\\partial^2 \\sigma}{\\partial\\nu \\; \\partial\\rho}}}\n\\mbox{\\hspace{0.5cm} GeV barn/atom}\n\\end{equation}\nwhereas the total cross-section for the emission of a hard \\Pep\\Pem-pair is:\n\\begin{equation}\n\\label{eq:phys450-2}\n\\sigma (Z,T,E_c) =\n 2 \\int_{\\nu_c}^{\\nu_{max}} d \\nu\\;\n \\int_{0}^{\\rho_{max}(\\nu)}\n d \\rho \\; \\frac{\\partial^2\\sigma}{ \\partial\\nu \\; \\partial\\rho}\n\\mbox{\\hspace{0.5cm} barn/atom}\n\\end{equation}\n\n\\subsection{Parameterisation of energy loss and total cross-section}\nInstead of using the explicit formula (\\ref{eq:phys450-1}) and\n(\\ref{eq:phys450-2}), we have chosen to parameterise directly \n$E_{loss}^{pair}(Z,T, E_c $) and $\\sigma(Z,T,E_c)$ as:\n\\begin{eqnarray}\n\\label{eq:phys450-3}\n\\sigma (Z,T,E_c) & = & Z [Z+ \\xi_{\\sigma} (1+ \\gamma \\ln Z)]\n \\left [\\ln \\frac{E_{max}}{E}\\right]^{\\alpha}\n F_{\\sigma} (Z,X,Y) \\\\\nE_{loss}^{pair}(Z,T,E_c) & = & Z [Z+ \\xi_l (1+ \\delta \\ln Z)] E\n\\label{eq:phys450-4}\n \\left [ \\frac{E_c - E_c^{min}}{E}\\right]^{\\beta}\n F_l(Z,X,Y)\n\\end{eqnarray}\nwhere $\\xi_{\\sigma,l}$, $\\alpha$, $\\beta$, $\\gamma$ and $\\delta$\nare parameters obtained by a fitting procedure and\n$ E_c^{min} = E\\:v_{min} = 4 m_{e}$ and\n$ E_{max} = E\\:v_{max}$\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)$ denotes a function constructed from two polynomials\n\\begin{equation}\n F_{ij}(X,Y) = \\left\\{ \\begin{array}{LlL}\n P_{ij}^{neg}(X,Y) & \\mbox{if} & Y \\leq 0 \\\\ [0.3cm]\n P_{ij}^{pos}(X,Y) & \\mbox{if} & Y > 0\n \\end{array} \\right.\n\\end{equation}\nand $P_{ij}^{neg}$, $P_{ij}^{pos}$ fulfil the conditions:\n\\[\nP_{ij}^{neg}(X,Y)_{Y=0} = P_{ij}^{pos}(X,Y)_{Y=0} \n\\hspace{2cm}\n\\left . \\frac{\\partial P_{ij}^{neg}}{\\partial Y } \\right |_{Y=0} =\n\\left . \\frac{\\partial P_{ij}^{pos}}{\\partial Y } \\right |_{Y=0}\n\\]\nThe detailed form of the $P_{ij}$ polynomials is:\n\\begin{eqnarray}\nP_{i0}^{neg}(X,Y)& = &\n (C_1+C_2X+\\cdots+C_6X^5)+(C_7+C_8X+\\cdots+C_{12}X^5)Y\n\\nonumber \\\\\n & + &(C_{13}+C_{14}X+\\cdots+C_{18}X^5)Y^2+\\cdots+(C_{31}+\\cdots+C_{36}X^5)Y^5\n\\nonumber\\\\\nP_{i0}^{pos}(X,Y)& = &\n (C_1+C_2X+\\cdots+C_6X^5)+(C_7+C_8X+\\cdots+C_{12}X^5)Y\n\\nonumber\\\\\n\\label{eq:phys450-5}\n & + &(C_{37}+C_{38}X+\\cdots+C_{42}X^5)Y^2+\\cdots+(C_{55}+\\cdots+C_{60}X^5)Y^5\n \\\\\nP_{i1}^{neg}(X,Y)& = &\n (C_{61}+C_{62}X+\\cdots+C_{65}X^4)+(C_{66}+C_{67}X+\\cdots+C_{70}X^4)Y\n\\nonumber \\\\\n & + &(C_{71}+C_{72}X+\\cdots+C_{75}X^4)Y^2+\\cdots+(C_{81}+\\cdots+C_{85}X^4)Y^4\n\\nonumber \\\\\n P_{i1}^{pos}(X,Y)& = &\n (C_{61}+C_{62}X+\\cdots+C_{65}X^4)+(C_{66}+C_{67}X+\\cdots+C_{70}X^4)Y\n\\nonumber \\\\\n & + &(C_{86}+C_{87}X+\\cdots+C_{90}X^4)Y^2+\\cdots+(C_{96}+\\cdots+C_{100}X^4)Y^4\n\\nonumber\n\\end{eqnarray}\nwith\n\\[\nX = \\ln \\frac{E}{m_{\\mu}} \\hspace{2cm} Y = \\ln \\frac{E_{c}}{v_{j} E}\n\\hspace{2cm} j = \\sigma, l\n\\]\nwhere $v_{\\sigma,l}$ are additional parameters of the fit.\nBy a numerical (twofold) integration of the formulae (\\ref{eq:phys450-3})\nand (\\ref{eq:phys450-4})\nabove, we have calculated 1800 {\\it data points} in the range\n$Z = 1, 6, 13, 26, 50, 82, 92$ and the energy ranges 1GeV $ \\leq T \\leq $ 10\nTeV and $ 4m \\leq E_c \\leq T$\nand performed a least-squares fit to determine the parameters.\nThe fitted values of the parameters are in the {\\tt DATA} statements in the\nfunctions \\Rind{GPRSGM} and \\Rind{GPRELM}, which compute the formulae \n(\\ref{eq:phys450-3}) and (\\ref{eq:phys450-4}) respectively.\nThe accuracy of the fit is:\n\\[ \\begin{array}{LL}\n\\frac{\\Delta \\sigma}{\\sigma} & \\leq \\left\\{\n\\begin{array}{RcLl}\n10\\% & \\mbox{if} & T\\leq 5 & \\mbox{GeV} \\\\\n5\\% & \\mbox{if} & T > 5 & \\mbox{GeV}\n\\end{array} \\right . \\\\ [0.5cm]\n\\frac{\\Delta E_{loss}^{pair}}{E_{loss}^{pair}} & \\leq \\left\\{\n\\begin{array}{RcLl}\n10\\% & \\mbox{if} & T\\leq 5 & \\mbox{GeV} \\\\\n4\\% & \\mbox{if} & T > 5 & \\mbox{GeV}\n\\end{array} \\right.\n\\end{array} \\]\n \nThe function \\Rind{GPRELM} contains a second formula to calculate the total\nenergy lost by the muon due to direct \\Pep\\Pem-production \nused when $E_c\\geq E_{\\mbox{max}} = E-0.75 \\surd e m_{\\mu}Z^{1/3}$.\nThis formula describes the total energy loss with an error less than 1\\%:\n\\begin{eqnarray}\nE_{loss}^{pair}(Z,T) & = &\nE_{loss}^{pair}(Z,T,E_c=E_{max}) \\\\\n& = & Z(Z+1) E_{max} [d_1+(d_2X+d_3Y)+(d_4X^2+d_5XY+d_6Y^2)+ \\nonumber\\\\\n&+ & \\cdots+(d_{22}X^6+d_{23}X^5Y+\\cdots+d_{28}Y^6)] \\nonumber\n\\end{eqnarray}\nwhere $ X=\\ln(E/m_{\\mu}) $ and $Y=Z^{1/3}$.\nThe fitted parameters $d_i$ can be found in the {\\tt DATA} \nstatement in the function \\Rind{GPRELM}.\n\n", "meta": {"hexsha": "f9b589f5c4cb801537999191592b574a9a942ec8", "size": 9597, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "geant/phys450.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": "geant/phys450.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": "geant/phys450.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.4936708861, "max_line_length": 80, "alphanum_fraction": 0.6093570908, "num_tokens": 3645, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.32766828768970435, "lm_q1q2_score": 0.18546632422834122}}
{"text": "\\section{Introduction}\nOne of the possible sources of the high-energy cosmic rays are the shock waves in astrophysical collisionless plasma due to the diffusive shock acceleration (DSA) mechanism, see \\cite{Bell1978}, \\cite{Blandford1978}. The particle acceleration on the shock front is a sophisticated and nonlinear problem, because the cosmic rays have a strong influence on the shock wave. The pressure of cosmic rays is comparable with the pressure of background plasma and significantly modifies the front (see, e.g., \\cite{Bykov2014}). \nAlso the instabilities in the anisotropic plasma can yield a strong field amplification, and according to the observations of synchrotron emission from supernova remnants (SNRs), the magnetic field there is about 100 times stronger than the interstellar field (see, e.g., \\cite{Berezhko2003},\\cite{Uchiyama2007}). \nOne of the most powerful methods to explore the processes in collisionless plasma is the Particle-in-Cell simulation.", "meta": {"hexsha": "31d527a7818155fc32936fa4ed5e17d825ec4d96", "size": 976, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "papers/Physica2017/intro.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/intro.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/intro.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": 244.0, "max_line_length": 520, "alphanum_fraction": 0.8125, "num_tokens": 217, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381667555714, "lm_q2_score": 0.33807713748839185, "lm_q1q2_score": 0.18483967437237464}}
{"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% Definitions\n%\\pagestyle{empty}\n\\documentclass[12pt,preprint]{aastex}\n%\\documentstyle[emulateapj,danonecolfloat]{article}\n%\\usepackage{emulateapj,danonecolfloat}\n\\usepackage{rotating}\n\n\\begin{document}\n\n\n\\subsection{Extraction}\n\nWe utilize an optimal extraction procedure to transform a 2-dimensional image of\nthe fiber spectrograms to a set of 320 1-dimensional spectra (per spectrograph).\nWe use the same procedure on all processed frames, \nand will describe the details in processing the flat-field frames, the\narc lamp frames, and finally the science frames. \nThe extraction is performed row-by-row, so each frame requires an \noutside loop over 2048 individual rows.\nThe counts in each row of 2048 columns are modeled with a linear \ncombination of 320 profiles plus a low-order\npolynomial background. In addition, deviations to the trace centers and\nthe profile widths are calculated as linear basis modes (reflecting the first\nand second spatial derivatives, respectively). The compiled routine\nwe implement to fit the profiles in a single row (extract\\_row.c) can\nbe invoked with any combination of these parameters.\n\nWe decided to perform profile fitting to the \nSDSS spectral images for the following reasons: \n\n\\begin{enumerate}\n\n\\item{The fiber profiles overlap significantly with their nearest neighbors.}\n\n\\item{The profiles are relatively stable and smoothly vary over \nlocation on the CCDs. They result from the convolution of the fiber \nillumination pattern + the point-spread function\nof the optics in the SDSS spectrographs + the window funciton of the \nSite CCD 24 micron square pixels. }\n\n\\item{A least-squares fit with the true profile delivers an \nunbiased and minimum variance estimate of the counts (e.g. Horne et al. 1995).}\n\n\\item{A model profile fit leads to a model image of the SDSS data,\nand iteration allows cosmic-ray rejection and goodness-of-fit tests.}\n\n\\end{enumerate}\n\nThe major obstacle to actual optimal extraction is the determination of \nthe exact shape and position of the underlying profile. \nWe investigated a range of symmetric, analytic profiles with a \nminimum number of free parameters. In the end, we found the best \nresults using a simple Gaussian or a slightly steeper profile \ncharacterized by $e^{-|x|^3/\\sigma^3}$. The profiles are defined to be \nnormalized to unity, so the amplitude of the profile fit is a \ndirect estimator of the counts at a single spectral position. \n\nExtraction is first carried out on all flat-field exposures \n(typically 10 second observations of 4 quartz lamps projected on petals covering the entrance aperture of the telescope) which were observed\nwith a common plug plate configuration (a spectroscopic sequence). \nThe flat-field extraction is used to determine the shape of\nthe profile as a function of wavelength and position on the CCD. \nThe resulting spectral extractions are also used to \ndetermine the empirical fiber-to-fiber variations in throughput \nas a function of wavelength. \nA flat-field frame is rejected by the pipeline if one of the\nfollowing conditions is met: 1) More the 2\\% of the CCD pixels are labeled\nbad by sdssproc, 2) More than 100 rows of the image show saturation, \n3) The 80th percentile count level is less than 1000 counts, \n4) Fewer than all 8 flat-field telescope petals were closed, \n5) Fewer than all 4 flat-field lamps were on,\n6) More than 10000 pixels were rejected during fiber tracing, \n7) Fiber tracing fails, or traces are seperated by less than 3 pixels anywhere\non the flat-field image.\n\nThe first very critical step is to robustly determine the fiber positions \nin CCD pixel coordinates.\nThis is performed by identifying peaks in a cross-sectional cut of across \nthe center row (actually a median cross-section of the central 9 rows). \nThe correct identification of the 320 fibers per frame can be \nuniquely determined by demanding a wider spacing between the bundles \nof 20 fibers (spaced by about 10 pixels) relative to the nominal inter-fiber \nspacing (6.1 pixels on average). Once the starting peaks and \nidentification have been determined, we trace the fiber centers \nby performing flux-weighted centroids on subsequent rows\nusing the previous row's center as the intial guess. This has proven to \nwork well on SDSS flat-fields, and we have yet to uncover a failure \nmode in over 10000 flat-field frames.\nThe flux-weighted centroids do have scatter from shot noise, \nso we fit a 7th order polynomial to each set of fiber centroids, \nand the best-fit coefficients are stored to represent the fiber positions \non each flat-field frame.\n\n\nEach flat-field frame is extracted twice, once assuming a Gaussian\nprofile and again assuming the steeper $|x|^3$ profile. In both cases,\nthe width is allowed to vary freely. The total number of free parameters\nper row in the flat-field extractions is equal to 2 per fiber plus 10\nparameters to represent a smooth polynomial background. After the extractions\nare complete, $\\chi^2$ is computed by directly comparing the model fit\nto the flat-field image. The median $\\chi^2$ for each case is compared\ndirectly, and the better fit and profile (lower median $\\chi^2$) are retained\nand implemented for the extraction of the remaining frames. Also retained\nis a smooth polynomial fit the average profile width in each fiber bundle\nas a function of CCD row number.\n\nAfter all flat-field frames for a given sequence have been extracted\nand stored, the arc-lamp frames in the same sequence are extracted. \nEach arc-lamp frame is matched with the nearest (in time) \nnon-rejected flat-field frame. The matched flat-field gives the \ninitial trace centers to\nbe assumed, as well as the profile shape and width determined from the\nflat-field. To account for any flexure between the frames, the trace\ncenters are allowed to shift/stretch to the arc-lamp image given a \n3x3 polynomial distortion kernel over the entire extent of the image\n(match\\_trace.pro).\n\nThe arc-lamp frames are extracted row-by-row, in the same\nmanner as the flat-fields, the number of free parameters assumed\nfor the model fit is 2 per fiber (profile area and width) and 1 parameter\nto fit for a constant background per row. The restricted freedom in the\nbackground parameterization reflects the lower scattered light levels in\nthe images of the arc-lamps.\n\n\\subsection{(or arc-lamp spectra -> wavelength map)}\n\nWe determine an initial wavelength solution for every arc-lamp frame\nsuccessfully extracted in the following manner:\n\nFor the appropriate side of each spectrograph (red or blue), we \nconstruct a list of suitable unblended lines from a parent list including\nknown lines of Mercury, Cadmium, Neon and (a trace of) Argon \nthat are readily observable in the standard set of SDSS arc-lamps. \nA representative spectrum is calculated as the median extracted spectrum\nof the 5 closest \"unflagged\" spectra falling near the central columns \nof the arc-lamp image. This median arc-spectrum is matched with \ncross-correlation to a simulated spectrum of suitable arc-line positions and \nstrengths by systematically searching a small volume of \nparameter space which conservatively covers\nthe polynomial coefficients of the SDSS wavelength solution.\nIn the first iteration, we search a set of \n100 coefficient vectors allowing for quadratic changes and return \nthe best match. In the second iteration, we search in a smaller region\nabout the previous best match, and search a list of 125 coefficient vector\nallowing for cubic deviations. The coefficient vector with the best\nmatch from the second iteration is returned as an initial guess along with\nthe cross-correlation coefficient. \n\nWe apply the best guess coefficients to predict the approximate pixel \npositions of the suitable list of arc lines. The arc line centroids\nare traced across extracted spectra (along the axis of 320 fibers).\nThe centroids are fit to a smooth polynomial as a function of fiber\nposition on the arc-lamp image, and subsequently fit through 6 iterations\nwith simple flux weighting to arrive at a converged measure of line \ncentroids in each extracted spectrum. Lines are excluded from the resulting\nlist if the flux-weighted centroids are bad in more than 10\\% of the\nspectra or if the RMS residuals are larger than 20\\% of a pixel.\nWe perform an iterative 4th order Legendre polynomial fit of \nlogarithmic wavelength as a function of pixel in each spectrum, \nand retain a list of rejected centroids, \nwhich have deviations relative to the model of\n10\\% of a pixel width. An additional requirement is applied to each\nsuitable arc line, wherein the line is rejected in no more than 3 fibers\nper bundle of 20. Rejected centroids are replaced with the appropriate\npositions based on a linear interpolation of the differences of non-masked\ncentroids relative to updated polynomial fits per spectrum.\nThe final set of positions, where the same number of line positions have\nreliable centroids per spectrum, are fit with equal weighting per line\nposition to produce the final wavelength\ncoefficients which give the logarithmic (base 10) wavelengths as a function\nof spectral pixel.\n\nAn arc-lamp image is declared unacceptable using the first 4 tests as employed\nin tests of the flat-field images. In addition, an arc-lamp exposure\nis declared unacceptable (\"BAD\") if any of these following criteria are met:\n5) All 8 arc-lamps must be on, 4 Neon lamps and 5 Mercury-Cadmium lamps,\n6) The initial cross-correlation coefficient is less than 0.5,\n7) Less than 6 arc lines are acceptable after quality assurance checks.\n\nThe width of unblended arc lines are determined as an average over\neach bundle of 20 spectra. In short, the arc-lamp emission lines \nare extracted (with a Gaussian spectral profile) \nallowing free parameters for the area and width of each suitable line.\nThe resulting Gaussian widths per fiber bundle are fit \nwith a low order polynomial as a function of average line position\n(the fit is quadratic and cubic for the blue and red side respectively).\nThe fitted quantity is referred to as the arc-lamp dispersion,\nbut the values reflect the standard deviation of a Gaussian \nprofile in pixel units and represents the line-spread function of the \narc-lamp spectra.\n\n(or just refer to data model appendix instead of the paragraph below:)\n\nThe arc-lamp reductions are written to disk at this stage, and\nstored in an extended FITS file: HDU \\#0 contains the processed\nand extracted arc-lamp spectra as counts per pixel, HDU \\#1 contains\nthe identified arc line wavelengths and the measured line centroids\n(including replaced positions of rejections), HDU \\#2 contains a single\nstructure with the Legendre polynomial coefficients applicable to each\nof the 320 arc-lamp spectra, HDU \\#3 contains the maskbits for each spectrum,\nand HDU \\#4 contains the polynomial coefficients to describe the arc-lamp\nGaussian widths as a function of spectral pixel.\n\n\\subsection{Constructing fiber flats}\n\nThe final step in the reduction of the calibration frames in a given\nsequence is the construction of the fiber flat vectors. Each flat-field\nframe is matched to the nearest arc-lamp frame as before, and the\nfinal flat-field fiber spectra are extracted in two steps. The first\nstep uses the preferred spatial profile and width determined above,\nand the extraction procedure produces a model of the flat-field frame.\nThe model is used to subtract a diffuse scattered background given\nby an exponential point-spread function of : (CCD halo PSF).\nWe apply a 1-dimensional version of this 2-d PSF as an approximation,\nand allow the PSF to vary appropriately with wavelength.\nThe final extraction is applied to the scattered light subtracted flat-field\nimage allowing for 2 free paramters per fiber per row and \n5 background parameters per row.\n\nThe final flat-field spectra are stored as \ndetected counts per fiber per pixel with wavelengths of each pixel\ngiven by the associated solution of the arc-lamp frame. \nWe model the flat-field spectra as the product:\n\n\n\\begin{equation} \n{\\rm Flat Model}_{ij} = A * f_{avg}(\\lambda) \\, {\\rm fflat_i} (\\lambda) \n\\end{equation} \n\nwhere $A$ is a overall normalization in counts, \n$f_{avg}$ is the average response per constant logarithmic wavelength\ninterval, $fflat_i$ is the fiber-to-fiber response as a function of wavelength.\nThis model of the extracted flat-field spectra provides a transformation to\ncompare detected counts from one fiber to another. \n\nThis should remove the differential response due to the individual fiber\nthroughput, as well as the small relative differences in the size of the\nspectral pixels at a constant wavelength. ??Why do we correct for pixel\nsizes later on if the differential wavelength dispersion is included in fflat??\n\nThe common normalized response function, $f_{avg}$, is specified as a B-spline\nfunction with breakpoints spaced approximately every native pixels.\nAn example of normalized individual fiber spectra \nand the resulting B-spline fit are shown in Figure ?. The individual fiber\nflat vectors are fits to the ratio of the extracted spectra to the superflat\n(define above). The individual vector fits are also B-splines with breakpoints\nspaced approximately every 5 native pixels. The final set of flat vectors are\nstored as an image with dimensions Nfiber x Npixels.\n\n\n\\subsection{Object Extraction}\n\nWith the extracted calibration frames for a given spectroscopic sequence\nreduced, we proceed to extract the remaining science frames.\n%To minimize the differences between individual science frames\nWe first select a set of arc-lamp and flat-field frames as the common\nchoice of initial calibrations for all science frame extractions in a given\nobserving sequence. We loop through the science exposures, processing the\nraw images with bias and pixel-to-pixel flat images (see section ??).\nWe reject a science exposure outright if 1) more than 10\\% of the pixels\nare flagged as bad, 2) more than 100 rows are saturated, 3) the 25th\npercentile count level is greater than 1000 counts (the nominal level\nis of order 10 counts), 4) any of the flat-field petals are closed, or 5)\nany of the calibration lamps are recorded as on.\n\nInputs to object extraction include the wavelength coefficients derived\nfrom the associated arc-lamp exposure, both the superflat and fiber flat\nvectors from the selected flat-field exposure, the profile shape and width\nas a function of position on the CCD image.\n\nThe first step in object extraction is a simple tophat aperture (boxcar) \nextraction centered at the fiber positions determined from the flat-field \nand with a full spatial width of 6 CCD pixels. The median counts per fiber \nare passed directly to a test for overly bright fibers. Fiber spectra are \nidentified as bright (a.k.a. \"WHOPPING\") if the median counts per pixel in the \nboxcar extraction are greater than 10000 counts above the median in the \nframe. In addition, only the brightest fiber in a spatially contiguous set of \nbright fibers is labelled \"WHOPPING\". \n\nA pixelmask vector is created for each fiber spectrum to be extracted.\nSee Appendix ?? for a description of the mask bits and their use.\n\nWe fit for a slight distortion of the stored flat-field fiber traces to \nbest match the fiber positions of the science image. Nominal shifts and\ndistortions are usually less than a native CCD pixel. The science frame\nis now extracted in a series of 6 steps which we detail below.\n\n\\begin{enumerate}\n\\item{Initial extraction including broad wings of bright (WHOPPING) fibers.}\n\\item{Reconstruct a smooth background light model based on fitted parameters.}\n\\item{Calculate a scattered halo image using the model of the fiber spectra less\nthe aforementioned smooth background.}\n\\item{Re-extract fiber spectra on the scattered halo subtracted image.}\n\\item{Reconstruct smooth background and subtract.}\n\\item{Final extraction with no free parameters in the background and\nno free parameters in the profile widths.}\n\\end{enumerate}\n\nThe extracted science spectra are first normalized by the fiber flat vectors.\nStrong atmospheric emission lines (sky lines) are identified in the the \nset of spectra, and the wavelength solution is shifted to match the \nidentified lines. Examples of the shift corrections are shown in Figure ??. \nThe widths of the identified sky lines are also measured with the same method\nas the arc-line width measurements. All spectra are also normalized by\nthe average flat-field spectrum (the superflat) to remove small scale\nfeatures likely attributed to the chromatic response of the dichroic.\nThe wavelength solution is corrected to both vacuum wavelengths and the\nheliocentric velocity frame.\n\n\\subsection{Sky Subtraction}\n\nSky subtraction is performed on a frame by frame basis using the \n\"flattened\" wavelength calibrated extractions. The goal of sky subtraction\nis to estimate the expected background counts contributing to each of \nthe native 320x2048 pixels in each extracted frame. A \"supersky\" model \nat a fiducial airmass of 1 is constructed by performing iterative fits to\nthe extracted spectra associated with blank sky positions (so-called\n\"sky\" fibers). The following steps are taken in 3 sequential iterations\nin order to produce the sky-subtracted spectra:\n\n\\begin{enumerate}\n\n\\item{Identify the \"sky\" fibers which have no bits flagged \nin the fiber mask array.}\n\n\\item{Divide each sky spectrum by the airmass of the fiber position appropriate\nfor the midpoint of the observation to produce respresentative sky spectra for \nan airmass of 1. The inverse variance is scaled accordingly.}\n\n\\item{Group and sort the sky spectra as a function of wavelength. This step\ntransforms a 2-dimensional set of $N_{\\rm sky}$ x 2048 pixels into a sorted 1-dimensional array. \nEach pixel maintains its associated central wavelength and inverse variance. }\n\n\\item{Perform a single cubic b-spline fit as a function of wavelength. \nThe number of breakpoints (number of free parameters is 4 greater) is set \nat 2048 on the red side and 1536 on the blue side. The breakpoint spacing \nis set automatically to maintain approximately constant S/N between breakpoint \npositions. The b-spline fit itself is iterative, with upper and lower rejection \nthresholds set to mask bad or deviant pixels. }\n\n\\item{The b-spline fit is evaluated at all 320x2048 wavelengths representing all\nspectral pixels in the frame. The airmass correction is applied for each individual \nfiber, and the rescaled super-sky is subtracted from each spectrum.}\n\n\\item{Estimate the significance of the residuals in the sky fibers used for the\nfit in wavelength bins separated by breakpoints determined above. for each bin\nwhere inverse the 67th percentile of $\\chi^2$ is greater than 1, we rescale \nall the inverse variance values down by the 67th percentile value of $\\chi^2$.\nThe rescaling is actually done with a smooth interpolation as a function of \nredshift with a constraint that the inverse variances cannot increase. }\n\n\\end{enumerate}\n\n%The b-spline routines from the numerical fortran library: {\\bf slatec}\n%were ported to IDL to be easily incorporated into the pipeline.\n\nThe sequence followed in the determination of the sky subtracted spectrum\nand re-scaled errors is called 3 times successively. After the 1st call,\nany sky fibers which have a median $\\chi^2$ per pixel greater than 2 is \nmasked as a 'BADSKYFIBER' and the corresponding bit is set in the fibermask\narray. If any fibers are masked, the sky subtraction is iterated a 2nd time.\nThe sky subtraction routine is invoked for one final iteration, but with extra \nfreedom allowed in the fit. The same freedom is allowed in wavelength, by\nkeeping the same number of breakpoints, but a quadratic polynomial fit is\nallowed as a function of wavelength. This triples the number of free \nparameters in the linear least-squares fit, but the values are still \noverconstrained due to the ample number of sky fibers. The extra freedom\nin the model can accomodate variation in the PSF of sky features as a function \nof position on the CCD.\n\nThe sky subtraction method which utilizes the b-spline model takes advantage \nof the inherent over-sampling in wavelength due to the large number of \nsky fibers assigned per plate, without the requirement of resampling the \npixel value to a fixed linear wavelength scale. The least squares fit\nis carried out for native spectral pixels where the errors are very nearly \nuncorrelated and the fit is evaluated for all the native pixels (320x2048) \nat the central wavelengths of the single spectral frames.\n \nThe accuracy of the SDSS spectral sky subtraction has been tested in recent\nscientific analyses using large numbers of background-limited spectra. \nThe distribution of flux residuals between spectral observations \non separate nights has been shown to be 8\\% larger in width than the average expected\nfrom the reported errors (McDonald et al. 2004, Burgess \\& Burles 2005).\nThe spectra of faint, background-limited galaxies observed with SDSS exhibit a \ndistribution of residuals about the best fit spectral models described by the sum of a\nGaussian and Laplace distribution (Bolton et al. 2004). \nThe influence of the exponential tail is greatly enhanced in the vicinity of strong sky \nemission lines representative of systematic errors in the brightest lines, but the gaussian \nwidth closely is closely represented by the reported variance array.\n\n\\end{document}\n\n", "meta": {"hexsha": "50bf9649ef36f15475ceaf72dad4d3fff0a222d4", "size": 21498, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "src/idl/extern/sdss/idlspec2d-v5_2_0/doc/paper/skysubtraction.tex", "max_stars_repo_name": "sfarrens/cosmostat", "max_stars_repo_head_hexsha": "a475315cda06dca346095a1e83cb6ad23979acae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-02-09T05:03:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-26T10:20:02.000Z", "max_issues_repo_path": "src/idl/extern/sdss/idlspec2d-v5_2_0/doc/paper/skysubtraction.tex", "max_issues_repo_name": "sfarrens/cosmostat", "max_issues_repo_head_hexsha": "a475315cda06dca346095a1e83cb6ad23979acae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2020-04-28T17:09:50.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-01T16:24:43.000Z", "max_forks_repo_path": "src/idl/extern/sdss/idlspec2d-v5_2_0/doc/paper/skysubtraction.tex", "max_forks_repo_name": "sfarrens/cosmostat", "max_forks_repo_head_hexsha": "a475315cda06dca346095a1e83cb6ad23979acae", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-06-22T07:53:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-10T19:59:53.000Z", "avg_line_length": 54.4253164557, "max_line_length": 140, "alphanum_fraction": 0.7972369523, "num_tokens": 4703, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.3040416749665474, "lm_q1q2_score": 0.18475492797147391}}
{"text": "\\section{Introduction to \\castro}\n\n\\castro\\ is a adaptive mesh, radiation hydrodynamics code that is\ndesigned to model astrophysical reacting flows on massively parallel\ncomputers.\n\nThe major capabilities:\n\\begin{itemize}\n\\item 1-, 2-, and 3-dimensional unsplit, 2nd-order hydrodynamics\n\\item multigroup flux-limited diffusion radiation hydrodynamics\n\\item adaptive mesh refinement with subcycling; jumps of 2x and 4x between levels\n\\item arbitrary equation of state (gamma-law and stellar EOSes are bundled)\n\\item general nuclear reaction networks\n\\item explicit thermal diffusion\n\\item full Poisson gravity (with isolated boundary conditions)\n\\item rotation (in the co-rotating frame) in 2-d axisymmetric and 3-d.\n\\item parallelization via MPI + OpenMP\n\\end{itemize}\n\n\n\n\\section{Units and Conventions}\n\n\\castro\\ works in CGS units unless otherwise specified.\nTable~\\ref{table:units} shows some of the common symbols / names used\nthroughout the code documentation and papers.\n\n\\begin{table}[t]\n\\renewcommand{\\arraystretch}{1.2}\n\\centering\n\\begin{tabular}{lll}\nname & units & description \\\\\n\\hline\n$t$ & s & time \\\\\n$\\rho$ & $\\gcc$ & mass density \\\\\n$\\ub$ & $\\cms$ & velocity vector \\\\\n$p$ & $\\presunit$ & pressure \\\\\n$\\gb$ & $\\accelunit$ & gravitational acceleration \\\\\n$\\Sb$ & varies & source term \\\\\n$E$ & $\\ergg$ & specific total energy \\\\\n$e$ & $\\ergg$ & specific internal energy \\\\\n$T$ & $K$ & temperature \\\\\n$\\kth$ & $\\mathrm{erg~cm^{-1}~s^{-1}~K~{-1}}$ & thermal conductivity \\\\\n$X_k$ & -- & mass fraction of species $k$ \\\\\n$\\omegadot_k$ & $\\mathrm{s^{-1}}$ & species creation rate (from reactions) \\\\\n\\hline\n\\end{tabular}\n\\caption{\\label{table:units} Common quantities and units.}\n\\renewcommand{\\arraystretch}{1.0}\n\\end{table}\n\nPhysical constants, again using the CGS system are available \nin {\\tt Castro/constants/constants\\_cgs.f90}\n\n", "meta": {"hexsha": "9b31816774b410c068cd123ab341ef6a707d100d", "size": 1908, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Docs/Introduction/Introduction.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/Introduction/Introduction.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/Introduction/Introduction.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": 34.6909090909, "max_line_length": 81, "alphanum_fraction": 0.7038784067, "num_tokens": 530, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266116, "lm_q2_score": 0.34510526422232046, "lm_q1q2_score": 0.1846652845961353}}
{"text": "\\section{Algorithm}\n\\label{sec:algorithm}\n\nIn this section, we describe the steps of our instance-based\nPOS-induction algorithm:\n\\begin{enumerate}\n \\item Sample $r$ substitutes for each word instance in the target\n corpus using an n-gram language model.\n \\item Construct $r$ tuples for each instance where each tuple\n consists of a sampled substitute, the target word, and the\n morphological and orthographical features of the target word (see\n Table~\\ref{tab:sampleswithfeatures}).\n \\item Construct Euclidean embeddings of each word and each feature based on\n all tuples following Gleberson et al.\\shortcite{globerson2007euclidean}\n and Maron et al.\\shortcite{maron2010sphere}.\n \\item Construct a vector representation for each instance by\n concatenating the embedding of the target word with the average of\n its substitute embeddings.\n \\item Use $k$-means clustering to cluster the instance vectors where\n $k$ is equal to the number of gold tags.\n %% \\item Construct a mapping from clusters to tags for evaluation using\n %% the most frequent tag found in each cluster.\n\\end{enumerate}\n\nSteps 1 and 2 construct a tuple representation for each instance.\nTable~\\ref{tab:sampleswithfeatures} gives some example tuples for Sentence (1)\nfrom the previous section. In this example $r=3$, so three substitutes are\nsampled for each instance as contextual features. The sampling is with\nreplacement from the substitute word distribution of a context given by the\nn-gram language model, so some substitute words may be repeated. The target\nword and its other features are identical for each of the $r$ tuples\nrepresenting a single instance.\n\n\\begin{table}[t]\n \\centering\n \\begin{tabular}{|lllll|}\n \\hline\n {\\bf Word} & {\\bf Subst} & {\\bf Suf} & {\\bf Cap} & {\\bf Num} \\\\\n \\hline\n Vinken & Makhlouf & -- & T & F\\\\\n Vinken & Makhlouf & -- & T & F\\\\\n Vinken & \\unk & -- & T & F\\\\\n 61 & 20 & -- & F & T\\\\\n 61 & 2000 & -- & F & T\\\\\n 61 & eleven & -- & F & T\\\\\n years & years & -s & F & F\\\\\n years & years & -s & F & F\\\\\n years & years & -s & F & F\\\\\n \\hline\n \\end{tabular}\n \\caption{The tuples constructed for the instances of ``Vinken'',\n ``61'' and ``years'' from Sentence (1). The elements of each tuple\n are the target word, sampled substitute, suffix, capitalization, and\n number features.}\n \\label{tab:sampleswithfeatures}\n\\end{table}\n\n%% We construct the co-occurrence data as word--features tuples that consist of\n%% word, and its contextual (substitutes), orthographic and morphological\n%% features. Contextual features are sampled from the substitute word\n%% distribution of the instance context. If $r$ random substitutes are sample for\n%% each instance than there will be $r$ identical tuples except the contextual\n%% features. Table~\\ref{tab:sampleswithfeatures} presents the co-occurrence\n%% tuples of each instance in a sample sentence when $r$ is equal to 1. \n\n%% \\begin{table*}[!t]\n%% \\centering\n%% \\footnotesize\n%% \\begin{tabular}{|lllllll|}\n%% \\hline\n%% \\textbf{Word} & {\\bf Contextual} & {\\bf Morphology} &\n%% \\specialcell{{\\bf Initial}\\\\{\\bf Capital}} & {\\bf Number} &\n%% \\specialcell{{\\bf Contains}\\\\{\\bf Hypen}} &\n%% \\specialcell{{\\bf Initial}\\\\{\\bf Apostrophe}}\n%% \\\\\n%% \\hline\n%% W:Pierre & \\textit{C:Adrian} & & {\\it F:IC} &&&\\\\\n%% W:Vinken & \\textit{C:Danon} & & {\\it F:IC} &&&\\\\\n%% W:, & \\textit{C:\\{} & & &&&\\\\\n%% W:61 & \\textit{C:fourteen} & & & {\\it F:N}&&\\\\\n%% W:years & \\textit{C:years} & {\\it F:s} &&&&\\\\\n%% %%W:old & \\textit{C:old} & & &&&\\\\\n%% %%W:join & \\textit{C:head} &&&&&\\\\\n%% %%W:the & \\textit{C:its} &&&&&\\\\\n%% %%W:board & \\textit{C:company} &&&&&\\\\\n%% %%W:as & \\textit{C:as} &&&&&\\\\\n%% %%W:a & \\textit{C:a} &&&&&\\\\\n%% %%W:nonexecutive & \\textit{C:non-executive} &&&&&\\\\\n%% %%W:director & \\textit{C:chairman} & {\\it F:or}&&&&\\\\\n%% %%W:Nov. & \\textit{C:May} &&{\\it F:IC}&&&\\\\\n%% %%W:29 & \\textit{C:9} &&&{\\it F:N}&&\\\\\n%% %%W. & \\textit{C:.} & &&&&\\\\\n%% \\hline\n%% \\end{tabular}\n%% \\caption{The first five words of the input sentence \\textit{``Pierre Vinken, 61\n%% years old, will join the board as a nonexecutive director Nov.~29 .''} is\n%% represented with their contextual, orthographic and morphological features as\n%% tuples. The leftmost column presents the target word, second column\n%% represents the contextual, third column is the morphological and the rest of\n%% the columns are the orthographic features. Unobserved features are set to\n%% null.}\n%% \\label{tab:sampleswithfeatures}\n%% \\end{table*}\n\nIn step 3, we construct Euclidean embeddings for each unique word and\nfeature value using the multi-variable version of the CODE algorithm\ndescribed in \\cite{globerson2007euclidean}. Given two categorical\nvariables $W$ and $F$, the CODE algorithm constructs Euclidean\nembeddings (vectors) for each of their distinct values in the same\nspace. The distance between the embedding of a $w$ value, $\\phi(w)$,\nand the embedding of an $f$ value, $\\psi(f)$, is related to their joint\ndistribution $p(w, f)$ as\nfollows\\footnote{\\cite{globerson2007euclidean} describes several ways\n to relate distances to probabilities, the model used here is the\n marginal-marginal (MM) model.}\n\n\\[ p(w,f) = \\frac{1}{Z} \\bar{p}(w) \\bar{p}(f) e^{-d^2_{w,f}} \\]\n\n\\noindent where $\\bar{p}$ represents empirical probabilities\n(frequencies from the training data), $d_{w,f}$ is the distance\nbetween the embeddings $\\phi(w)$ and $\\psi(f)$ and $Z=\\sum_{w,f}\n\\bar{p}(w) \\bar{p}(f) e^{-d^2_{w,f}}$ is a normalization constant.\nStarting with random vectors for each distinct value of $w$ and $f$,\nwe use stochastic gradient ascent to move the embedding vectors around\nto maximize the likelihood given by this model. Calculating the\nnormalization constant $Z$ is the most expensive part of this\nprocedure. We solve this problem following \\cite{maron2010sphere} who\nsuggest that a constant $Z$ approximation can be used if the embedding\nvectors are kept on the unit sphere.\n\nAs Table~\\ref{tab:sampleswithfeatures} shows, considering the target\nword and its contextual, morphological and orthographic features gives\nus more than two variables. Yatbaz et al. \n\\shortcite{yatbaz-sert-yuret:2012:EMNLP-CoNLL} adopt the two\nvariable CODE algorithm to this multi-variable case in an ad-hoc\nmanner by considering the target word as $w$ and all other features as\ndistinct $f$ values. We implement the multi-variable extension of\nCODE suggested by \\cite{globerson2007euclidean} (Section 6.2) which\noptimizes the following likelihood function:\n\n\\[ \\ell(\\phi, \\psi^{(1)}, \\ldots, \\psi^{(K)}) = \n \\sum_{i=1}^K \\sum_{w,f^{(i)}} \\bar{p}(w,f^{(i)}) \\log p(w,f^{(i)}) \\]\n\n\\noindent where $w$ are the target words, $\\phi$ are the embeddings of\ntarget words, $K$ is the number of different types of\nfeatures\\footnote{For example the number of features $K=4$ in\n Table~\\ref{tab:sampleswithfeatures}: Subst, Suf, Cap, and Num.},\n$f^{(i)}$ are the values of the $i$'th feature, and $\\psi^{(i)}$ are\nthe embeddings for the values of the $i$'th feature. This extension\ncan be seen as a set of $K$ bivariate CODE models $p(w,f^{(i)})$ that\nshare the same target word embeddings $\\phi(w)$ but build their own\nfeature embeddings $\\psi^{(i)}(f^{(i)})$.\n\n%% To handle co-occurrence tuples we use the modified version of S-CODE that can\n%% model more than two variables (see Appendix~\\ref{app:multiscode}). We feed\n%% the tuples to the modified S-CODE which places $n$-dimensional embeddings for\n%% word types that frequently co-occur with the same features (and features that\n%% co-occur with the same words types) close to each other on the sphere.\n%% Figure~\\ref{fig:scodeexample} illustrates the embeddings of a sample\n%% co-occurrence data on a sphere after S-CODE converges. This modified S-CODE is\n%% aware of the feature types which enables us to construct our instance based\n%% representation. In addition, the modified S-CODE can weight the different\n%% feature types and this will be the interest of future work. \n\n%% \\begin{figure}[h]\n%% \\centering\n%% \\begin{minipage}[c]{0.49\\columnwidth}\n%% \\footnotesize\n%% \\begin{tabular}{l|l}\n%% \\textbf{Word} & \\textbf{Substitute} \\\\\n%% \\hline\n%% $\\hdots$&$\\hdots$\\\\\n%% W:director & S:chairman \\\\\n%% W:chief & S:chairman \\\\\n%% $\\hdots$&$\\hdots$\\\\\n%% W:Pierre & S:John \\\\\n%% W:Frank & S:John \\\\\n%% $\\hdots$&$\\hdots$\\\\\n%% \\end{tabular}\n%% \\end{minipage} \\hfill\n%% \\begin{minipage}[c]{0.49\\columnwidth}\n%% \\raisebox{-\\height}{\n%% \\includegraphics[width=1\\columnwidth]{scode-ex.png}\n%% }\n%% \\end{minipage}\n%% \\caption{The table on the left is a co-occurrence data and figure on the\n%% right represents the final embeddings of the words and contextual features\n%% after S-CODE converges. Dashed circles represent the possible groupings of the\n%% word type embeddings on the sphere.}\n%% \\label{fig:scodeexample}\n%% \\end{figure}\n\n%The limitation of representing co-occurrence data as pairs is that S-CODE can\n%not distinguish whether the type of the word-feature pair is contextual,\n%orthographic or morphological. \n\nStep 4 constructs a vector representation for each word instance with the\nconcatenation of its word type embedding and the average of its $r$ substitute\nembeddings. If the original embeddings are in $d$ dimensional space, this\nresults in a $2d$ dimensional vector representing an instance.\n\nStep 5 clusters these $2d$ dimensional instance vectors using a\nmodified k-means algorithm with smart initialization\n\\cite{arthur2007k} and assigns each instance to one of $k$ clusters.\n%% Step 6 constructs a mapping between the clusters and the gold tags\n%% for evaluation. \n\n%% Yatbaz et al.\\shortcite{yatbaz-sert-yuret:2012:EMNLP-CoNLL} model co-occurrence\n%% pairs using the S-CODE with two variables and cluster the embeddings of word\n%% types with weighted k-means algorithm. The sentences in\n%% Figure~\\ref{fig:typelimitation} illustrates the limitation of clustering word\n%% type embeddings. The word {\\em offer} is a {\\em verb} in the first sentence\n%% and a {\\em noun} in the second one. S-CODE constructs only one embedding for\n%% each unique word type and feature value. Thus clustering the word type\n%% embeddings is actually applying the one-tag-per-word assumption.\n\n%% \\begin{figure}[ht]\n%% % \\begin{minipage}[c]{\\columnwidth}\n%% \\begin{tabular}{ll}\n%% (1) & $\\hdots$ it will also {\\em offer} buyers the option $\\hdots$\\\\\n%% &{\\bf Substitutes:} give, help, attract\\\\ \n%% (2) & The {\\em offer} is being launched $\\hdots$\\\\ \n%% &{\\bf Substitutes:} campaign, project, scheme\\\\ \n%% \\end{tabular}\n%% \\caption{Ambiguous occurrences of the word {\\em offer}.}\n%% \\label{fig:typelimitation}\n%% %\\end{minipage} \\hfill\n%% \\end{figure}\n%% On the other hand, the substitutes of {\\em offer} in both of the sentences can\n%% semantically and syntacticly disambiguates the correct category of the\n%% corresponding occurrences. \n\n%% The next section presents the results of our system and compares them with the\n%% results of the word based state-of-the-art system. \n%% To construct the co-occurrence data we pair each word instance with randomly\n%% sampled substitutes that can be observed in the context of the corresponding\n%% instance and with orthographic and morphological features of the word instance.\n%% Random substitutes were sampled (with replacement) from a substitute word\n%% distribution for the context calculated based on an n-gram language model. \n%% \n%% We enriched the word--substitute co-occurrence data by extracting morphological\n%% and orthographic features and incorporating them as word--feature pairs. They\n%% fed the co-occurrence data into the S-CODE algorithm. S-CODE places the\n%% embeddings for word types that frequently co-occur with the same substitutes or\n%% features (and substitutes or features that co-occur with the same words) close\n%% to each other on the $n$-dimensional sphere. Finally, they apply k-means\n%% clustering to group vectors of word types to induce word categories.\n%% \n%% First, we construct a pairwise co-occurrence\n%% representation of words and their substitutes. Next, we map each word and each\n%% substitute in the co-occurrence data to real vectors (embeddings) on an\n%% $n$-dimensional sphere using the S-CODE algorithm \\cite{maron2010sphere}.\n%% S-CODE places the vectors for words that frequently co-occur with the same\n%% substitutes (and substitutes that co-occur with the same words) close to each\n%% other on the sphere. We then construct vectors for each word instance by using\n%% the embeddings of the word itself and its sampled substitutes in the\n%% co-occurrence data. Finally, we apply k-means clustering to group these\n%% vectors to induce word categories. \n%% \n%% In Section~\\ref{sec:cooc} we detail the representation of words and their\n%% substitutes as co-occurrence data, in Section~\\ref{sec:embedding} we describe\n%% the embedding algorithm, and finally Section~\\ref{sec:clustering} describes how\n%% we represent the word instances using the embeddings calculate in the previous\n%% step.\n%% \n%% \\subsection{Context Representation}\n%% \\label{sec:cooc}\n%% % How we represent the context?\n%% % How we relate the word and the context?\n%% \n%% We represent the context of a word with random substitutes that are\n%% likely to occupy the same position as the word. We sample random\n%% substitutes (with replacement) from a substitute word distribution for\n%% the context calculated based on an n-gram language model. The sample\n%% space of the substitute word distribution is the vocabulary of the\n%% language model.\n%% %% \\footnote{Sampled substitutes might include the unknown\n%% %% word tag \\unk\\ representing words outside the fixed size\n%% %% vocabulary of the language model. For example proper nouns\n%% %% typically have \\unk\\ as a substitute.} \n%% In effect, we are using substitute word distributions and the sampled random\n%% substitutes as {\\em contextual features} that represent properties of a word's\n%% position. Table~\\ref{tab:subdist} shows the substitute word distributions for\n%% some positions in an example sentence.\n%% %% \\begin{table*}[t]\n%% %% \\footnotesize\n%% %% \\centering\n%% %% \\caption{The substitute word distributions (with probabilities in\n%% %% parentheses) for some of the positions in the example sentence\n%% %% \\textit{``Pierre Vinken, 61 years old, will join the board as a\n%% %% nonexecutive director Nov.~29.''} based on a 4-gram language\n%% %% model.}\n%% %% \\label{tab:subdist}\n%% %% \\begin{tabular}{|ll|} \\hline\n%% %% \\textbf{will:} & \\textit{will} (0.9985), \\textit{would} (0.0007), \\textit{to} (0.0006), \\textit{also} (0.0001), $\\ldots$ \\\\\n%% %% \\textbf{join:} & \\textit{join} (0.6528), \\textit{leave} (0.2140), \\textit{oversee} (0.0559), \\textit{head} (0.0262), \\textit{rejoin} (0.0074), $\\ldots$ \\\\\n%% %% \\textbf{the:} &\\textit{its} (0.9011), \\textit{the} (0.0981), \\textit{a} (0.0006), $\\ldots$ \\\\\n%% %% \\textbf{board:} & \\textit{board} (0.4288), \\textit{company} (0.2584), \\textit{firm} (0.2024), \\textit{bank} (0.0731), \\textit{strike} (0.0030), $\\ldots$ \\\\\n%% %% \\hline\n%% %% \\end{tabular}\n%% %% \\end{table*}\n%% %%\n%% To capture the relation between each word and its context we construct\n%% a co-occurrence representation by pairing the words with randomly\n%% sampled substitutes. Table~\\ref{tab:samples} shows random substitutes of each\n%% word and their pairwise co-occurrence representation input to S-CODE on an\n%% example sentence. It is possible (and beneficial) to sample more than one\n%% substitute and generate multiple pairs for the same word-context pair as seen\n%% in Table~\\ref{tab:samples}. In the co-occurrence data, a target word might\n%% appear both as a word and a random substitute therefore to clarify this\n%% ambiguity we prepend ``W:'' and ``S:'' to words and substitutes, respectively.\n%% The calculation of substitute distributions and substitute word sampling are\n%% detailed in Appendix~A.\n%% %% \\begin{table}[h]\n%% %% \\footnotesize\n%% %% \\caption{The table on the left shows three possible substitutes\n%% %% sampled with replacement for each position in an example sentence\n%% %% based on a 4-gram language model. The table on the right is the\n%% %% pairwise co-occurrence data fed to the S-CODE algorithm derived\n%% %% from these samples. The prefixes ``W:'' and ``S:'' are used to\n%% %% distinguish target words and substitutes. Sampled substitutes\n%% %% might include the unknown word tag ``\\unk'' representing words\n%% %% outside the fixed size vocabulary of the language model.}\n%% %% \\begin{tabular}{|ll|} \\hline\n%% %% \\textbf{Word} & \\textbf{Random Substitutes}\\\\\n%% %% \\hline\n%% %% Pierre & \\textit{Mr.} / \\textit{Pierre} / \\textit{John}\\\\\n%% %% Vinken & \\textit{\\unk} / \\textit{Beregovoy} / \\textit{Cardin}\\\\\n%% %% %, & \\textit{,} / \\textit{,} / \\textit{,}\\\\\n%% %% %61 & \\textit{48} / \\textit{52} / \\textit{41}\\\\\n%% %% %years & \\textit{years} / \\textit{years} / \\textit{years}\\\\\n%% %% %old & \\textit{old} / \\textit{old} / \\textit{old}\\\\\n%% %% %, & \\textit{,} / \\textit{,} / \\textit{,}\\\\\n%% %% %will & \\textit{will} / \\textit{will} / \\textit{will}\\\\\n%% %% $\\hdots$&\\\\\n%% %% join & \\textit{head} / \\textit{join} / \\textit{leave}\\\\\n%% %% the & \\textit{its} / \\textit{its} / \\textit{the}\\\\\n%% %% %board & \\textit{board} / \\textit{company} / \\textit{firm}\\\\\n%% %% $\\hdots$&\\\\\n%% %% %as & \\textit{as} / \\textit{as} / \\textit{as}\\\\\n%% %% %a & \\textit{a} / \\textit{a} / \\textit{a}\\\\\n%% %% %nonexecutive & \\textit{nonexecutive} / \\textit{non-executive} / \\textit{nonexecutive}\\\\\n%% %% $\\hdots$&\\\\\n%% %% director & \\textit{chairman} / \\textit{chairman} / \\textit{director}\\\\\n%% %% $\\hdots$&\\\\\n%% %% %Nov. & \\textit{April} / \\textit{May} / \\textit{of}\\\\\n%% %% %29 & \\textit{16} / \\textit{29} / \\textit{9}\\\\\n%% %% %. & \\textit{.} / \\textit{.} / \\textit{.}\\\\\n%% %% \\hline\n%% %% \\end{tabular}\n%% %% \\quad\n%% %% \\begin{tabular}{|ll|}\n%% %% \\hline\n%% %% \\textbf{Word} & \\textbf{Substitute}\\\\\n%% %% \\hline\n%% %% W:Pierre & \\textit{S:Mr.}\\\\\n%% %% W:Pierre & \\textit{S:Pierre}\\\\\n%% %% W:Pierre & \\textit{S:John}\\\\\n%% %% W:Vinken & \\textit{S:\\unk}\\\\\n%% %% W:Vinken & \\textit{S:Beregovoy}\\\\\n%% %% W:Vinken & \\textit{S:Cardin}\\\\\n%% %% $\\hdots$&\\\\\n%% %% W:join & \\textit{S:head}\\\\\n%% %% W:join & \\textit{S:join}\\\\\n%% %% W:join & \\textit{S:leave}\\\\\n%% %% W:the & \\textit{S:its}\\\\\n%% %% W:the & \\textit{S:its}\\\\\n%% %% W:the & \\textit{S:the}\\\\\n%% %% $\\hdots$&\\\\\n%% %% W:director & \\textit{S:chairman}\\\\\n%% %% W:director & \\textit{S:chairman}\\\\\n%% %% W:director & \\textit{S:director}\\\\\n%% %% $\\hdots$&\\\\\n%% %% \\hline\n%% %% \\end{tabular}\n%% %% \\label{tab:samples}\n%% %% \\end{table}\n%% \n%% The next section describes the S-CODE algorithm which takes the\n%% pairwise co-occurrence data as its input and calculates the embeddings\n%% of the words and their substitutes on an $n$-dimensional sphere.\n%% \n%% \\subsection{Co-occurrence Embedding}\n%% \\label{sec:embedding}\n%% The S-CODE algorithm maps each unique word and substitute in the\n%% co-occurrence data to a real vector (embedding) on an $n$-dimensional\n%% sphere as detailed in Appendix~B. The basic idea of the mapping is\n%% that words and substitutes that are frequently observed as pairs in\n%% the co-occurrence data will have close embeddings while pairs\n%% not observed together will have embeddings that are far apart from each\n%% other.\n%% \n%% %% \\begin{minipage}[c]{0.28\\columnwidth}\n%% %% \\footnotesize\n%% %% \\begin{tabular}{l|l}\n%% %% \\textbf{Word} & \\textbf{Substitute} \\\\\n%% %% \\hline\n%% %% $\\hdots$&$\\hdots$\\\\\n%% %% W:offer & S:give\\\\\n%% %% W:offer & S:help\\\\\n%% %% W:offer & S:attract\\\\\n%% %% W:offer & S:campaign\\\\\n%% %% W:offer & S:project\\\\\n%% %% W:offer & S:scheme\\\\\n%% %% $\\hdots$&$\\hdots$\\\\\n%% %% \\end{tabular}\n%% %% \\end{minipage} \\hfill\n%% %% \n%% %% \\begin{minipage}[c]{\\columnwidth}\n%% %% \\raisebox{-\\height}{\n%% %% \\includegraphics[width=0.5\\columnwidth]{sphere.png}\n%% %% }\n%% %% \\end{minipage}\n%% %% \\caption{The figure on the left presents the input sentences and the randomly\n%% %% sampled substitutes of the word {\\em offer} in each sentences. The right\n%% %% one presents the final embeddings on a representative sphere after S-CODE\n%% %% converges.}\n%% %% \\label{fig:scodeexample}\n%% %% \\end{figure}\n%% \n%% The co-occurrence data in Figure~\\ref{fig:scodeexample} consists of\n%% pairs such as (\\textit{W:director}, \\textit{S:chairman}) and\n%% (\\textit{W:chief}, \\textit{S:chairman}) therefore S-CODE forces the\n%% embeddings of \\textit{W:director} and \\textit{W:chief} to be close to\n%% the embedding of \\textit{S:chairman}. Similarly the embeddings of\n%% \\textit{W:Pierre} and \\textit{W:Frank} will be close to the embedding\n%% of \\textit{S:John} because they are frequently co-occurring pairs. As\n%% a result the final embeddings of \\textit{W:director} and\n%% \\textit{W:chief} will be close to each other due to the common\n%% substitute \\textit{S:chairman} and will be apart from\n%% \\textit{W:Pierre} and \\textit{W:Frank} due to the lack of common\n%% substitutes (similarly the embeddings of \\textit{W:Pierre} and\n%% \\textit{W:Frank} will be close to each other due to \\textit{S:John}).\n%% \n%% The coordinates of the embeddings for each unique word and substitute\n%% constitute the input to the clustering stage as described in the next\n%% subsection.\n%% \n%% % How we relate final embeddings and the input pairs?\n%% %% S-CODE constructs embeddings on an $n$-dimensional sphere for each word\n%% %% type and substitute. Each pair in the co-occurrence data can be\n%% %% represented in three different ways by using the output of S-CODE: (1)\n%% %% word embedding (${\\bf W}$) which represents the word type information,\n%% %% (2) substitute embedding (${\\bf C}$) which represents the context\n%% %% information, and (3) concatenation of word and substitute embeddings\n%% %% (${\\bf W}\\oplus{\\bf C}$). In the next section we apply k-means\n%% %% clustering to these three representation and analyze the\n%% %% characteristic of final clusters.\n%% \n%% \\subsection{Clustering}\n%% \\label{sec:clustering}\n%% %% In Section~\\ref{sec:cooc} we describe the transformation of an input\n%% %% sentence to a co-occurrence data and we represent each target word\n%% %% with the word--substitute pair(s). In the previous section we\n%% %% construct embeddings for each value observed in the co-occurrence data\n%% %% using the S-CODE algorithm. \n%% \n%% At this stage, each unique word in the text and each unique substitute\n%% sampled to represent their contexts is mapped to a real vector\n%% embedding on an $n$ dimensional sphere\\footnote{In fact many words\n%% that appear in the text also appear as substitutes and thus get two\n%% embeddings.}. We apply the instance weighted k-means clustering\n%% algorithm to three different representations derived from these\n%% embeddings, each with its own advantages and disadvantages:\n%% \n%% \\paragraph{Type Based:} \n%% In this clustering, each target word {\\em type} has a single embedding, and gets\n%% assigned to a single cluster. Clustering word embeddings was previously\n%% explored in \\cite{yatbaz-sert-yuret:2012:EMNLP-CoNLL}, which achieved the best\n%% results to date (80\\% \\mto) for English. Sections~\\ref{sec:typevsinstance}\n%% summarize these experiments for completeness. \n%% %% \\paragraph{Clustering substitute embeddings (${\\bf S}$)} \n%% %% In a second set of experiments, we ignore target word embeddings and\n%% %% apply clustering only to substitute embeddings, associating each\n%% %% substitute with a unique cluster. We then categorize target word {\\em\n%% %% tokens} based on what cluster the majority of their substitutes\n%% %% belong. It is important to note that in this setting we are ignoring\n%% %% the identity and features of the target words and in effect clustering\n%% %% word contexts (substitutes are determined by the context and are\n%% %% conditionally independent of the target word).\n%% %% \n%% %% For example, the target word {\\it W:board} in Table~\\ref{tab:samples}\n%% %% will be represented with the embeddings of {\\it S:board}, {\\it\n%% %% S:company} and {\\it S:firm} while another occurrence of the word\n%% %% {\\it W:board} in a different context might be represented with\n%% %% embeddings of different substitutes such as {\\it S:embark} or {\\it\n%% %% S:enter}. Each occurrence of the target word ``board'' is assigned\n%% %% to the cluster in which the majority of its substitute embeddings are\n%% %% present\\footnote{Ties are broken randomly.}. This approach generally\n%% %% results in higher accuracy for highly ambiguous words like {\\em offer}\n%% %% where clustering substitute embeddings achieves .82 \\mto\\ compared\n%% %% to the one-tag-per-word upper bound of .74.\n%% %% Section~\\ref{sec:clustering-s} presents the results of experiments\n%% %% clustering substitute embeddings.\n%% %% \n%% %% Unfortunately such highly ambiguous words do not constitute a\n%% %% significant portion of the corpus and the overall accuracy suffers\n%% %% (.64 compared to .80 \\mto\\ for word clustering). We also observed\n%% %% similar results in our preliminary experiments without S-CODE trying\n%% %% to cluster contexts directly (using the Kullback-Leibler divergence\n%% %% between their substitute distributions). Many common words that occur\n%% %% in similar contexts and that have similar substitutes, e.g. {\\em his}\n%% %% and {\\em the}, belong to different parts of speech. In addition,\n%% %% words that are generally not substitutable like ``do'' and ``put'' are\n%% %% placed in the same category by the PTB. This suggests that the\n%% %% identity and features of the target word are indispensable and that a\n%% %% purely substitutability based linguistic definition is insufficient\n%% %% for inducing parts of speech as tagged in the PTB.\n%% \n%% \\paragraph{Instance Based:}\n%% In this clustering, we represent each word instance by concatenating the type\n%% embedding ($n$ dimensional) with the average of substitutes of that particular\n%% instance ($n$ dimensional). We then apply k-means to the resulting\n%% $2n$-dimensional vectors and categorize each instance of a type separately.\n%% For instance, the target word ``Pierre'' in Table~\\ref{tab:samples} will be\n%% represented by concatenating the embedding of {\\it W:Pierre} with the average\n%% of the embeddings of {\\it S:Mr.}, {\\it S:Pierre} and {\\it S:John}. This model\n%% do not employ the one-tag-per-word assumption and clusters word instances\n%% therefore it handles ambiguity. Clusters that are constructed according to\n%% this representation tend to assign fewer categories to each word type than\n%% substitute clustering due to the concatenation of ${\\bf W}$. The advantage in\n%% highly ambiguous words is still retained (e.g. the \\mto\\ for {\\em offer} is\n%% .XX) and the overall result is comparable compared to clustering of word\n%% embeddings. Section~\\ref{sec:instance} presents results of the instance based \n%% clustering.\n%% \n%% \\paragraph{Summary} The first clustering applies the one-tag-per-word\n%% assumption from the beginning and clusters word types instead of instances. \n%% %The second setting clusters word contexts (as represented by\n%% %substitutes) and is able to categorize individual word tokens.\n%% %However it ignores the identity of the target word. \n%% The second one clusters word instances by representing each instance with the\n%% concatenation of the word type and average of corresponding substitute\n%% embeddings. The target word is represented without enforcing the\n%% one-tag-per-word assumption improves the results on highly ambiguous words\n%% while achieving close results with the state-of-the-art system.\n%% Section~\\ref{sec:exp} compares the performance of these two clustering on the\n%% part of speech induction problem, as well as\n%% experiments with different features and languages.\n", "meta": {"hexsha": "92d887a8baaa5eb2315ec8b2dbbd021dcce6cb2d", "size": 28120, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "papers/coling2014/algorithm.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/algorithm.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/algorithm.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": 52.0740740741, "max_line_length": 165, "alphanum_fraction": 0.6937411095, "num_tokens": 7973, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.550607350786733, "lm_q2_score": 0.334589441253186, "lm_q1q2_score": 0.18422740584962996}}
{"text": "% American Nuclear Society Transaction template\n% by Diego Mandelli (INL)\n% Most of the template has been built by Seth R. Johnson\n% based on the ANS transaction guidelines\n\n\\documentclass{anstrans}\n\n\\usepackage{algorithm}\n\\usepackage{algpseudocode}\n\\usepackage{graphicx}\n\\usepackage{amsmath}\n% \\usepackage{fmtcount}\n\n\\usepackage[none]{hyphenat}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\title{PERFORMING PROBABILISTIC RISK ASSESSMENT THROUGH RAVEN}\n\\author{A. Alfonsi \\and C. Rabiti \\and D. Mandelli \\and J.J. Cogliati \\and R.A. Kinoshita}\n\n\\institute{\nIdaho National Laboratory\n}\n\n\\email{ \\{andrea.alfonsi, cristian.rabiti, diego.mandelli, joshua.cogliati, robert.kinoshita\\}@inl.gov }\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{dblfloatfix} % fix two-column floats to allow bottom placement\n\n\\newcommand{\\SN}{S$_N$}\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\n\\begin{document}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n \\twocolumn[\n \\begin{@twocolumnfalse}\n \\maketitle\n \\end{@twocolumnfalse}\n ]\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Introduction}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nRAVEN (\\textbf{R}eactor \\textbf{A}nalysis and \\textbf{V}irtual control \\textbf{EN}viroment)~\\cite{ravenFY12,mandelliANS2012} is a software framework that acts as the control logic driver for the Thermal-Hydraulic code RELAP-7, a newly developed software at Idaho National Laboratory. This paper provide an overview of the RAVEN software structure and its utilization in conjunction with RELAP-7/MOOSE~\\cite{MOOSE,relap7FY12}. RAVEN is a multi-purpose Probabilistic Risk Assessment (PRA) code that allows dispatching different functionalities.\nIt is designed to derive and actuate the control logic required to simulate both plant control system and operator actions (guided procedures) and to perform both Monte-Carlo sampling of random distributed events and dynamic event tree based analysis~\\cite{ADAPTHakobyan}.\nIn order to assist the user in the input/output handling, a Graphical User Interface (GUI) and a post-processing data mining module, based on dimensionality and cardinality reduction~\\cite{mandelliEsrel2011}, are available.\nThis paper focuses on the link between the software layout and the mathematical framework from which its structure is derived. In order to show the code capabilities, a demo of a Station Black Out (SBO) analysis of a simplified Pressurized Water Reactor (PWR) model is presented.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{MATHEMATICAL FRAMEWORK}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:mathFramework}\nLet be $\\bar{\\theta}(t)$ a vector describing the plant status in the phase space; the dynamic of the plant, including the control system, can be summarized by the following equation:\n\\begin{equation}\n\\frac{\\partial \\bar{\\theta}}{\\partial t} = \\bar{H}(\\theta(t),t)\n\\label{eq:SystemDynamics}\n\\end{equation}\nIn the above equation it is assumed the time differentiability in the phase space. Performing an arbitrary decomposition of the phase space, the following statement is obtained:\n\\begin{equation}\n\\bar{\\theta}=\\binom{\\bar{x}}{\\bar{v}}\n\\label{eq:firstDecomposition}\n\\end{equation}\n\nThe decomposition is made in such a way that $\\bar{x}$ represents the unknowns solved by RELAP-7, while $\\bar{v}$ are the variables directly controlled by the control system (i.e., RAVEN). Equation~\\ref{eq:SystemDynamics} can now be rewritten as follows:\n\\begin{equation}\n\\begin{cases}\n\\dfrac{\\partial \\bar{x}}{\\partial t} = \\bar{F}(\\bar{x},\\bar{v},t) \\\\\n\\dfrac{\\partial \\bar{v}}{\\partial t} = \\bar{V}(\\bar{x},\\bar{v},t) \\\\\n\\end{cases}\n\\label{eq:generalSystemEquation}\n\\end{equation}\nIt is possible to note that the function $\\bar{V}(\\bar{x},\\bar{v},t)$ representing the control system, does not depend on the knowledge of the complete status of the system but on a restricted subset (i.e. control variables) $\\bar{C}$:\n\\begin{equation}\n\\begin{cases}\n\\dfrac{\\partial \\bar{x}}{\\partial t} = \\bar{F}(\\bar{x},\\bar{v},t) \\\\\n\\bar{C} = \\bar{G}(\\bar{x},t) \\\\\n\\dfrac{\\partial \\bar{v}}{\\partial t} = \\bar{V}(\\bar{x},\\bar{v},t)\n\\end{cases}\n\\label{eq:generalSystemEquationwithControl}\n\\end{equation}\n\nThe system of equations in Eq.~\\ref{eq:generalSystemEquationwithControl} is fully coupled and has commonly been solved by an operator splitting approach. The reasons for this choice are several:\n\\begin{itemize}\n\\item Control system reacts with an intrinsic delay\n\\item The reaction of the control system might move the system between two different discrete states and\ntherefore numerical errors will be always of first order unless the discontinuity is treated explicitly.\n\\end{itemize}\n\\begin{figure}\n\\centering\n\\includegraphics[width=0.35\\textwidth]{figures/ControlSystemSoftwareLayout.pdf}\n\\caption{Control System Software Layout.}\n\\label{fig:ControlSoftwareLayout}\n\\end{figure}\nThus, RAVEN is using this approach (Fig.~\\ref{fig:ControlSoftwareLayout}) to solve Eq.~\\ref{eq:generalSystemEquationwithControl} which becomes:\n\\begin{equation}\n\\begin{cases}\n\\dfrac{\\partial \\bar{x}}{\\partial t} = \\bar{F}(\\bar{x},\\bar{v}_{t_{i-1}},t) \\\\\n\\bar{C} = \\bar{G}(\\bar{x},t) & t_{i-1}\\leq t\\leq t_{i} = t_{i-1} + \\Delta t_{i}\\\\\n\\dfrac{\\partial \\bar{v}}{\\partial t} = \\bar{V}(\\bar{x},\\bar{v}_{t_{i-1}},t) \\\\\n\\end{cases}\n\\label{eq:generalSystemEquationwithControlSplitting}\n\\end{equation}\nEven if all information needed is contained in $\\bar{x}$ and $\\bar{v}$, it is not a practical and efficient way to implement the control system. Hence, a system of auxiliary variables has been introduced.\nThe auxiliary variables are those that in statistical analysis are artificially added, when possible, to non-Markovian systems into the space phase to obtain a Markovian behavior back, so that only the information of the previous time step is needed to determine the future status of the system.\nThus, the introduction of the auxiliary system into the mathematical framework leads to the following formulation of the Eq.~\\ref{eq:generalSystemEquationwithControlSplitting}:\n\\begin{equation}\n\\begin{cases}\n\\dfrac{\\partial \\bar{x}}{\\partial t} = \\bar{F}(\\bar{x},\\bar{v}_{t_{i-1}},t) \\\\\n\\bar{C} = \\bar{G}(\\bar{x},t) & t_{i-1}\\leq t\\leq t_{i} = t_{i-1} + \\Delta t_{i}\\\\\n\\dfrac{\\partial \\bar{a}}{\\partial t} = \\bar{A}(\\bar{x},\\bar{C},\\bar{a}_{t_{i-1}},\\bar{v}_{t_{i-1}},t) \\\\\n\\dfrac{\\partial \\bar{v}}{\\partial t} = \\bar{V}(\\bar{x},\\bar{v}_{t_{i-1}},\\bar{a},t)\n\\end{cases}\n\\label{eq:generalSystemEquationwithControlSplittingAndAux}\n\\end{equation}\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{SOFTWARE STRUCTURE}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nRAVEN, is plugged with the software environment MOOSE~\\cite{MOOSE}. MOOSE is a computer simulation framework, developed at Idaho National Laboratory (INL), that simplifies the process for predicting the behavior of complex systems and developing non-linear, multi-physics simulation tools. Other than providing the algorithms for the solution of the differential equation, MOOSE also provides all the manipulation tools for the \\verb!C++! classes containing the solution vector. This framework has been used to construct and develop the Thermal-Hydraulic code RELAP-7, giving an enormous flexibility in the coupling procedure with RAVEN.\n\nRELAP-7 is the next generation nuclear reactor system safety analysis. It will become the main reactor systems simulation toolkit for RISMC (\\textbf{R}isk \\textbf{I}nformed \\textbf{S}afety \\textbf{M}argin \\textbf{C}haracterization)~\\cite{mandelliANS_RISMC} project and the next generation tool in the RELAP reactor safety/systems analysis application series.\nRAVEN has been developed in a high modular and pluggable way in order to enable easy integration of different programming languages (i.e., \\verb!C++!, \\verb!Python!) and coupling with other applications including the ones based on MOOSE. The code consists of four main modules:\n\\begin{itemize}\n\\item RAVEN/RELAP-7 interface\n\\item \\verb!Python! Control Logic\n\\item \\verb!Python! Calculation Driver\n\\item Graphical User Interface\n\\end{itemize}\n\nThe RAVEN/RELAP-7 interface, coded in \\verb!C++!, is the container of all the tools needed to interact with RELAP-7/MOOSE. It has been designed in order to be general and pluggable with different solvers simultaneously in order to allow an easier and faster development of the control logic/PRA capabilities for multi-physics applications.\n%(to properly generate the monitored quantities and accordingly modify the controlled\n% parameters in the raven/relap7 simulation)\nThe interface provieds all the capabilities to generate the monitored quantities and accordingly modify the controlled parameters in the RELAP-7/MOOSE calculation.\n%The interface provides all the capabilities to control, monitor, and process the %parameters/quantities in order to drive the RELAP-7/MOOSE calculation.\nIn addition, it contains the tools to communicate to the MOOSE input parser which information, i.e. input syntax, must be provided in order to run a RAVEN calculation.\\\\The control logic module is used to drive a RAVEN/RELAP-7 calculation. Up to now it is implemented by the user via \\verb!Python! scripting. The reason of this choice is to try to preserve generality of the approach in the initial phases of the project so that further specialization is possible and inexpensive. The implementation of the control logic via \\verb!Python! is rather convenient and flexible. The user only needs to know few \\verb!Python! syntax rules in order to build an input. Although this extreme simplicity, it will be part of the GUI task to automatize the construction of the control logic scripting in order to minimize user effort.\n\nThe core of PRA analysis is contained in the module called \"Raven Runner\". It consists of a \\verb!Python! driver in which Monte-Carlo based algorithm has been implemented. It calls RAVEN multiple times, changes initial conditions and seeds the random generator for the distributions.\nThe multiple calculations, required by the employment of these algorithms, can be run in parallel, using queues/sub-process/\\verb!Python! systems. The analysis of dynamic stochastic systems through Monte-Carlo algorithm can be summarized as follows:\n\\begin{enumerate}\n\\item Initial Sampling of:\n \\begin{enumerate}\n \\item Physical parameters\n \\item Initial conditions\n \\item Transition conditions, i.e. time instant in which transition events occur (e.g., time in which a reactor scram occurs, etc.)\n \\end{enumerate}\n\\item Run the system simulator using the values previously sampled and eventually applying a random noise to some parameters at each time step\n\\item Repeat 1 and 2 for a large number of calculations (user input)\n\\end{enumerate}\nThe \"runner\" basically performs a different seeding of the random number generator and interact, through RAVEN, with the \\verb!Python! control logic input in order to sample the variables specified by the user.\n\nAs previously mentioned, a Graphical User Interface (GUI) is not required to run RAVEN, but it represents an added value to the whole code. The GUI is compatible with all the capabilities actually present in RAVEN (control logic, Monte-Carlo, etc.). Its development is performed using QtPy, which is a \\verb!Python! interface for a \\verb!C++! based library (\\verb!C++!) for GUI implementation. The GUI is based on a software named Peacock, which is a GUI interface for MOOSE based application and, in its base implementation, is only able to assist the user in the creation of the input. In order to make it fit all the RAVEN needs, the GUI has been specialized and is in continuous evolution.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{DEMO FOR A PWR PRA ANALYSIS}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nIn order to show the capabilities of RAVEN coupled with RELAP-7/MOOSE, a PRA analysis on a simplified PWR model (Fig.~\\ref{fig:PWRmodel}) has been employed.\n\\begin{figure}\n \\centering\n \\includegraphics[width=0.4\\textwidth]{figures/PWR_TMI_SCHEME.PNG}\n \\caption{PWR model scheme.}\n \\label{fig:PWRmodel}\n\\end{figure}\n\\\\Since RELAP-7 still has limitations for the component controllable parameters and models, it has been necessary to act on unconventional factors (i.e. inlet/outlet friction factors in order to simulate a realistic pump coast-down).\n\\begin{figure} [H]\n\\centering\n \\centering\n \\includegraphics[width=0.35\\textwidth]{figures/PRA_dist2.png}\n \\label{fig:pdf_temp}\n \\caption{Comparison between max reached clad temperature and clad failure temperature distributions: Probability distribution functions.}\n\\label{fig:distributionResults}\n\\end{figure}\n\nThe Probabilistic Risk Assessment analysis has been performed simulating a Station Black Out accident, running Monte-Carlo samplings (400 simulations) on the recovery time of the diesel generators $t_{1}$ (Normal distribution, mu = 120 s, sigma = 20 s) and the clad failure temperature $TC{f}$(Triangular distribution, xPeak = 1477.59 K, xMin~ =~1255.37 K, xMax = 1699.82 K). Since the scope of this demo is to show the functionalities contained in RAVEN and RELAP-7 is not yet optimized for long simulation times, the transient has been accelerated in order to simulate a maximum of 300 seconds.\nFigure~\\ref{fig:distributionResults} shows the distribution of the maximum temperature reached by the clad in the core channels (blue histogram) and compares it with the distribution of clad failure temperature (red histogram).\nAs already mentioned, the transient has been accelerated, since the scope of the analysis was just to show RAVEN capabilities to perform stochastic analysis of relatively complex systems. %That can explain the large overlapping of the two distributions, which indicates a high failure %probability of the system considered.\n\nFigure~\\ref{fig:limit_surface_rng_temp_and_dg} shows the limit surface, i.e. the boundaries between system failure (red points) and system success (green points), obtained by the 400 Monte-Carlo simulations. Since only two uncertain parameters have been considered (i.e., DG recovery time and clad fail temperature), this boundary lies in a 2-dimensional space.\nThe slope of the limit surface pictured in Fig.~\\ref{fig:limit_surface_rng_temp_and_dg} also shows, in this particular demo, how the DG recovery time has a greater impact on the system dynamics then the clad failure temperature.\n\\begin{figure}\n \\centering\n \\includegraphics[width=0.45\\textwidth]{figures/PRA_limitSurface.png}\n \\caption{Limit Surface for the SBO analysis of a simplified PWR model}\n \\label{fig:limit_surface_rng_temp_and_dg}\n\\end{figure}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{CONCLUSIONS}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nIn this paper it has been presented RAVEN as a tool to perform dynamic PRA through Monte-Carlo sampling. In particular, the software structure and all the components that are involved in the computation have been presented, including system simulator (i.e., RELAP-7) and the control logic, characterized by a monitoring system and on-line control of selected parameters.\nAn example of PRA analysis has been also presented for a SBO-like case for a simplified PWR loop.\nThe description of the implementation for such case demonstrates how the flexibility of the software framework provides the basic tools to perform Dynamic PRA, uncertainty quantification and plant control.\nNext capabilities, to be implemented to RAVEN and that are currently under development, include dynamic event tree generation~\\cite{ADAPTHakobyan}, adaptive sampling~\\cite{mandelliSVMANS} and more advanced data mining algorithms~\\cite{mandelliEsrel2011}.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{ENDNOTES}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nThis work is supported by the U.S. Department of Energy, under DOE Idaho Operations Office Contract DE-AC07-05ID14517. Accordingly, the U.S. Government retains a nonexclusive, royalty-free license to publish or reproduce the published form of this contribution, or allow others to do so, for U.S. Government purposes.\n\n\\bibliographystyle{ans}\n\\bibliography{bibl}\n\\end{document}\n\n", "meta": {"hexsha": "a6794b796c7d801918cd2b5dab752be557d7e1a6", "size": 16974, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "papers/ANS_summer2013/ANS_winter2013_SoftwareOverview.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": "papers/ANS_summer2013/ANS_winter2013_SoftwareOverview.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": "papers/ANS_summer2013/ANS_winter2013_SoftwareOverview.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": 82.8, "max_line_length": 824, "alphanum_fraction": 0.7309414398, "num_tokens": 4051, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857982, "lm_q2_score": 0.32766828768970435, "lm_q1q2_score": 0.18420741142463906}}
{"text": "\\chapter{Kinematic weighting}\n\\label{chap:cpv:kinematic_weighting}\n\nFor the assumptions in \\cref{eqn:cpv:theory:dacp} to hold, the\nkinematics of the particles contributing to the background asymmetries must be\nequal between the \\pKK\\ and \\ppipi\\ final states.\nThese are the kinematics of the \\PLambdab, the muon from the \\PLambdab, and the\nproton from the \\PLambdac.\nWithin a particular \\phh\\ final state, it must also be the case that the \\Php\\\nand \\Phm\\ kinematics are equal in order that $\\ADf(f)$ only contains\ncontributions from the proton detection asymmetry $\\AD(\\Pproton)$.\nA comparison of these distributions between the 2012 magnet down \\pKK\\ and\n\\ppipi\\ datasets is given in\n\\cref{fig:cpv:kinematic_weighting:pre:Lb,fig:cpv:kinematic_weighting:pre:Lb_mu,fig:cpv:kinematic_weighting:pre:Lc,fig:cpv:kinematic_weighting:pre:Lc_p,fig:cpv:kinematic_weighting:pre:pKK_h1h2,fig:cpv:kinematic_weighting:pre:ppipi_h1h2}.\nThe signal distributions are shown, where the contents of each bin is defined\nas the sum of signal sWeights within that bin, as computed from the result of\nthe mass fit to the charge-combined samples described in\n\\cref{chap:cpv:prelim_fits}.\nThe correlation of the variables with the \\PLambdac\\ mass is seen to be small,\nwith a correlation coefficient less than \\SI{2}{\\percent} for all variables.\nOnly the muon kinematics across the modes and the \\hmhp\\ kinematics within the\nmodes agree, and so a weighting is necessary.\n\nA \\acf{BDT} is used to equalise the relevant particle kinematics between the\ntwo modes.\nThis is an uncommon technique in physics analyses, with ratios of\nmulti-dimensional histograms being used more often, and so it will be briefly\nsummarised in the following.\n(An introduction to decisions trees and boosting is presented in\n\\cref{chap:decision_trees}.)\nThe creation of the specific models using for weighting will then be presented,\nfollowed by a discussion on weighting validation.\n\n\\section{Weighting with decision trees}\n\\label{chap:cpv:kinematic_weighting:bdt_method}\n\nIt is common in \\acl{HEP} to want to be able to bring two distributions into\nagreement, as is the case in this analysis where particle kinematics should be\nequal between the \\pKK\\ and \\ppipi\\ data.\nCall one possibly multi-dimensional distribution the \\emph{target} $f_{t}$ and\nthe other the \\emph{original} distribution $f_{o}$.\nTo transform $f_{o}$ to have the same form as $f_{t}$, there is some\ntransformation function $W$\n\\begin{equation}\n f_{t}(x) = W(x)f_{o}(x),\n\\end{equation}\nwhere $x$ is a possibly multi-dimensional parameter.\nAs the true distributions of $f_{t}$ and $f_{o}$ are not known in the data,\nthey are approximated as histograms, partitioning the data in $x$ and counting\nthe number of events that fall in each bin.\nThe transformation function is quantised as $w$ in bins, where in the $i$th bin\n\\begin{equation}\n f_{t}(x_{i}) = w(x_{i})f_{o}(x_{i}),\n\\end{equation}\nand where $f_{t(o)}(x_{i})$ is the count of the target (original) distribution\nin the $i$th bin.\nThe histogram of $f_{o}$ can be transformed to that of $f_{t}$ by computing the\nper-bin \\emph{weights}\n\\begin{equation}\n w(x_{i}) = \\frac{f_{t}(x_{i})}{f_{o}(x_{i})}.\n\\end{equation}\nThis is valid assuming there are no bins where $f_{o}(x_{i}) = 0$.\n\nTo model the true \\aclp{PDF} in $x$ as closely as possible, the histogram must\nhave a fine enough binning that all structures are resolved.\nSpecifically, as in the determination of the \\ac{PID} efficiency in\n\\cref{chap:prod:effs:pid}, the binning must be fine enough such that difference\nbetween the true \\acp{PDF} of the two distribution within any given bin are\nsmall.\nThis must be balanced with the limited statistical precision available in each\nbin: too fine a binning will result in the original distribution being weighted\nto match the statistical fluctuations in the target, rather than the physical\nfeatures.\nLimited sample sizes become particularly problematic for higher-dimensional\nweighting, when even 10 equally spaced bins per dimension in a\nthree-dimensional binning requires $1,000$ bins.\nGiven physical distributions such as momentum and pseudorapidity, which have\nlong tails, it can be difficult to invent a binning that avoids sparsely\npopulated or empty bins whilst still accounting for differences in the\ndistributions.\n\nTo overcome the limitations of histogram-based weighting, this analysis defers\nthe computation of the per-event weights $w_{i}$ to a decision tree with\ngradient boosting~\\cite{Rogozhnikov:2016bdp}.\nThe classifier is trained with the loss function\n\\begin{equation}\n L = \\sum_{l \\in \\text{Leaves}} \\frac{%\n {(w_{l,o} - w_{l,t})}^{2}\n }{%\n w_{l,o} + w_{l,t}\n },\n\\end{equation}\nwhere $w_{l,t(o)}$ is the sum of target (original) weights in the $l$th leaf\nnode of the regression tree.\nFor the initial iteration, and an unweighted set of training events, this is\nequal to the number of target (original) events in the leaf node.\nThis metric has the tree split the samples into regions where the differences\nbetween the sample sizes is maximal, such that the classifier focuses on\nweighting the entries in those regions.\nPredictions $p_{l}$ within a leaf are computed as\n\\begin{equation}\n p_{l} = \\log{\\frac{w_{l,t}}{w_{l,o}}}.\n\\end{equation}\nAt the end of the $i$th iteration, each event from the `original' sample is\nweighted by $w_{i} = w_{i - 1}e^{p_{l}}$, where $l$ is the leaf node the event\nfalls in.\nThe target distribution is assigned unit weights $w_{i} = w_{0}$.\nThis weighting has the same effect as the weighting in the \n\\adaboost~\\cite{Freund1997119} algorithm, increasing the importance of events \nin the original distribution that are in regions with a large original/target \ndifference.\n\nThe actual weighting of events is identical to that in the histogram weighting:\nit is the ratio of target to original events in some region.\nThe use of gradient boosting allows for a more intelligent way of finding the\n`bins' in which the weights are computed, and iteratively improves the weights\nbased on that method.\n\n\\section{Evaluation}\n\\label{chap:cpv:kinematic_weighting:evaluation}\n\nThe decision tree with gradient boosting is trained with the \\ppipi\\ data as\nthe `original' sample and the \\pKK\\ data as the `target'.\nThe weighting procedure is performed separately for each data sub-sample in\nyear and magnet polarity.\nAs it is expected that the \\PLambdab\\ and muon kinematics are correlated with\nthat of the \\PLambdac, the \\PLambdac\\ transverse momentum \\pT\\ and\npseudorapidity \\Eta\\ are included as inputs to the \\ac{BDT}.\nAlso included are the proton \\pT\\ and \\Eta, as these distributions are seen to\ndisagree after weighting when only the \\PLambdac\\ kinematics are used.\nTo avoid biases due to fluctuations in the data, two classifiers $A$ and $B$\nare trained, and the \\pKK\\ and \\ppipi\\ data are each randomly split into two\nsub-samples 1 and 2: classifier $A$ is trained using sub-sample 1, and the\nweights for sub-sample 2 are computed using $A$; likewise, classifier $B$ is\ntrained using sub-sample 2, and the weights for sub-sample 1 are computed using\n$B$.\nSub-samples 1 and 2 are then combined for the remainder of the analysis.\nThe input training data are weighted by signal sWeights, as computed from the\nresult of the mass fits described in \\cref{chap:cpv:prelim_fits}.\nEach classifier is boosted in 300 iterations, the maximum number of leaf nodes\nallowed in the regression tree is four, and the criteria for splitting includes\nthe requirement that any new nodes must contain at least 200 events.\nThe choice of these hyper-parameters will be discussed in\n\\cref{chap:cpv:kinematic_weighting:validation}, as well as the specific choice\nof original and target samples.\n\n\\Cref{fig:cpv:kinematic_weighting:post:Lb,fig:cpv:kinematic_weighting:post:Lb_mu,fig:cpv:kinematic_weighting:post:Lc,fig:cpv:kinematic_weighting:post:Lc_p}\nshow the \\PLambdab, muon, \\PLambdac, and proton kinematics after weighting with\nthe product of signal sWeights and the kinematic weights.\n\\Cref{fig:cpv:kinematic_weighting:post:pKK_h1h2,fig:cpv:kinematic_weighting:post:ppipi_h1h2}\nshow the $\\Phm\\Php$ kinematics, \\emph{within} the modes, after the same\nweighting.\nThere is a considerable improvement in the agreement between the \\pKK\\ and\n\\ppipi\\ data in the \\PLambdab\\ and proton kinematics.\nThe good agreement in the muon kinematics between the datasets and the\n$\\Phm\\Phm$ kinematics within the datasets does not change.\nIt is noted that the \\PLambdac\\ kinematic agreement also improves, although\nthis does not affect the measurement of \\dACP\\ as there is no associated\nasymmetry.\n\n\\section{Validation}\n\\label{chap:cpv:kinematic_weighting:validation}\n\nThe purpose of the kinematic weighting is to make the particle kinematics the\nsame between the \\pKK\\ and \\ppipi\\ modes.\n\\Cref{fig:cpv:kinematic_weighting:post:Lb,fig:cpv:kinematic_weighting:post:Lb_mu,fig:cpv:kinematic_weighting:post:Lc,fig:cpv:kinematic_weighting:post:Lc_p}\nshow good agreement `by eye', but a quantitative assessment is needed.\nWhat affects the measurement of \\dACP\\ is not so much the absolute level of\ndisagreement between the two histograms, for example, but the disagreement in a\nparticular region combined with both the size of the respective asymmetries\ninvolved and the density of the data in that region.\nThe effect of the remaining differences on \\dACP\\ is discussed in the context\nof systematic uncertainties in \\cref{chap:cpv:syst}.\n\nTo provide some quantitative estimate of the agreement, a \\ac{BDT} is employed.\nIf the two samples, the target weighted with signal sWeights and the original\nweighted with the product of signal sWeights and kinematic weights, are truly\nidentical, then a \\ac{BDT} designed to \\emph{discriminate} between them should\nperform no better than random guessing.\nThe performance of a \\ac{BDT} trained for binary classification can be\nevaluated by computing the area under the \\ac{ROC} curve, or just \\ac{AUC}.\nThe \\ac{ROC} curve compares the \\ac{FPR} of the classifier with the \\ac{TPR} as\na function of the classifier output probability.\nThe \\ac{TPR} is defined as the fraction of true signal events that are\ncorrectly classified as such, whilst the \\ac{FPR} is the fraction of background\nevents that are classified as signal.\nPlotting the \\ac{FPR} increasing along the $x$-axis and the \\ac{TPR} increasing\nalong the $y$-axis, the \\ac{ROC} curve for an optimal classifier passes through\nthe top-left corner of the plot, where a large fraction of the signal is\naccepted and a correspondingly large background fraction is rejected.\nA classifier that cannot distinguish between signal and background any better\nthan random guessing will have a \\ac{ROC} curve of the form $x = y$.\nIn these two extreme cases, the \\ac{AUC} is 1 and 0.5, respectively.\n\nA \\ac{BDT}, with gradient boosting, is trained to discriminate between the\nweighted \\pKK\\ and \\ppipi\\ data, using three-quarters of the available 2012\nmagnet down data as input.\nThe \\PLambdab, muon, and proton \\ptot, \\pT, \\Eta, and azimuthal angle $\\phi$\nare used as features.\nThe \\PLambdac\\ kinematics are not included as there is no asymmetry associated\nto any residual differences there might be.\nThe maximum number of leaf nodes for any one regression tree is 11, the number\nof boosting iterations performed is 400, and the minimum number of samples\nallowed in a leaf node is 200.\nThe performance of the \\ac{BDT} is evaluated using the remaining quarter of the\ndataset, and the resulting \\ac{ROC} curve is shown in\n\\cref{fig:cpv:kinematic_weighting:post:roc}.\nFor comparison, it is shown along with a curve obtained when the same\nclassifier is trained using data with no kinematic weighting, as well as a\ncurve when a rudimentary, two-dimensional, $10\\times10$ histogram weighting in\n\\PLambdac\\ \\pT\\ and \\Eta\\ is used.\nIt is seen that the inclusion of the kinematic weights significantly reduces\nthe \\ac{AUC}, from 0.61 with no kinematic weights to 0.52 for the \\ac{BDT}\nweighting.\nThis shows that the \\ac{BDT} weighting does increase the similarity between the\nkinematic distributions across the modes, and that it can be significantly more\npowerful than a two-dimensional histogram weighting.\n\nIt is the \\ac{AUC} metric evaluated on the training sample that was maximised\nwhen choosing the hyper-parameters to use for the weighting.\nA grid search was performed where the following hyper-parameter values were\ntested in all combinations: 100, 200, 300, and 400 boosting iterations; a\nminimum of 50, 100, 200, 300, 500, and 1000 events required to create a new\nnode; and a maximum number of allowed leaf nodes per regression tree of 2, 3,\n4, 5, 6, 7, and 8.\nThe hyper-parameters used for the weighting (300 iterations, a minimum of 200\nevents per node, and a maximum of 4 leaf nodes per tree) were those for which\nthe \\ac{AUC} was smallest.\n\n\\section{Weight statistics}\n\\label{chap:cpv:kinematic_weighting:stats}\n\nWeighting can increase the statistical contribution of individual entries\nwithin a dataset, but it cannot increase the overall statistical power.\nThe number of entries $N'$ in a weighted dataset can be computed as the sum of\nthe per-entry weights $w_{i}$, and the variance on this quantity is given as\nthe sum of the squares of the weights\n\\begin{equation}\n N' = \\sum_{i}^{N} w_{i},\\quad (\\unc{N'})^{2} = \\sum_{i}^{N} w_{i}^{2}\n\\end{equation}\nFor certain values of $w_{i}$, it can be that $\\unc{N'} < \\unc{N}$.\nTo prevent this, the number of `effective' entries in the weighted dataset is\ncomputed, under the relation that the relative variance on the effective\nentries is equal to the relative variance on the weights\n\\begin{equation}\n \\frac{\\neff}{\\unc{\\neff}} =\n \\frac{\\sum_{i}^{N} w_{i}}{\\sqrt{\\sum_{i}^{N} w_{i}^{2}}},\n\\end{equation}\nwhere \\neff\\ is assumed to be Poisson-distributed, and so $(\\unc{\\neff})^{2} =\n\\neff$, giving\n\\begin{equation}\n \\neff = \\frac{%\n {\\left(\\sum_{i}^{N}{w_{i}}\\right)}^{2}\n }{%\n \\sum_{i}^{N}{w_{i}^{2}},\n }.\n \\label{eqn:cpv:kinematic_weighting:neff}\n\\end{equation}\nThis relation can be enforced by redefining the weights $w_{i}$ by a factor $W\n= \\sum_{i} w_{i}/\\sum_{i} w_{i}^{2}$.\nFor unit weights, $\\neff = N$ and $\\unc{\\neff} = \\sqrt{N}$.\nOtherwise, \\neff\\ is the size of the hypothetical dataset that has the same\nstatistical power as the weighted dataset.\nFor this analysis, it provides a handle on how well the two data samples agree\nin the weighting variables before the weighting, as, in general, a higher level\nof disagreement requires a larger fraction of candidates to be `thrown away' by\nthe weighting, reducing the statistical power.\n\n\\Cref{tab:cpv:kinematic_weighting:validation:stats} gives several statistics\nrelated to the weighting procedure for the \\ppipi\\ data.\nFor all data sub-samples, the effective number of candidates is no less than\n\\SI{80}{\\percent} the number of candidates entering the weighting procedure.\nAs there are around five times more \\ppipi\\ candidates than \\pKK, the\nstatistical uncertainty of the \\dACP\\ measurement will still be dominated by\nthe \\pKK\\ sample size, even with an effective \\SI{20}{\\percent} reduction in\nthe \\ppipi\\ sample size.\nIt is this fact that motivates the choice of the \\ppipi\\ mode as the source of\nthe `original' distributions in the weighting and the \\pKK\\ mode as the\n`target'.\n\n\\begin{sidewaystable}\n \\centering\n \\caption{%\n Statistics computed on the weighted \\ppipi\\ data for all data sub-samples\n used in the analysis.\n The quantities are defined in \\cref{chap:cpv:kinematic_weighting:stats}.\n }\n \\label{tab:cpv:kinematic_weighting:validation:stats}\n \\input{tables/cpv/kinematic_weighting/weight_statistics-MVA.tex}\n\\end{sidewaystable}\n\n\\clearpage\n\n\\begin{figure}\n \\begin{subfigure}[b]{0.4\\textwidth}\n \\includegraphics[width=\\textwidth]{cpv/kinematic_weighting/preweighting_kinematics/LcToppipi_2012_MagDown_Lb_P}\n \\label{fig:cpv:kinematic_weighting:pre:Lb:P}\n \\end{subfigure}\n \\begin{subfigure}[b]{0.4\\textwidth}\n \\includegraphics[width=\\textwidth]{cpv/kinematic_weighting/preweighting_kinematics/LcToppipi_2012_MagDown_Lb_PT}\n \\label{fig:cpv:kinematic_weighting:pre:Lb:PT}\n \\end{subfigure}\\\\\n \\begin{subfigure}[b]{0.4\\textwidth}\n \\includegraphics[width=\\textwidth]{cpv/kinematic_weighting/preweighting_kinematics/LcToppipi_2012_MagDown_Lb_ETA}\n \\label{fig:cpv:kinematic_weighting:pre:Lb:ETA}\n \\end{subfigure}\n \\begin{subfigure}[b]{0.4\\textwidth}\n \\includegraphics[width=\\textwidth]{cpv/kinematic_weighting/preweighting_kinematics/LcToppipi_2012_MagDown_Lb_PHI}\n \\label{fig:cpv:kinematic_weighting:pre:Lb:PHI}\n \\end{subfigure}\n \\caption{%\n Clockwise from the top left: total momentum, transverse momentum, angle\n $\\phi$, and pseudorapidity of the \\PLambdab, weighted by signal sWeights.\n The 2012 magnet down data are shown.\n }\n \\label{fig:cpv:kinematic_weighting:pre:Lb}\n\\end{figure}\n\n\\begin{figure}\n \\begin{subfigure}[b]{0.4\\textwidth}\n \\includegraphics[width=\\textwidth]{cpv/kinematic_weighting/preweighting_kinematics/LcToppipi_2012_MagDown_Lb_mu_P}\n \\label{fig:cpv:kinematic_weighting:pre:Lb_mu:P}\n \\end{subfigure}\n \\begin{subfigure}[b]{0.4\\textwidth}\n \\includegraphics[width=\\textwidth]{cpv/kinematic_weighting/preweighting_kinematics/LcToppipi_2012_MagDown_Lb_mu_PT}\n \\label{fig:cpv:kinematic_weighting:pre:Lb_mu:PT}\n \\end{subfigure}\\\\\n \\begin{subfigure}[b]{0.4\\textwidth}\n \\includegraphics[width=\\textwidth]{cpv/kinematic_weighting/preweighting_kinematics/LcToppipi_2012_MagDown_Lb_mu_ETA}\n \\label{fig:cpv:kinematic_weighting:pre:Lb_mu:ETA}\n \\end{subfigure}\n \\begin{subfigure}[b]{0.4\\textwidth}\n \\includegraphics[width=\\textwidth]{cpv/kinematic_weighting/preweighting_kinematics/LcToppipi_2012_MagDown_Lb_mu_PHI}\n \\label{fig:cpv:kinematic_weighting:pre:Lb_mu:PHI}\n \\end{subfigure}\n \\caption{%\n Clockwise from the top left: total momentum, transverse momentum, angle\n $\\phi$, and pseudorapidity of the muon from the \\PLambdab, weighted by\n signal sWeights.\n The 2012 magnet down data are shown.\n }\n \\label{fig:cpv:kinematic_weighting:pre:Lb_mu}\n\\end{figure}\n\n\\begin{figure}\n \\begin{subfigure}[b]{0.4\\textwidth}\n \\includegraphics[width=\\textwidth]{cpv/kinematic_weighting/preweighting_kinematics/LcToppipi_2012_MagDown_Lc_P}\n \\label{fig:cpv:kinematic_weighting:pre:Lc:P}\n \\end{subfigure}\n \\begin{subfigure}[b]{0.4\\textwidth}\n \\includegraphics[width=\\textwidth]{cpv/kinematic_weighting/preweighting_kinematics/LcToppipi_2012_MagDown_Lc_PT}\n \\label{fig:cpv:kinematic_weighting:pre:Lc:PT}\n \\end{subfigure}\\\\\n \\begin{subfigure}[b]{0.4\\textwidth}\n \\includegraphics[width=\\textwidth]{cpv/kinematic_weighting/preweighting_kinematics/LcToppipi_2012_MagDown_Lc_ETA}\n \\label{fig:cpv:kinematic_weighting:pre:Lc:ETA}\n \\end{subfigure}\n \\begin{subfigure}[b]{0.4\\textwidth}\n \\includegraphics[width=\\textwidth]{cpv/kinematic_weighting/preweighting_kinematics/LcToppipi_2012_MagDown_Lc_PHI}\n \\label{fig:cpv:kinematic_weighting:pre:Lc:PHI}\n \\end{subfigure}\n \\caption{%\n Clockwise from the top left: total momentum, transverse momentum, angle\n $\\phi$, and pseudorapidity of the \\PLambdac, weighted by signal sWeights.\n The 2012 magnet down data are shown.\n }\n \\label{fig:cpv:kinematic_weighting:pre:Lc}\n\\end{figure}\n\n\\begin{figure}\n \\begin{subfigure}[b]{0.4\\textwidth}\n \\includegraphics[width=\\textwidth]{cpv/kinematic_weighting/preweighting_kinematics/LcToppipi_2012_MagDown_Lc_p_P}\n \\label{fig:cpv:kinematic_weighting:pre:Lc_p:P}\n \\end{subfigure}\n \\begin{subfigure}[b]{0.4\\textwidth}\n \\includegraphics[width=\\textwidth]{cpv/kinematic_weighting/preweighting_kinematics/LcToppipi_2012_MagDown_Lc_p_PT}\n \\label{fig:cpv:kinematic_weighting:pre:Lc_p:PT}\n \\end{subfigure}\\\\\n \\begin{subfigure}[b]{0.4\\textwidth}\n \\includegraphics[width=\\textwidth]{cpv/kinematic_weighting/preweighting_kinematics/LcToppipi_2012_MagDown_Lc_p_ETA}\n \\label{fig:cpv:kinematic_weighting:pre:Lc_p:ETA}\n \\end{subfigure}\n \\begin{subfigure}[b]{0.4\\textwidth}\n \\includegraphics[width=\\textwidth]{cpv/kinematic_weighting/preweighting_kinematics/LcToppipi_2012_MagDown_Lc_p_PHI}\n \\label{fig:cpv:kinematic_weighting:pre:Lc_p:PHI}\n \\end{subfigure}\n \\caption{%\n Clockwise from the top left: total momentum, transverse momentum, angle\n $\\phi$, and pseudorapidity of the proton from the \\PLambdac, weighted by\n signal sWeights.\n The 2012 magnet down data are shown.\n }\n \\label{fig:cpv:kinematic_weighting:pre:Lc_p}\n\\end{figure}\n\n\\begin{figure}\n \\begin{subfigure}[b]{0.5\\textwidth}\n \\centering\n \\includegraphics[width=0.8\\textwidth]{cpv/kinematic_weighting/preweighting_kinematics/LcToppipi_2012_MagDown_h1_h2_P_LcTopKK}\n \\label{fig:cpv:kinematic_weighting:pre:pKK_h1h2:P}\n \\end{subfigure}\n \\begin{subfigure}[b]{0.5\\textwidth}\n \\centering\n \\includegraphics[width=0.8\\textwidth]{cpv/kinematic_weighting/preweighting_kinematics/LcToppipi_2012_MagDown_h1_h2_PT_LcTopKK}\n \\label{fig:cpv:kinematic_weighting:pre:pKK_h1h2:PT}\n \\end{subfigure}\\\\\n \\begin{subfigure}[b]{\\textwidth}\n \\centering\n \\includegraphics[width=0.4\\textwidth]{cpv/kinematic_weighting/preweighting_kinematics/LcToppipi_2012_MagDown_h1_h2_ETA_LcTopKK}\n \\label{fig:cpv:kinematic_weighting:pre:pKK_h1h2:ETA}\n \\end{subfigure}\n \\caption{%\n Clockwise from the top left: total momentum, transverse momentum, and\n pseudorapidity of the \\PKminus\\ and \\PKplus\\ \\PLambdac\\ children in the\n \\pKK\\ data, weighted by signal sWeights.\n The 2012 magnet down data are shown.\n }\n \\label{fig:cpv:kinematic_weighting:pre:pKK_h1h2}\n\\end{figure}\n\n\\begin{figure}\n \\begin{subfigure}[b]{0.5\\textwidth}\n \\centering\n \\includegraphics[width=0.8\\textwidth]{cpv/kinematic_weighting/preweighting_kinematics/LcToppipi_2012_MagDown_h1_h2_P_LcToppipi}\n \\label{fig:cpv:kinematic_weighting:pre:ppipi_h1h2:P}\n \\end{subfigure}\n \\begin{subfigure}[b]{0.5\\textwidth}\n \\centering\n \\includegraphics[width=0.8\\textwidth]{cpv/kinematic_weighting/preweighting_kinematics/LcToppipi_2012_MagDown_h1_h2_PT_LcToppipi}\n \\label{fig:cpv:kinematic_weighting:pre:ppipi_h1h2:PT}\n \\end{subfigure}\\\\\n \\begin{subfigure}[b]{\\textwidth}\n \\centering\n \\includegraphics[width=0.4\\textwidth]{cpv/kinematic_weighting/preweighting_kinematics/LcToppipi_2012_MagDown_h1_h2_ETA_LcToppipi}\n \\label{fig:cpv:kinematic_weighting:pre:ppipi_h1h2:ETA}\n \\end{subfigure}\n \\caption{%\n Clockwise from the top left: total momentum, transverse momentum, and\n pseudorapidity of the \\Ppiminus\\ and \\Ppiplus\\ \\PLambdac\\ children in the\n \\ppipi\\ data, weighted by signal sWeights.\n The 2012 magnet down data are shown.\n }\n \\label{fig:cpv:kinematic_weighting:pre:ppipi_h1h2}\n\\end{figure}\n\n\\begin{figure}\n \\begin{subfigure}[b]{0.4\\textwidth}\n \\includegraphics[width=\\textwidth]{cpv/kinematic_weighting/postweighting_kinematics/LcToppipi_2012_MagDown_Lb_P-weighted}\n \\label{fig:cpv:kinematic_weighting:post:Lb:P}\n \\end{subfigure}\n \\begin{subfigure}[b]{0.4\\textwidth}\n \\includegraphics[width=\\textwidth]{cpv/kinematic_weighting/postweighting_kinematics/LcToppipi_2012_MagDown_Lb_PT-weighted}\n \\label{fig:cpv:kinematic_weighting:post:Lb:PT}\n \\end{subfigure}\\\\\n \\begin{subfigure}[b]{0.4\\textwidth}\n \\includegraphics[width=\\textwidth]{cpv/kinematic_weighting/postweighting_kinematics/LcToppipi_2012_MagDown_Lb_ETA-weighted}\n \\label{fig:cpv:kinematic_weighting:post:Lb:ETA}\n \\end{subfigure}\n \\begin{subfigure}[b]{0.4\\textwidth}\n \\includegraphics[width=\\textwidth]{cpv/kinematic_weighting/postweighting_kinematics/LcToppipi_2012_MagDown_Lb_PHI-weighted}\n \\label{fig:cpv:kinematic_weighting:post:Lb:PHI}\n \\end{subfigure}\n \\caption{%\n Clockwise from the top left: total momentum, transverse momentum, angle\n $\\phi$, and pseudorapidity of the \\PLambdab, weighted by the product of\n signal sWeights and kinematic weights.\n The 2012 magnet down data are shown.\n }\n \\label{fig:cpv:kinematic_weighting:post:Lb}\n\\end{figure}\n\n\\begin{figure}\n \\begin{subfigure}[b]{0.4\\textwidth}\n \\includegraphics[width=\\textwidth]{cpv/kinematic_weighting/postweighting_kinematics/LcToppipi_2012_MagDown_Lb_mu_P-weighted}\n \\label{fig:cpv:kinematic_weighting:post:Lb_mu:P}\n \\end{subfigure}\n \\begin{subfigure}[b]{0.4\\textwidth}\n \\includegraphics[width=\\textwidth]{cpv/kinematic_weighting/postweighting_kinematics/LcToppipi_2012_MagDown_Lb_mu_PT-weighted}\n \\label{fig:cpv:kinematic_weighting:post:Lb_mu:PT}\n \\end{subfigure}\\\\\n \\begin{subfigure}[b]{0.4\\textwidth}\n \\includegraphics[width=\\textwidth]{cpv/kinematic_weighting/postweighting_kinematics/LcToppipi_2012_MagDown_Lb_mu_ETA-weighted}\n \\label{fig:cpv:kinematic_weighting:post:Lb_mu:ETA}\n \\end{subfigure}\n \\begin{subfigure}[b]{0.4\\textwidth}\n \\includegraphics[width=\\textwidth]{cpv/kinematic_weighting/postweighting_kinematics/LcToppipi_2012_MagDown_Lb_mu_PHI-weighted}\n \\label{fig:cpv:kinematic_weighting:post:Lb_mu:PHI}\n \\end{subfigure}\n \\caption{%\n Clockwise from the top left: total momentum, transverse momentum, angle\n $\\phi$, and pseudorapidity of the muon from the \\PLambdab, weighted by the\n product of signal sWeights and kinematic weights.\n The 2012 magnet down data are shown.\n }\n \\label{fig:cpv:kinematic_weighting:post:Lb_mu}\n\\end{figure}\n\n\\begin{figure}\n \\begin{subfigure}[b]{0.4\\textwidth}\n \\includegraphics[width=\\textwidth]{cpv/kinematic_weighting/postweighting_kinematics/LcToppipi_2012_MagDown_Lc_P-weighted}\n \\label{fig:cpv:kinematic_weighting:post:Lc:P}\n \\end{subfigure}\n \\begin{subfigure}[b]{0.4\\textwidth}\n \\includegraphics[width=\\textwidth]{cpv/kinematic_weighting/postweighting_kinematics/LcToppipi_2012_MagDown_Lc_PT-weighted}\n \\label{fig:cpv:kinematic_weighting:post:Lc:PT}\n \\end{subfigure}\\\\\n \\begin{subfigure}[b]{0.4\\textwidth}\n \\includegraphics[width=\\textwidth]{cpv/kinematic_weighting/postweighting_kinematics/LcToppipi_2012_MagDown_Lc_ETA-weighted}\n \\label{fig:cpv:kinematic_weighting:post:Lc:ETA}\n \\end{subfigure}\n \\begin{subfigure}[b]{0.4\\textwidth}\n \\includegraphics[width=\\textwidth]{cpv/kinematic_weighting/postweighting_kinematics/LcToppipi_2012_MagDown_Lc_PHI-weighted}\n \\label{fig:cpv:kinematic_weighting:post:Lc:PHI}\n \\end{subfigure}\n \\caption{%\n Clockwise from the top left: total momentum, transverse momentum, angle\n $\\phi$, and pseudorapidity of the \\PLambdac, weighted by the product of\n signal sWeights and kinematic weights.\n The 2012 magnet down data are shown.\n }\n \\label{fig:cpv:kinematic_weighting:post:Lc}\n\\end{figure}\n\n\\begin{figure}\n \\begin{subfigure}[b]{0.4\\textwidth}\n \\includegraphics[width=\\textwidth]{cpv/kinematic_weighting/postweighting_kinematics/LcToppipi_2012_MagDown_Lc_p_P-weighted}\n \\label{fig:cpv:kinematic_weighting:post:Lc_p:P}\n \\end{subfigure}\n \\begin{subfigure}[b]{0.4\\textwidth}\n \\includegraphics[width=\\textwidth]{cpv/kinematic_weighting/postweighting_kinematics/LcToppipi_2012_MagDown_Lc_p_PT-weighted}\n \\label{fig:cpv:kinematic_weighting:post:Lc_p:PT}\n \\end{subfigure}\\\\\n \\begin{subfigure}[b]{0.4\\textwidth}\n \\includegraphics[width=\\textwidth]{cpv/kinematic_weighting/postweighting_kinematics/LcToppipi_2012_MagDown_Lc_p_ETA-weighted}\n \\label{fig:cpv:kinematic_weighting:post:Lc_p:ETA}\n \\end{subfigure}\n \\begin{subfigure}[b]{0.4\\textwidth}\n \\includegraphics[width=\\textwidth]{cpv/kinematic_weighting/postweighting_kinematics/LcToppipi_2012_MagDown_Lc_p_PHI-weighted}\n \\label{fig:cpv:kinematic_weighting:post:Lc_p:PHI}\n \\end{subfigure}\n \\caption{%\n Clockwise from the top left: total momentum, transverse momentum, angle\n $\\phi$, and pseudorapidity of the proton from the \\PLambdac, weighted by\n the product of signal sWeights and kinematic weights.\n The 2012 magnet down data are shown.\n }\n \\label{fig:cpv:kinematic_weighting:post:Lc_p}\n\\end{figure}\n\n\\begin{figure}\n \\begin{subfigure}[b]{0.5\\textwidth}\n \\centering\n \\includegraphics[width=0.8\\textwidth]{cpv/kinematic_weighting/postweighting_kinematics/LcToppipi_2012_MagDown_h1_h2_P_LcTopKK-weighted}\n \\label{fig:cpv:kinematic_weighting:post:pKK_h1h2:P}\n \\end{subfigure}\n \\begin{subfigure}[b]{0.5\\textwidth}\n \\centering\n \\includegraphics[width=0.8\\textwidth]{cpv/kinematic_weighting/postweighting_kinematics/LcToppipi_2012_MagDown_h1_h2_PT_LcTopKK-weighted}\n \\label{fig:cpv:kinematic_weighting:post:pKK_h1h2:PT}\n \\end{subfigure}\\\\\n \\begin{subfigure}[b]{\\textwidth}\n \\centering\n \\includegraphics[width=0.4\\textwidth]{cpv/kinematic_weighting/postweighting_kinematics/LcToppipi_2012_MagDown_h1_h2_ETA_LcTopKK-weighted}\n \\label{fig:cpv:kinematic_weighting:post:pKK_h1h2:ETA}\n \\end{subfigure}\n \\caption{%\n Clockwise from the top left: total momentum, transverse momentum, and\n pseudorapidity of the \\PKminus\\ and \\PKplus\\ \\PLambdac\\ children in the\n \\pKK\\ data, weighted by the product of signal sWeights and kinematic\n weights.\n The 2012 magnet down data are shown.\n }\n \\label{fig:cpv:kinematic_weighting:post:pKK_h1h2}\n\\end{figure}\n\n\\begin{figure}\n \\begin{subfigure}[b]{0.5\\textwidth}\n \\centering\n \\includegraphics[width=0.8\\textwidth]{cpv/kinematic_weighting/postweighting_kinematics/LcToppipi_2012_MagDown_h1_h2_P_LcToppipi-weighted}\n \\label{fig:cpv:kinematic_weighting:post:ppipi_h1h2:P}\n \\end{subfigure}\n \\begin{subfigure}[b]{0.5\\textwidth}\n \\centering\n \\includegraphics[width=0.8\\textwidth]{cpv/kinematic_weighting/postweighting_kinematics/LcToppipi_2012_MagDown_h1_h2_PT_LcToppipi-weighted}\n \\label{fig:cpv:kinematic_weighting:post:ppipi_h1h2:PT}\n \\end{subfigure}\\\\\n \\begin{subfigure}[b]{\\textwidth}\n \\centering\n \\includegraphics[width=0.4\\textwidth]{cpv/kinematic_weighting/postweighting_kinematics/LcToppipi_2012_MagDown_h1_h2_ETA_LcToppipi-weighted}\n \\label{fig:cpv:kinematic_weighting:post:ppipi_h1h2:ETA}\n \\end{subfigure}\n \\caption{%\n Clockwise from the top left: total momentum, transverse momentum, and\n pseudorapidity of the \\Ppiminus\\ and \\Ppiplus\\ \\PLambdac\\ children in the\n \\ppipi\\ data, weighted by the product of signal sWeights and kinematic\n weights.\n The 2012 magnet down data are shown.\n }\n \\label{fig:cpv:kinematic_weighting:post:ppipi_h1h2}\n\\end{figure}\n\n\\begin{figure}\n \\includegraphics[width=\\textwidth]{cpv/kinematic_weighting/postweighting_kinematics/LcToppipi_2012_MagDown_roc_curves}\n \\caption{%\n ROC curves for different kinematic weighting techniques.\n The ``no weights'' data has no \\emph{kinematic} weights applied, only\n signal sWeights.\n The ``2D binned'' and ``\\ac{BDT}'' data uses the product of the respective\n kinematic weights and the signal sWeights for the \\ppipi\\ data, and uses\n signal sWeights for the \\pKK\\ data.\n The area under each \\ac{ROC} curve, the \\acs{AUC}, is given in the legend.\n }\n \\label{fig:cpv:kinematic_weighting:post:roc}\n\\end{figure}\n", "meta": {"hexsha": "eaa783466e6862677959e12b21ec3e0b1a25d734", "size": 30877, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "chapters/cpv/kinematic_weighting.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/cpv/kinematic_weighting.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/cpv/kinematic_weighting.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": 50.206504065, "max_line_length": 236, "alphanum_fraction": 0.7759821226, "num_tokens": 9521, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185205547239, "lm_q2_score": 0.32423541204073586, "lm_q1q2_score": 0.18352324823474864}}
{"text": "\\section{Background Estimation}\n\\label{sec:background}\nThere are two main backgrounds in this research: \\ztt decays and QCD jets misidentified as $\\tau$s (fake background, Section.~\\ref{sec:background:fake}), which are estimated by Monte Carlo Simulation (MC) and data-driven methods respectively. \\ztt background is simulated by MC using \\sherpa samples. Normalization factors (NF) for two Z control regions (ZCR 0 and ZCR 1, in Section.~\\ref{sec:eventselection}) are defined to normalize the simulation to the data from \\ztt process. \n\nIn addition, there are processes with one real tau, such as $W\\rightarrow \\tau\\nu + $jets and top decays, where the second tau candidate is a misidentified QCD jet. A small contribution of events with two real taus come from \\ttbar and diboson decays. All these latter contributions are modeled from MC and grouped together in a ‘Other bkg’ category. The normalisation of this category is fixed to the theory prediction.\n\n\\subsection{Fake background}\n\\label{sec:background:fake}\n\n\\tauhad decays are composed of a neutrino and a set of visible decay products, most frequently one or three charged pions and up to two neutral pions. The reconstruction of these visible decay products (\\tauhadvis) is seeded by jets reconstructed using the anti-kt algorithm\\cite{antikt}, which, however, provides no discrimination against quarks or gluons initiating jets. To separate the true \\tauhadvis (initiating from hadronic tau decays) from jets initiated by quarks or gluons, a Recurrent Neural Network identification (RNN ID) [ATL-PHYS-PUB-2019-033] algorithm is trained and evaluated by MC simulations, employing information from reconstructed charged-particle tracks and clusters of energy in the calorimeter associated to \\tauhadvis candidates as well as high-level discriminating variables. Four working points of RNN tau-ID with increasing background rejection ($Very$ $loose$, $Loose$, $Medium$ and $Tight$) are defined, while only $Medium$ working point is used in this research due to the best \\PhiTau sensitivity obtained at $Medium$. \n\n\\subsubsection{\\taulh channel}\n\\label{sec:background:fakelh}\nFake background in \\taulh channel is estimated from quark- or gluon-initiated jets that are misidentified as hadronically decaying \\tauhadvis leptons in the \\taulh final state. Fake \\tauhadvis consists mostly of W + jets events, followed by QCD multi-jet and Top events. Unlike Z background, the fake background is poorly modeled by MC due to the statistical limitations in the simulated events sample (i.e. multi-jet processes), as well as the unknown systematic uncertainties related to objects misidentified as $\\tau$s [ATL-PHYS-PROC-2019-006]. \n\nA data-driven method named Fake-Factor is therefore put forward to estimate fake background. Given that RNN described above provides a superior classification of true and misidentified \\tauhadvis candidates, it is appropriate to define a anti-\\tauhadvis ID region that \\tauhadvis candidates pass all analysis requirements except for the $Medium$ RNN tau-ID working point requirement. \n\nThe number of events of fake $\\tau$ background in signal region is estimated by the number of events in anti-$\\tau$ region multiplying with the combined Fake-Factor $\\mathcal{F}$. Events in the anti-\\tauhadvis region not corresponding to fakes from jets are subtracted using simulated event samples. Then in each bin, the number of events with a jet misidentified as $\\tau$ is given by: \n\\begin{equation}\\label{eq:fakeeventsSR}\n\tN^{\\operatorname{SR}}_{\\operatorname{fakes}} = (N^{\\operatorname{anti-}\\tau}_{\\operatorname{Data}}-N^{\\operatorname{anti-}\\tau}_{\\operatorname{MC, no jet}\\rightarrow\\tau})\\times \\mathcal{F} \n\\end{equation}\nAs there are multi-fake backgrounds (W + jets, QCD multi-jet and Top events) generating \\tauhadvis candidates, Fake-Factor should therefore be constructed as the combined Fake-Factor ($\\mathcal{F}$) which is the sum of the individual Fake-Factors ($F_i, i = W, QCD$) for each relevant process, weighted by the expected fractional contribution ($R_i$) for the considered process in the anti-\\tauhadvis region. However, as the small background from Top production have the similar Fake-Factors as the W + jets background, therefore, it is assumed that all the processes except QCD multi-jet production can be described using the Fake-Factors derived for W + jets events. Hence, the combined Fake-Factor $\\mathcal{F}$ can be written as: \n\\begin{equation}\\label{eq:combinedFF}\n\t\\mathcal{F} = R_{W}F_{W} + R_{QCD} F_{QCD} \n\\end{equation}\nwhere $R_{W} = 1 - R_{QCD}$. $F_i$ is defined in the dedicated W + jets and QCD control regions as the ratio of the data events passing the $\\tau$ ID region to the corresponding events failing the $\\tau$ ID region, that is anti-$\\tau$ ID region, and the events not corresponding to fakes from jets are subtracted using MC simulated event samples: \n\\begin{equation} \n\tF_{i} = \\frac{N^{\\tau\\operatorname{ID},\\operatorname{CR}_{i}}_{\\operatorname{Data}}-N^{\\tau \\operatorname{ID},\\operatorname{CR}_{i}}_{\\operatorname{MC, no jet}\\rightarrow \\tau}}{ N^{\\operatorname{anti-}\\tau,\\operatorname{CR}_{i}}_{\\operatorname{Data}}-N^{\\operatorname{anti-}\\tau,\\operatorname{CR}_{i}}_{\\operatorname{MC, no jet}\\rightarrow \\tau}} \n\\end{equation}\n\n\\subsubsection{\\tauhh channel}\n\\label{sec:background:fakehh}\nFake background estimation methodology in \\tauhh channel is implemented by applying the Fake-Factor method in \\taulh channel twice as there are two hadronically decaying $\\tau$s (leading $\\tau$, subleading $\\tau$) in the final state. \n\nSimilar to \\taulh channel, \\tauhh channel is using anti-$\\tau$ ID region (not-medium) to estimate the misidentified \\tauhadvis candidates in the signal region. While especially, a minimum RNN ID requirement of at least one \\tauhadvis passing loose working point is applied in \\tauhh channel. This is because HIGG4D3 derivation removing all events where both \\tauhadvis fail the loose RNN criteria, because of which the loose-not-medium region is designed. \n\nTable.~\\ref{tab:hadhad_anti_tau_regions} shows the RNN ID region requirements for leading $\\tau$ and subleading $\\tau$ in \\tauhh channel. Therefore, two sets of FF are designed for not-medium (nm) and loose-not-medium (lnm) ID regions, and the numerator of the FFs is the W+jets CR with medium (m) ID requirement in both cases, described in Eq.~\\ref{eq:FFs-lnm-nm}. \n\\begin{equation}\n\\begin{aligned}\\label{eq:FFs-lnm-nm}\n\tFF^{\\operatorname{nm}} &= (N_{\\operatorname{Data}} - N_{\\operatorname{MC, no\\ jet}\\rightarrow\\tau})^{\\operatorname{WCR}}_{\\operatorname{medium\\;}\\tau \\operatorname{ID}}/(N_{\\operatorname{Data}} - N_{\\operatorname{MC, no\\ jet}\\rightarrow\\tau})^{\\operatorname{WCR}}_{\\operatorname{not-medium\\;}\\tau \\operatorname{ID}}\\\\\n\tFF^{\\operatorname{lnm}} &= (N_{\\operatorname{Data}} - N_{\\operatorname{MC, no\\ jet}\\rightarrow\\tau})^{\\operatorname{WCR}}_{\\operatorname{medium\\;}\\tau \\operatorname{ID}}/(N_{\\operatorname{Data}} - N_{\\operatorname{MC, no\\ jet}\\rightarrow\\tau})^{\\operatorname{WCR}}_{\\operatorname{loose-not-medium\\;}\\tau \\operatorname{ID}}\\\\\n\\end{aligned}\n\\end{equation}\n\n\\begin{table}[h!]\n\t\\begin{center}\n\t\t\\caption{Event categories used in the derivation and application of fake-factors for the estimation method based on anti-$\\tau$ ID events.}\n\t\t\\label{tab:hadhad_anti_tau_regions}\n\t\t\\begin{tabular}{ccc}\n\t\t\t\\hline\n\t\t\t\\hline\n\t\t\tregion&leading ID&sub-leading ID\\\\\n\t\t\t\\hline\n\t\t\tanti-\\tauhadvis¬-medium¬-medium\\\\\n\t\t\tlead-anti-\\tauhadvis¬-medium&medium\\\\\n\t\t\tsublead-anti-\\tauhadvis&medium¬-medium\\\\\n\t\t\tlead-anti-\\tauhadvis-loose&loose-not-medium&medium\\\\\n\t\t\tsublead-anti-\\tauhadvis-loose&medium&loose-not-medium\\\\\n\t\t\t\\hline\n\t\t\t\\hline\n\t\t\\end{tabular}\n\t\t\n\t\\end{center}\n\\end{table}\n\n\\begin{figure}[h!]\n\t\\begin{center}\n\t\t\\includegraphics[width=.37\\textwidth]{figures/background/app_FF_in_hh.jpg}\n\t\\end{center}\n\t\\caption{Pictorial representation of the application of fake-factors for the \\thadhad channel.}\n\t\\label{fig:hadhad_ff_cartoon}\n\\end{figure}\nFig.~\\ref{fig:hadhad_ff_cartoon} illustrates the application of FF in \\tauhh channel, where $\\tau_0$ and $\\tau_1$ indicate leading and subleading $\\tau$s, and $FF_0$, $FF_1$ are their Fake-Factors correspondingly. \nThe events with $\\tau_1^{lnm}$ and $\\tau_0^{nm}$ (colored in orange) are scaled into $\\tau_1^m$ and $\\tau_0^{nm}$ region (colored in blue) by Fake-Factor $FF_1^{\\operatorname{lnm}}$, which along with the events with $\\tau_1^m$ and $\\tau_0^{nm}$ (in blue) are then scaled into SR with $FF_0^{\\operatorname{nm}}$. \nSimilarly, the green region is first scaled into the purple region and then along with the $\\tau_1^{lnm}$ and $\\tau_0^{nm}$ events are scaled into SR. The overlap (in yellow) of the orange and green regions is scaled twice to SR, which should be Subtracted. Eq.~\\ref{eq:FFapphh} shows a detailed illustration of the application of FF, where $\\tau_0^T$ and $\\tau_1^T$ indicate the true \\tauhadvis contribution simulated by MC. \n\\begin{equation}\n\\label{eq:FFapphh}\n\\begin{aligned}\n\t\t\\tau_0^{\\operatorname{SR}}\\tau_1^{\\operatorname{SR}} = &\\tau_0^{\\operatorname{T}}\\tau_1^{\\operatorname{T}}\\; (\\mathrm{MC})\\; + (FF_1^{\\operatorname{lnm}}\\tau_0^{\\operatorname{nm}}\\tau_1^{\\operatorname{lnm}}+\\tau_0^{\\operatorname{nm}}\\tau_1^{\\operatorname{m}})FF_0^{\\operatorname{nm}}\\\\\n\t\t&+ (FF_0^{\\operatorname{lnm}}\\tau_0^{\\operatorname{lnm}}\\tau_1^{\\operatorname{nm}}+\\tau_0^{\\operatorname{m}}\\tau_1^{\\operatorname{nm}})\\;FF_1^{\\operatorname{nm}} \\\\\n\t\t&- \\frac{1}{2} (FF_0^{\\operatorname{lnm}}FF_1^{\\operatorname{nm}} + FF_0^{\\operatorname{nm}}FF_1^{\\operatorname{lnm}}) \\tau_0^{\\operatorname{lnm}}\\tau_1^{\\operatorname{lnm}} \n\\end{aligned}\n\\end{equation}\n%\\input{fake_bias}", "meta": {"hexsha": "b171c424d01e5bdebb39cb20579881e895b0ab1b", "size": 9698, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "background.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": "background.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": "background.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": 115.4523809524, "max_line_length": 1054, "alphanum_fraction": 0.7606723036, "num_tokens": 2817, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526368038302, "lm_q2_score": 0.32082130731838393, "lm_q1q2_score": 0.18282086791823304}}
{"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 342W / 650 Fall \\the\\year{} \\\\ Midterm Examination One}\n\\author{Professor Adam Kapelner}\n\n\\date{Thursday, March 25, \\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}\nThis exam is 100 minutes (variable time per question) and closed-book. You are allowed \\textbf{two} 8.5 $\\times$ 11'' 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{8} George Box and Norman Draper in 1987 wrote \\qu{All models are wrong but some are useful}. Below are some conceptual questions about this aphorism and modeling in general.\n\n\\vspace{-0.2cm}\\benum\\truefalsesubquestionwithpoints{12} \n\n\\begin{enumerate}[(a)]\n\\item \\qu{models are wrong} since their predictions are not exactly equal to the measurements.\n\\item In the quote, \\qu{models are wrong} since they are approximations.\n\\item In the quote, \\qu{models are wrong} since they can never be validated.\n\\item In the quote, \\qu{models are wrong} since they cannot be learned from data.\n\\item In the quote, \\qu{models are wrong} since some are non-mathematical.\n\\item In the quote, \\qu{models are wrong} since the prediction target is not well-defined.\n\\item In the quote, \\qu{some [models] are useful} since they can be validated.\n\\item In the quote, \\qu{some [models] are useful} since they can be learned from data.\n\\item In the quote, \\qu{some [models] are useful} since their predictions are \\qu{good enough} (where the builder of the model must define exactly what \\qu{good enough} means).\n\\item In the quote, \\qu{some [models] are useful} because they use precise measurements.\n\\item In the quote, \\qu{some [models] are useful} because they are better to use than a naive guess of what the phenomenon will be in a given setting.\n\\item In the quote, \\qu{some [models] are useful} because they can perform both regression and binary classification simultaneously.\n\\end{enumerate}\n\\eenum\\instr\\pagebreak\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\problem\\timedsection{7} We examine the famous aphorism \\qu{absence makes the heart grow fonder} as $g$, a model for reality. In case you aren't a poet, \\qu{fonder} means \\qu{more in love}.\n\n\n\\vspace{-0.2cm}\\benum\\truefalsesubquestionwithpoints{11} \n\n\\begin{enumerate}[(a)]\n\\item There is one target of prediction, $y$: the degree of the heart's fondness.\n\\item There is one setting, $x$: the amount of absence.\n\\item The model as stated is mathematical. \n\\item Comparing a binary metric for the degree of the heart's fondness is to a continuous metric for the degree of the heart's fondness, the more accurate metric for the degree of the heart's fondness is continuous.\n\\item The most accurate reading of the aphorism indicates that absence is a binary metric.\n\\item The most accurate reading of the aphorism indicates that absence is a continuous metric.\n\\item This aphorism describes to the reader all of the $z$'s.\n\\item $\\delta$ will be very large relative to $f$.\n\\item $g$ is monotonic.\n\\item $f$ is monotonic.\n\\item After establishing metrics and their means of measurement, a mathematical model can be learned from data.\n\\end{enumerate}\n\\eenum\\instr\\pagebreak\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\problem\\timedsection{13} Consider a dataset of $n$ observations. \n\n\n\\vspace{-0.2cm}\\benum\\truefalsesubquestionwithpoints{18} ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~Let $\\mathcal{X} = \\reals$, $\\mathcal{Y} = \\braces{0,1}$ and the dataset has $n$ unique values of $x$.\n\\vspace{-0.1cm}\n\\begin{enumerate}[(a)]\n\\item Modeling $y$ is called a \\qu{binary classification} problem.\n\\item $f$ must be monotonic.\n\\item $g$ must be monotonic.\n\\item $\\mathcal{H} = \\braces{w x : w \\in \\reals}$ is a reasonable model candidate set.\n\\item $\\mathcal{H} = \\braces{w_0 + w_1 x : w_0, w_1 \\in \\reals}$ is a reasonable model candidate set.\n\\item $g_0$ is the sample mode of all $y$ observations.\n\\item Any model $g$ will have nonzero $\\delta$.\n\\item This model is likely to have estimation error.\n\\item A reasonable error metric for this model is misclassification error.\n\\item A reasonable error metric for this model is hinge error.\n\\end{enumerate}\n\nFor the remaining questions in this problem, let $\\mathcal{Y} = \\reals$, $\\mathcal{X} = \\braces{0,1}$ and the dataset has $n$ unique values of $y$.\n\n\\begin{enumerate}[(a)]\n\\setcounter{enumi}{10}\n\\item $\\mathcal{H} = \\braces{w x : w \\in \\reals}$ is reasonable regardless of $\\mathcal{A}$.\n\\item $\\mathcal{H} = \\braces{w_0 + w_1 x : w_0, w_1 \\in \\reals}$ is reasonable regardless of $\\mathcal{A}$.\n\\item $g_0$ is the sample mode of all $y$ observations.\n\\item $g$ must be of the form $g(x) = a$ if $x = 0$ and $g(x) = b$ if $x=1$ where $a,b \\in \\reals$.\n\\item Any model $g$ will have nonzero $\\delta$.\n\\item Any model $g$ will have two parameters (i.e. two degrees of freedom).\n\\item To decrease misspecification error, we can collect more data ($n$ increases).\n\\item A reasonable error metric for this model is hinge error.\n\\end{enumerate}\n\\eenum\\instr\\pagebreak\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\problem\\timedsection{5} $\\mathbb{D}$ is illustrated below:\n\n\\begin{figure}[htp]\n\\centering\n\\includegraphics[width = 6in]{binary.pdf}\n\\end{figure}\n\n\\vspace{-0.2cm}\\benum\\truefalsesubquestionwithpoints{7} \n\n\\begin{enumerate}[(a)]\n\\item Modeling $y$ is called a \\qu{binary classification} problem.\n\\item $p_{raw}=2$\n\\item $p_{raw}=3$\n\\item The dataset is \\qu{linearly separable}.\n\\item The perceptron algorithm uses a default $\\mathcal{H} = \\braces{\\indic{w_0 ~+~ w_1 x ~+~ w_2 x_2~\\geq~0}: w_0, w_1, w_2 \\in \\reals}$\n\\item The perceptron algorithm with the default $\\mathcal{H}$ run with a max number of iterations of $3,000$ will converge.\n\\item The perceptron algorithm with the default $\\mathcal{H}$ run with a max number of iterations of $3,000$ will provide a $g$ that can be used for prediction.\n\\end{enumerate}\n\\eenum\\instr\\pagebreak\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\problem\\timedsection{8} \\ingray{$\\mathbb{D}$ is illustrated below} and now consider $\\mathcal{H}_{new} = \\braces{\\indic{[1~x_1~x_1^2~x_2~x_2^2]^\\top \\w~ \\geq~ 0}: \\w\\in \\reals^5}$. $\\mathbb{D}$ has $n=1000$ with 672 observations where $y=0$. \n\n\n\\begin{figure}[htp]\n\\centering\n\\includegraphics[width = 6in]{binary.pdf}\n\\end{figure}\n\n\\vspace{-0.2cm}\\benum\\truefalsesubquestionwithpoints{7} \n\n\\begin{enumerate}[(a)]\n\\item In contrast to the default $\\mathcal{H}$, $\\mathcal{H}_{new}$ now includes polynomial transformations.\n\\item $f \\in \\mathcal{H}_{new}$.\n\\item Under $\\mathcal{H}_{new}$, we have $g_0(x_1,x_2) = 0$.\n\\item A maximum-margin hyperplane model algorithm using $\\mathcal{H}_{new}$ will converge to a solution for the five parameters $\\w$.\n\\item Minimizing the objective function $AHE + \\lambda || \\w ||^2$ where AHE is average hinge error for the five parameters $\\w$ will converge to a solution.\n\\item Minimizing the objective function $AHE + \\lambda|| [w_1~w_2~w_3~w_4] ||^2$ where AHE denotes the average hinge error for the five parameters $\\w$ will converge to a solution.\n\\item The value of $\\lambda$ in (e) and (f) is specified before the model is fit.\n\\end{enumerate}\n\\eenum\\instr\\pagebreak\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\problem\\timedsection{5} \\ingray{$\\mathbb{D}$ is illustrated below and now consider $\\mathcal{H}_{new} = \\braces{\\indic{[1~x_1~x_1^2~x_2~x_2^2]^\\top \\w~ \\geq~ 0}: \\w\\in \\reals^5}$. $\\mathbb{D}$ has $n=1000$ with 672 observations where $y=0$. } \n\n\\vspace{-0.4cm}\n\\begin{figure}[htp]\n\\centering\n\\includegraphics[width = 6in]{binary.pdf}\\vspace{-0.4cm}\n\\end{figure}\n\n\\vspace{-0.4cm}\\benum\\truefalsesubquestionwithpoints{5} \n\nConsider the situation where you remove the points from $\\mathbb{D}$ that would allow for separability using a model from $\\mathcal{H}_{new}$, fit a maximum margin hyperplane $g$, then add those points back into $\\mathbb{D}$.\n\nNote: only one of (a), (b), (c) is true.\n\n\\begin{enumerate}[(a)]\n\\item The order of magnitude of the average hinge error in $\\mathbb{D}$ for $g$ is $10^{-1}$ in units of $y$.\n\\item The order of magnitude of the average hinge error in $\\mathbb{D}$ for $g$ is $10^{-2}$ in units of $y$.\n\\item The order of magnitude of the average hinge error in $\\mathbb{D}$ for $g$ is $10^{-3}$ in units of $y$.\n%\\item If this model were to be validated using one holdout test set which is 20\\% of $n$, there will be large variance in the out-of-sample misclassification error among many unique training-test splits.\n\\item If $K$-fold cross validation were employed where $K=10$, the out of sample misclassification error will be $\\approx$ 0.5\\%.\n\\item If $K$-fold cross validation were employed where $K=5$, the out of sample misclassification error will be $\\approx$ 0.5\\%.\n\\end{enumerate}\n\n%Now for the rest of the questions, fit $g$ using the KNN algorithm where $K=10$.\n%\n%\\begin{enumerate}[(a)]\n%\\setcounter{enumi}{3}\n%\\item \n%\\end{enumerate}\n\\eenum\\instr\\pagebreak\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\problem\\timedsection{6} $\\mathbb{D}$ is illustrated below. $\\mathbb{D}$ has $n=1000$ with 672 observations where $y=0$. We now fit $g$ using the KNN algorithm with the default distance metric.\n\n%\\vspace{-0.4cm}\n\\begin{figure}[htp]\n\\centering\n\\includegraphics[width = 6in]{binary.pdf}\\vspace{-0.4cm}\n\\end{figure}\n\n\\benum\\truefalsesubquestionwithpoints{6}\n\n\\begin{enumerate}[(a)]\n\\item If $K$ in the KNN algorithm was set to be 1, then there would be zero in-sample misclassification error.\n\\item If $K$ in the KNN algorithm was set to be 1, then there would be zero out-of-sample misclassification error.\n\\item If $K$ in the KNN algorithm was set to be 7, then there would be zero in-sample misclassification error.\n\\item If $K$ in the KNN algorithm was set to be 1, then $g(0.5, 0.5) = 0$.\n\\item If $K$ in the KNN algorithm was set to be 1, then $g(2, 0.13) = 0$.\n\\item If $K$ in the KNN algorithm was set to be 100, then $g(2, 0.13) = 0$.\n\\end{enumerate}\n\\eenum\\instr\\pagebreak\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\problem\\timedsection{8} Let the random variable $X$ and $Y$ be the models that realized the rows in $\\mathbb{D}$. An $n=2,000$ example $\\mathbb{D}$ is housed in an \\texttt{R} \\texttt{data.frame} object called \\texttt{Xy}. Below is a plot of this data frame.\n\n%\\vspace{-0.4cm}\n\\begin{figure}[htp]\n\\centering\n\\includegraphics[width = 9in]{sine.pdf}\\vspace{-0.4cm}\n\\end{figure}\n\n\\benum\\truefalsesubquestionwithpoints{8}\n\n\\begin{enumerate}[(a)]\n\\item $X$ are $Y$ are correlated.\n\\item $X$ are $Y$ are associated.\n\\item Running \\texttt{cov(Xy\\$x, Xy\\$y)} in \\texttt{R} would return zero.\n\\item Running \\texttt{coef(lm(y $\\sim$ x))} in \\texttt{R} would return a vector of dimension two where the values are both near zero.\n\\item The model produced by \\texttt{lm(y $\\sim$ x)} in \\texttt{R} suffers mostly from misspecification error.\n\\item A linear polynomial model of degree 5 would produce a model with lower out of sample error than the model produced by \\texttt{lm(y $\\sim$ x)} in \\texttt{R}.\n\\item A linear polynomial model of degree 5 has risky predictive performance when extrapolating.\n\\item It is reasonable to believe that $z \\approx x$ and that $t \\approx f$ in this case (at least within $\\mathcal{X} = \\bracks{0,2}$).\n\\end{enumerate}\n\\eenum\\instr\\pagebreak\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\problem\\timedsection{14} Let $\\X = \\bracks{\\x_{\\cdot 0}~|~\\x_{\\cdot 1}~|~\\ldots~|~\\x_{\\cdot p}} \\in \\reals^{n \\times (p +1)}$, $\\rank{\\X} = p + 1$, let $\\x_i$ denote the $i$th row of the matrix $\\X$ and $\\y \\in \\reals^n$. Your modeling task is to model the response using the $n$ observations. All notation is standard from class and we consider:\n\n\\beqn\n%\\H &=& \\XXtXinvXt \\\\\n\\mathcal{H} &=& \\braces{\\w^\\top \\x : \\w \\in \\reals^{p+1}} \\\\\n%h^*(\\x) &=& \\x\\bbeta \\\\\n\\b &=& \\displaystyle\\argmin_{\\w \\in \\reals^{p + 1}}\\braces{(\\y - \\X\\w)^\\top (\\y - \\X\\w)} \\\\\n\\hat{y}_i &=& g(\\x_i) = \\x_i \\b\n\\eeqn\n\n\\benum\\truefalsesubquestionwithpoints{15}\n\n\\begin{enumerate}[(a)]\n\\item The algorithm $\\mathcal{A}$ that returns $g$ minimizes $\\sum_{i=1}^n e_i^2$.\n\\item The algorithm $\\mathcal{A}$ that returns $g$ minimizes $\\sum_{i=1}^n \\mathcal{E}_i^2$.\n\\item The algorithm $\\mathcal{A}$ that returns $g$ is called \\qu{ordinary least squares} (OLS) regression if $\\x_{\\cdot 0} = \\onevec_n$.\n\\item The vector $\\yhat := \\bracks{\\hat{y}_1, \\ldots, \\hat{y}_n}^\\top$ is in the span of the columns of $\\X$.\n\\item If $p$ is substantially less than $n$, there would be no overfitting in this model.\n\\item SST = SSR + SSE\n\\item If $p=n-1$, then $R^2 = 1$.\n\\item This algorithm can accomodate additional columns in $\\X$ that are log transformations of original columns in $\\x$.\n\\item $\\rank{\\H} = p+1$\n\\item $\\rank{\\H\\X} = n$\n\\item $\\H\\Q = \\X$\n\\item $\\colsp{\\H} = \\colsp{\\Q}$\n\\item If $\\exists j$ such that $\\y = \\x_{\\cdot j}$, then MSE = 0.\n\\item $\\exists \\w \\in \\mathcal{H}$ where $\\w \\neq \\b$ and this $\\w$ provides a higher RMSE.\n\\item Consider $\\A$, an $n \\times (2p+2)$ matrix of $\\X$ and $\\Q$ column-binded together. $\\A$ is full rank.\n\\end{enumerate}\n\\eenum\\instr\\pagebreak\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\problem\\timedsection{7} \\ingray{Let $\\X = \\bracks{\\x_{\\cdot 0}~|~\\x_{\\cdot 1}~|~\\ldots~|~\\x_{\\cdot p}} \\in \\reals^{n \\times (p +1)}$, $\\rank{\\X} = p + 1$, let $\\x_i$ denote the $i$th row of the matrix $\\X$ and $\\y \\in \\reals^n$. Your modeling task is to model the response using the $n$ observations. All notation is standard from class and we consider:}\n\n\\beqn\n%\\H &=& \\XXtXinvXt \\\\\n\\ingray{\\mathcal{H}} &\\ingray{=}& \\ingray{\\braces{\\w^\\top \\x : \\w \\in \\reals^{p+1}}} \\\\\n%h^*(\\x) &=& \\x\\bbeta \\\\\n\\b &=& \\displaystyle\\argmin_{\\w \\in \\reals^{p + 1}}\\braces{|\\y - \\X\\w|^\\top \\onevec_n} \\\\\n\\ingray{\\hat{y}_i} &\\ingray{=}& \\ingray{g(\\x_i) = \\x_i \\b}\n\\eeqn\n\n\\benum\\truefalsesubquestionwithpoints{9}\n\n\\begin{enumerate}[(a)]\n\\item The algorithm $\\mathcal{A}$ that returns $g$ minimizes $\\sum_{i=1}^n e_i^2$.\n\\item The algorithm $\\mathcal{A}$ that returns $g$ minimizes $\\sum_{i=1}^n \\mathcal{E}_i^2$.\n\\item The algorithm $\\mathcal{A}$ that returns $g$ is called \\qu{ordinary least squares} (OLS) regression if $\\x_{\\cdot 0} = \\onevec_n$.\n\\item The vector $\\yhat := \\bracks{\\hat{y}_1, \\ldots, \\hat{y}_n}^\\top$ is in the span of the columns of $\\X$.\n\\item If $p$ is substantially less than $n$, there would be no overfitting in this model.\n\\item SST = SSR + SSE\n\\item If $p=n-1$, then $R^2 = 1$.\n\\item This algorithm can accomodate additional columns in $\\X$ that are log transformations of original columns in $\\x$.\n\\item This algorithm can accomodate additional columns in $\\X$ that are first-order interaction transformations of original columns in $\\x$.\n\\end{enumerate}\n\\eenum\\instr\\pagebreak\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\problem\\timedsection{8} Consider a continuous response fit by OLS. During lecture we illustrated in-sample $s_e$ and out-of-sample $s_e$ as a function of \\qu{model complexity} for a given dataset of size $n$ with $p_{raw} < n$ features. Below are questions related to this illustration. The quantity $K$ is the value that controls the size of the train-test split setting as we discussed in class.\n\n\\benum\\truefalsesubquestionwithpoints{7}\n\n\\begin{enumerate}[(a)]\n\\item In-sample $s_e$ converges to zero as the number of features increases to $n$.\n\\item Logging $y$ and rerunning the model will not change the in-sample $s_e$ curve.\n\\item Out-of-sample $s_e$ is an honest metric of future performance for any valid $K$.\n\\item Out-of-sample $s_e$ is always smaller (for any degree of model complexity) if we employ $K$-fold CV.\n\\item The out-of-sample $s_e$ curve is smoother if we employ $K$-fold CV if compared to not performing $K$-fold CV.\n\\item If you were to begin with $p_{raw}$ features and then add columns consisting of random noise until there are a total of $n$ columns, the minimum of the out-of-sample $s_e$ curve would be expected at the model built with only the $p_{raw}$ features.\n\\item If the minimum of the out-of-sample $s_e$ curve is at a $p$ much larger than $p_{raw}$, this means the additional $p - p_{raw}$ features allowed the OLS algorithm to fit non-linearities and/or interactions among the features.\n\\end{enumerate}\n\\eenum\\instr\\pagebreak\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\problem\\timedsection{11} Consider the following four models in \\texttt{R}:\n\n\\begin{lstlisting}[basicstyle=\\normalsize]\n> mod1 = lm(medv ~ log(tax) + poly(rm, 2) + poly(zn, 2) + poly(nox, 2), MASS::Boston)\n> mod2 = lm(medv ~ ., MASS::Boston)\n> mod3 = lm(medv ~ . * rm, MASS::Boston)\n> mod4 = lm(medv ~ . * rm + poly(rm, 2) + poly(zn, 2) + poly(nox, 2), MASS::Boston)\n\\end{lstlisting}\n\\vspace{-0.75cm}\n\n\\noindent Recall that \\texttt{medv} is the response, a continuous metric that measures average price in \\$1,000's; \\texttt{rm} is a continuous metric that measures the average number of rooms in the houses and it ranges between 3.56 and 8.78; and \\texttt{chas} is a dummy variable indicating whether the property is on the Charles River or not.\n\\benum\\truefalsesubquestionwithpoints{11}\n\n\\begin{enumerate}[(a)]\n\\item For model 1, you can say \\texttt{medv} increases by $b_1$ times a proportion change in \\texttt{tax}.\n\\item Model 1 can fit a non-linear monotonic relationship in \\text{rm} for the input space of \\text{rm}.\n\\item Model 1 can fit a non-linear monotonic relationship in \\text{rm} for all values in $\\reals$.\n\\item The model matrix for model 1 will include a column for the raw values of \\text{rm} and a transformed column that takes these raw values and squares them element-wise.\n\\item Model 2 has a higher $R^2$ than model 1.\n\\item Model 3 has a higher $R^2$ than model 2.\n\\item Model 4 has a higher $R^2$ than model 3.\n\\item Model 2 has a higher oos $R^2$ than model 1.\n\\item Model 3 has a higher oos $R^2$ than model 2.\n\\item Model 4 has a higher oos $R^2$ than model 3.\n\\item Within $\\b$ in model 3, the 18th element is named \\texttt{chas:rm} and has a value of -1.643. You can interpret this slope coefficient as follows: as the number of rooms increments (i.e. \\texttt{rm} increases by 1), the response \\texttt{medv} is predicted to decrease by \\$1,643.\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\\problem\\timedsection{7} These are conceptual questions about statistical inference in the Bayesian and Frequentist perspectives.\n\n\\vspace{-0.2cm}\\benum\\truefalsesubquestionwithpoints{10} \n\n\\begin{enumerate}[(a)]\n\\item The goal of point estimation is to find an approximation of the true value of $\\theta$.\n\\item The goal of theory testing is to find an approximation of the true value of $\\theta$.\n\\item The goal of statistical inference (in general) is to learn the true values of $\\xoneton$.\n\\item A parametric model $\\mathcal{F}$ must be assumed to do statistical inference using the Frequentist perspective.\n\\item A parametric model $\\mathcal{F}$ must be assumed to do statistical inference using the Bayesian perspective.\n\\item The data $\\xoneton$ cannot be collected without assuming an $\\mathcal{F}$.\n\\item To compute the value of the likelihood for the data $\\xoneton$, you must assume an $\\mathcal{F}$.\n%\\item The assumption of an $\\mathcal{F}$ implies a set $\\Theta$.\n\\item In the Frequentist perspective, $\\prob{\\theta}$ is degenerate.\n\\item In the Bayesian perspective, you can only do inference if the data is realized from $\\iid$ random variables.\n\\item In the Bayesian perspective, to compute the posterior, you must assume $\\mathcal{F}$ and $\\prob{\\theta}$.\n\\end{enumerate}\n\\eenum\\instr\\pagebreak\n\n\\problem\\timedsection{9} Assume $\\Xoneton \\iid p(x; \\theta)$, a discrete rv with support $\\mathcal{X}$ and parameter space $\\Theta$ and $p(\\theta)$ is the PMF for a rv with support $\\Theta$.\n\n\\vspace{-0.2cm}\\benum\\truefalsesubquestionwithpoints{14} \n\n\\begin{enumerate}[(a)]\n\\item $p(\\xoneton; \\theta) = p(x_1; \\theta)\\cdot p(x_2; \\theta) \\cdot \\ldots \\cdot p(x_n; \\theta)$\n\\item $\\mathcal{L}(\\theta; \\xoneton) = \\mathcal{L}(\\theta; x_1) \\cdot \\mathcal{L}(\\theta; x_2) \\cdot \\ldots \\cdot \\mathcal{L}(\\theta; x_n)$\n\\item $\\ell(\\theta; \\xoneton) = \\ell(\\theta; x_1) \\cdot \\ell(\\theta; x_2) \\cdot \\ldots \\cdot \\ell(\\theta; x_n)$\\item You can compute the maximum likelihood estimate by setting $\\sum_{i=1}^n \\displaystyle \\frac{d\\ell(\\theta;x_i) }{d\\theta} = 0$ and solving for $\\theta$.\n\\item You can compute the maximum likelihood estimate by setting $\\sum_{i=1}^n \\displaystyle \\frac{d\\ell(\\theta;x_i) }{dx_i} = 0$ and solving for $\\theta$.\n\\item If $n$ is large, the maximum likelihood estimator is approximately normally distributed.\n\\item $\\sum_{x \\in \\mathcal{X}} p(x; \\theta) = 1$.\n\\item $\\sum_{x \\in \\mathcal{X}} p(\\theta; x) = 1$.\n\\item $\\sum_{x \\in \\mathcal{X}} p(x) = 1$.\n\\item $\\sum_{x \\in \\mathcal{X}} p(\\theta) = 1$.\n\\item $\\sum_{\\theta \\in \\Theta} p(x; \\theta) = 1$.\n\\item $\\sum_{\\theta \\in \\Theta} p(\\theta; x) = 1$.\n\\item $\\sum_{\\theta \\in \\Theta} p(x) = 1$.\n\\item $\\sum_{\\theta \\in \\Theta} p(\\theta) = 1$.\n\\end{enumerate}\n\\eenum\\instr\\pagebreak\n\n%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\problem\\timedsection{9} Consider a rv $X$ with parameter space $\\Theta$. Below is an illustration of the universe of all values of $x$ and $\\theta$ drawn to-scale. The values inside the boxes are values of $x \\in \\support{X}$ and the values in the right margin are the values of $\\theta \\in \\Theta$.\n\n\\begin{figure}[htp]\n\\centering\n\\includegraphics[width = 6.5in]{x_theta_space.pdf}\n\\end{figure}\n\n\\vspace{-0.2cm}\\benum\\truefalsesubquestionwithpoints{9} \n\n\\begin{enumerate}[(a)]\n\\item $X$ is a discrete rv.\n\\item $\\Theta$ is discrete.\n\\item If you add up the areas of all the boxes above, you will get 100\\%.\n\\item The prior was created using the principle of indifference.\n\\item $\\prob{X = 1, \\theta = 1} > \\prob{X = 1, \\theta = 3}$.\n\\item $\\cprob{X = 1}{\\theta = 1} > \\cprob{X = 1}{\\theta = 3}$.\n\\item $\\cprob{\\theta = 1}{X = 3}$ can be computed by taking the yellow area and dividing by the sum of the yellow area, purple area and green area.\n\\item $\\cprob{\\theta = 3}{X = 1}$ can be computed by taking the blue area and dividing by the sum of the blue area, red area and green area.\n\\item $\\cprob{\\theta = 1}{X = 1}$ can be computed by taking the green area and dividing by the sum of the green area, purple area and yellow area.\n\\end{enumerate}\n\\eenum\\instr\\pagebreak\n\n%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\problem\\timedsection{8} Assume $X_1, X_2, X_3, X_4 \\iid \\text{Bernoulli}(\\theta)$ and $x_1 = 0, x_2 = 0, x_3 = 0, x_4 = 0$. For inference performed from the Bayesian perspective, assume Laplace's prior of indifference.\n\n\\vspace{-0.2cm}\\benum\\truefalsesubquestionwithpoints{7} \n\n\\begin{enumerate}[(a)]\n\\item The maximum likelihood estimate of $\\theta$ is $\\xbar$.\n\\item The maximum likelihood estimate of $\\theta$ is $\\half$.\n\\item The maximum likelihood estimate of $\\theta$ is 0.\n\\item $CI_{\\theta, 90\\%} = \\braces{0}$.\n\\item $CI_{\\theta, 100\\%} = \\reals$.\n\\item A frequentist hypothesis test of $H_a: \\theta \\neq 0.01$ at significance level 0.01 has a retainment region of $\\braces{0}$.\n\\item A frequentist hypothesis test of $H_a: \\theta \\neq 0.01$ at significance level 0.01 will result in a rejection of $H_0$.\n\\end{enumerate}\n\\eenum\\instr\\pagebreak\n\n%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\problem\\timedsection{11} Assume $X_1, X_2, X_3, X_4 \\iid \\text{Bernoulli}(\\theta)$ and $x_1 = 0, x_2 = 0, x_3 = 0, x_4 = 0$. For inference performed from the Bayesian perspective, assume Laplace's prior of indifference.\n\n\\vspace{-0.2cm}\\benum\\truefalsesubquestionwithpoints{16} \n\n\\begin{enumerate}[(a)]\n\\item The posterior after seeing only $x_1$ is $\\cprob{\\theta}{x} = \\betanot{1}{1}$.\n\\item The posterior after seeing only $x_1$ is $\\cprob{\\theta}{x} = \\betanot{1}{2}$.\n\\item The full posterior after all $n=4$ observations is $\\cprob{\\theta}{x} = \\betanot{1}{5}$.\n\\item The full posterior after all $n=4$ observations is $\\cprob{\\theta}{x} = \\betanot{5}{1}$.\n\\item The prior predictive distribution is $\\prob{x} = \\betanot{1}{1}$.\n\\item The prior predictive distribution is $\\prob{x} = \\binomial{n}{\\theta}$.\n\\item The maximum a posteriori estimate of $\\theta$ is 0.\n\\item The maximum a posteriori estimate of $\\theta$ is $>0$.\n\\item The minimum mean squared error estimate of $\\theta$ is 0.\n\\item The minimum mean squared error estimate of $\\theta$ is 1/5.\n\\item The minimum mean squared error estimate of $\\theta$ is 1/6.\n\\item The prior expectation is 1/2.\n\\item The prior median is 1/2.\n\\item The only prior mode is 1/2.\n\\item The minimum mean squared error estimator of $\\theta$ can be written as $\\displaystyle\\frac{2}{3}\\,\\thetahatmle$ + $\\displaystyle\\frac{1}{3}\\,\\expe{\\theta}$.\n\\item The $\\thetahatmmse$ and $\\thetahatmmae$ estimators for the value of $\\theta$ do not have any shrinkage whatsoever.\n\\end{enumerate}\n\\eenum\\instr\\pagebreak\n\n%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\problem\\timedsection{11} Assume $X_1, X_2, X_3, X_4 \\iid \\text{Bernoulli}(\\theta)$ and $x_1 = 0, x_2 = 0, x_3 = 0, x_4 = 0$. For inference performed from the Bayesian perspective, assume Laplace's prior of indifference.\n\n\\vspace{-0.2cm}\\benum\\truefalsesubquestionwithpoints{13} \n\n\\begin{enumerate}[(a)]\n\\item $CR_{\\theta, 90\\%} = \\bracks{\\text{qbeta}(5\\%, 1, 5), \\text{qbeta}(95\\%, 1, 5)}$\n\\item $CR_{\\theta, 90\\%} = \\bracks{0, \\text{qbeta}(90\\%, 1, 5)}$\n\\item $CR_{\\theta, 90\\%} = \\bracks{\\text{qbeta}(10\\%, 1, 5), 1}$\n\\item One needs to declare the test's significance level in order to compute a Bayesian p-value\n\\item When testing $H_a: \\theta < 0.3$, the Bayesian p-value can be computed via pbeta(0.3, 1, 5).\n\\item When testing $H_a: \\theta < 0.3$, the Bayesian p-value can be computed via pbeta(0.7, 1, 5).\n\\item When testing $H_a: \\theta < 0.3$, the Bayesian p-value can be computed via 1 - pbeta(0.3, 1, 5).\n\\item When testing $H_a: \\theta < 0.3$, the Bayesian p-value can be computed via 1 - pbeta(0.7, 1, 5).\n\\item When testing $H_a: \\theta < 0.3$, the Bayesian p-value can be computed via $\\int_{0.3}^1 \\oneover{B(1,5)} (1-\\theta)^4 d\\theta$.\n\\item When testing $H_a: \\theta < 0.3$, the Bayesian p-value can be computed via $\\int_0^{0.3} \\oneover{B(1,5)} (1-\\theta)^4 d\\theta$.\n\\item When testing $H_a: \\theta < 0.3$, the Bayesian p-value can be computed via $\\int_0^1 \\oneover{B(1,5)} (1-\\theta)^4 d\\theta$.\n\\item When testing $H_a: \\theta \\neq 0.3$, the Bayesian p-value is zero.\n\\item When testing $H_a: \\theta \\notin [0.3 \\pm \\delta]$, the Bayesian p-value is zero for all $\\delta > 0$.\n\\end{enumerate}\n\\eenum\\instr\\pagebreak\n\n%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\problem\\timedsection{15} This question is independet of those that came previously. Assuming a parametric model of the binomial with fixed $n$ and a beta prior, the posterior is plotted below:\n\n%RES = 1000\n%x = seq(0, 1, length.out = RES)\n%\n%alpha = 1\n%beta = 10\n%pacman::p_load(ggplot2, latex2exp)\n%ggplot(data.frame(x = x, y = dbeta(x, alpha, beta))) + \n% geom_area(aes(x = x, y = y), fill = \"red\", color = \"black\", alpha = 0.3) +\n% xlab(TeX(\"$\\\\theta$\")) +\n% ylab(TeX(\"$P(\\\\theta | x)$\"))\n%\n%qbeta(0.5, alpha, beta)\n%1 - pbeta(0.3, alpha, beta)\n\n%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\n\n\\begin{figure}[htp]\n\\centering\n\\includegraphics[width = 6.5in]{beta.pdf}\n\\end{figure}\n\n\\vspace{-0.2cm}\\benum\\truefalsesubquestionwithpoints{11} \n\n\\begin{enumerate}[(a)]\n\\item $HDR_{\\theta, 90\\%} = \\bracks{a, b}$ where the values $a$ and $b$ satisfies $0 < a < b < 1$.\n\\item $HDR_{\\theta, 90\\%} = \\bracks{0, b}$ where the value $b$ satisfies $0 < b < 1$.\n%\\item $HDR_{\\theta, 90\\%} = \\bracks{a, 1}$ where the value $a$ satisfies $0 < a < 1$.\n\\item If the Haldane prior was chosen, then we can be certain that $x > 0$ and $x < n$.\n\\item If the Haldane prior was chosen, there is no shrinkage in $\\thetahatmmse$.\n\\item $\\thetahatmap = \\thetahatmmae$.\n\\item $\\thetahatmmae = \\thetahatmmse$.\n\\item $\\thetahatmmae = 1 - (1/2)^{1/10}$.\n\\item $\\thetahatmmae = 0.5$.\n\\item When testing $H_a: \\theta < 0.3$, the Bayesian p-value is 0.0282 to the nearest three significant digits.\n\\item When testing $H_a: \\theta < 0.3$, the Bayesian p-value is 0.282 to the nearest three significant digits.\n\\end{enumerate}\n\\eenum\\instr\\pagebreak\n\n%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\end{document}\n\n", "meta": {"hexsha": "67211650d62e25d6f622fabd380e76b2f2666010", "size": 30658, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "exams/midterm1/midterm1.tex", "max_stars_repo_name": "kapelner/QC_MATH_342W_Spring_2021", "max_stars_repo_head_hexsha": "b78a71aab88d8ad2401c16a0b6746356dbbc4afb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2021-02-02T15:13:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-14T17:58:59.000Z", "max_issues_repo_path": "exams/midterm1/midterm1.tex", "max_issues_repo_name": "HubertMajewski/QC_MATH_342W_Spring_2021", "max_issues_repo_head_hexsha": "09afc327958f6c0aee12960617a49deff5d1304a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12, "max_issues_repo_issues_event_min_datetime": "2021-02-04T03:46:34.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-25T05:05:01.000Z", "max_forks_repo_path": "exams/midterm1/midterm1.tex", "max_forks_repo_name": "HubertMajewski/QC_MATH_342W_Spring_2021", "max_forks_repo_head_hexsha": "09afc327958f6c0aee12960617a49deff5d1304a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 19, "max_forks_repo_forks_event_min_datetime": "2021-02-01T05:00:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-25T05:20:23.000Z", "avg_line_length": 55.4394213382, "max_line_length": 893, "alphanum_fraction": 0.6937504077, "num_tokens": 9592, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3960681662740417, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.1825940704037935}}
{"text": "\\chapter{Sensitivity studies: production of $\\chinopm$ and $\\nino$}\n \\label{sec:CharginoNeutralinoProduction}\n\nIn this appendix, sensitivity studies are carried out for models involving squark-neutralino, chargino-neutralino, and neutralino-neutralino direct productions.\nMonte Carlo samples for these models have been produced using \\madgraph{}, interfaced with \\pythia{} to model the parton showering and hadronization.\nThe monojet analysis is expected to have low sensitivity to these models, and for this reason, the reconstruction of the physics objects is done with \\delphes{}~\\cite{Ovyn:2009tx}.\n\\delphes{} provides a very simple parametrization of the ATLAS detector acceptances, efficiencies and resolution, but does not model the trigger efficiency, the charged fraction and the electromagnetic fraction in the calorimeter.\nAltogether, this results into an about 10\\% to 20\\% difference between the signal acceptance predicted by \\delphes{} and the ATLAS simulation.\n\nThe sensitivity studies, closely follow the strategy used in Chapter~\\ref{sec:GravitinoProduction} for the light gravitino production in GMSB scenarios.\nThe ratio $\\sigma(\\text{SUSY})/$ $\\sigma(\\text{obs})$ is computed, where $\\sigma (SUSY)$ is the expected fiducial cross section for the signal model, and $\\sigma (obs)$ are the observed model independent limits of the monojet analysis, listed in Table \\ref{tab:modelIndependent}.\nModels for which $\\sigma (SUSY) / \\sigma (obs) > 1$ are excluded at 95\\% CL.\n\n\n\\section{Squark-neutralino production}\n \\label{subsec:SquarkNeutralinoProduction}\n\nThe study of the associated production of a scalar quark and a neutralino, $\\squarkneutralino$ (see Figure \\ref{fig:DiagramsElectroweakProduction} left), provides information on the coupling to the $\\ninoone$ as a DM candidate.\nSamples with squark mass ranges between $\\unit[100]{GeV}$ and $\\unit[1000]{GeV}$ have been generated for neutralino masses between 0~GeV and those values corresponding to a $\\Delta m = m_{\\squark} - m_{\\ninoone} = \\unit[3]{GeV}$.\nSince the squark, $\\squark$, decays into a quark, $q$, and a neutralino, $ \\ninoone$, the squark-neutralino production leads to a final state with an energetic jet and $\\met$.\n\nFigure \\ref{fig:squarkNeutralinoBestRegion} shows the signal region with the best sensitivity (higher $\\sigma (SUSY) / \\sigma (obs)$ ratio) for the different parameter configurations of this model.\nRegions M1, M2, M3 and M4 are found to be optimal for different values of $m_{\\squark}$ and $m_{\\ninoone}$.\n\n\\begin{figure}[!ht]\n\\begin{center}\n\\mbox{\n\\includegraphics[width=0.995\\textwidth]{Interpretations/Figures/sq_neu_best.eps}\n}\n\\end{center}\n\\caption[Ratio between the expected fiducial cross section for each squark-neutralino model, $\\sigma (SUSY)$, and the observed model independent limit.]{Ratio between the expected fiducial cross section for each squark-neutralino model, $\\sigma (SUSY)$, and the observed model independent limit, $\\sigma (obs)$, in the $m_{\\squark}$-$m_{\\ninoone}$ plane. The numbers in the boxes correspond to the index of the signal region with the best sensitivity.}\n\\label{fig:squarkNeutralinoBestRegion}\n\\end{figure}\n\nThe $\\sigma (SUSY) / \\sigma (obs)$ for the signal region providing the best sensitivity is shown in Figure~\\ref{fig:squarkNeutralinoLimits} as a function of $m_{\\squark}$, for $\\Delta m$ values of 100~GeV and 500~GeV.\nThe best sensitivity is obtained for $m_{\\squark} = \\unit[500]{GeV}$ and very small $m_{\\ninoone}$.\nFor this configuration of parameters, an energetic jet from the decay of the squark is produced in association to high $\\pt$ neutralinos.\n\nThe cross section of the signal is between one and four orders of magnitude smaller than the minimum visible cross section needed to provide any exclusion, in all the parameter space.\nTherefore, the possibility of setting limits in this region of the phase space with an early monojet analysis at 13~TeV is practically excluded.\n\n\\begin{figure}[!ht]\n\\begin{center}\n\\mbox{\n\\includegraphics[width=0.795\\textwidth]{Interpretations/Figures/sq_neu_limits.eps}\n}\n\\end{center}\n\\caption[Ratio $\\sigma (SUSY) / \\sigma (obs)$ as a function of $m_{\\squark}$ for different $\\Delta m$ values.]{Ratio $\\sigma (SUSY) / \\sigma (obs)$ as a function of $m_{\\squark}$ for $\\Delta m = 100,\\, 500$~GeV. For each mass point the best signal region giving the best ratio is used.}\n\\label{fig:squarkNeutralinoLimits}\n\\end{figure}\n\n\n\\section{Chargino-chargino and neutralino-chargino production}\n \\label{subsec:NeutralinoCharginoProduction}\n\nExclusion limits at the 95\\% CL on the direct production of charginos and neutralinos decaying to different final states have been computed by several analyses in ATLAS \\cite{Aad:2014nua}, and are summarized in Figure~\\ref{fig:SUSYEWSummary}.\nIn compressed scenarios where $m_{\\ninotwo} \\leq m_{\\ninoone} + m_Z$ and/or $m_{\\chinoonepm} \\leq m_{\\ninoone} + m_{W^{\\pm}}$, the gauge bosons are off-shell and produce soft leptons or jets that may not be reconstructed.\nAfter requiring that the system is balanced by an initial-state radiation jet, these models lead to monojet plus high $\\met$ final states.\n\n\\begin{figure}[!ht]\n\\begin{center}\n\\mbox{\n\\includegraphics[width=0.795\\textwidth]{Interpretations/Figures/ATLAS_SUSY_EWSummary.eps}\n}\n\\end{center}\n\\caption[Summary of ATLAS searches for electroweak production of charginos and neutralinos.]{Summary of ATLAS searches for electroweak production of charginos and neutralinos on $\\unit[20]{fb^{-1}}$ of $\\pp$ collision data at $\\sqrt{s} = \\unit[8]{TeV}$ \\protect\\cite{Aad:2014nua}. Exclusion limits at $95\\%$ CL are shown in the $m_{\\chinoonepm} = m_{\\ninotwo}$, $m_{\\ninoone}$ plane. The dashed and solid lines show the expected and observed limits respectively, including all uncertainties except the theoretical ones affecting the signal cross sections.}\n\\label{fig:SUSYEWSummary}\n\\end{figure}\n\nFigure~\\ref{fig:NeutralinoNeutralinoBestRegion} shows the ratio $\\sigma (SUSY) / \\sigma (obs)$ obtained in the most sensitive signal region for the generated samples with different mass configurations.\nThe best sensitivity is obtained for the selection M2 in the region of the parameter space with small $\\Delta m$, and for the selection M1 in models with low $m_{\\ninotwo , \\chinoonepm}$ and high $\\Delta m$.\nThe value of $\\sigma (SUSY) / \\sigma (obs)$ as a function of $m_{\\ninotwo , \\chinoonepm}$ is shown in Figure~\\ref{fig:NeutralinoNeutralinoLimits} for $\\Delta m = \\unit[5,\\, 25,\\, 50]{GeV}$. \nThe best sensitivity is obtained for low $m_{\\ninotwo , \\chinoonepm}$ and the $\\Delta m = \\unit[5]{GeV}$.\nThe monojet analysis is not sensitive enough to exclude any region of the parameter space under consideration, but the compressed configurations with low values of $m_{\\ninotwo , \\chinoonepm}$ are only a factor 2 below the threshold sensitivity.\nThese configurations might become important in future interpretations of the monojet analysis at 13~TeV.\n\n\\begin{figure}[!ht]\n\\begin{center}\n\\mbox{\n\\includegraphics[width=0.995\\textwidth]{Interpretations/Figures/NN-NC_grid.eps}\n}\n\\end{center}\n\\caption[Ratio between the expected fiducial cross section of $\\ninotwo \\chinoonepm$, $\\chinoonepm \\chinoonemp$ and the monojet observed model independent limit in the $m_{\\ninotwo , \\chinoonepm}$-$m_{\\ninoone}$ plane.]{Ratio between the expected fiducial cross section of $\\ninotwo \\chinoonepm$, $\\chinoonepm \\chinoonemp$ ($\\sigma (SUSY)$) and the monojet observed model independent limit ($\\sigma (obs)$) in the $m_{\\ninotwo , \\chinoonepm}$-$m_{\\ninoone}$ plane. The numbers on the boxes correspond to the index of the signal region with the best sensitivity.}\n\\label{fig:NeutralinoNeutralinoBestRegion}\n\\end{figure}\n\n\\begin{figure}[!ht]\n\\begin{center}\n\\mbox{\n\\includegraphics[width=0.795\\textwidth]{Interpretations/Figures/NN-NC_best.eps}\n}\n\\end{center}\n\\caption[Ratio $\\sigma (SUSY) / \\sigma (obs)$ as a function of $m_{\\ninotwo , \\chinoonepm}$ for $\\Delta m = 5, 25, 50$~GeV.]{Ratio $\\sigma (SUSY) / \\sigma (obs)$ as a function of $m_{\\ninotwo , \\chinoonepm}$ for $\\Delta m = \\unit[5,\\, 25,\\, 50]{GeV}$.}\n\\label{fig:NeutralinoNeutralinoLimits}\n\\end{figure}\n", "meta": {"hexsha": "7a68a4621fcc40bd5df15de8e8955e39c189953a", "size": 8148, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Appendix_SensitivityStudies/Appendix_SensitivityStudies.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": "Appendix_SensitivityStudies/Appendix_SensitivityStudies.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": "Appendix_SensitivityStudies/Appendix_SensitivityStudies.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.875, "max_line_length": 562, "alphanum_fraction": 0.765586647, "num_tokens": 2275, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.34864512179822543, "lm_q1q2_score": 0.18248795130657436}}
{"text": "%!TEX root = ../../common/main.tex\n\n\\section{Flavour tagging}\n\\label{sec:measurement_of_sin2beta:flavour_tagging}\n\nThe flavour tagging employed is described in detail in\n\\cref{ch:flavour_tagging}. Two different tagging decisions are utilised: the\n\\acf{OS} tagger combination and the \\acf{SSpi} tagger. The calibration and\nsubsequent combination of the two tagging decisions is performed within the fit\n(\\cf \\cref{sec:measurement_of_sin2beta:likelihood_fit}). To assure correct\npropagation of uncertainties and correlations of the calibration parameters to\nthe \\CP parameters Gaussian constraints based on the calibration parameters'\ncentral values and theirs statistical uncertainties are applied. The influence\nof the systematic uncertainties on the calibration parameters is described in\n\\cref{sec:measurement_of_sin2beta:systematics:systematics}.\n\n% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Performance}\n\\label{sec:measurement_of_sin2beta:flavour_tagging:performance}\n\nThe effective tagging efficiency\n(\\cref{eq:flavour_tagging:efftageff})---inherent in the used data sample given\nthe choice of utilised taggers---is calculated as the sum of the effective\ntagging efficiencies carried by each (including untagged) signal candidate\n%\n\\begin{equation}\n \\efftageff = \\frac{\\sum_{i=0}^{N} w_i \\tagdilution_i^2\\big(\\tagOS, \\tagSS, \\mistagOS, \\mistagSS \\big)}{\\sum_{i=0}^{N} w_i}\\eqcm\n\\end{equation}\n%\nwhere $\\mistagOS$ and $\\mistagSS$ refer to the calibrated mistag estimates. The\nsignal \\sWeights $w_i$ for each candidate are computed from an \\sPlot fit to the\n$\\Bd$ mass distribution using the nominal mass \\PDF described in\n\\cref{sec:measurement_of_sin2beta:likelihood_fit}. This adds up to an effective\ntagging efficiency of $\\efftageff = \\SI{3.02 +- 0.05}{\\percent}$, which splits\ninto a tagging efficiency of $\\tageff = \\SI{36.54\n+- 0.14}{\\percent}$ and an effective dilution of $\\tagdilution = \\SI{28.75 +-\n0.24}{\\percent}$ corresponding to an average mistag probability of $\\mistag =\n\\SI{35.62 +- 0.12}{\\percent}$.\n\n\\Cref{tab:flavour_tagging:performance:numbers} lists the tagging efficiency\nseparate for the \\catOS, \\catSS, and \\catBS parts of the dataset, as well as for\nthe case where all \\SSpi decisions are ignored and only the \\OS tagging\ninformation are exploited (\\enquote{all \\OS}) and vice versa (\\enquote{all\n\\SSpi}). This allows the performance obtained on the given dataset to be\ncompared with the results of the previous \\LHCb measurement \\cite{Aaij:1497268},\nwhere only the tagging information provided by the \\OS algorithms were used.\nHere, relative improvements of $\\SI{10}{\\percent}$ from $\\SI{2.38}{\\percent}$ to\n$\\SI{2.63}{\\percent}$ can be observed. Finally, supplementing the measurement\nwith information from the \\SSpi tagger allows for an overall improvement in\neffective tagging efficiency of almost $\\SI{27}{\\percent}$.\n%\n\\begin{table}\n \\centering\n \\caption{Effective tagging efficiency given for all three tagging categories.\n Additionally listed are the results just exploiting the information of the \\OS\n or \\SSpi tagging algorithms, as well as the total effective tagging efficiency\n of the dataset.}\n \\label{tab:flavour_tagging:performance:numbers}\n \\begin{tabular}{\n S[table-text-alignment = left]\n S\n [\n table-number-alignment = center,\n table-align-uncertainty = true,\n table-figures-decimal = 3,\n table-figures-uncertainty = 1,\n ]\n }\n \\toprule\n {Tagger} & {\\efftageff [$\\%$]}\\\\\n \\midrule\n {\\catOS} & 2.259 +- 0.034 \\\\\n {\\catSS} & 0.262 +- 0.017 \\\\\n {\\catBS} & 0.503 +- 0.010 \\\\\n \\midrule\n {all \\OS} & 2.63 +- 0.04 \\\\\n {all \\SSpi} & 0.376 +- 0.024 \\\\\n \\midrule\n {Total} & 3.02 +- 0.05 \\\\\n \\bottomrule\n \\end{tabular}\n\\end{table}\n% ", "meta": {"hexsha": "98579f00d23f639ac4f8c778ea83032849cdd446", "size": 3866, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "content/measurement-of-sin2beta/flavour-tagging.tex", "max_stars_repo_name": "ccauet/thesis", "max_stars_repo_head_hexsha": "96d26639af0c4aa4badc6a55be952edc72a5eebd", "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": "content/measurement-of-sin2beta/flavour-tagging.tex", "max_issues_repo_name": "ccauet/thesis", "max_issues_repo_head_hexsha": "96d26639af0c4aa4badc6a55be952edc72a5eebd", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2016-05-25T15:49:05.000Z", "max_issues_repo_issues_event_max_datetime": "2017-06-12T07:42:52.000Z", "max_forks_repo_path": "content/measurement-of-sin2beta/flavour-tagging.tex", "max_forks_repo_name": "ccauet/thesis", "max_forks_repo_head_hexsha": "96d26639af0c4aa4badc6a55be952edc72a5eebd", "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.578313253, "max_line_length": 129, "alphanum_fraction": 0.7128815313, "num_tokens": 1072, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621764862150634, "lm_q2_score": 0.3242353924510608, "lm_q1q2_score": 0.18227751363469946}}
{"text": "\\chapter{Implementation of Non-dyson ADC}\nIn this chapter I describe the implementation of second order Non-dyson ADC of restricted Electron Affinity calculation in development version of \\emph{adcman}.\n\\emph{Adcman} is a part of \\emph{Q-Chem} package, which is a general-purpose electronic structure package based on C++ and Fortran.\nIt contains a variety of established and new methods implemented using innovative algorithms that enable fast calculations of large systems.\nIt's features include:\n\\begin{itemize}\n\t\\item Variety of local, GGA, mGGA, hybrid, double-hybrid, dispersion-corrected, range separated functionals for DFT calculation.\n\t\\item TDDFT and spin-flip-TDDFT\n\t\\item Continuous Fast Multipole Method in HF and DFT\n\t\\item Linear-scaling HF-exchange method\n\t\\item Fourier transform Coulomb method\n\t\\item Fast numerical integration of exchange-correlation with multiresolution exchange-correlation (mrXC)\n\t\\item MP2\n\t\\item SCS and SOS MP2\n\t\\item CCD, QCISD, CCSD, OOCCD, VOOCCD\n\t\\item EOM-XX-CCSD methods for open-shell and electronically excited species\n\t\\item ADC methods\n\t\\item CIS, TDDFT, CIS(D), and SOS-CIS(D) methods for excited states\n\\end{itemize}\n\n\\begin{figure}[h]\n\t\\centering\n\t\\includegraphics[width=\\textwidth]{./figures/adcman.png}\n\t\\caption{Overview of implementation of ADC methods in \\emph{Q-Chem}}\n\t\\label{codestucture}\n\\end{figure}\n\nThen I will explain the overall code structure and then focus on my implementation part.\nFinally I will present the results calculated by my implementation and compare them with CCSD.\n\n\\section{Code Overview and Structure}\nThe overview of implementation of ADC methods is in Fig. \\ref{codestucture}.\nAll modules are written in the object-oriented C++ programming language. \nThe adcman module contains all top-level routines and methods necessary for an ADC calculation. \nIt coordinates the calculation process, sets up the solver and writes the results into an output file.\nI implemented restricted calculation of EA part in adcman.\n\nThe next sub-level contains electronic structure related libraries and utilities.\n\\emph{liblegacy} is the gateway between the ADC code and the Q-Chem interface.\nThese routines help to import data from other Q-Chem modules, for example all SCF results and MOs, which are needed for the ADC calculation.\nThe \\emph{libmo} module contains routines to set up the MO spaces, integrals and symmetry using the information imported from Q-Chem via the \\emph{liblegacy} interface.\nHence, both \\emph{libmo} and \\emph{liblegacy} are important for ADC calculations, because all integrals and Fock-matrix elements are indexed and created corresponding to the additional restriction of the core space.\nIn the \\emph{libadc} module, all ADC equations are implemented explicitly.\nI also implemented restricted calculation of EA part in \\emph{libadc}.\n\nFurthermore, \\emph{libmo} transforms the imported data in a format being compatible to the \\emph{libtensor} \\cite{libtensor} interface, which can be called the heart of the albegraic computation, since it contains all numerical routines to perform tensor algebra, which is the most time-consuming part all most of the quantum chemistry calculations.\n\\emph{libtensor} is specially designed for Post-Hartree-Fock electronic structure methods by including consideration of symmetries in the tensor structure.\nThese symmetries include Abelian point group symmetry, spin symmetry and other inner symmetry like that of two-electron integrals.\n\\begin{equation}\n\t\\langle i j\\| a b\\rangle=-\\langle j i\\| a b\\rangle=-\\langle i j \\| b a\\rangle=\\langle j i\\| b a\\rangle\n\\end{equation}\nThus, tensors of arbitrary order and size are stored in a blockwise manner to different kinds of symmetry to limit the amount of required memory and decrease the time needed.\nThe tensor operations in \\emph{libtensor} are fully parallelized and efficiently implemented.\n\nThe second important numerical library is \\emph{libsolve}, which contains all routines of\ngeneric solvers, e.g the Davidson algorithm, which are called from the top-level adcman\nroutines. \\emph{libsolve} is also based on the \\emph{libtensor} interface. At last, there are low-level\nroutines, which are responsible for support and operations in the background. The libvmm\nroutines manage the virtual memory, while \\emph{libctx} is a context manager based on key-value\nmapping of data objects. All imported or generated objects, e.g. integrals, keywords,\ntensors, vectors, etc., are stored in the context and can be easily accessed by other routines.\nThe libutil library contains further low-level machine-dependent routines.\n\nThe procedure of ADC calculation states as follows:\n\\begin{enumerate}\n\t\\item A HF calculation is performed, and all information including one-electron integrals, two-electron integrals, MOs, eigenvalues, Overlap matrix, Fock matrix and point group symmetry are imported through \\emph{libledacy} interface.\n\t\\item All tensors calculated in the previous step are transformed from atomic orbital (AO) basis to MO basis by \\emph{libmo} module.\n\t\\item MP2 calculation is performed and results are printed.\n\t\\item ADC secular matrix is constructed from the tensors in MO basis.\n\t\\item Guess vectors which are required by Davidson algorithm are set up with correct symmetry.\n\t\\item Davidson solver is started.\n\t\\item When convergence requirements are met, ADC energies and transition amplitudes are printed.\n\t\\item Other information required by adcman are printed.\n\\end{enumerate}\n\n\\section{Implementation of Non-dyson ADC}\n\n\\subsection{Implementation of ADC Secular Matrix}\n\nWe have illustrated the \\emph{libtensor} library which can efficiently and conveniently realize tensor algebra.\nFrom Eq \\ref{KCeigen}, our final purpose is to calculate the eigenvalues and eigenvectors of ADC secular matrix.\nHowever, usually we do not ask for all the eigenvalues and eigenvectors.\nInstead, people are only interested in the few states with lowest energies.\nThus, full diagonalization will waste much effort on eigenstates that we are not interested in.\nTo solve this problem, we can use Davidson algorithm, which can determine eigenstates one by one with lower algorithmic complexity.\nSince Davidson algorithm works by performing matrix vector product rather than direct access to matrix elements, we can rewrite the ADC secular matrix to matrix vector product form, i.e. calculate the result $W$ of matrix vector product when a vector $Y$ is given.\n\nBefore writing down the ADC secular matrix, we introduce some symbols:\n\\begin{equation}\n\t\\begin{aligned}\n\t\t\\langle pq \\| rs \\rangle&=V_{pq[rs]}\n\t\t\\\\\n\t\t\\mathrm{t}_{\\text { ijab }}&=\\frac{\\langle i j\\| a b\\rangle}{\\varepsilon_{a}+\\varepsilon_{\\mathrm{b}}-\\varepsilon_{i}-\\varepsilon_{j}}\n\t\\end{aligned}\n\\end{equation}\n\nUp to second order, ADC secular matrix of ionization potential calculation is\n\\begin{equation}\n\t\\mathrm{W}_{i}=\\sum_{j} \\mathrm{I}_{i j}^{(1)} \\mathrm{Y}_{j}-\\frac{1}{\\sqrt{2}} \\sum_{j k b}\\langle j k\\| b i\\rangle Y_{j k b}\n\\end{equation}\nfor 1h part, where\n\\begin{equation}\n\\mathrm{I}_{i j}^{(1)}=-f_{i j}+\\frac{1}{4}\\left(1+\\hat{\\mathrm{P}}_{i j}\\right) \\sum_{a b k} t_{i k a b}\\langle j k \\| a b\\rangle\n\\end{equation}\nand\n\\begin{equation}\n\t\\mathrm{W}_{i j a}=\\sum_{\\mathrm{b}} f_{a b} Y_{i j b}-\\left(1-\\hat{\\mathrm{P}}_{i j}\\right) \\sum_{k} f_{i k} \\mathrm{Y}_{k j a}+\\frac{1}{\\sqrt{2}} \\sum_{k}\\langle i j\\| k a\\rangle \\mathrm{Y}_{k}\n\\end{equation}\nfor 1p-2h part.\n\nUp to second order, ADC secular matrix of EA calculation is\n\\begin{equation}\n\t\\mathrm{W}_{a}=\\sum_{b} \\mathrm{I}_{a b}^{(1)} \\mathrm{Y}_{b}+\\frac{1}{\\sqrt{2}} \\sum_{b c j}\\langle b c\\| j a\\rangle Y_{b c j}\n\\end{equation}\nfor 1p part, where\n\\begin{equation}\n\\mathrm{I}_{a b}^{(1)}=-f_{a b}-\\frac{1}{4}\\left(1+\\hat{\\mathrm{P}}_{a b}\\right) \\sum_{i j c} t_{i j a c}\\langle b c \\| i j\\rangle\n\\end{equation}\nand\n\\begin{equation}\n\t\\mathrm{W}_{a b i}=\\sum_{\\mathrm{b}} f_{i j} Y_{a b j}-\\left(1-\\hat{\\mathrm{P}}_{a b}\\right) \\sum_{c} f_{a c} \\mathrm{Y}_{c b i}-\\frac{1}{\\sqrt{2}} \\sum_{c}\\langle a b\\| c i\\rangle \\mathrm{Y}_{c}\n\\end{equation}\nfor 1h-2p part.\n\nThe implementation of ADC secular matrix is by a class \\emph{adc2\\_matrix}:\n\n\\lstinputlisting[language=C++]{./code/adc2matrix.h}\n\n\\subsection{Implementation of Setting up Guess Vectors}\n\nBefore the Davidson algorithm starts, guess vectors need to be set up for the first matrix vector product.\nUsually, the setting up of guess vectors should be subjected to some principles: computationally cheap and close to the final eigenvectors.\nA simple idea is to use eigenvectors of some simple approximation of the ADC secular matrix.\nIn the implementation in Q-Chem, the approximation of second order ADC secular matrix is chosen to be the diagonal elements.\nSince people usually care about the states with lowest enegies, the guess vectors should be chosen to be those with smallest diagonal elements.\nMathmatically, if $d_a=K_{aa}+C_{aa}$, and the $n$ smallest elements are $d_{k_1} 25$ GeV and $|\\eta| < 2.4$.\nIn addition, the jets are cleaned such that they are not overlapping with leptons.\nThe truth matching enforces the following additional requirements:\n\\begin{itemize}\n \\item $|m_{jjj} - m_t| < 80$ GeV\n \\item All three reco jets are matched to generator-level quarks from a hadronically decaying top ($\\Delta R(\\text{jet, quark}) < 0.4$).\n\\end{itemize}\nThe training features are shown in Table \\ref{tab:tth_top_tagger_features}.\n\\begin{table}\n\t\\centering\n \\caption{Input features used in training the Top Tagger BDT.}\n\t\\begin{tabular}{c |c c c c} \\hline \\hline\n\t\tCategory & \\multicolumn{4}{c}{Features} \\\\ \\hline\n\t\t\\multirow{3}{*}{Single Jet Quantities} & $p_T$ & mass & & \\\\\n\t\t& DeepCSV b & DeepCSV c vs. light & DeepCSV c vs. b & \\\\\n\t\t& ptD & axis1 & multiplicity & \\\\ \\hline\n\t\t\\multirow{1}{*}{Di-Jet Quantities} & $\\Delta R(\\text{j,j})$ & $m_{\\text{jj}}$ & & \\\\\n\t\t\\multirow{1}{*}{Tri-Jet Quantities} & $\\Delta R(\\text{b,W})$ & $m_{\\text{jjj}}$ & & \\\\ \\hline \\hline\n\t\\end{tabular}\n %\\caption{Input features used in training the Top Tagger BDT.}\n \\label{tab:tth_top_tagger_features}\n\\end{table}\nThe training features are defined as follows:\n\\begin{itemize}\n \\item DeepCSV scores: for each jet, three DeepCSV quantities are provided: the b-tag score, and the c-tag score, given in terms of c vs. light and c vs. b.\n \\item ptD, axis1, multiplicity: standard quark-gluon discrimination variables. The fragmentation function is defined as $\\text{ptD} \\equiv \\frac{\\sqrt{\\sum p_{\\text{T}_i}^2}}{\\sum p_{\\text{T}_i}}$, axis1 is the jet shape variable describing the jet's long axis, and multiplicity provides the number of constituents in the jet.\n\\end{itemize}\nThe jet in the triplet with the highest DeepCSV b score is labeled as the b-jet, while the other two jets are labeled as $\\PW$-jet 1 and 2, with $\\pT(\\PW_{j1}) > \\pT(\\PW_{j2})$.\n\nThe ouput of the top tagger BDT is shown for both data and simulation in Fig.~\\ref{fig:tth_top_tagger_datamc}.\n\\begin{figure} [htbp!]\n \\centering\n \\includegraphics[width=0.48\\linewidth,page=48]{{figures/tth/ttHHadronic_RunII_MVA_Presel_v4.11_9Jun2020_impute_histogramsRunIIstd}.pdf}\n \\caption{Agreement between data and MC description of background for the top tagger BDT score.}\n \\label{fig:tth_top_tagger_datamc}\n\\end{figure}\nSimilar to the DNN scores, the top tagger BDT is given as an additional training feature to BDT-bkg.\nThe improvement in expected sensitivity gained by adding the top tagger to BDT-bkg is shown in Fig.~\\ref{fig:tth_top_tagger_za} and is about 5\\%.\n\\begin{figure} [htbp!]\n \\centering\n \\includegraphics[width=0.7\\linewidth]{{figures/tth/za_comparison_data_Hadronic_TopTagger_2May2020}.pdf}\n \\caption[Expected significance ($Z_A$) shown as a function of the number of \\ttH events passing a given cut on BDT-bkg for versions of BDT-bkg trained with (red) and without (black) the top tagger BDT scores as a training feature.]{Expected significance ($Z_A$) shown as a function of the number of \\ttH events passing a given cut on BDT-bkg for versions of BDT-bkg trained with (red) and without (black) the top tagger BDT as a training feature. Shaded bands show the $\\pm 1\\sigma$ statistical uncertainty in $Z_A$. The background yield is estimated from events in data in the \\mgg sidebands.}\n \\label{fig:tth_top_tagger_za}\n\\end{figure}\n\n\\subsection{BDT-bkg}\nThe final BDT-bkg algorithms for each channel use the high-level features listed in Table~\\ref{tab:tth_hlf}, the DNN scores described in Sec.~\\ref{sec:tth_dnns}, and the top tagger BDT score described in Sec.~\\ref{sec:tth_top_tagger_bdt} as the training features.\nThe outputs of the BDT-bkg algorithms are shown in Fig.~\\ref{fig:tth_bdt-bkg}, where agreement between data and simulation is observed within statistical and systematic uncertainties.\n\\begin{figure} [htbp!]\n \\centering\n \\begin{tabular}{c c}\n \\includegraphics[width=0.48\\linewidth]{figures/tth/Figure_001-a.pdf} &\n \\includegraphics[width=0.48\\linewidth]{figures/tth/Figure_001-b.pdf}\n \\end{tabular}\n \\caption[Output of the BDT-bkg algorithm for the hadronic channel (left) and the leptonic channel (right). Taken from~\\cite{tth_observation}.]{Output of the BDT-bkg algorithm for the hadronic channel (left) and the leptonic channel (right). Events from the \\mgg sidebands are shown for both data and simulation. The statistical (statistical $\\oplus$ systematic) uncertainties in simulation are shown with black (red) shaded bands. The thinly dashed lines show the boundaries of each signal region used for the cross section measurement, while the thickly dashed lines show the boundaries of signal regions used for a measurement of the CP structure. Events in the gray shaded region are discarded. Taken from~\\cite{tth_observation}.}\n \\label{fig:tth_bdt-bkg}\n\\end{figure}\n\n\\subsubsection{Validation in \\ttZ Events}\nAs an additional check of the agreement between data and simulation in the output of the BDT-bkg algorithms, a validation in a control region targeting \\ttZ (\\Zee) events is performed.\nThe rationale for using \\ttZ events is the following: \\ttZ and \\ttH should have very similar kinematic distributions for most components.\nTherefore, BDT-bkg should similarly assign high scores to \\ttZ events as it does for \\ttH events and a region of high \\ttZ purity should be present at high scores.\nBecause the cross section times branching fraction of \\ttZ (\\Zee) is much higher than that of \\ttH (\\Hgg), this control region provides a test of the agreement between data and simulation for high scores of BDT-bkg with much smaller statistical uncertainty than obtained in the \\mgg sidebands.\nLastly, it is important to emphasize that this check is qualitative in nature; no formal estimate of the compatibility between the distributions in data and simulation is performed.\n\nThe selection for the \\ttZ control region is the same as the preselection, with the exception that the cut on the conversion-safe electron veto is inverted to select for \\Zee events.\nThe reconstructed ``diphoton pairs'' in these events are then primarily composed of electrons that were reconstructed as photons.\n\nAdditional cuts are next applied on top of the preselection in order to increase the \\ttZ purity:\n\\begin{itemize}\n \\item $|m_{\\text{Z}} - m_{\\gamma \\gamma}| < 10$ GeV\n \\item $N_{\\text{jets}} \\geq 5 (3)$ for hadronic (leptonic)\n \\item $N_{\\text{b-jets}} \\geq 2$, using the tight (medium) working point for hadronic (leptonic)\n\\end{itemize}\n\nOne subtlety in validating the BDT-bkg performance in \\ttZ events is the fact that BDT-bkg is specifically trained to reject events in which electrons are reconstructed as photons through use of the pixel seed veto (defined in Sec.~\\ref{sec:evt_photon_vardef}).\nThis challenge is addressed by manually changing the value of the pixel seed veto for these events before evaluating their score with the BDT-bkg algorithm: although most of these events fail the pixel seed veto, BDT-bkg is told that they all pass the pixel seed veto.\nThis hard-coding of the pixel seed veto ensures that \\ttZ events are not assigned lower scores due to the fact that the typical diphoton pair in these events is suspiciously electron-like.\n\nComparisons of BDT-bkg between data and simulation are shown for events entering the \\ttZ control regions in Fig.~\\ref{fig:tth_bdt-bkg_ttz}.\n\n\\begin{figure} [htbp!]\n \\centering\n \\begin{tabular}{c c}\n \\includegraphics[width=0.48\\linewidth]{figures/tth/ttHHadronic_MVA_ttZ_12Jun2020.pdf}\n \\includegraphics[width=0.48\\linewidth]{figures/tth/ttHLeptonic_MVA_ttZ_12Jun2020.pdf}\n \\end{tabular}\n \\caption{Output of the BDT-bkg algorithm for the hadronic channel (left) and the leptonic channel (right) in the \\ttZ control region. The statistical (statistical $\\oplus$ systematic) uncertainties in simulation are shown with black (red) shaded bands. Events in the gray shaded region are discarded. Taken from ~\\cite{tth_observation}.} \n \\label{fig:tth_bdt-bkg_ttz}\n\\end{figure}\n\nThe purity of \\ttZ events is much higher in the leptonic channel, where good agreement between data and simulation is observed at high BDT-bkg scores.\nGood agreement is also observed in the hadronic channel of the \\ttZ control region, though the purity of \\ttZ events is lower.\nDisagreement is present at lower values of BDT-bkg; however, these events do not enter the analysis selection.\n", "meta": {"hexsha": "1f2f95cc9a59f46bd1122a1fdcf226434e00d36f", "size": 28900, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "tth_analysis/mvas.tex", "max_stars_repo_name": "sam-may/phd_thesis", "max_stars_repo_head_hexsha": "acd61f340e5677deba412b1b3baecd124c32440f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tth_analysis/mvas.tex", "max_issues_repo_name": "sam-may/phd_thesis", "max_issues_repo_head_hexsha": "acd61f340e5677deba412b1b3baecd124c32440f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tth_analysis/mvas.tex", "max_forks_repo_name": "sam-may/phd_thesis", "max_forks_repo_head_hexsha": "acd61f340e5677deba412b1b3baecd124c32440f", "max_forks_repo_licenses": ["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.5956112853, "max_line_length": 737, "alphanum_fraction": 0.7559861592, "num_tokens": 7686, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.3073580105206753, "lm_q1q2_score": 0.18216082706393583}}
{"text": "\n\\documentclass[a4paper]{article}\n\\usepackage[hmargin=2cm,vmargin=2cm]{geometry}\n\n\n\\pagestyle{plain}\n\n\\usepackage{amssymb,amsthm,amsfonts,longtable, comment,array, ifpdf, hyperref,cite,url}\n\\usepackage{graphicx}\n\\newtheorem{theorem}{Theorem}\n\\newtheorem{lemma}{Lemma}\n\\newcommand{\\Tag}{\\mathrm{Tag}}\n\n\n% *** MATH PACKAGES ***\n%\n\\usepackage[cmex10]{amsmath}\n\n\n\n\n% *** SPECIALIZED LIST PACKAGES ***\n%\n\\usepackage{algorithmic}\n\n\n\n\n\n\\begin{document}\n\n%FINISHED\n\n\\title{\\textsf{Argon2: the memory-hard function for password hashing and other applications}}\n\n\\author{Designers: Alex Biryukov, Daniel Dinu, and Dmitry Khovratovich\\\\University of Luxembourg, Luxembourg\n\\\\[10pt]\n%Submitters: Alex Biryukov and Dmitry Khovratovich\n%\\\\\n{\\tt alex.biryukov@uni.lu, dumitru-daniel.dinu@uni.lu, khovratovich@gmail.com}\\\\[10 pt]\n\\url{https://www.cryptolux.org/index.php/Argon2}\\\\\n\\url{https://github.com/khovratovich/Argon2}\\\\[10pt]\nVersion 1.2.1 of Argon2}\n\n\\maketitle\n\n\\section{Introduction}\n\nPasswords, despite all their drawbacks, remain the primary form of authentication on various web-services. Passwords are usually stored in a hashed form in a server's database. These databases are quite often captured by the adversaries, who then apply dictionary attacks since passwords tend to have low entropy. Protocol designers use a number of tricks to mitigate these issues. Starting from the late 70's, a password is hashed together with a random \\emph{salt} value to prevent detection of identical passwords across different users and services. The hash function computations, which became faster and faster due to Moore's law have been called multiple times to increase the cost of password trial for the attacker.\n\n In the meanwhile, the password crackers migrated to new architectures, such as FPGAs, multiple-core GPUs and dedicated ASIC modules, where the amortized cost of a multiple-iterated hash function is much lower. It was quickly noted that these new environments are great when the computation is almost memoryless, but they experience difficulties when operating on a large amount of memory. The defenders responded by designing \\emph{memory-hard} functions, which require a large amount of memory to be computed, and impose computational penalties if less memory is used. The password hashing scheme \\textsf{scrypt}~\\cite{percival2009stronger} is an instance of such function.\n\nMemory-hard schemes also have other applications. They can be used for key derivation from low-entropy sources. Memory-hard schemes are also welcome in cryptocurrency designs~\\cite{litecoin} if a creator wants to demotivate the use of GPUs and ASICs for mining and promote the use of standard desktops.\n\n\\paragraph{Problems of existing schemes} A trivial solution for password hashing is a keyed hash function such as HMAC. If the protocol designer prefers hashing without secret keys to avoid all the problems with key generation, storage, and update, then he has few alternatives: the generic mode PBKDF2, the Blowfish-based \\textsf{bcrypt}, and \\textsf{scrypt}. Among those, only \n\\textsf{scrypt} aims for high memory, but the existence of a trivial time-memory tradeoff~\\cite{ForlerLW14} allows compact implementations with the same energy cost.\n\nDesign of a memory-hard function proved to be a tough problem. Since early 80's it has been known that many cryptographic problems that seemingly require large memory actually allow for a time-memory tradeoff~\\cite{hellman1980cryptanalytic}, where the adversary can trade memory for time and do his job on fast hardware with low memory. In application\nto password-hashing schemes, this means that the password crackers can still be implemented on a dedicated hardware even though at some additional cost. \n\nAnother problem with the existing schemes is their complexity. The same \\textsf{scrypt} calls a stack of subprocedures, whose design rationale has not been fully motivated (e.g, \\textsf{scrypt} calls SMix, which calls ROMix, which calls BlockMix, which calls Salsa20/8 etc.). It is hard to analyze and, moreover, hard to achieve confidence. Finally, it is not flexible in separating time and memory costs. \nAt the same time, the story of cryptographic competitions~\\cite{robshaw2008new,sha3} has demonstrated that\nthe most secure designs come with simplicity, where every element is well motivated and a cryptanalyst has as few entry points as possible.\n\nThe Password Hashing Competition, which started in 2014, highlighted the following problems:\n\\begin{itemize}\n \\item Should the memory addressing (indexing functions) be input-independent or input-dependent, or hybrid? The first type of schemes, where the memory read location are known in advance, is immediately vulnerable to time-space tradeoff attacks,\n since an adversary can precompute the missing block by the time it is needed~\\cite{trade-att}. In turn, the input-dependent schemes are vulnerable to side-channel attacks~\\cite{RistenpartTSS09}, as the timing information allows for much faster password search.\n \\item Is it better to fill more memory but suffer from time-space tradeoffs, or make more passes over the memory to be more robust? This question was quite difficult to answer due to absence of generic tradeoff tools, which would analyze the security against tradeoff attacks, and the absence of unified metric to measure adversary's costs.\n \\item How should the input-independent addresses be computed? Several seemingly secure options have been attacked~\\cite{trade-att}.\n \\item How large a single memory block should be? Reading smaller random-placed blocks is slower (in cycles per byte) due to the spacial locality principle of the CPU cache. In turn, larger\n blocks are difficult to process due to the limited number of long registers.\n \\item If the block is large, how to choose the internal compression function? Should it be cryptographically secure or more lightweight, providing only basic mixing of the inputs? Many candidates simply proposed an iterative construction and argued against cryptographically strong transformations.\n\n \\item How to exploit multiple cores of modern CPUs, when they are available? Parallelizing calls to the hashing function without any interaction is subject to simple tradeoff attacks.\n\\end{itemize}\n\n\\paragraph{Our solution} We offer a hashing scheme called \\textsf{Argon2}.\n \\textsf{Argon2} summarizes the state of the art in the design of memory-hard functions. It is a streamlined and simple design. It aims at the highest memory filling rate and effective use of multiple computing units, while still\nproviding defense against tradeoff attacks. \\textsf{Argon2} is optimized for the x86 architecture and exploits the cache and memory organization of the recent Intel and AMD processors. \\textsf{Argon2} has two variants: \\textsf{Argon2d} and \\textsf{Argon2i}. \\textsf{Argon2d} is faster and uses data-depending memory access, which makes it suitable for cryptocurrencies and applications with no threats from side-channel timing attacks. \\textsf{Argon2i} uses data-independent memory access, which is preferred for password hashing and password-based key derivation. \\textsf{Argon2i} is slower as it makes more passes over the memory to protect from tradeoff attacks.\n\n\nWe recommend \\textsf{Argon2} for the applications that aim for high performance. Both versions of \\textsf{Argon2} allow to fill 1 GB of RAM in a fraction of second, and smaller amounts even faster. It scales easily to the arbitrary number of parallel computing units. Its design is also optimized for clarity to ease analysis and implementation.\n\nOur scheme provides more features and better tradeoff resilience than pre-PHC designs and equals in performance with the PHC finalists~\\cite{broz15}. \n\n\\section{Definitions}\n\n\\subsection{Motivation}\\label{sec:costs}\nWe aim to maximize the cost of password cracking on ASICs. There can be different approaches to measure this cost, but we turn to one of the most popular -- the time-area product~\\cite{Thompson79,BernsteinL13}. We assume that the password $P$ is hashed with salt $S$ but without secret keys, and the hashes may leak to the adversaries together with salts:\n$$\n\\begin{aligned}\n\\mathrm{Tag} &\\leftarrow \\mathcal{H}(P,S);\\\\\n\\mathrm{Cracker} &\\leftarrow \\{(\\mathrm{Tag}_i, S_i)\\}.\n\\end{aligned}\n$$\n\nIn the case of the password hashing, we suppose that the defender allocates certain amount of time (e.g., 1 second) per password and a certain number of CPU cores (e.g., 4 cores). Then he hashes the password using the maximum amount $M$ of memory. This memory size translates to certain ASIC area $A$. The running ASIC time $T$ is determined by the length of the longest computational chain and by the ASIC memory latency.\nTherefore, we maximize the value $AT$. The other usecases follow a similar procedure. \n\nSuppose that an ASIC designer that wants to reduce the memory and thus the area wants to compute $\\mathcal{H}$ using $\\alpha M$ memory only for some $\\alpha<1$. Using some tradeoff specific to $\\mathcal{H}$, he has to spend $C(\\alpha)$ times as much computation and his running time increases by at least the factor $D(\\alpha)$. Therefore, the maximum possible gain $\\mathcal{E}$ in the time-area product is \n$$\n\\mathcal{E}_{max}= \\max_{\\alpha}\\frac{1}{\\alpha D(\\alpha)}.\n$$\nThe hash function is called \\emph{memory-hard} if $D(\\alpha) >1/\\alpha$ as $\\alpha\\rightarrow 0$. Clearly, in this case the time-area product does not decrease. Moreover, the following aspects may further increase it:\n\\begin{itemize}\n\\item Computing cores needed to implement the $C(\\alpha)$ penalty may occupy significant area.\n\\item If the tradeoff requires significant communication between the computing cores, the memory bandwidth limits may impose additional restrictions on the running time.\n\\end{itemize}\n\nIn the following text, we will not attempt to estimate time and area with large precision. However, an interested reader may use the following implementations as reference:\n \\begin{itemize}\n \\item The 50-nm DRAM implementation~\\cite{giridhar2013dram} takes 550 mm${}^2$ per GByte;\n \\item The Blake2b implementation in the 65-nm process should take about 0.1 mm${}^2$ (using Blake-512 implementation in~\\cite{gurkaynak2012sha3});\n \\item The maximum memory bandwidth achieved by modern GPUs is around 400 GB/sec.\n \\end{itemize}\n \n \\subsection{Model for memory-hard functions}\n \n The memory-hard functions that we explore use the following mode of operation. The memory array $B[]$ is filled with the compression function $G$:\n\n \\begin{equation}\\label{eq:class}\n\\begin{array}{rl}\nB[0] &= H(P,S);\\\\\n\\text{for $j$ }&\\text{from 1 to } t\\\\\n &B[j] = G \\bigl(B[\\phi_1(j)] , B[\\phi_2(j)] ,\\cdots , B[\\phi_k(j)]\\bigr),\n\\end{array}\n\\end{equation}\nwhere $\\phi_i()$ are some \\emph{indexing functions}.\n\n\nWe distinguish two types of indexing functions:\n\\begin{itemize}\n \\item Independent of the password and salt, but possibly dependent on other public parameters (\\emph{data-independent}). Thus the addresses can be calculated by the adversaries. We suppose that the dedicated hardware can handle parallel memory access, so that the cracker can prefetch the data from the memory. Moreover, if she implements a time-space tradeoff, then the missing blocks can be also precomputed without losing time. Let the single $G$ core occupy the area equivalent to the $\\beta$ of the entire memory. Then if we use $\\alpha M$ memory, then the gain in the time-area product is\n $$\n \\mathcal{E}(\\alpha) = \\frac{1}{\\alpha + C(\\alpha)\\beta}.\n $$\n \\item Dependent on the password (\\emph{data-dependent}), in our case: $\\phi(j) = g(B[j-1])$. This choice prevents the adversary from prefetching and precomputing missing data. The adversary figures out what he has to recompute only at the time the element is needed. If an element is recomputed as a tree of $F$ calls of average depth $D$, then the total processing time is multiplied by $D$. The gain in the time-area product is\n $$\n \\mathcal{E}(\\alpha) = \\frac{1}{(\\alpha + C(\\alpha)\\beta)D(\\alpha)}.\n $$\n\\end{itemize}\n\n\n The maximum bandwidth $Bw_{max}$ is a hypothetical upper bound on the memory bandwidth on the adversary's architecture. Suppose that for each call to $G$ an adversary has to load\n $R(\\alpha)$ blocks from the memory on average. Therefore, the adversary can keep the execution time the same as long as\n $$\n R(alpha) Bw \\leq Bw_{max},\n $$\n where $Bw$ is the bandwidth achieved by a full-space implementation. In the tradeoff attacks that we apply the following holds:\n $$\n R(alpha) = C(alpha).\n $$\n\n\n\n\\section{Specification of Argon2}\n\nThere are two flavors of \\textsf{Argon2}\\ -- \\textsf{Argon2d} and \\textsf{Argon2i}. The former one uses data-dependent memory access to thwart tradeoff attacks. However, this makes it vulnerable for side-channel attacks, so \\textsf{Argon2d} is recommended primarily for cryptocurrencies and backend servers. \\textsf{Argon2i} uses data-independent memory access, which is recommended for password hashing and password-based key derivation.\n\n\\subsection{Inputs}\n\n\\textsf{Argon2}\\ has two types of inputs: primary inputs and secondary inputs, or parameters. Primary inputs are message $P$ and nonce $S$, which are password and salt, respectively, for the password hashing. Primary inputs must always be given by the user such that\n\\begin{itemize}\n \\item Message $P$ may have any length from $0$ to $2^{32}-1$ bytes;\n \\item Nonce $S$ may have any length from $8$ to $2^{32}-1$ bytes (16 bytes is recommended for password hashing).\n\\end{itemize}\n Secondary inputs have the following restrictions:\n\\begin{itemize}\n \\item Degree of parallelism $p$ determines how many independent (but synchronizing) computational chains can be run. It may take any integer value from 1 to 255.\n \\item Tag length $\\tau$ may be any integer number of bytes from 4 to $2^{32}-1$.\n \\item Memory size $m$ can be any integer number of kilobytes from $8p$ to $2^{32}-1$. The actual number of blocks is $m'$, which is $m$ rounded down to the nearest multiple of $4p$. \n \\item Number of iterations $t$ (used to tune the running time independently of the memory size) can be any integer number from 1 to $2^{32}-1$;\n \\item Version number $v$ is one byte $0x10$;\n \\item Secret value $K$ (serves as key if necessary, but we do not assume any key use by default) may have any length from $0$ to $32$ bytes.\n \\item Associated data $X$ may have any length from $0$ to $2^{32}-1$ bytes.\n \\item Type $y$ of \\textsf{Argon2}: 0 for \\textsf{Argon2d}, 1 for \\textsf{Argon2i}.\n\\end{itemize}\n\n\\textsf{Argon2}\\ uses internal compression function ${G}$ with two 1024-byte inputs and a 1024-byte output, and internal hash function ${H}$. Here ${H}$ is the Blake2b hash function, and ${G}$ is based on its internal permutation. The mode of operation of \\textsf{Argon2} is quite simple when no parallelism is used: function ${G}$ is iterated $m$ times. At step $i$ a block with index $\\phi(i)1$, we repeat the procedure; however the first two blocks of a lane are now computed in the same way:\n\\begin{align*}\nB[i][0] &=G(B[i][q-1], B[i'][j']);\\\\\nB[i][j] &= G(B[i][j-1], B[i'][j']).\n\\end{align*}\n\nWhen we have done $t$ iterations over the memory, we compute the final block $B_m$ as the XOR of the last column:\n$$\nB_m = B[0][q-1] \\oplus B[1][q-1]\\oplus \\cdots\\oplus B[d-1][q-1].\n$$\nThen we apply $H'$ to $B_m$ to get the output tag.\n\n\\paragraph{Variable-length hash function.} Let $H_x$ be a hash function with $x$-byte output (in our case $H_x$ is Blake2b, which supports $1\\leq x \\leq 64$). We define $H'$ as follows. Let $V_i$ be a 64-byte block, and $A_i$ be its first 32 bytes,\nand $\\tau<2^{32}$ be the tag length in bytes. \nThen we define\n\\begin{align*}\nH'(X):\\quad V_0 &\\leftarrow\\tau||X;\\\\\nV_1 &\\leftarrow H_{64}(V_0);\\\\\nV_2 &\\leftarrow H_{64}(V_1);\\\\\n&\\cdots\\\\\nV_m & \\leftarrow H_{64}(V_{m-1}),\\quad m = \\lfloor\\tau/32\\rfloor-1;\\\\\nV_{m+1} &\\leftarrow H_{\\tau\\hspace{-10pt} \\pmod{64}}(V_{m-1})\\quad \\text{(absent if 64 divides }\\tau).\\\\\n\\text{Tag} & \\leftarrow A_1||A_2||\\ldots A_m||V_{m+1}.\n\\end{align*}\n\n \\begin{figure}[ht]\n \\ifpdf\n\\begin{center}\n \\includegraphics[scale=0.3]{pics/argon2-par.pdf}\n \\caption{Single-pass \\textsf{Argon2} with $p$ lanes and 4 slices. }\\label{fig:argon2}\n\\end{center}\n\\fi\n \\end{figure}\n\n\\subsection{Indexing}\\label{sec:index}\n\nTo enable parallel block computation, we further partition the memory matrix into $S=4$ vertical \\emph{slices}. Intersection of a slice and a lane is \\emph{segment} of length $q/S$. Segments of the same slice\n are computed in parallel, and may not reference blocks from each other. All other blocks can be referenced, and now we explain the procedure in details.\n\n\\paragraph{Getting two 32-bit values.} In Argon2d we select the first 32 bits of block $B[i][j-1]$ and denote this value by $J_1$. Then we take the next 32 bits of $B[i][j-1]$ and denote this value by $J_2$. In \\textsf{Argon2i} we run $G^2$ --- the 2-round compression function $G$ -- in the counter mode, where the first input is all-zero block, and the second input is constructed as \n $$\n (\\underbrace{r}_{\\text{8 bytes}}||\\underbrace{l}_{\\text{8 bytes}}||\\underbrace{s}_{\\text{8 bytes}}||\\underbrace{m'}_{\\text{8 bytes}}||\\underbrace{t}_{\\text{8 bytes}}||\\underbrace{x}_{\\text{8 bytes}}||\\underbrace{i}_{\\text{8 bytes}}||\\underbrace{0}_{\\text{968 bytes}}),\n $$ where\n \\begin{itemize}\n \\item $r$ is the pass number;\n \\item $l$ is the lane number;\n \\item $s$ is the slice number;\n \\item $m'$ is the total number of memory blocks;\n \\item $t$ is the total number of passes;\n \\item $x$ is the type of the Argon function (equals $1$ for \\textsf{Argon2i});\n \\item $i$ is the counter starting in each segment from 1.\n \\end{itemize} All the numbers are put as little-endian. We increase the counter so that each application of $G^2$ gives 128 64-bit values $J_1||J_2$.\n \n \\paragraph{Mapping $J_1,J_2$ to the reference block index} The value $l = J_2 \\bmod p$ determines the index of the lane from which the block will be taken. If we work with the first slice and the first pass ($r=s=0$), then $l$ is set to the current lane index. \n \n Then we determine the set of indices $\\mathcal{R}$ that can be referenced for given $[i][j]$ according to the following rules:\n\\begin{enumerate}\n \\item If $l$ is the current lane, then $\\mathcal{R}$ includes all blocks computed in this lane, which are not overwritten yet, excluding $B[i][j-1]$.\n \\item If $l$ is not the current lane, then $\\mathcal{R}$ includes all blocks in the last $S-1=3$ segments computed and finished in lane $l$. If $B[i][j]$ is the first block of a segment, then the very last block from $\\mathcal{R}$ is excluded.\n\\end{enumerate}\n We are going to take a block from $\\mathcal{R}$ with a non-uniform distribution over $[0..|\\mathcal{R}|)$:\n $$\n J_1\\in [0..2^{32}) \\rightarrow |\\mathcal{R}|(1-\\frac{(J_1)^2}{2^{64}}).\n $$ To avoid floating-point computation, we use the following integer approximation:\n\\begin{align*}\nx &= (J_1)^2/2^{32};\\\\\ny &= (|\\mathcal{R}|*x)/2^{32};\\\\\nz & = |\\mathcal{R}|-1-y.\n\\end{align*}\nThen we enumerate the blocks in $\\mathcal{R}$ in the order of construction and select $z$-th block from it as the reference block.\n\n\n\n\\subsection{Compression function $G$}\\label{sec:compr}\n\nCompression function $G$ is built upon the Blake2b round function $\\mathcal{P}$ (fully defined in Section~\\ref{sec:blakeround}). $\\mathcal{P}$ operates on the 128-byte input, which can be viewed as 8 16-byte registers (see details below):\n$$\n\\mathcal{P}(A_0,A_1,\\ldots, A_7) = (B_0,B_1,\\ldots, B_7).\n$$\n\nCompression function ${G}(X,Y)$ operates on two 1024-byte blocks $X$ and $Y$. It first computes $R=X\\oplus Y$. Then $R$ is viewed as a $8\\times 8$-matrix of 16-byte registers $R_0, R_1,\\ldots, R_{63}.$ Then\n$\\mathcal{P}$ is first applied rowwise, and then columnwise to get $Z$:\n\\begin{align*}\n (Q_0,Q_1,\\ldots,Q_7) &\\leftarrow \\mathcal{P}(R_0,R_1,\\ldots,R_7);\\\\\n (Q_8,Q_9,\\ldots,Q_{15})&\\leftarrow \\mathcal{P}(R_8,R_9,\\ldots,R_{15});\\\\\n \\ldots&\\\\\n (Q_{56},Q_{57},\\ldots,Q_{63})&\\leftarrow \\mathcal{P}(R_{56},R_{57},\\ldots,R_{63});\\\\[10pt]\n (Z_0,Z_8,Z_{16},\\ldots,Z_{56})&\\leftarrow \\mathcal{P}(Q_0,Q_8,Q_{16},\\ldots,Q_{56});\\\\\n (Z_1,Z_9,Z_{17},\\ldots,Z_{57})&\\leftarrow \\mathcal{P}(Q_1,Q_9,Q_{17},\\ldots,Q_{57});\\\\\n \\ldots&\\\\\n (Z_7,Z_{15},Z_{23},\\ldots,Z_{63})&\\leftarrow \\mathcal{P}(Q_7,Q_{15},Q_{23},\\ldots,Q_{63}).\n \\end{align*}\n Finally, $G$ outputs $Z\\oplus R$:\n $$\n G:\\quad (X,Y)\\; \\rightarrow\\; R = X\\oplus Y\\; \\xrightarrow{\\mathcal{P}}\\;Q\\;\\xrightarrow{\\mathcal{P}}\\;Z\\;\n \\rightarrow \\;Z\\oplus R.\n $$\n \n \\begin{figure}[ht]\n \\ifpdf\n\\begin{center}\n \\includegraphics[scale=0.6]{pics/compression.pdf}\n \\caption{Argon2 compression function $G$. }\\label{fig:compression}\n\\end{center}\n\\fi\n \\end{figure}\n \n \\section{Features}\n\n\\textsf{Argon2} is a multi-purpose family of hashing schemes, which is suitable for password hashing, key derivation, cryptocurrencies and other applications that require provably high memory use. \\textsf{Argon2} is optimized for the x86 architecture, but it does not slow much on older processors. The key feature of \\textsf{Argon2} is its performance and the ability to use multiple computational cores in a way that prohibit time-memory tradeoffs. Several features are not included into this version, but can be easily added later.\n\n\\subsection{Available features}\nNow we provide an extensive list of features of Argon2.\n\n\\textbf{Performance}. \\textsf{Argon2} fills memory very fast, thus increasing the area multiplier in the time-area product for ASIC-equipped adversaries. Data-independent version \\textsf{Argon2i} securely fills the memory spending about 2 CPU cycles per byte, and \\textsf{Argon2d} is three times as fast. This makes it suitable for applications that need memory-hardness but can not allow much CPU time, like cryptocurrency peer software.\n\n\\textbf{Tradeoff resilience}. Despite high performance, \\textsf{Argon2} provides reasonable level of tradeoff resilience. Our tradeoff attacks previously applied to Catena and Lyra2 show the following. With default number of passes over memory (1 for \\textsf{Argon2d}, 3 for \\textsf{Argon2i}, an ASIC-equipped adversary can not decrease the time-area product if the memory is reduced by the factor of 4 or more. Much higher penalties apply if more passes over the memory are made. \n\n\\textbf{Scalability}. \\textsf{Argon2} is scalable both in time and memory dimensions. Both parameters can be changed independently provided that a certain amount of time is always needed to fill the memory. \n\n\\textbf{Parallelism}. \\textsf{Argon2} may use up to 64 threads in parallel, although in our experiments 8 threads already exhaust the available bandwidth and computing power of the machine.\n\n\\textbf{GPU/FPGA/ASIC-unfriendly}. \\textsf{Argon2} is heavily optimized for the x86 architecture, so that implementing it on dedicated cracking hardware should be neither cheaper nor faster. Even specialized ASICs would require significant area and would not allow reduction in the time-area product.\n\n\\textbf{Additional input support}. \\textsf{Argon2} supports additional input, which is syntactically separated from the message and nonce, such as secret key, environment parameters, user data, etc..\n\n\n\\subsection{Possible future extensions}\\label{sec:future2}\n\nArgon2\\ can be rather easily tuned to support other compression functions, hash functions and block sizes.\nROM can be easily integrated into \\textsf{Argon2} by simply including it into the area where the blocks are referenced from.\n\n\n\\section{Security analysis}\n\n\n\n\n\n\\subsection{Ranking tradeoff attack}\\label{sec:tradeoff} To figure out the costs of the ASIC-equipped adversary, we first need to calculate the time-space tradeoffs for \\textsf{Argon2}. To the best of our knowledge, the first generic\ntradeoffs attacks were reported in~\\cite{trade-att}, and they apply to both data-dependent and data-independent schemes. The idea of the ranking method~\\cite{trade-att} is as follows. When we generate a memory block $B[l]$, we make a decision, to store it or not. If we do not store it, we calculate the access complexity of this block --- the number of calls to $F$ needed to compute the block, which is based on the access complexity of $B[l-1]$ and $B[\\phi(l)]$. The detailed strategy is as follows:\n \\begin{enumerate}\n \\item Select an integer $q$ (for the sake of simplicity let $q$ divide $T$).\n \\item Store $B[kq]$ for all $k$;\n \\item Store all $r_i$ and all access complexities;\n \\item Store the $T/q$ highest access complexities. If $B[i]$ refers to a vertex from this top, we store $B[i]$.\n\\end{enumerate}\nThe memory reduction is a probabilistic function of $q$. We applied the algorithm to the indexing function of \\textsf{Argon2} and obtained the results in Table~\\ref{tab:generic3}. Each recomputation is a tree of certain depth, also given in the table.\n\nWe conclude that for data-dependent one-pass schemes the adversary is always able to reduce the memory by the factor of 4 and still keep the time-area product the same.\n\\begin{table}[hb]\n\\renewcommand{\\arraystretch}{1.3}\n$$\n\\begin{array}{|c||c|c|c|c|c|c|c|c|}\n\\hline\n\\text{$\\alpha$ } &\\frac{1}{2} &\\frac{1}{3} &\\frac{1}{4} &\\frac{1}{5} &\\frac{1}{6} &\\frac{1}{7} \\\\\n\\hline\n\\text{$C(\\alpha)$} &1.5& 4& 20.2& 344& 4660 & 2^{18}\\\\\n\\text{($D(\\alpha)$} & 1.5 & 2.8 & 5.5 & 10.3 & 17 &27 \\\\\n\\hline\n\\end{array}\n$$\n\\caption{Time and computation penalties for the ranking tradeoff attack for the Argon2 indexing function.}\\label{tab:generic3}\n\\end{table}\n\n\n\\subsection{Attack on iterative compression function}\\label{sec:att-iter}\n\nLet us consider the following structure of the compression function $F(X,Y)$, where $X$ and $Y$ are input blocks:\n\\begin{itemize}\n \\item The input blocks of size $t$ are divided into shorter subblocks of length $t'$ (for instance, 128 bits) $X_0,X_1,X_2,\\ldots$ and $Y_0,Y_1,Y_2,\\ldots$.\n \\item The output block $Z$ is computed subblockwise:\n \\begin{align*}\n Z_0 = G(X_0,Y_0);\\\\\n Z_i = G(X_i,Y_i,Z_{i-1}),\\;i>0.\n \\end{align*}\n\\end{itemize}\nThis scheme resembles the duplex authenticated encryption mode, which is secure under certain assumptions on $G$. However, it is totally insecure against tradeoff adversaries, as shown below.\n\nSuppose that an adversary computes $Z = F(X,Y)$ but $Y$ is not stored. Suppose that $Y$ is a tree function of stored elements of depth $D$. The adversary starts with computing $Z_0$, which requires only $Y_0$. In turn, $Y_0 = G(X_0', Y_0')$ for some $X',Y'$.\nTherefore, the adversary computes the tree of the same depth $D$, but with the function $G$ instead of $F$. $Z_1$ is then a tree function of depth $D+1$, $Z_2$ of depth $D+2$, etc. In total, the recomputation takes $(D+s)L_G$ time, where $s$ is the number of subblocks and $L_G$ is the latency of $G$. This should be compared to the full-space implementation, which takes time\n$sL_G$. Therefore, if the memory is reduced by the factor $q$, then the time-area product is changed as\n$$\nAT_{new} = \\frac{D(q)+s}{sq}AT.\n$$\nTherefore, if\n\\begin{equation}\\label{att:iter}\nD(q) \\leq s(q-1),\n\\end{equation}\nthe adversary wins.\n\nOne may think of using the $Z_{m-1}[l-1]$ as input to computing $Z_0[l]$. Clearly, this changes little in adversary's strategy, who could simply store all $Z_{m-1}$, which is feasible for large $m$. In concrete proposals, $s$ can be 64, 128, 256 and even larger.\n\nWe conclude that $F$ with an iterative structure is insecure. We note that this attack applies also to other PHC candidates with iterative compression function.\n\n\\begin{comment}\n \\subsection{Multi-pass schemes}\n\n If the defender has more time than needed to fill the available memory, then he can run several passes on the memory. Also some designers decided to process memory several times\n to get better time-space tradeoffs. Let us figure out how the adversary's costs are affected in this case.\n\n Suppose we make $K$ passes with $T$ iterations each following the scheme~\\eqref{eq:class}, so that after the first pass any address in the memory may be used. Then this is equivalent\n to running a single pass with $KT$ iterations such that $\\phi(j)\\geq j-T$. The time-space tradeoff would be the same as in a single pass with $T$ iterations and additional condition\n $$\n \\phi(j) \\geq j-\\frac{T}{K}.\n $$\n We have applied the ranking algorithm (Section~\\ref{sec:tradeoff}) and obtained the results in Tables~\\ref{tab:generic4},\\ref{tab:generic5}. We conclude that for the data-dependent schemes\n using several passes does increase the time-area product for the adversary who uses tradeoffs. Indeed, suppose we run a scheme with memory $A$ with one pass for time $T$,\n or on $A/2$ with 2 passes.\n If the adversary reduces the memory to $A/6$ GB (i.e. by the factor of 6) for the first case, the time grows by the factor of 8.2, so that the time-area product is $1.35 AT$. However, if in the second setting the memory is reduced to $A/6$ GB (i.e. by the factor of 3), the time grows by the factor of 14.3, so that the time-area product is $2.2AT$. For other reduction factors the ratio between the two products remains around 2.\n\n Nevertheless, we do not immediately argue for the prevalence of multi-pass schemes, since it can be possible that new tradeoff algorithms change their relative strength.\n\n \\begin{table}[ht]\n\\renewcommand{\\arraystretch}{1.3}\n$$\n\\begin{array}{|c||c|c|c|c|c|}\n\\hline\n\\text{Memory fraction ($\\alpha$) } &\\frac{1}{2} &\\frac{1}{3} &\\frac{1}{4} &\\frac{1}{5} &\\frac{1}{6}\\\\\n\\hline\n\\text{1 pass} & 1.7 & 3 & 6.3 & 16.6 & 55\\\\\n\\text{2 passes} & 15 & 410 & 19300& 2^{20} & 2^{25}\\\\\n\\text{3 passes} &3423& 2^{22}& 2^{32}\\\\\n\\hline\n\\end{array}\n$$\n\\caption{Computation penalties for the ranking tradeoff attack.}\\label{tab:generic4}\n\\end{table}\n\n \\begin{table}[ht]\n\\renewcommand{\\arraystretch}{1.3}\n$$\n\\begin{array}{|c||c|c|c|c|c|}\n\\hline\n\\text{Memory fraction ($\\alpha$) } &\\frac{1}{2} &\\frac{1}{3} &\\frac{1}{4}&\\frac{1}{5} &\\frac{1}{6}\\\\\n\\hline\n\\text{1 pass} & 1.7 & 2.5 & 3.8 & 5.7 & 8.2\\\\\n\\text{2 passes} & 5.7 & 14.3 & 28.8 & 49 & 75\\\\\n\\text{3 passes} &20.7& 56& 103 &- & -\\\\\n\\hline\n\\end{array}\n$$\n\\caption{Time penalties for the ranking tradeoff attack.}\\label{tab:generic5}\n\\end{table}\n\\end{comment}\n\n\\subsection{Security of Argon2 to generic attacks}\\label{sec:generic}\n\nNow we consider preimage and collision resistance of both versions of \\textsf{Argon2}. Variable-length inputs are prepended with their lengths, which shall ensure\n the absence of equal input strings. Inputs are processed by a cryptographic hash function, so no collisions should occur at this stage.\n \n \\paragraph{Internal collision resistance.} The compression function $G$ is not claimed to be collision resistant, so it may happen that distinct inputs produce identical outputs. Recall\nthat $G$ works as follows:\n$$\nG(X,Y) = P(Z)\\oplus (Z), \\quad Z = X\\oplus Y.\n$$\nwhere $P$ is a permutation based on the 2-round Blake2b permutation. Let us prove that all $Z$ are different under certain assumptions.\n\\begin{theorem}\n Let $\\Pi$ be \\textsf{Argon2d} or \\textsf{Argon2i} with $d$ lanes, $s$ slices, and $t$ passes over memory. Assume that\n \\begin{itemize}\n \\item $P(Z)\\oplus Z$ is collision-resistant, i.e. it is hard to find $a,b$ such that $P(a)\\oplus a = P(b)\\oplus b$.\n \\item $P(Z)\\oplus Z$ is 4-generalized-birthday-resistant, i.e. it is hard to find distinct $a,b,c,d$ such that $P(a)\\oplus P(b)\\oplus P(c)\\oplus P(d) = a\\oplus b\\oplus c \\oplus d$.\n \\end{itemize}Then all the blocks $B[i]$ generated in those $t$ passes are different.\n\\end{theorem}\n\\begin{proof}\n By specification, the value of $Z$ is different for the first two blocks of each segment in the first slice in the first pass. Consider the other blocks.\n\n Let us enumerate the blocks according to the moment they are computed. Within a slice, where segments can be computed in parallel, we enumerate lane 0 fully first, then lane 1, etc.. Slices are then computed and enumerated sequentially.\n Suppose the proposition is wrong, and let $(B[a],B[b])$ be a block collision such that $x0$, $l$ invocations to $H$ continue to run in parallel, but the indexing functions now may refer not only to their own slice, but also to all $jp$ slices of previous columns $Q[*][0],Q[*][1],\\ldots,Q[*][j-1]$.\n \\item The last blocks produced in each slice of the last column are XORed.\n\\end{itemize}\nThis idea is easily implemented in software with $p$ threads and $l$ joining points. It is easy to see that the adversary can use less memory when computing the last column, for instance\nby computing the slices sequentially and storing only the slice which is currently computed. Then his time is multiplied by $(1+\\frac{p-1}{l})$, whereas the memory use is multiplied\nby $(1-\\frac{p-1}{pl})$, so the time-area product is modified as\n$$\nAT_{new} = AT \\left(1-\\frac{p-1}{pl}\\right)\\left(1+\\frac{p-1}{l}\\right).\n$$\nFor $2 \\leq p,l \\leq 10$ this value is always between $1.05$ and $3$. We have selected $l=4$ as this value gives low synchronisation overhead while imposing time-area penalties on the adversary who reduces the memory even by the factor 3/4. We note that values $l=8$ or $l=16$ could be chosen.\n\nIf the compression function is collision-resistant, then one may easily prove that block collisions are highly unlikely. However, we employ a weaker compression function, for which the following holds:\n$$\nG(X,Y) = F(X\\oplus Y),\n$$\nwhich is invariant to swap of inputs and is not collision-free. We take special care to ensure that the mode of operation does not allow such collisions by introducing additional rule:\n\\begin{itemize}\n \\item First block of a segment can not refer to the last block of any segment in the previous slice.\n\\end{itemize}\nWe prove that block collisions are unlikely under reasonable conditions on $F$ in Section~\\ref{sec:generic}.\n\n \\subsection{Compression function design}\\label{sec:compression}\n\n \\subsubsection{Overview}\n\nIn contrast to attacks on regular hash functions, the adversary does not control inputs to the compression function $G$ in our scheme. Intuitively, this should relax the cryptographic properties required from the compression function and allow for a faster primitive. To avoid being the bottleneck, the compression function ideally should be on par with the performance of memcpy() or similar function, which may run at 0.1 cycle per byte or even faster. This much faster than ordinary stream ciphers or hash functions, but we might not need strong properties of those primitives.\n\nHowever, we first have to determine the optimal block size. When we request a block from a random location in the memory, we most likely get a cache miss. The first bytes would arrive at the CPU from RAM within at best 10 ns, which accounts for 30 cycles. In practice, the latency of a single load instruction may reach 100 cycles and more. However, this number can be amortized if we request a large block of sequentially stored bytes. When the first bytes are requested, the CPU stores the next ones in the L1 cache, automatically or using the \\texttt{prefetch} instruction. The data from the L1 cache can be loaded as fast as 64 bytes per cycle on the Haswell architecture, though we did not manage to reach this speed in our application.\n\nTherefore, the larger the block is, the higher the throughput is. We have made a series of experiments with a non-cryptographic compression function, which does little beyond simple XOR of its inputs, and achieved the performance of around 0.7 cycles per byte per core with block sizes of 1024 bits and larger.\n\n\\subsubsection{Design criteria}\n\nIt was demonstrated that a compression function with a large block size may be vulnerable to tradeoff attacks if it has a simple iterative structure, like modes of operation for a blockcipher~\\cite{trade-att} (some details in Appendix~\\ref{sec:att-iter}). \n\nThus we formulate the following design criteria:\n\\begin{itemize}\n \\item \\emph{The compression function must require about $t$ bits of storage (excluding inputs) to compute any output bit.}\n \\item \\emph{Each output byte of $F$ must be a nonlinear function of all input bytes, so that the function has differential probability below certain level, for example $\\frac{1}{4}$}.\n\\end{itemize}\nThese criteria ensure that the attacker is unable to compute an output bit using only a few input bits or a few stored bits. Moreover, the output bits should not be (almost) linear functions of input bits, as otherwise the function tree would collapse.\n\nWe have not found any generic design strategy for such large-block compression functions. It is difficult to maintain diffusion on large memory blocks due to the lack of CPU instructions that interleave many registers at once. A naive approach would be to apply a linear transformation with certain branch number. However, even if we operate on 16-byte registers, a 1024-byte block would consist of 64 elements. A $64\\times 64$-matrix would require 32 XORs per register to implement, which gives a penalty about 2 cycles per byte.\n\nInstead, we propose to build the compression function on the top of a transformation $P$ that already mixes several registers. We apply $P$ in parallel (having a P-box), then shuffle the output registers and apply it again. If $P$ handles $p$ registers, then the compression function may transform a block of $p^2$ registers with 2 rounds of P-boxes. We do not have to manually shuffle the data, we just change the inputs to P-boxes. As an example, an implementation of the Blake2b~\\cite{AumassonNWW13} permutation processes 8 128-bit registers, so with 2 rounds of Blake2b we can design\na compression function that mixes the 8192-bit block. We stress that this approach is not possible with dedicated AES instructions. Even though they are very fast, they apply only to the 128-bit block, and we still have to diffuse its content across other blocks.\n\n\n\n\\subsection{User-controlled parameters}\n\nWe have made a number of design choices, which we consider optimal for a wide range of applications. Some parameters can be altered, some should be kept as is. We give a user full control over:\n\\begin{itemize}\n \\item Amount $M$ of memory filled by algorithm. This value, evidently, depends on the application and the environment. There is no \"insecure\" value for this parameter, though clearly the more memory the better.\n \\item Number $T$ of passes over the memory. The running time depends linearly on this parameter. We expect that the user chooses this number according to the time constraints on the application. Again, there is no \"insecure value\" for $T$.\n \\item Degree $d$ of parallelism. This number determines the number of threads used by an optimized implementation of \\textsf{Argon2}. We expect that the user is restricted by a number of CPU cores (or half-cores) that can be devoted to the hash function, and chooses $d$ accordingly (double the number of cores).\n \\item Length of password/message, salt/nonce, and tag (except for some low, insecure values for salt and tag lengths).\n\\end{itemize}\n\nWe allow to choose another compression function $G$, hash function $H$, block size $b$, and number of slices $l$. However, we do not provide this flexibility in a reference implementation as we guess that\nthe vast majority of the users would prefer as few parameters as possible.\n\n\n\n\\section{Performance}\n\n\\subsection{x86 architecture}\nTo optimize the data load and store from/to memory, the memory that will be processed has to be alligned on 16-byte boundary when loaded/stored into/from 128-bit registers and on 32-byte boundary when loaded/stored into/from 256-bit registers. If the memory is not aligned on the specified boundaries, then each memory operation may take one extra CPU cycle, which may cause consistent penalties for many memory accesses.\n\n\nThe results presented are obtained using the \\texttt{gcc 4.8.2} compiler with the following options: \\texttt{-m64 -mavx -std=c++11 -pthread -O3}.\nThe cycle count value was measured using the \\texttt{\\_\\_rdtscp} Intel intrinsics C function which inlines the \\texttt{RDTSCP} assembly instruction that returns the 64-bit Time Stamp Counter (TSC) value. The instruction waits for prevoius instruction to finish and then is executed, but meanwhile the next instructions may begin before the value is read. Although this shortcoming, we used this method because it is the most realiable handy method to measure the execution time and also it is widely used in other cryptographic operations benchmarking.\n\n\\begin{table}\n\\begin{center}\n\\begin{tabular}{|cc||cc|cc|}\n\\hline\n& & \\multicolumn{2}{c|}{\\textsf{Argon2d} (1 pass)} & \\multicolumn{2}{|c|}{\\textsf{Argon2i} (3 passes)} \\\\\n\\cline{3-6}\nProcessor & Threads & Cycles/Byte & Bandwidth & Cycles/Byte & Bandwidth \\\\\n& & & (GB/s) & & (GB/s)\\\\\n\\hline\n i7-4500U & 1 &1.6 & 2.2 & 4.7 & 2.6 \\\\\n\\hline\n i7-4500U & 2 &1.0& 3.6&2.8 & 4.5\\\\\n\\hline\n i7-4500U & 4 &0.7 & 5.1 & 2 & 5.4 \\\\\n\\hline\n i7-4500U & 8 & 0.7 & 5.1 & 1.9 & 5.8\\\\\n\\hline\n\\end{tabular}\n\\end{center}\n\\caption{Speed and memory bandwidth of Argon2(d/i) measured on 1 GB memory filled. Core i7-4500U --- Intel Haswell 1.8 GHz, 4 cores}\n\\label{table:cycle_per_byte_results}\n\\end{table}\n\n\\section{Applications}\n\\textsf{Argon2d} is optimized for settings where the adversary does not get regular access to system memory or CPU, i.e. he can not run side-channel attacks based on the timing information, nor he\ncan recover the password much faster using garbage collection~\\cite{cryptoeprint:2014:881}. These settings are more typical for backend servers and cryptocurrency minings. For practice we suggest the following settings:\n\\begin{itemize}\n \\item Cryptocurrency mining, that takes 0.1 seconds on a 2 Ghz CPU using 1 core --- \\textsf{Argon2d} with 2 lanes and 250 MB of RAM;\n \\item Backend server authentication, that takes 0.5 seconds on a 2 GHz CPU using 4 cores --- \\textsf{Argon2d} with 8 lanes and 4 GB of RAM.\n\\end{itemize}\n\n\\textsf{Argon2i} is optimized for more dangerous settings, where the adversary possibly can access the same machine, use its CPU or mount cold-boot attacks. We use three passes to get rid entirely of the password in the memory. We suggest the following settings:\n\\begin{itemize}\n \\item Key derivation for hard-drive encryption, that takes 3 seconds on a 2 GHz CPU using 2 cores --- \\textsf{Argon2i}with 4 lanes and 6 GB of RAM;\n \\item Frontend server authentication, that takes 0.5 seconds on a 2 GHz CPU using 2 cores --- \\textsf{Argon2i} with 4 lanes and 1 GB of RAM.\n\\end{itemize}\n\n\n\n\n\\section{Conclusion}\n\nWe presented the memory-hard function \\textsf{Argon2}, which maximizes the ASIC implementation costs for given CPU computing time. We aimed to make the design clear and compact, so that any feature and operation has certain rationale. The clarity and brevity of the Argon2 design has been confirmed by its eventual selection as the PHC winner.\n\nFurther development of tradeoff attacks with dedication to \\textsf{Argon2} is the subject of future work. It also remains to be seen how \\textsf{Argon2} withstands GPU cracking with low memory requirements.\n\n\n\n\\bibliographystyle{IEEEtranS}\n\\bibliography{tradeoff}\n\n\\appendix \n\n\n\n\\section{Permutation $\\mathcal{P}$}\\label{sec:blakeround}\n\nPermutation $\\mathcal{P}$ is based on the round function of Blake2b and works as follows. Its 8 16-byte inputs $S_0, S_1,\\ldots, S_7$ are viewed as a $4\\times 4$-matrix of 64-bit words, where $S_i = (v_{2i+1}||v_{2i})$:\n$$\n\\begin{pmatrix}\n v_0 & v_1 & v_2 & v_3\\\\\n v_4 & v_5 & v_6 & v_7\\\\\n v_8 & v_9 & v_{10} & v_{11}\\\\\n v_{12} & v_{13} & v_{14} & v_{15}\\\\\n\\end{pmatrix}\n$$\nThen we do\n\\begin{eqnarray*}\nG(v_0, v_4, v_8, v_{12})\\quad G(v_1, v_5, v_9, v_{13}) \\\\ G(v_2, v_6, v_{10}, v_{14}) \\quad G(v_3, v_7, v_{11}, v_{15})\\\\\nG(v_0, v_5, v_{10}, v_{15})\\quad G(v_1, v_6, v_{11}, v_{12}) \\\\ G(v_2, v_7, v_{8}, v_{13}) \\quad G(v_3, v_4, v_{9}, v_{14}),\n\\end{eqnarray*}\nwhere $G$ applies to $(a,b,c,d)$ as follows:\n\\begin{equation}\\label{eq:blake-orig}\n\\begin{aligned}\n a &\\leftarrow a + b+ 2*a_L*b_L;\\\\\n d &\\leftarrow (d\\oplus a)\\ggg 32;\\\\\n c &\\leftarrow c + d+ 2*c_L*d_L;\\\\\n b &\\leftarrow (b\\oplus c)\\ggg 24;\\\\\n a &\\leftarrow a + b+ 2*a_L*b_L;\\\\\n d &\\leftarrow (d\\oplus a)\\ggg 16;\\\\\n c &\\leftarrow c + d+ 2*c_L*d_L;\\\\\n b &\\leftarrow (b\\oplus c)\\ggg 63;\\\\\n\\end{aligned}\n\\end{equation}\nHere $+$ are additions modulo $2^{64}$ and $\\ggg$ are 64-bit rotations to the right. $x_L$ is the 64-bit integer $x$ truncated to the 32 least significant bits. The modular additions in $G$ are combined with 64-bit multiplications (that is the only difference to the original Blake2 design). \n\n\nOur motivation in adding multiplications is to increase the circuit depth (and thus the running time) of a potential ASIC implementation while having roughly the same running time on CPU thanks to parallelism and pipelining. Extra multiplications in the scheme serve well, as the best addition-based circuits for multiplication have latency about 4-5 times the addition latency for 32-bit multiplication (or roughly $\\log_n$ for $n$-bit multiplication).\n\nAs a result, any output 64-bit word of $\\mathcal{P}$ is implemented by a chain of additions, multiplications, XORs, and rotations. The shortest possible chain for the 1 KB-block (e.g, from $v_0$ to $v_0$) consists of 12 MULs, 12 XORs, and 12 rotations.\n\n\\section{Additional functionality}\n\nThe following functionality is enabled in the reference implementation but is \nnot officially included in the version 1.2.1.:\n\\begin{itemize}\n\\item Hybrid construction \\textsf{Argon2id}, which has type $y=2$ (used in the pre-hashing and address generation). In the first two slices of the first pass it generates reference addresses data-independently as in \\textsf{Argon2i}, whereas in later slices and next passes it generates them data-dependently as in \\textsf{Argon2d}.\n\\item Sbox-hardened version \\textsf{Argon2ds}, which has type $y=4$. In this version the compression function $G$ includes the 64-bit transformation $\\mathcal{T}$, which is a chain of S-boxes, multiplications, and additions. In terms of Section~\\ref{sec:compr}, we additionally compute \n\\begin{align*}\nW&= LSB_{64}(R_0\\oplus R_{63});\\\\\nZ_0 &+= \\mathcal{T}(W);\\\\\nZ_{63}&+=\\mathcal{T}(W)\\ll 32.\n\\end{align*}\nThe transformation $\\mathcal{T}$, on the 64-bit word $W$ is defined as follows:\n\\begin{itemize}\n\\item Repeat 96 times:\n\\begin{enumerate}\n\\item $y\\leftarrow S[W[8:0]]$;\n\\item $z\\leftarrow S[512+W[40:32]]$;\n\\item $W \\leftarrow ((W[31:0]\\circ W[63:32])+y)\\oplus z$.\n\\end{enumerate}\n\\item $T(W)\\leftarrow W$.\n\\end{itemize}\nAll the operations are performed modulo $2^{64}$. $\\circ$ is the 64-bit multiplication, $S[]$ is the Sbox (lookup table) that maps 10-bit indices to 64-bit values. $W[i:j]$ is the subset of bits of $W$ from $i$ to $j$ inclusive. \n\nThe S-box is generated in the start of every pass in the following procedure. In total we specify $2^{10}\\cdot 8$ bytes, or 8 KBytes. We take block $B[0][0]$ and apply $F$ (the core of $G$) to it 16 times. After each two iterations we use the entire 1024-byte value and initialize 128 lookup values.\n\nThe properties of $\\mathcal{T}$ and its initialization procedure is subject to change.\n\\end{itemize}\n\n\\section{Change log}\n\n\\subsection{v1.2.1 -- 8th September, 2015}\n\\begin{itemize}\n\\item The total number of blocks can reach $2^{32}-1$;\n\\item The reference block index now requires 64 bits; the lane number is computed separately.\n\\item New modes \\textsf{Argon2id} and \\textsf{Argon2ds} are added as optional.\n\\end{itemize}\nThe specification of v1.2.1 released on 26th August, 2015, had incorrect description of the first block generation. The version released on 2d September, 2015, had incorrect description of the counter used in generating addresses for \\textsf{Argon2i}.\n\n\\subsection{v1.2 -- 21th June, 2015}\n\nNon-uniform indexing rule, the compression function gets multiplications.\n\n\\subsection{v1.1 -- 6th February, 2015}\n\\begin{itemize}\n\\item New indexing rule added to avoid collision with a proof. \n\\item New rule to generate first two blocks in each lane.\n\\item Non-zero constant added to the input block used to generate addresses in \\textsf{Argon2i}.\n\\end{itemize}\n\n\\end{document}\n\n", "meta": {"hexsha": "6642a2207b118361d288a9d476490608d5b472bd", "size": 60929, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "benchmarks/khovratovich-Argon2/Doc/LaTeX/argon2-spec.tex", "max_stars_repo_name": "pointhi/benchmarks", "max_stars_repo_head_hexsha": "68899480c0fc8d361079a81edc6d816d5f17d58e", "max_stars_repo_licenses": ["UPL-1.0"], "max_stars_count": 210, "max_stars_repo_stars_event_min_datetime": "2015-06-18T20:33:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-23T03:25:03.000Z", "max_issues_repo_path": "benchmarks/khovratovich-Argon2/Doc/LaTeX/argon2-spec.tex", "max_issues_repo_name": "pointhi/benchmarks", "max_issues_repo_head_hexsha": "68899480c0fc8d361079a81edc6d816d5f17d58e", "max_issues_repo_licenses": ["UPL-1.0"], "max_issues_count": 23, "max_issues_repo_issues_event_min_datetime": "2018-06-07T07:46:27.000Z", "max_issues_repo_issues_event_max_datetime": "2018-08-06T17:57:39.000Z", "max_forks_repo_path": "benchmarks/khovratovich-Argon2/Doc/LaTeX/argon2-spec.tex", "max_forks_repo_name": "pointhi/benchmarks", "max_forks_repo_head_hexsha": "68899480c0fc8d361079a81edc6d816d5f17d58e", "max_forks_repo_licenses": ["UPL-1.0"], "max_forks_count": 21, "max_forks_repo_forks_event_min_datetime": "2015-04-01T16:31:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-09T00:42:13.000Z", "avg_line_length": 70.5196759259, "max_line_length": 741, "alphanum_fraction": 0.7406489521, "num_tokens": 17210, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.35577487985229844, "lm_q1q2_score": 0.18205591355705053}}
{"text": "% $Id: CoordinateSystems.tex,v 1.1 2008/01/31 18:04:16 dconway Exp $\n\\chapter{\\label{chapter:CoordinateSystems}Coordinate Systems}\n\\chapauthor{Darrel J. Conway}{Thinking Systems, Inc.}\n\n\\textbf{NOTE: This chapter currently contains the original design spec for the coordinate systems.\nIt needs to be reviewed against the current GMAT system, the figures need to be recreated, and some\nof the text needs to be fitted into the rest of the design document.}\n\nThis chapter presents design guidelines for the coordinate system classes in the Goddard Mission\nAnalysis Tool (GMAT). It describes how the GMAT software implements the coordinate system math\ndescribed in the GMAT Mathematical Specifications\\cite{mathSpec}. This description includes the\ninitial design for the classes that provide coordinate system support in GMAT. The interactions\nbetween these classes and the rest of the GMAT system are also described.\n\n\\section{Introduction}\n\nThe Goddard Mission Analysis Tool (GMAT) is a multi-platform orbit simulator designed to support\nmultiple spacecraft missions flying anywhere in the solar system. GMAT is written in C++ and runs on\nWindows, Macintosh and Linux computer systems. The tool provides an integrated interface to MATLAB,\na high level computing environment from the Mathworks, Inc\\cite{MATLAB}. The GMAT graphical user\ninterface (GUI) is written using the wxWidgets GUI Toolkit\\cite{wxWidgets}, an open source library\nthat compiles and runs under all of the target operating systems.\n\nGMAT is an object-oriented system, using the full extent of the C++ language to implement the object\nmodel that provides GMAT's functionality. The first three builds of GMAT provided capabilities to\nmodel orbits in the vicinity of the Earth, including detailed force modeling, impulsive\nmaneuvers, and parameter targeting using a differential corrector. All of these capabilities can be\ncontrolled either using either the GMAT graphical user interface or a custom scripting language\ndesigned to simplify GMAT and MATLAB interactions. The fourth build of the system generalizes the\ncapabilities of GMAT modeling for other orbital regimes.\n\nIn order to model spacecraft trajectories in these regimes, GMAT needs to be able to represent the\nspacecraft state and related quantities in coordinate systems that are convenient to each regime.\nThis document describes how these coordinate systems are implemented in the GMAT code.\n\n\n\\section{\\label{sec:CSClassDescription}Coordinate System Classes}\n\nFigure \\ref{figure:HighLevelCSClasses} shows the core C++ classes (drawn using\nPoseidon\\cite{poseidon}) added to GMAT to provide support for coordinate systems in Build 4. The\ncoordinate system capabilities are provided by the incorporation of these classes into the GMAT base\nsubsystem\\footnote{The GMAT code base consists of a set of classes that provide the core\nfunctionality of the system, the {}``base'' subsystem, and classes that comprise the graphical user\ninterface, the {}``gui'' subsystem. All of the classes described in this document are members of\nthe base subsystem, with the exception of the recommendations for changes to the panels on the\nGUI.}.\n\n\\begin{figure}[htb]\n\\begin{center}\n\\includegraphics[scale=0.5]{Images/Highlevelcoordinatesystemclasses.eps}\n\\caption{\\label{figure:HighLevelCSClasses}Coordinate System Classes in GMAT}\n\\end{center}\n\\end{figure}\n\nThe coordinate system classes consist of a CoordinateSystem class that acts as the interface between\nthe conversions and the rest of GMAT, an AxisSystem base class with a derived hierarchy used for\nrotational conversions, a CoordinateConverter class that manages conversions between different\ncoordinate systems, and a factory constructed as a singleton that create the AxisSystem objects. The\nCoordinateSystem class is the component that is instantiated when a user {}``Creates'' a coordinate\nsystem object.\n\nPrevious builds of GMAT included classes that model spacecraft, formations, and celestial objects.\nThese classes were derived from a core base class named GmatBase. A new intermediate class,\nSpacePoint, is implemented in GMAT to make access to position, velocity, and rotational data\navailable to the coordinate system classes when needed. Section~\\ref{sub:SpacePointClassDescription}\ndescribes this class.\n\n\n\\subsection{The CoordinateSystem Class}\n\nThe CoordinateSystem class is a configured component that implements the functionality needed to\nconvert into and out of a specified coordinate system. Internally, GMAT performs computations in a\nMean of J2000 Earth Equatorial coordinate system, centered at one of the celestial bodies in the\nGMAT solar system (i.e. the Sun, a planet, or a moon) or at a barycenter or libration point. Each\nCoordinateSystem instance provides methods to transform into and out of these J2000 coordinate\nsystems. It contains the data necessary for translation calculations, along with a member object\npointer that is set to an AxisSystem instance for coordinate systems whose principle axes are not\nparallel to the Mean of J2000 Earth Equatorial axes, or to NULL for coordinate systems that are\noriented parallel to these axes.\n\nThe AxisSystem class provides the methods needed to rotate the coordinate system into and out of the\nMean of J2000 Earth Equator frame. The AxisSystem is set for a given CoordinateSystem by setting\nthe axes member to an AxisSystem instance.\n\nGMAT uses a late binding scheme to provide interconnections between objects used when modeling an\nanalysis problem. Individual components are configured from either the grapical user interface or a\nscript file describing the objects that need to be modeled. Connections between these objects are\ndefined using the names of the objects, but the actual object instances used in the model are not\nset until the simulation is run. Upon execution, the configured objects are copied into the analysis\nworkspace, called the Sandbox, and the connections between the configured objects are established\nimmediately prior to the run of the simulation. The Initialize method in the CoordinateSystem class\nimplements this late binding for the connection between the coordinate system instance and the\nrelated SpacePoints.\n\n\n\\subsection{The AxisSystem Class Hierarchy}\n\nGMAT is capable of supporting numerous coordinate system orientations. These orientations are\ndefined through the AxisSystem class; each unique axis orientation is implemented as a separate\nclass derived from the AxisSystem base class. Figure~\\ref{figure:AxisSystemOverview} shows an\noverview of the AxisSystem class hierarchy, and identifies the top level classes in this hierarchy.\n\n\\begin{figure}\n\\begin{center}\n\\includegraphics[scale=0.5]{Images/AxisSystemOverview.eps}\n\\caption{\\label{figure:AxisSystemOverview}Top level AxisSystem Derived Classes}\n\\end{center}\n\\end{figure}\n\nThe orientations of the coordinate systems in GMAT fall into two broad categories: axes that change\norientation over time, and those that remain fixed in orientation. The latter category requires\ncomputation of the rotation matrices one time, at initialization, in order to perform the rotations\ninto and out of the coordinate system. Figure~\\ref{figure:InertialAxisHierarchy} shows the six\ninertial axis systems supported in GMAT. These systems support equatorial and ecliptic versions\nof Mean of J2000, Mean of Epoch, and True of Epoch transformations.\n\n\\begin{figure}\n\\begin{center}\n\\includegraphics[scale=0.5]{Images/AxisSystemInertial.eps}\n\\caption{\\label{figure:InertialAxisHierarchy}Inertial Axis Classes}\n\\end{center}\n\\end{figure}\n\nCoordinate systems that are not fixed in orientation over time are derived from the DynamicAxes\nclass, as is shown in Figure~\\ref{figure:DynamicAxisHierarchy}. These coordinate systems include\nequatorial and ecliptic versions of the mean of date and true of date axes, along with axes that\nevolve with the polar motion of the body's rotational axis (implemented in the EquatorAxes class)\nand axes that are fixed on the body's prime meridian (the BodyFixedAxes class). All of these classes\nrequire recomputation of the orientation of the axes as the epoch of the model evolves.\n\n\\begin{figure}\n\\begin{center}\n\\includegraphics[scale=0.5]{Images/AxisSystemDynamic.eps}\n\\caption{\\label{figure:DynamicAxisHierarchy}Dynamic Axis Classes}\n\\end{center}\n\\end{figure}\n\nOne additional class in Figure~\\ref{figure:DynamicAxisHierarchy} bears discussion here. GMAT\nsupports numerous coordinate systems that reference bodies that are not celestial objects --\nspecifically coordinate systems that use Lagrange points, barycenters, spacecraft, and formations to\ndefine the coordinate origins and axes. These coordinate systems use the ObjectReferencedAxes class\nto construct the coordinate basis and rotation matrices. The GMAT Mathematical\nSpecifications\\cite{mathSpec} provide detailed descriptions of how this class operates.\n\n\\subsection{CoordinateSystem and AxisSystem Collaboration}\n\nThe GMAT Mathematical Specification\\cite{mathSpec} includes a flow chart that describes the\nprocess of transforming between coordinate systems. This process is performed in the GMAT code using\nthe CoordinateConverter class and the public methods of the CoordinateSystem class. When GMAT needs\na conversion from one coordinate system to another, the method \\texttt{CoordinateConverter::Convert}\nis called with the epoch, input state, input coordinate system, output state, and output coordinate\nsystem as parameters. The converted state vector is stored in the output state parameter.\n\nThe Convert method calls the conversion method \\texttt{CoordinateSystem::ToMJ2000Eq} on the input\ncoordinate system, followed by \\texttt{CoordinateSystem::FromMJ2000Eq} on the output coordinate\nsystem. \\texttt{ToMJ2000Eq} calls the \\texttt{AxisSystem::RotateToMJ2000Eq} method followed by the\n\\texttt{Coordinate\\-System::TranslateToMJ2000Eq} method, converting the input state from the input\ncoordinate system into Mean of J2000 Equatorial coordinates. Similarly, \\texttt{FromMJ2000Eq} calls\nthe \\texttt{Coordinate\\-System::TranslateFromMJ2000Eq} method and then the\n\\texttt{AxisSystem::RotateFromMJ2000Eq} method, converting the intermediate state from Mean of J2000\nEquatorial coordinates into the output coordinate system, completing the transformation from the\ninput coordinate system to the output coordinate system. Each of the conversion routines takes a\nSpacePoint pointer as the last parameter in the call. This parameter identifies the J2000 coordinate\nsystem origin to the conversion routine. If the pointer is NULL, the origin is set to the Earth.\n\nThe following paragraphs provide programmatic samples of these conversions.\n\n\\subsubsection{Code Snippets for a Conversion}\n\nFigure~\\ref{figure:TransformDetails}, generalized from the GMAT mathematical\nspecification, illustrates the procedure used to implement a transformation\nfrom one coordinate system to another. The following paragraphs provide\ncode snippets with the corresponding function arguments for this process.\n\n\\begin{figure}\n\\begin{center}\n\\includegraphics[scale=0.5]{Images/CoordinateConversionControlFlow.eps}\n\\caption{\\label{figure:TransformDetails}GMAT Procedure for a Generic Coordinate Transformation}\n\\end{center}\n\\end{figure}\n\nWhen GMAT needs to convert from one coordinate system to another, this method is called:\n\n\\begin{quotation}\n\\begin{verbatim}\nif (!coordCvt->Convert(epoch, instate, inputCS, outstate, outputCS))\n throw CoordinateSystemException(\"Conversion from \" +\n inputCS->GetName() + \" to \" + outputCS->GetName() + \" failed.\");\n\\end{verbatim}\n\\end{quotation}\n\nThis method invokes the calls listed above, like this:\n\n\\begin{quotation}\n\\begin{verbatim}\n// Code in CoordinateConverter::Convert\nif (!inputCS->ToMJ2000Eq(epoch, instate, internalState, J2000Body))\n throw CoordinateSystemException(\"Conversion to MJ2000 failed for \" +\n inputCS->GetName());\n\nif (!outputCS->FromMJ2000Eq(epoch, internalState, outState, J2000Body))\n throw CoordinateSystemException(\"Conversion from MJ2000 failed for \" +\n outputCS->GetName());\n\\end{verbatim}\n\\end{quotation}\n\nThe conversion code from the input state to Mean of J2000 Equatorial\nCoordinates is accomplished using the calls\n\n\\begin{quotation}\n\\begin{verbatim}\n// Code in CoordinateSystem::ToMJ2000Eq\nif (axes) // axes == NULL for MJ2000Eq orientations\n if (!axes->RotateToMJ2000Eq(epoch, instate, internalState, J2000Body))\n throw CoordinateSystemException(\"Rotation to MJ2000 failed for \" +\n instanceName);\nelse // Set the intermediate state to the input state\n internalState = instate;\n\nif (!TranslateToMJ2000Eq(epoch, internalstate, internalState, J2000Body))\n throw CoordinateSystemException(\"Translation to MJ2000 failed for \" +\n instanceName);\n\\end{verbatim}\n\\end{quotation}\n\nand the conversion from Mean of J2000 Equatorial Coordinates to the output state is performed using\nthese calls:\n\n\\begin{quotation}\n\\begin{verbatim}\n// Code in CoordinateSystem::FromMJ2000Eq\nif (!TranslateFromMJ2000Eq(epoch, internalstate, internalState, J2000Body))\n throw CoordinateSystemException(\"Translation from MJ2000 failed for \" +\n instanceName);\n\nif (axes) // axes == NULL for MJ2000Eq orientations\n if (!axes->RotateFromMJ2000Eq(epoch, internalState, outstate, J2000Body))\n throw CoordinateSystemException(\"Rotation from MJ2000 failed for \" +\n instanceName);\nelse // Set the output state to the intermediate state\n outstate = internalState;\n\\end{verbatim}\n\\end{quotation}\n\n\\subsection{\\label{sub:SpacePointClassDescription}The SpacePoint Class}\n\nIn general, coordinate systems are defined in reference to locations and directions in space. Many\nof the coordinate systems used in GMAT have the direction fixed based on an external reference --\nfor example, the MJ2000Eq system has the z-axis pointed along the Earth's rotation axis at the J2000\nepoch and the x-axis aligned with the vernal equinox at the same epoch. GMAT also supports\ncoordinate systems constructed in reference to objects internal to the GMAT -- typically a planet,\nthe Sun, a moon, or a spacecraft can be used, as can special points in space like Lagrange points or\nthe barycenter of a multi-body system. The coordinate system classes need to be able to access\nposition and velocity data about these objects in a generic fashion. GMAT has a class, SpacePoint,\nthat provides this access. SpacePoint is the base class for all of the objects that model location\ndata in the solar system, as is shown in Figure~\\ref{figure:SpacePointHierarchy}. The SpacePoint\nclass is described in more detail in Chapter~\\ref{chapter:SolarSystem}.\n\n\\begin{figure}\n\\begin{center}\n\\includegraphics[scale=0.5]{Images/EnvironmentalObjects.eps}\n\\caption{\\label{figure:SpacePointHierarchy}The SpacePoint Class Hierarchy}\n\\end{center}\n\\end{figure}\n\n\\section{\\label{sec:CSScriptConfiguration}Configuring Coordinate Systems}\n\n\\subsection{Scripting a Coordinate System}\n\nThe script commands used to create a coordinate system object in GMAT are defined in the GMAT\nMathematical Specifications\\cite{mathSpec}. Coordinate System scripting is performed using the\nfollowing lines of script:\n\n\\begin{quotation}\n\\begin{verbatim}\nCreate CoordinateSystem csName\nGMAT csName.Origin = ;\nGMAT csName.Axes = ;\nGMAT csName.Primary = ;\nGMAT csName.Secondary = ;\nGMAT csName.Epoch. = ;\n\n% Only two of these three can exist for a given coordinate system;\n% see the coordinate system table for more information\nGMAT csName.XAxis = <$\\pm$R, $\\pm$V, or $\\pm$N>;\nGMAT csName.YAxis = <$\\pm$R, $\\pm$V, or $\\pm$N>;\nGMAT csName.ZAxis = <$\\pm$R, $\\pm$V, or $\\pm$N>;\n\\end{verbatim}\n\\end{quotation}\n\nThe fields in angle brackets are used to set the parameters that define the coordinate system.\nTable~\\ref{table:CSParms} provides a brief description of these fields; more details are available\nin \\cite{mathSpec}.\n\n%\n\\begin{table}\n\\caption{\\label{table:CSParms}Coordinate System Parameters}\n\\begin{center}\\begin{tabular}{|p{0.8in}|p{0.9in}|p{1.3in}|p{2.5in}|}\n\\hline\nParameter&\nRequired/ Optional&\nAllowed Values&\nDescription\\tabularnewline\n\\hline\n\\hline\nOrigin&\nRequired&\n\\begin{flushleft}Any Named SpacePoint\\end{flushleft}&\nDefines the location of the coordinate system origin.\\tabularnewline\n\\hline\nAxes&\nRequired&\n\\begin{flushleft}Equator, MJ2000Ec, MJ2000Eq, TOEEq, MOEEq, TODEq,\nMODEq, TOEEc, MOEEc, TODEc, MODEc, Fixed, ObjectRefernced\\end{flushleft}&\nDefines the orientation of the coordinate axes in space.\\tabularnewline\n\\hline\nPrimary&\nOptional&\n\\begin{flushleft}Any Named SpacePoint\\end{flushleft}&\nDefines the primary body used to orient axes for systems that need\na primary body.\\tabularnewline\n\\hline\nSecondary&\nOptional&\n\\begin{flushleft}Any Named SpacePoint\\end{flushleft}&\nDefines the secondary body used to orient axes for systems that need\na secondary body.\\tabularnewline\n\\hline\nEpoch&\nOptional&\nAny GMAT Epoch&\nSets the reference epoch for systems that need a reference epoch.\\tabularnewline\n\\hline\nXAxis&\nOptional&\n$\\pm\\textrm{R,}\\pm\\textrm{V,}\\pm\\textrm{N}$&\nUsed for ObjectReferences axes only; two of the three axes are set,\nand one must reference $\\pm N$.\\tabularnewline\n\\hline\nYAxis&\nOptional&\n$\\pm\\textrm{R,}\\pm\\textrm{V,}\\pm\\textrm{N}$&\nUsed for ObjectReferences axes only; two of the three axes are set,\nand one must reference $\\pm N$.\\tabularnewline\n\\hline\nZAxis&\nOptional&\n$\\pm\\textrm{R,}\\pm\\textrm{V,}\\pm\\textrm{N}$&\nUsed for ObjectReferences axes only; two of the three axes are set,\nand one must reference $\\pm N$.\\tabularnewline\n\\hline\n\\end{tabular}\\end{center}\n\\end{table}\n\nIn the following paragraphs, the interactions between the script interpreter subsystem and the\ncoordinate system classes are described.\n\n\\subsubsection{Script Interpreter Actions}\n\nIn GMAT, the ScriptInterpreter reads each line of script and sets up the corresponding objects. The\nlines of script above map to calls made in the ScriptInterpreter code, as described in the following\ntext.\n\nThe Create line causes the ScriptInterpreter to call the CoordinateSystemFactory and requests a\nCoordinateSystem instance:\n\n\\begin{quotation}\n\\begin{verbatim}\n// In the Interpreter subsystem\nGmatBase *csInstance = moderator->CreateCoordinateSystem(\"CoordinateSystem\", \"csName\");\n\\end{verbatim}\n\\end{quotation}\n\nThe resulting coordinate system is registered with the configuration manager.\n\nThe Origin line sets the originName parameter on this instance:\n\n\\begin{quotation}\n\\begin{verbatim}\n// First determine that the parm is a string\nGmat::ParameterType type = csInstance->GetParameterType({}``Origin'');\n\n// Here type is a string, so this is called:\ncsInstance->SetStringParameter({}``Origin'', );\n\\end{verbatim}\n\\end{quotation}\n\nThe Axes line creates an instance of the AxisSystem and passes it to the coordinate system:\n\n\\begin{quotation}\n\\begin{verbatim}\n// First determine that the parm is an internal object\nGmat::ParameterType type = csInstance->GetParameterType({}``Axes'');\n\n// Here type is an object, so this is called:\nGmatBase {*}axesInstance = moderator->CreateAxisSystem(, {}``'');\n\n// Then the object is set on the coordinate system\ncsInstance->SetRefObject(axesInstance);\n\\end{verbatim}\n\\end{quotation}\n\nThe Primary line sets the primary body on the AxisSystem instance. This is done by passing the data\nthrough the CoordinateSystem object into the AxisSystem object:\n\n\\begin{quotation}\n\\begin{verbatim}\n// First determine that the parm is a string\nGmat::ParameterType type = csInstance->GetParameterType({}``Primary'');\n\n// Pass the string to the coordinate system\ncsInstance->SetStringParameter({}``Primary'', );\n\n...\n\n// In CoordinateSystem, this parameter is passed to the AxisSystem:\naxes->SetStringParameter({}``Primary'', );\n\\end{verbatim}\n\\end{quotation}\n\nThe Secondary line is treated similarly to the primary line:\n\n\\begin{quotation}\n\\begin{verbatim}\n// First determine that the parm is a string\nGmat::ParameterType type = csInstance->GetParameterType({}``Secondary'');\n\n// Pass the string to the coordinate system\ncsInstance->SetStringParameter({}``Secondary'', );\n\n...\n\n// In CoordinateSystem, this parameter is passed to the AxisSystem:\naxes->SetStringParameter({}``Secondary'', );\n\\end{verbatim}\n\\end{quotation}\n\nThe Epoch line is handled like in the Spacecraft object, and the XAxis, YAxis and ZAxis lines are\ntreated as string inputs, like the Primary and Secondary lines, above.\n\n\\subsection{Default Coordinate Systems}\n\nGMAT defines several coordinate systems by default when it is initialized. These systems are listed\nin Table \\ref{table:DefaultCSs}.\n\n\\begin{table}\n\\caption{\\label{table:DefaultCSs}Default Coordinate Systems defined in GMAT}\n\\centerline{\\begin{tabular}{|p{1in}|p{1in}|p{1.5in}|p{2in}|}\n\\hline\nName&\nOrigin&\nAxis System&\nComments\\tabularnewline\n\\hline\n\\hline\nEarthMJ2000Eq&\nEarth&\nMJ2000 Earth Equator&\nThe default coordinate system for GMAT\\tabularnewline\n\\hline\nEarthMJ2000Ec&\nEarth&\nMJ2000 Ecliptic&\n\\tabularnewline\n\\hline\nEarthFixed&\nEarth&\nBody Fixed&\nThe Earth fixed system is used by the gravity model for full field\nmodeling\\tabularnewline\n\\hline\nBodyFixed&\nOther celestial bodies&\nBody Fixed&\nFixed systems used by the gravity model for full field modeling at\nother bodies\\tabularnewline\n\\hline\n\\end{tabular}}\n\\end{table}\n\n\\section{Coordinate System Integration }\n\nSections \\ref{sec:CSClassDescription} and \\ref{sec:CSScriptConfiguration} describe the internal\nworkings of the GMAT coordinate systems, but do not explain how the coordinate system code interacts\nwith the rest of GMAT. This section outlines that information.\n\n\n\\subsection{General Considerations}\n\nGMAT uses coordinate systems in several general areas: for the input of initial state data,\ninternally in the impulsive and finite burn code, force models and propagation code, in the\ncalculation of parameters used to evaluate the behavior of the model being run, and in the graphical\nuser interface (GUI) to display data as viewed from a coordinate system based perspective.\n\n\\subsection{Creation and Configuration}\n\n\\subsubsection{Coordinate System Creation}\n\nCoordinate systems are created through a series of interactions between the GMAT interpreters, the\nModerator, and the Factory system. Figure~\\ref{figure:CSCreationSequence} shows the sequence\nfollowed by the ScriptInterpreter when a coordinate system is configured from a script. The\nprocedure is similar when the GUI configures a coordinate system, with one exception. The\nScriptInterpreter translates a script file a line at a time, so it needs to look up the\nCoordinateSystem object each time it is referenced in the script. The GUI configures the coordinate\nsystem from a single panel, so the coordinate system object does not need to be found each time a\nparameter is accessed.\n\n\\begin{figure}\n\\begin{center}\n\\includegraphics[scale=0.5]{Images/CSCreationSequence.eps}\n\\caption{\\label{figure:CSCreationSequence}Coordinate System Creation and Configuration Sequence}\n\\end{center}\n\\end{figure}\n\n\\subsubsection{Startup Considerations}\n\nWhen a user starts GMAT, the executable program creates a singleton instance of the Moderator. The\nModerator is the core control module in GMAT; it manages the creation and deletion of resources, the\ninterfaces between the core components of the system and the external interfaces (including the GUI\nand the scripting engines), and the execution of GMAT simulations. When the Moderator is created, it\ncreates a variety of default resources, including the default factories used to create the objects\nin a simulation. The factories that get created include the CoordinateSystemFactory.\n\nAfter it has created the factories and constructed the default solar system, the Moderator creates\nthe default coordinate systems listed in Table \\ref{table:DefaultCSs}, following a procedure like\nthe one shown in Figure \\ref{figure:CSCreationSequence}. These coordinate systems are registered\nwith the Configuration Manager using the names in the table. Users can use these coordinate systems\nwithout any taking any additional configuration actions.\n\n\\subsection{Sandbox Initialization}\n\nWhen a user runs a mission sequence, the Moderator takes the following sequence of actions\n\\footnote{The description here references a Sandbox for the run. The Moderator can be configured to\nmanage a collection of Sandboxes; in that case, the actions described here are applied to the\ncurrent Sandbox from that collection.}:\n\n\\begin{enumerate}\n\\item Send the current SolarSystem to the Sandbox for cloning\n\\item Load the configured objects one at a time into the Sandbox. These objects are cloned\n\\footnote{The current build of GMAT does not fully implement cloning for the configured objects.\nThis issue is being corrected.} into the Sandbox.\n\\item The Sandbox is initialized.\n\\item The Mission is executed.\n\\end{enumerate}\n\n\\noindent The critical piece for successful execution of a GMAT mission is the third step. When the\nSandbox is initialized, the following actions are executed:\n\n\\begin{enumerate}\n\\item The local solar system object is set for all of the objects that need it.\n\\item Reference object pointers are set on objects that use them.\n\\item \\label{enu:ObjectInit}The objects are initialized.\n\\item Parameters are configured.\n\\item The command sequence is configured.\n\\begin{enumerate}\n\\item The object table is passed to each command.\n\\item The solar system is passed to each command.\n\\item \\label{enu:CS-CommandInit}The command is initialized.\n\\end{enumerate}\n\\end{enumerate}\n\n\\noindent The coordinate system objects are fully initialized and ready for use by the end of the\nstep \\ref{enu:ObjectInit}. Commands that use the coordinate system objects have the object\nassociations set in step~\\ref{enu:CS-CommandInit}.\n\n\\subsection{Initial States}\n\nUsers need to set the locations and initial motion of spacecraft, ground stations, and other\nphysical entities modeled in GMAT using a coordinate system that makes this data simple to specify.\nFor this reason, GMAT lets users select all or a portion of the coordinate system needed for these\nobjects.\n\n\\subsubsection{Spacecraft}\n\nThe initial state for a spacecraft is expressed as an epoch and six numerical quantities\nrepresenting the spacecraft's location and instantaneous motion. These quantities are typically\nexpressed as either six Cartesian elements -- the x, y, and z components of the position and\nvelocity, six Keplerian elements -- the semimajor axis, eccentricity, inclination, right ascension\nof the ascending node, argument of pariapsis, and the anomaly in one of three forms (true, mean, or\neccentric), or one of several other state representations. The element representation depends on the\ncoordinate system used. Some representations cannot be used with some coordinate systems -- for\nexample, the Keplerian representation requires a gravitational parameter, $\\mu=GM$, in order to\ncalculate the elements, so coordinate systems that do not have a massive body at the origin cannot\nbe used for Keplerian elements. For these cases, GMAT reports an error if the element type is\nincompatible with the coordinate system.\n\n\\subsubsection{Ground Stations and Other Body Fixed Objects}\n\nGround station objects and other objects connected to physical locations on a body are expressed in\nterms of the latitude, longitude, and height above the mean ellipsoid for the body. The coordinate\nsystem used for these objects is a body fixed coordinate system. Users can specify the central body\nwhen they configure these objects. The body radius and flattening factor for that body are used to\ncalculate the mean ellipsoid. Latitude is the geodetic latitude of the location, and longitude is\nmeasured eastwards from the body's prime meridian.\n\nGMAT does not currently support ground stations or other body fixed objects. This section will be\nupdated when this support is added to the system.\n\n\\subsection{Forces and Propagators}\n\nInternal states in GMAT are always stored in a Mean of J2000 Earth-Equator coordinate system. The\norigin for this system is set to either a celestial body (i.e. the Sun, a planet, or a moon), a\nbarycenter between two or more bodies, or a Lagrange point. The propagation subsystem in GMAT allows\nthe user to specify this origin, but no other coordinate system parameters. Propagation is performed\nin the Mean of J2000 Earth-Equator frame located at the specified origin.\n\nIndividual forces in the force model may require additional coordinate system transformations. These\ntransformations are described in the next section.\n\n\\subsubsection{Coordinate Systems Used in the Forces }\n\nGMAT contains models for point mass and full field gravity from both a central body and other\nbodies, atmospheric drag, solar radiation pressure, and thrust from thrusters during finite\nmaneuvers. Table~\\ref{table:ForceModelCoordinateSystems} identifies the coordinate system used for\neach force. Users set the point used as the origin for the force model. This point is labeled\n$\\mathbf{r_{o}}$ in the table. Forces that require a central body reference that body as\n$\\mathbf{r_{cb}}$ in the table. Users also specify the coordinate system used for finite maneuvers.\nAll other coordinate systems are set up internally in the force model code, and managed by the\nconstituent forces.\n\n\\begin{table}\n\\caption{\\label{table:ForceModelCoordinateSystems}Coordinate Systems Used by Individual Forces}\n\\centerline{\\begin{tabular}{|p{1.5in}|>{\\raggedright}p{1.5in}|p{3in}|}\n\\hline\nForce&\nCoordinate System&\nNotes\\tabularnewline\n\\hline\n\\hline\nPoint Mass Gravity&\n$\\mathbf{r_{o}}$ centered MJ2000 Earth Equator&\nPoint mass forces use the default representations\\tabularnewline\n\\hline\nFull Field Gravity&\n$\\mathbf{r_{cb}}$ centered Body Fixed&\nFull field models use the body fixed system to calculate latitude\nand longitude data, and calculate accelerations in the MJ2000 frame\nbased on those values.\\tabularnewline\n\\hline\nDrag&\n$\\mathbf{r_{cb}}$ centered MJ2000 Earth Equator&\nDrag forces set the atmosphere to rotate with the associated body,\nso the reference frame remains inertial (i.e. MJ2000 based).\\tabularnewline\n\\hline\nSolar Radiation Pressure&\n$\\mathbf{r_{o}}$ centered MJ2000 Earth Equator&\nSolar Radiation Pressure calculations are performed in MJ2000 coordinates\\tabularnewline\n\\hline\nFinite Maneuver Thrust&\nAny Defined Coordinate System, user specified&\nFinite maneuvers determine the thrust direction based on the thrust vector associated with the\nengines. The spacecraft are aligned with this coordinate system. A future build will add an\nadditional transformation to allow specification of the spacecraft's attitude in this\nframe.\\tabularnewline\n\\hline\n\\end{tabular}}\n\\end{table}\n\n\\subsubsection{Transformations During Propagation}\n\nGMAT's propagators consist of a numerical integrator and an associated force model. Each force model\nis a collection os individual forces that get added togehter to determine the net acceleration\napplied to the object that is propagated. The preceding section defined the coordinate systems used\nby each of these forces. Figure~\\ref{figure:forceFlow} shows the procedure that is followed each\ntime the force model calculates the acceleration applied to an object.\n\n\\begin{figure}\n\\begin{center}\n\\includegraphics[scale=0.5]{Images/PropagationandCoordinateSystems.eps}\n\\caption{\\label{figure:forceFlow}Control Flow for Transformations During Propagation}\n\\end{center}\n\\end{figure}\n\nThe force model calls each force in turn. As a force is called, it begins by transforming from the\ninternal Mean of J2000 equatorial coordinate system into the coordinate system required for that\nforce. The acceleration from the force is then calculated.\n\n\\subsection{Maneuvers}\n\nThe impulsive and finite burn models are used to simulate thruster actions on a spacecraft.\nManeuvers are applied either as an impulsive delta-V or as an acceleration in the force model. In\neither case, the coordinate system related operations in the maneuver object are the same: the basis\nvectors for the coordinate system are calculated in the MJ2000 frame, the magnitude of the change in\nthe velocity is calculated for the maneuver (resulting in a delta-V magnitude for impulsive\nmaneuvers, or the time rate of change of velocity for finite maneuvers), and the resultant is\nprojected along the basis vectors using attitude data in the maneuver object.\nFigure~\\ref{figure:ManeuverFlow} illustrates this flow.\n\n\\begin{figure}\n\\begin{center}\n\\includegraphics[scale=0.5]{Images/Maneuverflow.eps}\n\\caption{\\label{figure:ManeuverFlow}Calculating the Direction Used for Maneuvers}\n\\end{center}\n\\end{figure}\n\n\\subsection{Parameters}\n\nMany of the parameters that GMAT can calculate are computed based on the coordinate system of the\ninput data; in some cases this dependency uses the full coordinate system, and in other cases, it\nuses the origin or central body of the coordinate system. The Parameter subsystem contains flags for\neach parameter taht are used to indicate the level of coordinate system information required for\nthat parameter. These flags indicate if the parameter is specified independently from the coordinate\nsystem, depends only on the origin of a coordinate system, or depends on a fully specified\ncoordinate system.\n\n\\subsection{Coordinate Systems and the GUI }\n\n\\subsubsection{\\label{sub:OpenGLViewPoints}OpenGL ViewPoints}\n\nThe OpenGL visualization component in the first three GMAT builds set the Earth at the center of the\ndisplay view and allowed users to move their Earth-pointing viewpoint to different locations. The\nincorporation of coordinate systems into the code opens GMAT to a greatly expanded visualization\ncapability in this component. Users can set the viewing direction to point towards any SpacePoint or\nan offset from that direction. Users can also set the viewpoint location to either a point in space,\nto the origin of any defined coordinate system, or to locations offset from any specified\nSpacePoints. The latter capability allows the OpenGL view to follow the motion of the entities\nmodeled in GMAT.\n\n\\subsubsection{New Panels}\n\nGMAT needs a new GUI panel used to configure coordinate system objects.\n\n\\subsubsection{Panel Changes}\n\nSeveral of the existing GUI panels in GMAT will change once the Coordinate System classes are\nfunctional. Both the report file and the X-Y plot components use parameter data to produce output.\nThe configuration panels for these elements needs the ability to specify either the coordinate\nsystem or the origin for the calculated data that requires these elements. One way to add this\ncapability to the GUI is shown in Figure~\\ref{figure:ParameterSubpanel}. As different parameters\nare selected, the {}``Coordinate System'' and {}``Coordinate Origin'' comboboxes become active or\ndisabled ({}``grayed out''), depending on the needs of the selected parameter.\n\n\\begin{figure}\n\\begin{center}\n\\includegraphics[scale=0.5]{Images/ParameterSubpanel.eps}\n\\caption{\\label{figure:ParameterSubpanel}The Updated Parameter Subpanel}\n\\end{center}\n\\end{figure}\n\nThe propagator subsystem needs information about the global origin for the forces in a force model.\nFigure~\\ref{figure:PropPanelUpdate} shows one way to add this data to the panel.\n\n\\begin{figure}\n\\begin{center}\n\\includegraphics[scale=0.5]{Images/PropPanel.eps}\n\\caption{\\label{figure:PropPanelUpdate}Addition of the Propagation Origin}\n\\end{center}\n\\end{figure}\n\nThe OpenGL panel needs to be updated to allow configuration of the capabilities described in Section\n\\ref{sub:OpenGLViewPoints}. Users can use the settings on this panel to specify both the coordinate\nsystem used to plot the mission data and the location and orientation of the viewpoint used to\nobserve these data. In some cases, the viewpoint will not be a fixed point in space -- for example,\nusers will be able to view a spacecraft's environment in the simulation by specifying the location\nand orientation of the viewpoint relative to the spacecraft in a spacecraft centered coordinate\nsystem, and thus observe how other objects move in relation to that spacecraft.\n\n\\section{Validation}\n\nIn this section, several tables are presented that show the data for a single state in several\ndifferent coordinate systems. GMAT tests will be run that transform between these systems and\nvalidates that the conversions are in agreement with the data in the tables to an acceptable level\nof precision. The test data were generated in Astrogator by GSFC, Code 595. This output should be in\nagreement with GMAT results to at least one part in $10^{12}$. (Subject to change once tests are run\n-- seems like a good value as a starting point.)\n\n\\subsection{Tests for a LEO}\n\nTable~\\ref{table:LEOTests} lists the expected state data for a spacecraft orbiting near the Earth.\n\n\\begin{table}\n\\caption{\\label{table:LEOTests}Coordinate Conversions for an orbit near the Earth}\n\\centerline{\n%\\begin{sidewaystable}\n\\begin{tabular}{|p{1.4in}|c|c|c|c|c|c|}\n\\hline\n\\multicolumn{7}{|c|}{\\textbf{A LEO State}}\\tabularnewline\n\\hline\n\\hline\n\\textbf{Epoch:}&\n\\multicolumn{2}{c|}{UTC Gregorian}&\n\\multicolumn{2}{c|}{UTC Julian}&\n\\multicolumn{2}{c|}{Ephemeris Time}\\tabularnewline\n\\hline\n\\hline\n&\n\\multicolumn{2}{c|}{1 Jan 2005 12:00:00.00}&\n\\multicolumn{2}{c|}{2453372}&\n\\multicolumn{2}{c|}{2453372.00074287}\\tabularnewline\n\\hline\n\\hline\n\\textbf{Coordinate System}&\n\\textbf{X}&\n\\textbf{Y}&\n\\textbf{Z}&\n$V_{x}$&\n$V_{y}$&\n$V_{z}$\\tabularnewline\n\\hline\n\\hline\n{\\footnotesize Earth Centered Mean J2000 Equator}&\n{\\footnotesize 15999.999999999998}&\n{\\footnotesize 0.0000000000000}&\n{\\footnotesize 0.0000000000000}&\n{\\footnotesize 0.0000000000000}&\n{\\footnotesize 3.8662018270519716}&\n{\\footnotesize 3.8662018270519711}\\tabularnewline\n\\hline\n{\\footnotesize Earth Centered Fixed}&\n{\\footnotesize 3100.7006422193112}&\n{\\footnotesize 15696.674760971226}&\n{\\footnotesize 7.54822029656669}&\n{\\footnotesize -2.6485022470204602}&\n{\\footnotesize 0.5213224286561129}&\n{\\footnotesize 3.8663431768510996}\\tabularnewline\n\\hline\n{\\footnotesize Earth Centered Mean Ecliptic of Date}&\n{\\footnotesize 15999.988100569937}&\n{\\footnotesize 19.513619701949061}&\n{\\footnotesize 0.0163246416692983}&\n{\\footnotesize -0.0062037647908650}&\n{\\footnotesize 5.0850309969931660}&\n{\\footnotesize 2.0093417847447261}\\tabularnewline\n\\hline\n{\\footnotesize Earth Centered Mean Ecliptic of J2000}&\n{\\footnotesize 15999.999999999998}&\n{\\footnotesize 0.0000000000000}&\n{\\footnotesize 0.0000000000000}&\n{\\footnotesize 0.0000000000000}&\n{\\footnotesize 5.0850575916827729}&\n{\\footnotesize 2.0092840576358051}\\tabularnewline\n\\hline\n{\\footnotesize Earth Centered Mean of Date }&\n{\\footnotesize 15999.9881005699370}&\n{\\footnotesize 17.8969907643261870}&\n{\\footnotesize 7.7768465297859297}&\n{\\footnotesize -0.0062037647908650}&\n{\\footnotesize 3.8661983573941092}&\n{\\footnotesize 3.8662003193814876}\\tabularnewline\n\\hline\n\\end{tabular}\n%\\end{sidewaystable}\n}\n\\end{table}\n\n\\subsection{Tests for a Libration Point State}\n\nTable~\\ref{table:L2Tests} lists the expected state data for a spacecraft flying near the Earth-Sun.\n\n\\begin{table}\n\\caption{\\label{table:L2Tests}Coordinate Conversions for an orbit near the Earth/Moon-Sun L2 Point}\n\\centerline{\n%\\begin{sideways}\n\\begin{tabular}{|p{1.25in}|c|c|c|c|c|c|}\n\\hline\n\\multicolumn{7}{|c|}{\\textbf{A L2 State}}\\tabularnewline\n\\hline\n\\hline\n\\textbf{Epoch:}&\n\\multicolumn{2}{c|}{UTC Gregorian}&\n\\multicolumn{2}{c|}{UTC Julian}&\n\\multicolumn{2}{c|}{Ephemeris Time}\\tabularnewline\n\\hline\n\\hline\n&\n\\multicolumn{2}{c|}{25 Sep 2003 16:22:47.94}&\n\\multicolumn{2}{c|}{2452908.18249931}&\n\\multicolumn{2}{c|}{2452908.18324218}\\tabularnewline\n\\hline\n\\hline\n\\textbf{Coordinate System}&\n\\textbf{X}&\n\\textbf{Y}&\n\\textbf{Z}&\n$V_{x}$&\n$V_{y}$&\n\\textbf{$V_{z}$}\\tabularnewline\n\\hline\n\\hline\n{\\footnotesize Earth Centered Mean J2000 Equator}&\n{\\footnotesize 1152413.9609139508}&\n{\\footnotesize 164482.90400985131}&\n{\\footnotesize -270853.37069837836}&\n{\\footnotesize -0.0237491328055502}&\n{\\footnotesize 0.5463496092937017}&\n{\\footnotesize 0.1896952705370667}\\tabularnewline\n\\hline\n{\\footnotesize Sun-Earth/Moon Barycenter L1}&\n{\\footnotesize 2659568.8530356660}&\n{\\footnotesize -467.97516783879695}&\n{\\footnotesize -314259.10186388291}&\n{\\footnotesize -0.0062197634008832}&\n{\\footnotesize 0.3610507604664427}&\n{\\footnotesize -0.0425806711166933}\\tabularnewline\n\\hline\n{\\footnotesize Sun-Earth L2}&\n{\\footnotesize -352659.29964214563}&\n{\\footnotesize -0.0002161438986659}&\n{\\footnotesize -313927.71991658572}&\n{\\footnotesize 0.0027515868356648}&\n{\\footnotesize 0.3488514802312706}&\n{\\footnotesize -0.0432916179713184}\\tabularnewline\n\\hline\n{\\footnotesize Solar System Barycenter Mean J2000 Earth Equator}&\n{\\footnotesize 151524360.68432158}&\n{\\footnotesize 4848014.2434389694}&\n{\\footnotesize 1751879.7152567047}&\n{\\footnotesize -1.6146582474186386}&\n{\\footnotesize 27.776726415749529}&\n{\\footnotesize 11.995657174332731}\\tabularnewline\n\\hline\n\\end{tabular}\n%\\end{sideways}\n}\n\\end{table}\n\n\\subsection{Tests for an Earth-Trailing State}\n\nTable~\\ref{table:EarthTrailingTests} lists the expected state data for a deep space object trailing\nbehind the Earth.\n\n\\begin{table}\n\\caption{\\label{table:EarthTrailingTests}Coordinate Conversions for an Earth-Trailing\nstate}\n\\centerline{\n%\\begin{sideways}\n\\begin{tabular}{|p{1.25in}|c|c|c|c|c|c|}\n\\hline\n\\multicolumn{7}{|c|}{\\textbf{An Earth-Trailing State}}\\tabularnewline\n\\hline\n\\hline\n\\textbf{Epoch:}&\n\\multicolumn{2}{c|}{UTC Gregorian}&\n\\multicolumn{2}{c|}{UTC Julian}&\n\\multicolumn{2}{c|}{Ephemeris Time}\\tabularnewline\n\\hline\n\\hline\n&\n\\multicolumn{2}{c|}{1 Jan 2012 00:00:00.00}&\n\\multicolumn{2}{c|}{2455927.5}&\n\\multicolumn{2}{c|}{2455927.50074287}\\tabularnewline\n\\hline\n\\hline\n\\textbf{Coordinate System}&\n\\textbf{X}&\n\\textbf{Y}&\n\\textbf{Z}&\n$V_{x}$&\n$V_{y}$&\n$V_{z}$\\tabularnewline\n\\hline\n\\hline\n{\\footnotesize Earth Centered Mean J2000 Equator}&\n{\\footnotesize 18407337.2437560}&\n{\\footnotesize 146717552.364272}&\n{\\footnotesize 2436998.6080801622}&\n{\\footnotesize -29.85775713588113}&\n{\\footnotesize 3.7988731566283533}&\n{\\footnotesize -0.0883535323140749}\\tabularnewline\n\\hline\n{\\footnotesize Earth Centered Mean Ecliptic of Date}&\n{\\footnotesize 18010745.506277718}&\n{\\footnotesize 135634904.81496251}&\n{\\footnotesize -56121251.238084592}&\n{\\footnotesize -29.8677194647804920}&\n{\\footnotesize 3.3629312165175098}&\n{\\footnotesize -1.5921471032003145}\\tabularnewline\n\\hline\n{\\footnotesize Earth Centered Mean Ecliptic of J2000}&\n{\\footnotesize 18407337.2437560}&\n{\\footnotesize 135580104.86024788}&\n{\\footnotesize -56124988.196549937}&\n{\\footnotesize -29.8577571358811300}&\n{\\footnotesize 3.4502529604822207}&\n{\\footnotesize -1.5921677410083135}\\tabularnewline\n\\hline\n{\\footnotesize Solar System Barycenter Mean J2000 Earth Equator}&\n{\\footnotesize -7095223.559007301}&\n{\\footnotesize 279535881.30854195}&\n{\\footnotesize 60015670.739229225}&\n{\\footnotesize -59.6890476068945470}&\n{\\footnotesize -0.969033406060170}&\n{\\footnotesize -2.1549980100429815}\\tabularnewline\n\\hline\n{\\footnotesize Sun Centered Earth Equator Mean J2000}&\n{\\footnotesize -6610248.770514084}&\n{\\footnotesize 279718577.50517684}&\n{\\footnotesize 60095016.884433664}&\n{\\footnotesize -59.6964420074725410}&\n{\\footnotesize -0.9617072219755838}&\n{\\footnotesize -2.1516618821901923}\\tabularnewline\n\\hline\n{\\footnotesize Venus Centered Fixed}&\n{\\footnotesize 234671807.87997022}&\n{\\footnotesize -184530264.43020287}&\n{\\footnotesize -49090196.384031780}&\n{\\footnotesize 87.7042809962516540}&\n{\\footnotesize 130.412316317457850}&\n{\\footnotesize -3.652395853117925}\\tabularnewline\n\\hline\n{\\footnotesize Moon Centered Fixed}&\n{\\footnotesize -28218680.593746454}&\n{\\footnotesize -133515637.46513638}&\n{\\footnotesize -56782561.270103499}&\n{\\footnotesize -325.9434285713376800}&\n{\\footnotesize 70.716401043687014}&\n{\\footnotesize -2.3269361125638657}\\tabularnewline\n\\hline\n{\\footnotesize Moon Centered Inertial Moon Equator}&\n{\\footnotesize 18009331.473252095}&\n{\\footnotesize 146686558.45310178}&\n{\\footnotesize 2386670.4083221816}&\n{\\footnotesize -29.7707871076046790}&\n{\\footnotesize 2.8992895961634191}&\n{\\footnotesize -0.4430059951218515}\\tabularnewline\n\\hline\n{\\footnotesize Jupiter Centered Inertial Jupiter Equator}&\n{\\footnotesize -562256455.23257434}&\n{\\footnotesize -225513430.99244595}&\n{\\footnotesize -25746106.471387718}&\n{\\footnotesize -50.5813599808322610}&\n{\\footnotesize -13.854862630504574}&\n{\\footnotesize -0.5555336109134552}\\tabularnewline\n\\hline\n{\\footnotesize Mars Centered Inertial Mars Equator}&\n{\\footnotesize 207783148.71266919}&\n{\\footnotesize -43368297.655312374}&\n{\\footnotesize 13161295.341311477}&\n{\\footnotesize -19.7427310285643220}&\n{\\footnotesize 35.2164929323613260}&\n{\\footnotesize -21.767269119097524}\\tabularnewline\n\\hline\n{\\footnotesize Mars Centered Fixed}&\n{\\footnotesize 127577563.32704885}&\n{\\footnotesize -169644368.24313599}&\n{\\footnotesize 13138473.444519326}&\n{\\footnotesize -12016.3787728729480}&\n{\\footnotesize -9003.4840556769759}&\n{\\footnotesize -21.769072220711045}\\tabularnewline\n\\hline\n\\end{tabular}\n%\\end{sideways}\n}\n\\end{table}\n\n\\section{Some Mathematical Details}\n\n\\textbf{This section will probably appear in some form in the mathematical specifications. I'm\nleaving it here until I can confirm that assumption.}\n\nA spatial coordinate system is fully specified by defining the origin of the system and two\northogonal directions. Given these pieces of data, space can be gridded into triplets of numbers\nthat uniquely identify each point. The purpose of this section is to provide some guidance into how\nto proceed with the definition of the coordinate system axes once the origin and two directions are\nspecified.\n\n\\subsection{Defining the Coordinate Axes}\n\nThe coordinate system axes are defined from the two orthogonal directions in the system\nspecification. These directions are given two of the three labels $\\hat{X}$, $\\hat{Y}$, and\n$\\hat{Z}$. These labels are used to define the corresponding directions for the coordinate\nsystem. The third axis is calculated by taking the inner product of the other two axes, using\n\\begin{eqnarray}\n\\hat{X} & = & \\hat{Y}\\times\\hat{Z}\\nonumber \\\\\n\\hat{Y} & = & \\hat{Z}\\times\\hat{X}\\nonumber \\\\\n\\hat{Z} & = & \\hat{X}\\times\\hat{Y}\\label{eq:UnitVectorTriplets}\\end{eqnarray}\n\n\\subsection{Setting Directions in GMAT}\n\nThe principal directions for a coordinate system are set in GMAT by specifying a primary direction\nand a secondary direction. The specified secondary axis need not be orthogonal (i.e. perpendicular)\nto the primary axis. Given a primary direction $\\vec{P}$ and a secondary direction $\\vec{S}$, the\nprimary axis is oriented along a unit vector given by\n\\begin{equation}\\hat{P}=\\frac{\\vec{P}}{\\left|\\vec{P}\\right|}\\end{equation}\n\nThe unit vector defining the secondary axis is constructed by projecting the secondary direction\n$\\vec{S}$ into the plane perpendicular to the primary direction, and unitizing the resulting vector.\nThis is done by calculating\n\\begin{equation} \\hat{S}=\\frac{\\vec{S}-\\left(\\vec{S}\\cdot\\hat{P}\\right)\\hat{P}}{\\left|\\vec{S}\n-\\left(\\vec{S}\\cdot\\hat{ P}\\right)\\hat{P}\\right|}\\end{equation}\n\nIn general, two points are needed to specify a direction.\n", "meta": {"hexsha": "46c2d87e47d028bfd64b65f816d9c9849ad82425", "size": 47306, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/SystemDocs/ArchitecturalSpecification/CoordinateSystems.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/ArchitecturalSpecification/CoordinateSystems.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/ArchitecturalSpecification/CoordinateSystems.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": 43.6805170822, "max_line_length": 100, "alphanum_fraction": 0.7989895574, "num_tokens": 12072, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795672, "lm_q2_score": 0.3451052574867685, "lm_q1q2_score": 0.18197970457793314}}
{"text": "\\documentclass{ximera}\n\\input{../preamble}\n\\title{Integration by Parts}\n%%%%%\\author{Philip T. Gressman}\n\n\\begin{document}\n\\begin{abstract}\nWe study the integration technique of integration by parts.\n\\end{abstract}\n\\maketitle\n\n\\section*{(Video) Calculus: Single Variable}\n\n\\youtube{xWm3b8GWHrg}\n\n\\section*{Online Texts}\n\\begin{itemize}\n\\item \\link[OpenStax II 3.1: Integration by Parts]{https://openstax.org/books/calculus-volume-2/pages/3-1-integration-by-parts}\n\\item \\link[Ximera OSU: Integration by Parts]{https://ximera.osu.edu/mooculus/calculus2/integrationByParts/titlePage}\n\\item \\link[Community Calculus 8.4: Integration by Parts]{https://www.whitman.edu/mathematics/calculus_online/section08.04.html}\n\\end{itemize}\n\n\\section*{Examples}\n\n\n\\begin{example}\nCompute the indefinite integral\n\\[ \\int x e^{3x} dx. \\]\n\\begin{itemize}\n\\item Because integrating $e^{3x}$ and differentiating $e^{3x}$ are at a similar level of difficulty, we opt to differentiate $x$ so that its degree as a polynomial will be decreasing.\n\\item This gives\n\\[ \\int x e^{3x} dx = \\answer{\\frac{1}{3} x e^{3x}} - \\int \\answer{ \\frac{1}{3} e^{3x} } dx = \\answer{ \\frac{1}{3} x e^{3x} - \\frac{1}{9} e^{3x} } + C. \\]\n\\end{itemize}\n\\end{example}\n\n\n\\begin{example}\nCompute the indefinite integral\n\\[ \\int x^2 \\ln |x| dx. \\]\n\\begin{itemize}\n\\item Because integrating $\\ln |x|$ is much harder than differentiating it, we choose to differentiate $\\ln |x|$ and integrate $x^2$. \n\\item This gives\n\\[ \\int x^2 \\ln |x| dx = \\answer{\\frac{x^3}{3}} \\ln |x| - \\int \\answer{\\frac{x^2}{3}} dx = \\answer{ \\frac{x^3}{3} \\ln |x| - \\frac{x^3}{9}} + C. \\]\n\\end{itemize}\n\\end{example}\n\n\n\\begin{example}\nCompute the indefinite integral\n\\[ \\int x^4 e^{2x} dx. \\]\n\\begin{itemize}\n\\item We'll do this using an organizational technique called ``tabular integration'' that many people find helpful when doing repeated integrations by parts.\n\\item Make a table: one column for $u$ and another for $dv$. In the first row, rewrite the functions that you will use for $u$ and $dv$:\n\\begin{center}\n\\begin{tabular}{ccc}\n & $u$ & $dv$ \\\\\n \\hline\n& $\\displaystyle x^4$ & $\\displaystyle e^{2x}$ \n\\end{tabular}\n\\end{center}\n\\item Add new rows: differentiate items in the $u$ column and integrate items in the $dv$ column to determine what items go in the next row. \n\\begin{center}\n\\begin{tabular}{ccc}\n & $u$ & $dv$ \\\\\n \\hline\n& $\\displaystyle x^4$ & $\\displaystyle e^{2x}$ \\\\\n& $\\displaystyle 4 x^3$ & $\\displaystyle e^{2x}/2$ \\\\\n& $\\displaystyle \\answer{12 x^2}$ & $\\displaystyle \\answer{e^{2x}/4}$ \\\\\n& $\\displaystyle \\answer{24 x}$ & $\\displaystyle \\answer{e^{2x}/8}$ \\\\\n& $\\displaystyle \\answer{24}$ & $\\displaystyle \\answer{e^{2x}/16}$ \\\\\n\\end{tabular}\n\\item Now you combine terms by matching items in the first column with items \\textit{one row down}. For the last item in the $u$ column, match it with the last item in the $dv$ column (which you'll end up using twice):\n\\[ \\begin{aligned} x^4 \\cdot \\frac{e^{2x}}{2}, \\qquad {4 x^3} & \\cdot \\answer{\\frac{e^{2x}}{4}}, \\qquad \\answer{12 x^2} \\cdot \\answer{\\frac{e^{2x}}{8}}, \\\\ & \\answer{24 x} \\cdot \\answer{\\frac{e^{2x}}{16}}, \\qquad \\answer{24} \\cdot \\answer{\\frac{e^{2x}}{16}} \\end{aligned} \\]\n\\end{center}\n\\item To finish, you alternate addition and subtraction. Give a $+$ to the first term, a $-$ to the second, and so on. Last but not least, put an integral on the last term as well:\n\\[ + x^4 \\frac{e^{2x}}{2} - \\answer{4 x^3 \\frac{e^{2x}}{4}} + \\answer{12 x^2 \\frac{e^{2x}}{8}} - \\answer{24 x\\frac{e^{2x}}{16} }+ \\int \\answer{24 \\frac{e^{2x}}{16}} dx \\]\nIn this way, we arrive at the formula\n\\[ \\int x^4 e^{2x} dx = \\frac{1}{2} x^4 e^{2x} - x^3 e^{2x} + \\frac{3}{2} x^2 e^{2x} - \\frac{3}{2} x e^{2x} + \\int \\frac{3}{2} e^{2x} dx \\]\n\\item Sometimes the integrand of the last term is zero. This would happen when $u$ is a polynomial if you have enough lines in your table. In that case there would be nothing else to compute. (We stopped one line short of that point on purpose in this example to show how you would handle a case where there the last term \\textit{isn't} zero.)\n\\item In this case, the final answer is\n\\[ \\int x^4 e^{2x} dx = \\frac{1}{2} x^4 e^{2x} - x^3 e^{2x} + \\frac{3}{2} x^2 e^{2x} - \\frac{3}{2} x e^{2x} + \\frac{3}{4} e^{2x} +C \\]\n\\end{itemize}\n\\end{example}\n\n\n\\begin{example}\nCompute the indefinite integral below using tabular integration:\n\\[ \\int \\cos 3x \\cos 5x ~dx \\]\n\\begin{itemize}\n\\item Let us take $u = \\cos 3x$ and $dv = \\cos 5x$ (it would have been fine to choose them the other way around as well). The table is then\n\\begin{center}\n\\begin{tabular}{ccc}\n& $u$ & $dv$ \\\\\n\\hline\n& $\\answer{\\cos 3x}$ & $\\answer{\\cos 5x}$ \\\\\n& $\\answer{-3 \\sin 3 x}$ & $\\answer{(\\sin 5x)/5}$ \\\\\n& $\\answer{-9 \\cos 3x}$ & $\\answer{-(\\cos 5x)/25}$\n\\end{tabular}\n\\end{center}\nWhich gives\n\\[ \\begin{aligned} \\int & \\cos 3x \\cos 5x ~dx = \\\\ & \\answer{ \\frac{1}{5} \\cos 3x \\sin 5x} - \\answer{\\frac{3}{25} \\sin 3x \\cos 5x} + \\int \\answer{\\frac{9}{25} \\cos 3x \\cos 5x} ~dx. \\end{aligned} \\]\n\\item This example has a twist: the integral on the right-hand side is just a constant times the integral on the left-hand side. This indicates that further integrations by parts would be unfruitful because you'd end up in something like a cycle. What you \\textit{can} do is \\textit{solve} for the answer by moving both integrals to the left side of the equation and then combining like terms:\n\\[ \\answer{\\frac{16}{25}} \\int \\cos 3x \\cos 5x ~dx = \\answer{ \\frac{1}{5} \\cos 3x \\sin 5x} - \\answer{\\frac{3}{25} \\sin 3x \\cos 5x} \\]\nand therefore\n\\[ \\int \\cos 3x \\cos 5x ~ dx = \\answer{ \\frac{5}{16} \\cos 3x \\sin 5x - \\frac{3}{16} \\sin 3x \\cos 5x} + C. \\]\n\\end{itemize}\n\\end{example}\n\n\n\\end{document}\n", "meta": {"hexsha": "dd7c9cfbc192be1f0635bb18e75cf6be690532e1", "size": 5702, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "techniques/09ibpwarm.tex", "max_stars_repo_name": "ptgressman/math104", "max_stars_repo_head_hexsha": "3b797f5622f6c7b93239a9a2059bd9e7e1f1c7c0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "techniques/09ibpwarm.tex", "max_issues_repo_name": "ptgressman/math104", "max_issues_repo_head_hexsha": "3b797f5622f6c7b93239a9a2059bd9e7e1f1c7c0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "techniques/09ibpwarm.tex", "max_forks_repo_name": "ptgressman/math104", "max_forks_repo_head_hexsha": "3b797f5622f6c7b93239a9a2059bd9e7e1f1c7c0", "max_forks_repo_licenses": ["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.3693693694, "max_line_length": 394, "alphanum_fraction": 0.6641529288, "num_tokens": 2027, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47268347662043286, "lm_q2_score": 0.38491214448393346, "lm_q1q2_score": 0.18194161064809203}}
{"text": "\\input{../header.tex}\n\\title{\\vspace{-2cm}INF3490/INF4490 Exercise Solutions - Support Vector Machines}\n\\author{Eivind Samuelsen\\input{../author_footnote.tex}}\n\\date{}\n\n% Removing paragraph indents is sometimes useful:\n\\setlength\\parindent{0pt}\n% ==============================================================================\n\n% ================================= DOCUMENT ===================================\n\\begin{document}\n \\renewcommand\\marginsymbol[1][0pt]{%\n \\tabto*{0cm}\\makebox[-1cm][c]{$\\mathbb{P}$}\\tabto*{\\TabPrevPos}}\n\n\\maketitle\n\\input{../intro.tex}\n\n\\section{SVM vs MLP}\nWhat advantages and disadvantages are there to support vector machines (svm) versus multilayer perceptrons (mlp)?\nWhat problems do they both suffer from?\\\\\n\n\\textit{Answer:}\n\nAdvantages of SVM:\n\\begin{itemize}\n \\item Guarantees optimal separation\n \\item Usually gives better classification performance\n\\end{itemize}\nDisadvantages of SVM:\n\\begin{itemize}\n \\item Need to decide on an appropriate kernel function\n \\item Training is slow on really large training sets (SVM is at leas O(\\(n^2\\)), while neural net training is O(\\(n\\) on the size of the training data)\n\\end{itemize}\nProblems with both:\n\\begin{itemize}\n \\item Both ave several parameters to tune which may have pretty unintuitive effects\n \\item Both are prone to overfitting\n\\end{itemize}\n\n\\section{Kernel functions}\nWhat is a kernel function?\nWhich are the most common kernel functions and roughly what kind of transformations do they correspond to?\\\\\n\n\\textit{Answer:}\n\nA support vector machine kernel is a function that rolls the transformation of two points and subsequent inner product between the transformed points into one.\nUsually, the transformation maps the points into a higher dimensionality, and the inner product is the scalar dot product \\(x \\dot y = \\sum\\limits_{i=1}^{n} x_i \\dot y_i\\).\n\nThis is done mainly because it simplifies calculation, because the kernel in most cases is less computationally intensive than doing the same one step at a time.\nA convenient byproduct is that it enables transformations that are well-defined, but physically impossible to calculate.\nThe most common kernels are:\n\\begin{itemize}\n \\item None: \\(x \\cdot y\\) - simply calculates the dot product, no transformation at all.\n \\item Polynomial: \\((1 + x \\cdot y)^p\\) - transformation into a polynomial space (e.g. \\([1,x,x^2,x^3,...,x^p]\\))\n \\item Radial basis function: \\(\\exp\\big(-\\frac{(x-y)^2}{2\\sigma^2}\\big)\\) or \\(\\exp\\big(-\\gamma(x-y)^2\\big)\\) - transformation into an infinite-dimensional space that has a \"smoothness\" that is controlled by \\(\\sigma\\).\n\\end{itemize}\n\n\\section{Soft Margins}\nWhat two factors must be balanced when using an SVM with soft margin?\\\\\n\n\\textit{Answer:}\n\nAn SVM with soft margin allows some of the training data to be misclassified.\nThis is done to avoid over-fitting to the (perhaps faulty) training data, but we would still like to get as much of the training data as possible outside of the margin.\nThis gives us two conflicting factors to worry about: Classifying training data right and avoid over-fitting.\n\n\\section{Ensemble}\nTry to come up with a few cases when using an ensemble of classifiers where it would be fine to just pick the most popular class, and where you would want to have the majority in favor of a single class or even full consensus.\\\\\n\n\\textit{Answer:}\n\nWhat cases where it would be wisest to not classify depends on how critical it is to have high precision: when in doubt, it is best to guess or refuse to give an opinion.\n\nExamples of cases where a guess should always be made includes cases where a faulty classification is harmless, like recommendations for movies or music.\nThe opposite case would be something like making medical diagnosis, where it is always better to ask a real doctor when there is disagreement in the ensemble.\n\n\\section{Principle Component Analysis}\nWhat is the motivation behind principle component analysis?\\\\\n\n\\textit{Answer:}\n\nThere are actually two main motivations:\n\\begin{itemize}\n \\item Make it easier to train a classifier because information is removed or make the classifier simpler and more efficient because of reduced computational complexity.\n \\item Make the data easier to visualize, to manually deduce patterns or to help tune some classifier.\n\\end{itemize}\n\n\\section{Covariance}\nWork out the covariance between the x and y dimensions of the following 2-dimensional data set.\nDescribe what the results indicate about the data.\n\n\\begin{table}[H]\n\\centering\n \\begin{tabular}{c|c|c|c|c|c}\n Index & 1 & 2 & 3 & 4 & 5 \\\\ \\hline\n x & 10 & 39 & 19 & 23 & 28 \\\\\n y & 43 & 13 & 32 & 21 & 20 \\\\ \\hline\n \\end{tabular}\n \\caption{Two-dimensional data set}\n \\label{tab:cov}\n\\end{table}\n\n\\textit{Answer:}\n\nThe covariance\\footnotemark is\n\\begin{equation}\n \\text{cov}_{xy} = \\frac{1}{n}\\sum\\limits_{i=1}^{n}(x_i-\\mu_x)(y_i-\\mu_y)\n\\end{equation}\nFirst we have to estimate the arithmetic means:\n\\begin{equation}\n \\mu = \\frac{1}{n}\\sum\\limits_{i=1}^{n}x_i\n\\end{equation}\n\\begin{align*}\n \\mu_x &= \\frac{1}{n}\\sum\\limits_{i=1}^{n}x_i = 23.8\\\\\n \\mu_y &= \\frac{1}{n}\\sum\\limits_{i=1}^{n}y_i = 25.8\n\\end{align*}\n\nCalculating the covariance by the formula above then gives us \\(\\text{cov}_{xy} = -96.44\\).\nThis indicates that there are some negative correlation between x and y, that y decreases when x increases, but to determine how large it is, one would have to calculate the variances for both x and y as well.\n\\footnotetext{Note: covariance of a sample should be calculated using \\(n-1\\) instead of \\(n\\).\nLearn more about samples and sample variance in \\textbf{\\href{https://www.khanacademy.org/math/ap-statistics/quantitative-data-ap/measuring-spread-quantitative/v/review-and-intuition-why-we-divide-by-n-1-for-the-unbiased-sample-variance}{\"Review and intuition why we divide by n-1 for the unbiased sample variance\" on khanacademy.org}}.}\n\n\\input{../contact.tex}\n\\end{document}\n% ==============================================================================\n", "meta": {"hexsha": "d35abbed30fca26d33f6ccd4676bbcc15b8165d0", "size": 6070, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "material/week8/inf3490-sol8.tex", "max_stars_repo_name": "mpambasange/MachineLearning", "max_stars_repo_head_hexsha": "8b813345264513a57934317b01e1311628dc5b01", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16, "max_stars_repo_stars_event_min_datetime": "2016-09-01T08:50:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T20:56:07.000Z", "max_issues_repo_path": "material/week8/inf3490-sol8.tex", "max_issues_repo_name": "olehermanse/INF3490-PythonAI", "max_issues_repo_head_hexsha": "8b813345264513a57934317b01e1311628dc5b01", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2016-10-20T09:36:19.000Z", "max_issues_repo_issues_event_max_datetime": "2017-08-29T00:28:54.000Z", "max_forks_repo_path": "material/week8/inf3490-sol8.tex", "max_forks_repo_name": "olehermanse/INF3490-PythonAI", "max_forks_repo_head_hexsha": "8b813345264513a57934317b01e1311628dc5b01", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15, "max_forks_repo_forks_event_min_datetime": "2016-10-31T12:30:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-15T12:12:50.000Z", "avg_line_length": 48.1746031746, "max_line_length": 337, "alphanum_fraction": 0.718121911, "num_tokens": 1571, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4339814648038986, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.18170669803104608}}
{"text": "\\documentclass[12pt]{article}\n\\usepackage{graphics}\n\\begin{document}\n\\setcounter{page}{0}\n\\thispagestyle{empty}\n\n\\section*{NYU Engineering Physics 1---Final Exam}\n\n\\vfill\n\n\\paragraph{Name:} ~\n\n\\paragraph{email:} ~\n\n\\vfill\n\nThis exam consists of seven problems. Write only in this booklet. Be\nsure to show your work.\n\n\\vfill\n\n\\emph{You must ensure that the proctor checks off your name on the\nattendance sheet when you hand in your exam. Your exam will\n\\textbf{not} be graded if your name is not checked off.}\n\n\\clearpage\n\n\\section*{Problem 1}\n\n(a) A block of mass $M$ slides down a plane inclined at an angle\n$\\theta$ to the horizontal. There is a coefficient of sliding\nfriction $\\mu$ between block and plane. What is the magnitude of the\nacceleration $a$ of the block down the plane? \\emph{Be sure to draw a\nfree-body diagram.}\n\n\\vfill\n\n(b) A \\emph{different} block of mass $M$ sits on the same plane. In\nthis case, the frictional force is so great that the block does not\nslide down the plane. What is the magnitude $f$ and direction of the\nfrictional force? Try to give your answer in terms of $M$, $g$ and\n$\\theta$ only.\n\n\\vfill ~\n\n\\clearpage\n\n\\section*{Problem 2}\n\nA major-league baseball pitcher can throw a baseball at about\n$90~\\mathrm{mi\\,hr^{-1}}$. Estimate the impulse $\\Delta p$ given to\nthe ball by the pitcher. Make an estimate of the work done $\\Delta W$\nby the pitcher on the ball during the throw. Use the work to figure\nout the average force $F$ applied by the pitcher to the ball in SI\nunits (Newtons). Does your answer seem reasonable? \\emph{Clearly\nstate your assumptions, and justify any that are non-trivial.}\n\n\\clearpage\n\n\\section*{Problem 3}\n\nDraw free-body diagrams for all the masses and pulleys in this\nmechanism. Find the tensions in all three strings and the\naccelerations of the two blocks.\n\\\\ \\rule{0.35\\textwidth}{0pt}\n\\resizebox{0.3\\textwidth}{!}{\\includegraphics{../mp/tackle_blocks.eps}}\n\\\\\nBe careful with your kinematic constraints (\\textit{ie,} the\nrelationship between the two accelerations), and assume that all the\nstrings and pulleys are massless and frictionless.\n\n\\clearpage\n\n\\section*{Problem 4}\n\n~\\hfill\\includegraphics{../mp/stick_n_force.eps}\\hfill~\\\\ A stick of\nmass $m$ and length $\\ell$, initially at rest, experiences a force $F$\nat one end, as shown, for a \\emph{very short} time $\\Delta t$. This\nimpulse causes the stick to move (translate) and to rotate. At what\nangular speed $\\omega$ does the stick end up rotating around its\ncenter of mass? Its moment of inertia is $(1/12)\\,m\\,\\ell^2$.\n\\emph{Assume this is happening in outer space; there is no gravity or\nfriction.} Use the center of mass as the reference point or axis for\nyour calculation.\n\n\\clearpage\n\n\\section*{Problem 5}\n\nA ``seconds'' pendulum has a period of exactly $2.000~\\mathrm{s}$.\n\n\\textsl{(a)}~If $g=9.797~\\mathrm{m\\,s^{-2}}$ in Austin Texas, how long\nshould a Texan make her or his seconds pendulum?\n\n\\vfill\n\n\\textsl{(b)}~If $g$ is 0.1~percent (a factor of 1.001) larger in\nParis, France, than in Austin, how different, in percent, should the\nlength of a Parisian's seconds pendulum be than a Texan's? Should it\nbe longer or shorter? \\emph{Note:} You can answer this question\nwithout getting part (a) correct.\n\n\\vfill ~\n\n\\clearpage\n\n\\section*{Problem 6}\n\nAt what radius $R$ from the center of the Earth (mass $M$) does a\ngeostationary (one orbit every $T=24$~h) satellite (mass $m$) orbit on\na uniform circular orbit? Solve this problem in three \\emph{easy}\nsteps.\n\n\\emph{Hint:} Every step in your calculation should have correct\ndimensions!\n\n\\textsl{(a)}~Write a symbolic expression for the acceleration $a$ of\n an object undergoing uniform circular motion with radius $R$ and\n period $T$.\n\n\\vfill\n\n\\textsl{(b)}~Use Newton's law of gravity ($F=G\\,M\\,m/r^2$) to write a\n symbolic expression for the acceleration due to gravity of an\n object with mass $m$ at radius $R$.\n\n\\vfill\n\n\\textsl{(c)}~Use the fact that $g=10~\\mathrm{m\\,s^{-2}}$ at the\n surface of the Earth ($R_E=6000$~km) to eliminate the quantity\n $G\\,M$ and solve for the radius of the orbit $R$. Give your answer\n in km.\n\n\\vfill ~\n\n\\clearpage\n\n\\section*{Problem 7}\n\nCompute---approximately---the terminal velocity of a penny dropped\nfrom the Empire State Building as follows.\n\n\\textsl{(a)}~The magnitude of the drag force $F_d$ depends on the\ndensity of air $\\rho$, speed of the penny $v$, and cross-sectional\narea of the penny $A$. What is the \\emph{only} combination of these\nquantities that has dimensions of force? Give a symbolic answer.\n\n\\vfill\n\n\\textsl{(b)}~Estimate the mass of the penny (it's made of metal), the\narea of the penny (assuming it falls face-on), the density of air,\netc., and find the (approximate) ``terminal'' falling speed\n$v_\\mathrm{term}$ at which the drag force cancels the gravitational\nforce. Give a numerical answer in m\\,s$^{-1}$.\n\n\\vfill\n\n\\textsl{(c)}~How much faster is the terminal speed when the penny\nfalls edge-on rather than face-on?\n\n\\vfill ~\n\n\\clearpage\n\n\\resizebox{\\textwidth}{!}{\\includegraphics{formulae.eps}}\n\n\\clearpage\n\n[This page intentionally left blank for calculations or other work.]\n\n\\end{document}\n", "meta": {"hexsha": "ac0e15eda48f048e052c4c7e6242c66a4d2ceacc", "size": 5182, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "tex/old/final_2004e.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/final_2004e.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/final_2004e.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": 30.1279069767, "max_line_length": 71, "alphanum_fraction": 0.7325357005, "num_tokens": 1493, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.476579651063676, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.18168148786500185}}
{"text": "\\chapter{Object Reconstruction and Event Generation}\n\\label{chap:event_sim}\n\\epigraph{Any one who considers arithmetical methods of producing random digits is, of course, in a state of sin. For, as has been pointed out several times, there is no such thing as a random number --- there are only methods to produce random numbers, and a strict arithmetic procedure of course is not such a method.}{\\textit{Jon von Neumann}}\n\\vskip 0.5in\n\\section{Introduction}\n\\label{intro}\nThis chapter is divided into two parts. In the first part, the procedure for the generation of simulated events is described. This is done in several distinct stages with the output of one stage serving as an input for the next. A suite of software packages, developed mostly by the particle and nuclear physics communities, is used to achieve this. This part concludes by detailing the simulated datasets used in the analyses described in this thesis. In the second part of this chapter, the reconstruction of physics objects is described in detail. It starts with a description of the particle-flow algorithm which is a global event reconstruction scheme for the entire event. This is followed by descriptions of track, muon and electron reconstructions. Reconstruction of jets is described next followed by description of composite objects used in the analysis such as collinear mass and transverse mass.\n \n\n\\section{Event simulation}\nA $pp$ collision at the LHC, like any hadronic collision, is more complex than the hard interaction of two participating partons. The proton being a composite object, the colliding partons from the hard interaction are accompanied by other quarks and gluons that interact and rearrange themselves into color singlets due to color confinement. A $pp$ collision thus consists of: the Hard Scattering which represents the part of the collision where two partons in the initial state interact by exchanging high transverse momentum, and the Underlying Event that represent the interaction of the everything else in the collision except the partons in hard scattering. In addition to the implementing the above, i.e. physics of a $pp$ collision that produces a bunch of final state particles, the event simulation also has to include interactions of these particles with the CMS detector. Monte Carlo methods, that use generation of random numbers to simulate sampling from a given probability distribution, are used to model the above event simulations~\\cite{mc_evtsim}.\n\n\\subsection{Monte Carlo method}\n\nMonte Carlo (MC) methods (named after a famous casino in the city state of Monaco) are a broad class of computational algorithms that rely on repeated random sampling to obtain numerical results~\\cite{mcwiki}. In particle physics, these methods play a key role in generation of events and are used primarily for : generation of samples from specified probability distributions, and the calculation of integrals. Programs which implement the above method, called MC event generators, use generation of random numbers to make decisions about physics processes. These can range from selection of processes that are generated in the collision, to which decay channel a particle decays in, to making decisions on how the particle interacts with detector material. Usually, each such decision is the result of a draw from a distribution which depends only on the current state the process is in, and not on previous states. The MC generator is provided as input the distributions that represent the physics of the generated particles, their production, their decay modes and their couplings. A MC generator starts by using a pseudo-random number generator that usually outputs a random number between 0 and 1. Although, true random number generation can only be done by physical processes, modern pseudo-random number generators are known to generate numbers with a high degree of randomness. Starting from this distribution, the MC event generator uses one of the various methods such as the inverse-transform method, or the rejection sampling method to convert this uniform distribution into a desired probability distribution, $p(x)$. It is then possible to generate random numbers according to this distribution to simulate physical processes. \n\n\n\\subsection{CMS simulation pipeline}\n\nThe MC simulation of events in CMS consists of the following sequential steps. The first step is simulation of the Hard Scattering. As mentioned earlier, this represents the primary hard interaction in a collision where two partons in the initial state interact by exchanging high transverse momentum resulting in a final state with two or more partons. The parton density function (pdf) which parametrizes the distributions of the partons inside each hadron are used to model the momenta of incoming partons. It represents the probability of finding a parton of a certain flavor at a certain longitudinal momentum fraction, when the hadron, that contains it, is probed at a certain scale. The PDF are extracted from fits to the data, mainly from ep collisions, and various PDF sets are available for each parton flavor. Commonly used pdf sets include ones provided by the CTEQ, HERA (H1 and ZEUS) and NNPDF collaborations. The LHAPDF library provides a unified C++ interface to all major PDF sets. The matrix element formulation is used to model the hard scattering process to leading order in perturbative QCD, or to higher orders depending on the generator. The next step is simulation of the parton shower. The hadronization and radiation of quarks and gluons in the initial and final states cannot be feasibly encapsulated in the matrix element computation. Parton shower describes these missing parts. The matrix element calculations are combined with the parton shower by one of the different matching schemes which ensure that there is no double counting of terms present in both the matrix element and the parton shower expansion. The matching schemes that are most often used are MLM~\\cite{mlm}, CKKW~\\cite{ckkw} and FxFx~\\cite{Frederix:2012ps}. The simulation of the Underlying Event comes next. Underlying event includes everything in the collision that is not associated with the primary hard scattering process. This consists mostly of soft QCD interactions, and implemented using the MC event generators and interfaced with the matrix element simulation. The hadronization of the quarks and gluons is simulated next and it consists of recombination of individual partons into colorless hadrons. Lastly, the decay of short-lived particles is simulated.\n\nAn important part of the event generation chain is the simulation of pileup. The protons circulate inside the LHC not as a continuous beam but in discrete closely packed bunches. This leads to more than one proton-proton collision per bunch crossing, i.e. pileup both in-time and out-of-time (see chapter~\\ref{chap:exper_setup}). Event generators add pile-up events to the hard scattering samples by randomly simulating soft inelastic collisions and overlapping them. The distribution of the number of pileup interactions in data is hard to predict. MC event generators usually produce events for a scenario with a higher number of pileup vertices, and with a flat distribution of number of vertices . This is afterwards reweighted to match the observed distribution of pileup interactions in data.\n\nSeveral MC generators have been developed. Some of these can produce all components of the above simulation pipeline while some calculate only the matrix element and need to be interfaced with other generators for the simulation of remaining parts. Pythia~\\cite{Sjostrand:pythia8} and Herwig~\\cite{herwig} can produce the entire chain while Powheg~\\cite{Nason:2004rx,Frixione:2007vw, Alioli:2010xd, Alioli:2010xa, Alioli:2008tz, Bagnaschi:2011tu}, aMC@NLO~\\cite{Alwall:2014} and Madgraph~\\cite{Alwall:2011uj} produce up to matrix element stage. Powheg and aMC@NLO can perform next-to-leading order calculations. \n\nFinally, the Geant4 (GEometry ANd Tracking)~\\cite{GEANT4} package is used to simulate the interaction of physical particles after the collision, produced by pipeline described above, with a sophisticated and complex simulation of the detector itself. This simulated detector response is used as input for the same physics reconstruction algorithms (described in the next section), that are used to reconstruct the data, thus enabling a direct comparison of the two. If differences are observed in the behavior of these reconstruction algorithms for MC events in comparison to observed data, the MC events are tuned to the behavior observed in data. \n\n\n\\section{MC samples used for the analyses}\n\\label{samples_mc}\n\nThe {ggH} and VBF Higgs boson samples are generated with POWHEG 2.0 while an extension of POWHEG 2.0~\\cite{Luisoni:2013kna} is used for the $\\PW\\PH$ and $\\PZ\\PH$ simulated samples. For the \\Hmue analysis, only the gluon fusion (ggH) production mode has been considered. Samples are generated for a range of H masses from 200 to 900 GeV.\n\nThe $\\zjets$ and $\\wjets$ processes are simulated using the \\aMCATNLO generator at leading order (LO) with the MLM jet matching and merging scheme. The same generator is also used for diboson production which is simulated at next-to-LO (NLO) with the FxFx jet matching and merging scheme. POWHEG 2.0 and 1.0 are used for top quark-antiquark ($\\ttb$) and single top quark production, respectively. The POWHEG and MADGRAPH generators are interfaced with PYTHIA 8 for parton showering, fragmentation, and decays. \n\nAs mentioned earlier in this chapter, additional pileup interactions are also a part of the MC generation pipeline. All simulated samples are reweighted to the pileup distribution observed in data. An event weight is applied based on the number of simulated pileup events and the instantaneous luminosity per bunch-crossing, averaged over the run period. Several other scale factors are used to reweight the events in order to get the MC simulation to match the data closely. These include scale factors based on trigger, lepton identification, lepton isolation and b-jet tagging efficiencies.\n\n\\section{Physics object reconstruction}\n\\label{p_ob_recon}\nThis section begins with the description of the particle-flow algorithm followed by reconstruction of tracks and vertices, electrons, muons, jets and other physics objects. \n\\subsection{Particle flow}\n\\label{p_flow}\nThe overarching algorithm used by CMS to produce a unified global (synchronized for all sub-detectors) description of an event is the particle-flow (PF) algorithm~\\cite{Sirunyan:2017ulk}. The idea behind the PF algorithm is that if the basic building blocks or elements from the various sub-detectors can be correlated in a well-defined way, then the description of the event and that of each particle in it can be refined by using the global information from the entire detector. The ALEPH experiment at the CERN LEP collider was the first experiment to use such a holistic approach towards event reconstruction. The CMS experiment, owing to its very granular layers of sub-detector, is the first hadron collider experiment to successfully use particle-flow. The first step of the PF algorithm is the linking of the several building-blocks or PF elements that a single particle can give rise to, across different sub-detector layers. The link algorithm tests pairs of neighbors in the $\\eta-\\phi$ plane and combines (links) them to form PF blocks. Reconstruction and identification algorithms are run according to a predefined sequence in each of these PF blocks. First, muon candidates are reconstructed and identified. If a muon candidate successfully passes PF quality criterion, the PF elements associated with it are removed from the block. Electron reconstruction proceeds next with electron candidates successfully becoming PF electrons if their tracks in the tracker, when extrapolated, have a corresponding energy deposit in the ECAL. The reconstruction procedure of muons, electrons and tracks are discussed in detail in the sections ~\\ref{mu_recon},~\\ref{track_recon},~\\ref{e_recon}. The PF block now consists of photons and hadrons. To reduce fake track identification, tracks with momentum uncertainty larger than the resolution of the calorimeters are removed at this stage. The remaining tracks are then associated with charged hadrons. The remaining calorimeter energy deposits are then associated with photons (ECAL) and hadrons (HCAL). In this manner, PF finally produces a list of all electrons, photons, muons, charged hadrons and neutral hadrons in the event with optimally determined direction, charge and energy. \n\n\n\n\\subsection{Track and primary vertex reconstruction}\n\\label{track_recon}\n\nTracks of charged particles, that traverse the CMS tracker (described in section~\\ref{tracker}), are reconstructed~\\cite{track_reconstruction} using hits from the pixel and strip detectors in the tracker. Hits are reconstructed by clustering signals above specified thresholds in the pixel and strip channels, and then estimating the cluster positions and uncertainties in a local orthogonal system plane of each sensor. During track reconstruction, a translation is made between the local coordinate system of these hits to the global coordinate system of the tracks. The software used to reconstruct tracks by CMS is called the Combinatorial Track Finder (CTF) and is adaptation of the Kalman filter~\\cite{kalman_filter}. Tracks are reconstructed using a iterative procedure with the basic idea being, tracks that are easiest to find (e.g., high $\\pt$ tracks, and tracks produced near the interaction region) are searched in the initial iterations, with subsequent iterations looking for more difficult sets of tracks (e.g., low $\\pt$ tracks , or tracks produced far from the interaction region). Hits unambiguously assigned to the track in the previous iterations are removed for the subsequent ones, thus reducing the combinatorial complexity. Each iteration can be divided into four sequential steps.\n\nThe first step is seed generation which provides initial track candidates that define the starting trajectory parameters and associated uncertainties of potential tracks. Charged particles follow helical paths in the quasi-uniform magnetic field of the tracker, requiring a total of five parameters to determine the trajectory. These five parameters are extracted using two or three hits in the inner region of the tracker. The seeds are constructed in the inner part (and then tracks constructed outwards, and not in the opposite manner) because the high granularity of pixel detectors (in contrast to outer strip layers) ensure that low fraction of channels are hit. Also, particles like pions and electrons interact inelastically with tracker material or lose energy due to bremsstrahlung radiation as they traverse through the tracker to its outer regions, making the idea of constructing seeds in the inner region a better choice.\n\nThe second step in track generation is track finding which is closely based on the Kalman filter. It extrapolates the seed trajectories along the expected path of a charged particle, beginning with an estimate of the track parameters provided by the trajectory seeds generated in the last step. It then uses the location and uncertainty of detected hits, and estimations of effects such as Coulomb scattering, at successive detector layers, to build track candidates, updating the parameters at each layer. First, using the parameters of the track candidate, evaluated at the current layer, an analytical extrapolation is done that determines which adjacent layers of the detector the trajectory can intersect. This takes into account the current uncertainty in that trajectory just like a Kalman filter. Secondly, a search is performed for silicon modules in these layers that are compatible with the extrapolated trajectory. All compatible modules in each layer are then grouped into mutually exclusive groups, such that no two modules in each group overlap. The collection of all hits from from one such module group forms a group of hits. Finally, new track candidates are formed by adding exactly one of the compatible hits from each group, to each original track candidate. The modules in a given group are mutually exclusive and a contribution of more than one hit from each group is not expected. The trajectory parameters of the new candidates are then updated by combining the information from the added hits with the extrapolated trajectory of the original track candidates. Figure~\\ref{fig:trackrecon} illustrates the reconstruction efficiency of tracks in case of isolated muons.\n\nThe third step in track generation track fitting. In this step the collection of hits from the last step are refitted using a Kalman filter and smoother, to provide a best possible estimate of parameters for each track trajectory. The procedure described above, in conditions as challenging as the LHC, can yields several fake tracks that are not associated with any charged particle passing through the tracker. The fourth and final step applies several quality requirements to the set of reconstructed tracks and substantially reduces the fake contribution. The requirements are based on criteria such as the minimum number of layers the track has hits in, how compatible its origin is with a primary vertex, how good a fit it yields etc.\n\n\\begin{figure*}\n\\begin{center}\n\\captionsetup{width=0.9\\textwidth,justification=centering}\n\\includegraphics[width=0.9\\textwidth,keepaspectratio]{plots_and_figures/chapter4/trackrecon.png}\n\\caption{Track reconstruction efficencies for single isolated muons as a function of $\\eta$ and \\pt~\\cite{track_reconstruction}.}\n\\label{fig:trackrecon}\n\\end{center}\n\\end{figure*}\n\n\nProton-proton interaction vertices are reconstructed by selecting tracks that are produced promptly in the primary interaction region. The selected tracks are then clustered on the basis of their z-coordinates at their point of closest approach to the centre of the beam spot, which represents a 3-D profile of the region where the LHC beams collide inside the CMS detector. The exact positions of the vertices are then obtained from these clustered candidates, by using a fitting procedure, called the adaptive vertex fitter~\\cite{vertex_fitting}. The vertex which has the largest sum of squared transverse momenta of tracks originating from it is considered the primary interaction vertex. \n\n\n\\subsection{Muon reconstruction}\n\\label{mu_recon}\nHits in the muon system (described in section~\\ref{muon_system}) and tracks (muons being charged particles leave tracks in the tracker) from the tracker are used to reconstruct muons~\\cite{muon_recon2018}. When muons traverse a muon subdetector (such as RPC, CSC or DT) in the muon system, they ionize the gas in the chambers. The electrical signals produced on the wires and strips as a consequence of the ionization are read out by electronics systems that associate these ``hits'' with well-defined locations in the detector. Various algorithms depending on the subdetector technology are used to reconstruct these hits. Reconstruction of muon tracks using these hits first proceeds independently of track reconstruction in the tracker. These tracks, called \\textit{standalone-muon tracks}, are built using these reconstructed hits from the muon system using a Kalman filter. Muon tracks are also built inside-out by propagating tracker tracks (described in previous section) with transverse momentum above 0.5 GeV to the muon system and matching them to (straight-line) segments of hits in DT or CSC. If a match is found, the tracker track qualifies as a \\textit{tracker muon track}. Muon tracks are also built outside-in by matching standalone-muon tracks with tracker tracks, and combining information from both using a Kalman filter fit. These are called \\textit{global muon tracks}. The global muon reconstruction is especially efficient for muons leaving hits in several muon stations. The \\textit{tracker muon} reconstruction is more efficient for low $\\pt$ muon candidates but it can cause fake muon tracks due to hadronic particles which \\textit{punch-through} to the innermost muon stations. The \\textit{global muon} reconstruction has high efficiency for muons penetrating through more than one muon station, and reduces the muon misidentification rate compared to tracker muons. Combining both \\textit{tracker muon tracks} and \\textit{global muon tracks}, the efficiency for reconstructing a muon is as high as 99\\%. The particle-flow algorithm applies a set of requirements, based on various quality parameters from muon reconstruction as well as information from other sub-detectors, to reconstructed candidates. The PF muon candidates used in the analyses described in this thesis were required to satisfy the following set of criterion to be identified as a muon:\n\n\\begin{itemize}\n\\item Must be a global muon or a tracker muon.\n\\item Must have at least one hit in the pixel subdetector of the tracker\n\\item $\\chi^2$ of the compatibility between the position of the standalone and trackers tracks $<12$\n\\item Transverse impact parameter of the associated tracker track with respect to the primary vertex $d_{xy}< 2 mm$\n\\item Longitudinal distance of the (origin of )associated tracker track with respect to the primary vertex $d_z <5 mm$\n\\item constraints on muon segment matching compatibility between tracker and muon system dependent on if it is a global muon\n\\end{itemize}\nThe efficiency of the above selection for muon identification is illustrated using a plot from a study performed by the CMS Muon Physics Object group in Fig.~\\ref{fig:muoneff}. As can be seen from the plots, there is a difference in the efficiencies in data and MC simulation. This is corrected using a set a of scale-factors applied as a function $\\eta$ and $\\pt$ to adjust the efficiency in simulation to get it to match the efficiency in data. \n\n\\begin{figure*}[!htpb]\n\\centering\n\\captionsetup{width=0.98\\textwidth,justification=centering}\n\\includegraphics[width=0.47\\textwidth]{plots_and_figures/chapter4/muoneffveta.png}\n\\includegraphics[width=0.49\\textwidth]{plots_and_figures/chapter4/muoneffvpt1.png} \\\\\n\\includegraphics[width=0.49\\textwidth]{plots_and_figures/chapter4/muoneffvpt2.png}\n\\includegraphics[width=0.49\\textwidth]{plots_and_figures/chapter4/muoneffvpt3.png} \n\\caption{Efficiency of muon identification as a function of $\\eta$ and $\\pt$, for data (black) and simulation (blue)~\\cite{muon_pog}}\n \\label{fig:muoneff}\n\\end{figure*} \n \nThe momentum of muons is measured by CMS using one among different possible ways involving the tracker and muon system~\\cite{muon_recon2012} and then using the PF algorithm to refine this measurement exploiting information from the full event.\n\n\n\n\\subsection{Electron reconstruction}\n\\label{e_recon}\nBesides muons, electron form the other primary part of the final state of the decay we are searching for in this thesis. Electrons, in the CMS, are reconstructed using clusters of energy formed in the ECAL (described in section ~\\ref{Ecal}) and associating them with tracks from the tracker~\\cite{e_recon}. The reconstruction of electrons is made complicated by the fact that they can radiate a significant amount of energy before reaching the ECAL. This happens due to the radiation of bremsstrahlung photons caused by the interaction of electrons with atoms as they pass through the tracker. This loss can range from 33\\% to as high as 86\\% depending on $\\eta$ (as a consequence of the fact that the amount of detector material the electron has to cross is $\\eta$ dependent). In order to measure the an electron's energy, clustering algorithms thus need to take into account the energy from these bremsstrahlung photon showers, together with the deposit made in the ECAL by the electron. The energy from these radiated photons spreads primarily in the $\\phi$ direction, owing to bend in electron trajectory in the magnetic field of CMS. The spread in the $\\eta$ direction is relatively small. These facts are used by the clustering algorithms.\n\nThe algorithm used to cluster the electron energy deposit in the ECAL barrel is called the \\textit{hybrid} algorithm. It exploits the above property of the electron shower shape, and uses the geometry of the ECAL to form clusters that are narrow in $\\eta$ direction but wide in $\\phi$ direction. Starting with a (seed) crystal containing the largest amount of energy deposited in a considered region above a certain threshold (1 GeV), it adds 5x1 arrays of crystals in $\\eta\\times\\phi$ around the seed crystals in both directions of $\\phi$ if the energy contained in the arrays is above another predefined threshold (0.1 GeV). Contiguous arrays are merged into clusters, and finally a electron supercluster is formed from all such strip clusters which have at least one seed strip with energy above another predefined threshold (0.35 GeV). The position of the supercluster is computed as the energy-weighted mean of the cluster positions, whereas its energy is simply taken as the sum of the energy of all its constituent clusters. In the ECAL endcap a different clustering algorithm is used owing to different geometrical arrangement of the crystals. This algorithm called the 5x5 algorithm starts similarly with a seed crystal with maximum energy in a local region, and satisfying the minimum energy requirement of 0.18 GeV. Clusters of 5x5 crystals are progressively grouped around the seed crystal, making a supercluster, if the total cluster energy exceeds 1 GeV and they are within $\\pm 0.7$ and $\\pm 0.3$ respectively in $\\eta$ and $\\phi$ around the seed crystal. The position and energy of the supercluster is calculated in the same manner as the barrel. The energy from the preshower is also added into the supercluster, using it's most energetic cluster and it's maximum distance in $\\phi$ to other clusters, and extrapolating it to the preshower plane to define the spread in the preshower. The thresholds used in the above algorithms were optimized using simulation and adjusted during data taking periods.\n\nThe standard track reconstruction (section~\\ref{track_recon}) is not efficient for electrons. This is because the standard approach is compromised by the large radiative losses in the tracker leading to a poor estimation of track parameters~\\cite{track_reconstruction}. Therefore, a dedicated tracking procedure is used for electron candidates that uses information not only from the tracker but also the ECAL. Just like the standard track reconstruction procedure, the first step in electron track reconstruction is seeding. This is done in two ways and the results are then combined. In the first method, superclusters from ECAL are used. As mentioned earlier, owing to strong magnetic field, the bremsstrahlung photons emitted by the electrons deposit energy in the ECAL at $\\eta$ values similar to that of the electron, but at different $\\phi$ leading to a spread. The ECAL supercluster algorithms described above recover this energy. The position and energy of these reconstructed superclusters along with the assumption that the electrons originated close to the center of the beam spot can be used to constrain the trajectory of the electron through the tracker. Hits in the first layers of the trackers compatible with these trajectories are deemed electron seeds. In the second method of seeding, the ``opposite'' is done. Tracks constructed by the regular tracking algorithm are extrapolated to the ECAL and matched with a supercluster. The seeds corresponding to such matching tracks are retained as electron seeds. The seed collections from these two methods are merged leading to a increase in overall efficiency of the seeding procedure. These seeds are then used to initiate electron track finding and fitting phases. This track finding procedure is similar to that used in standard tracking except for small adjustments. The $\\chi^2$ fit thresholds used by the Kalman filter to decide whether a hit is compatible with a trajectory (see section~\\ref{track_recon}) is weakened to accommodate tracks that deviate from their expected trajectory because of bremsstrahlung. Similar adjustments are made to the penalties assigned to track candidates for passing through a tracker layer without being assigned a hit. The final track fit uses a modified version of the Kalman filter, called the Gaussian Sum Filter (GSF), to account for the fact that the energy loss of an electron traversing the tracker material is non-Gaussian. This makes it unsuitable to use a conventional Kalman filter algorithm which assumes gaussian distribution. The GSF technique deals with this by approximating this non-Gaussian energy-loss distribution as the sum of several Gaussian functions, and is found to perform much better than the regular fitting procedure.\n\nFinally, electron candidates are constructed by associating a electron track (called GSF track) produced by the above procedure with a supercluster in the ECAL. For ECAL-seeded candidates this association is made by a geometrical matching in $\\eta-\\phi$, while for tracker-seeded candidates a multivariate (MVA) technique that combines information from supercluster and GSF track is used. The electron charge is estimated using a combination of three procedures involving the use of the GSF track curvature, use of ECAL supercluster position and its relative position in $\\phi$ to that of the first hit in the GSF track, and also by using KF tracks that have common hits with the GSF tracks. The combination of a best vote of three methods reduces the charge misidentification probability to 1.5\\% compared to 10\\% when using just the GSF track curvature method. Like other variables, the momentum of electrons is also estimated using a combination of tracker and ECAL measurements.\n\n\nFurther, several quality requirements are used on reconstructed electron candidates to identify (real/signal) electrons to suppress fake sources such as photon conversions, jets misidentified as electrons etc.\nThese requirements are based on variables that fall into three broad categories: variables that compare measurements from ECAL and the tracker, variables that come only from ECAL (such as transverse shape of electromagnetic showers, ratio of energy fractions deposited in the HCAL to the ECAL ) and purely tracking based variables (such as information from GSF track, difference between the information from GSF and KF-fitted tracks). These variables can be used in two ways: a cut-based method that uses the variables above directly to apply threshold requirements, or a multivariate (MVA) technique that uses all these variables as an input to a Boosted Decision Trees classifier to obtain a combined discriminator variable on which a threshold is applied. The BDT based method has much better performance as is illustrated in Fig~\\ref{fig:elec_eff}. Two separate BDTs are trained depending on whether electron is required to pass a HLT triggering requirement or it is not. The trigger selection used in the analyses described in this thesis uses trigger based on muons. The BDT based identification criterion for non-triggering electrons is thus used in this analysis. The threshold corresponding to the working point used in this analysis has an efficiency of approximately 80\\%. The difference in efficiencies of electron identification based on the above criteria in data and MC simulation is corrected using a set a of scaled factors, applied as a function $\\eta$ and $\\pt$. This adjusts the efficiency in simulation to get it to match the efficiency in data. \n \n\n\\begin{figure*}[!htpb]\n\\centering\n\\captionsetup{width=0.95\\textwidth,justification=centering}\n\\includegraphics[width=0.95\\textwidth]{plots_and_figures/chapter4/elec_eff.png}\n\\caption{Performance of the BDT-based electron identification algorithm (red dots) compared with results from several working points of cut-based selection for electron candidates in the ECAL barrel (left), and endcaps (right)~\\cite{e_recon}.}\n \\label{fig:elec_eff}\n\\end{figure*}\n\n\n\\subsection{Hadronic tau leptons}\n\\label{tau_recon}\nTau leptons decay hadronically in several ways or decay modes. The primary decay modes consist of: one charged hadron and up to two neutral pions, or three charged hadrons. The algorithm that is used to reconstruct hadronically decaying tau leptons in CMS is called the hadrons-plus-strips (HPS) algorithm~\\cite{Khachatryan:2015dfa,Sirunyan:tau16}. This algorithm proceeds in two steps. In the first step, the topology of the candidate is checked to match the topology of one of the decay modes. The second step consists of a MVA-based discriminator (built using variables such as lifetime information, decay mode etc.), that is used to reject electrons, muons, quarks or gluon jets wrongly identified as hadronic taus. The reconstruction efficiency is also improved, in the case of converted photons from a neutral-pion decay, by considering PF photons and electrons from a strip along the $\\phi$ direction. The final states in the analyses presented here do not contain hadronically decaying taus. Hence, all events which contain hadronically decaying taus are rejected.\n\n\n\\subsection{Jet reconstruction}\n\\label{jet_recon}\nJets are clusters of particles that are experimental signatures of quark and gluons which hadronize (due to color confinement) producing a narrow spray or ``jet'' of particles~\\cite{jet_recon}. Jets are reconstructed in CMS by clustering PF objects. In order to group together objects into a jet, CMS uses the anti-$k_{T}$ clustering algorithm. This belongs to a broader class of clustering algorithms called sequential clustering algorithms which cluster objects into jet in a sequential order following a predefined set of rules. The general form of a sequential clustering algorithm is based on the quantities $d_{ij}$, which represents the distance between two entities, and $d_{iB}$ which represents the distance of the i-th entity from the beam axis. These distances are defined as:\n\\begin{equation}\n d_{ij}=min(k_{ti}^{2p},k_{tj}^{2p})\\frac{\\Delta_{ij}^{2}}{R^2}\n\\end{equation}\n\\begin{equation}\n d_{iB}=k_{ti}^{2p}\n\\end{equation}\nwhere $\\Delta_{ij}^{2}=(\\eta_i-\\eta_j)^2+(\\phi_i-\\phi_j)^2$, $k_{ti}$ is the transverse momentum of the i-th entity and R is the radius parameter which is set as 0.4. The parameter p governs the relative power of energy versus geometrical scales and the particular value of $p=-1$ defines the anti-$k_{T}$ clustering algorithm. The algorithm first computes distance $d_{ij}$ between all entity pairs present at that stage. If the minimum of those distances (say between entity i and j) is smaller than the minimum distance $d_{iB}$ of any entity from the beam axis, those entities i and j are combined into a single entity. Otherwise, the entity closest to the beam axis is considered a jet and removed from the list of entities to be further clustered. This continues until all entities are clustered. The anti-$k_{T}$ is dominated by high $\\pt$ particles which it clusters first, subsequently including softer and softer constituents. Soft particles tend to cluster with hard particles before they tend to cluster among themselves. A hard particle that has no hard neighbors within a distance 2R accumulates all the soft particles within a circle of radius R. It tries to produce jets with fairly conical shapes that are centered around the hardest particles of the event, and with boundaries that resilient to the effect of soft radiation.\n\nJets being complex objects suffer from several effects that cause their energy, reconstructed as described above, to differ from their true values. Multiplicative correction factors are applied to calibrate their $\\pt$ and to ensure a uniform response in $\\eta$~\\cite{jet_recon1,jet_recon2}. A total of four multiplicative corrections are applied. Firstly, the energy coming from pileup that has been clustered into the jet needs to be corrected for. A correction is applied based on the \\textit{hybrid jet area} method which is a combination of two methods viz., the average offset method and the jet area method. The average offset method uses zero bias events to measure the average amount of energy added to the event due to pileup. The assumption is that averaging over zero bias events makes this measurement insensitive to high $\\pt$ objects and primarily represents soft pileup contributions. The average offset is measured in bins of $\\eta$ and number of pileup vertices ($N_{PV}$) averaged over $\\phi$. The correction is then given by $1-\\frac{}{p_{T}^{RAW}}$, where $p_{T}^{RAW}$ is the uncorrected jet $\\pt$. The drawback of this method is that it assumes that every jet contains the same amount of pileup contribution. The jet area method, on the other hand , calculates corrections on a jet-by-jet basis. It calculates an energy density per event by clustering jets using the $k_{T}$ algorithm (this has a value of parameter p=1 and favors clustering soft jets as opposed to hard ones) and dividing the $\\pt$ by jet area, which is defined as the region in $\\eta-\\phi$ occupied by soft particles clustered in the jet. The median of this distribution ($\\rho$) for an event is expected to be insensitive to hard particles and thus $\\rho A_{j}$ is a good approximation of pileup contribution to the i-th jet. The drawback of this second approach, however is that it doesn't take into account the fact that the detector response is $\\eta$ dependent. The \\textit{hybrid jet area} method combines these two methods to calculate a jet-by-jet correction depending on $\\eta$ and $N_{PV}$. Secondly, a MC calibration factor, which corrects the energy of reconstructed jets to match the generated MC particle jet energy on average, is applied. This factor is based on simulated events. Finally, two other factors are used that each calibrate the energy response of reconstructed jets to be uniform with respect to $\\eta$ and $\\pt$. These are also measured using simulated events. A QCD dijet sample is used to uniformize the dependence in $\\eta$. Conservation of momentum in the transverse plane tells us that the sum of momentum in the transverse plane should be zero. Using jets that are approximately back-to-back in the azimuthal direction but at different $\\eta$ regions of the detector, the difference in response between these two $\\eta$ regions can be ascertained and corrected/uniformized. Using the same method of measuring residual response in the transverse direction in $\\gamma + jets$ or $Z +jets$ events, the absolute jet energy scale as a function of $\\pt$ can be made uniform.\n\n\n\\subsection{Missing transverse energy: \\ptvecmiss} \n\\label{mt_met_recon}\nThe CMS detector is unable to detect neutrinos (and other hypothetical particles) that are weakly interacting. However, the momentum balance (or imbalance) in the plane transverse to beam direction can be used to infer their presence. This ``missing'' transverse momentum vector is referred to as the \\ptvecmiss and its magnitude is referred to as \\ptmiss. It is defined as the negative vector sum of the $\\pt$ of entire list of objects reconstructed in the event by the above reconstruction algorithms and refined by particle-flow (PF objects):\n\\begin{equation}\n \\ptvecmiss=-\\Sigma\\ptvec\n\\end{equation}\nThe \\ptvecmiss plays an important role in this analysis as it helps gauge the momentum of the neutrinos from the decaying tau lepton. The \\ptvecmiss reconstruction is directly dependent on the reconstruction of all the other objects in the event, from jets to muons to electrons. Consequently, it is sensitive to all the effects that influence the precise reconstruction and calibration of these objects. The largest effects come from biases in jet reconstruction and pileup (which are interconnected). Jet energy corrections described in previous section and pileup mitigation techniques discussed earlier can help significantly reduce the bias in \\ptvecmiss reconstruction~\\cite{Sirunyan:2019kia}. \n\n\n\\subsection{Relative isolation}\n\\label{isolation}\nThe isolation of an object is the measure of the absence of other objects in its vicinity. In other words, it is the measure of how ``isolated'' an object is. It is calculated by summing up the $\\pt$ of all objects in a cone with predefined radius $\\Delta R=0.4$ around the lepton. The relative isolation which is obtained by dividing the isolation by the $\\pt$ of the lepton is then given by:\n\n\\begin{equation}\nI_\\text{rel}^{\\ell} = \\left( \\sum \\pt^\\text{charged} + \\text{max}\\left[ 0, \\sum \\pt^\\text{neutral}\n + \\sum \\pt^{\\gamma} - \\pt^\\text{PU}\\left(\\ell\\right) \\right] \\right) / \\pt^{\\ell},\n\\end{equation}\nwhere $\\pt^\\text{charged}$, $\\pt^\\text{neutral}$, and $\\pt^{\\gamma}$ indicate the $\\pt$ of a charged particle, a neutral particle, and a photon within the cone, respectively. The contribution to isolation sum from charged particles in the cone coming from pileup is excluded by requiring the track origins be consistent with the primary vertex associated with the hard interaction. However, the same procedure cannot be adopted for neutral particles in the cone coming from pileup. This contribution, $\\pt^\\text{PU}\\left(\\ell\\right)$, is estimated using a jet area method for electrons~\\cite{isolation_1,isolation_2}, and simply as half of the scalar $\\pt$ sum of charged particles from pileup inside the cone for muons. The definition ensures that the total contribution to the isolation cone sum for neutral particles is always greater than or equal to 0. \n\nThe relative isolation is an useful variable in this analysis as prompt objects are usually isolated. More importantly, for an analyses with electrons and muons in the final state such as this, a tightened isolation requirement helps to reject those events where a jet is misidentified as either one of these leptons. Strict isolation requirements are thus used in the event selection in this analysis as described in sections ~\\ref{h125_presel_cat} and ~\\ref{H_presel_cat}. \n\n\n\n\n\\subsection{Collinear mass: \\mcol and transverse mass: $M_{T}$}\n\\label{col_mass}\nAn important variable of interest in this analysis is the collinear mass, $\\mcol$. As mentioned in later chapters, $\\mcol$ is used as the signal variable in the $\\Hmue$ analysis and in the $\\mcol$ fit method of the $\\hmue$ analysis. The visible mass of the muon-electron system, $\\mvis$ is not a very good estimator of the Higgs boson mass. This is because the neutrinos from the tau decay do not interact with the detector and the energy they carry is ``lost''. $\\mcol$ provides a better estimate of the Higgs mass by approximating the neutrino momenta using the collinear approximation~\\cite{Ellis:1987xu}. The primary idea is the following. The mass of the Higgs being much larger than that of the tau lepton causes the tau lepton to become highly boosted. Consequently, the decay products of the tau lepton, i.e. the electron, the tau neutrino and the electron neutrino, are produced in a highly collimated region around the direction of the tau lepton momentum. The momenta of the neutrinos ($\\pt^{\\nu,\\,\\text{est}}$) can thus be approximated from the projection of \\ptvecmiss in the direction of momenta of the visible tau decay product (electron), i.e. $\\vec{\\pt^{\\Pe}}$. The visible fraction of the tau lepton momentum is then given as $x_{\\Pgt}^\\text{vis}={\\pt^{\\vec{\\Pgt}^{\\text{vis}}}}/{(\\pt^{\\vec{\\Pgt}^\\text{vis}}+\\pt^{\\nu,\\,\\text{est}})}$. Finally, $\\mcol$ is given as $M_{\\text{col}}= M_{\\text{vis}} / \\sqrt{\\smash[b]{x_{\\Pgt}^\\text{vis}}}$. A very simple illustration in Figure~\\ref{fig:mcol_v_mvis} shows the superimposition the $\\mcol$ and $\\mvis$ spectrums for a 300 GeV Higgs boson. Evidently, $\\mcol$ is a better estimator of the mass and also has a sharper peak.\n\n\\begin{figure*}[!htpb]\n \\centering\n \\captionsetup{width=0.8\\textwidth,justification=centering}\n \\includegraphics[width=0.9\\textwidth]{plots_and_figures/chapter4/mcol_v_mvis.pdf}\n\\caption{\\mcol and \\mvis distributions for Higgs mass of 300 GeV.}\n \\label{fig:mcol_v_mvis}\n\\end{figure*}\n\n\nAnother variable that is used in this analyses and is useful to discriminate signal from background (see chapter~\\ref{evt_sel}) is the transverse mass, $\\mt(\\ell)$ ($\\ell = \\Pgm, \\Pe$). It is defined as follows: $ {\\mt}(\\ell)=\\sqrt{\\smash[b]{2|\\ptvec^{\\ell}||\\ptvecmiss|(1-\\cos{\\Delta \\phi_{\\ell - \\ptmiss}})}} $, where $\\Delta \\phi_{\\ell - \\ptmiss}$ is the angle between the lepton transverse momentum and \\ptvecmiss.\n\n\n% % uncomment the following lines,\n% if using chapter-wise bibliography\n%\n% \\bibliographystyle{ndnatbib}\n% \\bibliography{example}\n\n% % uncomment the following lines,\n% if using chapter-wise bibliography\n%\n% \\bibliographystyle{ndnatbib}\n% \\bibliography{example}\n", "meta": {"hexsha": "d058b990df3a40c478fc55a24ce4aa291caf9938", "size": 44887, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "thesis/chapter4.tex", "max_stars_repo_name": "Nabarun21/My_PhD_Thesis", "max_stars_repo_head_hexsha": "9dfc42f19a4e5f49b9e5023a88f93f092874240b", "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/chapter4.tex", "max_issues_repo_name": "Nabarun21/My_PhD_Thesis", "max_issues_repo_head_hexsha": "9dfc42f19a4e5f49b9e5023a88f93f092874240b", "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/chapter4.tex", "max_forks_repo_name": "Nabarun21/My_PhD_Thesis", "max_forks_repo_head_hexsha": "9dfc42f19a4e5f49b9e5023a88f93f092874240b", "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": 231.3762886598, "max_line_length": 3120, "alphanum_fraction": 0.8033060797, "num_tokens": 9742, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6039318194686359, "lm_q2_score": 0.3007455789412415, "lm_q1q2_score": 0.18162982468713226}}
{"text": "\\documentclass[addpoints, 11pt]{exam}\n\\usepackage{url}\n\\usepackage{amsmath,amsthm,enumitem,amssymb}\n\\usepackage{graphicx}\n%\\input myfonts\n\n\\newtheorem*{claim}{Claim}\n\\title{CS 6150: HW5 -- Randomized algorithms, optimization}\n\\date{Submission date: Monday, Nov 29, 2021 (11:59 PM)}\n\\begin{document}\n\\maketitle\n\\begin{center}\n\\fbox{\\fbox{\\parbox{5.5in}{\\centering\n%This assignment has \\numquestions\\ questions, for a total of \\numpoints\npoints. % and \\numbonuspoints\\ bonus points. \nUnless otherwise specified, complete and reasoned arguments will be expected for all answers. }}}\n\\end{center}\n\n\\qformat{Question \\thequestion: \\thequestiontitle\\dotfill \\textbf{[\\totalpoints]}}\n\\pointname{}\n\\bonuspointname{}\n\\pointformat{[\\bfseries\\thepoints]}\n\n\\begin{center}\n \\gradetable\n\\end{center}\n\\newpage\n\\paragraph{Instructions.} For all problems in which you are asked to develop an algorithm, write down the pseudocode, along with a rough argument for correctness and an analysis of the running time (unless specified otherwise). Failure to do this may result in a penalty. If you are unsure how much detail to provide, please contact the instructors on Piazza.\n\n\\begin{questions}\n\n\\titledquestion{Trade-offs in sampling}\nFor this problem, you need to run some basic experiments and write down the results you obtained. You {\\bf do not need to submit your code}, but if you prefer, you may add a publicly accessible link to the code (e.g., on github). \n\nSuppose we have a population of size 10 million, and suppose 52\\% of them vote for $A$ and 48\\% of them vote for $B$. \n\n\\begin{parts}\n\\part[4] Randomly pick samples of size (a) 20, (b) 100, (c) 400, and evaluate the probability that $A$ is majority even in your sample (by running the experiment say 100 times and taking the count of times $A$ is the majority in your sample). Write down the values you observe for these probabilities in the cases (a-c).\n\\part[4] What is the size of the sample you need for the probability above to become 0.9? (Your answer can be within 20\\% of the `best' value.)\n\\part[4] Suppose the population is more biased ---55\\% of them vote for $A$ and 45\\% of them vote for $B$--- and re-solve part (b).\n\\end{parts}\n\n\\titledquestion{Satisfying ordering constraints}\nThis problem is meant to illustrate a rather cool paradigm for solving problems, which is picking a {\\em random solution}, and understanding how well it does. Indeed, there are many problems (\"3-SAT\", a version of boolean satisfiability, being the chief of them) where doing better than a random solution is actually NP-hard!\n\nSuppose we have $n$ elements, labeled $1, 2, \\dots, n$. Our goal is to find an ordering of these elements that satisfies as many ``constraints'' as possible, of the kind described below. We are given $m$ constraints, where each constraint is given by a triple $(a, b, c)$, where $a, b, c \\in \\{1, 2, \\dots, n\\}$. The constraint is said to be {\\em satisfied} if in the ordering we output, $a$ does {\\bf not} lie ``between'' $b$ and $c$ (but the order between $b$ and $c$ doesn't matter). For example, if $n=4$ and we consider the ordering $2 4 3 1$, then the constraint $(1, 4, 3)$ is satisfied, but $(3, 1, 2)$ is not.\n\nGiven the constraints, the goal is to find an ordering that satisfies as many constraints as possible (for simplicity, assume in what follows that {\\bf $m$ is a multiple of $3$}). For large $m, n$, this problem becomes very difficult. \n\n\\begin{parts}\n\\part[6] As a baseline, let us consider a {\\em uniformly random} ordering. What is the expected number of constraints that are satisfied by this ordering? [{\\em Hint: } define appropriate random variables whose sum is the quantity of interest, and apply the linearity of expectation.]\n\\part[4] Let $X$ be the random variable which is the number of constraints satisfied by a random ordering, and let $E$ denote its expectation (which we computed in part (a)). Now, Markov's inequality tells us, for example, that $\\Pr[ X \\ge 2E ] \\le 1/2$. But it does not directly imply that $\\Pr[ X \\ge E ]$ is ``large enough'' (which we need if we want to say that generating a few random orderings and picking the best one leads to many constraints being satisfied with high probability). \nUse the definition of $X$ above to conclude that $\\Pr[ X \\ge E ] \\ge 1/m$. \n\n[{\\em Hint:} $X$ is a non-negative integer!]\n\\end{parts}\n\n\\titledquestion{Writing constraints}[6]\nWe will see how writing down constraints can be tricky when formulating problems as optimization.\n\nRecall the traveling salesman problem (TSP): we are given a \\underline{directed} graph $G = (V, E)$ with edge lengths $w(e)$. The goal is to find a {\\em directed cycle} that (a) visits every vertex exactly once, and (b) minimizes the total length (sum of lengths of the edges of the cycle). \n\nConsider the following optimization formulation. We have variables $x_{uv} \\in \\{0,1\\}$, one for each edge $(u,v)$ (remember that the graph is directed). The objective is to minimize $\\sum_{(u,v) \\in E} w(uv) x_{uv}$. The constraints are as follows: let $N_+(u)$ and $N_-(u)$ denote the out-neighbors and in-neighbors of $u$; then we consider the constraints:\n\\begin{align*}\n\\forall ~u,~ \\sum_{v \\in N_+(u)} x_{uv} = 1, \\\\\n\\forall ~u,~ \\sum_{w \\in N_-(u)} x_{wu} = 1.\n\\end{align*}\n(Intuitively, the constraints say that exactly one incoming edge and one outgoing edge must be chosen --- as in a directed cycle.) Does an optimal solution to this optimization problem {\\em always yield} an optimal solution to TSP? Provide a proof or a counterexample with a full explanation.\n\n[{\\em Hint:} consider a feasible solution to the optimization problem and focus on the edges with $x_{uv}=1$. Do they have to form a {\\em single} cycle?]\n\n\\titledquestion{LP Basics}\nConsider the following two-variable linear program. The variables are $x, y \\in \\mathbb{R}$. And the constraints are:\n\\begin{align*}\n2x + y & \\le 10, \\\\\nx &\\ge 0, \\\\\ny &\\ge -1, \\\\\nx+3y &\\le 8.\n\\end{align*}\n\\begin{parts}\n\\part[4] Plot the feasible region for the linear program. (Diagram can be drawn approximately to scale + scanned).\n\\part[2] Suppose the objective function is to {\\em maximize} $x+y$. Find the maximum value and the point at which this is attained.\n\\part[4] Say the maximum value found in part (b) is $C$. Then could you have concluded that $x+y \\le C$ by just ``looking at'' the equations? [{\\em Hint:} does adding equations, possibly with constants, yield a bound?]\n\\end{parts}\n\n\\titledquestion{Identifying Corners}[6]\nConsider the following linear program, with variables $x_1, x_2, \\dots, x_n \\in \\mathbb{R}$. Suppose that the constraints are:\n\\begin{align*}\n0 \\le x_i \\le 1 \\text{ for all $i$}, \\\\\nx_1 + x_2 + \\dots + x_n \\le k,\n\\end{align*}\nwhere $k$ is some integer between $1$ and $n$. Consider any point $(a_1, a_2, \\dots, a_n)$ where $a_i \\in \\{0,1\\}$, and exactly $k$ of the $\\{a_i\\}$ are $1$. Prove that any such point is (a) a feasible point for the LP, and (b) a corner point of the polytope defining the feasible set. \n\n[{\\em Hint:} To prove that a point is a corner point, we use the definition we mentioned in class: a feasible point $x$ is a corner point if and only if for {\\em all} nonzero vectors $z$, either $x + z$ or $x-z$ is infeasible.]\n\n[{\\em Remark:} It turns out that these are the only corner points of the polytope, and so it is an example of a polytope defined by $2n+1$ constraints and having $\\binom{n}{k}$ corner points.]\n\n\\titledquestion{Checking feasibility vs optimization}[6]\nSome of the algorithms for linear programming (e.g. simplex) start off with one of the corner points of the feasible set. This turns out to be tricky in general. In this problem, we will see that {\\bf in general}, finding one feasible point is as difficult as actually performing the optimization! \n\nConsider the following linear program (in $n$ variables $x_1, \\dots, x_n$, represented by the vector $x$):\n\\begin{align*}\n\\text{minimize } &c^T x ~~\\text{subject to} \\\\\na_1^T x &\\ge b_1 \\\\\na_2^T x &\\ge b_2 \\\\\n&\\cdots \\\\\na_m^T x &\\ge b_m.\n\\end{align*}\nSuppose you know that the optimum value (i.e. the minimum of $c^T x$ over the feasible set) lies in the interval $[-M, M]$ for some real number $M$ (this is typically possible in practice). Suppose also that you have an {\\bf oracle} that can take any linear program and say whether it is feasible or not. Prove that using $O(\\log (M/\\epsilon))$ calls to the oracle, one can determine the optimum value of the LP above up to an error of $\\pm \\epsilon$, for any given accuracy $\\epsilon > 0$. [\\emph{Hint: } can you write a new LP that is feasible only if the LP above has optimum value $\\le z$, for some $z$?]\n\n\\end{questions}\n\\end{document}", "meta": {"hexsha": "6daa2a71251cab152f3b53c4d162f5e02b1fa46f", "size": 8676, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "HW5/hw5-f21.tex", "max_stars_repo_name": "Taosheng-ty/CS650_graduate_algorithm", "max_stars_repo_head_hexsha": "210d59f8cf6158d4412c57f38b3f5c2a597a4fa9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "HW5/hw5-f21.tex", "max_issues_repo_name": "Taosheng-ty/CS650_graduate_algorithm", "max_issues_repo_head_hexsha": "210d59f8cf6158d4412c57f38b3f5c2a597a4fa9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "HW5/hw5-f21.tex", "max_forks_repo_name": "Taosheng-ty/CS650_graduate_algorithm", "max_forks_repo_head_hexsha": "210d59f8cf6158d4412c57f38b3f5c2a597a4fa9", "max_forks_repo_licenses": ["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.4642857143, "max_line_length": 619, "alphanum_fraction": 0.7283310281, "num_tokens": 2423, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.399811640739795, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.18121936313978312}}
{"text": "\\chapter{Liquid Nitrogen Cooling in IR Thermography applied to steel specimen}\r\nThe results of this study were firstly presented at an oral session of SPIE Commercial+ Scientific Sensing and Imaging. International Society for Optics and Photonics, 2017.\r\nThen it was accepted for publication in Proceedings Volume 10214, Thermosense: Thermal Infrared Applications XXXIX; 102140T (2017).\r\n\r\n\r\n%\r\n\\section{Résumé}\r\nLa thermographie pulsée (PT) est l'une des méthodes les plus courantes dans les procédures de thermographie active de la thermographie pour NDT \\& E (essais non destructifs \\& évaluation), en raison de la rapidité et la commodité de cette technique d'inspection. Des éclairs ou des lampes sont souvent utilisés pour chauffer les échantillons dans la PT traditionnelle. Cet article explore principalement exactement la stimulation externe opposée en IR Thermographie: refroidissement au lieu de chauffage. Un échantillon d'acier avec des trous à fond plat de différentes profondeurs et tailles a été testé. De l'azote liquide (LN$_2$) est répandu sur la surface de l'échantillon et l'ensemble du processus est capturé par une caméra thermique. Pour obtenir une bonne comparaison, deux autres techniques classiques de CND, la thermographie pulsée et la thermographie verrouillée, sont également utilisées. En particulier, la méthode Lock-in est implémentée avec trois fréquences différentes. Dans la procédure de traitement d'image, la méthode de thermographie en composantes principales (PCT) a été effectuée sur toutes les images thermiques. Pour les résultats Lock-in, les images de phase et d'amplitude sont générées par la transformée de Fourier rapide (FFT). Les résultats montrent que toutes les techniques présentaient en partie les défauts tandis que la technique LN $_2$ affichait les défauts seulement au début du test. De plus, un poste-traitement de seuil binaire est appliqué aux images thermiques, et en comparant ces images à une carte binaire de l'emplacement des défauts, les courbes caractéristiques de fonctionnement du récepteur (ROC) correspondantes sont établies et discutées. Une comparaison des résultats indique que la meilleure courbe ROC est obtenue en utilisant la technique flash avec la méthode de traitement PCT.\r\n\r\n%Cette recherche étudie une stimulation externe - refroidissement au lieu de chauffer en thermographie infrarouge pour NDT \\& E. Un spécimen en acier est utilisé afin de tester trois stimulations différentes sur les images thermiques et également une comparaison d'analyse ROC. Les résultats montrent que toutes les techniques mettent en évidence une partie des défauts de l'échantillon, alors que la technique LN $ _2 $ ne représente les défauts qu'au début; ceci peut être dû à la conductivité élevée de l'acier. Dans les résultats thermiques, la méthode de post-traitement PCT affiche de meilleurs résultats pour toutes les procédures. Plus de défauts sont exposés dans la stimulation Flash avec le traitement PCT.\r\n% Les résultats de cette étude ont d'abord été présentés lors d'une session orale de SPIE Thermosense: Thermal Infrared Applications XXXIX 2017, aux Etats-Unis.\r\n\r\n\\section{Abstract}\r\nPulsed Thermography (PT) is one of the most common methods in Active Thermography procedures of the Thermography for NDT \\& E (Nondestructive Testing \\& Evaluation), due to the rapidity and convenience of this inspection technique. Flashes or lamps are often used to heat the samples in the traditional PT. This paper mainly explores exactly the opposite external stimulation in IR Thermography: cooling instead of heating. A steel sample with flat-bottom holes of different depths and sizes has been tested. Liquid nitrogen (LN$_2$) is sprinkled on the surface of the specimen and the whole process is captured by a thermal camera. To obtain a good comparison, two other classic NDT techniques, Pulsed Thermography and Lock-In Thermography, are also employed. In particular, the Lock-in method is implemented with three different frequencies. In the image processing procedure, the Principal Component Thermography (PCT) method has been performed on all thermal images. For Lock-In results, both Phase and Amplitude images are generated by Fast Fourier Transform (FFT). Results show that all techniques presented part of the defects while the LN$_2$ technique displays the flaws only at the beginning of the test. Moreover, a binary threshold post-processing is applied to the thermal images, and by comparing these images to a binary map of the location of the defects, the corresponding Receiver Operating Characteristic (ROC) curves are established and discussed. A comparison of the results indicates that the better ROC curve is obtained using the Flash technique with PCT processing method. \r\n\r\n\\newpage\r\n\\textbf{\\texttt{Contributing authors:}}\r\n\r\n\\textbf{\\textsf{Lei Lei}} (Ph.D candidate): developing protocol, experiment preparation and planning, data analysis, personnel coordination and manuscript preparation.\r\n\r\n\\textbf{Giovanni Ferrarini} (Researcher of CNR-ITC): discussion in developing protocol, experiment preparation.\r\n\r\n\\textbf{Alessandro Bortolin} (Ph.D student of CNR-ITC): discussion and experiment preparation.\r\n\r\n\\textbf{Gianluca Cadelano} (Ph.D student of CNR-ITC): data collection, discussion and experiment preparation.\r\n\r\n\\textbf{Paolo Bison} (Research supervisor of CNR-ITC): student supervision, revision and correction of the manuscript. \r\n\r\n\\textbf{Xavier Maldague} (Research director of LVSN in University Laval): student supervision, revision and correction of the manuscript.\r\n\r\n% \\phantomsection\\addcontentsline{lof}{table}{5.1\\quad Experimental set-up in the reflection mode}\r\n% \\phantomsection\\addcontentsline{lof}{table}{5.2\\quad Steel sample dimension details with Flat-Bottom Holes of different depths and sizes.}\r\n% \\phantomsection\\addcontentsline{lof}{table}{5.3\\quad Experimental set-up for LN$_2$ cooling}\r\n% \\phantomsection\\addcontentsline{lof}{table}{5.4\\quad One example of ROC analysis (LN$_2$ results) and binary map of defect locations}\r\n% \\phantomsection\\addcontentsline{lof}{table}{5.5\\quad Thermal Raw Images of PT and LN$_2$ stimulation techniques}\r\n% \\phantomsection\\addcontentsline{lof}{table}{5.6\\quad FFT in amplitude and Phase results for LIT}\r\n% \\phantomsection\\addcontentsline{lof}{table}{5.7\\quad PCT results of corresponding technique}\r\n% \\phantomsection\\addcontentsline{lof}{table}{5.8\\quad ROC curves obtained from above results}\r\n\r\n% \\includepdf[pages=-]{Thermosense2017_Lei}\r\n\\newpage\r\n\\section{Introduction}\r\n\\label{sect:intro} % \\label{} allows reference to this section\r\nIn the Nondestructive Testing \\& Evaluation (NDT \\& E) field, active InfraRed (IR) thermography (\\citet{Maldague2001theory}) is a technique widely used in assessing the conditions of parts of material components, with an extremely broad range of applications (\\citet{Vavilov2017Thermal, Cadelano2016Corrosion}). Traditionally, Pulsed Thermography (PT) deploys a thermal stimulation pulse (flash or lamp heating) to produce a thermal contrast between the feature of interest and the background, then monitors the time evolution of the surface temperature by a thermal camera. With this rapidity and convenience, numerous studies have been devoted to this technique, that is now a standard procedure for thermal testing (\\citet{Maldague1993Nondestructive,Maldague1994bInfra,2007-Ibarra-Castanedo,2011-ClementeIbarra-Castanedo,duan2013quantitative,Vavilov2015Review}). \r\n%\\added [id=GF] {that is now a standard procedure for thermal testing.}\r\n\r\nHowever, if the temperature of the material to inspect is already higher than the ambient temperature, it can be of interest to make use of a cold thermal source such as a line of air jets (or water jets; sudden contact with ice, snow, etc.). In fact, a thermal front propagates the same way whether being hot or cold: what is important is the temperature differential between the thermal source and the specimen. An advantage of a cold thermal source is that it does not induce spurious thermal reflections into the IR camera as in the case of a hot thermal source. The main limitations of cold stimulation sources are related to practical considerations, as it is generally easier and more efficient to heat rather then to cool a part.\r\n% \\replaced [id=GF] {, as it is generally easier and more efficient to heat rather then to cool a part.} {as for instance it is generally easier and more efficient, to heat rather then to cool a part.} \r\nThus, the advantage and convenience of using the cold stimulation in active infrared thermography still remains to be investigated in detail and better understood. \r\n\r\nUsing a cold source could extend the range of application of infrared thermography to cases where the specimen under analysis could not be heated, due to safety issues or physical reasons~(\\citet{Livingston2018High}). A cold source could be required while handling biological or organic materials that could not withstand a temperature increase, such as food. Another field of investigation is the survey of concrete and composite materials in order to find cracks and delaminations due to the presence of water or ice. Also in this case, a cold source would significantly decrease the risk of altering the physical characteristics of the specimen. \r\n% \\added [id=GF] {Using a cold source could extend the range of application of infrared thermography to cases where the specimen under analysis could not be heated, due to safety issues or physical reasons. A cold source could be required while handling biological or organic materials that could not withstand a temperature increase, such as food. Another field of investigation is the survey of concrete and composite materials in order to find cracks and delaminations due to the presence of water or ice. Also in this case, a cold source would significantly decrease the risk of altering the physical characteristics of the specimen} \r\n\r\nNonetheless,in the past in the scientific community, only a limited number of studies investigating a cold approach (cooling as the external stimulation in active infrared thermography) have been performed on industrial product inspection~(\\citet{endohdynamical2012,2012-LewisHom}). A study by Burleigh~(\\citet{Burleigh1989Thermographic}) showed that the cooling method with refrigerating liquids is feasible but requires caution to ensure the safety.\r\n% \\added [id=GF] {A study by Burleigh(\\citet{1989Burleigh} showed that the cooling method with refrigerating liquids is feasible but requires caution to ensure the safety.} \r\nThe work of (\\citet{lei2017detection}) chose instead to use air cooling to survey refrigerated vehicles. All the available works do not give a quantitative information about the reliability of the cooling technique, especially in comparison with the traditional heating procedure.\r\n% \\replaced [id=GF] {chose instead to use air cooling to survey refrigerated vehicles.} {demonstrates an example that air cooling approach applied in detection of the truck panel.} \r\n% \\added [id=GF] {All the available works do not give a quantitative information about the reliability of the cooling technique, especially in comparison with the traditional heating procedure.}\r\n\r\nTherefore, the aim of this paper is improving the current knowledge on cooling thermal stimulation\r\n% \\replaced [id=GF] {improving the current knowledge on cooling thermal stimulation} {then the continuous investigation of cold approach} \r\nin IR thermography. In order to perform a reliable comparison, three methods (two traditional techniques, Pulsed Thermography and Lock-in Thermography act as the reference) will be applied on a steel slab with different sizes of flat-bottom-holes. The thermographic images of the experiments will be treated to eventually produce a binary map of the location of the defects. This map will be statistically evaluated in terms of sensitivity and specificity~(\\citet{Fawcett2006}) by comparison with the `true' map of the defects, furnishing a rank of the three stimulation methods. \r\n\r\n\\section{Experimental setup} % (fold)\r\n\\label{sec:experimental_setup}\r\nOne side stimulation approach is often used in the Infrared Thermography NDT \\& E field, which is also known as the reflection scheme: both the stimulation device and the camera stay on the same side of the sample being tested. This approach applied in reality is shown in Figure~\\ref{Exp_setup}.\r\n\r\n\\begin{figure}[ht]\r\n % \\centering\r\n % \\begin{center}\r\n \\hspace{-0.95cm}\r\n \\begin{tabular}{c}\r\n \\includegraphics[scale=0.95]{chp5/Exp_setup.png}\r\n \\\\\r\n \\footnotesize{(a) Pulsed Thermography set-up} \\hspace{4cm} \\footnotesize{(b) Lock-in Thermography set-up} \r\n \\end{tabular} \r\n % \\end{center}\r\n \\caption{Experimental set-up in the \\textit{reflection} mode}\r\n \\label{Exp_setup}\r\n\\end{figure}\r\n\r\n% \\begin{figure}[ht]\r\n% \\centering\r\n% \\subfloat[Pulsed Thermography set-up]\r\n% {\r\n% \\includegraphics[scale=0.3]{chp5/Flash_Setup.png}\r\n% }\r\n% %\\hspace{5pt}\r\n% \\subfloat[Lock-in Thermography set-up]\r\n% {\r\n% \\includegraphics[scale=0.3]{chp5/LIT_setup.png}\r\n% }\r\n% \\caption{Experimental set-up in the \\textit{reflection} mode}\r\n% \\label{Exp_setup}\r\n% \\end{figure}\r\n\r\nThe following equipment was set up for this study:\r\n\\begin{itemize}\r\n \\item Infrared Camera FLIR SC3000 (spatial resolution equal to 320$\\times$240 pixels, frame rate up to 50Hz, GaAs sensor, spectral range 8-9 $\\mu m$)\r\n% \\replaced [id=GF] {spatial resolution equal to 320$\\times$240 pixels, framerate up to 50Hz, GaAs sensor, spectral range 8-9 $\\mu m$)}{320$\\times$240 pixels, framerate 50Hz, GaAs , 8-9 $\\mu m$)}\r\n \\item Two pairs of flash \r\n% \\replaced [id=GF] {}{halogen} \r\n lamps for a total of 10 kJ (electric) released in 5 $ms$ \r\n \\item One pair of modulated halogen lamps with 1kW each served as Lock-in stimulation\r\n \\item An isolated bottle (500 ml)\r\n% ??? \\added [id=LL] {need to be rechecked, thanks Giovanni~}\r\nfilled with\r\n% \\replaced [id=GF] {(500 ml???) filled with}{full of}\r\n Liquid Nitrogen.\r\n\\end{itemize}\r\n\r\n\\subsection{Specimen} % (fold)\r\n\\label{sub:specimen}\r\nIn this study, a steel specimen comprising flat-bottom holes of different depths and sizes will be examined. Their dimensions are depicted in Figure~\\ref{specimen}.\r\n \\begin{figure}[ht]\r\n \\centering \r\n % \\begin{tabular}{c} %% tabular useful for creating an array of images \r\n \\includegraphics[scale=0.4]{chp5/specimen_schema.pdf}\r\n % \\end{tabular}\r\n \\caption{Steel sample dimension details with Flat-Bottom Holes of different depths and sizes (mirror image)} \r\n% \\added [id=LL] {Mirror image}\r\n%>>>> use \\label inside caption to get Fig. number with \\ref{}\r\n \\label{specimen} \r\n \\end{figure} \r\n\r\nThe steel plate has seventeen holes whose diameters vary from 0.4 $cm$ to 3 $cm$, and whose depths (from bottom) vary from 0.3 $cm$ to 0.9 $cm$. The entire thickness is 1 $cm$. This specimen is painted before the test, in order to increase its emissivity and to obtain a homogeneous external stimulation.\r\n\r\n% subsection specimen (end)\r\n\\subsection{Stimulation Techniques} % (fold)\r\n\\label{sub:stimulation_techniques}\r\nThree external stimulations were deployed on the sample, for the sake of obtaining a good comparison in results: \r\n\\begin{itemize}\r\n \\item Pulse Thermography (PT) \r\n \\item Lock-in Thermography (LIT)\r\n \\item Liquid Nitrogen cooling (LN$_2$)\r\n\\end{itemize}\r\nKnown as the traditional and fast technique in NDT \\& E, Pulse Thermography (PT) acts as the reference during this test. One reason for this popularity is the quickness of the inspection relying on a thermal stimulation pulse, with duration going from a few ms for high thermal conductivity material inspection (such as metal specimen in this study) to a few seconds for low thermal conductivity specimens. Such quick thermal stimulation allows direct deployment on the plant floor with convenient heating sources.\r\n\r\n% When neglecting heat exchange with the environment, the pulse of energy $Q$, delivered on a layer of thickness $L$, characterized by a density $\\rho$, a specific heat $C_p$ and a thermal conductivity $\\lambda$ (or a thermal diffusivity $\\alpha$) produces a temperature increment behavior on the heated surface given by:\r\n% \\begin{equation}\r\n% T(t) = \\frac{Q}{\\rho C_p L}[1+2\\sum_{n=1}^{\\infty} e^{-\\frac{n^2 \\pi ^2\\alpha t}{L^2}}]\r\n% \\label{eq_pt}\r\n% \\end{equation}\r\n\r\nLock-in thermography (LIT) is based on thermal waves generated inside the inspected specimen and detected remotely. Wave generation is for instance performed by periodically depositing heat on the specimen surface (e.g. through sine-modulated lamp heating) while the resulting oscillating temperature field in the stationary regime is remotely recorded through its thermal infrared emission.\r\n\r\nIn this study, 3 different frequencies of 0.0625~$Hz$ (LIT16--one period is equivalent to 16 seconds), 0.125~$Hz$ (LIT8--one period is equivalent to 8 seconds) and 0.25~$Hz$ (LIT4--one period is equivalent to 4 seconds) are performed in Lock-in Thermography. \r\n\r\n% By the convolution integral, Eq~(\\ref{eq_pt}) becomes:\r\n% \\begin{equation}\r\n% T(t) = \\frac{W}{\\lambda}\\frac{\\alpha}{L}\\int_0^t d\\tau \\Big(1+\\sin(\\omega \\tau - \\frac{\\pi}{2})\\Big)\\Big\\{1+2\\sum_{n=1}^{\\infty} e^{-\\frac{n^2 \\pi ^2\\alpha(t-\\tau)}{L^2}}\\Big\\}\r\n% \\end{equation}\r\n% where $W$ is the absorbed heating power.\r\n\r\nThe Liquid Nitrogen is applied in the test by means of pouring it out directly onto the surface in order to cool the sample. LN$_2$ was sprinkled onto the specimen center and allowed to spread out towards the edges. The whole capture duration is 500 frames with 50~$Hz$ of image frequency, ie. 10 seconds of recording. The pouring time (cooling time) is about 2 seconds, due to the bottle with a volume of 500 ml, with 100 frames in the results sequence. This way of cooling has a limit of that the central part will be first and mainly cooled, then the cold front propagates from center to the edges. This can lead to a drawback that in the final thermograms defects closer to the edges will be difficulty to detected. The experimental set-up is shown in Figure~\\ref{Exp_LN2}.\r\n\r\n\\begin{figure}[ht]\r\n \\centering\r\n \\includegraphics[scale=0.4]{chp5/LN2_setup.png}\r\n \\caption{Experimental set-up for LN$_2$ cooling}\r\n \\label{Exp_LN2}\r\n\\end{figure}\r\n\r\n% subsection stimulation_techniques (end)\r\n\r\n% section experimental_setup (end)\r\n\r\n\r\n\\section{Processing Methods} % (fold)\r\n\\label{sec:processing_methods}\r\nThe following image-processing techniques and data-analysis methods were employed for this study:\r\n\\begin{itemize}\r\n \\item Principal Component Thermography (PCT)\r\n \\item Phase and Amplitude images by Fast Fourier Transform (FFT)\r\n \\item Receiver Operating Characteristic curves (ROC Curves)\r\n\\end{itemize}\r\n\r\n\\subsection{Principal Component Thermography (PCT)}\r\nThe Principal Component Thermography technique~(\\citet{Rajic2002}) uses ``singular value decomposition (SVD) to reduce the matrix of observations to a highly compact statistical representation of the spatial and temporal variations relating to contrast information associated with underlying structural flaws\".\r\n\r\n\\subsection{FFT in Phase and Amplitude for LIT}\r\nIn addition to the common technique for NDT \\& E, Fast Fourier Transform in LIT~(\\citet{wu1998lock}) is also one of the most applied techniques in IR Thermography, which is based on the periodic heating of the object being tested. A thermal wave is likewise generated and propagates inside the material. In real experimental cases the thermal wave is composed by a principal frequency and several harmonics where the amplitude of the Fast Fourier Transform is a function of frequency. By selecting the component with the highest amplitude it is possible to produce a phase map at the corresponding frequency where the defect appears enhanced.\r\n\r\n\r\n\\subsection{ROC Curve analysis} % (fold)\r\n\\label{sub:roc_curve_analysis}\r\nThe Receiver operating characteristic (ROC) curve is a technique in statistics which helps visualize, organize and select classifiers based on their performance. The curve graph is created by plotting the the true positive rate (TPR) against the false positive rate (FPR) at various threshold settings. More details about concepts and definitions can be found in (\\citet{Fawcett2006}). While being frequently chosen a standard method in several scientific fields, ROC are rarely applied in the thermographic field~(\\citet{Bison2014a}). \r\n\r\nImplemented in this study, a binary map of the defect locations is built and correlated to the post-processed images in gray scale, and the lay-out is provided in Figure~\\ref{binary}.\r\n% \\deleted [id=LL]{, and the lay-out is provided in Figure~\\ref{binary}}. \r\nThe main algorithm in the calculation of TPR and FPR is clarified as:\r\n\\begin{enumerate}\r\n \\item Choose the post-processed thermogram in which most defects shown as the test image;\r\n% \\replaced [id=LL] {Choose the post-processed thermogram in which most defects shown as the test image;}{Identify the best gray-scale result from the post-processing thermal images as the test image;}\r\n \\item Resize the defect map to the same size as that of the test image;\r\n \\item Choose a thresholding step number $N$($N=1000$ in this study) and establish the step value of thresholding [from $0$, $\\frac{1}{N}$, $\\frac{2}{N}$ till $1 (=\\frac{N}{N})$];\r\n \\item For each thresholding step, binarize the test image with the thresholding and then compare it to the defect map, in order to obtain the corresponding TPR and FPR values;\r\n \\item Iterate the binarization and comparison so as to plot a whole curve.\r\n\\end{enumerate}\r\n\r\n% \\begin{figure}[ht]\r\n% \\begin{center}\r\n% \\begin{tabular}{c}\r\n% \\includegraphics[scale=1.0]{ROC_exm.png}\r\n% \\\\\\footnotesize{(a) Binary map of defects} \\hspace{4cm} \\footnotesize{(b) Cool map} \r\n% \\end{tabular} \r\n% \\end{center}\r\n% \\caption{One example of ROC analysis (LN$_2$ results) and binary map of defect locations}\r\n% \\label{binary}\r\n% \\end{figure}\r\n\r\n\\begin{figure}[ht]\r\n \\centering\r\n \\subfloat[Binary map of defects]\r\n {\r\n \\includegraphics[scale=0.195]{chp5/Schema_done.png}\r\n \\label{bin_map}\r\n }\r\n \\subfloat[Cool map]\r\n {\r\n \\includegraphics[scale=0.8]{chp5/Cool_ROC.png}\r\n \\label{cool_map}\r\n } \r\n \\caption{One example of ROC analysis (LN$_2$ results) and binary map of defect locations}\r\n \\label{binary}\r\n\\end{figure}\r\n\r\n%% subsection roc_curve (end)\r\n\r\n\r\n% section methods (end)\r\n\\section{Results \\& Discussion} % (fold)\r\n\\label{sec:results_&_discussion}\r\nFigure~\\ref{raw_results} illustrates the thermal raw images of PT and LN$_2$. The Lock-In FFT results can be found in Figure~\\ref{LIT_results}.\r\n\r\n% \\begin{figure}[ht]\r\n% \\begin{center}\r\n% % \\begin{tabular}{c}\r\n% \\includegraphics[scale=0.60]{chp5/Raw_results.png}\r\n% % \\\\\\footnotesize{(a) Binary map of defects} \\hspace{4cm} \\footnotesize{(b) Cool map} \r\n% % \\end{tabular} \r\n% \\end{center}\r\n% \\caption{Thermal raw images of PT and LN$_2$ stimulation techniques}\r\n% \\label{raw_results}\r\n% \\end{figure}\r\n\r\n\r\n\\begin{figure}[htpb]\r\n \\centering\r\n \\subfloat[Flash raw frame 23]\r\n {\r\n \\includegraphics[scale=0.55]{chp5/flash_raw23_2.png}\r\n \\label{Flash_raw23}\r\n }\r\n \\hspace{10pt}\r\n \\subfloat[Flash raw frame 60]\r\n {\r\n \\includegraphics[scale=0.55]{chp5/flash_raw60_2.png}\r\n \\label{Flash_raw60}\r\n }\r\n \\hspace{10pt}\r\n \\subfloat[LN$_2$ raw frame 41]\r\n {\r\n \\includegraphics[scale=0.55]{chp5/cool_raw_2.png}\r\n \\label{LN2_raw}\r\n }\r\n \\caption{Thermal raw images of PT and LN$_2$ stimulation techniques} \r\n \\label{raw_results}\r\n\\end{figure}\r\n\r\n% \\begin{figure}[ht]\r\n% \\begin{center}\r\n% % \\begin{tabular}{c}\r\n% \\includegraphics[scale=0.6]{chp5/LIT_results.png}\r\n% % \\\\\\footnotesize{(a) Binary map of defects} \\hspace{4cm} \\footnotesize{(b) Cool map} \r\n% % \\end{tabular} \r\n% \\end{center}\r\n% \\caption{FFT in amplitude and phase results for LIT}\r\n% \\label{LIT_results}\r\n% \\end{figure}\r\n\r\n\\begin{figure}[htpb]\r\n \\centering\r\n \\subfloat[LIT4 FFT in amplitude]\r\n {\r\n \\includegraphics[scale=0.57]{chp5/LIT4_AMP.png}\r\n }\r\n \\hspace{10pt}\r\n \\subfloat[LIT4 FFT in phase]\r\n {\r\n \\includegraphics[scale=0.57]{chp5/LIT4_PHA.png}\r\n }\r\n \\hspace{10pt}\r\n \\subfloat[LIT8 FFT in amplitude]\r\n {\r\n \\includegraphics[scale=0.57]{chp5/LIT8_AMP.png}\r\n }\r\n \\hspace{10pt}\r\n \\subfloat[LIT8 FFT in phase]\r\n {\r\n \\includegraphics[scale=0.57]{chp5/LIT8_PHA.png}\r\n \\label{LIT8_ph}\r\n }\r\n \\hspace{10pt}\r\n \\subfloat[LIT16 FFT in amplitude]\r\n {\r\n \\includegraphics[scale=0.57]{chp5/LIT16_AMP.png}\r\n \\label{LIT16_ph}\r\n }\r\n \\hspace{10pt}\r\n \\subfloat[LIT16 FFT in phase]\r\n {\r\n \\includegraphics[scale=0.57]{chp5/LIT16_PHA.png}\r\n }\r\n \\caption{FFT in amplitude and phase results for LIT} \r\n \\label{LIT_results}\r\n\\end{figure}\r\n\r\n\\subsection{Thermal images comparison} \r\n\r\nFrom the results above, raw images in Figure~\\ref{raw_results} indicate that the most detectable flaws are the ones with a high aspect ratio (ie. diameter-to-depth). In addition, for the PT stimulation, a small hole with diameter 0.4 $cm$, depth\\footnote{It should be noted that the depth values mentioned here and after are from the bottom of the sample, therefore the real corresponding depths should be these values subtracted from the thickness.} 0.9 $cm$ (left-upper in Figure~\\ref{Flash_raw23}) appeared in frame 23, and disappeared after. Other holes, two with diameter 2 $cm$ and depth 0.9 $cm$, and two with diameter 3 $cm$ and depth 0.5 $cm$, \r\n% \\replaced [id=GF]{. Other holes, two with diameter 2 $cm$ and depth 0.9 $cm$, and two with diameter 3 $cm$ and depth 0.5 $cm$,} {, while another two holes with diameter 2 $cm$, depth 0.9 $cm$ and two with diameter 3 $cm$, depth 0.5 $cm$}\r\n(center in Figure~\\ref{Flash_raw60}) appeared in frame 60. Nonetheless, in LN$_2$ raw results, same defects as the one in Flash frame 60 appeared in LN$_2$ frame 41 (however, it should be noted that the first 100 frames of cooling time has been removed from the these final raw images. The reason is because there was much noise from nitrogen gases in the thermal images).\r\n% \\added [id=LL] {The reason is because there was much noise from nitrogent gases in the thermal images})\r\nAfter this, there was no more defect that emerged. Another remark is that since the LN$_2$ is sprinkled onto the center of the surface, there could be the situation that the center part of specimen was over cooled while the `cold front' (opposite to heat front) might have not be able to propagate to the edges. Due to the high conductivity of steel, defects only showed up at the beginning\r\n% \\replaced [id=LL] {end} {beginning}\r\nof the cooling procedure. These may be the main issues of pouring-out method.\r\n\r\nFor LIT results, FFT in amplitude has a better flaw detection capability than FFT in phase, as there is some noise in all of the phase images. LIT8 and LIT16 have about four more detected flaws than LIT4. Whereas, for FFT in phase for LIT8 and LIT16, there some inverse gray-scale values occur. This might be due to the reverse image question.\r\n\r\nFollowing PCT processing, figure~\\ref{PCT_results} exhibits a clearer result. It can be observed that most of the flaws are visible, especially in the flash image (Figure~\\ref{PCT_Flash}). Less flaws are visible in the LIT4 PCT third image.\r\n%The corresponding PCT results are represented in Figure~\\ref{PCT_results}.\r\n% \\begin{figure}[ht]\r\n% \\begin{center}\r\n% % \\begin{tabular}{c}\r\n% \\includegraphics[scale=0.6]{chp5/PCT_results.png}\r\n% % \\\\\\footnotesize{(a) Binary map of defects} \\hspace{4cm} \\footnotesize{(b) Cool map} \r\n% % \\end{tabular} \r\n% \\end{center}\r\n% \\caption{PCT results of corresponding technique}\r\n% \\label{PCT_results}\r\n% \\end{figure}\r\n\r\n\\begin{figure}[htpb]\r\n \\centering\r\n \\subfloat[Flash PCT 2nd Image]{\r\n \\includegraphics[scale=0.57]{chp5/Flash_PCT_2.png}\r\n \\label{PCT_Flash}\r\n }\r\n \\hspace{10pt}\r\n \\subfloat[LN$_2$ PCT 2nd Image]{\r\n \\includegraphics[scale=0.57]{chp5/Cool_PCT_2.png}\r\n }\r\n \\hspace{10pt}\r\n \\subfloat[LIT4 PCT 3rd Image]{\r\n \\includegraphics[scale=0.57]{chp5/LIT4_PCT_3.png}\r\n } \r\n \\\\ %\\hspace{10pt}\r\n \\subfloat[LIT8 PCT 3rd Image]{\r\n \\includegraphics[scale=0.57]{chp5/LIT8_PCT_3.png}\r\n }\r\n \\hspace{10pt}\r\n \\subfloat[LIT16 PCT 3rd Image]{\r\n \\includegraphics[scale=0.57]{chp5/LIT16_PCT_3.png}\r\n }\r\n % \\includegraphics[scale=0.4]{graph/LIT4_PCT_3.png}\r\n % \\includegraphics[scale=0.4]{graph/LIT8_PCT_3.png}\r\n % \\includegraphics[scale=0.4]{graph/LIT16_PCT_3.png}\r\n \\caption{PCT results of corresponding technique}\r\n \\label{PCT_results}\r\n\\end{figure}\r\n\r\n\r\nComparing the processed thermal images, the following observations can be made: \r\n\\begin{itemize}\r\n \\item All techniques present part of the flaws in the sample;\r\n \\item The PCT post-processing method displays a better results for all images;\r\n \\item More defects are exhibited in Flash stimulation with PCT processing;\r\n %\\item For LIT8 and LIT16, there are some reverse image question.\r\n\\end{itemize}\r\n\r\n\r\n\\subsection{Corresponding ROC curves comparison}\r\nThe ROC curves obtained from comparing the binary map of defect locations to the above results are represented in Figure \\ref{roc_pct} and ~\\ref{ROC_curve}.\r\n\\begin{figure}[htbp]\r\n \\centering\r\n \\includegraphics[scale=0.7]{chp5/ROC_PCT_2017.pdf}\r\n \\caption{ROC curves for PCT processing results}\r\n \\label{roc_pct}\r\n\\end{figure}\r\n\r\n% \\begin{figure}[htbp]\r\n% % \\centering\r\n% \\begin{center}\r\n% \\begin{tabular}{c}\r\n% \\includegraphics[scale=0.75]{chp5/ROC_LIT_results.png}\r\n% \\\\\\footnotesize{(a) ROC from LIT FFT in amplitude results} \\hspace{2.1cm} \\footnotesize{(b) ROC from LIT FFT in phase results} \r\n% \\end{tabular}\r\n% \\end{center} \r\n% \\caption{ROC curves for LIT processing results}\r\n% \\label{roc_lit}\r\n% \\end{figure}\r\n\r\n\\begin{figure}[ht]\r\n \\centering\r\n % \\subfloat[ROC from PCT Results]\r\n % {\r\n % \\includegraphics[scale=0.75]{chp5/ROC_PCT_2017.pdf}\r\n % }\r\n % %\\hspace{10pt}\r\n % \\\\\r\n \\subfloat[ROC from LIT FFT in amplitude results]\r\n {\r\n \\includegraphics[scale=0.70]{chp5/ROC_LIT_AMP_2017.pdf}\r\n \\label{roc_amp}\r\n }\r\n \\hspace{10pt}\r\n \\subfloat[ROC from LIT FFT in phase results]\r\n {\r\n \\includegraphics[scale=0.70]{chp5/ROC_LIT_PHA_2017.pdf}\r\n \\label{roc_pha}\r\n } \r\n \\caption{ROC curves for LIT processing results}\r\n \\label{ROC_curve}\r\n\\end{figure}\r\n\r\n%\\added[id=GF] {Before you called the true positive rate TPR (and the false FPR). From here you call them tp rate and fp rate, maybe it is better to choose the same nomenclature }\r\n\r\nIn the ROC curves definitions, the \\textit{sensitivity} is the True Positive Rate (\\textit{TPR}), and \\textit{1-specificity} is the False Positive Rate (\\textit{FPR}).\r\nFrom the curves of the PCT results (Figure~\\ref{roc_pct}), one can easily notice that the five curves have almost the same performance of classification in the beginning. When the \\textit{TPR} arrives at $0.3$, the PT curve becomes the nearest to the northwest (where the \\textit{TPR} is higher, the \\textit{FPR} is lower or both). The second one is the LN$_2$ curve that has a slightly higher \\textit{TPR} than PT after the \\textit{FPR} reaches $0.4$. The LIT8 and LIT16 curves have almost the same performance before the \\textit{TPR} attains $0.7$. After that the LIT16 has a higher \\textit{TPR} than LIT8. The worst one is the LIT4 curve as it is the closest one to the diagonal line $y=x$, which represents the strategy of randomly guessing a class.\r\n\r\nThe situation is the same for the curves of LIT amplitude (Figure~\\ref{roc_amp}), in which LIT4 has an unfavorable performance in classification. LIT16 also has a slightly higher \\textit{TPR} than LIT8. However, in the curves of LIT phase results (Figure~\\ref{roc_pha}), LIT16 shows a poor performance while LIT4 displays a better classification\r\n% \\added[id=GF] {while LIT4 displays a better classification}\r\n, contrary to the former results. \r\n% \\replaced[id=GF] {} {While LIT4 displays a better classification.}\r\nBecause of the reverse image problem, the result LIT8 presents a region (top-right) which is under the equal diagonal line.\r\n\r\n\r\n\\subsection{Area under curve analysis and comparison}\r\nIn ROC analysis, a common method to compare different classifiers is to calculate the area under the ROC curve, known as AUC~(\\citet{Fawcett2006}). In this way, a single scalar value will represent the expected performance of the classifiers. As in the ROC curve profile, the AUC is a part of the unit square are, therefore, its value will be between 0 and 1. Thus, random guessing classifier produces a diagonal line between (0,0) and (1,1), which has an area of 0.5. It can be then indicated that a classifier AUC value less than 0.5 is even worse than a random guessing. \r\n\r\nThe corresponding AUC obtained from the above ROC curves is found in Tab. \\ref{tab_auc}. Their comparison in form of the bar chart is illustrated in Fig. \\ref{fig_auc}. A straight comparison shows that the Flash method with PCT second component has the highest AUC value of 0.9. The second one is the Liquid Nitrogen method, that is very close to the flash method with an AUC value of 0.87. At the bottom of the ranking, LIT4 with PCT third component and its amplitude one have the worst values as 0.67 and 0.65 respectively, which are just a bit better and a random guessing.\r\nOn the contrary, LIT8 and LIT16 technique have a better result both in PCT processing and their amplitude images. This might be caused by the fact that during one period, 4 seconds of heating (LIT4) were not enough to penetrate the steel specimen deeply as those of 8 seconds (LIT8) and 16 seconds (LIT16). On the other hand, all the Lock-in Thermography techniques have similar AUC value in their phase images, which indicates that for phase image results, heating time does not make an effective influence in Lock-in Thermography in this study. Considering all these results, though the best approach is Flash technique with PCT processing, the LN$_2$ technique can be considered as a valid alternative method\r\n\r\n% Figure AUC to be added.\r\n% Table to be added.\r\n\\begin{table}[htbp]\r\n \\centering\r\n \\begin{tabular}{lr}%ccccccccc}\r\n \\toprule\r\n \\textbf{Method} & \\textbf{Value} \\\\\r\n \\midrule\r\n Flash-2nd & 0.90 \\\\\r\n LN2-2nd & 0.87 \\\\\r\n \\midrule\r\n LIT4-3rd & 0.67 \\\\\r\n LIT8-3rd & 0.80 \\\\\r\n LIT16-3rd & 0.82 \\\\\r\n \\midrule\r\n LIT4-AMP & 0.65 \\\\\r\n LIT8-AMP & 0.79 \\\\\r\n LIT16-AMP & 0.82 \\\\\r\n \\midrule\r\n LIT4-PHA & 0.71 \\\\\r\n LIT8-PHA & 0.69 \\\\\r\n LIT16-PHA & 0.67 \\\\\r\n\r\n% 0.90 & 0.87 & 0.67 & 0.80 & 0.82 & 0.65 & 0.79 & 0.82 & 0.71 & 0.69 & 0.67 \\\\\r\n \\bottomrule\r\n \\end{tabular}\r\n \\caption{AUC value comparison}\r\n \\label{tab_auc}\r\n\\end{table}\r\n\r\n% $x = ['Flash_2nd', 'LN2_2nd', 'LIT4_3rd', 'LIT8_3rd', 'LIT16_3rd',\r\n% 'LIT4_AMP', 'LIT8_AMP', 'LIT16_AMP', 'LIT4_PHA', 'LIT8_PHA', 'LIT16_PHA']\\\\\r\n% y = np.array([0.90, 0.87, 0.67, 0.80, 0.82,\r\n% 0.65, 0.79, 0.82, 0.71, 0.69, 0.67])$\r\n \r\n\\begin{figure}[htpb]\r\n \\centering\r\n \\includegraphics[scale=0.48]{chp5/AUC.png}\r\n \\caption{AUC value comparison}\r\n \\label{fig_auc}\r\n\\end{figure}\r\n\r\n% section results_&_discussion (end)\r\n\r\n\r\n\r\n\\section{Conclusion} % (fold)\r\n\\label{sec:conclusion}\r\nThis study investigates an external stimulation--cooling instead of heating in IR Thermography for NDT \\& E. \r\nA steel specimen is used to test three different stimulations for thermal images and also ROC analysis comparison. \r\nResults shows that all techniques highlight part of the flaws in the sample, whereas the LN$_2$ technique represents the defects at the end of cooling process; this maybe due to the high conductivity of steel. \r\nIn thermal results, the PCT post-processing method displays a better results for all procedures. More defects are exhibited in Flash stimulation with PCT processing.\r\nROC curve analysis and its AUC analysis have elucidated a straightforward classification comparison, in which the best values are obtained with the Flash technique with PCT processing, trailed narrowly by the Liquid Nitrogen method.\r\n\r\n\r\nThe LN$_2$ technique should therefore be considered as a valid option for the survey of objects that should not be heated, such as biological tissues, organic materials, dry or iced samples. With this purpose, future work will analyze different kinds of specimens.\r\n% \\replaced[id=GF] {The LN$_2$ technique should therefore be considered as a valid technique for the survey of objects that should not be heated, such as biological tissues, organic materials, dry or iced samples. With this purpose, future work will analyze different kinds of specimens.} {In future work, other common composite materials such as CFRP (Carbon fiber reinforced polymer), GFRP (Glass Fiber Reinforced Polymer) will be chosen as specimen.}\r\nThe method of Liquid Nitrogen pouring may be replaced by spraying onto the sample surface, which can reduce the inhomogeneous cooling problem. To enhance the penetration of heat inside the sample, a proposition involving heating on one side of the specimen and cooling the other side might be taken into consideration.\r\n% \\replaced[id=GF] {} {Even though LN$_2$ technique in this study has not shown enough advantages,}\r\n% \\replaced[id=GF] {The} {this}\r\nThe exploration of an opposite means of external stimulation in InfraRed Thermography might favor new ideas \r\n% \\replaced[id=GF] {} {of approaches}\r\nfor NDT \\& E.\r\n\r\n\r\n\\section*{Acknowledgments} \r\n \r\nThis research was supported by the governments of Italy and Quebec (Minist\\`{e}re des Relations internationales et de la Francophonie) through the Joint Subcommittee Qu\\'{e}bec-Italy, project n$^{\\circ}$08.0203. It was also supported by the Natural Sciences and Engineering Research Council of Canada (NSERC). We are also thankful to our collaborative institute CNR-ITC Padova which provided expertise that greatly helped in this research.\r\n\r\n\r\n\\bibliographystyle{unsrtnat} % style de la bibliographie\r\n\\bibliography{U:/Desktop/Bibliography/Biblio_th} \r\n", "meta": {"hexsha": "71d11954795cfc1ac5be98d48f6194243101272b", "size": 38502, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "main/chapitre5.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/chapitre5.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/chapitre5.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": 74.4719535783, "max_line_length": 1846, "alphanum_fraction": 0.7468702925, "num_tokens": 10067, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.3174262655876758, "lm_q1q2_score": 0.18088619907363146}}
{"text": "\\documentclass[11pt, oneside]{article}\n\n% Packages\n\\usepackage{jmlr2e}\n\\usepackage{xcolor}\n\\usepackage[super]{nth}\n\\usepackage{mathtools, amsfonts}\n\n% Package config\n% \\sectionfont{\\normalfont\\sffamily\\bfseries}\n% \\subsectionfont{\\normalfont\\sffamily\\bfseries}\n\\hypersetup{colorlinks,\n linkcolor={red!50!black},\n citecolor={blue!50!black},\n urlcolor={blue!80!black}\n}\n\n% Notation and macros\n\\input{notation.tex}\n\n% Preamble\n\n% Heading arguments are\n% {volume}{year}{pages}{submitted}{published}{author-full-names}\n% \\jmlrheading{}{}{}{}{}{}\n\n% Short headings should be running head and authors last names\n\\ShortHeadings{\\revrand~Technical Report}{Steinberg, Tiao, Reid, McCalman and\n O'Callaghan}\n\\firstpageno{1}\n\n\\title{\\revrand: Technical Report}\n\\author{\\name Daniel Steinberg \\email daniel.steinberg@data61.csiro.au \\\\\n \\name Louis Tiao \\email louis.tiao@data61.csiro.au \\\\\n \\name Alistair Reid \\email alistair.reid@data61.csiro.au \\\\\n \\name Lachlan McCalman \\email lachlan.mccalman@data61.csiro.au \\\\\n \\name Simon O'Callaghan \\email simon.ocallaghan@data61.csiro.au \\\\\n \\addr DATA61, CSIRO \\\\\n Sydney, Australia}\n\n\\date{}\n\n\\begin{document}\n\n\\maketitle\n% \\vspace{-0.5cm}\n% \\noindent\\makebox[\\linewidth]{\\rule{\\linewidth}{0.8pt}}\n% \\vspace{0.3cm}\n\n\\begin{abstract}\n This is a technical report on the \\revrand software library. This\n library implements Bayesian linear models (Bayesian linear regression),\n generalized linear models and approximate Gaussian processes. These\n algorithms have been implemented such that they can be used for large-scale\n learning by using stochastic variational inference. All of the algorithms\n in \\revrand use a unified feature composition framework that allows\n for easy concatenation and selective application of regression basis\n functions.\n\\end{abstract}\n\n\\tableofcontents\n\n\\section{Core Algorithms}\n\nRecent developments in stochastic gradient optimisation have simplified the\napplication of machine learning to massive datasets, in particular, modern\nstochastic optimisation algorithms are far more robust to initial learning rate\nsettings. Furthermore, Bayesian machine learning algorithms have a number of\nwell defined methods for learning model parameters and \\emph{hyperparameters}\nfrom training data, that do not involve cross validation. When used in\ncombination, stochastically optimized Bayesian machine learning algorithms\nallow practitioners to learn probabilistic predictors from large data sets with\nminimal tuning and retraining.\n\nWe make use of some of these recent developments in stochastic gradient methods\nand stochastic variational inference in \\revrand for supervisd regression\ntasks. We outline the core algorithms implemented in \\revrand in this section.\n\n\\subsection{Stochastic Gradients and Variational Objective Functions}\n\\label{sub:stochvar}\n\nWhen a machine learning objective function factorises over data,\n\\begin{equation}\n \\ffunc{\\ins, \\param}{} = \\sum_{\\inss \\in \\ins} \\ffunc{\\inss, \\param}{},\n\\end{equation}\na regular gradient descent would perform the following iterations to minimise\nthe function w.r.t.\\ the parameters $\\param$,\n\\begin{equation}\n \\param_k := \\param_{k-1} - \\lrate_k \\sum_{\\inss \\in \\ins}\n \\nabla_{\\param} \\ffunc{\\inss, \\param}{}\\!|_{\\param = \\param_{k-1}},\n\\end{equation}\nwhere $\\lrate_k$ is the learning rate (step size) at iteration $k$. Stochastic\ngradients proposes the following update,\n\\begin{equation}\n \\param_k := \\param_{k-1} - \\lrate_k \\sum_{\\inss \\in \\minibatch}\n \\nabla_{\\param} \\ffunc{\\inss, \\param}{}\\!|_{\\param = \\param_{k-1}},\n \\label{eq:sg}\n\\end{equation}\nwhere $\\minibatch \\subset \\ins$ is a mini-batch of the original dataset, where\n$|\\minibatch| \\ll |\\ins|$.\nFrequently objective functions to not entirely decompose over the data, i.e.,\n\\begin{equation}\n \\ffunc{\\ins, \\param}{} = \\sum_{\\inss \\in \\ins} \\ffunc{\\inss, \\param}{}\n + \\func{g}{\\param}{}.\n \\label{eq:objwconst}\n\\end{equation}\nHowever, it is trivial to make these objectives work in a stochastic gradient\nsetting. Let $M = |\\minibatch|$ and $N = |\\ins|$, then we divide the\ncontribution of the constant term amongst the mini-batches in stochastic \ngradients,\n\\begin{equation}\n \\param_k := \\param_{k-1} - \\lrate_k \\sum_{\\inss \\in \\minibatch}\n \\nabla_{\\param} \\ffunc{\\inss, \\param}{}\\!|_{\\param = \\param_{k-1}}\n - \\frac{M}{N} \\lrate_k \\nabla_{\\param} \n \\func{g}{\\param}{}\\!|_{\\param = \\param_{k-1}}.\n \\label{eq:wsg}\n\\end{equation} \nor, equivalently, boost the contribution of the mini-batch,\n\\begin{equation}\n \\param_k := \\param_{k-1} - \\frac{N}{M} \\lrate_k \\sum_{\\inss \\in \\minibatch}\n \\nabla_{\\param} \\ffunc{\\inss, \\param}{}\\!|_{\\param = \\param_{k-1}}\n - \\lrate_k \\nabla_{\\param} \n \\func{g}{\\param}{}\\!|_{\\param = \\param_{k-1}}.\n \\label{eq:wsg2}\n\\end{equation} \nThis is particularly relevant for variational inference where the evidence\nlower bound objective has a component independent of the data. For example, \nlets consider the model,\n\\begin{align}\n \\text{Likelihood:} \\quad &\\prod^N_{n=1} \\probC{\\targs_n}{\\param}, \\\\\n \\text{prior:} \\quad &\\probC{\\param}{\\hyper},\n\\end{align}\nwhere we want to learn the values of the hyper-parameters, $\\hyper$. Minimising\nnegative log-marginal likelihood is a good objective in this instance, since we\ndon't care about the value(s) of $\\param$,\n\\begin{equation}\n \\argmin_\\hyper - \\log \\int \\prod^N_{n=1} \\probC{\\targs_n}{\\param}\n \\probC{\\param}{\\hyper} d \\param.\n \\label{eq:lml}\n\\end{equation}\nThere are two problems with this objective however, (1) it may not factor over\ndata and (2) the integral may be intractable, for instance, if the prior and\nlikelihood are not conjugate. In variational inference we use Jensen's\ninequality to lower-bound log-marginal likelihood with a tractable objective\nfunction called the evidence lower bound (ELBO),\n\\begin{align}\n \\log \\probC{\\targ}{\\hyper} =& \\log \\int \n \\prod^N_{n=1} \\probC{\\targs_n}{\\param} \n \\probC{\\param}{\\hyper} d \\param \\nonumber \\\\\n =& \\log \\int \n \\frac{\\prod_n \\probC{\\targs_n}{\\param} \\probC{\\param}{\\hyper}}\n {\\qrob{\\param}} \\qrob{\\param} d \\param \\nonumber \\\\\n \\geq& \\int \\qrob{\\param} \\log \\sbrac{%\n \\frac{\\prod_n \\probC{\\targs_n}{\\param} \n \\probC{\\param}{\\hyper}}{\\qrob{\\param}}}\n d \\param\n\\end{align}\nwhere $\\qrob{\\param}$ is an approximation of $\\probC{\\param}{\\hyper}$ that \nmakes inference easier. This can be re-written as,\n\\begin{equation}\n \\elbo = \\sum^N_{n=1} \\expec{q}{\\log\\probC{\\targs_n}{\\param}} -\n \\KL{\\qrob{\\param}}{\\probC{\\param}{\\hyper}},\n \\label{eq:elbo}\n\\end{equation}\nwhich takes the form of Equation~\\eqref{eq:objwconst}, and so if we use\nstochastic gradients optimisation we can weight the Kullback-Leibler term like\nthe constant term, $\\func{g}{\\cdot}{}$, from Equation~\\eqref{eq:wsg}, or boost\nthe expected log likelihood term like in Equation~\\eqref{eq:wsg2}.\n\n\n\\subsection{Bayesian Linear Regression -- \\texttt{StandardLinearModel}}\n\nThe first machine learning algorithm in \\revrand is a simple Bayesian linear\nregressor of the following form,\n\\begin{align}\n \\text{Likelihood:} \\quad &\\prod^N_{n=1} \n \\gausC{\\targs_n}{\\feats_n\\T\\weights, \\var}, \\\\\n \\text{prior:} \\quad &\\gausC{\\weights}{\\mathbf{0}, \\Reg},\n\\end{align}\nwhere $\\feats_n := \\func{\\featsym}{\\inss_n, \\param}{}$ is a feature, or basis,\nfunction that maps $\\featsym : \\real{d} \\to \\real{D}$, and $\\Reg \\in\n\\real{D\\times D}$ is a diagonal matrix (i.e.~it could be $\\reg\\ident{D}$) that\nhas the effect of regularising the magnitude of the weights. This is the same\nalgorithm described in~\\citet[Chapter 2]{Rasmussen2006}. We then:\n\\begin{itemize}\n \\item Optimise $\\var, \\Reg$ and $\\param$ w.r.t.\\ log-marginal likelihood,\n \\begin{equation}\n \\log \\probC{\\targ}{\\var, \\Reg, \\param} =\n \\log \\gausC{\\targ}{\\mathbf{0}, \\var\\ident{N} + \\feat\\T\\Reg\\feat},\n \\end{equation}\n where $\\feat \\in \\real{N \\times D}$ is the concatenation of all the\n features, $\\feats_n$. Note this results in the covariance of the\n log-marginal likelihood being $N \\times N$, though we can use the\n Woodbury identity to simplify the corresponding matrix inversion.\n \\item Solve analytically for the posterior over weights, $\\weights | \\targ\n \\sim \\gaus{\\pomean, \\pocov}$ given the above hyperparameters, where,\n \\begin{align*}\n \\pocov &= \\sbrac{\\Reg\\inv + \\frac{1}{\\var}\n \\feat\\T \\feat}\\inv, \\\\\n \\pomean &= \\frac{1}{\\var} \\pocov \\feat\\T \\targ.\n \\end{align*}\n \\item Use the predictive distribution\n \\begin{align}\n \\probC{\\targs\\test}{\\targ, \\ins, \\inss\\test} &= \\int\n \\gausC{\\targs\\test}{\\feats\\testT\\weights, \\var}\n \\gausC{\\weights}{\\pomean, \\pocov} d\\weights, \\nonumber \\\\\n &= \\gausC{\\targs\\test}{\\feats\\testT \\pomean,\n \\var + \\feats\\testT \\pocov \\feats\\test}\n \\end{align}\n for query inputs, $\\inss\\test$. This gives us the useful expectations,\n \\begin{align}\n \\expece{}{\\targs\\test} &= \\feats\\testT\\pomean, \\\\\n \\evar{}{\\targs\\test} &= \\var + \\feats\\testT\\pocov\\feats\\testT.\n \\end{align}\n\\end{itemize}\n\nIt is actually easier to use the ELBO form with stochastic gradients for\nlearning the parameters of this algorithm, rather than log-marginal likelihood\nrecast using the Woodbury identity. This is because it is plainly in the same\nform as Equation \\eqref{eq:objwconst}, though it would give the same result as\nlog-marginal likelihood because the ``approximate'' posterior is the same form\nas the true posterior, i.e.\\ $\\qrob{\\weights} = \\gausC{\\weights}{\\pomean,\n \\pocov}$. The ELBO for this model is,\n\\begin{equation}\n \\elbo = \\sum^N_{n=1} \n \\expec{q}{\\log\\gausC{\\targs_n}{\\feats_n\\T\\weights, \\var}}\n - \\KL{\\gausC{\\weights}{\\pomean, \\pocov}}\n {\\gausC{\\weights}{\\mathbf{0}, \\Reg}}.\n \\label{eq:slmobj}\n\\end{equation}\nMore specifically,\n\\begin{align*}\n \\expec{q}{\\log\\gausC{\\targs_n}{\\feats_n\\T\\weights, \\var}} &=\n \\log \\gausC{\\targs_n}{\\feats_n\\T\\pomean, \\var}\n - \\frac{1}{2 \\var} \\trace{\\feats_n\\T\\feats_n\\pocov}, \\\\\n \\KL{\\gausC{\\weights}{\\pomean, \\pocov}}\n {\\gausC{\\weights}{\\mathbf{0}, \\Reg}} &=\n \\frac{1}{2} \\sbrac{\\trace{\\Reg\\inv\\pocov} + \\pomean\\T\\Reg\\inv\\pomean \n - \\log\\deter{\\pocov} + \\log\\deter{\\Reg} - D}\n\\end{align*}\nWe have not implemented a stochastic gradient version of this algorithm since\nit still requires a matrix solve of a $D \\times D$ matrix, and so is \\bigo{D^3}\nin complexity, per iteration. This is true even if we optimise the posterior\ncovariance directly (or a triangular parameterisation). The GLM presented in\nthe next section circumvents this issue, and is more suited to really large $N$\nand $D$ problems.\n\n\n\\subsection{Bayesian Generalized Linear Models --\n \\texttt{GeneralizedLinearModel}}\n\nThe algorithm of primary interest in \\revrand is the Bayesian generalized\nlinear model. The general form of the model implemented by this algorithm is,\n\\begin{align}\n \\text{Likelihood:} \\quad &\\prod^N_{n=1} \n \\probC{\\targs_n}{\\activ{\\feats_n\\T\\weights}, \\lparam}, \n \\label{eq:glmlike} \\\\\n \\text{prior:} \\quad &\\gausC{\\weights}{\\mathbf{0}, \\Reg},\n\\end{align}\nfor an arbitrary univariate likelihood, $\\prob{\\cdot}$, with an appropriate\ntransformation (inverse link) function, $\\activ{\\cdot}$, and parameter(s),\n$\\lparam$. \n\nNaturally, both calculating the exact posterior over the weights,\n$\\probC{\\weights}{\\targ, \\ins}$, and the log-marginal likelihood,\n$\\prob{\\targ}$, for hyperparameter learning are intractable since we may have a\nnon-conjugate relationship between the likelihood and prior. Therefore we must\nresort to approximating the true posterior and the log-marginal likelihood.\n\nFirstly, we approximate the true posterior over weights with a mixture of $K$\ndiagonal Gaussians,\n\\begin{align}\n \\probC{\\weights}{\\targ, \\ins} &\\approx \\qrob{\\weights}, \\nonumber \\\\\n &= \\frac{1}{K} \\sum^K_{k=1} \\gausC{\\weights}{\\pomean_k, \\dpocov_k},\n\\end{align}\nwhere $\\dpocov_k = \\diag{[\\dpocovs_{k,1}, \\ldots, \\dpocovs_{k, D}]\\T}$, which\nis inspired from similar approximations made in \\citet{gershman2012,\n nguyen2014automated}. This is a very flexible form for the approximate\nposterior, and has the nice property that our algorithm no longer has a\n\\bigo{D^3} cost associated with the number of features.\n\nThen we approximate the log marginal likelihood using auto-encoding variational\nBayes \\citep{kingma2014auto}. The exact lower bound on log marginal likelihood\nis,\n\\begin{equation}\n \\elbo = \\sum^N_{n=1} \n \\expec{q}{\\log\\probC{\\targs_n}{\\activ{\\feats_n\\T\\weights}, \\lparam}}\n - \\KL{\\textstyle\\frac{1}{K}\\textstyle\\sum_{k}\n \\gausC{\\weights}{\\pomean_k, \\dpocov_k}}\n {\\gausC{\\weights}{\\mathbf{0}, \\Reg}}.\n \\label{eq:glmobj}\n\\end{equation}\nThis can be expanded,\n\\begin{multline}\n \\elbo = \\frac{1}{K} \\sum^K_{k=1} \\sum^N_{n=1} \n \\expec{q_k}{\\log\\probC{\\targs_n}\n {\\activ{\\feats_n\\T\\weights}, \\lparam}}\n + \\frac{1}{K} \\sum^K_{k=1}\n \\expec{q_k}{\\log\\gausC{\\weights}{\\mathbf{0}, \\Reg}} \\\\\n + \\entropy{\\textstyle\\frac{1}{K}\\textstyle\\sum_{k}\n \\gausC{\\weights}{\\pomean_k, \\dpocov_k}},\n \\label{eq:glmobj_exp}\n\\end{multline}\nbut unfortunately there are two intractable integrals here, the expected log\nlikelihood, and the entropy of the Gaussian mixture. We can use the lower bound\non the entropy term also used in \\citet{gershman2012, nguyen2014automated},\n\\begin{equation}\n \\entropy{\\textstyle\\frac{1}{K}\\textstyle\\sum_{k}\n \\gausC{\\weights}{\\pomean_k, \\dpocov_k}} \\geq\n - \\frac{1}{K} \\sum_{k=1}^K \\log \\sum_{j=1}^K \\frac{1}{K}\n \\gausC{\\pomean_k}{\\pomean_j, \\dpocov_k + \\dpocov_j}.\n\\end{equation}\nWe can then use the reparameterisation trick in auto-encoding variational Bayes\n\\citep{kingma2014auto} to sample the expected log likelihood,\n\\begin{equation}\n \\sum^N_{n=1} \n \\expec{q_k}{\\log\\probC{\\targs_n}\n {\\activ{\\feats_n\\T\\weights}, \\lparam}} \\approx\n \\frac{1}{L} \\sum^{L}_{l=1} \\sum^N_{n=1} \\log\\probC{\\targs_n}\n {\\activ{\\feats_n\\T\\hat{\\weights}_k^{\\brac{l}}}, \\lparam}\n\\end{equation}\nwhere,\n\\begin{equation}\n \\hat{\\weights}_k^{\\brac{l}} =\n \\func{f}{\\pomean_k, \\dpocov_k, \\resamp^{(l)}}{k} =\n \\pomean_k + \\sqrt{\\dpocov_k} \\odot \\resamp^{(l)},\n \\qquad \\resamp^{(l)} \\sim \\gaus{\\mathbf{0}, \\ident{D}}.\n\\end{equation}\nHere $\\odot$ is the element-wise product. We can also use this trick to compute\napproximate derivatives, $\\frac{\\partial}{\\partial \\alpha}\n\\expec{q(\\alpha)}{\\log \\probC{\\targs}{\\alpha}} \\approx \\frac{1}{L} \\sum^L_{l=1}\n\\frac{\\partial}{\\partial\\alpha} \\log \\probC{\\targs}{\\func{f}{\\alpha,\n \\resamp^{(l)}}{}}$, which simplifies the implementation greatly! The\nfinal auto-encoding variational Bayes objective for our GLM is,\n\\begin{multline}\n \\elbo \\approx \\frac{1}{K} \\sum^K_{k=1} \\Bigg[\n \\frac{1}{L} \\sum^L_{l=1} \\sum^N_{n=1} \n \\log\\probC{\\targs_n}\n {\\activ{\\feats_n\\T \\hat{\\weights}_k^{\\brac{l}}}, \\lparam}\n + \\log\\gausC{\\pomean_k}{\\mathbf{0}, \\Reg}\n - \\frac{1}{2} \\trace{\\Reg\\inv\\dpocov_k} \\\\\n - \\log \\sum_{j=1}^K \\frac{1}{K}\n \\gausC{\\pomean_k}{\\pomean_j, \\dpocov_k + \\dpocov_j}\n \\Bigg].\n \\label{eq:glmobj_exp}\n\\end{multline}\nWe can straight forwardly use this objective within a stochastic gradients\nsetting using with the tactic in Equations \\eqref{eq:wsg} or \\eqref{eq:wsg2}.\n\nThe most simple and accurate method for approximating the predictive\ndistribution, $\\probC{\\targs\\test}{\\targ, \\ins, \\inss\\test}$ is to Monte-Carlo\nsample the integral,\n\\begin{equation}\n \\probC{\\targs\\test}{\\targ, \\ins, \\inss\\test} \\approx\n \\int \\probC{\\targ}{\\activ{\\feats\\testT\\weights}, \\lparam}\n \\frac{1}{K} \\sum^K_{k=1} \\gausC{\\weights}{\\pomean_k, \\dpocov_k} d \\weights.\n \\label{eq:glppred}\n\\end{equation}\nHowever, this integral is not particularly useful unless we wish to evaluate\nknown $\\targ\\test$ under the model. For prediction, it is more useful to\ncompute (using Monte-Carlo integration) the predictive expectation, \n\\begin{align}\n \\expece{}{\\targs\\test} \\approx&\n \\int \\frac{1}{K} \\sum^K_{k=1} \\gausC{\\weights}{\\pomean_k, \\dpocov_k}\n \\int \\targs\\test \\probC{\\targs\\test}{\\activ{\\feats\\testT\\weights}, \\lparam}\n d \\targs\\test d \\weights\n \\nonumber\\\\\n =& \\int \\expece{}{\\probC{\\targs\\test}\n {\\activ{\\feats\\testT\\weights}, \\lparam}}\n \\frac{1}{K} \\sum^K_{k=1} \\gausC{\\weights}{\\pomean_k, \\dpocov_k}\n d \\weights.\n \\label{eq:glmexpec}\n\\end{align}\nOften we find $\\expece{}{\\probC{\\targs\\test}{\\activ{\\feats\\testT\\weights},\n \\lparam}} = \\activ{\\feats\\testT\\weights}$, however this is only true\nwith with right choice and usage of the activation function. Furthermore, it is\nuseful to compute quantiles of the predictive density in order to ascertain the\npredictive uncertainty. We start by sampling the predictive cumulative density\nfunction, $\\Prob{\\cdot}$,\n\\begin{align}\n &\\ProbC{\\targs\\test \\leq \\cdfAlph}{\\targ, \\ins, \\inss\\test} \\nonumber\\\\ \n &\\qquad\\approx \\int \n \\frac{1}{K} \\sum^K_{k=1} \\gausC{\\weights}{\\pomean_k, \\dpocov_k}\n \\int^{\\cdfAlph}_{-\\infty} \n \\probC{\\targs\\test}{\\activ{\\feats\\testT\\weights}, \\lparam}\n d \\targs\\test d \\weights \\nonumber\\\\\n &\\qquad= \\int\n \\ProbC{\\targs\\test \\leq \\cdfAlph}{\\activ{\\feats\\testT\\weights}, \\lparam}\n \\frac{1}{K} \\sum^K_{k=1} \\gausC{\\weights}{\\pomean_k, \\dpocov_k}\n d \\weights.\n \\label{eq:lapexpec}\n\\end{align}\nOnce we have obtained sufficient samples from the (mixture) posterior we can\nobtain quantiles, $\\cdfAlph$, for some chosen level of probability, $p$, using\nroot finding techniques. Specifically, we use root finding techniques to solve\nthe following for $\\cdfAlph$,\n\\begin{equation}\n \\ProbC{\\targs\\test \\leq \\cdfAlph}{\\targ, \\ins, \\inss\\test} - p = 0.\n\\end{equation}\n\n\\subsection{Large Scale Gaussian Process Approximation}\n\nIn \\revrand we approximate Gaussian Processes \\citep{Rasmussen2006} with\nour standard and generalized linear models by using random feature functions\nsuch as those of \\citeauthor{rahimi2007} \\citeyearpar{rahimi2007,rahimi2008}\nand \\cite{le2013fastfood}. They use Bochner's theorem regarding the\nrelationship between a kernel and the Fourier transform of a non-negative\nmeasure (e.g.~a probability measure) that establishes the duality of the\ncovariance function of a stationary process and its spectral density,\n\\begin{align}\n\t\\kernl(\\tfourier) &= \\int \\specfourier(\\ffourier) \n e^{i \\ffourier\\T \\tfourier} d \\ffourier, \\\\\n\t\\specfourier(\\ffourier) &= \\int \\kernl(\\tfourier) \n e^{- i \\ffourier\\T \\tfourier} d \\tfourier.\n\t\\label{eq:fourier}\n\\end{align}\nwhere $\\kernl(\\cdot)$ is a kernel function, and $\\specfourier(\\cdot)$ its\nspectral density. \\citeauthor{rahimi2007}'s main insight\n\\citeyearpar{rahimi2007} is that we can approximate the kernel by constructing\n`suitable' random features and Monte Carlo averaging over samples from\n$\\specfourier(\\ffourier)$ for \\emph{shift invariant} kernels,\n\\begin{equation}\n \\kernl(\\inss - \\inssprime) = \\kernl(\\tfourier) \n \\approx \\frac{1}{D} \\sum_{i=1}^{D} \\singlefeatfunc{\\inss}{i}\\T\\!\n\t\\singlefeatfunc{\\inssprime}{i},\n\t\\label{eq:mcapprox}\n\\end{equation}\n$\\singlefeatfunc{\\inss}{i}$ corresponds to the $i$th sample from the feature\nmap. An example of a radial basis kernel feature vector construction using the \nabove approximation is,\n\\begin{align}\n\t\\nonumber\n \\sbrac{\\singlefeatfunc{\\inss}{i}, \\singlefeatfunc{\\inss}{D+i}}&= \n \\frac{1}{\\sqrt{D}} \\sbrac{\\cos(\\ffourier_i^T \\inss), \n \\sin(\\ffourier_i^T \\inss)}, \\qquad \\\\\n \\text{with}~\\ffourier_i & \\sim \n \\gausC{\\ffourier_i}{\\mathbf{0}, \\lenscale\\inv \\ident{d}},\n\\end{align}\nfor $i=1, \\ldots, D$, which in fact is a mapping into a $2 D$-dimensional\nfeature space. See Table~\\ref{tab:randommappings} for some of the random kernel\napproximations we use in \\revrand.\n\n\\begin{table}[htb]\n\n \\centering\n\n \\caption{Kernels and the corresponding Fourier weight ($\\ffourier_i$)\n sampling distributions for the \\citet{rahimi2007}-style random bases in\n \\revrand. Here GAL refers to a multivariate Laplace\n distribution~\\cite{kozubowski2013multivariate}.}\n\n \\begin{tabular}{r|c c}\n \\textbf{Kernel} & $\\kernl\\!\\brac{\\inss - \\inssprime}$\n & $\\specfourier(\\ffourier)$ \\\\\n \\hline\n RBF &\n $\\exp\\brac{-\\frac{\\lnorm{}{\\inss - \\inssprime}^2}{2\\lenscale^2}}$ &\n $\\ffourier_i \\sim \\gaus{\\mathbf{0}, \\lenscale\\inv\\ident{d}}$, \\\\\n Laplace & $\\exp\\brac{-\\frac{\\lnorm{}{\\inss-\\inssprime}}{\\lenscale}}$ &\n $\\ffourier_i \\sim \\prod_d \\text{Cauchy}\\!\\brac{\\lenscale\\inv}$ \\\\\n Cauchy &\n $\\frac{1}{1+\\brac{\\lnorm{}{\\inss-\\inssprime}/\\lenscale}^2}$ & \n $\\ffourier_i \\sim \\text{GAL}\\brac{1, \\mathbf{0},\n \\lenscale\\inv\\ident{d}}$ \\\\\n Matern $3/2$ & \n $\\brac{1 + \\frac{\\sqrt{3}\\lnorm{}{\\inss-\\inssprime}}{\\lenscale}}\n \\exp\\brac{-\\frac{\\sqrt{3}\\lnorm{}{\\inss-\\inssprime}}{\\lenscale}}$ & \n $\\ffourier_i \\sim \n \\text{t}_{\\nu=3}\\!\\brac{\\mathbf{0}, \\lenscale\\inv\\ident{d}}$ \\\\\n Matern $5/2$ &\n $\\brac{1 + \\frac{\\sqrt{5}\\lnorm{}{\\inss-\\inssprime}}{\\lenscale} + \n \\frac{5\\lnorm{}{\\inss - \\inssprime}^2}{3\\lenscale^2}}\n \\exp\\brac{-\\frac{\\sqrt{5}\\lnorm{}{\\inss-\\inssprime}}{\\lenscale}}$ & \n $\\ffourier_i \\sim \n \\text{t}_{\\nu=5}\\!\\brac{\\mathbf{0}, \\lenscale\\inv\\ident{d}}$ \\\\\n \\hline\n \\end{tabular}\n\n \\label{tab:randommappings}\n\n\\end{table}\n\nAll of the kernel functions in Table \\ref{tab:randommappings} have length scale\nhyperparameters, and in \\revrand these can be isotropic or anisotropic\nlength scales that are learned alongside the other hyperparameters. We have\nalso implemented a few other variants of these random basis functions, namely\nthe Fastfood \\citep{le2013fastfood} and A la Carte \\citep{yang2014} basis\nfunctions that improve scalability and representational flexibility\nrespectively. We refer the reader to our demo notebooks for further discussion\nand experiments comparing these approximate basis functions and the kernels\nthey approximate.\n\nTODO: a few figures of the approximate kernels?\n\nTODO: Basis CONCATENATION and how regularizer act as amplitude parameters\n\nAn important feature of \\revrand is that we can combine these random features\n(and non-random features) to build even more expressive features. In\nparticular, we support basis \\emph{concatenation} while still allowing basis\nfunction hyperparameter learning,\n\\begin{equation}\n \\func{\\featsym}{\\ins, \\boldsymbol\\param}{} = \\sbrac{\n \\func{\\featsym}{\\ins, \\param_1}{1},\n \\func{\\featsym}{\\ins, \\param_2}{2},\n \\ldots,\n \\func{\\featsym}{\\ins, \\param_P}{P}\n } \n\\end{equation}\nThis is in fact equivalent to kernel addition,\n\\begin{equation}\n TODO\n\\end{equation}\nWe also support \\emph{partial application} of basis functions to certain\ndimensions of the inputs ($\\ins$), while also allowing concatentation, e.g,\n\\begin{equation}\n \\func{\\featsym}{\\ins, \\boldsymbol\\param}{} = \\sbrac{\n \\func{\\featsym}{\\ins_{1:10}, \\param_1}{1},\n \\func{\\featsym}{\\ins_{5:D}, \\param_2}{2},\n \\ldots,\n \\func{\\featsym}{\\ins, \\param_P}{P}\n } \n\\end{equation}\nWhere the subscript of $\\ins$ denotes (arbitrary) column slices. See \\revrand's \ndocumentation for how to use this features.\n\n\\section{Experiments}\n\n\\subsection{Boston Housing Regression}\n\n\\begin{table}[htb]\n\n \\centering\n \\begin{tabular}{r|c c}\n \\textbf{Algorithm} & \\textbf{R-square} & \\textbf{MSLL} \\\\\n \\hline\n \\emph{SLM} & 0.9018 (0.0134) & -1.504 (0.1191) \\\\\n % \\emph{GLM} & 0.8340 (0.0491) & -0.8763 (0.1242) \\\\\n \\emph{GLM} & 0.8411 (0.0491) & -0.9209 (0.1530) \\\\\n GP & \\textbf{0.9027 (0.0137)} & \\textbf{-1.1792 (0.1581)} \\\\\n RF & 0.8467 (0.0709) & N/A \\\\ \n SVR & 0.6295 (0.0863) & N/A \\\\\n \\hline\n \\end{tabular}\n\n\\end{table}\n\n\\subsection{Handwritten Digits Classification}\n\n\\begin{table}[htb]\n\n \\centering\n \\begin{tabular}{r|c c}\n \\textbf{Algorithm} & \\textbf{Log-loss} & \\textbf{Error (\\%)} \\\\\n \\hline\n \\emph{GLM} & 0.1138 & \\textbf{2.07} \\\\\n Logistic & 0.1734 & 3.62 \\\\\n SVC & \\textbf{0.1003} & 6.99 \\\\\n GPC & 0.1405 & 2.59 \\\\\n RF & 0.1368 & 2.72 \\\\\n \\hline\n \\end{tabular}\n\n\\end{table}\n\n\\subsection{SARCOS Regression}\n\n1 million iterations\n\n\\begin{table}[htb]\n\n \\centering\n \\begin{tabular}{r|c|c c}\n \\textbf{Algorithm} & \\textbf{Approximation size} & \\textbf{SMSE} &\n \\textbf{MSLL} \\\\\n \\hline\n \\emph{GLM} & 256 & 0.0358 & -1.6644 \\\\\n & 512 & 0.0252 & -1.8397 \\\\\n & 1024 & 0.0207 & -1.9341 \\\\\n & 2048 & 0.0171 & -2.0243 \\\\\n & 8192 & 0.0152 & -1.9804 \\\\\n \\hline\n \\end{tabular}\n\n\\end{table}\n\n\\bibliography{report}\n\n\\end{document}\n", "meta": {"hexsha": "2f67c78280b79a4401bcc8b2c33518fa96ca3606", "size": 25125, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "docs/report/report.tex", "max_stars_repo_name": "smokarizadeh/revrand", "max_stars_repo_head_hexsha": "52288c48eb3c3d5d887292ff669b33babdefcda7", "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/report/report.tex", "max_issues_repo_name": "smokarizadeh/revrand", "max_issues_repo_head_hexsha": "52288c48eb3c3d5d887292ff669b33babdefcda7", "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/report/report.tex", "max_forks_repo_name": "smokarizadeh/revrand", "max_forks_repo_head_hexsha": "52288c48eb3c3d5d887292ff669b33babdefcda7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-08-06T14:16:22.000Z", "max_forks_repo_forks_event_max_datetime": "2018-08-06T14:16:22.000Z", "avg_line_length": 42.6570458404, "max_line_length": 80, "alphanum_fraction": 0.6749054726, "num_tokens": 8279, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.34510528442897664, "lm_q1q2_score": 0.18063512839558432}}
{"text": "% !TEX root=/home/tavant/these/manuscript/src/manuscript.tex\n\n\n\\section{Characteristics and performances of the LPPic simulation code }\n\\label{sec-lppic}\n\n\n\\LPPic is the electrostatic particle-in-cell simulation code developed at \\ac{LPP} to study principally magnetized plasma thruster, such as the \\ac{HET}.\nWritten in Fortran (2008), it uses the Message Passing Interface (MPI) to parallelize the computational load using a domain decomposition.\nThe principle of the domain decomposition is that each Central Processing Unit (CPU) knows a small chunk of the whole domain.\nWe use {\\sc Hypre}'s multigrid solver to solve Poisson equation in \\ac{2D} \\citep{falgout2002}.\n\nThe main data input/output is done using the HDF5 format, which enables parallel access to a hierarchical file.\nThe output data does not yet use the open standard for particle-mesh data files (openPMD).\nThus, the data post processing is done using a python package.\n\nThe use of these efficient libraries allows us to obtain a good scalability.\n\\Cref{fig-strongperfo} shows the speed up measured for the Strong Scalability test.\nThe Strong scalability compares the performances of the execution of the task at fixed workload with varying the number of CPUs.\nThe theoretical speedup accessible is given by \\citet{amdahl1967} as\n\\begin{equation} \\label{eq-amdahl}\n S = \\frac{1}{1 - \\alpha + \\frac{\\alpha}{s}}\n\\end{equation}\nwith $\\alpha$ the proportion of the task that is parallel, and $s$ the speedup of the parallelized part.\nA perfectly parallel code has $\\alpha=1$, hence a speedup $S=s$.\n\nIn \\cref{fig-strongperfo} are shown the speedup for the overall simulation, as well as the main functions of the \\ac{PIC} algorithm (Charge deposition to the mesh, Particle pusher, Monte Carlo Collision and the Poisson solver).\nThe scalability test is realized over two \\ac{2D} radial-azimuthal cases. \nThe bigger case uses a mesh of $1000\\times1024$ cells with $140$ particles per cell, which corresponds to a typical simulation case.\nUnfortunately, this case cannot be run with less than 240 CPUs because of the maximum memory available per CPU. \nHence, we use a case four times smaller to test fewer number of CPU.\nThe simulation is run over 2000 time steps.\nMore information on the scalability is given in \\cref{an-scalability}.\n\\begin{figure}[hbt]\n \\centering\n \\includegraphics[width=\\textwidth]{StrongScalingOccigen_speedup.pdf}\n \\caption{Strong scalability profile of \\LPPic with a small and a large job on the Cluster Occigen (CINES). In addition to the overall performance, the profiles of the main sub-functions of the \\acs{PIC} loops are given. }\n \\label{fig-strongperfo}\n\\end{figure}\n\n\nWe can see that the overall performance of the code is very good, as it scales as if it is parallelized at 91\\% from Amdahl's law.\nMost of the sub-functions have higher speed-ups, but the Poisson solver does not scale at all.\nIt is due to the size of the chunk of domain of each CPU, which is too small.\nA way to improve the performances of \\LPPic would be to use an hybrid parallelization with the shared memory openMP library.\nBut the current performance is acceptable, as the typical simulation cases presented in this manuscript run in around one week (7 days) on 360 CPUs.\n\n\\vspace{1em}\n\nThe development of the simulation code \\LPPic started in 2015 by Vivien Croes.\nI joined the development with Romain Lucken in 2016, and Thomas Charoy started in 2017.\nBecause of the number of contributors, and our different experiences in software development, we quickly set a Continuous Integration (CI) pipeline on a self hosted server using Teamcity.\nThis allows a systematic verification of the modifications by the mean of unit, mezzanine and integration tests \\citep{turner2016}.\n\nThe validation of the code is done using the Benchmark of Turner et al.(2013) \\citenum{turner2013}.\nWhile it allows to validate a significant part of the \\ac{PIC} code, it is not magnetized and only in \\ac{1D}.\nUnfortunately, this is the only Benchmark available.\nHence, the comparison of several codes on a \\ac{2D} magnetized has been conducted in 2019 by Thomas Charoy in order to create a new Benchmark to validate such simulation codes, in \\citet{charoy2019}.\n\n\nSince 2015, \\LPPic has grown to 23000 lines of code, has been used on more than 5 different clusters of various architectures, and has been used to produce several publications \\citep{croes2017a,croes2018,tavant2018,tavant2019,lucken2018,lucken2019}.\n", "meta": {"hexsha": "6da8751d83f87a1374da119cf5d78caad6a0a3d6", "size": 4467, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "src/Chapitre1/6_LPPIC.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/6_LPPIC.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/6_LPPIC.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.0483870968, "max_line_length": 250, "alphanum_fraction": 0.788896351, "num_tokens": 1101, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.3040416623541848, "lm_q1q2_score": 0.18019533827183798}}
{"text": "%%\n%% Automatically generated file from DocOnce source\n%% (https://github.com/hplgit/doconce/)\n%%\n%%\n% #ifdef PTEX2TEX_EXPLANATION\n%%\n%% The file follows the ptex2tex extended LaTeX format, see\n%% ptex2tex: http://code.google.com/p/ptex2tex/\n%%\n%% Run\n%% ptex2tex myfile\n%% or\n%% doconce ptex2tex myfile\n%%\n%% to turn myfile.p.tex into an ordinary LaTeX file myfile.tex.\n%% (The ptex2tex program: http://code.google.com/p/ptex2tex)\n%% Many preprocess options can be added to ptex2tex or doconce ptex2tex\n%%\n%% ptex2tex -DMINTED myfile\n%% doconce ptex2tex myfile envir=minted\n%%\n%% ptex2tex will typeset code environments according to a global or local\n%% .ptex2tex.cfg configure file. doconce ptex2tex will typeset code\n%% according to options on the command line (just type doconce ptex2tex to\n%% see examples). If doconce ptex2tex has envir=minted, it enables the\n%% minted style without needing -DMINTED.\n% #endif\n\n% #define PREAMBLE\n\n% #ifdef PREAMBLE\n%-------------------- begin preamble ----------------------\n\n\\documentclass[%\noneside, % oneside: electronic viewing, twoside: printing\nfinal, % draft: marks overfull hboxes, figures with paths\n10pt]{article}\n\n\\listfiles % print all files needed to compile this document\n\n\\usepackage{relsize,makeidx,color,setspace,amsmath,amsfonts,amssymb}\n\\usepackage[table]{xcolor}\n\\usepackage{bm,ltablex,microtype}\n\n\\usepackage[pdftex]{graphicx}\n\n\\usepackage{ptex2tex}\n% #ifdef MINTED\n\\usepackage{minted}\n\\usemintedstyle{default}\n% #endif\n\n\\usepackage[T1]{fontenc}\n%\\usepackage[latin1]{inputenc}\n\\usepackage{ucs}\n\\usepackage[utf8x]{inputenc}\n\n\\usepackage{lmodern} % Latin Modern fonts derived from Computer Modern\n\n% Hyperlinks in PDF:\n\\definecolor{linkcolor}{rgb}{0,0,0.4}\n\\usepackage{hyperref}\n\\hypersetup{\n breaklinks=true,\n colorlinks=true,\n linkcolor=linkcolor,\n urlcolor=linkcolor,\n citecolor=black,\n filecolor=black,\n %filecolor=blue,\n pdfmenubar=true,\n pdftoolbar=true,\n bookmarksdepth=3 % Uncomment (and tweak) for PDF bookmarks with more levels than the TOC\n }\n%\\hyperbaseurl{} % hyperlinks are relative to this root\n\n\\setcounter{tocdepth}{2} % levels in table of contents\n\n% prevent orhpans and widows\n\\clubpenalty = 10000\n\\widowpenalty = 10000\n\n% --- end of standard preamble for documents ---\n\n\n% insert custom LaTeX commands...\n\n\\raggedbottom\n\\makeindex\n\\usepackage[totoc]{idxlayout} % for index in the toc\n\\usepackage[nottoc]{tocbibind} % for references/bibliography in the toc\n\n%-------------------- end preamble ----------------------\n\n\\begin{document}\n\n% matching end for #ifdef PREAMBLE\n% #endif\n\n\\newcommand{\\exercisesection}[1]{\\subsection*{#1}}\n\n\n% ------------------- main content ----------------------\n\n\n\n% ----------------- title -------------------------\n\n\\thispagestyle{empty}\n\n\\begin{center}\n{\\LARGE\\bf\n\\begin{spacing}{1.25}\nDay 3: Exercise set 2\n\\end{spacing}\n}\n\\end{center}\n\n% ----------------- author(s) -------------------------\n\n\\begin{center}\n{\\bf Data Analysis and Machine Learning for Nuclear Physics${}^{}$} \\\\ [0mm]\n\\end{center}\n\n\\begin{center}\n% List of all institutions:\n\\end{center}\n \n% ----------------- end author(s) -------------------------\n\n% --- begin date ---\n\\begin{center}\nJun 25, 2020\n\\end{center}\n% --- end date ---\n\n\\vspace{1cm}\n\n\n\\subsection{Day three exercises}\n\n\n\\paragraph{Exercise 1.}\nThis exercise is a continuation of exercise 3 from exercise set 1. We will\nuse the same function to generate our data set, still staying with a\nsimple function $y(x)$ which we want to fit using linear regression,\nbut now extending the analysis to include the Ridge and the Lasso\nregression methods. You can use the code under the Regression as an example on how to use the Ridge and the Lasso methods, see the \\href{{https://compphysics.github.io/MachineLearning/doc/pub/Regression/html/Regression-bs.html}}{regression slides}). \n\nWe will thus again generate our own dataset for a function $y(x)$ where \n$x \\in [0,1]$ and defined by random numbers computed with the uniform\ndistribution. The function $y$ is a quadratic polynomial in $x$ with\nadded stochastic noise according to the normal distribution $\\cal{N}(0,1)$.\n\nThe following simple Python instructions define our $x$ and $y$ values (with 100 data points).\n\\bpycod\nx = np.random.rand(100,1)\ny = 5*x*x+0.1*np.random.randn(100,1)\n\\epycod\n\n\\begin{enumerate}\n\\item (1a) Write your own code for the Ridge method (see chapter 3.4 of Hastie \\emph{et al.}, equations (3.43) and (3.44)) and compute the parametrization for different values of $\\lambda$. Compare and analyze your results with those from exercise 2. Study the dependence on $\\lambda$ while also varying the strength of the noise in your expression for $y(x)$. \n\n\\item (1b) Repeat the above but using the functionality of \\textbf{Scikit-Learn}. Compare your code with the results from \\textbf{Scikit-Learn}. Remember to run with the same random numbers for generating $x$ and $y$. \n\n\\item (1c) Our next step is to study the variance of the parameters $\\beta_1$ and $\\beta_2$ (assuming that we are parameterizing our function with a second-order polynomial). We will use standard linear regression and the Ridge regression. You can now opt for either writing your own function or using \\textbf{Scikit-Learn} to find the parameters $\\beta$. From your results calculate the variance of these paramaters (recall that this is equal to the diagonal elements of the matrix $(\\hat{X}^T\\hat{X})+\\lambda\\hat{I})^{-1}$). Discuss the results of these variances as functions of $\\lambda$. In particular, try to link your discussion with the discussion in Hastie \\emph{et al.} and their figures 3.10 and 3.11. \\textbf{Scikit-Learn} may not provide the variance of the parameters $\\beta$. This needs to be checked. With your own code you can however do so.\n\n\\item (1d) Repeat the previous step but add now the Lasso method, see equation (3.53) of Hastie \\emph{et al.}. Discuss your results and compare with standard regression and the Ridge regression results. You can write your own code or use the functionality of \\textbf{scikit-learn}. We recommend the latter since we have not yet discussed how to solve the Lasso equations numerically. Also, you do not need to compute the variance of the parameters $\\beta$ but you can extract their values and study their behavior as functions of the regularization parameter $\\lambda$.\n\n\\item (1e) Finally, using \\textbf{Scikit-Learn} or your own code, compute also the mean square error, a risk metric corresponding to the expected value of the squared (quadratic) error defined as\n\\end{enumerate}\n\n\\noindent\n\\[ MSE(\\hat{y},\\hat{\\tilde{y}}) = \\frac{1}{n}\n\\sum_{i=0}^{n-1}(y_i-\\tilde{y}_i)^2, \n\\] \nand the $R^2$ score function.\nIf $\\tilde{\\hat{y}}_i$ is the predicted value of the $i-th$ sample and $y_i$ is the corresponding true value, then the score $R^2$ is defined as\n\\[\nR^2(\\hat{y}, \\tilde{\\hat{y}}) = 1 - \\frac{\\sum_{i=0}^{n - 1} (y_i - \\tilde{y}_i)^2}{\\sum_{i=0}^{n - 1} (y_i - \\bar{y})^2},\n\\]\nwhere we have defined the mean value of $\\hat{y}$ as\n\\[\n\\bar{y} = \\frac{1}{n} \\sum_{i=0}^{n - 1} y_i.\n\\]\nDiscuss these quantities as functions of the variable $\\lambda$ in the Ridge and Lasso regression methods. \n\n\\subsection{Exercise 2}\n\n\nA much used approach before starting to train the data is to preprocess our\ndata. Normally the data may need a rescaling and/or may be sensitive\nto extreme values. Scaling the data renders our inputs much more\nsuitable for the algorithms we want to employ.\n\n\\textbf{Scikit-Learn} has several functions which allow us to rescale the\ndata, normally resulting in much better results in terms of various\naccuracy scores. The \\textbf{StandardScaler} function in \\textbf{Scikit-Learn}\nensures that for each feature/predictor we study the mean value is\nzero and the variance is one (every column in the design/feature\nmatrix). This scaling has the drawback that it does not ensure that\nwe have a particular maximum or minimum in our data set. Another\nfunction included in \\textbf{Scikit-Learn} is the \\textbf{MinMaxScaler} which\nensures that all features are exactly between $0$ and $1$. The\n\n\nThe \\textbf{Normalizer} scales each data\npoint such that the feature vector has a euclidean length of one. In other words, it\nprojects a data point on the circle (or sphere in the case of higher dimensions) with a\nradius of 1. This means every data point is scaled by a different number (by the\ninverse of it’s length).\nThis normalization is often used when only the direction (or angle) of the data matters,\nnot the length of the feature vector.\n\nThe \\textbf{RobustScaler} works similarly to the StandardScaler in that it\nensures statistical properties for each feature that guarantee that\nthey are on the same scale. However, the RobustScaler uses the median\nand quartiles, instead of mean and variance. This makes the\nRobustScaler ignore data points that are very different from the rest\n(like measurement errors). These odd data points are also called\noutliers, and might often lead to trouble for other scaling\ntechniques.\n\n\nIt also common to split the data in a \\textbf{training} set and a \\textbf{testing} set. A typical split is to use $80\\%$ of the data for training and the rest\nfor testing. This can be done as follows with our design matrix $\\bm{X}$ and data $\\bm{y}$ (remember to import \\textbf{scikit-learn})\n\\bpycod\n# split in training and test data\nX_train, X_test, y_train, y_test = train_test_split(X,y,test_size=0.2)\n\\epycod\nThen we can use the stadndard scale to scale our data as\n\\bpycod\nscaler = StandardScaler()\nscaler.fit(X_train)\nX_train_scaled = scaler.transform(X_train)\nX_test_scaled = scaler.transform(X_test)\n\\epycod\n\n\nIn this exercise we want you to to compute the MSE for the training\ndata and the test data as function of the complexity of a polynomial,\nthat is the degree of a given polynomial. We want you also to compute the $R2$ score as function of the complexity of the model for both training data and test data. You should also run the calculation with and without scaling. \n\nOne of \nthe aims is to reproduce Figure 2.11 of \\href{{https://github.com/CompPhysics/MLErasmus/blob/master/doc/Textbooks/elementsstat.pdf}}{Hastie et al}.\nWe will also use Ridge and Lasso regression. \n\n\nOur data is defined by $x\\in [-3,3]$ with a total of for example $100$ data points.\n\\bpycod\nnp.random.seed()\nn = 100\nmaxdegree = 14\n# Make data set.\nx = np.linspace(-3, 3, n).reshape(-1, 1)\ny = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)\n\\epycod\nwhere $y$ is the function we want to fit with a given polynomial.\n\n\\begin{enumerate}\n\\item (2a) Write a first code which sets up a design matrix $X$ defined by a fifth-order polynomial. Scale your data and split it in training and test data. \n\n\\item (2b) Perform an ordinary least squares and compute the means squared error and the $R2$ factor for the training data and the test data, with and without scaling.\n\n\\item (2c) Add now a model which allows you to make polynomials up to degree $15$. Perform a standard OLS fitting of the training data and compute the MSE and $R2$ for the training and test data and plot both test and training data MSE and $R2$ as functions of the polynomial degree. Compare what you see with Figure 2.11 of Hastie et al.~Comment your results. For which polynomial degree do you find an optimal MSE (smallest value)?\n\n\\item (2d) Repeat part (2c) but now using Ridge regressions with various hyperparameters $\\lambda$. Make the same plots for the optimal $\\lambda$ value for each polynomial degree. Compare these results with those from the standard OLS approach.\n\\end{enumerate}\n\n\\noindent\n\\subsection{Example of how to solve the previous exercise}\n\n\\bpycod\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.linear_model import Ridge\nfrom sklearn.preprocessing import PolynomialFeatures\nfrom sklearn.metrics import mean_squared_error, r2_score, mean_absolute_error\n\nn = 100\n# Make data set.\nx = np.linspace(-3, 3, n).reshape(-1, 1)\ny = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)\nX_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2)\n\nfrom sklearn.preprocessing import StandardScaler\nscaler = StandardScaler()\nscaler.fit(X_train)\nX_train_scaled = scaler.transform(X_train)\nX_test_scaled = scaler.transform(X_test)\n\n\n\n# Decide which values of lambda to use\nnlambdas = 500\nlambdas = np.logspace(-3, 5, nlambdas)\n\n\nestimated_mse_sklearn = np.zeros(nlambdas)\ni = 0\nfor lmb in lambdas:\n clf_ridge = Ridge(alpha=lmb).fit(X_train_scaled, y_train)\n yridge = clf_ridge.predict(X_test_scaled)\n estimated_mse_sklearn[i] = mean_squared_error(y_test, yridge)\n i += 1\nplt.figure()\nplt.plot(np.log10(lambdas), estimated_mse_sklearn, label = 'Ridge MSE')\nplt.xlabel('log10(lambda)')\nplt.ylabel('MSE')\nplt.legend()\nplt.show()\n\n\\epycod\n\n\\subsection{And now with OLS only and Bootstrap}\n\n\\bpycod\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.utils import resample\nfrom sklearn.linear_model import LinearRegression, Ridge, Lasso\nfrom sklearn.preprocessing import PolynomialFeatures\nfrom sklearn.metrics import mean_squared_error, r2_score, mean_absolute_error\n\nn = 100\nn_boostraps = 100\nmaxdegree = 14\n\n# Make data set.\nx = np.linspace(-3, 3, n).reshape(-1, 1)\ny = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)\nerror = np.zeros(maxdegree)\nbias = np.zeros(maxdegree)\nvariance = np.zeros(maxdegree)\npolydegree = np.zeros(maxdegree)\n\n\n# Make data set.\nx = np.linspace(-3, 3, n).reshape(-1, 1)\ny = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)\nX_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2)\n\nfrom sklearn.preprocessing import StandardScaler\nscaler = StandardScaler()\nscaler.fit(X_train)\nX_train_scaled = scaler.transform(X_train)\nX_test_scaled = scaler.transform(X_test)\n\nfor degree in range(maxdegree):\n model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False))\n y_pred = np.empty((y_test.shape[0], n_boostraps))\n for i in range(n_boostraps):\n x_, y_ = resample(X_train_scaled, y_train)\n y_pred[:, i] = model.fit(x_, y_).predict(X_test_scaled).ravel()\n\n polydegree[degree] = degree\n error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )\n bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )\n variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) )\n print('Polynomial degree:', degree)\n print('Error:', error[degree])\n print('Bias^2:', bias[degree])\n print('Var:', variance[degree])\n print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))\n\nplt.plot(polydegree, error, label='Error')\nplt.plot(polydegree, bias, label='bias')\nplt.plot(polydegree, variance, label='Variance')\nplt.legend()\nplt.show()\n\n\n\n\\epycod\n\n\n\n% ------------------- end of main content ---------------\n\n% #ifdef PREAMBLE\n\\end{document}\n% #endif\n\n", "meta": {"hexsha": "9239f36e10685117bab4c646f87d8b988d9e2d0d", "size": 15286, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/ProjectsExercises/2020/hw2/pdf/hw2.p.tex", "max_stars_repo_name": "UWCNuclear/MachineLearningECT", "max_stars_repo_head_hexsha": "708b91e2e98e79e6806f32d90abb959f8d38f44b", "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/ProjectsExercises/2020/hw2/pdf/hw2.p.tex", "max_issues_repo_name": "UWCNuclear/MachineLearningECT", "max_issues_repo_head_hexsha": "708b91e2e98e79e6806f32d90abb959f8d38f44b", "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/ProjectsExercises/2020/hw2/pdf/hw2.p.tex", "max_forks_repo_name": "UWCNuclear/MachineLearningECT", "max_forks_repo_head_hexsha": "708b91e2e98e79e6806f32d90abb959f8d38f44b", "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.1948717949, "max_line_length": 860, "alphanum_fraction": 0.7285097475, "num_tokens": 4157, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4301473485858429, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.18010136542043564}}
{"text": "This chapter describes the proposed system for sense discovery problem. First, I would like to present the tools and operations in Section \\ref{section:operations}, then clarify their different variations and combinations in Section \\ref{section:variations}. The pipeline starts with calculating substitute distribution of a word in a given context explained in Section \\ref{section:subs-dist}. Then, a list of substitutes are generated by using this substitute distribution and paired with context id. Context id (e.g., $car_1$) is basically a unique identifier that helps to distinguish each context from others. The euclidean embedding algorithm SCODE uses this co-occurrence data and outputs the embedding for each word. Section \\ref{section:scode} clarifies co-occurrence modeling step and Section \\ref{section:diff-approaches} defines three types of approaches: local approach, part-of-speech based approach, global approach. Using these word embeddings and the substitute distributions I obtained word representations and context representations which will be clarified in Section \\ref{section:representations}. When each context is represented in spherical space, then $k$-means algorithm is employed detailed in Section \\ref{section:clustering}.\n\n\n\\section{Tools and Operations}\n\\label{section:operations}\n\n\n\\subsection{Data Enrichment}\n\\label{section:enrichment}\n\nSense annotation is a hard task. For the lexical sample tasks, organizers provide a test data annotated by humans which is used for system evaluation. The systems should use a training data if provided, or corpora for sense induction. Typically test data does not contain enough instance for sense induction. Data enrichment aims to increase the number of instances of target words. Assuming that our target word is $book$ in noun form. I randomly fetch arbitrary number of additional contexts from ukWaC where our target word occurs with the same part-of-speech tag. This implies that I skip those sentences in which the word $book$ functions as a verb. \\\\\n\nFor all experiments in Section \\ref{chapter:experiments}, the number of additional contexts is fixed and it is equal to $20000$, and uKWaC is used as a corpus for data enrichment.\n\n\\subsection{Substitute Word Distributions}\n\\label{section:subs-dist}\n\nIn this section, I will explain how substitute word distribution captures the paradigmatic relations of word token, and how it is computed. \\cite{sahlgren2006word} investigates the syntagmatic and paradigmatic relations captured by the Vector Space Models. His paradigmatic representation models word types using co-occurrence counts. Following the methodology used in \\citet{yatbaz2012learning} and \\citet{yatbaz2012learning}, I represent the context of word tokens using probabilities of likely substitutes. The substitute word distribution is a probability distribution of observing a word in the context of a word token. Context of a target word in a sentence is defined as the sequence of words in the window of size $2n - 1$ centered at the position of the\ntarget word token. The context excludes the target word token. \n\n\n\\begin{quote}\n``\\emph{Accordingly, the last chapter of this \\textbf{book} is devoted to our reflections on the impact of channel integration on certain public policies issues.}''\n\\end{quote}\n\n\nFor instance, in the sentence above, the context of the word token `\\emph{book}', when $n = 4$, is ``\\emph{chapter of this --- is devoted to}'', where `\\emph{---}' denotes the target word token. \\\\\n\nAssuming the position of the target word token is $0$, the context\nspans from positions $-n + 1$ to $n - 1$ and the probability of\nobserving each type $w$ in our vocabulary in the context of the target\nword token is computed using the following equation:\n\\begin{eqnarray}\n P(w_{0} = w | c_{w_{0}}) & \\propto & P(w_{-n + 1} \\dots w_{0} \\dots w_{n - 1}) \\label{eq:ngram1} \\\\\n & = & P(w_{-n + 1}) \\dots P(w_{0} | w_{-n + 1}^{-1}) \\dots P(w_{n - 1} | w_{-n + 1}^{n - 2}) \\label{eq:ngram2} \\\\\n & \\approx & P(w_{-n + 1}) \\dots P(w_{0} | w_{-n + 1}^{-1}) \\dots P(w_{n - 1} | w_{0}^{n - 2}) \\label{eq:ngram3} \\\\\n & \\propto & P(w_{0} | w_{-n + 1}^{-1}) \\dots P(w_{n - 1} | w_{0}^{n - 2}) \\label{eq:ngram4}\n\\end{eqnarray}\nWhere $w_{i}^j$ is the word sequence from $w_i$ to $w_j$ (for $i < j$)\nand $c_{w_{0}}$ is the context of the target word token at position\n$0$ of length $2n - 1$, meaning $w_{-n+1}^{-1}$ to the left and\n$w_{1}^{n-1}$ to the right of $w_{0}$. \\\\\n\nIn the Equation \\ref{eq:ngram1}, the right-hand side is proportional\nto the left-hand side because $P(c_{w_{0}})$ is independent of any\ngiven word $w$ for $w_{0}$. Using the chain rule,\nEquation \\ref{eq:ngram2} is obtained from the Equation\n\\ref{eq:ngram1}. By applying $n^{th}$-order Markov assumption, only the\nclosest $n - 1$ words in each term of the Equation \\ref{eq:ngram2} are\nused and others excluded. Result is the Equation \\ref{eq:ngram3}. The Equation \\ref{eq:ngram4} is proportional to the Equation \\ref{eq:ngram3}\nbecause terms which are do not depend on $w_{0}$ is fixed since the\ncontext of the word at position $0$ is fixed. Near the boundaries of\nthe sentence, specifically the first and last $n - 1$ words,\nappropriate terms of the Equation \\ref{eq:ngram4} are truncated or\ndropped (e.g. if $0$ is the first word of a sentence, $P(w_{0} | w_{-n\n + 1}^{-1})$ becomes $P(w_{0})$). \\\\\n \nThe probabilities required to compute the Equation \\ref{eq:ngram4} can\nbe obtained from an $n$-gram language model. For this step, I used SRILM (\\cite{stolcke02srilm}) to build a 4-gram language model with interpolated Kneser-Ney discounting using the uKWaC, a web corpus with 2 billion tokens. Words that were observed less than 2 times in the language model training data were replaced by tags, which gave us a vocabulary size of 4,254,946. For computational efficiency only the top 100 substitutes and their probabilities were computed for each position in the context of a target word using the FASTSUBS algorithm (\\cite{fastsubs}). These top 100 probabilities were normalized to add up to 1.0 giving us a legitimate probability distribution for a context.\n\nAs you seen in Table \\ref{table:subs}, the high probability substitutes reflect both semantic and syntactic properties of the context of a target word in the sentence above.\n\n\n\\begin{table}\n\\begin{center}\n \\begin{tabular}{ l | r } \\Xhline{2\\arrayrulewidth} \n \\bf Substitute Word & \\bf Probability \\\\ \\Xhline{2\\arrayrulewidth}\n book & .638 \\\\\n section & .139 \\\\\n paper & .089 \\\\\n volume & .053 \\\\\n document & .014 \\\\\n report & .013 \\\\\n work & .012 \\\\\n tutorial & .005 \\\\\n edition & .003 \\\\\n biography & .001 \\\\\n \\Xhline{2\\arrayrulewidth} \n \\end{tabular}\n\\end{center}\n \\caption[Top 10 substitutes and their probabilities for a context]{\\label{table:subs}{Top 10 substitutes and their probabilities for the context, ``\\emph{chapter of this --- is devoted to}''.}}\n\\end{table}\n\n\n\\subsection{Discretization of Substitute Word Distribution}\n\\label{section:sampling}\n\nAlthough the context of a target word was modeled as a substitute word distribution, the Euclidean co-occurrence modeling algorithm which will be introduced in the next section expects its input as discrete objects. I will list two methods to discretize substitute word distribution into discrete counterpart. \\cite{sert2013word} proposed a method which creates proximity matrix of substitute word distributions, and ids of $k$-nearest neighbors of each distribution. The second method introduced in \\cite{yatbaz2012learning} draws $k$ word types with replacement from the substitute word distributions. This method is computationally cheaper than the former one, however, the number of samples should not be small and requires attention to pick. Too small $k$ values make this setting not to represent the distribution, however, too large $k$ values make the following steps computationally expensive. From my preliminary experiments, 100 samples enough for each context. Thus, for each context, I sampled 100 word types from their correspondent substitute distributions.\n\n\\subsection{Co-occurrence Modeling with S-CODE algorithm}\n\\label{section:scode}\n\nIn this section, I give a brief introduction for the Symmetric Interaction Model of the Co-occurrence Data Embedding (CODE, \\cite{globerson2004euclidean}) and its extension Spherical Co-Occurrence Data Embedding (S-CODE, \\cite{Maron2010}). S-CODE randomly initializes co-occurrence data generated using substitute word distributions and discretization operation explained in the previous section into $d$ dimensional Euclidean sphere. After the algorithm converges, the contexts with similar substitute word distributions are close to each other. In Section \\ref{section:clustering}, I will explain how S-CODE output used, and how it combined with substitute word distributions in order to obtain high quality context embeddings. \\\\ \n\nLet $X$ and $Y$ be two categorical variables with finite cardinality\n$|X|$ and $|Y|$. We observe a set of pairs $\\{x_i, y_i\\}_{i=1}^n$\ndrawn IID from the joint distribution of $X$ and $Y$. These pairs are\nsummarized by the empirical distributions $\\bar{p}(x,y)$, $\\bar{p}(x)$\nand $\\bar{p}(y)$. The task is to find embeddings $\\phi(x)$ and\n$\\psi(y)$ for each unique variable $x$ and $y$. These embeddings require to reflect the statistical relationship between the variables $x$ and $y$ such that pairs occur together frequently should close to each other. hence, the square of Euclidean distance, \\mbox{$d^2_{x,y} = |\\phi(x) - \\psi(y)|^2$}, should be small in $d$ dimensional space. \\\\\n\nLater, \\citet{Maron2010} constrain the embedding to lie on a high dimensional\nunit sphere so that enables to approximate the partition function which is a dynamic variable, $Z$, using a constant, $\\bar{Z}$, which arises from a coarse approximation in which all pairs of embedded variables are distributed uniformly and independently on the sphere. This constraint allows to work on large datasets by avoiding to calculate $Z$ after each gradient step. Thus, in this thesis I used Spherical CODE:\n\n\\begin{equation} \\label{eq:marginal-marginal-model}\n p(x,y) = \\frac{1}{Z} \\bar{p}(x) \\bar{p}(y) e^{-d^2_{x,y}}\n\\end{equation}\nwhere $Z = \\sum_{x,y} \\bar{p}(x) \\bar{p}(y) e^{-d^2_{x,y}}$ is the\nnormalization term. We can express the log-likelihood of the joint\ndistribution over all embeddings $\\phi$ and $\\psi$ as the following:\n\n\\begin{eqnarray} \\label{eq:log-likelihood}\n \\ell(\\phi,\\psi) & = & \\sum_{x,y} \\bar{p}(x,y) \\log p(x,y) \\nonumber \\\\\n & = & \\sum_{x,y} \\bar{p}(x,y) (-\\log Z + \\log \\bar{p}(x) \\bar{p}(y) - d^2_{x,y}) \\nonumber \\\\\n & = & -\\log Z + const - \\sum_{x,y} \\bar{p}(x,y) d^2_{x,y}\n\\end{eqnarray}\n\nThe gradient of the log-likelihood depends on the sum of embeddings\n$\\phi(x)$ and $\\psi(y)$, for $x \\in X$ and $y \\in Y$, and to maximize\nthe log-likelihood, \\cite{Maron2010} use a gradient-ascent\napproach. The gradient is as follows:\n\n\\begin{equation} \\label{eq:gradient-phi}\n \\frac{\\partial \\ell(\\phi,\\psi)}{\\partial \\phi(x)} =%\n \\sum_{y} 2 \\bar{p}(x,y) {[}\\psi(y) - \\phi(x){]} +%\n \\frac{1}{Z} \\sum_{y} \\bar{p}(x) \\bar{p}(y) {[}\\phi(x) - \\psi(y){]} e^{-d^2_{x,y}}\n\\end{equation}\n\n\\begin{equation} \\label{eq:gradient-psi}\n \\frac{\\partial \\ell(\\phi,\\psi)}{\\partial \\psi(y)} =%\n \\sum_{x} 2 \\bar{p}(x,y) {[}\\phi(x) - \\psi(y){]} +%\n \\frac{1}{Z} \\sum_{x} \\bar{p}(x) \\bar{p}(y) {[}\\psi(y) - \\phi(x){]} e^{-d^2_{x,y}}\n\\end{equation}\n\nThe first sum, the gradient of the part with $d^2_{x,y}$ in\n(\\ref{eq:log-likelihood}), in (\\ref{eq:gradient-phi})\n{[}(\\ref{eq:gradient-psi}){]} acts attraction force between the\n$\\phi(x)$ ($\\psi(y)$) and all the embeddings $\\psi$ ($\\phi$) in\nproportion to respective joint empirical probabilities $\\bar{p}(x,y)$. The second sum, the gradient of $-\\log Z$ in\n(\\ref{eq:log-likelihood}), in (\\ref{eq:gradient-phi})\n{[}(\\ref{eq:gradient-psi}){]} acts a repulsion force between the\n$\\phi(x)$ ($\\psi(y)$) and all the embeddings $\\psi$ ($\\phi$) in\nproportion to respective marginal empirical probabilities $\\bar{p}(x)$\nand $\\bar{p}(y)$. \\\\\n\nIn this work, I use S-CODE with sampling based stochastic gradient ascent, a constant approximation of $Z$ (which is 0.166) and randomly initialized $\\phi$ and $\\psi$ vectors in 100 dimensional sphere ($d = 100$). The algorithm stops if the difference between two consecutive likelihood values is less than 0.0001.\n\n\n\\subsection{Clustering}\n\\label{section:clustering}\n\nIn this thesis, I tested three different clustering algorithms: Weighted $k$-means which is $k$-means algorithm with (optional) instance weights with careful initialization (\\cite{arthur2007k})\\footnote{An efficient implementation can be found in https://github.com/ai-ku/wkmeans}. In literature, there are two common methods to specify $k$, required parameter for $k$-means algorithm: \\emph{Gap Statistics} (\\cite{tibshirani00estimating}) and Pham’s heuristic (\\cite{pham2005selection}). \\\\\n\nI also tried Spherical Clustering (\\cite{shi2000normalized}) and DBSCAN (\\cite{ester1996density}). The representations I used for clustering will be explain in the following section \\ref{section:representations} and the performance of these algorithms will compare in Chapter \\ref{chapter:experiments}.\n\n\n\\section{Variations and combinations}\n\\label{section:variations}\n\nIn the previous section I explained the pipeline of operations I used for Word Sense Induction problem. In this section, I will explain the combinations of operations and their variations. In Section \\ref{section:scode} we successfully obtain embeddings that reflect the statistical relations by using S-CODE algorithm. The following section describes how can we use these embeddings to acquire context embeddings. After that, in Section \\ref{section:diff-approaches} I will discuss local, POS-based, and global approach for the co-occurrence modeling step and the clustering step. \n\n\n\\subsection{Different Representations}\n\\label{section:representations}\n\n\n\n\\subsection{Different approaches}\n\\label{section:diff-approaches}\n\nThe following three approaches tested in the thesis:\n\n\\paragraph{Local approach:} In the local approach, clustering is employed for each target word, separately. In other words, \n", "meta": {"hexsha": "abfecc4bcaecb45b026bdbd439b158a110894295", "size": 14269, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "thesis/system.tex", "max_stars_repo_name": "osmanbaskaya/wsid", "max_stars_repo_head_hexsha": "b486fb907a85981aa0d0c30210df1d0c33fcbff2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2016-12-22T21:41:21.000Z", "max_stars_repo_stars_event_max_datetime": "2016-12-22T21:41:21.000Z", "max_issues_repo_path": "thesis/system.tex", "max_issues_repo_name": "osmanbaskaya/wsid", "max_issues_repo_head_hexsha": "b486fb907a85981aa0d0c30210df1d0c33fcbff2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2015-06-20T14:09:35.000Z", "max_issues_repo_issues_event_max_datetime": "2015-06-26T18:29:26.000Z", "max_forks_repo_path": "thesis/system.tex", "max_forks_repo_name": "osmanbaskaya/wsid", "max_forks_repo_head_hexsha": "b486fb907a85981aa0d0c30210df1d0c33fcbff2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-05-11T00:12:59.000Z", "max_forks_repo_forks_event_max_datetime": "2018-05-11T00:12:59.000Z", "avg_line_length": 82.0057471264, "max_line_length": 1254, "alphanum_fraction": 0.7440605508, "num_tokens": 3810, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.34864514210180597, "lm_q1q2_score": 0.17976837878777202}}
{"text": "%% LyX 2.2.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[DM,lsstdraft,toc,authoryear]{lsstdoc}\n\\usepackage{amsmath}\n\\usepackage{amssymb}\n\\usepackage{fontspec}\n\\usepackage{graphicx}\n\\ifx\\hypersetup\\undefined\n \\AtBeginDocument{%\n \\hypersetup{unicode=true}\n }\n\\else\n \\hypersetup{unicode=true}\n\\fi\n\n\\makeatletter\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% User specified LaTeX commands.\n%\\usepackage{caption}\n%\\usepackage{authblk}\n%% \\usepackage{natbib,twoopt,ifthen}\n%\\usepackage{aas_macros}\n \n\\newcommand{\\FixMe}[1]{{\\bf \\large #1}}\n\\newcommand{\\ClName}[1]{{\\bf #1}}\n\\newcommand{\\RoutineName}[1]{\\texttt{#1}}\n%\\def\\arcsec{\\hbox{$^{\\prime\\prime}$}}\n%\\addmargin{-0.5cm}{-0.5cm}\n%\\providecommand{\\eprint}[1]{\\href{http://arxiv.org/abs/#1}{#1}}\n\n% Change history defined here.\n% Order: oldest first.\n% Fields: VERSION, DATE, DESCRIPTION, OWNER NAME.\n% See LPM-51 for version number policy.\n\\setDocChangeRecord{%\n \\addtohist{1}{2017-09-01}{Unreleased.}{John Parejko}\n}\n\n\\makeatother\n\n\\usepackage{xunicode}\n\\begin{document}\n\n\\title[jointcal]{jointcal: Simultaneous Astrometry \\& Photometry for thousands of\nExposures with Large CCD Mosaics}\n\n\\author{John Parejko (University of Washington), Pierre Astier (LPNHE/IN2P3/CNRS\nParis)}\n\n\\setDocRef{DMTN-036}\n\n\\date{\\today}\n\n\\setDocAbstract{The jointcal package simultaneously optimizes the astrometric and\nphotometric calibrations of a set of astronomical images. In principle\nand often in practice, this approach produces distortion and thoroughput\nmodels which are more precise than when fitted independently. This\nis especially true when the images are deeper than the astrometric\nreference catalogs. In the ``Astromatic'' software suite, this simultaneous\nastrometry functionality is fulfilled by ``SCAMP''. The code we\ndescribe here has similar aims, but follows a slightly different route.\nJointcal is built on top of the the LSST Data Management software\nstack.}\n\n\\maketitle\n\\tableofcontents{}\n\n\\section{Introduction}\n\nWith deep astronomical images, it is extremely common that the relative\nastrometry and photometry between images is considerably more precise\nthan the accuracy of external catalogs, where ``more precise'' can\nbe as large as two orders of magnitude. For applications where the\nquality of relative astrometry is important or vital, it is important\nto rely on some sort of simultaneous astrometry solution, if possible\noptimal in a statistical sense.\n\nThis package performs a least-squares fit to a set of images. Since\nit aims at statistical optimality, we maximize the likelihood of the\nmeasurements with respect to all unknown parameters required to describe\nthe data. These parameters are mostly in two sets: the position on\nthe sky of the objects in common between the images, and the mapping\nof each image to the sky. To these obvious parameters, one can add\nproper motions (where applicable), and parameters describing the differential\neffect of atmospheric refraction on the position of objects. It is\nclear that one cannot fit simultaneously the position on the sky and\nthe mappings from CCD coordinates to the sky, without extra constraints:\nthe ``sky'' coordinate system is then undefined, and one needs reference\npositions in order to fully define this frame. We use the GAIA catalog\nas our reference catalog, and may supplement it with deeper data (e.g.\nPS1) where available.\n\nSCAMP \\footnote{See \\href{http://www.astromatic.net/software/scamp}{http://www.astromatic.net/software/scamp}}is\nthe reference package for simultaneous astrometry in astronomy, at\nleast for relative alignment of wide-field images prior to stacking.\nRegarding optimization, SCAMP follows a somewhat different route from\nours: it does not optimize over the position of common objects but\nrather minimizes the distance between pairs of transformed measurements\nof the same object. This approach is not a maximum likelihood optimization,\nand is likely statistically sub-optimal. The main drawback of SCAMP\nin the context of LSST is the fact that it is a program and not a\nlibrary, and hence not flexible regarding formats of images and catalogs.\nBut since SCAMP has been used for almost a decade in production by\nvarious teams, the quality checking tools it provides should likely\nbe reproduced in the context of our package. We provide residual ntuples\nand hope that the first serious users will contribute plotting tools.\n\nLoading input catalogs and their metadata from disk is a large fraction\nof the total time. We can save time by re-using the input catalog\nto fit a similar style of multi-component model for the relative and\nabsolute photometry.\n\nThe plan of this note is as follows: we first sketch the algorithm\n(\\S\\ref{sec:algo}). We provide our least-squares formulation in\n\\S\\ref{sec:mathematical-formalism}, and describe the how we evaluate\nthe derivatives with respect to the parameters. We then describe how\nwe associate the measurements of each object in different exposures\nin \\S \\ref{sec:catalog-association}. \n\n\\section{Past work}\n\nA summary of past work on this topic will go here eventually...\n\\begin{itemize}\n\\item SDSS übercal \\citep{2008ApJ...674.1217P}\n\\item Pan-Starrs übercal \\citep{2013ApJS..205...20M}\n\\item DECam WcsFit \\citep{2017PASP..129g4503B}\n\\end{itemize}\n\n\\section{Algorithm flow \\label{sec:algo}}\n\nThe algorithm assumes that the initial single-frame WCS fits of the\ninput images are accurate to $\\sim1\\arcsec$. Currently, the code\nproperly interprets the SIP WCS's (relying on \\ClName{lsst::afw::wcs}),\nwith or without distortions. The code might handle transparently the\n``PV'' encoding of distortions (used in SCAMP and Swarp), but lacks\nthe IO's required to use this format. Note that in both instances,\nthe WCS boils down to a polynomial 2D transform from CCD space to\na tangent plane, followed by a gnomonic de-projection to the celestial\nsphere. The difference between formats lies into the encoding of the\npolynomial, but they map exactly the same space of distortion functions.\n\nThe algorithm can be roughly split into these successive steps: \n\\begin{enumerate}\n\\item load the input catalogs and 'rough' WCS's and catalogs, and select\nthe sources to use in the fit (e.g. good centroids, unblended, high\nenough signal-to-noise) via the configured SourceSelectorTask.\n\\item Associate these catalogs, i.e. associate each detection of the same\non-sky source, and associate those on-sky sources with a reference\ncatalog (if provided).\n\\item Iteratively fit the model parameters and ``true'' on-sky values,\nclipping outliers at each iteration.\n\\item Output results. \n\\end{enumerate}\n\n\\section{Mathematical formalism\\label{sec:mathematical-formalism}}\n\n\\subsection{Definitions\\label{subsec:Definitions}}\n\n\\begin{figure*}\n\\begin{centering}\n\\includegraphics[width=0.8\\textwidth]{_static/CcdImageDiagram}\n\\par\\end{centering}\n\\caption{The relationship between MeasuredStars, CcdImages, and FittedStars.\\label{fig:NotationDigram}}\n\\end{figure*}\n\nWe use the following notation in the mathematics that follows, with\n\\ClName{CamelCased} words referring to the objects in the code..\nThese terms are diagramed in Fig. \\ref{fig:NotationDigram}.\n\\begin{itemize}\n\\item $\\gamma$ is the \\ClName{CcdImage} representing one exposure (\\emph{visit}\nin LSST terminology) on one CCD. The \\ClName{CcdImage} contains metadata\nabout that visit and CCD detector, as well as the catalog of sources\nthat were selected for use in the fit;\n\\item $S_{\\gamma,i}$ is the position (pixels) and flux (instrument-flux\ncounts) ($x_{\\gamma i},y_{\\gamma i},f_{\\gamma i}$) of the \\ClName{MeasuredStar}\non \\ClName{CcdImage} $\\gamma$ corresponding to the on-sky \\ClName{FittedStar}\n$i$;\n\\item $F_{i}$ is the (sky) position and calibrated-flux $(\\alpha_{i},\\beta_{i},\\phi_{i})$\nof the star $i$, with some corresponding number of measurements represented\nby \\ClName{MeasuredStar}s;\n\\item $M_{\\gamma}$ is the mapping for \\ClName{CcdImage} $\\gamma$ from\npixels/instrument-flux $(x,y,f)$ to the tangent plane on the sky/calibrated-flux\n$(\\alpha,\\beta,\\phi)$. This mapping may consist of models constrained\nacross visits (different between CCDs; e.g. an affine model for each\nCCD position, assuming CCDs do not move), constrained across CCDs\nand visits (e.g. a 2d radial polynomial of the optics) or constrained\nacross CCDs (different between visits; e.g. a 2d polynomial of the\nsky);\n\\item $R_{j}$ refers to the (sky) position and (reference) calibrated-flux\n$(\\alpha_{j},\\beta_{j},\\phi_{j})$ of \\ClName{RefStar} $j$.\n\\end{itemize}\nIn addition to the terms defined in the diagram above, we define the\nfollowing terms for the measurement component,\n\\begin{itemize}\n\\item $P_{\\gamma}$ is a projector from sidereal coordinate to some tangent\nplane; $P_{\\gamma}$ is user-defined;\n\\item $W_{\\gamma,i}$ is the measurement weight of $M_{\\gamma}(S_{\\gamma,i})$,\ni.e. the inverse of the 2$\\times$2 covariance matrix (for astrometry),\nor the inverse of the transformed instrument-flux error;\n\\end{itemize}\nand reference component, \n\\begin{itemize}\n\\item $P$ is some (user-provided) sky to tangent plane projector;\n\\item $W_{j}$ is the weight matrix of the reference star, i.e. the inverse\nof the projected position error $P(R_{j})$, or the inverse of the\nreference flux error.\n\\end{itemize}\n\n\\subsection{Least-squares expression}\n\nThe fit consists of minimizing, for photometry, \n\\begin{align}\n\\chi^{2} & =\\sum_{\\gamma,i}[M_{\\gamma}(S_{\\gamma,i})-F_{i}]^{T}W_{\\gamma,i}[M_{\\gamma}(S_{\\gamma,i})-F_{i}] & \\textrm{(meas. terms)}\\nonumber \\\\\n & +\\sum_{j}[F_{j}-R_{j}]^{T}W_{j}[F_{j}-R_{j}] & \\textrm{(ref. terms)}\\label{eq:photometry-chi2}\n\\end{align}\nand for astrometry, taking into account the projection from the sky\nto the tangent plane $P$:\n\\begin{align}\n\\chi^{2} & =\\sum_{\\gamma,i}[M_{\\gamma}(S_{\\gamma,i})-P_{\\gamma}(F_{i})]^{T}W_{\\gamma,i}[M_{\\gamma}(S_{\\gamma,i})-P_{\\gamma}(F_{i})] & \\textrm{(meas. terms)}\\nonumber \\\\\n & +\\sum_{j}[P(F_{j})-P(R_{j})]^{T}W_{j}[P(F_{j})-P(R_{j})] & \\textrm{(ref. terms)}\\label{eq:astrometry-chi2}\n\\end{align}\nwhere the first line iterates on all \\ClName{MeasuredStar} $\\gamma,i$,\nfrom all \\ClName{CcdImage} $\\gamma$, and the second iterates on\nall \\ClName{RefStar} $j$. In the first terms, the object at position\n$F_{i}$ is the one that was measured at position $S_{\\gamma,i}$\nin image $\\gamma$. The association between \\ClName{MeasuredStar}s,\n\\ClName{FittedStar}s, and \\ClName{RefStar}s is described in Section\n\\ref{sec:catalog-association}.\n\nThe measurement terms compare the measurement positions/fluxes to\nobjects positions/fluxes (the relative astrometry/photometry), the\nreference terms compare object positions/fluxes to reference positions/fluxes\n(the absolute astrometry/photometry). We need these two sets of terms\nbecause not all objects $F_{i}$ in the first terms appear in the\nsecond terms: many objects in the images will not be in the reference\ncatalogs, but those objects do help to constrain the mappings $M_{\\gamma}$.\nIn addition, with so many measurements of our sources, we may have\nbetter overall errors on the positions and fluxes than the reference\ncatalog can provide.\n\nThe expressions above depend on two sets of parameters: the parameters\ndefining the mappings $M$ and the on-sky positions/calibrated fluxes\n$F_{i}$. For a practical problem, this amounts to a very large number\nof parameters, which becomes tractable when one notes that every term\nin the $\\chi2$ is only linked to a small number of parameters. We\nexploit this feature to rapidly compute the gradient and the Hessian\nof the $\\chi^{2}$ in order to find the minimum.\n\nSo far, we have not specified how we model the mappings $M$ nor how\nwe choose the various projectors that appear in expression \\ref{eq:astrometry-chi2}.\nThe code has been written to allow the user to provide their own versions\nof both the model for mappings and the projection scheme. We however\nprovide some implementations for both aspects that we discuss in the\nnext two sections.\n\n\\subsection{Minimization approach}\n\nThe expressions for astrometry (eq. \\ref{eq:astrometry-chi2}) and\nphotometry (eq. \\ref{eq:photometry-chi2}) depend on two sets of parameters:\nthe parameters $\\eta$ defining the mappings $M_{\\gamma}(S_{\\gamma,i})\\equiv M_{\\gamma}(\\eta_{\\gamma},S_{\\gamma,i})$,\nand the ``true'' calibrated fluxes $F_{i}$. We write the measurement\nand reference residuals, with their respective weights $W_{\\gamma i}$\nand $W_{j}$, as separate functions of their parameters, for photometry,\n\n\\begin{align}\nD_{\\gamma i} & =M_{\\gamma}(S_{\\gamma,i})-F_{i}\\label{eq:photometry_residual_vector_measurement}\\\\\nD_{j} & =F_{j}-R_{j}\\label{eq:photometry_residual_vector_reference}\n\\end{align}\nand for astrometry,\n\n\\begin{align}\nD_{\\gamma i} & =M_{\\gamma}(S_{\\gamma,i})-P_{\\gamma}(F_{i})\\label{eq:astrometry_residual_vector_measurement}\\\\\nD_{j} & =[P(F_{j})-P(R_{j})]\\label{eq:astrometry_residual_vector_reference}\n\\end{align}\nThis results in the generalized $\\chi^{2}$ expression (compare to\neq. \\ref{eq:astrometry-chi2} and \\ref{eq:photometry-chi2}),\n\n\\begin{align}\n\\chi^{2} & =\\sum_{\\gamma,i}{D_{\\gamma i}}^{T}W_{\\gamma,i}D_{\\gamma i}\\nonumber \\\\\n & +\\sum_{j}{D_{j}}^{T}W_{j}D_{j}\\label{eq:chi2-with-residuals}\n\\end{align}\nTo minimize this $\\chi^{2}$, we want to find the point in parameter\nspace where the gradient $\\nabla\\chi^{2}=d\\chi^{2}/d\\theta=0$, where\n$\\theta$ denotes the vector of parameters (of size $N_{p}$– see\nbelow). Applying the product rule and noting the symmetry of $D$\nand $D^{T}$, we have\n\\begin{align}\n\\frac{1}{2}\\frac{d\\chi^{2}}{d\\theta} & =\\sum_{\\gamma,i}{D_{\\gamma i}}^{T}W_{\\gamma,i}\\nabla D_{\\gamma i}\\nonumber \\\\\n & +\\sum_{j}{D_{j}}^{T}W_{j}\\nabla D_{j}\\label{eq:def_chi2_gradient}\n\\end{align}\nwhere the $\\nabla D$ matrices have size $2\\times N_{p}$ (for astrometry)\nand $1\\times N_{p}$ (for photometry):\n\\begin{align}\n\\nabla D_{\\gamma i} & =\\frac{d{D_{\\gamma i}}}{d\\theta}\\\\\n\\nabla D_{j} & =\\frac{d{D_{j}}}{d\\theta}\n\\end{align}\n\nWe call the vector that gathers all the parameters to be fit during\nthe minimization $\\theta=(\\eta_{\\gamma},F_{i})$. This vector can\neasily exceed $N_{p}>10^{5}$ entries. As an example with LSST (having\na 189-CCD camera), a mapping consisting of a 3rd order 2-D polynomial\nper visit (16 $\\eta_{k}$ parameters per visit) and 100 viable sources\nper CCD with 15 visits (roughly a year of LSST observations of one\nsky location in one filter), $\\theta$ will have $N_{p}=283,740$\nentries ($283,500$ $F_{i}$ parameters + $240$ model parameters).\nHowever, the second derivative matrix, $d^{2}\\chi^{2}/d\\theta^{2}$,\nis very sparse, because there are no terms connecting $F_{i}$ and\n$F_{j}$ if $i\\neq j$, and depending on how the mappings are parametrized,\na set of $\\eta_{\\gamma}$ parameters could be connected (in the second\nderivative matrix) to only a small set of $F_{j}$'s. So, we can search\nfor the minimum $\\chi^{2}$ using methods involving the second derivative\nmatrix, taking advantage of its sparseness.\n\nWe are looking for the offset to the starting parameters that zeros\nthe gradient, so we can Taylor expand about that starting parameter\nvector $\\theta_{0}$,\n\n\\[\n0=\\frac{d\\chi^{2}}{d\\theta}(\\theta_{0}+\\delta\\theta)=\\frac{d\\chi^{2}}{d\\theta}(\\theta_{0})+\\frac{d^{2}\\chi^{2}}{d\\theta^{2}}(\\theta_{0})\\delta\\theta+O(\\delta\\theta^{2})\n\\]\nand solve for the offset $\\delta\\theta$ that zeroes it to first order,\n\\begin{eqnarray}\n\\left[\\frac{d^{2}\\chi^{2}}{d\\theta^{2}}(\\theta_{0})\\right]\\delta\\theta & = & -\\frac{d\\chi^{2}}{d\\theta}(\\theta_{0})\\label{eq:step_definition}\\\\\nH\\delta\\theta & = & -\\nabla\\chi^{2}\\label{eq:hessian_step}\n\\end{eqnarray}\nwhere we have identified the second derivative matrix with the Hessian\nmatrix $H$. Working from eq. \\ref{eq:def_chi2_gradient}, we can\nwrite the second derivative matrix (the Hessian) as:\n\\begin{align}\n\\frac{1}{2}\\frac{d^{2}\\chi^{2}}{d\\theta^{2}} & =\\sum_{\\gamma,i}{\\nabla D_{\\gamma i}}^{T}W_{\\gamma,i}\\nabla D_{\\gamma i}\\nonumber \\\\\n & +\\sum_{j}{\\nabla D_{j}}^{T}W_{j}\\nabla D_{j}\\label{eq:def_hessian}\n\\end{align}\nwhere we have neglected the second derivatives of the residual vectors\n$D$. This second derivative matrix is by construction symmetric,\nand hence the parameter offsets (defined in eq. \\ref{eq:step_definition})\ncan be evaluated using the (fast) Cholesky $LDL^{T}$ factorization\n(see \\S \\ref{subsec:linear-solver-note}). If possible, mappings\n$M_{\\gamma}(\\eta_{\\gamma},S)$ linear with respect to their parameters\n$\\eta_{\\gamma}$, for example polynomials, are to be favored because\nthe second derivatives will no longer depend on that parameter. If\nthe problem were non-linear (more precisely, if the second derivative\nvaries rapidly) we would have to implement a line search to minimize\n$\\chi^{2}(\\theta_{0}+\\lambda\\times\\delta\\theta)$ over $\\lambda$.\n\nReturning to the weights, we note that the matrices $W_{\\gamma,i}$\nare positive-definite and thus they have square roots (e.g. the Cholesky\nsquare root) and can be written as: $W_{\\gamma,i}=\\alpha_{\\gamma i}^{T}\\alpha_{\\gamma i}$.\nDefining $K_{\\gamma i}=\\alpha_{\\gamma i}D_{\\gamma i}$, the Hessian\nexpression becomes:\n\\begin{align}\n\\frac{1}{2}\\frac{d^{2}\\chi^{2}}{d\\theta^{2}} & =\\sum_{\\gamma,i}{K_{\\gamma i}}^{T}K_{\\gamma i}+\\sum_{j}{K_{j}}^{T}K_{j}\\label{eq:def_symmetric_hessian}\n\\end{align}\nThe sums present in this expression can be performed using matrix\nalgebra; we concatenate all the $K$ matrices into a single large,\nsparse matrix (the Jacobian),\n\\[\nJ\\equiv\\left[\\{K_{\\gamma i},\\forall\\gamma,i\\},\\{K_{j},\\forall j\\}\\right]\n\\]\nand thus we simply have \n\\[\n\\frac{1}{2}\\frac{d^{2}\\chi^{2}}{d\\theta^{2}}=J^{T}J\n\\]\nIn the code, we take advantage of the fact that each term of the $\\chi^{2}$\nonly depends on a small number of parameters. The \\RoutineName{Model::getMappingIndices}\nmethod allows us to rapidly collect the indices of these parameters,\nand we evaluate the $D$ matrices at these indices only, as all other\nindices are zero.\n\nThe computation of the Jacobian and the gradient is performed in the\nrespective \\ClName{PhotometryFit} and \\ClName{AstrometryFit} classes.\nThe methods \\RoutineName{leastSquareDerivativesMeasurement} and\n\\RoutineName{leastSquareDerivativesReference} compute the contributions\nto the Jacobian and gradient of the $\\chi^{2}$ from the measurement\nterms and the references terms respectively. In these routines, the\nJacobian is represented as a list of \\ClName{Eigen::Triplets} $(i,j,J_{ij})$\ndescribing its elements. This list is then transformed into a representation\nof sparse matrices suitable for algebra, and in particular suitable\nto evaluate the product $J^{T}J$. Once we have evaluated $H\\equiv J^{T}J$,\nwe can solve eq. \\ref{eq:hessian_step} using a Cholesky factorization.\nFor sparse linear algebra, the Cholmod and Eigen packages provide\nthe required functionality. It turns out that for the mappings we\nhave currently employed, the calculation of $J^{T}J$ and the factorization\nare the most CPU intensive parts of the calculations, and there is\nhence not much to be gained in speeding up the calculation of derivatives.\nFor the factorization, we have tried both Eigen and Cholmod (via the\nEigen interface) and their speeds differ by less than 10\\%.\n\n\\subsection{Photometry example}\n\nAs an illustrative example, we will work through a particular photometry\nmapping, consisting of a constant zero-point per CCD ($f_{0}$: the\nCCD's filter response) and an $(n+m)$th order 2-D Chebyshev polynomial\n($\\sum a_{j,k}T_{j}(u)T_{k}(v)$: the optics+sky response, where $(u(x,y),v(x,y))$\nare the focal plane coordinates of pixel $(x,y)$ on a given CCD)\nper visit. Thus, the mapping will be\n\\[\nM_{\\gamma i}(\\eta,S_{\\gamma i})=M_{CCD}(f_{0}^{-1},f_{\\gamma i})M_{visit}(a_{j,k},x_{\\gamma i},y_{\\gamma i})=f_{\\gamma i}[f_{0}]^{-1}\\sum_{j=0}^{j=n}\\sum_{k=0}^{k=m}a_{j,k}T_{j}(u_{\\gamma i})T_{k}(v_{\\gamma i})=\\phi_{\\gamma i}\n\\]\nwhere we will fit $f_{0}^{-1}$ instead of $f_{0}$ in order to simplify\nthe derivatives (with respect to $\\eta=\\left(f_{0}^{-1},a_{j,k}\\forall j,k\\right)$).\nComputing those derivatives gives us:\n\\begin{eqnarray*}\n\\nabla D_{\\gamma i} & = & (\\frac{\\partial D_{\\gamma i}}{\\partial f_{0}^{-1}},\\frac{\\partial D_{\\gamma i}}{\\partial a_{0,0}},\\ldots,\\frac{\\partial D_{\\gamma i}}{\\partial a_{n,m}},\\frac{\\partial D_{\\gamma i}}{\\partial F_{i}})\n\\end{eqnarray*}\nwhere, for the measurement terms we have (recall eq. \\ref{eq:photometry_residual_vector_measurement}),\n\\begin{eqnarray*}\n\\frac{\\partial D_{\\gamma i}}{\\partial f_{0}^{-1}} & = & f_{\\gamma i}M_{visit}(a_{j,k}x_{\\gamma i},y_{\\gamma i})\\\\\n\\frac{\\partial D_{\\gamma i}}{\\partial a_{j,k}} & = & f_{\\gamma i}f_{0}^{-1}T_{jk}(u_{\\gamma i},v_{\\gamma i})\\\\\n\\frac{\\partial D_{\\gamma i}}{\\partial F_{i}} & = & -1\n\\end{eqnarray*}\nand for the reference terms (recall eq. \\ref{eq:photometry_residual_vector_reference}),\n\\[\n\\nabla D_{j}=\\frac{\\partial D_{j}}{\\partial F_{j}}=1\n\\]\n\nThis model is degenerate to multiplying by a scale factor: $M_{CCD}\\rightarrow aM_{CCD},M_{visit}\\rightarrow a^{-1}M_{visit}$.\nThis degeneracy is not removed by the reference catalog. To break\nthis degeneracy, we hold fixed one CCD's $f_{0}^{-1}$ (chosen to\nbe the CCD closest to the center of the focal plane), and fit all\nother CCD's relative to that.\n\n\\subsection{The astrometric distortion model}\n\nThe routines in the \\ClName{AstrometryFit} class do not really evaluate\nthe derivatives of the mappings, but rather defer those to other classes.\nThe main reason for this separation is that one could conceive different\nways to model the mappings from pixel coordinates to the tangent plane,\nand the actual model should be abstract in the routines accumulating\ngradient and Jacobian. The class \\ClName{AstrometryModel} is an\nabstract class aiming at connecting generically the fitting routines\nto actual models. We have so far coded two of these models: \n\\begin{itemize}\n\\item \\ClName{SimplePolyModel} implements one polynomial mapping per input\n\\ClName{CcdImage} (i.e. Calexp). \n\\item \\ClName{ConstrainedPolyModel} implements a model where the mapping\nfor each CcdImage is a composition of a polynomial for each CCD and\na polynomial for each exposure. For one of the exposures, the mapping\nshould be fixed or the model is degenerate. \n\\end{itemize}\nFor example, if one fits 10 exposures from a 36-CCD camera, there\nwill be $10\\times36$ polynomials to fit with the first model, and\n$10+36$ with the second model. The \\ClName{ConstrainedPolyModel}\nassumes that the focal plane of the instrument does not change across\nthe data set. We could consider coding a model made from one \\ClName{ConstrainedPolyModel}\nper set of images for which the instrument can be considered as geometrically\nstable. This is similar to how Scamp models the distortions.\n\nIn both of these models, we have used standard polynomials in 2 dimensions\nrather than an orthogonal set (e.g. Legendre, Laguerre, ...) because\nregular polynomials are easy to compose (i.e. one can easily compute\nthe coefficients of P(Q(X)) ), and they map exactly the same space\nas the common orthogonal sets. We have taken care to normalize the\ninput coordinates (mapping the range of fitted data over the $[-1,1]$\ninterval), in order to alleviate the well-know numerical issues associated\nto fitting of polynomials.\n\n\\subsection{Choice of projectors}\n\nIn the least squares expression \\ref{eq:astrometry-chi2}, the residuals\nof the measurement terms read: \n\\[\nD_{\\gamma i}=M_{\\gamma}(S_{\\gamma i})-P_{\\gamma}(F_{i})\n\\]\nIf the coordinates $F_{i}$ are sidereal coordinates, the projector\n$P_{\\gamma}$ determine the meaning of the mapping $M_{\\gamma}$.\nIf one is aiming at producing WCS's for the image, it seems wise to\nchoose for $P_{\\gamma}$ the projection used for the envisioned WCS,\nso that the mapping $M_{\\gamma}$ just describes the transformation\nfrom pixel space to the projection plane. For a SIP WCS, one will\nthen naturally choose a gnomonic projector, so that $M_{\\gamma}$\ncan eventually be split into the ``CD'' matrix and the SIP-specific\nhigher order distortion terms (see \\S \\ref{sec:sip-wcs} for a brief\nintroduction to WCS concepts).\n\nSo, the choice of the projectors involved in the fit are naturally\nleft to the user. This is done via a virtual class \\ClName{ProjectionHandler},\nan instance of which has to be provided to the \\ClName{AstrometryFit}\nconstructor. There are obviously ready-to-use \\ClName{ProjectionHandler}\nimplementations which should suit essentially any need. For the standard\nastrometric fit aiming at setting WCS's, we provide the \\ClName{OneTPPerShoot}\nderived class, which implements a common projection point for all\nchips of the same exposure. It is fairly easy to implement derived\nclasses with other policies.\n\nThe choice of the projector appearing in the reference terms of \\ref{eq:astrometry-chi2}\nis not left to the user because we could not find a good reason to\nprovide this flexibility, and we have implemented a gnomonic projection.\nWe use a projector there so that the comparison of positions is done\nusing an Euclidean metric.\n\n\\subsection{Proper motions and atmospheric refraction}\n\nThe expression \\ref{eq:astrometry-chi2} above depends on two sets\nof parameters: the parameters defining the mappings and the positions\n$F_{k}$. This expression hides two details implemented in the code:\naccounting for proper motions and differential effects of atmospheric\nrefraction.\n\nProper motions can be accounted for to predict the expected positions\nof objects and even be considered as fit parameters. At the moment\nwe neither have code to detect that some (presumably stellar) object\nis moving, nor code to ingest proper motions from some external catalog.\nEach \\ClName{FittedStar} has a flag that says whether it is affected\nby a proper motion and the proper motion parameters can all be fitted\nor not (see \\S \\ref{sec:indices_whattofit}).\n\nThe code allows to account for differential chromatic effects of atmospheric\nrefraction, i.e. the fact that objects positions in the image plane\nare shifted by atmospheric refraction in a way that depends on their\ncolor. The shift reads: \n\\begin{equation}\n\\delta S=k_{b}(c-c_{0})\\hat{n}\\label{eq:refrac_corr}\n\\end{equation}\nwhere $k_{b}$ is a fit parameter (one per band $b$), $c$ is the\ncolor of the object in hand, $c_{0}$ is the average color, and $\\hat{n}$\nis the direction of the displacement in the tangent plane (i.e. a\nnormalized vector along the parallactic direction, computed once for\nall for each Calexp). We have not accounted for pressure variations\nbecause they are usually small, but it would not be difficult. The\ncode accounts for color-driven differential effects within a given\nband, but ignores the differences across bands, would one attempt\nto fit images from different bands at the same time. Differences in\nrecorded positions across bands will be accounted for in the fitted\nmappings. It is important to do so because we are fitting WCS's, and\nwe want the fitted mappings to reflect at best the effects affecting\nmeasured positions. Since the color correction \\ref{eq:refrac_corr}\nis not accounted for when using WCS's to transform measured position,\nwe have made this correction zero on average. As for proper motions,\nfitting or not these refraction-induced differential position shifts\nis left to the user (see \\S \\ref{sec:indices_whattofit}).\n\n\\subsection{Astrometry example}\n\nThe matrix $W_{\\gamma,i}$ is obtained by transporting the measurement\nerrors through the fitted mapping. This introduces an extra dependency\nof the $\\chi^{2}$ on the parameters, that we have decided not to\ntrack in the derivatives, because these errors mostly depend on the\nmapping scaling, which is very well determined from the beginning.\nHowever, small changes of scaling can lead to the $\\chi^{2}$ increasing\nbetween iterations. This is why we provide the \\ClName{AstrometryModel::freezeErrorScales}\nwhich allows one to use the \\textit{current} state of the model to\npropagate errors, even if mappings are updated. $dD_{\\gamma i}/d\\theta$\nhas two non-zero blocks: the derivatives with respect to the parameters\nof the $M_{\\gamma}$ mapping (which are delivered by the Gtransfo-derived\nclass that implements the fitted mapping, namely by the \\ClName{Gtransfo::paramDerivatives}\nroutine); and the derivative with respect to the $F_{k}$ position\nwhich reads $dP_{\\gamma}(F_{k})/dF_{k}$ (delivered as well by the\nclass that implements the projector, via the \\ClName{Gtransfo::computeDerivative}\nroutine).\n\nRegarding reference terms, the matrix $W_{j}$ should be derived from\nthe reference catalog position uncertainty matrix $V_{0}$ (typically\ndelivered for $(\\alpha,\\delta)$ coordinates): \n\\[\nW_{j}=(P'^{T}V_{0}P')^{-1}\n\\]\nwhere $P'$ is the derivative of the projector. The inverse of $W_{j}$\nis in practice obtained using the routine \\ClName{Gtransfo::transformPosAndErrors}\nwhich is attached to the projector. The derivative of the reference\nresidual $D_{j}$ with respect to the \\ClName{FittedStar} position\n$F_{j}$ (see eq. \\ref{eq:astrometry_residual_vector_reference}),\nis just the $2\\times2$ matrix of the derivative $P'$ of the projector\n$P$, which we compute using \\ClName{Gtransfo::computeDerivative}.\n\n\\subsection{A note about our choice for linear solvers\\label{subsec:linear-solver-note}}\n\nThe standard Cholesky decomposition of a matrix H consists in finding\na factor $L$ such that $H=LL^{T}$, with L triangular (possibly after\na permutation of indices). Both Eigen and Cholmod offer a variant,\n$H=LDL^{T}$, where D is diagonal and L (still triangular) has 1's\non its diagonal. We have settled for this variant, because it offers\nimproved numerical stability and allows one, if needed, to add constraints\n(via Lagrange multipliers) to the problem. We have also improved the\nEigen interface to Cholmod by exposing to the user the factorization\nupdate capability of Cholmod, which considerably speeds up the outlier\nremoval. This is done in the \\ClName{CholmodSimplicialLDLT2} class.\nUsing Cholmod has a drawback: we need its run-time library. Cholmod\nis now packaged in SuiteSparse, much bigger than what we need. This\nis why we{\\huge{} }have packaged the smallest possible subset of SuiteSparse\nthat fulfills our needs into jointcal\\_cholmod.\n\n%In the basic tests we have performed (with typically $\\sim 1000$ calexps),\n%factorizing the Hessian requires typically 10s while computing the\n%Jacobian and gradient takes of the order of 1s.\n\n\\subsection{Indices of fits parameters and Fits of parameter subsets \\label{sec:indices_whattofit}}\n\nSince we use vector algebra to represent the fit parameters, we need\nsome sort of mechanism to associate indices in the vector parameter\nto some subset (e.g. the position of an FittedStar) of these parameters.\nFurthermore, the implementation we have chosen does not allow trivially\nto allocate the actual parameters at successive positions in memory.\nThe \\RoutineName{AstrometryFit::AssignIndices} takes care of assigning\nindices to all classes of parameters. For the mappings, the actual\n\\ClName{AstrometryModel} implementation does this part of the job.\nAll these indices are used to properly fill the Jacobian and gradient,\nand eventually to offset parameters in the \\RoutineName{AstrometryFit::OffsetParams}.\n\nSince the indexing of parameters is done dynamically, it is straightforward\nto only fit a subset of parameters. This is why the routine \\RoutineName{AstrometryFit::AssignIndices}\ntakes a string argument that specifies what is to be fitted.\n\n\\section{Association of the input catalogs \\label{sec:catalog-association}}\n\nIn the LSST stack \\citep{LDM-151} framework, each reduced input image\nis call a ``calexp'' (Calibrated Exposure). Each calexp holds the\ndata from one exposure of one CCD, and we associate the ``reduction''\nproducts, typically a variance map, image mask planes, and the derived\ncatalog and WCS obtained by matching the catalog to some external\nreference during single-frame processing. The data that jointcal needs\nfrom the calexp is stored in a \\ClName{CcdImage} object. It stores\nthe objects selected from the source catalog (using a configurable\n\\ClName{SourceSelector}), the relevant exposure metadata and the\ninitial WCS and \\ClName{PhotoCalib}.\n\n\\begin{figure}[ht]\n\\centering{}\\includegraphics[width=0.8\\textwidth]{_static/AssocClasses}\n\\caption{Chart of class relations which implement the associations between\ninput catalogs. One \\ClName{FittedStar} usually has several \\ClName{MeasuredStar}\npointing to it, and each \\ClName{RefStar} points to exactly one\n\\ClName{FittedStar}. Most \\ClName{FittedStar's} have no \\ClName{RefStar}.\n\\label{fig:AssocClasses} }\n\\end{figure}\n\nThe \\ClName{Associations} class holds the list of input \\ClName{CcdImage's}\nand connects together the measurements of the same object. The input\nmeasurements are called \\ClName{MeasuredStar} and the common detections\nare called \\ClName{FittedStar}. The objects collected in an external\ncatalog are called \\ClName{RefStar}. Despite their names, these\nclasses can represent galaxies as well as stars. The collections of\nsush objects are stored into \\ClName{MeasuredStarList}, \\ClName{RefStarList}\nand \\ClName{FittedStarList}, which are container derived from \\ClName{std::list}.\nThe relations between these classes, all implemented in C++, are displayed\nin figure \\ref{fig:AssocClasses}.\n\n\\section{Fitting the transformations between a set of images}\n\nSome applications require determination of transformations between\nimages rather than mappings on the sky. For example a simultaneous\nfit of PSF photometry for the computation of the light curve a point-like\ntransient requires mappings between images to transport the common\nposition in pixel space from some reference image to any other in\nthe series. The calexp series would typically involve the CCD from\neach exposure that covers the region of interest. The package described\nhere can fit for the needed mappings: \n\\begin{itemize}\n\\item in order to remove all reference terms from the $\\chi^{2}$ of eq.~\\ref{eq:astrometry-chi2},\none avoids calling \\RoutineName{Associations::CollectRefStars}. \n\\item One chooses polynomial mappings for all Calexp except, reserving one\nto serve as a reference with a fixed identity mapping. The distortion\nmodel \\ClName{SimplePolyModel} allows that. \n\\item Chose identity projectors (the class \\ClName{IdentityProjector}\ndoes precisely that). \n\\end{itemize}\nSo, fitting transformations between image sets can be done with the\nprovided code.\n\n\\section{Run example}\n\\begin{verbatim}\n\n assoc = Associations()\n\n# iterate on the input calexps \n for dataRef in ref :\n src = dataRef.get(\"src\", immediate=True)\n calexp = dataRef.get(\"calexp\", immediate=True)\n tanwcs = afwImage.TanWcs.cast(calexp.getWcs())\n bbox = calexp.getBBox()\n md = dataRef.get(\"calexp_md\", immediate=True)\n calib = afwImage.Calib(md)\n filt = calexp.getFilter().getName()\n# select proper sources \n newSrc = ss.select(src, calib)\n\n# actually load the data \n assoc.AddImage(newSrc, tanwcs, md, bbox, filt, calib,\n dataRef.dataId['visit'], dataRef.dataId['ccd'],\n dataRef.getButler().mapper.getCameraName(), \n astromControl)\n\n# carry out the association \n matchCut = 3.0\n assoc.AssociateCatalogs(matchCut)\n# collect reference objects\n assoc.CollectRefStars(False) # do not project RefStars\n# select objects measured at least twice.\n assoc.SelectFittedStars()\n# Send back fitted stars on the sky.\n assoc.DeprojectFittedStars() # required for AstrometryFit\n# Chose a ProjectionHandler\n sky2TP = OneTPPerShoot(assoc.TheCcdImageList())\n# chose a distortion model\n spm = SimplePolyModel(assoc.TheCcdImageList(), sky2TP, True, 0)\n# Assemble the whole thing\n fit = AstrometryFit(assoc,spm)\n# we are ready to run. Initialize parameters by running \"partial fits\"\n fit.Minimize(\"Distortions\")\n fit.Minimize(\"Positions\")\n# now fit both sets simultaneously.\n fit.Minimize(\"Distortions Positions\")\n# output residual tuples\n fit.MakeResTuple(\"res.list\")\n\\end{verbatim}\n\n\\appendix\n\n\\section{Representation of distortions in SIP WCS's \\label{sec:sip-wcs}}\n\nThe purpose of the appendix is to provide the minimal introduction\nto WCS concepts required to understand the code (and the comments)\nwhen browsing through it. Readers familiar with WCSs can give up here.\n\nWCS's are abstract concepts meant to map data on coordinate systems.\nIn the astronomical imaging framework, this almost always means mapping\nthe pixel space into sidereal coordinates, expressed in some conventional\nspace\\footnote{The WCS concepts are broad enough to accommodate mapping of planet\nimages, but we will obviously not venture into that.}. One key aspect of the WCS ``system'' is that it proposes some\nimplementation of the mappings in FITS headers, which comes with software\nlibraries to decode and encode the mappings. The WCS conventions cover\na very broad scope of applications, and wide-field imaging makes use\nof a very small subset of those.\n\nFor the mappings used in wide-field imaging, the transformation from\npixel space to sky can be pictured in two steps: \n\\begin{enumerate}\n\\item mapping coordinates in pixel space onto a plane. \n\\item de-projecting this plane to the celestial sphere. \n\\end{enumerate}\nLet us clear up the projection/de-projection step first. There are\nplenty of choices possible here, and the differences only matter fir\nreally large images. The projection used by default in the imaging\ncommunity seems to be the gnomonic projection: the intermediate space\nis a plane tangent to the celestial sphere and the plane$\\rightarrow$sphere\ncorrespondence is obtained by drawing lines that go through the center\nof the sphere. In practice there is no need to know that, because\nany software dealing with WCS's can pick up the right FITS keywords\nand compute the required projection and de-projection. For this gnomonic\nprojection, one finds \\verb&CTYPE1='RA---TAN'& and \\verb&CTYPE2='DEC--TAN'&\nin the FITS header. This projection is often used to generate re-sampled\nand/or co-added images and one should keep in mind that, for large\nimages, the pixels are not exactly iso-area. One point of convention\nthat might be useful to keep in mind; is that WCS conventions express\nangles in degrees. In the gnomonic projection, offsets in the tangent\nplane are expressed in degrees (defined through angles along great\ncircles at the tangent point), so that the metric in the tangent plane\nis ortho-normal), and sidereal angles evaluated on the sky are also\nprovided in degrees by the standard implementations. A notable exception\nis the LSST software stack where, by default, the angles are provided\nin radians.\n\nWe now come back to the first mapping step, i.e. converting coordinates\nmeasured in pixel units into some intermediate coordinate system.\nThe universal WCS convention here is pretty minimal: it allows for\nan affine transform, which is in general not sufficient to map the\noptical distortions of the imaging system, even after a clever choice\nof the projection. Extensions of the WCS convention have been proposed\nhere, but none is universally understood. The LSST software stack\nimplements the SIP addition, which consists in applying a 2-d polynomial\ntransform to the CCD space coordinates, prior to entering the standard\nWCS chain (affine transform, then de-projection). In practice, the\nSIP ``twisting'' is applied by the LSST software itself (in the\nclass \\ClName{afw::image::TanWcs}), and the ``standard'' part\n(affine and de-projection, or the reverse transform) are sub-contracted\nto the ``libwcs'' code.\n\nOne common complication of the WCS arena is that it was designed in\nthe FITS framework convention, itself highly fortran-biased for array\nindexing, so that the first corner pixel of an image is indexed (1,1).\nThe LSST software, and most modern environments use C-like indexing,\ni.e. images stars at (0,0), as well as coordinates in images. The\nWCS LSST software hides this detail to users, by offsetting the pixel\nspace coordinates provided and obtained from the wcs-handling library.\n\nWe now detail what is involved in the SIP convention: the SIP ``twisting''\nitself is encoded through 4 polynomials of 2 variables, which encode\nthe direct and reverse transformations. The standard affine transform\nis expressed through a $2\\times2$ matrix ($Cd$) and a reference\npoint $X_{ref}$ (called \\verb'CRPIX' in the fits header): \n\\[\nY_{TP}=Cd(X_{pix}-X_{ref})\n\\]\n$X_{pix}$ is a point in the CCD space, and $Y_{TP}$ is its transform\nin the tangent plane. Obviously, $X_{pix}$ and $X_{ref}$ should\nbe expressed in the same frame so that the transform does not depend\nthis frame choice. We write symbolically this transform as $Y_{TP}=L(X_{pix})$\nThe SIP distortions are defined by a polynomial transformation in\npixel space, that we call $P_{A}$, for the forward transformation.\nBy convention, the transform from pixel space to tangent plane then\nreads: \n\\[\nY_{TP}=L\\left(X_{pix}-X_{ref}+P_{A}(X_{pix}-X_{ref})\\right)\n\\]\nwhich again does not depend on the frame choice (0-based or 1-based),\nprovided $X_{pix}$ and $X_{ref}$ are expressed in the same frame.\n\nIn jointcal ,the internal representation of SIP WCS's uses three straight\n2d$\\rightarrow$2d transformations: the SIP correction, the affine\ntransformation and the de-projection. Those are just composed to yield\nthe actual transform, and the two first ones are generic polynomial\ntransformations. We provide routines to translate the TanWcs objects\ninto our representation (\\RoutineName{ConvertTanWcs}) and back (\\RoutineName{GtransfoToTanWcs}).\nIn the latter case, we also derive the reverse distortion polynomials,\nwhich are built if needed in our representation of SIP WCSs.\n\n\\section{Notes on meas\\_mosaic (from HSC)}\n\nNaoki Yasuda\\emph{ }wrote \\emph{meas\\_mosaic} for HSC processing,\nwith a similar goal as jointcal.\n\nFor photometry, \\emph{meas\\_mosaic }fits a 7th order Chebyshev polynomial\non the focal plane, plus a zeropoint offset per CCD. The polynomial\ncoefficients are written to the header of \\textbf{fcr-{[}visit{]}-{[}ccd{]}.fits}\nfiles as \\textbf{C\\_N\\_M} values, while the zeropoint and its error\nis written as \\textbf{FLUXMAG0} and \\textbf{FLUXMAG0ERR}. That calibration\nis applied to all of the fluxes in the catalog, which are written\nout to the same ``\\emph{{*}\\_flux}'' catalog fields (converting\nthem to magnitudes in the process).\n\n\\bibliography{lsst,lsst-dm,refs,refs_ads,books,jointcal}\n\n\\end{document}\n", "meta": {"hexsha": "351264feea616351c0183b58d35330afc4077527", "size": 42596, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "tests/data/DMTN-036.tex", "max_stars_repo_name": "lsst-sqre/dochub-adapter", "max_stars_repo_head_hexsha": "3c155bc7ffe46f41e8de5108c936aed7587c8cdb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/data/DMTN-036.tex", "max_issues_repo_name": "lsst-sqre/dochub-adapter", "max_issues_repo_head_hexsha": "3c155bc7ffe46f41e8de5108c936aed7587c8cdb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/data/DMTN-036.tex", "max_forks_repo_name": "lsst-sqre/dochub-adapter", "max_forks_repo_head_hexsha": "3c155bc7ffe46f41e8de5108c936aed7587c8cdb", "max_forks_repo_licenses": ["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.8830694275, "max_line_length": 226, "alphanum_fraction": 0.763123298, "num_tokens": 11331, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.3451052844289767, "lm_q1q2_score": 0.179289553579195}}
{"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% GEANT manual in LaTeX form %\n% %\n% Michel Goossens (for translation into LaTeX) %\n% Version 1.00 %\n% Last Mod. Jan 24 1991 1300 MG + IB %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\Origin{I.Gavrilenko, P.Nevski, K.Lassila-Perini}\n\\Documentation{K.Lassila-Perini}\n\\Version{Geant 3.21}\\Routid{PHYS334}\n\\Submitted {11.03.94}\\Revised{11.03.94}\n\\Makehead {Models for energy loss fluctuations in thin layers}\n\n\\section{Subroutines}\n\n\\Shubr{GSTINI}{}\n\\Rind{GSTINI} initializes the tables that are used for sampling of\nthe energy loss, if the user has set the flag {\\tt STRA = 1}.\nIt calls the subroutine \\Rind{GSTXIN} to integrate\nan expression for the number of collisions and \\Rind{GSTTAB}\nfor preparing the tables for different Lorentz factors.\nIt is called from \\Rind{GPHYSI} at initialization time.\n\n\\Shubr{GSTXIN}{}\n\\Rind{GSTXIN} computes the values needed for the sampling tables.\nIt uses the functions \\Rind{GOSCIN} to integrate over the\nphotoelectric cross-sections and the function \\Rind{GKOKRI}\nto compute the real part of the complex dielectric constant.\n\\Rind{GSTXIN} is called from \\Rind{GSTINI}.\n\n\\Sfunc{GOSCIN}{VALUE = GOSCIN(EIN1EV,EIN2EV)}\n\\Rind{GOSCIN} integrates the parameterization of the photoelectric\ncross-sections from energy {\\tt EIN1EV} to energy {\\tt EIN2EV}.\nIt is called from \\Rind{GSTXIN}.\n\n\\Sfunc{GKOKRI}{VALUE = GKOKRI(E,EMINEV,EMAXEV)}\n\\Rind{GKOKRI} computes the real part of the complex dieletric\nconstant which is needed in the preparation of energy loss\nsampling tables. {\\tt E} in the energy for which the values\nare being tabulated, {\\tt EMINEV} and {\\tt EMAXEV} are\nthe integration limits. \\Rind{GKOKRI} is called from\n\\Rind{GSTXIN}.\n\n\\Shubr{GSTTAB}{(GAM,NT,EN,FN)}\n\\Rind{GSTTAB} prepares the energy loss sampling tables for\ndifferent Lorentz factors. The input {\\tt GAM} is the Lorentz factor,\nthe output values are: {\\tt NT} the lenght of the table,\n{\\tt EN} the energy array and {\\tt FN} the cumulative probabilty array.\nIt calls \\Rind{GXGINT} to integrate over the probability\nfunction \\Rind{GSTDN} to\nget the value of {\\tt FN}. \\Rind{GSTTAB} is called from\n\\Rind{GSTINI}.\n\n\\Sfunc{GXGINT}{VALUE = GXGINT(EXT,A,B,EPS)}\n\\Rind{GXGINT} performs the Gaussian integration from {\\tt A} to\n{\\tt B} over the function {\\tt EXT} with accuracy {\\tt EPS}.\nIt is called from \\Rind{GSTTAB} to integrate over the probability\nfunction \\Rind{GSTDN}.\n\n\\Sfunc{GSTDN}{VALUE = GSTDN(LGE)}\n\\Rind{GSTDN} is the function which gives the probability for a collision\nwith energy transfer {\\tt LGE}. It is integrated to get the\ncumulative probabilty function to be used in the sampling\nof the energy loss.\n\n\\Shubr{GSTREN}{(GAMMA,ECUT,STEP)}\n\\Rind{GSTREN} computes the energy loss for a particle of\nLorentz factor {\\tt GAMMA} in a step of length {\\tt STEP}\nif the user has set the flag {\\tt STRA = 1}.\n{\\tt ECUT} is the cut for the $\\delta$-ray production.\n\\Rind{GSTREN} is called from \\Rind{GFLUCT}.\n\n\\section{The method}\nIn thin layers, the Landau model of energy loss fluctuations\nis not valid, because the number of collisions is too small.\nIn this case, the atomic structure of the atom has to be\ntaken into account. The photoabsorption ionization\n(PAI) model uses the photoelectric cross-sections\nto describe the energy loss distribution.\nThe results (the width and the most probable value of\nthe energy loss distribution function)\ngiven by this model are equal to those given by\nstandard {\\tt GEANT} procedure described in {\\tt [PHYS332]}.\nIn addition, however, it gives an estimate of the number\nof collision in each step ({\\tt NICOLL} in the common block\n{\\tt GCSTRA}). PAI model is slower than the standard\n{\\tt GEANT} method.\n\nPAI model is activated, if the user set the flag\n{\\tt STRA = 1}. The default value is 0.\n\n\\subsection{The photoabsorption ionization model}\nAn expression for the distribution of energy loss can be derived\nconsidering the energy loss as the sum of the energy transfers in\nthe electromagnetic interactions between\nthe particle and the atom.\nAs the interaction is small (i.e. the energy transfer is\nsmall compared to the energy of the passing particle),\nBorn approximation can be used in the perturbation theory.\nIn the derivation, the atomic transition current is\nconsidered as a sum of the transition currents of its\nelectrons.\n\n\n$\\varepsilon$ is the complex\ndielectric constant of a medium which describes the\nelectromagnetic properties of\nthe medium and thus the effect of the field of an atom\non the energy loss of the particle.\n\nThe complex dielectric constant can be written $\\varepsilon =\n\\varepsilon_1 + i \\varepsilon_2$ where $\\varepsilon_1$ describes\nthe polarization and $\\varepsilon_2$ the absorptive properties\nof the medium. $\\varepsilon_2$ can be expressed with the\nhelp of the oscillator strength function $f(k,\\omega)$ which\ndescribes the coupling of the electrons to the field of the\natom.\n\\begin{equation}\n\\label{eps2}\n\\varepsilon_2 = \\frac{2 \\pi^2 N e^2}{m \\omega} f(k,\\omega)\n\\end{equation}\n$m$ is the mass of the electron and $N$ is the electron density.\nIn a simplified model, the photoabsorption cross-section\n$\\sigma_{\\gamma}(\\omega)$ can be used for description of $f(k,\\omega)$:\n\\begin{equation}\nf(k,\\omega) = \\frac{mc}{2\\pi^2 e^2 Z} \\sigma_{\\gamma}(\\omega)\n\\end{equation}\n$Z$ being the atomic number of the medium.\nThe real part of $\\varepsilon$ can be expressed as an integral\nof the imaginary part according to the Kronig's and Kramers' dispersion\nrelation\\cite{bib-ALLIS}:\n\\begin{eqnarray}\n\\varepsilon_1 - 1 & = & \\frac{2}{\\pi} P \\int_0^{\\infty}\n \\frac{x \\varepsilon_2(x) dx}{x^2 - \\omega^2} \\nonumber \\\\\n & = & \\frac{2 N c}{\\pi Z} P \\int_0^{\\infty}\n \\frac{\\sigma_{\\gamma}(x) dx}{x^2 - \\omega^2}\n\\label{eps1}\n\\end{eqnarray}\nwhere $P$ indicates the Cauchy principal value.\nUsing these assumptions for the interaction between the projectile\nand the atom, the\nfollowing form is obtained for the collision cross-section \\cite{bib-GRISH}:\n\\begin{eqnarray}\n\\frac{d\\sigma}{dE} & = & - \\frac{e^2}{\\pi \\hbar^2c^2n_a}\n \\mbox{ Im} \\left[ \\left( \\frac{1}{\\beta^2\\varepsilon} - 1 \\right)\n \\ln \\frac{2mv^2}{E(1-\\beta^2\\varepsilon)} \\right] \\nonumber \\\\\n& & + \\frac{2\\pi Ze^4}{mv^2E^2} \\int_0^{\\infty}\n \\frac{f(E')}{\\varepsilon(E')^2} dE'\n\\label{xsection}\n\\end{eqnarray}\nwhere $n_a$ is the number of atoms per cm$^3$, $v$ velocity of the particle,\nand $\\beta=v/c$. The number of collisions per distance $x$ and\nthe energy $E$ is then\n\\begin{equation}\n\\frac{N^2}{dx dE} = n_a \\frac{d\\sigma}{dE}\n\\end{equation}\n\nFor the simulation purposes, the number of primary collisions\nin a unit length\nwith energy loss greater than a certain E\nis computed and tabulated for several values of the Lorentz factor.\nThis is done by integrating\n\\begin{eqnarray}\n\\left( \\frac{dN}{dx} \\right)_{>E}\n& = &\\int_E^{E_{max}} n_a \\frac{d\\sigma}{dE} dE\n\\label{integ}\n\\end{eqnarray}\n\n\\subsection{Implementation}\nA photoabsorption ionization Monte Carlo code provided to us by users\n%\\cite{trd}\nhas been implemented in {\\sc GEANT}. Tables are\nprepared at initialization time and sampling from these\ntables is done each step at running time. An important\nthing to note is the dependence of the $(dN/dx)_{>E}$\non the photoelectric\ncross-sections which, when taken from different sources,\nmay differ considerably, especially at low energies.\n\nTo fill the tables, the integration of equation \\ref{xsection}\nhas to be done.\nBefore the integration over the energy, the integral\nover\nthe oscillator strength function $f(k,\\omega) \\sim\n\\sigma_{\\gamma}(\\omega)$ (last term in equation \\ref{xsection})\nand the dielectric constant (equations \\ref{eps1} and \\ref{eps2})\n$\\varepsilon$ have to be computed. These integaration\ncan be done analytically when the parameterized cross-sections\nare used.\n\nThe oscillator strength function should\nfulfill the Bethe sum rule \\cite{bib-BETH}:\n\\begin{equation}\n\\int_0^{\\infty} f(k,\\omega) d\\omega = 1\n\\label{sumrule}\n\\end{equation}\nTo respect this condition, in the PAI model, one has to add some\ncontribution from the excitation processes to low-energy region\nof the photoelectric cross-sections \\cite{bib-ALLIS}. In {\\sc GEANT}, the\nphotoelectric cross-section\nparameterization of the Sandia \\cite{bib-SANDIA} report is used.\nIn order not to change the tabulated parameterization, the sum\nrule is taken into account by lowering the energy\nlimit for the integration below the ionization limit.\nThis will not satisy the equation \\ref{sumrule} in all cases.\nIn the program, however, the Bethe sum rule is forced by\ndividing the integrated cross-section from $E$ to $\\infty$\nby the value given by the integration over the whole range.\n\\begin{figure}[t]\n \\centering\n \\epsfig{file=eps/phys334-1.eps,width=10cm}\n \\caption{Above, the integrated and normalized cross-section\n of the gas mixture 70\\% Xe - 10\\% CO$_2$ - 20\\% CF$_4$\n for two different data sets. The low energy limit\n of the cross-sections from the Sandia data in chosen\n to be 11 eV. In the figure below, the low energy limit\n is the ionization limit for each component of the mixture}\n \\label{fosc}\n\\end{figure}\nIn figure \\ref{fosc}, the integrated cross-section (oscillator\nstrength function)\n$\\int_{E}^{E_{max}} \\sigma_{\\gamma} / \\int_{E_0}^{E_{max}} \\sigma_{\\gamma}$\nis given for two different sets of photoelectric cross-section\ndata for a gas mixture 70\\% Xe - 10\\% CO$_2$ - 20\\% CF$_4$.\nIn the figure below, the continuous line is the result of the\nintegration tabulated from \\cite{bib-ATOM1} \\cite{bib-ATOM2} \\cite{bib-ATOM3} \nand the dashed line\nis from the integration of {\\sc GEANT} cross-sections\nconsidering the lower limit of the cross-section the ionization\nenergy (12.3 eV for Xe, 11.26 eV for C, 13.6 for O, and\n17.42 for F).\nIn the figure above, the continuous line is as before, but for\nthe dashed line, the lower limit of the cross-sections is\nconsidered to be 11 eV for all elements of the mixture\nto compensate for the sum rule.\n\nThe imaginary part of the complex dielectric constant can then\nbe computed from the integrated cross-section.\nTo compute the real part of $\\varepsilon$, one needs to take the\nCauchy principal value which is basically a limiting process\ncancelling the two infinite contribution around the pole\n$(x_0-\\delta,x_0+\\delta)$. The derivation of the real part\nwith the Sandia parametrization is shown in detail\nin the appendix.\n\\begin{figure}[t]\n \\centering\n \\epsfig{file=eps/phys334-2.eps,width=10cm}\n \\caption{Above, the integrated and normalized cross-section\n of the gas mixture 70\\% Xe - 10\\% CO$_2$ - 20\\% CF$_4$\n for two different data sets. The low energy limit\n of the cross-sections from the Sandia data in chosen\n to be 11 eV. In the figure below, the low energy limit\n is the ionization limit for each component of the mixture}\n \\label{idndx}\n\\end{figure}\n\nKnowing the values of complex dielectric constant and the integrated\ncross-section, the integration of equation \\ref{integ} can\nbe done. This is done for several values of Lorentz factor\nduring the initialization time in subroutine {\\tt GSTINI}.\nThe value of energy loss is sampled from these tables in\nsubroutine {\\tt GSTREN}.\n\nOne should remember the dependence of this method on the\nphotoelectric cross section data.\nFigure \\ref{idndx} shows the results for the two different\ndata sets. The difference in the low-energy part is very\nsignificative as the sampling is done from these tables\nand, according the inverse transverse method, the number of\ncollisions is sampled between the maximum and minimum\nof the curves in figure \\ref{idndx}.\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "d6628bd927fdec6612f3f3710ebd5998603d4a5b", "size": 12012, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "geant/phys334.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": "geant/phys334.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": "geant/phys334.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": 42.5957446809, "max_line_length": 78, "alphanum_fraction": 0.7234432234, "num_tokens": 3345, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370308082623217, "lm_q2_score": 0.2814056194821861, "lm_q1q2_score": 0.17926404922829636}}
{"text": "\n\n\\documentclass[11pt]{article}\n\n\\usepackage{pdflscape}\n\\usepackage{amsmath}\n\\usepackage{amssymb}\n\\usepackage{graphicx}\n\\usepackage{cite}\n%\\usepackage{pdfsync}\n\n\\usepackage{color} \n\n\\usepackage{setspace} \n\\doublespacing\n\n\\usepackage[round]{natbib}\n%\\usepackage[english]{babel}\n\n% Text layout\n\\topmargin 0.0cm\n\\oddsidemargin 0.5cm\n\\evensidemargin 0.5cm\n\\textwidth 16cm \n\\textheight 21cm\n\n\\usepackage[labelfont=bf,labelsep=period,justification=raggedright]{caption}\n\n\n\\makeatletter\n\\renewcommand{\\@biblabel}[1]{\\quad#1.}\n\\makeatother\n\n\n\\date{}\n\n\\usepackage{xspace}\n%\\usepackage{soul}\n\\usepackage{verbatim}\n\\newcommand{\\etal}{{\\em et al.}\\xspace}\n\\newcommand{\\var}[1]{\\mathrm{Var}\\left( #1 \\right)}\n\\newcommand{\\cov}[2]{\\mathrm{Cov}\\left( #1 , #2 \\right) }\n\\newcommand{\\se}[1]{\\mathrm{SE}\\left( #1 \\right)}\n\\usepackage{lscape}\n\\newcommand{\\beginsupplement}{%\n \\setcounter{table}{0}\n \\renewcommand{\\thetable}{S\\arabic{table}}%\n \\setcounter{figure}{0}\n \\renewcommand{\\thefigure}{S\\arabic{figure}}%\n }\n\n\\newcommand{\\bcomment}[1]{{\\bf{\\emph{\\large{[Buhm's comment:#1]}}}}}\n\\usepackage{bm} \n\n\n\n\\begin{document}\n\n\n\\begin{flushleft}\n{\\Large\n\\textbf{An association mapping framework to account for the sex difference in genetic architectures\n}\n}\n\n\n\n Eun Yong Kang\\,$^{1,\\dagger}$,\n Cue Hyunkyu Lee\\,$^{5,6,\\dagger}$,\n Nicholas A. Furlotte\\,$^{1}$,\n Jong Wha Joo\\,$^{2}$,\n Emrah Kostem\\,$^{1}$,\n Noah Zaitlen\\,$^{3}$, \n Eleazar Eskin\\,$^{1,4,\\ast}$,\n Buhm Han\\,$^{5,6,\\ast}$\\\\\n {\\bf $1$} Computer Science Department, University of California, Los Angeles, California, USA\\\\\n {\\bf $2$} Interdepartmental Program in Bioinformatics, University of California Los Angeles, California, USA\\\\\n {\\bf $3$} Department of Medicine, University of California San Francisco, California, USA\\\\\n {\\bf $4$} Department of Human Genetics, University of California, Los Angeles, California, USA\\\\\n {\\bf $5$} Asan Institute for Life Sciences, Asan Medical Center, Seoul, Republic of Korea\\\\ \n {\\bf $6$} Department of Convergence Medicine, University of Ulsan College of Medicine, Seoul, Republic of Korea\\\\ \n$\\ast$ Corresponding Authors E-mails: eeskin@cs.ucla.edu, buhm.han@amc.seoul.kr\\\\\n$\\dagger$ These authors contributed equally.\n\\end{flushleft}\n\n% Please keep the abstract between 250 and 300 words\n\\clearpage\n\\section*{Abstract}\n% \\bcomment{need some refinements}\nOver the past few years, \ngenome-wide association studies have identified many trait-associated loci\nthat have different effects on females and males,\nwhich increased attention to the genetic architecture differences between the sexes.\n%Using analyses of the North Finland Birth Cohort (NFBC) data,\n%we show that \nThe between-sex differences in genetic architectures can cause a \n%number of different observed \nvariety of phenomena \nsuch as \nthe differences in effect sizes at trait-associated loci,\ndifferences in the magnitudes of polygenic background effects,\nand\ndifferences in phenotypic variances. \n%effect size differences, polygenic background effects differences,\n%and phenotypic variance differences.\nHowever, \ncurrent approaches for dealing with sex such as including sex as a covariate\ncannot fully account for these phenomena and can be suboptimal in statistical power.\nWe present a novel framework, MetaSex, that can\ncomprehensively account for the genetic architecture differences between the sexes.\n%Our framework uses a unique statistical procedure that combines a linear mixed model and a meta-analysis approach.\n%to effectively account for multiple possible \n%phenomena caused by sex differences.\nThrough simulations and applications to real data, \nwe show that our framework has a superior performance than previous approaches.\n\n\n%\n%\\section*{Author Summary}\n%Over the past few years, \n%genome-wide association studies have identified many loci associated to human traits.\n%These loci have certain effect sizes on the traits. \n%However, the effect sizes often differ between sexes; for example,\n%having a variant at a locus can increase susceptibility to a disease by 2-fold in men,\n%but only 1.5-fold in women. \n%Moreover, real datasets show that many other things can also differ between sexes, such as\n%phenotypic variances.\n%Here we propose a comprehensive framework that accounts for these \n%genetic architecture differences between the sexes\n%using a unique statistical model. \n\n\n%\n%are not optimized for detecting these sex-interacting effects.\n%Here we present a novel framework that combines linear mixed model and meta-analysis\n%to effectively identify sex-interacting effects.\n%%We show that each of the statistical components of standard model can have sex differences\n%%and design out method to comprehensively account for those differences.\n%Our method is comprehensive in that \n%it accounts for possible sex differences\n%%Our model comprehensively account for sex differences\n%in all statistical components of the standard model,\n%including the polygenic background effects and the random errors.\n%%phenotypic mean, genetic effects, polygenic effects, and residual errors.\n%Through simulations and application to the North Finland Birth Cohort data, \n%we show that our method has a superior performance compared to previous approaches.\n%We also show that phenotypic variances differ by sex in many traits of real dataset,\n%emphasizing that a comprehensive approach accounting for sex differences in variance components should\n%be applied.\n\n\n\n\n%a significant number of loci implicated in genome wide association studies \n%show differences in effect sizes of males and females. \n%There are two traditional approaches for dealing with differences in sex in GWAS. \n%The first approach is to analyze each sex separately and the second approaches is analyzing both \n%sex together using sex as a covariates. \n%Unfortunately, these approaches \n%ignores the potential for a difference in effect sizes between the two sexes and thus \n%may lead to a loss in power when sex-interacting effects are present at the loci being tested.\n%In this paper, we propose a new method that is optimized for identifying genetic loci with sex-interacting effects.\n%In particular, our method is designed to achieve optimal power by considering the following two scenarios.\n%First, the effect size may differ by sex at the locus that we perform testing.\n%Second, the small effects of causal loci over the genome can interact with sex, which can yield sex-interacting polygenic effects.\n%Our approach combines linear mixed model and random effects meta-analysis to account for \n%both phenomena for an optimal analysis of sex-interacting effects in GWAS. To account for sex-interacting polygenic \n%effects, we model the interaction as a variance component in a linear mixed model. To account for sex-interacting \n%effects at the locus we test, we employ hierarchical modeling of effect sizes using random effects meta-analysis framework.\n%Through simulation experiments and the analysis of North Finland Birth Cohort data, \n%we show that our method has superior performance compared to the previous approaches such as traditional sex as covariate\n%approach or another meta-analysis-based approach, GWAMA.\n\n\n%Over the past several years, a significant number of loci implicated in genome wide association studies \n%show differences in effect sizes for males and females. \n%The prevalence of sex-interacting effects \n%both motivates strategies for discovery of sex-interacting effects and raises questions of how to analyze \n%%complicates the analysis of \n%association studies \n%consisting of both males and females. The traditional approach to \n%%address this issue in genome wide association \n%discover sex-interacting effects is to analyze each sex separately and the traditional \n%approach to analyze association studies consisting of both males and females\n%is to include sex as a covariate in the statistical model \n%when performing association analysis.\n%Unfortunately, these approaches \n%%ignores the potential for a difference in effect sizes between \n%%the two sexes and thus \n%may lead to a loss in power when sex-interacting effects are present at the loci being tested.\n%%throughout the genome.\n%%Furthermore, genome-wide \n%%gene-by-sex effects introduce additional background phenotypic variance, \n%%which can induce additional power loss.\n%%leading to \n%%both power loss and the introduction of false positive associations.\n%In this paper, we present RE+SST, a novel meta-analytic approach for the analysis of genome-wide \n%association studies consisting of both males and females. In our approach, males and \n%females are analyzed separately and the results are combined using a random effects \n%meta-analysis approach allowing for differences in effect sizes between sexes. We \n%show that by analyzing males and females separately, our method reduces the overall \n%variance in each study, leading to an increase in statistical power. \n%Through simulation experiments and application of Northern Finland Birth Cohort data,\n%we show that the power of identifying the sex-interacting loci is dependent on \n%the effect size difference between male and female studies as well as \n%the phenotypic variance difference between male and female studies after regressing out \n%the SNP effect. \n%%Through simulations and application of \n%%our method to the \n%%Northern Finland Birth Cohort data,\n%In addition, we show that our method has increased power over the traditional \n%approaches including GWAMA\n%for discovering associated loci with and without sex-interacting effects while controlling for false positives.\n\n\\clearpage\n\\section{Introduction}\n\n\nGenome-wide association studies (GWAS) have successfully identified numerous genetic loci \nassociated with complex human traits. \n%Previously conducted GWAS collected samples of both male and female individuals.\nIn recent years, increasing attention has been paid to the sex difference in genetic architectures in GWAS. \nA number of studies have found differences in effect sizes between males and females on loci associated with traits. \n\\citep{Kubo:Gut:2013,Peters:Stroke:2013,Chen:ObesRev:2013,Boraska:HumMolGenet:2012,Kostis:JAmCollCardiol:2012,Magi:GenetEpidemiol:2010,Fox:PlosGenet:2012,Porcu:PlosGenet:2013,Mason:AlcoholClinExpRes:2012,kang2014metagxe,Ohmen:JAssocResOtolaryngol:2014,Randall:PlosGenet:2013}.\nIn particular, a large-scale meta-analysis\n of 46 studies of anthropomorphic phenotypes \ndiscovered seven loci with different effects between the sexes \n\\citep{Randall:PlosGenet:2013}.\n\nIt remains unclear how best to account for the sex difference in genetic architectures in association mapping.\n%Traditional approaches are limited in what they can detect.\n%that exist in both sexes with differing effect sizes. \nOne traditional approach is to analyze each sex separately using sex-specific tests (SST). \nThis approach is optimal for detecting sex-specific effects that only exist in one sex,\nbut is not powerful for detecting effects that exist in both sexes.\nAnother traditional approach is to analyze the whole sample and use sex as a covariate (CV). \nThis approach is optimal for detecting effects that exist in both sexes in a constant effect size, \nbut is not powerful for detecting sex-interacting effects that exist in both sexes in\ndiffering effect sizes.\n\n%Because this approach implicitly assumes that the effect size is the same for the two sexes, it is suboptimal for detecting sex-interacting\n%effects. \n\nIn the present study, we first enumerate three possible phenomena that can be caused by\nthe sex difference in genetic architectures.\n%argue that the difference in genetic architecture between the sexes can cause a variety of phenomena.\nOne is the effect size difference between the sexes at the associated locus,\n%This sex-interacting effect \nwhich was observed in previous studies \\citep{Randall:PlosGenet:2013}.\n%To achieve high power to detect sex-interacting effects, it is necessary to model\n%the effect size heterogeneity in statistical testing.\nAnother is the effect size difference between the sexes at \nnumerous loci spread throughout the genome with small effects, %. %, genome-wide loci bearing small effects.\n%which we call polygenic effects.\n%The aggregation of these small effects \nwhich can manifest as \n%This phenomenon can appear as random \npolygenic background effects that interact with sex.\n%If this phenomenon occurs, it is necessary to extend the standard linear mixed model\n%\\citep{Kang2010,Kang:2008bx,Zhou:NatGenet:2012}, \n%which is commonly used\n%to control for polygenic effects, to account for the sex difference.\nThe final one is the phenotypic variance difference between the sexes,\nwhich can be caused by many factors such as sex acting as a biological environment (e.g. hormone difference)\nand sex interacting with external environments (e.g. lifestyle difference). \n%Because the sex can act as a biological environment, the dispersion of the phenotypic values can also\n%be affected.\n%In such situations, it is necessary to model distinct error terms for the two sexes in\n%the statistical model. \nIn our analysis of the North Finland Birth Cohort (NFBC) dataset \\citep{Sabatti:NatGenet:2009}, \nwe often observed these phenomena in some human traits.\n%If we do not fully account for these phenomena, \n%we may not be able to achieve optimal power from association testing.\n\nHere, we present a novel association mapping framework, MetaSex, \nthat accounts for the sex difference in genetic architectures\nto effectively map associations in GWAS.\nOur framework comprehensively takes into account the three aforementioned phenomena\nby\nuniquely combining linear mixed model and meta-analysis.\n%in order to \n%take into account the three aforementioned phenomena comprehensively.\n%Our statistical model combines a linear mixed model and meta-analysis framework to account for multiple possible phenomena caused by gender differences. \n%We begin with a linear mixed model with five variance components.\nOur linear mixed model includes five variance components, \nwhere three are for capturing sex-interacting polygenic effects\nand two are for modeling distinct variances of the two sexes. \n%random effect components that illustrate the polygenic background effect difference between the sexes. \n%Remaining two variance components are random error components for each gender.\nWe then combine the observed effect sizes of the two sexes \n%We model effect size of each sex separately, and then combine them\nusing the random effects meta-analysis \\citep{Han:AmJHumGenet:2011} \nthat provides high power for detecting sex-interacting effects.\nBecause this five variance component model can be\n%Although being comprehensive and powerful,\n%this initial model has little utility in GWAS because fitting five variance components is \nimpractically slow to be applied to millions of markers in GWAS,\n%To overcome this challenge, \nwe propose an approximated model that splits the problem into two optimization problems each requiring only two variance components.\n%we decompose the five-variance-component model into a pair of\n%two-variance-component models. The model parameters in the decomposed model have a unique mapping relationship\n%to the parameters in the original model. \n%Thus, our framework based on the decomposed model provides an accurate approximation to the \n%original model \n%while being computationally efficient for GWAS.\nUsing simulations and real data,\nwe demonstrate that our framework is powerful, comprehensive, and efficient.\n\n%Therefore, we propose a practical approximation that can expedite the framework by replacing the proposed five-variance-component model with two sets of two-variance-component models,\n%where each model provides separate effect size estimate for each sex. \n%We then combine those estimates using the random effects meta-analysis framwork(RE)\\citep{Han:AmJHumGenet:2011} to account for effect size heterogeneity between the sexes. \n%Using simulations and real data, we demonstrate that our method has a superior performance than previous approaches.\n\n\\section{Results}\n\\subsection{Overview of MetaSex}\n%\\subsection{Combining sex-interacting test and meta-analysis method to handle sex-interacting effects}\n\n\nWe first provide an overview of our proposed framework.\nWe constructed a toy example \nwith six individuals (three females and three males).\nThe equation in Figure \\ref{overview}A shows the components in our model for testing a single SNP. \nIn this equation, vector $\\bf{y}$ is the observed phenotype measurements, where \nsubscripts $(f)$ and $(m)$ denote females and males.\n$\\mu$ denotes the phenotypic mean. \n${\\bf h}$ is the sex status indicator (female = 1 and male = 0),\nwhich is included as a covariate to account for the sex-specific phenotypic mean. \n%\\hl{Eun -- please change X column 1 and 2 in Figure. Thanks!}\n% Cue : I did\nThe first column of $\\bf{X}$ is the genotype vector of the SNP, whose effect size is $\\beta$.\nThe second column of $\\bf{X}$ is the \ngenotype-by-sex interaction term (SNP $\\times$ $\\bf{h}$), \nwhose effect size is $\\beta_{g \\times s}$.\n$\\mathbf{u_g}$ is a variance component that models the polygenic background effects from the genome-wide loci that affect both sexes.\n%except the testing SNP. \nConsistently to the standard linear mixed model\\citep{Kang2010,Kang:2008bx,Zhou:NatGenet:2012}, \nwe assume that $\\mathbf{u_g}$ follows a normal distribution with mean zero and variance-covariance\nmatrix $\\sigma_g^2 \\bf{K}$ where $\\bf{K}$ is the kinship matrix representing the relationship between individuals.\n$\\mathbf{u_{f}}$ is an additional variance component that we introduced, which represents the\nfemale-specific polygenic effects.\nWe assume that $\\mathbf{u_{f}}$ have mean zero and variance\n$\\sigma_{g,f}^2 (\\bf{K}\\circ \\bf{hh}^T)$.\n%where $K_{g \\times s}$ is a block diagonal kinship matrix, that is,\n%where elements representing the relationship between a male and female pair become zero.\nSimilarly, $\\mathbf{u_{m}}$ is a variance component representing the male-specific\npolygenic effects,\nwhich have mean zero and variance\n$\\sigma_{g,m}^2 (\\bf{K}\\circ \\bf{(1-h)(1-h)}^T)$.\nWe then modeled separate error terms for females and males, assuming that error variances can be different.\n$\\mathbf{e_f}$ is a female-specific error term that follows a normal distribution with mean zero and variance $\\sigma_{e,f}^2(\\bf{I\\circ hh^T})$, \nwhere $\\bf{I}$ is the identity matrix. \n%a modified identity matrix that has ones for females in the diagonal and zero for others.\nSimilarly, $\\mathbf{e_m}$ is a male-specific error term that have mean zero and variance $\\sigma_{e,m}^2(\\bf{I \\circ (1-h)(1-h)^T})$.\n%$e$ is the standard random error term that follows a normal distribution with mean zero and variance $\\sigma_{e}^2 I$.\n%$e_s$ is an additional random error term to account for sex-specific errors, \n%and is assumed to follow\n%a normal distribution with mean zero and variance $\\sigma_{e_m}^2 I'$,\n%where $I'$ is the same to $I$ but the latter three diagonal elements are zero.\n\nApplying this full model to GWAS can be computationally challenging \nbecause there are five variance components to fit ($\\mathbf{u_g}$, $\\mathbf{u_f}$, $\\mathbf{u_m}$, $\\mathbf{e_f}$, and $\\mathbf{e_m}$).\nCurrently available linear mixed model methods for association mapping are optimized for models with two variance components \\citep{Zhou:NatGenet:2012,Kang2010,Kang:2008bx}.\nIf there is a third component, a state-of-the-art association mapping method uses a simple grid search \\citep{Lippert:NatureMethods:2011}. \nThus, fitting five variance components may require a three-dimensional grid search, which can be prohibitively slow for GWAS.\n\nTo expedite the application of our model to GWAS, we propose an efficient decomposition of the model.\nSuppose that we restrict our scope to individuals of one sex.\nThen, the full model with five variance components collapses into a sex-specific model with two variance components (Figure \\ref{overview}B).\n%This is because \n%$\\bf{K}$ and $\\bf{K}\\circ \\bf{hh}^T$ have the same form for the female individuals.\n%Similarly, we also assume that we only have a subset of individuals that are males.\n%This gives us a male-specific linear mixed model with two variance components.\nThus, the model can be efficiently solved using existing approaches \\citep{Zhou:NatGenet:2012,Kang2010,Kang:2008bx}.\n%The key intuition is that by solving two sex-specific models separately,\n%we can automatically account for the between-sex differences in phenotypic mean as well as error variances.\nIn the decomposed model, \n%This approximation differs from the original model in that \nwe cannot\ndistinguish the whole-sample polygenic component ($\\sigma^2_g$) from the sex-specific polygenic components ($\\sigma^2_{g,f}$ or $\\sigma^2_{g,m}$),\nbecause they follow the exactly same distribution conditioned on one sex.\nHowever, this distinction is unimportant for association mapping, \nbecause we anyhow want to control for both. \n%However, for the purpose of association testing, distinction of these is unimportant;\n%as long as the estimate of the summation (e.g. $\\sigma^2_g+\\sigma^2_{g,f}$ for females) is accurate, the association results are the same.\n%However, if the sample size of each sex is large enough, we expect that the loss of information will have minimal impact.\n\n%%If we choose to ignore $\\mathbf{u_g}$ for a moment, we could decompose the model into two sex-specific models (Figure \\ref{overview}B).\n%%Then, in each model, we can put $\\mathbf{u_g}$ back. \n%As a result, we approximate the original model by using two sets of linear mixed models with two variance components,\n%for which efficient optimization methods are available.\n%%An optimization technique for two-variance-components models are already known and were efficiently applied to genome-wide scales \\citep{Kang2010}.\n%The difference in the phenotypic mean of the two models ($\\mu_f$ and $\\mu_m$) accounts for the sex-specific mean difference $\\mu_s$.\n%The difference in genetic effects ($\\beta_f$ and $\\beta_m$) accounts for the sex-interacting genetic effect $\\beta_{g \\times s}$.\n%The polygenic component in each model ($\\mathbf{u_f}$ and $\\mathbf{u_m}$) accounts for both the polygenic and sex-interacting polygenic effects ($\\mathbf{u_g}$ and $\\mathbf{u_{g \\times s}}$).\n%Finally, the random error terms ($\\mathbf{e}$) in the two models are not required to have the same variance,\n%which accounts for the different random error variances of $\\mathbf{e_{f}}$ and $\\mathbf{e_m}$. \n%\n%The difference in this approximation compared with the original model is that\n%the maximum likelihood estimates of $\\sigma^2_g$ and $\\sigma^2_{g \\times s}$ can be different between \n%the two sexes, which would not occur in the original model.\n%Also, the between-sex elements of $K_g$ are ignored, which can give additional information for estimating parameters.\n%However, if the number of individuals of each sex is large enough, $\\sigma^2_g+\\sigma^2_{g \\times s}$ estimates\n%($\\sigma^2_f$ and $\\sigma^2_m$) %$\\sigma_m$ and $\\sigma_f$ estimates \n%will be sufficiently accurate enough in each sex.\n%%even if\n%%we use only within-sex information in the approximated model.\n\nFinally, given the sex-specific effect size estimates and the standard errors,\n%from the two-variance-component model \n%male estimate and female estimatean effect size estimate and its standard error \n%from each sex-specific model \n($\\hat{\\beta_m}$, se($\\hat{\\beta_m}$), $\\hat{\\beta_f}$, se($\\hat{\\beta_f})$), we apply a series of statistical tests.\nWe first apply SST, \nwhich is optimal for detecting sex-specific effects. \n%Because it is a common practice that\n%investigators look at each sex separately first, %without noticing that they are performing multiple testing.\n%we explicitly include SST in our framework to account for multiple testing.\n%We first test each sex separately (sex-specific test, SST) to detect sex-specific effects.\nThen, to effectively detect sex-interacting effects, \nwe combine the two sex-specific estimates %using meta-analysis. %information from the two sexes.\n%There can be different approaches for doing this; for example, one can combine chi-square\n%statistics of two sexes as is done in GWAMA \\citep{Magi:GenetEpidemiol:2010}.\n%We apply \nusing the random effects meta-analysis method (RE) \\citep{Han:AmJHumGenet:2011} (Figure \\ref{overview}C),\nwhich explicitly models heterogeneity. % and has high power.\n%In this approach, the two effect sizes are assumed to come from the same underlying distribution, \n%thus modeling both the similarities and differences of them. \n%As shown below, this approach turns out to be powerful for detecting sex-interacting effects.\nAs a result, our framework involves three tests (Female SST, Male SST, and RE),\nrequiring multiple testing correction. \n%the significance threshold must be adjusted in order to account for multiple test. \nA powerful multiple testing strategy can be to adjust the significance threshold for each test \nto maximize power while controlling for overall false positive rate \\citep{Eskin:GenomeRes:2008}.\nWe identify and propose \n%We perform extensive null simulations to identify\na set of thresholds for the three tests, what we call smart thresholding,\nthat exactly controls the false positive rate to the GWAS threshold ($5\\times10^{-8}$) while maximizing power.\n\n%Since the proposed approach involves performing three association tests at each locus, \n%the significant threshold must be adjusted in order to take into account these multiple tests. One such way is to use the \n%Bonferroni correction that uses\n%the significance threshold of $1.67 \\times 10^{-8}$ instead of the traditional threshold of $5 \\times 10^{-8}$,\n%but this can be overly conservative due to correlations of tests.\n%%Since the tests are correlated, this can be overly conservative. \n%We perform extensive null simulations to identify\n%the threshold that exactly controls the false positive rate.\n%Moreover, we choose to define different significant thresholds for SST and RE to increase power\n%while still controlling for overal false positive rate,\n%a strategy we call smart thresholding.\n%To control false positive rate to $5 \\times 10^{-8}$,\n%we found that using unequal thresholds \n%$2.41 \\times 10^{-8}$ for RE and $1.36 \\times 10^{-8}$ for SST gives us better power.\n\n\\subsection{Power simulations}\n\n\n\n\n%\\subsubsection*{Power comparison design}\n\n%Random-effects meta-analysis is not the only possible meta-analysis method that can be used in a meta-analytic approach for handling sex-interacting effects.\nWe performed simulations to evaluate the power of our MetaSex approach. \nBelow, we also refer to our MetaSex method as RE+SST \nbecause the framework involves simultaneous testing of RE and SST.\n%both random effects model meta-analysis (RE) and sex-specific test (SST). \n%\\citep{Han:AmJHumGenet:2011} \nWe compared our method to two other approaches:\n%the fixed-effect meta-analysis method (FE) and\n(1) CV, the traditional approach using sex as a covariate, \n and (2) GWAMA \\citep{Magi:GenetEpidemiol:2010}, another meta-analysis approach designed to discover \nsex-interacting effects.\nBecause CV and GWAMA are methods using the whole sample similarly to RE, \nwe assumed the \ncommon practice in which investigators examine each sex separately using SST regardless of which method is used for the whole sample.\nThus, we compared the power of our MetaSex (RE+SST) approach with that of CV+SST and GWAMA+SST,\nwhere A+B denotes a combination method that calls a result significant \nif either A or B method gives a significant result\nafter correcting for multiple testing.\n%where we correct for the multiple testing. % burden using numerous null simulations.\nWe also compared the power of the bare SST to get a sense of how much power is increased by the methods using the whole sample.\n\nTo make a fair comparison between these methods, \nwe corrected for multiple testing within each method \n%multiple testing has to be corrected \nin an equitable way. \nIn MetaSex (RE+SST), CV+SST, and GWAMA+SST, we performed three tests, \nwhereas in SST, we performed two tests.\nTherefore, for each of these methods,\nwe generated 10 billion ($10^{10}$) null male/female statistic pairs \nand chose the 500th smallest p-value, which was the method-specific\nsignificance threshold to control the false positive rate (family-wise error rate) to $5\\times10^{-8}$.\nThe resulting significance thresholds were\n%$1.67 \\times 10^{-8}$ for FE+SST, \n$1.70\\times10^{-8}$ for CV+SST, \n$1.73\\times10^{-8}$ for GWAMA+SST, \nand $2.49\\times10^{-8}$ for SST.\nFor MetaSex (RE+SST), we used our smart thresholding strategy that applied\n$2.41 \\times 10^{-8}$ for RE and $1.36 \\times 10^{-8}$ for each of the two SST (see Methods).\nThese empirically calculated thresholds ensured that the false positive rates of all compared methods\nwere well controlled.\nSee Methods for the further details of our power simulations.\n%As a result, the false positive rates of all compared methods below were appropriately controlled.\n%still controlling the overall false positive rate to $5 \\times 10^{-8}$ (see Methods). \n%Therefore, all methods compared below have the correct family-wise error rate.\n\n%For RE+SST, FE+SST and GWAMA+SST, since we are performing 3 tests at each locus, \n%we use the significance threshold of $1.7 \\times 10^{-8}$. For SST, since we are performing only 2 tests at each locus, \n%we use the significance threshold of $2.5 \\times 10^{-8}$. \n%\n%For GWAMA, since we are performing only 1 test at each locus, we utilize the significance threshold of $5 \\times 10^{-8}$. \n%We compare the statistical power of simple sex-interacting test (SST) and combining sex-differentiated \n%(RE, GWAMA) approaches and sex-interacting (SST) while varying effect size ratios between \n%male and female studies. \n%\n%\n%To evaluate power, we generated 10,000 case and 10,000 control individuals in the male study \n%with a relative risk of 1.1, a disease prevalence of 0.001 and a minor allele frequency of 0.1. \n%We also generated the female study with the same parameters. \n%We then decreased the effect size ratio between the \n%male and the female studies to compare the power.\n%\n\n\\subsubsection*{Simulating the sex difference in effect sizes}\n\n%We performed two power simulations. \nIn the first power simulation, \nwe simulated the effect size difference between the sexes,\na phenomenon called ``effect size heterogeneity''.\n%We assumed that the error variances were the same for the two sexes.\n%In the second simulation below, we assumed the opposite.\n%Our purpose was to separate the two factors that may affect the power\n%and to evaluate them independently.\nWe assumed a SNP of minor allele frequency 0.3 and generated genotypes of 5,000 males and 5,000 females.\nThen we simulated continuous phenotypes of these individuals while assuming the same error variance\nfor the two sexes.\nFor each male individual, we generated a phenotype assuming a genetic effect size of 0.192 and variance of 1.0.\nFor each female individual, we generated a phenotype assuming 10\\% of the male effect size (0.019) and variance of 1.0.\nWe repeated this simulation 1,000 times and computed the power of a method as the proportion of simulations\nin which the test p-value was \nmore significant than the given significance threshold. \nWe then gradually increased the female effect size from 10\\% to 100\\% of the male effect size,\nto simulate differing levels of heterogeneity.\n\n%After we fix the male and female effect size to be 0.192 and \n%we repeat the whole procedure as we gradually decrease female effect size from 0.192 to 0.0195\n%(0.1923, 0.1731, 0.1539, 0.1347, 0.1155, 0.0963, 0.0771, 0.0579, 0.0387, 0.0192)\n%to simulate sex-specific effect.\n%\\hl{Hi Eun, can you elaborate more? What's the effect size? What's the error term variance that we assumed?}\n\n\n%\n%\nFigure \\ref{power_four} shows the power of the four approaches \n(RE+SST, CV+SST,\n%, FE+SST\nGWAMA+SST, and SST) with respect to the effect size ratio between the two sexes.\n% in the balanced study (a) and the unbalanced study (b).\n%In the balanced study, the number of individuals are equivalent between male and female ($N_{female} = N_{male}$).. \n%However in the unbalanced study, the number of individuals in female study is twice as the number of \n%individuals in male study ($N_{female} = 2N_{male}$).\n%\nAs expected, when the effect size ratio was very small (e.g., 0.1), meaning \nthat the effect is almost sex-specific,\n%that effect sizes of the male and female\n%studies are extremely different, \nSST showed the highest statistical power. \nAs the effect size of the female study increased, the MetaSex (RE+SST) approach showed the highest statistical power,\ndemonstrating that our approach can effectively detect sex-interacting effects.\n%both GWAMA+SST and SST approaches. \n%\n%In the balanced study (Figure \\ref{power_four}(a)), when the effect size ratio is extreme (e.g. 0.1), meaning that the effect size in female study \n%is 10 times larger than male study, SST outperforms all other methods. \n%However, in all other effect size ratios, RE+SST outperforms all other methods. \n%In unbalanced study (Figure \\ref{power_four}(b)), \n%in all effect size ratios, RE+SST outperforms all other methods in terms of statistical power. \n%We provide a more detailed power analysis of the different meta-analysis methods in the supplementary. \nEven at the ratio of 1.0, a situation that the effect size was identical for both sexes (no heterogeneity),\nwhere CV was expected to be the most powerful,\nMetaSex (RE+SST) slightly outperformed CV+SST. \nThis was because of our smart thresholding strategy that allowed a more liberal significance threshold for RE\nwith the expense of \na more stringent threshold for SST.\n%in our RE+SST approach, \n%which gives power advantage compared to CV+SST where the same significance threshold is applied to CV and two tests of SST.\n\n\\subsubsection*{Simulating the sex difference in error variances}\n\nIn the second power simulation, we simulated the error variance difference between the sexes\nwhile assuming a constant effect size (no heterogeneity). \n%In this simulation, we assume that there exists inherent phenotypic error, which we \n%cannot capture with genetic effect and the standard error term ${\\bf e}$ that follows a normal \n%distribution with mean $0$ and variance $\\sigma_e^2$. \nAs in the first simulation, \nfor each male and female individual, we generated a phenotype assuming a genetic effect size of 0.2\n%\\hl{$\\leftarrow$ Please fill in this number} \nand variance of 1.0.\nThen, we gradually increased the error variance of the females from 1.0 to 4.0 \n(standard deviation from 1.0 to 2.0).\nFigure \\ref{power_res} shows the power of the four approaches \n(RE+SST, CV+SST,\n%, FE+SST\nGWAMA+SST, and SST) with respect to \nthe standard deviation ratio between the two sexes.\n%As expected, as the error variance of females increased, the statistical power of all methods \n%decreased due to increased uncertainty.\n%As can be seen in Figure \\ref{power_res}, \nOur proposed approach (RE+SST) outperformed\nother methods in all simulated situations. \nWhen we examined the second and the third best methods,\nwe observed that GWAMA+SST outperformed CV+SST when the standard deviation ratio was large ($\\ge1.4$).\n%although not when the ratio was small ($<1.4$).\n%error ratio is larger than 1.4. On the other hand, when sex-specific residual \n%error ratio is less than 1.5, CV+SST outperforms GWAMA+SST. \nThis was because \nGWAMA,\nbeing \na meta-analytic approach that estimates the variance of error terms in each sex separately,\nwas robust to the variance difference between the sexes. \n%thereby being robust to the error variance difference, \n%whereas CV assumes that the error variance is the same for both sexes.\nAthough both our MetaSex (RE+SST) and GWAMA+SST were meta-analytic methods,\nour method consistently outperformed GWAMA+SST.\n \n\n\n%very small (e.g. 0.1), meaning \n%that effect is almost sex-specific,\n%%that effect sizes of the male and female\n%%studies are extremely different, \n%SST shows the highest statistical power. \n%As the effect size of the female study increases, the MetaSex (RE+SST) approach shows higher statistical power\n%compared to all other methods,\n%showing that our approach is effective for detecting sex-interacting effects.\n%%both GWAMA+SST and SST approaches. \n%%\n%%In the balanced study (Figure \\ref{power_four}(a)), when the effect size ratio is extreme (e.g. 0.1), meaning that the effect size in female study \n%%is 10 times larger than male study, SST outperforms all other methods. \n%%However, in all other effect size ratios, RE+SST outperforms all other methods. \n%%In unbalanced study (Figure \\ref{power_four}(b)), \n%%in all effect size ratios, RE+SST outperforms all other methods in terms of statistical power. \n%%We provide a more detailed power analysis of the different meta-analysis methods in the supplementary. \n%Even at ratio of 1.0, meaning that the effect size is the same for both sexes, \n%a situation that CV is typically more powerful than RE,\n%MetaSex (RE+SST) shows higher power than CV. \n%This is because of our smart thresholding strategy that gives higher weights to significance threshold applied to RE within our MetaSex (RE+SST) framework.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n%The question remains which meta-analysis method is the best approach to use. \n%Unfortunately, \n%there is no definite answer since\n%which meta-analysis approach is most powerful depends on the level of \n%heterogeneity resulting from the gene-by-sex interaction. \n\n\\subsubsection*{Power characteristics of the methods}\n\nWe examined why using RE to complement SST was more powerful \nthan using GWAMA or CV to complement SST. \nWe evaluated the power of the individual methods (RE, CV, GWAMA, and SST)\nover a wide range of female/male genetic effect size pairs, varying each from small value (0) to large value (1.0).\nNote that although we examined a specific effect size range (0,1), \nthe general tendencies in relative power are expected to be similar in different settings;\nfor example, if the effect size range was larger and the variances were larger, the power results\nwould be similar. \nHere, we assumed a error variance ratio of 1.2 (females/males) between the two sexes, %difference in sex-specific error variance.\nbecause this was the average ratio of the phenotypic variances in 10 phenotypes of the NFBC data below.\n%This is because in the NFBC data, \n%the ratio of phenotypic variance between the sexes in 10 phenotypes.\n%On average, the male phenotype had 1.201 times larger variance than the female phenotype in NFBC data.\n%Thus, we assumed this variance difference in this simulation.\n%We assumed that the male and female sample sizes are equal.\n\nFigure \\ref{power_comp11}\nshows the power of the four methods \n(RE, CV, SST, and GWAMA) \nin a two-dimensional space where x-axis is the male genetic effect size and y-axis is \nthe female genetic effect size of a SNP.\nWe plotted the $50\\%$ power lines \nof the four methods, so that each line denotes pairs of the male and female effect sizes where the method \nachieved an exact power of 50\\%.\n%under the balanced study\n%assumption between male and female studies. \nBecause the power increased as the effect size increased,\nthe closer the $50\\%$ line was to the bottom leftmost point on the graph,\n%effect size $0$, the powerful \nthe more powerful the method was.\nAs expected, when one of the effect sizes was close to zero\n(sex-specific effect: top left corner or bottom right corner), \nSST was the most powerful.\n%since other method will take into account the zero effect size of one study when it \n%computes sex-differentiated meta statistic. \n%However SST approach ignore the less significant statistic. \nWhen the\neffect sizes were at most moderately different between male and female studies (middle area), RE\nclearly outperformed other\n%and FE \napproaches. \n%But when the effect sizes are moderately different between male and female study, \n%RE outperforms all other methods. \nWe measured the size of the area whose power was greater than $50\\%$, \nwhich was the area outside of the each curve toward the top right corner. \n%containing the \n%point where the male effect size=1 and female effect size=1. \nThe sizes of the areas were \n$22.1\\%$ for SST, $23.5\\%$ for CV, $29.7\\%$ for GWAMA, and $29.9\\%$ for\nRE.\n%$29.9\\%$ for RE, $29.7\\%$ for GWAMA, $23.5\\%$ for CV, and $22.1\\%$ for\n%SST.\n%, $26.7\\%$ for FE \nThus, RE and GWAMA achieved the largest similar areas.\nHowever, the difference was that the GWAMA power line was more steeply curved than the RE power line,\nwhich demonstrated that GWAMA tended to detect effects that were extremely different between the sexes.\nTherefore, what GWAMA found could have substantial overlap to what SST found. \n%be nearly sex-specific and were already found by SST.\nIn contrast, RE and SST complemented each other resulting in\nthe largest combined area in this plot.\nTo quantify this difference, \nwe measured the area greater than $50\\%$ not \ncovered by the $50\\%$ power \nof the SST approach. \n%We observe $9.5\\%$ for GWAMA, $11.6\\%$ for RE and $11.1\\%$ for FE.\n%The areas were $14.0\\%$ for CV, $13.8\\%$ for GWAMA and $15.4\\%$ for RE.\nThe areas were $13.8\\%$ for GWAMA and $15.4\\%$ for RE.\nThus, if we assume the common practice of applying SST first, % to discover loci with sex-specific effects, \nRE \n%and FE \n%give us the largest area similarly.\ncan give us the biggest additional power.\n%Based on the graph and the area greater than $50\\%$ power, \n%we feel that \n%RE \n%balances \n%losing very little in terms of power when the effect \n%sizes are close to each other compared to FE while gaining a significant advantage over FE when the effect sizes are different.\n\n\n%RE has another advantage over GWAMA. In RE, the sample size differences between males and females are natually accounted for\n%by the differences in the standard errors of effect size estimates. In GWAMA, the chi-square statistics of two sexes are simply added, \n%which is not optimal when the sample sizes are unequal. \n\n%In Supplementary Figure \\ref{power_comp1}, we show the similar plots of power lines for the situations that male and female sample sizes are unequal.\n%%%We also note that GWAMA does not take into account differences in numbers of males and females.\n%In Supplementar Text, \n%%%In the supplementary section, \n%we also present a possible extension of GWAMA that takes into account sample size differences. \n\n\n\n\n\n\n\\begin{comment}\n\n\n%\\subsection{The presence of background GxS interactions explains the advantage of the sex-differentiated meta-analysis approach}\n\\subsection{RE increases power due to the ``background GxS effect''}\n\n\n\n\n\n\\hl{I had to comment this section because we explicitly model GxS background effects in the new model.}\n\n\\hl{But I thought it's good to show power difference by variance differences. }\n\n\\hl{We would have been able to include these results if phenotypic residual variance difference were simulated directly, not through GxS.}\n\t\n\n\n\\begin{figure}[h!]\n\\centering\n\\begin{tabular}{cc}\n%{\\includegraphics[width=0.45\\textwidth]{power10.pdf}} \\\\\n(a){\\includegraphics[width=0.43\\textwidth, height=0.43\\textwidth]{../heatmap/RE.pdf}}\n%(b){\\includegraphics[width=0.43\\textwidth, height=0.43\\textwidth]{heatmap/FE.pdf}} \\\\\n(b){\\includegraphics[width=0.45\\textwidth, height=0.43\\textwidth]{../heatmap/CV.pdf}} \\\\\n(c){\\includegraphics[width=0.47\\textwidth, height=0.43\\textwidth]{../heatmap/RE_CV.pdf}}\n%(e){\\includegraphics[width=0.42\\textwidth, height=0.40\\textwidth]{effects3.pdf}} \\\\\n\\end{tabular}\n\\caption{ Power of (a) random-effect meta-analysis (RE), %(b) fixed-effect meta-analysis (FE) and\n(b) sex-as-covariate methods (CV) as a function of the GxS heritability and \nthe heterogeneity between the male and the female study effect size. \n(c) shows a comparison of the two methods with the color \ncorresponding to the method with the highest power.}\n\\label{power_hetero}\n\\end{figure}\n\n\n\n\n\t\n\t\nHere we show a possible explanation of why meta-analysis methods have higher power than \ntraditional approaches in real data due to what we refer to as the ``background gene-by-sex effect''.\nThe background gene-by-sex effect represents the existence of small sex-interacting effects from a large number of \nloci throughout the genome.\nWe show that the presence of gene-by-sex interactions throughout the genome \nlead an advantage for RE approach over transitional approaches, \nbecause ``background gene-by-sex effect'' can be one of many causes\nof difference in residual phenotype variance between male and female. \n%\nThis effect can be quantified by considering the amount of heritability accounted for by gene-by-sex (GxS) interactions.\nTo test this, we generate simulated phenotype data using the Finland Birth Cohort as a model population.\nFor each simulated phenotype, we assume a given heritability ($h_g$) and a given GxS heritability ($h_s$) and \ngenerate a phenotype by \nsampling from a multivariate normal distribution with mean zero and covariance equal to $h_g{K}+h_s {K}_s + h_I {I}$, where ${K}$ \nrepresents the kinship matrix for males and females and ${K}_s$ represents the GxS kinship matrix (see Methods) \nand $h_I$ can be computed by $1 - h_g - h_s$. \nWe insert an effect for a given SNP and then attempt to identify this effect as significant using each method.\nPower is calculated as the proportion of the number of effects identified as significant for a large number of such simulations.\nWe calculate power for a range of $h_g$ and $h_s$ values and we vary the level of heterogeneity in effect size between males and females.\n\n\n\nWe compare the statistical power between the RE and CV approaches while varying gene-by-sex background effect and \nheterogeneity between male and female effect sizes. We first fix the amount of phenotypic variance explained by \nnoise ($h_I$) to be $0.5$ and \nvary GxS heritability ($h_s$) from 0 to 0.25. For each chosen GxS heritability ($h_s$), we set the $h_g$ to be $0.5 - h_s$. \nWe also vary the effect size of main genetic effect between male and female, which is represented as\n``Heterogeneity'' in the Figure \\ref{power_hetero}.\n%Figure \\ref{power_hetero} (a), (b) shows power of proposed random effect meta-analysis approach and\n%sex-as-covariate method respectively.\n%In these heat maps, as the color become darker, the power is higher as the legends show. \n%In Figure \\ref{power_hetero} (c), the region of heat map is colored with the color representing most powerful method in the region. \nThis resulting heat map plot indicates that in most cases\nthe RE approach is the most powerful except when the\neffect sizes in the male and female studies are equal and there exists small background gene-by-sex effect.\nWhen there is no difference in effect sizes between males and females and small gene-by-sex background effect, CV is \nmost powerful.\nThis result is expected because \nthe presence of many gene-by-sex interactions \nincreases the residual phenotype variance of the trait and \nCV method cannot properly account for this heterogeneity in the phenotype.\n%\n%when both genders are analyzed together compared to when they \n%are analyzed separately. \n%\n%This is consistent with our observation that the meta-analysis methods perform \n%better than the combined methods when there exist a large number of gene-by-sex interactions.\n\n\\end{comment}\n\n\\subsection{Analysis of the North Finland Birth Cohort data} \n\nWe analyzed the NFBC data \\citep{Sabatti:NatGenet:2009}\nwhich consisted of 5326 individuals (2546 males and 2780 females). This dataset provided\n10 phenotypic measurements of the individuals.\n\n\\subsubsection*{Sex difference in phenotypic variances}\n\nWe first investigated whether the phenotypic variances showed differences between the sexes.\n%The phenotypic variance can be affected \n%As shown in the simulations, the power of our MetaSex method \n%is dependent on both the effect size differences between the sexes and \n%the phenotypic variance differences between the sexes. \n%We first investigated if the phenotypic variances differed by gender in the 10 phenotypes of this real dataset. \nWe applied the Levene's test, \nwhich tested for the equality of the variance between two groups (see Methods).\nTable \\ref{finland_levene1} shows that five phenotypes (Triglycerides, HDL, LDL, BMI, and Diastolic blood pressure)\nhave significant differences in phenotypic variance between males and females ($P<0.005$, Bonferroni correction on 10 tests).\nThe most significant difference was observed in Triglycerides ($P<10^{-20}$).\n%One additional phenotype (diastolic blood pressure) also showed a statistically significant difference although the significance was not as strong as that of the four phenotypes.\n%These results suggested that if the phenotypic variance difference was due to non-genetic factors\n%such as sex acting as an environment or sex-interacting external environments, \n%distinct residual variances might need to be modeled for optimal testing.\n\n%can be different between the sexes\n%and that any method that does not account for this, such as CV, can be suboptimal.\n\n\n\\subsubsection*{Variance component analysis}\n\nTo investigate why the phenotypic variances of some traits differed between the sexes, \nwe performed a variance component analysis.\n%we evaluated the genetic and environmental variance components.\nWe used the five-variance-component linear mixed model described in Figure \\ref{overview}A,\nwhere we excluded the SNP terms.\nDecomposing the variance components could reveal if the phenotypic variance difference came from the differences\nin polygenic background effects, or the differences in the error variances.\nWe used the GCTA method to perform this analysis \\citep{Yang:NatGenet:2010}.\nFirst, we generated the genetic relationship matrix, $\\mathbf{K}$, implemented in GCTA framework.\nSecond, we created two modified GRM matrices, $\\mathbf{K_{f}}$ and $\\mathbf{K_{m}}$, from $\\mathbf{K}$ by having multiplications of $\\mathbf{hh}^T\\circ\\mathbf{K}$ and $\\mathbf{(1-h)(1-h)}^T\\circ\\mathbf{K}$, respectively.\nUnfortunately, GCTA did not allow us to separate the error term into two sex-specific terms as in the model in Figure \\ref{overview}A,\nbecause the default error term (with variance $\\sigma^2_e$) for the whole sample is automatically included in the model.\nThus, we added the sex-specific error term (with variance $\\sigma^2_{e,ss}$) to one sex. \nWe tried both males and females for this additional term, and chose the configuration with $\\sigma^2_{e,ss}>0$.\n\n%Third, the GCTA is not capable of changing the random error components; therefore, we added sex-specific random error variance, $\\sigma^2_{e,ss}$, of which each phenotype has sex specific random error\n%components of $\\mathbf{hh}^T\\circ\\mathbf{A_{e}}$ or $\\mathbf{(1-h)(1-h)}^T\\circ\\mathbf{A_{e}}$ and have positive variance component.\n\n\nTable \\ref{finland_gcta1} and Table S1 show the variance component estimates.\nThe polygenic background effect ($\\sigma^2_g$) was significantly non-zero in many traits\n($P<0.005$ for 5 traits; BMI, HDL, Height, LDL, and Systolic blood pressure).\nThe sex-interacting polygenic background effects ($\\sigma^2_{g,m}$ and $\\sigma^2_{f,m}$) \nwere non-zero in some traits,\nbut none of them showed significance ($P>0.005$) due to large standard errors.\n%but they did not significantly differ from zero \n%possibly because of large standard errors. \n%However, the standard errors of these components were large.\n%Thus, no trait showed a significant p-value in the test testing for non-zero $\\sigma^2_{g,m}$ or $\\sigma^2_{g,f}$ in our dataset.\nThe variance of sex-specific error term ($\\sigma^2_{e,ss}$) was significantly non-zero in Tryglyceride ($P=6.23 \\times 10^{-5}$) and BMI ($P=1.2 \\times 10^{-4}$).\nThus, in some phenotypes, \nthe phenotypic variance difference between the sexes was not completely explained by the genetic components alone,\nwhich suggested the need for explicitly modeling the sex difference in error variances as in our MetaSex method.\n\n%in some phenotypes are \n%partly driven by the residual error differences, \n%while the impact of \n%sex-specific polygenic background effects was not clear in this dataset.\n\n\\subsubsection*{Full model versus approximated model}\n\n%that six phenotypes (Triglycerides, LDL. C-reactive protein, Glucose, Insulin, and Height) have\n%large sex-specific variance components $\\mathbf{h_{ss}>0.05}$\n%where $\\mathbf{h_{ss}}$ is $(\\sigma^2_{g,f}+\\sigma^2_{g,m})/\\sigma^2_{p}$.\n%We then tested if the variance difference between female and male groups are significant by testing $\\chi^2_{1}$ statistics by taking \n%$ [ \\frac {\\sigma^2_{g,f} - \\sigma^2_{g,m}}{\\sqrt { SE(\\sigma^2_{g,f})^2 + SE(\\sigma^2_{g,m})^2 }}]^2$ for each traits, but none of phenotypes showes significance.\n%\n\nAlthough it is feasible to estimate five variance components one time using tools such GCTA, \napplying the full linear mixed model to millions of markers can be prohibitively slow\nbecause the variance component estimation needs to be repeated for each SNP.\n%it will be prohibitively slow to apply the full linear mixed model to the association test of millions of SNPs.\nTherefore, we proposed an approximated model that decomposes the problem into two sex-specific linear mixed models (Figure \\ref{overview}B).\n%under the assumption that the variance component estimates will still be accurate. \nHere, using the NFBC dataset, we examined if the variance components estimated by the approximated model\nwere similar to those estimated by the full model.\n\n\n%Next, we applied linear mixed model in each sex to distinguish the variance component representing polygenic background effects\n%from the variance component representing the random error term. \n%In this way, we could show the similarity between the estimates from the full model with five variance components and the\n%sex-specific models with three variance components.\nTo achieve this goal, we performed GCTA analyses in each sex-specific two-variance-component model described in Figure \\ref{overview}B. \n%, where\n%each model has two variance components.\n%In GCTA analysis, it is unnecessary to create extra sex-specific GRMs, $\\mathbf{A_{g,f}}$ and $\\mathbf{A_{g,m}}$, because we\n%already manually separated the samples by gender, and GCTA will automatically generate $\\mathbf{A_{g,f}}$ and\n%$\\mathbf{A_{g,m}}$ which has the exactly same element of the $\\mathbf{A_{g}}$.\n%Therefore, instead of having separated variance components of two, $\\sigma^2_{g}$ and $\\sigma^2_{g,f(m)}$, we\n%have a only one variance components $\\sigma^2_{g,f(m)}$.\nTable \\ref{finland_gcta2} shows the estimated variance components for the two sexes. \n%We assumed that if there was no discrepancy between the full and sex-specific models, the overall amount of variance components corresponding to a sex were similar.\n%If variance components of the two models show clear discrepancy, one could argue that an appropriate way of considering the differences is necessary. \nThe variance components can be categorized into two groups: the genetic variance and the random error variance.\nThe genetic variaces in the full and sex-specific models are $\\sigma^2_{g} + \\sigma^2_{g,f(m)}$ from Table \\ref{finland_gcta1} and $\\sigma^2_{g,f(m)}$ from Table \\ref{finland_gcta2}, respectively.\nThe random error variances in the full and sex-specific models are $\\sigma^2_{e} + \\sigma^2_{e,ss}$ from Table \\ref{finland_gcta1} (or $\\sigma^2_{e}$, depending on which sex $\\sigma^2_{e,ss}$ was added) and $\\sigma^2_{e,f(m)}$ from Table \\ref{finland_gcta2}, respectively. \n%Lastly, the genetic heritability for the full and sex-specific models are $(\\sigma^2_{g} + \\sigma^2_{g,f(m)})/\\sigma^2_{p}$ and $\\sigma^2_{g,f(m)}/\\sigma^2_{p}$, respectively. \n%We compared these estimates between the full and sex-specific models (Figure \\ref{gcta_summary}).\n%We used log of the summed variance components if the values are not normalized.\nWe compared if the genetic and random error variances are the same between the full and sex-specific models.\nFigure \\ref{gcta_summary} shows that the estimated variance components were highly concordant between the full and sex-specific models.\nMost of the points followed the $y=x$ line (dashed line) well.\n%To compare the differences in variances between the two models, We added a dashed line which represents the function $y = x$ in each plot.\n%As expected, most points in these plots show no evidence of discrepancy. \nThe Pearson correlations were high ($r^2>0.9$) in all comparisons, except for the male genetic variance.\nThe low correlation in the male genetic variance plot was driven by \none outlier (Diastolic blood pressure), which may reflect instability in optimization procedure.\n%for which the full model and sex-specific model estimates differ greatly.\nIf we excluded this outlier, the correlation was high ($r^2=0.979$).\nOverall, the estimates of the full and sex-specific models were highly concordant as expected,\n%there can be small discrepancies possibly driven by the instability of the optimization procedure. \n\n%However, interestingly, we found some outliers which causes the decreased $r^2$, which is derived from the pearson correlation coefficient. \n%These results show that the patterns of sex differences in variance components can be considerably different between traits\n%and therefore support that an analysis method should comprehensively account for sex differences in both polygenic effects and random error variances.\n%Thus, our MetaSex approach will outperform other methods such as CV which does not account for variance difference.\n%The variance difference is not because of gene-by-sex interaction of the polygenic model,\n%because we already accounted for sex-interacting polygenic background effects in our linear mixed model.\n%Rather, a more plausible explanation is that sex defines a physical or biological environment that affects the variance of phenotype\n%in an unknown way. Since we do not know how sex affects variance, our best possible strategy for now is to model\n%this variance difference in error terms, which is our MetaSex model.\n\n%This result underscores a few important points.\n%First, the variance of phenotypes can be extremely different between sexes in some phenotypes.\n%If these differences exist, a method should account for those differences.\n%Thus, our MetaSex approach will outperform other methods such as CV which does not account for variance difference.\n%Second, the variance difference is not because of gene-by-sex interaction of the polygenic model,\n%because we already accounted for sex-interacting polygenic background effects in our linear mixed model.\n%Rather, a more plausible explanation is that sex defines a physical or biological environment that affects the variance of phenotype\n%in an unknown way. Since we do not know how sex affects variance, our best possible strategy for now is to model\n%this variance difference in error terms, which is our MetaSex model.\n%\n\n% revise the paper above this point!! (CHL)\n\n\\subsubsection*{Association mapping}\n\nWe mapped associations to the 10 phenotypes in the NFBC dataset using our MetaSex approach.\n%We applied our MetaSex approach and other competing approaches to the association test for the 10 phenotypes in this dataset.\nWe used the efficient approximated model; \nthat is, in each sex, we applied a sex-specific linear mixed model to account for the polygenic effects and the sex-interacting polygenic effect simultaneously (Figure \\ref{overview}B).\nThen, we applied RE and SST to the resulting male and female effect size estimates.\nFor comparison, we also applied CV and GWAMA. \nIn both CV and GWAMA, we similarly accounted for polygenic background effects using variance components.\nFinally, for a fair comparison, we calculated the genomic control factor $\\lambda$ separately for each method and\ncorrected the resulting p-values of each method using this factor.\n(Table \\ref{finland_lambda1}).\n\n%\n%\n%compared to \n%the rest of the six phenotypes (crpres, glares, insures, sysres, diaries, height).\n%Thus the association mappings of former four phenotypes (tires, hdlres, ldlres, bmires) are\n%more likely to have an advantage with meta-analysis approaches (RE, GWAMA, SST) \n%compared to the CV method.\n%\n%We computed the association statistics and p-values \n%for males only (SST male), females only (SST females), males and females combined \n%using random effects meta-analysis (RE), and the\n%approach combining the male and female data and including sex as a covariate in \n%the statistical model (CV) and a two degrees of freedom $\\chi^2$ test (GWAMA).\n%We then compute the genomic control $\\lambda$ to see the inflation factor of each method. \n%Table \\ref{finland_lambda1} shows the genomic control $\\lambda$ for different approaches.\n%For each method, we apply genomic control to correct for inflation in order to \n%be able to fairly compare the different approaches.\n%\n\n\n\n%\n%\\begin{table}[h!]\n%%\\tiny\n%\\centering\n%\\resizebox{0.85\\textwidth}{!}{\n%\\begin{tabular}{cccccc}\n%\\hline\n%Phenotype & var(female) & var(male) & var(male)/var(female) & Levene test p-value \\\\\n%\\hline\n%tgres & 0.17152 & 0.2563 & 1.494 & 1.451e-21 \\\\\n%hdlres & 0.1349 & 0.1077 & 0.7989 & 2.546e-10 \\\\\n%ldlres & 0.67073 & 0.820 & 1.2234 & 1.394e-05 \\\\\n%bmires & 0.0309 & 0.0189 & 0.6113 & 6.142e-19 \\\\\n%crpres & 2.372 & 2.244 & 0.9462 & 0.0877 \\\\\n%glures & 0.00647 & 0.00678 & 1.0482 & 0.174 \\\\\n%insres & 0.1105 & 0.1172 & 1.0609 & 0.1173 \\\\\n%sysres & 156.77 & 171.357 & 1.092 & 0.0079 \\\\\n%diares & 118.56 & 136.053 & 1.147 & 0.0012 \\\\\n%height & 38.65 & 41.098 & 1.063 & 0.0154 \\\\\n%\\hline\n%\\end{tabular}\n%}\n%\\caption{ Levene statistics and p-values for 10 NFBC phenotypes.\n% }\n%\\label{finland_lambda1}\n%\\end{table}\n\n\n\n% mean variance ratio : 1.20728\n\n\n\n\n\n\n\n\nThe challenge in this real dataset analysis was the lack of objective measures to compare\nperformances of the methods, \n%In the real dataset, it is difficult to evaluate the performance of statistical tests, because\nbecause we do not know which loci are true positives.\nWhat we could do was to examine loci that were genome-wide significant and to compare the p-values of different methods.\nUnder the assumption that the loci exceeding the significance threshold have high chance of being true positives,\na putatively better method can be a method that gave smaller p-values at those loci.\n\n\n\nIn this analysis, we discovered 16 loci that were associated with\nat least one of the 10\n%any of 10 \nphenotypes at the threshold level $P<5\\times10^{-8}$ \nby at least one\n%in any of different \nmethod.\nAt these 16 loci, we calculated the p-values using RE, CV, GWAMA, and SST (Table \\ref{tab:NFBC1}).\n%The magnitude of the p-value at the loci which are significant can provide some insight \n%into the relative power of the various methods. However, this analysis has several caveats \n%including that since we can only apply it to significant loci, we can only perform the comparison \n%at a relatively small number of data points. \n%Nevertheless, examining the different methods applied to real data provides some \n%insights and highlights that there are significant differences in the p-values depending on \n%which method is applied.\n%%\n%In Figure \\ref{power_result}, we compare the association mapping results from\n%four approaches (RE, CV, GWAMA, SST) on the 16 significant loci (threshold : $5.0 \\times 10^{-8}$)\n%from the NFBC data containing 10 phenotypes. \nTo compare the p-values of the methods, % improvement of p-value of the meta-analysis methods (RE, GWAMA, SST)\nwe chose CV as a reference method to be compared with.\nWe plotted the $-log_{10} \\it{P}$ difference between\ndiffering methods and the CV approach in Figure \\ref{power_result}A\n([$-log_{10} \\it{P}$ of RE/GWAMA/SST] $-$ [$-log_{10} \\it{P}$ of CV]).\nThus for each SNP, the positively larger the difference is, the better the method is compared \nwith CV. \n%For the space limitation, if the $-log_{10} \\it{P}$ is less than $-4$ \n%(there are only several cases with SST approach), \n%we plot these cases as -4. \nAs shown in Figure \\ref{power_result}A, RE showed the best overall performance. %outperforms GWAMA and CV.\nRE gave smaller p-values than GWAMA at 14 out of 16 loci and better p-values than CV at 11 out of 16 loci. \n%\\hl{I wrote these numbers by looking at plot. Please check the actual numbers.}\nEven at loci where GWAMA or CV showed smaller p-values than RE, the\ndifference from RE was small. \n%RE showed reasonably good p-values.\nSpecifically, RE p-values were never larger by one order of magnitude than any of these methods at all 16 loci.\n\n\nWe further investigated on what characteristics of the loci caused these p-value differences between the methods.\nFigure \\ref{power_result}B shows the phenotype variance ratio (PVR) between males and females \nafter regressing out the genetic effect of the SNP tested. \nFigure \\ref{power_result}C shows the ratio of the effect size estimates between males \nand females for each SNP. \nBecause the power of the methods, as we showed in power simulations, depend on both the error variance ratio (which will affect PVR) \nand the effect size estimate ratio between males and females, \nfor each SNP, we can interpret the p-values of the methods \n(Figure \\ref{power_result}A) in terms of \nthe PVR (Figure \\ref{power_result}B) and the \neffect size ratio (Figure \\ref{power_result}C).\n\nIf we look at the SNP rs7298683 (indicated by $\\dagger$), \nthe effect size ratio between male and female studies was -0.0313, \nwhich means that the effect direction was opposite for the two sexes and that the absolute magnitude of \nthe male effect size was 33 times larger than that of the female effect size.\nHowever, there was almost no difference in PVR \n%\\hl{change this short name (also in SupTable) because I am not using residual any more}) \nbetween male and \nfemale studies (PVR of 0.965). In this case, the SST approach gave the smallest p-value,\nbecause SST was the best method to detect extreme effect size difference as we showed in simulations. % and \n%GWAMA, RE, CV in this order. \n\nIf we look at the SNP rs2167079 (indicated by $\\ast$), the PVR (female/male) was\n1.261 and the effect size ratio (female/male) was 0.43.\nVariance in females was larger, so the female effect size estimate were more uncertain than the male estimate.\nThus, when combining information from the two sexes, an optimal method should give more weight to male estimate.\nMoreover, effect size was greater in males. Thus, an optimal method should weight the male estimate even further.\nBecause CV ignores both variance difference and effect size difference, RE showed smaller p-values at this locus than CV.\n%In this case, the residual phenotype variance difference and effect size difference between \n%male and female studies affects in the same direction. Thus this situation make the SNP\n%appear to have even more sex-interacting effect than the SNP's original effect size difference\n%in the association mapping.\nA similar interpretation of the result can be applied to the SNPs rs7120118 and rs693 (indicated by $\\bullet$).\n\nNow consider the SNP rs11668477 (indicated by $\\ddagger$). \nThe PVR (female/male) was\n0.82 and the effect size ratio (female/male) was 0.5. \nIn this case, when combining information from the two sexes,\nbased on the variance, we should weight the female study more, but based on the effect size, we should weight the male study more.\nThus, the impact of differing variance and the impact of differing effect size canceled out, giving CV the smallest p-value of all approaches, because CV can be considered as equally weighting the two sexes.\n%In this case, the larger residual phenotype variance of the female study cancels out the larger effect \n%size of the female study. Thus this makes the SNP appear not to have a sex-interacting effect. \nA similar interpretation of the result can be applied to the SNPs rs2794520, rs560887, \nand rs10096633 (indicated by $\\diamond$).\nHowever, as described, even in such situations, RE was not much worse than CV.\n%Thus we can predict and interpret the behavior of the association methods correctly when \n%applying it to the NFBC data with\n%our hypothesis that the difference in residual phenotype variances and effect sizes \n%between male and female studies affects the power of association method in identifying \n%sex-interacting effects.\n\nIn summary, RE showed the best stable performance of all methods,\nexcept when the effect only existed in one sex where SST performed the best.\n%and when the situation that the effect size difference and the variance difference canceled each other out \n%(where CV performed the best, but RE was not much different). \nTherefore, this analysis demonstrates that our MetaSex framework where RE and SST complement each other can cover many possible situations with high power.\n\n\n\\section{Discussion}\n\nWe here presented MetaSex, a novel framework that accounts for the sex difference in genetic architecture for powerful association mapping.\nOur method built upon a comprehensive model that included multiple\nvariance components\nand expedited the optimization by using an approximation based on sex-specific models.\nWe utilized the meta-analysis framework to achieve high power \nin a wide range of situations. We have shown superior performances of our approach compared with previous approaches \nin both simulations and real data analysis. \n%in the analysis of NFBC data.\n\nThe high power of our approach was attributable to two factors: the effect size difference between the sexes\nand the error variance difference between the sexes.\nPrevious studies have observed effect size differences at a number of loci \\citep{Randall:PlosGenet:2013}.\nHowever, few studies have reported phenotypic variance differences between the sexes, which can reflect the error variance difference. \nIn our study, we showed that the phenotypic variance difference can be a real phenomenon in the existing dataset.\nThe non-genetic cause of the phenotypic variance difference can be \nsex acting as an environment (e.g. hormone) or sex interacting with external environments (e.g. lifestyle).\n%Surprisingly, these variance differences were apparent in a number of traits in the NFBC cohort data.\nWe demonstrated that accounting for the non-genetic causes by modeling differing error variances can increase power.\n\n%This phenomenon emphasizes that an optimal model should account for phenotypic variance differences as well.\n%%include an additional variance component to account\n%%for the variance difference.\n%%This is a striking observation showing that \n%This is why the traditional CV which assume the same error variance between sexes\n%can be sub-optimal.\n\n%It is of interest to elucidate what is the cause of the phenotypic variance difference between the sexes.\n%One possibility could be sex-interacting polygenic background effects,\n%because small polygenic effects over the genome can have differing effect sizes between the sexes.\n%Our method explicitly modeled this factor using sex-specific variance components of polygenic effects.\n%Another possibility could be \n%sex acting as an environment (e.g. hormone) or sex interacting with external environments (e.g. lifestyle). \n%Our method modeled this factor using sex-specific error variances.\n%%other factors caused by the sex-specific physical and biological environments,\n%%which cannot be explained by the polygenic components. %jllllllljcase the polygenic background \n%Our analysis on NFBC data supported the presence of the latter in some traits. \n%Testing the former was non-significant in our dataset, but that does not warrant the absence of those effects.\n%%To distinguish these two possibilities, we applied a linear mixed model to each sex\n%%and concluded that the cause of variance difference can be uniquely different among traits.\n%%This interesting observation suggests that \n\n\nAlthough we tried to account for possible phenomena that can occur due to the sex difference in genetic association mapping, \nour model might still have limitations.\nWe explictly modeled the sex difference in the effect sizes of the associated locus, magnitudes of the polygenic effects, and error variances.\nHowever, we did not model the sex difference in the phenotype distribution (i.e. shape), \ngenetic interaction with covariates, or the liability distribution of binary traits.\nWe expect that a large-scale study will be necessary to fully decipher the \nsex-interacting genetic architectures of human traits. \n\n%%how genetic architecture interacts with sex can be trait-specific\n%%and motivates further studies of the sex-dependent genetic architecture of each trait.\n\n%One challenge in combining information from the two sexes was how to account for the effect size heterogeneity to maximize power.\n%We chose to apply the random effects meta-analysis to female and male effect sizes, \n%which is equivalent to testing both the mean effect and the sex-interacting effect.\n%One limitation of such approaches combining information from multiple sources, as is the GWAMA approach,\n%is that the interpretation is difficult in distinguishing from which source the signal is coming.\n%We expect that the Bayesian framework \\citep{Han:2012aa} that provides posterior probabilities that the effect will exist in each sex, will be useful for interpretation. \n\n%There are a number of models in meta-analysis framework, such as the fixed effects model and random effects model,\n%and the terminologies for them can be confusing. Sometimes the fixed effects model refers to a model that assumes a common effect\n%between studies (sexes), but sometimes it refers to a model that assumes a fixed effect in each study (sex).\n%In that sense, our model is a fixed effects model, since we assume a fixed female effect and a fixed male effect.\n%Then, after estimating those effects, we apply SST and the random effects model additionally.\n\n%To show the performance of our approach in real data, we compared the association p-values at the loci that were genome-wide significant.\n%This approach has several limitations. First, the associations exceeding genome-wide threshold need not be true positives.\n%Second, the p-value can vary due to sampling errors. In spite of these shortcomings, \n%this was the best we could do for comparison in real data, because for many traits, we have an idea of what are associated loci,\n%but no idea of what are true causal loci. We expect that we will be able to perform more systematic comparison in the future,\n%if discovered loci by GWAS will become validated in functional studies.\n\n\n%\n%However, we effectively excluded this hypothesis \n%%that the variance difference is caused by sex-interacting polygenic effects,\n%because we have explicitly added the variance component to account for sex-interacting polygenic effects,\n%and we still observed variance difference in residual errors.\n%%Therefore, the variance difference is caused by something different from the sex-interacting polygenic effects.\n%Thus, it seems that sex defines a physical and biological environment that affects the variance in some unknown ways.\n%We expect that future studies will uncover the exact causes of this phenomenon. \n%\n%%We expect that future studies will discover what physical and biological environment the sex defines to incur\n%%phenotypic variance differences. \n\n%Our method (RE+SST) can cover a wide range of different situations with high power.\n%SST is optimal for detecting sex-specific effects, and\n%RE is effective for detecting sex-interacting effects. \n%Moreover, our meta-analytic framework accounts for different error variances of two sexes.\n%We expect that our method will help researchers identify more genetic loci that have sex differences \n%in residual variances and/or effect sizes. \n\n\n\\section{Methods}\n\n\\subsection{MetaSex}\n\nThe standard linear mixed model that accounts for polygenic background effects can be written as\n\\begin{equation}\n{\\bf y} = \\mu {\\bf 1} + \\beta {\\bf x} + {\\bf u} + {\\bf e} \n\\label{eq:standard}\n\\end{equation}\nwhere ${\\bf y}$ is a phenotype vector, $\\mu$ is an intercept, ${\\bf 1}$ is a vector of ones, ${\\bf x}$ is a genotype vector, $\\beta$ is the genetic effect,\n${\\bf u} \\sim N(0, \\sigma^2_g {\\bf K})$ is a variance component that accounts for polygenic effects,\nand ${\\bf e} \\sim N(0, \\sigma^2_e {\\bf I})$ is the random error term.\nTypically, ${\\bf K}$ is defined as the genotype similarity matrix between individuals.\nRecent studies have developed numerical optimization strategies that allow an efficient application of this standard linear mixed model to GWAS\\citep{Zhou:NatGenet:2012,Kang2010,Kang:2008bx}.\n\nWe expand this model to a model that comprehensively accounts for sex differences.\nWe assume that each of the four terms of the standard model (intercept, genetic effect, polygenic effect, and error variance) can \nhave differences between the sexes.\n%To account for sex differences in each of the four terms in this standard model, w\nWe expand the model as follows:\n\\begin{equation}\n{\\bf y} = \\mu {\\bf 1} + \\mu_s {\\bf h} + \\beta {\\bf x} + \\beta_{g \\times s} {\\bf x \\circ h} + {\\bf u_g} + {\\bf u_f} + \\mathbf{u_m} + {\\bf e_f} + {\\bf e_m} \n\\label{eq:comprehensive}\n\\end{equation}\nwhere ${\\bf h}$ is a sex-indicating vector with elements 1 if an individual is female and 0 if male and \n${\\bf x \\circ h}$ denotes an element-wise product.\nThere are five variance components in this model:\n${\\bf u_g} \\sim N(0, \\sigma^2_g {\\bf K} )$, \n${\\bf u_f} \\sim N(0, \\sigma^2_{g, f} ({\\bf K} \\circ \\bf{h}\\bf{h}^T))$,\n${\\bf u_m} \\sim N(0, \\sigma^2_{g, m} ({\\bf K} \\circ \\bf{(1-h)(1-h)}^T))$,\n%${\\bf u_{g \\times s}} \\sim N(0, \\sigma^2_{g \\times s} K_{g \\times s})$, \n${\\bf e_f} \\sim N(0, \\sigma^2_{e,f} {\\bf I \\circ \\bf{h}\\bf{h}^T})$, \nand ${\\bf e_m} \\sim N(0, \\sigma^2_{e,m} {\\bf I \\circ \\bf{(1-h)(1-h)}^T})$.\n${\\bf u_g}$ is the standard random component that accounts for polygenic effects where ${\\bf K}$ is the genotype similarity matrix.\n${\\bf u_{f}}$ is an additional random component that accounts for sex-interacting polygenic effects that are female-specific.\nSimilarly, ${\\bf u_{m}}$ is a random component that accounts for sex-interacting polygenic effects that are male-specific.\n%where\n%${\\bf K} \\circ {\\bf hh^T}$ is a ${\\bf K}$ matrix whose relationships between females are left non-zero. \n%whose male-related elements are zero. \n%${\\bf u_{m}}$ is similar defined for males. \n%${\\bf I_f}$ and ${\\bf I_m}$ are modified identity matrices whose diagonal elements are zero for males and females, respectively,\n%such that ${\\bf I_f} = {\\bf I} \\circ \\bf{h h^T}$ and ${\\bf I_m} = {\\bf I} \\circ \\bf{(1-h) (1-h)^T}$. \n%If we order individuals by sex without loss of generality, $K_{g \\times s}$ is a block diagonal genotype similarity matrix,\nWe use two random error terms, $\\mathbf{e_f}$ and $\\mathbf{e_m}$ for females and males respectively,\nto account for the difference in error variances between the sexes.\n\nBecause this comprehensive model involves five variance components, application of this model to GWAS can be computationally challenging. \nFor this reason, we applied the following approximation and\nsplit the model into two sex-specific models:\n\\begin{align}\n {\\bf y_f} &= \\mu_f {\\bf 1} + \\beta_f {\\bf x_f} + \\bm{\\upsilon}_f + {\\bm \\varepsilon}_f \\label{eq:approxf}\\\\\n {\\bf y_m} &= \\mu_m {\\bf 1} + \\beta_m {\\bf x_m} + \\bm{\\upsilon}_m + {\\bm \\varepsilon}_m \\nonumber\n \\end{align}\nwhere ${\\bf y_f}$ is the phenotype vector of female individuals, $\\beta_f$ is the effect size in females, ${\\bf x_f}$ is the \ngenotype vector of female individuals, $\\bm{\\upsilon}_f \\sim N(0, \\rho^2_{g,f} \\bf{K_f})$ is the polygenic effect within females,\nand $\\bm{\\epsilon}_f \\sim N(0, \\rho_{e,f}^2 \\bf{I_f})$ is the female-specific error term. \n$\\bf{K_f}$ is the genotype similarity matrix between female individuals and\n$\\bf{I_f}$ is an identity matrix defined for the female sample size.\nWe can similarly define terms for males.\nThis approximated model has the following relationships to the previous full model:\n\\begin{align*}\n\\mu_f &= \\mu + \\mu_s \\\\\n \\mu_m &= \\mu \\\\\n \\beta_f &= \\beta + \\beta_{g\\times s}\\\\\n \\beta_m &= \\beta\\\\\n \\rho^2_{g,f} &= \\sigma^2_g + \\sigma^2_{g,f}\\\\\n \\rho^2_{g,m} &= \\sigma^2_g + \\sigma^2_{g,m}\\\\\n \\rho^2_{e,f} &= \\sigma^2_{e,f}\\\\\n \\rho^2_{e,m} &= \\sigma^2_{e,m}\\\\\n %\\sigma^2_{f} &= \\sigma^2_s + \\sigma^2_e \\\\\n %\\sigma^2_{m} &= \\sigma^2_e\\\\\n\\end{align*}\nThese equalities hold because the approximated model can be considered as the same comprehensive model where\nwe only look at a subset of samples (one sex).\nIntuitively, since we separate each sex into two models, \nthe intercept is no more tied to be the same between the sexes.\nThis freedom accounts for the phenotypic mean difference between the sexes. %sex covariate and heterogeneity of effect sizes.\nThis is the same for the genetic effect size ($\\beta$) and the error variance.\nThe polygenic effect term for each sex simultaneously accounts for both the polygenic and the sex-interacting polygenic effects in the original model\nbecause, for each sex, the covariance matrix of the two terms become identical.\n%By separating the model, the error variance is also not required to be the same, which accounts for\n%variance differences between the sexes.\n\nThe benefit of this approximated model is that each model contains only two variance components.\nCurrently available methods are well optimized for this two-variance-component model. \n\\citep{Zhou:NatGenet:2012,Kang2010,Kang:2008bx}\n%recent methods are efficient for genome-wide analyses even if we exclude the tested SNP in the calculation of relationship matrix the relationship matrix differs by SNP \n%very efficient for models with two variance components, and can be used for genome-wide scale.\nThe difference in this approximated model compared with the original model\nis that, in the original model, $\\sigma^2_g$, $\\sigma^2_{g,f}$ and $\\sigma^2_{g,m}$ are estimated allowing the distinction between the three.\n%such that they are the same\nWhereas, in this approximated model, the estimates $\\rho^2_{g,f}$ and $\\rho^2_{g,m}$ do not allow distinction between the whole-sample polygenic component\nand the sex-interacting polygenic component. \nHowever, this distinction is not crucial in association mapping where we want to control for both effects. \nAnother difference is that the cross-sex elements in $\\bf{K}$ are not used, which would give more accurate estimates of variance components.\nHowever, if the sample size in each sex is sufficiently large, the variance component estimates can be accurate and\nthe approximated model will be almost identical to the original model.\nWe also note that the cryptic relatedness between the sexes are not accounted in this approximated model.\n\n\\subsubsection*{Sex-specific test}\nAfter obtaining the effect size estimate and its standard error from each sex-specific model \n(for example, $\\hat{\\beta_f}$ and se($\\hat{\\beta_f}$) for females), %, $\\hat{\\beta_f}$, and se($\\hat{\\beta_f})$,\nwe first apply the sex-specific test (SST). \nThe null hypothesis of sex-specific test is that the variant has no effect in both sexes. Thus, the null hypothesis is $H_0: \\beta_m=0$ and $\\beta_f=0$. \n%We explicitly include this testing in our framework so that we can account for multiple testing.\nWe perform SST by obtaining a p-value from female-specific test (SST(F)) and a p-value from male-specific test (SST(M)).\nSince we perform two independent tests in SST, we correct for multiple testing. \n%\n%We call female-specific test SST(F) and male-specific test SST(M).\n%Since in a typical situation we do not know which sex has effect, we will perform both SST(F) and SST(M).\n%We will call a variant significant if either SST(F) or SST(M) is significant. \n%We call this testing that performs both SST(F) and SST(M), SST.\n%Since we perform two independent tests, we correct for multiple testing within SST.\n%\nThe reason that we apply SST first is \nnot only because SST is optimal for detecting sex-specific effects, but also because in practice, \ninvestigators typically look at each sex separately in their data.\nBy explicitly including this test in our framework, we can account for the additional multiple testing burden induced by this test. \n\n\\subsubsection*{Whole sample test using meta-analysis}\n\\label{meta_sex}\nThen, we perform whole sample test by combining information from both sexes. \nOur goal is to find a locus that has either common effect (effect that exists for both sexes with the same effect size), or \ninteraction effect (effect that exists for both sexes with differing effect sizes). \nIn the comprehensive model, our null hypothesis is $H_0:\\beta=0\\mbox{ and }\\beta_{g\\times s}=0$.\nIn our approximated model, this null hypothesis translates to an equivalent null hypothesis, $H_0:\\beta_m=0\\mbox{ and }\\beta_f=0$.\nWhat would be an optimal approach for simultaneously testing $\\beta_m$ and $\\beta_f$ will depend on the alternative models.\nIf $\\beta_m$ and $\\beta_f$ are expected to be completely different\n(e.g. opposite directions of effects),\nsimply adding chi-square statistics as is done in GWAMA method \\citep{Magi:GenetEpidemiol:2010} would be powerful. \nHowever, in practice, it is rare to observe opposite effect directions of one genetic variant for the two sexes.\nMore common situations would be that the effects are in the same direction but in different magnitudes.\nNevertheless, if the magnitudes of effects are extremely different such that one effect is relatively very close to zero, then the variant is likely to be already found by SST.\nThus, we can specifically target effect size pairs whose directions are the same and whose magnitudes can be different, but none is very close to zero. \n%that can be different in magnitude, but in the same direction.\nTo this end, we chose to use the random effects (RE) model meta-analysis method which assumes that the male and female effect sizes are random variables drawn from the same underlying distribution.\n%, thereby modeling differences between them,\n%and assumes that the effect sizes are sampled from the same distribution, thereby modeling their similarities.\n\nSpecifically, in an RE model, we assume that the effect size of male and female studies, $\\beta_i$ \n($i = m, f$),\nfollow a distribution with the grand mean $\\bar{\\beta}$ and the variance $\\tau^2$ \\citep{Han:AmJHumGenet:2011,DerSimonian:ControlClinTrials:1986}:\n\\[\\beta_i \\sim N(\\bar{\\beta}, \\tau^2).\\]\n%We recently developed a powerful random effects model, which\n%address the problem of conservative nature of traditional random effects model by \n%assuming no heterogeneity under the null hypothesis \\citep{Han:AmJHumGenet:2011}.\n% removing the assumption of randomness in the null hypothesis of the random effect model. \n%This modification is natural because the effect size should be fixed to be zero under\n%the null hypothesis. \nThe recently proposed RE model by Han and Eskin \\citep{Han:AmJHumGenet:2011} tests\nthe null hypothesis $H_0: \\bar{\\beta} = 0 \\mbox{ and } \\tau^2=0$ versus the \nalternative hypothesis $H_1: \\bar{\\beta} \\ne 0 \\mbox { or } \\tau^2 \\ne 0$.\nNote that when we apply RE to our framework, this null hypothesis exactly corresponds to $H_0:\\beta_m=0\\mbox{ and }\\beta_f=0$.\nLet $\\beta_i$ and $V_i$ be the effect size estimate and its variance respectively.\nAs in the traditional random effect model \\citep{DerSimonian:ControlClinTrials:1986},\nHan-Eskin model uses the likelihood ratio framework considering each statistic ($\\beta_i$ and $V_i$ pair)\nas a single observation. \n%To avoid the problem of the overly conservative nature of the traditional RE model, \nThe difference from the traditional RE model is that\nthe Han-Eskin model assumes no heterogeneity under the null hypothesis \\citep{Han:AmJHumGenet:2011}. \nThis assumption is valid if the causes of heterogeneity do not exist under the null hypothesis,\nwhich is likely to be the case for GWAS.\n%which is natural because the effect size should be fixed to zero under\n%the null hypothesis in GWAS.\n% is used as follows.\n%Since %heterogeneity exists only under the alternative hypothesis,\n%we assume no heterogeneity under the null,\n%$\\mu = 0$ and $\\tau^2 = 0$ under the null hypothesis.\n%the alternative hypothesis is $\\mu \\ne 0$ or $\\tau^2 > 0$.\nThe likelihoods are then:\n%do not have the heterogeneity under the null,\n\\begin{align*}\n L_0 &= \\prod_{i = m, f} \\frac{1}{\\sqrt{2\\pi V_i}} \\exp \\left(\n-\\frac{\\beta_i^2}{2V_i}\\right)\\\\\nL_1 &= \\prod_{i = m, f} \\frac{1}{\\sqrt{2\\pi (V_i+{\\tau}^2)}} \\exp \\left(\n-\\frac{(\\beta_i-\\bar{\\beta})^2}{2(V_i+{\\tau}^2)}\\right).\n\\end{align*} \n% In our framework,\n% we maximize $L_1$ with respect to both parameters, $\\mu$ and $\\tau$.\nThe maximum likelihood estimates $\\widehat{\\bar{\\beta}}$ and $\\hat{\\tau}^2$ can be \nfound by an iterative procedure suggested by \nHardy and Thompson \\citep{Hardy96}.\n%Specifically, given the current estimate $\\hat{\\mu}_{(n)}$ and $\\hat{\\tau}^2_{(n)}$,\n%the next estimates are obtained by the formula\n%\\begin{align*}\n%\\hat{\\mu}_{(n+1)} &= \\frac{\\sum \\frac{X_i}{V_i+\\hat{\\tau}^2_{(n)}}}{\\sum \\frac{1}{V_i+\\hat{\\tau}^2_{(n)}}}\\\\\n%\\hat{\\tau}^2_{(n+1)} &= \\frac{\\sum \\frac{(X_i-\\hat{\\mu}_{(n+1)})^2 - V_i}{(V_i+\\hat{\\tau}^2_{(n)})^2}}{\\sum \\frac{1}{(V_i+\\hat{\\tau}^2_{(n)})^2}}\\;.\n%\\end{align*}\n%Once we find the maximum likelihood estimates $\\hat{\\mu}$ and $\\hat{\\tau}^2$,\nThen the likelihood ratio test statistic can be built\n\\begin{equation}\n\\label{eq:newRE}\nS_{\\rm meta} = -2\\log(\\lambda) \n= \\sum \\log \\left( \\frac{V_i}{V_i+\\hat{\\tau}^2}\\right)\n+ \\sum \\frac{\\beta_i^2}{V_i} - \\sum \\frac{(\\beta_i-\\widehat{\\bar{\\beta}})^2}{V_i+\\hat{\\tau}^2},\n\\end{equation}\nwhich asymptotically follows a half and half mixture of $\\chi^2_{(1)}$ and $\\chi^2_{(2)}$.\nA p-value after small sample adjustment can be efficiently calculated using pre-computed tabulated values \\citep{Han:AmJHumGenet:2011}.\n\n\\subsubsection*{Smart thresholding}\n\nIn our MetaSex framework, we perform three tests: SST, which consists of SST(F) and SST(M), and whole sample test using RE.\nTo account for multiple testing, we can use the Bonferroni correction, but that can be overly conservative\nbecause of the dependency between the test statistics of SST and RE.\nInstead, we can perform null simulations to empirically determine the significance threshold.\nMoreover, we can use a strategy similar to one published previously \\citep{Eskin:GenomeRes:2008}, \n%\\hl{please citep Zar's genome research paper.}\n%\\hl{Is this the one Eleazar Eskin. ?Increasing Power in Association Studies by using \\\\ Linkage Disequilibrium Structure \n%and Molecular Function as Prior Information.? Genome Research.}\nwhich uses different levels of significance thresholds for multiple tests to achieve higher power while\n%which adjusts the significance threshold of multiple tests to achieve higher power while \ncontrolling the overall \nfalse positive rate (family-wise error rate) to a fixed level.\n\nTo find an optimal threshold pair for RE and SST while controlling the false positive rate at\n$5.0 \\times 10^{-8}$, \nwe generated 10 billion null statistic pairs for the male studies and the female studies. \nAny pair of thresholds for RE and SST that rejected 500 null statistics \n%Then we find 500 smallest p-values for RE and SST method respectively for the null statistics.\n%With these 1000 smallest p-values, we can make 500 pairs which \nwould control the false positive rate \nat $5 \\times 10^{-8}$. \n%For example, smallest p-value in RE and largest p-value in SST among\n%500 p-values can be the significant threshold pair which can correctly control the false positive rate. \n%After finding 500 pairs correctly controling false positive rate, we search for the optimal threshold \n%pair for the statistical power. \nThen, we adjusted the thresholds for RE and SST while keeping the total number of rejections to 500.\n%There are a total of 500 such threshold pairs in our simulation. \nFor example, a threshold pair can have one false positive for RE and 499 false positives \nfor SST. Next, one can have two false positives for RE and 498 false positives for SST. \nThere were 500 such threshold pairs that control the false positive rate of $5 \\times 10^{-8}$. \nAmong all 500 pairs of thresholds that gave the same false positive rate, we \nchose the threshold pair that gave us the maximum power.\nTo calculate power, we needed a model assumption for the alternative hypothesis. \nWe assumed the model in Figure \\ref{power_comp11}, which uniformly sampled the female effect size\nand male effect size from a range between 0 and 1.\nAlthough this alternative model was just one possible model, we expect that it will cover a wide range\nof possible situations.\nUnder this uniform prior assumption, we calculated the power of each pair.\nWe found that using unequal thresholds, \n$2.41 \\times 10^{-8}$ for RE and $1.36 \\times 10^{-8}$ for each of SST(F) and SST(M), gave us the best power\nwhile still controlling the false positive rate.\nNote that although our pair of thresholds was optimized for a specific alternative model,\neven if the true alternative model would be different from the assumed model, \nour false positive rate can be still controlled; only the power will be affected.\nThe users using our method can just use these pre-computed thresholds.\n\n\\begin{comment}\n\\subsubsection*{Controlling for the population structure within each sex}\n%\\hl{Can you clean up this section a bit, to fit to the flow?}\n\nGenetic similarities between individuals, called the population structure or cryptic relatedness,\nare well-known for \nboth inhibiting the ability to find true associations and causing the \nappearance of a large number of false or spurious associations \\citep{Devlin01,voight2005confounding}.\nOne popular method to correct this problem uses mixed models\\citep{Lange02,Yu06,Kang08,Kang2010, Price06,Zhou:NatGenet:2012,Furlotte:Genetics:2012,listgarten2013powerful,Lippert:NatureMethods:2011}.\nIn the MetaSex framework, we separate each sex into two groups and correct\nfor the population structure within each sex with the previously proposed linear mixed model approach\\citep{Kang2010} in the following way:\n%\n\\begin{equation}\n {\\bf y_i} = \\mu_i {\\bf 1} + \\beta_i {\\bf x_i} + {\\bf u_i} + {\\bf e} \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ (i =\\mbox{male , female})\n\\label{mix1}\n\\end{equation}\nwhere ${\\bf y_i}$ (i = male or female) denotes the $N_i \\times 1$ phenotype vector ($N_i$ is the \nnumber of individuals for male and female), $\\mu$ is the \nphenotypic mean, $\\beta_i$ is the effect size of the testing SNP for male (i = male) and female (i = female),\n${\\bf x_i}$ is the $N_i \\times 1$ SNP vector, ${\\bf u_i}$ is the random variable explaining the population \nstructure effect assumed to follow a normal distribution with ${\\bf u_i } \\sim N(0,\\sigma_g^2 K_i)$, \nwhere $K_i$ is the $N_i \\times N_i$ kinship coefficient matrix for study $i$, and ${\\bf e}$ is \na residual error term following a normal distribution (${\\bf e} \\sim N(0, \\sigma_e^2 I)$).\nThen, for both males and females, we will have the following model separately: \n\\begin{equation}\n{\\bf y} \\sim N(\\mu {\\bf 1} + \\beta {\\bf x}, \\Sigma) \\ \\ \\ \\ \\Sigma_i = \\sigma_g^2 K + \\sigma_e^2 I\n\\label{mix2}\n\\end{equation}\n%\nThe maximum likelihood estimates of $\\sigma_g^2$ and $\\sigma_e^2$ can be obtained by numerical methods, \nas previously proposed \\citep{Kang08,Kang2010,Lippert:NatureMethods:2011}.\nAfter obtaining maximum likelihood estimates of $\\sigma_g^2$ and $\\sigma_e^2$,\nthe computing effect size estimates of the male and female studies ($\\hat{\\beta_m}\\mbox{ and } \\hat{\\beta_f}$) and \ntheir standard errors ($SE(\\hat{\\beta_m})\\mbox{ and }SE(\\hat{\\beta_f})$) can be \neasily computed \\citep{Kang08,Kang2010,Lippert:NatureMethods:2011}, which \nwill be used as inputs for the MetaSex framework.\n\n\\end{comment}\n\n\n% \n%\n%These mixed model approaches introduce a random variable into the traditional linear model. \n%\n% \\begin{equation}\n% {Y}_i = \\mu + \\beta_i X_{r} + u_i + \\epsilon \\label{mixed00} \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ (i = m, f)\n% \\end{equation}\n% \n% In the model in equation (\\ref{mixed00}), the random variable $u_i$ represents the vector of genetic contributions to the phenotype for individuals in study $i$. \n% This random variable is assumed to follow a normal distribution with $u_i \\sim N(0,\\sigma_g^2 K_i)$, where $K_i$ is the $n_i \\times n_i$ kinship coefficient matrix for study $i$. \n% With this assumption, the total variance of $Y_i$ is given by $\\Sigma_i = \\sigma_g^2 K_i + \\sigma_e^2 I$. \n%A z-score statistic is derived for the test $\\beta_i=0$ by noting the distribution of the estimate of $\\hat{\\beta}_{i}$. In order to avoid complicated notation, we introduce a more basic matrix form of the model in equation (\\ref{mixed00}), shown in equation (\\ref{mixed01}). \n% \n% \\begin{equation}\n% Y_i = {S}_{i}\\Gamma + {u}_i + \\epsilon \\label{mixed01}\n% \\end{equation}\n% \n% In equation (\\ref{mixed01}), ${S}_{i}$ is a $n_i \\times 2$ matrix encoding the global mean and SNP vectors and $\\Gamma$ is a $2 \\times 1$ coefficient vector. \n%%We note that this form also easily extends to models with multiple covariates.\n%%\n%The maximum likelihood estimate for $\\Gamma$ in study $i$ is given by $\\hat{\\Gamma}_{i} = (\\mathbf{S}_{i}^\\prime \\mathbf{\\Sigma}_i^{-1} {S}_{i})^{-1} {S}_{i}^\\prime {\\Sigma}_i^{-1} {Y}_i$ which follows a normal distribution with a mean equal to the true $\\Gamma$ and variance $({S}_{i}^\\prime {\\Sigma}_i^{-1} {S}_{i})^{-1}$. The estimates of the effect size $\\beta_i$ and standard error of the $\\beta_i$ ($\\sigma_i$) are then given in equation (\\ref{x01}) and\n% equation (\\ref{s01}), \n% where ${R}=[0 \\quad 1]$ is a vector used to select the appropriate entry in the vector $\\hat{\\Gamma}_i$.\n% \n% \\begin{eqnarray}\n% \\beta_{i} = & {R} ({S}_{i}^\\prime {\\Sigma}_i^{-1} {S}_{i})^{-1} {S}_{i}^\\prime {\\Sigma}_i^{-1} {Y}_i \\label{x01} \\\\\n% \\sigma_i = & [{R}({S}_{i}^\\prime {\\Sigma}_i^{-1} {S}_{i})^{-1}{R}^\\prime]^{1/2} \\label{s01}\n% \\end{eqnarray} \n%\n%%The above mixed model based approach can be utilized in conjunction with any of above \n%%sex-differentiated methods such as fixed effects meta-analysis, \n%%the SST approach, the GWAMA approach, and the RE approach to control the population structure \n%%in each male and female studies. \n%\n%%The above mixed model based approach is well-known for correcting population structure. \n%%However correcting a population structure problem with mixed model\n%%will be harder and more likely not complete as we combine \n%%more large number of studies with heterogeneous populations. \n%%Thus it is more natural and easy to control population structure by correcting it to each cohort. \n%\n\n\n\\subsection{Existing approaches}\n\n\\subsubsection*{CV}\n\nThe standard approach for dealing with sex is to use sex as a covariate.\nWe refer to this model as CV in short. \nThe CV model is: \n\\[ {\\bf y} = \\mu {\\bf 1} + \\mu_s {\\bf h} + \\beta {\\bf x} + {\\bf u} + {\\bf e} \\]\nwhich is equivalent to the traditional model in equation (\\ref{eq:standard})\nwith the only difference being the inclusion of the covariate denoting sex ($\\mu_s$).\nCV accounts for the phenotypic mean differences between the sexes.\nHowever, CV does not account for the followings:\npossible sex differences in the effect size ($\\beta$), \npolygenic background effect ($\\mathbf{u}$),\nand the error variance ($\\var{\\mathbf{e}}$).\n\n\\subsubsection*{GWAMA}\n\nGWAMA (Genome-Wide Association Meta-Analysis) is another meta-analytic approach proposed by Magi \\textit{et al.}\n\\citep{Magi:GenetEpidemiol:2010}.\n%we first estimate the \n%genetic effect size ($\\beta_m, \\beta_f$) and its standard error ($\\sigma_m^2, \\sigma_f^2$) in \n%male and female study separately in the linear model \n%as in equation (\\ref{eq:lin}).\nIn GWAMA, as in MetaSex, each sex is analyzed separately. \nThen, the $\\chi^2$ statistics of males and females are calculated\nby squaring the corresponding z-scores, that is, \n\\[\\chi^2_m = z_m^2 = ( \\frac{\\beta_m}{\\sqrt{V_m}} )^2 \\mbox{ and } \\chi^2_f = z_f^2 = ( \\frac{\\beta_f}{\\sqrt{V_f}} )^2\\]\nThe GWAMA statistic can be obtained by summing male $\\chi^2$ and female $\\chi^2$\n\\[S_{GWAMA} = \\chi^2_m + \\chi^2_f\\]\nThe p-value can be obtained using\n$\\chi^2$ distribution with two degrees of freedom. \n\nBecause GWAMA is a meta-analytic approach that analyzes each sex separately and combines them,\n%combines summary statistics from each sex, \nit shares some of the advantages with our MetaSex approach.\nThat is, GWAMA framework can also account for \nbetween-sex differences\nin intercept and error variances.\n%The limitation of GWAMA is that it simply adds chi-square statistics, thereby ignoring sample size information.\n%In the Supplementary Materials, we extend the GWAMA to Weighted GWAMA, which accounts \n%for sample size difference between sexes.\n\n\n%\n%\\subsection{Traditional meta analysis approaches for discovering sex-interacting effects}\n%\\label{trad_methods}\n%%\\subsubsection{Fixed effects model meta analysis for sex-differentiated analysis}\n%%\\label{fixed}\n%\n%In standard fixed effect model meta analysis, we first estimate the \n%genetic effect size of male and female studies separately in the linear model. \n%%\n%%\n%\\begin{align}\n%\\label{eq:lin}\n% y_f &= \\mu_f + \\beta_f X_f + e_f \\\\\n% \\label{eq:lin2}\n% y_m &= \\mu_m + \\beta_m X_m + e_m\n%\\end{align}\n%%\n%where $y_f$ and $y_m$ is the phenotype vector for females and males, \n%$\\mu_f$ and $\\mu_m$ is the phenotypic mean for males and females respectively,\n%$\\beta_f$, $\\beta_m$ denotes the genetic effect size for females and males, $X_f$ and \n%$X_m$ are SNP vectors and $e_f$ and $e_m$ are the residual errors. \n%Given the estimates of genetic effect size ($\\beta_m$, $\\beta_f$) and their variance ($\\sigma_m^2$, $\\sigma_f^2$),\n%we can compute z-scores for male and female studies separately ($Z_m = \\frac{\\beta_m}{\\sigma_m}$, $Z_f = \\frac{\\beta_f}{\\sigma_f}$).\n%%\n%%\n%%In the fixed effects model meta-analysis, \n%%we assume that the underlying effect sizes are the same in male and female studies as $\\beta$ \n%%($\\beta = \\beta_m = \\beta_f$).\n%%The best estimate of $\\beta$ is the inverse-variance weighted effect size \\citep{deBakker2008},\n%%\\begin{equation}\n%%\\label{eq:fixed}\n%%\\bar{\\beta}=\\frac{w_m \\beta_m + w_f \\beta_f}{ w_m + w_f}\\;, \\ \\ \\ \\ \n%%SE(\\bar{\\beta}) = \\frac{1}{\\sqrt{w_m + w_f}} \\\\\n%%\\end{equation}\n%%\\begin{equation}\n%%\\label{eq:fixedz}\n%%Z_{FE} = \\frac{\\bar{\\beta}}{SE(\\bar{\\beta})} = \\frac{w_m \\beta_m + w_f \\beta_f}{\\sqrt{w_m + w_f}} = \\frac{\\sqrt{w_m} Z_m + \\sqrt{w_f} Z_f}{\\sqrt{w_m + w_f}}\n%%\\end{equation}\n%%where $w_m= 1/\\sigma_m^2$ and $w_f= 1/\\sigma_f^2$ so-called inverse variance.\n%%Then we can test the null hypothesis $\\beta = 0$ versus the alternative hypothesis $\\beta \\ne 0$.\n%\n%\n%\n%\n%%\\subsubsection{Sex-specific test approach for discovering extreme sex-interacting loci}\n%%\\label{max}\n%The sex-interacting test (SST) approach can be utilized to discover extreme sex-interacting loci.\n%In the SST approach, we first estimate the \n%genetic effect size ($\\beta_m, \\beta_f$) and its standard error ($\\sigma_m, \\sigma_f$) in \n%male and female studies separately in the linear model \n%as in equation (\\ref{eq:lin}).\n%Then we compute the z-score statistic of male and female studies separately\n%by $z_m = \\frac{\\beta_m}{\\sigma_m}$ and $z_f = \\frac{\\beta_f}{\\sigma_f}$.\n%%Then the SST statistic is chosen by maximum between absolute value of z-scores ($S_{max}$ = max($|z_m|, |z_f|$)). \n%%$\\textit{p-value}$ can be obtained with $S_{max}$ under the null hypothesis of standard normal distribution. \n%\n%\n%\n%\n%%\\subsubsection{GWAMA approach for sex-differentiated analysis}\n%%\\label{gwama}\n%In the GWAMA approach \\citep{Magi:GenetEpidemiol:2010}, \n%%we first estimate the \n%%genetic effect size ($\\beta_m, \\beta_f$) and its standard error ($\\sigma_m^2, \\sigma_f^2$) in \n%%male and female study separately in the linear model \n%%as in equation (\\ref{eq:lin}).\n%Then we compute the $\\chi^2$ statistic of male and female studies separately\n%by squaring z-scores, which we obtain in equation (\\ref{eq:lin}) (\n%$\\chi^2_m = z_m^2 = ( \\frac{\\beta_m}{\\sigma_m} )^2 $ and $\\chi^2_f = z_f^2 = ( \\frac{\\beta_f}{\\sigma_f} )^2$ ).\n%GWAMA statistic can be obtained by summing male $\\chi^2$ and female $\\chi^2$\n%($S_{GWAMA} = \\chi^2_m + \\chi^2_f$). \n%$\\textit{p-value}$ can be obtained with $S_{GWAMA}$ under the null hypothesis of \n%central $\\chi^2$ distribution with 2 degrees of freedom. \n%\n%\n%\n%\n\n%\\subsection{Combined approach with sex as a covariate}\n\n\n%\\subsection{Empirical power estimation for RE}\n%\n%Unlike the %FE, \n%GWAMA, and SST methods, the analytical distribution of the RE\n%statistic is unknown.\n%Thus, to estimate the statistical power of the RE approach, we employ a simulation approach.\n\n\\subsection{Power calculation}\n\\label{anal_power}\n\nTo evaluate the power of methods, we performed simulations as follows.\nWe assumed a specific effect size. %assumed that we know the standard error. \nThen based on an assumed standard error, we sampled an observed estimate of effect size.\nWe performed this sampling for males and females separatly by $N$ times.\nGiven $N$ male estimates and $N$ female estimates,\n%Given the true effect sizes and standard errors of male and female groups, an $N$ number of \n%male and female effect sizes is sampled.\n% and standard errors. \nwe can apply any of the tested methods.\n%For SST, we compute $N$ p-values for each sex. \n%Or, for methods combining both sexes, we compute $N$ p-values using observed effect sizes of both sexes. \n%We use our method MetaSex to combine summary statistics from both sexes, which gives us $N$ p-values.\n%The $N$ number of p-values are then computed.\nThe statistical power was computed as the proportion of p-values that were\nmore significant than a significance threshold. %, $5.0 \\times 10^{-8}$.\nAs described, we found the correct significance threshold by performing null simulations under the null hypothesis of no effects;\nEmpirical null simulation was necessary because some methods involved multiple testing.\nFor example, SST consists of two tests (SST(F) and SST(M)), and MetaSex (RE+SST) consists of three tests (SST(F), SST(M), and RE).\nAs with MetaSex, each of GWAMA+SST and CV+SST consists of three tests.\nWe used $N$ of at least 10,000 in all of our simulations.\n\n\n%Suppose we have a male and female association study results to combine to compute \n%the p-value for each SNP. For a given SNP, let $\\beta_m$ and $\\beta_f$ be the true effect sizes\n%from male and female study respectively and $\\sigma_m$ and $\\sigma_f$ be the true standard\n%error for the effect sizes underlying alternative distribution. \n%Then the true Z-scores given effect size and standard error for these study can be easily computed \n%: $z_m = \\displaystyle\\frac{\\beta_m}{\\sigma_m}$, \n%$z_f = \\displaystyle\\frac{\\beta_f}{\\sigma_f}$. \n%To obtain the Z-score for fixed effect meta analysis (FE), we get the weighted sum of Z-scores.\n%$S_{FE} = Z_{FE} = \\displaystyle\\frac{w_f z_f + w_m z_m}{\\sqrt{w_f^2 + w_m^2 }}$. \n%The optimal weights for $S_{FE}$ is a inverse-variance weight \n%($w_f = \\displaystyle\\frac{1}{\\sigma_f^2}$ and $w_m = \\displaystyle\\frac{1}{\\sigma_m^2}$).\n%Let $S_{meta-sex}$ be the statistic obtained by Meta-Sex method explained in Section \\ref{meta_sex}.\n%Let $S_{gwama}$ be the statistic from GWAMA approach. \n%This statistic can be computed by summing two $\\chi^2$ statistic from $z_f$ and $z_m$ \n%and it follows $\\chi^2$ distribution with two degree of freedom under the null\n%hypothesis ( \n%$S_{gwama} = z_f^2 + z_m^2$).\n%Let $S_{Max}$ be the statistic obtained by Max approach.\n%The Max approach is simply choosing larger statistic between $z_m$ and $z_f$.\n%Thus $S_{Max} = max(z_m, z_f)$.\n\nFor some methods, specifically SST and GWAMA, \nit was also possible to calculate the exact power analytically. \n%When we calculated the power of some methods, in particular\n%SST and GWAMA, it was also possible to obtain the exact power analytically. \nLet $\\alpha$ be the desired significance threshold level.\nLet $\\Phi(x; \\mu, \\sigma)$ be the cumulative density function (CDF) of \na normal distribution evaluated at $x$ \ngiven the mean $\\mu$ and standard deviation $\\sigma$ of the distribution.\nBecause SST consists of two independent tests (SST(F) and SST(M)),\nwe should use the significance threshold $\\alpha'$ that satisfies $\\alpha=1-(1-\\alpha')^2$ for each of SST(F) and SST(M).\nAssuming a two-sided test, the z-score threshold corresponding to $\\alpha'$ can be obtained by \nthe inverse CDF of $\\frac{\\alpha'}{2}$\n($T_{\\alpha'}$ = $\\Phi^{-1}(\\frac{\\alpha'}{2}; 0, 1)$).\nGiven the true effect sizes ($\\beta_m, \\beta_f$) and the standard errors of the estimates ($\\sqrt{V_m}, \\sqrt{V_f}$) that we assumed\nfor males and females, let $\\bar{z}_m = \\frac{\\beta_m}{\\sqrt{V_m}}$ and $\\bar{z}_f = \\frac{\\beta_f}{\\sqrt{V_f}}$ \nbe the expected z-scores of males and females. % studies for the testing SNP.\nThen, the statistical power of the SST approach is \n%the probability that the hypothesis testings for\n%both male and female studies are not rejected, given $z_m$ and $z_f$, $T_{\\alpha}$.\n%This quantity can be analytically computed by the following equation: \n\\begin{align*}\nPower_{SST} = 1 - \\bigg[ \\Big(1 - \\Phi( T_{\\alpha'} ; \\bar{z}_m, 1) - (1 - \\Phi(-T_{\\alpha'}; \\bar{z}_m, 1 ) ) \\Big) \\\\\n \\times \\\\\n \\Big(1 - \\Phi( T_{\\alpha'}; \\bar{z}_f, 1) - (1 - \\Phi(-T_{\\alpha'}; \\bar{z}_f, 1 ) ) \\Big) \\bigg]\n\\end{align*}\n\nFor GWAMA, \nwe can first define $F_{\\chi^2}(x; m, k)$ as the CDF of a $\\chi^2$ distribution evaluated at $x$ given the non-centrality parameter $m$\nand $k$ degrees of freedom. \nBecause the GWAMA statistic follows the central $\\chi^2$ distribution with two degrees of\nfreedom under the null hypothesis, \ngiven the desired significance threshold $\\alpha$, \n%given the p-value threshold $\\alpha$ for controlling the false positive rate,\nthe threshold of GWAMA statistic that corresponds to $\\alpha$ can be\nexpressed as $T_\\alpha = F_{\\chi^2}^{-1}(1-\\alpha; 0, 2)$.\nThe non-centrality parameter for the GWAMA statistic is\n$\\bar{z}_m^2 + \\bar{z}_f^2$.\n%\\ref{gwama}.\nThen the statistical power of the GWAMA approach can be computed analytically with the\nfollowing formula: \n\\begin{equation}\nPower_{GWAMA} = 1-F_{\\chi^2}(T_{\\alpha} ; \\bar{z}_m^2 + \\bar{z}_f^2, 2)\n\\label{power_gwama}\n\\end{equation}\nWe observed that, as expected, the analytically calculated power was nearly identical to the empirical estimate.\n\n\n%\n%For the analytical power computation of fixed effect meta analysis approach,\n%let $\\Phi(x; \\mu, \\sigma)$ be the CDF of normal distribution for statistic $x$ \n%given mean $\\mu$ and standard deviation $\\sigma$ of the distribution.\n%Then given the $\\textit{p-value}$ threshold $\\alpha$ for controlling false positive rate,\n%since GWAMA statistic follows central $\\chi^2$ distribution with 2 degree of\n%freedom under the null hypothesis, \n%the threshold statistic for GWAMA approach is $\\Phi^{-1}(\\alpha; 0, )$.\n%\n%\n%\n%\n%To compare the statistical power, we set the threshold $\\alpha$, which will control \n%the false positive rate for each method, when we reject the null hypothesis based\n%on the observed statistic and threshold statistic based on $\\alpha$ level.\n%Let $\\Phi(x; \\mu, \\sigma)$ be the PDF of normal distribution with mean $\\mu$ and\n%standard deviation $\\sigma$.\n%Then for FE method, the threshold statistic will be $\\Phi^{-1}(-\\frac{\\alpha}{2} ; 0, 1)$. \n%%Here $\\Phi^{-1}$ represents the inverse of PDF for normal distribution. \n%For GWAMA approach, let $F_{\\chi^2}(x; m, k)$ be the CDF of $\\chi^2$ distribution with\n%non-centrality parameter $m$ and $k$ degree of freedom. \n%The threshold statistic, which control the false positive rate\n%of $\\alpha$, will be $F_{\\chi^2}(1-\\alpha; 0, 2)$.\n%Similarly for Meta-Sex approach, let $F_{meta-sex}(x)$ be the CDF of\n%the distribution of the meta-sex statistic.\n%The threshold statistic, which control the false positive rate\n%of $\\alpha$, will be $F_{meta-sex}(1-\\alpha/2)$.\n%For Meta-Sex statistic, the distribution of the statistic, CDF and PDF are unknown, \n%we have to \n%use the statistics in the precomputed-table.\n%\n%\n%\n%Second statistical power of the GWAMA method under the null of model of\n%normal distribution with the non-centrality parameter 0 and degree of freedom\n%2 can be computed given\n%threshold statistic $F_{\\chi^2}(1-\\alpha; 0, 2)$ and non-centrality parameter \n%for the alternative distribution \n%$S_{gwama} = z_f^2 + z_m^2$\n%computed with given effect sizes and their corresponding standard errors. \n%\n%\n%\\begin{equation}\n%Power_{GWAMA} = F_{\\chi^2}( F_{\\chi^2}^{-1}(1-\\alpha; 0, 2) ; S_{gwama}, 2)\n%\\label{power_gwama}\n%\\end{equation}\n%In this equation (\\ref{power_gwama}), $S_{gwama}$ is the \n%non-centrality parameter for the alternative distribution. \n%\n%\n%Third, statistical power of Meta-Sex approach cannot be obtained, \n%since we do not know the distribution of the statistic. Thus for \n%this case, we ....\n%\n%Fourth, statistical power of the Max approach can be computed \n%by subtracting the probability that both $z_m$ and $z_f$ statistics are not rejected \n%given significant threshold $ \\Phi^{-1}(-\\frac{\\alpha}{2}, 0, 1)$\n%from 1. \n%\n%\\begin{align*}\n%Power_{Max} = 1 - \\bigg[ \\Big(1 - \\Phi( \\Phi^{-1}(\\frac{\\alpha}{2}, 0, 1) ; z_m, 1) - (1 - \\Phi(-\\Phi^{-1}(\\frac{\\alpha}{2}), z_m, 1 ) ) \\Big) \\\\\n% \\times \\\\\n% \\Big(1 - \\Phi( \\Phi^{-1}(\\frac{\\alpha}{2}, 0, 1) ; z_f, 1) - (1 - \\Phi(-\\Phi^{-1}(\\frac{\\alpha}{2}), z_f, 1 ) ) \\Big) \\bigg]\n%\\end{align*}\n%\n%\n%\\begin{equation}\n%\\end{equation}\n\n\n\n\n\n\n\n\\subsection{Levene's test}\n\nLevene's test determines if there is a significant difference among the variances of multiple groups \\citep{Brown:1974aa}.\n%male and female groups. The variance difference can be one of the factors affecting the statistical power of different association \n%methods.\n%\n%Levene's test tests the null hypothesis \n%that population variances of two different groups are equal (called homoscedasticity).\n%Under the null hypothesis, it assumes that the population variances are equal for the two groups (called homoscedasticity).\n%If the resulting p-value of Levene's test is less than the significance threshold, \n%we conclude that there is a significant difference between the variances in two different groups.\nThe statistic is\n%\n%\n\\begin{equation}\nW = \\displaystyle\\frac{(N-K)}{(k-1)} \\displaystyle\\frac{\\sum_{i=1}^k N_i (Z_{i.} - Z_{..})^2}{ \\sum_{i=1}^k \\sum_{j=1}^{N_i} (Z_{ij} - Z_{i.})^2 }\n\\end{equation}\n%\nwhere $k$ is the number of different groups to which the samples belong ($k=2$ for our between-sex test), $N$ is the total number of samples in all groups,\nand $N_i$ is the number of sample in the $i$th group. \nLet $Y_{ij}$ be the value of the measured variable for the $j$th sample from the $i$th group.\nWe define $Z_{ij} = |Y_{ij} - \\bar{Y_i} |$ ($\\bar{Y_i}$ is a mean of $i$th group), $Z_{..} = \\displaystyle\\frac{1}{N} \\sum_{i=1}^k \\sum_{j=1}^{N_i} Z_{ij}$,\n and $Z_{i.} = \\displaystyle\\frac{1}{N} \\sum_{j=1}^{N_i} Z_{ij} $. The resulting statistic $W$ follows an $F$ distribution with \n$k-1$ and $N-1$ degrees of freedom under the null hypothesis.\n%\n%We can also apply Levene's test after regressing out the SNP effects from phenotypes, to test differences in what we call residual phenotypic variance. \n%Here the residual phenotypic variance refers to the the variance of the phenotype after regressing out the \n%testing SNP effect from the phenotype and the polygenic background effects.\n\n\\subsection{NFBC data}\n\nIn our current study, we used the previously reported NFBC data \\citep{Sabatti:NatGenet:2009},\nwhich contained 5326 individuals (2546 males and 2780 females).\nTo investigate the sex difference \nin genetic architectures of human traits, \nwe examined 10 phenotypes:\nTriglycerides, High-density lipoprotein, Low-density lipoprotein, C-reactive protein,\nGlucose, Insulin, Body mass index, Systolic and Diastolic blood pressure, and Height. \nDetailed trait measurements and sample genotype collection have previously been described \\citep{Sabatti:NatGenet:2009}.\n\n\n\n\n\n\n%\\hl{Please describe what the data is like, e.g. sample size, who collected, etc.}\n\n% \\begin{comment}\n%\\subsection{Simulating background gene-by-sex (GxS) interactions}\n%%Simulating GxS interactions}\n%To examine how the background gene-by-sex (GxS) interactions affect the statistical power of the \n%association study when applying different methods, we perform a simulation experiments by\n%implanting the background GxS effect in the simulated phenotype.\n%To implant the background GxS effect in the simulated phenotype, \n%the phenotype $y$ is sampled from the following multivariate normal distribution.\n%\n%\\begin{equation}\n%y \\sim N(0, h_g K + h_s K_s + h_I I)\n%\\end{equation}\n%In the above equation, $K$ is a genetic relationship matrix between individuals to capture the population structure,\n%$K_s$ is sex-interacting genetic relationship matrix, which we will explain in detail below, $I$ is an identity matrix. \n%$h_g$ , $h_s$ and $h_I$ denotes the heritability of three covariance matrices to the total covariance matrix and \n%we set $h_g + h_s + h_I$ to be 1. \n%\n%In order to simulate GxS interactions, we sample from the appropriate multivariate normal distribution.\n%We are given the kinship matrices ${K}_m$ and ${K}_f$ for males and females respectively.\n%The sex-interacting kinship or GxS kinship matrix $\\mathbf{K}_s$ is then given by the following.\n%\n%\\begin{eqnarray}\n%\t{K}_s = & \\begin{bmatrix}\n%\t\t\t\t\t\t{K}_m & {0} \\\\\n%\t\t\t\t\t\t{0} & {K}_f\n%\t\t\t\t\t\\end{bmatrix}\n%\\end{eqnarray}\n%\n%%\\noindent Given a heritability $h$ and a GxS heritability $h_s$, a simulated phenotype is generated by sampling from a multivariate normal distribution with mean zero and variance $h{K}_a + h_s {K}_s + (1 - h - h_s) {I}$. \n%The intuition is that shared genetics between individuals accounts on average for some proportion of the overall phenotypic variance ($h$), while the proportion of variance accounted for by genetics for only males or only females is $h + h_s$.\n%That is, same-sex individuals have a similar genetic contribution to their overall trait value and this contribution is different when comparing across sexes.\n%%\n%%\n%\n%\n%\\pagebreak\n%\n%\n%\\beginsupplement\n%\\renewcommand{\\figurename}{Supplementary Figure}\n%\\renewcommand{\\tablename}{Supplementary Table}\n%\n%\\end{comment}\n\n\\bibliographystyle{genetics}\n\\bibliography{metaSex}\n\n\n\n\n\\clearpage\n%\\section{Supplementary Materials}\n\n\\section{Tables}\n\n\\begin{table}[h]\n%\\tiny\n\\centering\n\\resizebox{0.95\\textwidth}{!}{\n\\begin{tabular}{ccccc}\n\\hline\nPhenotype & Var(female) & Var(male) & Ratio (larger/smaller) & Levene's test p-value \\\\\n\\hline\nTriglyceride & 0.171 & 0.256 & 1.494 & 1.451e-21 \\\\\nHDL & 0.134 & 0.107 & 1.251 & 2.546e-10 \\\\\nLDL & 0.670 & 0.820 & 1.223 & 1.394e-05 \\\\\nBMI & 0.0309 & 0.0189 & 1.635 & 6.142e-19 \\\\\nC-reactive protein & 2.372 & 2.244 & 1.056 & 0.0877 \\\\\nGlucose & 0.00647 & 0.00678 & 1.048 & 0.174 \\\\\nInsulin & 0.1105 & 0.1172 & 1.061 & 0.1173 \\\\\nSystolic blood pressure & 156.77 & 171.357 & 1.092 & 0.0079 \\\\\nDiastolic blood pressure & 118.56 & 136.053 & 1.147 & 0.0012 \\\\\nHeight & 38.65 & 41.098 & 1.063 & 0.0154 \\\\\n\\hline\n\\end{tabular}\n}\n\\caption{Phenotypic variances of 10 NFBC phenotypes in the two sexes.\n}\n\\label{finland_levene1}\n\\end{table}\n\n\\begin{table}[p]\n \\centering\n \\resizebox{0.95\\textwidth}{!}{\n \\begin{tabular}{cccccc}\n \\hline\nPhenotype & $\\sigma_{g}^2(SE)$ & $\\sigma_{g,f}^2(SE)$ & $\\sigma_{g,m}^2(SE)$ & $\\sigma_{e,ss}^2(SE)$ & $\\sigma_{e}^2(SE)$ \\\\ \n \\hline\n\nTriglyceride & 0.0189(0.014) & 0.0323(0.0219) & 0.0031(0.0236) & 0.1134(0.0283) & 0.1205(0.0189) \\\\\nHDL & 0.0375(0.0072) & 0(0.011) & 0(0.0117) & 0.0017(0.0137) & 0.0694(0.0103) \\\\\nLDL & 0.2569(0.0511) & 0.0237(0.0786) & 0.042(0.082) & 0.1186(0.0983) & 0.3921(0.067) \\\\\nBMI & 0.0052(0.0014) & 0(0.0022) & 0(0.0023) & 0.0107(0.0028) & 0.0118(0.002) \\\\\nC-reactive protein & 0.222(0.1553) & 0.1346(0.243) & 0.0301(0.2641) & 0.0227(0.3108) & 1.9925(0.2321) \\\\\nGlucose & 0.0011(0.0005) & 0.0002(0.0008) & 0.0014(0.0008) & 0.0009(0.0009) & 0.0043(0.0007) \\\\\nInsulin & 0.0121(0.0082) & 0.0139(0.0132) & 0.004(0.0142) & 0.0163(0.0167) & 0.0847(0.0113) \\\\\nSystolic blood pressure & 37.1421(10.5002) & 4.5774(16.7722) & 1.9977(17.5993) & 18.3323(21.4657) & 114.189(14.6194) \\\\\nDiastolic blood pressure & 22.0399(8.3115) & 0.0001(12.9059) & 0.0001(13.6516) & 11.6098(16.1558) & 97.5402(11.0647) \\\\\nHeight & 24.0673(2.6501) & 1.2284(3.8886) & 1.1577(4.2184) & 3.2263(4.9783) & 12.6085(3.326) \\\\\n\n\\hline\n\\end{tabular}\n }\n\\caption {Variance components of 10 NFBC phenotypes in the full five-variance-component model.}\n\n\\label{finland_gcta1}\n\\end{table}\n\n\\begin{table}[p]\n \\centering\n \\resizebox{0.95\\textwidth}{!}{\n \\begin{tabular}{ccccc}\n \\hline\n & \\multicolumn{2}{c}{Female} & \\multicolumn{2}{c}{Male}\\\\ \n Phenotype & $\\sigma_{g,f}^2(SE)$ & $\\sigma_{e,f}^2(SE)$ & $\\sigma_{g,m}^2(SE)$ &\n $\\sigma_{e,m}^2(SE)$ \\\\ \n \\hline\n\nTriglyceride & 0.0073(0.0159) & 0.1642(0.0165) & 0.0565(0.0267) & 0.1997(0.0269) \\\\ \nHDL & 0.0315(0.0122) & 0.1032(0.0123) & 0.0546(0.0119) & 0.0531(0.0115) \\\\ \nLDL & 0.2459(0.0631) & 0.4228(0.062) & 0.4762(0.0885) & 0.3405(0.0846) \\\\ \nBMI & 0.0067(0.003) & 0.0243(0.0031) & 0.0037(0.002) & 0.0152(0.002) \\\\ \nC-reactive protein & 0.2633(0.2215) & 2.1086(0.227) & 0.1493(0.221) & 2.0952(0.2281) \\\\ \nGlucose & 0.0021(0.0007) & 0.0043(0.0007) & 0.002(0.0007) & 0.0048(0.0007) \\\\ \nInsulin & 0.0176(0.0114) & 0.0929(0.0116) & 0.0261(0.013) & 0.0911(0.0131) \\\\ \nSystolic blood pressure & 50.6003(14.4485) & 105.9015(14.3043) & 24.6972(14.9829) & 146.4733(15.3913) \\\\ \nDiastolic blood pressure & 36.1682(11.0625) & 82.26(10.9817) & 0.0001(12.4726) & 136.0544(13.0823) \\\\ \nHeight & 29.2825(3.5946) & 8.8902(3.3024) & 26.1134(4.3118) & 14.7954(4.0722) \\\\ \n\n\\hline\n\\end{tabular}\n }\n\\caption {Variance components of 10 NFBC phenotypes in the sex-specific models.}\n\n\\label{finland_gcta2}\n\\end{table}\n\n%\\begin{table}[h!]\n%%\\tiny\n%\\centering\n%\\resizebox{0.75\\textwidth}{!}{\n%\\begin{tabular}{cccccc}\n%\\hline\n%Phenotype & $\\sigma_g^2$(F) & $\\sigma_e^2$(F) & $\\sigma_g^2$(M) & $\\sigma_e^2$(M) \\\\\n%\\hline\n%Triglyceride & 0.007(0.016)&0.164(0.017) & 0.057(0.027)&0.200(0.027) \\\\\n%HDL & 0.032(0.012)&0.103(0.012) & 0.055(0.012)&0.053(0.012) \\\\\n%LDL & 0.246(0.063)& 0.423(0.062)& 0.476(0.089)&0.341(0.085)\\\\\n%BMI & 0.007(0.003) & 0.024(0.003) & 0.004(0.002)&0.015(0.002) \\\\\n%C-reactive protein & 0.263(0.221) & 2.109(0.227) & 0.149(0.221)&2.095(0.228)\\\\\n%Glucose & 0.002(0.001)&0.004(0.001)& 0.002(0.001)&0.005(0.001) \\\\\n%Insulin & 0.018(0.011)&0.093(0.012) & 0.026(0.013)&0.091(0.013) \\\\\n%Systolic blood pressure & 50.600(14.449)&105.90(14.304) & 24.697(14.983)&146.47(15.391) \\\\\n%Diastolic blood pressure & 36.168(11.062) & 82.260(10.982) & 0.000(12.473)&136.05(13.082)\\\\\n%Height & 29.282(3.595)&8.890(3.302)& 26.113(4.312)&14.795(4.072) \\\\\n%\\hline\n%\\end{tabular}\n%}\n%\\caption{ Comparison of variance components in 10 NFBC phenotypes.% \\hl{Switch F and M}\n% }\n%\\label{tab:var_comp}\n%\\end{table}\n\n\n\\clearpage\n\n\\section{Figure Legends}\n\n\\begin{figure}[p]\n \\centering\n {\\includegraphics[width=0.96\\textwidth]{../Figures/Fig1/Fig1_A4.pdf}}\n \\caption{Overview of the MetaSex method.}\n \\label{overview}\n\\end{figure}\n\n\\begin{figure}[h]\n\\centering\n{\\includegraphics[width=0.96\\textwidth]{../Figures/Fig2/power19_3_cv_CHL.pdf}}\n\\caption{ Power comparison between MetaSex (RE+SST), CV+SST, GWAMA+SST, \nand SST approaches while varying \nthe effect size ratios of females and males. \nAll methods were appropriately corrected for multiple testing.\n}\n\\label{power_four}\n\\end{figure}\n\n\\begin{figure}[h]\n\\centering\n{\\includegraphics[width=0.96\\textwidth]{../Figures/Fig3/power19_cv_res_CHL.pdf}}\n\\caption{ Power comparison between MetaSex (RE+SST), CV+SST, GWAMA+SST,\nand SST approaches while varying \nthe error variance ratio in females and males. \n%the ratio of the sex-specific standard errors of the random error term\n%between female studies and male studies. \nAll methods were appropriately corrected for multiple testing.\n}\n\\label{power_res}\n\\end{figure}\n\n\\begin{figure}[h]\n\\centering\n{\\includegraphics[width=0.96\\textwidth]{../Figures/Fig4/power50_case2_CHL.pdf}}\n\\caption{Power characteristics of\nRE, CV, GWAMA, and SST in a space \nvarying the effect sizes of males and females.\n%in a study consisting of an equal number of males and females.\n%For the particular male and female effect size pair, \n%the simulated phenotype was generated assuming a ratio of 1.2 between sex-specific error variances\n%(chosen based on NFBC data, male variance = 1.2 $\\times$ female variance).\n%study \n%under the assumption of balanced number of individuals. %between male and female study\n%(b) and when there are twice as many females as males.\nThe lines denote the points where each method achieved 50\\% power. \n%This figure shows the $50\\%$ power lines for the four different approaches.\n%Because power increases as effect size increases, the area outside of the $50\\%$ power line\n%(area containing the point where male effect size=1 and female effect size=1) shows the \n%area which the method achieves more than $50\\%$ power.\nThe diagonal line shows the points where the effect sizes of the two sexes are equal.\nThe $50\\%$ power line is skewed due to the error variance ratio of 1.2 that we assumed.\n%under unbalanced number of individuals between the male and the female study.\n}\n\\label{power_comp11}\n\\end{figure}\n\n\\begin{figure}[h]\n \\centering\n {\\includegraphics[width=0.96\\textwidth]{../Figures/Fig5/GCTA_summary.pdf}}\n \\caption{Comparison of the variance components between the full and the sex-specific\n models in 10 phenotypes of NFBC data. The points represent phenotypes and the\n dotted line is where the variance estimates of the two models are equal. We\nevaluated $r^2$ in the log scale and labeled an outlier(Diastolic blood pressure) observed in the male genetic variance plot.}\n \\label{gcta_summary}\n\\end{figure}\n\n\\begin{figure}[h!]\n\\centering\n{\\includegraphics[width=0.96\\textwidth]{../Figures/Fig6/result_plot_CHL_affinity_symbol.pdf}}\n\\caption{\n Association results of RE, CV, GWAMA, and SST at the 16 associated loci in \n any of 10 phenotypes of NFBC data. \n %Comparison of the four approaches (RE, CV, GWAMA, SST) \n%for the 16 significant loci (threshold : $5.0 \\times 10^{-8}$) from\n%the Northern Finland Birth Cohort data (CRP : C-reactive protein).\n%If there were more than one significant locus in the same linkage disequilibrium block, we choose the most significant one. \n(A) Relative $-log_{10} \\it{P}$ improvement of the other methods compared with the CV method,\nnamely, [$-log_{10} \\it{P}$ of RE/GWAMA/SST] $-$ [$-log_{10} \\it{P}$ of CV]. \n%The horizontal line represents the $-log_{10} \\it{P}$ of the CV method.\nThe RSIDs of 16 significant SNPs as well\nas their CV p-values are shown at the bottom. \n(B) The ratio of phenotypic variance between males and females after regressing out the genetic effect of each SNP.\n(C) The ratio of the genetic effect size of each SNP between males and females.\n}\n\\label{power_result}\n\\end{figure}\n\\clearpage\n\\beginsupplement\n\\section{Supplementary Tables}\n%\n\n\\begin{landscape}\n\n\t\n\\begin{table}[p]\n \\centering\n \\resizebox{1\\textwidth}{!}{\n \\begin{tabular}{cccccccccc}\n \\hline\n Phenotype & $\\sigma_{g}^2(SE)$ & $\\sigma_{g,f}^2(SE)$ & $\\sigma_{g,m}^2(SE)$ &\n $\\sigma_{e,ss}^2(SE)$ & $\\sigma_{e}^2(SE)$ & $P_{g}$ & $P_{g,f}$ & $P_{g,m}$ & $P_{ss}$\\\\ \n \\hline\n\nTriglyceride & 0.0189(0.014) & 0.0323(0.0219) & 0.0031(0.0236) & 0.1134(0.0283) &\n0.1205(0.0189) & $1.79^{-1}$ & $1.4^{-1}$ & $8.95^{-1}$ & $\\bf{6.23^{-5}}$ \\\\\nHDL & 0.0375(0.0072) & 0(0.011) & 0(0.0117) & 0.0017(0.0137) & 0.0694(0.0103) &\n$\\bf{1.72^{-7}}$ & $1.00$ & $1.00$ & $8.99^{-1}$ \\\\\nLDL & 0.2569(0.0511) & 0.0237(0.0786) & 0.042(0.082) & 0.1186(0.0983) & 0.3921(0.067)\n& $\\bf{4.88^{-7}}$ & $7.63^{-1}$ & $6.08^{-1}$ & $2.27^{-1}$ \\\\\nBMI & 0.0052(0.0014) & 0(0.0022) & 0(0.0023) & 0.0107(0.0028) & 0.0118(0.002) &\n$\\bf{2.53^{-4}}$ & $1.00$ & $1.00$ & $\\bf{1.20^{-4}}$ \\\\\nC-reactive protein & 0.222(0.1553) & 0.1346(0.243) & 0.0301(0.2641) & 0.0227(0.3108) &\n1.9925(0.2321) & $1.53^{-1}$ & $5.80^{-1}$ & $9.09^{-1}$ & $9.42^{-1}$ \\\\\nGlucose & 0.0011(0.0005) & 0.0002(0.0008) & 0.0014(0.0008) & 0.0009(0.0009) &\n0.0043(0.0007) & $2.31^{-2}$ & $7.83^{-1}$ & $8.66^{-2}$ & $3.56^{-1}$ \\\\\nInsulin & 0.0121(0.0082) & 0.0139(0.0132) & 0.004(0.0142) & 0.0163(0.0167) &\n0.0847(0.0113) & $1.40^{-1}$ & $2.93^{-1}$ & $7.79^{-1}$ & $3.30^{-1}$ \\\\\nSystolic blood pressure & 37.1421(10.5002) & 4.5774(16.7722) & 1.9977(17.5993) &\n18.3323(21.4657) & 114.189(14.6194) & $\\bf{4.04^{-4}}$ & $7.85^{-1}$ & $9.10^{-1}$ & $3.93^{-1}$ \\\\\nDiastolic blood pressure & 22.0399(8.3115) & 0.0001(12.9059) & 0.0001(13.6516) &\n11.6098(16.1558) & 97.5402(11.0647) & $8.01^{-3}$ & $1.00$ & $1.00$ & $4.72^{-1}$ \\\\\nHeight & 24.0673(2.6501) & 1.2284(3.8886) & 1.1577(4.2184) & 3.2263(4.9783) &\n12.6085(3.326) & $\\bf{1.07^{-19}}$ & $7.52^{-1}$ & $7.84^{-1}$ & $5.17^{-1}$ \\\\\n\n\\hline\n\\end{tabular}\n }\n\\caption {Variance components of 10 NFBC phenotypes in the full five-variance-component model. \n For each trait, we tested if the variance of the polygenic background effect term($\\sigma_{g}^2$) is significantly non-zero ($P_{g}$) and if the variance of\n sex-specific error term($\\sigma_{e,ss}^2$) is significantly non-zero ($P_{ss}$). \n The p-values less than the 0.005 are in bold font. \n}\n\n\n\\label{finland_gcta_withP}\n\\end{table}\n\n\\end{landscape}\n\n\n\\begin{table}[h!]\n%\\tiny\n\\centering\n\\resizebox{0.75\\textwidth}{!}{\n\\begin{tabular}{cccccc}\n\\hline\nPhenotype & SST(F) & SST(M) & RE & CV & GWAMA \\\\\n\\hline\nTriglyceride & 1.007 & 0.991 & 0.995 & 1.001 & 1.006 \\\\\nHDL & 1.002 & 0.995 & 1.008 & 1.003 & 0.993 \\\\\nLDL & 1.001 & 0.996 & 1.011 & 1.002 & 1.004 \\\\\nBMI & 0.999 & 0.996 & 0.992 & 0.994 & 0.994 \\\\\nC-reactive protein & 0.994 & 0.989 & 0.998 & 0.993 & 0.994 \\\\\nGlucose & 1.006 & 1.000 & 1.011 & 1.008 & 1.006 \\\\\nInsulin & 1.004 & 0.996 & 1.006 & 1.005 & 1.001 \\\\\nSystolic blood pressure & 0.997 & 0.997 & 1.012 & 1.006 & 1.000 \\\\\nDiastolic blood pressure & 0.998 & 1.008 & 1.013 & 1.006 & 1.002 \\\\\nHeight & 1.004 & 1.002 & 1.028 & 1.003 & 1.001 \\\\\n\\hline\n\\end{tabular}\n}\n\\caption{ Genomic control factor in the genome-wide association mapping of 10 NFBC phenotypes.\n % \\hl{You can similarly change trait names here, too.}\n }\n\\label{finland_lambda1}\n\\end{table}\n\n\n\n\n\\begin{table}\n\\footnotesize\n\\centering\n\\resizebox{0.899\\textwidth}{!} {\n\\begin{tabular*}{1.11\\textwidth} {@{\\extracolsep{\\fill}} |c|c|c|c|c|c|c|c|c|}\n\\hline\n\\multicolumn{4}{|c|}{\\textbf{Phenotype : C-reactive protein }} & \\multicolumn{2}{c|}{\\textbf{sex-specific}} & \\multicolumn{2}{c|}{\\textbf{beta$\\pm$std error}} & \\textbf{best} \\\\\n\\hline\n\\textbf{rsid} & \\textbf{RE} & \\textbf{CV} & \\textbf{GWAMA} & \\textbf{SST(F)} & \\textbf{SST(M)} & \\textbf{female} & \\textbf{male} & \\textbf{methods} \\\\\n\\hline\n\\hline\nrs2794520 & 3.32e-23 & \\textbf{2.11e-23} & 1.64e-22 & 1.28e-13 & 2.93e-11 & 0.314$\\pm$0.042 & 0.291$\\pm$0.043 & RE,CV\\\\ \nrs2650000 & \\textbf{1.71e-12} & 1.64e-12 & 8.09e-12 & 2.79e-06 & 8.65e-08 & 0.199$\\pm$0.042 & 0.220$\\pm$0.041 & RE,CV \\\\ \n%Chr17:68989647 & rs7406617 & 0.00011 & \\textbf{3.61e-06} & 8.15e-05 & 8.11e-05 & 1.66e-07 & 0.88493 & -0.251$\\pm$0.048 & -0.006$\\pm$0.049 & RE \\\\ \n\\hline\n\\hline\n\\multicolumn{4}{|c|}{\\textbf{Phenotype : Glucose }} & \\multicolumn{2}{c|}{\\textbf{sex-specific}} & \\multicolumn{2}{c|}{\\textbf{beta$\\pm$std error}} & \\textbf{best} \\\\\n\\hline\n\\textbf{rsid} & \\textbf{RE} & \\textbf{CV} & \\textbf{GWAMA} & \\textbf{SST(F)} & \\textbf{SST(M)} & \\textbf{female} & \\textbf{male} & \\textbf{methods} \\\\\n\\hline\n\\hline\nrs560887 & 5.30e-12 & \\textbf{1.14e-12} & 1.39e-09 & 8.19e-06 & 4.83e-08 & 0.011$\\pm$0.002 & 0.014$\\pm$0.002 & CV \\\\ \n%Chr7:15030358 & rs10244051 & 2.14e-07 & 2.61e-07 & \\textbf{1.74e-07} & 1.77e-07 & 0.00029 & 0.00021 & -0.007$\\pm$0.002 & -0.007$\\pm$0.002 & FE,RE,CV,CM \\\\ \n%Chr11:92362409 & rs1447352 & 1.31e-07 & 1.59e-07 & 9.07e-08 & \\textbf{8.72e-08} & 0.00037 & 9.46e-05 & 0.007$\\pm$0.002 & 0.007$\\pm$0.002 & FE,RE,CV,CM \\\\ \n%Chr11:92363999 & rs7121092 & 1.32e-07 & 1.59e-07 & 9.53e-08 & \\textbf{9.12e-08} & 0.00031 & 0.00011 & 0.007$\\pm$0.002 & 0.007$\\pm$0.002 & FE,RE,CV,CM \\\\ \nrs7298683 & 2.01e-07 & 8.14e-05 & 7.23e-08 & 0.86718 & \\textbf{5.92e-09} & -0.0007$\\pm$0.004 & 0.026$\\pm$0.004 & SST(M) \\\\ \n\\hline\n\\hline\n\\multicolumn{4}{|c|}{\\textbf{Phenotype : HDL }} & \\multicolumn{2}{c|}{\\textbf{sex-specific}} & \\multicolumn{2}{c|}{\\textbf{beta$\\pm$std error}} & \\textbf{best} \\\\\n\\hline\n\\textbf{rsid} & \\textbf{RE} & \\textbf{CV} & \\textbf{GWAMA} & \\textbf{SST(F)} & \\textbf{SST(M)} & \\textbf{female} & \\textbf{male} & \\textbf{methods} \\\\\n\\hline\n\\hline\n%Chr2:21047434 & rs6728178 & \\textbf{2.19e-07} & 2.68e-07 & 4.52e-07 & 4.54e-07 & 0.00390 & 1.16e-05 & -0.031$\\pm$0.011 & -0.043$\\pm$0.010 & FE,RE \\\\\n%Chr8:19875201 & rs10096633 & 4.74e-07 & \\textbf{4.62e-07} & 2.66e-06 & 2.69e-06 & 0.04291 & 6.66e-07 & -0.034$\\pm$0.017 & -0.074$\\pm$0.015 & FE,RE \\\\\nrs2167079 & \\textbf{4.46e-08} & 1.26e-06 & 5.06e-08 &0.01838 & 9.78e-08 & -0.024$\\pm$0.010 & -0.055$\\pm$0.010 & RE, GWAMA \\\\\nrs7120118 & \\textbf{4.62e-08} & 1.13e-06 & 5.07e-08 & 0.01679 & 1.15e-07 & -0.024$\\pm$0.010 & -0.054$\\pm$0.010 & RE, GWAMA \\\\\n rs1532085 & \\textbf{3.53e-12} & 1.08e-11 & 2.98e-11 &1.87e-06 & 2.25e-07 & -0.048$\\pm$0.010 & -0.050$\\pm$0.009 & RE \\\\\n rs3764261 & \\textbf{4.15e-32} & 4.89e-32 & 2.88e-31 & 8.85e-16 & 3.63e-18 & -0.090$\\pm$0.011 & -0.092$\\pm$0.010 & RE,CV \\\\\n rs255049 & \\textbf{5.26e-09} & 1.45e-08 & 3.94e-08 &0.00014 & 5.85e-06 & -0.047$\\pm$0.012 & -0.053$\\pm$0.011 & RE \\\\\n rs1800961 & \\textbf{2.39e-08} & 2.82e-08 & 8.96e-08 &0.00051 & 6.29e-06 & 0.083$\\pm$0.023 & 0.108$\\pm$0.023 & RE,CV \\\\\n\\hline\n\\hline\n\\multicolumn{4}{|c|}{\\textbf{Phenotype : LDL }} & \\multicolumn{2}{c|}{\\textbf{sex-specific}} & \\multicolumn{2}{c|}{\\textbf{beta$\\pm$std error}} & \\textbf{best} \\\\\n\\hline\n\\textbf{rsid} & \\textbf{RE} & \\textbf{CV} & \\textbf{GWAMA} & \\textbf{SST(F)} & \\textbf{SST(M)} & \\textbf{female} & \\textbf{male} & \\textbf{methods} \\\\\n\\hline\n\\hline\n rs646776 & \\textbf{1.97e-15} & 4.17e-15 & 9.71e-15 & 8.36e-10 & 2.11e-07 & 0.169$\\pm$0.027 & 0.166$\\pm$0.031 & RE \\\\\n%Chr1:205941798 & rs4844614 & \\textbf{1.27e-07} & 1.52e-07 & 2.52e-07 & 2.52e-07 & 0.00080 & 2.78e-05 & -0.080$\\pm$0.024 & -0.113$\\pm$0.027 & FE,RE,CV,CM \\\\\nrs693 & \\textbf{1.25e-11} & 2.97e-11 & 5.84e-11 & 8.81e-09 & 0.00013 & -0.131$\\pm$0.022 & -0.103$\\pm$0.026 & RE \\\\\n rs11668477 & 1.98e-08 & \\textbf{4.04e-09} & 1.96e-08 & 0.00240 & 2.62e-07 & 0.090$\\pm$0.029 & 0.179$\\pm$0.034 & CV \\\\\n%Chr19:50087106 & rs157580 & \\textbf{3.18e-07} & 3.86e-07 & 3.24e-07 & 3.25e-07 & 9.62e-06 & 0.00682 & 0.110$\\pm$0.025 & 0.075$\\pm$0.028 & FE,RE,CV,CM \\\\\n\\hline\n%\\hline\n%\\multicolumn{6}{|c|}{\\textbf{Phenotype : sysres }} & \\multicolumn{2}{c|}{\\textbf{sex-specific}} & \\multicolumn{2}{c|}{\\textbf{beta$\\pm$std error}} & \\textbf{best} \\\\\n%\\hline\n%\\textbf{Position} & \\textbf{rsid} & \\textbf{FE} & \\textbf{RE} & \\textbf{Covariate} & \\textbf{Combined} & \\textbf{female} & \\textbf{male} & \\textbf{female} & \\textbf{male} & \\textbf{methods} \\\\\n%\\hline\n%\\hline\n%Chr2:55702813 & rs782602 & \\textbf{7.30e-08} & 8.55e-08 & 1.42e-07 & 1.42e-07 & 6.00e-06 & 0.00246 & 1.555$\\pm$0.343 & 1.115$\\pm$0.368 & FE,RE,CV,CM \\\\\n%Chr7:33208521 & rs10486523 & 5.47e-07 & 6.67e-07 & 4.95e-07 & \\textbf{4.94e-07} & 0.00027 & 0.00059 & -2.351$\\pm$0.646 & -2.435$\\pm$0.710 & FE,RE,CV,CM \\\\\n%\\hline\n\\hline\n\\multicolumn{4}{|c|}{\\textbf{Phenotype : Triglyceride }} & \\multicolumn{2}{c|}{\\textbf{sex-specific}} & \\multicolumn{2}{c|}{\\textbf{beta$\\pm$std error}} & \\textbf{best} \\\\\n\\hline\n\\textbf{rsid} & \\textbf{RE} & \\textbf{CV} & \\textbf{GWAMA} & \\textbf{SST(F)} & \\textbf{SST(M)} & \\textbf{female} & \\textbf{male} & \\textbf{methods} \\\\\n\\hline\n\\hline\n rs673548 & \\textbf{2.61e-08} & 6.54e-08 & 2.21e-07 &6.11e-06 & 0.00097 & 0.058$\\pm$0.012 & 0.054$\\pm$0.016 & RE \\\\\nrs1260326 & \\textbf{1.64e-10} & 1.88e-10 & 1.49e-09 & 1.32e-06 & 2.10e-05 & -0.057$\\pm$0.011 & -0.065$\\pm$0.015 & RE,CV \\\\\n rs10096633 & 5.32e-08 & \\textbf{1.98e-08} & 1.19e-07 & 0.00109 & 3.47e-06 & 0.062$\\pm$0.019 & 0.113$\\pm$0.024 & CV \\\\\n\\hline\n\\end{tabular*}\n}\n\\caption{ Association mapping results of the NFBC data. \n %Comparison of different approaches in the Northern Finland Birth Cohort data. \nThe SNPs are presented for which any method gave $P < 5\\times 10^{-8}$ in any of 10 phenotypes.\n%After correcting with genomic control,\n%if any $\\textit{p-value}$ from any approach is significant \n%(threshold: $5.0 \\times 10^{-8}$)\n%(threshold RE+SST : $2.39 \\times 10^{-8}$, \n%FE, Covariate, Combined : $5 \\times 10^{-8}$), \n%then we include this result in the table. \nFor each SNP, the most significant p-value among the four methods (RE, CV, GWAM, and SST)\nis in bold font. \nThe ``beta'' column shows the effect sizes of male- and female-only studies and their estimated standard errors.\nFor each significant association, we report the ``best methods'', \nthe set of methods whose p-value was less than two times the most significant \np-value for each association.\n%For example, for the association at rs1532085 in the HDL phenotype, \n%the most significant p-value is $2.93 \\times 10^{-12}$ . \n%However, the p-value for the CV method ($1.01 \\times 10^{-11}$) and \n%the GWAMA method ($3.39 \\times 10^{-11}$) are greater than \n%twice that value. %$7.92 \\times 10^{-8}$.\n%Thus, only RE is included in the best methods for this SNP.\n%To get an overall comparison of the relative power of the approaches, we compare the \n%number of times the each approach is selected as the best methods. \n%For the six NFBC phenotypes with significant associations, \n%the RE approach is the best methods for 12 associated loci whereas\n%the CV approach is the best methods for 8 associated loci and the \n%GWAMA approach is the best methods for only 2 associated loci.\n%The SST approach is the best method for only one associated locus. \n}\n\\label{tab:NFBC1}\n\\end{table}\n\n\n\n\n\\end{document}\n", "meta": {"hexsha": "5edf86455cdfb96222a33345671788986844a194", "size": 139454, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Cue_Manuscript/2017-09-19 v26 CHL/meta_sex.tex", "max_stars_repo_name": "cuelee/meta-sex", "max_stars_repo_head_hexsha": "6113c8f9cbc11d5a5fe8a08664e5f580f312bb62", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Cue_Manuscript/2017-09-19 v26 CHL/meta_sex.tex", "max_issues_repo_name": "cuelee/meta-sex", "max_issues_repo_head_hexsha": "6113c8f9cbc11d5a5fe8a08664e5f580f312bb62", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Cue_Manuscript/2017-09-19 v26 CHL/meta_sex.tex", "max_forks_repo_name": "cuelee/meta-sex", "max_forks_repo_head_hexsha": "6113c8f9cbc11d5a5fe8a08664e5f580f312bb62", "max_forks_repo_licenses": ["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.0574521232, "max_line_length": 461, "alphanum_fraction": 0.7411978143, "num_tokens": 39063, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.33458942798284697, "lm_q1q2_score": 0.17903827714869822}}
{"text": "\\section{Simple Transformation}\n\\label{sec:transformations-slco:simple}\nThe transformation~\\TSim takes a model and a channel name as input.\nIf the channel is used for synchronous communication, it is replaced by an asynchronous channel, and the classes of the objects that are connected by the channel are adapted.\nIt is defined as\n%\n\\[\n\\begin{array}{l}\n\\TSim(\\it{mn}~\\it{class^*}~\\it{obj^*}~\\it{chan^*}, \\it{chn}) = \\\\\n\\quad \\it{mn} ~\nT^S_{\\it{CS}}(\\it{class^*}, \\it{cn_1}, \\it{pn_1}, \\it{cn_2}, \\it{pn_2}) ~\n\\it{obj^*} \\\\\n\\quad \\it{chan_1^*}~\\it{chn}(\\it{type^*})~\\textbf{async lossless between}~\\it{on_1}.~\\it{pn_1}~\\textbf{and}~\\it{on_2}.~\\it{pn_2}~\\it{chan_2^*},\n\\end{array}\n\\]\nif~$\\it{chan^*} \\equiv \\it{chan_1^*}~\\it{chn}(\\it{type^*})~\\textbf{sync}~\\textbf{from}~\\it{on_1}.~\\it{pn_1}~\\textbf{to}~\\it{on_2}.~\\it{pn_2}~\\it{chan_2^*}$, $\\it{obj^*} \\equiv \\it{obj_1^*}~\\it{on_1}:\\it{cn_1}~\\it{obj_2^*}$,\nand~$\\it{obj^*} \\equiv \\it{obj_3^*}~\\it{on_2}:\\it{cn_2}~\\it{obj_4^*}$,\nand it is defined as\n\\[\n\\TSim(\\it{mn}~\\it{class^*}~\\it{obj^*}~\\it{chan^*}, \\it{chn}) = \\it{mn}~\\it{class^*}~\\it{obj^*}~\\it{chan^*}\n\\]\notherwise.\n\nThe transformation~$T^S_{\\it{CS}}$ defined below takes a sequence of classes, two class names, and two port names as input.\nIt returns a sequence of classes.\nThe classes with the names provided as input are modified, and all other classes remain intact.\nThere are two cases for this transformation.\nIn one case, the class with name $\\it{cn_1}$ is first in the sequence of classes.\nIn the other case, the class with name $\\it{cn_2}$ is first.\n\n\\[\n\\begin{array}{l}\nT^S_{\\it{CS}}(\\it{class^*}, \\it{cn_1}, \\it{pn_1}, \\it{cn_2}, \\it{pn_2}) =\\\\\n\\quad \\it{class_1^*}~T^S_{\\it{C}}(\\it{class_1}, \\it{pn_1})~\\it{class_2^*}~T^S_{\\it{C}}(\\it{class_2}, \\it{pn_2})~\\it{class_3^*},\n\\end{array}\n\\]\nif~$\\it{class^*} \\equiv \\it{class_1^*}~\\it{class_1}~\\it{class_2^*}~\\it{class_2}~\\it{class_3^*}$, $\\it{class_1} \\equiv \\it{cn_1}~\\it{pn_1^*}~\\it{var_1^*}~\\it{sm_1^*}$, and $\\it{class_2} \\equiv \\it{cn_2}~\\it{pn_2^*}~\\it{var_2^*}~\\it{sm_2^*}$, and\n\\[\n\\begin{array}{l}\nT^S_{\\it{CS}}(\\it{class^*}, \\it{cn_1}, \\it{pn_1}, \\it{cn_2}, \\it{pn_2}) = \\\\\n\\quad \\it{class_1^*}~T^S_{\\it{C}}(\\it{class_2}, \\it{pn_2})~\\it{class_2^*}~T^S_{\\it{C}}(\\it{class_1}, \\it{pn_1})~\\it{class_3^*},\n\\end{array}\n\\]\nif~$\\it{class^*} \\equiv \\it{class_1^*}~\\it{class_2}~\\it{class_2^*}~\\it{class_1}~\\it{class_3^*}$, $\\it{class_1} \\equiv \\it{cn_1}~\\it{pn_1^*}~\\it{var_1^*}~\\it{sm_1^*}$, and~$\\it{class_2} \\equiv \\it{cn_2}~\\it{pn_2^*}~\\it{var_2^*}~\\it{sm_2^*}$.\n\nThe transformation~$T^S_{\\it{C}}$ defined below takes a class and a port name as input and returns a class with modified state machines.\nOnly the state machines that send or receive signals over the given port are modified.\n%\n\\[\nT^S_{\\it{C}}(\\it{cn}~\\it{pn^*}~\\it{var^*}~\\it{sm^*}, \\it{pn}) = \\it{cn}~\\it{pn^*}~\\it{var^*}~T^S_{\\it{SMS}}(\\it{sm^*}, \\it{pn})\n\\]\n\nThe transformation~$T^S_{\\it{SMS}}$ defined below takes a sequence of state machines and a port name as input, and returns a modified sequence of state machines.\nOnly the state machines that send or receive signals over the given port are modified.\nThere are two cases for this transformation.\nOne case deals with empty sequences of state machines and one case with non-empty sequences of state machines.\n%\n\\begin{align*}\nT^S_{\\it{SMS}}(\\epsilon, \\it{pn}) & = \\epsilon \\\\\nT^S_{\\it{SMS}}(\\it{sm}~\\it{sm^*}, \\it{pn}) & = T^S_{\\it{SM}}(\\it{sm}, \\it{pn})~T^S_{\\it{SMS}}(\\it{sm^*}, \\it{pn})\n\\end{align*}\n\nThe transformation~$T^S_{\\it{SM}}$ defined below takes a state machine and a port name as input, and returns a state machine with modified transitions and a number of additional states.\nOnly the transitions that send or receive signals over the given port are modified.\nThere are two cases for this transformation.\nOne case deals with state machines without final states, and the other with state machines with final states.\n%\n\\[\nT^S_{\\it{SM}}(\\it{smn}~\\it{var^*}~\\textbf{initial}~\\it{sn}~\\it{sn^*}~\\it{trans^*}, \\it{pn}) = \\it{smn}~\\it{var^*}~\\textbf{initial}~\\it{sn}~\\it{sn^*}~\\it{sn^*_1}~\\it{trans^*_1},\n\\]\nwhere~$\\langle \\it{sn^*_1}, \\it{trans^*_1} \\rangle = T^S_{\\it{TS}}(\\it{trans^*}, \\it{pn})$, and\n\\[\n\\begin{array}{l}\nT^S_{\\it{SM}}(\\it{smn}~\\it{var^*}~\\textbf{initial}~\\it{sn}~\\it{sn^*}~\\textbf{final}~\\it{sn^+}~\\it{trans^*}, \\it{pn}) = \\\\\n\\quad \\it{smn}~\\it{var^*}~\\textbf{initial}~\\it{sn}~\\it{sn^*}~\\it{sn^*_1}~\\textbf{final}~\\it{sn^+}~\\it{trans^*_1},\n\\end{array}\n\\]\nwhere~$\\langle \\it{sn^*_1}, \\it{trans^*_1} \\rangle = T^S_{\\it{TS}}(\\it{trans^*}, \\it{pn})$.\nThe syntax definition given in Appendix~\\ref{ap:sos-slco} is extended as follows to accommodate final states.\n%\n\\[\n\\it{sm} ::= \\it{smn}~\\it{var^*}~``\\textbf{initial}\"~\\it{sn}~\\it{sn^*}~[``\\textbf{final}\"~\\it{sn^+}]~\\it{trans^*}\n\\]\n\n\nThe transformation~$T^S_{\\it{TS}}$ defined below takes a sequence of transitions and a port name as input, and returns a modified sequence of transitions and a set of new states.\nOnly the transitions that send or receive signals over the given port are modified.\nThere are two cases for this transformation.\nOne case deals with empty sequences of transitions and the other with non-empty sequences.\n%\n\\begin{align*}\nT^S_{\\it{TS}}(\\epsilon, \\it{pn}) & = \\langle \\epsilon, \\epsilon \\rangle \\\\\nT^S_{\\it{TS}}(\\it{trans}~\\it{trans^*}, \\it{pn}) & = \\langle \\it{sn^*_1}~\\it{sn^*_2}, \\it{trans^*_1}~\\it{trans^*_2} \\rangle,\n\\end{align*}\nwhere~$\\langle \\it{sn^*_1}, \\it{trans^*_1} \\rangle = T^S_{\\it{T}}(\\it{trans}, \\it{pn})$ and~$\\langle \\it{sn^*_2}, \\it{trans^*_2} \\rangle = T^S_{\\it{TS}}(\\it{trans^*}, \\it{pn})$.\n\nThe transformation~$T^S_{\\it{T}}$ defined below takes a transition and a port name as input, and returns a set of states and a set of transitions.\nOnly transitions that have a signal reception trigger or a send signal statement are replaced by new transitions.\nAll other transitions are left unaltered.\nThere are three cases for this transformation.\nOne case deals with transitions that send a signal, one case deals with transitions that receive signals, and one case deals with all other transitions.\n%\n\\[\n\\begin{array}{l}\nT^S_{\\it{T}}(\\it{tn}~\\textbf{from}~\\it{sn_1}~\\textbf{to}~\\it{sn_2}~\\textbf{send}~\\it{sgn}()~\\textbf{to}~\\it{pn}, \\it{pn}) =\n\\langle \\\\\n\\quad \\it{sn_3}, \\\\\n\\quad \\it{tn_1}~\\textbf{from}~\\it{sn_1}~\\textbf{to}~\\it{sn_3}~\\textbf{send}~\\it{sgn_1}()~\\textbf{to}~\\it{pn} \\\\\n\\quad \\it{tn_2}~\\textbf{from}~\\it{sn_3}~\\textbf{to}~\\it{sn_2}~\\textbf{receive}~\\it{sgn_2}()~\\textbf{from}~\\it{pn} \\\\\n\\rangle,\n\\end{array}\n\\]\nwhere~$\\it{sn_3}$ is a fresh state name, $\\it{tn_1}$ and~$\\it{tn_2}$ are fresh transition names, $\\it{sgn_1}~\\equiv~``s\\_\"+\\it{sgn}$, and $\\it{sgn_2}~\\equiv~``a\\_\"+\\it{sgn}$,\n\\[\n\\begin{array}{l}\nT^S_{\\it{T}}(\\it{tn}~\\textbf{from}~\\it{sn_1}~\\textbf{to}~\\it{sn_2}~\\textbf{receive}~\\it{sgn}()~\\textbf{from}~\\it{pn}, \\it{pn}) =\n\\langle \\\\\n\\quad \\it{sn_3}, \\\\\n\\quad \\it{tn_1}~\\textbf{from}~\\it{sn_1}~\\textbf{to}~\\it{sn_3}~\\textbf{receive}~\\it{sgn_1}()~\\textbf{from}~\\it{pn} \\\\\n\\quad \\it{tn_2}~\\textbf{from}~\\it{sn_3}~\\textbf{to}~\\it{sn_2}~\\textbf{send}~\\it{sgn_2}()~\\textbf{to}~\\it{pn} \\\\\n\\rangle,\n\\end{array}\n\\]\nwhere~$\\it{sn_3}$ is a fresh state name, $\\it{tn_1}$ and~$\\it{tn_2}$ are fresh transition names, $\\it{sgn_1}~\\equiv~``s\\_\"+\\it{sgn}$, and~$\\it{sgn_2}~\\equiv~``a\\_\"+\\it{sgn}$, and\n\\[\n\\begin{array}{l}\nT^S_{\\it{T}}(\\it{trans}, \\it{pn}) = \\langle \\epsilon, \\it{trans} \\rangle,\n\\end{array}\n\\]\nfor all other transitions. ", "meta": {"hexsha": "86b02cf676fa6d2d27f6e344b4efdba765fc2a84", "size": 7460, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "transformations-slco/sync2asyncsimple.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": "transformations-slco/sync2asyncsimple.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": "transformations-slco/sync2asyncsimple.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": 57.3846153846, "max_line_length": 244, "alphanum_fraction": 0.6495978552, "num_tokens": 3220, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.35220178204788966, "lm_q1q2_score": 0.17885224354419688}}
{"text": "\\chapter{\\label{chap:information-theory}Information theory}\n\nThe field of information theory is concerned with measurement, storage\nand transmission of information.\nI has its roots in communication theory,\nbut applications in many different fields including machine learning\nand natural language processing.\nIn this chapter,\nwe will briefly introduce some of the main ideas,\nand discuss a few important information theoretic measures\nthat will be used in the rest of the course.\n\n\\section{The noisy channel model}\n\nA basic motivation in information theory is communication over \na noisy channel.\nIn a \\emph{noisy channel model},\nas the one depicted in Figure~\\ref{fig:noisy-channel},\nthe sender encodes the given message,\nand sends it through the channel,\nbut the receiver receives a possibly corrupted version of the coded message.\n\\begin{marginfigure}\n \\tikzsetnextfilename{noisy-channel}\n \\begin{tikzpicture}\n \\node (in) {a};\n \\node[draw,thick,right=3mm of in, minimum height=4ex] (enc) {encoder};\n \\node[draw,thick,right=15mm of enc, minimum height=4ex] (dec) {decoder};\n \\node[right=3mm of dec] (out) {a};\n \\node[below=0.5mm of enc,xshift=2em,font=\\small]\n {100\\textcolor{red}{0}0010};\n \\node[below=0.5mm of dec,xshift=-2em,font=\\small]\n {100\\textcolor{red}{1}0010};\n \\draw[thick,->] (in) -- (enc);\n \\draw[thick,->] (dec) -- (out);\n \\draw[thick,decorate, decoration={snake,post length=1mm},->]\n (enc) -- (dec)\n node[midway, above,yshift=2mm,font=\\small,text width=1cm,align=center]\n {noisy\\\\channel};\n \\end{tikzpicture}\n \\caption{\\label{fig:noisy-channel}%\n Schematic description of the noisy-channel model.\n The encoder codes the message and sends through a noisy channel\n to the decoder.\n The encoded message may possibly be corrupted during the transmission.\n The decoder's task is to reconstruct the original message,\n despite the potential noise introduced.\n }\n\\end{marginfigure}\nThe task of the decoder is to recover the original message,\neven if there are some errors introduced in the noisy channel.\nThere are two competing objectives within the noisy channel model.\nFirst, we want to use codes that use of the \\emph{channel capacity}\nas \\emph{efficient}ly as possible.\nWe want coding schemes that result in short coded messages,\nto transmit or store.\nThis is where the strong connection between the information theory \nand compression comes into the picture.\nSecond,\nwe want to be able to detect and correct the errors introduced by the noisy channel.\nAn obvious way to detect and correct errors is \nto send multiple copies of the code.\nAs we introduce more redundant copies,\nit is more likely to recover the original message.\nHowever,\nreplication also wastes the bandwidth of the channel.\nCoding information efficiently,\nwhile allowing error detection and error correction is fundamental\ntopics in information theory.\nThe example code in Figure~\\ref{fig:noisy-channel},\nis simply the ASCII code followed by an odd parity bit,\nwhich means the last bit is set to \\num{1} if the number of \\num{1}s\nin the code is an odd number,\notherwise,\nthe last bit is set to \\num{0}.\nNote that with the given code at hand,\nthe decoder can detect the error.%\n\\footnote{Can the decoder correct the error in Figure~\\ref{fig:noisy-channel}?}\nHere, we will not discuss error-correcting codes,\nneither most of the other fascinating topics in information theory.\nInterested readers are referred to the textbooks on information theory,\nsuch as \\textcite{mackay2003}.\n\nClearly, the noisy channel model is useful in the study of computer networks.\nHowever, it has many other uses.\nNote that the channel does not have to be a network connection.\nFor example,\nthe model fits equally well to storing data to a permanent storage.\nPermanent storage systems (e.g., hard disks) are fairly accurate,\nhowever, they are not error free.\nAs a result,\nerror resilience and efficiency is a concern here too.\nThe encoder encodes the information,\nand sends it to the disk,\nthe decoder reads code (possibly after a long time) from the disk and\nhas to make sure that the information it decodes was not corrupted.\n\nBeyond those obvious extensions,\nthe noisy channel model found its use in many other applications.\nFor an example close to home,\nwe often model \\emph{speech recognition} with a noisy channel model.\nThe information here is a linguistic message,\ne.g., a sentence.\nThe speaker codes this information as an acoustic signal,\nand the recognizer's task is to decode the sentence\nfrom the acoustic signal (code).\nAnother common use for the noisy channel model in NLP is\nin machine translation, which we will return later.\nWe will not further discuss\nthe applications of the noisy channel model here.\nHowever,\nwe introduce some of the concepts, particularly some measures,\nthat have very frequent uses in machine learning and NLP.\n\n\\section{Entropy and information}\n\nIn information theory,\n\\emph{entropy} is a measure of uncertainty.\nThe measure is analogous to `physical' entropy measure\nin statistical thermodynamics,\nbut measures the uncertainty of\nan information system rather than a physical system.\nIn ambiguous contexts, it is also called \\emph{information entropy} or \n\\emph{Shannon entropy} after Claude Shannon,\nthe inventor of the measure and the founder of the field.\nEntropy and information are tightly connected concepts.\nMore concretely,\ninformation in a message\n(e.g., in the noisy channel model described above)\nis the reduction of entropy after receiving the message.\n\nBefore introducing entropy properly,\nwe will first introduce a related measure \\emph{surprisal},\nwhich is also called \\emph{self information}\nor \\emph{information content}.\nThe information theoretic measure of surprisal of an event $x$ is defined as\n\\begin{equation}\\label{eq:surprisal}\n log \\frac{1}{P(x)} = - log P(x) .\n\\end{equation}\nIf the probability of the event is \\num{1}\n(event occurs with certainty)\nthe surprisal will be \\num{0}.\nFor events with decreasing probabilities,\nwe will get higher values for surprisal.\nThe value of surprisal will approach to $\\infty$\nwhile the probability of the event approaches to \\num{0}.\n\nThe base of the logarithm in Equation~\\ref{eq:surprisal}\nis not very important,\nsince the logarithms in a different base can be obtained\nby multiplication with a constant\n(with a linear transformation).\nMost common choices include base \\num{2} logarithms,\nwhich results in surprisal (or information) measured in \\emph{bit}s.\nIf we use natural logarithm (with base $e$, Euler's number),\nthan the unit is called \\emph{nat}.\nIn this course we will always use base-\\num{2} logarithms,\nand measure the information in bits.\n\nThe same quantity having names `surprisal' and `self information'\nmay not sound right at first sight.\nThe intuition here is that\nwe learn more from low-probability events.\nLow probability events are surprising,\nbut also have more information content.\nThere is nothing surprising with\na weather report that tells it will rain in a very rainy country.\nIt also does not have much information content,\nwe can already predict it.\nBut if it predicts a sunny day in the middle of a rainy season,\nthen it is surprising as well as news-worthy,\nit contains more information.\n\n% The inverse relationship between surprisal and probability is intuitive.\n% You may wonder, however, the reason for taking the logarithm.\n% The main reason seems to be it is more convenient.\n% We will try to get the intuition about logarithms with an example.\n% Let's assume that we have a language with four letters,\n% where occurrence of each letter has probability of \\num{1/4},\n% that is \n% \n% or information content of a state.\n% High entropy means high unpredictability,\n% hence high information content.\n% If the outcome of a particular random variable is deterministic,\n% then there is no uncertainty.\n% Hence, the entropy is \\num{0}.\n\nEntropy of a system is the average surprisal.\nWe define entropy, $H$, of a random variable $X$ as\n\\begin{equation}\\label{eq:entropy}\n H(X) = - \\sum_{x \\in X} P(x) log P(x)\n\\end{equation}\nwhere, $x$ ranges over all values of $X$.\nThe above definition is for discrete variables,\nwhich is much more common in NLP.\nThe notion of entropy can be extended to continuous random variables,\nby replacing the sum with an integral\nand $P(x)$ with the appropriate probability density function.\nThe resulting definition (for continuous random variables)\nis called \\emph{differential entropy}.\n\nTo get a sense of what entropy does,\nconsider the `guess the number' game,\nwhere the first player picks a number between \\num{1} and a larger number $M$,\n(say 32),\nand the task of the second player is to guess the number.\nAfter every guess,\nthe first player tells whether the guess was\nlarger or smaller than the number he/she picked.\nAssuming the first player picks the number completely randomly\n(samples from the uniform distribution),\nand if the second player follows the optimum strategy (binary search),\nthe first player will need to make $\\log_{2} M$ guesses at most.%\n\\sidenote{What is the best strategy,\n if the number picked randomly,\n but follows a known non-uniform distribution?\n}\nWhich is exactly what you will find if you use Equation~\\ref{eq:entropy},\nto calculate the entropy of this system.\nFor $M = 32$, \n\\[\n H = - \\sum_{1 \\le x \\le 32} \\frac{1}{32} \\log_{2} \\frac{1}{32}\n = - 32 \\frac{1}{32} \\log_{2} \\frac{1}{32} = - \\log_{2} \\frac{1}{32}\n = 5 .\n\\]\nNote that since the numbers are equally likely,\nprobabilities for each number is the same ($1/32$).\nAs a result,\nat the beginning we have \\num{5} bits of entropy.\nYou should also see that we reduce the entropy by \\num{1} bit for every guess\n(unless we guess the correct number).\nHence, information we gain with every guess is \\num{1} bit.\n\nIt is important to realize that\nthe entropy, or the information,\nincrease or decrease proportional to the logarithm of the states (the numbers).\nIf we double the range of numbers to pick from,\nthe entropy will not double, but only increase with one bit.\nThis logarithmic relationship is convenient,\nsince states of many systems we are interested in grow exponentially.\n\n\\begin{margintable}\n \\caption{\\label{tbl:binary-code-example}\n Example binary coding of an eight letter alphabet.\n }\n \\begin{center}\n \\begin{tabular}{lS[minimum-integer-digits=3]}\n \\toprule\n letter & {code} \\\\\n \\midrule\n a & 000 \\\\\n b & 001 \\\\\n c & 010 \\\\\n d & 011 \\\\\n e & 100 \\\\\n f & 101 \\\\\n g & 110 \\\\\n h & 111 \\\\\n \\bottomrule\n \\end{tabular}\n \\end{center}\n\\end{margintable}\nTo get a sense of why logarithm is a good idea,\nconsider we want to code a \\num{8}-letter alphabet on a binary medium\n(or want to send over a binary channel).\nWe can use as many bits as the number of letters\n(setting one of the bits to \\num{1}, and the rest to \\num{0},\nsimilar to the one-hot representation discussed in Section~\\ref{desc:one-hot}),\nbut this is wasteful.\nThe optimum coding would not require \\num{8} bits.\nWe can easily represent \\num{8} letters letters with \\num{3} bits,\nwhich turns out to be exaclty $\\log_{2} 8$.\nAn example coding of \\num{8}-letter alphabet is shown\nin Table~\\ref{tbl:binary-code-example}.\nNote that if we double the letters,\nwe would not need to double the number of bits used,\nall we need to do is add one more bit.\nHence,\nthe number of bits needed to represent $M$ letters is $log_{2} M$.\nThis is optimum if the letters we want to transmit are distributed uniformly.\nWe will soon see that we can do better,\nif we have more structure in the distribution of the letters.\n\n\n\\begin{marginfigure}\n \\tikzsetnextfilename{bernoulli-entropy}\n \\begin{tikzpicture}[\n ]\n\n \\begin{axis}[axis lines=left,\n enlarge x limits=true,\n enlarge y limits=upper,\n samples=50,\n width=1.1\\linewidth,\n xlabel={$P(X=1)$},\n ylabel={$H(X)$},\n ylabel style={at={(rel axis cs:0,1)}, anchor=west,rotate=-90}\n ]\n \\addplot[smooth, thick, blue, domain=0:1]\n {- x * (ln(x)/ln(2)) - (1-x) * (ln(1-x)/ln(2))};\n \\end{axis}\n \\end{tikzpicture}\n \\caption{\\label{fig:bernoulli-entropy}%\n Entropy of Bernoulli random variables (in bits)\n as a function of the parameter $p$. \n }\n\\end{marginfigure}\nFor simplicity,\nwe assumed uniform distribution in the discussion/demonstration above.\nWhat if the distribution of the random variable is not uniform?\nTo answer this question,\nconsider a Bernoulli trial, for example,\na coin-toss experiment or \npicking letters from a two-letter alphabet like Morse code.\nIf the letters were equally probable as in our earlier example,\nthe entropy would be,\n\\[\n% - \\left(P(\\mathbf{-}) \\log P(\\mathbf{-}) \n% + P(\\mathbf{\\cdot}) \\log (\\mathbf{\\cdot})\\right)\n H = - \\left(0.5 \\times \\log_{2} 0.5 + 0.5 \\times \\log_{2} 0.5 \\right)\n = - \\log_{2} 0.5 = 1.\n\\]\nSo, the entropy of a Bernoulli random variable with equal probabilities ($p = 0.5$),\nsuch as outcome of a fair coin toss, is \\num{1} bit.\nWe can also calculate the entropy with non-equal probability values.\nFor example, entropy of a Bernoulli random variable with $p=0.8$,\n\\[\n% - \\left(P(\\mathbf{-}) \\log P(\\mathbf{-}) \n% + P(\\mathbf{\\cdot}) \\log (\\mathbf{\\cdot})\\right)\n H = - \\left(0.8 \\times \\log_{2} 0.8 + 0.2 \\times \\log_{2} 0.2 \\right)\n = \\num{0.7219281} .\n\\]\nNote that the entropy reduced from 1 bit to \\num{0.7219281} bits.\nThis should all be intuitive,\nsince knowing that some of the outcomes are more likely than others reduces\nthe average surprisal.\nIf we do the above calculations for the parameter of Bernoulli distribution\n$p$ in range $[0, 1]$,\nwe get the graph in Figure~\\ref{fig:bernoulli-entropy}.\nIf the outcome of the variable is certain with $p = 1$ or $p = 0$,\nthen the entropy is \\num{0},\nand the entropy peaks at \\num[round-precision=1]{0.5},\nwith a value of \\num{1} bit,\nwhere the uncertainty is at its maximum.\n\nIn general, uniform distribution is the distribution\nwith the maximum entropy\nfor distributions with the same support\n(the set of values/events the distribution is defined on).\nIf the number of outcomes increase,\nthe uncertainty and the entropy will increase.\nAnd, as the distribution diverges from the uniform distribution\nby assigning higher probabilities to a small set of events,\nthe entropy will decrease.\nFigure~\\ref{fig:entropy-demo} demonstrates these two factors\nwith the categorical distribution.\n\n\\begin{figure}\n \\tikzset{external/export next=false}\n %\\tikzsetnextfilename{entropy-viz1}\n \\begin{tikzpicture}[x=1mm,y=1mm]\n \\newcounter{x}\n \\newcounter{y}\n \\def\\xstep{22}\n \\def\\r{8mm}\n \\draw[fill=blue!20] (\\thex,\\they) circle[radius=\\r];\n\n \\addtocounter{x}{\\xstep}\n \\filldraw[fill=green!20!white, draw=green!50!black]\n (\\thex,0) ++(0:\\r) arc[start angle=0, end angle=180, radius=\\r] -- cycle;\n \\filldraw[fill=blue!20!white, draw=green!50!black]\n (\\thex,0) ++(180:\\r) arc[start angle=180, end angle=360, radius=\\r] -- cycle;\n\n \\addtocounter{x}{\\xstep}\n \\filldraw[fill=green!20!white, draw=green!50!black]\n (\\thex,0) ++(0:\\r) arc[start angle=0, end angle=90, radius=\\r] -- (\\thex,0) -- cycle;\n \\filldraw[fill=blue!20!white, draw=green!50!black]\n (\\thex,0) ++(90:\\r) arc[start angle=90, end angle=180, radius=\\r] -- (\\thex,0) --cycle;\n \\filldraw[fill=red!20!white, draw=green!50!black]\n (\\thex,0) ++(180:\\r) arc[start angle=180, end angle=270, radius=\\r] -- (\\thex,0) --cycle;\n \\filldraw[fill=gray!20!white, draw=green!50!black]\n (\\thex,0) ++(270:\\r) arc[start angle=270, end angle=360, radius=\\r] -- (\\thex,0) --cycle;\n\n \\addtocounter{x}{\\xstep}\n \\filldraw[fill=green!20!white, draw=green!50!black]\n (\\thex,\\they) ++(0:\\r) arc[start angle=0, end angle=60, radius=\\r] -- (\\thex,\\they) -- cycle;\n \\filldraw[fill=blue!20!white, draw=green!50!black]\n (\\thex,\\they) ++(60:\\r) arc[start angle=60, end angle=120, radius=\\r] -- (\\thex,\\they) --cycle;\n \\filldraw[fill=red!20!white, draw=green!50!black]\n (\\thex,\\they) ++(120:\\r) arc[start angle=120, end angle=280, radius=\\r] -- (\\thex,\\they) --cycle;\n \\filldraw[fill=gray!20!white, draw=green!50!black]\n (\\thex,\\they) ++(180:\\r) arc[start angle=180, end angle=360, radius=\\r] -- (\\thex,\\they) --cycle;\n\n \\addtocounter{x}{\\xstep}\n \\filldraw[fill=green!20!white, draw=green!50!black]\n (\\thex,\\they) ++(0:\\r) arc[start angle=0, end angle=30, radius=\\r] -- (\\thex,\\they) -- cycle;\n \\filldraw[fill=blue!20!white, draw=green!50!black]\n (\\thex,\\they) ++(30:\\r) arc[start angle=30, end angle=60, radius=\\r] -- (\\thex,\\they) --cycle;\n \\filldraw[fill=red!20!white, draw=green!50!black]\n (\\thex,\\they) ++(60:\\r) arc[start angle=60, end angle=90, radius=\\r] -- (\\thex,\\they) --cycle;\n \\filldraw[fill=gray!20!white, draw=green!50!black]\n (\\thex,\\they) ++(90:\\r) arc[start angle=90, end angle=360, radius=\\r] -- (\\thex,\\they) --cycle;\n\n\n \\foreach[count=\\i, evaluate=\\i as \\x using int((\\i-1)*\\xstep)] \\v in {0,1,2,1.79,1.06}{%\n \\node[anchor=north] at (\\x,-10) {$H = \\v$};\n }\n \\end{tikzpicture}\n \\caption{\n Demonstration of entropy values (in bits)\n with the categorical distribution.\n First three circles from the left represent\n uniform categorical distributions with increasing number of categories.\n Increasing possible outcomes increase the uncertainty, hence the entropy.\n Last three circles demonstrate categorical distributions with equal\n number of possible outcomes.\n As the distribution diverge from the uniform distribution,\n the uncertainty and entropy is reduced.\n }\\label{fig:entropy-demo}%\n\\end{figure}\n\nBy now,\nyou should be able to calculate the entropy of a categorical distribution\nover \\num{8} symbols,\njust like the letters in Table~\\ref{tbl:binary-code-example}.\nGiven that these letters are distributed uniformly\n(each having probability of $1/8$),\nthe entropy of the distribution is \\num{3} bits,\nwhich corresponds to how many bits we need for optimally coding the alphabet.\nWe noted that we can do better if the distribution was not uniform.\nLet us assume that,\nthe letter `a' occurs with probability $1/2$,\nthe letter `b' occurs with probability $1/4$,\nthe letter `c' occurs with probability $1/8$,\nthe letter `d' occurs with probability $1/16$,\nand the other letters occur with probability $1/64$.\nNow, using trhee bits for all comibinations is just wasteful.\nWe can do much better with the codes on Table~\\ref{tbl:huffman-code-example}.\nThe type of coding example here is called \\emph{Huffmann} coding.\nAlthough the number of bits are variable,\nwe can unabiguously determine each code with its prefix.\nOne can easily show that this coding requires less storage or channel bandwidth\non average.\nIn fact,\nthis corresponds to the entropy of the distribution,\nwhich is \\num{2} bits:\nwe save \\num{1} bit on average.\nThis is exactly another way to interpret entropy,\nit is the average code-length for the best achievable code\nfor a given distribution.\nIn other words,\nentropy gives us the upper bound on\nan optimal encoder (in terms of efficient channel utilization)\nin a noisy channel model (Figure~\\ref{fig:noisy-channel}).\n\\begin{margintable}\n \\caption{\\label{tbl:huffman-code-example}\n Example Huffman coding of an eight letter alphabet.\n }\n \\begin{center}\n \\begin{tabular}{lrl}\n \\toprule\n letter & prob &{code} \\\\\n \\midrule\n a & $1/2$& \\num{0} \\\\\n b & $1/4$& \\num{10} \\\\\n c & $1/8$& \\num{110} \\\\\n d & $1/16$& \\num{1110} \\\\\n e & $1/64$& \\num{111100} \\\\\n f & $1/64$& \\num{111101} \\\\\n g & $1/64$& \\num{111110} \\\\\n h & $1/64$& \\num{111111} \\\\\n \\bottomrule\n \\end{tabular}\n \\end{center}\n\\end{margintable}\n\n\n% \\begin{margintable}\n% \\caption{\\label{tbl:cond-prob-table}%\n% Conditional probabilities of $P(\\text{letter}\\:\\vert\\:\\text{dialect})$.\n% }\n% \\begin{center}\n% \\setlength{\\tabcolsep}{4pt}\n% \\begin{tabular}{lS[round-precision=3]S[round-precision=3]S[round-precision=3]}\n% \\toprule\n% let. & {east} & {north} & {south} \\\\\n% \\midrule\n% a & 0.2829786& 0.0326985& 0.283765\\\\\n% b & 0.0413973& 0.0624915& 0.009443\\\\\n% c & 0.0363760& 0.0465435& 0.116444\\\\\n% d & 0.0892564& 0.0738920& 0.068607\\\\\n% e & 0.2458984& 0.4862595& 0.165408\\\\\n% f & 0.0241540& 0.0131360& 0.067122\\\\\n% g & 0.0720066& 0.0647505& 0.000000\\\\\n% h & 0.2079327& 0.2202285& 0.289211\\\\\n% \\bottomrule\n% \\end{tabular}\n% \\end{center}\n% \\end{margintable}\n\\begin{margintable}\n \\caption{\\label{tbl:marginal-prob-table2}%\n Joint probability table for letters and dialects\n with marginal probabilities.\n $P(D)$ is the (marginal) probability of dialects,\n and $P(L)$ is the probability of letters in the corpus.\n This is the same as Table~\\ref{tbl:marginal-prob-table},\n repeated here for convenience.\n }\n \\begin{center}\n \\setlength{\\tabcolsep}{4pt}\n \\begin{tabular}{lS[round-precision=2]S[round-precision=2]S[round-precision=2]|S[round-precision=2]}\n \\toprule\n let. & {east} & {north} & {south} & {$P(L)$} \\\\\n \\midrule\n a & 0.1980850&0.0065397&0.0283765 & 0.2330012\\\\\n b & 0.0289781&0.0124983&0.0009443 & 0.0424207\\\\\n c & 0.0254632&0.0093087&0.0116444 & 0.0464163\\\\\n d & 0.0624795&0.0147784&0.0068607 & 0.0841186\\\\\n e & 0.1721289&0.0972519&0.0165408 & 0.2859216\\\\\n f & 0.0169078&0.0026272&0.0067122 & 0.0262472\\\\\n g & 0.0504046&0.0129501&0.0 & 0.0633547\\\\\n h & 0.1455529&0.0440457&0.0289211 & 0.2185197\\\\\n \\midrule\n $P(D)$ & 0.7&0.2&0.1 & 1.0\\\\\n \\bottomrule\n \\end{tabular}\n \\end{center}\n\\end{margintable}\nTo give a more concrete example,\nwe re-introduce our dialects with eight letters from Chapter~\\ref{chap:prob}.\nTable~\\ref{tbl:marginal-prob-table2} lists the joint probabilities of \nletters and dialects (east, north and south),\nas well as marginal probabilities.\nFrom this table,\nwe can easily calculate the entropy of the distributions of letters for the \ncomplete language,\nand the entropy of the letter distribution for each dialect.\nNow you should take a moment and try to phrase\nwhat high or low entropy means for letters or dialects.\nFor the sake of making things more concrete,\nwe will calculate the entropy of dialect distribution in our document set.\nThe entropy of letter distribution over dialects\n\\[\n H(d) = -\\left(0.7 \\times log_{2} 0.7 + 0.2 \\times log_{2} 0.2 + 0.1 \\times log_{2} 0.1\\right)\n = \\num{1.15678}\n\\]\nis lower than a uniform distribution of letters over the dialects\nwhich is \\num{1.584963}.\nIn other words,\nby knowing $P(D)$, we gain \\num{0.428183} bits of information,\nin comparison to a setting where the dialects were equally represented\nin the data.\nThe distribution over individual letters is more interesting,\nyou are encouraged to calculate the entropy of letters ($P(L)$)\nand compare it with a uniform distribution.\nNote that if you want to calculate entropy of letters within each dilaect,\nyou need conditional probabilities, e.g., $P(L\\given{}D=\\text{east})$,\nfor calculating letter-entropy values of individual dialects.\n%\\todo{exercise}\n\n\\begin{tcolorbox}\n Note that entropy is about complete probability distributions,\n while surprisal is about probabilities of individual events.\n\\end{tcolorbox}\n\n\\section{Mutual Information and conditional entropy}\n\nAnother very important quantity from information theory used \nwidely in computational and corpus linguistics is \\emph{mutual information}.\nMutual information measures\nthe amount of information obtained (reduced entropy) about a random variable,\nby knowledge of another random variable.\nMutual information is a measure of dependence between two variables.\nIf the variables are dependent (provide information about each other),\nthen the mutual information will be high.\nIf the variables are independent the mutual information will be \\num{0}.\n\nAs we did with introduction to entropy,\nwe will first introduce another relevant measure,\n\\emph{pointwise mutual information} (PMI),\nwhich measures the (in)dependence of two events.\nThe PMI value for two events\n$X = x$ (or simply $x$) and $Y = y$ (or $y$) is calculated by\n\\begin{equation}\\label{eq:pmi}\n \\text{PMI}(x, y) = \\log \\frac{P(x,y)}{P(x)P(y)}\n\\end{equation}\nA quick study of the formula indicates\nthat pointwise mutual information is high\nif the joint probability of the two events involved is high.\nHowever,\nsince the high-probability events can cooccur by chance frequently,\nthe denominator of the term in Equation~\\ref{eq:pmi} includes\n(marginal) probabilities of both events.\nHence, it discounts the by-chance cooccurrences of the events\ndue to high marginal probability.\nRemember that the joint probability of two independent events is\nthe product of their probabilities ($P(x,y) = P(x) P(y)$,\nfor independent events $x$ and $y$).\nAs a result,\nthe division within the logarithm in Equation~\\ref{eq:pmi} will result in \\num{1},\nand PMI will be \\num{0}, for independent events.\nIf two events are highly positively associated (they occur together),\nthen PMI will be positive,\nand if events are highly negatively associated\n(one does not occur if the other event occurs),\nthen the PMI value will be negative.\n\nJust for the sake of example,\nwe will calculate the PMI of letter `e' occurring in the `east' dialect\nin the distribution presented in Table~\\ref{tbl:marginal-prob-table2}.\n\\[\n \\text{PMI}(\\text{east},\\text{e})\n = log \\frac{P(\\text{east}, \\text{e})}{P(\\text{east})P(\\text{e})}\n = log \\frac{\\num{0.1721289}}{\\num{0.7}\\times \\num{0.2859216}}\n = \\num{-0.2175571}\n\\]\nDespite the fact that the joint probability of the two events is rather high,\nwe find a negative association between them%\n---in `e', in fact, occurs less than chance in the eastern dialect.\n\nOne of the most common uses of PMI is to find \\emph{collocations},\ngroups of words that occur frequently together.\nUsing PMI,\nit is likely to find linguistically plausible collocations like,\n`corpus linguistics',\neven though it is much less likely than non-interesting frequent bigrams like `that the'.\n\nThe \\emph{mutual information} (MI) of two random variables\nis a measure of dependence of the variables.\nMutual information is the expected value of (average) PMI.\nThe mutual information of two discrete random variables $X$ and $Y$ is\n\\begin{equation}\\label{eq:mi}\n \\text{MI}(X, Y) \n = \\sum_{x\\in X} \\sum_{y\\in Y} P(x,y) \\log \\frac{P(x,y)}{P(x)P(y)} .\n\\end{equation}\n\nSimilar to PMI,\na positive MI value indicates a positive association between\nthe random variables,\nzero indicates independence (no association),\nand negative values indicate negative association.\nLike \\emph{correlation} (Section~\\ref{sec:correlation}),\nmutual information measures dependence between two random variables.\nHowever, unlike correlation, it is not limited to linear dependence.\n\nMutual information is related to entropy\nthrough a measure known as \\emph{conditional entropy}.\nWe note the conditional entropy of a random variable $X$ given\nanother random variable $Y$ takes the value $y$ as $H(X\\given{}Y=y)$.\nIntuitively,\nif the event $Y=y$ gives information about the random variable $X$,\nwe expect low conditional entropy.\nThe conditional entropy of $X$ given $Y$,\nnoted $H(X\\given{}Y)$,\nis the average entropy of $X$ given $Y$.\nThe conditional entropy of $X$ given $Y$ can be calculated by\n\\begin{equation}\\label{eq:conditional-entropy}\n \\begin{aligned}\n H(X\\given{}Y) &= & &\\sum_{y\\in Y} P(y) H(X\\given{}Y=y)\\\\\n &= &- & \\sum_{x\\in X, y\\in Y} P(x,y) \\log P(x\\given{}y)\n \\text{.\\footnotemark}\\\\\n \\end{aligned}\n\\end{equation}%\n\\footnotetext{You are recommended to derive this equation.\n Meanwhile, you may also want to show that\n \\[ \n H(X\\given{}Y) = \\sum_{x\\in X, y\\in Y} P(x,y) \\log \\frac{P(y)}{P(x,y)}\n \\]\n is also correct.\n}\n\nThe conditional entropy has also a straightforward interpretation.\nThe conditional entropy $H(X\\given{}Y)$ equals to\nthe entropy of the variable $X$ ($H(X)$),\nif the variables are independent.\nAs the dependence between variables increase,\nthe conditional entropy will decrease.\n\n\n\\begin{marginfigure}\n \\tikzsetnextfilename{entropy-mi-relation}\n \\begin{tikzpicture}\n% \\draw[help lines] (0,0) grid (5,5);\n \\node[draw,circle,minimum size=3.5cm,inner sep=0pt,fill=blue,opacity=0.2]\n at (2,2) {};\n \\node[draw,circle,minimum size=3.5cm,inner sep=0pt,fill=red,opacity=0.2]\n at (3,3) {};\n \\node at (0.7,3.7) {$H(X)$};\n \\node at (4.3,1.3) {$H(Y)$};\n \n \\node at (1.3, 1.5) {$H(X\\given{}Y)$};\n \\node at (3.7, 3.5) {$H(Y\\given{}X)$};\n\n \\node at (2.5, 2.5) {$MI(X,Y)$};\n\n \\node at (3.5, 0) {$H(X,Y)$};\n \\end{tikzpicture}\n \\caption{\\label{fig:entropy-mi}%\n Relation between conditional entropy entropy and mutual information.\n The total shaded area is the joint entropy of two variables $H(X,Y)$.\n }\n\\end{marginfigure}\n\nNote that entropy, conditional entropy, and mutual information are all related.\nFigure~\\ref{fig:entropy-mi} shows the relationship between these measures\nschematically using a Venn diagram.\nFor example, we can see from the figure that $H(X,Y) = H(X) + H(Y) - MI(X,Y)$.\nThe total entropy associated with two random variables is reduced if the \nmutual information (dependence) between them is high.\nIf one of the variables ($Y$) completely determines the other ($Y$),\nthe conditional entropy ($H(X|Y)$) will be \\num{0},\nthe joint entropy will be equal to the entropy of one one of the variables\n($H(Y)$),\nand mutual information will be equal to entropy of the other variable $H(X)$.\nThe mutual information is symmetric ($MI(X,Y) = MI(Y,X)$),\nwhile conditional entropy is not ($H(X\\given{}Y) \\ne H(Y\\given{}X)$). \nAlso note that the relationships\nbetween the information theoretic measures are additive,\nwhile the relationship between the corresponding probabilities are multiplicative.\n\n\\section{Cross entropy}\n\n\\emph{Cross entropy} is another important concept from information theory\nthat has wide usage, particularly in machine learning.\nRemember that entropy gives us the best achievable compression\ngiven a distribution.\nIn many practical cases we do not know the true distribution of the data,\ninstead we use an approximate one.\nIf we do not use the true distribution,\ninevitably, our code will be less optimum.\nThis means that we will get higher entropy.\nIf the true distribution is $P(x)$ and the its approximation is $\\hat{P}(x)$,\nthe cross entropy is defined as\n\\begin{equation}\n H(P, \\hat{P}) = - \\sum_{x} P(x) log \\hat{P}(x) .\n\\end{equation}\nThe hat-notation used here is used for estimated objects.\nIf $P$ was the true distribution,\nwe would note an estimation of it as $\\hat{P}$.\nAlthough this is most common context we will see cross entropy used,\nthe distribution $\\hat{P}$ does not have to be an estimate of $P$.\nTechnically, the only requirement is\nthat the distribution should have the same support.\nNote that the notation $H(X, Y)$ is also used for joint entropy,\nbut for joint entropy the arguments are random variables\nnoted like $X$ and $Y$,\nand for cross entropy distribution functions\nnoted with letters like $P$ and $Q$.\n\nThe formula above makes sense if you think about it\nin terms of the noisy channel model.\nRemember that we are coding the data using $\\hat{P}$,\nhence the code length is determined by the approximate model.\nHowever, the average is taken over the true distribution,\nhence, we multiply by $P(x)$ not $\\hat{P}(x)$.\nCross entropy is always larger than entropy.\nSince we are using the wrong (approximate) distribution to code the data,\nthe code length will not be optimum.\nAs $\\hat{P}$ gets closer to the $P$,\nthe cross entropy will approach the entropy of $P$.\nNote that cross entropy is not symmetric ($H(P, Q) \\ne H(Q, P)$).\n\nA very common use of cross entropy is as a \\emph{loss function}\nin some machine learning methods.\nIn many machine learning methods,\ntraining the model is equivalent to minimizing a loss function.\nHence,\nas we minimize cross entropy of true distribution\nthat comes from the training data\nand the approximate distribution the machine learning system produces,\nwe get closer to the true distribution of the answers we are seeking.\nThat way,\nthe output of the machine learning model becomes\nmore similar to the expected output.\nWe will see example uses of cross entropy later in this course.\n\n\\begin{margintable}\n \\caption{\\label{tbl:east-overall}%\n Probability distributions of letters in our hypothetical dialect data.\n $P(L\\given{}D=\\text{east})$ is the distribution of letters\n given the dialect is east dialect,\n $P(L)$ is the marginal distribution of letters (for all dialects).\n }\n \\begin{center}\n \\setlength{\\tabcolsep}{4pt}\n \\begin{tabular}{lS[round-precision=2]S[round-precision=2]}\n \\toprule\n let. & {$P(L\\given{}\\text{east})$} & {$P(L)$} \\\\\n \\midrule\n a & 0.2829786 & 0.2330012\\\\\n b & 0.0413973 & 0.0424207\\\\\n c & 0.0363760 & 0.0464163\\\\\n d & 0.0892564 & 0.0841186\\\\\n e & 0.2458984 & 0.2859216\\\\\n f & 0.0241540 & 0.0262472\\\\\n g & 0.0720066 & 0.0633547\\\\\n h & 0.2079327 & 0.2185197\\\\\n \\bottomrule\n \\end{tabular}\n \\end{center}\n\\end{margintable}\nFor a concrete example,\nwe return to the hypothetical dialects with \\num{8}-letter alphabets\nin Table~\\ref{tbl:marginal-prob-table2}.\nAssume that we do not know the distribution of the letters\nin the eastern dialect,\nand we are using the total distribution\nfor coding (e.g., compressing) the data from the eastern dialect.\nBoth distributions are summarized in Table~\\ref{tbl:east-overall}.\nWe simply calculate cross entropy by \n\\[\n \\begin{aligned}\n H\\left(P(L\\given{}\\text{east}), P(L)\\right) \n = - \\sum_{x\\in \\text{letters}} P(x\\given{}\\text{east}) \\log_{2} P(x)\n = \\num[round-precision=3]{2.577201} .\n \\end{aligned}\n\\]\nAs expected,\nthis is larger than entropy of $P(L\\given{}\\text{east})$,\nwhich is \\num[round-precision=3]{2.562475} bits.\n\n\\section{Perplexity}\n\nA measure related to entropy,\nused often in computational linguistic literature,\nis \\emph{perplexity} (PP).\nPerplexity is simply the exponentiated version of entropy.\nIf we measure entropy in bits, then the perplexity is\n\\begin{equation*}\n \\text{PP}(X) = 2^{H(X)} .\n\\end{equation*}\n\nLike entropy, perplexity measures uncertainty.\nHowever, since it measures it in a different scale,\nsometime it offers a more intuitive interpretation.\nIts main use in NLP is evaluating language models,\nwhich are conditional distributions on words given a history of earlier words.\nIn this context, the intuitive interpretation is\nthe average number of words expected after each word.\n\n\\section{Kullback--Leibler divergence}\n\n\\begin{marginfigure}\n \\tikzsetnextfilename{kl-divergence-viz}\n \\begin{tikzpicture}[\n declare function={%\n normpdf(\\x,\\m,\\s) = exp(-(\\x -\\m)^2/(2*\\s)^2) /%\n (\\s*(2*pi)^0.5);%\n }\n ]\n \\begin{axis}[\n axis lines=middle,\n hide y axis,\n enlargelimits=true,\n samples=50,\n x=4mm,\n y=70mm,\n ymin=0,\n clip=false,\n x axis line style={<->}\n ]\n \\addplot[smooth, thick, blue, domain=-6:6,name path=curve1]\n {normpdf(x,-0.5,1)};\n \\addplot[smooth, thick, red, domain=-6:6,name path=curve2]\n {normpdf(x,0.5,1.2)};\n \\addplot[draw=none, domain=-6:6,name path=xax] {0};\n \\addplot[blue,opacity=0.2]\n fill between[of=curve1 and xax,soft clip={domain=-5:5}];\n \\addplot[red,opacity=0.2]\n fill between[of=curve2 and xax,soft clip={domain=-5:5}];\n \\node[blue] at (-4.2, 0.1) {$P$};\n \\node[red] at (3.8, 0.1) {$Q$};\n \\node (a) at (2, 0.15) {};\n \\node (kpq) at (4, 0.3) {$D_{KL}(P\\;\\Vert\\;Q)$};\n \\draw[->] (a) -- (kpq);\n\n \\node (b) at (-1.6, 0.18) {};\n \\node (kqp) at (-4, 0.3) {$D_{KL}(Q\\;\\Vert\\;P)$};\n \\draw[->] (b) -- (kqp);\n \\end{axis}\n \\end{tikzpicture}\n \\caption{\\label{fig:kl-diverngence}%\n Visualization of KL divergences between two distributions.\n Note, however, this is a demonstration to show the asymmetry\n of measure, the areas indicated are not exactly what\n KL-divergence measures.\n }\n\\end{marginfigure}\nAnother important quantity we often see during this course is\n\\emph{Kullback-Leibler divergence} which is also known as\n\\emph{relative entropy}.\nIt is often abbreviated as \\emph{KL divergence}.\nSimilar to cross entropy,\nKL divergence is a about two probability distributions with the same support.\nIt measures the amount of information lost,\nor extra bits of entropy,\nwhile using a distribution $Q$ instead of using the true distribution $P$.\nIt is defined as,\n\\begin{equation}\\label{eq:kl-divergence}\n D_{KL} (P\\;\\Vert\\;Q) = - \\sum_{x} P(x) \\log \\frac{P(x)}{Q(x)}.\n\\end{equation}\nIt is the average logarithmic difference\nbetween distributions $P$ and $Q$,%\n\\footnote{%\n Remember that \n \\[\n \\log \\frac{a}{b} = \\log(a) - \\log(b) .\n \\]\n}\nwhere average calculated according to $P$.\nKL divergence is often used as a measure of difference\nbetween two distributions.\nHowever, it is not symmetric\n(as a result, it is not a proper distance measure).\nFigure~\\ref{fig:kl-diverngence} visualizes the KL divergence\nbetween two continuous distributions.\nFor continuous distributions,\nas usual,\nyou can simply replace probability mass functions\nwith probability density functions, \nand summation with the integral in Equation~\\ref{eq:kl-divergence}.\n\nFor a concrete example,\nwe will return to the question of using an approximate distribution,\nthe marginal letter distribution,\ninstead of one of the conditional distributions\nin our letter distribution example in Table~\\ref{tbl:east-overall}.\nAs in our cross entropy example,\nassume that we do not know the distribution of the eastern dialect,\nand approximating it with the marginal distribution.\nIf we do the calculation,\n\\[\n D_{KL} \\left(P(L\\given{}\\text{east})\\;\\Vert\\;P(L)\\right) = - \\sum_{x} P(x|\\text{east}) \\log \\frac{P(x|east)}{P(x)}\n = \\num[round-precision=3]{0.0147261}\n\\]\nwhich is the amount of information we lose by using the marginal distribution\ninstead of the dialect-specific distribution in bits.\n\nConceptually,\nyou should already be expecting a link between \nthe cross entropy and the KL divergence divergence.\nCross entropy measures the entropy of a distribution ($P$) under \nanother distribution ($Q$),\nwhile KL divergence measures the amount of additional entropy if one uses one distribution ($Q$) instead of another ($P$).\nAs a result,\n\\[\n H(P, Q) = H(P) + D_{KL}(P\\;\\Vert\\;Q).\n\\]\n\nYou can easily verify this\nwith our running example of dialect letter distributions as well\n(maybe with some rounding error).\n\n% \\section*{Where to go from here}\n% \n% \\textcite{mackay2003}\n% \n% \\textcite{pierce1980}\n% \n% \\textcite{stone2015}\n% \n% \\textcite{ghahramani2003}\n% \n% \\textcite{shannon1948}\n% \n% \\textcite{seife2007}\n% \n% \\section*{Exercises}\n% \n% % \\begin{question}\n% What is the name of the following measure?\n% \\[\n% \\log \\frac{P(x\\given{}y)}{P(x)}\n% \\]\n% \\end{question}\n\n% p = c(0.2829786, 0.0413973, 0.0363760, 0.0892564, 0.2458984, 0.0241540, 0.0720066, 0.2079327)\n% q = c(0.2330012, 0.0424207, 0.0464163, 0.0841186, 0.2859216, 0.0262472, 0.0633547, 0.2185197)\n", "meta": {"hexsha": "e91fa05f12f531b5919e42e47181a58d63898814", "size": 39554, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "information-theory.tex", "max_stars_repo_name": "coltekin/snlp-notes", "max_stars_repo_head_hexsha": "02dddcda0a8ff24f959675f0ad6a9079d573f49b", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-08-05T12:58:44.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-21T14:17:47.000Z", "max_issues_repo_path": "information-theory.tex", "max_issues_repo_name": "coltekin/snlp-notes", "max_issues_repo_head_hexsha": "02dddcda0a8ff24f959675f0ad6a9079d573f49b", "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": "information-theory.tex", "max_forks_repo_name": "coltekin/snlp-notes", "max_forks_repo_head_hexsha": "02dddcda0a8ff24f959675f0ad6a9079d573f49b", "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.4024514811, "max_line_length": 122, "alphanum_fraction": 0.7119381099, "num_tokens": 11162, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.39606816627404173, "lm_q2_score": 0.4493926344647597, "lm_q1q2_score": 0.1779901166695181}}
{"text": "\\documentclass[12pt]{article}\n\\usepackage[utf8]{inputenc}\n\\usepackage[english]{babel}\n\\usepackage{amsmath}\n\\usepackage{amsfonts}\n\\usepackage{amssymb}\n\\usepackage{bbm}\n\\usepackage{tikz}\n\\usepackage{mathtools}\n\\usepackage{subfigure}\n\\usepackage[hang]{footmisc}\n\n\\setlength{\\footnotemargin}{2.5mm}\n\\usetikzlibrary{shapes,automata,arrows}\n\\graphicspath{{images/}{../images/}}\n\\setcounter{tocdepth}{1}\n\n\\newcommand{\\transpose}[1]{#1^{\\mathsf{T}}}\n\\newcommand{\\inverse}[1]{#1^{-1}}\n\\newcommand{\\iterate}[2]{#1^{(#2)}}\n\\newcommand{\\parens}[1]{ \\left( #1 \\right) }\n\\newcommand{\\prob}{\\mathbb{P}}\n\\newcommand{\\dee}{\\mathrm{d}}\n\\renewcommand{\\thesubtable}{\\Roman{subtable}}\n\\DeclareMathOperator{\\rank}{rank}\n\\DeclareMathOperator{\\Null}{null}\n\\DeclarePairedDelimiterX{\\norm}[1]{\\lVert}{\\rVert}{#1}\n\\DeclarePairedDelimiter{\\abs}{\\lvert}{\\rvert}\n\n\\title{Exploring PageRank}\n\\author{Nathanael Gentry}\n\\date{30 April 2019}\n\n\\begin{document}\n\\maketitle\n\n\n\n\\section{Motivation}\nIn 1995, the public Internet contained about 2.5 million pages\n\\cite{TotalNumberWebsites}, but search techniques relied upon classical\nstrategies for collections much smaller and less interconnected than the nascent\nInternet. By 1998, two Stanford students -- Sergey Brin and Larry Page --\nendeavored to bring order to the Web. The students’ graduate project, then hosted at\n\\texttt{google.stanford.edu}, did not rely on simple heuristics like URL length\nor date of publication; their program used the link structure of the Web itself\nto decide how relevant a page was to a user's query. Brin and Page thus defined\ntheir problem as a problem of spectral ranking, or eigencentrality. Spectral\nranking provides a tractable definition of an entity's relative\n\\textit{importance} within a collection and thus gives an excellent heuristic\nfor its relevance in a search query. In this paper, we explore the foundation of\nthe Google enterprise: PageRank, the algorithm that provides a spectral ranking\nof all pages on the indexed Web.\n\n\n\n\\section{First Steps}\n\\begin{figure}[h]\n \\centering \\scalebox{0.75}{\\begin{tikzpicture}[\n\t\t\tscale=0.6,\n > = stealth,\n\t\t\tshorten > = 1pt,\n\t\t\tauto,\n\t\t\tnode distance = 3cm,\n\t\t\tsemithick]\n\t\t\t\\tikzstyle{every state}=[\n\t\t\tdraw = black,\n\t\t\tthick,\n\t\t\tfill = white,\n\t\t\tminimum size = 4mm]\n\n\t\t\t\\node[state] (a) {$p_1$};\n\t\t\t\\node[state] (b) [above right of=a] {$p_2$};\n\t\t\t\\node[state] (c) [right of=a] {$p_3$};\n\t\t\t\\node[state] (d) [below right of=a] {$p_4$};\n\t\t\t\\node[state] (e) [right of=c] {$p_5$};\n\n\t\t\t\\path[->] (a) edge node {} (b);\n\t\t\t\\path[->] (a) edge node {} (d);\n\t\t\t\\path[->] (a) edge node {} (c);\n\t\t\t\\path[->] (c) edge node {} (b);\n\t\t\t\\path[->] (d) edge node {} (c);\n\t\t\t\\path[->] (e) edge node {} (b);\n\t\t\t\\path[->] (b) edge [bend left=45] node {} (e);\n\t\t\t\\path[->] (d) edge node {} (b);\n\t\t\t\\path[->] (e) edge node {} (c);\n\t\t\t\\path[->] (d) edge node {} (e);\n\t\t\\end{tikzpicture}}\n \\caption{A Miniscule Web}\n \\label{fig:web}\n\\end{figure}\nConsider a digraph $\\mathcal{W}$, such as that given in Figure \\ref{fig:web}.\nEach vertex $p$ represents a Web page, and each edge represents the existence of\nat least one hyperlink between pages $p_i$ and $p_j$. We seek to calculate the\nimportance of a Web page, and we can view a hyperlink to that page as an\nendorsement of importance from the linking page. The more such votes of support\na page has, the more important it probably is. The votes of importance imparted\nby a Web page should be distributed evenly across the pages it endorses. Let us\nnow formalize this intuition. Let $N^-_i$ represent the set of $p_i$'s\npredecessors, and let $N^+_i$ represent the set of $p_i$'s successors. Note that\n$|N^+_i|$ gives the out-degree of $p_i$. We thus define the importance score\n$\\pi_i$ of a page $p_i$:\n\\begin{equation}\\label{eqn:pi_i}\n \\pi_i = \\sum_{p_j\\in N^-_i}{\\frac{\\pi_j}{|N^+_i|}}.\n\\end{equation}\n\nEquation \\eqref{eqn:pi_i} gives an impredicative definition of an importance\nscore.\\footnote{Logicians disagree about the distinction between\n \\textit{recursion} and \\textit{impredicativity}. In this paper, we take\n recursion to be constructive -- that is, recursion builds a class by feeding\n the results of a generator into itself. Impredicativity, however, defines an\n impredicative object $X$ as an instantiation of a class which itself contains\n $X$. Equation \\eqref{eqn:pi_i} thus gives an impredicative definition of\n $\\pi_i$.} We store all the $\\pi_i$ in a vector $\\pi$, which we take henceforth\nas a row vector.\\footnote{Some authors denote row vectors by transposing a\n column vector every time, but we have found this notation wearying. In this\n paper the probability distribution $\\pi$ will always be given by a row vector,\n without indication of transposition.} Take some initial score vector\n$\\iterate{\\pi}{0}$, say a uniform distribution $\\pi = [1/|\\mathcal{W}|]$. Then,\nwe define an iterative calculation for an iterator $t\\geq 1$ to refine the\ninitial distribution:\n\n\\begin{equation}\n \\label{eqn:pi_t}\n \\iterate{\\pi}{t+1}_i = \\sum_{p_j\\in N^-_i}{\\frac{\\iterate{\\pi}{t}_j}{|N^+_i|}}.\n\\end{equation}\nWe encode the system given by Equation \\eqref{eqn:pi_i} over $\\mathcal{W}$ in a hyperlink matrix:\n\\begin{equation*}\n H(\\mathcal{W})_{ij}=\\begin{cases}\n 1/|N^+_i|, & \\text{if } p_i \\in N^-_j; \\\\\n 0, & \\text{otherwise}.\n \\end{cases}\n\\end{equation*}\n\nThus, we have the following iterative calculation:\n\\begin{equation}\n \\iterate{\\pi}{k+1} = \\iterate{\\pi}{k} H.\n\\end{equation}\nThe hyperlink matrix gives an adjacency matrix of $\\mathcal{W}$ modified to\nensure that each nonzero row provides a probability distribution. By\nconstruction, $H$ is nonnegative; that is, $H_{ij}\\geq 0$ for all components.\n\\begin{figure}[t!]\n \\centering\n \\begin{subfigure}\n \\centering\n $\\begin{bmatrix}\n 0 & 1/3 & 1/3 & 1/3 & 0 \\\\\n 0 & 0 & 0 & 0 & 1 \\\\\n 0 & 1 & 0 & 0 & 0 \\\\\n 0 & 1/3 & 1/3 & 0 & 1/3 \\\\\n 0 & 1/2 & 1/2 & 0 & 0\n \\end{bmatrix}$\n \\caption{Hyperlink Matrix for Figure \\ref{fig:web}}\n \\label{fig:hyperlink}\n \\end{subfigure}\n \\vspace{2em}\n \\begin{subfigure}\n \\centering\n \\begin{tabular}{|c||c|c|c|c|c|}\n \\hline\n $k$ & $\\pi_1$ & $\\pi_2$ & $\\pi_3$ & $\\pi_4$ & $\\pi_5$ \\\\\n \\hline\\hline\n 0 & 0.2 & 0.2 & 0.2 & 0.2 & 0.2 \\\\\n 1 & 0 & 0.433 & 0.233 & 0.067 & 0.267 \\\\\n 2 & 0 & 0.389 & 0.156 & 0 & 0.456 \\\\\n 3 & 0 & 0.383 & 0.228 & 0 & 0.390 \\\\\n 4 & 0 & 0.422 & 0.194 & 0 & 0.383 \\\\\n \\hline\n \\end{tabular}\n \\caption{Score Iteration for Figure \\ref{fig:web}}\n \\label{fig:example_calculation}\n \\end{subfigure}\n\\end{figure}\n\nFigures \\ref{fig:hyperlink} and \\ref{fig:example_calculation} show the\nhyperlink matrix and some iterative calculations for the digraph given in\nFigure \\ref{fig:web}. We simply rank the pages by the distribution given in\n$\\pi$.\n\nObserve that $p_2$ has the highest rank, as most other pages point into it\nand it only links to one page. However, this page $p_5$ also receives a high\nscore, since an important page directly links to it. Our na{\\\"i}ve approach\nshuts out $p_1$ and $p_4$ entirely, which destroys the uniqueness of the\nranking. There are other problems with our formulation. Note that the zero\nrows of $H$ correspond to dangling pages, i.e. vertices with zero\nout-degree. These rank sinks will break our current calculation, but we\ncannot simply exclude them. Some sinks -- for instance, published PDF\ndocuments -- might be highly cited and quite important. Consider also the\ntrouble posed by cyclic graphs, which would eternally shift their importance\naround their cycles. If we continued the iterative calculation in Figure\n\\ref{fig:example_calculation}, we would find the scores of $p_2$ and $p_5$\nkeep oscillating as the number of iterations grew. We will discuss the\nproblem of cyclicity later, but we easily fix can rank sinks by making $H$\nfully row-stochastic.\n\n\n\n\\section{Markov Chains}\n\n\n\\subsection{Stochasticity}\nConsider a vector $d$, where $d_i=1$ if page $p_i$ dangles and $d_i=0$\notherwise. Let $v$ be a distribution over all pages in a Web graph\n$\\mathcal{W}$. We stochasticize $H$ thusly:\n\\begin{equation}\n \\label{eqn:S}\n S=H + d\\transpose{v}.\n\\end{equation}\n\nIf an ideal ``random surfer'' on the Web hits a dangling page, it chooses based\nupon the distribution $v$ what page to next visit. Let $\\mathbbm{1}$ represent a\nvector of ones, and note that the row-stochasticity of $S$ implies\n$\\Vert S \\Vert_{\\infty} = 1$, i.e. $S \\mathbbm{1} = \\mathbbm{1}$. Thus,\n$(1, \\mathbbm{1})$ provides a right eigenpair for every stochastic matrix. Now\nconsider an eigenpair $(v, \\lambda)$ of a stochastic matrix $S$ and suppose\n$|\\lambda| > 1$. Then, the vector given by $|\\lambda|^n v = S^n v$ grows\nexponentially, so at least one $(S^n)_{ij} > 1$ for some $n$. This, however,\ncontradicts the stochasticity of $S$. Thus, we conclude that $|\\lambda| \\leq 1$,\nand since we have already 1 as an eigenvalue, we conclude the spectral radius\n$\\rho(S)=1$. This result can be proved directly from the Gershgorin circle\ntheorem, but we will not explore that here.\n\n\n\\subsection{Transition Probability}\nAs noted above, we can view $S_{ij}$ as the probability that a random surfer on\na Web jumps from page $p_i$ to page $p_j$ at a given time. Thus, we can model\nour spectral ranking problem as a Markov chain. In this conversation, we\nconsider homogeneous Markov chains -- those that have transition probabilities\nindependent of time. This probabalistic insight leads us to view $S$ as the\n1-transition matrix of a finite-state, discrete-time Markov chain. Recall that a\ndiscrete-time stochastic process $\\{X_t\\}_{t \\in T}$ for a countable set $T$\nover a finite $n$-sized state space $\\Omega = \\{s_i\\}_{i\\leq n}$ is a Markov chain if, for\neach $t$, the Markov property holds. Markov chains are colloquially described by\n\\textit{memorylessness}, which the Markov property formalizes:\n\\begin{equation*}\n \\prob(X_{t+1} = s_j \\mid X_t = s_{i_t}, X_{t-1} = s_{i_{t-1}},\\cdots, X_0 =\ns_{i_0}) = \\prob(X_{t+1} = s_j \\mid X_t=s_{i_{t}}).\n\\end{equation*}\nWe encode the $k$-step transition probabilities for a homogeneous Markov chain\nin a stochastic matrix of dimension $|\\Omega| \\times |\\Omega|$:\n\\begin{equation}\n \\iterate{P}{k} = [ \\iterate{p}{k}_{ij} ] = [ \\prob(X_{t+k} = s_j \\mid X_t =\ns_i) ] = [ \\prob(X_{t} = s_j \\mid X_0 = s_i) ].\n\\end{equation}\nNote how the memorylessness of the Markov chain enables the powerful final\nequality above. By the definition of the transition matrix, we see\n$ [ \\iterate{p}{1}_{ij} ] = P$. Now, suppose inductively that\n$\\iterate{p}{\\ell}_{ij} = \\parens{\\iterate{P}{\\ell}}_{ij}$ for all\n$i, j \\in \\Omega$. Then, observe the following:\n\\begin{align*}\n \\iterate{p}{1+\\ell}_{ij} &= \\prob(X_{\\ell+1} = s_j \\mid X_0 = s_i) \\\\\n &= \\sum_{s_k\\in\\Omega}{\\prob(X_1 = s_k \\mid X_0 = s_i) \\prob(X_{1+\\ell} = s_j \\mid\n X_1 = s_k)} && \\text{(total probability)} \\\\\n &= \\sum_{s_k\\in\\Omega}{\\prob(X_1 = s_k \\mid X_0 = s_i) \\prob(X_{\\ell} = s_j \\mid X_0 = s_k)} &&\n \\text{(homogeneity)} \\\\\n &= \\sum_{k\\leq\n |\\Omega|}{\\parens{\\iterate{p}{1}_{ik}\\iterate{p}{\\ell}_{kj}}}\n && \\text{(definition of transition matrix)}\\\\\n &= p^{1+\\ell}_{ij}. && \\text{(matrix multiplication)}\n\\end{align*}\nFrom this result, we derive the Chapman-Kolmogorov equations:\n\\begin{equation}\n \\iterate{p}{m+n}_{ij} = \\sum_{k\\leq |\\Omega|}{\\parens{\\iterate{p}{n}_{ik} \\iterate{p}{m}_{kj}}}.\n\\end{equation}\n\nWe will denote the $k$-step transition probability from state $s_i$ to $s_j$ by\ndirectly referencing the components of the transition matrix. Since Markov\nchains are memoryless, we simply take each successive iteration as if it were\nthe first; in this way, we understand that iteration of transitions is given by\nmatrix multiplication in a homogenous chain. Recall that $k$-paths of graphs are\nalso given by the $k^\\text{th}$ power of the adjacency matrix.\n\nWith this in mind, consider a distribution $\\iterate{v}{\\ell}$ over $\\Omega$,\ndefined by $\\iterate{v}{\\ell}_i = \\prob(X_\\ell = i)$. Then, by the total law of\nprobability, we calculate the following:\n\\begin{align*}\n \\iterate{v}{\\ell}_i &= \\sum_{s_k\\in\\Omega}{\\prob(X_0 = s_k) \\prob(x_\\ell = s_i \\mid X_0 = s_k)} \\\\\n &= \\sum_{k\\leq |\\Omega|}{\\parens{\\iterate{v}{0}_k \\iterate{p}{\\ell}_{ki}}}.\n\\end{align*}\n\nFrom these results, we conclude that\n$\\iterate{v}{\\ell} = \\iterate{v}{0} \\iterate{P}{\\ell} = \\iterate{v}{0} P^\\ell$,\nfor some initial iterate $\\iterate{v}{0}$. We have now more clearly justified\nthe construction of equation \\eqref{eqn:pi_t}.\n\n\n\\subsection{Stationarity}\nWe may take the stochastic process $\\{X_t\\}_{t \\in T}$ underlying a Markov chain\nas a categorical distribution over $\\mathcal{S}$, the state space.\\footnote{The\n categorical (multinoulli) distribution is a generalization of the Bernoulli\n distribution, where each random variable may take one of $k$ states.} A chain\ndistribution $\\pi$ gives a simplex of dimension $|S| - 1$. Choose such a\n$P$-invariant simplex. By Brouwer's fixed point theorem, within this simplex\nmust be a $P$-invariant distribution, i.e., a\n$P$-eigenvector.\\footnote{Brower's fixed point theorem leads to an elegeant\n argument for Perron's theorem of positive matrices. Michael Brin -- Sergey's\n father -- first advanced such topological arguments for Perron-Frobenius\n theory in 1993. We encourage the reader to consult\n \\cite{boyleBasicPerronFrobeniusTheory} for more details. \\vspace{0.5em} \\\\\n Note further that the simplexical argument for the stationary distribution is\n interesting but not at all constructive. We can, in fact, construct an exact\n definition of $\\pi$ from the expected number of visits to each state in a\n positive recurrent chain. See \\cite{freedmanConvergenceTheoremFinite} for an\n excellent summary of these probabalistic arguments. In this paper, we take a\n linear-algebraic approach to convergence via the Perron-Frobenius theorem. In\n hindsight, we see that our route of exposition might have been the messier\n option. However, since Google determines PageRank through power iteration on\n the transition matrix, our conversation shows more clearly how PageRank works\n in the real world.} We denote this fixed distribution $\\pi$ such that\n$\\pi P = \\pi$. That is, $\\pi_i = \\prob(X_t = s_i)$ for all $t\\in T$ over all\nstates. This time independence defines the stationarity of a distribution $\\pi$,\nand it thus gives an eigenequation for spectral analysis. Consider a stationary\ndistribution $\\pi$ that is also a limiting distribution, so that we have the\nfollowing:\n\\begin{equation*}\n \\pi = \\lim_{k\\to\\infty}{{\\iterate{\\pi}{k}}} = \\lim_{k\\to\\infty}{\\parens{{\\iterate{\\pi}{0}} P^k}}.\n\\end{equation*}\n\nIn a Markov chain with a limiting distribution, any initial distribution\n$\\iterate{\\pi}{0}$ will eventually converge upon $\\pi$. However, a stationary\ndistribution does not itself imply a limiting distribution. For instance,\nconsider the Markov chain given by\n$P=\\begin{bsmallmatrix} 0 & 1 \\\\ 1 & 0 \\end{bsmallmatrix}$. This standard\nexample corresponds to turning a coin over, so the opposite state is reached\nwith certainty at each step. However, the probability of revealing a certain\nface at a given step depends entirely upon the initial state -- what face of the\ncoin was initially facing up. Thus, this chain does not have a limiting\ndistribution. However, we have an easy stationary distribution:\n$v = [\\frac{1}{2}, \\frac{1}{2}]$, corresponding to choosing the initial state by\nflipping a fair coin. The stationary distribution hides the chain's dependence\nupon its initial state. However, if we have a biased coin, say one for which\n$\\iterate{v}{0} = [\\frac{3}{5}, \\frac{4}{5}]$, the transition probabilities at\neach turn of the coin clearly depend upon the initial state of the coin.\n\nWe can also show that no limiting distribution exists by examining the\ntransition matrix. As $k\\to\\infty$, the iterate $\\iterate{P}{k}$ swaps certainty\nof transition between states; it alternates between $P$ and $I$. Thus, the limit\nof the transition matrix does not exist, and so a limiting distribution does not\nexist.\n\nThe nature of our spectral ranking problem thus becomes stunningly clear, for\nthe time-independent probabilities within $\\pi$ yield a unique metric of the\nimportance we have sought to codify. We can predict, from the structure of the\nWeb itself, how much time a random Web surfer will spend on a given page, and we\ncan take these probabilities as evidence for how important a page actually is.\nAnalyzing the asymptopic behavior of $P$ will show us when such a limiting\ndistribution exists, and we will thus know when we have a unique solution to the\nstationary eigenequation. We now answer the vital question of when a Markov\nchain has such distribution by exploring a fundamental theory of dynamical\nsystems.\n\n\n\n\n\\section{Perron-Frobenius Theory}\n\n\n\\subsection{Irreducibility}\nIn a Markov chain, states $s_i$ and $s_j$ communicate if\n$\\iterate{P}{k}_{ij} > 0$, for some iterate $k$. That is, there is a path of\nnonzero probability (a random walk) between states $s_i$ and $s_j$.\nCommunicativity is easily shown to be an equivalence relation.\n\nConsider partitioning a Markov state space $\\Omega$ of size $n$ into partitions\n$\\Omega_1 = \\{ s_i \\}_{i\\leq k}$ and $\\Omega_2 = \\{ s_j \\}_{k < j \\leq n}$.\nMoreover, suppose there are random walks from $\\Omega_2$ to $\\Omega_1$ but none\nthe other way. Note that the chain eventually never visits states in $\\Omega_2$;\nwhen $\\Omega_1$ is a communicating class, the chain reduces to the states of\n$\\Omega_1$. We model such reducibility of a Markov chain in a lower-triangular\ncanonical form:\n\\begin{equation*}\n \\label{eqn:reducible}\n P =\n \\begin{bmatrix}\n \\omega_{1\\to 1} & 0 \\\\\n \\omega_{2 \\to 1} & \\omega_{2 \\to 2}\n \\end{bmatrix},\n\\end{equation*}\nwhere $\\omega_{1\\to 1}$ and $\\omega_{2\\to 2}$ are substochastic square matrices\nrepresenting transition probabilities within $\\Omega_1$ and $\\Omega_2$,\nrespectively, and $\\omega_{2 \\to 1}$ holds the transition probabilities from\n$\\Omega_2$ to $\\Omega_1$. Note that when $\\omega_{2\\to 1} = 0$, the chain is\ndisconnected and so \\textit{completely} reducible.\n\nWe say a Markov chain is irreducible if and only if it contains a single\ncommunicating class. Equivalently, a digraph is irreducible when it has no\nstrongly connected components (SCCs) smaller than itself.\\footnote{Note that a\n topological sort on a reducible graph can factorize it into its disjoint\n strongly-connected components.} An irreducible matrix is a matrix\ncorresponding to such irreducible objects. Note that an irreducible matrix is\nnonnegative; the transition matrix motivation above shows the classes of\nreducibility and irreducibility arise through the arrangement of zeroes within\nthe matrix. To find reducbility in a chain-graph, we simply attempt to permute\nthe state-vertices in the underlying matrix to obtain the above canonical form.\n\nConsider further what reducibility means in a Markov chain. As time passes, the\nprobability of visiting the pages in $\\Omega_2$ drops to zero. To our iterative\nimportance calculation on Web pages, these pages will eventually appear not at\nall important, but there is no reason why they shouldn't be. We must not permit\nthis artifact of the Web structure to corrupt our importance scores. For now, we\ntake reducibility of a Markov chain as a hypothetical difficulty; later, we will\nsee that the real Web is quite reducible and requires a less naïve model to give\nconvergent and unique importance scores.\n\n\n\\subsection{Periodicity}\nConsider a Markov chain with states $s_i \\in \\mathcal{S}$. Let\n$D(s_i) = \\{n\\in \\mathbb{Z}_{\\geq 0} : \\iterate{p}{n}_{ii} > 0 \\} \\subset\n\\mathbb{N}$. Note that $D(s_i)$ is trivially nonempty, as\n$\\iterate{p}{0}_{ii} = 1$ for all $s_i$. We observe that $D(s_i)$ forms a\nnumerical semigroup under addition. We define the period of a state by\n$d(s_i)=\\text{gcd}\\{D(s_i)\\}$. In other words, a random walk (a path where each\nstep has nonzero probability) from state $s_i$ can only return to $s_i$ in\nmultiples of $d(s_i)$ steps. Consider states $s_i$ and $s_j$ in the same\ncommunicating class. Thus, $\\iterate{p}{m}_{ij} > 0$ and\n$\\iterate{p}{n}_{ji} > 0$ for some nonnegative iterators. Otherwise stated,\nconsider a random $m$-path from $s_i$ to $s_j$ and a a random $n$-path from\n$s_j$ to $s_i$.\n\\begin{figure}[h]\n \\centering \\scalebox{0.75}{\\begin{tikzpicture}[\n\t\t\tscale=0.6,\n > = stealth,\n\t\t\tshorten > = 1pt,\n\t\t\tauto,\n\t\t\tnode distance = 3cm,\n\t\t\tsemithick]\n\n\t\t\t\\tikzstyle{every state}=[\n\t\t\tdraw = black,\n\t\t\tthick,\n\t\t\tfill = white,\n\t\t\tminimum size = 4mm]\n\n\t\t\t\\node[state] (a) {$s_i$};\n\t\t\t\\node[state] (b) [right of=a] {$s_j$};\n\n\t\t\t\\path[->] (a) edge [bend left=45] node {$m$-step} (b)\n (a) edge [loop above] node {$\\ell$-step} (a)\n (b) edge [bend left=45] node {$n$-step} (a);\n\t\t\\end{tikzpicture}}\n \\caption{Communicating States}\n \\label{fig:markov}\n\\end{figure}\n\nFigure \\ref{fig:markov} illustrates these cycles. Note that there are random\ncycles of length $\\ell \\equiv m+n \\pmod{d(s_i)}$ on state $s_i$. The\ncommunicativity of $s_i$ and $s_j$ implies $\\iterate{p}{n+m}_{jj} > 0$ and\n$\\iterate{p}{n + \\ell + m}_{jj} > 0$. That is, there is a random $\\ell$-cycle on\n$s_j$; moreover, there is a random cycle on $s_j$ that goes from $s_j$ to $s_i$\nand returns to $s_i$ before terminating at $s_j$. Thus, $d(s_j) \\mid \\ell$.\nHowever, since we have shown that $s_i$ has a random $\\ell$-cycle, we know that\n$d(s_j) \\mid d(s_i)$. By the symmetry of $s_i$ and $s_j$, we find\n$d(s_i) \\mid d(s_j)$, and so $d(s_i) = d(s_j)$ whenever $s_i$ and $s_j$\ncommunicate. Thus, when $P$ is irreducible, $d(P)$ is well-defined; every state\nhas the same period. When $d(P) = 1$, we say the Markov chain is aperiodic.\n\n\n\\subsection{Primitivity}\nMuch has been said on the conditional convergence of periodic Markov chains, but\nwe confine this conversation to the aperiodic case. Suppose we have an aperiodic\nirreducible Markov chain, and recall $D(s_i)$, the numerical semigroup given\nabove.\\footnote{Markovian semigroups form an important part of ergodic theory,\n which we barely explore here.} For a semigroup $V$ with $d=\\gcd(V)$, it can be\nshown that there exists an integer $N$ such that $v\\equiv n \\pmod{d}$ for any\n$v\\in V$ and all $n \\geq N$. Since we have supposed an aperiodic Markov chain,\nwe have a coprime numerical semigroup. Thus, there is some bound $t_i$ beyond\nwhich $\\iterate{p}{t}_{ii} > 0$ for all $t \\geq t_i$ over all states. By the\nirreducibility of the chain, we have a $k = k_{(i,j)}$ for which\n$\\iterate{p}{k}_{ij} > 0$. Thus, for $t \\geq t_i + k$, the Chapman-Kolmogorov\nequations yield the following:\n\\begin{align*}\n \\iterate{p}{t}_{ij} \\geq \\iterate{p}{t-k}_{ii} \\iterate{P}{k}_{ij} > 0.\n\\end{align*}\nLet $t'_i = t_i + \\max_{j\\in\\Omega}\\{ k_{(i,j)} \\}$. Thus, for $t \\geq t'_i$, we\nhave $\\iterate{p}{t}_{xy} > 0$ for all $y\\in\\Omega$. Then, for\n$t \\geq \\max_{i\\in\\Omega}\\{ t'_i \\}$, we conclude that, for an irreducible\naperiodic chain, there is a $t$ that gives $\\iterate{p}{t}_{ij} > 0$ over all\nstates, and so $P^t > 0$. We take this result as the definition of matrix\nprimitivity.\n\nPrimitivity is irreducibility plus aperiodicity. Recall that a merely\nirreducible Markov chain requires an iterate-function of state pairs. However, a\nprimitive chain guarantees that \\textit{all} states communicate -- not just that\nthey are a part of the same communicating class -- after $t$ transitions.\n\nConsider a primitive Markov chain with eigenpair $(v, \\lambda)$. The underlying\nprimitivity of the transition matrix $P$ gives $P^k v = \\lambda^k v > 0$ for\nsome iterate $k$ and forever thereafter, so we see the eigenpair must be\npositive. Take another eigenpair $(w, \\gamma)$ such that $\\norm{w} < \\norm{v}$\nand $\\gamma = \\rho(P)$. Then for all iterates $n$, we have the following:\n\\begin{equation*}\n \\gamma^n w = P^n w \\leq P^n v = \\lambda^n v.\n\\end{equation*}\nHowever, since we supposed $\\norm{w} < \\norm{v}$, we cannot have\n$\\beta < \\lambda$. By the inequality above, we must conclude $\\beta = \\lambda$,\nand so a primitive $P$ has only one eigenvalue on its spectral circle, namely\nthe spectral radius itself. This eigenvalue is the dominant eigenvalue of $P$.\nSince all stochastic matrices have spectral radius 1, we conclude that primitive\nMarkov chains have an eigenpair $(1, \\pi)$. This is exactly what we want to\nsatisfy our limiting distribution condition $\\pi = \\pi P$. The following\nspectral properties of primitive Markov chains should not be terribly surprising\nby now, but they are are quite beautiful.\n\n\n\\subsection{Perron-Frobenius Theorem}\nPerron's theorem, proved in 1907, provided spectral properties of positive\nmatrices -- most notably, that such matrices have only one eigenvalue on their\nspectral circle, the dominant eigenvalue $\\lambda_1=\\rho(A)$. However, Perron's\nresults results did not generally apply to nonnegative matrices. Frobenius\nsubsequently realized that irreducible matrices behave like positive matrices,\nexcept that they may have multiple eigenvalues that are roots of unity of\n$d(P)$. Primitive matrices, however, do have a dominant eigenvalue, as we have\nseen above. The Perron-Frobenius theorem, proved in 1912, gives the following\nproperties for a primitive square matrix:\n\\begin{enumerate}\n\\item The spectral radius $\\rho$ equals some real eigenvalue $\\lambda_1$;\n\\item This eigenvalue (the Perron root) is simple, and it is the only eigenvalue on the spectral circle;\n\\item The Perron root has unique, strictly positive left and right eigenvectors (Perron vectors);\n\\item These left and right Perron eigenvectors are, up to normalization, the only nonnegative eigenvectors of $A$.\n\\end{enumerate}\nNote that the Perron root is a dominant eigenvalue; it is the unique $\\lambda_1$\nsuch that $|\\lambda_1|>|\\lambda_2|\\geq\\cdots\\geq |\\lambda_{n}|$ for all\n$\\lambda \\in \\sigma(A)$. Recall that $A$ and $\\transpose{A}$ share a spectrum,\nand a left eigenvector of $A$ is a right eigenvector of $\\transpose{A}$.\n\nWe will not prove the complete Perron-Frobenius theorem in this paper -- its\nfull statement contains far more than we have given here -- although we have\nheretofore outlined some basic arguments for the properties we find useful for\nspectral ranking.\n\n\n\n\n\\section{Limiting Distributions}\n\n\n\\subsection{Spectral Resolution\\protect\\footnote{The results in this section\n summarize the extended treatment of matrix functions and convergence given\n in \\cite{meyerMatrixAnalysisApplied2000}}.}\nRecall that, for a a diagonalizable matrix $A=PD\\inverse{P}$, the columns of the\nsimilarity transformation $P$ correspond to distinct right eigenvectors of $A$.\nConsider partitioning $P$ into bases $\\beta_{\\mathcal{E}_\\lambda}$ for distinct\nright eigenspaces of $A$. Similarly, we partition the rows of $\\inverse{P}$ into\nbases $\\gamma_{\\mathcal{E}_\\lambda}$ for distinct left eigenspaces. Thus, for a\nmatrix $A$ with with spectrum $\\sigma$, we have an outer product formulation of\nthe spectral decomposition:\n\\begin{equation}\n \\label{eqn:spectral_decomposition}\n A = PD\\inverse{P} = \\sum_{\\lambda\\in\\sigma}{\\lambda [\\beta_{\\mathcal{E}_\\lambda}]\\transpose{[\\gamma_{\\mathcal{E}_\\lambda}]}}.\n\\end{equation}\n\nNote that\n$E_\\lambda =\n[\\beta_{\\mathcal{E}_\\lambda}]\\transpose{[\\gamma_{\\mathcal{E}_\\lambda}]}$\nprojects onto the eigenspace $\\mathcal{E}_\\lambda$. In fact, $A$ is\ndiagonalizable if and only if it can be written as a sum of such spectral\nprojectors. Consider $x$ and $\\transpose{y}$ as the handed eigenvectors of a\nsimple eigenvalue $\\lambda_s$. We see this elegant formula for the corresponding\neigenprojection:\n\\begin{equation}\n \\label{eqn:simple_eigenprojection}\n E_{\\lambda_s} = \\frac{x \\transpose{y}}{\\transpose{y} x},\n\\end{equation}\nwhere the inner product in the denominator comes from normalization to ensure projection properties.\n\n\n\\subsection{Matrix Functions}\nConsider generalizing a scalar function $f$ to be a matrix function. As the\nwell-known matrix exponential illustrates, we often do not define matrix\nfunctions as scalar functions applied entrywise, for we then might lose the nice\nproperties associated with the scalar functions. Using the Taylor expansion of a\nsufficiently-differentiable $f$, we first define such a function about a Jordan\nblock $J_k(\\lambda)$:\n\\begin{equation*}\n f\\big( J_k(\\lambda) \\big)=f(\\lambda)I + f'(\\lambda)(J_k(\\lambda) - \\lambda I) + \\frac{f'(\\lambda)(J_k(\\lambda) - \\lambda I)^2}{2!} + \\cdots.\n\\end{equation*}\nHowever, since $(J_k(\\lambda) - \\lambda I)$ is nilpotent of order $k$, the\nTaylor expansion reduces nicely:\n\\begin{equation}\n \\label{eqn:f_jordan_block}\n f\\big( J_k(\\lambda) \\big) = \\sum_{i=0}^{k - 1}\\parens{\\frac{f^{[i]}(\\lambda)}{i!} (J_k(\\lambda) - \\lambda I)^i}.\n\\end{equation}\n\nThus, for $f$ with at least $(k - 1)$ derivatives that exist at $\\lambda$, we\nhave the definition of a function applied to a Jordan block:\n\\begin{equation}\\label{eq:f_jordan_block}\n f\\big( J_k(\\lambda) \\big) =\n \\begin{bmatrix}\n f(\\lambda) & f'(\\lambda) & \\frac{f''(\\lambda)}{2!} & \\ldots & \\frac{f^{[k - 1]}(\\lambda)}{(k-1)!} \\\\\n 0 & f(\\lambda) & f'(\\lambda) & \\ldots & \\frac{f^{[k - 2]}(\\lambda)}{(k-2)!} \\\\\n 0 & \\vdots & \\vdots & \\ddots & \\vdots \\\\\n 0 & 0 & 0 & \\ldots & f(\\lambda)\n \\end{bmatrix}.\n\\end{equation}\n\nFor a diagonalizable matrix $A$ as above, note that we can we apply Equation\n\\eqref{eqn:spectral_decomposition} to obtain a nice result:\n\\begin{align*}\n f(A) = Pf(D)\\inverse{P} = \\sum_{\\lambda \\in \\sigma}{f(\\lambda) E_\\lambda}.\n\\end{align*}\n\nWe can extend $f$ to a Jordan form $J$ by requiring that $f$ has at least\n$(\\iota - 1)$ derivatives, where $\\iota = \\iota_\\lambda$ is the index of\n$\\lambda$, i.e., the size of the largest $\\lambda$-block. Then, for $A$ with\nspectrum $\\sigma$, not necessarily diagonalizable, we have this function\ndefinition:\n\\begin{equation*}\n f(A) = P f(J) \\inverse{P} = \\sum_{\\lambda \\in \\sigma}\\parens{ [\\beta_{\\mathcal{E}_\\lambda}]\\, f\\big( J_{k_\\lambda}(\\lambda) \\big)\\, \\transpose{[\\gamma_{\\mathcal{E}_\\lambda}]} }.\n\\end{equation*}\nExpanding the definition of the function and applying the eigenprojection gives\nthis form:\n\\begin{equation}\n f(A) = \\sum_{\\lambda \\in \\sigma}\\sum_{j=0}^{\\iota_{\\lambda} - 1}\\parens{ \\frac{f^{[j]}(\\lambda)}{i!} (J_{k_\\lambda}(\\lambda) - \\lambda I)^j E_{\\lambda} }.\n\\end{equation}\n\n\n\\subsection{Matrix Convergence}\nConsider the function $f(x) = x^n$ for some real $n$. Note that when we apply\n$f$ to a Jordan block, we can easily give the coefficients of differentiation as\nbinomial coefficients.\n\\begin{equation}\\label{eq:power_jordan_block}\n \\big( J_k(\\lambda) \\big)^n =\n \\begin{bmatrix}\n \\lambda^n & \\binom{n}{1}(\\lambda^{n-1}) & \\binom{n}{2}(\\lambda^{n-2}) & \\ldots & \\binom{n}{k-1}(\\lambda^{n-(k+1)}) \\\\\n 0 & \\lambda^n & \\binom{n}{1}(\\lambda^{m-1}) & \\ldots & \\binom{n}{k-2}(\\lambda^{m-(k+2)}) \\\\\n 0 & \\vdots & \\vdots & \\ddots & \\vdots \\\\\n 0 & 0 & 0 & \\ldots & \\lambda^n\n \\end{bmatrix}.\n\\end{equation}\nIn general, then, we define $f(A)$ thusly:\n\\begin{equation}\n A^n = \\sum_{\\lambda \\in \\sigma}\\sum_{j=0}^{\\iota_{\\lambda} - 1}\\parens{ \\binom{n}{j} \\lambda^{n-j} (J_{k_\\lambda}(\\lambda) - \\lambda I)^j E_{\\lambda} }.\n\\end{equation}\n\nSuppose $| \\lambda | < 1$. Then, for each $j \\in [1, n-(k+1)]$, we have\n\\begin{equation*}\n \\abs*{\\binom{n}{j}\\lambda^{m-j}} \\leq \\frac{k^j}{j!}{\\abs*{\\lambda^{m-j}}}.\n\\end{equation*}\nNote that as $m \\to \\infty$, the numerator $k^j$ diverges polynomially since $j$\nis fixed. However, since $| \\lambda | < 1$, $\\abs{\\lambda^{m-j}}$ converges to\nzero exponentially. Thus, we conclude the following:\n\\begin{equation*}\n \\lim_{n\\to\\infty}{\\big( J_k(\\lambda) \\big)^n} = 0.\n\\end{equation*}\nWe can extend this argument to show that, for a square matrix $A$,\n$\\lim_{n\\to\\infty}{\\parens{A^n}} = 0$ if and only if $\\rho(A) < 1$, and similar\nreasoning shows the limit does not exist when $\\rho(A) > 1$.\n\nWe now study the convergence of a matrix with $\\rho(A) = 1$, such as we have\nwith all stochastic (and primitive) matrices. Suppose we have a primitive Markov\nchain with transition matrix $P$. By the Perron-Frobenius theorem, we know $P$\nhas dominant eigenvalue $\\lambda_1 = 1$. As all non-dominant eigenvalues have\nmodulus less than 1, we simply have the following:\n\\begin{equation*}\n \\lim_{n\\to\\infty}{A^n} = E_{\\lambda_1}.\n\\end{equation*}\nPowers of a primitive matrix will eventually converge upon the dominant\neigenprojector. For primitive Markov chains, we have a left eigenvector $\\pi$,\nthe stationary distribution. Moreover, we previously showed that all stochastic\nmatrices have right eigenvector $\\mathbbm{1}$. Thus, using the limit we just\ndiscovered, we have a limiting distribution:\n\\begin{equation}\n \\lim_{k\\to\\infty}{{\\iterate{\\pi}{k}}} = \\lim_{k\\to\\infty}{\\parens{{\\iterate{\\pi}{0}} P^k}} = \\iterate{\\pi}{0} \\parens{\\frac{\\mathbbm{1} \\pi}{\\pi \\mathbbm{1}}} = \\parens{\\iterate{\\pi}{0} \\mathbbm{1}} \\pi = \\pi.\n\\end{equation}\nThus, primitivity guarantees a distribution completely independent of the\nchain's starting state. The convergence of a primitive chain is a rather\nremarkable result, one often called the fundamental theorem of Markov chains.\n\n\n\\subsection{Power Iteration}\nApplying Perron-Frobenius theory to primitive Markov chains gives a classical\nmethod for calculating the limiting distribution. Techniques based on Gaussian\nelimination would not be a smart choice for calculating a limiting distribution\n$\\pi$ of the Internet, since this family of alogrithms generally has arithmetic\ncomplexity of order $O(n^3)$.\n\nHere, we explore the power method -- the simplest iterative calculation method.\nSuppose a square matrix $A$ has $n$ eigenpairs $\\{ (\\lambda_i,x_i) \\}_{i\\leq n}$\nwith $\\lambda_1$ as a dominant eigenvalue. Consider a starting vector\n$x^{(0)}=\\sum_i{\\gamma_i x_i}$ for scalars $\\gamma_i$. Then, we again consider\nan iterative calculation:\n\\begin{equation}\n \\iterate{x}{k} = A^k \\iterate{x}{0} = \\sum_{i=1}^{k}{\\gamma_i \\lambda_i^k x_i} = \\lambda_1^k\\parens{\\gamma_1 x_1 + \\sum_{i=2}^{k}{\\gamma_i \\frac{\\lambda_i}{\\lambda_1} x_i}} \\to \\lambda_1^k \\gamma_1 x_1.\n\\end{equation}\nSince $\\lambda_i<\\lambda_1$ for $i>1$, the sum approaches 0 as $k\\to\\infty$. The\nspeed of convergence clearly depends upon the subdominant eigenvalue\n$\\lambda_2$. Power method applications often normalize the the estimated\neigenvector after each iteration to avoid underflow or overflow under successive\npowers of the eigenvalue, but we need not worry about this since primitive\nMarkov chains have dominant eigenvalue $\\lambda_1 = 1$.\n\n\n\n\\section{The Google Matrix}\nDeriving a limiting distribution from the Web graph still requires a bit more\nwork, for the real Web is quite reducible.\n\\begin{figure}\n \\centering\n \\includegraphics[scale=0.6]{bow-tie}\n \\caption{The Bow Tie \\cite{broderGraphStructureWeb}}\n \\label{fig:bow-tie}\n\\end{figure}\nIn 1999, \\cite{broderGraphStructureWeb} crawled over 1.5 billion links to\ngenerate a comprehensive map of the Web. Their macroscopic figure, given in\nFigure \\ref{fig:bow-tie}, stylizes the Web super-graph as a rather eldritch bow\ntie. Note that the figure has the form of a directed acyclic graph given from a\ntopological sort. In the middle is the ``bow knot'' -- the largest\nstrongly-connected component (SCC) of the Web. In 2012, when the last public Web\nmapping occured, about half of mapped Web pages were strongly connected. The\n``thistle ends'' of the tie, denoted \\texttt{IN} and \\texttt{OUT}, respectively\nreference pages from which surfers can link into (out of) the SCC but cannot\nreturn by the same route. Pages within the tendrils and tubes are likewise\nunidirectional on this macroscopic scale: They be reached from \\texttt{IN} and\n\\texttt{OUT}, but these components cannot be reached from within them. Although\nthe numbers in Figure \\ref{fig:bow-tie} are obsolete, its bow-tie model wtill\ndescribes the Web well.\n\nWe previously eliminated individual dangling pages, but we could view these\nentire tendrils and tubes again as ``dangling pages,'' and we can again correct\nfor them. In our Markov discussion, we interpreted the stochastic Web matrix $S$\nas the matrix of probabilities that an ideal random surfer follows links from a\npage or chooses another randomly when it hits a dead end. However,\n\\textit{human} Web surfers often get bored. They will not follow a linear path\nthrough the Web; they might suddenly elect to teleport -- shift course\naltogether and visit a page on whim. Let $\\mathbbm{1}$ represent a vector of\nones, and again consider a distribution $u$ over all Web pages. We model this\nteleportation behavior with a rank-one matrix $T = \\mathbbm{1}\\transpose{u}$.\n\nNow, consider a matrix $G$ formed from a convex combination of $S$ and $T$:\n\\begin{equation}\n \\label{eqn:google_matrix}\n G = \\alpha S + (1-\\alpha)T.\n\\end{equation}\nEvery page now communicates with every other page, and our process is still\nstochastic. In fact, $G$ is trivially primitive, as each page has a random loop.\nIn this model, the random surfer on page $p_i$ follows the Web's link structure\nabout $\\alpha s_i$ percent of the time and teleports with probability\n$(1-\\alpha) u_j$. Note that the teleportation matrix need not give equal\ndeference to each Web page. External factors -- a user's search preferences or\nbrowsing habits or a search engine's fiat against suspected abusers -- can\ninfluence the teleportation probabilities. Here, however, we take a rank-one\ndistribution. The teleportation factor $\\alpha$ dampens the wild, raw Web graph\ninto a more friendly model; it is the damping factor.\n\nNote that the teleportation adjustment provides all we need for a guaranteed\nlimiting distribution, from which we can directly rank pages. In sum, $G$ simply\nrepresents a lazy random walk on the Web graph $\\mathcal{W}$. The matrix $G$ is\nthe Google matrix -- the original foundation of PageRank calculations.\n\nAlthough the primitive Google matrix is completely dense, we can expand $S$ and\n$T$ into their constituent distributions $v$ and $u$ to obtain a power\niteration:\n\\begin{align*}\n \\iterate{\\pi}{k+1} &= \\iterate{\\pi}{k} G\n = \\alpha \\iterate{\\pi}{k} (H + d \\transpose{v}) + (1 - \\alpha) \\iterate{\\pi}{k} (\\mathbbm{1} \\transpose{u}).\n\\end{align*}\n\nNote that the rank-one reduction given above does not require us to actually\ngenerate the dense component matrices $S$ and $G$. Unlike decompositional\nmethods (e.g. UR factorization and GMRES), we do not ruin the sparsity of $H$.\nAs we see above, we must only store the current iterate $\\iterate{\\pi}{k}$ and\nthe dangling page vector $d$ to apply the power method; we do not need $O(n^2)$\nmatrix multiplication. We need only perform vector-matrix multiplication on the\nvery sparse $H$, and sparse multiplications have approximate complexity\n$O(\\eta(H))$, where $\\eta(H)$ is the number of nonzero elements in $H$.\nEmpirical data shows the average Web page has about 10 outgoing links, so\n$\\eta(H) \\approx 10n$.\n\nWhen we apply the power method to a primitive matrix, we have an\nessentially linear algorithm. The power method beats more complex algorithms\nhere because it gives only the simple result we want: the dominant eigenvalue of\na primitive matrix. However, the convergence of a primitive Markov chain depends\nupon how quickly powers of its subdominant eigenvalue converge to zero. We now\nexamine this eigenvalue more closely, and also investigate an optimum value for\n$\\alpha$.\n\n\n\n\\section{Network Topology}\n\\begin{figure}\n \\centering\n \\includegraphics[scale=1.8]{scale-free-network}\n \\caption{A Scale-Free Network (Yeast Proteome) \\cite{wangKineticConformationalCharacterization}}\n \\label{fig:scale-free}\n\\end{figure}\n\n\n\\subsection{Near-Reducibility}\nConsider a Markov chain given by\n$P=\\begin{bsmallmatrix} 1 & 0 \\\\ 0 & 1 \\end{bsmallmatrix}$. The chain is fully\nreducible, and equivalently, the underlying graph is disconnected. Clearly, $P$\nwill only have eigenvalue 1 with multiplicity 2. Suppose now we have a chain\nwith\n$P'=\\begin{bsmallmatrix} 1 - \\epsilon_1 & \\epsilon_1 \\\\ \\epsilon_2 & 1 -\n \\epsilon_2 \\end{bsmallmatrix}$, for $\\epsilon \\in (1,0)$. Thus, the spectrum\n$\\sigma(P') =P' \\{ 1, 1-\\epsilon_1 - \\epsilon_2 \\}$.\n\nNearly-reducible Markov chains have strong interactions within their clusters,\nbut relatively weak interactions between clusters.\\footnote{The formal study of\n clustering in Markov chains is a well-developed field much more clearly\n understood through the probabilistic convergence theorem, which we have\n eschewed in this paper for a linear-algebraic focus. Powerful analysis of\n graph clustering and subdominant eigenvalues can also be done through the\n graph Laplacian, but we will not expound that tool here.} Considering the\ncanonical form of reducibility in Equation \\eqref{eqn:reducible}, we note that\nan irreducible Markov chain with subdominant eigenvalue $\\lambda_2 \\approx 1$\nwill be nearly reducible. However, the existence of such a subdominant\neigenvalue does not itself ensure near-reducibility.\n\n\n\\subsection{Scale-Free Networks}\nIn 1959, Erdős and Rényi proposed generating random graphs by considering a\nPoisson distribution over the out-degree of vertices. In such a random graph\n(also called an exponential network), most nodes share a similar number of\nout-links, and there are very few nodes that deviate from this mean. A random\nnetwork is thus very democratic and has a steep bell curve. Most natural\nnetworks, however, do not follow a random structure.\n\\begin{figure}\n \\centering\n \\includegraphics[scale=0.15]{random-graph}\n \\caption{A Random Graph \\cite{RandomGeometricGraph}}\n \\label{fig:random}\n\\end{figure}\nConsider Figure \\ref{fig:scale-free}, which maps the partial proteome of a\nyeast. The red nodes, which denote proteins most essential for life, tend to\nbind together clusters of proteins of lesser importance. Note our use of the\nterm \\textit{importance} here. If we only had the proteome graph, sans color, we\nwould likely be able to determine which proteins were most ``important'' for\nlife by computing a spectral rank like the PageRank. Indeed, we have assumed\nfrom the start that the most connected nodes are the most important nodes. In\nfact, HITS -- another spectral rank developed at IBM contemporaneously with\nPageRank -- makes the pursuit more explicit by splitting Web pages into hubs and\nauthorities; it uses the more complex heuristic that good hubs link to good\nauthorities and vice versa. In a random graph, however, such a definition of\nimportance breaks down.\n\nA music theorist analyzes a piece of classical music by first determining what\nchords are most important -- that is, what chords are most tonally connected to\nother chords. However, an atonal piece by Schönberg defies such straightforward\nanalysis. A twelve-tone series ensures an equal distribution of tones so no few\ntones or chords distinguish themselves as tonally important, just as a random\ngraph ensures no few nodes stand out.\\footnote{Note that this does not mean\n atonal music is ``random\" in the standard sense; just like an Erdős-Rényi\n random graph, an atonal piece provides little information about the\n connections between tones. Thus, from a tonal perspective, we cannot easily\n determine which chords are more important than others. Tonality concerns\n itself about relations between chords, and these relations are evenly\n distributed by design in a twelve-tone piece. The progressions in such a piece\n mostly sound alike to our tonal ears, except for a few serendipitous ones that\n give a fleeting sense of tonality. This perhaps gives\n insight into why Schönberg abhored the label \\textit{atonal} and much\n preferred to call his music \\textit{pan-tonal}.}\n\nNetworks such as these follow a power law. The probability that a node has $k$\noutlinks is proportional to $1/k^\\gamma$, for some power $\\gamma$. Although most\nnodes have only a few links to others, a few have thousands. Removing just these\nmost important nodes (the hubs) can catastrophically fragment the network into\nits isolated components disrupt the network. These networks also reveal a\nbeautiful fractal structure, so we we call them scale-free networks.\nSociologists have long known of these networks. The Erdős number and the ``six\ndegrees of Kevin Bacon'' work because a few people are highly connected; they\nbridge groups of people who would otherwise be unrelated. Income distribution in\nWestern countries can be similarly modeled with a scale-free network. Note that\nscale-free networks will also be very reducible, as they have strong\ninteractions within their clusters but relatively weak interactions among them.\n\nBoth the physical and logical Internet have been shown to be scale-free\nnetworks. The Internet is thus highly resilient to random attacks, but\ndestroying just about 3\\% of hubs -- the most highly connected ones -- would be\nenough to fragment the Internet into dozens of isolated components\n\\cite{barabasiNetworkScienceScaleFree}. This suggests that even the large SCC of\nFigure \\ref{fig:web} is vulnerable to targeted attacks. By contrast, the\nstrongly-connected components of a random graph would be quite strong, as a\nrandom graph does not encode much information in unique locations.\n\nAs we have seen, only scale-free networks have a sufficiently heterogeneous,\ninformation-rich structure to permit a meaningful spectral importance rank.\nThus, Markov chains over scale-free networks will have a subdominant eigenvalue\nquite close to $\\lambda_1 = 1$. Although the teleportation adjustment ensured\nthe primitivity of the Google matrix, it still tends to leave the dampened Web\nonly weakly irreducible -- that is, nearly reducible.\n\n\n\\subsection{Damping Factor}\nRecall $\\alpha$, the damping factor used in Equation \\eqref{eqn:google_matrix}.\nThis probability $\\alpha$ controls the fidelity of the model to the raw Web\nstructure. As $\\alpha \\to 1$, the Google matrix becomes more nearly reducible,\nits subdominant eigenvalue $\\lambda \\to 1$, and the power method converges ever\nmore slowly. Moreover, as $\\alpha \\to 1$, the limiting distribution becomes far\nmore sensitive -- both in terms of importance score and the consequent PageRanks\n-- to link changes even within minor clusters; further approaching 1 magnifies\nthese effects. We can explore these results more by analyzing the vector\nderivative $\\dee\\pi(\\alpha)/\\dee\\alpha$, but we will not do so here.\n\nWe learn in \\cite{haveliwalaSecondEigenvalueGoogle} that a stochastic matrix $S$\nwith $\\sigma_S = \\{ 1, \\lambda_2, \\lambda_3, \\cdots, \\lambda_n \\}$ gives a\nGoogle matrix with\n$\\sigma_G = \\alpha\\sigma_S = \\{ \\alpha, \\alpha\\lambda_2, \\alpha\\lambda_3,\n\\cdots, \\alpha\\lambda_n \\}$. From this, we see $\\lambda_2 \\leq \\alpha$ for the\nGoogle matrix. Thus, the power method converges at the rate which\n$\\alpha^k \\to 0$ as $k$ grows. With $\\alpha = 0.85$, Google's formulation of the\npower method converges within a thousandth by approximately 50 iterations. Note\nthat the power method scales well to immense datasets like the Web graph -- it\nrequires at most 100 iterations to converge upon a unique ranking all pages on\nthe indexed Web.\n\n\n\n\\section{Evaluation}\nSince PageRank incorporates the entire Web into its calculation, it is\nquery-independent. The refinements given in\n\\cite{haveliwalaAnalyticalComparisonApproaches2003} adapt the stochasticity and\nteleportation distributions to provide a personalized PageRank. Query-dependent\nalgorithms like HITS beat PageRank in personalized searching, as they run a\npower method on small components of the Web. However, the more serious induced\ndeficiencies -- like more imprecise ranking and susceptibility to link spamming\n-- have made PageRank the dominant spectral ranking algorithm on the Web.\nMoreover, the definition of importance built into PageRank means it can predict\nbacklinks (citations) well; Brin and Page \\cite{brinPageRankCitationRanking1998}\nshowed that PageRank determines an optimal path for Web crawlers, who should\nindex the most important parts of the Web quickly and not be trapped by\nclosely-linked local chains.\n\nGoogle still relies heavily upon the traditional vector space relevance models\nand sophisticated analysis of anchor text, font style, and capitalization.\nPageRank, after all, addresses a specific problem of structural relevance; other\nsystems must decide the a page's contextual relevance to a query. PageRank,\nhowever, forms the central part of Google's search strategy -- a system designed\nto scale even to a Web with $10^{100}$ pages -- a \\textit{googol}.\n\n\\newpage\n\\bibliographystyle{ieeetr}\n\\bibliography{references}\n\\end{document}\n", "meta": {"hexsha": "3d26cb468d763a2d5b7d5ca46945fc9e8f3f397b", "size": 48889, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "paper/exploring-pagerank.tex", "max_stars_repo_name": "chopinesque64/exploring-pagerank", "max_stars_repo_head_hexsha": "5026a5d1d76d5c989600ca5202133d8a8c502da3", "max_stars_repo_licenses": ["MIT"], "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/exploring-pagerank.tex", "max_issues_repo_name": "chopinesque64/exploring-pagerank", "max_issues_repo_head_hexsha": "5026a5d1d76d5c989600ca5202133d8a8c502da3", "max_issues_repo_licenses": ["MIT"], "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/exploring-pagerank.tex", "max_forks_repo_name": "chopinesque64/exploring-pagerank", "max_forks_repo_head_hexsha": "5026a5d1d76d5c989600ca5202133d8a8c502da3", "max_forks_repo_licenses": ["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.2877005348, "max_line_length": 211, "alphanum_fraction": 0.7327006075, "num_tokens": 14020, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48047867804790706, "lm_q2_score": 0.37022539259558657, "lm_q1q2_score": 0.17788540721409482}}
{"text": "\\newcommand{\\pKa}{\\text{p}K_{\\text{a}}}\n\\newcommand{\\pKaX}[1]{\\text{p}K_{\\text{a}}^{\\text{#1}}}\n\n\\section{\nConstant-pH Simulations\n\\footnote[1]{\nThe features described in this section were implemented by Brian K. Radak \n (Argonne National Laboratory, Argonne, IL USA) with considerable technical \n support from James C. Phillips (University of Illinois, Urbana, IL USA) and\n Wei Jiang (Argonne National Laboratory).\nThe algorithm draws heavily from earlier work by Yunjie Chen and Beno{\\^i}t\n Roux and later by Donghyuk Suh (University of Chicago, Chicago, IL USA), as\n well as time spent as a postdoctoral scholar at University of Chicago.\nTesting and validation were also aided by Christophe Chipot\n (Universit\\'{e} de Lorraine, Vand{\\oe}uvre-l\\`{e}s-Nancy cedex France and\n University of Illinois).\n}\n}\n\\label{section:constantph}\n\nConstant-pH MD in NAMD is based on the scheme first proposed by\n Stern~\\cite{Stern_JChemPhys_2007_v126_p164112} and later revised and extended\n by Chen and Roux~\\cite{Chen_JChemTheoryComput_2015_v11_p3919}.\nA detailed description of the modifications and improvements made in the NAMD\n implementation has been presented elsewhere by Radak,\n \\textit{et al.}~\\cite{Radak_JChemTheoryComput_2017_v13_p5933} and this is likely the\n best comprehensive description of the method, its uses, and its limitations/pitfalls.\nHerein the goal is to provide a working understanding of how the implementation\n works and what kinds of data it produces.\n\n\\subsection{Overview and Theoretical Background}\n\nConstant-pH MD is a simulation methodology specially formulated for the\n treatment of variable protonation states.\nThis is to be contrasted with conventional force-field based MD simulations,\n which generally treat protonation states by assuming they are fixed.\nConsider, for example, a protein with two titratable residues which may both be\n either protonated or deprotonated (Figure~\\ref{fig:cphStateCycle});\nthe system has four possible protonation states.\nIn the conventional route, the user must enumerate these possibilities,\n construct distinct topologies, and then simulate the cases individually.\nThe simulations for each state must then be connected by either asserting\n knowledge about the system (\\textit{e.g.},~by assuming that only certain\n states are of biological importance) or by performing additional simulations\n to probe transitions between states directly (\\textit{e.g.},~by performing\n free energy calculations).\nIn a constant-pH MD simulation, knowledge of the transformations is not\n assumed and is instead actively explored by interconverting between the\n various protonation states.\nThis is especially useful when the number of protonation states is extremely\n large and/or prior information on the importance of particular states is\n not available.\n\n\\begin{figure}[h]\\center{\n \\includegraphics[width=\\textwidth]{figures/namdcph_cycle}\n \\caption{\\label{fig:cphStateCycle}\n The core difference between conventional and constant-pH MD can be\n illustrated by a simple enzyme $E$ with four protonation states\n describing the occupancy of two titratable residues, $R_1$ and $R_2$.\n A conventional MD simulation handles the states \\emph{separately} (left\n panel).\n The relative importance of the states must be known beforehand or computed\n by other means.\n Conversely, a constant-pH MD simulation handles the states\n \\emph{collectively} and actively simulates interconversion (right panel).\n Determining the relative importance of the states is a direct result of the\n simulation.\n }\n}\\end{figure}\n\nIn formal terms, conventional MD samples from a canonical ensemble, whereas\n constant-pH MD samples from a semi-grand canonical ensemble.\nThe new partition function,\n\\begin{equation}\\label{eqn:semigrand}\n \\Xi(\\text{pH})\n =\n \\sum_{\\text{$\\bm \\lambda$} \\in \\mathcal{S}}\n Q_{\\text{$\\bm \\lambda$}}\n 10^{-n_{\\text{$\\bm \\lambda$}} \\text{pH}},\n\\end{equation}\n is essentially a weighted summation of canonical partition functions,\n $Q_{\\text{$\\bm \\lambda$}}$, each of which are defined by an occupancy vector,\n ${\\bm \\lambda}$.\nThe elements of ${\\bm \\lambda}$ are either one or zero depending on whether a\n given protonation site is or is not occupied, respectively.\nFor a vector of length $m$, the set of all protonation states, $\\mathcal{S}$,\n has at most $2^m$ members.\nIn order to sample from the corresponding semi-grand canonical distribution\n function, a simulation must explore \\emph{both} the phase space defined by\n the canonical paritition functions and the state space defined by the\n different occupancy vectors.\nThe fraction of simulation time spent in each state is dictated by the weights\n in the summation and these depend on the pH and the number of protons,\n $n_{\\text{$\\bm \\lambda$}}$, in the system (\\textit{i.e.},~the sum of the\n elements in ${\\bm \\lambda}$).\n\nAlthough a constant-pH MD system may contain any number of titratable protons,\n the base transformation is always the movement of \\emph{one} proton from a\n molecule into a bath of non-interacting protons ``in solution.''\nFor a generic chemical species A, this corresponds to the usual deprotonation\n reaction definition, except with fixed pH:\n\\begin{equation*}\n \\mathrm{\n HA\n \\underset{\\text{pH fixed}}{\\stackrel{-H^{+}}{\\rightleftharpoons}}\n A^{-}\n }.\n\\end{equation*}\nIn the language of statistical mechanics the species HA and A$^{-}$ refer to\n all terms in Eq.~\\eqref{eqn:semigrand} which do and do not, respectively,\n contain the specific proton in question (\\textit{i.e.},~the particular\n element of ${\\bm \\lambda}$ is one or zero).\nBy taking out a factor of $10^{-\\text{pH}}$, this can be re-written as\n\\begin{equation*}\n \\Xi(\\text{pH})\n =\n \\Xi_{\\text{A}^{-}}(\\text{pH})\n +\n \\Xi_{\\text{HA}}(\\text{pH}) 10^{-\\text{pH}}\n\\end{equation*}\n and then recast as a statistical mechanical analog of the \n Henderson-Hasselbalch equation by recognizing that\n $\\Xi_{\\text{A}^{-}}(\\text{pH}) / \\Xi_{\\text{HA}}(\\text{pH})$ is just the\n ratio of deprotonated / protonated fractions of species A.\nThe \\emph{protonated} fraction is then\n\\begin{equation}\\label{eqn:HH}\n P_{\\text{HA}}(\\text{pH})\n =\n \\frac{1}{1 + 10^{\\text{pH} - \\pKa(\\text{pH})}};\n \\qquad\n \\pKa(\\text{pH})\n \\equiv\n -\\log{\n \\frac{\n \\Xi_{\\text{A}^{-}}(\\text{pH})\n }{\n \\Xi_{\\text{HA}}(\\text{pH})\n }\n }.\n\\end{equation}\nIn practice, $P_{\\text{HA}}(\\text{pH})$ can be calculated from a simulation by\n simply counting the fraction of time spent in state HA (\\textit{e.g.},~the\n fraction of time a specific element of ${\\bm \\lambda}$ is one).\nNote also that $\\pKa(\\text{pH})$ is formally a pH dependent function\n unless the system only contains one proton (or type of proton).\n\nIn most experimental contexts, a different form of Eq.~\\eqref{eqn:HH} is used\n which is often referred to as a ``generalized'' Hill equation.\nThis corresponds to a specific choice of pH dependence such that\n\\begin{equation*}\n \\pKa(\\text{pH})\n \\approx\n \\pKaX{(a)}\n +\n (1 - n)\\left(\\text{pH} - \\pKaX{(a)}\\right).\n\\end{equation*}\nThe constant $n$ is then known as the Hill coefficient and the so-called\n apparent $\\pKa$, $\\pKaX{(a)}$, generally corresponds to the inflection point\n of a plot of $P_{\\text{HA}}(\\text{pH})$.\nBoth quantities are usually determined by non-linear regression after\n $P_{\\text{HA}}$ has been determined at different pH values.\n\n\\subsection{Implementation Details}\n\nIn NAMD, each canonical partition function is represented by a specific force\n field description embodied in a PSF -- in order to change the protonation\n state the underlying PSF must also be modified.\nThis is accomplished by a close coupling to \\texttt{psfgen}.\nThe models that can be used with constant-pH MD are thus limited to only those\n which can be completely implemented within \\texttt{psfgen}.\nThis also means that NAMD requires access to residue topology files (RTFs)\n during the course of a simulation.\nThese must be specified with the \\texttt{psfgen} \\texttt{topology} command.\n\nFor consistency between topological descriptions, NAMD uses ``dummy'' atoms to\n represent non-interacting protons.\nThese atoms have the same mass as protons but only interact with the system\n via a minimal number of force field bonded terms.\nThis formalism guarantees that:\n 1) the number of atoms/coordinates during the simulation remains fixed\n and\n 2) the thermodynamics of the model is unchanged.\nThe latter point is subtle and warrants comment.\nAs implemented in NAMD, constant-pH MD only captures the thermodynamics of\n the semi-grand canonical ensemble.\nThere is no active description of proton dissociation events.\nHowever, this is more of a limitation of classical MD than a particular\n shortcoming of NAMD.\nA useful analogy may be the use of Langevin dynamics as a thermostat as\n opposed to a phenomonological model for Brownian motion.\n\n\\begin{figure}[h]\\center{\n \\includegraphics[width=0.6\\textwidth]{figures/namdcph_nemdmc_scheme}\n \\caption{\\label{fig:namdcph_nemdmc}\n The basic constant-pH MD scheme in NAMD is to alternate equilibrium \n sampling in a fixed protonation state followed by a nonequilibrium MD\n Monte Carlo move to sample other protonation states. \n The latter move can be accepted or rejected.\n If accepted, the simulation continues in the new protonation state.\n If the move is rejected, sampling continues as if the move were never\n attempted at all.\n }\n}\\end{figure}\n\nThe basic scheme in NAMD is to alternately sample the protonation state and\n then the configuration space within that state.\nProtonation state sampling is accomplished by an alchemical coupling scheme\n that forcibly turns off interactions with the current protonation state and\n turns on interactions with a candidate protonation state.\nThis nonequilibrium ``switching'' is accomplished with the alchemy code \n (specifically the thermodynamic integration code branch) and necessarily has\n lower performance (by about 30\\%) than regular MD due to the added\n electrostatic calculations in the reciprocal space (\\textit{i.e.}, when\n using PME).\nHowever, the configuration space sampling should still have normal performance.\nThe switching process exerts work on the system and thus drives the system out\n of equilibrium.\nHowever, an appropriately designed Monte Carlo (MC) move using an accept/reject\n criterion can recover the correct semi-grand canonical equilibrium \n distribution in both the state and configuration\n spaces~\\cite{Nilmeier_ProcNatlAcadSci_2011_v108_pE1009,\n Chen_JChemPhys_2015_v142_p024101}.\nThe resulting scheme is a hybrid nonequilibrium MD/MC (neMD/MC) algorithm.\nThe most important conceptual change from conventional MD is that, rather than\n being a continuous trajectory, the simulation now becomes a series of cycles\n composed of an MD and neMD/MC step.\nThis means that the length of the simulation is no longer simply determined by\n the number of steps (\\texttt{numsteps}) but rather the number of cycles.\nThe length of a cycle is also determined by two parts -- the amount of time on\n equilibrium sampling and the amount of time executing the switch.\n\nIt may be profitable/necessary to vary the switch time depending on the type of\n protonation change that is being effected.\nIndeed, this is a critical factor in the efficiency of the method.\nThat is, if the switch is too short, then moves are unlikely to be accepted and\n effort will be wasted when the move is rejected.\nHowever, if the switch is too long, then an inordinate amount of effort will be\n spent sampling the state space and there will be fewer resources left for\n exploring the configuration space.\nSome basic qualities of the system that affect sampling have been determined\n using nonequilibrium linear response\n theory~\\cite{Radak_JChemPhys_2016_v145_p134109}.\nIn short, there are intrinsic limits based on:\n 1) the extent that differing interactions between each state fluctuate\n (according to some variance, $\\sigma_0^2$)\n and\n 2) the ``molecular'' time scale, $\\tau_{\\text{m}}$, on which these\n fluctuations change.\nThese effects are roughly captured by the\n expression~\\cite{Radak_JChemPhys_2016_v145_p134109,\n Radak_JChemTheoryComput_2017_v13_p5933}:\n\\begin{equation*}\n \\tau_{\\text{opt}}\n \\le\n \\frac{\\sigma_0^2 \\tau_{\\text{m}}}{2.83475},\n\\end{equation*}\n where $\\tau_{\\text{opt}}$ is some optimal switching time, in the sense of\n maximizing the rate at which protonation states interconvert.\nOverall, switching times on the order of tens of picoseconds tend to be optimal\n in that they balance the high cost of switching versus the high acceptance\n rate at longer switching times (in the infinite time limit the perturbation\n is adiabatic and exerts zero work).\nFor titratable groups exposed primarily to aqueous solvent, a switch on the\n order of 10-20~ps appears to give near optimal\n results~\\cite{Radak_JChemPhys_2016_v145_p134109,\n Radak_JChemTheoryComput_2017_v13_p5933}. \nAn equivalent formulation of the above expression is that mean acceptance rates\n around 20-25\\% are likely near optimal.\n\n\\fbox{\n \\begin{minipage}[ht!]{15.3cm}\n \\addtolength{\\baselineskip}{0.225\\baselineskip}\n \\textbf{Important Limitations:}\\\\\n For various reasons concerning the implementation, constant-pH simulations\n are currently \\emph{incompatible} with the following NAMD\n functionalities in all or most situations:\n \\begin{itemize}\n \\item Any system using GPUs/CUDA\n \\item Generalized Born implict solvent (\\texttt{GBIS})\n \\item Alchemical free energy calculations, \\textit{e.g.},~ligand binding\n (\\texttt{alch})\n \\item Drude polarizable force fields\n \\item Hybrid quantum mechanical/molecular mechanical simulations\n \\item Collective variables (\\texttt{colvars})\n \\item \\texttt{extraBonds}\n \\end{itemize}\n This list is neither exhaustive nor definitive.\n In many instances the problem may be overcome by modest additional\n developments. %(see Notes for Developers).\n \\end{minipage}\n}\n\n\\newpage\n\\begin{center}\n \\includegraphics[width=0.9\\textwidth]{figures/namdcph_flowchart}\n\\end{center}\n\n\\newpage\n\\subsection{New Commands and Keywords}\n\nThe constant-pH implementation is largely implemented in Tcl and can be found\n in \\texttt{/lib/namdcph/namdcph.tcl}, where the base directory is the NAMD\n source home directory.\nWhen that file has been loaded with a suitable \\texttt{source} command, the \n following commands and keywords are available and appear to the user in a way\n similar to NAMD syntax.\nThe most significant change from normal NAMD usage is that there is generally\n no need to use the \\texttt{run} command.\nOne should instead use the new \\icommand{{\\tt cphRun}} command;\nthis can only be used \\emph{once} per script for now.\n\\textit{NB}, all commands and keywords are currently case sensitive!\n\\\\[11pt]\n\\noindent\n\\icommand{{\\tt cphRun}} $<$ Run constant-pH MD $>$\n\\\\\n\\textbf{Arguments:} {\\ARG{numsteps} \\OARG{numcycles}}\n\\\\\n\\textbf{Defaults:} {{\\tt numcycles} = 1}\n\\\\\n\\textbf{Description:}\nExecute {\\tt numcycles} cycles of constant-pH MD with the current settings.\nEach cycle consists of 1) a neMD/MC move in both configuration and protonation\n space and 2) MD based sampling in configuration space.\nBy default, configuration space sampling simply consists of {\\tt numsteps}\n dynamics, as in conventional MD.\nThe nature of the neMD/MC moves, however, is more elaborate and controlled by\n other keywords, \\emph{many of which are required} (see below).\n%\\\\[11pt]\n%\\noindent\n%\\icommand{{\\tt testResidue}} $<$ Test a constant-pH residue definition $>$\n%\\\\\n%\\textbf{Arguments:} {\\ARG{resname list} \\OARG{verbose}}\n%\\\\\n%\\textbf{Defaults:} {{\\tt verbose} = 0}\n%\\\\\n%\\textbf{Description:}\n%THIS IS AN ADVANCED OPTION, USE WITH CARE!\n%This is meant to be a convenience command for verifying that RTF, PRM, and\n% configuration file definitions are complete and consistent.\n%The \\texttt{resname list} argument should be a Tcl list containing the names\n% of one or more residue definitions described in the configuration file.\n%Accompanying \\texttt{parameter} and \\texttt{topology} information is also\n% required, as in normal simulations.\n%The command will iterate through all possible protonation state transitions and\n% check that the energy of each state does not depend on the pathway by which\n% it is reached.\n%Setting {\\tt verbose} $\\ne$ 0 will also show decomposition of energy terms\n% (\\textit{e.g.}, ELEC and VDW).\n\n\\subsubsection{Required Keywords}\n\\begin{itemize}\n\\item \\NAMDCONF{pH}\n{pH value that the system is in contact with}\n{decimal (usually between 0 and 14)}\n{\nThe \\KEY{pH} is effectively a chemical potential applied to protons\n \\emph{only}.\nThis value affects the details of neMD/MC moves but otherwise has no effect\n on the system dynamics.\n}\n\n\\item \\NAMDCONF{cphConfigFile}\n{File defining titratable residues}\n{filename}\n{\nThe \\KEY{cphConfigFile} contains definitions for the available titratable \n residues.\nThis is essentially meta information regarding the RTF contents, but also\n includes experimental references and additional force field parameterization.\n}\n\n\\item \\NAMDCONF{cphNumstepsPerSwitch}\n{Number of steps during nonequilibrium switching}\n{\n \\OARG{integer \\OARG{\\ARG{move label} \\ARG{integer}} \\ldots}\n}\n{\nEach move must have an associated number of steps per switch. \nIf an odd number number of arguments is specified, then the first such argument\n is assumed to be a default number for all such moves.\nAfter this (or if an even number of arguments is specified) all remaining\n arguments are assumed to be specific assignments for a given move label\n of the form \\ARG{segid}:\\ARG{resid}:\\ARG{resname}/\\ARG{segid}:\\ARG{resid}:\\ARG{resname}/\\ldots.\n}\n\\end{itemize}\n\n\\subsubsection{Commonly Used Options}\n\\begin{itemize}\n\\item \\NAMDCONF{cphSetResidueState}\n{Set the initial state of one or more titratable residues.}\n{\n\\ARG{segid}:\\ARG{resid}:\\ARG{resname} \\ARG{state} \\OARG{\\ldots}\n}\n{\nInitial residue states can be assigned in three ways (in descending order of \n precedence): 1) via this command, 2) from a \\KEY{cphRestartFile}, and 3)\n randomly from the assigned \\KEY{pH} and the current inherent pKa of each\n residue.\n}\n\n\\item \\NAMDCONF{cphSetResiduepKai}\n{Set the inherent pKa of one or more titratable residues.}\n{\n\\ARG{segid}:\\ARG{resid}:\\ARG{resname} \\ARG{pKai} \\OARG{\\ldots} \n}\n{\nThe two step inherent pKa algorithm implemented here permits on-the-fly update\n of an estimate for the pKa(s) of each residue.\nThese can either be guessed at the outset (the default is to use the reference\n pKa) or updated as the simulation progresses.\nA more accurate estimate of the inherent pKa increases the statistical\n efficiency of the method, but the long time result is formally unbiased\n regardless of the value.\nIf an extremely large or extremely small value is assigned, then the residue\n will be assigned the most probable protonation state at the given pH and\n likely remain fixed in that state.\n}\n\n\\item \\NAMDCONF{cphExcludeResidue}\n{Exclude one or more residues from being titratable}\n{\n\\ARG{segid}:\\ARG{resid}:\\ARG{resname} \\OARG{\\ldots}\n}\n{\nBy default, any residue that matches a titratable residue type will be allowed\n to change protonation state.\nThis command permits specific residues to be excluded from consideration in a\n manner that is similar to assigning an extreme inherent pKa (see\n \\texttt{cphSetResiduepKai}).\nThe main differences are that 1) the protonation state will not be modified and\n remain as it is in the original PSF and 2) the protons in the residue will\n \\emph{not} be tracked in the \\texttt{cphlog} file.\nThis command is not always recommended, but is currently necessary for handling\n disulfide linkages.\n}\n\n\\item \\NAMDCONF{cphRestartFile}\n{Restart file for constant-pH}\n{filename}\n{\nConstant pH requires additional checkpoint information regarding the state of\n the titratable residues and the nature of the neMD/MC moves.\nThis (optional) information is read from the file specified here.\nAfter/during a simulation, this information is written to \n \\KEY{[outputname]}.cphrst.\n}\n\n\\item \\NAMDCONFWDEF{cphRestartFreq}\n{Frequency at which constant-pH checkpoint files are written}\n{Non-negative integer}\n{0}\n{\nCheckpoint information is written to \\KEY{[outputname]}.cphrst every \n \\KEY{cphRestartFreq} cycles (\\emph{not} MD steps).\nA checkpoint file is \\emph{always} written at the end of the last cycle.\n}\n\n\\item \\NAMDCONFWDEF{cphOutFile}\n{Log file for constant-pH}\n{filename}\n{\\KEY{[outputname]}.cphlog}\n{Titratable residue state information is logged here after every cycle.}\n\n\\item \\NAMDCONF{cphProposalWeight}\n{MC move label and weight specifications}\n{\n\\ARG{move label} \\ARG{weight}\n \\OARG{\\OARG{\\ARG{move label} \\ARG{weight}} \\ldots}\n}\n{\nDuring each cycle, MC moves are selected from the move set and then \n accepted/rejected according to a Metropolis criterion based on the combined \n inherent pKa information and pH.\nThe move weight affects the probability that such a move is selected. \nNote that \\emph{this does not affect the probability that any given proposal\n is accepted}, it merely increases the number of attempts at the given\n proposal.\nThis may be useful in a system where one desires specific attention on a given\n process, such as proton transfer or the exchange of a given residue, but one\n does not want to assume that all other residue protonation states are\n nominally fixed.\nBy default all moves are assigned equal weights of 1.0.\nDuring the simulation these are automatically normalized to a discrete\n probability mass function.\n}\n\n\\item \\NAMDCONFWDEF{cphMaxProposalAttempts}\n{Maximum number of switch proposal attempts per cycle}\n{integer}\n{0}\n{\nDuring each cycle, MC moves are selected from the move set and then\n accepted/rejected according to a Metropolis criterion based on the combined\n inherent pKa information and pH.\nThis process stops when either a switch move is accepted or a maximum limit is\n reached.\nAny value less than one defaults to the number of titratable residues in the\n system.\n}\n\n\\item \\NAMDCONFWDEF{cphNumMinSteps}\n{Number of steps of minimization before dynamics}\n{integer}\n{0}\n{\nThis is a replacement for the normal minimize command, which is not compatible\n with constant-pH due to PSF modifications during initialization.\nSetting this option to a modest number (100--200, say) might be necessary when\n randomizing protonation states based on pH, since in that case it cannot be\n assumed that the starting structure is representative of the initial\n protonation state.\n}\n\n\\end{itemize}\n\n\\subsubsection{Specialized Options}\n\\begin{itemize}\n\\item \\NAMDCONFWDEF{cphForceConstant}\n{force constant for alchemical switches (in kcal/mol-\\AA$^2$)}\n{Non-negative decimal}\n{100.0}\n{\nDuring ``dual-topology'' alchemical switches, a harmonic bond is formed between\n analogous atoms in each alchemical region.\nThis rigorously leaves all static thermodynamic quantities intact and is\n generally expected to improve the stability of dynamic quantities.\n}\n\n\\item \\NAMDCONFWDEF{cphMDBasename}\n{basename of intermediate files for equilibrium MD}\n{string}\n{namdcph.md}\n{\nPSF/coordinate modifications are currently done via the file system and utilize \n intermediate files.\nIt may be advantageous to direct this I/O to a fast temporary directory.\n}\n\n\\item \\NAMDCONFWDEF{cphSWBasename}\n{basename of intermediate files for nonequilibrium (switch) MD}\n{string}\n{namdcph.sw}\n{\nPSF/coordinate modifications are currently done via the file system and utilize\n intermediate files.\nIt may be advantageous to direct this I/O to a fast temporary directory.\n}\n\\end{itemize}\n\n\\fbox{\n \\begin{minipage}[ht!]{15.3cm}\n \\addtolength{\\baselineskip}{0.225\\baselineskip}\n \\textbf{Undocumented Features:}\\\\\n The constant-pH code is actively under development, although future work\n will almost exclusively be in adding new features and capabilities as\n well as improving performance.\n Because the code is fairly lightweight and available in \\texttt{Tcl}, the\n intrepid user may discover ``easter egg'' features which are not listed\n in the documentation.\n \\textbf{USE UNDOCUMENTED FEATURES AT YOUR OWN RISK.}\n Such undocumented features may work (and even be advisable) for specific\n problems, but have not undergone as rigorous of testing and may be prone\n to unintended consequences.\n \\end{minipage}\n}\n\n\\subsection{Minimal Examples}\n\nConstant-pH simulations can be carried out with largely the same options as\n conventional MD simulations (with some exceptions, see previous sections).\nThe follwing examples assume that: 1) PSF and PDB files for the\n system of interest have already been constructed and 2) appropriate\n simulation keywords have already been chosen (\\textit{e.g.},~for PME,\n Langevin dynamics, \\textit{etc.}).\n\\begin{verbatim}\n# End conventional settings...\nsource .../namd/lib/namdcph/namdcph.tcl\n# Constant-pH MD requires additional force field files _during_ the simulation.\n# In general, all RTFs used to construct the system need to be included with\n# the ``topology'' command (just as in psfgen). Additional constant-pH specific\n# RTF and PRM files are also necessary, as well as an accompanying\n# configuration file in JSON format.\n#\ncphConfigFile \ntopology \ntopology \npH 7.0\n# The following defaults all nonequilibrium switches to 5000 steps and then\n# increases the time for residue 5 of segid PROA to 7500 steps -- multiple\n# residues can be specified \n#\ncphNumStepsPerSwitch 5000 PROA:5:ASP 7500\n# Run 100 minimization cycles before starting dynamics.\ncphNumMinSteps 100\n# Run 2500 steps of MD between attempted protonation state changes. Run 10\n# cycles of MD and neMD/MC. The _upper_ bound of the simulation is thus:\n#\n# 10*(2500 + 7500) = 100000 steps\n#\n# but the actual simulation may be shorter in length.\n#\ncphRun 2500 10\n\\end{verbatim}\n\n\\newpage\n\\noindent\n\\textbf{Restarting a simulation}\n\n\\noindent\nThe following assumes that a simulation has already been run (as in the example\n above).\nFor clarity we shall assume that \\texttt{outputname} was set to \"foo\" such that\n restart files have been written to foo.coor and foo.vel (normal output) as\n well as foo.psf, foo.pdb, and foo.cphrst (constant-pH specific output).\n\n\\begin{verbatim}\n# End conventional settings...\nsource .../namd/lib/namdcph/namdcph.tcl\n# Constant-pH MD requires additional force field files _during_ the simulation.\n# In general, all RTFs used to construct the system need to be included with\n# the ``topology'' command (just as in psfgen). Additional constant-pH specific\n# RTF and PRM files are also necessary, as well as an accompanying\n# configuration file in JSON format.\n#\ncphConfigFile \ntopology \ntopology \npH 7.0\n\nstructure foo.psf\ncoordinates foo.pdb\nbinCoordinates foo.coor\nbinVelocities foo.vel\ncphRestartFile foo.cphrst\n# NB: switch times and inherent pKa values are read here and no longer need to\n# be specified as during initialization\n\ncphRun 2500 10\n\\end{verbatim}\n\n%% COMING SOON\n%\\newpage\n%\\subsection{Notes for Developers}\n%\n%This section of the user's guide is likely not necessary reading for those\n% who simply want to perform constant-pH simulations.\n%Rather, it is a companion guide for the code and comments so that furthur\n% developments can be made as a community.\n\n", "meta": {"hexsha": "72dc705453ac71d19dd66e7b1df7c95951705995", "size": 27541, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "ug/ug_constantph.tex", "max_stars_repo_name": "gwli/namd", "max_stars_repo_head_hexsha": "a2ce2a1bfe68350cde94a72d32192ad8f1ffa175", "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": "ug/ug_constantph.tex", "max_issues_repo_name": "gwli/namd", "max_issues_repo_head_hexsha": "a2ce2a1bfe68350cde94a72d32192ad8f1ffa175", "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": "ug/ug_constantph.tex", "max_forks_repo_name": "gwli/namd", "max_forks_repo_head_hexsha": "a2ce2a1bfe68350cde94a72d32192ad8f1ffa175", "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": 42.3707692308, "max_line_length": 97, "alphanum_fraction": 0.7654769253, "num_tokens": 7137, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.3311197264277872, "lm_q1q2_score": 0.17718164529878241}}
{"text": "%---------------------------------------------------\r\n% Exponential (& Logarithmic) Functions\r\n%---------------------------------------------------\r\n\\chapter[Exponential Functions]{Exponential \\& Logarithmic \\\\Functions}\r\nWe defined the polynomial $a^{x}$ in Chapter 1 (page~\\pageref{sec:polynomials}), however $x$ was restricted to rational numbers. (Recall rational numbers can be expressed as a fraction: $\\frac{a}{b}$.) We now want to explore $a^{x}$ where and $x$ is any real number. Consider $y =2^{x}$. This is an \\textit{exponential} function because the variable, $x$, is in the exponent. The graph is shown below. Notice it will never go below $y=0$.\r\n\r\n\\begin{multicols}{2}\r\n\t\\begin{center}{\\renewcommand{\\arraystretch}{1.25}%\r\n\t\t\\begin{tabular}{clr} \r\n\t\t\t\\toprule\r\n\t\t\tvariable&function&\\\\\r\n\t\t\t$x$&$f(x)=2^x$& \\\\\r\n\t\t\t\\midrule\r\n\t\t\t$-4$ & $f(-4)=2^{-4}$&$=0.0625$\\\\\r\n\t\t\t$-3$ & $f(-3)=2^{-3}$&$=0.125$\\\\\r\n\t\t\t$-2$ & $f(-2)=2^{-2}$&$=0.25$\\\\\r\n\t\t\t$-1$ & $f(-1)=2^{-1}$&$=0.5$ \\\\\r\n\t\t\t$0$ & $f(0)=2^0$&$=1$ \\\\\r\n\t\t\t$1$ & $f(1)=2^1$&$=2$ \\\\\r\n\t\t\t$2$ & $f(2)=2^2$&$=4$ \\\\\r\n\t\t\t\\bottomrule\r\n\t\t\\end{tabular}}\r\n\t\t\\captionof*{tabular}{A \\textbf{table of values} for the function $f(x)=2^x$}\r\n\t\\end{center}\r\n\t\\columnbreak\r\n\t\\begin{center}\r\n\t\t\\begin{tikzpicture}\\label{fig:y2x}\r\n\t\t\t\\begin{axis}[\r\n\t\t\t\tscale=1,\r\n\t\t\t\taxis lines=center,\r\n\t\t\t\tymax=4.5,ymin=0,\r\n\t\t\t\txmax=4.5,xmin=-4.5,\r\n\t\t\t\txlabel=$x$,ylabel=$y$,\r\n\t\t\t\t]\r\n\t\t\t\t\\addplot [<->,domain=-4.5:2.1,thick, samples=100, black] {2^x};\r\n\t\t\t\t\\node[anchor=south] at (axis cs:1.8,0.5) {$f(x)=2^x$};\r\n\t\t\t\t\\addplot[mark=*] coordinates {(-4,0.0625)};\r\n\t\t\t\t\\addplot[mark=*] coordinates {(-3,0.125)};\r\n\t\t\t\t\\addplot[mark=*] coordinates {(-2,0.25)};\r\n\t\t\t\t\\addplot[mark=*] coordinates {(-1,0.5)};\r\n\t\t\t\t\\addplot[mark=*] coordinates {(0,1)};\r\n\t\t\t\t\\addplot[mark=*] coordinates {(1,2)};\r\n\t\t\t\t\\addplot[mark=*] coordinates {(2,4)};\r\n\t\t\t\\end{axis}\r\n\t\t\\end{tikzpicture}\r\n\t\t\\captionof*{tikzpicture}{A \\textbf{plot of the points} showing an exponential relationship}\r\n\t\\end{center}\r\n\\end{multicols}\r\n\r\n\\subsection*{The Exponential Function $f(x)=a^x$}\r\nLet $y =a^{x}$ where $a >0$. Here, $f(x) =a^{x}$ is called an \\emph{exponential} function where $a$ is called the \\emph{base}. The domain is the set of real numbers, $\\mathbb{R}$. The range is $\\left (0 ,\\infty \\right )$. The $x$-axis forms an asymptote. \r\n\\begin{multicols}{2}\r\n\t\\begin{center}\r\n\t\t\\begin{tikzpicture}\\pgfplotsset{ticks=none}\r\n\t\t\t\\begin{axis}[\r\n\t\t\t\tscale=0.8,\r\n\t\t\t\taxis lines=center,\r\n\t\t\t\tymax=10,ymin=-0.5,\r\n\t\t\t\txmax=6,xmin=-4,\r\n\t\t\t\txlabel=$x$,ylabel=$y$,\r\n\t\t\t\t]\r\n\t\t\t\t\\addplot [->,domain=-3.2:5,thick, samples=100, black] {(0.5)^x};\r\n\t\t\t\t\\node[anchor=south] at (axis cs:2,2) {decay};\r\n\t\t\t\\end{axis}\r\n\t\t\\end{tikzpicture}\\end{center}\\captionof*{tikzpicture}{When $0,domain=-5:3.2,thick, samples=100, black] {2^x};\r\n\t\t\t\t\\node[anchor=south] at (axis cs:3,1) {growth};\r\n\t\t\t\\end{axis}\r\n\t\t\\end{tikzpicture}\\end{center}\r\n\t\\captionof*{tikzpicture}{When $a>1$, $y=a^{x}$ `grows' as $x$ gets big}\r\n\\end{multicols}\r\n\r\n\r\n\\example Find the equation of the exponential function that passes through $\\left (0 ,1\\right )$ and $\\left (3 ,125\\right )$. \r\n\r\n\\solution An exponential function that passes through $\\left (0 ,1\\right )$ is of the form $f (x) =a^{x}$. As $f (3) =125$ we substitute $x =3$ and get\r\n\\begin{align*}a^{3} & = 125 \\\\\r\na & = \\sqrt[{3}]{125} =5\\\\\r\n\\therefore f(x)&=5^x \\text{ satisfies the conditions.}\r\n\\end{align*}\r\n\r\n\\subsection*{Transformations of Exponential Functions}\r\nRecall the transformations we have met so far:\r\n\\begin{center}{\\renewcommand{\\arraystretch}{1.3}\r\n\\begin{tabular}{ll}Vertical stretch of $a$ & $y =f (x) \\leadsto y =a f (x)$ \\\\\r\n\tHorizontal stretch of $\\frac{1}{b}$ & $y =f (x) \\leadsto y =f (b x)$ \\\\\r\n\tVertical shift of $c$ $\\uparrow $ & $y =f (x) \\leadsto y =f (x) +c$ \\\\\r\n\tHorizontal shift of $d$ $ \\longrightarrow $ & $y =f (x) \\leadsto y =f (x -d)$ \\\\\r\n\tReflection in $x$-axis & $y =f (x) \\leadsto y = -f (x)$ \\\\\r\n\tReflection in $y$-axis & $y =f (x) \\leadsto y =f ( -x)$\r\n\\end{tabular}}\r\n\\end{center}\r\nEach of these transformations can be applied to an exponential function. Horizontal shifts are `attached' to the $x$ with brackets and opposite to convention. A shift to the right is represented by negative, e.g., $y=2^(x-3)$. Vertical shifts are positive to shift up and negative to shift down.\r\n\\begin{center}\\includegraphics[width=14cm]{expTrans1}\\end{center}\r\nReflections are accomplished by multiplying by negative one. To reflect in the $x$-axis, multiply the whole function by $-1$, e.g., $y=-2^x$. And for a reflection in the $y$-axis multiply the $x$ variable by $-1$, e.g., $y=2^{-x}$.\r\n\\begin{center}\\includegraphics[width=14cm]{expTrans2}\\end{center}\r\nSee the lecture notes for more examples.\\\\\r\n\r\n\\exercise Use Desmos to verify that $y =2^{-x}$ and $y =\\left(\\frac{1}{2}\\right)^x$ are equivalent. \r\n%---------------------------------------------------\r\n% the natural exponential function e^x\r\n%---------------------------------------------------\r\n%\\section{\\texorpdfstring{$e^x$}{}}\r\n\\section[$e^x$]{The Natural Exponential Function}\\label{sec:naturalExponential}\r\nThe \\emph{natural exponential function} has wide application in mathematics engineering. It arises naturally and crops up in applications such as finance, population, radioactivity, charge on a capacitor, and more. We have defined $f (x) =a^x$ and there is a particular value of $a$ that we denote by the letter $e$. It is an irrational number (like $\\pi $, $\\sqrt{2}$ etc.) and has a button on your calculator. To 10 decimal places it is\r\n\\[e \\approx 2.7182818285\\dots\\]\r\nThe natural exponential function $f (x) =e^x$ is often simply referred to as \\textit{the} exponential function. \r\n\r\nCompound interest can demonstrate an example of how the value above is found. Imagine a bank that pays 100\\% interest on your money. Given an initial deposit of \\$1, at the end of year you will receive \\$1 in interest payment and have a total of \\$2. Compounded interest allows this to happen at intervals smaller than 1 year. If the interest is compounded twice per year, then after 6 months, you will receive 50\\% interest and have \\$1.50. In the second half of the year you now have an additional \\$0.50 available to earn the second half interest. Now, $\\$1.50\\times50\\%=\\$0.75$, so at the end of the year you have \\$1.50+\\$0.75=\\$2.25.\r\n\r\nLets say the interest is compounded monthly, then after 1 month you will receive $\\frac{1}{12}\\times 100\\%=8.33\\%$ interest for \\$1+\\$0.0833=\\$1.0833. The second month will earn the same rate (8.33\\%) on \\$1.0833, for a total of \\$1.1736. After 12 months, your dollar will now be worth $\\$1.00\\times\\left(1+\\frac{1}{12}\\right)^{12}=\\$2.6130$. \r\n\r\nRepeat this process for shorter and shorter time intervals. What is the most money you can have? Compounding every second would get close to the maximum but there would still be gaps \\textit{between} the seconds. Closing these gaps yields a \\textit{continuous} function.\r\n\\begin{center}\r\n\\begin{tabular}{cll}\r\n\t\\toprule\r\n\tcompounding periods&interest (\\$)&total (\\$)\\\\\r\n\t\\midrule\r\n\t1 (yearly)&1.00&2.00\\\\\r\n\t2&1.25&2.25\\\\\r\n\t3&1.3704 &2.3704\\\\\r\n\t4 (quarterly)& 1.4414 & 2.4414 \\\\\r\n\t5& 1.48832 & 2.48832 \\\\\r\n\t6& 1.521626&2.521626\\\\\\midrule\r\n\t12 (monthly)& 1.613035&2.613035 \\\\\\midrule\r\n\t52 (weekly)&1.692597 &2.692597\\\\\\midrule\r\n\t365 (daily)&1.714567 &2.714567\\\\\\midrule\r\n\tcontinuous& 1.718282&\\textbf{2.7182818}$...=$\\textit{\\textbf{e}}\\\\\r\n\t\\bottomrule\r\n\\end{tabular}\r\n\\end{center}\r\n\\clearpage\r\n\\begin{multicols}{2}\r\nAs a function, $f(x)=e^x$, is plotted. Note the similarity to $y=2^x$ (page~\\pageref{fig:y2x}). \r\n\r\nThe exponential function, $e$, is naturally occurring, and useful mathematically as we will see in the next chapter on differentiation.\r\n\r\nReplacing the $x$ axis with time we can imagine the compounding benefits (or detriments) of the exponential function as time increases.\r\n\\columnbreak\r\n\\begin{center}\r\n\t\\begin{tikzpicture}\\pgfplotsset{ticks=none}\r\n\t\t\\begin{axis}[\r\n\t\t\tscale=1,\r\n\t\t\taxis lines=center,\r\n\t\t\tymax=9.5,ymin=-0.5,\r\n\t\t\txmax=5,xmin=-5,\r\n\t\t\txlabel=$x$,ylabel=$y$,\r\n\t\t\t]\r\n\t\t\t\\addplot [<->,domain=-5:2.2,thick, samples=100, black] {e^x};\r\n\t\t\t\\node[anchor=south] at (axis cs:3,5) {$y=e^x$};\r\n\t\t\t\\addplot[mark=*] coordinates {(0,1)};\r\n\t\t\t\\node[anchor=south] at (axis cs:-1,1) {$(0,1)$};\r\n\t\t\t\\addplot[mark=*] coordinates {(1,2.718)};\r\n\t\t\t\\node[anchor=south] at (axis cs:2,2.5) {$(1,e)$};\r\n\t\t\\end{axis}\r\n\\end{tikzpicture}\\end{center}\r\n\\end{multicols}\r\n%---------------------------------------------------\r\n% Logarithmic Functions\r\n%---------------------------------------------------\r\n\\section{Logarithmic Functions}\r\nThe \\emph{logarithmic function} is the inverse of the function $f (x) =a^{x}$. Recall the inverse of a function is the reflection of the function in the line $y =x$. Mathematically this is equivalent to swapping the $x$ and the y in $y =a^{x}$. So $x =a^{y}$ is the inverse of $y =a^{x}$. We have another notation for the inverse of a function, which is a little more complicated. Let $y =f (x)$ be a function of $x$ then $y =f^{ -1} (x)$ is the inverse of this function. \r\n\r\nSometimes the inverse of the function is also a function. For example the inverse of $y =x^{2}$ is $x =y^{2}$. $y =x^{2}$ is a function (vertical line test always applies), whereas $x =y^{2}$ is not a function (vertical line test is broken). \r\n\r\n\\begin{multicols}{2}\r\n\\includegraphics[ width=3.032in, height=2.4275in,]{L4SZ2832}\r\n\\includegraphics[ width=2.3419in, height=2.4267in,]{L4SZ2833}\r\n\\end{multicols}\r\n\r\nThe inverse of $y =10^{x}$ is $x =10^{y}$. $y =10^{x}$ is a function (vertical line test always applies) and so is $x =10^{y}$. \r\n\r\nAnother useful fact to remember about inverses concerns the domain and range. The \\emph{domain}\r\nof $f$ is the \\emph{range} of $f^{ -1}$ and the \\emph{range} of $f$ is the \\emph{domain} of $f^{ -1}$. \r\n\r\nWe have a notation for $x =a^{y}$ it is $y =\\log _{a} x$:\r\n\\begin{tcolorbox}\r\n\\[y =\\log _{a} x \\Leftrightarrow x =a^y\r\n\\]\r\n\\end{tcolorbox}\r\n\r\n\r\nIn $x =a^{y}$ substitute $y =\\log _{a} x$ and we get $x =a^{\\log _{a} x}$. This means that given a base of $a$ the power (or exponent) to which $a$ must be raised to get $x$ is $\\log _{a} x$. \r\n\r\nProblems involving logarithms will often require us to switch back and forth between $y =\\log _{a} x$ and $x =a^{y}$, however it is also helpful if you can remember to substitute for $y$ and write $x =a^{\\log _{a} x}$ so that you can say ``the logarithm is the power\". \r\n\r\n\\example\r\n\\begin{description}\r\n\t\\item [(a)] $\\log _{10} 100 =2$ because $10^{2} =100$ \r\n\t\r\n\t\\item [(b)] $\\log _{3} 81 =4$ because $3^{4} =81$ \r\n\t\r\n\t\\item [(c)] $\\log _{10} 0.01 = -2$ because $10^{ -2} =0.01$ \\end{description}\r\n\r\n\\subsection*{The graph of $y =\\log _{a} x$}\r\nThe exponential function $y =a^{x}$ where $a >0$ is now known and its domain is $\\mathbb{R}$ and its range is the positive real numbers. We can write $\\mathbb{R}^{ +}$, meaning the positive real numbers, instead of $(0 ,\\infty)$. \r\n\r\nThe graph of $f (x) =a^{x}$ can be reflected in the line $y =x$ and the result is $f^{ -1} (x) =\\log _{a} x$. \r\n\r\n\\textbf{Graphing Exercise} On the same set of axes draw:\r\n\\begin{tasks}(4)\r\n\t\\task $y =10^{x}$ \r\n\t\\task $y =\\log _{10} x$ \r\n\t\\task $y =x$ \r\n\t\\task $x =10^{y}$ \r\n\\end{tasks}\r\n\r\nMake a comment about each statement below. \r\n\\begin{tasks}\r\n\t\\task[1.] Check the graphs in (a), (b) and (c) are you confident that $y =\\log _{10} x$ is the reflection of $y =10^{x}$ in the line $y =x$?\r\n\t\\task[2.] When you enter $x =10^{y}$ describe what takes place.\r\n\t\\end{tasks}\r\n\r\n\\textbf{Graphing Exercise Solution} Using \\desmos we can see the different plots. Plots (b) and (d) are equivalent, so are on top of each other.\\\\\r\n\\begin{center}\r\n\\includegraphics[width=14cm]{logGraph1}\\\\\r\n\\end{center}\r\n\r\n\\textbf{Graphing Exercise} On the same set of axes draw:\r\n\\begin{tasks}(4)\r\n\t\\task $y =\\log _{2} x$ \r\n\t\\task $y =\\log _{3} x$ \r\n\t\\task $y =\\log _{4} x$ \r\n\t\\task $y =\\log _{10} x$ \\end{tasks}\r\n\\textbf{Graphing Exercise Solution} Using \\desmos we can see the relationship between the different bases in the log equation:\\\\\r\n\\begin{center}\\includegraphics[width=14cm]{logGraph2}\\end{center}\r\nNotice the point that is common to all curves and the behaviour of the family of curves for $x >1$ and for $0 }}\n\\newcommand{\\spacet}{{\\tt space\\_T}}\n\\newcommand{\\cvector}{{\\tt List}}\n\\newcommand{\\rvector}{{\\tt List}}\n\\newcommand{\\libname}{{\\tt libcmatrix}}\n\\newcommand{\\ket}[1]{\\ensuremath{\\langle #1 \\rangle}}\n\\newcommand{\\eq}[1]{Eqn.~(\\ref{#1})}\n\\newcommand{\\lp}{\\hspace{2em}}\n\\newcommand{\\indexheader}[2]{{\\tt #1}\\index{#2@{\\tt #1}}}\n\n\\usepackage[colorlinks=true,linkcolor=darkred,dvipdfm]{hyperref}\n%\\usepackage[colorlinks=true]{hyperref}\n\n\\begin{document}\n\n\\begin{center}\n\\Large {\\tt crystal} module of {\\tt libcmatrix}\\\\\n\\large (experimental version)\n\\end{center}\n\nThis code provides a way to generate Hamiltonians and spin operators\nfor spin systems with permutation symmetry, in particular resulting\nfrom translational symmetry.\n\nExisting \\libname\\ functions can be used\nto calculate operators in the conventional Zeeman eigenbasis that can then be\nblock-diagonalised by unitary transformations by matrices of the form\n\\begin{equation}\n\\begin{pmatrix}\n1 & 1 & 1 & \\dots \\\\\n1 & e^{2\\pi i/n} & e^{4\\pi i/n} & \\dots \\\\\n\\vdots & \\vdots & \\ddots & \n\\end{pmatrix}\n\\label{Vmatrix}\n\\end{equation}\nwhere $n$ is the number of states in a set linked by permutation.\n$n$ is necessarily a factor of $N$---the number of spins being permuted.\nThis approach is adequate for small problems, but is unsuited to large \nproblems. Most importantly, it doesn't allow larger spin systems\nto be studied.\n\nA better solution is to calculate the spin operators etc.\\\ndirectly in the symmetrised basis. The resulting matrices are smaller\nby a factor of $\\sim N$, allowing for much more efficient calculation\n(by a factor of $N^2$) for a given $N$, or larger problems\nto be solved. Although only an extra $\\log_2 N$ spin-1/2 spins can\nbe added, the efficiency savings do make calculations on large\n(say $>10$) spins a realistic possibility.\n\nThere are limitations to the current implementation:\n\\begin{itemize}\n\\item Limited to spin-1/2. Extension to other spin quantum numbers\nor mixed spin systems would not be too difficult, but is of relatively\nlittle interest. Large spin systems are only relevant to strongly\ncoupled systems, which is rarely an issue outside of spin-1/2 NMR\\@.\nThe existing {\\tt libcmatrix} functions can be used here in any case.\n\n\\item Limited to cyclic permutations of all spins, corresponding\nto one-dimensional translational symmetry (with periodic boundary).\nThe restriction to one dimension of translational symmetry\nis a major one. Adding additional \\emph{point} group symmetries\ne.g.\\ mirror planes, is not particularly useful since additional\nblock diagonalisation is restricted to ``special'' values of the\ntranslational eigenvalue, $k$, notably $k=0$. \nAdding ``independent'' symmetries such as additional translational\naxes would be useful. This would require some major addition to the\ncode (effectively all the functions would take on forms that\nhandled two, three etc.\\ $k$ eigenvalues), but is not impossible.\nUnfortunately the size of problem that\ncould be considered is small, even for just 2 dimensions, and may not be sufficient to be\nconvincing.\n\n\\item Only one level of ``$m_z$ blocking'' is supported. Under free precession,\n$m_z$ is a good quantum number for each nucleus type (high-field approximation).\nIn this case, blocking is limited to the \\emph{total} $m_z$, or to one nucleus\ntype.\n\n\\item Although the functions are intended to resemble existing\nfunctions closely, a perfect match\n(e.g.\\ having a {\\tt periodicspin\\_system} that ``looked''\nlike a {\\tt spin\\_system}) is impossible. Code that uses\nthese functions will always be signficantly more involved.\n\n\\end{itemize}\n\n\n\\section{Setting up the problem}\n\nTwo data objects are declared in {\\tt crystal.h}; {\\tt CrystalSpec}\n``specifies'' the symmetry by declaring which spin states are\nrelated by symmetry. Adding different permutation symmetries\nother than 1D translational is a matter of generating the correct\n{\\tt CrystalSpec}, but is still restricted to a single ``eigenvalue''.\n{\\tt CrystalSystem} then uses the information from a {\\tt CrystalSpec} object to\ncreate spin operators. A {\\tt CrystalSpec} is initialised using \n\\begin{description}\n\\item[CrystalSpec(spinhalf\\_system {\\it sys},$N$,bool {\\it mzblock},{\\it neigs})] creates \nthe ``symmetry specification'' for $N$ cells of a given system of spin-1/2 spins. The {\\it mzblock}\nflag should be {\\tt true} if the states will be blocked by $m_z$ quantum\nnumber i.e.\\ free-precession problems, or not. {\\it neigs} is the number\nof ``active'' eigenvalues; typical values are $N$ (also the default if omitted),\nor $(N+1)/2$ which corresponds to positive values of $k$ only (the translational\neigenstates are numbered 0 to $N-1$ where $N-1$ corresponds to $k=-2\\pi/N$ etc.).\nNote that the optional $m_z$ blocking is via the {\\emph total} $m_z$ quantum number\nwhich will not be appropriate for all heteronuclear problems. \n\\item[CrystalSpec(spinhalf\\_system {\\it sys},$N$,char* {\\it label},{\\it neigs})] allows a system\nto be blocked by $m_z$ of a chosen nucleus e.g. {\\tt \"13C\"} etc. This is necessary\nif $m_z$ is only a good quantum number for one set of spins in a heteronuclear system.\n\\end{description}\n\n\\begin{center}\n\\centerline{\\includegraphics[width=5.5in]{eigsfig.eps}}\n\\end{center}\n\nAs can be seen in the diagram above, the eigenvalues can be divided\ninto ``general'' values of $k$ which occur in pairs ($k$ and $-k$)\nand ``special'' values $k=0$ plus $k=\\pi$ if $N$ is even. \nIf the original Hamiltonian is symmetric (i.e.\\ purely real),\nthen $H_{k}=H_{-k}$. In favourable cases, the evolution can\nthen be calculated using only the postive values of $k$ \n(remembering to double the weighting of signals from general $k$),\nhalving the calculation time for large $N$. This relationship breaks down\nfor sample spinning; presumably because the directionality of the rotation \nbreaks the relationship between $k$ and $-k$. There may also be some\npossible speedups using the relations between $k$ and $k+\\pi$ ($N$ even only). \n\nAt the special values of $k$, $H_k$ is real for real starting Hamiltonians\n(at general values of $k$ the symmetrised Hamiltonian is necessarily complex,\nalbeit hermitian). Since operations such as diagonalisation are typically\na factor of 3 faster for purely real matrices, this is a useful efficiency\ngain, albeit one that becomes less important as $N$ increases.\n\nAlthough the contents of {\\tt CrystalSpec} are generally only\naccessible to {\\tt CrystalSystem}, there are a couple of member functions\nthat can be used to interrogate the object:\n\\begin{description}\n\\item[List permutation\\_vectorH()] returns the permutation\nthat ``translates'' states by one unit cell. \n\\item[ListList linkedstates()] returns the states broken\ndown into sets linked by the (translation) symmetry. \n\\end{description}\n\nThe convention $j=Mc+j'$ is used to relate the ``spatial'' definition\nof a spin in terms of unit cell number, $c$, and index within the cell, $j'$\nto spin index\nwithin the spin system, $j'$ (the spin system is always ``flat''). The\nfunction {\\tt cell\\_to\\_spin($M$,$c$,$j'$)} should be used to\nreturn $j$ for a given cell and spin index.\n\nMost NMR parameters are defined over the $M$ spins in the unit cell.\nDipolar couplings, however, are defined between the couplings within cell 0\nand between cell 0 and the other cells. The translational symmetry dictates\nthat the couplings between cells $c_1$ and $c_2$, for example, are identical\nto those between cell 0 and cell $c_2-c_1$. The coupling network must be\ncyclic, so cell $N-1$ can be considered as cell $-1$ etc.\n\n\\section{Using the {\\tt CrystalSystem} object}\n\nThe {\\tt CrystalSystem} is initialised from a {\\tt CrystalSpec}:\n\\begin{description}\n\\item[CrystalSystem(CrystalSpec {\\it defin})] creates a {\\tt CrystalSpec} object for\nthe complete space of {\\it defin} (no $m_z$ blocking).\n\\item[CrystalSystem(CrystalSpec {\\it defin}, {\\it bra $m_z$}, {\\it ket $m_z$})]\ncreates a {\\tt CrystalSpec} object spanning a given coherence block, specified\nin terms of the $m_z$ values of bra and ket sub-spaces. A {\\tt Failed}\nexception thrown if the {\\tt CrystalSpec} does not use $m_z$ blocking.\n\\end{description}\n\nOnce the object is defined, it can then be used to generate spin \noperators. Its use differs from typical\nspin-operator generators such as {\\tt spin\\_system} and {\\tt spinhalf\\_system}\nin the following ways:\n\\begin{itemize}\n\\item Rather than return a single matrix, most functions return\nthe complete manifold for the $k$ states under consideration (as set up\nin the {\\tt CrystalSpec}). This is the most efficient way to generate\nthe spin operators, but other functions allow operators to be calculated\nfor specific values of $k$, which is useful if memory is tight.\n\n\\item Special attention is required when there are less than two states\nin the relevant $k$ subspace. In normal calculations, these cases are\ngenerally obvious and easily accounted for. In periodic calculations\nusing $m_z$ blocking, however, small subspaces occur quite frequently and it is useful\nto handle them efficiently. For example, the single state of maximum (or\nminimum) $m_z$ generates trivially one state of $k=0$ only. \n\n\\item The homonuclear dipolar coupling Hamiltonian requires special attention.\nNormally this is constructed by summing product operator expressions\nfor all the spin pairs. This is not practical for large (or even medium)\nsized problems. Instead special functions construct the symmetrised\ndipolar coupling Hamiltonian from a specification of the coupling network.\nThe other spin Hamiltonians do not require special treatment and\ncan be constructed from spin operators relatively efficiently.\n \n\\end{itemize}\n\nThe simple spin operator functions are\n\\begin{description}\n\\item[I(List\\&, $n$, {\\it op})] calculates the symmetrised\noperator, where $n$ is the spin index $0$ to $MN-1$ (although only\nthe index modulo $N$ is significant), and {\\it op} is {\\tt 'x'}, {\\tt 'y'}\netc. The destination is a list of complex matrices, where matrix 0\ncorresponds to $k=0$ etc. If a particular $k$ value is not represented\nin the selected sub-space, the corresponding matrix will be ``undefined''.\nSub-spaces of size 1 are not treated specially.\n\\item[I(cmatrix\\&,$n$,{\\it op},$k$)] returns the spin operator for the specified $k$.\nThe function above should be used whenever all the eigenvalue blocks are\nneeded; this function is useful for large problems where there is insufficient\nmemory to work with all the $k$ states at the same time.\n\\item[F(List\\&, {\\it op})] calculates a symmetrised sum operator (over all spins).\n\\item[F(List\\&, char* {\\it label},{\\it op})] restricts the summation to a particular nucleus type.\n\\item[F(cmatrix\\&, {\\it op}, $k$) {\\rm and} F(cmatrix\\&, char* {\\it label}, {\\it op}, $k$)] calculate a symmetrised sum operators for a given $k$ eigenvalue.\n\\item[ListList diag\\_Iz($n$)] returns a $z$ operator in\n``diagonal form''. The result is a {\\tt ListList} rather than the\nless efficient {\\tt List< List >}. {\\tt result(0)}, for example,\nis a {\\tt BaseList} corresponding to $k=0$.\n\\end{description}\nThere are also more basic {\\tt mla} functions that can be used to \naccumulate (scaled) spin operators efficiently.\nN.B.\\ The spin operator functions use temporary workspace within the {\\tt CrystalSystem}\nobject, hence a multi-threaded calculation should not share\n{\\tt CrystalSystem} objects, but rather each thread should use its own (the overhead\nis tiny).\n\nBecause the $z$ operators can be stored compactly, it makes sense\nto calculate these once at the start of the calculation. Full spin operators\nare generally too large to be kept around and must be generated as needed.\n\nThe following functions calculate symmetrised (homonuclear) dipolar Hamiltonians.\nIn static problems, the coupling network is specified by a $M \\times MN$ \\rmx\\, $\\bs{d}$,\nwhere $d_{ij}$ is the dipolar coupling between spin $i$ of unit cell``zero'' and\nspin $j= M c + j'$ ($c$ is the unit cell, $j'$ is the index within the unit cell). \nNote that the coupling network defined by $\\bs{d}$ must be cyclic (as explained above). Couplings that are identically zero are ignored.\n%Functions that deal with Hamiltonians treat singly-degenerate matrix blocks\n%separately, since $1 \\times 1$ matrices are extremely inefficient to handle \n%and they are usually special cases.\n\nIn spinning problems, it is necessary to provide a rank 2 tensor (as a {\\tt space\\_T}) to define the strength and orientation of the dipolar interaction.\nRather than return a {\\tt List}, the functions create a {\\tt List< Tensor >} i.e.\\ for each value of $k$, the Hamiltonian is defined in terms\nof components $H^{(l)}_m$ which transform as rank $l$ spherical tensors ($l$ is always 2).\nNote that the functions also take the $\\bs{d}$ matrix in addition to the spatial\ntensor information, where the $d_{ij}$ are just used to determine whether a\nparticular interaction is to be included or not.\n\n\\begin{description}\n\\item[sym\\_Hdipolar(List\\& $H$, List\\& $h$, rmatrix $\\bs{d}$)] creates\nthe symmetrised dipolar coupling Hamiltonian defined by coupling network $\\bs{d}$.\nIf the coupling is heteronuclear (as defined by the initial {\\tt spinhalf\\_system}), only the\nsecular components of the dipolar Hamiltonian are used.\n\\emph{If the $k$ block contains a\nsingle state, the symmetrised element is stored in $h(k)$ of the $h$ vector\nand the corresponding $H$ matrix will be undefined.}\n\n\\item[sym\\_Hdipolar(cmatrix\\& $H$, double\\& $h$, $\\bs{d}$, $k$)] stores the dipolar Hamiltonian for a particular $k$ value in $H$ or $h$. This function is for large\nproblems where memory is insufficient to handle all $k$ values at the same time.\n\\item[double sym\\_Hdipolar\\_element($\\bs{d}$)] handles the special case where the Hilbert space contains\na single state (i.e.\\ {\\tt rows()} is 1). It returns the single element of the dipolar Hamiltonian.\n\\item[sym\\_Hdipolar(List< Tensor >\\& $H$, List\\& $h$,$\\bs{d}$, Matrix $\\bs{D}$)] calculates the Fourier components $H^{l}_m$ of the dipolar\nHamiltonian under spinning\\footnote{By default, magic angle spinning is assumed for the sake of efficiency, but this can be easily changed}. Single-element $k$ blocks are stored in the simple {\\tt space\\_T}, $h$.\n\\item[sym\\_Hdipolar(Tensor\\& $H$, space\\_T\\& $h$,$\\bs{d}$,$\\bs{D}$,$k$)] calculates the Fourier components for a single value of $k$.\n\\item[complex sym\\_Hdipolar\\_element($\\bs{d}$,$\\bs{D}$,$k$)] return the single element of\nthe dipolar Hamiltonian for the special case of a Hilbert space consisting of a single state.\n\\end{description}\n\nOther member functions of {\\tt CrystalSystem}\n\\begin{description}\n\\item[isdiagonal()] returns {\\tt true} if the Hilbert space is diagonal (always true\nif no $m_z$ blocking).\n\\item[rows() \\& cols()] return the dimensions of the Hilbert space.\n\\item[rows($k$) \\& cols($k$)] return the dimensions of a particular eigenvalue block\nof the symmetrised space. \n\\end{description}\n\n\\section{How it works}\n\nThe mathematics of the symmetrisation is essentially limited to\nEquation~(\\ref{Vmatrix}). The complications lie in the book-keeping of\ncombining the right states and putting the result in the right place.\nThe spin operator generating functions use a {\\tt CrystalSystem\\_iterator} to\niterate over each set\nof symmetry-linked states, generating elements of the symmetrised operators.\nFor instance, if sets $i$ and $j$ both contain $N$ states, the $N \\times N$\nblock of the original operator is first calculated and then transformed\n(by the {\\tt symmetrise} internal functions)\nto generate a diagonal vector containing $N$ elements corresponding to the\n$N$ values of $k$. These are then placed into the $i,j$ elements of the\noutput matrix blocks (by the {\\tt place} functions). Things are complicated somewhat by the presence (for\nnon-prime $N$) of sets that contain less than $N$ states, but this is \nessentially book-keeping.\n\nVarious special cases are considered to make the whole thing go faster:\n\\begin{itemize}\n\\item Diagonal spin operators: only diagonal $i,i$ blocks need be considered\nand the maths can be further simplified.\n\\item For simple spin operators, it is more efficient to calculate the symmetrised\nmatrix elements directly rather than transform a fairly sparse matrix.\n\\item In the dipolar coupling Hamiltonian, it is not necessary to consider \nall the $MN(MN+1)/2$ couplings. The symmetry allows us to consider \njust the couplings from (and within) cell 0 ($\\sim M^2N$) and simply multiply the\nsymmetrised Hamiltonian by $N$.\n\\item $k=0$ can be handled specially. If the original matrix is real, the $k=0$ block is also real. In this implementation, the results are always stored\nin complex matrices which need to be turned into real versions before\nfunctions such as {\\tt symmetric\\_eigensystem} can be used.\nThe is somewhat wasteful, but the wastage is $O(n^2)$ compared to $O(n^3)$\nfor the major time-takers.\n\\end{itemize}\n\nProfiling a program that uses {\\tt crystal.h} shows\nthe vast majority of the time is spent in diagonalisation, matrix multiplication etc.,\ni.e.\\ the overhead of symmetrisation is not significant.\n\n\n\\end{document}\n", "meta": {"hexsha": "3ac7d549ef069004cddc1264046be9ad49d02546", "size": 17940, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "local/crystal.tex", "max_stars_repo_name": "dch0ph/libcmatrix", "max_stars_repo_head_hexsha": "1f5fae7a398fe2c643252f93371b407dbfb70855", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "local/crystal.tex", "max_issues_repo_name": "dch0ph/libcmatrix", "max_issues_repo_head_hexsha": "1f5fae7a398fe2c643252f93371b407dbfb70855", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "local/crystal.tex", "max_forks_repo_name": "dch0ph/libcmatrix", "max_forks_repo_head_hexsha": "1f5fae7a398fe2c643252f93371b407dbfb70855", "max_forks_repo_licenses": ["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.552238806, "max_line_length": 213, "alphanum_fraction": 0.7557413601, "num_tokens": 4774, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.34510527095787247, "lm_q1q2_score": 0.1765960975200735}}
{"text": "% !TEX root = main.tex\n% !TEX spellcheck = en-US\n\\section{Introduction}\nZero-knowledge proof systems that allow a prover to convince a verifier of a statement without revealing anything beyond the truth of the statement have applications in cryptography and theory of computation~\\cite{FOCS:GolMicWig86,STOC:Fortnow87,C:BGGHKMR88}. \nWhen restricted to computationally sound proofs, called \\emph{argument systems}, proof length can be shorter than the length of the witness~\\cite{brassard1988minimum}. \nZero-knowledge Succinct Non-interactive ARguments of Knowledge (zkSNARKs) are zero-knowledge argument systems that additionally have a succinctness property -- small proof sizes and fast verification. \nSince their introduction in~\\cite{micali1994cs}, zk-SNARKs have been a powerful and versatile design tool for secure cryptographic protocols. They became particularly relevant for blockchain applications that demand short proofs and fast verification, such as privacy-preserving cryptocurrencies~\\cite{SP:BCGGMT14} in Zcash and scalable and private smart contracts in Ethereum\\footnote{\\url{https://z.cash/}, \\url{https://ethereum.org}}.\n\nThe work of~\\cite{EC:GGPR13} proposed a preprocessing zk-SNARK for general NP statements phrased in the language of Quadratic Span Programs (QSP) and Quadratic Arithmetic Programs (QAP) for Boolean and arithmetic circuits respectively. This built on previous works of~\\cite{IKO07,AC:Groth10a,TCC:Lipmaa12} and led to several works~\\cite{TCC:BCIOP13,SP:PHGR13,C:BCGTV13,AC:Lipmaa13,USENIX:BCTV14,EC:Groth16} with very short proof sizes and fast verification. \nThe line of work on pre-processing zkSNARKs has seen rapid progress with many works proposing significant improvements in efficiency of different parameters like proof size, verifier efficiency, complexity of setup etc.\nMost modern zkSNARK constructions follow a modular blueprint that involves the design of an information theoretic interactive protocol, e.g. an Interactive Oracle Proof (IOP), that is then compiled via cryptographic tools to obtain an interactive argument system. This is then turned into a zkSNARK using the Fiat-Shamir transformation in the Random Oracle Model (ROM).\nIn particular, several schemes such as\n$\\sonic$~in \\cite{CCS:MBKM19}, $\\plonk$~\\cite{EPRINT:GabWilCio19}, $\\textsf{Marlin}$~\\cite{EC:CHMMVW20} \nfollow this approach where the information theoretic object is an algebraic variant of IOP, and the cryptographic primitive in the compiler is a polynomial commitment scheme (PC). \n\n\\paragraph{Simulation extractability.}\n\nMost zkSNARKs are shown to satisfy a standard knowledge soundness property. Intuitively, this guarantees that\na prover that creates a valid proof knew a valid witness. However, deployments of zkSNARKs in real-world applications require a stronger property -- \\textit{simulation-extractability} (SE). \nThis is because, in practice, an adversary against the zkSNARK has access to proofs provided by other parties using the same\nzkSNARK. The definition of knowledge soundness ignores the ability of an adversary to see other valid proofs that may occur in real-world applications. For instance, in applications of\nzkSNARKs in privacy-preserving blockchains, proofs are posted on the chain for all\nblockchain-participants to see. Therefore, it is necessary for a zero-knowledge proof system to be \\emph{non-malleable}, that is, resilient against adversaries that additionally get to see proofs generated by different parties before trying to forge.\nTherefore, it is necessary for a zero-knowledge proof system to be \\emph{simulation-extractable}, that is, resilient against adversaries that additionally get to see proofs generated by different parties before trying to forge.\nThis captures the more general scenario where an adversary against the zkSNARK has access to proofs provided by other parties as it is in applications of zkSNARKs in privacy-preserving blockchains, where proofs are posted on the chain for all\nparticipants in the network to verify. \n\n\\paragraph{zkSNARKs in the updatable setting.}\nOne of the downsides of efficient zkSNARKs like~\\cite{AC:Groth10a,TCC:Lipmaa12,EC:GGPR13,SP:PHGR13,AC:Lipmaa13,AC:DFGK14,EC:Groth16} is that they rely on a \\textit{trusted setup}, where there is a structured reference string (SRS) that is assumed to be generated by a trusted party. In practice, however, this assumption is not well founded; if the party that generates the SRS is not honest, then they can produce proofs of false statement. That is, if the trusted setup assumption does not hold, knowledge soundness breaks down.\nGroth et al~\\cite{C:GKMMM18} propose a setting to tackle this challenge which allows parties -- provers and verifiers -- to \\emph{update} the SRS, that is, take a current SRS and contribute to it randomness in a verifiable way to obtain a new SRS. The guarantee in this \\textit{updatable setting} is that knowledge soundness holds as long as one of the parties who updates the SRS is honest. The SRS is also \\emph{universal}, in that it does not depend on the relation to be proved but only an upper bound on the size of the statements.\nAlthough inefficient, as the SRS length is quadratic to the size of the statement,~\\cite{C:GKMMM18} set a new\nparadigm of universal updatable setting for designing zkSNARKs.\n\nThe first universal zkSNARK with updatable and linear size SRS was\n$\\sonic$ proposed by Maller et al.~in \\cite{CCS:MBKM19}. Subsequently, Gabizon et\nal.~designed $\\plonk$~\\cite{EPRINT:GabWilCio19} which currently is the\nmost efficient updatable universal zkSNARK. Independently, Chiesa et\nal.~\\cite{EC:CHMMVW20} proposed $\\textsf{Marlin}$ with comparable efficiency to\n$\\plonk$.\n\n\\paragraph{The challenge of SE in the updatable setting.}\n\nThe notion of simulation-extractability for zkSNARKs which is well motivated in practice has not been studied in this updatable setting. \nConsider the following scenario: an instance proof pair with respect to some SRS is available for public verification, $(\\srs,x,\\pi)$. Now, if there is a new purported proof $(\\srs',x,\\pi')$ with respect to an updated $\\srs'$, we would like the guarantee that the prover must have known a witness corresponding to $x$, and therefore computed $\\pi'$. Since everybody is allowed to update an SRS, the ability for an adversary to perform an update $\\srs$ to $\\srs'$, and ``move\" the proof $\\pi$ from the old SRS to a proof $\\pi'$ for the new SRS without knowing a witness clearly violates security. That is, even an adversary who knows the trapdoor for the update from $\\srs$ to $\\srs'$ should not be able to break SE as long as there was at least one honest update to $\\srs$.\n\nAs it turns out, defining SE for updatable SRS zkSNARKs requires some care. \nSince the SRS is being continually updated, there are proofs with respect to \\textit{different} SRSs available for the adversary to see before attempting to forge a proof with respect to a current SRS. \nThat is, each SRS in the update chain spawns a simulation oracle. Intuitively, the updatability of the SRS allows an adversarial prover to contribute to updating, and see proofs with respect to different updated SRSs before attempting to provide a proof for a false statement (potentially output a proof wrt a SRS that is different from the SRSs corresponding to all the simulated proofs seen). A definition of SE in the updatable setting should take into account this additional power of the adversary, which is not captured by existing definitions of SE. \nWhile generic lifting techniques/compilers~\\cite{EPRINT:KZMQCP15,CCS:AbdRamSla20} can be applied to updatable SRS SNARKs to obtain SE, not only do they inevitably incur overheads and lead to efficiency loss, we contend that the standard definition of SE does not suffice in the updatable setting.\n\n\n\\paragraph{Fiat--Shamir.}\nThe Fiat--Shamir (FS) transform takes a public-coin interactive protocol and\nmakes it interactive by hashing the current protocol transcript to compute the\nverifier's public coins. While in principle justifiable in the random oracle\nmodel (ROM)~\\cite{CCS:BelRog93}, it is theoretically\nunsound~\\cite{FOCS:GolKal03} and so only a heuristic that should be used with\ncare.\n%\nThe FS transform is a now popular design tool in constructing\nzkSNARKs. In the updatable universal SRS setting, works like \\sonic{}~\\cite{CCS:MBKM19}\n\\plonk{}~\\cite{EPRINT:GabWilCio19}, and \\marlin~\\cite{EC:CHMMVW20} are designed\nand proven secure as multi-round interactive protocols. Security is then only\n\\emph{conjectured} for their non-interactive variants by employing the FS\ntransform.\n\nWe investigate the non-malleability properties of a class of zkSNARK protocols obtained by FS-compiling multi-round protocols in the updatable SRS setting and give a modular approach to analyze non-malleablilty of zkSNARKs.\n\n\\subsection{Our Contributions}\n\\begin{itemize}\n\\item \n\\emph{Updatable simulation extractability (USE)}. \nWe propose a definition of simulation extractability in the updatable SRS setting called USE, that captures the additional power the adversary gets by having access to updating the SRS and seeing proofs with respect to different SRSs.\n \n\\item \n\\emph{General theorem for USE of FS-compiled interactive protocols.}\nWe then show that a class of interactive proofs of knowledge that are honest-verifier zero-knowledge,\nhave a unique response property, and satisfy a property we define called forking soundness \\emph{are USE out-of-the box} in the random oracle model when the Fiat--Shamir transformation is applied to them. \nInformally, our notion of forking soundness is a variant of special soundness where the transcripts provided to the extractor are\nobtained through interaction with an honest verifier, and the extraction guarantee is computational instead of unconditional. \nOur extractor only needs oracle access to the adversary, it does not depend on the adversary’s code, nor relies on knowledge\nassumptions.\n \n\\item\n\\emph{USE for concrete zkSNARKs.}\nWe then prove that the most efficient updatable SRS SNARKS -- Plonk/Sonic/Marlin -- satisfy the notions necessary to invoke our general theorem, thus showing that these zkSNARKs are updatable simulation extractable.\nProving that these protocols satisfy the required properties is done in the algebraic group model (AGM).\n\t\n%\\item\n%We make several technical contributions along the way. Our generalized forking lemma is of independent interest.\n\\end{itemize}\n\n\n\n\\subsection{Technical Overview}\n%unique response, forking soundness. general theorem without additional assumptions. to apply the theorem to concrete schemes like plonk, we show it satisfies unique response, forking soundness, in AGM.\n\nThe proof of our general theorem for USE is, at a high level, along the lines of the proof of SE for FS-compiled sigma protocol\nfrom~\\cite{INDOCRYPT:FKMV12}. However, we need new and stronger notions as we consider proof systems that are\nricher than simple sigma protocols. We discuss some of the technical challenges below.\n\n\\plonk~\\cite{EPRINT:GabWilCio19} and \\sonic~\\cite{CCS:MBKM19} were originally presented\nas interactive proofs of knowledge that are made non-interactive by the Fiat--Shamir transform. In the following,\nwe denote the underlying interactive protocols by $\\plonkprot$ (for $\\plonk$)\nand $\\sonicprot$ (for $\\sonic$) and the resulting non-interactive proof systems by\n$\\plonkprotfs$ and $\\sonicprotfs$, respectively.\n\n\\oursubsub{Forking soundness.} \nFollowing~\\cite{INDOCRYPT:FKMV12}, one would have to show that for the protocols we consider, a witness can be extracted from sufficiently many valid transcripts with a common prefix. However, many protocols\ndo not meet the standard definition of special soundness for sigma protocols, that requires extraction of a witness from any two transcripts, with the same first message. We put forth a notion analogous to special soundness, that is more general and applicable to a wider class of protocols -- protocols that are more than three rounds, and rely on an SRS. For $\\plonkprot$ and\n$\\sonicprot$ that are not three move protocols, the definition needs to be adapted. Furthermore, the number of transcripts\nrequired for extraction is more than two. Concretely, $(3 \\noofc + 1)$---where $\\noofc$ is the\nnumber of constraints in the proven circuit---for $\\plonkprot$ and\n$(\\multconstr + \\linconstr + 1)$---where $\\multconstr$ and $\\linconstr$ are the\nnumbers of multiplicative and linear constraints---for $\\sonicprot$. Hence, we\ndo not have a pair of transcripts, but a \\emph{tree of transcripts}.\n\nIn protocols that rely on SRS that come with a\ntrapdoors, an adversary in posession of the trapdoor can produce multiple\nvalid proof transcripts without knowing the witness and potentially for false\nstatements. This is true even in the updatable setting, where there exists a trapdoor for any updated SRS.\nRecall that the standard special soundness definition requires\nwitness extraction from \\emph{any} tree of acceptable transcripts that share a\ncommon root. This means that there are no such trees for false\nstatements. We define a different, forking lemma-related, version\nof soundness that we call \\emph{forking soundness}. Forking soundness guarantees that it is\npossible to extract a witness from all (but negligibly many) trees of accepting\ntranscripts produced by probabilistic polynomial time (PPT) adversaries, given\nthat the trees are generated as interactions between a (possibly malicious)\nprover and an honest verifier. That is, if extraction from such a tree fails, then we break an\nunderlying computational assumption.\n\n\\oursubsub{Unique response property.} \nAnother property required to show USE is the unique response property~\\cite{C:Fischlin05} which\nsays that for $3$-messages sigma\nprotocols, all but the first message sent by the prover are\ndeterministic (intuitively, the prover can only employ fresh randomness in the\nfirst message of the protocol). We cannot use this definition as is since the protocols we consider have other rounds where the prover messages are randomized. In $\\plonkprotfs$, both the first and the second prover's messages are randomized. Although $\\sonicprot$ prover is deterministic after it picks its first message, the protocol has more than $3$ rounds. We propose a generalisation of the\ndefinition which states that a protocol is $\\ur{i}$ if the prover is\ndeterministic starting from its $(i + 1)$-th message. For our proof it is\nsufficient that this property is met by $\\plonkprot$ for $i = 2$. Since\n\\sonic{}'s prover is deterministic from the second message on, it is $\\ur{1}$.\n\n\n\\oursubsub{HVZK.} In order to invoke our main theorem on $\\plonkprotfs$ and\n$\\sonicprotfs$ to conclude USE, we also need to show that (interactive)\n$\\plonkprot$ and $\\sonicprot$ are HVZK in the standard model. Although both\n$\\sonic$ and $\\plonk$ are zero-knowledge, their simulators utilize\ntrapdoors. However, for our reduction, we need simulators that rely only on\nreordering the messages and picking suitable verifier challenges, without\nknowing the SRS trapdoor. That is, any PPT party should be able to produce a\nsimulated proof by its own in a trapdoor-less way. (Note that this property does\nnot necessary break soundness of the protocol as the simulator is required only\nto produce a transcript and is not involved in a real conversation with a real\nverifier). We show simulators for $\\plonkprotfs$ and $\\sonicprotfs$ that rely\nonly on the programmability of the RO, where programmability is only needed from\nsome round $i$ onwards. \\chaya{revisit this. is HVZK for the interactive\n protocol? then why programming? it might be a good idea to elaborate on why a\n trapdoor-based simulator does not work in the reduction. I am not sure I have\n clarity on this.}\n\\michals{16.09}{maybe we should just define Trapdoor-less simulatable (TLZK) protocols?}\n\n\\oursubsub{Generalisation of the general forking lemma.} \nConsider an interactive $3$-message special-sound protocol $\\ps$ and its\nnon-interactive version $\\ps_\\fs$ obtained by the Fiat--Shamir transform. The\ngeneral forking lemma provides an instrumental lower bound for the probability\nof extracting a witness from an adversary who provides two proofs for the same\nstatement that share the first message. Since $\\plonkprot$ and $\\sonicprot$ have\nmore than $3$ messages and are not special-sound, the forking lemma of Bellare\nand Neven~\\cite{CCS:BelNev06}, cannot be used directly. We propose a\ngeneralization that covers multi-message protocols where witness extraction\nrequires more transcripts than merely two. Unfortunately, we also observe that\nthe security gap grows with the number of transcripts and the probability that\nthe extractor succeeds diminishes significantly; the security loss, albeit big, is polynomial.\n\nMost modern zkSNARKs~\\cite{SP:BBBPWM18,CCS:MBKM19} heavily\nrely on the Fiat--Shamir transform and thus potentially the forking lemma. First, an interactive\nprotocol is proposed and its security and forking soundness analysed. Second,\none uses an argument that the Fiat--Shamir transform can be used to get a\nprotocol that is non-interactive and shares the same security properties.\n\nWe see our generalized forking lemma as contributing to a critical assessment of\nthis approach. The analysis of the interactive protocol is not enough and one\nhas to consider the security loss implied by the Fiat-Shamir transform for the target security notion. Thus one has to either rely on our generalisation of the forking\nlemma or disclose a transformation that does not suffer this loss. We note that\nthe security loss may also apply when knowledge soundness is proven. That is the\ncase for the original $\\sonic$ paper, whose security proof relies on so-called witness-extended\nemulation. The authors of $\\plonk$ and recent work on $\\sonic$~\\cite{cryptoeprint:2020:1351} work around this problem by proving\nknowledge soundness directly in the AGM.\n\n\n\n\\subsection{Related Work}\n \n\n\\ourpar{Simulation extractability.}\nThere are many results on simulation extractability for\nnon-interactive zero-knowledge proofs (NIZKs). First, Groth \\cite{AC:Groth07}\nnoticed that a (black-box) SE NIZK is\nuniversally-composable (UC)~\\cite{EPRINT:Canetti00}. Then Dodis et al.~\\cite{AC:DHLW10} introduced a\nnotion of (black-box) \\emph{true simulation extractability} and showed that no\nNIZK can be UC-secure if it does not have this property. \n\nIn the context of zkSNARKs, the first\nSE zkSNARK was proposed by Groth and Maller~\\cite{C:GroMal17} and SE\nzkSNARK for QAP by Lipmaa~\\cite{EPRINT:Lipmaa19a}. \nKosba's et\nal.~\\cite{EPRINT:KZMQCP15} give a general transformation from a NIZK to a\nblack-box SE NIZK. Although their transformation works for zkSNARKs as well,\nsuccinctness of the proof system is not preserved by the transformation.\nRecently, Abdolmaleki et al.~\\cite{CCS:AbdRamSla20} showed another transformation that\nobtains non-black-box simulation extractability but also preserves\nsuccinctness of the argument. \nThe zkSNARK of~\\cite{EC:Groth16} has been shown to be SE by introducing minor modifications to the construction and making\nstronger assumptions \\cite{EPRINT:BowGab18,EPRINT:AtaBag19}. Recently,~\\cite{EPRINT:BKSV20} showed that the\noriginal Groth's proof system from~\\cite{EC:Groth16} is weakly SE and\nrandomizable. None of these results are for zkSNARKs in the updatable SRS setting.\n\n\\ourpar{Forking lemma generalizations.}\nThere are several task specific variants, e.g.,~\\cite{INDOCRYPT:HerSae03,CCS:BagCheJar08,AC:BelDaiLi19}, of the general forking lemma~\\cite{JC:PoiSte00,CCS:BelNev06} for analyzing the forking behavior of random-oracle based executions.\nIn~\\cite{EC:BCCGP16}, Bootle et al.~proposed a novel inner-product argument which\nsecurity relies on, so-called, witness-extended emulation. To show that\nproperty, the authors proposed a new version of forking lemma, which gives a\nlower bound on probability that a tree finding algorithm is able to produce a \ntree of acceptable transcripts by rewinding a conversation between a\n(potentially malicious) prover and verifier.\n\nAlthough the result in that paper is dubbed a ``forking lemma'' it\ndiffers from forking lemmas known from e.g.~\\cite{JC:PoiSte00,CCS:BelNev06}.\nFirst of all, the forking lemmas in these papers analyse the probability of building\na tree of acceptable transcripts for Fiat--Shamir based non-interactive proof\nsystems, while the protocol presented by Bootle et al.~is intended to work for\ninteractive proof systems.\n\nImportantly, it is not obvious how the result of Bootle et al.~can be used to\nshow security of non-interactive protocols as it relies on interactive provers\nwhose proving strategies are more limited than proving strategies of\nnon-interactive provers. For example, if a challenge given by the verifier does not\nsuit an interactive prover, it can only try to finish a proof with it or\nabort. On the other hand, a non-interactive prover has far wider scope of\npossible actions--when the protocol is non-interactive the prover may\nadapt its strategy based on the random oracle outputs. \nThis is reminiscent of \\emph{state restoration} security~\\cite{TCC:BenChiSpo16,EPRINT:Holmgren19} which is also about the security loss incurred by FS transformation for knowledge soundness from witness extended emulation.\n\nHere, we directly capture the state restoration capability of the prover in the forking lemma instead of defining an interactive game where the prover can rewind the verifier to an earlier state as is done in~\\cite{C:GhoTes21}. \nThe work of~\\cite{C:GhoTes21} further shows that state restoration security gives tight security guarantees for the\nnon-interactive versions of Bulletproof~\\cite{SP:BBBPWM18} and \\sonic~. \nOur work differs from~\\cite{C:GhoTes21} in the following ways. First, they\nfocus on showing security of concrete proof systems, while we show\na general theorem about the security of a wide class of protocols. \nSecond, they only consider knowledge soundness, while we focus on the stronger notion of simulation extractability. Third, the proof of~\\cite{C:GhoTes21} is in the AGM which allows for online extraction, whereas we aim to minimize our reliance on the AGM. In particular, our main theorem does not rely on AGM and we tackle technical challenges arising from extraction by rewinding. \nHowever, note that we show that concrete protocols satisfy the preconditions of our main theorem in the AGM.\n\n ", "meta": {"hexsha": "dd1d50752388b6a9b1d8f99828ce9ccc21d08f4c", "size": 22402, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "ECsubmission/intro.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/intro.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/intro.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": 88.1968503937, "max_line_length": 773, "alphanum_fraction": 0.8025622712, "num_tokens": 5462, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165085228825, "lm_q2_score": 0.3345894545235253, "lm_q1q2_score": 0.17643454294792113}}
{"text": "\\documentclass[12pt]{article}\n\\usepackage{graphics}\n\\begin{document}\n\n\\section*{NYU Physics 1---Final Exam}\n\n\\vfill\n\n\\paragraph{Name:} ~\n\n\\paragraph{email:} ~\n\n\\paragraph{recitation:} ~\n\n\\vfill\n\nThis exam consists of six problems. Write only in this booklet. Be\nsure to show your work.\n\n\\vfill\n\n\\emph{You must ensure that the proctor checks off your name on the\nattendence sheet when you hand in your exam. Your exam will\n\\textbf{not} be graded if your name is not checked off.}\n\n\\clearpage\n\n\\section*{Problem 1}\n\n(a) A block of mass $M$ slides down a plane inclined at an angle\n$\\theta$ to the horizontal. There is a coefficient of sliding\nfriction $\\mu$ between block and plane. What is the magnitude of the\nacceleration $a$ of the block down the plane? Be sure to draw a\nfree-body diagram.\n\n\\vfill\n\n(b) A \\emph{different} block of mass $M$ sits on the same plane. In\nthis case, the frictional force is so great that the block does not\nslide down the plane. What is the magnitude $f$ and direction of the\nfrictional force? Try to give your answer in terms of $M$, $g$ and\n$\\theta$ only.\n\n\\vfill ~\n\n\\clearpage\n\n\\section*{Problem 2}\n\nA block of mass $M$, initially at rest, hangs from a massless string.\nA bullet of mass $m$ travelling at speed $v$ lodges in the block. The\nblock (now of mass $M+m$) recoils and swings on the string. To what\nmaximum height $h_\\mathrm{max}$ does the block swing, relative to its\nstarting position?\n\n\\clearpage\n\n\\section*{Problem 3}\n\nA Japanese Shinkansen (bullet train) (of mass $M=2\\times\n10^5~\\mathrm{kg}$), moving at $v_S=250~\\mathrm{km\\,h^{-1}}$ with\nrespect to the tracks, hits and collides elastically with a superball\n(of mass $m=4~\\mathrm{g}$), which is initially at rest. The front\nface of the train is inclined at an angle of $\\theta=45~\\mathrm{deg}$\nto the horizontal, as shown.\n\\\\ \\rule{0.1\\textwidth}{0pt}\n\\resizebox{0.8\\textwidth}{!}{\\includegraphics{../mp/shinkansen.eps}}\n\n(a) Draw a diagram of the ball--train system, just before the\ncollision, in the center-of-mass rest frame, ie, as observed by an\nobserver at rest with respect to the center of mass. Clearly show the\nvelocities of the ball and train in this frame.\n\n\\vfill\n\n(b) What is the final speed and direction of the ball, immediately\nafter the collision, in the rest frame of the tracks (ie, \\emph{not}\nin the center-of-mass frame)?\n\n\\vfill ~\n\n\\clearpage\n\n\\section*{Problem 4}\n\n(a) Why does a ball roll down an inclined ramp more slowly than a\nfrictionless block would slide down the same ramp? Give a concise,\nverbal, physical explanation.\n\n\\vfill\n\n(b) Imagine rolling a solid spherical wooden ball and a thin steel\nhoop down a plane inclined at an angle of 25~deg to the horizontal.\nThe wooden ball has mass $m=1~\\mathrm{kg}$ and radius\n$R=7~\\mathrm{cm}$ and the steel hoop has mass $m=5~\\mathrm{kg}$ and\nradius $R=15~\\mathrm{cm}$. Assume that they both roll without\nslipping. In the absence of air resistance, which will roll down the\nplane with greater acceleration? Explain your answer with a concise,\nverbal, physical explanation, backed-up with formulae \\emph{only if\nnecessary.} (It shouldn't be necessary.)\n\n\\vfill ~\n\n\\clearpage\n\n\\section*{Problem 5}\n\nA ``seconds'' pendulum has a period of exactly 2.0 seconds.\n\n(a) If $g=9.793~\\mathrm{m\\,s^{-2}}$ in Austin Texas, how long should a\nTexan make her or his seconds pendulum?\n\n\\vfill\n\n(b) If $g$ is 0.1~percent larger in Paris, France, than in Austin, how\ndifferent, in percent, should the length of a Parisian's seconds\npendulum be than a Texan's? Should it be longer or shorter?\n\\emph{Note:} You can answer this question without getting part (a)\ncorrect.\n\n\\vfill ~\n\n\\clearpage\n\n\\section*{Problem 6}\n\nConsider the following attractive radial force law, which is\n\\emph{very different} from Newton's law of gravity:\n\\begin{equation}\nF = \\frac{k\\,M\\,m}{r^3}\n\\end{equation}\nWhere $k$ is a constant. Consider a body of mass $m$ orbiting in a\ncircular orbit of radius $R$ around another body of mass $M$, with\n$m\\ll M$, according to the above force law.\n\n(a) What are the dimensions of the constant $k$, in terms of kg, m and\ns?\n\n\\vfill\n\n(b) What is the period of the orbit $T$ as a function of radius $R$?\n\n\\vfill\n\n(c) What is the potential energy of the mass $m$ at radius $R$,\nrelative to the potential energy at infinity?\n\n\\vfill ~\n\n\\clearpage\n\n[This page intentionally left blank for calculations or other work.]\n\n\\end{document}\n", "meta": {"hexsha": "51eb7f674128ecbd3807496aa7136c98b3be0a7d", "size": 4417, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "tex/old/final_2001.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/final_2001.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/final_2001.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": 28.4967741935, "max_line_length": 70, "alphanum_fraction": 0.7333031469, "num_tokens": 1275, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.480478678047907, "lm_q2_score": 0.3665897432423098, "lm_q1q2_score": 0.17613855521898666}}
{"text": "\\documentclass{article}\n\\usepackage[utf8]{inputenc}\n\\usepackage{mathtools} % Required for display matrices. Extension on top of amsmath package.\n\\usepackage{bm} % for rendering vectors correctly\n\\usepackage{xcolor}\n\\usepackage{amssymb} % for rendering dimension symbol R\n\\usepackage[nocfg,notintoc]{nomencl}\n\\makenomenclature\n\\usepackage{booktabs}\n%\\renewcommand{\\arraystretch}{2.0} % affects matrices too.\n\\usepackage[letterpaper, hmargin=0.8in]{geometry}\n\\usepackage{fancyhdr}\n\\pagestyle{fancy}\n\n% with this we ensure that the chapter and section\n% headings are in lowercase.\n%\\renewcommand{\\chaptermark}[1]{\\markboth{#1}{}}\n\\renewcommand{\\sectionmark}[1]{%\n\\markright{\\thesection\\ #1}}\n\\fancyhf{} % delete current header and footer\n\\fancyhead[L,R]{\\bfseries\\thepage}\n\\fancyhead[LO]{\\bfseries\\rightmark}\n%\\fancyhead[RE]{\\bfseries\\leftmark}\n\\renewcommand{\\headrulewidth}{0.5pt}\n\\renewcommand{\\footrulewidth}{0pt}\n\\addtolength{\\headheight}{0.5pt} % space for the rule\n\\fancypagestyle{plain}{%\n\\fancyhead{} % get rid of headers on plain pages\n\\renewcommand{\\headrulewidth}{0pt} % and the line\n}\n\n\\usepackage{biblatex}\n\\addbibresource{BackPropagationBasicMatrixOperations.bib}\n\n% hyperref package doesn't seem to be working.\n\n\n\\renewcommand{\\nomname}{} % We don't to use any word here.\n\\newcommand{\\transpose}[1]{#1^\\top}\n\\newcommand{\\vecr}[1]{\\bm{#1}}\n\\newcommand{\\matr}[1]{\\mathbf{#1}} % undergraduate algebra version\n%\\newcommand{\\matr}[1]{#1} % pure math version\n%\\newcommand{\\matr}[1]{\\bm{#1}} % ISO complying version\n\n\\newcommand{\\eqncomment}[1]{\n\\footnotesize\n\\textcolor{gray}{\n\\begin{pmatrix*}[l]\n\\text{#1}\n\\end{pmatrix*}\n}}\n\\newcommand{\\longeqncomment}[2]\n{\\footnotesize\n\\textcolor{gray}{\n\\begin{pmatrix*}[l]\n\\text{#1} \\\\\n\\text{#2}\n\\end{pmatrix*}\n}}\n\n\\title{CS231N: Backpropagation - Vector and Matrix Calculus}\n\\author{\n Ashish Jain \\\\\n Stanford University \\\\\n \\texttt{ashishj@stanford.edu/cs231n@ashishjain.io}\n }\n\\date{\\today}\n\n\\begin{document}\n\\pagestyle{empty}\n\\maketitle\n\n\\tableofcontents\n\n\\newpage\n\\pagestyle{fancy}\n\\section{Introduction}\n\\subsection{Intended Audience}\nThis document is primarily targeted towards CS231N students who don't have a formal background in vector and matrix calculus.\n\n\\subsection{Learning Goals}\nCS231N assignments have a heavy emphasis on vector and matrix calculus. Several different notation and layout conventions are popular in the literature which can be confusing and overwhelming for students just starting out with vector and matrix calculus. This document firmly aligns and sticks with the layout conventions for matrix calculus taught in CS231N lectures \\cite{li_krishna_xu_2021}. This document hopes to bring the students who lack a formal background in vector and matrix calculus up to speed as well as serve as a reference while solving the various assignments. \n\n\\subsection{Content}\nThrough small non-trivial examples, we show how and why certain backpropagation operations reduce to the equations they reduce to for basic operations such as matrix multiplication, some element-wise operation on a matrix, element-wise operations between two matrices, reductions of a matrix to a vector and broadcasting of a vector to a matrix. The example matrices and vectors are deliberately kept small to ensure one can convince oneself or alternately verify on paper if the contents of this document are correct (please feel free to submit bugs or corrections). The examples considered while small are kept as general as possible throughout the derivations. Therefore, a motivated student can easily extend these examples to general proofs.\n\nEach section from section \\ref{Matrix Multiplication} onward is written independently of each other, and therefore, you can directly jump to a section of your interest.\n\n\\section{Nomenclature}\n\\vspace{-2.5em}\n\\nomenclature[N]{\\(\\vecr{x}\\)}{Row or column vector}\n\\nomenclature[N]{\\(\\matr{X}\\)}{Two dimensional matrix}\n\\nomenclature[N]{\\(L\\)}{Loss/Cost scalar}\n\\nomenclature[N]{\\(\\mathbb{R}\\)}{Real numbers}\n\\nomenclature[O]{\\(\\mathrm{d}\\text{Variable}\\)}{$\\frac{\\partial L}{\\partial \\text{Variable}}$}\n\n\\printnomenclature\n\n\\section{Layout Convention}\nGiven a vector $\\vecr{y}$ where $\\bm{y} \\in \\mathbb{R}^{m}$ and a vector $\\bm{x}$ where $\\bm{x} \\in \\mathbb{R}^{n}$, we are going to follow the \\textbf{denominator layout} convention whereby $\\frac{\\partial y}{\\partial x}$ is written as $n \\times m$ matrix. This is in contrast to the \\textbf{numerator layout} whereby $\\frac{\\partial y}{\\partial x}$ is written as $m \\times n$ matrix. For more details, please refer to the Wikipedia page \\cite{wiki:Matrix_calculus}.\n\nFor example, if $\\bm{x} \\in \\mathbb{R}^{3}$ and $\\bm{y} \\in \\mathbb{R}^{2}$ then:\n\n\\begin{flalign}\n\\frac{\\partial \\bm{y}}{\\partial \\bm{x}} &= \n\\begin{bmatrix}\n\\frac{\\partial y_{1}}{\\partial x_{1}} & \\frac{\\partial y_{2}}{\\partial x_{1}} \\\\[0.5em]\n\\frac{\\partial y_{1}}{\\partial x_{2}} & \\frac{\\partial y_{2}}{\\partial x_{2}} \\\\[0.5em]\n\\frac{\\partial y_{1}}{\\partial x_{3}} & \\frac{\\partial y_{2}}{\\partial x_{3}} \\\\[0.5em]\n\\end{bmatrix}\n& \\longeqncomment{Denominator layout where layout is according to $\\transpose{\\vecr{y}}$ across axis 1 and $\\vecr{x}$ across axis 0.}{In other words, the elements of $\\vecr{y}$ are laid out in columns and the elements of $\\vecr{x}$ are laid out in rows.}\n\\nonumber\n\\end{flalign}\n\n\\section{Summary}\n\\small\n\\begin{tabular}{cllll}\n\\toprule\nIndex & Name & $\\matr{Z}$/$\\vecr{z}$ & $\\frac{\\partial L}{\\partial \\matr{X}}$/$\\frac{\\partial L}{\\partial \\vecr{x}}$ & $\\frac{\\partial L}{\\partial \\matr{Y}}$/$\\frac{\\partial L}{\\partial \\vecr{y}}$ \\\\[0.3em]\n\n\\midrule\n\n1 & Matrix Multiplication & $\\matr{Z} = \\matr{X}\\matr{Y}$ &\n$\\frac{\\partial L}{\\partial \\matr{X}}=\\frac{\\partial L}{\\partial \\matr{Z}} \\transpose{\\matr{Y}}$ &\n$\\frac{\\partial L}{\\partial \\matr{Y}}=\\transpose{\\matr{X}} \\frac{\\partial L}{\\partial \\matr{Z}}$ \\\\[1em]\n\n2 & Element-wise function & $\\matr{Z} = g(\\matr{X})$ &\n$\\frac{\\partial L}{\\partial \\matr{X}}=g'(\\matr{X}) \\circ \\frac{\\partial L}{\\partial \\matr{Z}}$ & \\\\[1em]\n\n3 & Hadamard Product & $\\matr{Z} = \\matr{X} \\circ \\matr{Y}$ &\n$\\frac{\\partial L}{\\partial \\matr{X}}=\\matr{Y} \\circ \\frac{\\partial L}{\\partial \\matr{Z}}$ &\n$\\frac{\\partial L}{\\partial \\matr{Y}}=\\matr{X} \\circ \\frac{\\partial L}{\\partial \\matr{Z}}$ \\\\[1em]\n\n4 & Matrix Addition & $\\matr{Z} = \\matr{X} + \\matr{Y}$ &\n$\\frac{\\partial L}{\\partial \\matr{X}}=\\frac{\\partial L}{\\partial \\matr{Z}}$ &\n$\\frac{\\partial L}{\\partial \\matr{Y}}=\\frac{\\partial L}{\\partial \\matr{Z}}$\\\\[1em]\n\n5 & Transpose & $\\matr{Z} = \\transpose{\\matr{X}}$ &\n$\\frac{\\partial L}{\\partial \\matr{X}}=\\transpose{\\frac{\\partial L}{\\partial \\matr{Z}}}$ & \\\\[1em]\n\n6 & Sum along axis=0 & $\\vecr{z}$ = \\verb|np.sum(|${\\matr{X}}$\\verb|, axis=0)| &\n$\\frac{\\partial L}{\\partial \\matr{X}}=\\mathbf{1}_{\\text{rows}(\\matr{X}),1} \\frac{\\partial L}{\\partial \\vecr{z}}$ & \\\\[1em]\n\n7 & Sum along axis=1 & $\\vecr{z}$ = \\verb|np.sum(|${\\matr{X}}$\\verb|, axis=1)| &\n$\\frac{\\partial L}{\\partial \\matr{X}}=\\frac{\\partial L}{\\partial \\vecr{z}} \\mathbf{1}_{1, \\text{cols}(\\matr{X})}$ & \\\\[1em]\n\n8 & Broadcasting a column vector & $\\matr{Z} = \\vecr{x} \\mathbf{1}_{1,\\text{C}}$ &\n$\\frac{\\partial L}{\\partial \\vecr{x}}=\\mathtt{np.sum(} \\frac{\\partial L}{\\partial \\matr{Z}} \\mathtt{, axis=1)}$ & \\\\[1em]\n\n9 & Broadcasting a row vector & $\\matr{Z} = \\mathbf{1}_{\\text{R},1} \\vecr{x}$ &\n$\\frac{\\partial L}{\\partial \\vecr{x}}=\\mathtt{np.sum(} \\frac{\\partial L}{\\partial \\matr{Z}} \\mathtt{, axis=0)}$ & \\\\[0.3em]\n\\bottomrule\n\\end{tabular}\n\n\\normalsize\n\n\\section{NumPy}\n\\footnotesize\n\\begin{tabular}{cllll}\n\\toprule\nIndex & Name & $\\matr{Z}$/$\\vecr{z}$ &\n\\verb dX = $\\frac{\\partial L}{\\partial \\matr{X}}$/ \\verb dx = $\\frac{\\partial L}{\\partial \\vecr{x}}$ &\n\\verb dY = $\\frac{\\partial L}{\\partial \\matr{Y}}$/ \\verb dy = $\\frac{\\partial L}{\\partial \\vecr{y}}$ \\\\[0.3em]\n\n\\midrule\n1 & Matrix Multiplication & \\verb Z = \\verb X@Y &\n\\verb dX = \\verb dZ@Y.T &\n\\verb dY = \\verb X.T@dZ \\\\[0.7em]\n\n2 & Element-wise function & \\verb Z = \\verb g(X) &\n\\verb dX = \\verb g'(X) *\\verb dZ & \\\\[0.7em]\n\n3 & Hadamard Product & \\verb Z = \\verb X*Y &\n\\verb dX = \\verb Y*dZ &\n\\verb dY = \\verb X*dZ \\\\[0.7em]\n\n4 & Matrix Addition & \\verb Z = \\verb X+Y &\n\\verb dX = \\verb dZ &\n\\verb dY = \\verb dZ \\\\[0.7em]\n\n5 & Transpose & \\verb Z = \\verb X.T &\n\\verb dX = \\verb dZ.T & \\\\[0.7em]\n\n6 & Sum along axis=0 & \\verb z = \\verb|np.sum(X,axis=0)| &\n\\verb dX = \\verb|np.ones((X.shape[0],1))@dz| & \\\\[0.7em]\n\n7 & Sum along axis=1 & \\verb z = \\verb|np.sum(X,axis=1)| &\n\\verb dX = \\verb|dz@np.ones((1,X.shape[1]))| & \\\\[0.7em]\n\n8 & Broadcasting a column vector & \\verb Z = \\verb|x+np.zeros((1,C))| &\n\\verb dx = \\verb|np.sum(dZ,axis=1)| & \\\\[0.7em]\n\n9 & Broadcasting a row vector & \\verb Z = \\verb|x+np.zeros((R,1))| &\n\\verb dx = \\verb|np.sum(dZ,axis=0)| & \\\\[0.3em]\n\\bottomrule\n\\end{tabular}\n\n\\normalsize\n\\section{Matrix Multiplication} \\label{Matrix Multiplication}\n\\subsection{Forward Pass}\nLet $\\matr{X}$ be a $2 \\times 3$ matrix, and let $\\matr{Y}$ be a $3 \\times 2$ matrix. Let $\\matr{Z} = \\matr{X}\\matr{Y}$.\n\n\\begin{flalign}\n\\matr{X} &=\n\\begin{bmatrix}\nx_{1,1} & x_{1,2} & x_{1,3} \\\\%[0.5em]\nx_{2,1} & x_{2,2} & x_{2,3} \\\\%[0.5em]\n\\end{bmatrix} &\n\\nonumber\n\\end{flalign}\n\n\\begin{flalign}\n\\matr{Y} &=\n\\begin{bmatrix}\ny_{1,1} & y_{1,2} \\\\%[0.5em]\ny_{2,1} & y_{2,2} \\\\%[0.5em]\ny_{3,1} & y_{3,2} \\\\%[0.5em]\n\\end{bmatrix} &\n\\nonumber\n\\end{flalign}\n\n\\vspace{1em}\n\\noindent Given $\\matr{Z} = \\matr{X}\\matr{Y}$, Z is a $2 \\times 2$ matrix which can be expressed as:\n\n\\begin{flalign}\n\\matr{Z} &= \\begin{bmatrix}\nz_{1,1} & z_{1,2}\\\\[0.5em]\nz_{2,1} & z_{2,2}\\\\[0.5em]\n\\end{bmatrix}\n&\n\\nonumber\n\\\\\n&=\n\\begin{bmatrix}\nx_{1,1}.y_{1,1} + x_{1,2}.y_{2,1} + x_{1,3}.y_{3,1} & x_{1,1}.y_{1,2} + x_{1,2}.y_{2,2} + x_{1,3}.y_{3,2}\\\\[0.5em]\nx_{2,1}.y_{1,1} + x_{2,2}.y_{2,1} + x_{2,3}.y_{3,1} & x_{2,1}.y_{1,2} + x_{2,2}.y_{2,2} + x_{2,3}.y_{3,2}\\\\[0.5em]\n\\end{bmatrix}\n\\nonumber\n\\end{flalign}\n\n\\subsection{Backward Pass}\nWe are given $\\frac{\\partial L}{\\partial \\matr{Z}}$. It will be of shape $2 \\times 2$.\n\n\\begin{flalign}\n\\frac{\\partial L}{\\partial \\matr{Z}} &=\n\\begin{bmatrix}\n\\frac{\\partial L}{\\partial z_{1,1}} & \\frac{\\partial L}{\\partial z_{1,2}} \\\\[0.5em]\n\\frac{\\partial L}{\\partial z_{2,1}} & \\frac{\\partial L}{\\partial z_{2,2}} \\\\[0.5em]\n\\end{bmatrix} & \\eqncomment{$\\frac{\\partial L}{\\partial \\matr{Z}}$ is the same shape as $\\matr{Z}$ as $L$ is a scalar} \\label{dZ_matrix_multiplication}\n\\end{flalign}\n\n\\noindent We need to compute $\\frac{\\partial L}{\\partial \\matr{X}}$ and $\\frac{\\partial L}{\\partial \\matr{Y}}$. Using chain rule, we get:\n\n\\begin{flalign} \\label{dX_matrix_multiplication}\n\\frac{\\partial L}{\\partial \\matr{X}} &= \\frac{\\partial \\matr{Z}}{\\partial \\matr{X}}\\frac{\\partial L}{\\partial \\matr{Z}} &\n\\end{flalign}\n\n\\begin{flalign} \\label{dY_matrix_multiplication}\n\\frac{\\partial L}{\\partial \\matr{Y}} &= \\frac{\\partial \\matr{Z}}{\\partial \\matr{Y}}\\frac{\\partial L}{\\partial \\matr{Z}} &\n\\end{flalign}\n\n\\subsubsection{Computing $\\frac{\\partial L}{\\partial \\matr{X}}$}\nTo compute $\\frac{\\partial L}{\\partial \\matr{X}}$, we need to compute $\\frac{\\partial \\matr{Z}}{\\partial \\matr{X}}$. To make it easy for us to think about and capture the Jacobian in a two dimensional matrix (as opposed to a tensor), we will reshape matrices $\\matr{X}$, $\\matr{Y}$ and $\\matr{Z}$ as column vectors, and compute Jacobians on them. Once we have computed the column vector corresponding to $\\frac{\\partial L}{\\partial \\matr{X}}$, we will reshape it back to a matrix with the same shape as $\\matr{X}$.\n\n\\begin{flalign}\n\\frac{\\partial \\matr{Z}}{\\partial \\matr{X}} &=\n\\begin{bmatrix}\n\\frac{\\partial z_{1,1}}{\\partial x_{1,1}} & \\frac{\\partial z_{1,2}}{\\partial x_{1,1}} & \\frac{\\partial z_{2,1}}{\\partial x_{1,1}} & \\frac{\\partial z_{2,2}}{\\partial x_{1,1}} \\\\[0.5em]\n\\frac{\\partial z_{1,1}}{\\partial x_{1,2}} & \\frac{\\partial z_{1,2}}{\\partial x_{1,2}} & \\frac{\\partial z_{2,1}}{\\partial x_{1,2}} & \\frac{\\partial z_{2,2}}{\\partial x_{1,2}} \\\\[0.5em]\n\\frac{\\partial z_{1,1}}{\\partial x_{1,3}} & \\frac{\\partial z_{1,2}}{\\partial x_{1,3}} & \\frac{\\partial z_{2,1}}{\\partial x_{1,3}} & \\frac{\\partial z_{2,2}}{\\partial x_{1,3}} \\\\[0.5em]\n\\frac{\\partial z_{1,1}}{\\partial x_{2,1}} & \\frac{\\partial z_{1,2}}{\\partial x_{2,1}} & \\frac{\\partial z_{2,1}}{\\partial x_{2,1}} & \\frac{\\partial z_{2,2}}{\\partial x_{2,1}} \\\\[0.5em]\n\\frac{\\partial z_{1,1}}{\\partial x_{2,2}} & \\frac{\\partial z_{1,2}}{\\partial x_{2,2}} & \\frac{\\partial z_{2,1}}{\\partial x_{2,2}} & \\frac{\\partial z_{2,2}}{\\partial x_{2,2}} \\\\[0.5em]\n\\frac{\\partial z_{1,1}}{\\partial x_{2,3}} & \\frac{\\partial z_{1,2}}{\\partial x_{2,3}} & \\frac{\\partial z_{2,1}}{\\partial x_{2,3}} & \\frac{\\partial z_{2,2}}{\\partial x_{2,3}} \\\\[0.5em]\n\\end{bmatrix}\n& \\eqncomment{$\\matr{X}$, $\\matr{Z}$ are being treated as column vectors. Therefore, $\\frac{\\partial \\matr{Z}}{\\partial \\matr{X}}$ is of shape $6\\times4$.}\n\\nonumber \\\\\n\\label{dZbydX_matrix_multiplication}\n&=\n\\begin{bmatrix}\ny_{1,1} & y_{1,2} & 0 & 0 \\\\[0.5em]\ny_{2,1} & y_{2,2} & 0 & 0 \\\\[0.5em]\ny_{3,1} & y_{3,2} & 0 & 0 \\\\[0.5em]\n0 & 0 & y_{1,1} & y_{1,2} \\\\[0.5em]\n0 & 0 & y_{2,1} & y_{2,2} \\\\[0.5em]\n0 & 0 & y_{3,1} & y_{3,2} \\\\[0.5em]\n\\end{bmatrix}\n\\end{flalign}\n\n\\noindent Now, $\\frac{\\partial L}{\\partial \\matr{Z}}$ in equation \\ref{dZ_matrix_multiplication} expressed as a column vector will be:\n\n\\begin{flalign}\n\\label{dZAsColumnVector_matrix_multiplication}\n\\frac{\\partial L}{\\partial \\matr{Z}} &=\n\\begin{bmatrix}\n\\frac{\\partial L}{\\partial z_{1,1}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{1,2}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{2,1}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{2,2}} \\\\[0.7em]\n\\end{bmatrix} & \\eqncomment{Reshaping $\\frac{\\partial L}{\\partial \\matr{Z}}$ from shape $2 \\times 2$ to $4 \\times 1$}\n\\end{flalign}\n\n\\noindent Plugging equations \\ref{dZbydX_matrix_multiplication} and \\ref{dZAsColumnVector_matrix_multiplication} into equation \\ref{dX_matrix_multiplication}, we get:\n\n\\begin{flalign}\n\\frac{\\partial L}{\\partial \\matr{X}} &=\n\\frac{\\partial \\matr{Z}}{\\partial \\matr{X}}\\frac{\\partial L}{\\partial \\matr{Z}} &\n\\nonumber \\\\\n&=\n\\begin{bmatrix}\ny_{1,1} & y_{1,2} & 0 & 0 \\\\[0.5em]\ny_{2,1} & y_{2,2} & 0 & 0 \\\\[0.5em]\ny_{3,1} & y_{3,2} & 0 & 0 \\\\[0.5em]\n0 & 0 & y_{1,1} & y_{1,2} \\\\[0.5em]\n0 & 0 & y_{2,1} & y_{2,2} \\\\[0.5em]\n0 & 0 & y_{3,1} & y_{3,2} \\\\[0.5em]\n\\end{bmatrix}\n\\begin{bmatrix}\n\\frac{\\partial L}{\\partial z_{1,1}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{1,2}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{2,1}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{2,2}} \\\\[0.7em]\n\\end{bmatrix}\n& \\eqncomment{$\\matr{X}$, $\\matr{Z}$ and $\\frac{\\partial L}{\\partial \\matr{Z}}$ are being treated as column vectors}\n\\nonumber \\\\ \n&= \n\\begin{bmatrix}\ny_{1,1}.\\frac{\\partial L}{\\partial z_{1,1}} + y_{1,2}.\\frac{\\partial L}{\\partial z_{1,2}} \\\\[0.7em]\ny_{2,1}.\\frac{\\partial L}{\\partial z_{1,1}} + y_{2,2}.\\frac{\\partial L}{\\partial z_{1,2}} \\\\[0.7em]\ny_{3,1}.\\frac{\\partial L}{\\partial z_{1,1}} + y_{3,2}.\\frac{\\partial L}{\\partial z_{1,2}} \\\\[0.7em]\ny_{1,1}.\\frac{\\partial L}{\\partial z_{2,1}} + y_{1,2}.\\frac{\\partial L}{\\partial z_{2,2}} \\\\[0.7em]\ny_{2,1}.\\frac{\\partial L}{\\partial z_{2,1}} + y_{2,2}.\\frac{\\partial L}{\\partial z_{2,2}} \\\\[0.7em]\ny_{3,1}.\\frac{\\partial L}{\\partial z_{2,1}} + y_{3,2}.\\frac{\\partial L}{\\partial z_{2,2}} \\\\[0.7em]\n\\end{bmatrix} \\label{dXAsColumnVector_matrix_multiplication}\n\\end{flalign}\n\n\\noindent Reshaping column vector in equation \\ref{dXAsColumnVector_matrix_multiplication} as a matrix of shape $\\matr{X}$, we get:\n\\begin{flalign}\n\\frac{\\partial L}{\\partial \\matr{X}} &=\n\\begin{bmatrix}\ny_{1,1}.\\frac{\\partial L}{\\partial z_{1,1}} + y_{1,2}.\\frac{\\partial L}{\\partial z_{1,2}} &\ny_{2,1}.\\frac{\\partial L}{\\partial z_{1,1}} + y_{2,2}.\\frac{\\partial L}{\\partial z_{1,2}} &\ny_{3,1}.\\frac{\\partial L}{\\partial z_{1,1}} + y_{3,2}.\\frac{\\partial L}{\\partial z_{1,2}} \\\\[0.7em]\ny_{1,1}.\\frac{\\partial L}{\\partial z_{2,1}} + y_{1,2}.\\frac{\\partial L}{\\partial z_{2,2}} &\ny_{2,1}.\\frac{\\partial L}{\\partial z_{2,1}} + y_{2,2}.\\frac{\\partial L}{\\partial z_{2,2}} &\ny_{3,1}.\\frac{\\partial L}{\\partial z_{2,1}} + y_{3,2}.\\frac{\\partial L}{\\partial z_{2,2}} \\\\[0.7em]\n\\end{bmatrix}\n\\nonumber \\\\ \n&=\n\\begin{bmatrix}\n\\frac{\\partial L}{\\partial z_{1,1}} & \\frac{\\partial L}{\\partial z_{1,2}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{2,1}} & \\frac{\\partial L}{\\partial z_{2,2}} \\\\[0.7em]\n\\end{bmatrix}\n\\begin{bmatrix}\ny_{1,1} & y_{2,1} & y_{3,1} \\\\%[0.5em]\ny_{1,2} & y_{2,2} & y_{3,2} \\\\%[0.5em]\n\\end{bmatrix}\n& \\eqncomment{Decomposing into a matmul operation}\n\\nonumber \\\\\n&=\n\\underbrace{\n\\begin{bmatrix}\n\\frac{\\partial L}{\\partial z_{1,1}} & \\frac{\\partial L}{\\partial z_{1,2}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{2,1}} & \\frac{\\partial L}{\\partial z_{2,2}} \\\\[0.7em]\n\\end{bmatrix}}_{\\frac{\\partial L}{\\partial \\matr{Z}}}\n\\underbrace{\n\\transpose{\\begin{bmatrix}\ny_{1,1} & y_{1,2} \\\\%[0.5em]\ny_{2,1} & y_{2,2} \\\\%[0.5em]\ny_{3,1} & y_{3,2} \\\\%[0.5em]\n\\end{bmatrix}}}_{\\transpose{\\matr{Y}}}\n\\nonumber \\\\ \\label{dXFinal}\n&= \\frac{\\partial L}{\\partial \\matr{Z}} \\transpose{\\matr{Y}}\n\\end{flalign}\n\n\\subsubsection{Computing $\\frac{\\partial L}{\\partial \\matr{Y}}$}\nTo compute $\\frac{\\partial L}{\\partial \\matr{Y}}$, we need to compute $\\frac{\\partial \\matr{Z}}{\\partial \\matr{Y}}$. To make it easy for us to think about and capture the Jacobian in a two dimensional matrix (as opposed to a tensor), we will reshape matrices $\\matr{X}$, $\\matr{Y}$ and $\\matr{Z}$ as column vectors, and compute Jacobians on them. Once we have computed the column vector corresponding to $\\frac{\\partial L}{\\partial \\matr{Y}}$, we will reshape it back to a matrix with the same shape as $\\matr{Y}$.\n\n\\begin{flalign}\n\\frac{\\partial \\matr{Z}}{\\partial \\matr{Y}} &=\n\\begin{bmatrix}\n\\frac{\\partial z_{1,1}}{\\partial y_{1,1}} & \\frac{\\partial z_{1,2}}{\\partial y_{1,1}} & \\frac{\\partial z_{2,1}}{\\partial y_{1,1}} & \\frac{\\partial z_{2,2}}{\\partial y_{1,1}} \\\\[0.5em]\n\\frac{\\partial z_{1,1}}{\\partial y_{1,2}} & \\frac{\\partial z_{1,2}}{\\partial y_{1,2}} & \\frac{\\partial z_{2,1}}{\\partial y_{1,2}} & \\frac{\\partial z_{2,2}}{\\partial y_{1,2}} \\\\[0.5em]\n\\frac{\\partial z_{1,1}}{\\partial y_{2,1}} & \\frac{\\partial z_{1,2}}{\\partial y_{2,1}} & \\frac{\\partial z_{2,1}}{\\partial y_{2,1}} & \\frac{\\partial z_{2,2}}{\\partial y_{2,1}} \\\\[0.5em]\n\\frac{\\partial z_{1,1}}{\\partial y_{2,2}} & \\frac{\\partial z_{1,2}}{\\partial y_{2,2}} & \\frac{\\partial z_{2,1}}{\\partial y_{2,2}} & \\frac{\\partial z_{2,2}}{\\partial y_{2,2}} \\\\[0.5em]\n\\frac{\\partial z_{1,1}}{\\partial y_{3,1}} & \\frac{\\partial z_{1,2}}{\\partial y_{3,1}} & \\frac{\\partial z_{2,1}}{\\partial y_{3,1}} & \\frac{\\partial z_{2,2}}{\\partial y_{3,1}} \\\\[0.5em]\n\\frac{\\partial z_{1,1}}{\\partial y_{3,2}} & \\frac{\\partial z_{1,2}}{\\partial y_{3,2}} & \\frac{\\partial z_{2,1}}{\\partial y_{3,2}} & \\frac{\\partial z_{2,2}}{\\partial y_{3,2}} \\\\[0.5em]\n\\end{bmatrix}\n& \\eqncomment{$\\matr{Y}$, $\\matr{Z}$ are being treated as column vectors. Therefore, $\\frac{\\partial \\matr{Z}}{\\partial \\matr{Y}}$ is of shape $6\\times4$.}\n\\nonumber\n\\\\\n&=\n\\begin{bmatrix}\nx_{1,1} & 0 & x_{2,1} & 0 \\\\[0.5em]\n0 & x_{1,1} & 0 & x_{2,1} \\\\[0.5em]\nx_{1,2} & 0 & x_{2,2} & 0 \\\\[0.5em]\n0 & x_{1,2} & 0 & x_{2,2} \\\\[0.5em]\nx_{1,3} & 0 & x_{2,3} & 0 \\\\[0.5em]\n0 & x_{1,3} & 0 & x_{2,3} \\\\[0.5em]\n\\end{bmatrix} \\label{dZbydY_matrix_multiplication}\n\\end{flalign}\n\n\\noindent Plugging equations \\ref{dZbydY_matrix_multiplication} and \\ref{dZAsColumnVector_matrix_multiplication} into equation \\ref{dY_matrix_multiplication}, we get:\n\n\\begin{flalign}\n\\frac{\\partial L}{\\partial \\matr{Y}} &=\n\\begin{bmatrix}\nx_{1,1} & 0 & x_{2,1} & 0 \\\\[0.5em]\n0 & x_{1,1} & 0 & x_{2,1} \\\\[0.5em]\nx_{1,2} & 0 & x_{2,2} & 0 \\\\[0.5em]\n0 & x_{1,2} & 0 & x_{2,2} \\\\[0.5em]\nx_{1,3} & 0 & x_{2,3} & 0 \\\\[0.5em]\n0 & x_{1,3} & 0 & x_{2,3} \\\\[0.5em]\n\\end{bmatrix}\n\\begin{bmatrix}\n\\frac{\\partial L}{\\partial z_{1,1}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{1,2}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{2,1}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{2,2}} \\\\[0.7em]\n\\end{bmatrix}\n& \\eqncomment{$\\matr{Y}$, $\\matr{Z}$ and $\\frac{\\partial L}{\\partial \\matr{Z}}$ are being treated as column vectors}\n\\nonumber \\\\\n&=\n\\begin{bmatrix}\nx_{1,1}.\\frac{\\partial L}{\\partial z_{1,1}} + x_{2,1}.\\frac{\\partial L}{\\partial z_{2,1}} \\\\[0.7em]\nx_{1,1}.\\frac{\\partial L}{\\partial z_{1,2}} + x_{2,1}.\\frac{\\partial L}{\\partial z_{2,2}} \\\\[0.7em]\nx_{1,2}.\\frac{\\partial L}{\\partial z_{1,1}} + x_{2,2}.\\frac{\\partial L}{\\partial z_{2,1}} \\\\[0.7em]\nx_{1,2}.\\frac{\\partial L}{\\partial z_{1,2}} + x_{2,2}.\\frac{\\partial L}{\\partial z_{2,2}} \\\\[0.7em]\nx_{1,3}.\\frac{\\partial L}{\\partial z_{1,1}} + x_{2,3}.\\frac{\\partial L}{\\partial z_{2,1}} \\\\[0.7em]\nx_{1,3}.\\frac{\\partial L}{\\partial z_{1,2}} + x_{2,3}.\\frac{\\partial L}{\\partial z_{2,2}} \\\\[0.7em]\n\\end{bmatrix} \\label{dYAsColumnVector_matrix_multiplication}\n\\end{flalign}\n\n\\noindent Reshaping column vector in equation \\ref{dYAsColumnVector_matrix_multiplication} as a matrix of shape $\\matr{Y}$, we get:\n\n\\begin{flalign}\n\\frac{\\partial L}{\\partial \\matr{Y}} &=\n\\begin{bmatrix}\nx_{1,1}.\\frac{\\partial L}{\\partial z_{1,1}} + x_{2,1}.\\frac{\\partial L}{\\partial z_{2,1}} &\nx_{1,1}.\\frac{\\partial L}{\\partial z_{1,2}} + x_{2,1}.\\frac{\\partial L}{\\partial z_{2,2}} \\\\[0.7em]\nx_{1,2}.\\frac{\\partial L}{\\partial z_{1,1}} + x_{2,2}.\\frac{\\partial L}{\\partial z_{2,1}} &\nx_{1,2}.\\frac{\\partial L}{\\partial z_{1,2}} + x_{2,2}.\\frac{\\partial L}{\\partial z_{2,2}} \\\\[0.7em]\nx_{1,3}.\\frac{\\partial L}{\\partial z_{1,1}} + x_{2,3}.\\frac{\\partial L}{\\partial z_{2,1}} &\nx_{1,3}.\\frac{\\partial L}{\\partial z_{1,2}} + x_{2,3}.\\frac{\\partial L}{\\partial z_{2,2}} \\\\[0.7em]\n\\end{bmatrix}\n\\nonumber \\\\\n&=\n\\begin{bmatrix}\nx_{1,1} & x_{2,1} \\\\%[0.5em]\nx_{1,2} & x_{2,2} \\\\%[0.5em]\nx_{1,3} & x_{2,3} \\\\%[0.5em]\n\\end{bmatrix}\n\\begin{bmatrix}\n\\frac{\\partial L}{\\partial z_{1,1}} & \\frac{\\partial L}{\\partial z_{1,2}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{2,1}} & \\frac{\\partial L}{\\partial z_{2,2}} \\\\[0.7em]\n\\end{bmatrix}\n& \\eqncomment{Decomposing into a matmul operation}\n\\nonumber \\\\\n&=\n\\underbrace{\n\\transpose{\n\\begin{bmatrix}\nx_{1,1} & x_{1,2} & x_{1,3} \\\\%[0.5em]\nx_{2,1} & x_{2,2} & x_{2,3} \\\\%[0.5em]\n\\end{bmatrix}}}_{\\transpose{\\matr{X}}}\n\\underbrace{\n\\begin{bmatrix}\n\\frac{\\partial L}{\\partial z_{1,1}} & \\frac{\\partial L}{\\partial z_{1,2}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{2,1}} & \\frac{\\partial L}{\\partial z_{2,2}} \\\\[0.7em]\n\\end{bmatrix}}_{\\frac{\\partial L}{\\partial \\matr{Z}}}\n\\nonumber \\\\\n&= \\transpose{\\matr{X}} \\frac{\\partial L}{\\partial \\matr{Z}}\n\\end{flalign}\n\n\\section{Element-wise operation on a Matrix}\n\\subsection{Forward Pass}\nConsider some function $g(x)$ which is applied element-wise on a matrix $\\matr{X}$ of shape $3 \\times 2$. Let $\\matr{Z} = g(\\matr{X})$. $\\matr{Z}$ will be of shape $3 \\times 2$.\n\n\\begin{flalign}\n\\matr{X} &=\n\\begin{bmatrix}\nx_{1,1} & x_{1,2} \\\\%[0.5em]\nx_{2,1} & x_{2,2} \\\\%[0.5em]\nx_{3,1} & x_{3,2} \\\\%[0.5em]\n\\end{bmatrix} &\n\\nonumber\n\\end{flalign}\n\n\\noindent $\\matr{Z}$ can be expressed as:\n\n\\begin{flalign}\n\\matr{Z} &=\n\\begin{bmatrix}\nz_{1,1} & z_{1,2} \\\\%[0.5em]\nz_{2,1} & z_{2,2} \\\\%[0.5em]\nz_{3,1} & z_{3,2} \\\\%[0.5em]\n\\end{bmatrix} &\n\\nonumber \\\\\n&=\n\\begin{bmatrix}\ng(x_{1,1}) & g(x_{1,2}) \\\\[0.5em]\ng(x_{2,1}) & g(x_{2,2}) \\\\[0.5em]\ng(x_{3,1}) & g(x_{3,2}) \\\\[0.5em]\n\\end{bmatrix}\n\\nonumber\n\\end{flalign}\n\n\\subsection{Backward Pass}\nWe have $\\frac{\\partial L}{\\partial \\matr{Z}}$ of shape $3 \\times 2$.\n\n\\begin{flalign}\n\\frac{\\partial L}{\\partial \\matr{Z}} &=\n\\begin{bmatrix}\n\\frac{\\partial L}{\\partial z_{1,1}} & \\frac{\\partial L}{\\partial z_{1,2}} \\\\[0.5em]\n\\frac{\\partial L}{\\partial z_{2,1}} & \\frac{\\partial L}{\\partial z_{2,2}} \\\\[0.5em]\n\\frac{\\partial L}{\\partial z_{3,1}} & \\frac{\\partial L}{\\partial z_{3,2}} \\\\[0.5em]\n\\end{bmatrix} & \\eqncomment{$\\frac{\\partial L}{\\partial \\matr{Z}}$ is the same shape as $\\matr{Z}$ as $L$ is a scalar}\n\\label{dZ_elewise_single_matrix}\n\\end{flalign}\n\n\\noindent We now need to compute $\\frac{\\partial L}{\\partial \\matr{X}}$. Using chain rule, we get:\n\n\\begin{flalign} \\label{dX_elewise_single_matrix}\n\\frac{\\partial L}{\\partial \\matr{X}} &= \\frac{\\partial \\matr{Z}}{\\partial \\matr{X}}\\frac{\\partial L}{\\partial \\matr{Z}} &\n\\end{flalign}\n\n\\subsubsection{Computing $\\frac{\\partial L}{\\partial \\matr{X}}$}\nTo compute $\\frac{\\partial L}{\\partial \\matr{X}}$, we need to compute $\\frac{\\partial \\matr{Z}}{\\partial \\matr{X}}$. To make it easy for us to think about and capture the Jacobian in a two dimensional matrix (as opposed to a tensor), we will reshape matrices $\\matr{X}$ and $\\matr{Z}$ as column vectors, and compute Jacobians on them. Once we have computed the column vector corresponding to $\\frac{\\partial L}{\\partial \\matr{X}}$, we will reshape it back to a matrix with the same shape as $\\matr{X}$.\n\n\\begin{flalign}\n\\frac{\\partial \\matr{Z}}{\\partial \\matr{X}} &=\n\\begin{bmatrix}\n\\frac{\\partial z_{1,1}}{\\partial x_{1,1}} & \\frac{\\partial z_{1,2}}{\\partial x_{1,1}} & \\frac{\\partial z_{2,1}}{\\partial x_{1,1}} & \\frac{\\partial z_{2,2}}{\\partial x_{1,1}} & \\frac{\\partial z_{3,1}}{\\partial x_{1,1}} & \\frac{\\partial z_{3,2}}{\\partial x_{1,1}}\\\\[0.7em]\n\\frac{\\partial z_{1,1}}{\\partial x_{1,2}} & \\frac{\\partial z_{1,2}}{\\partial x_{1,2}} & \\frac{\\partial z_{2,1}}{\\partial x_{1,2}} & \\frac{\\partial z_{2,2}}{\\partial x_{1,2}} & \\frac{\\partial z_{3,1}}{\\partial x_{1,2}} & \\frac{\\partial z_{3,2}}{\\partial x_{1,2}}\\\\[0.7em]\n\\frac{\\partial z_{1,1}}{\\partial x_{2,1}} & \\frac{\\partial z_{1,2}}{\\partial x_{2,1}} & \\frac{\\partial z_{2,1}}{\\partial x_{2,1}} & \\frac{\\partial z_{2,2}}{\\partial x_{2,1}} & \\frac{\\partial z_{3,1}}{\\partial x_{2,1}} & \\frac{\\partial z_{3,2}}{\\partial x_{2,1}}\\\\[0.7em]\n\\frac{\\partial z_{1,1}}{\\partial x_{2,2}} & \\frac{\\partial z_{1,2}}{\\partial x_{2,2}} & \\frac{\\partial z_{2,1}}{\\partial x_{2,2}} & \\frac{\\partial z_{2,2}}{\\partial x_{2,2}} & \\frac{\\partial z_{3,1}}{\\partial x_{2,2}} & \\frac{\\partial z_{3,2}}{\\partial x_{2,2}}\\\\[0.7em]\n\\frac{\\partial z_{1,1}}{\\partial x_{3,1}} & \\frac{\\partial z_{1,2}}{\\partial x_{3,1}} & \\frac{\\partial z_{2,1}}{\\partial x_{3,1}} & \\frac{\\partial z_{2,2}}{\\partial x_{3,1}} & \\frac{\\partial z_{3,1}}{\\partial x_{3,1}} & \\frac{\\partial z_{3,2}}{\\partial x_{3,1}}\\\\[0.7em]\n\\frac{\\partial z_{1,1}}{\\partial x_{3,2}} & \\frac{\\partial z_{1,2}}{\\partial x_{3,2}} & \\frac{\\partial z_{2,1}}{\\partial x_{3,2}} & \\frac{\\partial z_{2,2}}{\\partial x_{3,2}} & \\frac{\\partial z_{3,1}}{\\partial x_{3,2}} & \\frac{\\partial z_{3,2}}{\\partial x_{3,2}}\\\\[0.7em]\n\\end{bmatrix}\n& \\longeqncomment{$\\matr{X}$, $\\matr{Z}$ are being treated as column vectors.}{Therefore, $\\frac{\\partial \\matr{Z}}{\\partial \\matr{X}}$ is of shape $6\\times6$.}\n\\nonumber\n\\\\ \\label{dZbydX_elewise_single_matrix}\n&=\n\\begin{bmatrix*}[c]\ng'(x_{1,1}) & 0 & 0 & 0 & 0 & 0 \\\\[0.0em]\n0 & g'(x_{1,2}) & 0 & 0 & 0 & 0 \\\\[0.0em]\n0 & 0 & g'(x_{2,1}) & 0 & 0 & 0 \\\\[0.0em]\n0 & 0 & 0 & g'(x_{2,2}) & 0 & 0 \\\\[0.0em]\n0 & 0 & 0 & 0 & g'(x_{3,1}) & 0 \\\\[0.0em]\n0 & 0 & 0 & 0 & 0 & g'(x_{3,2}) \\\\[0.0em]\n\\end{bmatrix*}\n\\end{flalign}\n\n\\noindent Now, $\\frac{\\partial L}{\\partial \\matr{Z}}$ in equation \\ref{dZ_elewise_single_matrix} expressed as a column vector will be:\n\n\\begin{flalign} \\label{dZAsColumnVector_elewise_single_matrix}\n\\frac{\\partial L}{\\partial \\matr{Z}} &=\n\\begin{bmatrix}\n\\frac{\\partial L}{\\partial z_{1,1}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{1,2}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{2,1}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{2,2}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{3,1}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{3,2}} \\\\[0.7em]\n\\end{bmatrix}\n& \\eqncomment{Reshaping $\\frac{\\partial L}{\\partial \\matr{Z}}$ from shape $3 \\times 2$ to $6 \\times 1$}\n\\end{flalign}\n\n\\noindent Plugging equations \\ref{dZbydX_elewise_single_matrix} and \\ref{dZAsColumnVector_elewise_single_matrix} into equation \\ref{dX_elewise_single_matrix}, we get:\n\n\\begin{flalign}\n\\frac{\\partial L}{\\partial \\matr{X}} &=\n\\frac{\\partial \\matr{Z}}{\\partial \\matr{X}}\\frac{\\partial L}{\\partial \\matr{Z}} &\n\\nonumber \\\\\n&=\n\\begin{bmatrix}\ng'(x_{1,1}) & 0 & 0 & 0 & 0 & 0 \\\\[0.5em]\n0 & g'(x_{1,2}) & 0 & 0 & 0 & 0 \\\\[0.5em]\n0 & 0 & g'(x_{2,1}) & 0 & 0 & 0 \\\\[0.5em]\n0 & 0 & 0 & g'(x_{2,2}) & 0 & 0 \\\\[0.5em]\n0 & 0 & 0 & 0 & g'(x_{3,1}) & 0 \\\\[0.5em]\n0 & 0 & 0 & 0 & 0 & g'(x_{3,2}) \\\\[0.5em]\n\\end{bmatrix}\n\\begin{bmatrix}\n\\frac{\\partial L}{\\partial z_{1,1}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{1,2}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{2,1}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{2,2}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{3,1}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{3,2}} \\\\[0.7em]\n\\end{bmatrix}\n& \\longeqncomment{$\\matr{X}$, $\\matr{Z}$ and $\\frac{\\partial L}{\\partial \\matr{Z}}$ are being}{treated as column vectors.}\n\\nonumber \\\\\n&=\n\\begin{bmatrix}\ng'(x_{1,1}).\\frac{\\partial L}{\\partial z_{1,1}} \\\\[0.7em]\ng'(x_{1,2}).\\frac{\\partial L}{\\partial z_{1,2}} \\\\[0.7em]\ng'(x_{2,1}).\\frac{\\partial L}{\\partial z_{2,1}} \\\\[0.7em]\ng'(x_{2,2}).\\frac{\\partial L}{\\partial z_{2,2}} \\\\[0.7em]\ng'(x_{3,1}).\\frac{\\partial L}{\\partial z_{3,1}} \\\\[0.7em]\ng'(x_{3,2}).\\frac{\\partial L}{\\partial z_{3,2}} \\\\[0.7em]\n\\end{bmatrix} \\label{dXAsColumnVector_elewise_single_matrix}\n\\end{flalign}\n\n\\noindent Note, we will be using $\\circ$ to denote element-wise multiplication between matrices popularly known as Hadamard product. Also $g'(\\matr{X})$ like $g(\\matr{X})$ will be applied element-wise.\n\n\\begin{flalign}\ng'(\\matr{X}) &=\n\\begin{bmatrix}\ng'(x_{1,1}) & g'(x_{1,2}) \\\\[0.5em]\ng'(x_{2,1}) & g'(x_{2,2}) \\\\[0.5em]\ng'(x_{3,1}) & g'(x_{3,2}) \\\\[0.5em]\n\\end{bmatrix} & \\nonumber\n\\end{flalign}\n\n\\noindent Now, reshaping column vector in equation \\ref{dXAsColumnVector_elewise_single_matrix} as a matrix of shape $\\matr{X}$, we get:\n\n\\begin{flalign}\n\\frac{\\partial L}{\\partial \\matr{X}} &=\n\\begin{bmatrix}\ng'(x_{1,1}).\\frac{\\partial L}{\\partial z_{1,1}} &\ng'(x_{1,2}).\\frac{\\partial L}{\\partial z_{1,2}} \\\\[0.7em]\ng'(x_{2,1}).\\frac{\\partial L}{\\partial z_{2,1}} &\ng'(x_{2,2}).\\frac{\\partial L}{\\partial z_{2,2}} \\\\[0.7em]\ng'(x_{3,1}).\\frac{\\partial L}{\\partial z_{3,1}} &\ng'(x_{3,2}).\\frac{\\partial L}{\\partial z_{3,2}} \\\\[0.7em]\n\\end{bmatrix}\n\\nonumber \\\\\n&=\n\\underbrace{\n\\begin{bmatrix}\ng'(x_{1,1}) & g'(x_{1,2}) \\\\[0.5em]\ng'(x_{2,1}) & g'(x_{2,2}) \\\\[0.5em]\ng'(x_{3,1}) & g'(x_{3,2}) \\\\[0.5em]\n\\end{bmatrix}}_{g'(\\matr{X})}\n\\circ\n\\underbrace{\n\\begin{bmatrix}\n\\frac{\\partial L}{\\partial z_{1,1}} & \\frac{\\partial L}{\\partial z_{1,2}} \\\\[0.5em]\n\\frac{\\partial L}{\\partial z_{2,1}} & \\frac{\\partial L}{\\partial z_{2,2}} \\\\[0.5em]\n\\frac{\\partial L}{\\partial z_{3,1}} & \\frac{\\partial L}{\\partial z_{3,2}} \\\\[0.5em]\n\\end{bmatrix}}_{\\frac{\\partial L}{\\partial \\matr{Z}}}\n& \\eqncomment{Decomposing into an element-wise multiplication between matrices.}\n\\nonumber \\\\\n&=\ng'(\\matr{X}) \\circ \\frac{\\partial L}{\\partial \\matr{Z}}\n\\end{flalign}\n\n\\section{Hadamard product}\n\\subsection{Forward Pass}\nLet $\\matr{X}$ be a $3 \\times 2$ matrix, and let $\\matr{Y}$ be a $3 \\times 2$ matrix. Let $\\matr{Z} = \\matr{X} \\circ \\matr{Y}$ that is element-wise multiplication between $\\matr{X}$ and $\\matr{Y}$.\n\n\\begin{flalign}\n\\matr{X} &=\n\\begin{bmatrix}\nx_{1,1} & x_{1,2} \\\\%[0.5em]\nx_{2,1} & x_{2,2} \\\\%[0.5em]\nx_{3,1} & x_{3,2} \\\\%[0.5em]\n\\end{bmatrix} &\n\\nonumber\n\\end{flalign}\n\n\\begin{flalign}\n\\matr{Y} &=\n\\begin{bmatrix}\ny_{1,1} & y_{1,2} \\\\%[0.5em]\ny_{2,1} & y_{2,2} \\\\%[0.5em]\ny_{3,1} & y_{3,2} \\\\%[0.5em]\n\\end{bmatrix} &\n\\nonumber\n\\end{flalign}\n\n\\noindent Given $\\matr{Z} = \\matr{X} \\circ \\matr{Y}$, $\\matr{Z}$ is a $3 \\times 2$ matrix which can be expressed as:\n\n\\begin{flalign}\n\\matr{Z} &= \\begin{bmatrix}\nz_{1,1} & z_{1,2}\\\\[0.5em]\nz_{2,1} & z_{2,2}\\\\[0.5em]\nz_{3,1} & z_{3,2}\\\\[0.5em]\n\\end{bmatrix}\n&\n\\nonumber\n\\\\\n&=\n\\begin{bmatrix}\nx_{1,1}.y_{1,1} & x_{1,2}.y_{1,2} \\\\[0.5em]\nx_{2,1}.y_{2,1} & x_{2,2}.y_{2,2} \\\\[0.5em]\nx_{3,1}.y_{3,1} & x_{3,2}.y_{3,2} \\\\[0.5em]\n\\end{bmatrix}\n\\nonumber\n\\end{flalign}\n\n\\subsection{Backward Pass}\nWe have $\\frac{\\partial L}{\\partial \\matr{Z}}$ of shape $3 \\times 2$.\n\n\\begin{flalign}\n\\frac{\\partial L}{\\partial \\matr{Z}} &=\n\\begin{bmatrix}\n\\frac{\\partial L}{\\partial z_{1,1}} & \\frac{\\partial L}{\\partial z_{1,2}} \\\\[0.5em]\n\\frac{\\partial L}{\\partial z_{2,1}} & \\frac{\\partial L}{\\partial z_{2,2}} \\\\[0.5em]\n\\frac{\\partial L}{\\partial z_{3,1}} & \\frac{\\partial L}{\\partial z_{3,2}} \\\\[0.5em]\n\\end{bmatrix}\n& \\eqncomment{$\\frac{\\partial L}{\\partial \\matr{Z}}$ is the same shape as $\\matr{Z}$ as $L$ is a scalar}\n\\label{dZ_hadamard_product}\n\\end{flalign}\n\n\\noindent We now need to compute $\\frac{\\partial L}{\\partial \\matr{X}}$ and $\\frac{\\partial L}{\\partial \\matr{Y}}$. Using chain rule, we get:\n\n\\begin{flalign} \\label{dX_hadamard_product}\n\\frac{\\partial L}{\\partial \\matr{X}} &= \\frac{\\partial \\matr{Z}}{\\partial \\matr{X}}\\frac{\\partial L}{\\partial \\matr{Z}} &\n\\end{flalign}\n\n\\begin{flalign} \\label{dY_hadamard_product}\n\\frac{\\partial L}{\\partial \\matr{Y}} &= \\frac{\\partial \\matr{Z}}{\\partial \\matr{Y}}\\frac{\\partial L}{\\partial \\matr{Z}} &\n\\end{flalign}\n\n\\subsubsection{Computing $\\frac{\\partial L}{\\partial \\matr{X}}$}\nTo compute $\\frac{\\partial L}{\\partial \\matr{X}}$, we need to compute $\\frac{\\partial \\matr{Z}}{\\partial \\matr{X}}$. To make it easy for us to think about and capture the Jacobian in a two dimensional matrix (as opposed to a tensor), we will reshape matrices $\\matr{X}$, $\\matr{Y}$ and $\\matr{Z}$ as column vectors, and compute Jacobians on them. Once we have computed the column vector corresponding to $\\frac{\\partial L}{\\partial \\matr{X}}$, we will reshape it back to a matrix with the same shape as $\\matr{X}$.\n\n\\begin{flalign}\n\\frac{\\partial \\matr{Z}}{\\partial \\matr{X}} &=\n\\begin{bmatrix}\n\\frac{\\partial z_{1,1}}{\\partial x_{1,1}} & \\frac{\\partial z_{1,2}}{\\partial x_{1,1}} & \\frac{\\partial z_{2,1}}{\\partial x_{1,1}} & \\frac{\\partial z_{2,2}}{\\partial x_{1,1}} & \\frac{\\partial z_{3,1}}{\\partial x_{1,1}} & \\frac{\\partial z_{3,2}}{\\partial x_{1,1}}\\\\[0.7em]\n\\frac{\\partial z_{1,1}}{\\partial x_{1,2}} & \\frac{\\partial z_{1,2}}{\\partial x_{1,2}} & \\frac{\\partial z_{2,1}}{\\partial x_{1,2}} & \\frac{\\partial z_{2,2}}{\\partial x_{1,2}} & \\frac{\\partial z_{3,1}}{\\partial x_{1,2}} & \\frac{\\partial z_{3,2}}{\\partial x_{1,2}}\\\\[0.7em]\n\\frac{\\partial z_{1,1}}{\\partial x_{2,1}} & \\frac{\\partial z_{1,2}}{\\partial x_{2,1}} & \\frac{\\partial z_{2,1}}{\\partial x_{2,1}} & \\frac{\\partial z_{2,2}}{\\partial x_{2,1}} & \\frac{\\partial z_{3,1}}{\\partial x_{2,1}} & \\frac{\\partial z_{3,2}}{\\partial x_{2,1}}\\\\[0.7em]\n\\frac{\\partial z_{1,1}}{\\partial x_{2,2}} & \\frac{\\partial z_{1,2}}{\\partial x_{2,2}} & \\frac{\\partial z_{2,1}}{\\partial x_{2,2}} & \\frac{\\partial z_{2,2}}{\\partial x_{2,2}} & \\frac{\\partial z_{3,1}}{\\partial x_{2,2}} & \\frac{\\partial z_{3,2}}{\\partial x_{2,2}}\\\\[0.7em]\n\\frac{\\partial z_{1,1}}{\\partial x_{3,1}} & \\frac{\\partial z_{1,2}}{\\partial x_{3,1}} & \\frac{\\partial z_{2,1}}{\\partial x_{3,1}} & \\frac{\\partial z_{2,2}}{\\partial x_{3,1}} & \\frac{\\partial z_{3,1}}{\\partial x_{3,1}} & \\frac{\\partial z_{3,2}}{\\partial x_{3,1}}\\\\[0.7em]\n\\frac{\\partial z_{1,1}}{\\partial x_{3,2}} & \\frac{\\partial z_{1,2}}{\\partial x_{3,2}} & \\frac{\\partial z_{2,1}}{\\partial x_{3,2}} & \\frac{\\partial z_{2,2}}{\\partial x_{3,2}} & \\frac{\\partial z_{3,1}}{\\partial x_{3,2}} & \\frac{\\partial z_{3,2}}{\\partial x_{3,2}}\\\\[0.7em]\n\\end{bmatrix}\n& \\longeqncomment{$\\matr{X}$, $\\matr{Z}$ are being treated as column vectors.}{Therefore, $\\frac{\\partial \\matr{Z}}{\\partial \\matr{X}}$ is of shape $6\\times6$.}\n\\nonumber\n\\\\ \\label{dZbydX_hadamard_product}\n&=\n\\begin{bmatrix}\ny_{1,1} & 0 & 0 & 0 & 0 & 0 \\\\[0.5em]\n0 & y_{1,2} & 0 & 0 & 0 & 0 \\\\[0.5em]\n0 & 0 & y_{2,1} & 0 & 0 & 0 \\\\[0.5em]\n0 & 0 & 0 & y_{2,2} & 0 & 0 \\\\[0.5em]\n0 & 0 & 0 & 0 & y_{3,1} & 0 \\\\[0.5em]\n0 & 0 & 0 & 0 & 0 & y_{3,2} \\\\[0.5em]\n\\end{bmatrix}\n\\end{flalign}\n\n\\noindent Now, $\\frac{\\partial L}{\\partial \\matr{Z}}$ in equation \\ref{dZ_hadamard_product} expressed as a column vector will be:\n\n\\begin{flalign} \\label{dZAsColumnVector_hadamard_product}\n\\frac{\\partial L}{\\partial \\matr{Z}} &=\n\\begin{bmatrix}\n\\frac{\\partial L}{\\partial z_{1,1}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{1,2}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{2,1}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{2,2}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{3,1}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{3,2}} \\\\[0.7em]\n\\end{bmatrix}\n& \\eqncomment{Reshaping $\\frac{\\partial L}{\\partial \\matr{Z}}$ from shape $3 \\times 2$ to $6 \\times 1$}\n\\end{flalign}\n\n\\noindent Plugging equations \\ref{dZbydX_hadamard_product} and \\ref{dZAsColumnVector_hadamard_product} into equation \\ref{dX_hadamard_product}, we get:\n\n\\begin{flalign}\n\\frac{\\partial L}{\\partial \\matr{X}} &=\n\\frac{\\partial \\matr{Z}}{\\partial \\matr{X}}\\frac{\\partial L}{\\partial \\matr{Z}} &\n\\nonumber \\\\\n&=\n\\begin{bmatrix}\ny_{1,1} & 0 & 0 & 0 & 0 & 0 \\\\[0.5em]\n0 & y_{1,2} & 0 & 0 & 0 & 0 \\\\[0.5em]\n0 & 0 & y_{2,1} & 0 & 0 & 0 \\\\[0.5em]\n0 & 0 & 0 & y_{2,2} & 0 & 0 \\\\[0.5em]\n0 & 0 & 0 & 0 & y_{3,1} & 0 \\\\[0.5em]\n0 & 0 & 0 & 0 & 0 & y_{3,2} \\\\[0.5em]\n\\end{bmatrix}\n\\begin{bmatrix}\n\\frac{\\partial L}{\\partial z_{1,1}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{1,2}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{2,1}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{2,2}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{3,1}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{3,2}} \\\\[0.7em]\n\\end{bmatrix}\n& \\eqncomment{$\\matr{X}$, $\\matr{Z}$ and $\\frac{\\partial L}{\\partial \\matr{Z}}$ are being treated as column vectors}\n\\nonumber \\\\\n&=\n\\begin{bmatrix}\ny_{1,1}.\\frac{\\partial L}{\\partial z_{1,1}} \\\\[0.7em]\ny_{1,2}.\\frac{\\partial L}{\\partial z_{1,2}} \\\\[0.7em]\ny_{2,1}.\\frac{\\partial L}{\\partial z_{2,1}} \\\\[0.7em]\ny_{2,2}.\\frac{\\partial L}{\\partial z_{2,2}} \\\\[0.7em]\ny_{3,1}.\\frac{\\partial L}{\\partial z_{3,1}} \\\\[0.7em]\ny_{3,2}.\\frac{\\partial L}{\\partial z_{3,2}} \\\\[0.7em]\n\\end{bmatrix} \\label{dXAsColumnVector_hadamard_product}\n\\end{flalign}\n\n\\noindent Reshaping column vector in equation \\ref{dXAsColumnVector_hadamard_product} as a matrix of shape $\\matr{X}$, we get:\n\n\\begin{flalign}\n\\frac{\\partial L}{\\partial \\matr{X}} &=\n\\begin{bmatrix}\ny_{1,1}.\\frac{\\partial L}{\\partial z_{1,1}} &\ny_{1,2}.\\frac{\\partial L}{\\partial z_{1,2}} \\\\[0.7em]\ny_{2,1}.\\frac{\\partial L}{\\partial z_{2,1}} &\ny_{2,2}.\\frac{\\partial L}{\\partial z_{2,2}} \\\\[0.7em]\ny_{3,1}.\\frac{\\partial L}{\\partial z_{3,1}} &\ny_{3,2}.\\frac{\\partial L}{\\partial z_{3,2}} \\\\[0.7em]\n\\end{bmatrix}\n\\nonumber \\\\\n&=\n\\underbrace{\n\\begin{bmatrix}\ny_{1,1} & y_{1,2} \\\\%[0.5em]\ny_{2,1} & y_{2,2} \\\\%[0.5em]\ny_{3,1} & y_{3,2} \\\\%[0.5em]\n\\end{bmatrix}}_{\\matr{Y}}\n\\circ\n\\underbrace{\n\\begin{bmatrix}\n\\frac{\\partial L}{\\partial z_{1,1}} & \\frac{\\partial L}{\\partial z_{1,2}} \\\\[0.5em]\n\\frac{\\partial L}{\\partial z_{2,1}} & \\frac{\\partial L}{\\partial z_{2,2}} \\\\[0.5em]\n\\frac{\\partial L}{\\partial z_{3,1}} & \\frac{\\partial L}{\\partial z_{3,2}} \\\\[0.5em]\n\\end{bmatrix}}_{\\frac{\\partial L}{\\partial \\matr{Z}}}\n& \\eqncomment{Decomposing into an element-wise multiplication between matrices.}\n\\nonumber \\\\\n&=\n\\matr{Y} \\circ \\frac{\\partial L}{\\partial \\matr{Z}}\n\\end{flalign}\n\n\\subsubsection{Computing $\\frac{\\partial L}{\\partial \\matr{Y}}$}\nTo compute $\\frac{\\partial L}{\\partial \\matr{Y}}$, we need to compute $\\frac{\\partial \\matr{Z}}{\\partial \\matr{Y}}$. To make it easy for us to think about and capture the Jacobian in a two dimensional matrix (as opposed to a tensor), we will reshape matrices $\\matr{X}$, $\\matr{Y}$ and $\\matr{Z}$ as column vectors, and compute Jacobians on them. Once we have computed the column vector corresponding to $\\frac{\\partial L}{\\partial \\matr{Y}}$, we will reshape it back to a matrix with the same shape as $\\matr{Y}$.\n\n\\begin{flalign}\n\\frac{\\partial \\matr{Z}}{\\partial \\matr{Y}} &=\n\\begin{bmatrix}\n\\frac{\\partial z_{1,1}}{\\partial y_{1,1}} & \\frac{\\partial z_{1,2}}{\\partial y_{1,1}} & \\frac{\\partial z_{2,1}}{\\partial y_{1,1}} & \\frac{\\partial z_{2,2}}{\\partial y_{1,1}} & \\frac{\\partial z_{3,1}}{\\partial y_{1,1}} & \\frac{\\partial z_{3,2}}{\\partial y_{1,1}}\\\\[0.7em]\n\\frac{\\partial z_{1,1}}{\\partial y_{1,2}} & \\frac{\\partial z_{1,2}}{\\partial y_{1,2}} & \\frac{\\partial z_{2,1}}{\\partial y_{1,2}} & \\frac{\\partial z_{2,2}}{\\partial y_{1,2}} & \\frac{\\partial z_{3,1}}{\\partial y_{1,2}} & \\frac{\\partial z_{3,2}}{\\partial y_{1,2}}\\\\[0.7em]\n\\frac{\\partial z_{1,1}}{\\partial y_{2,1}} & \\frac{\\partial z_{1,2}}{\\partial y_{2,1}} & \\frac{\\partial z_{2,1}}{\\partial y_{2,1}} & \\frac{\\partial z_{2,2}}{\\partial y_{2,1}} & \\frac{\\partial z_{3,1}}{\\partial y_{2,1}} & \\frac{\\partial z_{3,2}}{\\partial y_{2,1}}\\\\[0.7em]\n\\frac{\\partial z_{1,1}}{\\partial y_{2,2}} & \\frac{\\partial z_{1,2}}{\\partial y_{2,2}} & \\frac{\\partial z_{2,1}}{\\partial y_{2,2}} & \\frac{\\partial z_{2,2}}{\\partial y_{2,2}} & \\frac{\\partial z_{3,1}}{\\partial y_{2,2}} & \\frac{\\partial z_{3,2}}{\\partial y_{2,2}}\\\\[0.7em]\n\\frac{\\partial z_{1,1}}{\\partial y_{3,1}} & \\frac{\\partial z_{1,2}}{\\partial y_{3,1}} & \\frac{\\partial z_{2,1}}{\\partial y_{3,1}} & \\frac{\\partial z_{2,2}}{\\partial y_{3,1}} & \\frac{\\partial z_{3,1}}{\\partial y_{3,1}} & \\frac{\\partial z_{3,2}}{\\partial y_{3,1}}\\\\[0.7em]\n\\frac{\\partial z_{1,1}}{\\partial y_{3,2}} & \\frac{\\partial z_{1,2}}{\\partial y_{3,2}} & \\frac{\\partial z_{2,1}}{\\partial y_{3,2}} & \\frac{\\partial z_{2,2}}{\\partial y_{3,2}} & \\frac{\\partial z_{3,1}}{\\partial y_{3,2}} & \\frac{\\partial z_{3,2}}{\\partial y_{3,2}}\\\\[0.7em]\n\\end{bmatrix}\n& \\longeqncomment{$\\matr{Y}$, $\\matr{Z}$ are being treated as column vectors.}{Therefore, $\\frac{\\partial \\matr{Z}}{\\partial \\matr{Y}}$ is of shape $6\\times6$.}\n\\nonumber\n\\\\ \\label{dZbydY_hadamard_product}\n&=\n\\begin{bmatrix}\nx_{1,1} & 0 & 0 & 0 & 0 & 0 \\\\[0.5em]\n0 & x_{1,2} & 0 & 0 & 0 & 0 \\\\[0.5em]\n0 & 0 & x_{2,1} & 0 & 0 & 0 \\\\[0.5em]\n0 & 0 & 0 & x_{2,2} & 0 & 0 \\\\[0.5em]\n0 & 0 & 0 & 0 & x_{3,1} & 0 \\\\[0.5em]\n0 & 0 & 0 & 0 & 0 & x_{3,2} \\\\[0.5em]\n\\end{bmatrix}\n\\end{flalign}\n\n\\noindent Plugging equations \\ref{dZbydY_hadamard_product} and \\ref{dZAsColumnVector_hadamard_product} into equation \\ref{dY_hadamard_product}, we get:\n\n\\begin{flalign}\n\\frac{\\partial L}{\\partial \\matr{Y}} &=\n\\frac{\\partial \\matr{Z}}{\\partial \\matr{Y}}\\frac{\\partial L}{\\partial \\matr{Z}} &\n\\nonumber \\\\\n&=\n\\begin{bmatrix}\nx_{1,1} & 0 & 0 & 0 & 0 & 0 \\\\[0.5em]\n0 & x_{1,2} & 0 & 0 & 0 & 0 \\\\[0.5em]\n0 & 0 & x_{2,1} & 0 & 0 & 0 \\\\[0.5em]\n0 & 0 & 0 & x_{2,2} & 0 & 0 \\\\[0.5em]\n0 & 0 & 0 & 0 & x_{3,1} & 0 \\\\[0.5em]\n0 & 0 & 0 & 0 & 0 & x_{3,2} \\\\[0.5em]\n\\end{bmatrix}\n\\begin{bmatrix}\n\\frac{\\partial L}{\\partial z_{1,1}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{1,2}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{2,1}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{2,2}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{3,1}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{3,2}} \\\\[0.7em]\n\\end{bmatrix}\n& \\eqncomment{$\\matr{Y}$, $\\matr{Z}$ and $\\frac{\\partial L}{\\partial \\matr{Z}}$ are being treated as column vectors}\n\\nonumber \\\\\n&=\n\\begin{bmatrix}\nx_{1,1}.\\frac{\\partial L}{\\partial z_{1,1}} \\\\[0.7em]\nx_{1,2}.\\frac{\\partial L}{\\partial z_{1,2}} \\\\[0.7em]\nx_{2,1}.\\frac{\\partial L}{\\partial z_{2,1}} \\\\[0.7em]\nx_{2,2}.\\frac{\\partial L}{\\partial z_{2,2}} \\\\[0.7em]\nx_{3,1}.\\frac{\\partial L}{\\partial z_{3,1}} \\\\[0.7em]\nx_{3,2}.\\frac{\\partial L}{\\partial z_{3,2}} \\\\[0.7em]\n\\end{bmatrix} \\label{dYAsColumnVector_hadamard_product}\n\\end{flalign}\n\n\\noindent Now, reshaping column vector in equation \\ref{dYAsColumnVector_hadamard_product} as a matrix of shape $\\matr{Y}$, we get:\n\n\\begin{flalign}\n\\frac{\\partial L}{\\partial \\matr{X}} &=\n\\begin{bmatrix}\nx_{1,1}.\\frac{\\partial L}{\\partial z_{1,1}} &\nx_{1,2}.\\frac{\\partial L}{\\partial z_{1,2}} \\\\[0.7em]\nx_{2,1}.\\frac{\\partial L}{\\partial z_{2,1}} &\nx_{2,2}.\\frac{\\partial L}{\\partial z_{2,2}} \\\\[0.7em]\nx_{3,1}.\\frac{\\partial L}{\\partial z_{3,1}} &\nx_{3,2}.\\frac{\\partial L}{\\partial z_{3,2}} \\\\[0.7em]\n\\end{bmatrix}\n\\nonumber \\\\\n&=\n\\underbrace{\n\\begin{bmatrix}\nx_{1,1} & x_{1,2} \\\\%[0.5em]\nx_{2,1} & x_{2,2} \\\\%[0.5em]\nx_{3,1} & x_{3,2} \\\\%[0.5em]\n\\end{bmatrix}}_{\\matr{X}}\n\\circ\n\\underbrace{\n\\begin{bmatrix}\n\\frac{\\partial L}{\\partial z_{1,1}} & \\frac{\\partial L}{\\partial z_{1,2}} \\\\[0.5em]\n\\frac{\\partial L}{\\partial z_{2,1}} & \\frac{\\partial L}{\\partial z_{2,2}} \\\\[0.5em]\n\\frac{\\partial L}{\\partial z_{3,1}} & \\frac{\\partial L}{\\partial z_{3,2}} \\\\[0.5em]\n\\end{bmatrix}}_{\\frac{\\partial L}{\\partial \\matr{Z}}}\n& \\eqncomment{Decomposing into an element-wise multiplication between matrices.}\n\\nonumber \\\\\n&=\n\\matr{X} \\circ \\frac{\\partial L}{\\partial \\matr{Z}}\n\\end{flalign}\n\n\\section{Matrix Addition}\n\\subsection{Forward Pass}\nLet $\\matr{X}$ be a $3 \\times 2$ matrix, and let $\\matr{Y}$ be a $3 \\times 2$ matrix. Let $\\matr{Z} = \\matr{X} + \\matr{Y}$ that is element-wise addition between $\\matr{X}$ and $\\matr{Y}$.\n\n\\begin{flalign}\n\\matr{X} &=\n\\begin{bmatrix}\nx_{1,1} & x_{1,2} \\\\%[0.5em]\nx_{2,1} & x_{2,2} \\\\%[0.5em]\nx_{3,1} & x_{3,2} \\\\%[0.5em]\n\\end{bmatrix} &\n\\nonumber\n\\end{flalign}\n\n\\begin{flalign}\n\\matr{Y} &=\n\\begin{bmatrix}\ny_{1,1} & y_{1,2} \\\\%[0.5em]\ny_{2,1} & y_{2,2} \\\\%[0.5em]\ny_{3,1} & y_{3,2} \\\\%[0.5em]\n\\end{bmatrix} &\n\\nonumber\n\\end{flalign}\n\n\\noindent Given $\\matr{Z} = \\matr{X} + \\matr{Y}$, Z is a $3 \\times 2$ matrix which can be expressed as:\n\n\\begin{flalign}\n\\matr{Z} &= \\begin{bmatrix}\nz_{1,1} & z_{1,2}\\\\[0.5em]\nz_{2,1} & z_{2,2}\\\\[0.5em]\nz_{3,1} & z_{3,2}\\\\[0.5em]\n\\end{bmatrix}\n&\n\\nonumber\n\\\\\n&=\n\\begin{bmatrix}\nx_{1,1} + y_{1,1} & x_{1,2} + y_{1,2} \\\\[0.5em]\nx_{2,1} + y_{2,1} & x_{2,2} + y_{2,2} \\\\[0.5em]\nx_{3,1} + y_{3,1} & x_{3,2} + y_{3,2} \\\\[0.5em]\n\\end{bmatrix}\n\\nonumber\n\\end{flalign}\n\n\\subsection{Backward Pass}\nWe have $\\frac{\\partial L}{\\partial \\matr{Z}}$ of shape $3 \\times 2$.\n\n\\begin{flalign}\n\\frac{\\partial L}{\\partial \\matr{Z}} &=\n\\begin{bmatrix}\n\\frac{\\partial L}{\\partial z_{1,1}} & \\frac{\\partial L}{\\partial z_{1,2}} \\\\[0.5em]\n\\frac{\\partial L}{\\partial z_{2,1}} & \\frac{\\partial L}{\\partial z_{2,2}} \\\\[0.5em]\n\\frac{\\partial L}{\\partial z_{3,1}} & \\frac{\\partial L}{\\partial z_{3,2}} \\\\[0.5em]\n\\end{bmatrix}\n& \\eqncomment{$\\frac{\\partial L}{\\partial \\matr{Z}}$ is the same shape as $\\matr{Z}$ as $L$ is a scalar}\n\\label{dZ_matrix_addition}\n\\end{flalign}\n\n\\noindent We now need to compute $\\frac{\\partial L}{\\partial \\matr{X}}$ and $\\frac{\\partial L}{\\partial \\matr{Y}}$. Using chain rule, we get:\n\n\\begin{flalign} \\label{dX_matrix_addition}\n\\frac{\\partial L}{\\partial \\matr{X}} &= \\frac{\\partial \\matr{Z}}{\\partial \\matr{X}}\\frac{\\partial L}{\\partial \\matr{Z}} &\n\\end{flalign}\n\n\\begin{flalign} \\label{dY_matrix_addition}\n\\frac{\\partial L}{\\partial \\matr{Y}} &= \\frac{\\partial \\matr{Z}}{\\partial \\matr{Y}}\\frac{\\partial L}{\\partial \\matr{Z}} &\n\\end{flalign}\n\n\\subsubsection{Computing $\\frac{\\partial L}{\\partial \\matr{X}}$}\nTo compute $\\frac{\\partial L}{\\partial \\matr{X}}$, we need to compute $\\frac{\\partial \\matr{Z}}{\\partial \\matr{X}}$. To make it easy for us to think about and capture the Jacobian in a two dimensional matrix (as opposed to a tensor), we will reshape matrices $\\matr{X}$, $\\matr{Y}$ and $\\matr{Z}$ as column vectors, and compute Jacobians on them. Once we have computed the column vector corresponding to $\\frac{\\partial L}{\\partial \\matr{X}}$, we will reshape it back to a matrix with the same shape as $\\matr{X}$.\n\n\\begin{flalign}\n\\frac{\\partial \\matr{Z}}{\\partial \\matr{X}} &=\n\\begin{bmatrix}\n\\frac{\\partial z_{1,1}}{\\partial x_{1,1}} & \\frac{\\partial z_{1,2}}{\\partial x_{1,1}} & \\frac{\\partial z_{2,1}}{\\partial x_{1,1}} & \\frac{\\partial z_{2,2}}{\\partial x_{1,1}} & \\frac{\\partial z_{3,1}}{\\partial x_{1,1}} & \\frac{\\partial z_{3,2}}{\\partial x_{1,1}}\\\\[0.7em]\n\\frac{\\partial z_{1,1}}{\\partial x_{1,2}} & \\frac{\\partial z_{1,2}}{\\partial x_{1,2}} & \\frac{\\partial z_{2,1}}{\\partial x_{1,2}} & \\frac{\\partial z_{2,2}}{\\partial x_{1,2}} & \\frac{\\partial z_{3,1}}{\\partial x_{1,2}} & \\frac{\\partial z_{3,2}}{\\partial x_{1,2}}\\\\[0.7em]\n\\frac{\\partial z_{1,1}}{\\partial x_{2,1}} & \\frac{\\partial z_{1,2}}{\\partial x_{2,1}} & \\frac{\\partial z_{2,1}}{\\partial x_{2,1}} & \\frac{\\partial z_{2,2}}{\\partial x_{2,1}} & \\frac{\\partial z_{3,1}}{\\partial x_{2,1}} & \\frac{\\partial z_{3,2}}{\\partial x_{2,1}}\\\\[0.7em]\n\\frac{\\partial z_{1,1}}{\\partial x_{2,2}} & \\frac{\\partial z_{1,2}}{\\partial x_{2,2}} & \\frac{\\partial z_{2,1}}{\\partial x_{2,2}} & \\frac{\\partial z_{2,2}}{\\partial x_{2,2}} & \\frac{\\partial z_{3,1}}{\\partial x_{2,2}} & \\frac{\\partial z_{3,2}}{\\partial x_{2,2}}\\\\[0.7em]\n\\frac{\\partial z_{1,1}}{\\partial x_{3,1}} & \\frac{\\partial z_{1,2}}{\\partial x_{3,1}} & \\frac{\\partial z_{2,1}}{\\partial x_{3,1}} & \\frac{\\partial z_{2,2}}{\\partial x_{3,1}} & \\frac{\\partial z_{3,1}}{\\partial x_{3,1}} & \\frac{\\partial z_{3,2}}{\\partial x_{3,1}}\\\\[0.7em]\n\\frac{\\partial z_{1,1}}{\\partial x_{3,2}} & \\frac{\\partial z_{1,2}}{\\partial x_{3,2}} & \\frac{\\partial z_{2,1}}{\\partial x_{3,2}} & \\frac{\\partial z_{2,2}}{\\partial x_{3,2}} & \\frac{\\partial z_{3,1}}{\\partial x_{3,2}} & \\frac{\\partial z_{3,2}}{\\partial x_{3,2}}\\\\[0.7em]\n\\end{bmatrix}\n& \\longeqncomment{$\\matr{X}$, $\\matr{Z}$ are being treated as column vectors.}{Therefore, $\\frac{\\partial \\matr{Z}}{\\partial \\matr{X}}$ is of shape $6\\times6$.}\n\\nonumber\n\\\\ \\label{dZbydX_matrix_addition}\n&=\n\\begin{bmatrix}\n1 & 0 & 0 & 0 & 0 & 0 \\\\%[0.5em]\n0 & 1 & 0 & 0 & 0 & 0 \\\\%[0.5em]\n0 & 0 & 1 & 0 & 0 & 0 \\\\%[0.5em]\n0 & 0 & 0 & 1 & 0 & 0 \\\\%[0.5em]\n0 & 0 & 0 & 0 & 1 & 0 \\\\%[0.5em]\n0 & 0 & 0 & 0 & 0 & 1 \\\\%[0.5em]\n\\end{bmatrix}\n\\end{flalign}\n\n\\noindent Now, $\\frac{\\partial L}{\\partial \\matr{Z}}$ in equation \\ref{dZ_matrix_addition} expressed as a column vector will be:\n\n\\begin{flalign} \\label{dZAsColumnVector_matrix_addition}\n\\frac{\\partial L}{\\partial \\matr{Z}} &=\n\\begin{bmatrix}\n\\frac{\\partial L}{\\partial z_{1,1}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{1,2}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{2,1}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{2,2}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{3,1}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{3,2}} \\\\[0.7em]\n\\end{bmatrix}\n& \\eqncomment{Reshaping $\\frac{\\partial L}{\\partial \\matr{Z}}$ from shape $3 \\times 2$ to $6 \\times 1$}\n\\end{flalign}\n\n\\noindent Plugging equations \\ref{dZbydX_matrix_addition} and \\ref{dZAsColumnVector_matrix_addition} into equation \\ref{dX_matrix_addition}, we get:\n\n\\begin{flalign}\n\\frac{\\partial L}{\\partial \\matr{X}} &=\n\\frac{\\partial \\matr{Z}}{\\partial \\matr{X}}\\frac{\\partial L}{\\partial \\matr{Z}} &\n\\nonumber \\\\\n&=\n\\begin{bmatrix}\n1 & 0 & 0 & 0 & 0 & 0 \\\\%[0.5em]\n0 & 1 & 0 & 0 & 0 & 0 \\\\%[0.5em]\n0 & 0 & 1 & 0 & 0 & 0 \\\\%[0.5em]\n0 & 0 & 0 & 1 & 0 & 0 \\\\%[0.5em]\n0 & 0 & 0 & 0 & 1 & 0 \\\\%[0.5em]\n0 & 0 & 0 & 0 & 0 & 1 \\\\%[0.5em]\n\\end{bmatrix}\n\\begin{bmatrix}\n\\frac{\\partial L}{\\partial z_{1,1}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{1,2}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{2,1}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{2,2}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{3,1}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{3,2}} \\\\[0.7em]\n\\end{bmatrix}\n& \\eqncomment{$\\matr{X}$, $\\matr{Z}$ and $\\frac{\\partial L}{\\partial \\matr{Z}}$ are being treated as column vectors}\n\\nonumber \\\\\n&=\n\\begin{bmatrix}\n\\frac{\\partial L}{\\partial z_{1,1}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{1,2}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{2,1}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{2,2}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{3,1}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{3,2}} \\\\[0.7em]\n\\end{bmatrix} \\label{dXAsColumnVector_matrix_addition}\n\\end{flalign}\n\n\\noindent Reshaping column vector in equation \\ref{dXAsColumnVector_matrix_addition} as a matrix of shape $\\matr{X}$, we get:\n\n\\begin{flalign}\n\\frac{\\partial L}{\\partial \\matr{X}} &=\n\\underbrace{\n\\begin{bmatrix}\n\\frac{\\partial L}{\\partial z_{1,1}} &\n\\frac{\\partial L}{\\partial z_{1,2}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{2,1}} &\n\\frac{\\partial L}{\\partial z_{2,2}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{3,1}} &\n\\frac{\\partial L}{\\partial z_{3,2}} \\\\[0.7em]\n\\end{bmatrix}}_{\\frac{\\partial L}{\\partial \\matr{Z}}}\n&\n\\nonumber \\\\\n&=\n\\frac{\\partial L}{\\partial \\matr{Z}}\n\\end{flalign}\n\n\\subsubsection{Computing $\\frac{\\partial L}{\\partial \\matr{Y}}$}\nTo compute $\\frac{\\partial L}{\\partial \\matr{Y}}$, we need to compute $\\frac{\\partial \\matr{Z}}{\\partial \\matr{Y}}$. To make it easy for us to think about and capture the Jacobian in a two dimensional matrix (as opposed to a tensor), we will reshape matrices $\\matr{X}$, $\\matr{Y}$ and $\\matr{Z}$ as column vectors, and compute Jacobians on them. Once we have computed the column vector corresponding to $\\frac{\\partial L}{\\partial \\matr{Y}}$, we will reshape it back to a matrix with the same shape as $\\matr{Y}$.\n\n\\begin{flalign}\n\\frac{\\partial \\matr{Z}}{\\partial \\matr{Y}} &=\n\\begin{bmatrix}\n\\frac{\\partial z_{1,1}}{\\partial y_{1,1}} & \\frac{\\partial z_{1,2}}{\\partial y_{1,1}} & \\frac{\\partial z_{2,1}}{\\partial y_{1,1}} & \\frac{\\partial z_{2,2}}{\\partial y_{1,1}} & \\frac{\\partial z_{3,1}}{\\partial y_{1,1}} & \\frac{\\partial z_{3,2}}{\\partial y_{1,1}}\\\\[0.7em]\n\\frac{\\partial z_{1,1}}{\\partial y_{1,2}} & \\frac{\\partial z_{1,2}}{\\partial y_{1,2}} & \\frac{\\partial z_{2,1}}{\\partial y_{1,2}} & \\frac{\\partial z_{2,2}}{\\partial y_{1,2}} & \\frac{\\partial z_{3,1}}{\\partial y_{1,2}} & \\frac{\\partial z_{3,2}}{\\partial y_{1,2}}\\\\[0.7em]\n\\frac{\\partial z_{1,1}}{\\partial y_{2,1}} & \\frac{\\partial z_{1,2}}{\\partial y_{2,1}} & \\frac{\\partial z_{2,1}}{\\partial y_{2,1}} & \\frac{\\partial z_{2,2}}{\\partial y_{2,1}} & \\frac{\\partial z_{3,1}}{\\partial y_{2,1}} & \\frac{\\partial z_{3,2}}{\\partial y_{2,1}}\\\\[0.7em]\n\\frac{\\partial z_{1,1}}{\\partial y_{2,2}} & \\frac{\\partial z_{1,2}}{\\partial y_{2,2}} & \\frac{\\partial z_{2,1}}{\\partial y_{2,2}} & \\frac{\\partial z_{2,2}}{\\partial y_{2,2}} & \\frac{\\partial z_{3,1}}{\\partial y_{2,2}} & \\frac{\\partial z_{3,2}}{\\partial y_{2,2}}\\\\[0.7em]\n\\frac{\\partial z_{1,1}}{\\partial y_{3,1}} & \\frac{\\partial z_{1,2}}{\\partial y_{3,1}} & \\frac{\\partial z_{2,1}}{\\partial y_{3,1}} & \\frac{\\partial z_{2,2}}{\\partial y_{3,1}} & \\frac{\\partial z_{3,1}}{\\partial y_{3,1}} & \\frac{\\partial z_{3,2}}{\\partial y_{3,1}}\\\\[0.7em]\n\\frac{\\partial z_{1,1}}{\\partial y_{3,2}} & \\frac{\\partial z_{1,2}}{\\partial y_{3,2}} & \\frac{\\partial z_{2,1}}{\\partial y_{3,2}} & \\frac{\\partial z_{2,2}}{\\partial y_{3,2}} & \\frac{\\partial z_{3,1}}{\\partial y_{3,2}} & \\frac{\\partial z_{3,2}}{\\partial y_{3,2}}\\\\[0.7em]\n\\end{bmatrix}\n& \\longeqncomment{$\\matr{Y}$, $\\matr{Z}$ are being treated as column vectors.}{Therefore, $\\frac{\\partial \\matr{Z}}{\\partial \\matr{Y}}$ is of shape $6\\times6$.}\n\\nonumber\n\\\\ \\label{dZbydY_matrix_addition}\n&=\n\\begin{bmatrix}\n1 & 0 & 0 & 0 & 0 & 0 \\\\%[0.5em]\n0 & 1 & 0 & 0 & 0 & 0 \\\\%[0.5em]\n0 & 0 & 1 & 0 & 0 & 0 \\\\%[0.5em]\n0 & 0 & 0 & 1 & 0 & 0 \\\\%[0.5em]\n0 & 0 & 0 & 0 & 1 & 0 \\\\%[0.5em]\n0 & 0 & 0 & 0 & 0 & 1 \\\\%[0.5em]\n\\end{bmatrix}\n\\end{flalign}\n\n\\noindent Plugging equations \\ref{dZbydY_matrix_addition} and \\ref{dZAsColumnVector_matrix_addition} into equation \\ref{dY_matrix_addition}, we get:\n\n\\begin{flalign}\n\\frac{\\partial L}{\\partial \\matr{Y}} &=\n\\begin{bmatrix}\n1 & 0 & 0 & 0 & 0 & 0 \\\\%[0.5em]\n0 & 1 & 0 & 0 & 0 & 0 \\\\%[0.5em]\n0 & 0 & 1 & 0 & 0 & 0 \\\\%[0.5em]\n0 & 0 & 0 & 1 & 0 & 0 \\\\%[0.5em]\n0 & 0 & 0 & 0 & 1 & 0 \\\\%[0.5em]\n0 & 0 & 0 & 0 & 0 & 1 \\\\%[0.5em]\n\\end{bmatrix}\n\\begin{bmatrix}\n\\frac{\\partial L}{\\partial z_{1,1}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{1,2}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{2,1}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{2,2}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{3,1}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{3,2}} \\\\[0.7em]\n\\end{bmatrix}\n& \\eqncomment{$\\matr{Y}$, $\\matr{Z}$ and $\\frac{\\partial L}{\\partial \\matr{Z}}$ are being treated as column vectors}\n\\nonumber \\\\\n&=\n\\begin{bmatrix}\n\\frac{\\partial L}{\\partial z_{1,1}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{1,2}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{2,1}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{2,2}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{3,1}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{3,2}} \\\\[0.7em]\n\\end{bmatrix} \\label{dYAsColumnVector_matrix_addition}\n\\end{flalign}\n\n\\noindent Reshaping column vector in equation \\ref{dYAsColumnVector_matrix_addition} as a matrix of shape $\\matr{Y}$, we get:\n\n\\begin{flalign}\n\\frac{\\partial L}{\\partial \\matr{Y}} &=\n\\underbrace{\n\\begin{bmatrix}\n\\frac{\\partial L}{\\partial z_{1,1}} &\n\\frac{\\partial L}{\\partial z_{1,2}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{2,1}} &\n\\frac{\\partial L}{\\partial z_{2,2}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{3,1}} &\n\\frac{\\partial L}{\\partial z_{3,2}} \\\\[0.7em]\n\\end{bmatrix}}_{\\frac{\\partial L}{\\partial \\matr{Z}}}\n&\n\\nonumber \\\\\n&=\n\\frac{\\partial L}{\\partial \\matr{Z}}\n\\end{flalign}\n\n\\section{Transpose}\n\\subsection{Forward Pass}\nSuppose we are given a matrix $\\matr{X}$ of shape $3 \\times 2$. Let $\\matr{Z} = \\transpose{\\matr{X}}$. $\\matr{Z}$ will be of shape $2 \\times 3$.\n\n\\begin{flalign}\n\\matr{X} &=\n\\begin{bmatrix}\nx_{1,1} & x_{1,2} \\\\%[0.5em]\nx_{2,1} & x_{2,2} \\\\%[0.5em]\nx_{3,1} & x_{3,2} \\\\%[0.5em]\n\\end{bmatrix} &\n\\nonumber\n\\end{flalign}\n\n\\noindent $\\matr{Z}$ can be expressed as:\n\n\\begin{flalign}\n\\matr{Z} &=\n\\begin{bmatrix}\nz_{1,1} & z_{1,2} & z_{1,3}\\\\%[0.5em]\nz_{2,1} & z_{2,2} & z_{2,3}\\\\%[0.5em]\n\\end{bmatrix} &\n\\nonumber \\\\\n&=\n\\begin{bmatrix}\nx_{1,1} & x_{2,1} & x_{3,1} \\\\%[0.5em]\nx_{1,2} & x_{2,2} & x_{3,2} \\\\%[0.5em]\n\\end{bmatrix}\n\\nonumber\n\\end{flalign}\n\n\\subsection{Backward Pass}\nWe have $\\frac{\\partial L}{\\partial \\matr{Z}}$ of shape $2 \\times 3$.\n\n\\begin{flalign}\n\\frac{\\partial L}{\\partial \\matr{Z}} &=\n\\begin{bmatrix}\n\\frac{\\partial L}{\\partial z_{1,1}} & \\frac{\\partial L}{\\partial z_{1,2}} & \\frac{\\partial L}{\\partial z_{1,3}} \\\\[0.5em]\n\\frac{\\partial L}{\\partial z_{2,1}} & \\frac{\\partial L}{\\partial z_{2,2}} & \\frac{\\partial L}{\\partial z_{2,3}} \\\\[0.5em]\n\\end{bmatrix}\n& \\eqncomment{$\\frac{\\partial L}{\\partial \\matr{Z}}$ is the same shape as $\\matr{Z}$ as $L$ is a scalar}\n\\label{dZ_transpose}\n\\end{flalign}\n\n\\noindent We now need to compute $\\frac{\\partial L}{\\partial \\matr{X}}$. Using chain rule, we get:\n\n\\begin{flalign} \\label{dX_transpose}\n\\frac{\\partial L}{\\partial \\matr{X}} &= \\frac{\\partial \\matr{Z}}{\\partial \\matr{X}}\\frac{\\partial L}{\\partial \\matr{Z}} &\n\\end{flalign}\n\n\\subsubsection{Computing $\\frac{\\partial L}{\\partial \\matr{X}}$}\nTo compute $\\frac{\\partial L}{\\partial \\matr{X}}$, we need to compute $\\frac{\\partial \\matr{Z}}{\\partial \\matr{X}}$. To make it easy for us to think about and capture the Jacobian in a two dimensional matrix (as opposed to a tensor), we will reshape matrices $\\matr{X}$ and $\\matr{Z}$ as column vectors, and compute Jacobians on them. Once we have computed the column vector corresponding to $\\frac{\\partial L}{\\partial \\matr{X}}$, we will reshape it back to a matrix with the same shape as $\\matr{X}$.\n\n\\begin{flalign}\n\\frac{\\partial \\matr{Z}}{\\partial \\matr{X}} &=\n\\begin{bmatrix}\n\\frac{\\partial z_{1,1}}{\\partial x_{1,1}} & \\frac{\\partial z_{1,2}}{\\partial x_{1,1}} & \\frac{\\partial z_{1,3}}{\\partial x_{1,1}} & \\frac{\\partial z_{2,1}}{\\partial x_{1,1}} & \\frac{\\partial z_{2,2}}{\\partial x_{1,1}} & \\frac{\\partial z_{3,3}}{\\partial x_{1,1}}\\\\[0.7em]\n\\frac{\\partial z_{1,1}}{\\partial x_{1,2}} & \\frac{\\partial z_{1,2}}{\\partial x_{1,2}} & \\frac{\\partial z_{1,3}}{\\partial x_{1,2}} & \\frac{\\partial z_{2,1}}{\\partial x_{1,2}} & \\frac{\\partial z_{2,2}}{\\partial x_{1,2}} & \\frac{\\partial z_{3,3}}{\\partial x_{1,2}}\\\\[0.7em]\n\\frac{\\partial z_{1,1}}{\\partial x_{2,1}} & \\frac{\\partial z_{1,2}}{\\partial x_{2,1}} & \\frac{\\partial z_{1,3}}{\\partial x_{2,1}} & \\frac{\\partial z_{2,1}}{\\partial x_{2,1}} & \\frac{\\partial z_{2,2}}{\\partial x_{2,1}} & \\frac{\\partial z_{3,3}}{\\partial x_{2,1}}\\\\[0.7em]\n\\frac{\\partial z_{1,1}}{\\partial x_{2,2}} & \\frac{\\partial z_{1,2}}{\\partial x_{2,2}} & \\frac{\\partial z_{1,3}}{\\partial x_{2,2}} & \\frac{\\partial z_{2,1}}{\\partial x_{2,2}} & \\frac{\\partial z_{2,2}}{\\partial x_{2,2}} & \\frac{\\partial z_{3,3}}{\\partial x_{2,2}}\\\\[0.7em]\n\\frac{\\partial z_{1,1}}{\\partial x_{3,1}} & \\frac{\\partial z_{1,2}}{\\partial x_{3,1}} & \\frac{\\partial z_{1,3}}{\\partial x_{3,1}} & \\frac{\\partial z_{2,1}}{\\partial x_{3,1}} & \\frac{\\partial z_{2,2}}{\\partial x_{3,1}} & \\frac{\\partial z_{3,3}}{\\partial x_{3,1}}\\\\[0.7em]\n\\frac{\\partial z_{1,1}}{\\partial x_{3,2}} & \\frac{\\partial z_{1,2}}{\\partial x_{3,2}} & \\frac{\\partial z_{1,3}}{\\partial x_{3,2}} & \\frac{\\partial z_{2,1}}{\\partial x_{3,2}} & \\frac{\\partial z_{2,2}}{\\partial x_{3,2}} & \\frac{\\partial z_{3,3}}{\\partial x_{3,2}}\\\\[0.7em]\n\\end{bmatrix}\n& \\longeqncomment{$\\matr{X}$, $\\matr{Z}$ are being treated as column vectors.}{Therefore, $\\frac{\\partial \\matr{Z}}{\\partial \\matr{X}}$ is of shape $6\\times6$.}\n\\nonumber\n\\\\ \\label{dZbydX_transpose}\n&=\n\\begin{bmatrix}\n1 & 0 & 0 & 0 & 0 & 0 \\\\%[0.5em]\n0 & 0 & 0 & 1 & 0 & 0 \\\\%[0.5em]\n0 & 1 & 0 & 0 & 0 & 0 \\\\%[0.5em]\n0 & 0 & 0 & 0 & 1 & 0 \\\\%[0.5em]\n0 & 0 & 1 & 0 & 0 & 0 \\\\%[0.5em]\n0 & 0 & 0 & 0 & 0 & 1 \\\\%[0.5em]\n\\end{bmatrix}\n\\end{flalign}\n\n\\noindent Now, $\\frac{\\partial L}{\\partial \\matr{Z}}$ in equation \\ref{dZ_transpose} expressed as a column vector will be:\n\n\\begin{flalign} \\label{dZAsColumnVector_transpose}\n\\frac{\\partial L}{\\partial \\matr{Z}} &=\n\\begin{bmatrix}\n\\frac{\\partial L}{\\partial z_{1,1}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{1,2}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{1,3}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{2,1}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{2,2}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{2,3}} \\\\[0.7em]\n\\end{bmatrix}\n& \\eqncomment{Reshaping $\\frac{\\partial L}{\\partial \\matr{Z}}$ from shape $2 \\times 3$ to $6 \\times 1$}\n\\end{flalign}\n\n\\noindent Plugging equations \\ref{dZbydX_transpose} and \\ref{dZAsColumnVector_transpose} into equation \\ref{dX_transpose}, we get:\n\n\\begin{flalign}\n\\frac{\\partial L}{\\partial \\matr{X}} &=\n\\frac{\\partial \\matr{Z}}{\\partial \\matr{X}}\\frac{\\partial L}{\\partial \\matr{Z}} &\n\\nonumber \\\\\n&=\n\\begin{bmatrix}\n1 & 0 & 0 & 0 & 0 & 0 \\\\%[0.5em]\n0 & 0 & 0 & 1 & 0 & 0 \\\\%[0.5em]\n0 & 1 & 0 & 0 & 0 & 0 \\\\%[0.5em]\n0 & 0 & 0 & 0 & 1 & 0 \\\\%[0.5em]\n0 & 0 & 1 & 0 & 0 & 0 \\\\%[0.5em]\n0 & 0 & 0 & 0 & 0 & 1 \\\\%[0.5em]\n\\end{bmatrix}\n\\begin{bmatrix}\n\\frac{\\partial L}{\\partial z_{1,1}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{1,2}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{1,3}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{2,1}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{2,2}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{2,3}} \\\\[0.7em]\n\\end{bmatrix}\n& \\eqncomment{$\\matr{X}$, $\\matr{Z}$ and $\\frac{\\partial L}{\\partial \\matr{Z}}$ are being treated as column vectors}\n\\nonumber \\\\\n&=\n\\begin{bmatrix}\n\\frac{\\partial L}{\\partial z_{1,1}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{2,1}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{1,2}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{2,2}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{1,3}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{2,3}} \\\\[0.7em]\n\\end{bmatrix} \\label{dXAsColumnVector_transpose}\n\\end{flalign}\n\n\\noindent Reshaping column vector in equation \\ref{dXAsColumnVector_transpose} as a matrix of shape $\\matr{X}$, we get:\n\n\\begin{flalign}\n\\frac{\\partial L}{\\partial \\matr{X}} &=\n\\begin{bmatrix}\n\\frac{\\partial L}{\\partial z_{1,1}} &\n\\frac{\\partial L}{\\partial z_{2,1}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{1,2}} &\n\\frac{\\partial L}{\\partial z_{2,2}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{1,3}} &\n\\frac{\\partial L}{\\partial z_{2,3}} \\\\[0.7em]\n\\end{bmatrix}\n&\n\\nonumber \\\\\n&=\n\\underbrace{\n\\transpose{\n\\begin{bmatrix}\n\\frac{\\partial L}{\\partial z_{1,1}} & \\frac{\\partial L}{\\partial z_{1,2}} & \\frac{\\partial L}{\\partial z_{1,3}} \\\\[0.5em]\n\\frac{\\partial L}{\\partial z_{2,1}} & \\frac{\\partial L}{\\partial z_{2,2}} & \\frac{\\partial L}{\\partial z_{2,3}} \\\\[0.5em]\n\\end{bmatrix}}}_{\\transpose{\\frac{\\partial L}{\\partial \\matr{Z}}}}\n\\nonumber \\\\\n&=\n\\transpose{\\frac{\\partial L}{\\partial \\matr{Z}}}\n\\end{flalign}\n\n\\section{Sum along axis=0}\n\\subsection{Forward Pass}\nSuppose we are given a matrix $\\matr{X}$ of shape $3 \\times 2$. Let $\\vecr{z}$ = \\verb|np.sum(|${\\matr{X}}$\\verb|, axis=0)|. $\\vecr{z}$ will be of shape $1 \\times 2$.\n\n\\begin{flalign}\n\\matr{X} &=\n\\begin{bmatrix}\nx_{1,1} & x_{1,2} \\\\%[0.5em]\nx_{2,1} & x_{2,2} \\\\%[0.5em]\nx_{3,1} & x_{3,2} \\\\%[0.5em]\n\\end{bmatrix} &\n\\nonumber\n\\end{flalign}\n\n\\noindent $\\vecr{z}$ can be expressed as:\n\n\\begin{flalign}\n\\vecr{z} &=\n\\begin{bmatrix}\nz_{1,1} & z_{1,2} \\\\%[0.5em]\n\\end{bmatrix}\n&\n\\nonumber \\\\\n&=\n\\begin{bmatrix}\nx_{1,1} + x_{2,1} + x_{3,1} &\nx_{1,2} + x_{2,2} + x_{3,2} \\\\%[0.5em]\n\\end{bmatrix}\n\\nonumber\n\\end{flalign}\n\n\\subsection{Backward Pass}\nWe have $\\frac{\\partial L}{\\partial \\vecr{z}}$ of shape $1 \\times 2$.\n\n\\begin{flalign}\n\\frac{\\partial L}{\\partial \\vecr{z}} &=\n\\begin{bmatrix}\n\\frac{\\partial L}{\\partial z_{1,1}} & \\frac{\\partial L}{\\partial z_{1,2}} \\\\[0.3em]\n\\end{bmatrix}\n& \\eqncomment{$\\frac{\\partial L}{\\partial \\vecr{z}}$ is the same shape as $\\vecr{z}$ as $L$ is a scalar}\n\\label{dZ_sum_along_axis_0}\n\\end{flalign}\n\n\\noindent We now need to compute $\\frac{\\partial L}{\\partial \\matr{X}}$. Using chain rule, we get:\n\n\\begin{flalign} \\label{dX_sum_along_axis_0}\n\\frac{\\partial L}{\\partial \\matr{X}} &= \\frac{\\partial \\vecr{z}}{\\partial \\matr{X}}\\frac{\\partial L}{\\partial \\vecr{z}} &\n\\end{flalign}\n\n\\subsubsection{Computing $\\frac{\\partial L}{\\partial \\matr{X}}$}\nTo compute $\\frac{\\partial L}{\\partial \\matr{X}}$, we need to compute $\\frac{\\partial \\vecr{z}}{\\partial \\matr{X}}$. To make it easy for us to think about and capture the Jacobian in a two dimensional matrix (as opposed to a tensor), we will reshape matrix $\\matr{X}$ as well as vector $\\vecr{z}$ as column vectors, and compute Jacobians on them. Once we have computed the column vector corresponding to $\\frac{\\partial L}{\\partial \\matr{X}}$, we will reshape it back to a matrix with the same shape as $\\matr{X}$.\n\n\\begin{flalign}\n\\frac{\\partial \\vecr{z}}{\\partial \\matr{X}} &=\n\\begin{bmatrix}\n\\frac{\\partial z_{1,1}}{\\partial x_{1,1}} & \\frac{\\partial z_{1,2}}{\\partial x_{1,1}} \\\\[0.7em]\n\\frac{\\partial z_{1,1}}{\\partial x_{1,2}} & \\frac{\\partial z_{1,2}}{\\partial x_{1,2}} \\\\[0.7em]\n\\frac{\\partial z_{1,1}}{\\partial x_{2,1}} & \\frac{\\partial z_{1,2}}{\\partial x_{2,1}} \\\\[0.7em]\n\\frac{\\partial z_{1,1}}{\\partial x_{2,2}} & \\frac{\\partial z_{1,2}}{\\partial x_{2,2}} \\\\[0.7em]\n\\frac{\\partial z_{1,1}}{\\partial x_{3,1}} & \\frac{\\partial z_{1,2}}{\\partial x_{3,1}} \\\\[0.7em]\n\\frac{\\partial z_{1,1}}{\\partial x_{3,2}} & \\frac{\\partial z_{1,2}}{\\partial x_{3,2}} \\\\[0.7em]\n\\end{bmatrix}\n& \\longeqncomment{$\\matr{X}$, $\\vecr{z}$ are being treated as column vectors.}{Therefore, $\\frac{\\partial \\vecr{z}}{\\partial \\matr{X}}$ is of shape $6\\times2$.}\n\\nonumber\n\\\\ \\label{dZbydX_sum_along_axis_0}\n&=\n\\begin{bmatrix}\n1 & 0 \\\\%[0.5em]\n0 & 1 \\\\%[0.5em]\n1 & 0 \\\\%[0.5em]\n0 & 1 \\\\%[0.5em]\n1 & 0 \\\\%[0.5em]\n0 & 1 \\\\%[0.5em]\n\\end{bmatrix}\n\\end{flalign}\n\n\\noindent Now, $\\frac{\\partial L}{\\partial \\vecr{z}}$ in equation \\ref{dZ_sum_along_axis_0} expressed as a column vector will be:\n\n\\begin{flalign} \\label{dZAsColumnVector_sum_along_axis_0}\n\\frac{\\partial L}{\\partial \\vecr{z}} &=\n\\begin{bmatrix}\n\\frac{\\partial L}{\\partial z_{1,1}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{1,2}} \\\\[0.7em]\n\\end{bmatrix} &\n& \\eqncomment{Reshaping $\\frac{\\partial L}{\\partial \\vecr{z}}$ from shape $1 \\times 2$ to $2 \\times 1$}\n\\end{flalign}\n\n\\noindent Plugging equations \\ref{dZbydX_sum_along_axis_0} and \\ref{dZAsColumnVector_sum_along_axis_0} into equation \\ref{dX_sum_along_axis_0}, we get:\n\n\\begin{flalign}\n\\frac{\\partial L}{\\partial \\matr{X}} &=\n\\frac{\\partial \\vecr{z}}{\\partial \\matr{X}}\\frac{\\partial L}{\\partial \\vecr{z}} &\n\\nonumber \\\\\n&=\n\\begin{bmatrix}\n1 & 0 \\\\%[0.5em]\n0 & 1 \\\\%[0.5em]\n1 & 0 \\\\%[0.5em]\n0 & 1 \\\\%[0.5em]\n1 & 0 \\\\%[0.5em]\n0 & 1 \\\\%[0.5em]\n\\end{bmatrix}\n\\begin{bmatrix}\n\\frac{\\partial L}{\\partial z_{1,1}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{1,2}} \\\\[0.7em]\n\\end{bmatrix}\n& \\eqncomment{$\\matr{X}$, $\\vecr{z}$ and $\\frac{\\partial L}{\\partial \\vecr{z}}$ are being treated as column vectors}\n\\nonumber \\\\\n&=\n\\begin{bmatrix}\n\\frac{\\partial L}{\\partial z_{1,1}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{1,2}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{1,1}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{1,2}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{1,1}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{1,2}} \\\\[0.7em]\n\\end{bmatrix} \\label{dXAsColumnVector_sum_along_axis_0}\n\\end{flalign}\n\n\\noindent Reshaping column vector in equation \\ref{dXAsColumnVector_sum_along_axis_0} as a matrix of shape $\\matr{X}$, we get:\n\n\\begin{flalign}\n\\frac{\\partial L}{\\partial \\matr{X}} &=\n\\begin{bmatrix}\n\\frac{\\partial L}{\\partial z_{1,1}} &\n\\frac{\\partial L}{\\partial z_{1,2}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{1,1}} &\n\\frac{\\partial L}{\\partial z_{1,2}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{1,1}} &\n\\frac{\\partial L}{\\partial z_{1,2}} \\\\[0.7em]\n\\end{bmatrix} \\nonumber\n\\\\\n&=\n\\begin{bmatrix}\n1 \\\\\n1 \\\\\n1 \\\\\n\\end{bmatrix}\n\\underbrace{\n\\begin{bmatrix}\n\\frac{\\partial L}{\\partial z_{1,1}} & \\frac{\\partial L}{\\partial z_{1,2}} \\\\[0.3em]\n\\end{bmatrix}}_{\\frac{\\partial L}{\\partial \\vecr{z}}}\n& \\eqncomment{Decomposing into a matmul operation}\n\\nonumber\n\\\\\n&=\n\\mathbf{1}_{3,1} \\frac{\\partial L}{\\partial \\vecr{z}} \\nonumber\n& \\eqncomment{We are using a bold 1 namely $\\mathbf{1}$ to denote matrix of ones}\n\\\\\n&=\n\\mathbf{1}_{\\text{rows}(\\matr{X}),1} \\frac{\\partial L}{\\partial \\vecr{z}}\n& \\eqncomment{Generalizing beyond our considered example}\n\\end{flalign}\n\n\\section{Sum along axis=1}\n\\subsection{Forward Pass}\nSuppose we are given a matrix $\\matr{X}$ of shape $3 \\times 2$. Let $\\vecr{z}$ = \\verb|np.sum(|${\\matr{X}}$\\verb|, axis=1)|. $\\vecr{z}$ will be of shape $3 \\times 1$.\n\n\\begin{flalign}\n\\matr{X} &=\n\\begin{bmatrix}\nx_{1,1} & x_{1,2} \\\\%[0.5em]\nx_{2,1} & x_{2,2} \\\\%[0.5em]\nx_{3,1} & x_{3,2} \\\\%[0.5em]\n\\end{bmatrix} &\n\\nonumber\n\\end{flalign}\n\n\\noindent $\\vecr{z}$ can be expressed as:\n\n\\begin{flalign}\n\\vecr{z} &=\n\\begin{bmatrix}\nz_{1,1} \\\\\nz_{2,1} \\\\\nz_{3,1} \\\\\n\\end{bmatrix}\n&\n\\nonumber \\\\\n&=\n\\begin{bmatrix}\nx_{1,1} + x_{1,2} \\\\\nx_{2,1} + x_{2,2} \\\\\nx_{3,1} + x_{3,2} \\\\\n\\end{bmatrix}\n\\nonumber\n\\end{flalign}\n\n\\subsection{Backward Pass}\nWe have $\\frac{\\partial L}{\\partial \\vecr{z}}$ of shape $3 \\times 1$.\n\n\\begin{flalign}\n\\frac{\\partial L}{\\partial \\vecr{z}} &=\n\\begin{bmatrix}\n\\frac{\\partial L}{\\partial z_{1,1}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{2,1}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{3,1}} \\\\[0.7em]\n\\end{bmatrix}\n& \\eqncomment{$\\frac{\\partial L}{\\partial \\vecr{z}}$ is the same shape as $\\vecr{z}$ as $L$ is a scalar}\n\\label{dZAsColumnVector_sum_along_axis_1}\n\\end{flalign}\n\n\\noindent We now need to compute $\\frac{\\partial L}{\\partial \\matr{X}}$. Using chain rule, we get:\n\n\\begin{flalign} \\label{dX_sum_along_axis_1}\n\\frac{\\partial L}{\\partial \\matr{X}} &= \\frac{\\partial \\vecr{z}}{\\partial \\matr{X}}\\frac{\\partial L}{\\partial \\vecr{z}} &\n\\end{flalign}\n\n\\subsubsection{Computing $\\frac{\\partial L}{\\partial \\matr{X}}$}\nTo compute $\\frac{\\partial L}{\\partial \\matr{X}}$, we need to compute $\\frac{\\partial \\vecr{z}}{\\partial \\matr{X}}$. To make it easy for us to think about and capture the Jacobian in a two dimensional matrix (as opposed to a tensor), we will reshape matrix $\\matr{X}$ as a column vector, and compute Jacobians on the column vectors instead. Once we have computed the column vector corresponding to $\\frac{\\partial L}{\\partial \\matr{X}}$, we will reshape it back to a matrix with the same shape as $\\matr{X}$.\n\n\\begin{flalign}\n\\frac{\\partial \\vecr{z}}{\\partial \\matr{X}} &=\n\\begin{bmatrix}\n\\frac{\\partial z_{1,1}}{\\partial x_{1,1}} & \\frac{\\partial z_{2,1}}{\\partial x_{1,1}} & \\frac{\\partial z_{3,1}}{\\partial x_{1,1}}\\\\[0.7em]\n\\frac{\\partial z_{1,1}}{\\partial x_{1,2}} & \\frac{\\partial z_{2,1}}{\\partial x_{1,2}} & \\frac{\\partial z_{3,1}}{\\partial x_{1,2}} \\\\[0.7em]\n\\frac{\\partial z_{1,1}}{\\partial x_{2,1}} & \\frac{\\partial z_{2,1}}{\\partial x_{2,1}} & \\frac{\\partial z_{3,1}}{\\partial x_{2,1}} \\\\[0.7em]\n\\frac{\\partial z_{1,1}}{\\partial x_{2,2}} & \\frac{\\partial z_{2,1}}{\\partial x_{2,2}} & \\frac{\\partial z_{3,1}}{\\partial x_{2,2}} \\\\[0.7em]\n\\frac{\\partial z_{1,1}}{\\partial x_{3,1}} & \\frac{\\partial z_{2,1}}{\\partial x_{3,1}} & \\frac{\\partial z_{3,1}}{\\partial x_{3,1}} \\\\[0.7em]\n\\frac{\\partial z_{1,1}}{\\partial x_{3,2}} & \\frac{\\partial z_{2,1}}{\\partial x_{3,2}} & \\frac{\\partial z_{3,1}}{\\partial x_{3,2}} \\\\[0.7em]\n\\end{bmatrix}\n& \\longeqncomment{$\\matr{X}$ is being treated as a column vector.}{Therefore, $\\frac{\\partial \\vecr{z}}{\\partial \\matr{X}}$ is of shape $6\\times3$.}\n\\nonumber\n\\\\ \\label{dZbydX_sum_along_axis_1}\n&=\n\\begin{bmatrix}\n1 & 0 & 0 \\\\%[0.5em]\n1 & 0 & 0 \\\\%[0.5em]\n0 & 1 & 0 \\\\%[0.5em]\n0 & 1 & 0 \\\\%[0.5em]\n0 & 0 & 1 \\\\%[0.5em]\n0 & 0 & 1 \\\\%[0.5em]\n\\end{bmatrix}\n\\end{flalign}\n\n\\noindent Plugging equations \\ref{dZbydX_sum_along_axis_1} and \\ref{dZAsColumnVector_sum_along_axis_1} into equation \\ref{dX_sum_along_axis_1}, we get:\n\n\\begin{flalign}\n\\frac{\\partial L}{\\partial \\matr{X}} &=\n\\frac{\\partial \\vecr{z}}{\\partial \\matr{X}}\\frac{\\partial L}{\\partial \\vecr{z}} &\n\\nonumber \\\\\n&=\n\\begin{bmatrix}\n1 & 0 & 0 \\\\%[0.5em]\n1 & 0 & 0 \\\\%[0.5em]\n0 & 1 & 0 \\\\%[0.5em]\n0 & 1 & 0 \\\\%[0.5em]\n0 & 0 & 1 \\\\%[0.5em]\n0 & 0 & 1 \\\\%[0.5em]\n\\end{bmatrix}\n\\begin{bmatrix}\n\\frac{\\partial L}{\\partial z_{1,1}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{2,1}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{3,1}} \\\\[0.7em]\n\\end{bmatrix}\n& \\eqncomment{$\\matr{X}$ and $\\frac{\\partial L}{\\partial \\vecr{z}}$ are being treated as column vectors}\n\\nonumber \\\\\n&=\n\\begin{bmatrix}\n\\frac{\\partial L}{\\partial z_{1,1}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{1,1}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{2,1}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{2,1}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{3,1}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{3,1}} \\\\[0.7em]\n\\end{bmatrix} \\label{dXAsColumnVector_sum_along_axis_1}\n\\end{flalign}\n\n\\noindent Reshaping column vector in equation \\ref{dXAsColumnVector_sum_along_axis_1} as a matrix of shape $\\matr{X}$, we get:\n\n\\begin{flalign}\n\\frac{\\partial L}{\\partial \\matr{X}} &=\n\\begin{bmatrix}\n\\frac{\\partial L}{\\partial z_{1,1}} &\n\\frac{\\partial L}{\\partial z_{1,1}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{2,1}} &\n\\frac{\\partial L}{\\partial z_{2,1}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{3,1}} &\n\\frac{\\partial L}{\\partial z_{3,1}} \\\\[0.7em]\n\\end{bmatrix} \\nonumber\n\\\\\n&=\n\\underbrace{\n\\begin{bmatrix}\n\\frac{\\partial L}{\\partial z_{1,1}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{2,1}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{3,1}} \\\\[0.7em]\n\\end{bmatrix}}_{\\frac{\\partial L}{\\partial \\vecr{z}}}\n\\begin{bmatrix}\n1 & 1 \\\\%[0.3em]\n\\end{bmatrix}\n& \\eqncomment{Decomposing into a matmul operation}\n\\nonumber\n\\\\\n&=\n\\frac{\\partial L}{\\partial \\vecr{z}} \\mathbf{1}_{1,2}\n& \\eqncomment{We are using a bold 1 namely $\\mathbf{1}$ to denote matrix of ones}\n\\nonumber\n\\\\\n&=\n\\frac{\\partial L}{\\partial \\vecr{z}} \\mathbf{1}_{1, \\text{cols}(\\matr{X})}\n& \\eqncomment{Generalizing beyond our considered example}\n\\end{flalign}\n\n\\section{Broadcasting a column vector}\n\\subsection{Forward Pass}\nSuppose we are given a vector $\\vecr{x}$ of shape $3 \\times 1$. Let $\\matr{Z} = \\vecr{x} \\mathbf{1}_{1,\\text{C}}$ where $\\mathbf{1}$ denotes a matrix of ones. $\\matr{Z}$ will be of shape $3 \\times \\text{C}$. Let us suppose that C = 2.\n\n\\begin{flalign}\n\\vecr{x} &=\n\\begin{bmatrix}\nx_{1,1} \\\\%[0.5em]\nx_{2,1} \\\\%[0.5em]\nx_{3,1} \\\\%[0.5em]\n\\end{bmatrix} &\n\\nonumber\n\\end{flalign}\n\n\\noindent $\\matr{Z}$ can be expressed as:\n\n\\begin{flalign}\n\\matr{Z} &=\n\\begin{bmatrix}\nz_{1,1} & z_{1,2} \\\\\nz_{2,1} & z_{2,2} \\\\\nz_{3,1} & z_{2,3} \\\\\n\\end{bmatrix}\n&\n\\nonumber \\\\\n&=\n\\begin{bmatrix}\nx_{1,1} & x_{1,1} \\\\\nx_{2,1} & x_{2,1} \\\\\nx_{3,1} & x_{3,1} \\\\\n\\end{bmatrix}\n\\nonumber\n\\end{flalign}\n\n\\subsection{Backward Pass}\nWe have $\\frac{\\partial L}{\\partial \\matr{Z}}$ of shape $3 \\times 2$.\n\n\\begin{flalign}\n\\frac{\\partial L}{\\partial \\matr{Z}} &=\n\\begin{bmatrix}\n\\frac{\\partial L}{\\partial z_{1,1}} & \\frac{\\partial L}{\\partial z_{1,2}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{2,1}} & \\frac{\\partial L}{\\partial z_{2,2}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{3,1}} & \\frac{\\partial L}{\\partial z_{3,2}} \\\\[0.7em]\n\\end{bmatrix} \\label{dZ_broadcast_column_vector}\n& \\eqncomment{$\\frac{\\partial L}{\\partial \\vecr{z}}$ is the same shape as $\\vecr{z}$ as $L$ is a scalar}\n\\end{flalign}\n\n\\noindent We now need to compute $\\frac{\\partial L}{\\partial \\vecr{x}}$. Using chain rule, we get:\n\n\\begin{flalign} \\label{dX_broadcast_column_vector}\n\\frac{\\partial L}{\\partial \\vecr{x}} &= \\frac{\\partial \\matr{Z}}{\\partial \\vecr{x}}\\frac{\\partial L}{\\partial \\matr{Z}} &\n\\end{flalign}\n\n\\subsubsection{Computing $\\frac{\\partial L}{\\partial \\vecr{x}}$}\nTo compute $\\frac{\\partial L}{\\partial \\vecr{x}}$, we need to compute $\\frac{\\partial \\matr{Z}}{\\partial \\vecr{x}}$. To make it easy for us to think about and capture the Jacobian in a two dimensional matrix (as opposed to a tensor), we will reshape matrix $\\matr{Z}$ as a column vector, and compute Jacobians on the column vectors instead.\n\n\\begin{flalign}\n\\frac{\\partial \\matr{Z}}{\\partial \\vecr{x}} &=\n\\begin{bmatrix}\n\\frac{\\partial z_{1,1}}{\\partial x_{1,1}} & \\frac{\\partial z_{1,2}}{\\partial x_{1,1}} & \\frac{\\partial z_{2,1}}{\\partial x_{1,1}} & \\frac{\\partial z_{2,2}}{\\partial x_{1,1}} & \\frac{\\partial z_{3,1}}{\\partial x_{1,1}} & \\frac{\\partial z_{3,2}}{\\partial x_{1,1}} \\\\[0.7em]\n\\frac{\\partial z_{1,1}}{\\partial x_{2,1}} & \\frac{\\partial z_{1,2}}{\\partial x_{2,1}} & \\frac{\\partial z_{2,1}}{\\partial x_{2,1}} & \\frac{\\partial z_{2,2}}{\\partial x_{2,1}} & \\frac{\\partial z_{3,1}}{\\partial x_{2,1}} & \\frac{\\partial z_{3,2}}{\\partial x_{2,1}} \\\\[0.7em]\n\\frac{\\partial z_{1,1}}{\\partial x_{3,1}} & \\frac{\\partial z_{1,2}}{\\partial x_{3,1}} & \\frac{\\partial z_{2,1}}{\\partial x_{3,1}} & \\frac{\\partial z_{2,2}}{\\partial x_{3,1}} & \\frac{\\partial z_{3,1}}{\\partial x_{3,1}} & \\frac{\\partial z_{3,2}}{\\partial x_{3,1}} \\\\[0.7em]\n\\end{bmatrix}\n& \\longeqncomment{$\\matr{Z}$ is being treated as a column vector.}{Therefore, $\\frac{\\partial \\matr{Z}}{\\partial \\vecr{x}}$ is of shape $3\\times6$.}\n\\nonumber\n\\\\ \\label{dZbydX_broadcast_column_vector}\n&=\n\\begin{bmatrix}\n1 & 1 & 0 & 0 & 0 & 0\\\\%[0.5em]\n0 & 0 & 1 & 1 & 0 & 0\\\\%[0.5em]\n0 & 0 & 0 & 0 & 1 & 1\\\\%[0.5em]\n\\end{bmatrix}\n\\end{flalign}\n\n\\noindent Now, $\\frac{\\partial L}{\\partial \\matr{Z}}$ in equation \\ref{dZ_broadcast_column_vector} expressed as a column vector will be:\n\n\\begin{flalign} \\label{dZAsColumnVector_broadcast_column_vector}\n\\frac{\\partial L}{\\partial \\matr{Z}} &=\n\\begin{bmatrix}\n\\frac{\\partial L}{\\partial z_{1,1}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{1,2}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{2,1}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{2,2}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{3,1}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{3,2}} \\\\[0.7em]\n\\end{bmatrix}\n& \\eqncomment{Reshaping $\\frac{\\partial L}{\\partial \\matr{Z}}$ from shape $3 \\times 2$ to $6 \\times 1$}\n\\end{flalign}\n\n\\noindent Plugging equations \\ref{dZbydX_broadcast_column_vector} and \\ref{dZAsColumnVector_broadcast_column_vector} into equation \\ref{dX_broadcast_column_vector}, we get:\n\n\\begin{flalign}\n\\frac{\\partial L}{\\partial \\vecr{x}} &=\n\\frac{\\partial \\matr{Z}}{\\partial \\vecr{x}}\\frac{\\partial L}{\\partial \\matr{Z}}\n&\n\\nonumber \\\\\n&=\n\\begin{bmatrix}\n1 & 1 & 0 & 0 & 0 & 0\\\\%[0.5em]\n0 & 0 & 1 & 1 & 0 & 0\\\\%[0.5em]\n0 & 0 & 0 & 0 & 1 & 1\\\\%[0.5em]\n\\end{bmatrix}\n\\begin{bmatrix}\n\\frac{\\partial L}{\\partial z_{1,1}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{1,2}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{2,1}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{2,2}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{3,1}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{3,2}} \\\\[0.7em]\n\\end{bmatrix}\n& \\eqncomment{$\\matr{Z}$ and $\\frac{\\partial L}{\\partial \\matr{Z}}$ are being treated as column vectors}\n\\nonumber \\\\\n&=\n\\begin{bmatrix}\n\\frac{\\partial L}{\\partial z_{1,1}} +\n\\frac{\\partial L}{\\partial z_{1,2}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{2,1}} +\n\\frac{\\partial L}{\\partial z_{2,2}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{3,1}} +\n\\frac{\\partial L}{\\partial z_{3,2}} \\\\[0.7em]\n\\end{bmatrix} \\nonumber\n\\\\\n&=\n\\underbrace{\n\\begin{bmatrix}\n\\frac{\\partial L}{\\partial z_{1,1}} & \\frac{\\partial L}{\\partial z_{1,2}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{2,1}} & \\frac{\\partial L}{\\partial z_{2,2}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{3,1}} & \\frac{\\partial L}{\\partial z_{3,2}} \\\\[0.7em]\n\\end{bmatrix}}_{\\frac{\\partial L}{\\partial \\matr{Z}} }\n\\begin{bmatrix}\n1 \\\\\n1 \\\\\n\\end{bmatrix}\n& \\eqncomment{Decomposing into a matmul operation}\n\\nonumber\n\\\\\n&=\n\\frac{\\partial L}{\\partial \\matr{Z}} \\mathbf{1}_{\\text{2},1}\n& \\eqncomment{We are using a bold 1 namely $\\mathbf{1}$ to denote matrix of ones}\n\\nonumber\n\\\\\n&=\n\\frac{\\partial L}{\\partial \\matr{Z}} \\mathbf{1}_{\\text{C},1}\n& \\eqncomment{Generalizing beyond our considered example}\n\\nonumber\n\\\\\n&= \\mathtt{np.sum(} \\matr{Z} \\mathtt{, axis=1)}\n& \\eqncomment{Using $\\mathtt{NumPy}$ notation for brevity}\n\\end{flalign}\n\n\\section{Broadcasting a row vector}\n\\subsection{Forward Pass}\nSuppose we are given a vector $\\vecr{x}$ of shape $1 \\times 3$. Let $\\matr{Z} = \\mathbf{1}_{\\text{R},1} \\vecr{x}$ where $\\mathbf{1}$ denotes a matrix of ones. $\\matr{Z}$ will be of shape $\\text{R} \\times 3$. Let us suppose that R = 2.\n\n\\begin{flalign}\n\\vecr{x} &=\n\\begin{bmatrix}\nx_{1,1} & x_{1,2} & x_{1,3} \\\\%[0.5em]\n\\end{bmatrix} &\n\\nonumber\n\\end{flalign}\n\n\\noindent $\\matr{Z}$ can be expressed as:\n\n\\begin{flalign}\n\\matr{Z} &=\n\\begin{bmatrix}\nz_{1,1} & z_{1,2} & z_{1,3} \\\\\nz_{2,1} & z_{2,2} & z_{2,3} \\\\\n\\end{bmatrix}\n&\n\\nonumber \\\\\n&=\n\\begin{bmatrix}\nx_{1,1} & x_{1,2} & x_{1,3} \\\\%[0.5em]\nx_{1,1} & x_{1,2} & x_{1,3} \\\\%[0.5em]\n\\end{bmatrix}\n\\nonumber\n\\end{flalign}\n\n\\subsection{Backward Pass}\nWe have $\\frac{\\partial L}{\\partial \\matr{Z}}$ of shape $2 \\times 3$.\n\n\\begin{flalign}\n\\frac{\\partial L}{\\partial \\matr{Z}} &=\n\\begin{bmatrix}\n\\frac{\\partial L}{\\partial z_{1,1}} & \\frac{\\partial L}{\\partial z_{1,2}} & \\frac{\\partial L}{\\partial z_{1,3}}\\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{2,1}} & \\frac{\\partial L}{\\partial z_{2,2}} & \\frac{\\partial L}{\\partial z_{2,3}}\\\\[0.7em]\n\\end{bmatrix}\n& \\eqncomment{$\\frac{\\partial L}{\\partial \\vecr{z}}$ is the same shape as $\\vecr{z}$ as $L$ is a scalar}\n\\label{dZ_broadcast_row_vector}\n\\end{flalign}\n\n\\noindent We now need to compute $\\frac{\\partial L}{\\partial \\vecr{x}}$. Using chain rule, we get:\n\n\\begin{flalign} \\label{dX_broadcast_row_vector}\n\\frac{\\partial L}{\\partial \\vecr{x}} &= \\frac{\\partial \\matr{Z}}{\\partial \\vecr{x}}\\frac{\\partial L}{\\partial \\matr{Z}} &\n\\end{flalign}\n\n\\subsubsection{Computing $\\frac{\\partial L}{\\partial \\vecr{x}}$}\nTo compute $\\frac{\\partial L}{\\partial \\vecr{x}}$, we need to compute $\\frac{\\partial \\matr{Z}}{\\partial \\vecr{x}}$. To make it easy for us to think about and capture the Jacobian in a two dimensional matrix (as opposed to a tensor), we will reshape matrix $\\matr{Z}$ as well as vector $\\vecr{x}$ as a column vector, and compute Jacobians on the column vectors instead.\n\n\\begin{flalign}\n\\frac{\\partial \\matr{Z}}{\\partial \\vecr{x}} &=\n\\begin{bmatrix}\n\\frac{\\partial z_{1,1}}{\\partial x_{1,1}} & \\frac{\\partial z_{1,2}}{\\partial x_{1,1}} & \\frac{\\partial z_{1,3}}{\\partial x_{1,1}} & \\frac{\\partial z_{2,1}}{\\partial x_{1,1}} & \\frac{\\partial z_{2,2}}{\\partial x_{1,1}} & \\frac{\\partial z_{2,3}}{\\partial x_{1,1}} \\\\[0.7em]\n\\frac{\\partial z_{1,1}}{\\partial x_{1,2}} & \\frac{\\partial z_{1,2}}{\\partial x_{1,2}} & \\frac{\\partial z_{1,3}}{\\partial x_{1,2}} & \\frac{\\partial z_{2,1}}{\\partial x_{1,2}} & \\frac{\\partial z_{2,2}}{\\partial x_{1,2}} & \\frac{\\partial z_{2,3}}{\\partial x_{1,2}} \\\\[0.7em]\n\\frac{\\partial z_{1,1}}{\\partial x_{1,3}} & \\frac{\\partial z_{1,2}}{\\partial x_{1,3}} & \\frac{\\partial z_{1,3}}{\\partial x_{1,3}} & \\frac{\\partial z_{2,1}}{\\partial x_{1,3}} & \\frac{\\partial z_{2,2}}{\\partial x_{1,3}} & \\frac{\\partial z_{2,3}}{\\partial x_{1,3}} \\\\[0.7em]\n\\end{bmatrix}\n& \\longeqncomment{$\\matr{Z}$ and $\\vecr{x}$ are being treated as column vectors.}{Therefore, $\\frac{\\partial \\matr{Z}}{\\partial \\vecr{x}}$ is of shape $3\\times6$.}\n\\nonumber\n\\\\ \\label{dZbydX_broadcast_row_vector}\n&=\n\\begin{bmatrix}\n1 & 0 & 0 & 1 & 0 & 0\\\\%[0.5em]\n0 & 1 & 0 & 0 & 1 & 0\\\\%[0.5em]\n0 & 0 & 1 & 0 & 0 & 1\\\\%[0.5em]\n\\end{bmatrix}\n\\end{flalign}\n\n\\noindent Now, $\\frac{\\partial L}{\\partial \\matr{Z}}$ in equation \\ref{dZ_broadcast_row_vector} expressed as a column vector will be:\n\n\\begin{flalign} \\label{dZAsColumnVector_broadcast_row_vector}\n\\frac{\\partial L}{\\partial \\matr{Z}} &=\n\\begin{bmatrix}\n\\frac{\\partial L}{\\partial z_{1,1}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{1,2}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{1,3}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{2,1}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{2,2}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{2,3}} \\\\[0.7em]\n\\end{bmatrix}\n& \\eqncomment{Reshaping $\\frac{\\partial L}{\\partial \\matr{Z}}$ from shape $2 \\times 3$ to $6 \\times 1$}\n\\end{flalign}\n\n\\noindent Plugging equations \\ref{dZbydX_broadcast_row_vector} and \\ref{dZAsColumnVector_broadcast_row_vector} into equation \\ref{dX_broadcast_row_vector}, we get:\n\n\\begin{flalign}\n\\frac{\\partial L}{\\partial \\vecr{x}} &=\n\\frac{\\partial \\matr{Z}}{\\partial \\vecr{x}}\\frac{\\partial L}{\\partial \\matr{Z}}\n&\n\\nonumber \\\\\n&=\n\\begin{bmatrix}\n1 & 0 & 0 & 1 & 0 & 0\\\\%[0.5em]\n0 & 1 & 0 & 0 & 1 & 0\\\\%[0.5em]\n0 & 0 & 1 & 0 & 0 & 1\\\\%[0.5em]\n\\end{bmatrix}\n\\begin{bmatrix}\n\\frac{\\partial L}{\\partial z_{1,1}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{1,2}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{1,3}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{2,1}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{2,2}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{2,3}} \\\\[0.7em]\n\\end{bmatrix}\n& \\eqncomment{$\\matr{Z}$, $\\vecr{x}$ and $\\frac{\\partial L}{\\partial \\matr{Z}}$ are being treated as column vectors}\n\\nonumber \\\\\n&=\n\\begin{bmatrix}\n\\frac{\\partial L}{\\partial z_{1,1}} +\n\\frac{\\partial L}{\\partial z_{2,1}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{1,2}} +\n\\frac{\\partial L}{\\partial z_{2,2}} \\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{1,3}} +\n\\frac{\\partial L}{\\partial z_{2,3}} \\\\[0.7em]\n\\end{bmatrix} \\label{dXAsColumnVector_broadcast_row_vector}\n\\end{flalign}\n\n\\noindent Now reshaping $\\frac{\\partial L}{\\partial \\vecr{x}}$ from column vector of shape $3 \\times 1$ in equation \\ref{dXAsColumnVector_broadcast_row_vector} into row vector of shape $1 \\times 3$ we get:\n\n\\begin{flalign}\n\\frac{\\partial L}{\\partial \\vecr{x}} &=\n\\begin{bmatrix}\n\\frac{\\partial L}{\\partial z_{1,1}} +\n\\frac{\\partial L}{\\partial z_{2,1}} &\n\\frac{\\partial L}{\\partial z_{1,2}} +\n\\frac{\\partial L}{\\partial z_{2,2}} &\n\\frac{\\partial L}{\\partial z_{1,3}} +\n\\frac{\\partial L}{\\partial z_{2,3}} \\\\[0.7em]\n\\end{bmatrix}\n\\nonumber \\\\\n&=\n\\begin{bmatrix}\n1 & 1\\\\\n\\end{bmatrix}\n\\underbrace{\n\\begin{bmatrix}\n\\frac{\\partial L}{\\partial z_{1,1}} & \\frac{\\partial L}{\\partial z_{1,2}} & \\frac{\\partial L}{\\partial z_{1,3}}\\\\[0.7em]\n\\frac{\\partial L}{\\partial z_{2,1}} & \\frac{\\partial L}{\\partial z_{2,2}} & \\frac{\\partial L}{\\partial z_{2,3}}\\\\[0.7em]\n\\end{bmatrix}}_{\\frac{\\partial L}{\\partial \\matr{Z}}}\n& \\eqncomment{Decomposing into a matmul operation}\n\\nonumber \\\\\n&=\n\\mathbf{1}_{1, \\text{2}} \\frac{\\partial L}{\\partial \\matr{Z}}\n& \\eqncomment{We are using a bold 1 namely $\\mathbf{1}$ to denote matrix of ones}\n\\nonumber \\\\\n&=\n\\mathbf{1}_{1, \\text{R}} \\frac{\\partial L}{\\partial \\matr{Z}}\n& \\eqncomment{Generalizing beyond our considered example}\n\\nonumber \\\\\n&=\n\\mathtt{np.sum(} \\matr{Z} \\mathtt{, axis=0)}\n& \\eqncomment{Using $\\mathtt{NumPy}$ notation for brevity}\n\\end{flalign}\n\n\\medskip\n\n\\printbibliography\n\n\\end{document}\n", "meta": {"hexsha": "4230efdbc681ae5ca6a0c055cf13f2bd6b6741ae", "size": 87223, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "student-contributions/BackPropagationBasicMatrixOperations.tex", "max_stars_repo_name": "trajo/cs231n.github.io", "max_stars_repo_head_hexsha": "e0c439dcd9632993d40adfce1ea548dd5933a6e6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9615, "max_stars_repo_stars_event_min_datetime": "2015-01-05T06:56:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T06:46:07.000Z", "max_issues_repo_path": "student-contributions/BackPropagationBasicMatrixOperations.tex", "max_issues_repo_name": "trajo/cs231n.github.io", "max_issues_repo_head_hexsha": "e0c439dcd9632993d40adfce1ea548dd5933a6e6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 191, "max_issues_repo_issues_event_min_datetime": "2015-01-20T02:04:45.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-07T18:24:43.000Z", "max_forks_repo_path": "student-contributions/BackPropagationBasicMatrixOperations.tex", "max_forks_repo_name": "trajo/cs231n.github.io", "max_forks_repo_head_hexsha": "e0c439dcd9632993d40adfce1ea548dd5933a6e6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4678, "max_forks_repo_forks_event_min_datetime": "2015-01-05T18:40:56.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T00:40:15.000Z", "avg_line_length": 45.0532024793, "max_line_length": 746, "alphanum_fraction": 0.6293408849, "num_tokens": 36332, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48047867804790706, "lm_q2_score": 0.3665897294020099, "lm_q1q2_score": 0.17613854856901767}}
{"text": "% Johdanto\n\\section{Introduction}\n%Non-static Object Capture Using Multi-view Stereo Video\n%% Leave first page empty\n% (wat?)\n\\thispagestyle{empty}\n\nComputer vision is a mature field; the steps of acquiring three-dimensional structure of a real-life scene are well known.\nMultiple view geometry (or multi-view stereo) is a method to interpret depth in camera images and thus to acquire 3D scans.\n\\cite{hartley03multiview,szeliski10vision,trucco1998introductory,heyden2005multiple}\nFor detailed scanning dealing arbitrary reconstruction types, there exist a wide range of algorithms, each suited for different setups.\n\\cite{seitz2006comparison}.\n\nStereo vision and the related motion capture are well studied fields.\n3D scanning and reconstruction has been successfully done on single objects and bigger scenes accurately with the help of ever increasing computing power\n\\cite{goesele2007multi,furukawa2010towards,pollefeys1999hand},\nand mocap in coarser form is an ubiquitous tool in the film industry \\cite{moeslund2006survey}.\nMicrosoft Photosynth \\cite{photosynth}, for example, is able to take an arbitrary collection of photos from the internet and reconstruct three-dimensional models of publicly photographed targets. Users can also upload their own collections.\nAnother web-based tool is Autodesk 123D Catch \\cite{autodeskcatch}, which is popular among hobbyists. It reconstructs three-dimensional models from photographs with no configuration, but with a restricted accuracy.\n\nUsing similar principles as the human eyes to calculate point disparity and depth of individual pixels from photos, 3D point clouds can be constructed, given only a set of two-dimensional images taken of a same target from different poses and and a few camera parameters.\n\\cite{hartley03multiview}\nThis technique, also called photogrammetry, has applications in many fields ranging from mapping of larger scenes to scanning of individual objects.\nThe principles are mature; current state of computing power and quality cameras has introduced lots of progress in automatic software tools.\n\n%Recent advances in additive fabrication, informally called 3D printing, have brought the need to scan the geometry of arbitrary objects accurately in order to replicate them by printing.\n%Hobby-grade printer enthusiasts have needed to rely mostly on manual measurements and/or lots of manual work in modeling tools; low-cost scanning could bring new dimensions to the area.\n%Professional quality capture still needs a laboratory environment with a large number of cameras \\cite{winder2008technical,motionscan}.\n\nThree-dimensional structure can be scanned with other means too, such as laser range finders \\cite{levoy2000digital} or structured light \\cite{rocchini2001low}; in this seminar work, the focus is kept on stereo-based computer vision.\n\nWhen 3D scanning is extended to take into account temporal changes in geometry or appearance (color), more complex hardware and calculations are needed in order to cope with the changing data.\nNon-static cases need a larger set of cameras set up so that the captured target can move while the geometry is imaged from several different directions.\nApplications include for example performance capture for video games or movies \\cite{bradley2010high}, cloth deformation capture \\cite{pritchard2003cloth} and aerial heritage mapping \\cite{remondino2011heritage}.\nA related field in robotics is simultaneous localization and mapping (SLAM), where the surroundings are mostly static but the camera moves in an unknown environment. \\cite{durrant2006simultaneous}\n\nFor there are several methods on the topic, choices must be made when implementing the reconstruction setup.\nThe length of this seminar work cannot cover all the details; the common initial steps are described, sometimes referring to more detailed papers for details.\nThe bottom-up structure of this work is divided as follows: the first part presents the basic geometric principles behind most implementations on stereo vision, starting from grabbing images of real-life scenes, finally extending to multi-view stereo.\nIssues in the dynamic case are discussed when applicable.\nThen, the next chapter focuses on what should be done when tracking the dynamic actions of a scanned target.\nFinally, the current state of software tools and applications are presented. The last chapter summarizes the methods.\n", "meta": {"hexsha": "3fb9c8995c9fca9898d147a5019a5cf2def315c0", "size": 4387, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "semma/tex/introduction.tex", "max_stars_repo_name": "sooda/thesis", "max_stars_repo_head_hexsha": "25838d80eeb93d7fc2028c6a69ee745652c9efa4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2015-06-06T23:57:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-15T01:13:52.000Z", "max_issues_repo_path": "semma/tex/introduction.tex", "max_issues_repo_name": "sooda/thesis", "max_issues_repo_head_hexsha": "25838d80eeb93d7fc2028c6a69ee745652c9efa4", "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": "semma/tex/introduction.tex", "max_forks_repo_name": "sooda/thesis", "max_forks_repo_head_hexsha": "25838d80eeb93d7fc2028c6a69ee745652c9efa4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-04-27T03:55:10.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-27T03:55:10.000Z", "avg_line_length": 102.023255814, "max_line_length": 271, "alphanum_fraction": 0.8269888306, "num_tokens": 879, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.3415825128436339, "lm_q1q2_score": 0.17612674648489038}}
{"text": "\\documentclass[11pt,a4paper]{article}\n\n% These are extra packages that you might need for writing the equations:\n\\usepackage{amsmath}\n\\usepackage{amsfonts}\n\\usepackage{amssymb}\n\\usepackage{booktabs}\n\\usepackage{hyperref}\n\\usepackage{listings}\n\\usepackage{xcolor}\n\\lstset {language=C++,\n\t\t basicstyle=\\ttfamily,\n keywordstyle=\\color{blue}\\ttfamily,\n stringstyle=\\color{red}\\ttfamily,\n commentstyle=\\color{purple}\\ttfamily,\n morecomment=[l][\\color{magenta}]{\\#},\n \t basicstyle=\\tiny}\n\n% You need the following package in order to include figures in your report:\n\\usepackage{graphicx}\n\n% With this package you can set the size of the margins manually:\n\\usepackage[left=2cm,right=2cm,top=2cm,bottom=2cm]{geometry}\n\n\n\\begin{document}\n\n% Enter the exercise number, your name and date here:\n\\noindent\\parbox{\\linewidth}{\n \\parbox{.25\\linewidth}{ \\large HPCSE I, Exercise 04 }\\hfill\n \\parbox{.5\\linewidth}{\\begin{center} \\large Beat Hubmann \\end{center}}\\hfill\n \\parbox{.2\\linewidth}{\\begin{flushright} \\large Oct 22, 2018 \\end{flushright}}\n}\n\\noindent\\rule{\\linewidth}{2pt}\n\n\\section{Question 1: Amdahl's Law}\n\n\\subsection{Task a)}\nDisregarding the misplaced marketing hyperbole for the sake of the argument and assuming the new train route follows the bus route (i.e. has the same length),\n we designate the section from Luzern to Rotkreuz as serial fraction:\n$f_1 = \\frac{55 \\text{km} - 36 \\text{km}}{55 \\text{km}} = 0.345$. This leaves the potential new train section as improvable fraction: $f_p = 1 - f_1 = 0.655$.\nBased on the information given, we assume that the average speed $v_b = \\frac{55 \\text{km}}{1.5 \\text{h}} = 36.67 \\text{km/h} $ of the bus \non the total leg LU-ZH also applies to the fraction $f_1$, whereas $v_t = 70 \\text{km/h}$ is given for the train speed on the fraction $f_p$.\nThis in turn gives a speedup factor $p = \\frac{70 \\text{km/h}}{36.67 \\text{km/h}} = 1.91$.\n\n\\subsubsection{Task a.i)}\nNobody will get any improvement from the announcement per se, but if implemented, it will offer a speedup of 1.453 as seen from equation~\\ref{eqn:1}.\nIn other words, the ideal one-way journey time will reduce from 90 minutes to 62 minutes.\n\n\\begin{equation}\n S_p = \\frac{1}{f_1 + \\frac{f_p}{p}} = \\frac{1}{0.345 + \\frac{0.655}{1.91}} = 1.453\n\\label{eqn:1}\n\\end{equation}\n\n\\subsubsection{Task a.ii)}\nAgain using equation~\\ref{eqn:1}, this time with a (rounded) speedup factor of $p = 3 \\cdot 10^7$, we get a theoretical speedup of 2.9 and thus\na one-way journey time of about 30 minutes.\n\n\\subsection{Task b)}\nAs per the task description, we disregard hyperthreading and thus plainly assume 12 CPU cores per socket. Also, we are given that \n$f_p = 0.9$ and thus $f_1 = 1 - f_p = 0.1$. Finally, we assume that the code currently is in serialized form running on a single core.\n\n\\subsubsection{Task b.i)}\nThe desired speedup is given as $S_p = 8$. Solving equation~\\ref{eqn:1} for $p$, \nwe get that the desired speedup from serial execution requires a minimum of 36 cores (equation~\\ref{eqn:2}).\n\n\\begin{equation}\n p = \\frac{S_p \\cdot f_p}{1 - S_p \\cdot f_1 } = \\frac{8 \\cdot 0.9}{1 - 8 \\cdot 0.1} = 36\n\\label{eqn:2}\n\\end{equation}\n\n\\subsubsection{Task b.ii)}\nAs we need three full sockets (36 / 12 = 3), but sockets only come paired up as nodes, we require two nodes. As we then might as well\nuse them completely, the obtainable speed up is, again using equation~\\ref{eqn:1}, $S_{p=48} = \\frac{1}{0.1 + \\frac{0.9}{48}} = 8.42$.\n\n\\subsubsection{Task b.iii)}\nThe price for additional nodes can safely be assumed to be non-negligible. It can therefore credibly be argued that buying more nodes doesn't \nmake any sense, as obviously even for $p \\rightarrow \\infty$ the absolute best obtainable speedup would be\n $\\lim_{p \\rightarrow \\infty} S_p = \\frac{1}{0.1 + \\frac{0.9}{p}} = 10$.\n\n% \\begin{figure}[ht]\n% \\begin{center}\n% \\includegraphics[scale=0.5]{results.png} \n% \\end{center}\n% \\caption{Parallel Monte Carlo integration on Euler compute cluster.}\n% \\label{fig1}\n% \\end{figure}\n\n\\section{Question 2: Manual Vectorization of Reduction Operator}\n\n\n\\subsection{Task a)}\nDone as instructed.\n\n\\subsection{Task b)}\nDone as instructed.\n\n\\subsection{Task c)}\nDone as instructed.\n\n\\subsubsection{Task c.i)}\nIn accordance with the SIMD width, a speed up of 4 and 2 respectively was expected for serial execution.\nWith thread level parallelism, the maximum additional speedup factor should be in the order of the number of threads employed.\n\n\\subsubsection{Task c.ii)}\nThe differences between lasrge and small vector size seem somewhat inconclusive. However it is evident that the overhead\nin the OpenMP implementation as expected didn't result perfect speedup.\n\n\n\\begin{figure}[ht]\n\\begin{center}\n\\includegraphics[scale=0.5]{2-way.pdf} \n\\end{center}\n\\caption{Thread level parallelism speedup of reduction operator: Double precision data.}\n\\label{fig1}\n\\end{figure}\n\n\n\\begin{figure}[ht]\n\\begin{center}\n\\includegraphics[scale=0.5]{4-way.pdf} \n\\end{center}\n\\caption{Thread level parallelism speedup of reduction operator: Single precision data.}\n\\label{fig2}\n\\end{figure}\n \n\n\n\n\\section{Question 3}\n\n\n\\subsection{Task a)}\n\n\nDone as instructed.\n\n\\subsection{Task b)}\n\nDone as instructed.\n\\subsection{Task c)}\n\nAttempted as instructed, however ran out of time when trying to properly implement\n\\texttt{ISPC} matrix multiplication.\n\n\\subsection{Task d)}\nSee c) above; implementation not fully functional.\n\n\\subsection{Task e)}\nSee c) above; implementation not fully functional.\n\n\\subsection{Task f)}\nSee c) above; implementation not fully functional.\n\n\n\n%\\begin{thebibliography}{99}\n%\n%\\bibitem{nasa}\n%\tNASA,\n%\t\\emph{Haswell Processors},\n%\tonline (\\url{https://www.nas.nasa.gov/hecc/support/kb/haswell-processors_492.html}),\n%\taccessed 30-Sep-2018.\n%\n%\\bibitem{intel}\n%\tIntel Corporation,\n%\t\\emph{Intel Xeon Processor E5-2680 v3 Product Specifications},\n%\tonline (\\url{https://ark.intel.com/products/81908/}),\n%\taccessed 30-Sep-2018.\n%\t\n%\\bibitem{euler}\n%\tETH Zurich,\n%\t\\emph{scientific computing wiki: Euler},\n%\tonline (\\url{https://scicomp.ethz.ch/wiki/Euler#Euler_II}),\n%\taccessed 30-Sep-2018.\t\n%\n%\\bibitem{kou}\n%\tPetros Koumoutsakos,\n%\t\\emph{HPCSE I Lecture Notes},\n%\tonline (\\url{http://www.cse-lab.ethz.ch/wp-content/uploads/2018/09/HPCSE_I_1_Intro.pdf}),\n%\taccessed 30-Sep-2018.\n%\n%\\end{thebibliography}\n%\n\n%\\appendix\n%\\section{Question 4, task d)}\\label{app}\n%\\lstinputlisting{ex01_q4_task_d.cpp}\n\\end{document}", "meta": {"hexsha": "7da8c7f07d5258e3c7c6304cc6dd87c5b88b4a0e", "size": 6461, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "ex04/ex04_report.tex", "max_stars_repo_name": "BeatHubmann/18H-HPC1", "max_stars_repo_head_hexsha": "48545c83b4f71b7f7021ff1090c8d9cbada17dbc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ex04/ex04_report.tex", "max_issues_repo_name": "BeatHubmann/18H-HPC1", "max_issues_repo_head_hexsha": "48545c83b4f71b7f7021ff1090c8d9cbada17dbc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ex04/ex04_report.tex", "max_forks_repo_name": "BeatHubmann/18H-HPC1", "max_forks_repo_head_hexsha": "48545c83b4f71b7f7021ff1090c8d9cbada17dbc", "max_forks_repo_licenses": ["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.1851851852, "max_line_length": 158, "alphanum_fraction": 0.7299179694, "num_tokens": 1964, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45713671682749485, "lm_q2_score": 0.38491214448393346, "lm_q1q2_score": 0.17595747399641568}}
{"text": "%This documents the Ballad VM. If we end up releasing it bare-bones, wrap this\n%document in appropriate silly or challenge related stuff later.\n\n\n\\section{Ballad} Ballad is a programming language expressed in music. It is an\n`interpreted', Turing complete language which does not follow the von Neumann\narchitecture. This is the case insofar as code memory is separate from static,\nnon-executable memory as well as the actual, active memory. The Ballad VM has a\nseries of registers as well as a stack, in which active data is processed. \n\nThe code memory cannot be modified during the execution of a program, nor can\nthe static memory section. These are not placed on a heap or stack, as in a\nmore conventional program, but are maintained separately from the active\nmemory. The static memory can be of arbitrary size, but the code memory is\nrestricted to a maximum of 256 bytes. The implementation of the Ballad VM\nshould reflect this.\n\nThe stack is similarly limited in size to 256 bytes. It can be pushed and\npopped from, but it can also be addressed and written to directly in the style\nof a stack of fixed length backed by an array. A stack pointer internal to the\nVM should track the location of the top of the stack; the bottom is fixed to\nthe zero position and the stack grows upwards. The stack is addressed by Ballad\ninstructions ranging from 0x00 (the bottom) to 0xFF (the largest value).\n\nAll data is, by default, an unsigned eight bit integer. Modifications to this\nmay be made by the program (for example, implementing two's complement or the\nlike), but the Ballad VM should treat all numbers as such for the purpose of\ncalculating overflow.\n\nThere are two sets of registers which Ballad uses. These are the math registers\nand the swap registers. One set is designed for and used by all arithmetic\noperations, the other set is designed for moving data between locations and as\na general purpose register set. There are eight registers of each type and are\naddressed by a byte of value 0x00 to 0x07. \n\n\\subsection{Decoding} Ballad programs consist of static data sections and code\nsections which are expressed as music in (at least) two-track MIDI files. The\nfirst track consists of the static memory section and the second of the code\nsection. Other tracks are ignored. \n\nWithin a track, interpretation is ignored until one whole note (4 beats in 4/4)\nis found by the Ballad VM. All Ballad tracks must have this whole note at the\nbeginning of a valid section, code or data. This note is used to decode the\nrest of the section, by providing the appropriate key, or MIDI note number.\nThis key is used to demodulate the rest of the song, which is restricted to\nnotes on the major scale, based on this key.\n\nDemodulation occurs by first transposing the key of song to a common key\n(typically by subtracting the MIDI number of the tonic note mentioned above\nfrom the MIDI number of the given note to decode). The only relevant note in a\nchord is its root; all higher notes are ignored in this version of Ballad. Once\nthe song is in a uniform key, it is necessary to obtain the offset \\emph{in the\nscale} of the given note to decode (as opposed to its raw MIDI number). In any\ngiven Ballad program, there are only sixteen notes of the major scale given as\nchord roots or individual notes. To obtain Ballad bytecode from a Ballad song,\nit is necessary to map these to bytes.\n\nThe mapping of notes to bytes is done by first obtaining the aforementioned\noffset. This yields one of sixteen numbers, or 0x0 to 0xF. Taken in pairs, from\nthe beginning of the Ballad song to the end, then converted into bytes, Ballad\nbytecode is obtained. For example, if the whole note at the start of one of the\ntracks was `A-0', then the next two notes were `A-0' then `D-1', the resulting\nhex byte would be 0x0a, or newline in ASCII (where 0 represents the first\noctave, 1 represents the one above it). By applying this to each of the first\ntwo tracks of the Ballad song, a sequence of bytes can be obtained.\n\n\\subsection{Static Memory} Static memory is used to provide predetermined input\nto a Ballad program. In other languages, this would usually take the form of\nconstant character strings. It is indexed from zero by Ballad instructions and\ncan be loaded via the static loading commands.\n\n\\subsection{Code Memory} Code memory is a linear chain of instructions and\ntheir arguments. There are instructions which take between one and three\narguments. Each instruction to a Ballad argument is one byte long, which makes\ncalls fairly straightforward.\n\n\\clearpage\n\\section{Ballad Instructions} This section describes the various Ballad\ninstructions, their calling conventions and what registers are accessed by a\ngiven call, if any. Math registers are referenced as \\emph{m}, the general\npurpose, or swap registers, are referenced by \\emph{s} and immediate\ninstructions (in unsigned single-byte representations) are indicated by\n\\emph{im}. If an instruction accepts no arguments, \\emph{None} is used.\n\n\\subsection{Mathematical Instructions}\nAll arithmetic operations imply unsigned integer arithmetic and overflow where\nappropriate.\n\\\\\n\\begin{table}[h!]\n\\centering\n\\caption{Mathematical Instructions}\n\\begin{tabular}{| l | l | l | p{8cm} | }\n\t\\hline\n\tInstruction & Opcode & Arguments & Semantics \\\\\\hline\n\t\t add & 1 & m0, m1 & Add the values stored in m0 to m1 and store the result\n\tin m0 \\\\\\hline\n\t\t sub & 2 & m0, m1 & Subtract the values stored in m1 from m0 and store the result\n\tin m0 \\\\\\hline\n\t\t mul & 3 & m0, m1 & Multiply the values stored in m0 to m1 and store the result\n\tin m0 \\\\\\hline\n\t\t div & 4 & m0, m1 & Divide m0 by m1 and store the result\n\tin m0 \\\\\\hline\n\t\t xor & 5 & m0, m1 & Perform a bitwise exclusive or on the values stored in \n\tm0 to m1 and store the result in m0 \\\\\\hline\n\t\t and & 6 & m0, m1 & Perform a bitwise `and' on the values stored in \n\tm0 to m1 and store the result in m0 \\\\\\hline\n\t\t or & 7 & m0, m1 & Perform a bitwise `or' on the values stored in \n\tm0 to m1 and store the result in m0 \\\\\\hline\n\t\t or & 8 & m0, m1 & Perform a bitwise inverse (0b00000000 $\\rightarrow$ 0b11111111) on the \n\tvalues stored in \n\tm0 to m1 and store the result in m0 \\\\\\hline\n\tinc & 9 & m0 & Increment the value in m0 by one and save it to m0 \\\\\\hline\n\tdec & 10 & m0 & Decrement the value in m0 by one and save it to m0 \\\\\\hline\n\\end{tabular}\n\\end{table}\n\\clearpage\n\\subsection{Jump Instructions}\nThese instructions change the instruction pointer (IP) in some way. Offsets\nrange from 0 (the start of the code section) and can end at 255 (the end of the\ncode section). When given, an immediate (\\emph{im}) value is an offset.\n\\begin{table}[h!]\n\t\\centering\n\t\\caption{Jump Instructions}\n\t\\begin{tabular}{|l|l|l|p{8cm}|}\n\t\t\\hline\n\t\tInstruction & Opcode & Arguments & Semantics \\\\\\hline\n\t\t\t jmp & 11 & im & Set the IP to the given offset \\\\\\hline\n\t\t\t jeq & 12 & m0, m1, im & If the value in m0 is equal to the value stored\n\t\t\t\t\tin m1, set the IP to the offset \\\\\\hline\n\t\t\t jne & 13 & m0, m1, im & If the value in m0 is not equal to the value stored\n\t\t\t\t\tin m1, set the IP to the offset \\\\\\hline\n\t\t\t jlt & 14 & m0, m1, im & If the value in m0 is less than the value stored\n\t\t\t\t\tin m1, set the IP to the offset \\\\\\hline\n\t\t\t jgt & 15 & m0, m1, im & If the value in m0 is greater than the value stored\n\t\t\t\t\tin m1, set the IP to the offset \\\\\\hline\n\t\t\t jlte & 16 & m0, m1, im & If the value in m0 is less than \n\t\t\t\t\tor equal to the value stored\n\t\t\t\t\tin m1, set the IP to the offset \\\\\\hline\n\t\t\t jgte & 17 & m0, m1, im & If the value in m0 is greater than \n\t\t\t\t\tor equal to the value stored\n\t\t\t\t\tin m1, set the IP to the offset \\\\\\hline\n\t\t\t\tret & 28 & m0 & Set the IP to the value stored in m0 \\\\\\hline\n\t\\end{tabular}\n\\end{table}\n\n\\clearpage\n\\subsection{Memory Instructions}\nThese instructions deal with moving data in and out of static memory and the\nstack. Typically, the value to move is stored in an \\emph{s} register and the\noffset in the target memory location is stored in an \\emph{m} register.\n\\begin{table}[h!]\n\t\\centering\n\t\\caption{Memory Instructions}\n\t\\begin{tabular}{|l|l|l|p{8cm}|}\n\t\t\\hline\n\t\tInstruction & Opcode & Arguments & Semantics \\\\\\hline\n\t\t push & 18 & s0 & Put the value stored in s0 at the top of the stack, then \n\t\tincrement the stack pointer \\\\\\hline\n\t\tpop & 19 & s0 & put the value on the top of the stack into s0, then decrement \n\t\tthe stack pointer\\\\\\hline\nlstat & 23 & s0, m0 & Fetch the byte stored in static memory from the offset stored in m0 and put it into\n\t\ts0 \\\\\\hline\n\t\tstget & 24 & s0, m0 & Fetch the value stored on the stack at the offset stored in\n\t\tm0 and put it into s0 \\\\\\hline\n\t\tstput & 25 & m0, s0 & Put the value stored in s0 onto the stack at the offset stored\n\t\tin m0\\\\\\hline\n\t\\end{tabular}\n\\end{table}\n\n\\clearpage\n\\subsection{Move Instructions}\nThese instructions handle moving data between registers and putting immediate\ndata into registers. They also handle things like immediate loading from within\nthe code. As usual, assume unsigned bytes.\n\\begin{table}[h!]\n\t\\centering\n\t\\caption{Move Instructions}\n\t\\begin{tabular}{|l|l|l|p{8cm}|}\n\t\t\\hline\n\t\tInstruction & Opcode & Arguments & Semantics \\\\\\hline\n\t\t movim & 30 & m0, im & This stores the value of the immediate into the math register\n\t\tindexed by m0 \\\\\\hline\n\t\tmovis & 29 & s0, im & This stores the value of the immediate into the swap register\n\t\tindexed by s0 \\\\\\hline\n\t\tmovrm & 21 & m0, s0 & This moves the value stored in the swap register s0 into the \n\t\tmath register indexed by m0 \\\\\\hline\n\t\tmovrs & 21 & s0, m0 & This moves the value stored in the math register m0 into the \n\t\tswap register indexed by s0 \\\\\\hline\n\t\\end{tabular}\n\\end{table}\n\n\\clearpage\n\\subsection{Utility Instructions}\nThese instructions handle `system' level instructions, reading and writing from the user.\n\\begin{table}[h!]\n\t\\centering\n\t\\caption{Move Instructions}\n\t\\begin{tabular}{|l|l|l|p{8cm}|}\n\t\t\\hline\n\t\tInstruction & Opcode & Arguments & Semantics \\\\\\hline\n\t\t read & 27 & m0, m1 & This command reads in bytes numbering the value stored\n\t\tin m1 onto the stack at the address (offset) given by the value stored in m0\\\\\\hline\n\t\t print & 26 & s0, s1 & This command prints out bytes numbering the value stored\n\t\tin s1 from the stack at the address (offset) given by the value stored in s0\\\\\\hline\n\t\\end{tabular}\n\\end{table}\n\n", "meta": {"hexsha": "822303939912806c4ba76930264ff77fdc5a4e55", "size": 10417, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/Ballad_Spec.tex", "max_stars_repo_name": "mitre-cyber-academy/2013-grabbag-500", "max_stars_repo_head_hexsha": "99a423032c09032cebdf5046e9194b5eda0108eb", "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/Ballad_Spec.tex", "max_issues_repo_name": "mitre-cyber-academy/2013-grabbag-500", "max_issues_repo_head_hexsha": "99a423032c09032cebdf5046e9194b5eda0108eb", "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/Ballad_Spec.tex", "max_forks_repo_name": "mitre-cyber-academy/2013-grabbag-500", "max_forks_repo_head_hexsha": "99a423032c09032cebdf5046e9194b5eda0108eb", "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.0817307692, "max_line_length": 105, "alphanum_fraction": 0.7355284631, "num_tokens": 2851, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583270090337583, "lm_q2_score": 0.3140505449918074, "lm_q1q2_score": 0.17534290147069756}}
{"text": "\\documentclass[%\n% preprint,\nsuperscriptaddress,\n%groupedaddress,\n%unsortedaddress,\n%runinaddress,\n%frontmatterverbose,\n%preprint,\n%showpacs,preprintnumbers,\n%nofootinbib,\n%nobibnotes,\n%bibnotes,\n%twocolumn,\namsmath,amssymb,\naps,\npre,\n%prb,\n%rmp,\n%prstab,\n%prstper,\nfloatfix,\n]{revtex4-2}\n\n\\usepackage{graphicx}% Include figure files\n\\usepackage{overpic}% Include figure files\n\\usepackage{dcolumn}% Align table columns on decimal point\n\\usepackage{bm}% bold math\n\\usepackage{hyperref}% add hypertext capabilities\n\\usepackage{color}\n\\usepackage{verbatim}\n\\graphicspath{{./fig/}}\n%\\usepackage{epstopdf}\n%\\usepackage{auto-pst-pdf}\n\n%todo Chris: Write about 1/1 mode\n%todo Chris: Write results/figure explanation section\n\n%todo Ralf: Write q_\\infty derivation\n%todo Ralf: Read and improve introduction. \n\n\n\\begin{document}\n\\title{An interactive toy model for the sawtooth oscillation in tokamak fusion reactors}\n\\author{R.J.J. Mackenbach}\n\\affiliation{Science and Technology of Nuclear Fusion, Department of Applied Physics, Eindhoven University of Technology, 5600 MB Eindhoven, The Netherlands}\n\\author{C. B. Smiet}\n\\affiliation{Princeton Plasma Physics Laboratory, Princeton University, Princeton, New Jersey, USA}\n\\affiliation{Huygens-Kamerlingh Onnes Laboratory, Leiden University, P.O.\\ Box 9504, 2300 RA Leiden, The Netherlands}\n\n\\begin{abstract}\n The sawtooth crash is an instability occurring in the core of a tokamak plasma that redistributes the temperature and pressure in the core region.\n In the Kadomtsev model the crash is caused by a 1/1 internal kink that reconnects the hot plasma within the core region.\n In this paper we present a minimal analytical model with two free parameters that reproduces the predicted changes in topology.\n This paints an intuitive picture of how the magnetic topology changes during a sawtooth crash.\n\\end{abstract}\n\\maketitle\n\n\n\\section{Introduction}\nGlobal energy consumption keeps increasing, and so do greenhouse gas emissions. This in turn, through many feedback mechanisms \\cite{Curry1995,Bloom2010}, raises the earth's average temperature and sea-levels. Since the energy-thirst of the human race is hard to quench, we must turn to renewable energy resources. Many options exist, but only few will be able to sustain the increasing need for energy in the long run. Nuclear fusion, in which small atomic nuclei combine to larger ones releasing vast amounts of energy, is one of those options. \nThere are many different concepts for a fusion energy power plant. The tokamak (a Russian acronym for ``\\textit{toroidal chamber with magnetic coils}\") is the leading candidate as of now (in terms of funding and technological readiness). This doughnut-shaped machine confines a plasma (an ionized gas) by making use of strong magnetic fields and large currents. \nThe field in the toroidal direction (long way around the torus) is generated by external coils, while the poloidal field (short way around the tours) that `twists' the field as it goes around is generated by currents in the plasma itself. \nThis twisting is quantified by the safety factor $q=n/m$ (where $n$ is the number of toroidal windings of a field line and $m$ the number of poloidal windings).\nThe plasma contains the fuel of our machine - the deuterium and tritium nuclei which will fuse into helium and produce energy. Using this configuration the tokamak tries to produce more energy than is needed to heat the machine to operating temperature (quantified in Lawson's criterion \\cite{Lawson1957}), a feat which ITER hopes to demonstrate.\n\n\nTokamaks however, are not free of problems. These machines are plagued by many different complications, such as large heat fluxes and neutron activation of materials. We will focus on one such complication, the sawtooth oscillation. During a sawtooth event, the hot and dense plasma in the core is redistributed through a region in the center of the plasma, causing a sudden drop in the core temperature and density. Slowly, the plasma in the core heats up again and becomes more dense, until the process repeats. If one plots the plasma temperature in the core over time, one would typically see a sawtooth-like pattern, hence the name of the phenomenon.\n\nThe sawtooth crash has been observed in tokamak fusion reactors since 1974 \\cite{von1974studies, vershkov1974role}.\nBecause of the temperature dependent Spitzer resistivity, the plasma current that creates the poloidal field in the reactor preferentially concentrates on the hottest plasma region near the magnetic axis.\nThis decreases the safety factor (increases the twisting) around the core.\nCurrent diffuses onto the core of the tokamak on a slow, resistive timescale, until a fast instability is triggered at a specific value of $q_0$ (the safety factor on the magnetic axis).\nThis instability leads to mixing of all the plasma in the core, and results in a flat temperature and pressure profile.\nIt also affects the poloidal and toroidal flux, resulting in a higher $q_0$.\nThe sawtooth cycle resets, and current slowly accumulates on the axis until the instability is triggered again.\n\nA numerical simulation of a sawtoothing discharge done with M3DC1~\\cite{jardin2012multiple} is shown in figure [REF]. [ADD ANIMATED GIF TO PAPER m3dsim.gif]. \nA simulation such as this reproduces the observed phenomena to a degree, but in order to keep the computing resources manageable, many simplifications to the plasma dynamics need to be made. \nThe most advanced calculations of the plasma dynamics cost millions of cpu-hours and are run on exascale devices. \nAnother approach is to develop analytical models that reduce the complexity of the problem as much as possible, to still reproduce the essential features of the phenomenon. \n\n\\begin{figure}\n \\centering\n \\includegraphics[width=0.7\\textwidth]{fullfig149.png}\n \\caption{Sawtoothing behavior reproduced in a low-resolution full numerical simulation of plasma dynamics.}\n \\label{fig:my_label}\n\\end{figure}\n\nOne of the most enduring models for the sawtooth was presented by Kadomtsev~\\cite{kadomtsev1975disruptive}.\nIn this model the region within the $q=1$ surface becomes susceptible to an internal kink mode, a resistive tearing instability of the $q=1$ surface, or both~\\cite{coppi1976resistive}.\nThe plasma in the core reconnects with cold plasma from outside the $q=1$ surface along a helical ribbon on the $q=1$ surface, and is deposited in a growing 1/1 island.\nThis growing island eventually completely displaces the hot core, and the temperature and current are redistributed.\nAfter the crash, the hot core is completely replaced by the $1/1$ island, which has $q_0=1$.\n\nIn this paper we present a simple analytical toy model that approximates the above process and which uses only two independent parameters to reproduce the predicted change in topology: a 1/1 internal kink that displaces the core, and a linear interpolation between the initial and final flux predicted by Kadomtsev.\nOther expressions for the time-dependent magnetic topology during the sawtooth crash have been presented by Kolesnichenko~\\cite{kolesnichenko1996theory} and Jaulmes~\\cite{jaulmes2014redistribution}.\nThese works calculate the intermediate states in the Kadomtsev reconnection process. \nOur model separates the reconnection phase into two separate and independent perturbations, resulting in a more analytically tractable and intuitive picture, at the cost of accuracy.\n\n\n\n\\section{Theory}\n\n\\section*{Initial magnetic field}\nThe magnetic field in a tokamak ideally consists of nested toroidal magnetic surfaces with a monotonically increasing $q$-profile.\nWe generate such an equilibrium field using a poloidal flux function $\\psi_p(R, Z)$ and a toroidal current function $I(\\psi_p)$.\nThe coordinates used are illustrated in figure~\\ref{fig:coords}.\nPhysically $\\psi_p$ represents the amount of flux through the circular disc with radius R centered on the $Z$ axis (indicated by the green circle in figure~\\ref{fig:coords}.\n$I$, which is sometimes called $F$ or $G$, represents the current through the same surface divided by 2$\\pi$.\n\n\n\\begin{figure}\\label{fig:coords}\n \\begin{overpic}[scale=.5]{fig/torus.png}\n \\put(80, 42){\\Large $\\theta$}\n \\put(48, 60){\\Large $Z$}\n \\put(90, 40){\\Large $R$}\n \\put(55, 45){\\Large $\\phi$}\n \\end{overpic}\n \\caption{Coordinates used for generating the magnetic field. }\n\\end{figure}\n\nThe magnetic fields are calculated from $\\psi_p$ and $I$ using:\n\\begin{equation}\\label{eq:unperturbed}\n B_R = -\\frac{1}{R} \\frac{\\partial \\psi_p}{\\partial Z}, \\quad B_z= \\frac{1}{R} \\frac{\\partial\n \\psi_p}{\\partial R}, \\quad\n B_\\phi = \\frac{1}{R} I.\n\\end{equation}\n\nFor the poloidal flux function we use\n\\begin{equation}\n \\psi_p = a^2,\n\\end{equation}\nwhere $a=\\sqrt{Z^2 + (R-R_0)^2}$ with $R_0$ the location of the equilibrium magnetic axis.\nThe surfaces of constant $\\psi_p$, which are magnetic surfaces, are thus circular-cross-section concentric tori around a magnetic axis located at $R=R_0$.\n\nFor our current function $I$ we choose the following relation:\n\\begin{equation}\n I(\\psi) = 2(q_0 + \\gamma \\psi_p)\\sqrt{R_0-\\psi_p}.\n\\end{equation}\n\n\nThe safety factor on each surface is calculated through~\\cite{wesson2011tokamaks}:\n\\begin{equation}\\label{eq:qprofint}\n q=\\frac{1}{2\\pi} \\oint \\frac{1}{R}\\frac{B_\\phi}{B_p}\\mathrm{d} l,\n\\end{equation}\nwhere $B_p=\\sqrt{B_R^2+B_Z^2}$ is the magnitude of the poloidal magnetic field.\nThe integration is carried out over a magnetic surface, which in the circular-cross-section concentric toroidal geometry can be done analytically.\nThe quantity $R B_p$ is constant in this geometry, so we get:\n\\begin{equation}\n q = \\frac{1}{2\\pi} \\frac{I(\\psi_p)}{RB_p}\\oint \\frac{1}{R} \\mathrm{d}l.\n\\end{equation}\nWe evaluate the integral by integrating over $\\theta$ and using the identities $R=R_0 +a \\cos(\\theta)$ and $\\mathrm{d}l = a \\mathrm{d}\\theta$ to yield:\n\\begin{equation}\n \\oint \\frac{1}{R} \\mathrm{d}l = \\int_0^{2\\pi} \\frac{a}{R_0 + a \\cos(\\theta)} \\mathrm{d}l =\n \\frac{2\\pi a}{\\sqrt{R_0^2 -a^2}}\n\\end{equation}\nIn the above integration we used the facts that $R_0>0$ and $R_0>a>0$.\nThis explains our choice of the function $I$, whose square root term cancels against the integrand, giving us the safety factor profile of:\n\\begin{equation}\n q=q_0 + \\gamma \\psi_p.\n\\end{equation}\n\nThe expressions in \\ref{eq:unperturbed} thus give us an axisymmetric magnetic field where field lines lie on nested concentric toroidal magnetic surfaces with monotonically increasing safety factor.\nFor this calculation we choose the parameters $\\gamma=1$ and $q_0=2/3$.\nThis field has no Shafranov shift (a shift of the magnetic axis outwards, induced by plasma pressure).\nIncluding a Shafranov shift would make the factor $RB_p$ non-constant on a magnetic surface, thus requiring numerical integration for the evaluation of the integral in~\\eqref{eq:qprofint}.\n\n\\section*{Internal Kink}\nWe calculate the change in magnetic field caused by an ideal displacement $\\boldsymbol{\\xi}$. \nHere $\\boldsymbol{\\xi}(R, \\phi, Z)$ is called the displacement vector that at every point specifies the direction and magnitude of the displacement. \nIn linearized ideal MHD, the first order change in magnetic field is given by the expression: \n\\begin{equation}\\label{eq:kinky}\n \\delta \\mathbf{B} = \\nabla \\times (\\boldsymbol{\\xi} \\times \\mathbf{B}_0)\n\\end{equation}\n(For those familiar with differential geometry, this expression can be interpreted as the first order effect of Lie dragging the magnetic field in the direction of the displacement vector; $\\mathcal{L}_{\\boldsymbol{\\xi}} \\mathbf{B} = \\left[\\boldsymbol{\\xi}, \\mathbf{B}\\right]$. This reduces to equation~\\eqref{eq:kinky} when $\\boldsymbol{\\xi}$ and $\\mathbf{B}$ are divergence free and $\\boldsymbol{\\xi}$ is infinitesimal.)\n\nThe displacement associated with the internal kink is a rigid top-hat displacement of the entire region within the $q=1$ surface. \nAt different angles around the torus, the direction varies, making one full rotation around the torus. \nSuch a displacement would result in singularities in the perturbed magnetic field when equation~\\eqref{eq:kinky} is evaluated. \nThese singularities correspond with current sheet formation, but will be troublesome for our numeric integration.\n\nThe rigid top-hat displacement of the internal kink has a limiting case that is the marginally stable quasi-interchange mode described by Waelbroeck~\\cite{waelbroeck1989nonlinear}. \nThis mode occurs when the safety factor is flat and close to 1 in the core region. \nTo avoid singularities in our field we opt to implement this smooth displacement function. \n\nThe displacement vector is calculated from a stream function $\\Psi$ given by the equation: \n\\begin{equation}\n \\Psi = e^{-\\frac{a^2}{\\Delta^2}}\\cos(n \\phi - m \\theta)\n\\end{equation}\nWhere $\\Delta$ is a characteristic width that limits the extent of the displaced region. \nThe displacement is calculated from $\\xi_R= -(1/R) (\\partial \\Psi/\\partial z)$ and $\\xi_Z= (1/R) (\\partial \\Psi/\\partial R)$. \nThe $\\phi$-component of the displacement vector is zero. \n\nAs can be seen from equation~\\eqref{eq:kinky}, the perturbed field depends on the equilibrium field $\\mathbf{B}_0$. \n\n\n\n\\section*{The Kadomtsev final state}\nWe would like to know the final state of the magnetic field after the sawtooth crash. We calculate the predictions of the Kadomtsev model~\\cite{kadomtsev1975disruptive} adapting the derivation presented by Biskamp~\\cite{Biskamp1997}. Employing the conservation of helical flux $\\psi_*$, which is the component of the vector potential in the direction of a helical coordinate, one can find an expression for the final magnetic field. Taking our helical coordinate to be $(1,1)$, the expression for the helical flux in the large aspect ratio limit becomes:\n\\begin{equation}\n \\psi_{*} = (1-q_0)a^2 - \\frac{\\gamma}{2}a^4.\n\\end{equation}\nThis $\\psi_*$ has the shape of a ``Mexican hat\" potential since $q_0<1$ and $\\gamma>0$. The Kadomstev model states that during the crash surfaces inside the $q=1$ surface reconnect with the surfaces outside of the $q=1$ surface. In terms of helical flux, this means that surfaces with equal $\\psi_*$ merge with one another. The surfaces of equal $\\psi_*$ can be found by solving the equation\n\\begin{equation}\n \\psi_{*} = C = \\text{constant.}\n\\end{equation}\nSolving this equation to $a^2$ will yield two solutions, $a_i^2$ and $a_e^2$, with the property that $a_i^2 < a_e^2$. The final coordinate where the merged surfaces will end up can be found by employing conservation of area between the two merging surfaces,\n\\begin{equation}\n a_{\\infty}^2 = a_e^2 - a_i^2\n\\end{equation}\nUsing this, we can find that the helical flux after reconnection becomes\n\\begin{equation}\n \\psi_{*,\\infty} = \\frac{1}{2}\\frac{(1-q_0)^2}{\\gamma} - \\frac{1}{8} \\gamma a^4.\n \\label{eq:final-helical-flux}\n\\end{equation}\nReconnection only occurs when there are two surfaces with equal flux. Otherwise the flux function is unchanged. The last radial coordinate where this reconnection occurs is the mixing radius $a_{\\text{mix}}$ , and can be calculated to be\n\\begin{equation}\n a_{\\text{mix}} = \\sqrt{ \\frac{2(1-q_0)}{\\gamma} }.\n\\end{equation}\nSince the toroidal field is mostly generated by the external coils, we expect that the toroidal magnetic field is unchanged. This means that the change in $\\psi_*$ comes purely from the poloidal flux function. This results in the final poloidal flux function\n\\begin{equation}\n \\psi_\\infty = \\begin{cases}\n \\frac{3}{8} \\gamma a^4 + q_0 a^2 + \\frac{1}{2} \\frac{( 1 - q_0 )}{\\gamma} , & a a_{\\rm mix}\n \\end{cases}\n\\end{equation}\nfrom which the magnetic field is calculated in the same way as equation~\\eqref{eq:unperturbed}.\nOne can now also calculate the corresponding safety factor. It is found to be\n\\begin{equation}\n q_\\infty(a) = \\begin{cases} \n \\frac{4 \\gamma a^2 + 4 q_0}{3 \\gamma a^2 + 4 q_0}, & aa_{\\rm mix}\n \\end{cases}\n\\end{equation}\nThis $q$-profile is larger than unity everywhere except at $a=0$, which is as expected. Furthermore, the $q$-profile is discontinuous at $a=a_{\\text{mix}}$.\n\n\n\\section{Results}\nWe construct a Poincar\\'e plot of the magnetic field. \nA Poincar\\'e plot gives a good sense of the magnetic topology. \nIt is calculated by taking a point in the $\\phi=0$ plane, numerically calculating the magnetic field line passing through that point, and noting the location where the that field line passes through the $\\phi=0$ plane every time it does so. \nIf a field line fills out a magnetic surface, and the the field line is followed for long enough, then the Poincar\\'e section will start to fill out the circle that corresponds with the intersection of that magnetic surface and the $\\phi=0$ plane. \n\n\nThis procedure is done for 100 different field lines, and each field line is given a different color.\nIntegration is carried out by a 5th order Runge-kutta method with adaptive step size that runs on a distributed computing network. \nWe also calculate the safety factor of each field line, buy counting the number of times it winds around the magnetic axis of the unperturbed field. \nThis information is shown below the Poincar\\'e plot. \nThe Poincar\\'e section for the unperturbed field (equation~\\eqref{eq:unperturbed}) is visible in figure [REF TO FIG]. \n\n\n\nWe can now calculate the total magnetic field, by making use of all our previously calculated functions. The magnetic field takes on the following form:\n\\begin{equation}\\label{eq:totalfield}\n \\mathbf{B}_{\\text{total}}(\\epsilon,\\alpha) = \\mathbf{B}_0 + \\alpha \\mathbf{B}_{1,1}+ \\epsilon (\\mathbf{B}_\\infty -\\mathbf{B}_0). \n\\end{equation}\nThe factor $\\alpha$ determines the strength of the internal kink perturbation, whereas $\\epsilon$ linearly interpolates between the initial state and the final state, as predicted by the Kadomtsev model. \n\nThe effects of these two perturbations on the field can be interactively explored in figure [REF]. \nIn figure [REF] different combinations of $\\alpha$ and $\\epsilon$ can be specifed along a path, and a Poincar\\'e plot of every set of ($\\alpha$, $\\epsilon$) along this path will be computed. \n\nWhen a path is chosen such that only $\\alpha$ varies, but $\\epsilon$ remains zero, we see the effect of the internal kink on the magnetic configuration. \nAs can be seen, this results in a shifting of the magnetic axis in the direction of the perturbation, and back again. \n\nWhen only $\\epsilon$ is varied, but $\\alpha$ is kept constant, the magnetic structure does not change at all. \nThe only change is seen in the plot of the safety factor, which just linearly interpolates between the initial value of $q_0=2/3$ [change!] and $q_0=0.9$ in the final Kadomtsev state. \n\nAn interesting thing happens when we first apply the internal kink $\\alpha$, and with this perturbation in place, start increasing $\\epsilon$. \nAs soon as $\\epsilon$ is non-zero, we see a drastic change in the magnetic structure. \nWe see a set of crescent-moon shaped curves in the Poincar\\'e plot. \nThese are caused by field lines lying on a new type of magnetic surface, that does not surround the magnetic axis anymore. \nSuch a structure is called a \\emph{magnetic island}. \nBecause this structure has appeared on the surface where previously $q=n/m=1/1$, this is called a $1/1$-island. \nOpposite to the center of the island, we see the point where the tips of the crescent moon touch. \nThe point where the tips touch exactly is called an X-point. \nThere is a field line at the center of the X-point that comes back to itself after one rotation. \n\nAs we continue to increase $\\epsilon$, the size of the island keeps increasing, even when we keep $\\alpha$ constant. \nIncreasing $\\epsilon$ tends to flatten the safety factor profile, bringing $q$ closer to 1 everywhere in the core region.\nAs $q$ gets closer to 1, it means that field lines rotate around exactly once poloidally per toroidal rotation. \nThe perturbation $\\mathbf{B}_{1,1}$ given by equation~\\eqref{eq:kinky} has exactly the same angular dependence. \nThat means that the effect of $\\mathbf{B}_{1,1}$ on the trajectory of a field line gets larger and larger, the closer $q$ gets to 1. \nIf $\\mathbf{B}_{1,1}$ adds a little push to the direction of a field line in one location, it will be adding the same push further along, and at every point, eventually completely changing the trajectory of the field line. \nThis effect, where the magnetic structure is strongly affected even by a very small perturbation, if the effect accumulates in this way, is called \\emph{magnetic resonance}. \n\nAs we change $\\epsilon$ towards 1, the safety factor becomes flatter, and closer to 1. \nThis means that the effect of the internal kink becomes stronger, pushing the original magnetic axis further out, and at the same time increasing the size of the island.\nWhen $\\epsilon$ gets really close to 1, the original axis gets closer and closer to the X-point, and fewer and field lines surround it, while more and more field lines are part of the island. \nBefore $\\epsilon$ reaches 1, the effect of the kink is already so strong, that the original axis is pushed into the X-point, and both disappear!\n\nThe island has grown so large that it has completely taken over, and the original axis has completely disappeared. \nIf we have not returned $\\alpha$ to zero, the magnetic field in the core will still be strongly distorted. \nBut the drive for such a perturbation has disappeared now that the safety factor is above 1 everyhwere, so the last step should be to return $\\alpha$ to 1, and see that the magnetic structure becomes axisymmetric again. \nThe final step is to return to the original profile with $q_0<1$, from which the cycle starts anew. \n\n- fast and slow\n- kink triggering\n- realistic path\n\n\\section*{Conclusions and Discussion}\nThe model we have presented above gives a very simple intuitive picture of a minimal set of perturbations that result in the topological changes associated with the Kadomtsev sawtooth process. \nWe take two effects; the ideal kink and a linear interpolation between two axisymmetric states, to reproduce the changes in magnetic topology that constitute the Kadomtsev satwooth. \n\n\nThe evolution of the magnetic structure exhibited by our model is probably simpler than what would be physically realized. \nA better approximation would be given by the models presented in~\\cite{kolesnichenko1996theory, jaulmes2014redistribution}, as these models give a physical picture for the intermediate states between initial and final state (they for example conserve flux during the process, which the process presented here does not necessarily do). \nNevertheless, the states in these models will also not correspond exactly to the actual magnetic state during the sawtooth crash, as there will be many other effects present such as current sheet formation, deformation of the shape of the original axis, etc.\n\n\\subsection*{Acknowledgements}\nWe would like to thank H. J. De Blank for enlightening discussions. We would like to thank the entire KingsDS team, D. Desjardins, KC Erb, and P. Navaeiopour, for implementing the model on the distributed computing network. \n\n\\bibliographystyle{naturemag}\n\\bibliography{refs}\n\n\\end{document}\n", "meta": {"hexsha": "df6975556fe7f8c0ae8ee982a710d77da43fb390", "size": 23346, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "sawtooth.tex", "max_stars_repo_name": "smiet/Analytical_Sawtooth", "max_stars_repo_head_hexsha": "e0d101077d3e4ed1b1bc997d90b5542a24205cf8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sawtooth.tex", "max_issues_repo_name": "smiet/Analytical_Sawtooth", "max_issues_repo_head_hexsha": "e0d101077d3e4ed1b1bc997d90b5542a24205cf8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sawtooth.tex", "max_forks_repo_name": "smiet/Analytical_Sawtooth", "max_forks_repo_head_hexsha": "e0d101077d3e4ed1b1bc997d90b5542a24205cf8", "max_forks_repo_licenses": ["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.8797468354, "max_line_length": 655, "alphanum_fraction": 0.7721665382, "num_tokens": 5982, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.34510527095787247, "lm_q1q2_score": 0.1752485510176972}}
{"text": "\\chapter{De-Entanglement by Priors - Case study with Acoustic Unit Discovery}\n\n\\section{Problem Introduction}\nA major bottleneck in the progress of many data-intensive language processing tasks such as speech recognition and synthesis is scalability to new languages and domains. \nBuilding such technologies for unwritten or under-resourced languages is often not feasible due to lack of annotated data or other expensive resources. \nA fundamental resource required to build such a stack is a phonetic lexicon - something that translates acoustic input to textual representation. Having such a lexicon, even if noisy, can help bootstrap speech recognition models, synthesis, and other technologies. Typical approaches may involve a pivot language or bootstrapping or adapting from a closely related high-resource language.\nBut, this can be a deceptively non-trivial task due to linguistic differences which can pose inherent difficulties. \nFor instance, it may be unreasonable to analyze a Sino-Tibetan language using English as a source. Moreover, using an additional language might make the model learn unintended surface level associations or biases between the participating languages that prevent them from generalizing across languages. Associations between these languages over a set of units that may better generalize to other languages. Therefore, in this paper we are interested in discovering the appropriate acoustic phonetic units. \n\n\\begin{figure}[t]\n\\centering\n\\includegraphics[width=80mm,scale=0.5]{images/vaconda_architecture_zerospeech2019.png}\n\\caption{Illustration of our procedure for automatically discovering acoustic units from a speech utterance. We pass the speech utterance through a downsampling encoder. The encoded representation is hashed to a latent code based on a discrete articulatory prior bank. The code is passed to the decoder, a WaveNet using speaker embeddings as global conditioning that regenerates audio. } \n\\label{frame_replacement_overview}\n\\end{figure} \n\n\nIn ZeroSpeech Challenge\\citep{zerospeech2019} resynthesis is considered a good proxy task to evaluate the performance of systems when training using unsupervised approaches. To accomplish this we use neural generative models. %Resynthesis might be a good proxy. \nDeep Neural Generative models have seen a tremendous amount of progress in the recent past. These models aim to model the joint probability of the data distribution and the conditioning information as a product of conditional distributions. Typical implementations of such models follow an autoregressive framework, although other formulations have been suggested as well. Such models have been shown very effective in addressing one of the major challenges with conventional vocoding techniques - fidelity. \nNeural generative models has been shown to generate speech that rivals natural speech when conditioned on predicted mel spectrum \\citep{shen2017natural}. Speech has a lot of natural variations in terms of content, speaker, channel information, speaking style, prosodic variations, etc. Accordingly, we are interested in models which have flexibility to marginalize such variations but preserve the phonetic content and distinguish meaningful differences between phonetic units.To accomplish this, we employ sequence to sequence models with latent random variables (referred to as latent stochastic models hereafter). These models provide a mechanism to jointly train both the latent representations as well as the downstream inference network. They are expected to both discover and disentangle causal factors of variation present in the distribution of original data, so as to generalize at inference time. While training latent stochastic models, optimizing the exact log likelihood can be intractable. To address this, a recognition network is employed to approximate the posterior probability using reparameterization \\citep{vae}. When deployed in encoder-decoder models, this approach is often subject to an optimization challenge referred to as KL-collapse \\citep{bowman_continuous}, wherein the generator (usually an RNN) marginalizes the learnt latent representation. Typical approaches to dealing this issue involve annealing the KL divergence loss~\\citep{bowman_continuous,zhou2017multi}, weakening the generator \\citep{zhao2017learning} and ensuring the recall using bag of words loss. In our work, we present an approach to deal with the KL-collapse problem by vector quantization in the latent space. Building on \\citep{vq-vae, chorowski2019unsupervised}, we add additional constraints in the prior space forcing the latent representations to follow articulatory dimensions: The encoded representation is hashed to a latent code based on a articulatory prior bank designed using a discrete codebook. Our decoder is a conditional WaveNet using speaker embedding as global embedding trained to regenerate input audio using the code sequence as local information. \n\n\n\\section{Background - Acoustic Unit Discovery}\n\nLet us consider a speech corpus X which consists of speakers $\\{ s_1, s_2...,s_n \\}$. The goal of acoustic unit discovery is to come up with a set of units \\textbf{U} that represent a speech utterance \\textit{x} $\\subset$ X allowing robust resynthesis. %comprehensively. \nThe elements of such a set also might conform to desirable characteristics such as being injective, consistent and compact, i.e. that different inputs should have discriminant acoustic units, but expected variance such as speaker or dialect should produce the same acoustic units. %, and the set of units should be \n% We aim to discover a minimal set of units to fit these goals.\n%must be well corresponding to the acoustic vectors(predictable)\n\n\nThere have been numerous attempts to discover such acoustic units in an unsupervised fashion. In \\citep{subword_diarization}, authors presented an approach to modify the speaker diarization system to detect speaker-dependent acoustic units. \\citep{unsupervised_AMtraining_ArenJansen} proposed a GMM-based approach to discover speaker-independent subword units. However, their system requires a separate Spoken Term Detector. Recently, due to the surge of deep generative model, using unsupervised method such as auto-encoder and variational auto-encoder (VAE). \\citep{badino_autoencoder} designed a stacked AutoEncoder using backpropagation and then cluster the representations at the bottleneck layer. To avoid quick transitions leading to repeated units, they employed a smoothing function based on transition probabilities of the individual states. \\citep{hmm-vae_bhiksha} extended the structured VAE to incorporate the Hidden Markov Models as latent model. \\citep{vq-vae, chorowski2019unsupervised} proposed VQ-VAE and argue that by vector quantization the ``“posterior collapse\" problem could be circumvented.\n\n\n\\section{\\textit{VACONDA}}\n\\label{proposed_approach}\n\n\n\\subsection{Analysis of optimization and de-entanglement}\n\\label{analysis}\n\nWaveNet \\citep{van2016WaveNet} is an autoregressive neural model with a stack of 1D convolutional layers that is capable of directly generating audio signal. It has been shown to produce generated speech that rivals natural speech when conditioned on predicted mel spectrum \\citep{shen2017natural}. The input to WaveNet is subjected to corresponding gated activations while passing through each dilated convolutional layer and is classified by the final softmax layer into a $\\mu$ law encoding. The concrete form of the residual gated activation function is given by following equation:\n\n\n\\begin{equation} \\label{WaveNet_Eqn}\n\\begin{split}\n r_d(x) = tanh(W_{f} * x) \\odot \\sigma (W_{g} * x) \\\\ \n\\end{split}\n\\end{equation}\n\n\\noindent where $x$ and $r_d(x)$ are the input and output with dilation $d$, respectively. The symbol $*$ is a convolution operator with dilation $d$ and the symbol $\\odot$ is an element-wise product operator. $W$ represents a convolution weight. The subscripts $f$ and $g$ represent a filter and a gate, respectively. The joint probability of a waveform \\textbf{X} can be written as:\n\n\n\\begin{equation} \\label{WaveNet_gen_Eqn}\n\\begin{split}\n P(X | \\theta) = \\prod_{t=1}^{T} P(x_t | x_1, x_2 .. x_{t-1}, \\theta) \\\\\n\\end{split}\n\\end{equation} \n\n\\noindent given model parameters $\\theta$. During implementation of WaveNet, the autoregressive process is realized by a stack of dilated convolutions. The final output $y_t$ at time step $t$ can be expressed mathematically as:\n\n\\begin{equation} \n\\begin{split}\n \\hat{y_t} \\sim \\sum_{d=0}^{D} h_d * r_d(x) \\\\\n\\end{split}\n\\label{WaveNet_Eqn}\n\\end{equation} \n\n\\noindent where $x$, $y$ represent input and output vectors; $D$ is the number of different dilation used and $d$ is the dilation factor; $h_d$ is the convolution weights. This stack of convolutions is repeated multiple times in the original WaveNet. Optimization in WaveNet is performed based on the error between predicted sample and the ground truth sample conditioned on previous samples in the receptive field alongside the local conditioning. Expressing the loss function being optimized mathematically the error at sample $t$ is:\n\n\n\\begin{equation} \\label{discrete_Eqn}\n\\begin{split}\n l_t = Div(\\hat{y_t} || y_t)\n\\end{split}\n\\end{equation} \n\nHere, we define the divergence similar to the \\citep{salimans2017pixelcnn++}, To optimize this loss, the contribution from the individual convolution layers towards this global error function must be nullified. Now let us consider the expression for intermediate output for a single filter in Eqn~\\ref{WaveNet_Eqn}:\n\n\\begin{equation}\n\\begin{split}\n x_{out}(t) = \\sum_{\\tau=0}^{t} h(\\tau)x(t-\\tau)\n\\end{split}\n\\end{equation} \n\n\\noindent where $\\tau$ is the receptive field covered by the model and $h(\\tau)$ represents the discrete state representation at time $t$. Without loss of generality and dropping the term $\\tau$ for brevity, the spectral representation generated by the model can be expressed as:\n\n\\begin{equation} \\label{transfer_function_representation}\n Y(z) = H(z) X(z) \n\\end{equation} \n\n\nConsidering the discrete nature of input from Eqn \\ref{discrete_Eqn}, an interpretation of Eqn \\ref{transfer_function_representation} is that the neural autoregressive model acts as the transfer function and is discretized by convolving with the samples from original signal. It has to be noted that this is similar to the formulation of source filter model of speech, specifically the periodic components aka voiced sounds. Voiced sounds typically represented as impulse train are convolved with the transfer function to generate spectral envelope. As a corollary, from Eqn \\ref{discrete_Eqn} and \\ref{transfer_function_representation}, we posit that the optimization in WaveNet model is performed by minimizing the divergence between true and approximate spectral envelope. Note that latent stochastic models such as VAEs are aimed to minimize the divergence between true and approximate posterior distributions of input data. The advantage with such models is the presence of stochastic random variables that capture the causal factors of variation in input based on some prior information about the distributional characteristics of data. Techniques aimed at this \\citep{beta_vae} have shown that it is possible to effectively disentangle the factors of variation using stochastic variables. Hence, we postulate that it should be possible to augment WaveNet decoder with a suitable encoder and an appropriate prior distribution to disentangle the acoustic phonetic units from a given utterance. \n\n\nHowever, this is a deceptively non-trivial task. If the prior is too simplistic, such as unit normal distribution, the model is trivially incentivized to force the posterior distribution to closely follow the Gaussian prior distribution \\citep{lossy_vae}, particularly early in training. This results in the decoder marginalizing out the latent variable completely, manifesting in poor reconstruction ability. On the other hand, making the prior distribution arbitrarily complex also leads to unreasonable constraints on the decoder. For instance, in scenarios that have categorical distributions as their output (tasks such as language modeling, machine translation, and 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. We make an observation that dealing with speech presents a characteristic advantage - speech has both continuous as well as discrete priors. The generative process of speech assumes a Gaussian prior distribution which is continuous in nature. However, the language which is also present in the utterance can be approximated to be sampled from a discrete prior distribution. Exact manifestation of this in the linguistics can be at different levels: phonemes, words, syllables, subword units, etc. From the analysis presented in the previous section, we hypothesize that if we use background knowledge about the data distribution while designing the priors, we can help the encoder effectively disentangle the latent causal factors of variation in the data. In other words, this presents us with an opportunity to control what gets disentangled in the latent space by appropriately choosing a prior distribution. Therefore, we engineer our prior space to account for the phonetic information in the utterance by representing the prior as a discrete latent variable bank, similar to the filterbanks used for feature extraction from speech. Each discrete latent variable has a different set of states reflecting one of the articulatory dimensions. The specific design of our latent space is highlighted in Table \\ref{articulatory features}.\n\n\n\\renewcommand{\\arraystretch}{1.0}\n\\begin{table}[t]\n\\caption{Articulatory Features\\label{tab:arti}}\n\\centering\n\\begin{tabular}{l | c | c}\\toprule[\\heavyrulewidth] \\textbf{Feature name} & \\textbf{Value} & \\textbf{Details} \\\\\n\\toprule[\\heavyrulewidth]\nvc & + - 0 & vowel or consonant \\\\\nvlng & s l d a 0 & vowel length\\\\\nvheight & 1 2 3 0 - & vowel height \\\\\nvfront & 1 2 3 0 - & vowel frontness\\\\\nvrnd & + - 0 & lip rounding\\\\\nctype & s f a n l r 0 & consonant type \\\\\ncplace & l a p b d v g 0 & place of articulation \\\\\ncvox & + - 0 & consonant voicing\\\\\nasp & + - 0 & consonant voicing\\\\\nnuk & + - 0 & consonant voicing\\\\\n\\bottomrule[\\heavyrulewidth]\n\\end{tabular}\n\\label{articulatory features}\n\\end{table}\n\n\n\n\\section{Experiments}\n\\label{expts}\n\n\n\\subsection{ZeroSpeech 2019 dataset}\n% The goal of ZeroSpeech dataset is to learn the Phonetic representation of the audio without any supervision, discover the symbolic representation of the audio, and resynthesize the audio using these unit. The evaluation metric look at both the quality of sub-unit and the resynthesized audio.\n\nZeroSpeech Challenge 2019: TTS without T is to propose to build a speech synthesizer without any text or phonetic labels~\\citep{sakti2008development1, sakti2008development2, zerospeech2019}. The systems are required to extract the symbolic representation of the raw audio, and then re-synthesize the audio using these discovered units. There are three datasets in total: (1) \\textit{Unit Discovery Dataset} provides audio from a variety of speakers and is used to unsupervised acoustic modeling, (2) \\textit{Voice Dataset} provides audio from the targeted speaker and is used for synthesizer modeling and (3) \\textit{Parallel Dataset} is intended for finetuning both the sub-systems. We have not utilized the parallel dataset for our observations in this study. The development language is English and the test language is Standard Indonesian. The system is constrained to not use any pre-existing resource or models. To ensure that the model generalizes out of the box, the hyperparameter will be fine-tuned only on the development dataset, and the model will be trained in test language under the same parameters. \n\n\\iffalse\n\\begin{enumerate}\n \\item \\textit{Unit Discovery Dataset} provides audio from a variety of speakers and is used to unsupervised acoustic modeling\n \\item \\textit{Voice Dataset} provides audio from the targeted speaker and is used for synthesizer modeling\n \\item \\textbit{Parallel Dataset} is used for finetuning the both sub-systems\n\\end{enumerate}\n\nThe development language is English and the test language is Standard Indonesian. The system is refrained from using any pre-existing resource or models. To ensure that the model generalizes out of the box, the hyper-parameter will be fine-tuned only on the development dataset, and the model will be trained in test language under the same parameters. \n\\fi\n\n% \\subsubsection{CSTR VCTK Corpus}\n\n% CSTR VCTK is an English speech dataset, which contains 109 native speakers with various accents. Each speaker is required to record 400 sentences from newspaper, plus Rainbow Passage and an elicitation paragraph intended to identify the speaker's accent.\n\n%\\subsection{Implementation Details}\n\n% CSTR VCTK Corpus includes speech data uttered by 109 native speakers of English with various accents. Each speaker reads out about 400 sentences, most of which were selected from a newspaper plus the Rainbow Passage and an elicitation paragraph intended to identify the speaker's accent\n% \n% newspaper sentences,\n\n\\iffalse\nOur voice building process employs the phone sharing approach as outlined in \\citep{rallabandi_mixedlingual_IS2017} - where the combined phoneset is formed by the union of phones from both the languages - to build acoustic models. In this section, we present our approaches to generate the required bilingual acoustic data using just monolingual recordings. Specifically, in each of the subsections, we introduce the approaches we follow to artificially generate spectral content in English. We then follow the outlined procedure to build a bilingual voice using the native (L1) recordings and `pseudo English' (L2) recordings. \n\nIn this section, present our approaches for ZeroSpeech 2019. Specifically, our aim is to build robust models capable of accomplishing (1) Discovering acoustic units given a speech utterance. and (2) Generating novel utterances conditioned on the discovered acoustic units. For this, we have built two systems: (1) System A which is a pipeline based approach and (2) System B which is an end-to-end approach. \n\\fi \n\n\\section{Baseline System}\n\nWe have a three-stage pipeline: (1) \\textit{Unit Discovery}: We hypothesize acoustic units given a speech utterance using latent Stochastic Models; (2) \\textit{Unit Alignment}: We fine-tune the alignment between the utterance and the proposed acoustic units ; (3) \\textit{Unit Synthesis}: We build a speech synthesizer using the acoustic units and the target voice.\n\n\n%In this section, we will elaborate on each of the three stages.\n\n%\\subsubsection{Acoustic Unit Discovery}\n%\\subsubsection{Acoustic Unit Alignment}\n\nAs proposed in \\citep{sitaram2013bootstrapping}, we take the initially discovered transcription of the acoustic units for our speech corpus and train an ASR model on it. Then we re-encode the corpus using the ASR model, and train a TTS system on it. Here we using Bi-LSTM with CTC loss as our ASR model, and tacotron \\citep{tacotron_transferlearning2multispeaker} as TTS system. \n\n% At each iteration, an acoustic model is trained from the parallel speech-transcription data. This acoustic model is then used to re-decode the speech data, and so on for 10 iterations. At the end of each iteration, we have produced a rebuilt acoustic model and a re-decoded transcript. These two are used to build a synthetic CLUSTERGEN \\citep{black2006clustergen} voice (given the noise in the generated data, statistical parametric synthesis is appropriate) using Festvox for the purpose of evaluation on a held out test set on the basis of MCD scores. The best-aligned transcription is taken as the one producing the synthetic voice with the lowest distortion score.\n\n%\\subsubsection{Acoustic Unit Synthesis}\n\n\n\n\n\n\\begin{figure}[t]\n \\centering \n \\subfigure[Original speech]{ \n \\includegraphics[width=0.95\\linewidth]{images/target4.png}}\n\\subfigure[Generated speech]{\n \\includegraphics[width=0.95\\linewidth]{images/generated4.png}}\n\\subfigure[Converted speech]{\n \\includegraphics[width=0.95\\linewidth]{images/transferred4.png}}\n \\caption{Spectrograms of original, generated, and converted speech. The source speaker is female while the target speaker is male.\\label{fig:waveform}}\n\\end{figure}\n\n\n\\subsection{VACONDA}\n\nThe architecture of our model is built on top of VQ-VAE. It consists of three modules: an encoder, quantizer and a decoder. As our encoder, we use a dilated convolution stack of layers which downsamples the input audio by 64. The speech signal was power normalized and squashed to the range (-1,1) before feeding to the downsampling encoder. To make the training faster, we have used chunks of 2000 time steps. This means we get 31 timesteps at the output of the encoder. The quantizer acts as a bottleneck and performs vector quantization to generate the appropriate code from a parameterized codebook. We define the latent space $e \\in \\mathbmm{R}^{k\\times d}$ to contain $k$ $d$-dim continuous vector. Quantization is implemented using minimum distance in the embedding space. The number of classes was chosen to be 64, approximating 64 universal phonemes. We use a linear mapping to first project the 128 dimensional vector to 160 dimensions. We then perform comparisons with respect to individual articulatory dimensions each of which is 16 in size. Assuming $z_e(x)$ denotes the encoder output in the latent space, then the input of decoder $z_d(x)$ will be obtained by $\\argmin_{j}d(e_j, z_e(x))$, where $d$ is a similarity function of two vectors. In this paper, we consider Euclidean distance as the similarity metric. Our decoder is an iterated dilated convolution-based WaveNet that uses a 256-level quantized raw signal as the input and the output from vector quantization module as the conditioning. Although using a Mixture of Logistics loss function might yield a better output, we have only used a 256 class softmax in this study. The decoder takes the output from the quantizer along with the speaker label as global conditioning and aims to reconstruct the input in an autoregressive fashion. Following IDCNNs, we have shared the parameters of all the stacks.\n\n\n\n% In this subsection we describe our end-to-end approach for the task. We extend the framework proposed in \\citep{vq-vae} to accomplish subword unit discovery. Although a structure such as HMM \\citep{hmm-vae_bhiksha} might be intuitively better at capturing the transitions, we have limited ourselves to a vector quantization based approach as we observed it to be better at handling the posterior collapse problem in VAEs. We have used 3 stacks of 10 layers each in the decoder and residual blocks with similar dilation factors in each of the stacks shared their parameters \\citep{strubell2017fast}.\n\n% Our voice building process employs the VQ-VAE approach as outlined in \\citep{rallabandi_mixedlingual_IS2017}, where the raw audio is first fed to a downsampling encoder which reduces the time resolution by 64. This encoded representation is then hashed into a latent representation that is forced to follow articulatory constraints. Specifically, we employ a set of discrete embeddings of cardinality 5, where each is a multi-dimensional array in itself associated with a continuous vector. The output from this hash function is fed to the decoder, which is a conditional WaveNet implemented using iterated dilated convolutions. In this section, we first present our analysis of the optimization that happens in our models. We then present a case for controlling the disentanglement that happens in such models to accomplish voice conversion. This is followed by an explanation of each component in our model in detail.\n\n% Aside from the architecture discussed in Section~\\ref{proposed_approach}, we argue that adding meaningful inductive bias can help the model learn better. We first normalize the vector representation to ensure the same scale in the latent space. Compared to VQ-VAE, we incorporate the articulatory features information in Table~\\ref{tab:arti}. The above articulatory features apply to all human languages. To incorporate them, we first transpose the embedding from 128-dimension to 160-dimension by a linear layer. Then, we equally divide the latent embedding into 10 parts, and perform the vector quantization separately. Finally we concatenate all vectors, and feed into the linear layer to map it back to 128-dimension. In each class, the number of latent embedding is the number of possible values.\n\n\n\\subsection{Analysis}\n\nIn this section, we will discuss different design choices in the architecture, including input features and latent space constraints. \n\n% \\subsubsection{Input Feature}\n\n% We first compare the performance gap between different features as our model's input. The feature used along with its performance is shown in Table~\\ref{tab:input}.\n\n\\subsubsection{Acoustic Unit Discovery}\n\nHere we analyze the AUD performance of three different models in ZeroSpeech dataset as shown in Table~\\ref{tab:aud}. We only show the results in English since we don't have ground truth for the Indonesian language.\n\n% Now all is baseline \n\n\\renewcommand{\\arraystretch}{1.1}\n\\begin{table}[!htbp]\n\\caption{Performance of different systems in ZeroSpeech}\n\\centering\n\\begin{tabular}{l c c}\\toprule[\\heavyrulewidth]\n& \\multicolumn{2}{c}{English}\\\\\nModel & ABX score & bitrate \\\\\n\\toprule[\\heavyrulewidth]\nBaseline & \\textbf{27.46} & 74.5\\\\\nThree-stage Model & 34.86 & 68.54 \\\\\nVACONDA & 38 & \\textbf{58.19} \\\\\n\n\\bottomrule[\\heavyrulewidth]\n\\end{tabular}\n\\label{tab:aud}\n\\end{table}\n\nAs in Table~\\ref{tab:aud}, the VACONDA achieves the best bit rate among three models. With such small number of unit, we could resynthesize and even convert the speech in a very high quality.\n\n\\subsubsection{Speech Resynthesis and Conversion}\n\nThe proposed model supports synthesizing the same speech in both the same speaker and a different speaker. Here we show a sample in the test dataset of Indonesian language in Figure~\\ref{fig:waveform}. When we feed the decoder with the same speaker identification, the decoder will generate the original audio. Otherwise, it will perform speech convertion. The three audio shares similar structure. However, the converted audio has denser waveform, suggesting it's a different speaker. For the sampled audio, please visit the \\href{http://tts.speech.cs.cmu.edu/rsk/campaigns/interspeech2019/submissions/acoustic_unit_discovery/}{our website}.\n\n\n\n%The results are shown in Table~\\ref{tab:constraints}. We use \n\n% \\renewcommand{\\arraystretch}{1.1}\n% \\begin{table}[htbp]\n% \\caption{System performance with latent space constraints}\n% \\centering\n% \\begin{tabular}{l | c}\\toprule[\\heavyrulewidth] \\textbf{Model} & \\textbf{ABX score}\\\\\n% \\toprule[\\heavyrulewidth]\n% Baseline model & 12\\\\\n% \\bottomrule[\\heavyrulewidth]\n% \\end{tabular}\n% \\label{tab:constraints}\n% \\end{table}\n\n\\label{analysis}\n\n\n\\subsection{Conclusion}\n\nIn this case study, we present an approach to automatically discover acoustic-phonetic units from a speech utterance in an unsupervised fashion. We first present an analysis to show that incorporating latent random variables into neural generative models using suitable priors allows us to control what gets encoded into the latent space. Based on this, we employ articulatory features as a discrete prior bank in the latent space and obtain acoustic units that are speaker and language independent. To validate effectiveness of the discovered units, we perform discriminability tests as part of ZeroSpeech Challenge 2019. \n", "meta": {"hexsha": "0bb7cf0598173a6a28f185399062413dfcc53605", "size": 27824, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "quarterly_stuff/2020Q2/chapters/deentanglement_by_priors.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_by_priors.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_by_priors.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": 107.0153846154, "max_line_length": 2195, "alphanum_fraction": 0.8037305923, "num_tokens": 6169, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5234203638047913, "lm_q2_score": 0.33458945452352534, "lm_q1q2_score": 0.17513093401195032}}
{"text": "\\section{Extending Extended \\UTXO}\n\\label{sec:EUTXOma}\n\nBefore discussing applications and the formal model of \\EUTXOma, we briefly summarise the structure of \\EUTXO, and then informally introduce the multi-asset extension that is the subject of this paper.\nFinally, we will discuss a shortcoming in the state machine mapping of \\EUTXO\\ as introduced in~\\cite{eutxo-1-paper} and illustrate how the multi-asset extension fixes that shortcoming.\n\n\\subsection{The starting point: Extended \\UTXO}\n\\label{sec:informal-eutxo}\n\nIn Bitcoin's \\UTXO\\ ledger model, the ledger is formed by a list of transactions grouped into blocks.\nAs the block structure is secondary to the discussion in this paper, we will disregard it in the following.\nA transaction $\\tx$ is a quadruple \\((I, O, r, S)\\) comprising a set of \\emph{inputs} $I$, a list of \\emph{outputs} $O$, a \\emph{validity interval} $r$, and a set of signatures $S$, where inputs and outputs represent cryptocurrency value flowing into and out of the transaction, respectively.\nThe sum of the inputs must be equal to the sum of the outputs; in other words, transactions preserve value.\n% True, but not crucial IMHO and we need to save space. -= chak\n%\\footnote{\n% Real transactions will likely have other fields that need to be balanced, such as fees or new tokens that are minted or forged.\n% We will omit these for now for simplicity, but in general they also need to observe preservation of value.\n%}\nTransactions are identified by a collision-resistant cryptographic hash $h$ computed from the transaction.\\footnote{%\n We denote the hash of some data $d$ as $d^\\#$.%\n}\n\nAn input $i\\in I$ is represented as a pair \\((\\outRef, \\rho)\\) of an \\emph{output reference} $\\outRef$ and a \\emph{redeemer value} $\\rho$.\nThe output reference $\\outRef$ uniquely identifies an output in a preceding transaction by way of the transaction's hash and the output's position in the transaction's list of outputs.\n\nIn plain \\UTXO, an output $o\\in O$ is a pair of a \\emph{validator script} $\\nu$ and cryptocurrency value $\\val$.\nIn the Extended \\UTXO\\ model (\\EUTXO)~\\cite{eutxo-1-paper}, outputs become triples \\((\\nu, \\val, \\delta)\\), where the added \\emph{datum} $\\delta$ enables passing additional information to the validator.\n\nThe purpose of the validator is to assess whether an input $i$ of a subsequent transaction trying to spend (i.e., consume) an output $o$ should be allowed to do so.\nTo this end, we execute the validator script to check whether \\(\\nu(\\rho, \\delta, \\sigma) = \\true\\) holds.\nHere $\\sigma$ comprises additional information about the \\emph{validation context} of the transaction.\nIn the plain \\UTXO\\ model that contextual information is fairly limited: it mainly consists of the validated transaction's hash, the signatures $S$, and information about the length of the blockchain. In the \\EUTXO\\ model, we extend $\\sigma$ to include the entirety of the validated transaction $\\tx$ as well as all the outputs spent by the inputs of $\\tx$.\n\n\\subsection{Token bundles}\n\\label{sec:informal-token-bundles}\n\nIn \\UTXO\\ and \\EUTXO, the $\\val$ carried by an output is represented as an integral value denoting a specific quantity of the ledger's native cryptocurrency.\nAs discussed in more detail in the companion paper~\\cite{plain-multicurrency}, we can generalise $\\val$ to carry a two-level structure of \\emph{finitely-supported functions.}\nThe technicalities are in Appendix~\\ref{app:model}; for now, we can regard them as nested finite maps to quantities of tokens.\nFor example, the value\n\\(\\{\\mathsf{Coin} \\mapsto \\{\\mathsf{Coin} \\mapsto 3\\}, g \\mapsto \\{t_1\n\\mapsto 1, t_2 \\mapsto 1\\}\\}\\) contains $3$ $\\mathsf{Coin}$ coins\n(there is only one (fungible) token $\\mathsf{Coin}$ for a payment\ncurrency also called $\\mathsf{Coin}$), as well as (non-fungible) tokens $t_1$ and $t_2$,\nboth in asset group $g$. Values can be added naturally, e.g.,\n\\begin{align*}\n & \\{\\mathsf{Coin} \\mapsto \\{\\mathsf{Coin} \\mapsto 3\\}, g \\mapsto \\{t_1\n \\mapsto 1, t_2 \\mapsto 1\\}\\} \\\\\n + \\ & \\{\\mathsf{Coin} \\mapsto \\{\\mathsf{Coin} \\mapsto 1\\}, g \\mapsto \\{t_3 \\mapsto 1\\}\\} \\\\\n = \\ & \\{\\mathsf{Coin} \\mapsto \\{\\mathsf{Coin} \\mapsto 4\\}, g \\mapsto \\{t_1\n \\mapsto 1, t_2 \\mapsto 1, t_3 \\mapsto 1\\}\\} \\ .\n\\end{align*}\n%\nIn a bundle, such as \\(g \\mapsto \\{t_1 \\mapsto 1, t_2 \\mapsto 1, t_3 \\mapsto 1\\}\\), we call $g$ an \\emph{asset group} comprising a set of tokens $t_1$, $t_2$, and $t_3$. In the case of a fungible asset group, such as $\\mathsf{Coin}$, we may call it a \\emph{currency}.\nIn contrast to fungible tokens, only a single instance of a non-fungible token may be minted.\n\n\\subsection{Forging custom tokens}\n\nTo enable the introduction of new quantities of new tokens on the ledger (\\emph{minting}) or the removal of existing tokens (\\emph{burning}), we add a \\emph{forge field} to each transaction.\nThe use of the forge field needs to be tightly controlled, so that the minting and burning of tokens is guaranteed to proceed according to the token's \\emph{forging policy}.\nWe implement forging policies by means of scripts that are much like the validator scripts used to lock outputs in \\EUTXO.\n\nOverall, a transaction in \\EUTXOma\\ is thus a sextuple \\((I, O, r, \\forge, \\fpss, S)\\), where $\\forge$, just like $\\val$ in an output, is a token bundle and $\\fpss$ is a set of \\emph{forging policy scripts}.\nUnlike the value attached to transaction outputs, $\\forge$ is allowed to contain negative quantities of tokens. Positive quantities represent minted tokens and negative quantities represent burned tokens.\nIn either case, any asset group $\\phi$ that occurs in $\\forge$ (i.e., \\(\\forge = \\{\\ldots, \\phi \\mapsto \\mathit{toks}, \\ldots\\}\\)) must also have its forging policy script in the transaction's $\\fpss$ field.\nEach script $\\pi$ in $\\fpss$ is executed to check whether $\\pi(\\sigma) = \\true$, that is whether the transaction, including its $\\forge$ field, is admissible.\n\\ifootnote{%\n In fact we have a slightly different $\\sigma$ here, which we elaborate on in Appendix~\\ref{app:model}.%\n}\n\n\\subsection{Constraint emitting machines}\n\\label{sec:cem-example}\nIn the \\EUTXO\\ paper~\\cite{eutxo-1-paper}, we explained how we can map \\emph{Constraint Emitting Machines} (CEMs) ---a variation on Mealy machines--- onto an \\EUTXO\\ ledger. A CEM consists of its type of states \\s{S} and inputs\n\\s{I}, predicates $\\s{initial}, \\s{final} : \\s{S} \\rightarrow \\B$\nindicating which states are initial and final, respectively, and a valid set of transitions,\ngiven as a partial function $\\s{step} : \\s{S} \\rightarrow \\s{I} \\rightarrow\n\\s{Maybe}\\ (\\s{S} \\times \\s{TxConstraints})$ from source state and input symbol to\ntarget state and constraints.\n\\ifootnote{%\n The result may be \\s{Nothing}, in case no valid transitions exist from a given state/input.%\n}\n%\nOne could present CEMs using the traditional five-tuple notation $(Q, \\Sigma, \\delta, q_0, F)$,\nbut we opt for functional notation to avoid confusion with standard \\textit{finite state machines}\n(see \\cite{eutxo-1-paper} on how CEMs differ from FSMs),\nas well as being consistent with our other definitions.\n\nA sequence of CEM state transitions, each of the form $\\CStepArrow{s}{i}{\\txeq}$, is mapped to a sequence of transactions, where each machine state $s$ is represented by one transaction $\\tx_s$. Each such transaction contains a \\emph{state machine output} $o_s$ whose validator $\\nu_s$ implements the CEM transition relation and whose datum $\\delta_s$ encodes the CEM state $s$.\n\nThe transition $\\tx_{s'}$, representing the successor state, spends $o_s$ with an input that provides the CEM input $i$ as its redeemer $\\rho_i$. Finally, the constraints $\\txeq$ generated by the state transition need to be met by the successor transition $\\tx_{s'}$. (We will define the correspondence precisely in \\S\\ref{sec:formalization}.)\n\n\\begin{figure}[t]\n \\centering\n \\begin{tikzpicture}[\n state/.style =\n { shape = circle,\n fill = gray!40,\n align = center,\n font = \\large,\n minimum size = 2.5cm },\n transition/.style =\n { ->,\n thick },\n move/.style =\n { align = center,\n anchor = center,\n font = \\small }\n ]\n \\node[state] (a) {\\Holding};\n \\node[state, right = 3cm of a] (b) {\\msf{Collecting}\\\\\\normalsize ($v$, $p$, $d$, $sigs$)};\n\n \\path\n (a.north east) edge[transition, bend left = 15]\n node[move, above] {$\\Propose{v}{p}{d}$\\\\$sigs' = \\{\\}$}\n (b.north west)\n (b) edge[transition, out = 30, in = -30, looseness = 3]\n node[move, right] {\\Add{sig}\\\\$sigs' = sigs \\cup sig$\\\\ if $sig \\in sigs_{auth}$}\n (b)\n edge[transition, bend left = 15]\n node[move, above] {\\Pay\\\\if $|sigs| \\geq n$}\n (a)\n edge[transition, bend left = 30]\n node[move, below] {\\Cancel\\\\if $d$ expired}\n (a)\n ;\n \\end{tikzpicture}\n \\caption{Transition diagram for the multi-signature state machine;\n edges labelled with input from redeemer and transition constraints.}\n \\label{fig:multisig-machine}\n\\end{figure}\n\nA simple example for such a state machine is an on-chain $n$--of--$m$ multi-signature contract. Specifically, we have a given amount\n$\\val_\\msc$ of some cryptocurrency and we require the approval of at\nleast $n$ out of an \\textit{a priori} fixed set of $m \\geq n$ owners to spend\n$\\val_\\msc$. With plain \\UTXO{} (e.g., on Bitcoin), a multi-signature\nscheme requires out-of-band (off-chain) communication to collect all\n$n$ signatures to spend $\\val_\\msc$. On Ethereum, and also in the\n\\EUTXO{} model, we can collect the signatures on-chain, without any\nout-of-band communication. To do so, we use a state machine operating\naccording to the transition diagram in\nFigure~\\ref{fig:multisig-machine}, where we assume that the threshold\n$n$ and authorised signatures $\\sigs_\\auth$ with \\(|\\sigs_\\auth| = m\\)\nare baked into the contract code.\n\nIn the multi-signature state machine's implementation in the \\EUTXO{} model, we use a validator\nfunction $\\nu_\\msc$ accompanied by the datum $\\delta_\\msc$ to lock\n$\\val_\\msc$. The datum $\\delta_\\msc$ stores the machine state,\nwhich is of the form \\(\\Holding\\) when only holding the locked value\nor \\(\\Collecting{\\val}{\\kappa}{d}{\\sigs}\\) when collecting\nsignatures $\\sigs$ for a payment of $\\val$ to $\\kappa$ by the deadline\n$d$. The initial output for the contract is \\((\\nu_\\msc, \\val_\\msc,\n\\Holding)\\).\n\nThe validator $\\nu_\\msc$ implements the state transition diagram from\nFigure~\\ref{fig:multisig-machine} by using the redeemer of the spending input to determine the transition that needs to be taken. That redeemer (state machine input) can take four forms:\n\\begin{inparaenum}[(1)]\n\\item \\(\\Propose{\\val}{\\kappa}{d}\\) to propose a payment of $\\val$ to $\\kappa$\n by the deadline $d$,\n\\item \\(\\Add{\\sig}\\) to add a signature $\\sig$ to a payment,\n\\item $\\Cancel$ to cancel a proposal after its deadline expired, and\n\\item $\\Pay$ to make a payment once all required signatures have been collected.\n\\end{inparaenum}\nIt then validates that the spending transaction $\\mi{tx}$ is a valid\nrepresentation of the newly reached machine state. This implies that\n$\\mi{tx}$ needs to keep $\\val_\\msc$ locked by $\\nu_\\msc$ and that the\nstate in the datum $\\delta^{\\prime}_\\msc$ needs to be the successor state\nof $\\delta_\\msc$ according to the transition diagram.\n\nWhile the state machine in Figure~\\ref{fig:multisig-machine} is fine, its mapping to \\EUTXO\\ transactions comes with a subtle caveat: what if, for a 2--of--3 contract, somebody posts a transition $\\tx_{\\mathrm{bad}}$ corresponding to the state \\(\\Collecting{\\val}{\\kappa}{d}{\\{\\sig_1, \\sig_2\\}}\\) onto the chain \\emph{without} going through any of the previous states, including without starting in $\\Holding$?\nGiven that $\\Pay$ merely checks \\(|\\sigs| \\geq 2\\), the payment would be processed when requested on $\\tx_{\\mathrm{bad}}$, even if \\(\\{\\sig_1, \\sig_2\\}\\) are invalid signatures.\nWe would not have been allowed to add the invalid signatures $\\sig_1$ and $\\sig_2$ by way of \\(\\Add{\\sig}\\) since its state transition checks signature validity, but by initialising the state machine in an intermediate state $s$ with \\(\\s{initial}(s) = \\false\\), we were able to circumvent that check.\n\nIn the plain \\EUTXO\\ model, there is no simple way for the validator implementing a state machine to assert that the state it is operating on arose out of a succession of predecessor states rooted in an initial state.\nAs a consequence of this limitation, the formal result presented in the \\EUTXO\\ paper~\\cite{eutxo-1-paper} is not as strong as one might hope.\nMore precisely, this previous work did establish soundness and completeness for a weak bisimulation between CEMs and transactions on a \\EUTXO\\ ledger;\nhowever, it fell short in that it did not show that an inductive property met by the states of a CEM may also be asserted for the corresponding states on the ledger.\nThe reason for this omission is precisely the problem we just discussed: for a ledger-representation of a CEM state, we can never be sure that it arose out of a transaction sequence rooted in an initial CEM state.\n\n\\subsection{Token provenance}\n\\label{sec:state-machine-provenance}\n\nIn the present work, we solve the problem described above. We will show that non-fungible tokens can be used to identify a unique trace of transactions through an \\EUTXOma\\ ledger that corresponds to all the states of the corresponding CEM. Moreover, we introduce a notion of \\emph{token provenance} that enables us to identify the first CEM state in such a trace and to ensure that it is a state accepted by \\(\\s{initial} : \\s{S} \\rightarrow \\B\\). Together, these allow a state machine validator to ensure that a current CEM state indeed arose out of a trace of transactions rooted in a transaction corresponding to an initial CEM state merely by checking that the non-fungible token associated with this state machine instance is contained in the $\\val$ of the state machine output that it locks: this would be $\\val_\\msc$ for the multi-signature contract of \\S\\ref{sec:cem-example}.\n", "meta": {"hexsha": "c91675d51efacf92b80ef7c9b87f6ab935bebb96", "size": 14059, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "papers/eutxoma/informal.tex", "max_stars_repo_name": "AriFordsham/plutus", "max_stars_repo_head_hexsha": "f7d34336cd3d65f62b0da084a16f741dc9156413", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1299, "max_stars_repo_stars_event_min_datetime": "2018-10-02T13:41:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T01:10:02.000Z", "max_issues_repo_path": "papers/eutxoma/informal.tex", "max_issues_repo_name": "AriFordsham/plutus", "max_issues_repo_head_hexsha": "f7d34336cd3d65f62b0da084a16f741dc9156413", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2493, "max_issues_repo_issues_event_min_datetime": "2018-09-28T19:28:17.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T15:31:31.000Z", "max_forks_repo_path": "papers/eutxoma/informal.tex", "max_forks_repo_name": "AriFordsham/plutus", "max_forks_repo_head_hexsha": "f7d34336cd3d65f62b0da084a16f741dc9156413", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 399, "max_forks_repo_forks_event_min_datetime": "2018-10-05T09:36:10.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T11:18:25.000Z", "avg_line_length": 76.825136612, "max_line_length": 885, "alphanum_fraction": 0.7321288854, "num_tokens": 3872, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.3174262591305011, "lm_q1q2_score": 0.17477723629155176}}
{"text": "\\chapter{Conclusion and Perspectives}\n\\label{chap:9}\nIn this chapter, we conclude this thesis by summarizing the achievements and pointing out\ninteresting future working directions. \n\n\\section{Achievements}\n\\subsection*{Knowledge Based Optimization Approach}\nIn this thesis, we presented an intermediate distributed representation (Send/Receive model) for \ndistributed ream-time systems. This representation proposes an implementation method for\nsystems with multiparty interactions through simpler primitives such as\nmessages passing. It also provides a scheduling mechanism, more appropriate to distributed\nreal-time systems, since it is based on partial information of a given system.\n\nOur first contribution was to propose an optimization methods for such intermediate \nrepresentation. We presented a methods that relies on invariants in order to refine the\nset of conflicting interactions, required for building the Send/Receive model.\nBased on the original model, an approximation of the set of reachable states of a timed system\nis derived on the form of invariants. The latter are used later on for checking the \nsimultaneous enabledness of two potentially conflicting interactions. \nBased on the obtained results, either the potential conflict between two interactions is cleared \nout meaning that both interactions are never enabled at the same time, or the real conflict \ncannot be attested which in this case a counter-example is proposed.\nThis optimization aims particularly at reducing the effort of scheduling interactions\nby removing any unnecessary exchange of messages or evaluation computations. \n\n\\subsection*{Modeling Communication Delays}\nThe Send/Receive model presented in Chapter~\\ref{chap:3} assumes that the communication \nmechanisms are fast enough to not impact the behavior of the overall system. Effectively, this\nis due to the zero delay between the decision of executing interactions in schedulers and\nthe concrete execution of the corresponding actions in the participating components.\nThe resulting model was proven to be observationally equivalent to the initial model.\nTo reduce the impact of communication delays on the system behavior,~\\cite{ahlem_these} proposed\nan approach based on the idea of \\emph{early decision making}. In this solution, schedulers\nplan ahead the execution of interactions and notify the corresponding components in advance.\nMoreover, it was suggested that schedulers are required to observe an additional subset of\ncomponents called \\emph{observed components}, not participating in the planned interactions, \nin order to achieve global deadlines.\nHowever, besides the fact that this method is restricted to systems where components have non \ndecreasing deadlines, the characterization of the set of observed components is incomplete. In \nfact this set is greater than the presented characterization, and in many cases is equal to \nall the component of the system. This is mainly due to the nature of the location invariants:\nLocal constraints that propagate on the global level.\n\nOur second contribution was to propose a method, based on the same idea of early decision making,\nbut that differs from the approach of~\\cite{ahlem_these} in the following points:\n\\begin{itemize}\n \\item No restriction on components constraints was made\n \\item No restriction on the form of timing constraints (In ~\\cite{ahlem_these} timing \n constraints are restricted to constraints of the form $x\\le k$ or $x\\ge k$)\n \\item Our method works on the semantics level conversely to the aforementioned method that\n relies directly on transformations and model construction. Effectively, we introduced \n the local planning semantics that plan the execution of interactions based only on \n the set of its participating components. The planning operations are constrained by \n the worst estimation of communication delays as well as the planned interactions. This\n semantics is suited for distributed real-time systems since it is based on local (partial)\n information. We also provided a proof for weak simulation, and a strategy based on \n sufficient conditions guaranteeing the preservation of the system behavior from deadlocks. \n Finally, we presented an alternative method based on real-time controller synthesis \n paradigm and discussed its convenience with respect to our method. \n\\end{itemize}\n\n\\subsection*{Robustness to Clock Imperfections}\nWe studied in Chapter~\\ref{chap:6} the effect of clock imperfections (clock drift) on the \nbehavior of a timed system. We considered a perturbation model where clock rates are not \nperfect (not equal and may change during the execution) but under the assumption that clocks \nare resynchronized which induces that their difference of clock values will stay within a certain\nthreshold. \nOur robustness analysis approach was based on the characterization of potential bad states\nthat invalidates the $\\epsilon$-simulation between the initial model and the perturbated model.\nWe proposed a solution for verifying the robustness of a given timed system based on \nshrinkability analysis and suggested the \\texttt{Shrinktech} tool for achieving such analysis\nwhich is basically based on parameter synthesis.\n\n\n\\section{Future Works}\n\\subsection*{Partitioning and Mapping}\n\nIn this thesis, we presented the partitioning of interactions as being an important parameter\nof the Send/Receive transformation. Interaction partitioning is of importance since the \nset of conflicting interactions is calculated based on the latter. The immediate question is\nwhether a given partitioning is better than an other. In other terms, how can we evaluate \nif a given partition of interaction is good or bad. Instinctively, the choice of partitioning\ninteractions is based on two main factors, namely the degree of parallelism and the effort\nfor solving conflicts (in terms of messages and computational evaluation).\nThis choice is generally guided by the choice of a specific target platform: how expensive\nis the communication? This introduce necessarily the problem of mapping an application\non a given target platform~\\cite{map}. This question is of great importance since its answer\nwill define how each application process will be mapped to the platform interconnected \nprocessing nodes. Consequently, it decides on workload of each processing nodes and \nthe communication volume induced by such mapping.\nThus an optimal partition would be a partition that takes into account the target platform\nand proposes a partitioning that optimize all the above points. This can be done either\nby computing directly the optimal solution or by tuning a proposed partition by merging or \nsplitting some processes of the application.\n\n\\subsection*{Invariants for Distributed Real-Time Systems}\n\nIn Chapter~\\ref{chap:5} and Chapter~\\ref{chap:6}, we presented different semantics reflecting\nthe behavior of a real-time system in a distributed setting (under communication delays or \nwith clock drift). \n\nIn Chapter~\\ref{chap:5}, we relied on the invariants of the initial model\nto verify the sufficient conditions for deadlock freedom of the local planning semantics.\nThis usage is due to the fact that invariants of the system under the standard semantics \nare proven to be invariants of the system under the local planning semantics.\nAn interesting direction is to try to derive invariants characterizing specifically the reachable\nstates of the planning semantics. This will help directly in the verification process in term of \nresults precision.\n\nIn Chapter~\\ref{chap:6}, we proposed the \\texttt{Shrinktech} tool for the robustness analysis.\nHowever, such tool relies on the computation of the region graph of a timed automaton, which\nin term of complexity suffers from the state explosion problem when the increasing the number of\nclocks. A solution to reduce this cost is to compute a parametric invariant of the system\nwith drifting clocks. The latter represents a cheap over-approximations may in some cases \nallow to avoid overly eager and expensive computations of the precise parametric images of \nthe set of reachable states. \n\n\\subsection*{Modeling vs Semantics}\n\nModel-based development is one promising approach in building real-time systems today.\nThis paradigm relies on models with well defined semantics when building systems all the way\nform the design phase until reaching a concrete implementation.\nThis approach is really important when working with large scale heterogeneous systems since\nit reduces both the engineering efforts and the development costs and time.\nNevertheless, a model represents only an abstraction of the reality and is often based\non idealized assumptions, which will not hold at a given stage of the model-based workflow, \nprecisely when reaching the implementation point.\nIn this thesis, we tried to bridge this gap by introducing new semantics to tackle the different\nissues inherent to the distributed context.\nAn interesting working direction would be to answer the following question: \nCan similar results be obtained without introducing new semantics, but using modeling\ninstead? \nThis question is of a big interest since it can indicate which direction efforts need to be made.\nFor instance, the introduction of a new semantics can be in some case complicated and \nerrors-prone whereas modeling is known to be more general, much easier and trivial to understand.\nAlso, modeling has also the benefit of being modular in the sense that if we change \nthe target execution platform on will have just to replace the corresponding model.\n\n\\subsection*{Scheduling Distributed Real-Time Systems}\nIn this thesis, we often mentioned the words \\say{schedulers or scheduling} but without \nreferring to any scheduling scheme or policy. An interesting working direction is to refine \nthe behavior of given system by imposing some scheduling constraints. In fact, since we presented\nmethods based on over-approximations and sufficient conditions, the results of our analysis may\nin some cases yield counter-examples that are either false-positives or real counter-examples.\nThe idea is to identify scheduling schemes that could identify the needs, based on a given set\nof properties, in order to achieve a correct behavior.\n\n\n\n", "meta": {"hexsha": "eee23b932782eea56e4a69be0553460a128c9ea0", "size": 10256, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Chapter9/chapter9.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": "Chapter9/chapter9.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": "Chapter9/chapter9.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": 68.3733333333, "max_line_length": 97, "alphanum_fraction": 0.8188377535, "num_tokens": 1985, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.3311197396289915, "lm_q1q2_score": 0.17460490992350727}}
{"text": "\\section{Systematic uncertainties}\n\\label{sec:syst}\n\n\n\\subsection{Theory uncertainties}\n\\label{ssec:theoryuncert}\nThe estimation of the CP BSM parameters from the OO shape requires the precise knowledge of the SM contributions and related uncertainties. This includes both SM gluon-gluon fusion (background) and SM VBF (signal).\n Therefore, the different theoretical uncertainties affecting the SM predictions are included in the fitting likelihood. This includes uncertainties from PDF, QCD order and $\\alpha_s$.\n\nFor the gluon-fusion production mode, nine uncertainty sources are used to model the QCD theory\nuncertainties, following the recommendation of the LHC Higgs cross section working group~\\cite{LHCXS_4}. These sources are:\n\\begin{itemize}\n\\item two sources correspond to yield uncertainties related to the total cross section. Their magnitude is taken from the\nSTWZ-BLPTW predictions~\\cite{ggF_qcd_unc_1,ggF_qcd_unc_2,LHCXS_4} and their impact on the different bins is evaluated using\nNNLOPS.\n\\item two sources correspond to migration uncertainties related to splitting the phase space by jet multiplicity. Their magnitude and impact are derived similarly to the yield uncertainties\n\\item two uncertainty sources are related to the $p_\\mathrm{T}^H$ shape and are estimated from scale\nvariations in NNLOPS, including variations of the HNNLO input scales and the renormalization\nand factorization scales in Powheg.\n\\item two uncertainty sources related to the enhancement of uncertainties for events with typical VBF topology (due to explicit or implicit third-jet vetos), and are estimated by scale variations in MCFM~\\cite{MCFM}, and the corresponding uncertainties are estimated using the same procedure use for yield and migration uncertainties.\n\\item one uncertainty source is related to the treatment of $m_t$ and is most important at large $p_\\mathrm{T}^H$.\n\\end{itemize}\n\nFollowing the recommendations of PDF4LHC~\\cite{pdf4lhc}, the PDF uncertainties are evaluated using the 30 eigenvectors set and treating each of them as an uncorrelated source. One additional nuisance parameter accounts for the uncertainties in $\\alpha_{s}$.\n\nFor the $VBF+VH$ production modes, QCD uncertainties are estimated as an envelope of the scale variations available in Powheg~\\cite{Nason:2009ai,VBFVH_theoryUnc}. Uncertainties from the choice of the PDF set and $\\alpha_\\mathrm{s}$ are evaluated similar to the gluon-fusion case.\nA summary of the magnitude of these uncertainties in the different categories and OO bins is shown in the Figure ~\\ref{fig:theoryUnc_ggF} ~\\ref{fig:theoryUnc_VBF}.\n\n\\begin{figure}[htbp]\n\\centering\n \\subfloat[TT ]{ \\includegraphics[width= 0.23\\textwidth]{figure/TheorySyst/ggF_theoryUnc_TT_d_0.pdf} }\n \\subfloat[TL ]{ \\includegraphics[width= 0.23\\textwidth]{figure/TheorySyst/ggF_theoryUnc_TL_d_0.pdf} }\n \\subfloat[LT ]{ \\includegraphics[width= 0.23\\textwidth]{figure/TheorySyst/ggF_theoryUnc_LT_d_0.pdf} } \n \\subfloat[LL ]{ \\includegraphics[width= 0.23\\textwidth]{figure/TheorySyst/ggF_theoryUnc_LL_d_0.pdf} } \n \\caption{Theory uncertainty in different OO bins for ggF process}\n \\label{fig:theoryUnc_ggF}\n\\end{figure}\n\n\\begin{figure}[htbp]\n\\centering\n \\subfloat[TT ]{ \\includegraphics[width= 0.23\\textwidth]{figure/TheorySyst/VBF_theoryUnc_TT_d_0.pdf} }\n \\subfloat[TL ]{ \\includegraphics[width= 0.23\\textwidth]{figure/TheorySyst/VBF_theoryUnc_TL_d_0.pdf} }\n \\subfloat[LT ]{ \\includegraphics[width= 0.23\\textwidth]{figure/TheorySyst/VBF_theoryUnc_LT_d_0.pdf} }\n \\subfloat[LL ]{ \\includegraphics[width= 0.23\\textwidth]{figure/TheorySyst/VBF_theoryUnc_LL_d_0.pdf} }\n \\caption{Theory uncertainty in different OO bins for VBF process}\n \\label{fig:theoryUnc_VBF}\n\\end{figure}\n\n\n\n\n\\subsection{Uncertainties from signal and background modeling}\n\\label{ssec:modeluncert}\n\n\\paragraph{} The Higgs peak described by double-side crystal ball function can be influence by several experimental effects. \nPhoton energy scale uncertainties shift the position of signal peak by between $\\pm0.2\\%$ and $\\pm0.4\\%$, while the photon resolution uncertainties change the width of signal peak by between $\\pm 6\\%$ and $\\pm 15\\%$, following Ref ~\\cite{ref:phscaleres}. \nUncertainty due to knowledge of Higgs boson mass of 0.24GeV ~\\cite{ref:mHerror} would also affect the signal peak position. \nThese sources are considered independently into systematic uncertainties. \n\\# \\textcolor{red}{NUMBER NEED CHECK}\n\n\\paragraph{} The uncertainty due to the background choice is taken to be the spurious signal yield discussed in \\Sect{\\ref{ssec:spurious_signal}}, and assumed to be uncorrelated in each bins. \n\n\n\\subsection{Experimental systematic uncertainties affecting the expected signal yields}\n\\label{ssec:expuncert}\n\n\\paragraph{} With data taken during 2015-2018, the uncertainty from integrate luminosity is 2.0\\%. Other sources of experimental uncertainty affecting the expected signal yields include: the efficiency of diphoton trigger, the photon identification and isolation efficiencies, the photon energy scale and resolution, the modelling of pile-up in the simulation, the jet energy scale and resolution, the efficiency of the jet vertex tagger. Among them the dominant one is jet flavor composition \\texttt{ATLAS\\_JET\\_Flavor\\_Composition} which contributes 5.5\\%. \\\\\n\nThe considered systematic uncertainty terms are shown in Figure ~\\ref{fig:syst_ranking}. \n\n\\begin{figure}[h]\n \\centering\n \\includegraphics[width=.9\\textwidth]{figure/ranking.pdf}\n \\caption{Ranking plot for all systematic uncertainty terms. }\n \\label{fig:syst_ranking}\n\\end{figure}\n\n\n", "meta": {"hexsha": "dc01592ec48294d50b27cbe3e2e24ce2f5b46436", "size": 5582, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "tex/Systematic.tex", "max_stars_repo_name": "phreborn/vbfcp_INT", "max_stars_repo_head_hexsha": "904cd56e96a3489887bb9e808d28f6dae4d7f058", "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/Systematic.tex", "max_issues_repo_name": "phreborn/vbfcp_INT", "max_issues_repo_head_hexsha": "904cd56e96a3489887bb9e808d28f6dae4d7f058", "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/Systematic.tex", "max_forks_repo_name": "phreborn/vbfcp_INT", "max_forks_repo_head_hexsha": "904cd56e96a3489887bb9e808d28f6dae4d7f058", "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": 70.6582278481, "max_line_length": 561, "alphanum_fraction": 0.7993550699, "num_tokens": 1441, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.3073580105206753, "lm_q1q2_score": 0.17397033089570058}}
{"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 369 / 650 Fall \\the\\year{} \\\\ Midterm Examination Two}\n\\author{Professor Adam Kapelner}\n\n\\date{Wednesday, November 11, \\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\\problem\\timedsection{5} These are questions on method of moments estimators.\n\n\\vspace{-0.2cm}\\benum\\truefalsesubquestionwithpoints{11} \n\n\\begin{enumerate}[(a)]\n\\item For any DGP, $\\thetahatmm$ will be a function of the data.\n\\item For any DGP, $\\thetahatmm$ will be a function of the data and of $\\theta$.\n\\item For any DGP, its fifth moment is $\\expe{X^5}$ if it exists.\n\\item For any iid DGP with a finite expectation, $\\thetahat = \\Xbar := \\oneover{n}\\sum_{i=1}^n X_i$ is an MM estimator for the DGP's expectation.\n\\item For any iid DGP with a finite variance, $\\thetahat = \\sigsqhat := \\oneover{n}\\sum_{i=1}^n (X_i - \\Xbar)^2$ is an MM estimator for the DGP's variance.\n\\item Let $\\thetahatmm$ be an estimator for $\\theta$. Its estimate $\\thetahathatmm$ must be a legal value in the parameter space of $\\theta$.\n\\item For an iid DGP with a finite variance where $\\theta := \\expe{X} / \\sd{X}$, then $\\thetahatmm = \\Xbar / \\sqrt{\\sigsqhat}$ where $\\Xbar$ and $\\sigsqhat$ are defined in (d) and (e).\\\\\n\nConsider a DPG $\\Xoneton \\iid \\text{ShiftedParetoI}(1, \\theta) := \\theta (x + 1)^{-\\theta - 1}$ which has support in positive numbers only. Using calculus you can show that $\\expe{X} = \\frac{1}{\\theta - 1}$.\n\\item $\\thetahatmm = \\Xbar$\n\\item $\\thetahatmm = 1 / \\Xbar$\n\\item $\\thetahatmm = 1 / \\Xbar + 1$\n\\item $\\thetahatmm = (\\Xbar + 1) / \\Xbar$\n\\end{enumerate}\n\\eenum\\instr\\pagebreak\n\n%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\problem\\timedsection{13} Consider the DPG from the previous problem, $\\iid \\text{ShiftedParetoI}(1, \\theta) := \\theta (x + 1)^{-\\theta - 1}$ which has support in positive numbers only and consider a dataset $\\xoneton$ to be realizations from this DGP.\n\n\\vspace{-0.2cm}\\benum\\truefalsesubquestionwithpoints{19} \n\n\\begin{enumerate}[(a)]\n\\item The likelihood for all the data is $=\\theta (\\xoneton + 1)^{-\\theta - 1}$.\n\\item The likelihood for all the data is $=\\prod_{i=1}^n \\theta (x_i + 1)^{-\\theta - 1}$.\n\\item The log likelihood for all the data is $=\\prod_{i=1}^n \\theta (\\natlog{x_i} + 1)^{-\\theta - 1}$.\n\\item The log likelihood for all the data is $=\\natlog{\\prod_{i=1}^n \\theta (x_i + 1)^{-\\theta - 1}}$.\n\\item The log likelihood for all the data is $=n\\natlog{\\theta} + \\natlog{(-\\theta - 1)\\prod_{i=1}^n (x_i + 1)}$.\n\\item The log likelihood for all the data is $=n\\natlog{\\theta} + (-\\theta - 1) \\sum_{i=1}^n \\natlog{x_i + 1}$.\n\\item The score function for all the data is the derivative of the log likelihood function.\n\\item The deriviative of the log likelihood for all the data is $=\\frac{n}{\\theta} - \\sum_{i=1}^n \\natlog{x_i + 1}$.\n\\item Assuming (h) is true, $\\thetahathatmle = n \\Big/ \\sum_{i=1}^n \\natlog{x_i + 1}$.\n\\item The Fisher information for this DGP is $I(\\theta) = 1$.\n\\item The Fisher information for this DGP is $I(\\theta) = n / \\theta^2$.\n\\item The Fisher information for this DGP is $I(\\theta) = -1 / \\theta^2$.\n\\item The Fisher information for this DGP is $I(\\theta) = 1 / \\theta^2$.\n\\item The variance of any unbiased estimator for $\\theta$ for this DGP must be at least $1 / n$.\n\\item The variance of any unbiased estimator for $\\theta$ for this DGP must be at least $\\theta / n$.\n\\item The variance of any unbiased estimator for $\\theta$ for this DGP must be at least $\\theta^2 / n$.\n\\item To show that $\\thetahatmle$ is/isn't the UMVUE for $\\theta$ involves simple algebra / calculus on information available to you on this page.\n\\item To show that $\\thetahatmle$ is/isn't the UMVUE for $\\theta$ involves a lot of algebra / calculus but the information you require is available to you on this page.\n\\item To show that $\\thetahatmle$ is/isn't the UMVUE for $\\theta$ is impossible given the information available to you on this page.\n\\end{enumerate}\n\\eenum\\instr\\pagebreak\n\n%%%%%%%%%%%%%%%%%%%%%%%%\n\n\\problem\\timedsection{6} \\ingray{Consider the DPG from the previous problem, $\\iid \\text{ShiftedParetoI}(1, \\theta) := \\theta (x + 1)^{-\\theta - 1}$ which has support in positive numbers only and consider a dataset $\\xoneton$ to be realizations from this DGP.} Let $\\sigsq$ denote the variance of this DGP model. You can show that $\\thetahathatmle = n \\Big/ \\sum_{i=1}^n \\natlog{x_i + 1}$ and $I(\\theta) = 1 / \\theta^2$. \n\n\\vspace{-0.2cm}\\benum\\truefalsesubquestionwithpoints{13} \n\n\\begin{enumerate}[(a)]\n\\item $\\var{\\thetahatmle} = \\theta^2 / n$.\n\\item $\\thetahatmle$ is normally distributed.\n\\item $\\thetahatmle$ is distributed as a Student's $t$ distribution.\n\\item $\\thetahatmle$ is an asymptotically normally estimator.\n\\item $\\thetahatmle \\approxdist \\normnot{0}{1}$.\n\\item $\\thetahatmle \\approxdist \\normnot{\\theta}{\\sigsq / n}$.\n\\item $\\thetahatmle \\approxdist \\normnot{\\theta}{\\oneover{n\\theta^2}}$.\n\\item You can use the fact in (g) to create a confidence interval for $\\theta$ (i.e. a function of $\\xoneton$ and constants).\n\\item $\\thetahatmle \\approxdist \\normnot{\\theta}{\\squared{\\oversqrtn{\\theta}}}$.\n\\item You can use the fact in (i) to create a confidence interval for $\\theta$ (i.e. a function of $\\xoneton$ and constants).\n\\item $\\thetahatmle \\approxdist \\normnot{\\thetahathatmle}{\\squared{\\oversqrtn{\\thetahathatmle}}}$.\n\\item You can use the fact in (k) to create a confidence interval for $\\theta$ (i.e. a function of $\\xoneton$ and constants).\n\\item $\\thetahatmle$ can provide arbitrary precision to measure $\\theta$ given a higher sample size $n$.\n\\end{enumerate}\n\\eenum\\instr\\pagebreak\n\n%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n%\\problem\\timedsection{4} Consider the DGP $\\Xoneton \\iid U(0, \\theta)$. We showed in class that $\\thetahatmm = 2\\Xbar$ and $\\thetahatmle = \\max{\\Xoneton}$.\n%\n%\\vspace{-0.2cm}\\benum\\truefalsesubquestionwithpoints{5} \n%\n%\\begin{enumerate}[(a)]\n%\\item $\\thetahathatmm > \\thetahathatmle$.\n%\\item $\\bias{\\thetahatmm} = 0$.\n%\\item $\\var{\\thetahatmm} > \\var{\\thetahatmle}$.\n%\\item $\\mse{\\thetahatmm} > \\mse{\\thetahatmle}$.\n%\\end{enumerate}\n%\\eenum\\instr\\pagebreak\n\n%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n\\problem\\timedsection{6} Consider $\\xoneton$ to be realizations from an iid DGP, $\\thetahat$ to be an unbiased estimator for $\\theta$ and assume the conditions needed to prove the Cramer-Rao Lower Bound (CRLB). A quantity primed (e.g. $\\ell'$) denotes differentiation with respect to $\\theta$. \n\n\\vspace{-0.2cm}\\benum\\truefalsesubquestionwithpoints{7} \n\n\\begin{enumerate}[(a)]\n\\item ${\\ell'\\parens{\\thetahat; \\xoneton}} = 0$\n\\item $\\expe{\\ell\\parens{\\theta; \\Xoneton}} = 0$\n\\item $\\expe{\\ell\\parens{\\theta; \\Xoneton}} = n\\expe{\\ell\\parens{\\theta; X}}$\n\\item $\\expe{\\ell\\parens{\\theta; \\Xoneton}^2} = 0$\n\\item $\\expe{\\ell'\\parens{\\theta; \\Xoneton}^2} = 0$\n\\item $\\partialop{\\theta}{\\expe{\\ell\\parens{\\theta; \\Xoneton}}} = 0$\n\\item $\\var{\\ell\\parens{\\theta; \\Xoneton}^2} = 0$\n\\item $\\var{\\ell'\\parens{\\theta; \\Xoneton}^2} = nI(\\theta)$\n\\end{enumerate}\n\\eenum\\instr\\pagebreak\n\n%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n%\\problem\\timedsection{4} These are some questions about some theorems we discussed in class. Let $X_1, X_2, ... $ be rv's and $a_1, a_2, ...$ be constants.\n%\n%\\vspace{-0.2cm}\\benum\\truefalsesubquestionwithpoints{5} \n%\n%\\begin{enumerate}[(a)]\n%\\item If $X_1 \\convp a_1$, then $\\natlog{X_1} \\convp \\natlog{a_1}$.\n%\\end{enumerate}\n%\\eenum\\instr\\pagebreak\n\n%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n\\problem\\timedsection{5} These are some questions about some theorems we discussed in class. Let $X_1, X_2, ... $ be rv's indexed also by $n$, the sample size, and $a_1, a_2, ...$ be positive constants.\n\n\\vspace{-0.2cm}\\benum\\truefalsesubquestionwithpoints{6} \n\n\\begin{enumerate}[(a)]\n\\item If $X_1 \\convp a_1$, then $\\natlog{X_1} \\convp \\natlog{a_1}$.\n\\item If $X_1 \\convp a_1$, then $\\displaystyle\\oneover{X_1} \\convp \\oneover{a_1}$.\n\\item If $X_1 \\convp a_1$ and $\\displaystyle \\frac{X_2 - \\mu}{a_1} \\convd \\stdnormnot$ then $\\displaystyle\\frac{X_2 - \\mu}{X_1} \\convd \\stdnormnot$\n\\item If $\\displaystyle \\frac{X_1 - \\mu}{a_1} \\sim \\stdnormnot$ then $\\displaystyle\\frac{(X_1 - \\mu)^2}{a_1^2} \\sim \\stdnormnot$\n\\item If $\\displaystyle \\frac{X_1 - \\mu}{a_1} \\sim \\stdnormnot$ then $\\displaystyle\\frac{(X_1 - \\mu)^2}{a_1^2} \\sim \\chisq{n}$\n\\item If you do a one-sample t test with $n=20$ and get a standardized estimate of -2.30. If the square of this estimate is less than 95\\% quantile of the $F_{1,19}$ distribution, then you retain $H_0$.\n\\end{enumerate}\n\\eenum\\instr\\pagebreak\n\n%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n\\problem\\timedsection{7} According to Benford's Law in Base 10, in any measurement setting that spans orders of magnitude, the first digit of measurements is more likely to be a one than a two, a two than a three, etc. This phenomenon is ubiquitous and can be used to describe measurements for city populations, surface area of rivers, dollar amounts on tax returns, etc. The distribution is on the first row of the table below.\n\nHere we investigate possible fraud in the 2009 Iranian election, a topic of many academic papers. We examine the vote counts in the 366 districts for one of the five main candidates and count the number of districts who's count had first digit = 1, first digit = 2, ..., first digit = 9. The tally is the second row of the table below. \n\n\\begin{table}[htp]\n\\centering\n\\begin{tabular}{l|ccccccccc|c}\n& \\multicolumn{9}{c}{First Digit is $x = $} &\\\\\n & 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9 & Total \\\\\\hline\\hline\nBenford's Law in Base 10 $p_X(x) = $ & .301 & .176 & .125 & .097 & .079 & .067 & .058 & .051 & .046 & 1.000 \\\\\\hline\nObserved Count & 125 & 57 & 44 & 29 & 24 & 16 & 41 & 13 & 17 & 366\\\\ \n\\ingray{Row 3 Name} & 110.17 & 64.42 & 45.75 & 35.50 & 28.91 & 24.52 & 21.23 & 18.67 & 16.84 & ?\\\\ \n\\ingray{Row 4 Name} & 2.00 & 0.85 & 0.07 & 1.19 & 0.83 & 2.96 & 18.42 & 1.72 & 0.00 & ?\n\\end{tabular}\n\\end{table}\n\\FloatBarrier\n\nWe wish to test if the voting counts \\emph{differ} from Benford's Law at $\\alpha = 5\\%$. Let $\\theta_1$ denote the true probability of a count having a first digit = 1, $\\theta_2$ denote the true probability of a count having a first digit = 2, ..., $\\theta_9$ denote the true probability of a count having a first digit = 9. Note: $F_{\\chisq{8}}(15.51) = F_{\\chisq{9}}(16.92) = F_{\\chisq{24}}(36.42) = F_{\\chisq{27}}(40.11) = 95\\%$.\n\n\\vspace{-0.2cm}\\benum\\truefalsesubquestionwithpoints{9} \n\n\\begin{enumerate}[(a)]\n\\item This test is a \\qu{goodness of fit} test.\n\\item This test is an \\qu{independence} of $\\geq 2$ events test.\n\\item The number of parameters in Benford's Law in Base 10 is 8.\n\\item $H_0: \\theta_1 = \\theta_2 = \\ldots = \\theta_9 = 1/9$.\n\\item $H_0:$ The $\\theta_k$'s are equal to the values in the table's first row.\n\\item $H_a: \\theta_1 = \\theta_2 = \\ldots = \\theta_9 = 1/9$.\n\\item $H_a:$ at least one $\\theta_k$ is not equal to the value in the table's first row.\n\\item The name of row 3 could be \\qu{expected number of first digits in the district counts under Benford's Law in Base 10}.\n\\item The name of row 4 could be \\qu{expected number of first digits in the district counts under Benford's Law in Base 10}.\n\\end{enumerate}\n\\eenum\\instr\\pagebreak\n\n%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n\\problem\\timedsection{7} \\textbf{This header is the same as in the previous problem.} According to Benford's Law in Base 10, in any measurement setting that spans orders of magnitude, the first digit of measurements is more likely to be a 1 than a 2, a 2 than a 3, etc. This phenomenon is ubiquitous and can be used to describe measurements for city populations, surface area of rivers, dollar amounts on tax returns, etc. The distribution is on the first row of the table below.\n\nHere we investigate possible fraud in the 2009 Iranian election, a topic of many academic papers. We examine the vote counts in the 366 districts for one of the five main candidates and count the number of districts who's count had first digit = 1, first digit = 2, ..., first digit = 9. The tally is the second row of the table below. \n\n\\begin{table}[htp]\n\\centering\n\\begin{tabular}{l|ccccccccc|c}\n& \\multicolumn{9}{c}{First Digit is $x = $} &\\\\\n & 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9 & Total \\\\\\hline\\hline\nBenford's Law in Base 10 $p_X(x) = $ & .301 & .176 & .125 & .097 & .079 & .067 & .058 & .051 & .046 & 1.000 \\\\\\hline\nObserved Count & 125 & 57 & 44 & 29 & 24 & 16 & 41 & 13 & 17 & 366\\\\ \n\\ingray{Row 3 Name} & 110.17 & 64.42 & 45.75 & 35.50 & 28.91 & 24.52 & 21.23 & 18.67 & 16.84 & ?\\\\ \n\\ingray{Row 4 Name} & 2.00 & 0.85 & 0.07 & 1.19 & 0.83 & 2.96 & 18.42 & 1.72 & 0.00 & ?\n\\end{tabular}\n\\end{table}\n\\FloatBarrier\n\nWe wish to test if the voting counts \\emph{differ} from Benford's Law at $\\alpha = 5\\%$. Let $\\theta_1$ denote the true probability of a count having a first digit = 1, $\\theta_2$ denote the true probability of a count having a first digit = 2, ..., $\\theta_9$ denote the true probability of a count having a first digit = 9. Note: $F_{\\chisq{8}}(15.51) = F_{\\chisq{9}}(16.92) = F_{\\chisq{24}}(36.42) = F_{\\chisq{27}}(40.11) = 95\\%$.\n\n\\vspace{-0.2cm}\\benum\\truefalsesubquestionwithpoints{7} \n\n\\begin{enumerate}[(a)]\n\n\\item The Pearson chisq statistic has an estimate = 366.00.\n\\item The Pearson chisq statistic has an estimate = 28.04.\n\\item The Pearson chisq statistic estimator here is asymptotically $\\chisq{24}$.\n\\item The Pearson chisq statistic estimator here is asymptotically $\\chisq{8}$.\n\\item If (d) were to be true, the retainment region for the estimate would be $\\bracks{-15.51, +15.51}$.\n\\item $H_0$ is rejected and we conclude that the counts for this specific candidate is \\emph{not} Benford-Law-distributed.\n\\item Assuming (f), the digit that is most incongruent with Benford's law is $x=9$.\n\\end{enumerate}\n\\eenum\\instr\\pagebreak\n\n%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n\n\\begin{figure}\n\\centering\n\\includegraphics[width = 6in]{windspeeds.pdf}\n\\end{figure}\n\n\\problem\\timedsection{10} Above is a histogram of wind speeds at JFK airport measured at midnight for every day in 2013. We fit eight different iid DGPs / models to this data. Below are the models, the maximum likelihood estimates for their parameter(s) and their log likelihood value estimates:\n\n\\begin{table}[htp]\n\\centering\n\\begin{tabular}{r|cccccccc}\n& \\multicolumn{8}{c}{Name of Model / DGP}\\\\\n & Exponential & Normal & Weibull & Gamma & Gumbel & Gompertz & Frechet & Generalized Logistic \\\\\\hline\n$\\thetahathatmle_1$ & 0.05 & 18.97 & 3.52 & 11.71 & 15.17 & 0.14 & 3.18 & 3.49 \\\\ \n$\\thetahathatmle_2$ & & 5.59 & 21.01 & 0.62 & 4.84 & 0.05 & 15.59 & 12.22 \\\\ \n$\\thetahathatmle_3$ & & & & & & & & 4.03 \\\\ \\hline\n$\\ell(\\thetahathatmle_1, \\ldots, \\thetahathatmle_{K_m}; \\xoneton)$ & -1435.12 & -1142.72 & -1148.11 & -1129.28 & -1143.31 & -1200.26 & -1174.37 & -1129.65\n\\end{tabular}\n\\end{table}\n\\FloatBarrier\n\n\n\\vspace{-0.2cm}\\benum\\truefalsesubquestionwithpoints{9} \n\n\\begin{enumerate}[(a)]\n\\item All of these models have the same number of parameters $K$.\n\\item The true model will be one of these eight models candidates.\n\\item According to the log-likelihood estimates, the best fitting model candidate is the Gamma.\n\\item According to the AICC metric, the best fitting model candidate is the Generalized Logistic.\n\\item The asymptotic bias on the true log-likelihood for the normal model is the same as the bias for the Gompertz model.\n\\item The AIC metric for the generalized logistic model candidate is 2263.30. %false\n\\item The AIC metric for the exponential model candidate is 2872.24. %true\n\\item Assuming (b), the probability the exponential model is the true model is negligibly small.\n\\item AICC values will not significantly differ from the AIC values.\n\\end{enumerate}\n\\eenum\\instr\\pagebreak\n\n%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n\\problem\\timedsection{16} In the \\qu{Topiramate for the Treatment of Binge Eating Disorder Associated With Obesity: A Placebo-Controlled Study}, the researchers were also interested in adverse effects of the drug Topiramate. One such bad effect is \\qu{Upper Respiratory Tract Infection} which we call \\emph{infection}. The experimental results are below.\n\n\\begin{itemize}\n\\item In the $n_T = 202$ Topiramate group, there were 75 cases of infection and \n\\item in the $n_C = 202$ placebo group that did not take Topiramate, there were 40 cases of infection. \n\\end{itemize}\nLet $\\theta_T$ be the true proportion of infection in Topiramate-takers and $\\theta_C$ be the true proportion of infection among non Topiramate-takers. All numbers below are rounded to the nearest 3 digits.\n\n\\vspace{-0.2cm}\\benum\\truefalsesubquestionwithpoints{13} \n\n\\begin{enumerate}[(a)]\n\\item When testing $H_a: \\theta_T \\neq \\theta_C$ at $\\alpha = 5\\%$, a retainment region for $H_0$ is equal to or is approximately $\\bracks{-0.086, 0.086}$.%true\n\\item When testing $H_a: \\theta_T \\neq \\theta_C$ at $\\alpha = 5\\%$, a retainment region for $H_0$ is equal to or is approximately $\\bracks{-0.088, 0.088}$.%true\n\\item $CI_{\\theta_T - \\theta_C, 95\\%}$ is equal to or is approximately $\\bracks{0.087, 0.260}$.%true\n\\item There is a 95\\% chance that the CI estimate in (c) contains the true mean difference $\\theta_T - \\theta_C$.\n\\item The estimate of the odds against infection in the Topiramate group is 1.693. %true\n\\item The estimate of the odds against infection in the Topiramate group is 0.591. %false\n\\item When testing $H_a: \\displaystyle \\frac{1 - \\theta_T}{\\theta_T} \\neq \\half$ at $\\alpha = 5\\%$, a retainment region for $H_0$ is equal to or is approximately $\\bracks{0.224, 0.776}$.%true\n\\item The estimate of the risk ratio of infection in the Topiramate group vs the control group is 0.173.%false\n\\item The estimate of the risk ratio of infection in the Topiramate group vs the control group is 1.875.%true\n\\item $CI_{\\theta_T / \\theta_C, 95\\%}$ is equal to or is approximately $\\bracks{1.255, 2.495}$.%true\n\\item $CI_{\\theta_T / \\theta_C, 95\\%}$ is equal to or is approximately $\\bracks{-0.088, 0.088}$.%false\n\\item It would be possible to create an exact CI for the risk ratio of infection in the Topiramate group vs the control group given the data here and the concepts learned in class.%false\n\\item The CI estimator in (j) is more approximate in coverage probability than the CI estimator in (c).\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", "meta": {"hexsha": "53d32b9ccf1904e19c40ba1313eca6f2befa3148", "size": 21249, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "exams/midterm2/midterm2.tex", "max_stars_repo_name": "kapelner/QC_Math_369_Fall_2020", "max_stars_repo_head_hexsha": "1ff69eb22cd004dcfb095c99b0673d152aaba117", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-08-25T01:50:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-16T01:21:15.000Z", "max_issues_repo_path": "exams/midterm2/midterm2.tex", "max_issues_repo_name": "kapelner/QC_Math_369_Fall_2020", "max_issues_repo_head_hexsha": "1ff69eb22cd004dcfb095c99b0673d152aaba117", "max_issues_repo_licenses": ["MIT"], "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/midterm2/midterm2.tex", "max_forks_repo_name": "kapelner/QC_Math_369_Fall_2020", "max_forks_repo_head_hexsha": "1ff69eb22cd004dcfb095c99b0673d152aaba117", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-08-30T04:15:19.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-27T02:37:09.000Z", "avg_line_length": 60.8853868195, "max_line_length": 873, "alphanum_fraction": 0.6909031013, "num_tokens": 6746, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.42632157796989345, "lm_q2_score": 0.40733340004593027, "lm_q1q2_score": 0.17365501786742285}}
{"text": "\\documentclass{article}\n\\usepackage{parskip}\n\\usepackage{amsmath}\n\n\\setlength{\\parindent}{0cm}\n\n\\begin{document}\n\n\\title{CPSC 413 \\\\ Assignment 1 - Analysis of Simple Algorithms}\n\\author{Andrew Helwer}\n\\date{February 2011}\n\\maketitle\n\n\\section{Partial Correctness of FindLeaf}\n\n\\emph{Precondition:}\t\n\\begin{itemize}\n\\item A nonempty binary tree $T$ is given as input\n\\end{itemize}\n\n\\emph{Postcondition:}\n\\begin{itemize} \\item A leaf of $T$ is returned as output \n\\item The tree $T$ has not been changed \n\\end{itemize}\n\n\\textbf{Assertion A:} $v:=$ the root of $T$ and $T$ has not been modified\n\n\\textbf{Assertion B:} $v:=$ a leaf of $T$ and $T$ has not been modified\n\n\\textbf{Assertion C:} $v$ is an interior vertex of $T$\n\n\\textbf{Assertion D:} The depth of $v$ has increased by one, and $T$ has not\nbeen modified\n\nAssuming the precondition is satisfied, $T$ is nonempty - that is, it contains\nat least one element, the root vertex. $v$ is set equal to this vertex before\nexecution of the loop, satistfying assertion $A$ as simply changing the\nreference $v$ does not modify $T$.\n\nIf there is only one vertex in $T$, then $v$ (the root vertex) is a leaf and\nthe loop invariant $C$ is not satisfied. If there is more than one vertex in\n$T$, then $v$ will be an interior vertex of $T$ as the root must then have at\nleast one child (either left or right) and so $C$ will be satisfied and the\nloop entered.\n\nBy satisfying $C$ and entering the loop, $v$ is guaranteed to have either a\nleft or right child, specified $v.left$ and $v.right$ respectively. Once the\nloop body has executed, $v$ has been set to either $v.left$ or $v.right$, and so\nthe number of $v:=v.parent$ operations it would take to reach the root node has\nincreased by one - thus the depth of $v$ has increased by one, partially\nsatisfying $D$. As well, the operations $v:=v.left$ and $v:=v.right$ make no\nmodifications to $T$ - they change only the reference $v$. Thus $T$ is not\nmodified during the loop body, and $D$ is fully satisfied. Therefore $C\n\\Rightarrow D$ over execution of the loop body.\n\n$C$ is once again tested for, and if satisfied the loop body again executes. If\n$C$ is not satisfied, the loop is exited. Since $C$ is not satisfied, $v$ is not\nan interior vertex of $T$. Since $v$ is not an interior vertex, by definition it\nmust be a leaf. Thus $B$ is partially satisfied, which in turn satisfies one of\nthe postrequisites as $v$ is returned. The second postrequisite, and second\npart of $B$ - that $T$ has not been modified - is ensured by satisfying $D$ at\nthe end of every execution of the loop body, or $A$ if there is only one vertex\nin $T$. Thus $A \\Rightarrow B$ over execution of the findLeaf function.\n\nThe above is sufficient to prove that the satisfaction of the preconditions\nprior to findLeaf execution implies the satisfaction of the postconditions\nafter findLeaf execution. Since termination has not been proven, findLeaf has\nonly been shown to be partially correct.\n\n\\section{Termination of FindLeaf}\n\nThe following assumes that a binary tree consists of a finite number of\nvertices.\n\nAssume that findLeaf is executed on valid input whereby the precondition is\nsatisfied. Observe that instructions 1 and 6 are guaranteed to execute only\nonce, as they are not contained within the body of a loop. They may therefore\nbe disregarded when proving termination, and only the loop (instructions 2\nthrough 5) considered.\n\nA fundamental property of binary trees is depth, which is the number of edges\non the longest path from the root to any leaf in $T$. The depth of the root\nis therefore zero. For any interior vertex $v$ of $T$, setting $v:=v.left$ or\n$v:=v.right$ increases the depth of $v$ by one, as it adds an additional edge\nto traverse to reach the root.\n\nIn question 1 it was proved that after every execution of the loop\nbody on valid input, the depth of $v$ was increased by one. Define a new\nfunction $D$, whereby if $D(v)$ is computed for some $v \\in T$, $D$ returns the\ndepth of $v$ in $T$, and if $D(T)$ is computed for some binary tree $T$, $D$\nreturns the depth of $T$. Thus after every execution of the loop body, where\n$v'$ is the value of $v$ before execution, $D(v'):=D(v')+1=D(v)$.\n\nDefine another function $B(T,v) = D(T) - D(v)$, called the bound function. Since\n$D(v)$ increases by one every time the loop body executes and $D(T)$ remains\nconstant (due to the condition of $T$ not being modified), $|B|$ decreases in\nvalue with every execution of the loop body. Because the size of $T$ is finite,\n$D(T)$ is finite as well, and so the loop body will execute only a finite\nnumber of times before $B(T,v) = 0$ - at this point, $D(v) = D(T)$, and so $v$\nmust be a leaf node of $T$, as otherwise $v$ possesses a child with depth\ngreater than the depth of the tree, by definition impossible. Since $v$ is not\nan interior vertex of $T$, the loop invariant is not satisfied and so the loop\nwill terminate when $B(T,v) = 0$ after a finite number of executions.\n\nThus it has been shown that the loop body will execute only a finite number of\ntimes on valid input, and so findLeaf will terminate on valid input.\n\n\\section{Upper Bound on Cost of FindLeaf}\n\nAs in question 2, observe that on valid input steps 1 and 6 are executed only\nonce, for a total constant cost of 2. Also observe that the depth of $T$ is\nmaximized when every vertex in $T$ counts toward the depth of $T$ - that is,\nwhen $T$ is in a configuration resembling a linked list with each vertex having\nexactly one parent and one child except for the root (which lacks a parent) and\nthe leaf (which lacks a child). It will be in this case then that the bound\nfunction defined in question 2 is initialized to a value furthest from zero.\n\nThe configuration described above will result in $T$ having a depth of\n$|T|-1$, where $|T|$ is the number of vertices in $T$, also known as the size of\n$T$. Since the depth of the root node is zero, $B$ is initialized to the value\nof $|T|-1$, which is also the number of times the loop runs as $B$\ndecreases by exactly one with every execution of the loop body.\n\nInside the loop, three instructions will be executed every time it is run - the\ninitial check to see if the loop invariant is satisfied, a check whether the\nvertex has a left child, and the assignment of the vertex reference to either\nits left or right child depending on the outcome of this check. Thus the number\nof instructions executed before the loop terminates will be $3*n$, where $n$ is\nthe number of times the loop executes.\n\nAssembling these observations, the worst case running time of findLeaf may be\ngiven by $R_U(s) = 3(s-1)+2 = 3s-1$, where $s=|T|$.\n\n\\section{Lower Bound on Cost of FindLeaf}\n\nSteps 1 and 6 are executed exactly once, resulting in a cost of 2.\nSince the number of other instructions executed has been proven to\nbe a function of the depth of the input, finding the binary tree\nconfiguration with the least depth per unit size will also result in\na function for the lower bound on instruction executions in findLeaf.\n\nLogically, this configuration results when each depth level of $T$ is completely\nfilled before putting a vertex on the next level - the binary tree cannot be\ncompressed any further. The structure described is one that is as close to a\nfull binary tree as possible. Since the capacity of each level is double the\nprevious, the function that relates $|T|$ to $D(T)$ is given by\n$D(|T|)=fl(\\log_2(|T|))$, where $fl$ is the flooring function that transforms\nany real number into the next lowest integer value.\nFollowing the same derivations as in question 3, we arrive at the best case\nrunning time of findLeaf given by $R_L(s)=3*fl(\\log_2(s))+2$, where $s=|T|$.\n\n\\section{The Action of the VertexCover Function}\n\n\\textbf{Proof A:}\n\nBy the action of vertexCover instruction either 6 or 7, the parent of the root\nof $T_L$ in $T$ is $w$. Due to instructions 12 or 13, there is no path leading\nfrom any vertex in $T_U$ to $w$, and thus no path leading from any vertex in\n$T_U$ to any vertex in $T_L$. Thus any vertex in $T_U$ is not a vertex in\n$T_L$, and vice versa - they are disjoint sets, with the addition that $u$ and\n$v$ are in neither.\n\nSince $v$ is defined to be a leaf, it has no children. The children of $w$ are\n$v$ and the root of $T_L$, which could be $null$. Thus the removal of $T_L \\cup\n\\{v\\} \\cup \\{w\\}$ from $T$ results in no lost vertices - all removed vertices\nare in $T_L \\cup \\{v\\} \\cup \\{w\\}$. $T_U$ may thus be written $T \\setminus T_L\n\\cup \\{v\\} \\cup \\{w\\}$. Therefore $T_U$, $T_L$, $\\{w\\}$, and $\\{v\\}$ partition\n$T$.\n\nFrom the above it follows that every vertex of $T$ except $v$ and $w$ is a\nvertex of exactly one of $T_U$ or $T_L$, so that $|T| = |T_U| + |T_L| + 2$.\n\n\\textbf{Proof B:}\n\nThe basis for the proof of disjointness in part A was that after the execution\nof instructions 12 or 13, there is no path leading from any vertex in $T_U$ to\n$w$, and thus no path leading from any vertex in $T_U$ to any vertex in $T_L$.\nThis may be modified slightly to prove something similar for edges in $T$.\nObserve that of all the edges in $T$, there are only three that join to at\nleast one element outside of $T_U$ and $T_L$ - the edge from $x$ to $w$ (before\nremoval), the edge from the root of $T_L$ to $w$, and the edge from $v$ to $w$.\nIf these edges are disregarded, due to the partitioning nature of $T_U$ and\n$T_L$ and how edges by definition must join two vertices, all other edges must\nexist within $T_U$ or $T_L$.\n\nThus it is true that every edge in $T$ is an edge in exactly one of $T_U$ or\n$T_L$, except for the edges that touch the vertex $w$.\n\n\\section{Correctness of VertexCover}\n\nProve: For all nonnegative integers $n = |T|$, $vertexCover(T)$ returns the\ncorrect output\n\nBase cases:\n\nIf $|T|$ = 0 or $|T|$ = 1, then the vertex cover is the empty set, as\nthere are no edges in $T$ to connect to the vertices in $T$.\n\nStrong Inductive Hypothesis:\n\nAssume the correct vertex cover is returned for $0...n$.\nShow $vertexCover(n+1)$ also holds:\n\n$vertexCover(n+1)$ splits $T$ up such that $|T| = |T_U| + |T_L|\n+ 2$. Thus $|T_U| + |T_L| = |T|-2$, and so $|T_U| < |T|-2$ and $|T_U| < |T|-2$,\nso by inductive hypothesis $vertexCover(T_U)$ and $vertexCover(T_L)$ return the\ncorrect vertex cover of $T_U$ and $T_L$ respectively. Since $vertexCover(n+1) =\nvertexCover(T_U) \\cup vertexCover(T_L) \\cup \\{w\\}$, $vertexCover(n+1)$ also\nreturns the correct vertexCover and so by the strong inductive hypothesis\nvertexCover is correct for all nonnevative integers $n = |T|$.\n\n\\section{Worst-Case Cost of VertexCover}\n\nThe worst case running time will result from the same circumstances as the\nworst case for findLeaf - that of a linked list configuration for $T$. Since\nthis is a recursive function, it is best to consider instruction 15 and work\nfrom there.\n\nStep 15 specifies returning $vertexCover(T_U) \\cup vertexCover(T_L) \\cup\n\\{w\\}$. In the linked list configuration, $T_L$ will always be $null$, leading\nto a cost of 2 for calling $vertexCover(T_L)$ as only instructions 1 and 2 will\nbe executed. The real cost lies in calling $vertexCover(T_U)$ - observe that by\nremoving both the leaf node and its parent from $T$ upon every execution of the\nbody of vertexCover, $|T_U| = |T|-2$. Since the precondition does not specify\nwhether $|T|$ is even or odd, this necessitates two base cases:\n\n\\begin{enumerate}\n\\item if $s = 0$, $C(s) = 2$\n\\item if $s = 1$, $C(s) = 2$\n\\item otherwise $C(s) = R_U(s) + 11 + 2 + C(s-2)$\n\\end{enumerate}\n\nIn the above, $s$ is initialized to $|T|$, $R_U(s)$ is the cost function of the\nworst case for findLeaf defined back in question 3, and 11 is then number of\ninstructions that will be executed during a single level of recursion in\nvertexCover, with 2 the number of instructions executed during the\n$vertexCover(T_L)$ call.\n\n\\section{Upper Bound on Cost of VertexCover}\n\nIf we consider the recurrence defined in the previous question, it's clear that\nthere will be approximately $\\frac{|T|}{2}$ levels of recursion. Consider the\nquantities $A = C(s)$ and $B = C(s-2)$. As the recurrence is defined, $A$ must\nbe greater than or equal to $B$. Thus $A' = C(s) - C(s-2)$ is greater than or\nequal to $B' = C(s-2) - C(s-4)$, and so $\\frac{|T|}{2}(C(s) - C(s-2)) \\geq C(s)$\nfor some large value of $s$, as $\\frac{|T|}{2}(C(s) - C(s-2))$ may be viewed as\nreplacing the number of operations performed by all $\\frac{|T|}{2}$ levels of\nrecursion with $C(s) - C(s-2)$, an increase over what they would have been.\n\nObserving the above, the upper bound of the recurrence may be written\n$\\frac{|T|}{2}(R_U(s) + 13)$, which is of course linear in the product of the\nsize of $T$ and the number of steps used by findLeaf in the worst case.\n\n\\section{Lower Bound on Cost of VertexCover}\n\nObserving that the best-case running time will occur if $T$ is as close\nto a full binary tree as possible, using similar arguments to question 8 it is\nascertained that the lower bound on the running time will be of the order\n$\\frac{|T|}{2}(R_L(s) + C)$, where $C$ is some positive integer constant and\n$R_L(s)$ is the lower bound on the running time of findLeaf defined in question\n4. Thus the lower bound is also linear in the product of the size of $T$ and\nthe number of steps used by findLeaf in the best case.\n\n\\section{Bounds of VertexCover in Asymptotic Notation}\n\nThe worst-case running time of vertexCover, as a function of the size of the\ninput tree, $n$, is:\n\n\\begin{equation}\nf(n) \\in O(n^2)\n\\end{equation}\n\n\\end{document}", "meta": {"hexsha": "0dc9370420cb664107b621a15283c2f07db5e6a0", "size": 13468, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "cpsc413/as1/cpsc413as1.tex", "max_stars_repo_name": "edwardchen123/UofC", "max_stars_repo_head_hexsha": "ecc49eee798772e560397fb00ad692e6f664c19b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-04-11T10:17:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-11T10:17:41.000Z", "max_issues_repo_path": "cpsc413/as1/cpsc413as1.tex", "max_issues_repo_name": "edwardchen123/UofC", "max_issues_repo_head_hexsha": "ecc49eee798772e560397fb00ad692e6f664c19b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cpsc413/as1/cpsc413as1.tex", "max_forks_repo_name": "edwardchen123/UofC", "max_forks_repo_head_hexsha": "ecc49eee798772e560397fb00ad692e6f664c19b", "max_forks_repo_licenses": ["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.3333333333, "max_line_length": 80, "alphanum_fraction": 0.732031482, "num_tokens": 3799, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4571367168274948, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.17258770180324082}}
{"text": "\\chapter{Theory and overview}\n\\label{chapter:overview}\n\n\n\\section{Terminology and data products}\n\\label{sec:terminology}\n%\nAs mentioned in the Introduction, the overall topic of this document is the\nextraction of geophysical data from observed spectra. This calculation step is\nnormally denoted as the retrieval or the inversion, where mainly the first term\nis used in this document. The objective of \\smr\\ is to estimate atmospheric\nquantities, mainly the concentration of different gases, and these variables\nare accordingly the main target of the retrieval, and, together with auxiliary\ninformation, they form the L2 data. \n\nBesides geophysical variables, the retrieval must consider a number of\ninstrumental aspects to avoid that e.g.\\ pointing errors cause unnecessary\nlarge retrieval errors. The result of this part of the retrieval can be seen as\ndiagnostics data. Some of the quality fields of the L2 data are based on the\ndiagnostics data, and the data are also stored internally for further analysis\n(then denoted as L2I), to e.g.\\ detect instrumental drifts.\n\nThe retrieval can also include atmospheric state variables that influence the\nmeasurement, but the accuracy of the retrieval is not sufficiently high to\njustify inclusion in the L2 data. Regarding atmospheric gases, the ones\nincluded in the L2 data are denoted as target species, while other retrieved\ngases are called secondary species.\n\n\n\n\\section{Radiative transfer basics}\n\\label{sec:rt}\n%\nThere is no \\ATBD\\ dedicated to radiative transfer, as a general software is used\nto handle this task (Sec.~\\ref{sec:setup:forward}). Instead the main\nconsiderations around radiative transfer are commented inside this \\ATBD. For a\nmore detailed discussion, targeting \\smr, the reader is referred to\n\\citet{eriksson:studi:02}.\n\nA strong advantage of using microwaves is that local thermodynamic equilibrium\n(LTE) can be assumed, even for radiative transfer in the mesosphere and lower\nthermosphere. Further, as long as the lowest altitude of the line-of-sight, the\ntangent point, is some kilometres above the tropopause, scattering can safely\nbe neglected as \\smr\\ operates at wavelengths $>$\\,0.5\\,mm. Such a restriction in\ntangent altitudes is made for the operational \\smr\\ retrievals. \n\nThe combination of LTE and no scattering makes the basic simulation task\nrelatively simple. In fact, when it comes to atmospheric radiative transfer,\nthe required simulations boil down to summing up emission along the propagation\npath, weighted with the transmission between \\smr\\ and the point of emission.\nThat is, the expression for radiative transfer to handle is \\citep[see\ne.g.][Eq.~50]{chandrasekhar:60}:\n\\begin{equation}\n \\label{eq:rteq}\n I(\\nu) = I_0(\\nu)e^{-\\int^l_0{k(s,\\nu)ds}} + \n \\int^l_0{k(s,\\nu)B(T(s),\\nu) e^{-\\int^l_0{k(s',\\nu)ds'}} ds},\n\\end{equation}\nwhere $I$ is radiance, $I_0$ is the radiance along the line-of-sight (\\LOS) at\nthe top of the atmosphere, where the propagation path starts, $l$ is the length\nof this propagation path, $k$ is the absorption coefficient, $s$ is the\ndistance along the propagation path, and $B$ is the Planck function giving the\nemission of a blackbody at temperature $T$ and frequency $\\nu$.\nEq.~\\ref{eq:rteq} assumes that the gaseous absorption is unpolarised. This is a\nvalid assumption in the microwave region for all species, except for oxygen which\nis affected by the Zeeman effect. That is, Earth's magnetic field induces\npolarised absorption and emission, and a matrix-vector equivalent to\nEq.~\\ref{eq:rteq} is required to handle oxygen \\citep[see\ne.g.][]{larsson:zeema:14}.\n\nEvaluation of Eq.~\\ref{eq:rteq} gives the monochromatic intensity (radiance)\nalong pencil-beam propagation paths, matching infinite frequency and angular\nresolution. Accordingly, Eq.~\\ref{eq:rteq} must be solved for a set of\nfrequencies and propagation paths, to make it possible to incorporate the\nantenna pattern, channel frequency response and other characteristics of the\nsensor in the simulations \\citep[see e.g.][]{eriksson:studi:02,read2006clear}.\n\n\n\\section{Theoretical formalism}\n\\label{sec:formalism}\n\n\\subsection{Forward and inverse models}\n%\nThe retrievals are presented and discussed using the formalism presented in\nChapter~3 of \\citet{rodgers:00}. The data to be inverted are appended to create\nthe measurement vector, \\MsrVct. This vector is related to other variables as\n\\begin{equation}\n \\label{eq:fmodel1}\n \\MsrVct = \\FrwMdl(\\SttVct,\\FrwMdlVct) + \\MsrErrVct_n,\n\\end{equation}\nwhere \\FrwMdl\\ is denoted as the forward model, \\SttVct\\ as the state vector,\n\\FrwMdlVct\\ as the vector of forward model parameters and $\\MsrErrVct_n$\nrepresents measurement noise. The distinction between the two arguments of the\nforward model is that all variables that we want to retrieve form \\SttVct,\nwhile all other quantities required of the forward model are placed in\n\\FrwMdlVct. \n\nThe forward model treated explicitly in this document is the software used to\nmodel atmospheric radiative transfer and sensor responses. This is a model\noperating with discrete quantities, while the ``true'', hypothetical, forward\nmodel, \\trueFrwMdl, representing the actual physical mechanisms in the atmosphere\nand the instrument, must be seen as a continuous function. If \\FrwMdl\\ is\nconstructed and used carefully, the discrete representation should not cause\nany fundamental problems, and it is here assumed that all deviations between\n\\trueFrwMdl\\ and \\FrwMdl\\ can be treated as imperfect values in \\FrwMdlVct.\nThat is, $\\trueFrwMdl=\\FrwMdl(\\SttVct,\\FrwMdlVct)$, but the exact values of\n\\FrwMdlVct\\ are unknown and all we can do is to use the best possible estimate,\n\\FrwMdlVctHat. That is:\n\\begin{equation}\n \\label{eq:fmodel2}\n \\MsrVct = \\FrwMdl(\\SttVct,\\FrwMdlVctHat) + \\MsrErrVct_b + \\MsrErrVct_n,\n\\end{equation}\nwhere \n\\begin{equation}\n \\label{eq:eps_b}\n \\MsrErrVct_b = \\trueFrwMdl - \\FrwMdl(\\SttVct,\\FrwMdlVctHat).\n\\end{equation}\nThis difference ($\\MsrErrVct_b$) is below denoted as the forward model\nuncertainty. \n\nThe retrieval process is formalised in the inverse model, \\InvMdl:\n\\begin{equation}\n \\label{eq:imodel}\n \\RtrVct = \\InvMdl(\\MsrVct,\\aSttVct{a},\\FrwMdlVctHat,\\InvMdlVct),\n\\end{equation}\nwhere \\RtrVct\\ is the retrieved state vector and \\InvMdlVct\\ covers all\nadditional variables introduced by the inverse model. The exact nature\nof the vector \\aSttVct{a}\\ varies between retrieval approaches, but in general it \nrepresents an a priori estimate of \\SttVct.\n\n\n\\subsection{Linearisation}\n%\nFrom this point it is assumed that the retrieval problem is not strongly\nnon-linear, and a local linear analysis is possible. Or expressed differently,\nthat derivatives of the forward and inverse models are approximately valid over\na significant range. The Jacobian, or the weighting function matrix, is the\npartial derivative of \\FrwMdl\\ with respect to \\SttVct:\n\\begin{equation}\n \\label{eq:kx}\n \\aWfnMtr{\\SttVct} = \\frac{\\PartD\\FrwMdl}{\\PartD\\SttVct}.\n\\end{equation}\nIn the same manner, we define \\aWfnMtr{\\FrwMdlVct} as\n\\begin{equation}\n \\label{eq:kb}\n \\aWfnMtr{\\FrwMdlVct} = \\frac{\\PartD\\FrwMdl}{\\PartD\\FrwMdlVct}.\n\\end{equation}\nThe contribution function matrix, \\CtrFncMtr, is defined as the partial\nderivative of the inverse model with respect to the measurement vector:\n\\begin{equation}\n \\label{eq:g}\n \\CtrFncMtr = \\frac{\\PartD\\InvMdl}{\\PartD\\MsrVct}.\n\\end{equation}\nHaving these partial derivatives at hand, the retrieval error can be related\nto the fundamental uncertainties. As a first step, the forward model is\nlinearised around (\\aSttVct{a},\\FrwMdlVctHat):\n\\begin{equation}\n \\label{eq:fmodel3}\n \\MsrVct = \\FrwMdl(\\aSttVct{a},\\FrwMdlVctHat) + \n \\aWfnMtr{\\SttVct}\\left(\\SttVct-\\aSttVct{a}\\right) +\n \\aWfnMtr{\\FrwMdlVct}\\left(\\FrwMdlVct-\\FrwMdlVctHat\\right) +\n \\MsrErrVct_n\n\\end{equation}\nUnder these assumptions, we now have a second way to express the forward\nmodel uncertainty:\n\\begin{equation}\n \\MsrErrVct_b = \\aWfnMtr{\\FrwMdlVct}\\left(\\FrwMdlVct-\\FrwMdlVctHat\\right).\n\\end{equation}\nBy combining the equations above and rearranging the terms, we can finally\nderive an expression for the total retrieval error, $\\RtrErr = \\RtrVct - \\SttVct$:\n\\begin{equation}\n \\label{eq:delta}\n \\RtrErr = \\left(\\AvrKrnMtr-\\IdnMtr\\right)\n \\left(\\SttVct-\\aSttVct{a}\\right) + \n \\CtrFncMtr\\aWfnMtr{\\FrwMdlVct}\\left(\\FrwMdlVct-\\FrwMdlVctHat\\right) +\n \\CtrFncMtr\\MsrErrVct_n,\n\\end{equation}\nwhere \\IdnMtr\\ is the identity matrix and\n\\begin{equation}\n \\label{eq:A}\n \\AvrKrnMtr = \\CtrFncMtr\\aWfnMtr{\\SttVct},\n\\end{equation}\nis the averaging kernel matrix. The terms on the right hand side of\nEq.~\\ref{eq:delta} are denoted as smoothing error, forward model retrieval\nerror and measurement noise retrieval error, respectively. These error\ncomponents are discussed further in Chapter~\\ref{chapter:characterisation}.\n\n\n\\subsection{Calculation of retrieval error}\n%\nDespite that Eq.~\\ref{eq:delta} gives an expression for the retrieval error it cannot be used in practice, for the simple reason that \\SttVct\\ and \\FrwMdlVct\\\nare not known. The retrieval error can only evaluated in a statistical sense,\nand for this purpose uncertainties and errors are described by\ncovariance matrices (\\CvrMtr). See e.g.\\\n\\url{en.wikipedia.org/wiki/Covariance_matrix} for a description of this type of\nmatrices, as well as the basic calculation rules needed to understand the error\npropagation. The statistical correspondence to Eq.~\\ref{eq:delta} is\n\\begin{equation}\n \\label{eq:Sdelta1}\n \\aCvrMtr{\\RtrErr} = \\left(\\AvrKrnMtr-\\IdnMtr\\right)\\aCvrMtr{\\SttVct}\n \\left(\\AvrKrnMtr-\\IdnMtr\\right)^T + \n \\CtrFncMtr\\aWfnMtr{\\FrwMdlVct}\\aCvrMtr{\\FrwMdlVct}\n \\aWfnMtr{\\FrwMdlVct}^T\\CtrFncMtr^T + \n \\CtrFncMtr\\aCvrMtr{\\MsrErrVct_n}\\CtrFncMtr^T.\n\\end{equation}\nThe combination of the instrument and the forward model can be seen as\nthe ``observation system'', then having an uncertainty of\n\\begin{equation}\n \\label{eq:eps_o}\n \\MsrErrVct_o = \\MsrErrVct_b + \\MsrErrVct_n. \n\\end{equation}\nThe covariance matrix of the observation system uncertainty is \n\\begin{equation}\n \\label{eq:So}\n \\aCvrMtr{\\MsrErrVct_o} = \\aWfnMtr{\\FrwMdlVct}\\aCvrMtr{\\FrwMdlVct}\n \\aWfnMtr{\\FrwMdlVct}^T + \\aCvrMtr{\\MsrErrVct_n}.\n\\end{equation}\nUsing the definition of $\\aCvrMtr{\\MsrErrVct_o}$, Eq.~\\ref{eq:Sdelta1}\ncan be written in a somewhat more compact form:\n\\begin{equation}\n \\label{eq:Sdelta2}\n \\aCvrMtr{\\RtrErr} = \\left(\\AvrKrnMtr-\\IdnMtr\\right)\\aCvrMtr{\\SttVct}\n \\left(\\AvrKrnMtr-\\IdnMtr\\right)^T + \\CtrFncMtr\\aCvrMtr{\\MsrErrVct_o}\\CtrFncMtr^T.\n\\end{equation}\n\n\n\n\\section{Selected set-up}\n\\label{sec:setup}\n\n\\subsection{Retrieval method}\n\\label{sec:setup:inverse}\n%\n\n\\subsubsection{The need for regularisation}\n\\label{sec:setup:inverse:reg}\n%\nIn short, the task of the retrieval method is to derive \\RtrVct\\ from \\MsrVct.\nIt turns out that the mapping from \\MsrVct\\ to \\RtrVct\\ is not unique. That is,\nthere exists an infinite set of $\\SttVct$-vectors that result in a fit with the\nmeasurement, considering the measurement noise. Instead, some ``optimal'' state\nmust be selected, among this set of possible solutions.\n\nIf we for a moment assume that the retrieval problem can be treated as fully\nlinear around (\\aSttVct{a},\\FrwMdlVctHat), we\nhave that $\\aWfnMtr{\\SttVct}\\left(\\SttVct-\\aSttVct{a}\\right)\\approx \\MsrVct\n-\\FrwMdl(\\aSttVct{a},\\FrwMdlVctHat)$ and the solution can be written as\n\\begin{equation}\n \\label{eq:linretrieval}\n \\RtrVct = \\aSttVct{a} + \\CtrFncMtr(\\MsrVct-\\FrwMdl(\\aSttVct{a},\\FrwMdlVctHat)).\n\\end{equation}\nIt is clear that \\CtrFncMtr, at least roughly, represents an inverse of\n\\aWfnMtr{\\SttVct}, but to use the standard inverse of \\aWfnMtr{\\SttVct} (only\npossible if \\aWfnMtr{\\SttVct} is square) or to apply the least squares method\n($\\CtrFncMtr=(\\aWfnMtrTrp{\\SttVct}\\aWfnMtr{\\SttVct})^{-1}\\aWfnMtr{\\SttVct}$)\nwill result in an extremely high sensitivity to noise. The retrieval problem at\nhand is said to be ill-posed, which is the standard situation for passive\natmospheric sounding.\n\n\n\\subsubsection{The optimal estimation method}\n\\label{sec:setup:inverse:oem}\n%\nThe normal way to tackle ill-posed problems of this type is\n``regularisation'', where some constrain on the solution is introduced. In\npassive atmospheric sounding, using statistical information as basis for the\nregularisation has become the standard approach, and it is also the approach\nselected for \\smr. The method is probably most widely known as the optimal\nestimation method (\\OEM), which is the name used in this document. The method\ncan be seen as an application of Bayes theorem, under certain conditions, and\nanother possible name of the method the maximum a posteriori solution, see\nfurther \\citet{rodgers:00}.\n\nThe aspect of ``statistical regularisation'' is probably most clearly\nidentified by noting that \\OEM\\ minimises the following ``cost function'':\n\\begin{equation}\n \\label{eq:costfun}\n \\CstFnc(\\SttVct) = (\\MsrVct-\\FrwMdl(\\SttVct,\\FrwMdlVctHat))^T\\aCvrMtr{o}^{-1}\n (\\MsrVct-\\FrwMdl(\\SttVct,\\FrwMdlVctHat)) +\n (\\SttVct-\\aSttVct{a})^T\\aCvrMtr{a}^{-1}(\\SttVct-\\aSttVct{a}),\n\\end{equation}\nthat is,\n\\begin{equation}\n \\label{eq:mincost}\n \\RtrVct = \\min\\limits_{\\SttVct}(\\CstFnc(\\SttVct)).\n\\end{equation}\nThe cost function \\CstFnc\\ can be seen as the sum of the two penalty terms. The\nfirst term weights how well the solution corresponds to the measurement. If\n\\CstFnc\\ would be set to only contain this term, the standard least squares\nsolution would be obtained. The regularisation is introduced by the second\nterm, that evaluates the probability of \\SttVct\\ based on a priori\ninformation.\n\nIf the retrieval problem is linear around (\\aSttVct{a},\\FrwMdlVctHat), \\RtrVct\\\ncan be calculated using Eq.~\\ref{eq:linretrieval}, with\n\\citep[][Eq.~4.5]{rodgers:00}\n\\begin{equation}\n \\label{eq:lindy}\n \\CtrFncMtr = (\\aWfnMtrTrp{\\SttVct}\\aCvrMtr{o}^{-1}\\aWfnMtr{\\SttVct}\n +\\aCvrMtr{a}^{-1})^{-1}\\aWfnMtrTrp{\\SttVct}\\aCvrMtr{o}^{-1}.\n\\end{equation}\nHowever, the inversion of \\smr\\ measurements result in a (moderately)\nnon-linear problem and an iterative process is required to find the minimum of\n\\CstFnc, see Sec.~\\ref{sec:ml}.\n\n\n\\subsubsection{Considerations around \\SttVct\\ and \\FrwMdlVct}\n\\label{sec:setup:inverse:xb}\n%\nFormally, \\aCvrMtr{a}\\ shall be set to \\aCvrMtr{\\SttVct}\\ \\citep{rodgers:00},\nthat is, a description of the natural variability (including correlations) of\nthe elements in \\SttVct, but this rule is not always obeyed. First of all,\nnormally there is no manner in which an exact \\aCvrMtr{\\SttVct} can be derived,\nand this matrix is set in some parametric way, loosely based on measurements\nand general knowledge of atmospheric physics. It could also be the case that\n\\aCvrMtr{a}\\ is partly used as a ``tuning parameter''. The most common example\nis that the variances in \\aCvrMtr{a}\\ are set with some margin with respect to\nthe true values, to maintain measurement information as far as possible, or\nexpressed differently, not to constrain the solution more than necessary.\nFurther, it is likely that \\aSttVct{a}\\ differs from the true mean value of\n\\SttVct, and this systematic deviation should also be represented in\n\\aCvrMtr{a}\\ \\citep{eriksson:analy:00}. For a continued discussion, and\ncomments on the relationship between \\aCvrMtr{a}\\ and the corresponding\nregularisation matrix used in ``Tikhonov regularisation'', see, for example,\n\\citet{eriksson:analy:00} and \\citet{ungermann2011tomographic}.\n\nFinally regarding \\aCvrMtr{a}, the point made in Sec.~2.6 of \\citet{rodgers:00}\nis stressed, for given values along the diagonal, setting \\aCvrMtr{a}\\ to be\npurely diagonal means a stronger regularisation than including reasonable\noff-diagonal elements (to reflect correlations). It is a popular mistake to\nthink that this relationship is reversed. Here it should be noted that using a\ndiagonal \\aCvrMtr{a}\\ equals the common choice in Tikhonov regularisation to\nselect the ``smallest norm'' ($\\MtrStl{L}_0$) solution.\n\nThe formally correct choice for \\aCvrMtr{o} is \\aCvrMtr{\\MsrErrVct_o}\n\\citep{eriksson:analy:00,rodgers:00}, but again this theoretical guideline is\nseldomly followed exactly. The normal choice is to set\n$\\aCvrMtr{o}=\\aCvrMtr{\\MsrErrVct_n}$. One important practical consideration is\nthat the inverse of \\aCvrMtr{\\MsrErrVct_o}\\ must be calculated and this is a\nhighly costly operation in the general case, but \\aCvrMtr{\\MsrErrVct_n}\\ is in\ngeneral a pure diagonal matrix and the inverse can be determined with a minimal\ncalculation cost. \n\nFurther, the setting of \\aCvrMtr{o}\\ is influenced by the exact choice of\nvariables included in \\SttVct. As discussed in Sec.~4.1.2 of \\citet{rodgers:00}\nthere is no strict division line between \\SttVct\\ and \\FrwMdlVct. Obviously,\n\\SttVct\\ must contain a representation of the quantities targeted by the\nmeasurements, but for variables of interfering character (e.g.\\ frequency\noff-set) there is a choice to make. For a perfectly linear retrieval case, exactly\nthe same results will be obtained for the target quantities independent of whether\ninterfering factors are covered by \\SttVct\\ or \\FrwMdlVct. However, inclusion\nin \\SttVct\\ is to prefer as this will result in that values describing the\ninterfering effects are obtained, which can provide important diagnostic\ninformation (e.g.\\ to detect instrumental changes). In addition, in a\nnon-linear situation a more optimal solution is obtained by placing interfering\nfactors in \\SttVct, as it is likely that \\aWfnMtr{\\FrwMdlVct}, and then also\n\\aCvrMtr{\\MsrErrVct_o} (cf.\\ Eq.~\\ref{eq:So}), varies with \\SttVct. That is,\nthe description of observation uncertainties is likely to deteriorate with\nthe deviation between $\\SttVct$ and $\\aSttVct{a}$. If interfering species are part\nof \\SttVct, such non-linear effects will be taken care of by the reevaluation of \n\\aWfnMtr{\\SttVct}.\n\n\n\\subsection{Forward model}\n\\label{sec:setup:forward}\n%\nSome basic requirements on the forward model were introduced in\nSec.~\\ref{sec:rt}. The simulation problem to be tackled is basically the\nsimplest possible, Eq.~\\ref{eq:rteq} should be handled by all forward models\nfor passive microwave measurements (but limb sounding requires that refraction\nand the spherical shape of the Earth is considered when determining the\npropagation path, which excludes all ``plane-parallel'' models). On the other\nhand, the analysis of some \\smr\\ data requires non-standard forward model\nfeatures: the 118\\,GHz oxygen measurements give rise to a demand for treatment\nof Zeeman effects, and Doppler effects due to winds could have a significant\nimpact on mesospheric spectra.\n\nBeside the atmospheric radiative transfer, the second main task of the forward\nmodel is to incorporate effects of sensor characteristics. For the \\smr\\\nradiometer package the sensor features needing consideration are antenna\nangular response, mixer, sideband filtering and frequency response of each\nspectrometer channel. Compensation of the Doppler shift due to\nthe satellite's movement is part of the L1b processing.\n\nA further requirement is that the forward model can deliver the Jacobian\n(\\aWfnMtr{\\SttVct}), a demand that should be clear from Eq.~\\ref{eq:lindy}.\nThis task must be handled for all quantities that can be part of the state\nvector. That is, the Jacobian is needed not only for the relevant atmospheric\nvariables (VMRs, temperature and winds), but also fitting of various sensor\nimperfections must be handled (pointing off-set, frequency off-set and baseline\nfit), see further Sec.~\\ref{sec:x}.\n\nIn contrast to many other satellite missions \\citep[e.g.][]{read2006clear}, no\n\\smr\\ specific forward model has been developed. Instead, the general forward\nmodel \\ARTS\\ (\\ARTSlong) is used for \\smr\\ L2 processing. Earlier operational\nL2 processing \\citep{urban:odins:05-b} made use of the first \\ARTS\\ version\n\\citep{buehler:artst:05}, as well as the Moliere forward model\n\\citep{urban2004moliere}), while the retrievals described in this document are\nbased on the latest version (version 2.3). At this point it is just noted that\n\\ARTS\\ complies fully with the demands listed above, and the presentation of\n\\ARTS\\ is continued in Chapter~\\ref{chapter:arts}.\n\n\n\n\\section{Non-standard retrievals}\n\\label{sec:nonstandard}\n%\nAs mentioned already in Sec.~\\ref{sec:aim}, the operational retrievals do not\nhandle all \\smr\\ measurements. Most importantly, scattering is not activated in\nthe forward model simulations and special retrievals have been developed to\nextract information from spectra containing tropospheric information.\nThis retrieval scheme was introduced by \\citet{rydberg:nonga:09} and the latest\nresults are found in \\citet{eriksson:overw:14}. However, the method of\n\\citet{rydberg:nonga:09} is only applicable for tangent altitudes below 9\\,km\nand latitudes between 30$^\\circ$S and 30$^\\circ$N. This leaves a gap between\nthe operational and the tropical-tropospheric retrievals, and there are\nstill \\smr\\ spectra that are not part of any inversion. \n\nThe operational processing is of 1D character (Sec.~\\ref{sec:arts:config}), as\nthe standard limb scanning pattern of \\smr\\ does not provide a basis for\nresolving along-track features. However, Odin has during some shorter periods\nmade measurements dedicated to polar mesospheric clouds. During these\nmeasurement campaigns, Odin has just scanned over a narrow altitude region in\norder to enhance the along-track resolution. Accordingly, to maintain the\nmeasurement information of these special observations, 2D (or tomographic)\nretrievals were needed. These retrievals were also made by combing \\OEM\\ and\n\\ARTS\\ but are presented separately, in \\citet{christensen:tomog:15}.\n\n\n\n%%% Local Variables: \n%%% mode: latex\n%%% TeX-master: \"L2_ATBD\"\n%%% End: \n", "meta": {"hexsha": "a7b86bcb1b658a84a84a5baf8022bbb29e70589b", "size": 21700, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "L2_ATBD/overview.tex", "max_stars_repo_name": "Odin-SMR/docs", "max_stars_repo_head_hexsha": "19a7fea949a8839897f511bc8ddc6abbb52e9cb0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "L2_ATBD/overview.tex", "max_issues_repo_name": "Odin-SMR/docs", "max_issues_repo_head_hexsha": "19a7fea949a8839897f511bc8ddc6abbb52e9cb0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-09-28T09:28:13.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-12T13:45:33.000Z", "max_forks_repo_path": "L2_ATBD/overview.tex", "max_forks_repo_name": "Odin-SMR/docs", "max_forks_repo_head_hexsha": "19a7fea949a8839897f511bc8ddc6abbb52e9cb0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-05-18T15:26:54.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-18T15:26:54.000Z", "avg_line_length": 50.0, "max_line_length": 158, "alphanum_fraction": 0.7782949309, "num_tokens": 6418, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.3345894279828469, "lm_q1q2_score": 0.17252097265832755}}
{"text": "\\chapter{Orbital workflow} \\label{workflow}\n\nTo appreciate the scope of the design and implementation Skylab, we detail the major work processes that the various user roles need to accomplish during an iteration (one year's cohort) of Orbital. We describe the workflow for Orbital students first, and circle back to describe the workflows of other supporting roles in the process.\n\n\\section{Registration} \\label{registration}\n\nTo enroll in the Orbital program, students will need to register in Skylab first. When a user first logs into Skylab, a \\textit{User} object will be created for user. And since it is the first time the user logs in to the system, there is no existing role assigned to current user in current cohort. Then Skylab assumes that the user is trying to register and therefore a link to registration will be displayed. This workflow works for most users who are students in Orbital program. As for roles like \\textit{Adviser}, \\textit{Mentor} and \\textit{Tutor}, admin users will create those roles manually. This is because there are only a few such roles and they have higher privileges and therefore creation of such roles should definitely be controlled by admin users.\n\nFor students' registration, after a user click the registration link, a form consisting of different questions will be presented to the user. Among these questions, several are to get a sense of what sort of interests the user has for the project over the summer. The user is supposed to select interested topics from different categories like programming language, web framework or mobile platform, IDE or text editor, e-commerce, cloud platform, purpose, embedded system, game framework, content management system and audience. These information will be recorded for match-making among students who need to find a teammate in Skylab.\n\nAfter completing the registration form, if the user already has a teammate in mind, he/she can send an invitation to the potential teammate to form a team. Some users, on the other hand, do not have anyone to partner with for Orbital yet and a match-making algorithm will be run offline by admin user based on the interested topics they have selected during registration. An illustration of the whole workflow is as Figure~\\ref{fig:RegistrationWorkflow}.\n\n\\begin{figure}[h]\n \\centering\n \\includegraphics[width=\\textwidth]{Images/Skylab_Registration_Workflow.png}\n \\caption{Illustration of registration workflow in Skylab}\n \\label{fig:RegistrationWorkflow}\n\\end{figure}\n\n\\subsection{Match making algorithm}\n\nFor students who do not have potential teammates at the time of registration, we will run a matching making algorithm based on the interested topics recorded in registration form submission. The algorithm composes of mainly two steps:\n\n\\begin{itemize}\n \\item Calculate inverse document frequency of tags: inverse document frequency is to reflect how rare a term is in the corpus\\cite{citationir}. In Skylab's match making's case, a document is a user's selection of interested topics, or tags; the corpus is the collection of users' interested topic sets; a term is a tag in a users' selections. If a term(tag) is rare among registration form results, we will be more confident that if both students choose this term and they will have higher chance of forming a team. The formula of calculation is as Formula~\\ref{eq:idf}.\n\n \\begin{equation}\n idf(t,D) = \\log \\frac{N}{\\{ d \\in D : t \\in d \\} + 1} \\\n \\label{eq:idf}\n \\end{equation}\n \n with \\(N\\) as total number of documents in the corpus \\( N = |D| \\) and \\(\\{ d \\in D : t \\in d \\}\\) as number of documents where the term \\(t\\) appears\\cite{citationir}.\n\n \\item Construct a vector space model based on students' selected tags and each tag's weight calculated in previous step and calculate similarity(cosine) of different students. The formula for calculating cosine of two vectors is as Formula~\\ref{eq:veccos}\\cite{citationvecspacemodel}.\n\n \\begin{equation}\n \\cos\\theta = \\frac{d_2 \\cdot q}{ \\norm{d_2} \\norm{q} } \\\n \\label{eq:veccos}\n \\end{equation}\n\n And we represent a user's interested topics with tags' weights and the similarity between 2 users will be the cosine between 2 vectors representing the 2 users. The formula for calculating cosine of two vectors is as Formula~\\ref{eq:similarity}\\cite{citationvecspacemodel}.\n\n \\begin{equation}\n sim(d_j, q) = \\frac{d_j \\cdot q}{ \\norm{d_j} \\norm{q} } \\ = \\frac{sum_{i=1}^{N} \\omega_{i,j} \\omega_{i,q}}{ \\sqrt{sum_{i=1}^{N} \\omega_{i,j}^2} \\sqrt{sum_{i=1}^{N} \\omega_{i,q}^2}} \\\n \\label{eq:similarity}\n \\end{equation}\n\n\\end{itemize}\n\nAs matching making only needs to be run once before Orbital officially starts for those students who do no have a team yet, the algorithm is currently designed to run offline as a rake task. Currently it is only for students but in the future with recoding of mentors' and advisers' interested tags, this algorithm can be easily extended to students and mentors or students and advisers as well.\n\n\\section{Submission} \\label{submission}\n\nStudents in Orbital are supposed to report their progress regarding their project at each milestone via \\textit{Submission}. Basically a submission contains 3 parts:\n\n\\begin{itemize}\n \\item README: highlights what are the changes and new features in the project.\n \\item Project Log: a summary of work done during the phase and time used for each task.\n \\item Video link: a link to a video introducing the project to evaluators.\n\\end{itemize}\n\nAs the structure of \\textit{README} and \\textit{Project Log} is free and we should allow creativity of students when it comes to describing their own projects, we decided to support rich text for submissions and there are some issues coming along with this decision such as SQL injection and XSS attacks. What is more, during use of Skylab, many good suggestions regarding user experience were brought up by students and advisers, like uploading of images and auto-expanding textareas during editing.\n\n\\subsection{Handling of rich text}\n\nWe used TinyMCE to support rich text editing feature in Skylab as it is a very popular WYSIWYG(what-you-see-is-what-you-get) editor with a rich set of features\\cite{citationtinymce}. There are some libraries with markdown syntax supported such as EpicEditor, Vue.js and Hallo.js which are more lightweight. However, as Skylab is built for freshmen to get more hands-on experience with coding, we do not expect students to be equipped with much prior knowledge such as markdown syntax. In the contrast, markup based editors such as TinyMCE and CKEditor do not require any learning and are easily to get started with. What is more, the large community using TinyMCE has made various plug-ins available for different features. There are also quite good resources online about integrating TinyMCE editor in a Rails project. Therefore, we decided to use TinyMCE for \\textit{Submissions}' rich text support.\n\nOne particular disadvantage of using TinyMCE is that the size of this editor is pretty large and loading of the page will be slowed down because of it. Therefore, TinyMCE related resources is only loaded if the page is requiring rich text editing. This is done by configuration to disable auto loading of all JavaScript, which is the default behavior of Rails. In this way, most pages can be loaded within a very short time. What is more, assets whose names start with ``tinymce'' are set to expire in a year to reduce frequent requesting of such resources from clients --- which basically means students only need to load these resources once in one year.\n\nRails has built-in checking against SQL injection attacks and therefore Skylab is safe from such attacks when storing submissions' contents\\cite{citationrorsecurity}. However, there is still currently a known bug in the implementation when it comes to viewing of submissions. As contents like \\textit{README} and \\textit{Project Log} should be rendered as rich text, it is possible for students to perform XSS attacks by injecting executable JavaScript code in the submission. This sort of vulnerabilities will be fixed in the future.\n\n\\subsection{Usability}\n\nSkylab is a software engineering project and therefore improvements in user experience is one key part when it comes to implementation. During the use of Skylab, many suggestions were brought up by students and advisers about usability. And by addressing these issues, Skylab is serving users better with a smoother user experience.\n\n\\subsubsection{Target Milestone Selection}\n\nWhen Skylab was used for the first time, students were expected to choose the target milestone, which the submission is for. However, many students reported that it is just a redundant step as every time they will only submit to the currently active milestone. After hearing this, a quick fix of automatically selecting the current milestone for students using JavaScript functions was done, while the manual selection is still possible. And then during the \\textit{Adviser Focus Group Meeting}, some advisers further pointed out that the selection should not even be presented to users as it is of completely no use and therefore the whole selection was completely removed from Skylab after the meeting by moving the task to the backend logic. \n\n\\subsubsection{Rich Text Editing}\n\nAs quite some students want to insert image to \\textit{README} sections, an image uploading feature was soon added to submission page for users' convenience. Behind the scene Skylab is using a third-party API from Imgur. This was done mainly for 2 reasons: using Imgur is relatively easy to implement; we can also avoid heavy server load due to file uploading and possible attacks in uploaded files.\n\nAnother improvement over user experience is auto expanding of TinyMCE editing area as feedback from students mentioned that their \\textit{README} and \\textit{Project Log} are usually quite lengthy. So auto expanding would not require too much scrolling during creating/editing a submission.\n\n\\section{Peer Evaluation} \\label{peerevaluation}\n \n After students have submitted to milestones, peer evaluation process can begin. Teams will look through evaluated teams' projects and submissions and then evaluate their performance in \\textit{PeerEvaluation}, which is a very important component in determining whether the evaluated teams can pass Orbital or not. Although there are different questions for each peer evaluation, all evaluations contains essentially 2 parts:\n\n \\begin{itemize}\n \\item Public: a section with general feedback on how well the evaluated team has done and the response will be viewed by target team with evaluator team name available.\n \\item Private: a section with critiques and overall rating. Critiques will only be viewed by target team without any evaluator team information while overall rating is only for grading purpose and not viewable by target teams.\n\\end{itemize}\n\n\\subsection{Loading of Peer Evaluation templates}\n\nWhen Skylab was first developed, the public part of a \\textit{PeerEvaluation} templates will be one HTML form and the private part is another one. This means all questions in the public part are coded in one predefined html template and same goes for questions in private part.\n\nThis approach does not seem to have much problem at first and it really served Skylab's purpose well by delivering perfectly workable features in time. However, since questions are different for different milestones, separate templates have to be created for each new milestone. And when user wants to view/submit/edit a \\textit{PeerEvaluation}, the corresponding templates will have to be loaded based on properties of the milestone. In this way, the system is not really open to extension and clearly it violates Open-Close principle. After realizing this, a system for dynamically creating questions has been implemented for \\textit{Feedback} and migration of \\textit{PeerEvaluations} to the survey-template-and-questions based system has been done as well. A more detailed description for how the dynamic loading of questions is in Section~\\ref{feedback}.\n\n\\section{Feedback} \\label{feedback}\n\n\\textit{Feedback} is for evaluated teams to evaluate the \\textit{PeerEvaluations} they have received and it is also a very important component in determining whether the evaluator team can pass or not. After realizing the lack of extensibility in the design for \\textit{PeerEvaluations} and with more time available for implementation of \\textit{Feedback}, a survey-template-and-questions system has been set up, which made the system open to extensions for more questions and even question types.\n\n\\subsection{Survey-template-and-questions system}\n\nThe basic flow when a request to create a \\textit{Feedback} is illustrated in Figure~\\ref{fig:FeedbackFlow}.\n\n\\begin{figure}[h]\n \\centering\n \\includegraphics[width=0.8\\textwidth]{Images/Skylab_Feedback_Flow.png}\n \\caption{Flow of a feedback creation process}\n \\label{fig:FeedbackFlow}\n\\end{figure}\n\nSo when a student clicks the button to create feedback, \\textit{FeedbacksController}'s \\textit{new} action will be invoked and inside the method, the corresponding \\textit{SurveyTemplate} and all \\textit{Questions} belonging to the \\textit{SurveyTemplate} will be sent to view. Then instruction for the \\textit{Feedback} and all questions will be rendered as response to the student. After the student completed and pressed submit button, responses to all questions will be sent to server and a Feedback instance containing all submitted responses will be created.\n\nThere currently 4 types of \\textit{Questions} in the system as Figure~\\ref{fig:SkylabQuestions}:\n\n\\begin{itemize}\n \\item \\textbf{TextQuestion}: a text question which will be rendered in the format of textarea and text-based responses are expected. \n \\item \\textbf{RichTextQuestion}: a rich text question which will be rendered in the format of TinyMCE editable area and rich text is expected as response.\n \\item \\textbf{MultipleChoiceQuestion}: a multiple choice question which will be rendered as radio buttons followed by option descriptions and one option value is expected.\n \\item \\textbf{MultipleSelectQuestion}: a multiple choice question which will be rendered as a select element with ``multiple'' enabled with each option as one choice of selection.\n\\end{itemize}\n\n\\begin{figure}[h]\n \\centering\n \\includegraphics[width=\\textwidth]{Images/Skylab_Questions.png}\n \\caption{All types of questions in Skylab}\n \\label{fig:SkylabQuestions}\n\\end{figure}\n\nAll types of question will have \\textit{title}, \\textit{instruction}, \\textit{content}, \\textit{extras} and \\textit{question\\_type} and each type of question will have its own way of rendering and validation. In this way, adding new types of questions can simply be done via creating a new question model with its own rendering and validation methods.\n", "meta": {"hexsha": "83bcfa9100ebf9cbf89df5b011afcf293fae2fa9", "size": 14890, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "docs/2015_2016_Sem2_Final_Report/Chapters/Chapter_Workflow.tex", "max_stars_repo_name": "w-yuchen/nusskylab", "max_stars_repo_head_hexsha": "c79b9c44dcc7fae1a44555357f34a8217450c737", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 26, "max_stars_repo_stars_event_min_datetime": "2015-05-11T06:58:50.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-24T14:11:10.000Z", "max_issues_repo_path": "docs/2015_2016_Sem2_Final_Report/Chapters/Chapter_Workflow.tex", "max_issues_repo_name": "w-yuchen/nusskylab", "max_issues_repo_head_hexsha": "c79b9c44dcc7fae1a44555357f34a8217450c737", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 755, "max_issues_repo_issues_event_min_datetime": "2015-03-19T12:39:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T22:09:42.000Z", "max_forks_repo_path": "docs/2015_2016_Sem2_Final_Report/Chapters/Chapter_Workflow.tex", "max_forks_repo_name": "w-yuchen/nusskylab", "max_forks_repo_head_hexsha": "c79b9c44dcc7fae1a44555357f34a8217450c737", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 53, "max_forks_repo_forks_event_min_datetime": "2015-11-30T16:26:02.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-29T15:26:35.000Z", "avg_line_length": 110.2962962963, "max_line_length": 901, "alphanum_fraction": 0.795567495, "num_tokens": 3280, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3415824927356586, "lm_q1q2_score": 0.17212552583420318}}
{"text": "% Chapter Template\n\n\\chapter{Topical n-grams model} % Main chapter title\n\n\\label{topicalngram} % Change X to a consecutive number; for referencing this chapter elsewhere, use \\ref{ChapterX}\n\n\\lhead{Chapter 5. \\emph{Topical n-grams model}} % Change X to a consecutive number; this is for the header on each page - perhaps a shortened title\n\n%----------------------------------------------------------------------------------------\n%\tIntroduction\n%----------------------------------------------------------------------------------------\n\nJoint sentiment and topic models have been used to tackle this classification problem. Despite having a hierarchical structure, these generative models have\na bag of words assumption. Due to this fact, they tend to misclassify texts having sentiment in the form of phrases. \\textit{LDA} and it's extensions don't \nwork properly with phrases. To tackle this situation, we propose an unsupervised approach to sentiment analysis using the topical n-grams model which has been\nshown to be effective with phrases. We train the topical n-grams model using two topics i.e., positive, and negative, list of positive and negative\nwords, and rules to detect positive and negative phrases. New documents are then classified using this trained model. The system gives better results than the \nexisting Joint Sentiment Topic model. We also propose an approach to generate a list of positive and negative words using LDA based on our observations reported in~\\cref{experiments}.\n\n\\section{Introduction}\n\n\n\n\n\nIn the next section, we will discuss the topical n-gram model in detail.\n\n\\section{Topical n-grams model}\n\nn-gram phrases (or collocations) are fundamentally important in many areas of natural language processing (e.g., parsing, machine translation and information retrieval). \nPhrase as the whole carries more information than the sum of its individual components, thus it is much more crucial in determining the topics of document collections \nthan individual words \\citep*{wang2005note}. However, most of the topic models assume that words are generated independently to each other, i.e., under the bag of words\nassumption. The possible over complicacy caused by introducing phrases makes these topic models completely ignore them. It is true that these models with the bag of words\nassumption have enjoyed a big success, and attracted a lot of interests from researchers with different backgrounds. A topic model considering phrases would be more \nuseful in certain applications. Topical n-grams model is one such generative model. It's generative process is explained as follows,\n\n\\begin{enumerate}\n \\item Draw multinomial \\(\\phi_z\\) from a Dirichlet prior \\(\\beta\\);\n \\item Draw binomial \\(\\psi_z\\) from a Beta prior \\(\\gamma\\);\n \\item Draw multinomial \\(\\sigma_{zw}\\) from a Dirichlet prior \\(\\delta\\);\n \\item For each document d, draw a multinomial \\(θ^{(d)}\\) from a Dirichlet prior \\(\\alpha\\); then for each word \\({w_i}^{(d)}\\) in document \\(d\\),\n \\begin{enumerate}\n \\item Draw \\({x_i}^{(d)}\\) from binomial \\(\\psi_{{w_{i-1}}^{(d)}}\\);\n \\item Draw \\({z_i}^{(d)}\\) from multinomial \\(\\theta_{(d)}\\);\n \\item Draw \\({w_i}^{(d)}\\) from multinomial \\(\\sigma_{{w_{i-1}}^{(d)}}\\) if \\({x_i}^{(d)} = 1\\); else draw \\({w_i}^{d}\\) from multinomial \\(\\phi_{{z_i}^{(d)}}\\).\n \\end{enumerate}\n\\end{enumerate}\n\nThe main point to infer from this generative process is that the topic assignments for the two terms in a bigram are not required to be identical. In the description of\ntopic n-grams given in \\citep*{wang2005note}, they have used the topic of the last term as the topic of the phrase. But in our experiments, we have used certain rules\nas prior information to assign topics to a phrase initially.\n\n\n\\includegraphics[width=\\textwidth]{topicalngram.png} \n\\begin{center}\n Figure 5.1 Topical n-grams model\n\\end{center}\n\n\\subsection{Inferencing}\n\nGibbs sampling is used to conduct approximate inference in this paper. During Gibbs sampling, we draw the topic assignment \\(z_i\\) and the bigram status \\(x_i\\) \niteratively for each word \\(w_i\\) according to the following conditional probability distribution:\n\n\\begin{equation}\np(z_i,x_i | z_{-i},w_{-i},w,\\alpha,\\beta,\\gamma,\\delta) \\propto\n\\frac{\\gamma_{x_i} + p_{z_{i-1}w_{i-1}x_i}}{\\sum_{k=0}^1 {(\\gamma_k+p_{z_{i-1}}w_{i-1}k)}} {(\\alpha_{z_i} + q_{d_{z_i}})} \\times \\left\\{ \n \\begin{array}{l l}\n \\frac{\\beta_{w_i} + n_{z_i w_i}}{\\sum_{v=1}^V {(\\beta_v+n_{z_i v})}} & \\quad \\text{if $x_i$ is even}\\\\\n \\frac{\\delta_{w_i} + m_{z_i w_{i-1} w_i}}{\\sum_{v=1}^V {(\\delta_v + m_{z_i w_{i-1} v})} } & \\quad \\text{if $n$ is odd}\n \\end{array} \\right.\n\\end{equation}\n\nwhere, \n\n\\(z_{-i}\\) denotes the topic assignments for all word tokens except word \\(w_i\\), \\\\ \n\\(x_{-i}\\) represents the bigram status for all tokens except word \\(w_i\\), \\\\ \n\\(n_{zw}\\) represents how many times word \\(w\\) is assigned into topic \\(z\\) as a unigram, \\\\\n\\(m_{zwv}\\) represents how many tmes word \\(v\\) is assigned as the second term of a bigram given the previous word \\(w\\), \\\\\n\\(p_{zwk}\\) denotes how many times the status variable \\(x\\) equals \\(k\\) given the previous word \\(w\\) and previous word's topic \\(z\\), and \\\\\n\\(q_{dz}\\) represents how many times a word is assigned to topic \\(z\\) in document d.\n\nIn next section, we will explain the use of topical n-grams model for sentiment analysis\n\n\\section{Topical n-grams model for Sentiment Analysis}\n\nTo make use of topical n-grams model for sentiment classification, we use an approach similar to using LDA for sentiment classification.\n\n\\begin{itemize}\n \\itemsep0em\n \\item Set number of topics equal to 2.\n \\item Remove stop-words.\n \\item Remove objective words as they won't affect sentiment. The objective words in this case do not include the negation words like \\textit{doesn't, \n won't, no}, etc. This is to ensure that we can catch negation of polarity when they are used with subjective words.\n \\item Apply Gibbs Sampling with prior. The prior used in this case is more sophisticated and can handle both words and phrases. In case of words, if\n is not present in a bigram then simply use a list of positive and negative words to assign positive or negative topic. If the word is present in a \n bigram then assign it the topic of the bigram. There are some rules to detect and assign topics to bigrams which are explained next.\n \\item Use the trained model to classify a new document as positive or negative.\n\\end{itemize}\n\n\\subsubsection*{Rules for Topic assignment of phrases}\n\nAt present, our rules are restricted to bigrams. We plan to extend them as explained in Section~\\cref{conclusions}.\nIn the following rules, we mean topic when we say polarity. The use of polarity makes it easy to understand\nthe rules as they are concerned with subjectivity.\n\n\\begin{enumerate}\n \\itemsep0em\n \\item If the first word in the bigram is a negation word and the second word is subjective then the polarity\n of the bigram is opposite to the polarity of the second word. \\\\\n \\textbf{Examples:} \\textit{won't like, won't regret, etc.}. Here, \\textit{won't like} is assigned negative\n polarity and \\textit{won't regret} is assigned positive polarity.\n \\item If both the words in the bigram are subjective then are two cases. If both words are of the same polarity\n then resultant polarity is the same. But if their polarities are different, then the polarity of the first word\n is assigned to the bigram. \\\\\n \\textbf{Examples:} \\textit{beautifully amazing} is positive as both words as positive. \\textit{lack respect} is\n assigned negative as per the rules.\n\\end{enumerate}\n\nOne salient feature of this approach is that it is an unsupervised method and can work on any domain. \n\n\\section*{SUMMARY}\n\nIn this chapter, we dicussed the motivation behind the topical n-grams model. Later on, we discussed the inference equation used by it. At the end,\nwe proposed an approach to use this model for sentiment analysis. The experiments and results obtained are discussed in ~\\cref{experiments}.\n\nIn the next chapter, we will show the use of deep semantics for sentiement analysis.", "meta": {"hexsha": "700fa32ce858aa3d6059519f08220874d5d94103", "size": 8105, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Report/tex_files/Chapters/topicalngram.tex", "max_stars_repo_name": "nikolodien/Paper-submissions", "max_stars_repo_head_hexsha": "3b1b8b0b3b33d3728f000a4260aa2e264df39079", "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/tex_files/Chapters/topicalngram.tex", "max_issues_repo_name": "nikolodien/Paper-submissions", "max_issues_repo_head_hexsha": "3b1b8b0b3b33d3728f000a4260aa2e264df39079", "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/tex_files/Chapters/topicalngram.tex", "max_forks_repo_name": "nikolodien/Paper-submissions", "max_forks_repo_head_hexsha": "3b1b8b0b3b33d3728f000a4260aa2e264df39079", "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": 64.3253968254, "max_line_length": 183, "alphanum_fraction": 0.7322640345, "num_tokens": 2057, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.33111975283019596, "lm_q1q2_score": 0.1720237717147937}}
{"text": "\n\\section{Calibration and detector behavior\\label{sec:strategy}}\n\n\\subsection{Calibration}\n\nThis section describes how different correction factors are obtained: the energy calibration (MIP, $\\pi^{0}$, run by run), the time calibration and the bad channel mask.\\\n\nAll these correction factors or masks are stored in the OCDB but also the OADB. Since these calibration parameters do not arrive before the full ALICE data reconstructions of the first periods are completed, the parameters are stored not only in the OCDB but also in the OADB so that the clusters can be corrected at the analysis level. For the moment we do not store the time calibration and run by run correction factors in OCDB just in OADB.\n\n\\subsubsection{Energy calibration: MIP calibration before installation - Julien}\nFirst, the calibration is done on cosmic measurements before installing the SuperModules at P2, but the accuracy obtained using MIPs is not good enough.\n\n\\subsubsection{Energy calibration: $\\pi^{0}$ - Catherine}\n\nThe energy calibration relies during data taking on the measurement of the $\\pi^{0}$ mass position per cell. Each tower has a calibration coefficient. In what follows, a calibration parameter is equal to the result of the fitted mass over the PDG mass value, where the fitted mass denotes the mass given by a gaussian fit on the $\\pi^{0}$ invariant mass peak distribution in a given tower (plus a combinatorial background, fitted by a 2nd degree polynomial).\nAbout 100-200 M events EMCAL (L0) triggered (trigger threshold at 1.5-2 GeV) allow to calibrate a majority of the towers. The towers located on rows 0 and 23 of each super modul (SM ) and those behind the support frame (about 5 columns per SM) have much fewer statistics and would need a minimum of 150 Mevts (probably more). It is to be noted that the run-to-run temperature variations change the towers' response in a non-uniform way, i.e. the width of the $\\pi^{0}$ peak increases, and the mean $\\pi^{0}$ mass is shifted differently for the various towers. Also the $\\pi^{0}$ mass shifts to lower values for the towers with material in front, due to photoconversion close to the EMCAL surface.\n\nA few iterations on the data, obtaining in each iteration improved calibration coefficients, are needed to achieve a good accuracy (1-2\\%). Since the online calibration has a strong effect on the trigger efficiency, the voltage gains of the APDs are varied after each running period, to get a uniform trigger performance. Still, some towers are difficult to calibrate because they are behind of a lot of material (TRD support structures). For those MIPs or $J/\\Psi$ measurements could help.\n\n\\paragraph*{$\\pi^{0}$ Calibration Procedure\\\\}\n\nSince $\\pi^{0}$s decay into 2 gammas, their invariant mass is calculated from the energy of 2 clusters (and angle between the clusters). The position of the invariant mass peak of a tower therefore doesn't depend only on its response and calibration coefficient, but also on an average of the responses and calibration coefficients of all the other towers of the SM, weighted by how often they appear in combination with a cluster in the considered tower. The 2nd effect, of weaker magnitude maybe, originates from the fact that a cluster most often covers more than the considered tower. To simplify the calibration process, the calibration coefficient is calculated as if the whole energy of the cluster was contained in the tower of the cluster which has the largest signal. So the position of the invariant mass peak of a tower also depends on an average of the responses and calib coeffs of its neighbouring towers. For these reasons, the calibration of the calorimeter with the $\\pi^{0}$ is an iterative procedure :\n\\begin{itemize}\n\\item Set all calib coeffs to 0 in OCDB.\n\\item Reconstruct the $\\pi^{0}$'s with these OCDB coeffs.\n\\item Run the analysis code on this data to produce the analysis histograms and a 1st version of the calib coeffs.\n\\item Look at the fits on the towers invariant mass histograms and discard the value (or set it by hand) of the calib coeff of the towers for which the fit can't be trusted.\n\\item Create a 1st set of OCDB coeffs.\n\\item Reconstruct the $\\pi^{0}$'s with these OCDB coeffs.\n\\item Run the analysis code on this data to produce the analysis histograms and a 2nd version of the calib coeffs.\n\\item Look at the fits on the towers invariant mass histograms and discard the value (or set it by hand) of the calib coeff of the towers for which the fit can't be trusted.\n\\item Create a 2nd set of OCDB coeffs.\n\\item Etc..., until the invariant mass is satisfactory in all the towers.\n\\end{itemize}\nWhen the statistics is enough, 4 iterations should be enough to finalize the calibration (in practice, more are needed, due to outliers or studies that are needed).\n\nThere are 3 sets of codes :\n\\begin{itemize}\n\\item Reco code : reads the data, reconstructs the $\\pi^{0}$ inv mass distrib in each tower after it applies some cuts on the clusters and $\\pi^{0}$ parameters. The output is a root file with invariant mass histograms (per tower, and summed-up per SM, per pT-bin).\n\\item Analysis code : reads the file produced by the reco code and analyses the histograms to produce the calib coeffs. This code is the one I present in what follows.\n\\item A code which reads the calib coeffs and writes them into a format that is loadable to OCDB.\n\\end{itemize}\nThe code is located in EMCAL/calibPi0/ :\n\\begin{itemize}\n\\item macros/ : contains the various macros.\n\\item input/ : contains the root files produced by the analysis code for the various iterations (\"passes\"). It has subdirectories \"pass0/\", \"pass1/\", etc... with, in each dir, the root file.\n\\item output/ : contains the various files produced by the analysis code for the various passes. It has subdirectories \"pass0/\", \"pass1/\", etc... with, in each dir, the various output files related to the pass.\\footnote{Note that it wouldn't necessarily help to set-up a code that automatically reads and writes the pass number to avoid the hardcoded directories in the code, because it happens to do several times the same pass with various parameters (e.g. cuts in the reconstruction, or more statistics, or various masked zones, or hand-customization of a few calib coeffs, etc...).}\n\\end{itemize}\n\nThe cuts which must be put in the reconstruction are :\n\\begin{itemize}\n\\item Bad towers masked.\n\\item Both clusters in the same SM (to avoid misalignment effects).\n\\item Cut the 1-tower clusters out.\n\\item 20~ns timing cut.\n\\item Non-linearity correction (for the cluster energy)-- from beam test AFAIK.\n\\item No asymetry cut.\n\\item $E_{cluster} > 0.8$ ~GeV, or 0.7 GeV if there is little statistics. Tests showed that to remove the residual non-linearity (the $pi_{0}$ invariant mass rises with $p_{T}$), tightening the cut on $E_{cluster}$ was more efficient than requiring symetric decays (both gamma's of similar energy) (e.g. $asym < 0.5$ with $E_{gamma} > 0.5$~GeV).\n\\end{itemize}\nIt has the possibility to mask some areas. This is useful to disentangle the zones which have more material in front of them from those which don't. In the invariant mass distributions, the $\\pi^{0}$ candidates kept are only those for which both clusters belong to the non-masked zones. In 2011, we considered masking the zones behind the support frame (in all the SMs or only in the SMs with TRD modules in front of them, i.e. SM 6-9 that year), plus additionnal problematic zones, to avoid taking clusters in these zones for the calculation of the average invariant mass in the towers with less material. (NB : not used for final calibration results, but for studies).\n\nThe analysis code has 3 input files :\n\\begin{itemize}\n\\item the root file f05 with inv mass histograms produced by the reconstruction code,\n\\item a file txtFileIn (output\\_calibPi0\\_parameters.txt) that contains the values of various parameters of the fit for each tower, at the previous pass,\n\\item a file txtFilePrevCalib (output\\_calibPi0\\_coeffs\\_clean.txt) that contains the value of the calibration coefficient for each tower, at the previous pass (and after the hand-made corrections).\n\\end{itemize}\nThe 2 last files are therefore useless for the \"pass0\". To run the code for \"pass0\" (1st iteration), put the name of a valid file (e.g. one of last year) and just ignore the plots (red colour, in the last section -- see below).\n\nThere are 4 output files, that are written in the current directory (calibPi0/) : be careful not to overwrite an existing file ! After the code has been run, simply move those files to the relevant passXX directory := output/passXX/=.\n\\begin{itemize}\n\\item a postscript file psfile (output\\_calibPi0.ps) with the plots described below,\n\\item a root file rootFileOut (output\\_calibPi0.root) that contains the same plots in root format,\n\\item a file txtFileOut (output\\_calibPi0\\_parameters.txt) that contains the values of various parameters of the fit for each tower, for the current pass,\n\\item a file outputFile (output\\_calibPi0\\_coeffs.txt) that contains the value of the calib coeff for each tower, for the current pass.\nOnce the code has been run and the output files copied to the relevant output directory, I copy output\\_calibPi0\\_coeffs.txt to output\\_calibPi0\\_coeffs\\_clean.txt, and modify the latter by hand to put the desired calib coeffs where we estimate that they can't be trusted.\n\\end{itemize}\n\n9 parameters are defined to qualify the invariant mass distribution in each tower : the distribution is fitted by a gaussian + pol2 for the combinatorial background. The parameters are :\n\\begin{itemize}\n\\item amplitude of gaussian fit,\n\\item mean of the gaussian fit,\n\\item sigma of the gaussian fit,\n\\item c, b and a parameters of the combinatorial background fit $ax^2+bx+c$, I (histo integral),\n\\item I-S, S (integral of the gaussian fit). Minimal and maximal cut values are hardcoded (and to be changed at each iteration) for each parameter.\n\\end{itemize}\nWhen the value of all the parameters lie between both extremes, the tower (i.e. the fit values, hence the mean, hence the calculated calib coeff) is \"trusted\". If one or more parameter has a value beyond the max cut value or below the min cut value, the tower is \"untrusted\".\nBecause these cut values can't be guessed in advance, the analysis code must be run twice per pass. The 1st time, so as to get the distributions of all 9 parameters, and decide on the basis of those distributions what are the suitable cut values to separate the towers to be trusted and those not to be trusted. The values are plugged in the code, and the code is then run a 2nd time, for real this time.\nThe macro (currently called DrawJulienFullEMCAL6.C) runs with 1 parameter in argument (set to 10 by default) : choice, which sets the number of SMs that one desires to include in the analysis. The values are either 4 (for the older SMs), or 6 (for only the newer SMs), or 10 (for the whole EMCAL). Here is the code. The macro is run this way :\n\\begin{lstlisting}\naliroot -b -q 'macros/DrawJulienFullEMCAL6.C++(10)'\n\\end{lstlisting}\nThere are various places where things must be customized before running the code ; they can be spotted by searching for this line : //CUSTOMIZE customize :.\n\\begin{itemize}\n\\item testChoice : this variable is a flag that allows to shorten the execution time for tests. 0 = not a test ; 1 = runs with only the 2 first columns of each SM ; 2 = runs with only the 2 first columns of the first SM,\n\\item the root input file f05,\n\\item the text input file txtFilePrevCalib (in principle not the name, only the path),\n\\item the text input file txtFileIn (in principle not the name, only the path),\n\\item if necessary : the min and max range values for the parameter histograms : tabMin and tabMax,\n\\item the min and max cut values for the parameters cutMin and cutMax,\n\\item if necessary : the number of bins in pT (for the 1st section, see below) nbPtBins and their range tabPtBins.\n\\item Text output on the standard output (\"printf's\") :\n\\end{itemize}\n\nFinally, the first iteration needs the recalibration factors. This file is made running macros/RecalibrationFactors\\_TextToHistoJulien\\_mult\\_2012.C on the output\\_calibPi0\\_coeffs.txt file. Once the RecalibrationFactors.root file is created it needs to be linked properly to re-run the reconstruction.\n\n\n\\subsubsection{Energy calibration: Run by run temperature gain variations - Evi, David }\n\nThe SuperModules calibration depends on the temperature dependence of the different towers gains. We observe that from one period to other, where the T changes, the $\\pi^{0}$ peak positions also changes. There are 2 ways to correct for this effect : either measure the mean T per run, and get the gain curves per tower a calculate the corresponding correction; or use the calibration LED events to quantify the variation from one reference run. Each of those 2 procedures have problems, poor or lack of knowledge of the gain curves of some towers or bad performance of the LED system in certain regions.\nThese temperature or time-dependent corrections are still under study: for further, and up-to-date, information, please see the wiki: \nhttps://twiki.cern.ch/twiki/bin/viewauth/ALICE/EMCalTimeDependentCalibrations\n\n\n\\subsubsection{Time calibration - Marie }\n\nThe time of the amplitude measured by a given cell is a good candidate to reject noisy towers, identify pile up events when coming from different Bunch Crossing, or even identify heavy hadrons at low energy. The average time is around 580 ns. The aim of the time calibration is to do a relative calibration between cells to align all cells to a mean value of 0 ns, with as small spread as possible (negative values are unavoidable for the moment). The time calibration coefficient for each cell is the result of the average time of the cell when belonging to a cluster with enough energy (>1GeV). \nThe calibration coefficient have to be subtracted to the cell time.\n\n\\paragraph*{Time Calibration Procedure\\\\}\n\nSince the some variations of mean time have been observed depending on the bunch cross numbers (BC) $\\%$ 4 the computation of the time coefficients is done for each bunch cross numbers BC$\\%$ 4 scheme.\n\nThe time calibration coefficient computing is done in 2 iterations. \n\\begin{itemize}\n\\item 1$^{rst}$ iteration:\\\\\nGet Bunch Cross Number for the event.\nLoop on all cluster of the event. \\\\ Loop on all cells in the cluster.\nIf cell amplitude is > 0.9 GeV and 500ns < cell time < 700ns then \ncompute average per cell per BC$\\%$4 and fill in 1D histogam with calibration coefficients: hAveragesBC$x$ where $x$ stands for the result of BC$\\%$4.\n\\item 2$^{nd}$iteration:\\\\\nGet Bunch Cross Number for the event.\\\\ \nLoop on all cluster of the event. \\\\ Loop on all cells in the cluster.\\\\ \nGet Calibration coefficient for BC$\\%$4 from hAveragesBC$x$. If cell amplitude is > 0.9 GeV and -20ns < (cell time-cell Calibration Coefficient) < 20ns.\\\\\nCompute average time per cell per BC$\\%$4 and fill in 1D histogam with those new calibration coefficients: hAllAveragesBC$x$.\n\\end{itemize}\n\n\n\\paragraph*{Acces time calibration coefficients\\\\}\n\nThe time calibration coefficient are stored in OADB in TH1D histograms named hAllTimeAvBCx where x stands for the BC$\\%$4 value.\nThey have the usual structure:\nrunrange/pass/\n\nTo use them in your analysis you may do the following:\\\\\n\\begin{DDbox}{\\linewidth}\n\\begin{lstlisting}\n AliOADBContainer *contTRF=new AliOADBContainer(\"\");\ncontTRF->InitFromFile(Form(\"%s/EMCALTimeCalib.root\",fOADBFilePathEMCAL.Data()),\"AliEMCALTimeCalib\");\nTObjArray trecal=(TObjArray)contTRF->GetObject(runnumber);\nif(trecal)\n{TObjArray trecalpass=(TObjArray)trecal->FindObject(pass);\nif(trecalpass)\n{printf(\"AliCalorimeterUtils::SetOADBParameters() - Time Recalibrate EMCAL \\n\");\nfor (Int_t ibc = 0; ibc < 4; ++ibc)\n{\nTH1F *h = GetEMCALChannelTimeRecalibrationFactors(ibc);\nif (h)\ndelete h;\nh = (TH1F*)trecalpass->FindObject(Form(\"hAllTimeAvBC%d\",ibc));\n}}\n\\end{lstlisting}\n\\end{DDbox}\n\nAs already mentioned the time calibration of the cells is not done at the reconstruction level but offline during analysis. The methods to recalibrate cells is implemented in the class \n\\texttt{\\$ALICE\\_ROOT/\\\\EMCAL/AliEMCALRecoUtils}.\nThe method \\texttt{RecalibrateCellTime(absId,bc,time)}: is called by the method \\texttt{SwitchOnTimeRecalibration} , modifies the provided time with the calibration parameters. The inputs are the bunch crossing number that can be recovered from the event with InputEvent()->GetBunchCrossNumber(), and the absolute ID of the cell.\nThe way to pass the calibration parameters to AliEMCALRecoUtils is the following.\\\\ \n\\begin{DDbox}{\\linewidth}\n\\begin{lstlisting}\nAliCalorimeterUtils *cu = new AliCalorimeterUtils ;\nTGeoManager::Import(\"geometry.root\") ; //need file \"geometry.root\" in local dir!!!!\nAliEMCALRecoUtils * reco = cu->GetEMCALRecoUtils();\nand then \nfor(Int_t i =0; i< 4; i++) reco->SetEMCALChannelTimeRecalibrationFactors( i, (TH1F*) file->Get(Form(\"hAllTimeAvBC%d\",i)))\n\\end{lstlisting}\n\\end{DDbox}\n, where TFile *file is in the file containing the time calibration coefficients.\n\nSome more details on time recalibration can be found in twikis:\nhttps://twiki.cern.ch/twiki/bin/\\\\viewauth/ALICE/EMCalCode:HowTo\\#Energy\\_and\\_Time\\_calibration and in \\\\\nhttps://twiki.cern.ch/twiki/bin/viewauth/ALICE/EMCALTimeCalibration\n\n\\subsection{Alignment - Marco}\n\nCERN provides survey measurements of the position of different EMCAL Supermodules points at the beginning of the running period (and on request?). As soon this information is available, the ideal EMCAL positions used in the reconstruction by default, are corrected with special position matrices calculated from the measurements. Finally, once the data is reconstructed, the accuracy of the alignment is cross checked with track matching and $\\pi^{0}$ mass measurements, since those values change depending on variations on the positions of the SuperModules.\n\n\\subsection{Bad channel finding - Alexis}\n\nThe analysis is done on the output of offline Quality assurance see section \\ref{sec:QAOffline} histograms \\texttt{TH2F EMCAL\\_hAmpId} containing the distribution of amplitudes (energy) of cell versus cell Absolute ID number (AbsId). The idea is to check distributions over the cells of different observables extracted from this histograms. Then each cell is tested regarding to the distribution over all the cells for each obbservable. The different tests are the following:\n\n\\begin{enumerate}\n\\item average energy (average computed for Emin< E \n\\]\nThe Requirement Machine}\n\\subtitle{Sound and decidable generic programming for Swift}\n\\author{Slava Pestov}\n\\date{}\n\n\\pagestyle{headings}\n\n\\begin{document}\n\n\\maketitle\n\n\\tableofcontents\n\n\\chapter{Introduction}\n\nThe Swift 5.6 compiler incorporates a new generic programming implementation, dubbed the ``requirement machine''. The goals were to improve the correctness, performance and maintainability of this aspect of the compiler. Internally, the requirement machine is based around confluent rewrite systems.\n\nIt is really best that you have at least a passing familiarity with the Swift language before reading this book; actually \\emph{learning} generic programming by studying how the compiler goes about implementing things might prove to be unnecessarily difficult.\n\nRegardless, in the interest of scoping the effort, defining terminology, and maybe filling in small gaps in your understanding, I'll quickly review Swift's generic programming features in Chapter \\ref{languageoverview}.\n\nChapter~\\ref{history} will give the historical context showing how the evolution of the language and implementation motivated work on the requirement machine.\n\nChapter \\ref{genericsignatures} explains the interface to the requirement machine from the point of view of the rest of compiler; this interface is centered on resolving queries involving type parameters written with respect to a generic signature.\n\nChapters \\ref{monoids}, \\ref{monoidsasprotocols} and \\ref{rewritesystemintro} give an overview of the mathematical theory of confluent rewrite systems that underpins the requirement machine.\n\nChapter \\ref{protocolsasmonoids} will begin to translate this theory into practice, then Chapter~\\ref{associatedtypes} builds up a series of progressively more complex examples showing how rewrite systems can be used to reason about type parameters in a generic signature.\n\nChapter \\ref{requirementmachine} will build upon this intuitive understanding to give a formal definition of the requirement machine rewrite system.\n\nChapter \\ref{propertymap} introduces the ``property map,'' which builds upon the rewrite system and answers queries that cannot be resolved with term rewriting alone. The property map also plays a crucial role in the implementation of superclass and concrete type requirements.\n\nOccasionally, I will find occasion to talk about some specific part of the compiler codebase. Usually this will be tangental to the main point being discussed. These will be demarcated with a vertical bar, and if you're only interested in learning the theory behind the requirement machine, you can skip these sections. If you're planning on contributing to the compiler you can read them. Here's the first one:\n\n\\begin{leftbar}\n\\noindent The source code for the requirement machine is in the \\texttt{lib/AST/RequirementMachine} directory of the Swift source repository.\n\\end{leftbar}\n\n\\chapter{Language Overview}\\label{languageoverview}\n\nSwift supports \\emph{parametric polymorphism}. Functions and types can be equipped with a generic parameter list containing one or more generic parameters, together with a set of requirements which constrain these generic parameters.\n\n\\index{substitution}\nWherever a generic definition is used, the use site substitutes concrete types in place of the definition's generic parameters, and these concrete types in turn must satisfy the requirements imposed on those generic parameters. Unlike the C++ template expansion model where type checking is delayed until concrete substitutions are known, Swift supports separate type checking and compilation of generic definitions across module boundaries. For this reason, the Swift compiler must be able to reason about generic parameters and their requirements abstractly.\n\nThe simplest case is a definition with a single unconstrained generic parameter. Here is the identity function over all possible concrete types:\n\\begin{Verbatim}\nfunc identity(x: T) -> T {\n return x\n}\n\\end{Verbatim}\n\n\\index{protocol}\n\\index{inheritance clause}\nYou can't do much with an unconstrained generic parameter type other than pass its instances around, as the values themselves are completely opaque. In order to manipulate ``the contents'' of generic values, generic parameters must be constrained in some manner. This restricts the set of substitutable concrete types but in turn introduces capabilities on the generic type.\n\n\\index{conformance requirement}\nThe most fundamental kind of constraint is the \\emph{protocol conformance requirement}. A protocol conformance requirement can be stated in a generic parameter's inheritance clause:\n\\begin{Verbatim}\nfunc draw(shape: S, at points: [(Int, Int)]) {\n // shape.draw(x:y:) exists because `shape : S'\n // and `S : Shape'.\n points.forEach(shape.draw(x:y:))\n}\n\nprotocol Shape {\n func draw(x: Int, y: Int)\n}\n\\end{Verbatim}\n\n\\index{associated type}\n\\index{nested type}\nProtocols can define associated types, the canonical example being the lazy iterator protocol from the standard library:\n\\begin{Verbatim}\nprotocol IteratorProtocol {\n associatedtype Element\n mutating func next() -> Element?\n}\n\\end{Verbatim}\nA generic function that takes an iterator and returns its second element can be defined by constraining a generic parameter $\\genericparam{I}$ to $\\proto{IteratorProtocol}$, and declaring a return type of $\\genericparam{I}.\\namesym{Element}$:\n\\begin{Verbatim}\nfunc second(of iterator: inout I) -> I.Element {\n _ = iterator.next() // drop the first element and advance\n return iterator.next()!\n}\n\\end{Verbatim}\nThe \\texttt{second(of:)} function defines one generic parameter, but two \\emph{type parameters} are visible in its lexical scope: $\\genericparam{I}$ and $\\genericparam{I}.\\namesym{Element}$.\n\nAssociated types can also state a protocol conformance requirement, just like generic parameters; for example, you can define the protocol of sequence types which vend an iterator (this version is slightly simpler than what's in the standard library; you'll see the real definition shortly):\n\\begin{Verbatim}\nprotocol Sequence {\n associatedtype Iterator : IteratorProtocol\n func makeIterator() -> Iterator\n}\n\\end{Verbatim}\n% present this after the code example\nA different version of the above \\texttt{second(of:)} that ranges over types conforming to $\\proto{Sequence}$ has \\emph{three} type parameters; $\\genericparam{S}$, $\\genericparam{S}.\\namesym{Iterator}$, and $\\genericparam{S}.\\namesym{Iterator}.\\namesym{Element}$. Notice how all three appear in the definition below.\n\\begin{Verbatim}\nfunc second(of sequence: S) -> S.Iterator.Element {\n var iterator: S.Iterator = sequence.makeIterator()\n _ = iterator.next()\n return iterator.next()!\n}\n\\end{Verbatim}\n\\index{desugaring}\nInstead of stating a protocol conformance requirement in the inheritance clause of a generic parameter, you can attach a more general \\texttt{where} clause to the parent declaration. A \\texttt{where} clause can constrain nested type parameters, not just top-level generic parameters. It can also state more kinds of requirements.\n\\index{where clause}\n\n\\eject\nThe \\texttt{second(of:)} function can be written with a \\texttt{where} clause:\n\\begin{Verbatim}\nfunc second(of iterator: inout I) -> I.Element\n where I : IteratorProtocol {...}\n\\end{Verbatim}\nSimilarly, the $\\proto{Sequence}$ protocol could have used one instead:\n\\begin{Verbatim}\nprotocol Sequence {\n associatedtype Iterator where Iterator : IteratorProtocol\n}\n\\end{Verbatim}\nOr even like this---a \\texttt{where} clause attached to a protocol is no different than one on an associated type (you can even mix both; it's a purely stylistic choice, and in more complicated examples carefully organizing requirements helps readability):\n\\begin{Verbatim}\nprotocol Sequence where Iterator : IteratorProtocol {\n associatedtype Iterator\n}\n\\end{Verbatim}\n\nThe next example shows a requirement that cannot be expressed without using \\texttt{where}. First define a protocol for linearly-ordered types:\n\\begin{Verbatim}\nprotocol Comparable {\n static func <(lhs: Self, rhs: Self) -> Bool\n}\n\\end{Verbatim}\nNow you can define a function ranging over types conforming to $\\proto{Sequence}$ whose element type conforms to $\\proto{Comparable}$:\n\\begin{Verbatim}\nfunc minimum(of elements: S) -> S.Iterator.Element\n where S : Sequence,\n S.Iterator.Element : Comparable {\n // Elements of this iterator are Comparable\n var iterator = elements.makeIterator()\n ...\n}\n\\end{Verbatim}\nA particularly powerful kind of generic requirement---and perhaps the entire reason the requirement machine exists---is the same-type requirement.\n\nSuppose you're working with $\\genericparam{S}$, a generic parameter ranging over $\\proto{Sequence}$. Writing $\\genericparam{S}.\\namesym{Iterator}.\\namesym{Element}$ everywhere will get awkward fast. As I mentioned, the real version of $\\proto{Sequence}$ in the standard library is slightly more complex. Indeed, it defines an $\\namesym{Element}$ associated type in the protocol itself, so that the user can write $\\genericparam{S}.\\namesym{Element}$. Simply adding the associated type definition is not enough, because now $\\genericparam{S}.\\namesym{Element}$ and $\\genericparam{S}.\\namesym{Iterator}.\\namesym{Element}$ are \\emph{different} type parameters and cannot be used interchangeably.\n\n\\index{same-type requirement}\nTo express this restriction that concrete types conforming to $\\proto{Sequence}$ must provide an iterator type compatible with the element type, a \\texttt{where} clause in the protocol can state a same-type requirement:\n\\begin{Verbatim}\nprotocol Sequence {\n associatedtype Element\n where Element == Iterator.Element\n associatedtype Iterator : IteratorProtocol\n}\n\\end{Verbatim}\nNow, for a generic parameter $\\genericparam{S}$ ranging over $\\proto{Sequence}$, $\\genericparam{S}.\\namesym{Iterator}.\\namesym{Element}$ and $\\genericparam{S}.\\namesym{Element}$ become two equivalent ways to refer to the \\emph{same} type parameter.\n\n\\index{requirement}\n\\index{conformance requirement}\n\\index{superclass requirement}\n\\index{layout requirement}\n\\index{concrete type requirement}\nSo far you've seen protocol conformance requirements and same-type requirements between type parameters. Here is the full list of requirement kinds:\n\n\\index{substitution}\n\\begin{itemize}\n\\item \\textbf{Protocol conformance requirements}: written as $\\namesym{T}\\colon\\proto{P}$ where $\\namesym{T}$ is a type parameter and $\\proto{P}$ is a protocol. States that the concrete substitution for $\\namesym{T}$ must conform to $\\proto{P}$.\n\\item \\textbf{Layout requirements}: written as $\\namesym{T}\\colon\\proto{L}$ where $\\namesym{T}$ is a type parameter and $\\proto{L}$ is a layout constraint. The only kind of layout constraint available in the surface language is $\\namesym{AnyObject}$, which states that the concrete type substituted for $\\namesym{T}$ must be \\emph{some} class type. This makes the reference storage qualifiers \\texttt{weak}, \\texttt{unowned} and \\texttt{unowned(unsafe)} available for use on stored properties of type $\\namesym{T}$. Other kinds of layout constraints are available via the unofficial \\texttt{@\\_specialize} attribute, but other than the fact that they exist, the details of their implementation don't really matter to the requirement machine.\n% implies layout requirement\n\\item \\textbf{Superclass requirements}: written as $\\namesym{T}\\colon\\namesym{C}$ where $\\namesym{T}$ is a type parameter and $\\namesym{C}$ is a class. States that the concrete substitution for $\\namesym{T}$ must be an instance of $\\namesym{C}$ or some subclass of $\\namesym{C}$. As with protocol conformance requirements, superclass requirements can be also stated in the inheritance clause of a generic parameter; this is completely equivalent to the \\texttt{where} clause form. If the class is generic, the type constructor can be instantiated with other type parameters; for example,\n\\begin{Verbatim}\nfunc cache(elements: S, in cache: C)\n where C : Cache\n\\end{Verbatim}\n\\item \\textbf{Concrete type requirements}: written as $\\namesym{T} == \\namesym{U}$, where exactly one of $\\namesym{T}$ or $\\namesym{U}$ is a type parameter, and the other is a concrete type. This states that the concrete type substitution for the type parameter must exactly equal the concrete type (no subclassing, implicit conversions, etc, are allowed).\n\\item \\textbf{Same type requirements}: written as $\\namesym{T}==\\namesym{U}$, where both $\\namesym{T}$ and $\\namesym{U}$ are type parameters. This requirement states that whatever concrete types are substituted for $\\namesym{T}$ and $\\namesym{U}$, they must be identical types.\n\\end{itemize}\n\nWhat about same-type requirement where \\emph{both} sides are concrete types? The compiler allows this, but always produces a warning, because it looks a little silly and doesn't give you any more expressive power. Something like $\\namesym{Int} == \\namesym{Int}$ is tautological, and $\\namesym{Int} == \\namesym{String}$ is invalid. To be fair, you \\emph{can} state a non-trivial requirement with concrete types on both sides if at least one of them involves a generic type constructor instantiated with a type parameter, for example:\n\\begin{Verbatim}\nfunc sum(elements: S) -> Int\n where Array == Array {...}\n\\end{Verbatim}\nBut in this case, you may as well just peel off the $\\namesym{Array}\\langle\\bullet\\rangle$ type constructor from both sides and write a simpler concrete type requirement:\n\\[\\genericparam{T}.\\namesym{Element} == \\namesym{Int}.\\]\n\n\\index{power set}\nOne more small language feature is worth mentioning. You might want to define a function that constructs the set of all subsets of a set, i.e., the power set. The $\\namesym{Set}\\langle\\bullet\\rangle$ type constructor requires that its argument conforms to $\\proto{Hashable}$:\n\\begin{Verbatim}\nstruct Set {...}\n\\end{Verbatim}\nWhen you declare your \\texttt{powerSet(of:)} function, the requirement $\\genericparam{Element}\\colon\\proto{Hashable}$ doesn't need to be stated since it can be inferred from the application $\\namesym{Set}\\langle\\genericparam{Element}\\rangle$ appearing in the type signature of \\texttt{powerSet(of:)}:\n\\begin{Verbatim}\nfunc powerSet(of set: Set) -> Set> {...}\n\\end{Verbatim}\n\\index{requirement inference}\n\\index{desugaring}\nThis feature is known as \\emph{requirement inference}, and it is an example of what is called a \\emph{desugaring}. By the time the requirement machine comes into play, all inferred requirements have already become explicit.\n\n% talk about concrete types conforming to protocols and meniton associated type inference\n\nWe've now seen enough to dive---or at least begin dipping our toes---into the depths of the implementation. But first, a quick history lesson.\n\n\\chapter{A Little Bit of History}\\label{history}\n\nThe original Swift 1.0 language supported all the modern kinds of generic requirements except for layout requirements; those did not exist because $\\proto{AnyObject}$ was actually a special protocol with built-in support from the compiler, but it behaved much like the $\\proto{AnyObject}$ layout constraint does today.\n\nHowever, Swift 1.0 imposed two major restrictions on the expressivity of protocol definitions:\n\\begin{itemize}\n\\item protocol definitions did not allow \\texttt{where} clauses,\n\\item associated types in protocols could not state a conformance requirement which referenced the protocol containing the associated type, either directly or indirectly.\n\\end{itemize}\nSwift 4.0 introduced \\texttt{where} clauses on protocols and associated types \\cite{se0142}. Swift 4.1 lifted the restriction prohibiting recursive protocol conformances \\cite{se0157}. Both features are desirable, as the modern $\\proto{Collection}$ protocol demonstrates as part of the definition of the $\\namesym{SubSequence}$ associated type:\n\\begin{Verbatim}\nprotocol Collection : Sequence {\n associatedtype SubSequence : Collection\n where SubSequence.Element == Element,\n SubSequence.SubSequence == SubSequence\n}\n\\end{Verbatim}\nIntuitively, these requirements have the following interpretation:\n\\begin{itemize}\n\\item Slicing a collection can return another, possibly different type of collection, but the slice must have the same element type as the original.\n\\item If you slice a slice, you get the same type, since it would not be desirable if slices stacked recursively.\n\\end{itemize}\n\n\\index{recursive conformance requirement}\n\\index{conformance requirement!recursive|see{recursive conformance requirement}}\nA requirement like $\\namesym{SubSequence}\\colon\\proto{Collection}$ is called a \\emph{recursive conformance requirement}, because it appears inside the definition of the $\\proto{Collection}$ protocol itself.\n\nIn the $\\proto{Collection}$ protocol, the recursion via $\\namesym{SubSequence}$ only goes one level deep, because of the second same-type requirement which ``ties it off''. That is, if $\\genericparam{T}$ is constrained to $\\proto{Collection}$, $\\genericparam{T}.\\namesym{SubSequence}$ is a distinct type parameter conforming to $\\proto{Collection}$, but $\\genericparam{T}.\\namesym{SubSequence}.\\namesym{SubSequence}$ is equivalent to $\\genericparam{T}.\\namesym{SubSequence}$.\n\nHowever, it is also permissible to use an unconstrained recursive conformance requirement to define an infinite sequence of type parameters. The SwiftUI $\\proto{View}$ protocol is one example:\n\\begin{Verbatim}\nprotocol View {\n associatedtype Body : View\n var body: Body { get }\n}\n\\end{Verbatim}\nIf $\\genericparam{V}$ is constrained to conform to $\\proto{View}$, there is an infinite sequence of unique type parameters rooted at $\\genericparam{V}$:\n\\begin{align*}\n&\\genericparam{V}\\\\\n&\\genericparam{V}.\\namesym{Body}\\\\\n&\\genericparam{V}.\\namesym{Body}.\\namesym{Body}\\\\\n&\\genericparam{V}.\\namesym{Body}.\\namesym{Body}.\\namesym{Body}\\\\\n&\\cdots\n\\end{align*}\n\nIn contrast, in the absence of recursive protocol conformances, a generic signature can only induce a \\emph{finite} set of distinct type parameters.\n\nIn Swift 3.1 and older, the compiler component for reasoning about type parameters had a simple design:\n\\begin{algorithm}[Old \\texttt{ArchetypeBuilder} algorithm]\\label{archetypebuilder} The inputs are a list of generic parameters and generic requirements. The output is a directed graph.\n\n\\index{equivalence class}\nA path beginning at a root node corresponds to a valid type parameter. Multiple type parameters that are equivalent via same-type requirements are different paths that reach the same node. A node corresponds to an equivalence class of type parameters. Nodes store a list of conformance, superclass and concrete type requirements that apply to each type parameter in the equivalence class.\n\nThe algorithm proceeds in two phases:\n\\begin{enumerate}\n\\item (Expand) Begin by building a ``forest'' of type parameters, with generic parameters at the roots. Each generic parameter node starts out without children.\n\\begin{enumerate}\n\\item For every top-level requirement, find the subject generic parameter, record the requirement in the generic parameter's node, and if its a conformance requirement, add new children corresponding to each associated type of the protocol.\n\\item Recursively record and expand requirements on any associated type nodes introduced above.\n\\end{enumerate}\n\\item (Union-find) Then, process top-level same-type requirements:\n\\begin{enumerate}\n\\item First, resolve the left and right-hand sides, and merge the two nodes into an equivalence class.\n\\item Find any pairs of child nodes in the two merged nodes that have the same name, and recursively merge those child nodes as well.\n\\end{enumerate}\n\\end{enumerate}\n\\end{algorithm}\n\n% add a graph\n\nA side effect of both the recursive expansion and union-find steps is the gathering of a list of requirements in each equivalence class. These gathered requirements were used to answer queries such as ``does this type parameter conform to a protocol''.\n\nThis algorithm survived the introduction of protocol \\texttt{where} clauses in Swift 4.0 with some relatively minor changes; namely, the processing of same-type requirements became somewhat more complex, since they could be introduced at any level in the graph.\n\nWhen recursive conformances were introduced in Swift 4.1, the \\texttt{ArchetypeBuilder} underwent a major overhaul, where it was renamed to \\texttt{GenericSignatureBuilder}. Since the equivalence class graph was no longer necessarily finite, the biggest change was the move to a lazy evaluation approach---traversing a hitherto-unvisited part of the equivalence class graph would now lazily expand conformance requirements as needed.\n\nUnfortunately the limitations of this lazy expansion approach soon made themselves apparent. The equivalence class graph could be mutated both as a consequence of adding the initial set of requirements in a generic signature, and also by lazy expansion performed while answering queries. The highly mutable nature of the implementation made it difficult to understand and debug. It also became a performance problem, because ``expanding too much'' had to be balanced against ``not expanding enough.''\n\nFor example, any generic signature referencing one of the more complicated protocol towers, such as $\\proto{RangeReplaceableCollection}$ or $\\proto{FixedWidthInteger}$ from the standard library, would re-build the entire sub-graph of all nested associated types of each protocol from scratch. On the other hand, skipping expansion of recursive nested types could lead to same-type requirements being missed, which would result in the incorrect formation of multiple distinct equivalence classes that should actually be a single class.\n\nI later realized the lazy expansion strategy suffers from an even fundamental problem; as you will see in Chapter~\\ref{monoidsasprotocols}, the full generality of the generics system makes generic signature queries undecidable. The design of the \\texttt{GenericSignatureBuilder} was not sufficiently principled to determine if the input was too complex for its internal model, either crashing or silently producing incorrect results if this occurred.\n\nThe development of the requirement machine was motivated by the desire to find an immutable, closed-form representation of an entire, potentially infinite, type parameter graph. While the undecidability of the problem means this is not possible in the general case, I believe the formulation in terms of a confluent rewrite system should handle any reasonable generic signatures that appear in practice.\n\n\\chapter{Generic Signatures}\\label{genericsignatures}\n\\begin{listing}\\caption{A single linked list data type}\\label{linkedlist}\n\\begin{Verbatim}\nenum LinkedList {\n indirect case node(Element, LinkedList)\n case none\n \n func map(_ fn: (Element) -> Result) -> LinkedList {\n switch self {\n case .none:\n return .none\n case let .node(x, xs):\n return .node(fn(x), xs.map(fn))\n }\n }\n}\n\\end{Verbatim}\n\\end{listing}\n\n\\index{nested generic declaration}\nThe compiler itself is a large software system, and the generics system is just one component; you can look at its interface and implementation separately. The ``interface'' part does not expose the ``requirement machine,'' rewrite systems, monoids, or any other such nonsense; in fact, the interface of the generics system barely changed when I implemented the requirement machine. In this section, I'll talk about the interface to the generics system, while hand-waving away the implementation details.\n\nGeneric declarations can be nested almost arbitrarily in Swift:\n\\begin{itemize}\n\\item Generic functions may appear inside other generic functions.\n\\item Generic functions may appear inside generic types.\n\\item Generic types may appear inside other generic types.\n\\end{itemize}\nThe only restriction at this time is that generic types cannot be nested in generic functions. This mostly stems from some limitations in other parts of the compiler, and is not inherent to the generics system.\n\nListing \\ref{linkedlist} shows the implementation of a linked list with a \\texttt{map(\\_:)} function. Both $\\namesym{LinkedList}$ and \\texttt{map(\\_:)} introduce a new generic parameter. Since \\texttt{map(\\_:)} is nested within \\texttt{LinkedList}, both generic parameters are visible from the body \\texttt{map(\\_:)}.\n\nThe compiler doesn't really care about the names of generic parameters, but it still needs some way to talk about them, so it assigns each one a \\emph{depth} and \\emph{index}. The depth is the level of nesting; every declaration that has a generic parameter list increases the depth of any generic parameters introduced, with generic parameters in the outer-most declaration having a depth of 0. The index is the ordinal of the generic parameter relative to a single generic parameter list. In the linked list example, there are two generic parameters:\n\\begin{itemize}\n\\item $\\genericparam{Element}$ with depth 0 and index 0, and\n\\item $\\genericparam{Result}$ with depth 1 and index 0.\n\\end{itemize}\n\\index{canonical type}\nMost of the time I will still refer to generic parameters by names, but in some formal definitions I will use the notation $\\uptau_{d,i}$, where of course $d$ is the depth and $i$ is the index.\\footnote{And sometimes, the compiler loses track of a name and accidentally spits out $\\mathtt{\\uptau\\_1\\_0}$ or something in a diagnostic. That's a bug when it happens.}\n\nWhile the depth and index uniquely identify a generic parameter visible at a given source location, they do not uniquely identify a generic parameter globally. In order to answer a question about a generic parameter or one of its nested type parameters, the query must be asked with respect to some generic signature.\n\n\\index{generic signature}\n\\begin{definition} A \\emph{generic signature} is a ``flat'' list of all generic parameters that are in scope at some source location, together with all generic requirements from every \\texttt{where} clause.\n\\end{definition}\n\\begin{example}\nThe generic signature of \\texttt{map(\\_:)} has two generic parameters and no requirements:\n\\[\\langle\\genericparam{Element}, \\genericparam{Result}\\rangle\\]\n\\end{example}\n\\begin{example}\n\\index{where clause}\nSuppose we define an extension of $\\namesym{LinkedList}$ with a \\texttt{where} clause:\n\\begin{Verbatim}\nextension LinkedList where Element == Int {\n func sum() -> Int {\n switch self {\n case .none: return 0\n case let .node(x, xs) return x + xs.sum()\n }\n }\n}\n\\end{Verbatim}\nThe extension starts from the generic signature of $\\namesym{LinkedList}$ and adds a new same-type requirement. The \\texttt{sum()} function has this generic signature:\n\\[\\gensig{\\genericparam{Element}}{\\genericparam{Element}==\\namesym{Int}}\\]\n\\end{example}\n\\begin{example}\nHere is a funny example. Suppose we want to build linked lists from the elements of some lazy iterator:\n\\begin{Verbatim}\nextension LinkedList {\n init(from iterator: inout I)\n where I.Element == Element {\n if let elt = iterator.next() {\n self = .node(elt, .init(from: iterator))\n } else {\n self = .none\n }\n }\n}\n\\end{Verbatim}\nThe declaration of \\texttt{.init(from:)} has the following generic signature:\n\\[\\gensig{\\genericparam{Element}, \\genericparam{I}}{\\genericparam{Element}==\\genericparam{I}.\\namesym{Element}}\\]\nOr alternatively, using the ``canonical type'' notation,\n\\[\\gensig{\\genericsym{0}{0}, \\genericsym{1}{0}}{\\genericsym{0}{0}==\\genericsym{1}{0}.\\namesym{Element}}\\]\n\\end{example}\n\n\\index{protocol Self type}\nA protocol has a generic signature too, even though it doesn't have a generic parameter list in the source language.\n\n\\begin{definition}\nThe generic signature of a protocol $\\proto{P}$ has a single generic parameter $\\genericparam{Self}$, together with a conformance requirement that says $\\genericparam{Self}$ must conform to $\\proto{P}$:\n\\[\\gensig{\\genericparam{Self}}{\\genericparam{Self}\\colon\\proto{P}}\\]\n\\end{definition}\nThis is where the $\\genericparam{Self}$ type inside a protocol definition comes from; it is the generic parameter that is substituted with the concrete conforming type when the protocol is used. Since protocols cannot be nested inside other declarations, $\\genericparam{Self}$ is always at depth and index 0; or in other words, its canonical type is $\\genericsym{0}{0}$.\n\nGeneric signatures do not tell you anything about what is ``inside'' protocols. The protocol $\\proto{P}$ might have one or more associated types, or a \\texttt{where} clause, but none of this information appears in the protocol's generic signature. There is another, related concept that peels back one level of indirection to encode the ``guts'' of a protocol.\n\n\\index{requirement signature}\n\\begin{definition} A \\emph{requirement signature} of a protocol $\\proto{P}$ is the single generic parameter $\\genericparam{Self}$ together with any requirements collected from inheritance clauses and \\texttt{where} clauses written inside the protocol.\n\\end{definition}\n\nFor example, here is the requirement signature of the $\\proto{Sequence}$ protocol:\n\\begin{align*}\n\\gensig{\\genericparam{Self}}{&\\genericparam{Self}.\\namesym{Element}==\\genericparam{Self}.\\namesym{Iterator}.\\namesym{Element},\\\\\n&\\genericparam{Self}.\\namesym{Iterator}\\colon\\proto{IteratorProtocol}}\n\\end{align*}\n\n\\index{desugaring}\n\\index{protocol inheritance}\nThe definition of a requirement signature mentions that it collects requirements from inheritance clauses and \\texttt{where} clauses. Associated types can have inheritance clauses, but so can protocols. How can protocol inheritance be represented in a protocol requirement signature? Well, it's just a protocol conformance requirement on $\\genericparam{Self}$. For example the requirement signature of $\\proto{Hashable}$ shown in Listing \\ref{hashableequatable} records the inheritance relationship with $\\proto{Equatable}$:\n\\[\\gensig{\\genericparam{Self}}{\\genericparam{Self}\\colon\\proto{Equatable}}.\\]\n\\begin{listing}\\caption{Simplified forms of the $\\proto{Hashable}$ and $\\proto{Equatable}$ protocols.}\\label{hashableequatable}\n\\begin{Verbatim}\nprotocol Hashable : Equatable {\n func hash(into: inout Hasher)\n}\n\nprotocol Equatable {\n static func ==(lhs: Self, rhs: Self) -> Bool\n}\n\\end{Verbatim}\n\\end{listing}\n\n\\index{name lookup}\nThere is an important caveat here. Protocol inheritance is not equivalent to writing down a conformance requirement on $\\genericparam{Self}$ in the \\emph{source language}. The reason is that protocol inheritance has a special meaning to name lookup, which sits ``below'' the generics implementation in the compiler. In order to build the requirement signature of a protocol in the first place, the compiler performs name lookup, so name lookup must rely on constructs more primitive than the generic requirements in order to resolve identifiers without causing an infinite recursion through the compiler. For this reason, the compiler emits a warning upon encountering a conformance requirement on $\\genericparam{Self}$ not stated via protocol inheritance syntax.\n\\vfill\n\\eject\n\\section{Reasoning About Type Parameters}\n\\begin{listing}\\caption{A function to compare the first element of two sequences for equality}\\label{areequalex}\n\\begin{Verbatim}\nfunc areFirstElementsEqual(\n _ first: S1, _ second: S2) -> Bool\n where S1.Element : Equatable,\n S1.Element == S2.Element {\n let firstIter = first.makeIterator()\n let secondIter = second.makeIterator()\n\n let firstElt = firstIter.next()!\n let secondElt = secondIter.next()!\n\n // `==' called with S1.Iterator.Element and S2.Iterator.Element\n return firstElt == secondElt\n}\n\\end{Verbatim}\n\\end{listing}\nTo understand how generic code might be type checked, let's look at the example in Listing \\ref{areequalex}. While it looks rather simple, there's a fair amount of complexity here. The generic signature of the \\texttt{areFirstElementsEqual(\\_:\\_:)} function itself is:\n\\begin{align*}\n\\gensig{\\genericparam{S1},\\genericparam{S2}}\n{&\\genericparam{S1}\\colon\\proto{Sequence},\\\\\n&\\genericparam{S2}\\colon\\proto{Sequence},\\\\\n&\\genericparam{S1}.\\namesym{Element}\\colon\\proto{Equatable},\\\\\n&\\genericparam{S1}.\\namesym{Element}==\\genericparam{S2}.\\namesym{Element}}\n\\end{align*}\nNow consider the call to the \\texttt{==} operator on line 11. The \\texttt{==} operator is defined in the $\\proto{Equatable}$ protocol as taking two parameters, both of type $\\genericparam{Self}$, given by the protocol generic signature $\\gensig{\\genericparam{Self}}{\\genericparam{Self}\\colon\\proto{Equatable}}$. At the call site, the arguments\n\\texttt{firstElt} and \\texttt{secondElt} are of type $\\genericparam{S1}.\\namesym{Iterator}.\\namesym{Element}$ and\n$\\genericparam{S2}.\\namesym{Iterator}.\\namesym{Element}$, respectively.\n\nIn order for this application of \\texttt{==} to be valid, the type checker must prove two things:\n\\begin{enumerate}\n\\item first, $\\genericparam{S1}.\\namesym{Iterator}.\\namesym{Element}$ and $\\genericparam{S2}.\\namesym{Iterator}.\\namesym{Element}$ must be the same type;\n\\item second, that either one or the other (since they're the same type!) must conform to $\\proto{Equatable}$.\n\\end{enumerate}\nBoth facts can be proven as follows:\n\\begin{itemize}\n\\item $\\genericparam{S1}\\colon\\proto{Sequence}$ together with the same-type requirement in the $\\proto{Sequence}$ protocol implies $\\genericparam{S1}.\\namesym{Element}==\\genericparam{S1}.\\namesym{Iterator}.\\namesym{Element}$.\n\\item $\\genericparam{S2}\\colon\\proto{Sequence}$ together with the same-type requirement in the $\\proto{Sequence}$ protocol implies $\\genericparam{S2}.\\namesym{Element}==\\genericparam{S2}.\\namesym{Iterator}.\\namesym{Element}$.\n\\item $\\genericparam{S1}.\\namesym{Element}==\\genericparam{S2}.\\namesym{Element}$ together with the above implies the following, which concludes the proof of the first fact:\n\\[\\genericparam{S1}.\\namesym{Iterator}.\\namesym{Element}==\\genericparam{S2}.\\namesym{Iterator}.\\namesym{Element}.\\] \n\\item $\\genericparam{S1}.\\namesym{Element}\\colon\\proto{Equatable}$ together with the above implies the second fact.\n\\end{itemize}\n\n\\section{Generic Signature Queries}\\label{intqueries}\n% define what an archetype is\n\nProving properties about type parameters is non-trivial, which is why this functionality is encapsulated in a series of re-usable \\emph{generic signature queries}.\nTable \\ref{querytable} shows a summary, grouping the queries into three sets. You can probably guess what some of them do just by seeing their names. You will see the actual implementation of these queries later, in Section~\\ref{implqueries}.\n\\begin{leftbar}\n\\noindent In the compiler, each generic signature query is a method in the \\texttt{GenericSignature} class.\n\\end{leftbar}\n\n\\begin{table}\\caption{Generic signature queries}\\label{querytable}\n\\begin{center}\n\\begin{tabular}{|l|l|}\n\\hline\nQuery kind&Query name\\\\\n\\hline\n\\hline\n\\multirow{3}{7.5em}{Predicates}&\\texttt{requiresProtocol()}\\\\\n&\\texttt{requiresClass()}\\\\\n&\\texttt{isConcreteType()}\\\\\n\\hline\n\\multirow{4}{7.5em}{Properties}&\\texttt{getRequiredProtocols()}\\\\\n&\\texttt{getSuperclassBound()}\\\\\n&\\texttt{getConcreteType()}\\\\\n&\\texttt{getLayoutConstraint()}\\\\\n\\hline\n\\multirow{3}{7.5em}{Canonical types}&\\texttt{areSameTypeParameterInContext()}\\\\\n&\\texttt{isCanonicalTypeInContext()}\\\\\n&\\texttt{getCanonicalTypeInContext()}\\\\\n\\hline\n\\end{tabular}\n\\end{center}\n\\end{table}\n\nThe simplest of all queries are the binary predicates, which respond with a true/false answer.\n\\begin{description}\n\\item [\\texttt{requiresProtocol()}] answers if a type parameter conforms to a protocol.\n\\item [\\texttt{requiresClass()}] answers if a type parameter is represented at runtime as a single retainable pointer.\n\\item [\\texttt{isConcreteType()}] answers if a type parameter is fixed to a concrete type.\n\\end{description}\n\n\\begin{example}\n\\index{protocol inheritance}\n\\index{conformance requirement}\nRecall from Listing \\ref{hashableequatable} there is an inheritance relationship from $\\proto{Hashable}$ and $\\proto{Equatable}$, and take the generic signature\n\\[\\gensig{\\genericparam{T}}{\\genericparam{T}\\colon\\proto{Hashable}}.\\]\nSince protocol inheritance is expressed as a conformance requirement on $\\genericparam{Self}$, both of these queries will return true:\n\\begin{itemize}\n\\item \\texttt{requiresProtocol(T, Hashable)}\n\\item \\texttt{requiresProtocol(T, Equatable)}\n\\end{itemize}\n\\end{example}\n\n\\index{layout requirement}\n\\index{superclass requirement}\nNext, I'll show two examples of \\texttt{requiresClass()}. The $\\namesym{AnyObject}$ layout constraint, which states that an instance of a type is represented as a single retainable pointer, can either be stated explicitly, or be inferred from a superclass requirement.\n\n\\begin{example}\nAn example of the first case, where \\texttt{requiresClass(T.Element)} is true:\n\\[\\gensig{\\genericparam{T}}{\\genericparam{T}\\colon\\proto{Sequence}, \\genericparam{T}.\\namesym{Element}\\colon\\proto{Executor}}\\]\nThis follows from the definition of the $\\proto{Executor}$ protocol in the standard library, which constrains $\\genericparam{Self}$ to $\\namesym{AnyObject}$:\n\\begin{Verbatim}\nprotocol Executor : AnyObject {...}\n\\end{Verbatim}\n\\end{example}\n\n\\begin{example}An example of the second case, where \\texttt{requiresClass(C)} is true:\n\\[\\gensig{\\genericparam{C}}{\\genericparam{C}\\colon\\namesym{Cache}}\\]\n\\begin{Verbatim}\nclass Cache {...}\n\\end{Verbatim}\n\\end{example}\n\n\\begin{example}\n\\index{concrete type requirement}\nConsider this generic signature:\n\\[\\gensig{\\genericparam{T},\\genericparam{U}}{\\genericparam{T}\\colon\\proto{Sequence},\\genericparam{T}.\\namesym{Element}==\\namesym{Array}\\langle\\genericparam{U}\\rangle}\\]\nHere both of the following are true:\n\\begin{itemize}\n\\item \\texttt{isConcreteType(T.Element)}\n\\item \\texttt{isConcreteType(T.Iterator.Element)}\n\\end{itemize}\n\\end{example}\n\n% what is 'empty type' or just drop 'if there is one'\n% 'empty layout constraint'\nThe next set of queries derive more complex properties that are not just true/false predicates.\n\\begin{description}\n\\item [\\texttt{getRequiredProtocols()}] returns the list of all protocols that a type parameter must conform to. The list is minimal in the sense that no protocol inherits from any other protocol in the list (Definition~\\ref{minimalproto}), and this list is sorted in canonical protocol order (Definition~\\ref{canonicalprotocol}).\n\\index{superclass requirement}\n\\item [\\texttt{getSuperclassBound()}] returns the superclass bound of a type parameter if there is one, or the empty type otherwise.\n\\index{concrete type requirement}\n\\item [\\texttt{getConcreteType()}] returns the concrete type to which a type parameter is fixed if there is one, or the empty type otherwise.\n\\index{layout requirement}\n\\item [\\texttt{getLayoutConstraint()}] returns the layout constraint describing a type parameter's runtime representation if there is one, or the empty layout constraint otherwise.\n\\end{description}\n\n\\begin{example}\n% move code example before description\n In the following, \\texttt{getSuperclassBound(T)} is $\\namesym{G}\\langle\\genericparam{U}\\rangle$:\n\\[\\gensig{\\genericparam{T}, \\genericparam{U}}{\\genericparam{T}\\colon\\namesym{G}\\langle\\genericparam{U}\\rangle}\\]\n\\begin{Verbatim}\nclass G {}\n\\end{Verbatim} \n\\end{example}\n\n\\begin{example}\n% Range's Element is the same as Range.Element\nIn the following, \\texttt{getConcreteType(T.Index)} is $\\namesym{Int}$:\n\\[\\gensig{\\genericparam{T}}{\\genericparam{T}\\colon\\proto{Collection},\\genericparam{T}.\\namesym{Indices}==\\namesym{Range}\\langle\\namesym{Int}\\rangle}\\]\nThis is a non-trivial consequence of several requirements:\n\\begin{itemize}\n\\item the concrete type requirement $\\genericparam{T}.\\namesym{Indices}==\\namesym{Range}\\langle\\namesym{Int}\\rangle$ stated above;\n\\item $\\genericparam{Self}.\\namesym{Indices}.\\namesym{Element}==\\genericparam{Self}.\\namesym{Index}$ in the requirement signature of $\\proto{Collection}$;\n\\item the standard library's conditional conformance of $\\namesym{Range}\\langle\\namesym{Element}\\rangle$ to $\\proto{Collection}$ where $\\namesym{Element}$ is $\\proto{Strideable}$.\n\\end{itemize}\n\\end{example}\n\n\\section{Canonical Types}\\label{canonicaltypes}\n\n\\index{canonical type}\nThe final set of generic signature queries concern so-called canonical types, but before I can say what a canonical type \\emph{is}, I need to formally define type parameters.\n\n% each associated type is defined in a protocol that the prefix conforms to\n% maybe a recursive definition is better\n\n\\begin{definition} A \\emph{type parameter} is a non-empty sequence where the first element is a generic parameter (or really, a depth and an index), and all remaining elements are associated types. The \\emph{length} of a type parameter $T$, denoted $|T|$, is the length of this sequence.\n\\end{definition}\n\\begin{leftbar}\n\\noindent In the compiler implementation, type parameters are represented recursively. A type parameter is either a \\texttt{GenericTypeParameterType}, or a \\texttt{DependentMemberType}\\footnote{The ``dependent type'' terminology comes from C++. These are not dependent types in the sense of the lambda cube, but rather dependent on the concrete type substitution when the generic declaration is ultimately referenced from source.} whose base type is some other type parameter. Furthermore, \\texttt{DependentMemberType} comes in two flavors:\n\\begin{itemize}\n\\item ``resolved'' \\texttt{DependentMemberTypes} point to an \\texttt{AssociatedTypeDecl}.\n\\item ``unresolved'' \\texttt{DependentMemberTypes} store an \\texttt{Identifier}.\n\\end{itemize}\nMost of the time, the requirement machine implementation works on resolved type parameters.\n\\end{leftbar}\n\n% why do we care about 'non-root' associated types\n\\index{root associated type}\n\\begin{definition}\\label{rootassoctypedef} A \\emph{root associated type} is an associated type defined in a protocol such that no inherited protocol has an associated type with the same name.\n\\end{definition}\n\\begin{example}\nIn Listing \\ref{rootassoctypesrc}, $\\proto{Q}.\\namesym{A}$ is not a root associated type, because $\\proto{Q}$ inherits $\\proto{P}$ and $\\proto{P}$ also declares an associated type named $\\namesym{A}$.\n\\end{example}\n\\begin{listing}\\caption{Examples of root and non-root associated types}\\label{rootassoctypesrc}\n\\begin{Verbatim}\nprotocol P {\n associatedtype A // root\n}\n\nprotocol Q : P {\n associatedtype A // not a root\n associatedtype B // root\n}\n\\end{Verbatim}\n\\end{listing}\nNow, I'm going to equip type parameters with a linear order, which is just a way of saying that one type is ``smaller'' than another.\n\\index{linear order}\n\\index{protocol order!canonical}\n\\begin{definition}[Canonical protocol order]\\label{canonicalprotocol} If $\\bm{\\mathsf{P}}$ and $\\bm{\\mathsf{Q}}$ are protocols, then $\\bm{\\mathsf{P}} < \\bm{\\mathsf{Q}}$ if\n\\begin{itemize}\n\\item $\\bm{\\mathsf{P}}$ is in a different module than $\\bm{\\mathsf{Q}}$, and the module name of $\\bm{\\mathsf{P}}$ lexicographically precedes the module name of $\\bm{\\mathsf{Q}}$, or\n\\item $\\bm{\\mathsf{P}}$ is in the same module as $\\bm{\\mathsf{Q}}$, and the name of $\\bm{\\mathsf{P}}$ lexicographically precedes the name of $\\bm{\\mathsf{Q}}$.\n\\end{itemize}\n\\end{definition}\n\n\\begin{example} If the $\\namesym{Barn}$ module defines a $\\proto{Horse}$ protocol, then by Rule 1, $\\proto{Horse}<\\proto{Collection}$, since $\\proto{Collection}$ is defined in a module named $\\namesym{Swift}$, and $\\namesym{Barn}<\\namesym{Swift}$.\n\nIf the $\\namesym{Barn}$ module also defines a $\\proto{Saddle}$ protocol, then by Rule 2, $\\proto{Horse}<\\proto{Saddle}$.\n\\end{example} \n\n\\index{type parameter order!canonical}\n\\begin{definition}[Canonical type order]\\label{canonicaltypeorder} If $T$ and $U$ are type parameters, then $T < U$ if\n\\begin{itemize}\n\\item $|T| < |U|$, or\n\\item $|T|=|U|$ and there exists $0\\le j < |T|$ such that\n\\begin{itemize}\n\\item $T_j0$, then $T_j$ and $U_j$ are associated types; in this case, $T_j(_ x: X) -> X.A.B.A {\n return x.a.b.a\n}\n\nfunc multiplyByBB(_ x: X) -> X.B.B {\n return x.b.b\n}\n\\end{Verbatim}\n\\end{listing}\n\nConsider the generic signature $\\gensig{\\genericparam{T}}{\\genericparam{T}\\colon\\proto{P}}$, with $\\proto{P}$ as shown in Listing \\ref{freetwoproto}. The two associated types $\\namesym{A}$ and $\\namesym{B}$ recursively conform to $\\proto{P}$, which generates infinitely many type parameters. These type parameters all begin with $\\genericparam{T}$ followed by an arbitrary sequence of $\\namesym{A}$'s and $\\namesym{B}$'s:\n\n\\begin{quote}\n\\noindent$\\genericparam{T}$\\\\\n$\\genericparam{T}.\\namesym{A}$\\\\\n$\\genericparam{T}.\\namesym{B}$\\\\\n$\\genericparam{T}.\\namesym{A}.\\namesym{A}$\\\\\n$\\genericparam{T}.\\namesym{A}.\\namesym{B}$\\\\\n$\\genericparam{T}.\\namesym{B}.\\namesym{A}$\\\\\n$\\genericparam{T}.\\namesym{B}.\\namesym{B}$\\\\\n$\\ldots$\n\\end{quote}\n\nYou might (correctly) guess that this definition of $\\bm{\\mathsf{P}}$ is in fact a representation of the free monoid over two generators $\\{a, b\\}$ in the Swift language. Compositions of the property accessors \\texttt{.a}, \\texttt{.b} and \\texttt{.id} are actually performing the monoid operation $\\otimes$ \\emph{at compile time}, with type parameters as monoid elements.\n\nListing \\ref{freetwoproto} also shows a pair of function definitions, \n\\begin{itemize}\n\\item \\texttt{multiplyByBB(\\_:)}, and\n\\item \\texttt{multiplyByABA(\\_:)}.\n\\end{itemize}\nThese functions implement ``multiplication'' by $bb$ and $aba$, respectively. Say that \\texttt{t} is a $\\genericparam{T}$, and $\\genericparam{T}$ conforms to $\\bm{\\mathsf{P}}$. If we first apply \\texttt{multiplyByABA(\\_:)} to \\texttt{t}, and then apply \\texttt{multiplyBB(\\_:)} to the result, you will have ``multiplied'' the type $\\genericparam{T}$ by $ababb$ on the right:\n\\begin{itemize}\n\\item First, substituting $\\genericparam{X}:=\\genericparam{T}$ into the type of \\texttt{multiplyByABA(\\_:)} gives\n\\[\\genericparam{T}.\\namesym{A}.\\namesym{B}.\\namesym{A}.\\]\n\\item Then, substituting $\\genericparam{X} := \\genericparam{T}.\\namesym{A}.\\namesym{B}.\\namesym{A}$ into the type of \\texttt{multiplyByBB(\\_:)} gives the final result\n\\[\\genericparam{T}.\\namesym{A}.\\namesym{B}.\\namesym{A}.\\namesym{B}.\\namesym{B}.\\]\n\\end{itemize}\n\nIn a free monoid, each term denotes a unique element; in the world of Swift that means each path of $\\namesym{A}$'s and $\\namesym{B}$'s is a unique type parameter. This can be formalized as follows:\n\\begin{algorithm}[Constructing a protocol from a free monoid]\\label{freemonoidproto}\nLet $A^*$ be the free monoid over the alphabet $\\{a_1,a_2,\\ldots,a_n\\}$. A protocol $\\proto{P}$ can be constructed from $A^*$ as follows:\n\\begin{enumerate}\n\\item First, begin with an empty protocol definition:\n\\begin{Verbatim}\nprotocol P {}\n\\end{Verbatim}\n\\item Now, for each element $a_i\\in A$, declare an associated type conforming to $\\proto{P}$ within the protocol's body:\n\\begin{Verbatim}\nassociatedtype Ai : P\n\\end{Verbatim}\n\\end{enumerate}\n\\end{algorithm}\n\n\\index{lifting map}\n\\index{lowering map}\n\\begin{definition}[Lowering and lifting maps]\\label{liftingloweringmaps}\nLet $\\proto{P}$ be a protocol constructed from a free monoid $A^*$ by the above algorithm, and write $\\mathsf{Type}$ for the set of all type parameters of $\\proto{P}$. The elements of $\\mathsf{Type}$ all begin with the protocol $\\genericparam{Self}$ type, followed by zero or more associated type names, joined with ``\\texttt{.}''.\n\nDefine a pair of maps, called the \\emph{lifting map} and the \\emph{lowering map}. The lowering map sends terms to type parameters, and the lifting map sends type parameters to terms:\n\\begin{align*}\n\\Lambda_{\\proto{P}}&\\colon \\mathsf{Type}\\rightarrow A^*\\\\\n\\Lambda^{-1}_{\\proto{P}}&\\colon A^*\\rightarrow\\mathsf{Type}\n\\end{align*}\n\\index{protocol $\\genericparam{Self}$ type}\n\\begin{itemize}\n\\item The lowering map $\\Lambda_{\\proto{P}}$ drops the $\\genericparam{Self}$ parameter, and maps each associated type name $\\namesym{Ai}$ to the corresponding element $a_i\\in A$, concatenating all elements to form the final result.\n\\item The lifting map $\\Lambda^{-1}_{\\proto{P}}$ operates in reverse; given an arbitrary term in $A^*$, it replaces each element $a_i\\in A$ with the associated type name $\\namesym{Ai}$, joins the associated type names with ``\\texttt{.}'' to form Swift syntax for a nested type, and finally prepends the protocol $\\genericparam{Self}$ type to the result.\n\\end{itemize}\nNote that applying the lifting map to the identity element $\\varepsilon\\in A^*$ produces the protocol $\\genericparam{Self}$ type.\n\\end{definition}\n\\begin{lemma}\nThe lowering and lifting maps have a couple of interesting properties:\n\\begin{itemize}\n\\item They are inverses of each other; that is, for all $x\\in A^*$ and $T\\in\\mathsf{Type}$,\n\\begin{align*}\n\\Lambda_{\\proto{P}}(\\Lambda_{\\proto{P}}^{-1}(x))&=x,\\\\\n\\Lambda_{\\proto{P}}^{-1}(\\Lambda_{\\proto{P}}(T))&=T.\n\\end{align*}\n\\item If $T$, $U\\in\\mathsf{Type}$, define $T[\\genericparam{Self}:=U]$ to be the type parameter obtained by substituting the protocol $\\genericparam{Self}$ type of $T$ with $U$. This type satisfies the following identity:\n\\[\\Lambda_{\\proto{P}}(T[\\genericparam{Self}:=U]) = \\Lambda_{\\proto{P}}(U)\\otimes \\Lambda_{\\proto{P}}(T).\\]\nThat is, the lowering and lifting maps are compatible with the monoid operation in $A^*$.\n\\end{itemize}\n\\end{lemma}\n\nThe construction performed by Algorithm~\\ref{freemonoidproto} can be generalized to finitely-presented monoids. The overall idea is the same as with free monoids, except for the addition of relations, which become same-type requirements in the Swift world.\n\nListing \\ref{bicyclicproto} shows a Swift protocol representation of the bicyclic monoid from Example \\ref{bicyclic}, together with a \\texttt{multiplyByBA(\\_:)} function that performs some compile-time monoid arithmetic.\n\n\\begin{listing}\\caption{Bicyclic monoid}\\label{bicyclicproto}\n\\begin{Verbatim}\nprotocol Bicyclic {\n associatedtype A : Bicyclic\n associatedtype B : Bicyclic\n where A.B == Self\n \n var a: A { get }\n var b: B { get }\n var id: Self { get }\n}\n\nfunc multiplyByBA(_ x: X) -> X.B.A {\n return x.b.a\n}\n\\end{Verbatim}\n\\end{listing}\nUnlike our free monoid, the bicyclic monoid's presentation has a relation, so some elements can be spelled in multiple ways; for example, $aabba=a$. What does this identity mean in Swift? Well, an equivalence of monoid elements becomes an equivalence of type parameters.\n\nYou can write down some type parameters in the signature $\\gensig{\\genericparam{T}}{\\genericparam{T}\\colon\\proto{Bicyclic}}$, and then pass a pair of values to the \\texttt{same(\\_:\\_:)} function, which will only type check if both values have equivalent types. In Listing \\ref{bicycliccheck}, the first call to \\texttt{same(\\_:\\_:)} will type check, since $aabba=a$. The second call will not type check, since $ab\\ne ba$.\n\\begin{listing}\\caption{Checking equivalences in the bicyclic monoid}\\label{bicycliccheck}\n\\begin{Verbatim}\nfunc same(_: X, _: X) {}\n\nfunc bicyclicTest(_ x: X) {\n let s: X.A.A.B.B.A = x.a.a.b.b.a\n let t: X.A = x.a\n \n same(s, t) // this is OK\n \n let u: X.A.B = x.a.b\n let v: X.B.A = x.b.a\n \n same(u, v) // type check failure\n}\n\\end{Verbatim}\n\\end{listing}\n\n\\index{monoid}\nYou can construct similar code examples for any finitely-presented monoid; there is nothing special about the bicyclic monoid here.\n\\begin{algorithm}[Constructing a protocol from a finitely-presented monoid]\\label{protocolmonoidalgo} Let $\\langle A;R\\rangle$ be a finitely-presented monoid. A protocol $\\proto{P}$ can be constructed from $\\langle A;R\\rangle$ as follows:\n\\begin{enumerate}\n\\item First, build $\\proto{P}$ from the free monoid $A^*$ using Algorithm~\\ref{freemonoidproto}.\n\\item Second, introduce an empty \\texttt{where} clause in the declaration of $\\proto{P}$.\n\\item Finally, for every equation $s=t$ of $R$, add a same-type requirement to this \\texttt{where} clause, using the lifting map to obtain a pair of type parameters from $s$ and $t$:\n\\[\\Lambda_{\\proto{P}}^{-1}(s)==\\Lambda_{\\proto{P}}^{-1}(t)\\]\n\\end{enumerate}\n\\end{algorithm}\n\\begin{theorem}\\label{protocolmonoidthm} Let $\\langle A;R\\rangle$ be a finitely-presented monoid. The protocol~\\proto{P} constructed by Algorithm~\\ref{protocolmonoidalgo} has the property that if $x$, $y \\in A^*$ are equal as elements of $\\langle A;R\\rangle$, then applying the \\texttt{areSameTypeParametersInContext()} generic signature query to the type parameters $\\Lambda_{\\proto{P}}^{-1}(x)$ and $\\Lambda_{\\proto{P}}^{-1}(y)$ should return true. The other direction also holds, showing that type parameter equality is exactly the monoid congruence $\\sim_R$ on $A^*$.\n\\end{theorem}\n\\begin{proof}\nIf $x$, $y\\in A^*$ are equal as elements of $\\langle A;R\\rangle$, it means that they satisfy $x\\sim_R y$, where $\\sim_R$ is the monoid congruence generated by $R$. This means that $y$ can be obtained from $x$ by applying a series of equations from $R$, replacing subterms at different positions.\n\\index{derivation path}\nThis can be formalized by writing down a \\emph{derivation path}, which is a sequence of pairs $(s_i \\Rightarrow t_i, k_i)$ where $s_i=t_i$ or $t_i=s_i$ is an equation of $R$ (depending on the direction in which the equation is applied), and $k_i\\in\\mathbb{N}$ is a non-negative number indicating the position at which to replace $s$ with $t$ with the intermediate term.\n\nDerivation paths satisfy a validity property. Let $x_i\\in A^*$ be the $i$th intermediate term, obtained by applying the first $i$ components of the derivation path to the initial term $x$. Notice that $x_0=x$ since no components have been applied yet, and if $n$ is the total number of components, then $x_n=y$ is the final term. Also, if the $i$th derivation path component is $(s_i\\Rightarrow t_i, k_i)$, the subterm of $x_i$ beginning at position $k$ is equal to $s_i$, and the subterm of $x_{i+1}$ beginning at position $k$ is equal to $t_i$.\n\nEach associated type of $\\proto{P}$ conforms to $\\proto{P}$ itself, which implies that every nested type parameter also conforms to $\\proto{P}$. So the $k_i$-length prefix of $\\Lambda_{\\proto{P}}^{-1}(x_i)$ also conforms to $\\proto{P}$. By construction, one of the equations $s=t$ or $t=s$ corresponds to a same-type requirement of $\\proto{P}$. By the validity property, this same-type requirement can be applied to the type parameter $\\Lambda_{\\proto{P}}^{-1}(x_i)$ at position $k_i$ to obtain $\\Lambda_{\\proto{P}}^{-1}(x_{i+1})$.\n\nThe derivation path that witnesses an equivalence between $x$ and $y$ via the intermediate terms $x_i$ can be viewed as a proof of the equivalence of the type parameters $\\Lambda_{\\proto{P}}^{-1}(x)$ and $\\Lambda_{\\proto{P}}^{-1}(y)$ via a series of same-type requirements applied to the intermediate type parameters $\\Lambda_{\\proto{P}}^{-1}(x_i)$.\n\nThe other direction can be shown to hold via a similar argument.\n\\end{proof}\n\\section{Examples}\nThis section re-states examples of finitely-presented monoids from the previous chapter as Swift protocol definitions using Algorithm~\\ref{protocolmonoidalgo}. Feel free to skip ahead if you're not interested.\n\n\\index{integers modulo $n$}\n\\begin{example}\n% FIXME: re-state monoid presentation here\nThe monoid of integers modulo 5 under addition:\n\\begin{Verbatim}\nprotocol Z5 {\n associatedtype A : Z5 where A.A.A.A.A == Self\n}\n\\end{Verbatim}\n\\end{example}\n\n\\index{free commutative monoid}\n\\begin{example}\nThe free commutative monoid with two generators:\n\\begin{Verbatim}\nprotocol F2 {\n associatedtype A : F2\n associatedtype B : F2 where A.B == B.A\n}\n\\end{Verbatim}\n\\end{example}\n\n\\index{group of integers}\n\\begin{example}\nThe group of integers under addition:\n\\begin{Verbatim}\nprotocol Z {\n associatedtype A : Z where A.B == Self\n associatedtype B : Z where B.A == Self\n}\n\\end{Verbatim}\n\\end{example}\n\n\\index{infinite dihedral group}\n\\begin{example}\nThe infinite dihedral group:\n\\begin{Verbatim}\nprotocol DInf {\n associatedtype A : DInf where A.A == Self\n associatedtype B : DInf where B.B == Self\n}\n\\end{Verbatim}\n\\end{example}\n\\index{binary icosahedral group}\n\\begin{example}\nThe binary icosahedral group:\n\\begin{Verbatim}\nprotocol TwoI {\n associatedtype S : TwoI where S.S.S == Self,\n associatedtype T : TwoI where T.T.T.T.T == Self, S.T.S.T == Self\n}\n\\end{Verbatim}\n\\end{example}\n\\section{Undecidability}\nAlgorithm~\\ref{protocolmonoidalgo} allows you to write down a ``well-formed'' protocol definition isomorphic to an arbitrary finitely-presented monoid, and Theorem~\\ref{protocolmonoidthm} shows this construction can express computations in the monoid at compile-time. Note that I was very careful with the use of ``should'' in the statement of Theorem~\\ref{protocolmonoidthm}. This is because it describes the operation of a ``platonic ideal'' Swift compiler. As it turns out, this is unimplementable in the real world, because Swift generics as specified are a little bit \\emph{too} expressive.\n\n\\index{decidability}\n\\index{word problem}\nThe \\emph{word problem on finitely-presented monoids} asks if two strings in the free monoid $A^*$ are equivalent as elements of a finitely-presented monoid $\\langle A; R\\rangle$. All examples of monoids I've shown so far have decidable word problems. However, finitely-presented monoids with undecidable word problems do exist, meaning there is no computable function which can solve it in the general case.\n\\begin{theorem}[From \\cite{undecidablegroup}]\\label{undecidablemonoid} The monoid presented by the following set of generators and relations has an undecidable word problem:\n\\[\\langle a, b, c, d, e;\\;ac=ca;\\;bc=cb;\\;bd=db;\\;ce=eca;\\;de=edb;\\;cca=ccae\\rangle\\]\n\\end{theorem}\nApplying Algorithm~\\ref{protocolmonoidalgo} to the above presentation produces the Swift program in Listing \\ref{undecidableproto}. The requirement machine must be able to solve the word problem in any protocol definition it does accept. Therefore, this protocol definition must be rejected as invalid by the requirement machine. The best we can do is carve out a useful sub-class of protocols where the word problem is decidable, and reject all other protocol definitions. This is the focus of the next chapter.\n\\begin{listing}\\caption{Protocol with undecidable word problem}\\label{undecidableproto}\n\\begin{Verbatim}\nprotocol Impossible {\n associatedtype A : Impossible\n associatedtype B : Impossible\n associatedtype C : Impossible\n associatedtype D : Impossible\n associatedtype E : Impossible\n where A.C == C.A, A.D == D.A\n B.C == C.B, B.D == D.B\n C.E == E.C.A,\n D.E == E.D.B\n C.C.A == C.C.A.E\n}\n\\end{Verbatim}\n\\end{listing}\n\n\\chapter{Rewrite Systems}\\label{rewritesystemintro}\n\nThis section presents an informal introduction to the theory of \\emph{rewrite systems}. A very thorough treatment of this subject can be found in \\cite{andallthat}. This book talks about rewrite systems that manipulate more general ``tree-like'' algebraic terms, of which strings are just a special case. The requirement machine only needs \\emph{string} rewriting, which greatly simplifies the theory, so I will re-state some of the key ideas in a self-contained manner below.\n\nTo motivate some formal definitions, let's look at another finitely-presented monoid:\n\\[\\langle a,b,c;\\; cc=c,\\; a=ba,\\; ca=a\\rangle\\]\nThe intuitive mental model is that these equations are bi-directional; the equation $c=cc$ could just as easily been written as $cc=c$.\n\nThe bi-directional nature of these equations will become apparent in the proof that $acca=bcaa$. First, let's list and number the relations:\n\\begin{align}\ncc&\\Longleftrightarrow c\\tag{1}\\\\\na&\\Longleftrightarrow ba\\tag{2}\\\\\nca&\\Longleftrightarrow a\\tag{3}\n\\end{align}\nStarting with the term $acca$, you can replace the $cc$ with $c$ by applying equation (1) in the $\\Rightarrow$ direction, leaving us with $aca$. Then you can continue applying equations as follows:\n\\begin{align}\na\\underline{cc}a&\\rightarrow a\\underline{c}a\\tag{Eq 1, $\\Rightarrow$}\\\\\n\\underline{a}ca&\\rightarrow \\underline{ba}ca\\tag{Eq 2, $\\Rightarrow$}\\\\\nb\\underline{a}ca&\\rightarrow b\\underline{ca}ca\\tag{Eq 3, $\\Leftarrow$}\\\\\nbca\\underline{ca}&\\rightarrow bca\\underline{a}\\tag{Eq 3, $\\Rightarrow$}\n\\end{align}\nIt so happens that the monoid presented above has a decidable word problem. Despite that, from looking at the presentation of the monoid, it is not immediately apparent that $acca=bcaa$, and proving this fact required applying equations in both directions, making the intermediate terms ``larger'' and ``smaller'' at different steps. This doesn't seem to produce a viable evaluation strategy. So clearly some additional structure is needed, even for this simple example.\n\n\\index{rewrite rules}\n\\index{irreducible term}\n\\index{reducing a term}\nInstead of looking for a way to transform one term into another by applying equations in both directions, you can ``orient'' the relations by choosing to only apply the direction where the left-hand side is always larger than the right-hand side. This turns the equations into unidirectional rewrite rules:\n\\begin{align}\ncc&\\Longrightarrow c\\tag{1}\\\\\nba&\\Longrightarrow a\\tag{2}\\\\\nca&\\Longrightarrow a\\tag{3}\n\\end{align}\nThis guarantees that at each step, the original term can only become shorter. If a term can be transformed into another term by applying zero or more unidirectional rewrite rules, the original term is said to \\emph{reduce} to the other term. A term which cannot be reduced further is said to be \\emph{irreducible}. Now you can reformulate the word problem slightly. Instead of attempting to transform an arbitrary term into another, you reduce both terms as much as possible. If both terms have the same irreducible form, they must be equivalent.\n\nLet's attempt this new strategy with our original inputs, $acca$ and $bcaa$. First, $acca$ reduces to $aa$:\n\\begin{align}\na\\underline{cc}a&\\rightarrow a\\underline{c}a\\tag{Rule 1}\\\\\na\\underline{ca}&\\rightarrow a\\underline{a}\\tag{Rule 3}\n\\end{align}\nAt this point, the term $aa$ is irreducible. Now, $bcaa$ also reduces to $aa$:\n\\begin{align}\nb\\underline{ca}a&\\rightarrow b\\underline{a}a\\tag{Rule 3}\\\\\n\\underline{ba}a&\\rightarrow \\underline{a}a\\tag{Rule 2}\n\\end{align}\nThis shows that both $acca$ and $bcaa$ reduce to $aa$; therefore, $acca=bcaa$. In fact, this strategy completely solves the word problem in this specific monoid at least. It won't work in many other interesting cases, as you will see below, but it forms the basis for what comes next.\n\nNow, I will formalize what is meant by rewrite rules producing a ``shorter'' term at every step. The following definitions are standard.\n\\index{partial order}\n\\index{linear order}\n\\begin{definition}\\label{partialorderdef}\nA \\emph{partial order} on a set $S$ is a relation $<$ satisfying two properties:\n\\begin{itemize}\n\\item (Transitivity) If $xx_2>x_3>\\ldots>x_n>\\ldots\\]\n\\end{definition}\n\nUsing a well-founded order guarantees that applying a reduction relation until fixed point will always terminate, since a non-terminating reduction sequence would witness an infinite descending chain, contradicting the assumption of well-foundedness.\n\n\\index{translation-invariant relation}\nA partial order used for reduction must also be translation-invariant (Definition~\\ref{transinv}). Translation invariance means that if you have a rule like $ca\\Rightarrow a$, then not only is it true that $ca>a$, but also replacing $ca$ with $a$ anywhere in the \\emph{middle} of a term produces a smaller term; for example $bcab$ can be reduced to $bab$, because $ca>a$ implies that $bcab>bab$.\n\\begin{definition}A \\emph{reduction order} on the free monoid $A^*$ is a well-founded and translation invariant partial order.\n\\end{definition}\nNext, I will define the specific reduction order used from here on out. This generalizes the canonical type order from Section~\\ref{canonicaltypes}.\n\n\\index{shortlex order}\n\\index{translation-invariant relation}\n\\index{linear order}\n\\index{well-founded order}\n\\begin{definition}(Shortlex order)\\label{shortlex}\nSuppose $A^*$ is a free monoid where the generating set $A$ is equipped with a partial order $<$. This partial order can be extended to the \\emph{shortlex order} on $A^*$, also written as $<$. For $x, y\\in A^*$, $xab>aab>aaab>aaaab>\\ldots\\]\n\nFinally, I can formalize the notion of ``reducing'' terms by making them ``smaller''.\n\\index{relation}\n\\index{reduction relation}\n\\begin{definition}[Reduction relation]\\label{transinvdef} If $A^*$ is equipped with a reduction order $<$, then a relation $\\rightarrow$ is a \\emph{reduction relation} with respect to $<$ if $x\\rightarrow y$ implies that $y$, the inverse relation of $<$. \n\\end{definition}\n\\index{rewrite system}\nAs you saw in the previous example, a reduction relation for a finitely-presented monoid can be constructed by orienting the equations from the presentation with respect to some reduction order, a process which converts the equations into rewrite rules. Such a set of rewrite rules is called a \\emph{rewrite system}. There is a simple algorithm for reducing a term into an irreducible form:\n\\begin{algorithm}[Reducing a term]\\label{reducingaterm} Let $t$ be a term in some rewrite system $R$.\n\\begin{enumerate}\n\\item Initialize the boolean flag to false.\n\\item If there is some rewrite rule $x\\Rightarrow y$ in $R$ such that $t$ contains $x$ as a subterm,\n\\begin{itemize}\n\\item write $t=u\\otimes x\\otimes v$ for some prefix $u$ and suffix $v$,\n\\item set $t$ to $u\\otimes y\\otimes v$, replacing the occurrence of $x$ with $y$,\n\\item set the flag to true.\n\\end{itemize}\n\\item If the flag is now true, go back to Step 1.\n\\item Otherwise, the algorithm returns with the final value of $t$.\n\\end{enumerate}\n\\end{algorithm}\n\n\\section{Confluence and Completion}\\label{confluenceandcompletion}\nApplying Algorithm \\ref{reducingaterm} to the relations of a finitely-presented monoid let us solve the word problem, at least in one case. Of course this can't solve the word problem in all cases, since the word problem is undecidable. So where does this approach go wrong?\n\nThe basic problem is right there in the name---we're using a reduction \\emph{relation}, not a ``reduction function,'' so for a given term $x\\in A^*$, there might be two (or more) distinct terms $y$, $z\\in A^*$ such that both $x\\rightarrow y$ and $x\\rightarrow z$ can apply. This corresponds to non-determinism in Step~2 of Algorithm~\\ref{reducingaterm}, where a choice has to be made between multiple rules which could all apply at a single step.\n\nTo see this phenomenon in action, consider the following finitely-presented monoid:\n\\[\\langle a, b, c, d;\\; ab=a,\\; bc=b,\\; d=b\\rangle\\]\nI'm going to use the order $a{t}_2{\\downarrow}$),}\\]\nor\n\\[{t}_2{\\downarrow}\\Rightarrow {t}_1{\\downarrow}\\qquad\\hbox{(if ${t}_2{\\downarrow}>{t}_1{\\downarrow}$).}\\]\nThe process for resolving critical pairs is summarized in Figure \\ref{criticalfig}.\n\\end{enumerate}\n\\item If the above loop added new rules, go back to Step 1 to check if any of the new rules overlap with existing rules. Otherwise, all critical pairs have been resolved and the completion procedure has produced a confluent rewrite system.\n\\item There is a final simplification step. For each rule $x\\Rightarrow y$,\n\\begin{enumerate}\n\\item If $x$ can be reduced by some other rule $x'\\Rightarrow y'$, meaning $x=ux'w$ for some $u$, $v\\in A^*$, delete $x\\Rightarrow y$.\n\nThis deletion is valid; since the rewrite system is now confluent, rewrite rules can be applied in any order, meaning $x'\\Rightarrow y'$ can always be applied before $x\\Rightarrow y$, so there is never any reason to apply $x\\Rightarrow y$. \n\\item Otherwise, reduce $y$ to canonical form ${y}\\,{\\downarrow}$, and replace the rule $x\\Rightarrow y$ with $x\\Rightarrow {y}\\,{\\downarrow}$.\n\\end{enumerate}\n\\end{enumerate}\n\\end{algorithm}\n\\begin{figure}\\caption{Resolving critical pairs in Algorithm \\ref{knuthbendix}}\\label{criticalfig}\n\\begin{center}\n\\begin{tikzcd}\n&uvw \\arrow[ld, bend right] \\arrow[rd, bend left] \\\\\nt_1\\arrow[d]&&t_2\\arrow[d]\\\\\n{t}_1{\\downarrow}\\arrow[rr, leftrightarrow, dashed]&&{t}_2{\\downarrow}\n\\end{tikzcd}\n\\end{center}\n\\end{figure}\n\\index{convergent presentation}\nIf the Knuth-Bendix completion procedure terminates after a finite number of steps, the monoid is said to be \\emph{convergent}. If the monoid is not convergent, the algorithm will continue adding new rewrite rules forever, as longer and longer overlapped terms are discovered in Step 2. In practice, you want an algorithm that will succeed or fail, instead of always succeeding after a possibly-infinite number of steps. This is can be handled by limiting the maximum number of iterations or the maximum length of the left-hand side of a rewrite rule. If either limit is exceeded, the rewrite system is rejected.\n\nPreviously I showed you a couple of finitely-presented monoids and made some hand-wavy claims about the resulting rewrite system. By applying the Knuth-Bendix algorithm we can verify that those claims were correct.\n\n\\begin{example}[Trivial case]\\label{trivialex}\nIn this example, I claimed that orienting the equations to form rewrite rules and applying them in any order is sufficient to solve the word problem:\n\\[\\langle a,b,c;\\; cc=c,\\; a=ba,\\; ca=a\\rangle\\]\nTo see why, you can check for overlapping rules. There is a single overlapping pair of rules, $cc\\Rightarrow c$ and $ca\\Rightarrow a$. The overlapped term is $cca$. Reducing this term with both rules produces the pair $(ca,ca)$. Reducing both sides yields the critical pair $(a, a)$. This critical pair is trivial, so the Knuth-Bendix algorithm terminates successfully without adding any new rules; the rewrite system is already confluent. Figure \\ref{trivialfig} summarizes this.\\footnote{The idea of representing critical pairs as diagrams comes from \\cite{guiraud:hal-00818253}.}\n\\begin{figure}\\caption{Trivial critical pair in Example \\ref{trivialex}}\\label{trivialfig}\n\\begin{center}\n\\begin{tikzcd}\n&cca \\arrow[ld, bend right] \\arrow[rd, bend left] \\\\\nca\\arrow[rr, equal]&&ca\n\\end{tikzcd}\n\\end{center}\n\\end{figure}\n\\end{example}\n\n\\begin{example}[Adding a single rule]\\label{singleruleex}\nIn this example, I claimed that adding the single rule $ac\\Rightarrow a$ ensures the resulting rewrite system is confluent:\n\\[\\langle a, b, c, d;\\; ab=a,\\; bc=b,\\; d=b\\rangle\\]\nOnce again, you can check for overlapping rules. There is a single overlapping pair of rules, $ab\\Rightarrow a$ and $bc\\Rightarrow b$. The overlapped term is $abc$. Reducing this term with both rules produces the pair $(ac,ab)$. While $ac$ is irreducible, you can further reduce $ab$ to $a$. This yields the critical pair $(ac,a)$, which is resolved by adding a new rule $ac\\Rightarrow a$. A second iteration of the Knuth-Bendix algorithm does not discover any new critical pairs, so the algorithm terminates successfully. Once again, this can be summarized in a diagram, show in Figure \\ref{singleruleex}.\n\\begin{figure}\\caption{Critical pair in Example \\ref{singleruleex}}\\label{singlerulefig}\n\\begin{center}\n\\begin{tikzcd}\n&abc \\arrow[ld, bend right] \\arrow[rd, bend left] \\\\\nac\\arrow[d, equal]&&ab \\arrow[d]\\\\\nac\\arrow[rr, dashed]&&a\n\\end{tikzcd}\n\\end{center}\n\\end{figure}\n\\end{example}\n\n\\index{convergent presentation}\nNow I will show you a finitely-presented monoid where the presentation is not convergent.\n\\begin{example}[Infinite case]\\label{infiniteex}\nConsider the following finitely-presented monoid $M$:\n\\[\\langle a, b;\\; aba=ab\\rangle\\]\nThe rule $aba\\Rightarrow ab$ overlaps with itself. The overlapped term is $ababa$. There are two ways to reduce this term using our rule, which yields the pair $(abba, abab)$. The second term in the pair, $abab$, can be reduced with a further application of our original rule, producing the critical pair $(abba, abb)$. Resolving this critical pair adds a new rewrite rule $abba\\Rightarrow abb$.\n\nA new rule was added, so the algorithm runs again. This time, we have an overlap between the new rule $abba\\Rightarrow abb$ and the original rule $aba\\Rightarrow ab$. The overlapped term is $abbaba$. Reducing this term with both rules produces the pair $(abbba, abbab)$. The second term in the pair, $abbab$, can be reduced with a further application of $abba\\Rightarrow abb$, yields the critical pair $(abbba, abbb)$. Resolving this critical pair adds a new rewrite rule $abbba\\Rightarrow abbb$.\n\nThis process continues forever, adding an infinite series of rewrite rules of the form\n\\[ab^na\\Rightarrow ab^n\\]\nFigure \\ref{infinitefig} shows these ``runaway'' critical pairs in diagram form.\n\\begin{figure}\\caption{Infinitely many critical pairs in Example \\ref{infiniteex}}\\label{infinitefig}\n\\begin{center}\n\\begin{tikzcd}\n&ababa \\arrow[ld, bend right] \\arrow[rd, bend left] \\\\\nabba\\arrow[d, equal]&&abab \\arrow[d]\\\\\nabba\\arrow[rr, dashed]&&abb\n\\end{tikzcd}\n\\begin{tikzcd}\n&abbaba \\arrow[ld, bend right] \\arrow[rd, bend left] \\\\\nabbba\\arrow[d, equal]&&abbab \\arrow[d]\\\\\nabbba\\arrow[rr, dashed]&&abbb\n\\end{tikzcd}\n\\begin{tikzcd}\n&ab^{n-1}aba \\arrow[ld, bend right] \\arrow[rd, bend left] \\\\\nab^na\\arrow[d, equal]&&ab^{n-1}ab \\arrow[d]\\\\\nab^na\\arrow[rr, dashed]&&ab^n\n\\end{tikzcd}\n\\end{center}\n\\end{figure}\n\\end{example}\n\nThe interesting thing about Example \\ref{infiniteex} is that the word problem in this monoid is still decidable, just not via this particular application of the Knuth-Bendix algorithm. Indeed, applying the Knuth-Bendix algorithm to a different presentation of the same monoid can still produce a confluent rewrite system.\n\n\\begin{example}[A different presentation]\\label{diffpresex}\nConsider the following equivalent presentation of the above monoid; call it $M'$:\n\\[\\langle t, u, v;\\; uv=t,\\; tu=t\\rangle\\]\n\\index{isomorphism}\nFirst of all, I should prove that $M$ and $M'$ are isomorphic by exhibiting an isomorphism $\\varphi\\colon~M'\\rightarrow M$:\n\\begin{align*}\nt&\\leftrightarrow ab\\\\\nu&\\leftrightarrow a\\\\\nv&\\leftrightarrow b\n\\end{align*}\nTo convince yourself that this is an isomorphism, apply $\\varphi$ to both sides of the relations in the presentation of $M'$:\n\\begin{itemize}\n\\item Applying $\\varphi$ to $uv=t$ gives $ab=ab$, which is trivial.\n\\item Applying $\\varphi$ to $tu=t$ gives $aba=ab$, which is the defining relation of $M$.\n\\end{itemize}\nGoing in the other direction, there is only the single relation in the presentation of $M$ to check:\n\\begin{itemize}\n\\item $\\varphi^{-1}$ applied to $aba=ab$ becomes $tu=t$, which is one of the defining relations of $M'$.\n\\end{itemize}\n\nNow, if you run the Knuth-Bendix algorithm on $M'$ you will see that $tu\\Rightarrow t$ overlaps with $uv\\Rightarrow t$. The overlapped term is $tuv$. Reducing this term with both rules produces the critical pair $(tv, tt)$. Orienting this pair produces a new rewrite rule $tv\\Rightarrow tt$. This is shown in Figure \\ref{diffpresfig}.\n\\begin{figure}\\caption{Critical pair in Example \\ref{diffpresex}}\\label{diffpresfig}\n\\begin{center}\n\\begin{tikzcd}\n&tuv \\arrow[ld, bend right] \\arrow[rd, bend left] \\\\\ntv\\arrow[rr, leftarrow, dashed]&&tt\n\\end{tikzcd}\n\\end{center}\n\\end{figure}\n\nA second iteration of the Knuth-Bendix algorithm does not discover any new critical pairs, so the algorithm terminates successfully. You will encounter this example again in Section \\ref{associatedtypes}.\n\\end{example}\n\nYou might ask, can \\emph{any} finitely-presented monoid with a decidable word problem be presented as a confluent rewrite system, just maybe with a different set of generators and relations? Unfortunately the answer is ``no,'' meaning there are ``bespoke'' monoids where the word problem is decidable, just not via the Knuth-Bendix algorithm.\n\\begin{theorem}[From \\cite{SQUIER1994271}] The following finitely-presented monoid has a decidable word problem, but cannot be presented as a confluent rewrite system:\n\\[\\langle a, b, t, x, y;\\; ab=\\varepsilon,\\; xa=atx,\\; xt=tx,\\; xb=bx,\\; xy=\\varepsilon\\rangle\\]\n\\end{theorem}\nThis result together with Theorem \\ref{undecidablemonoid} means the inclusions here are proper:\n\\[\n\\begin{array}{c}\n\\hbox{Confluent rewrite systems} \\\\\n\\subsetneq \\\\\n\\hbox{Decidable word problems} \\\\\n\\subsetneq \\\\\n\\hbox{Finitely-presented monoids}\n\\end{array}\n\\]\n\n\\chapter{Protocols are Monoids}\\label{protocolsasmonoids}\n\nTo recap the most important results from the two previous chapters:\n\\begin{itemize}\n\\item Algorithm \\ref{protocolmonoidalgo} shows how to construct a well-formed protocol definition from a finitely-presented monoid,\n\n\\item Theorem \\ref{protocolmonoidthm} shows that generic signature queries on this protocol can express the word problem,\n\\item Theorem \\ref{undecidablemonoid} shows that the word problem on finitely-presented monoids is in general undecidable,\n\\item Algorithm \\ref{knuthbendix} shows how to build a confluent rewrite system to solve the word problem on a finitely-presented monoid with a convergent presentation.\n\\end{itemize}\nThe ultimate goal here is to solve generic signature queries using a confluent rewrite system, but first a more general method for constructing a finitely-presented monoid from a set of Swift protocol definitions is needed. While Theorem \\ref{protocolmonoidthm} defined an isomorphism between finitely-presented monoids and a restricted subset of Swift protocols, it doesn't immediately generalize beyond protocols that satisfy some rather stringent restrictions:\n\\begin{itemize}\n\\item every associated type must conform to the same protocol,\n\\item conformance requirements to other protocols are not allowed,\n\\item the only kind of generic requirement allowed in a \\texttt{where} clause is a same-type requirement between type parameters.\n\\end{itemize}\n\\index{conformance requirement}\n\\index{same-type requirement}\nThis chapter sketches an overview of the more general construction by building the rewrite system from a stripped down set of standard library protocols, shown in Listing \\ref{protocolrewritesystemex}. I will call the formulation presented in this chapter ``the requirement machine with name and protocol symbols,'' to distinguish it from the real formulation, introduced in the next chapter.\n\n\\index{associated type}\n\\index{name symbol}\n\\index{protocol symbol}\n\\index{protocol Self type}\nFirst of all, the alphabet of this rewrite system will include the names of the associated types: $\\namesym{Element}$, $\\namesym{Iterator}$, and $\\namesym{SubSequence}$. Since there are multiple protocols in play, the alphabet also needs to be extended with additional symbols that represent protocol names.\n\nThese new protocol symbols are distinct from name symbols, so I'm going to write them differently:\n\\begin{itemize}\n\\item $\\namesym{Horse}$ is a name symbol;\n\\item $\\protosym{Horse}$ is a protocol symbol.\n\\end{itemize}\nThe four protocol symbols that will be used in this example are $\\protosym{IteratorProtocol}$, $\\protosym{Sequence}$, $\\protosym{Collection}$, and $\\protosym{OptionSet}$. Equipped with these, the type lowering map from Definition~\\ref{liftingloweringmaps} can be generalized to produce terms that are ``rooted'' in a protocol symbol.\n\n\\begin{listing}\\caption{Example protocols for building a rewrite system}\\label{protocolrewritesystemex}\n\\begin{Verbatim}\nprotocol IteratorProtocol {\n associatedtype Element\n}\n\nprotocol Sequence {\n associatedtype Element\n where Iterator.Element == Element\n associatedtype Iterator : IteratorProtocol\n}\n\nprotocol Collection : Sequence {\n associatedtype SubSequence : Collection\n where SubSequence.SubSequence == SubSequence,\n SubSequence.Element == Element\n}\n\nprotocol OptionSet : Collection\n where Element == Self {\n}\n\\end{Verbatim}\n\\end{listing}\n\n\\index{type lowering map}\n\\begin{definition}\\label{typelowering1} For each protocol $\\proto{P}$, define the \\emph{type lowering map} $\\Lambda_{\\proto{P}}:\\mathsf{Type}\\rightarrow\\mathsf{Term}$ as follows:\n\\begin{itemize}\n\\item The protocol $\\genericparam{Self}$ type appearing at the root of of a type parameter maps to the protocol symbol $\\protosym{P}$.\n\\item Each subsequent associated type name $\\namesym{T}$ maps to a name symbol $\\namesym{T}$.\n\\end{itemize}\nThis definition will be refined further in Chapter~\\ref{requirementmachine}, but it is good enough for now.\n\\end{definition}\nWith this new formulation, when a type parameter like $\\genericparam{Self}.\\namesym{Iterator}.\\namesym{Element}$ appears in the requirement signature of $\\proto{Sequence}$, the lowered term is now ``qualified'' with the protocol whence it came:\n\\[\\protosym{Sequence}.\\namesym{Iterator}.\\namesym{Element}\\]\n\n\\index{requirement lowering map}\nThe final step is to encode conformance requirements and same-type requirements as rewrite rules using a requirement lowering map.\n\\begin{definition}\\label{reqlowering1} The \\emph{requirement lowering map} $\\Lambda_{\\proto{P}}\\colon\\namesym{Requirement}\\rightarrow\\namesym{Rule}$ takes as input a generic requirement in the protocol $\\proto{P}$, and produces a rewrite rule using the type lowering map $\\Lambda_{\\proto{P}}\\colon\\namesym{Type}\\rightarrow\\namesym{Term}$ to lower types to terms:\n\\begin{itemize}\n\\item \\textbf{Protocol conformance requirements} $\\namesym{T}\\colon\\proto{P}$ lower to a rule eliminating a protocol symbol from the end of the lowered term for $\\namesym{T}$:\n\\[\\Lambda_{\\proto{P}}(\\namesym{T}).\\protosym{P} \\Rightarrow \\Lambda_{\\proto{P}}(\\namesym{T})\\]\n\\item \\textbf{Same-type requirements} $\\namesym{T}==\\namesym{U}$ lower to an equivalence of terms. Assuming that $\\Lambda_{\\proto{P}}(\\namesym{T}) > \\Lambda_{\\proto{P}}(\\namesym{U})$ in the reduction order on terms (if not, flip the terms around):\n\\[\\Lambda_{\\proto{P}}(\\namesym{T}) \\Rightarrow \\Lambda_{\\proto{P}}(\\namesym{U})\\]\n\\end{itemize}\nThis definition does not support layout, superclass or concrete type requirements. Those will be addressed in Chapter~\\ref{requirementmachine}.\n\\end{definition}\nApplying the requirement lowering map to the conformance requirements in our example produces eight rules: four same-type requirements, and four conformance requirements:\n\\begin{align}\n\\protosym{Sequence}.\\namesym{Iterator}.\\namesym{Element} &\\Rightarrow \\protosym{Sequence}.\\namesym{Element}\\tag{1}\\\\\n\\protosym{Collection}.\\namesym{SubSequence}.\\namesym{SubSequence} &\\Rightarrow \\protosym{Collection}.\\namesym{SubSequence}\\tag{2}\\\\\n\\protosym{Collection}.\\namesym{SubSequence}.\\namesym{Element} &\\Rightarrow \\protosym{Collection}.\\namesym{Element}\\tag{3}\\\\\n\\protosym{OptionSet}.\\namesym{Element} &\\Rightarrow \\protosym{OptionSet}\\tag{4}\\\\\n\\protosym{Sequence}.\\namesym{Iterator}.\\protosym{IteratorProtocol} &\\Rightarrow \\protosym{Sequence}.\\namesym{Iterator}\\tag{5}\\\\\n\\protosym{Collection}.\\protosym{Sequence} &\\Rightarrow \\protosym{Collection}\\tag{6}\\\\\n\\protosym{Collection}.\\namesym{SubSequence}.\\protosym{Collection} &\\Rightarrow \\protosym{Collection}.\\namesym{SubSequence}\\tag{7}\\\\\n\\protosym{OptionSet}.\\protosym{Collection} &\\Rightarrow \\protosym{OptionSet}\\tag{8}\n\\end{align}\n(Note that protocol inheritance being the trivial case of a conformance requirement on $\\genericparam{Self}$ explains why Rule 6 and Rule 8 look the way they do.)\n\nIntuitively, a protocol symbol at the \\emph{beginning} of a term means ``this rule applies to type parameters that conform to this protocol''; a protocol symbol at the \\emph{end} of a term means ``if you can construct this term, you \\emph{know} it conforms to this protocol''.\n\n\\index{confluence}\n\\index{Knuth-Bendix algorithm}\nThere's one more thing. This rewrite system is not confluent! For example, Rule~6 and Rule~1 overlap on the following term:\n\\[\\protosym{Collection}.\\protosym{Sequence}.\\namesym{Iterator}.\\namesym{Element}\\]\n\\index{canonical form of a term}\nThankfully, the Knuth-Bendix algorithm finishes successfully after three rounds, albeit adding a very large number of new rules, as you will see shortly. Nevertheless, this construction is good enough to solve a couple of generic signature queries, at least for type parameters from generic signatures of the form $\\gensig{\\genericparam{Self}}{\\genericparam{Self}\\colon\\proto{P}}$. The two queries and their implementation:\n\\begin{itemize}\n\\item \\texttt{areSameTypeParametersInContext(T, U)} answers true if the terms $\\Lambda_{\\proto{P}}(T)$ and $\\Lambda_{\\proto{P}}(U)$ both reduce to the same canonical form.\n\\item \\texttt{requiresProtocol(T, Q)} answers true if the terms $\\Lambda_{\\proto{P}}(T)$ and $\\Lambda_{\\proto{P}}(T).\\protosym{Q}$ both reduce to the same canonical form.\n\\end{itemize}\n\\begin{example}\nYou can show that $\\genericparam{Self}.\\namesym{SubSequence}.\\namesym{SubSequence}.\\namesym{Iterator}.\\namesym{Element}$ is equivalent to $\\genericparam{Self}$ in the $\\proto{OptionSet}$ protocol:\n\\begin{align}\n\\protosym{OptionSet}.\\namesym{SubSequence}.&\\namesym{SubSequence}.\\namesym{Iterator}.\\namesym{Element}\\nonumber\\\\\n&\\rightarrow\\protosym{OptionSet}.\\namesym{SubSequence}.\\namesym{Iterator}.\\namesym{Element}\\tag{Rule 11}\\\\\n&\\rightarrow\\protosym{OptionSet}\\tag{Rule 20}\n\\end{align}\nRule 11 was added by resolving the overlap between Rule~8 and Rule~3. Rule 20 was added by resolving the overlap between Rule~8 and Rule~15, which was added when resolving the overlap between Rule~10 and Rule~1, and finally, Rule~10 was added by resolving the overlap between Rule~7 and Rule~6.\n\\end{example}\n\\begin{example}\nThe $\\genericparam{Self}.\\namesym{SubSequence}.\\namesym{SubSequence}$ type parameter in the $\\proto{Collection}$ protocol conforms to $\\proto{Sequence}$:\n\\begin{align}\n\\protosym{Collection}.\\namesym{SubSequence}.&\\namesym{SubSequence}.\\protosym{Sequence}\\nonumber\\\\\n&\\rightarrow\\protosym{Collection}.\\namesym{SubSequence}.\\protosym{Sequence}\\tag{Rule 2}\\\\\n&\\rightarrow\\protosym{Collection}.\\namesym{SubSequence}\\tag{Rule 10}\n\\end{align}\n\\end{example}\n\n\\begin{listing}\\caption{Rewrite system for $\\proto{IteratorProtocol}$, $\\proto{Sequence}$, $\\proto{Collection}$ and $\\proto{OptionSet}$}\\label{rewritesystemcompleted}\n\\begin{itemize}\n\\item The initial set of rules obtained by lowering protocol requirement signatures:\n\\begin{align}\n\\protosym{S}.\\namesym{Iterator}.\\namesym{Element}&\\Rightarrow\\protosym{S}.\\namesym{Element}\\tag{1}\\\\\n\\protosym{C}.\\namesym{SubSequence}.\\namesym{SubSequence}&\\Rightarrow\\protosym{C}.\\namesym{SubSequence}\\tag{2}\\\\\n\\protosym{C}.\\namesym{SubSequence}.\\namesym{Element}&\\Rightarrow\\protosym{C}.\\namesym{Element}\\tag{3}\\\\\n\\protosym{O}.\\namesym{Element}&\\Rightarrow\\protosym{O}\\tag{4}\\\\\n\\protosym{S}.\\namesym{Iterator}.\\protosym{I}&\\Rightarrow\\protosym{S}.\\namesym{Iterator}\\tag{5}\\\\\n\\protosym{C}.\\protosym{S}&\\Rightarrow\\protosym{C}\\tag{6}\\\\\n\\protosym{C}.\\namesym{SubSequence}.\\protosym{C}&\\Rightarrow\\protosym{C}.\\namesym{SubSequence}\\tag{7}\\\\\n\\protosym{O}.\\protosym{C}&\\Rightarrow\\protosym{O}\\tag{8}\n\\end{align}\n\\item New rules added by the first round of the completion procedure:\n\\begin{align}\n\\protosym{C}.\\namesym{Iterator}.\\namesym{Element}&\\Rightarrow\\protosym{C}.\\namesym{Element}\\tag{9}\\\\\n\\protosym{C}.\\namesym{SubSequence}.\\protosym{S}&\\Rightarrow\\protosym{C}.\\namesym{SubSequence}\\tag{10}\\\\\n\\protosym{O}.\\namesym{SubSequence}.\\namesym{SubSequence}&\\Rightarrow\\protosym{O}.\\namesym{SubSequence}\\tag{11}\\\\\n\\protosym{O}.\\namesym{SubSequence}.\\namesym{Element}&\\Rightarrow\\protosym{O}\\tag{12}\\\\\n\\protosym{O}.\\protosym{S}&\\Rightarrow\\protosym{O}\\tag{13}\\\\\n\\protosym{O}.\\namesym{SubSequence}.\\protosym{C}&\\Rightarrow\\protosym{O}.\\namesym{SubSequence}\\tag{14}\n\\end{align}\n\\item New rules added by the second round of the completion procedure:\n\\begin{align}\n\\protosym{C}.\\namesym{SubSequence}.\\namesym{Iterator}.\\namesym{Element}&\\Rightarrow\\protosym{C}.\\namesym{Element}\\tag{15}\\\\\n\\protosym{C}.\\namesym{SubSequence}.\\namesym{Iterator}.\\protosym{I}&\\Rightarrow\\protosym{C}.\\namesym{SubSequence}.\\namesym{Iterator}\\tag{16}\\\\\n\\protosym{O}.\\namesym{Iterator}.\\namesym{Element}&\\Rightarrow\\protosym{O}\\tag{17}\\\\\n\\protosym{O}.\\namesym{Iterator}.\\protosym{I}&\\Rightarrow\\protosym{O}.\\namesym{Iterator}\\tag{18}\\\\\n\\protosym{O}.\\namesym{SubSequence}.\\protosym{S}&\\Rightarrow\\protosym{O}.\\namesym{SubSequence}\\tag{19}\n\\end{align}\n\\item New rules added by the third and final round of the completion procedure:\n\\begin{align}\n\\protosym{O}.\\namesym{SubSequence}.\\namesym{Iterator}.\\namesym{Element}&\\Rightarrow\\protosym{O}\\tag{20}\\\\\n\\protosym{O}.\\namesym{SubSequence}.\\namesym{Iterator}.\\protosym{I}&\\Rightarrow\\protosym{O}.\\namesym{SubSequence}.\\namesym{Iterator}\\tag{21}\n\\end{align}\n\\end{itemize}\n\\end{listing}\n\n\\begin{figure}\\caption{Non-trivial critical pairs resolved on the first iteration of the Knuth-Bendix algorithm.}\\label{rewritesystemfig1}\n\\begingroup\n\\tiny\n\\begin{center}\n\n\\begin{tikzcd}\n&\\mathmakebox[0pt][c]{\n\\protosym{C}.\\protosym{S}.\\namesym{Iterator}.\\namesym{Element}\n}\\arrow[ld, yshift=-3pt, shorten=6pt] \\arrow[rd, yshift=-3pt, shorten=6pt] \\\\\n\\protosym{C}.\\namesym{Iterator}.\\namesym{Element}\n\\arrow[d, equal] &&\n\\protosym{C}.\\protosym{S}.\\namesym{Element}\n\\arrow[d] \\\\\n\\protosym{C}.\\namesym{Iterator}.\\namesym{Element}\n\\arrow[rr, dashed] &&\n\\protosym{C}.\\namesym{Element}\n\\end{tikzcd}\n\n\\vspace{10mm}\n\n\\begin{tikzcd}\n&\\mathmakebox[0pt][c]{\n\\protosym{C}.\\namesym{SubSequence}.\\protosym{C}.\\protosym{S}\n}\\arrow[ld, yshift=-3pt, shorten=6pt] \\arrow[rd, yshift=-3pt, shorten=6pt] \\\\\n\\protosym{C}.\\namesym{SubSequence}.\\protosym{S}\n\\arrow[d, equal] &&\n\\protosym{C}.\\namesym{SubSequence}.\\protosym{C}\n\\arrow[d] \\\\\n\\protosym{C}.\\namesym{SubSequence}.\\protosym{S}\n\\arrow[rr, dashed] &&\n\\protosym{C}.\\namesym{SubSequence}\n\\end{tikzcd}\n\n\\vspace{10mm}\n\n\\begin{tikzcd}\n&\\mathmakebox[0pt][c]{\n\\protosym{O}.\\protosym{C}.\\namesym{SubSequence}.\\namesym{SubSequence}\n}\\arrow[ld, yshift=-3pt, shorten=6pt] \\arrow[rd, yshift=-3pt, shorten=6pt] \\\\\n\\protosym{O}.\\namesym{SubSequence}.\\namesym{SubSequence}\n\\arrow[d, equal] &&\n\\protosym{O}.\\protosym{C}.\\namesym{SubSequence}\n\\arrow[d] \\\\\n\\protosym{O}.\\namesym{SubSequence}.\\namesym{SubSequence}\n\\arrow[rr, dashed] &&\n\\protosym{O}.\\namesym{SubSequence}\n\\end{tikzcd}\n\n\\vspace{10mm}\n\n\\begin{tikzcd}\n&\\mathmakebox[0pt][c]{\n\\protosym{O}.\\protosym{C}.\\namesym{SubSequence}.\\namesym{Element}\n}\\arrow[ld, yshift=-3pt, shorten=6pt] \\arrow[rd, yshift=-3pt, shorten=6pt] \\\\\n\\protosym{O}.\\namesym{SubSequence}.\\namesym{Element}\n\\arrow[d, equal] &&\n\\protosym{O}.\\protosym{C}.\\namesym{Element}\n\\arrow[d] \\\\\n\\protosym{O}.\\namesym{SubSequence}.\\namesym{Element}\n\\arrow[rr, dashed] &&\n\\protosym{O}\n\\end{tikzcd}\n\n\\vspace{10mm}\n\n\\begin{tikzcd}\n&\\mathmakebox[0pt][c]{\n\\protosym{O}.\\protosym{C}.\\protosym{S}\n}\\arrow[ld, yshift=-3pt, shorten=6pt] \\arrow[rd, yshift=-3pt, shorten=6pt] \\\\\n\\protosym{O}.\\protosym{S}\n\\arrow[d, equal] &&\n\\protosym{O}.\\protosym{C}\n\\arrow[d] \\\\\n\\protosym{O}.\\protosym{S}\n\\arrow[rr, dashed] &&\n\\protosym{O}\n\\end{tikzcd}\n\n\\vspace{10mm}\n\n\\begin{tikzcd}\n&\\mathmakebox[0pt][c]{\n\\protosym{O}.\\protosym{C}.\\namesym{SubSequence}.\\protosym{C}\n}\\arrow[ld, yshift=-3pt, shorten=6pt] \\arrow[rd, yshift=-3pt, shorten=6pt] \\\\\n\\protosym{O}.\\namesym{SubSequence}.\\protosym{C}\n\\arrow[d, equal] &&\n\\protosym{O}.\\protosym{C}.\\namesym{SubSequence}\n\\arrow[d] \\\\\n\\protosym{O}.\\namesym{SubSequence}.\\protosym{C}\n\\arrow[rr, dashed] &&\n\\protosym{O}.\\namesym{SubSequence}\n\\end{tikzcd}\n\n\\end{center}\n\\endgroup\n\\end{figure}\n\n\\begin{figure}\\caption{Non-trivial critical pairs resolved on the second iteration of the Knuth-Bendix algorithm.}\\label{rewritesystemfig2}\n\\begin{center}\n\\begingroup\n\\tiny\n\n\\begin{tikzcd}\n&\\mathmakebox[0pt][c]{\n\\protosym{C}.\\namesym{SubSequence}.\\protosym{C}.\\namesym{Iterator}.\\namesym{Element}\n}\\arrow[ld, yshift=-3pt, shorten=6pt] \\arrow[rd, yshift=-3pt, shorten=6pt] \\\\\n\\protosym{C}.\\namesym{SubSequence}.\\namesym{Iterator}.\\namesym{Element}\n\\arrow[d, equal] &&\n\\protosym{C}.\\namesym{SubSequence}.\\namesym{Element}\n\\arrow[d] \\\\\n\\protosym{C}.\\namesym{SubSequence}.\\namesym{Iterator}.\\namesym{Element}\n\\arrow[rr, dashed] &&\n\\protosym{C}.\\namesym{Element}\n\\end{tikzcd}\n\n\\vspace{10mm}\n\n\\begin{tikzcd}\n&\\mathmakebox[0pt][c]{\n\\protosym{C}.\\namesym{SubSequence}.\\protosym{S}.\\namesym{Iterator}.\\protosym{I}\n}\\arrow[ld, yshift=-3pt, shorten=6pt] \\arrow[rd, yshift=-3pt, shorten=6pt] \\\\\n\\protosym{C}.\\namesym{SubSequence}.\\namesym{Iterator}.\\protosym{I}\n\\arrow[rr, dashed]\n&&\n\\protosym{C}.\\namesym{SubSequence}.\\namesym{Iterator}\n\\end{tikzcd}\n\n\\vspace{10mm}\n\n\\begin{tikzcd}\n&\\mathmakebox[0pt][c]{\n\\protosym{O}.\\protosym{S}.\\namesym{Iterator}.\\namesym{Element}\n}\\arrow[ld, yshift=-3pt, shorten=6pt] \\arrow[rd, yshift=-3pt, shorten=6pt] \\\\\n\\protosym{O}.\\namesym{Iterator}.\\namesym{Element}\n\\arrow[d, equal] &&\n\\protosym{O}.\\protosym{S}.\\namesym{Element}\n\\arrow[d] \\\\\n\\protosym{O}.\\namesym{Iterator}.\\namesym{Element}\n\\arrow[rr, dashed] &&\n\\protosym{O}\n\\end{tikzcd}\n\n\\vspace{10mm}\n\n\\begin{tikzcd}\n&\\mathmakebox[0pt][c]{\n\\protosym{O}.\\protosym{S}.\\namesym{Iterator}.\\protosym{I}\n}\\arrow[ld, yshift=-3pt, shorten=6pt] \\arrow[rd, yshift=-3pt, shorten=6pt] \\\\\n\\protosym{O}.\\namesym{Iterator}.\\protosym{I}\n\\arrow[d, equal] &&\n\\protosym{O}.\\protosym{S}.\\namesym{Iterator}\n\\arrow[d] \\\\\n\\protosym{O}.\\namesym{Iterator}.\\protosym{I}\n\\arrow[rr, dashed] &&\n\\protosym{O}.\\namesym{Iterator}\n\\end{tikzcd}\n\n\\vspace{10mm}\n\n\\begin{tikzcd}\n&\\mathmakebox[0pt][c]{\n\\protosym{O}.\\namesym{SubSequence}.\\protosym{C}.\\protosym{S}\n}\\arrow[ld, yshift=-3pt, shorten=6pt] \\arrow[rd, yshift=-3pt, shorten=6pt] \\\\\n\\protosym{O}.\\namesym{SubSequence}.\\protosym{S}\\arrow[rr, dashed]\n&&\n\\protosym{O}.\\namesym{SubSequence}\n\\end{tikzcd}\n\n\\vspace{10mm}\n\n\\begin{tikzcd}\n&\\mathmakebox[0pt][c]{\n\\protosym{O}.\\namesym{SubSequence}.\\protosym{C}.\\namesym{SubSequence}.\\protosym{S}\n}\\arrow[ld, yshift=-3pt, shorten=6pt] \\arrow[rd, yshift=-3pt, shorten=6pt] \\\\\n\\protosym{O}.\\namesym{SubSequence}.\\namesym{SubSequence}.\\protosym{S}\n\\arrow[d] &&\n\\protosym{O}.\\namesym{SubSequence}.\\protosym{C}.\\namesym{SubSequence}\n\\arrow[d] \\\\\n\\protosym{O}.\\namesym{SubSequence}.\\protosym{S}\n\\arrow[rr, dashed] &&\n\\protosym{O}.\\namesym{SubSequence}\n\\end{tikzcd}\n\n\\endgroup\n\\end{center}\n\\end{figure}\n\n\\begin{figure}\\caption{Non-trivial critical pairs resolved on the third iteration of the Knuth-Bendix algorithm.}\\label{rewritesystemfig3}\n\\begin{center}\n\\begingroup\n\\tiny\n\n\\begin{tikzcd}\n&\\mathmakebox[0pt][c]{\n\\protosym{O}.\\namesym{SubSequence}.\\protosym{S}.\\namesym{Iterator}.\\namesym{Element}\n}\\arrow[ld, yshift=-3pt, shorten=6pt] \\arrow[rd, yshift=-3pt, shorten=6pt] \\\\\n\\protosym{O}.\\namesym{SubSequence}.\\namesym{Iterator}.\\namesym{Element}\n\\arrow[d, equal] &&\n\\protosym{O}.\\namesym{SubSequence}.\\protosym{S}.\\namesym{Element}\n\\arrow[d] \\\\\n\\protosym{O}.\\namesym{SubSequence}.\\namesym{Iterator}.\\namesym{Element}\n\\arrow[rr, dashed] &&\n\\protosym{O}\n\\end{tikzcd}\n\n\\vspace{10mm}\n\n\\begin{tikzcd}\n&\\mathmakebox[0pt][c]{\n\\protosym{O}.\\namesym{SubSequence}.\\protosym{S}.\\namesym{Iterator}.\\protosym{I}\n}\\arrow[ld, yshift=-3pt, shorten=6pt] \\arrow[rd, yshift=-3pt, shorten=6pt] \\\\\n\\protosym{O}.\\namesym{SubSequence}.\\namesym{Iterator}.\\protosym{I}\n\\arrow[rr, dashed]&&\n\\protosym{O}.\\namesym{SubSequence}.\\namesym{Iterator}\n\\end{tikzcd}\n\n\\endgroup\n\\end{center}\n\\end{figure}\n\n%Listing \\ref{rewritesystemcompleted} shows the full list of rules in the confluent rewrite system output by the Knuth-Bendix algorithm. Figures \\ref{rewritesystemfig1}, \\ref{rewritesystemfig2}, and \\ref{rewritesystemfig3} show the non-trivial critical pairs resolved on each iteration, using the diagram notation first introduced in Section \\ref{confluenceandcompletion}. \n\nTo get some of the subsequent listings and diagrams to fit, I abbreviated the protocol symbols, showing only the first letter of each protocol's name---think of it as a particularly silly example of a rewrite system if you want:\n\\begin{itemize}\n\\item $\\protosym{IteratorProtocol}$ becomes $\\protosym{I}$, \n\\item $\\protosym{Sequence}$ becomes $\\protosym{S}$, \n\\item $\\protosym{Collection}$ becomes $\\protosym{C}$,\n\\item $\\protosym{OptionSet}$ becomes $\\protosym{O}$.\n\\end{itemize}\n\n\\section{Some Proofs}\nNow, I'm going to prove some results about the requirement machine with name and protocol symbols.\n\n\\index{domain of a term}\n\\begin{definition}\\label{domain1} The \\emph{domain map} is a partial function that maps a term $T$ to a set of protocol names. If the first symbol in the term is a protocol symbol $\\protosym{P}$, then $\\domain(T)=\\{\\proto{P}\\}$. Otherwise, the domain map is not defined. If $\\domain(T)$ is defined, then the term $T$ is \\emph{valid}.\n\nFor now, the domain of a term always contains exactly one protocol, if the mapping is defined at all. Later on, you will see that in the full requirement machine, certain kinds of valid terms can have an empty domain, or a domain of multiple protocols.\n\\end{definition}\n\\begin{lemma}\\label{domainoflowered} For any type parameter $T$ of a protocol $\\proto{P}$, $\\domain(\\Lambda_{\\proto{P}}(T))=\\{\\proto{P}\\}$. In particular, this means the type lowering map $\\Lambda_{\\proto{P}}$ always outputs valid terms.\n\\end{lemma}\n\\begin{proof}\nThis follows from Definition~\\ref{liftingloweringmaps}, where the term constructed by $\\Lambda_{\\proto{P}}$ always begins with the protocol symbol $\\protosym{P}$.\n\\end{proof}\nThe notion of validity can be extended to rewrite rules.\n\\index{domain of a term}\n\\begin{definition}\\label{validrule}\nA rewrite rule $T\\Rightarrow U$ is \\emph{valid} if the terms $T$ and $U$ are both valid, and $\\domain(T)=\\domain(U)$.\n\\end{definition}\n\nThe next proof shows equivalent terms always have the same domain. Intuitively, this makes sense, since terms are always ``relative'' to the protocol in which they appear, and it would not make sense for a type parameter in one protocol to be equivalent to a type parameter in another protocol.\n\\begin{lemma} If ${T}{\\downarrow}={U}{\\downarrow}$ and $\\domain(T)$ is defined, then $\\domain(U)=\\domain(T)$.\n\\end{lemma}\n\\begin{proof}\\index{derivation path}\\index{monoid congruence}\nSince ${T}{\\downarrow}={U}{\\downarrow}$, $T$ and $U$ are equivalent under the monoid congruence generated by the initial set of rewrite rules, and there exists a derivation path transforming $T$ to $U$ using these rules. Say this derivation path has length $n$, and let $(s_i\\Rightarrow t_i, k_i)$ be the $i$th component. For each $i$, one of $s_i\\Rightarrow t_i$ or $t_i\\Rightarrow s_i$ is an initial rewrite rule produced by the requirement lowering map $\\Lambda_{\\proto{Q}_i}$ for some $\\proto{Q}_i$. Let $x_i$ be the $i$th intermediate term in the derivation path, where $x_0=T$ and $x_n=U$.\n\nLet $\\domain(T)=\\{\\proto{P}\\}$. Induction on the length of the derivation path will show that $\\domain(U)=\\{\\proto{P}\\}$.\n\\begin{enumerate}\n\\item The base case is where $i=0$. Here, the derivation path is empty, so $T=U$ and $\\domain(U)=\\{\\proto{P}\\}$.\n\n\\item Now, assume that all derivation paths of length $i-1$ are domain-preserving. This means that $\\domain(x_{i-1})=\\{\\proto{P}\\}$. There are two cases to consider.\n\\begin{enumerate}\n\\item The first case is there the $i$th component of the derivation path has $k_i>0$, leaving the first symbol of the intermediate term untouched. In this case, $\\domain(x_i)=\\domain(x_{i-1})$.\n\\item The second case is where $k_i=0$, meaning that the derivation path component replaces a prefix $s_i$ with $t_i$. Since $s_i$ is a prefix of $x_{i-1}$, $\\domain(s_i)=\\{\\proto{P}\\}$ by the induction hypothesis. By Definition~\\ref{reqlowering1} and Lemma~\\ref{domainoflowered}, it is also the case that $\\domain(t_i)=\\{\\proto{P}\\}$. Therefore, $\\domain(x_i)=\\{\\proto{P}\\}$.\n\\end{enumerate}\n\\item Since the final term $x_n$ is equal to $U$, it follows that $\\domain(U)=\\{\\proto{P}\\}$.\n\\end{enumerate}\n\\end{proof}\nThe above lemma has a couple of interesting consequences.\n\\begin{lemma} If a term is valid, then its canonical form ${T}{\\downarrow}$ is also valid. Furthermore, the identity element $\\varepsilon$ is not the canonical form of any valid term.\n\\end{lemma}\n\\begin{proof} If some term $T$ is a valid term, then $\\domain(T)$ is defined, and since ${T}{\\downarrow}$ is equivalent to $T$, $\\domain({T}{\\downarrow})=\\domain(T)$. Therefore ${T}{\\downarrow}$ is a valid term.\n\nFor the second part, assume that $T$ is a valid term, and ${T}{\\downarrow}=\\varepsilon$. Since $|\\varepsilon|=0$, $\\domain(\\varepsilon)$ is not defined, and $\\domain(T)$ must not be defined either. This contradicts the assumption that $T$ is a valid term. Therefore, ${T}{\\downarrow}\\neq\\varepsilon$.\n\\end{proof}\n\nThe next results concern the structure of rules derived from conformance requirements.\n\\begin{definition} A \\emph{type-like} term is one where the first symbol is a protocol symbol, and all subsequent symbols, if there are any, are name symbols.\n\\end{definition}\n\\begin{lemma} Rewrite rules produced by the requirement lowering map $\\Lambda_{\\proto{P}}$ take on one of the following two forms:\n\\begin{enumerate}\n\\item $T.\\protosym{Q}\\Rightarrow T$ where $T$ is a type-like term and $\\proto{Q}$ is some protocol.\n\\item $T\\Rightarrow U$ where $T$ and $U$ are type-like terms.\n\\end{enumerate}\n\\end{lemma}\n\\begin{proof} This follows from Definition~\\ref{reqlowering1}.\n\\end{proof}\n\n\\begin{lemma}\\label{propliketerm1} Suppose that $T$ and $U$ are type-like symbols with domain $\\{\\proto{P}\\}$, and the canonical form of $T.\\protosym{Q}$ is $U$. Then the canonical form of $T$ is also $U$.\n\\end{lemma}\n\\begin{proof}\nTODO.\n\\end{proof}\n\nThe notion of canonical types defined in Section~\\ref{canonicaltypes} corresponds to canonical terms in this rewrite system.\n\\begin{lemma} If $T$ is a canonical type parameter in the protocol $\\proto{P}$, then $\\Lambda_{\\proto{P}}(T)$ is a canonical term.\n\\end{lemma}\n\\begin{proof}\nTODO.\n\\end{proof}\n\nPutting all this together, you can prove the following.\n\\begin{theorem}\\label{finiterqm} Let $\\proto{P}$ be a protocol defining an infinite set of unique canonical type parameters $\\{T_i\\}$ where each $T_i$ conforms to some protocol $\\proto{Q}$. Then the rewrite system constructed from this protocol is not convergent.\n\\end{theorem}\n\\begin{proof}\nFor any type parameter $T_i$, the term $\\Lambda_{\\proto{P}}(T_i)$ is canonical, since $T_i$ is canonical. Together with the fact that $T_i$ conforms to $\\proto{Q}$, Lemma~\\ref{propliketerm1} shows that the term $\\Lambda_{\\proto{P}}(T_i).\\protosym{Q}$ reduces to $\\Lambda_{\\proto{P}}(T_i)$. Since no proper suffix of a valid type-like term is valid, this means for each $T_i$, the confluent completion of the rewrite system must contain a valid rewrite rule of the form $\\Lambda_{\\proto{P}}(T_i).\\protosym{Q}\\Rightarrow \\Lambda_{\\proto{P}}(T_i)$. Each of these rules is distinct and there are infinitely many of them, therefore the rewrite system is not convergent.\n\\end{proof}\n\nIndeed, the toy requirement machine with name and protocol symbols is somewhat limited in what it can do:\n\\begin{enumerate}\n\\item Perhaps the most serious issue is shown in Theorem~\\ref{finiterqm}: this rewrite system cannot cope with recursive conformance requirements. In fact, it is no more expressive than the ancient \\texttt{ArchetypeBuilder}, described in Algorithm~\\ref{archetypebuilder}.\n\n\\item Even the \\emph{statement} of Theorem~\\ref{finiterqm} is awkward. There is no way to talk about what it means for a type parameter to actually ``exist,'' so the theorem must be phrased in terms of there being an infinite number of conformance requirements, when really it should talk about there being infinitely many unique type parameters.\n\n\\item Reducing terms to canonical form lets you determine if two type parameters are equivalent, but it's insufficient for \\texttt{getCanonicalTypeInContext()}.\n\nThe latter is expected to produce ``resolved'' \\texttt{DependentMemberTypes}, where the type is equipped with a pointer to a \\texttt{AssociatedTypeDecl}; so the canonical form of $\\genericparam{Self}.\\namesym{SubSequence}$ actually needs to point at the declaration of $\\namesym{SubSequence}$ in the $\\proto{Collection}$ protocol, rather than the ``unresolved'' form which consists of a bare identifier.\n\nThe issue is that this association between associated types and protocols is ``erased'' in this formulation, and there is no way to define a \\emph{lifting map} taking terms to types, to serve as the inverse of the type lowering map.\n\n\\item This rewrite system can only reason about type parameters in the trivial protocol generic signature $\\gensig{\\genericparam{Self}}{\\genericparam{Self}\\colon\\proto{P}}$ for some protocol $\\proto{P}$. This restricts it to answering queries about type parameters written inside protocols, and not top-level generic signatures attached to generic functions and types, which can have multiple generic parameters and requirements.\n\\item While the \\texttt{requiresProtocol()} generic signature query can be made to work, there doesn't seem to be any easy way to implement \\texttt{getRequiredProtocols()}, which returns \\emph{all} protocols that a type parameter must conform to.\n\\item Layout, superclass and concrete type requirements are not supported.\n\\end{enumerate}\n\nThe first three problems are closely intertwined and the full solution is the subject of the next chapter. \n\nProblem 3 has a straightforward solution, described in Section \\ref{genericparamsym}; it requires adding more symbols to the alphabet.\n\nProblem 4 is really not a shortcoming of the rewrite system itself, but rather something that requires building some machinery on top; that is the topic of Chapter \\ref{propertymap}.\n\n\\chapter{Associated Types}\\label{associatedtypes}\n\n\\index{recursive conformance requirement}\n\\begin{listing}\\caption{The SwiftUI $\\proto{View}$ protocol.}\\label{viewproto}\n\\begin{Verbatim}\nprotocol View {\n associatedtype Body : View\n}\n\\end{Verbatim}\n\\end{listing}\n\nTo motivate the introduction of the next concept, consider the SwiftUI $\\proto{View}$ protocol shown in Listing~\\ref{viewproto}. The protocol's requirement signature contains a recursive conformance requirement, $\\genericparam{Self}.\\namesym{Body}\\colon \\proto{View}$. By Theorem~\\ref{finiterqm}, the rewrite system constructed in the requirement machine with name and protocol symbols is not convergent.\n\nFirst, let's take a closer look at where exactly things go wrong. The initial rewrite system consists of a single rule:\n\\[\\protosym{View}.\\namesym{Body}.\\protosym{View}\\Rightarrow\\protosym{View}.\\namesym{Body}\\]\nThe rule's left-hand side has a prefix $\\protosym{View}$ equal to its own suffix, so the rule overlaps with itself with an overlap of the second kind. The overlapped term that can be reduced in two different ways is:\n\\[\\protosym{View}.\\namesym{Body}.\\protosym{View}.\\namesym{Body}.\\protosym{View}\\]\nApplying the rule both ways and reducing the result produces the new rule:\n\\[\\protosym{View}.\\namesym{Body}.\\namesym{Body}.\\protosym{View}\\Rightarrow\\protosym{View}.\\namesym{Body}.\\namesym{Body}\\]\nThe new rule, in turn, overlaps with the first rule, and the process continues forever (or until your algorithm's maximum iteration count is reached, or \\emph{in extremis}, when your computer runs out of memory). Figure \\ref{swiftuirunaway} shows what this infinite sequence of critical pairs looks like.\n\\begin{figure}\\caption{Infinitely many critical pairs while completing $\\proto{View}$ protocol}\\label{swiftuirunaway}\n\\begin{center}\n\\begin{tikzcd}\n&\\mathmakebox[0pt][c]{\n\\protosym{View}.\\namesym{Body}.\\protosym{View}.\\namesym{Body}.\\protosym{View}\n}\n\\arrow[ld, yshift=-3pt, shorten=6pt] \\arrow[rd, yshift=-3pt, shorten=6pt] \\\\\n\\protosym{View}.\\namesym{Body}.\\namesym{Body}.\\protosym{View}\n\\arrow[d, equal]&&\n\\protosym{View}.\\namesym{Body}.\\protosym{View}.\\namesym{Body}\n\\arrow[d]\\\\\n\\protosym{View}.\\namesym{Body}.\\namesym{Body}.\\protosym{View}\n\\arrow[rr, dashed]&&\n\\protosym{View}.\\namesym{Body}.\\namesym{Body}\n\\end{tikzcd}\n\n\\vspace{10mm}\n\n\\begin{tikzcd}\n&\\mathmakebox[0pt][c]{\n\\protosym{View}.\\namesym{Body}.\\namesym{Body}.\\protosym{View}.\\namesym{Body}.\\protosym{View}\n}\n\\arrow[ld, yshift=-3pt, shorten=6pt] \\arrow[rd, yshift=-3pt, shorten=6pt] \\\\\n\\protosym{View}.\\namesym{Body}.\\namesym{Body}.\\namesym{Body}.\\protosym{View}\n\\arrow[d, equal]&&\n\\protosym{View}.\\namesym{Body}.\\namesym{Body}.\\protosym{View}.\\namesym{Body}\n\\arrow[d]\\\\\n\\protosym{View}.\\namesym{Body}.\\namesym{Body}.\\namesym{Body}.\\protosym{View}\n\\arrow[rr, dashed]&&\n\\protosym{View}.\\namesym{Body}.\\namesym{Body}.\\namesym{Body}\n\\end{tikzcd}\n\n\\vspace{10mm}\n\n\\begin{tikzcd}\n&\\mathmakebox[0pt][c]{\n\\protosym{View}.\\namesym{Body}^{n-1}.\\protosym{View}.\\namesym{Body}.\\protosym{View}\n}\n\\arrow[ld, yshift=-3pt, shorten=6pt] \\arrow[rd, yshift=-3pt, shorten=6pt] \\\\\n\\protosym{View}.\\namesym{Body}^{n-1}.\\namesym{Body}.\\protosym{View}\n\\arrow[d, equal]&&\n\\protosym{View}.\\namesym{Body}^{n-1}.\\protosym{View}.\\namesym{Body}\n\\arrow[d]\\\\\n\\protosym{View}.\\namesym{Body}^n.\\protosym{View}\n\\arrow[rr, dashed]&&\n\\protosym{View}.\\namesym{Body}^n\n\\end{tikzcd}\n\n\\end{center}\n\\end{figure}\n\n\\index{convergent presentation}\nIn fact, this is exactly the same setup as monoid $M$ in Example \\ref{infiniteex} from earlier, only $a$ is $\\protosym{View}$, and $b$ is $\\namesym{Body}$:\n\\[\\langle a, b;\\;aba=ab \\rangle\\]\nWhile that presentation stumps the Knuth-Bendix algorithm, Example \\ref{diffpresex} gave an isomorphic monoid $M'$ with a different presentation which worked just fine:\n\\[\\langle t, u, v;\\;uv=t,\\;tu=t\\rangle\\]\nThis seems awfully convenient, almost as if I introduced these examples with the full intention of revisiting them later. Let's take a closer look at the isomorphism $\\varphi\\colon M'\\rightarrow M$ exhibited in Example \\ref{diffpresex}:\n\\begin{align*}\nt&\\leftrightarrow ab\\\\\nu&\\leftrightarrow a\\\\\nv&\\leftrightarrow b\n\\end{align*}\nThis means that adding a new \\emph{generator} to $M$ made the presentation convergent. What does this generator represent in the world of Swift? Well, $u\\in M'$ is $a\\in M$, which is $\\protosym{View}$ in Swift; and $v\\in M'$ is $b\\in M$, which is $\\namesym{Body}$. Therefore $t\\in M'$ is $ab\\in M$, which is $\\protosym{View}.\\namesym{Body}$. You may guess that $t$ could be a new kind of symbol, perhaps representing a ``bound'' associated type inside a specific protocol.\n\n\\index{associated type symbol}\n The crux of the issue is that name symbols like $\\namesym{Body}$ don't carry any information, and little can be said about them unless they're prefixed with some other term that is known to conform to a protocol. Thus, you cannot simply add a rewrite rule to say that $\\namesym{Body}$ conforms to $\\protosym{View}$:\n\\[\\namesym{Body}.\\protosym{View}\\Rightarrow\\namesym{View}\\]\nA rule like this would apply to all associated types named $\\namesym{Body}$, ever, \\emph{in all protocols}, which is wrong. The best we could do until now is try to introduce a rule for each valid prefix term that conforms to $\\proto{View}$, of which there are infinitely many here:\n\\[\\protosym{View}.\\underbrace{\\namesym{Body}\\ldots\\namesym{Body}}_{\\textrm{$n$ times}}.\\protosym{View}\\]\n\nIf there was instead a symbol representing the unique associated type $\\namesym{Body}$ defined in protocol $\\proto{View}$, you could introduce a single rewrite rule modeling the conformance requirement on that associated type for any length ``prefix''. This is exactly how it works. An \\emph{associated type symbol} is uniquely identified by the combination of a protocol name and an associated type name; they're written like so, where $\\proto{P}$ is the protocol and $\\namesym{A}$ is an identifier:\n\\[\\assocsym{P}{A}\\]\nThe notation is to enclose the entire symbol in square brackets [ and ] to remind you that it is one symbol, and not two; that is, $\\assocsym{P}{A}$ is a term of length 1. While I still haven't formally defined the reduction order here, it is also important that associated type symbols come before name symbols. You will see why shortly.\n\nTo be of any use, rules involving associated type symbols must be introduced when the rewrite system is built. Since rewrite system construction is starting to get more complex, I'm going to encapsulate it with the \\emph{protocol lowering map}.\n\\begin{definition}[Protocol lowering map]\\label{protoloweringmap}\nThe map $\\Lambda\\colon\\namesym{Proto}\\rightarrow\\namesym{Rule}^*$ takes a protocol and outputs a list of zero or more rewrite rules. This list contains two kinds of rules:\n\\begin{enumerate}\n\\item Every associated type $\\namesym{A}$ of $\\proto{P}$ adds an \\emph{introduction rule}:\n\\[\\protosym{P}.\\namesym{A}\\Rightarrow\\assocsym{P}{A}.\\]\n\\item Every generic requirement of $\\proto{P}$ adds a rewrite rule using the requirement lowering map $\\Lambda_{\\proto{P}}:\\namesym{Requirement}\\rightarrow\\namesym{Rule}$ from Definition~\\ref{reqlowering1}.\n\\end{enumerate}\nThis map is further amended in Definition~\\ref{protoloweringmap2} in the next section.\n\\end{definition}\nWith this amended rewrite system construction process, the initial rewrite system for the $\\proto{View}$ protocol now has two rules, the first one describing the associated type itself, and the second one describing the protocol conformance requirement on the associated type:\n\\begin{align}\n\\protosym{View}.\\namesym{Body}&\\Rightarrow\\assocsym{View}{Body}\\tag{1}\\\\\n\\protosym{View}.\\namesym{Body}.\\protosym{View}&\\Rightarrow\\protosym{View}.\\namesym{Body}\\tag{2}\n\\end{align}\nRule 1 overlaps with Rule 2 on this term:\n\\[\\protosym{View}.\\namesym{Body}.\\protosym{View}.\\]\nResolving this first critical pair introduces a new rewrite rule:\n\\begin{align}\n\\assocsym{View}{Body}.\\protosym{View}&\\Rightarrow\\assocsym{View}{Body}\\tag{3}\n\\end{align}\nNext, swapping things around, Rule 2 overlaps with Rule 1 on this term:\n\\[\\protosym{View}.\\namesym{Body}.\\protosym{View}.\\namesym{Body}.\\]\nResolving this second critical pair also introduces a new rewrite rule:\n\\begin{align}\n\\assocsym{View}{Body}.\\namesym{Body}&\\Rightarrow\\assocsym{View}{Body}.\\assocsym{View}{Body}\\tag{4}\n\\end{align}\n(Incidentally, this is why it is important that $\\assocsym{View}{Body}<\\namesym{Body}$. If the above rule was oriented in the other direction, completion would run off into the weeds again.)\n\nFinally, Rule 2 overlaps with itself on this term:\n\\[\\protosym{View}.\\namesym{Body}.\\protosym{View}.\\namesym{Body}.\\protosym{View}.\\]\nThis is the same overlapped term that caused trouble before, and once again this overlap produces the same critical pair:\n\\[(\\protosym{View}.\\namesym{Body}.\\namesym{Body}.\\protosym{View}, \\protosym{View}.\\namesym{Body}.\\protosym{View}.\\namesym{Body})\\]\nHowever, everything gets better from here. The reduced form of the left-hand side is different:\n\\begin{align}\n\\protosym{View}.\\namesym{Body}.\\namesym{Body}.\\protosym{View}\n&\\rightarrow\\assocsym{View}{Body}.\\namesym{Body}.\\protosym{View}\\tag{Rule 1}\\\\\n&\\rightarrow\\assocsym{View}{Body}.\\assocsym{View}{Body}.\\protosym{View}\\tag{Rule 4}\\\\\n&\\rightarrow\\assocsym{View}{Body}.\\assocsym{View}{Body}\\tag{Rule 3}\n\\end{align}\nAnd the best part is, the right-hand side reduces to the same term:\n\\begin{align}\n\\protosym{View}.\\namesym{Body}.\\protosym{View}.\\namesym{Body}\n&\\rightarrow\\protosym{View}.\\namesym{Body}.\\namesym{Body}\\tag{Rule 2}\\\\\n&\\rightarrow\\assocsym{View}{Body}.\\namesym{Body}\\tag{Rule 4}\\\\\n&\\rightarrow\\assocsym{View}{Body}.\\assocsym{View}{Body}\\tag{Rule 3}\n\\end{align}\n\\begin{listing}\\caption{Rewrite system of $\\proto{View}$ protocol after completion}\\label{swiftuiviewcompleterules}\n\\begin{align}\n\\protosym{View}.\\namesym{Body}&\\Rightarrow\\assocsym{View}{Body}\\tag{1}\\\\\n\\protosym{View}.\\namesym{Body}.\\protosym{View}&\\Rightarrow\\protosym{View}.\\namesym{Body}\\tag{\\textbf{Deleted}}\\\\\n\\assocsym{View}{Body}.\\protosym{View}&\\Rightarrow\\assocsym{View}{Body}\\tag{3}\\\\\n\\assocsym{View}{Body}.\\namesym{Body}&\\Rightarrow\\assocsym{View}{Body}.\\assocsym{View}{Body}\\tag{4}\n\\end{align}\n\\end{listing}\nHow exciting---the third critical pair can be discarded, and no more overlaps remain. Figure \\ref{swiftuiassocfig} presents this process in diagram form, and Listing \\ref{swiftuiviewcompleterules} shows the final list of rules. Note that the left-hand side of Rule 2 contains the left-hand side of Rule 1, so the post-processing step of the Knuth-Bendix algorithm deletes Rule 2.\n\n\\begin{figure}\\caption{Successful completion of $\\proto{View}$ protocol with an associated type symbol}\\label{swiftuiassocfig}\n\\begin{center}\n\n\\vspace{10mm}\n\n\\begin{tikzcd}\n&\\mathmakebox[0pt][c]{\n\\protosym{View}.\\namesym{Body}.\\protosym{View}\n}\n\\arrow[ld, yshift=-3pt, shorten=6pt] \\arrow[rd, yshift=-3pt, shorten=6pt] \\\\\n\\assocsym{View}{Body}.\\protosym{View}\n\\arrow[d, equal]&&\n\\protosym{View}.\\namesym{Body}\n\\arrow[d]\\\\\n\\assocsym{View}{Body}.\\protosym{View}\n\\arrow[rr, dashed]&&\n\\assocsym{View}{Body}\n\\end{tikzcd}\n\n\\vspace{10mm}\n\n\\begin{tikzcd}\n&\\mathmakebox[0pt][c]{\n\\protosym{View}.\\namesym{Body}.\\protosym{View}.\\namesym{Body}\n}\n\\arrow[ld, yshift=-3pt, shorten=6pt] \\arrow[rd, yshift=-3pt, shorten=6pt] \\\\\n\\protosym{View}.\\namesym{Body}.\\namesym{Body}\n\\arrow[d]&&\n\\protosym{View}.\\namesym{Body}.\\assocsym{View}{Body}\n\\arrow[d]\\\\\n\\assocsym{View}{Body}.\\namesym{Body}\n\\arrow[rr, dashed]&&\n\\assocsym{View}{Body}.\\assocsym{View}{Body}\n\\end{tikzcd}\n\n\\vspace{10mm}\n\n\\begin{tikzcd}\n&\\mathmakebox[0pt][c]{\n\\protosym{View}.\\namesym{Body}.\\protosym{View}.\\namesym{Body}.\\protosym{View}\n}\n\\arrow[ld, yshift=-3pt, shorten=6pt] \\arrow[rd, yshift=-3pt, shorten=6pt] \\\\\n\\protosym{View}.\\namesym{Body}.\\namesym{Body}.\\protosym{View}\n\\arrow[d]&&\n\\protosym{View}.\\namesym{Body}.\\protosym{View}.\\namesym{Body}\n\\arrow[d]\\\\\n\\assocsym{View}{Body}.\\assocsym{View}{Body}\n\\arrow[rr, dashed, equal]&&\n\\assocsym{View}{Body}.\\assocsym{View}{Body}\n\\end{tikzcd}\n\n\\end{center}\n\\end{figure}\n\nI'm going to call this ``the requirement machine with name, protocol and associated type symbols.'' Since the rewrite system generated by the $\\proto{View}$ protocol now has a confluent completion, the addition of associated type symbols gives you a strictly more powerful formalism.\n\nOne interesting phenomenon is when terms containing name symbols reduce to associated type symbols:\n\\begin{align}\n\\protosym{View}.\\namesym{Body}.\\namesym{Body}.&\\namesym{Body}\\nonumber\\\\\n&\\rightarrow\\assocsym{View}{Body}.\\namesym{Body}.\\namesym{Body}\\tag{Rule 1}\\\\\n&\\rightarrow\\assocsym{View}{Body}.\\assocsym{View}{Body}.\\namesym{Body}\\tag{Rule 4}\\\\\n&\\rightarrow\\assocsym{View}{Body}.\\assocsym{View}{Body}.\\assocsym{View}{Body}\\tag{Rule 4}\n\\end{align}\n\n\\index{domain of a term}\nSome terms no longer start with a protocol symbol, so an amended definition of the domain map is needed.\n\\begin{definition} If the first symbol of a term $T$ is an associated type symbol $\\assocsym{P}{A}$, then $\\domain(T):=\\{\\proto{P}\\}$.\n\\end{definition}\nAs before, the rewrite system is domain-preserving. Indeed, the only added rules are the associated type introduction rules, $\\proto{P}.\\namesym{A}\\Rightarrow\\assocsym{P}{A}$. These rules are domain-preserving by the above definition.\n\nPreviously, I mentioned that the earlier formulation of the requirement machine with name and protocol symbols could not express the fact that a type parameter actually exists. Now, associated type symbols offer a solution. If a fully-reduced term contains name symbols, it means that the type parameter represented by this term does not exist:\n\\[\\protosym{View}.\\namesym{Body}.\\namesym{Goat}\\rightarrow\\assocsym{View}{Body}.\\namesym{Goat}.\\]\nThe converse is not true however. A term that only contains associated type symbols might still not be a ``real'' type parameter. For example, the $\\proto{View}$ protocol's $\\namesym{Body}$ associated type does not conform to $\\proto{Sequence}$, so the following term does not represent an actual type parameter, even though it looks legitimate:\n\\[\\assocsym{View}{Body}.\\assocsym{Sequence}{Element}\\]\n\nThis new validity condition can be expressed using the tools I've already introduced. The domain of $\\assocsym{Sequence}{Element}$ is $\\{\\proto{Sequence}\\}$, but $\\assocsym{View}{Body}$ does not conform to $\\proto{Sequence}$, because $\\assocsym{View}{Body}.\\protosym{Sequence}$ does not reduce to $\\assocsym{View}{Body}$. This can be generalized.\n\\begin{definition} A term $T=T_1.\\ldots.T_n$ is \\emph{conformance-valid} if at every position, the prefix conforms to each protocol in the domain of the corresponding suffix.\n\nMore specifically, for every $1\\leq i 1$, the associated type symbol is called a merged associated type symbol. These were discussed in detail in Section~\\ref{mergedassoctypes}.\n\\index{name symbol}\n\\item \\textbf{Name symbols}: $\\namesym{T}$ for any valid Swift identifier.\n\\index{generic parameter symbol}\n\\item \\textbf{Generic parameter symbols}: $\\genericsym{d}{i}$ where $d$, $i\\geq 0$ are the depth and index of the generic parameter, respectively.\n\\index{layout symbol}\n\\item \\textbf{Layout symbols}: $\\layoutsym{L}$ where $\\namesym{L}$ is a Swift layout constraint.\n\\index{substitution}\n\\index{superclass symbol}\n\\item \\textbf{Superclass symbols}: $\\supersym{\\namesym{T};\\;\\sigma_0,\\ldots,\\sigma_n}$ where $\\namesym{T}$ is a Swift type, and the $\\{\\sigma_i\\}_{0\\le i \\le n}$ are a (possibly empty) ordered list of terms, referred to as \\emph{substitutions}.\n\\item \\index{concrete type symbol} \\textbf{Concrete type symbols}: $\\concretesym{\\namesym{T};\\;\\sigma_0,\\ldots,\\sigma_n}$ where $T$ and $\\sigma_i$ are as above.\n\\end{itemize}\n\\end{definition}\n\nGeneric parameter symbols are the subject of Section \\ref{genericparamsym}. Layout, superclass and concrete type symbols are described in excruciating detail in Section~\\ref{concretetypes}.\n\n\\index{reduction order}\nFirst though, I will define the reduction order on symbols.\n\n\\index{linear order}\n\\index{reduction protocol order}\n\\begin{definition}[Reduction protocol order]\\label{protocolorder} First, for each protocol $\\proto{P}$, define the \\emph{depth} of $\\proto{P}$ as one greater than the maximum depth of each protocol $\\proto{Q}_i$ inherited by $\\proto{P}$:\n\\[\\gpdepth(\\proto{P}) = 1 + \\max(\\gpdepth(\\proto{Q}_i))\\quad\\hbox{where}\\quad \\bm{\\mathsf{Q}}_i \\in \\hbox{protocols inherited by $\\proto{P}$}\\]\nIf $\\proto{P}$ does not inherit from any protocols, then $\\max(\\varnothing)=0$, and $\\gpdepth(\\proto{P})=1$. Now, given two protocols $\\proto{P}$ and $\\proto{Q}$, $\\proto{P}<\\proto{Q}$ in the reduction protocol order if:\n\n\\begin{itemize}\n\\item $\\gpdepth(\\proto{P}) > \\gpdepth(\\proto{Q})$, or\n\\item $\\gpdepth(\\proto{P}) = \\gpdepth(\\proto{Q})$, and $\\proto{P}$ precedes $\\proto{Q}$ with the canonical protocol order from Definition~\\ref{canonicalprotocol}.\n\\end{itemize}\n\\end{definition}\n\\begin{listing}\\caption{The standard library's Collection protocol tower}\\label{collectiontower}\n\\begin{Verbatim}\nprotocol Sequence {}\nprotocol Collection : Sequence {}\nprotocol BidirectionalCollection : Collection {}\nprotocol MutableCollection : Collection {}\nprotocol RangeReplaceableCollection : Collection {}\nprotocol RandomAccessCollection : BidirectionalCollection {}\n\\end{Verbatim}\n\\end{listing}\n\\begin{example}\nConsider the collection protocol tower from the standard library, shown in Listing \\ref{collectiontower}. The depth of each protocol is as follows:\n\\begin{itemize}\n\\item $\\proto{Sequence}$ has depth 1.\n\\item $\\proto{Collection}$ has depth 2.\n\\item $\\proto{BidirectionalCollection}$, $\\proto{MutableCollection}$, and $\\proto{RangeReplaceableCollection}$ all have depth 3.\n\\item $\\proto{RandomAccessCollection}$ has depth 4.\n\\end{itemize}\nHere is the linear order among these protocols:\n\\begin{align*}\\proto{RandomAccessCollection}<\\proto{BidirectionalCollection}&<\\proto{MutableCollection}\\\\\n<\\proto{RangeReplaceableCollection}&<\\proto{Collection}<\\proto{Sequence}\n\\end{align*}\nYou can see that protocols deeper in the inheritance graph precede other protocols. If you recall, associated type inheritance relies on this in Section \\ref{inheritedassoctypes}.\n\\end{example}\n\n\\index{partial order}\n\\begin{definition}[Reduction order on symbols]\\label{symbolorder}\nSay the two symbols are $\\alpha$ and $\\beta$.\n\\begin{figure}\\caption{symbol kind order}\\label{kindorder}\n\\[\n\\begin{array}{c}\n\\text{Protocol symbol}\\\\\n<\\\\\n\\text{Associated type symbol}\\\\\n<\\\\\n\\text{Name symbol}\\\\\n<\\\\\n\\text{Generic parameter symbol}\\\\\n<\\\\\n\\text{Layout symbol}\\\\\n<\\\\\n\\text{Superclass symbol}\\\\\n<\\\\\n\\text{Concrete type symbol}\n\\end{array}\n\\]\n\\end{figure}\n\nIf $\\alpha$ and $\\beta$ have different kinds, then $\\alpha<\\beta$ if the kind of $\\alpha$ precedes the kind of $\\beta$ in Figure~\\ref{kindorder}. Note that this is the same kind order as in Definition \\ref{symboldef}.\nIf $\\alpha$ and $\\beta$ have the same kind, then they are compared as follows:\n\n\\begin{itemize}\n\\item \\textbf{Protocol symbols:} Let $\\alpha=\\protosym{P}$ and $\\beta=\\protosym{Q}$. Then $\\alpha<\\beta$ if $\\proto{P}<\\proto{Q}$ in the reduction protocol order from Definition \\ref{protocolorder}.\n\\item \\textbf{Associated type symbols:} Let\n$\n\\alpha=[\\proto{P}_0\\cap\\ldots\\cap\\proto{P}_m:\\namesym{T}]$, $\n\\beta=[\\proto{Q}_0\\cap\\ldots\\cap\\proto{Q}_n:\\namesym{T}]$.\n\\begin{itemize}\n\\item If the identifier $T$ precedes $U$ in lexicographic order, then $\\alpha < \\beta$.\n\\item If $T=U$, and $m>n$, then $\\alpha < \\beta$.\n\\item If $T=U$, $m=n$, and there is some $j$ such that for all $i