{"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$$ \\\\ \\\\\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 \\Lambda_{\\proto{P}}(\\namesym{U})$ in the shortlex order on terms (if not, flip the terms around):\n\\[\\Lambda_{\\proto{P}}(\\namesym{T}) \\Rightarrow \\Lambda_{\\proto{P}}(\\namesym{U})\\]\n\\end{itemize}\n\\end{algorithm}\n\n\\section{Generic Parameters}\\label{genericparamsym}\n\\index{generic parameter symbol}\nSo far, I've only shown you how to build rewrite rules from requirements in the requirement signature of some protocol $\\proto{P}$. When lowering a type parameter, the protocol $\\genericparam{Self}$ type lowers to the protocol symbol $\\protosym{P}$. Once such a rewrite system is built, queries can be performed against the protocol generic signature $\\gensig{\\genericparam{Self}}{\\genericparam{Self}\\colon\\proto{P}}$. When lowering parameters and requirements in an arbitrary generic signature, generic parameter types instead become generic parameter symbols.\n\nGeneric parameter symbols should only ever appear as the initial symbol in a term. While the rewrite system would have no trouble with terms where generic parameter symbols appear elsewhere in the abstract, they don't actually make sense semantically, since they do not correspond to valid Swift type parameter types.\n\nThe lowering of type parameters in a generic signature is similar to Algorithm \\ref{lowertypeinproto}. The first associated type no longer plays a special rule, since the term is always ``rooted'' at a generic parameter symbol.\n\n\\index{type parameter}\n\\index{generic requirement}\n\\index{generic signature}\n\\begin{algorithm}[Type parameter lowering for generic signatures]\\label{lowertypeinsig}\nThe lowering map $\\Lambda\\colon\\namesym{Type}\\rightarrow\\namesym{Term}$ takes a type parameter $X$ as input:\n\\[X:=\\genericsym{d}{i}.X_1.X_2\\ldots X_n\\]\nThis algorithm constructs a new term $Y:=\\Lambda(X)$ from the type parameter $X$ as follows:\n\\begin{itemize}\n\\item\nThe first element of $X$ is a generic parameter type at depth $d$ and index $i$, so set $Y_0:=\\genericsym{d}{i}$.\n\\item\nAll subsequent elements are associated types. If the $i$th element is an associated type $A_i$ defined in a protocol $\\protosym{P}_i$, then set $Y_i:=\\assocsym{P}{A}$.\n\\end{itemize}\n\\end{algorithm}\n\n\\begin{algorithm}[Generic requirement lowering]\nThe generic signature requirement lowering map $\\Lambda\\colon \\namesym{Requirement}\\rightarrow\\namesym{Rule}^+$ is virtually identical to protocol requirement lowering map in Algorithm \\ref{lowerreqinproto}. The only difference is that types should be lowered to terms via $\\Lambda\\colon\\namesym{Type}\\rightarrow\\namesym{Term}$ defined above, in place of $\\Lambda_{\\proto{P}}\\colon\\namesym{Type}\\rightarrow\\namesym{Term}$ from Algorithm~\\ref{lowertypeinproto}.\n\\end{algorithm}\n\n\\begin{example}\nConsider the following generic signature:\n\\[\\gensig{\\genericsym{0}{0},\\genericsym{0}{1}}{\\genericsym{0}{0}\\colon\\proto{Collection},\\;\\genericsym{0}{1}\\colon\\proto{Collection},\\;\\genericsym{0}{0}.\\namesym{Element}==\\genericsym{0}{1}.\\namesym{Element}}\\]\nThe signature's requirements lower to the following rewrite rules:\n\\begin{align}\n\\genericsym{0}{0}.\\protosym{Collection}&\\Rightarrow\\genericsym{0}{0}\\tag{1}\\\\\n\\genericsym{0}{1}.\\protosym{Collection}&\\Rightarrow\\genericsym{0}{1}\\tag{2}\\\\\n\\genericsym{0}{1}.\\namesym{Element}&\\Rightarrow\\genericsym{0}{0}.\\namesym{Element}\\tag{3}\n\\end{align}\nRule 1 and Rule 2 are lowered conformance requirements of the form $\\namesym{T}.\\protosym{P}\\Rightarrow\\namesym{T}$ just like before, and Rule 3 is the lowered same-type requirement.\n\nThis rewrite system will also need to include the requirements of the $\\proto{Collection}$ protocol, as well as $\\proto{Sequence}$ and $\\proto{IteratorProtocol}$, which are referenced from the requirement signatures of $\\proto{Collection}$ and $\\proto{Sequence}$.\n\\end{example}\n\\begin{definition}The \\emph{protocol dependencies} of a generic signature (or protocol requirement signature) are all the protocols that appear on the right-hand side of the conformance requirements of the generic signature (or protocol requirement signature). The \\emph{complete} protocol dependencies of a generic signature is the transitive closure of its protocol dependencies.\n\\end{definition}\n\nWhile generic parameters are uniquely identified by their depth and index within a \\emph{single} generic signature, they are not unique \\emph{between} generic signatures, so each generic signature needs its own requirement machine. This process of constructing a requirement machine from a generic signature can be formalized as follows.\n\\begin{algorithm}[Requirement machine construction]\\label{rqmalgo}\nLet $G$ be the input generic signature $\\gensig{\\genericsym{0}{0},\\;\\ldots,\\;\\genericsym{m}{n}}{R_0,\\;\\ldots\\;R_i}$. Outputs a confluent rewrite system, or fails with a timeout.\n\\begin{enumerate}\n\\item Let $S$ be an empty rewrite system.\n\\item Let $W$ be an empty stack of protocols.\n\\item Let $V$ be an empty set of protocols.\n\\item For each requirement $R$ of $G$:\n\\begin{enumerate}\n\\item Lower $R$ to a rewrite rule $\\Lambda(R)$, and add the new rule to $S$. \n\\item If $R$ is a conformance requirement $\\namesym{T}\\colon\\proto{P}$ and $\\proto{P}\\notin V$, push $\\proto{P}$ onto $W$, and insert $\\proto{P}$ into $V$.\n\\end{enumerate}\n\\item While $W$ is not empty,\n\\begin{enumerate}\n\\item Pop the next protocol $\\proto{P}$ from $W$.\n\\item Add rewrite rules corresponding to the associated types and requirements of $\\proto{P}$ using the protocol lowering map from Definition~\\ref{protoloweringmap2}. \n\\item For each conformance requirement $\\namesym{T}\\colon\\proto{Q}$ in the requirement signature of $\\proto{P}$,\n\\begin{enumerate}\n\\item If $\\proto{Q}\\notin V$, push $\\proto{Q}$ onto $W$, and insert $\\proto{Q}$ into $V$.\n\\end{enumerate}\n\\end{enumerate}\n\\item Run the Knuth-Bendix completion procedure on $S$ (Algorithm~\\ref{knuthbendix}).\n\\item If the completion succeeds with the configured iteration and depth limits, return $S$; otherwise, diagnose an error.\n\\end{enumerate}\n\\end{algorithm}\n\n\\section{Concrete Types}\\label{concretetypes}\n\n\\index{concrete type symbol}\n\\index{superclass symbol}\n\\index{layout symbol}\nThe time has come to reveal the mystery of how layout, superclass and concrete type requirements work.\n\nDefinition \\ref{lowerreqinproto} showed that just like a conformance requirement $\\namesym{T}\\colon\\proto{P}$ becomes a rewrite rule $\\namesym{T}.\\protosym{P}\\Rightarrow\\namesym{T}$, a layout requirement $\\namesym{T}\\colon\\namesym{L}$ becomes a rewrite rule $\\namesym{T}.\\layoutsym{L}\\Rightarrow\\namesym{T}$. The situation with superclass and concrete type requirements is analogous, except that superclass and concrete type symbols are constructed in a more elaborate manner, described in Algorithm~\\ref{concretesymbolcons}.\n\nIn fact, this phenomenon where rules eliminate a symbol from the end of a term can be formalized. Figure \\ref{symbolclass} classifies the alphabet into the \\emph{property-like} and \\emph{type-like} symbols (protocol symbols straddle both classifications, because they can also arise as the protocol $\\proto{Self}$ type). This notion of property-like symbols also generalizes to property-like rules.\n\\begin{definition} A rewrite rule is \\emph{property-like} if it is of the form $\\namesym{T}.\\namesym{\\Pi}\\Rightarrow\\namesym{T}$ with $\\namesym{\\Pi}$ a property-like symbol.\n\\end{definition}\n\n\\index{property-like!symbol}\n\\index{type-like!symbol}\n\\begin{figure}\\caption{symbol kind classification}\\label{symbolclass}\n\\begin{center}\n\\begin{tabular}{|l|l|}\n\\hline\n\\multirow{3}{14em}{Property-like}& layout\\\\\n&superclass\\\\\n&concrete type\\\\\n\\hline\n\\multirow{3}{14em}{Type-like}& associated type\\\\\n&identifier\\\\\n&generic parameter\\\\\n\\hline\n\\multirow{1}{14em}{Both property and type-like}& protocol\\\\\n\\hline\n\\end{tabular}\n\\end{center}\n\\end{figure}\n\n\\index{substitution}\nRecall that superclass and concrete type symbols store a Swift type together with a list of substitutions. What do these represent exactly, and why is it not enough to store a Swift type alone? Well, consider this generic signature:\n\\begin{align*}\n\\gensig{\\genericsym{0}{0},\\;\\genericsym{0}{1}}\n{\n&\\genericsym{0}{0}\\colon\\proto{Sequence},\\\\\n&\\genericsym{0}{1}\\colon\\proto{Sequence},\\\\\n&\\genericsym{0}{0}.\\namesym{Element}==\n\\namesym{Array}\\langle\\genericsym{0}{1}.\\namesym{Element}\\rangle\n}\n\\end{align*}\nThe right-hand side of the concrete type requirement contains the type parameter $\\genericsym{0}{1}.\\namesym{Element}$. This type parameter lowers to the term $\\genericsym{0}{1}.\\assocsym{Sequence}{Element}$. It would be nice if the Swift type could directly contain this term, but a \\texttt{BoundGenericType} like $\\namesym{Array}\\langle\\bullet\\rangle$ only contains other types, not terms or any other arbitrary objects.\n\\begin{leftbar}\n\\noindent In theory it would be possible to duplicate the entire Swift type hierarchy in the world of concrete type symbols, but it would not be very practical. The parallel hierarchy would be quite large, with its own versions of metatypes, function types, tuple types, and so on. this would also be a maintenance burden going forward, since any addition to a Swift type representation, for example adding a new attribute to function types, would have to be mirrored in the world of concrete type terms.\n\nAnother option would be to introduce a special kind of placeholder type in the Swift AST, which can store a term, but this would also have undesirable ripple effects throughout the codebase.\n\\end{leftbar}\nThere is a simple solution. Concrete type symbols store the child terms off to the side in a list of substitutions. The substitution terms are referenced from within the Swift type using ``phantom'' generic parameters, disregarding the depth and using the index to refer to an element of the substitution list.\n\n\\begin{algorithm}[Concrete type symbol construction]\\label{concretesymbolcons}\nTakes as input a Swift type $X$ containing arbitrary type parameters, and as output returns a new type where the type parameters have been replaced with generic parameters indexing into a substitution list, together with the substitution list itself.\n\nThis algorithm can build a symbol for use in a rule constructed from a requirement in a protocol $\\proto{P}$, or a requirement in the generic signature of a function or type. The only difference is whether types are lowered via $\\Lambda_{\\proto{P}}$ (Algorithm~\\ref{lowertypeinsig}) or $\\Lambda$ (Algorithm~\\ref{lowertypeinproto}).\n\\begin{enumerate}\n\\item Initialize $S$ with an empty list of terms.\n\\item For each position $\\pi$ where $X|_{\\pi}$ is a type parameter,\n\\begin{enumerate}\n\\item Get the type parameter $T$ stored at $X|_{\\pi}$.\n\\item Replace $X|_{\\pi}$ with a new generic parameter type $\\genericsym{0}{j}$, where $j$ is the number of elements in $S$ so far.\n\\item Append the term $\\Lambda(T)$ (or $\\Lambda_{\\proto{P}}(T)$) to $S$.\n\\end{enumerate}\n\\item Build the concrete type symbol $\\concretesym{X;S}$ with the modified Swift type $X$ and substitutions $S$.\n\\end{enumerate}\n\\end{algorithm}\nThe same algorithm also constructs superclass symbols, if you replace $\\concretesym{X;S}$ with $\\supersym{X;S}$ in Step~3.\n\n\\begin{example}\nThe type $\\namesym{Array}\\langle\\genericsym{0}{1}.\\namesym{Element}\\rangle$, when written in a generic signature where $\\genericsym{0}{1}\\colon\\proto{Sequence}$, becomes the following concrete type symbol:\n\\[\\concretesym{\\namesym{Array}\\langle\\genericsym{0}{0}\\rangle;\\;\\sigma_0:=\\genericsym{0}{1}.\\assocsym{Sequence}{Element}}.\\]\nThe generic parameter $\\genericsym{0}{0}$ appearing within $\\namesym{Array}\\langle\\genericsym{0}{0}\\rangle$ is not a real generic parameter from the current generic context; instead, its just an index into the substitution list, here referring to the first element, $\\genericsym{0}{1}.\\namesym{Element}$.\n\nTo aid with readability, let's write a ``phantom'' generic parameter $\\genericsym{0}{i}$ as $\\sigma_i$. Now, the above symbol looks a little neater:\n\\[\\concretesym{\\namesym{Array}\\langle\\sigma_0\\rangle;\\;\\sigma_0:=\\genericsym{0}{1}.\\namesym{Element}}.\\]\n\\end{example}\n\n\\begin{example}\nThe function type $(\\namesym{Array}\\langle\\genericsym{1}{0}\\rangle,\\; \\namesym{Int})\\rightarrow \\genericsym{1}{1}.\\namesym{Element}$, when written in a generic signature where $\\genericsym{1}{1}\\colon\\proto{Sequence}$, maps to the following concrete type symbol:\n\\begin{align*}\n\\concretesym{&(\\namesym{Array}\\langle\\sigma_0\\rangle,\\; \\namesym{Int})\\rightarrow \\sigma_1;\\\\\n&\\sigma_0:=\\genericsym{1}{0},\\\\\n&\\sigma_1:=\\genericsym{1}{1}.\\assocsym{Sequence}{Element}}.\n\\end{align*}\n\\end{example}\n\\begin{example}\nThe tuple type $(\\genericparam{Self}.\\namesym{Magnitude},\\; \\genericparam{Self}.\\namesym{Words})$, when written in a protocol $\\proto{P}$ that defines associated types $\\namesym{Magnitude}$ and $\\namesym{Words}$, maps to the following concrete type symbol:\n\\begin{align*}\n\\concretesym{&(\\sigma_0,\\;\\sigma_1);\\\\\n&\\sigma_0:=\\assocsym{P}{Magnitude},\\\\\n&\\sigma_1:=\\assocsym{P}{Words}}.\n\\end{align*}\n\\end{example}\nNote that the Swift type in a superclass or concrete type symbol cannot itself be a type parameter. That is, the following is never valid:\n\\[\\concretesym{\\sigma_0;\\; \\sigma_0=\\hbox{some term}}\\]\nA same-type requirement between a type parameter and another type parameter is always represented as an equivalence of terms, no concrete type symbols are involved.\n\n\\index{partial order}\nOne thing to note is that the reduction order on symbols (Definition \\ref{symbolorder}) is a partial order, as layout, superclass and concrete type symbols are incomparable amongst themselves. Ordinarily, this would imply that the Knuth-Bendix completion procedure (Algorithm~\\ref{knuthbendix}) can fail in a new way: when resolving a critical pair $(t_0, t_1)$ to a rewrite rule, it might be the case that there is no way to orient the rule; that is, neither $t_0t_1$? Since $x'\\Rightarrow y'$ is a property-like rule, $x'$ is equal to $y'$ with a concrete type symbol appended, or in other words, $y'=vw$, so $t_1=uvw$. But $x=uv$, so $t_1=uvw$ reduces to $yw$. So indeed, the above critical pair either becomes trivial if $t_0$ can be reduced by some other rule, or it introduces the rewrite rule $t_0\\Rightarrow yw$.)\n\n\\begin{example}\nConsider the generic signature of class $\\namesym{C}$ from Listing~\\ref{overlapconcreteex}:\n\\begin{listing}\\caption{Example with overlap involving concrete type term}\\label{overlapconcreteex}\n\\begin{Verbatim}\nstruct G {}\n\nprotocol S {\n associatedtype E\n}\n\nprotocol P {\n associatedtype T\n associatedtype U where U == G\n associatedtype V\n}\n\nclass C\n where X : S,\n X.E : P,\n X.E.U == X.E.T {}\n\\end{Verbatim}\n\\end{listing}\n\\begin{align*}\n\\gensig{\\genericsym{0}{0}}{&\\genericsym{0}{0}\\colon\\proto{S},\\\\\n&\\genericsym{0}{0}.\\namesym{E}\\colon\\proto{P},\\\\\n&\\genericsym{0}{0}.\\namesym{E}.\\namesym{U}==\\genericsym{0}{0}.\\namesym{E}.\\namesym{T}}\n\\end{align*}\nThe relevant subset of this generic signature's rewrite rules:\n\\begin{align}\n%&\\protosym{P}.\\namesym{T}&\\Rightarrow\\;&\\assocsym{P}{T}\\tag{Rule 1}\\\\\n%&\\protosym{P}.\\namesym{U}&\\Rightarrow\\;&\\assocsym{P}{U}\\tag{Rule 2}\\\\\n%&\\protosym{P}.\\namesym{V}&\\Rightarrow\\;&\\assocsym{P}{V}\\tag{Rule 3}\\\\\n&\\assocsym{P}{U}.\\concretesym{\\namesym{G}\\langle\\sigma_0\\rangle;\\;\\sigma_0:=\\assocsym{P}{V}}&\\Rightarrow\\;&\\assocsym{P}{U}\\tag{Rule 1}\\\\\n&\\genericsym{0}{0}.\\protosym{S}&\\Rightarrow\\;&\\genericsym{0}{0}\\tag{Rule 2}\\\\\n&\\genericsym{0}{0}.\\assocsym{S}{E}.\\protosym{P}&\\Rightarrow\\;&\\genericsym{0}{0}.\\assocsym{S}{E}\\tag{Rule 3}\\\\\n&\\genericsym{0}{0}.\\assocsym{S}{E}.\\assocsym{P}{U}&\\Rightarrow\\;&\\genericsym{0}{0}.\\assocsym{S}{E}.\\assocsym{P}{T}\\tag{Rule 4}\n\\end{align}\nObserve that Rule 4 overlaps with Rule 1. The prefix $\\genericsym{0}{0}.\\assocsym{S}{E}$ must be prepended to the substitution $\\sigma_0$ in the concrete type symbol when computing the critical pair:\n\\begin{align*}\nt_0&=\\genericsym{0}{0}.\\assocsym{S}{E}.\\assocsym{P}{T}.\\concretesym{\\namesym{G}\\langle\\sigma_0\\rangle;\\;\\sigma_0:=\\genericsym{0}{0}.\\assocsym{S}{E}.\\assocsym{P}{V}}\\\\\nt_1&=\\genericsym{0}{0}.\\assocsym{S}{E}.\\assocsym{P}{U}\n\\end{align*}\nNow, $t_0$ cannot be reduced further, whereas Rule 7 reduces $t_1$ to\n$\\genericsym{0}{0}.\\assocsym{S}{E}.\\assocsym{P}{T}$.\nThis means that resolving the critical pair introduces the new rewrite rule:\n\\[\\genericsym{0}{0}.\\assocsym{S}{E}.\\assocsym{P}{T}.\\concretesym{\\namesym{G}\\langle\\sigma_0\\rangle;\\;\\sigma_0:=\\genericsym{0}{0}.\\assocsym{S}{E}.\\assocsym{P}{V}}\\Rightarrow\\genericsym{0}{0}.\\assocsym{S}{E}.\\assocsym{P}{T}.\n\\]\nIntuitively, the completion process began with the fact that\n\\[\\assocsym{P}{U}==\\namesym{G}\\langle\\assocsym{P}{V}\\rangle,\\]\nand derived that\\\n\\[\\genericsym{0}{0}.\\assocsym{S}{E}.\\assocsym{P}{T}==\\namesym{G}\\langle\\genericsym{0}{0}.\\assocsym{S}{E}.\\assocsym{P}{T}\\rangle.\\]\nAdjusting the concrete type symbol by prepending the prefix $\\genericsym{0}{0}.\\assocsym{S}{E}$ to the substitution $\\sigma_0$ appearing in the left-hand side of Rule 7 ``re-rooted'' the concrete type, giving the correct result shown above and preserving validity as per Definition~\\ref{concretevalid}. Without the adjustment, we would instead have derived the fact\n\\[\\genericsym{0}{0}.\\assocsym{S}{E}.\\assocsym{P}{T}==\\namesym{G}\\langle\\assocsym{P}{T}\\rangle,\\]\nwhich does not make sense.\n\\end{example}\nThe concrete type adjustment actually comes up again in the next chapter, during property map construction (Algorithm~\\ref{propmapconsalgo}) and lookup (Algorithm~\\ref{propmaplookupalgo}).\n\n\\chapter{The Property Map}\\label{propertymap}\n\nUntil now, you've seen how to solve the \\texttt{requiresProtocol()} generic signature\nquery. If $T$ is a type term, then the type parameter represented by $T$ conforms to a protocol\n$\\proto{P}$ if $T$ and $T.\\protosym{P}$ both reduce to the same canonical form ${T}{\\downarrow}$. The next\nstep is to solve more general queries, such as \\texttt{getRequiredProtocols()}. Here, you want to find\n\\emph{all} protocol symbols $\\protosym{P}$ such that $T.\\protosym{P}$ and $T$ reduce to some\n${T}{\\downarrow}$.\n\n\\index{layout requirement}\n\\index{conformance requirement}\n\\index{concrete type requirement}\n\\index{property-like symbol}\nOne potential implementation would use exhaustive enumeration. A rewrite system's rules only mention a\nfinite set of protocol symbols, so it would be enough to suffix a type term with every known\nprotocol symbol and attempt to reduce the result. While this shows that the query is implementable,\nit is an unsatisfying solution. The approach I'm going to outline below is more efficient, and also more generally useful with generic signature queries involving layout, superclass and concrete type requirements as well.\n\\begin{definition} If $T$ and $U$ are terms and there is some term $Z$ such that $T\\rightarrow Z$\nand $U\\rightarrow Z$, then $T$ and $U$ are said to be \\emph{joinable}, and this is written as $T\\downarrow U$.\n\\end{definition}\n\\begin{definition}\nIf $\\Pi$ is a property-like symbol and $T$ is a term, then $T$ \\emph{satisfies} $\\Pi$ if $T.\\Pi\\downarrow T$. The set of properties satisfied by $T$ is defined as the set of all symbols $\\Pi$ such that $T.\\Pi\\downarrow T$.\n\\end{definition}\n\n\\begin{theorem}\\label{propertymaptheorem} If $T$ is a type term with canonical form ${T}{\\downarrow}$, $\\Pi$ is a property-like\nsymbol, and $T$ satisfies $\\Pi$, then ${T}{\\downarrow}.\\Pi\\rightarrow{T}{\\downarrow}$. Furthermore, this\nreduction sequence consists of a single rule $V.\\Pi\\Rightarrow V$, for some non-empty suffix $V$ of ${T}{\\downarrow}$.\n\\end{theorem}\n\\begin{proof}\nSince $T$ can be reduced to ${T}{\\downarrow}$, the same reduction sequence when applied to $T.\\Pi$ will\nproduce ${T}{\\downarrow}.\\Pi$. This means that $T.\\Pi$ can be reduced to both ${T}{\\downarrow}$ (by\nassumption), and ${T}{\\downarrow}.\\Pi$. By confluence, ${T}{\\downarrow}.\\Pi$ must reduce to ${T}{\\downarrow}$.\n\nSince ${T}{\\downarrow}$ is canonical, ${T}{\\downarrow}.\\Pi$ cannot be reduced further except with a rewrite rule\nof the form $V.\\Pi\\Rightarrow V'$, where ${T}{\\downarrow}=UV$, for terms $U$, $V$ and $V'$. It remains to show\nthat $V=V'$. (TODO: This needs an additional assumption about conformance-valid rules.)\n\\end{proof}\n\nBy Theorem~\\ref{propertymaptheorem}, the properties satisfied by a type term can be discovered by\nconsidering all non-empty suffixes of ${T}{\\downarrow}$, and collecting rewrite rules of the form\n$V.\\Pi\\rightarrow V$ where $\\Pi$ is some property-like symbol.\n\n\\begin{listing}\\caption{Motivating example for property map}\\label{propmaplisting1}\n\\begin{Verbatim}\n\nprotocol P1 {}\n\nprotocol P2 {}\n\nprotocol P3 {\n associatedtype T : P1\n associatedtype U : P2\n}\n\nprotocol P4 {\n associatedtype A : P3 where A.T == A.U\n associatedtype B : P3\n}\n\\end{Verbatim}\n\\end{listing}\n\n\\begin{example}\\label{propmapexample1}\nConsider the protocol definitions in Listing~\\ref{propmaplisting1}. These definitions are used in a couple of examples below, so let's look at the constructed rewrite system first. Protocols $\\proto{P1}$ and $\\proto{P2}$ do not define any associated types or requirements, so they do not contribute any initial rewrite rules. Protocol $\\proto{P3}$ has two associated types $\\namesym{T}$ and $\\namesym{U}$ conforming to $\\proto{P1}$ and $\\proto{P2}$ respectively, so a pair of rules introduce each associated type, and another pair impose conformance requirements:\n\\begin{align}\n\\protosym{P3}.\\namesym{T}&\\Rightarrow\\assocsym{P3}{T}\\tag{1}\\\\\n\\protosym{P3}.\\namesym{U}&\\Rightarrow\\assocsym{P3}{U}\\tag{2}\\\\\n\\assocsym{P3}{T}.\\protosym{P1}&\\Rightarrow\\assocsym{P3}{T}\\tag{3}\\\\\n\\assocsym{P3}{U}.\\protosym{P2}&\\Rightarrow\\assocsym{P3}{U}\\tag{4}\n\\end{align}\nProtocol $\\proto{P4}$ adds five additional rules. A pair of rules introduce the associated types $\\namesym{A}$ and $\\namesym{B}$. Next, both associated types conform to $\\proto{P3}$, and $\\namesym{A}$ has a same-type requirement between it's nested types $\\namesym{T}$ and $\\namesym{U}$:\n\\begin{align}\n\\protosym{P4}.\\namesym{A}&\\Rightarrow\\assocsym{P4}{A}\\tag{5}\\\\\n\\protosym{P4}.\\namesym{B}&\\Rightarrow\\assocsym{P4}{B}\\tag{6}\\\\\n\\assocsym{P4}{A}.\\protosym{P3}&\\Rightarrow\\assocsym{P4}{A}\\tag{7}\\\\\n\\assocsym{P4}{B}.\\protosym{P3}&\\Rightarrow\\assocsym{P4}{B}\\tag{8}\\\\\n\\assocsym{P4}{A}.\\assocsym{P3}{U}&\\Rightarrow\\assocsym{P4}{A}.\\assocsym{P3}{T}\\tag{9}\n\\end{align}\nWhen applied to the above initial rewrite system, the Knuth-Bendix algorithm adds a handful of new rules to resolve critical pairs. First, there are four overlaps between the conformance requirements of $\\proto{P4}$ and the associated type introduction rules of $\\proto{P3}$:\n\\begin{align}\n\\assocsym{P4}{A}.\\namesym{T}&\\Rightarrow\\assocsym{P4}{A}.\\assocsym{P3}{T}\\tag{10}\\\\\n\\assocsym{P4}{A}.\\namesym{U}&\\Rightarrow\\assocsym{P4}{A}.\\assocsym{P3}{T}\\tag{11}\\\\\n\\assocsym{P4}{B}.\\namesym{T}&\\Rightarrow\\assocsym{P4}{B}.\\assocsym{P3}{T}\\tag{12}\\\\\n\\assocsym{P4}{B}.\\namesym{U}&\\Rightarrow\\assocsym{P4}{B}.\\assocsym{P3}{U}\\tag{13}\n\\end{align}\nFinally, there is an overlap between Rule~9 and Rule~4:\n\\begin{align}\n\\assocsym{P4}{A}.\\assocsym{P3}{T}.\\protosym{P2}&\\Rightarrow\\assocsym{P4}{A}.\\assocsym{P3}{T}\\tag{14}\n\\end{align}\nConsider the type parameter $\\genericparam{Self}.\\namesym{A}.\\namesym{U}$ in the generic signature of $\\proto{P4}$. This type parameter is equivalent to $\\genericparam{Self}.\\namesym{A}.\\namesym{T}$ via the same-type requirement in $\\proto{P4}$. The associated type $\\namesym{T}$ of $\\proto{P3}$ conforms to $\\proto{P1}$, and $\\namesym{U}$ conforms to $\\proto{P2}$. This means that $\\genericparam{Self}.\\namesym{A}.\\namesym{U}$ conforms to \\emph{both} $\\proto{P1}$ and $\\proto{P2}$.\n\nLet's see how this fact can be derived from the rewrite system. Applying $\\Lambda_{\\proto{P4}}$ to $\\genericparam{Self}.\\namesym{A}.\\namesym{U}$ produces the type term $\\assocsym{P4}{A}.\\assocsym{P3}{U}$. This type term can be reduced to the canonical term $\\assocsym{P4}{A}.\\assocsym{P3}{T}$ with a single application of Rule~9. By the result in Theorem~\\ref{propertymaptheorem}, it suffices to look at rules of the form $V.\\Pi\\Rightarrow V$, where $V$ is some suffix of $\\assocsym{P4}{A}.\\assocsym{P3}{T}$. There are two such rules:\n\\begin{enumerate}\n\\item Rule~3, which says that $\\assocsym{P3}{T}$ conforms to $\\proto{P1}$.\n\\item Rule~14, which says that $\\assocsym{P4}{A}.\\assocsym{P4}{T}$ conforms to $\\proto{P2}$.\n\\end{enumerate}\nThis shows that the set of properties satisfied by the type parameter $\\genericparam{Self}.\\namesym{A}.\\namesym{U}$ is exactly $\\{\\protosym{P1},\\protosym{P2}\\}$.\n\\end{example}\nThe above example might suggest that looking up the set of properties satisfied by a type parameter requires iterating over the list of rewrite rules, but in reality, it is possible to construct a multi-map of pairs $(V, \\Pi)$ once, after the completion procedure ends.\n\nAs you saw in the example, a type term can satisfy multiple properties via different suffixes. For the material presented in Section~\\ref{moreconcretetypes}, it is convenient to avoid having to take the union of sets in the lookup path. For this reason, the construction algorithm explicitly\n``inherits'' the symbols associated with a term $V$ when adding an entry for a term $UV$ that has $V$ as a suffix. As a result, the lookup algorithm only has to look for the longest suffix that appears in the multi-map to find all properties satisfied by a term.\n\nThe multi-map construction and lookup can be formalized in a pair of algorithms.\n\\begin{algorithm}[Property map construction]\\label{propmapconsalgo}\nThis algorithm runs after the completion procedure has constructed a confluent rewrite system with\nsimplified right hand sides. As output, it produces a multi-map mapping terms to sets of\nsymbols.\n\n\\begin{enumerate}\n\\item Initialize $S$ to the list of all rewrite rules of the form $V.\\Pi\\Rightarrow V$.\n\\item Initialize $P$ to a multi-map mapping terms to sets of symbols, initially empty.\n\\item Sort $S$ in ascending order by the lengths of the rewrite rules' left-hand sides. The\nrelative order of rules whose left hand sides have the same length is irrelevant.\n\\item For each rule $V.\\Pi\\Rightarrow V\\in S$,\n\\begin{enumerate}\n\\item If $V\\notin P$, initialize $P[V]$ first as follows.\n\nIf $P$ contains some $V''$ where $V=V'V''$, copy the symbols from $P[V'']$ to $P[V]$.\nWhen copying superclass or concrete type symbols, the substitution\nterms inside the symbol must be adjusted by prepending $V'$.\n\nThis is the point where the algorithm relies on the sorting of rules done in Step~2. Since\n$|V''|<|V|$, all rules of the form $V''.\\Pi\\Rightarrow V''$ have already been visited by the time\nthe algorithm can encounter a rule involving $V$.\n\nIn fact, since the map is constructed in\nbottom-up order, it suffices to only check the \\emph{longest} suffix $V''$ of $V$ such that $V''\\in P$.\n\n\\item Insert $\\Pi$ in $P[V]$.\n\\end{enumerate}\n\\end{enumerate}\n\\end{algorithm}\nOnce the property map has been built, lookup is very simple.\n\\begin{algorithm}[Property map lookup]\\label{propmaplookupalgo} Given a type parameter $T$ and a property map $P$, this\nalgorithm outputs the set of properties satisfied by $T$.\n\n\\begin{enumerate}\n\\item First, lower $T$ to a type term $\\Lambda(T)$, and reduce this term to canonical form $\\Lambda(T){\\downarrow}$.\n\\item If no suffix of $\\Lambda(T){\\downarrow}$ appears in $P$, return the empty set.\n\\item Otherwise, let $\\Lambda(T){\\downarrow}:=UV$, where $V$ is the longest suffix of $\\Lambda(T){\\downarrow}$ appearing in $P$.\n\\item Let $S:=V[P]$, the set of property symbols associated with $V$ in $P$.\n\\item For each superclass or concrete type symbol $\\Pi\\in S$, prepend $U$ to every substitution\nterm inside the symbol.\n\\end{enumerate}\n\\end{algorithm}\nNotice how in both algorithms, superclass and concrete type symbols are adjusted by prepending a\nprefix to each substitution. This is the same operation as described in\nSection~\\ref{concretetypeadjust}.\n\n\\begin{example}\\label{propmapexample2}\nRecall Example~\\ref{propmapexample1}, where a rewrite system was constructed from Listing~\\ref{propmaplisting}. The complete rewrite system contains five rewrite rules of the form $V.\\Pi\\Rightarrow V$:\n\\begin{enumerate}\n\\item Rule~3 and Rule~4, which state that the associated types $\\namesym{T}$ and $\\namesym{U}$ of $\\proto{P3}$ conform to $\\proto{P1}$ and $\\proto{P2}$, respectively.\n\\item Rule~7 and Rule~8, which state that the associated types $\\namesym{A}$ and $\\namesym{B}$ of $\\proto{P4}$ both conform to $\\proto{P3}$.\n\\item Rule~13, which states that the nested type $\\genericparam{A}.\\genericparam{T}$ of $\\proto{P4}$ also conforms to $\\proto{P2}$.\n\\end{enumerate}\nThe property map constructed by Algorithm~\\ref{propmapconsalgo} from the above rules is shown in Table~\\ref{propmapexample2table}.\n\\end{example}\n\\begin{table}\\caption{Property map constructed from Example~\\ref{propmapexample2}}\\label{propmapexample2table}\n\\begin{center}\n\\begin{tabular}{|l|l|}\n\\hline\nKey&Values\\\\\n\\hline\n\\hline\n$\\assocsym{P3}{T}$&$\\protosym{P1}$\\\\\n$\\assocsym{P3}{U}$&$\\protosym{P2}$\\\\\n$\\assocsym{P4}{A}$&$\\protosym{P3}$\\\\\n$\\assocsym{P4}{B}$&$\\protosym{P3}$\\\\\n$\\assocsym{P4}{A}.\\assocsym{P3}{T}$&$\\protosym{P1}$, $\\protosym{P2}$\\\\\n\\hline\n\\end{tabular}\n\\end{center}\n\\end{table}\n\\begin{example}\\label{propmapexample3}\nThe second example explores layout, superclass and concrete type requirements. Consider the protocol definitions in Listing~\\ref{propmaplisting} together with the generic signature:\n\\[\\gensig{\\genericsym{0}{0}}{\\genericsym{0}{0}\\colon\\proto{P}, \\genericsym{0}{0}.\\namesym{B}\\colon\\proto{Q}}\\]\nThe three protocols $\\proto{R}$, $\\proto{Q}$ and $\\proto{P}$ together with the generic signature generate the following initial rewrite rules:\n\\begin{align*}\n\\protosym{Q}.\\protosym{R}&\\Rightarrow\\protosym{Q}\\tag{1}\\\\\n\\protosym{P}.\\namesym{A}&\\Rightarrow\\assocsym{P}{A}\\tag{2}\\\\\n\\protosym{P}.\\namesym{B}&\\Rightarrow\\assocsym{P}{B}\\tag{3}\\\\\n\\protosym{P}.\\namesym{C}&\\Rightarrow\\assocsym{P}{C}\\tag{4}\\\\\n\\assocsym{P}{A}.\\layoutsym{AnyObject}&\\Rightarrow\\assocsym{P}{A}\\tag{5}\\\\\n\\assocsym{P}{B}.\\supersym{\\namesym{Cache}\\langle\\sigma_0\\rangle;\\,\\sigma_0:=\\assocsym{P}{A}}&\\Rightarrow\\assocsym{P}{B}\\tag{6}\\\\\n\\assocsym{P}{B}.\\layoutsym{\\_NativeClass}&\\Rightarrow\\assocsym{P}{B}\\tag{7}\\\\\n\\assocsym{P}{C}.\\concretesym{\\namesym{Array}\\langle\\sigma_0\\rangle;\\,\\sigma_0:=\\assocsym{P}{A}}&\\Rightarrow\\assocsym{P}{C}\\tag{8}\\\\\n\\genericsym{0}{0}.\\protosym{P}&\\Rightarrow\\genericsym{0}{0}\\tag{9}\\\\\n\\genericsym{0}{0}.\\assocsym{P}{B}.\\protosym{Q}&\\Rightarrow\\genericsym{0}{0}.\\assocsym{P}{B}\\tag{10}\n\\end{align*}\nThe Knuth-Bendix algorithm adds the following rules to make the rewrite system confluent:\n\\begin{align*}\n\\genericsym{0}{0}.\\namesym{A}&\\Rightarrow\\genericsym{0}{0}.\\assocsym{P}{A}\\tag{11}\\\\\n\\genericsym{0}{0}.\\namesym{B}&\\Rightarrow\\genericsym{0}{0}.\\assocsym{P}{B}\\tag{12}\\\\\n\\genericsym{0}{0}.\\namesym{C}&\\Rightarrow\\genericsym{0}{0}.\\assocsym{P}{C}\\tag{13}\\\\\n\\genericsym{0}{0}.\\assocsym{P}{B}.\\protosym{R}&\\Rightarrow\\genericsym{0}{0}.\\assocsym{P}{B}\\tag{14}\n\\end{align*}\n\\begin{listing}\\caption{Protocol with concrete type requirements}\\label{propmaplisting}\n\\begin{Verbatim}\nclass Cache {}\n\nprotocol R {}\nprotocol Q : R {}\n\nprotocol P {\n associatedtype A : AnyObject\n associatedtype B : Cache\n associatedtype C where C == Array\n}\n\\end{Verbatim}\n\\end{listing}\nThe following rewrite rules take the form $V.\\Pi\\Rightarrow V$, where $\\Pi$ is a property-like symbol:\n\\begin{enumerate}\n\\item Rule~1, which states that protocol $\\proto{Q}$ inherits from $\\proto{R}$.\n\\item Rule~5, which states that the associated type $\\namesym{A}$ in protocol $\\proto{P}$ is represented as an $\\namesym{AnyObject}$.\n\\item Rule~6, which states that the associated type $\\namesym{B}$ in protocol $\\proto{P}$ must inherit from $\\namesym{Cache}\\langle\\namesym{A}\\rangle$.\n\\item Rule~7, which states that the associated type $\\namesym{B}$ in protocol $\\proto{P}$ is also represented as a $\\namesym{\\_NativeClass}$.\n\\item Rule~8, which states that the associated type $\\namesym{C}$ in protocol $\\proto{P}$ is fixed to the concrete type $\\namesym{Array}\\langle\\namesym{A}\\rangle$.\n\\item Rule~9, which states that the generic parameter $\\genericsym{0}{0}$ conforms to $\\proto{P}$.\n\\item Rule~10, which states that the type parameter $\\genericsym{0}{0}.\\namesym{B}$ conforms to $\\proto{Q}$.\n\\item Rule~14, which states that the type parameter $\\genericsym{0}{0}.\\namesym{B}$ conforms to $\\proto{R}$.\n\nThis final rule was added by the completion procedure to resolve the overlap of Rule~10 and Rule~1 on the term $\\genericsym{0}{0}.\\assocsym{P}{B}.\\protosym{Q}.\\protosym{R}$.\n\\end{enumerate}\nWhen constructing the property map, sorting the rules by the length of their left hand sides guarantees that Rule~6 and Rule~7 are processed before Rule~10 and Rule~14. This is important because the subject type of Rule~6 and Rule~7 ($\\assocsym{P}{B}$), is a suffix of the subject type of Rule~10 and Rule~14 ($\\genericsym{0}{0}.\\assocsym{P}{B}$), which means that the property map entries for both Rule~10 and Rule~14 inherit the superclass and layout requirements from Rule~6 and Rule~7. Furthermore, the substitution $\\sigma_0:=\\assocsym{P}{A}$ in the superclass requirement is adjusted by prepending the prefix $\\genericsym{0}{0}$.\n\nThe property map constructed by Algorithm~\\ref{propmapconsalgo} from the above rules is shown in Table~\\ref{propmapexample2table}.\nIn the next section, you will see how this example property map can solve generic signature queries.\n\\begin{table}\\caption{Property map constructed from Example~\\ref{propmapexample3}}\\label{propmapexample2table}\n\\begin{center}\n\\begin{tabular}{|l|l|}\n\\hline\nKey&Values\\\\\n\\hline\n\\hline\n$\\protosym{Q}$&$\\protosym{R}$\\\\\n$\\assocsym{P}{A}$&$\\layoutsym{AnyObject}$\\\\\n$\\assocsym{P}{B}$&$\\supersym{\\namesym{Cache}\\langle\\sigma_0\\rangle;\\,\\sigma_0:=\\assocsym{P}{A}}$, $\\layoutsym{\\_NativeClass}$\\\\\n$\\assocsym{P}{C}$&$\\concretesym{\\namesym{Array}\\langle\\sigma_0\\rangle;\\,\\sigma_0:=\\assocsym{P}{A}}$\\\\\n$\\genericsym{0}{0}$&$\\protosym{P}$\\\\\n$\\genericsym{0}{0}.\\assocsym{P}{B}$&$\\protosym{Q}$, $\\protosym{R}$, $\\supersym{\\namesym{Cache}\\langle\\sigma_0\\rangle;\\,\\sigma_0:=\\genericsym{0}{0}.\\assocsym{P}{A}}$, $\\layoutsym{\\_NativeClass}$\\\\\n\\hline\n\\end{tabular}\n\\end{center}\n\\end{table}\n\\end{example}\n\n\\section{Generic Signature Queries}\\label{implqueries}\n\nRecall the categorization of generic signature queries into predicates, properties and canonical type queries previously shown in Section~\\ref{intqueries}. The predicates can be implemented in a straightforward manner using the property map. Each predicate takes a subject type parameter $T$.\n\nGeneric signature queries are always posed relative to a generic signature, and not a protocol requirement signature, hence the type parameter $T$ is lowered with the generic signature type lowering map $\\Lambda\\colon\\namesym{Type}\\rightarrow\\namesym{Term}$ (Definition~\\ref{lowertypeinsig}) and not a protocol type lowering map $\\Lambda_{\\proto{P}}\\colon\\namesym{Type}\\rightarrow\\namesym{Term}$ for some protocol $\\proto{P}$ (Definition~\\ref{lowertypeinproto}).\n\nThe first step is to look up the set of properties satisfied by $T$ using Algorithm~\\ref{propmaplookupalgo}. Then, each predicate can be tested as follows:\n\\begin{description}\n\\item[\\texttt{requiresProtocol()}] A type parameter $T$ conforms to a protocol $\\proto{P}$ if the property map entry for some suffix of $T$ stores $\\protosym{P}$ for some suffix of $T$.\n\\index{layout constraints}\n\\index{join of layout constraints}\n\\item[\\texttt{requiresClass()}] A type parameter $T$ is represented as a retainable pointer if the property map entry for some suffix of $T$ stores a layout symbol $L$ such that $L\\leq\\layoutsym{AnyObject}$.\n\nThe order relation comes into play because there exist layout symbols which further refine $\\layoutsym{AnyObject}$, for example $\\layoutsym{\\_NativeClass}$, so it is not enough to check for a layout symbol exactly equal to $\\layoutsym{AnyObject}$.\n\nGiven two layout symbols $A$ and $B$, $A\\wedge B$ is the most general symbol that satisfies both $A$ and $B$. The two elements are ordered $A\\leq B$ if $A=A\\wedge B$.\n\\item[\\texttt{isConcreteType()}] A type parameter $T$ is fixed to a concrete type if the property map entry for some suffix of $T$ stores a concrete type symbol.\n\\end{description}\n\\begin{leftbar}\n\\noindent Layout symbols store a layout constraint as an instance of the \\texttt{LayoutConstraint} class. The join operation used in the implementation of the \\texttt{requiresClass()} query is defined in the \\texttt{merge()} method on \\texttt{LayoutConstraint}.\n\\end{leftbar}\nYou've already seen the \\texttt{requiresProtocol()} query in Chapter~\\ref{protocolsasmonoids}, where it was shown that it can be implemented by checking if $\\Lambda(T).\\protosym{P}\\downarrow\\Lambda(T)$. The property map implementation is perhaps slightly more efficient, since it only simplifies a single term and not two. The $\\texttt{requiresClass()}$ and $\\texttt{isConcreteType()}$ queries are new on the other hand, and demonstrate the power of the property map. With the rewrite system alone, they cannot be implemented except by exhaustive enumeration over all known layout and concrete type symbols.\n\nAll of the subsequent examples reference the protocol definitions from Example~\\ref{propmapexample3}, and the resulting property map shown in Table~\\ref{propmapexample2table}.\n\\begin{example} Consider the canonical type term $\\genericsym{0}{0}.\\assocsym{P}{B}$. This type parameter conforms to $\\proto{Q}$ via a requirement stated in the generic signature, and also to $\\proto{R}$, because $\\proto{Q}$ inherits from $\\proto{R}$. The $\\texttt{requiresProtocol()}$ query will confirm these facts, because the property map entry for $\\genericsym{0}{0}.\\assocsym{P}{B}$ contains the protocol symbols $\\protosym{Q}$ and $\\protosym{R}$:\n\\begin{enumerate}\n\\item The conformance to $\\proto{Q}$ is witnessed by the rewrite rule $\\genericsym{0}{0}.\\assocsym{P}{B}.\\protosym{Q}\\Rightarrow \\genericsym{0}{0}.\\assocsym{P}{B}$, which is Rule~10 in Example~\\ref{propmapexample2}. This is the initial rule generated by the conformance requirement.\n\\item The conformance to $\\proto{R}$ is witnessed by the rewrite rule $\\genericsym{0}{0}.\\assocsym{P}{B}.\\protosym{R}\\Rightarrow \\genericsym{0}{0}.\\assocsym{P}{B}$, which is Rule~14 in Example~\\ref{propmapexample2}. This rule was added by the completion procedure to resolve the overlap between Rule~10 above, which states that $\\genericsym{0}{0}.\\assocsym{P}{B}$ conforms to $\\proto{Q}$, and Rule~1, which states that anything conforming to $\\proto{Q}$ also conforms to $\\proto{R}$.\n\\end{enumerate}\n\\end{example}\n\\begin{example} This example shows the \\texttt{requiresClass()} query on two different type terms.\n\nFirst, consider the canonical type term $\\genericsym{0}{0}.\\assocsym{P}{A}$. The query returns true, because the longest suffix with an entry in the property map is $\\assocsym{P}{A}$, which stores a single symbol, $\\layoutsym{AnyObject}$. The corresponding rewrite rule is $\\assocsym{P}{A}.\\layoutsym{AnyObject}\\Rightarrow\\assocsym{P}{A}$, or Rule~5 in Example~\\ref{propmapexample2}. This is the initial rule generated by the $\\namesym{A}\\colon\\namesym{AnyObject}$ layout requirement in protocol $\\proto{P}$.\n\nNow, consider the canonical type term $\\genericsym{0}{0}.\\assocsym{P}{B}$. The query also returns true. Here, the longest suffix is the entire type term, because the property map stores an entry for $\\genericsym{0}{0}.\\assocsym{P}{B}$ with layout symbol $\\layoutsym{\\_NativeClass}$. This symbol satisfies\n\\[\\layoutsym{\\_NativeClass}\\leq\\layoutsym{AnyObject},\\]\nbecause\n\\[\\layoutsym{\\_NativeClass}\\wedge \\layoutsym{AnyObject}=\\layoutsym{\\_NativeClass}.\\]\n\\end{example}\n\\begin{example}\nThe final predicate is the \\texttt{isConcreteType()} query. Consider the canonical type term $\\genericsym{0}{0}.\\assocsym{P}{C}$. The longest suffix that appears in the property map is $\\assocsym{P}{C}$. This entry stores the concrete type symbol $\\concretesym{\\namesym{Array}\\langle\\sigma_0\\rangle;\\,\\sigma_0:=\\assocsym{P}{A}}$, and so the query returns true.\n\\end{example}\n\nNext, I will describe the generic signature queries that return properties of type parameters, but this requires building up a little more machinery first. The first step is to define the invariants satisfied by the list of protocols returned by the \\texttt{getRequiredProtocols()} query.\n\n\\begin{definition}\\label{minimalproto} A list of protocols $\\{\\proto{P}_i\\}$ is \\emph{minimal} if\nno\nprotocol inherits from any other protocol in the list; that is, there do not exist $i,\nj\\in\\mathbb{N}$ such that $i\\neq j$ and $\\proto{P}_i$ inherits from $\\proto{P}_j$. The list is\n\\emph{canonical}\nif it is sorted in canonical protocol order.\n\nA minimal canonical list of protocols\ncan be constructed from an arbitrary list of protocols\n$P=\\{\\proto{P}_1,\\ldots,\\proto{P}_n\\}$ via the following algorithm:\n\\begin{enumerate}\n\\item Let $G=(V, E)$ be the directed acyclic graph\\footnote{Invalid code seen by the\ntype checker can have circular protocol inheritance. The ``request evaluator''\nframework in the compiler handles cycle breaking in a principled manner, so the\nrequirement machine does not have to deal with this explicitly.} where $V$ is the set\nof all protocols, and an edge in $E$ connects $\\proto{P}\\in V$ to $\\proto{Q}\\in V$ if\n$\\proto{P}$ inherits from $\\proto{Q}$.\n\\item Construct the subgraph $H\\subseteq G$ generated by $P$.\n\\item Compute the set of root nodes of $H$ (that is, the nodes with no incoming edges, or zero in-degree) to obtain the minimal set protocols of\n$P$.\n\\item Sort the elements of this set using the canonical protocol order (Definition~\\ref{canonicalprotocol}) to obtain the\nfinal minimal canonical list of protocols from $P$.\n\\end{enumerate}\n\\end{definition}\nThe second step is to define a mapping from type terms to Swift type parameters, for use by the \\texttt{getSuperclassBound()} and \\texttt{getConcreteType()} queries when mapping substitutions back to Swift types.\n\\begin{algorithm} The type lifting map $\\Lambda^{-1}:\\namesym{Term}\\rightarrow\\namesym{Type}$ takes as input\na type term $T$ and maps it back to a Swift type parameter. This is the inverse of the type lowering\nmap $\\Lambda\\colon\\namesym{Type}\\rightarrow\\namesym{Term}$ from Algorithm~\\ref{lowertypeinproto}.\n\\begin{enumerate}\n\\item Initialize $S$ to an empty type parameter.\n\\item The first symbol of $T$ must be a generic parameter symbol $\\tau_{d,i}$, which is mapped to a\n\\texttt{GenericTypeParamType} with depth $d$ and index $i$. Set $S$ to this type.\n\\item Any subsequent symbol in $T$ must be some associated type symbol\n$[\\proto{P}_1\\cap\\ldots\\cap\\proto{P}_n\\colon\\namesym{A}]$. This symbol is mapped to a\n\\texttt{DependentMemberType} whose base type is the previous value of $S$, and the associated type\ndeclaration is found as follows:\n\\begin{enumerate}\n\\item For each $\\proto{P}_i$, either $\\proto{P}_i$ directly defines an associated type named\n$\\namesym{A}$, or $\\namesym{A}$ was declared in some protocol $\\proto{Q}$ such that $\\proto{P}_i$\ninherits from $\\proto{Q}$. In both cases, collect all associated type declarations in a list.\n\\item If any associated type found above is a non-root associated type declaration, replace it with\nits anchor (Definition~\\ref{rootassoctypedef}).\n\\item Pick the associated type declaration from the above set that is minimal with respect to the\nassociated type order (Definition~\\ref{canonicaltypeorder}).\n\\end{enumerate}\n\\end{enumerate}\n\\end{algorithm}\nThe third and final step before the queries themselves can be presented is the algorithm for mapping a superclass or concrete type symbol back to a Swift type. This algorithm uses the above type lifting map on type parameters appearing in substitutions.\n\\begin{algorithm}[Constructing a concrete type from a symbol]\\label{symboltotype} As input, this algorithm takes a\nsuperclass symbol $\\supersym{\\namesym{T}\\colon\\sigma_0,\\ldots,\\sigma_n}$ or\nconcrete type symbol $\\concretesym{\\namesym{T}\\colon\\sigma_0,\\ldots,\\sigma_n}$. This is the inverse of Algorithm~\\ref{concretesymbolcons}.\n\n\\begin{enumerate}\n\\item Let $\\pi_0,\\ldots,\\pi_n$ be the set of positions such that $\\namesym{T}|_{\\pi_i}$ is a\n\\texttt{GenericTypeParamType} with index $i$.\n\\item For each $i$, replace $\\namesym{T}|_{\\pi_i}$ with $\\Lambda^{-1}(\\sigma_i)$, the type\nparameter obtained by applying the lifting map to $\\sigma_i$.\n\\item Return the final value of type $\\namesym{T}$ after performing all substitutions above.\n\\end{enumerate}\n\\end{algorithm}\n\nNow, the time has finally come to describe the implementation of the four property queries.\n\\begin{description}\n\\item[\\texttt{getRequiredProtocols()}] The list of protocol requirements satisfied by a type parameter $T$ is recorded in the form of protocol symbols in the property map. This list is transformed into a minimal canonical list of protocols using Definition~\\ref{minimalproto}.\n\\index{layout constraints}\n\\index{join of layout constraints}\n\\item[\\texttt{getLayoutConstraint()}] A type parameter $T$ might be subject to multiple layout constraints, in which case the property map entry will store a list of layout constraints $L_1,\\ldots,L_n$. This query needs to compute their join, which is the largest layout constraint that simultaneously satisfies all of them:\n\\[L_1\\wedge\\cdots\\wedge L_n.\\]\nSome layout constraints are disjoint on concrete types, meaning their join is the uninhabited ``bottom'' layout constraint, which precedes all other layout constraints in the partial order. In this case, the original generic signature is said to have conflicting requirements. While such a signature does not violate the requirement machine's invariants, it cannot be satisfied by any valid set of concrete substitutions. Detecting and diagnosing conflicting requirements is discussed later.\n\n\\item[\\texttt{getSuperclassBound()}] If the type parameter $T$ does not satisfy any superclass symbols, returns the empty type.\nOtherwise, $T$ can be written as $T=UV$, where $V$ is the longest suffix of $T$ present in the property map. Let $\\supersym{\\namesym{C};\\,\\sigma_0,\\ldots,\\sigma_n}$ be a superclass symbol in $T[V]$.\n\nThe first step is to adjust the symbol by prepending $U$ to each substitution $\\sigma_i$, to produce the superclass symbol\n\\[\\supersym{\\namesym{C};\\,\\sigma_0,\\ldots,U\\sigma_n}.\\]\nThen, Algorithm~\\ref{symboltotype} can be applied to convert the symbol to a Swift type.\n\\item\\texttt{getConcreteType()}: This query is almost identical to \\texttt{getSuperclassBound()}; you can replace ``superclass symbol'' with ``concrete type symbol'' above.\n\\end{description}\nNote how the \\texttt{getLayoutConstraint()} query deals with a multiplicity of layout symbols by computing their join, whereas the \\texttt{getSuperclassBound()} and \\texttt{getConcreteType()} queries just arbitrarily pick one superclass or concrete type symbol. Indeed in Section~\\ref{moreconcretetypes}, you will see that picking one symbol is not always sufficient, and a complete implementation must perform joins on superclass and concrete type symbols as well, and furthermore, a situation analogous to the uninhabited layout constraint can arise, where a type parameter can be subject to conflicting superclass or concrete type requirements. For now though, the current formulation is sufficient.\n\nNow, let's look at some examples of the four property queries. Once again, these examples use the property map shown in Table~\\ref{propmapexample2table}.\n\\begin{example}\nConsider the computation of the \\texttt{getRequiredProtocols()} query on the canonical type term $\\genericsym{0}{0}.\\assocsym{P}{B}$. The property map stores the protocol symbols $\\{\\protosym{Q},\\protosym{R}\\}$, but $\\proto{Q}$ inherits from $\\proto{R}$, so the minimal canonical list of protocols is just $\\{\\protosym{Q}\\}$.\n\\end{example}\n\\begin{example}\nConsider the computation of the \\texttt{getSuperclassBound()} query on the canonical type term $\\genericsym{0}{0}.\\assocsym{P}{B}$.\nThe superclass symbol $\\supersym{\\namesym{Cache}\\langle\\sigma_0\\rangle;\\,\\sigma_0:=\\assocsym{P}{A}}$ does not need to be adjusted by prepending a prefix to each substitution term, because the property map entry is associated with the entire term $\\genericsym{0}{0}.\\assocsym{P}{B}$.\n\nApplying Algorithm~\\ref{symboltotype} to the superclass symbol produces the Swift type:\n\\[\\namesym{Cache}\\langle\\genericsym{0}{0}.\\namesym{A}\\rangle\\].\n\\end{example}\n\\begin{example}\nConsider the computation of the \\texttt{getConcreteType()} query on the canonical type term $\\genericsym{0}{0}.\\assocsym{P}{C}$. Here, the property map entry is associated with the suffix $\\assocsym{P}{C}$, which means an adjustment must be performed on the concrete type symbol \n$\\concretesym{\\namesym{Array}\\langle\\sigma_0\\rangle;\\,\\sigma_0:=\\assocsym{P}{A}}$. The adjusted symbol is\n\\[\\concretesym{\\namesym{Array}\\langle\\sigma_0\\rangle;\\,\\sigma_0:=\\genericsym{0}{0}\\assocsym{P}{A}}.\\]\nApplying Algorithm~\\ref{symboltotype} to the adjusted concrete type symbol produces the Swift type:\n\\[\\namesym{Array}\\langle\\genericsym{0}{0}.\\namesym{A}\\rangle.\\]\n\\end{example}\n\n\\section{Canonical Types}\n\\index{canonical anchor}\n\\index{concrete type requirement}\nThe canonical type queries pull everything together.\n\\begin{description}\n\\item[\\texttt{areSameTypeParametersInContext()}] Two type parameters $T$ and $U$ are equivalent if $\\Lambda(T)\\downarrow\\Lambda(U)$, which is true if and only if $\\Lambda(T){\\downarrow}=\\Lambda(U){\\downarrow}$.\n\nNote that this query doesn't do anything useful if either $T$ or $U$ are fixed to a concrete type.\n\nThis is also the one and only generic signature query\nthat is solved with the rewrite system alone, and not the property map, but it is presented here for completeness.\n\\item[\\texttt{isCanonicalTypeInContext()}] This query performs a series of checks on a type $T$; if any of them fail, then $T$ is not canonical and false is returned.\n\nThere are two cases to consider; $T$ is either a type parameter, or a concrete type (which might possibly contain type parameters in nested positions):\n\\begin{enumerate}\n\\item If $T$ is a type parameter, then $T$ is a canonical type if it is both a canonical anchor, and not fixed to a concrete type.\n\\begin{enumerate}\n\\item\nPeculiarities of inherited and merged associated types mean that a type $T$ can be a canonical anchor at the \\emph{type} level, even if $\\Lambda(T)$ is not a canonical \\emph{term}. However there is a weaker condition that relates the two notions of canonical-ness: $T$ is a canonical anchor if and only if applying the type lowering map to $T$, reducing the result, and then finally applying the type lifting map produces $T$:\n\\[\\Lambda^{-1}(\\Lambda(T){\\downarrow})=T.\\]\n\\item\nOnce a type parameter $T$ is known to be a canonical anchor, checking if the \\texttt{isConcreteType()} query returns false is enough to determine that it is a canonical type parameter.\n\\end{enumerate}\n\\item Otherwise, $T$ is a concrete type. Let $\\pi_0,\\ldots,\\pi_n$ be the set of positions of $T$ such\nthat $T|_{\\pi_i}$ is a type parameter. Then $T$ is canonical if and only if all\nprojections $T|_{\\pi_i}$ are canonical type parameters.\n\\end{enumerate}\n\n\\item[\\texttt{getCanonicalTypeInContext()}] Once again, $T$ is either a type parameter, or a concrete type. The type parameter case is described first, and the concrete type case is implemented recursively by considering all nested positions that contain type parameters.\n\\begin{enumerate}\n\\item\nIf $T$ is a type parameter, the \\texttt{isConcreteType()} query will determine if $T$ is fixed to a concrete type or not.\n\\begin{enumerate}\n\\item If $T$ is fixed to some concrete type $T'$, the canonical type of $T$ is equal to the canonical type of $T'$. This can be computed by recursively calling \\texttt{getCanonicalTypeInContext()} on the result of \\texttt{getConcreteType()}.\n\\item Otherwise, $T$ is not fixed to a concrete type, which means that the canonical type of $T$ is the canonical anchor of $T$. Let $\\Lambda(T)$ be the type term corresponding to $T$, and let $\\Lambda(T){\\downarrow}$ be the canonical form of the term $\\Lambda(T)$. The canonical anchor of $T$ is $\\Lambda^{-1}(\\Lambda(T){\\downarrow})$.\n\\end{enumerate}\n\n\\item\nOtherwise, $T$ is a concrete type. Let $\\pi_0,\\ldots,\\pi_n$ be the set of positions of $T$ such\nthat $T|_{\\pi_i}$ is a type parameter. The canonical type of $T$ is the type obtained by substituting the type parameter at each position $\\pi_i$ with the result of a recursive call to \\texttt{getCanonicalTypeInContext()} on $T|_{\\pi_i}$.\n\\end{enumerate}\n\\end{description}\n\n\\begin{example} This example shows how protocol inheritance leads to a situation where a canonical anchor $T$ lowers to a non-canonical term $\\Lambda(T)$. Consider the generic signature $\\gensig{\\genericsym{0}{0}}{\\genericsym{0}{0}\\colon\\proto{P}}$ with the protocol definitions below:\n\\begin{Verbatim}\nprotocol Q {\n associatedtype A\n}\n\nprotocol P : Q {}\n\\end{Verbatim}\nThe rewrite system has two associated type introduction rules, one for the declaration of $\\namesym{A}$ in $\\proto{Q}$, and another for the inherited type $\\namesym{A}$ in $\\proto{P}$:\n\\begin{align}\n\\protosym{Q}.\\namesym{A}&\\Rightarrow\\assocsym{Q}{A}\\tag{1}\\\\\n\\protosym{P}.\\assocsym{Q}{A}&\\Rightarrow \\assocsym{P}{A}\\tag{2}\n\\end{align}\nThe protocol inheritance relationship also introduces a rewrite rule:\n\\begin{align}\n\\protosym{P}.\\protosym{Q}&\\Rightarrow\\protosym{P}\\tag{3}\n\\end{align}\nFinally, the conformance requirement in the generic signature adds the rewrite rule:\n\\begin{align}\n\\genericsym{0}{0}.\\protosym{P}&\\Rightarrow\\genericsym{0}{0}\\tag{4}\n\\end{align}\nResolving critical pairs adds a few additional rules:\n\\begin{align}\n\\protosym{P}.\\namesym{A}&\\Rightarrow\\assocsym{P}{A}\\tag{5}\\\\\n\\genericsym{0}{0}.\\protosym{Q}&\\Rightarrow\\genericsym{0}{0}\\tag{6}\\\\\n\\genericsym{0}{0}.\\assocsym{Q}{A}&\\Rightarrow\\genericsym{0}{0}.\\assocsym{P}{A}\\tag{7}\\\\\n\\genericsym{0}{0}.\\namesym{A}&\\Rightarrow\\genericsym{0}{0}.\\assocsym{P}{A}\\tag{8}\n\\end{align}\nNow consider the type parameter $T:=\\genericsym{0}{0}.\\namesym{A}$. This type parameter is a canonical anchor by Definition~\\ref{canonicalanchor}. Since Swift type parameters always point to an actual associated type declaration, the type term $\\Lambda(T)$ is $\\genericsym{0}{0}.\\assocsym{Q}{A}$, and not $\\genericsym{0}{0}.\\assocsym{P}{A}$. However, $\\genericsym{0}{0}.\\assocsym{Q}{A}$ is not canonical as a term, and reduces to $\\genericsym{0}{0}.\\assocsym{P}{A}$ via Rule~7, therefore $T$ is a canonical anchor and yet $\\Lambda(T)$ is not a canonical term.\n\nEssentially, the term $\\genericsym{0}{0}.\\assocsym{P}{A}$ is ``more canonical'' than any type parameter that can be output by $\\Lambda:\\namesym{Type}\\rightarrow\\namesym{Term}$. Protocol $\\proto{P}$ does not actually define an associated type named $\\namesym{A}$, therefore $\\Lambda$ can only construct terms containing the symbol $\\assocsym{Q}{A}$, and yet $\\assocsym{P}{A}<\\assocsym{Q}{A}$.\n\nThe key invariant here though is that $\\Lambda^{-1}(\\genericsym{0}{0}.\\assocsym{Q}{A})=\\Lambda^{-1}(\\genericsym{0}{0}.\\assocsym{P}{A})=T$, or in other words:\n\\[\\Lambda^{-1}(\\Lambda(T){\\downarrow})=T.\\]\n\nA similar situation arises with merged associated type symbols, which are also smaller than any ``real'' associated type symbol output by $\\Lambda$. Once again, you can have a canonical type parameter $T$ whose lowered type term $\\Lambda(T)$ is not canonical, but just as before, $\\Lambda^{-1}$ will map both $\\Lambda(T)$ and it's canonical form $\\Lambda(T){\\downarrow}$ back to $T$, because the only possible reduction path from $\\Lambda(T)$ to $\\Lambda(T){\\downarrow}$ introduces merged associated type symbols, which is invariant under the type lifting map.\n\\end{example}\n\\begin{example} \\label{concretecanonicalpropertymapex}\nThe next example demonstrates canonical type computation in the presence of concrete types. Table~\\ref{concretecanonicalpropertymap} shows the property map built from the generic signature:\n\\[\\gensig{\\genericsym{0}{0}}{\\genericsym{0}{0}\\colon\\proto{P},\\,\\genericsym{0}{0}.\\namesym{B}==\\namesym{Int}},\\]\ntogether with the below protocol definition:\n\\begin{Verbatim}\nprotocol P {\n associatedtype A where A == Array\n associatedtype B\n}\n\\end{Verbatim}\n\\begin{table}\\caption{Property map from Example~\\ref{concretecanonicalpropertymapex}}\\label{concretecanonicalpropertymap}\n\\begin{center}\n\\begin{tabular}{|l|l|}\n\\hline\nKeys&Values\\\\\n\\hline\n\\hline\n$\\assocsym{P}{A}$&$\\concretesym{\\namesym{Array}\\langle\\sigma_0\\rangle;\\,\\sigma_0:=\\assocsym{P}{B}}$\\\\\n$\\genericsym{0}{0}$&$\\protosym{P}$\\\\\n$\\genericsym{0}{0}.\\assocsym{P}{B}$&$\\concretesym{\\namesym{Int}}$\\\\\n\\hline\n\\end{tabular}\n\\end{center}\n\\end{table}\n\nConsider the type parameter $T:=\\genericsym{0}{0}.\\namesym{A}$. This type parameter is a canonical anchor because $\\Lambda(T)=\\genericsym{0}{0}.\\assocsym{P}{A}$ is a canonical term, however $T$ is still not a canonical type, because it is fixed to a concrete type. Therefore \\texttt{isCanonicalTypeInContext()} returns false on $T$.\n\nThe \\texttt{getConcreteType()} query on $T$ finds that the longest suffix of $\\Lambda(T)$ with a property map entry is $\\assocsym{P}{A}$, and the corresponding prefix is $\\genericsym{0}{0}$. This property map entry stores the concrete type symbol\n\\[\\concretesym{\\namesym{Array}\\langle\\sigma_0\\rangle;\\,\\sigma_0:=\\assocsym{P}{B}}.\\]\nPrepending $\\genericsym{0}{0}$ to the substitution term $\\sigma_0$ produces the adjusted concrete type symbol:\n\\[\\concretesym{\\namesym{Array}\\langle\\sigma_0\\rangle;\\,\\sigma_0:=\\genericsym{0}{0}.\\assocsym{P}{B}}.\\]\nConverting this symbol to a Swift type yields $\\namesym{Array}\\langle\\genericsym{0}{0}.\\namesym{B}\\rangle$. However, this is still not a canonical type, because the type parameter $\\genericsym{0}{0}.\\assocsym{P}{B}$ appearing in nested position is not canonical. A recursive application of \\texttt{getCanonicalTypeInContext()} on the type parameter $\\genericsym{0}{0}.\\namesym{B}$ returns $\\namesym{Int}$. Therefore, the original call to \\texttt{getCanonicalTypeInContext()} on $T$ returns\n\\[\\namesym{Array}\\langle\\namesym{Int}\\rangle.\\]\n\\end{example}\n\n\\section{More Concrete Types}\\label{moreconcretetypes}.\n\n\\bibliographystyle{IEEEtran}\n\\bibliography{RequirementMachine}\n\n\\printindex\n\n\\end{document}\t\n", "meta": {"hexsha": "a8a142b743c42de004a064fd60716da572de7ebb", "size": 266506, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "docs/RequirementMachine/RequirementMachine.tex", "max_stars_repo_name": "theMomax/swift", "max_stars_repo_head_hexsha": "199c90ef29a224fa7ec77d467cdd8530c44a9829", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-02T20:21:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-02T20:21:10.000Z", "max_issues_repo_path": "docs/RequirementMachine/RequirementMachine.tex", "max_issues_repo_name": "cabmeurer/swift", "max_issues_repo_head_hexsha": "e3b715bc2a39baad414078fe7d84db74f092e06b", "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/RequirementMachine/RequirementMachine.tex", "max_forks_repo_name": "cabmeurer/swift", "max_forks_repo_head_hexsha": "e3b715bc2a39baad414078fe7d84db74f092e06b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 69.5293503783, "max_line_length": 763, "alphanum_fraction": 0.7523733049, "num_tokens": 76243, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.33458945452352534, "lm_q1q2_score": 0.1699084946697535}} {"text": " \n\\chapter{Verification Dataset}\n\\label{chapter:vds}\n\n\\section{Overview}\n\n\\begin{table}\n\\caption{ \\smr\\ VDS content for the various frequency modes of \\smr\\..}\n\\label{table:comp}\n\\scalebox{0.9}{%\n\\footnotesize\n\\begin{tabular}{|l|l|l|l|l|}\n\\hline\n\\textbf{\\smr} & \\textbf{\\smr} & \\textbf{Instrument} & \\textbf{Species} & \\textbf{Number of}\\\\\n\\textbf{Frequency mode} & \\textbf{Frequency range [GHz]} & & & \\textbf{measurements}\\\\ \n\\hline\n 01 & 501.180--501.580, & SMILES & \\chem{O_3}, \\chem{ClO} & 2398, 1384 \\\\\n & 501.980--502.380 & MLS & \\chem{O_3}, \\chem{ClO}, \\chem{N_{2}O} & 14726 \\\\\n & & MIPAS-KIT & \\chem{O_3}, \\chem{N_{2}O} & 7228 \\\\\n & & MIPAS-ESA & \\chem{O_3}, \\chem{N_{2}O} & 6850 \\\\\n & & SAGEIII & \\chem{O_3} & 3115 \\\\\n & & OSIRIS & \\chem{O_3} & 7587 \\\\\n & & SMR & \\chem{O_3}, \\chem{ClO}, \\chem{N_{2}O} & 10450, 9824, 10371 \\\\\n\n\\hline\n 02 & 544.102--544.902 & SMILES & \\chem{O_3}, \\chem{HNO_3} & 2367, 1353 \\\\\n & & MLS & \\chem{O_3}, \\chem{HNO_3}, T & 14275 \\\\\n & & MIPAS-KIT & \\chem{O_3}, \\chem{HNO_3} & 7176 \\\\\n & & MIPAS-ESA & \\chem{O_3}, \\chem{HNO_3} & 6734 \\\\\n & & SAGEIII & \\chem{O_3} & 3063 \\\\\n & & OSIRIS & \\chem{O_3} & 7442 \\\\\n & & SMR & \\chem{O_3}, \\chem{HNO_3}, T & 11168, 11137, 11177 \\\\\n\n\\hline\n 08 & 488.950--489.350, & SMILES & \\chem{O_3} & 618 \\\\\n & 488.350--488.750 & MLS & \\chem{O_3}, \\chem{H_{2}O} & 14276 \\\\\n & & MIPAS-KIT & \\chem{O_3}, \\chem{H_{2}O} & 6249 \\\\\n & & MIPAS-ESA & \\chem{O_3}, \\chem{H_{2}O} & 5940 \\\\\n & & SAGEIII & \\chem{O_3}, \\chem{H_{2}O} & 284 \\\\\n & & OSIRIS & \\chem{O_3} & 2749 \\\\\n & & SMR & \\chem{O_3} & 8068 \\\\\n\n\\hline\n 13 & 556.598--557.398 & SMILES & \\chem{O_3} & 364 \\\\\n & & MLS & \\chem{O_3}, \\chem{H_{2}O}, T & 12516 \\\\\n & & MIPAS-KIT & \\chem{O_3}, \\chem{H_{2}O} & 5001 \\\\\n & & MIPAS-ESA & \\chem{O_3}, \\chem{H_{2}O} & 4845 \\\\\n & & MIPAS & \\chem{O_3}, \\chem{H_{2}O} & 5001 \\\\\n & & SAGEIII & \\chem{O_3}, \\chem{H_{2}O} & 170 \\\\\n & & OSIRIS & \\chem{O_3} & 1870 \\\\\n & & SMR & \\chem{O_3}, \\chem{H_{2}O}, T & 2644 \\\\\n \n\\hline\n 14 & 576.062--576.862 & SMILES & \\chem{O_3} & 409 \\\\\n & & MLS & \\chem{O_3}, \\chem{CO}, T & 12758 \\\\\n & & MIPAS-KIT & \\chem{O_3}, \\chem{CO} & 5005 \\\\\n & & MIPAS-ESA & \\chem{O_3} & 1212 \\\\\n & & SAGEIII & \\chem{O_3} & 170 \\\\\n & & OSIRIS & \\chem{O_3} & 1913 \\\\\n & & SMR & \\chem{O_3}, \\chem{CO}, T & 6 \\\\\n\n\\hline\n 17 & 489.950--490.750 & SMILES & \\chem{O_3} & 527 \\\\\n & & MLS & \\chem{O_3}, \\chem{H_{2}O} & 14191 \\\\\n & & MIPAS-KIT & \\chem{O_3}, \\chem{H_{2}O} & 6126 \\\\\n & & MIPAS-ESA & \\chem{O_3}, \\chem{H_{2}O} & 5817 \\\\\n & & SAGEIII & \\chem{O_3}, \\chem{H_{2}O} & 263 \\\\\n & & OSIRIS & \\chem{O_3} & 2862 \\\\\n & & SMR & \\chem{O_3}, \\chem{H_{2}O} & 7179 \\\\\n\n\\hline\n 19 & 556.550--557.350 & SMILES & \\chem{O_3} & 604 \\\\\n & & MLS & \\chem{O_3}, \\chem{H_{2}O}, T & 13360 \\\\\n & & MIPAS-KIT & \\chem{O_3}, \\chem{H_{2}O} & 6127 \\\\\n & & MIPAS-ESA & \\chem{O_3}, \\chem{H_{2}O} & 5822 \\\\\n & & SAGEIII & \\chem{O_3}, \\chem{H_{2}O} & 444 \\\\\n & & OSIRIS & \\chem{O_3} & 2779 \\\\\n & & SMR & \\chem{O_3}, \\chem{H_{2}O}, T & 8299 \\\\\n\n\\hline\n 21 & 551.152--551.552, & SMILES & \\chem{O_3} & 583 \\\\\n & 551.752--552.152 & MLS & \\chem{O_3}, \\chem{H_{2}O}, T & 12707 \\\\\n & & MIPAS-KIT & \\chem{O_3}, \\chem{H_{2}O}, \\chem{NO} & 4819 \\\\\n & & MIPAS-ESA & \\chem{O_3}, \\chem{H_{2}O} & 4673 \\\\\n & & SAGEIII & \\chem{O_3}, \\chem{H_{2}O} & 80 \\\\\n & & OSIRIS & \\chem{O_3} & 2508 \\\\\n & & SMR & \\chem{O_3}, \\chem{H_{2}O}, \\chem{NO}, T & 8201 \\\\\n\\hline\n 22 & 576.254 - 576.654, & MLS & \\chem{CO} & 7691 \\\\\n & 577.069 - 577.469 & MIPAS-KIT & \\chem{CO} & 2401 \\\\\n\\hline\n 24 & 576.062 - 576.862 & MLS & \\chem{CO} & 979 \\\\\n & & MIPAS-KIT & \\chem{CO} & 340 \\\\\n\\hline\n\\end{tabular}}\n\\end{table}\n\n\nThe verfication dataset (VDS) consists of a represenative subset of \nthe \\smr\\ complete dataset, and correlative datasets.\nIn short, the VDS is a dataset of \\smr\\ measurements \nand collocated measurements from a number of correlative\nlimb-sounding instruments, i.e. Aura/MLS, ENVISAT/MIPAS,\nISS/JEM/SMILES, Meteor3M/SAGEIII, and Odin/OSIRIS.\nTable~\\ref{table:comp} gives an overview of the correlative\ndatasets included in the VDS, and these datasets\nare described in more detail in Sect.~\\ref{sec:corrmeas}.\nSect.~\\ref{sec:vdsselection} describes the collocation criteria\napplied and how the VDS was selected. \n\n\\section{Correlative limb measurements}\n\\label{sec:corrmeas}\n\\subsection{Aura/MLS}\n\n%http://www.atmos-chem-phys.net/9/2387/2009/acp-9-2387-2009.pdf\n\\def \\ESADataURL{https://earth.esa.int/web/sppa/mission-performance/esa-missions/envisat/mipas/products-and-algorithms/products-information}\n\n\\begin{table}\n\\caption{ Characteristics of Aura/MLS, ENVISAT/MIPAS, ISS/JEM/SMILES, Meteor3M/SAGEIII, and Odin/OSIRIS Level2 data products included in the VDS.}\n\\label{table:complevel2}\n\\scalebox{0.8}{%\n\\begin{tabular}{|l|l|l|l|l|l|}\n \\hline\n \\multicolumn{6}{|c|}{\\textbf{Aura/MLS}}\\\\\n %\\multicolumn{6}{|c|}{\\textbf{}}\\\\\n \\hline \n \\textbf{Product} & \\textbf{Vertical} & \\textbf{Vertical} & \\textbf{Precision} & \\textbf{Version} & \\textbf{Reference} \\\\\n & \\textbf{coverage} & \\textbf{resolution} & & & \\\\\n \\hline\n \\chem{O_{3}} & 261--0.02\\,hPa & 3.5--5.5\\,km & 0.03--1.2\\,ppmv & v04-2x & \\citep{livesey:MLS} \\\\\n \\hline\n \\chem{ClO} & 147--1.0\\,hPa & 3--4.5\\,km & 0.1--0.3\\,ppbv & v04-2x & \\citep{livesey:MLS} \\\\\n \\hline\n \\chem{N_{2}O} & 68--0.46\\,hPa & 5.4--11\\,km & \\(\\sim\\)15\\,ppbv & v04-2x & \\citep{livesey:MLS} \\\\\n \\hline\n \\chem{HNO_{3}} & 215--1.5\\,hPa & 4--4.5\\,km & 1--0.5\\,ppbv & v04-2x & \\citep{livesey:MLS} \\\\\n \\hline\n \\chem{H_{2}O} & 316--0.002\\,hPa & 1.3--10\\,km & 4--152\\,\\(\\%\\) & v04-2x & \\citep{livesey:MLS} \\\\\n \\hline\n \\chem{CO} & 215--0.0046\\,hPa & 3.8--6.2\\,km & 9\\,ppbv--11\\,ppmv & v04-2x & \\citep{livesey:MLS} \\\\\n \\hline\n \\chem{T} & 261--0.001 \\,hPa & 4.2--13\\,km & 0.7--3.6\\,K & v04-2x & \\citep{livesey:MLS} \\\\\n \\hline\n \\multicolumn{6}{|c|}{\\textbf{ENVISAT/MIPAS}}\\\\\n %\\multicolumn{6}{|c|}{\\textbf{}}\\\\\n \\hline\n \\textbf{Product} & \\textbf{Vertical} & \\textbf{Vertical} & \\textbf{Precision} & \\textbf{Version} & \\textbf{Reference} \\\\\n & \\textbf{coverage} & \\textbf{resolution} & & & \\\\\n \\hline\n \\chem{O_{3}} & \\(\\sim\\)10--60\\,km & 3.5 -- 8\\,km & 0.1--0.2\\,ppmv & KIT: V5H-O3-21 & \\citep{steck:biasd:07}\\\\\n & & & & 2002-07 -- 2004-03 & \\\\\n & \\(\\sim\\)10--70\\,km & 2 -- 6\\,km & 0.03--0.09\\,ppmv & KIT: V5R-O3-22(4/5) & \\citep{laeng:valid:14}\\\\\n & & & & 2005-01 -- 2012-04 & \\\\\n & & & & ESA: ML2PP version 7.03 & \\href{\\ESADataURL}{ESA documentation}\\\\\n \\hline\n \\chem{N_{2}O} & \\(\\sim\\)15--60\\,km & 3--6\\,km & 10--20\\,\\(\\%\\) & KIT: V5H-N2O-21 & \\citep{plieninger:metha:15}\\\\\n & & & & 2002-07 -- 2004-03 & \\\\\n & \\(\\sim\\)15--60\\,km & 2.5--6\\,km & 10--20\\,\\(\\%\\) & KIT: V5R-N2O-22(4/5) & \\citep{plieninger:metha:15}\\\\\n & & & & 2005-01 -- 2012-04 & \\\\\n & & & & ESA: ML2PP version 7.03 & \\href{\\ESADataURL}{ESA documentation}\\\\\n \\hline\n \\chem{HNO_{3}} & \\(\\sim\\)20--50\\,km & 3--8\\,km & 2--6\\,\\(\\%\\) & KIT: V5H-HNO3-22 & \\citep{wang:valid:07}\\\\\n & & & & 2002-07 -- 2004-03 & \\\\\n & & & & KIT: V5R-HNO3-22(4/5) & \\\\\n & & & & 2005-01 -- 2012-04 & \\\\\n & & & & ESA: ML2PP version 7.03 & \\href{\\ESADataURL}{ESA documentation}\\\\\n \\hline\n \\chem{H_{2}O} & \\(\\sim\\)15--50\\,km & 3.5--4.5\\,km & 5--10\\,\\(\\%\\) & KIT: V5H-H2O-20 & \\citep{milz:valid:09}\\\\\n & & & & 2002-07 -- 2004-03 & \\\\\n & \\(\\sim\\)20--50\\,km & 2.3--6.9\\,km & 0.2 -- 0.9 ppmv & KIT: V5R-H2O-22(0/1) & \\citep{stiller:valid:2012}\\\\\n & & & & 2005-01 -- 2012-04 & \\\\\n & & & & ESA: ML2PP version 7.03 & \\href{\\ESADataURL}{ESA documentation}\\\\\n \\hline\n \\chem{CO} & \\(\\sim\\)10--70\\,km & 6--12\\,km & 10--70\\,\\(\\%\\) & KIT: V5H-CO-20 & \\citep{funke:analy:07}\\\\\n & & & & 2002-07 -- 2004-03 & \\\\\n & & & & KIT: V5R-H2O-22(0/1) & \\\\\n & & & & 2005-01 -- 2012-04 & \\\\\n \\hline\n \\chem{NO} & \\(\\sim\\)20--60\\,km\\ & 3.5--12\\,km & 0.2--0.3\\,ppbv & KIT: V5H-NO-20 & \\citep{funke:retri:05}\\\\\n & & & & 2002-07 -- 2004-03 & \\\\\n & & & & KIT: V5R-NO-22(0/1) & \\\\\n & & & & 2005-01 -- 2012-04 & \\\\\n \\hline\n \\multicolumn{6}{|c|}{\\textbf{ISS/JEM/SMILES}}\\\\\n %\\multicolumn{6}{|c|}{\\textbf{}}\\\\\n \\hline\n \\textbf{Product} & \\textbf{Vertical} & \\textbf{Vertical} & \\textbf{Precision} & \\textbf{Version} & \\textbf{Reference} \\\\\n & \\textbf{coverage} & \\textbf{resolution} & & & \\\\\n \\hline\n \\chem{O_{3}} & 16--73\\,km & 2.3--3\\,km & 2--5\\,\\(\\%\\) & JAXA v2.4 (008-11-0502) & \\citep{imai:valid:13} \\\\\n \\hline\n \\chem{ClO} & 20--60\\,km & 3.5--10\\,km & 20--50\\,\\(\\%\\) & JAXA v2.4 (008-11-0502) & \\citep{jaxa:2013} \\\\\n \\hline\n \\chem{HNO_{3}} & 18--40\\,km & \\(\\sim\\)10\\,km & 20--50\\,\\(\\%\\) & JAXA v2.4 (008-11-0502) & \\citep{jaxa:2013} \\\\\n \\hline\n \\multicolumn{6}{|c|}{\\textbf{Meteor3M/SAGEIII}}\\\\\n %\\multicolumn{6}{|c|}{\\textbf{}}\\\\\n \\hline\n \\textbf{Product} & \\textbf{Vertical} & \\textbf{Vertical} & \\textbf{Precision} & \\textbf{Version} & \\textbf{Reference} \\\\\n & \\textbf{coverage} & \\textbf{resolution} & & & \\\\\n \\hline\n \\chem{O_{3}} & 6--85\\,km & \\(\\sim\\)1\\,km & 10\\,\\(\\%\\) & NASA v04 & \\citep{SAGEIII_DPUG} \\\\\n \\hline\n \\chem{H_{2}O} & 0--50\\,km & \\(\\sim\\)1\\,km & 5--15\\,\\(\\%\\) & NASA v04 & \\citep{SAGEIII_DPUG} \\\\\n \\hline\n \\multicolumn{6}{|c|}{\\textbf{Odin/OSIRIS}}\\\\\n %\\multicolumn{6}{|c|}{\\textbf{}}\\\\\n \\hline\n \\textbf{Product} & \\textbf{Vertical} & \\textbf{Vertical} & \\textbf{Precision} & \\textbf{Version} & \\textbf{Reference} \\\\\n & \\textbf{coverage} & \\textbf{resolution} & & & \\\\\n \\hline\n \\chem{O_{3}} & 10--60\\,km & \\(\\sim\\)2-3\\,km & 3--4\\,\\(\\%\\) & SaskMART v5.07 & \\citep{adams:assess:14} \\\\\n \\hline \n\\end{tabular}}\n\\end{table}\n\n\n\nThe Aura satellite was launched on 2004-07-15 into a \nsun-synchronous orbit at 705\\,km altitude, with an ascending\nequator crossing local time of 13:45. Its\norbit is near-polar with a 98\\degree inclination, \nand the daily Microwave Limb Sounder (MLS) measurements cover \nthe latitudinal range from about 82\\degree\\,S to 82\\degree\\,N. \nMLS measures temperature and trace gas profiles \nusing thermal emission data from the\nupper troposphere to the mesosphere. MLS performs each\nlimb scan and related calibration in 25\\,s, and \nobtains \\(\\sim\\) 3500 vertical profiles a day \n\\citep{waters:eos:06}. The MLS data\nprocessing algorithms are based on the optimal estimation\nmethod (OEM), as explained by \\citet{livesey:MLS}. MLS uses\nspectral bands centered near 118, 190, 240, 640\\,GHz,\nand 2.3\\,THz. \n\nThe Aura/MLS Level2 products, and characteristics, included in the\nVDS are found in Table~\\ref{table:complevel2}.\n\n\n\\subsection{ENVISAT/MIPAS}\n\nThe Michelson Interferometer for Passive Atmospheric\nSounding (MIPAS) is a mid-infrared emission spectrometer\nmounted on the European ENVIronmantal SATellite (ENVISAT),\nwhich was launched in 2002-03-01 \\citep{fischer2008},\nand was in operation until 2012-04-08. \nENVISAT has a sun-synchronous orbit at an altitude of 800\\,km\nand with a 98.55\\degree\\ inclination and descending equator \ncrossing local time of 10:00.\n\nThe failure of a MIPAS mirror slide in 2004 led to the \ndivision of the 10 years of MIPAS\ndata into two operational periods: 2002--2004 when the \ninstrument measured with high spectral resolution \nand 2005--2012 when the instrument measured with lower \nspectral but better vertical resolution.\n\nMIPAS observed five mid-infrared spectral bands within the\nfrequency range of 685 to 2410\\,cm\\(^{-1}\\) (14.6 to 4.15\\,\\(\\mu\\)m),\nwith a resolution of 0.0625\\,cm\\(^{-1}\\).\nUntil 2004-03-26 MIPAS scanned 17 tangent altitudes from \n6 to 68\\,km with 3--8\\,km resolution.\nFrom January 2005 MIPAS started operating in a new mode\nat a reduced spectral resolution but at a finer altitude\ngrid. The latitudinal coverage was from 87\\degree\\,S to 89\\degree\\,N.\nIn the latter mode, MIPAS had about 95 scans per orbit, and about\n1360 vertical profiles were recorded in a day.\n\nLevel2 data from MIPAS, generated by ESA\n(MIPAS Level 2 ML2PP version 7.03)\nand by the Institut f\\\"ur Meteorologie und Klimatforschung\n(IMK) at Karlsruhe Institute of Technology (KIT) (V5), are\nincluded in the VDS.\nIncluded Species from the ESA MIPAS dataset are\n\\chem{O_{3}}, \\chem{H_{2}O}, \\chem{HNO_{3}}, and \\chem{N_{2}O}.\nThese species plus \\chem{NO} and \\chem{CO} are also included from the KIT\ndataset. The ENVISAT/MIPAS Level2 products and characteristics included in the\nVDS are described in more details in Table~\\ref{table:complevel2}.\n\n\n\\subsection{ISS/JEM/SMILES}\n\nThe Superconducting Submillimeter-Wave Limb-Emission Sounder (SMILES),\nattached to the Exposed Facility of the Japanese Experiment Module (JEM), \non the International Space Station (ISS), is a joint project of the\nNational Institute of Information and Communications Technology (NICT) and\nthe Japan Aerospace Exploration Agency (JAXA).\nThe ISS has a non-sun-synchronous circular orbit at\naltitudes of 340\\,-\\,360\\,km with an inclination angle of 51.6\\degree\nto the equator. \n\nSMILES observed a number of trace gases, e.g.: \\chem{O_{3}}, \\chem{H^{35}Cl}, \n\\chem{H^{37}Cl}, \\chem{ClO}, \\chem{HOCl}, \\chem{HO_{2}}, \\chem{BrO}, and \\chem{HNO_{3}}, \nfrom the upper troposphere up to the lower thermosphere, \nwith a nominal latitudinal coverage \nfrom 38\\degree\\,S to 65\\degree\\,N, between 2009-10-12 and 2010-04-21.\nTrace gas profiles are derived from observed thermal emission in two frequency\nbands around 625\\,GHz and one around 650\\,GHz;\n624.32--625.52\\,GHz (Band-A), 625.12--626.32\\,GHz (Band-B),\nand 649.12--650.32\\,GHz (Band-C), with a frequency resolution\nand channel separation of about 1\\,MHz and 0.8\\,MHz, \nrespectively. \nDuring each measurement, two out of the three SMILES frequency\nbands were observed simultaneously, by two acousto-optical spectrometers,\nand with a receiver noise temperature of 310--350\\,K.\n\nSMILES performed 1630 scans per day, where the limb was scanned\nfrom about -20\\,km to 120\\,km (geometric altitude), \nwith a sampling interval of about 2\\,km, and with an angle of \nabout 45\\degree\\ from the orbital plane. The size of the antenna beam, \nat the tangent point, was about 3 and 6\\,km in the vertical and \nhorizontal direction, respectively. \n\nAn interesting feature of SMILES observation is related to the fact\nthat ISS has a non-sunsynchronous orbit, which gives that SMILES \nobservations cover different local times and thereby provides insight\nof the diurnal variation of atmospheric short-lived species\n(e.g \\chem{ClO}, \\chem{BrO}, \\chem{HO_2}, and \\chem{HOCl}). \nA two month period is required to accumulate measurements covering \n24\\,h in local time for a given \"position\". However, such a \ndataset can also contain variation due to dynamical, seasonal, and \nlatitudinal effects.\nA second characteristic of SMILES observation is that \nmeasured spectra and retrieved profiles have high precision due \nto its 4\\,K mechanically cooled superconducting receiver system.\n\nThe SMILES Level2 products and characteristics included in the\nVDS are found in Table~\\ref{table:complevel2}.\n\n\n\\subsection{Meteor3M/SAGE III}\n\nSAGE III on Meteor-3M (SAGEIII) was a third generation, satellite-borne\ninstrument and an element in NASA's Earth Observing System (EOS) \\citep{SAGEIII_DPUG}. \nThe instrument was launched on the Russian Meteor-3M spacecraft on 2001-12-10\ninto into a Sun-synchronous orbit at an altitude of 1020 km and with an\napproximate 9:00 a.m. equatorial crossing time. The instrument was active from\n2002-02-27 to 2005-11-12.\n%\\footnote{all text in this section adapted from\n%\\cite{SAGEIII_DPUG}}\n\nThe SAGEIII instrument measures the attenuation of solar radiation resulting\nfrom the scattering and absorption by atmospheric constituents in the Earth's\natmosphere as the spacecraft observes a sunrise or sunset event. Due to the\norbital parameters, solar occultation measurement opportunities are limited to\nmostly high latitudes in the Northern Hemisphere (between 50\\degree~and\n80\\degree~N) and mid-latitudes in the Southern Hemisphere (between\n30\\degree~and 50\\degree~S). Level2 products from these measurements include\nprofiles of ozone~(\\chem{O_3}), water vapour~(\\chem{H_2O}) and nitrogen\ndioxide~(\\chem{NO_2}). Of these \\chem{O_3} and \\chem{H_2O} have been included\nin the VDS. The ozone profiles are are reported as reliable within 10\\% for\nthe altitude range 6--85\\,km, whereas the water vapour profiles are reported\nreliable to have an uncertainty of less than 5\\% for altitudes of 0--33\\,km and\nin the interval 5--15\\% for altitudes 33--50\\,km. The SAGEIII Level2\nproducts and characteristics included in the VDS are found in\nTable~\\ref{table:complevel2}.\n\nSimilar measurements were made during the lunar moonrise and moonset. These\nmeasurements were made only during the second and third quarter phases of\nthe Moon and when the atmosphere along the line-of-sight was not directly\nilluminated by the Sun. Level2 products from these measurements include\nprofiles of ozone~(\\chem{O_3}), nitrogen dioxide~(\\chem{NO_2}), nitrogen\ntrioxide~(\\chem{NO_3}) and chlorine dioxide~(\\chem{OClO}). Due to poor data\ncoverage, none of these products have been included in the VDS, but are\nlisted here for completeness.\n\n\\subsection{Odin/OSIRIS}\n\nOdin has two optically co-aligned instruments: the SMR \nand the Optical Spectrograph and InfraRed Imager System (OSIRIS)\n\\citep{llewellyn:osiris:04}. OSIRIS\nmeasures limb-scattered sunlight within the wavelength range of 280\\,-\\,\n800\\,nm with a spectral resolution of approximately 1\\,nm,\nOSIRIS is capable of measuring vertical profiles of stratospheric \n\\chem{O_{3}}, \\chem{NO_{2}}, and aerosols. \nOzone measurements are only taken in the\nsummer hemisphere, with coverage in both hemispheres in\nthe spring and autumn.\nNominally OSIRIS generates approximately 30\n\\chem{O_3} profiles per orbit over the sunlit hemisphere.\nCharacteristics of OSIRIS Level2 \\chem{O_{3}} product\nare found in Table~\\ref{table:complevel2}.\n\n\n\n\\section{Verification Dataset: collocation criteria and data selection}\n\\label{sec:vdsselection}\n\n\\begin{figure}[t]\n\\centering\n\\includegraphics[width=17cm]{test_collocation_fm1.png}\n\\caption{Positions of collocations for the various limb instruments\nand \\smr\\ frequency mode 1 scans, included in the VDS. The upper two panels show\nthe latitude of the collocations as function of time. The bottom panels\nshow the geograpical coverage of the collocations between \\smr\\\nand the other instruments. Note that the figure does not cover the \nmost recent year, but the VDS contains MLS and OSIRIS data until 2019.}\n\\label{fig:vdsfm1}\n\\end{figure}\n\n\nThe VDS should ideally include \\smr\\ measurements and correlative collocated \ndata from the complete mission and for all geopraphical regions.\nIn this section we describe how the VDS was constructed\nin order to fulfill this criteria.\n\nTwo measurements are considered to be collocated if they\nare close in time and space. The applied collocations\ncriteria are adjusted for the various sensors, in order\nto result in a useful comparison dataset, as described below:\n\n\\smr\\ and SMILES measurements are considered to be collocated if the \ndifferences in distance and observation time between the two profiles are\nless than 300\\,km and 1\\,h, respectively.\nAll measurements that fulfill this criteria are included\nin the VDS. This subset of the VDS\ncovers 60\\degree\\,N--40\\degree\\,S for the SMILES\nactive observation period, as can be seen in Fig.~\\ref{fig:vdsfm1}.\n\n\\smr\\ and SAGEIII measurements are considered to be collocated if the \ndifference in distance and observation time between the two profiles are\nless than 300\\,km and and 3\\,h, respectively.\nThis subset of the VDS covers approximately 80\\degree\\,N--50\\degree\\,N and\n40\\degree\\,S--60\\degree\\,S for the SAGEIII active observation period, as can\nbe seen in Fig.~\\ref{fig:vdsfm1}\n\nA problem with a ``strict'' time difference criteria\nbetween \\smr\\ and both ENVISAT/MIPAS and Aura/MLS\nis that collocations are only found for high latitudes\n (around 80\\degree\\,N and around 80\\degree\\,S),\ndue to the fact each of these platform follows a sun-synchronous orbit\nwith quite different ascending equator crossing local times \n(18:00 hour for \\smr\\, 10:00 hour for ENVISAT/MIPAS,\n 13:45 hour for Aura/MLS). \nThus, for low latitudes the time difference criteria\nis relaxed to 6\\,hour for ENVISAT/MIPAS and Aura/MLS.\nThis gives effectively that collocated ENVISAT/MIPAS and Aura/MLS \nmeasurements can be found for almost all \\smr\\ measurements, and a strategy\nto reduce the size of the VDS must be applied.\n\nThe set of collocated measurements for ENVISAT/MIPAS and Aura/MLS is reduced\nin size in the following way:\nFor each \\smr\\ observation mode and month, five collocated scans each\nfor ENVISAT/MIPAS and Aura/MLS\nare selected, within each 10\\degree\\ latitude bin\n(85\\degree\\,N--75\\degree\\,N, 75\\degree\\,N--65\\degree\\,N, \\ldots, 75\\degree\\,S--85\\degree\\,S),\nto be included in the VDS. For the two outer latitude bins the\ntime difference criteria is 1\\,h, while for the other bins it is set to 6\\,h.\nFigure~\\ref{fig:vdsfm1} shows a graphical view of the position in\ntime and space for the measurements included in the VDS for\nfrequency mode 1 of \\smr.\n\nThe VDS contains both KIT and ESA ENVISAT/MIPAS data. The KIT dataset was first\nadded to the VDS as described above, and available matching data from the ESA dataset was\nthen added for all scans where KIT data were already added. This explains\nwhy the VDS contains somewhat more KIT than ESA data. \n\nThe \\smr\\ and Odin/OSIRIS instruments are optically co-alignend and thus\nthe measurements can always be seen as highly collocated.\nThe selection of which OSIRIS measurements to include in the\nVDS is based on which measurements that are included \nfor MIPAS, MLS, SAGEIII, and SMILES, in order to not\nconstruct a too large VDS. That is,\nOSIRIS measurements are included in the VDS for all selected\ncollocations between \\smr\\ and the other sensors, given\nthat OSIRIS measurements are available. \n\nData from the previous \\smr\\ processing version are included in the VDS.\nThis data were added for all scans already included in the VDS,\ngiven that previous \\smr\\ data were available. \n\nThe total number of limb measurement collocations included in the VDS, for the various \n\\smr\\ frequency modes, is displayed in Table~\\ref{table:comp}. This gives that a few \npercent of the total \\smr\\ dataset is included in the VDS. Included measurements cover \napproximately all geographical positions and the complete observation period of \\smr.\n\n\n\n\n \n\n\n", "meta": {"hexsha": "12817a1841cad197dec68a37083b0dc5847a5edb", "size": 31103, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "VDS/dataset.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": "VDS/dataset.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": "VDS/dataset.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": 64.3954451346, "max_line_length": 170, "alphanum_fraction": 0.4934572228, "num_tokens": 8785, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792043, "lm_q2_score": 0.3345894478883556, "lm_q1q2_score": 0.16990849130033553}} {"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% MINUIT User Guide -- LaTeX Source %\n% %\n% Chapter 5 %\n% %\n% The following external EPS files are referenced: %\n% %\n% Editor: Michel Goossens / CN-AS %\n% Last Mod.: 17 Mar. 1992 10.20 mg %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n \n\\chapter{How to get the right answer from Minuit.}\n\nThe goal of Minuit --- to be able to minimize and analyze parameter\nerrors for all possible user functions with any number of variable\nparameters --- is of course impossible to realise, even in principle,\nin a finite amount of time. In practice, some assumptions must be made\nabout the behaviour of the function in order to avoid evaluating it\nat all possible points.\nIn this chapter we give some hints on how the user can help Minuit\nto make the right assumptions.\n\n\\section{Which Minimizer to Use.}\n\nOne of the historically interesting advantages of Minuit is that it\nwas probably the first minimization program to offer the user a choice\nof several minimization algorithms.\nThis could be taken as a reflection of the fact that none of the\nalgorithms known at that time were good enough to be universal, so\nusers were encouraged to find the one that worked best for them.\nSince then, algorithms have improved considerably, but Minuit still\noffers several, mostly so that old users will not feel cheated, but also to\nhelp the occasional user who does manage to defeat the best algorithms.\nMinuit currently offers five commands which can be used to find a\nsmaller function value, in addition to a few others,\nlike \\Cind[MINOs]{MINOS} and \\Cind[IMProve]{IMPROVE},\nwhich will retain a smaller function value if they stumble on one\nunexpectedly (or, in the case of \\Cind[IMProve]{IMPROVE}, hopefully).\nThe commands which can be used to minimize are:\n\n\\subsection{MIGRAD}\n\nThis is the best minimizer for nearly all functions. It is a\nvariable-metric method with inexact line search, a stable\nmetric updating scheme, and checks for positive-definiteness.\nIt will run faster if you \\Cind[SET STRategy]{SET STRATEGY 0}\nand will be more reliable if you \\Cind[SET STRategy]{SET STRATEGY 2}\n(although the latter option may not help much).\nIts main weakness is that it depends heavily on knowledge of the\nfirst derivatives, and fails miserably if they are very inaccurate.\nIf first derivatives are a problem, they can be\ncalculated analytically inside \\Rind{FCN} (see elsewhere in this writeup) or\nif this is not feasible, the user can try to improve the accuracy of\nMinuit's numerical approximation by adjusting values using the\n\\Cind[SET EPSmachine]{SET EPS} and/or \\Cind[SET STRategy]{SET STRATEGY} commands\n(see Floating Point Precision and \\Cind[SET STRategy]{SET STRATEGY}).\n\n\\subsection{MINIMIZE}\n\nThis is equivalent to \\Cind[MIGrad]{MIGRAD}, \nexcept that if \\Cind[MIGrad]{MIGRAD} fails,\nit reverts to \\Cind[SIMplex]{SIMPLEX} and then calls \n\\Cind[MIGrad]{MIGRAD} again.\nThis is what the old \\Cind[MIGrad]{MIGRAD} command used to do, \nbut it was removed from\nthe \\Cind[MIGrad]{MIGRAD} command so that users would have a choice, \nand because it is\nseldom of any use to call \\Cind[SIMplex]{SIMPLEX} when \n\\Cind[MIGrad]{MIGRAD} has failed (there are of course exceptions).\n\n\\subsection{SCAN}\n\nThis is not intended to minimize, and just scans the function, one\nparameter at a time.\nIt does however retain the best value after each scan,\nso it does some sort of highly primitive minimization.\n\n\\subsection{SEEK}\n\nWe have retained this Monte Carlo search mainly for sentimental\nreasons, even though the limited experience with it is\nless than spectacular.\n\\index{metropilis algorithm}\n\\index{Monte Carlo}\nThe method now incorporates a Metropolis algorithm which always\nmoves the search region to be centred at a new minimum,\nand has probability \n$ e ^{(-F/F_{\\mathrm{min}})}$\nof moving the search region to a higher point with function value $F$.\nThis gives it the theoretical ability to jump\nthrough function barriers like a multidimensional\nquantum mechanical tunneler in search of isolated minima, but it is\nwidely believed by at least half of the authors of Minuit that this\nis unlikely to work in practice (counterexamples are welcome)\nsince it seems to depend critically on choosing\nthe right average step size for the random jumps,\nand if you knew that, you wouldn't need Minuit.\n\n\\Subsection{4cm}{SIMPLEX}\n\n\\index{minimization!multidimensional}\n\\index{multidimensional minimization}\nThis genuine multidimensional minimization routine is usually much\nslower than \\Cind[MIGrad]{MIGRAD}, but it does not use first derivatives,\nso it should not be so sensitive to the precision of the \\Rind{FCN}\ncalculations, and is even rather robust with respect to\ngross fluctuations in the function value.\nHowever, it gives no reliable information about parameter errors,\nno information whatsoever about parameter correlations,\nand worst of all cannot be expected to converge accurately\nto the minimum in a finite time.\nIts estimate of \\Lit{EDM} is largely fantasy, so it would not even\nknow if it did converge.\n\n\\Section{4cm}{Floating point Precision}\n\nMinuit figures out at execution time the precision with which it was\ncompiled, and assumes that \\Rind{FCN} provides about the same precision.\nThat means not just the length of the numbers used and returned\nby \\Rind{FCN}, but the actual mathematical accuracy of the calculations.\nThe section on Floating point Precision in Chapter One describes\nwhat to do if this is not the case.\n\n\\section{Parameter Limits}\n\nPutting limits (absolute bounds) on the allowed values for\na given parameter, causes Minuit to make a non-linear\ntransformation of its own internal parameter values to obtain the\n(external) parameter values passed to \\Rind{FCN}.\nTo understand the adverse effects of limits, see ``The Transformation\nfor Parameters with Limits'' in Chapter 1.\nBasically, the use of limits should be avoided unless needed to\nkeep the parameter inside a desired range.\n \nIf parameter limits are needed, in spite of the effects described\nin Chapter One, then the user should be aware of the following\ntechniques to alleviate problems caused by limits:\n\n\\subsection{Getting the Right Minimum with Limits.}\n\nIf \\Cind[MIGrad]{MIGRAD} converges normally to a point where no parameter is\nnear one of its limits, then the existence of limits has\nprobably not prevented Minuit from finding the right minimum.\nOn the other hand, if one or more parameters is near its limit\nat the minimum, this may be because the true minimum is indeed\nat a limit, or it may be because the minimizer has become \n``blocked'' at a limit. \nThis may normally happen only if the parameter\nis so close to a limit (internal value at an odd multiple\nof $\\pm \\frac{\\Tstm \\pi}{\\Tstm 2}$ that Minuit prints a warning to this effect\nwhen it prints the parameter values.\n\nThe minimizer can become blocked at a limit, because at a limit\nthe derivative seen by the minimizer \n$\\partial F / \\partial P_{\\mathrm{int}}$\nis zero no matter what the real derivative\n$\\partial F / \\partial P_{\\mathrm{ext}}$ is.\n\n$$\n\\frac{\\partial F}{\\partial P_{\\mathrm{int}}} =\n\\frac{\\partial F}{\\partial P_{\\mathrm{ext}}}\n\\frac{\\partial P_{\\mathrm{ext}}}{\\partial P_{\\mathrm{int}}} =\n\\frac{\\partial F}{\\partial P_{\\mathrm{ext}}} = 0\n$$\n\nFor a stepping method (like \\Cind[SIMplex]{SIMPLEX}) \nthis seldom poses any problem,\nbut a method based on derivatives (\\Cind[MIGrad]{MIGRAD}) may become blocked\nat such a value.\nIf this happens, it may be necessary to move the value of the\nparameter in question a significant distance from the\nlimit (with \\Cind[SET PARameter]{SET PARam}) and restart the minimization, perhaps\nwith that parameter fixed temporarily.\nWe are investigating ways to induce Minuit to extricate itself from\nsuch situations automatically, but it is not so obvious as it seems,\nand for the moment must sometimes be done by hand.\n\n\\subsection{Getting the right parameter errors with limits.}\n\\label{sec:right-errors}\n\nIn the best case, where the minimum is far from any limits,\nMinuit will correctly transform the error matrix, and the\nparameter errors it reports should be accurate and very\nclose to those you would have got without limits.\nIn other cases (which should be more common, since\notherwise you wouldn't need limits), the very meaning of\nparameter errors becomes problematic. Mathematically, since\nthe limit is an absolute constraint on the parameter, a parameter\nat its limit has no error, at least in one direction.\nThe error matrix, which can assign only symmetric errors, then\nbecomes essentially meaningless.\nOn the other hand, the \\Cind[MINOs]{MINOS} analysis is still meaningful,\nat least in principle, as long as \\Cind[MIGrad]{MIGRAD} (which is called\ninternally by \\Cind[MINOs]{MINOS}) does not get blocked at a limit.\nUnfortunately, the user has no control over this aspect of\nthe \\Cind[MINOs]{MINOS} calculation, although it is possible to get enough\nprintout from the \\Cind[MINOs]{MINOS} command to be able to determine whether\nthe results are reliable or not.\n\n\\section{Fixing and Releasing Parameters}\n\nWhen Minuit needs to be guided to the ``right'' minimum,\noften the best way to do this is with the \\Cind{FIX} \nand \\Cind[RELease]{RELEASE} commands.\nThat is, suppose you have a problem with ten free parameters,\nand when you minimize with respect to all at once, Minuit goes to\nan unphysical solution characterized by an unphysical or unwanted\nvalue of parameter number four.\nOne way to avoid this is to \\Cind{FIX} parameter four at a ``good'' value\n(not necessarily the best, since you presumably don't know that yet),\nand minimize with respect to the others. \nThen \\Cind[RELease]{RELEASE 4} and minimize again. \nIf the problem admits a ``good'' physical solution, you will\nnormally find it this way. \nIf it doesn't work,\nyou may see what is wrong by the following sequence\n(where \\Lit{xxx} is the expected physical value for parameter four):\n\\begin{XMP}\nSET PARAM 4 xxx\nFIX 4\nMIGRAD\nRELEASE 4\nSCAN 4\n\\end{XMP}\nwhere the \\Cind[SCAn]{SCAN} command gives you a picture of \\Rind{FCN} as a \nfunction of parameter four alone,\nthe others being fixed at their current best values.\nIf you suspect the difficulty is due to parameter five,\nthen add the command\n\\begin{XMP}\nCONTOUR 4 5\n\\end{XMP}\nto see a two-dimensional picture.\n\n\\section{Interpretation of Parameter Errors}\n\nThere are two kinds of problems that can arise:\nThe {\\bf reliability} of Minuit's error estimates, and their\n{\\bf statistical interpretation}, assuming they are accurate.\n\n\\subsection{Statistical Interpretation.}\n\nFor discussuion of basic concepts, such as the meaning of the elements\nof the error matrix, parabolic versus \\Cind[MINOs]{MINOS} errors,\nthe appropriate value for \\Lit{UP} \n(see \\Cind[SET ERRordef]{SET ERRdef}), and setting of exact\nconfidence levels, see (in order of increasing complexity and completeness):\n\n\\begin{UL} \n\\item {\\em ``Interpretation of the Errors on Parameters'',}\n see Part 3 of this write-up.\n\\item {\\em ``Determining the Statistical Significance of Experimental\n Results''}\\cite{bib-MIN81}.\n\\item {\\em ``Statistical Methods in Experimental Physics''}\\cite{bib-EADIE}.\n\\end{UL}\n\n\\subsection{The Reliability of Minuit Error Estimates.}\n\nMinuit always carries around its own current estimates of the\nparameter errors, which it will print out on request, no matter how\naccurate they are at any given point in the execution.\nFor example, at initialization, these estimates are just the starting\nstep sizes as specified by the user. \nAfter a \\Cind[MIGrad]{MIGRAD} or \\Cind[HESse]{HESSE} step,\nthe errors are usually quite accurate, unless there has been a problem.\nMinuit, when it prints out error values,\nalso gives some indication of how reliable it thinks they are.\nFor example, those marked \\Lit{'CURRENT GUESS ERROR'} are only working values\nnot to be believed, and \\Lit{'APPROXIMATE ERROR'} means that they have been\ncalculated but there is reason to believe that they may not be accurate.\nIf no mitigating adjective is given, then at least Minuit believes\nthe errors are accurate, although there is always a small chance\nthat Minuit has been fooled.\nSome visible signs that Minuit may have been fooled are:\n\n\\begin{UL}\n\\item Warning messages produced during the minimization or error analysis.\n\\item Failure to find new minimum.\n\\item Value of \\Lit{EDM} too big. For a ``normal'' minimization, \n after \\Cind[MIGrad]{MIGRAD}, the value of \\Lit{EDM} is usually more \n than three orders of magnitude smaller than \\Lit{UP} \n (the \\Cind{SET ERRordef}), unless a looser tolerance has been specified.\n\\item Correlation coefficients exactly equal to zero, unless some parameters\n are known to be uncorrelated with the others.\n\\item Correlation coefficients very close to one (greater than 0.99).\n This indicates both an exceptionally difficult problem, and one\n which has been badly parametrized so that individual errors are not\n very meaningful because they are so highly correlated.\n\\item Parameter at limit. This condition, signalled by a Minuit warning\n message, may make both the function minimum and parameter errors\n unreliable. See section \\ref{sec:right-errors},\n {\\em Getting the right parameter errors with limits.}\n\\end{UL}\n\nThe best way to be absolutely sure of the errors, is to use\n``independent'' calculations and compare them, or compare the calculated\nerrors with a picture of the function if possible.\nFor example, if there is only one free parameter, the command \\Cind[SCAn]{SCAN}\nallows the user to verify approximately the function curvature.\nSimilarly, if there are only two free parameters, use \\Cind[CONtour]{CONTOUR}.\nTo verify a full error matrix, compare the results of \\Cind[MIGrad]{MIGRAD}\nwith those (calculated afterward) by \\Cind[HESse]{HESSE}, \nwhich uses a different method.\nAnd of course the most reliable and most expensive technique,\nwhich must be used if asymmetric errors are required, is \\Cind[MINOs]{MINOS}.\n\n\\Section{4cm}{Convergence in MIGRAD, and Positive-definiteness.}\n\n\\Cind[MIGrad]{MIGRAD} uses its current estimate of the covariance matrix of the\nfunction to determine the current search direction, since this is\nthe optimal strategy for quadratic functions and ``physical'' functions\nshould be quadratic in the neighbourhood of the minimum at least.\nThe search directions determined by \\Cind[MIGrad]{MIGRAD} are guaranteed to be\ndownhill only if the covariance matrix is positive-definite,\nso in case this is not true, it makes a positive-definite\napproximation by adding an appropriate constant along the diagonal\nas determined by the eigenvalues of the matrix.\nTheoretically, the covariance matrix for a ``physical'' function must be\npositive-definite at the minimum, although it may not be so\nfor all points far away from the minimum, even for a well-determined\nphysical problem. \nTherefore, if \\Cind[MIGrad]{MIGRAD} reports that it has found a\nnon-positive-definite covariance matrix, this may be\na sign of one or more of the following:\n\n\\begin{UL}\n\\item {\\bf A non-physical region.}\n On its way to the minimum, \\Cind[MIGrad]{MIGRAD}\n may have traversed a region which has\n unphysical behaviour, which is of course not a serious problem as long\n as it recovers and leaves such a region.\n\\item {\\bf An underdetermined problem.}\n If the matrix is not positive-definite even at the minimum,\n this may mean that the solution is not well-defined, for example\n that there are more unknowns than there are data points, or that the\n parametrization of the fit contains a linear dependence.\n If this is the case, then Minuit (or any other program) cannot solve\n your problem uniquely, and the error matrix will necessarily be\n largely meaningless, so the user must remove the underdeterminedness\n by reformulating the parametrization. Minuit cannot do this itself,\n but it can provide some hints (contours, global correlation coefficients,\n eigenvalues) which can help the clever user to find out what is wrong.\n\\item {\\bf Numerical inaccuracies.}\n It is possible that the apparent lack of positive-definiteness\n is in fact only due to excessive roundoff errors in numerical\n calculations, either in \\Rind{FCN} or in Minuit.\n This is unlikely in general, but becomes more likely if the number of\n free parameters is very large, or if the parameters are badly scaled\n (not all of the same order of magnitude), and correlations are\n also large.\n In any case, whether the non-positive-definiteness is\n real or only numerical is largely irrelevant, since in both cases the\n error matrix will be unreliable and the minimum suspicious.\n\\end{UL}\n\n\\section{Additional Trouble-shooting}\n\nWhen Minuit just doesn't work, some of the more common causes are:\n\n\\begin{UL}\n\\item {\\bf Precision mismatch.}\n Make sure your \\Rind{FCN} has been compiled with the same precision as the\n version of Minuit you are using.\n When using \\Lit{DOUBLE PRECISION}, it is safest to use the \\Lit{IMPLICIT}\n declaration to make sure that everything is \\Lit{DOUBLE PRECISION}, not\n just the arguments of \\Rind{FCN} but also the internal variables.\n Note that depending on the computer system used, floating-point\n constants may be passed as single precision in subroutine arguments,\n even if there is an \\Lit{IMPLICIT DOUBLE PRECISION} statement\n (which is strictly speaking correct since the \\Lit{IMPLICIT} statement\n refers only to variables, not constants).\n Therefore, if constants are used as arguments in subroutine calls,\n they must be explicitly of the right precision (for example, on Apollo,\n even 0. is not equal to \\Lit{0.D0}).\n \n If the problem is only one of precision, and not of word length mismatch,\n an appropriate \\Cind[SET EPSmachine]{SET EPS} command may fix it.\n\\item {\\bf Trivial bugs in \\Rind{FCN}.}\n The possibilities for Fortran bugs are numerous. Probably the most\n common among physicists inexperienced in Fortran is the confusion\n between \\Lit{REAL} and \\Lit{INTEGER} types, \n which you can sometimes get away with, but not always.\n [For example, if \\Lit{A} and \\Lit{B} are \\Lit{REAL} variables, \n the Fortran statement \\Lit{A = 2*B} is not good programming, \n but happens to do what the user\n probably intended, whereas the statement \\Lit{A = B + 2/3} almost\n certainly will not do what the user intended.]\n Minuit can spot some trivial bugs itself, and issues\n a warning when it detects an unusual \\Rind{FCN} behaviour. Such a warning\n should be taken seriously.\n \n Minuit also offers some tools (especially \\Cind[SCAn]{SCAN}) \n which can help the user to find trivial bugs.\n\\item {\\bf Overwriting in a user routine.}\n Overwriting most often occurs when setting the values of a local\n array or an array in \\Lit{COMMON}, and elements outside the\n dimensions of the array are addressed.\n Most computer systems do not detect this error unless you attempt to\n write into a protected area of memory, and of course Minuit is also\n helpless, especially if Minuit itself is being overwritten.\n The symptoms of user overwriting may be almost anything,\n including unusual behaviour of Minuit itself.\n The effects depend critically on where instructions and data are\n loaded in memory, so they may change completely if the same\n program is recompiled with different compiler options or reloaded\n in a different sequence, even though the compiler and loader\n are not at fault.\n\\item {\\bf Changing the values of input arguments.}\n In subroutine \\Rind{FCN}, for example, the arguments \\Lit{NPAR} and \\Lit{IFLAG},\n as well as the values of the parameters themselves, are only\n input to \\Rind{FCN} and their values should not be changed inside \\Rind{FCN}.\n Minuit is now protected against this in principle, since\n the user only gets a copy of the value, not the actual address\n of the internal Minuit variable, but still this is a symptom of\n misunderstanding by the user.\n \n If you really want to change the number of variable parameters,\n this must be done with commands like \\Cind{FIX} and \\Cind[RELease]{RELEASE}, \n by redefining parameters using command \\Cind[PARameters]{PARAMETER}\n or \\Cind[CLEar]{CLEAR}.\n \n Similarly, if a parameter takes on an unwanted value, it will do no good\n to change its value inside \\Rind{FCN}: In the best case, \n Minuit won't see your\n improved value, and in the worst case, it will produce unpredictable\n results. To set a parameter to a certain value, use the command\n \\Cind[SET PARameter]{SET PARam}, and to keep it within certain bounds, use the command\n \\Cind{SET LIMits}. If the parameter must obey more complicated constraints,\n you must find a trick such as adding a penalty value to \\Rind{FCN} outside\n of the physical region, to force it back to where you want it.\n\\item {\\bf An ill-posed problem.}\n For questions of parameter dependence, see the discussion above\n on postive-definiteness.\n Other mathematical problems which can arise are:\n {\\bf excessive numerical roundoff} ---\n be especially careful of exponential and factorial functions\n which get big very quickly and lose accuracy;\n {\\bf starting too far from the solution} ---\n the function may have unphysical local minima, especially\n at infinity in some variables;\n {\\bf incorrect normalization} ---\n in likelihood functions, the probability distributions must\n be normalized or at least have an integral which is independent\n of the values of the variable parameters.\n\\item {\\bf A bug in Minuit.}\n This is extremely unlikely, but it did happen once. If a bug is suspected, and\n all other possible causes can be eliminated, please try to save a copy of the\n input and output files, listing of \\Rind{FCN}, and other information that may be\n relevant, and send them to \\Lit{JAMES at CERNVM} or \\Lit{VXCERN::JAMES} or\n \\Lit{JAMES\\atsign CERNAPO.CERN.CH}.\n\\end{UL}\n", "meta": {"hexsha": "e992de80c8b7eb39443a900f9c1d7a56b49f2db8", "size": 22826, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "longwrups/minuit/minch5.tex", "max_stars_repo_name": "berghaus/cernlib-docs", "max_stars_repo_head_hexsha": "76048db0ca60708a16661e8494e1fcaa76a83db7", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-07-24T12:30:01.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-24T12:30:01.000Z", "max_issues_repo_path": "longwrups/minuit/minch5.tex", "max_issues_repo_name": "berghaus/cernlib-docs", "max_issues_repo_head_hexsha": "76048db0ca60708a16661e8494e1fcaa76a83db7", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "longwrups/minuit/minch5.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": 50.2775330396, "max_line_length": 92, "alphanum_fraction": 0.7378866205, "num_tokens": 5318, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.33458944125318596, "lm_q1q2_score": 0.16990848793091773}} {"text": "\\documentclass[a4paper,DIV12]{scrartcl}\n\\usepackage{graphicx}\n\\usepackage{natbib}\n\\usepackage{amsmath}\n\\usepackage{comment}\n\\usepackage{url}\n\\usepackage{color}\n\\usepackage{listings}\n\\usepackage[pdftex]{hyperref}\n\\graphicspath{{pics/}}\n\\include{commands}\n\\bibliographystyle{apalike}\n\\parindent 0pt\n\\author{\nThomas G{\\\"u}nther\\thanks{Leibniz Institute for Applied Geophysics, Hannover (Germany)} \n\\ \\& \\ \nCarsten R{\\\"u}cker\\thanks{Institute of Geology and Geophysics, University of Leipzig (Germany)}\n}\n\\title{GIMLi --\\\\ Geophysical Inversion and Modelling Library \\\\-- programmers tutorial}\n\\newcommand{\\cw}[1]{{\\textbf{\\texttt{#1}}}}\n\\newcommand{\\invert}{invert}\n\\newcommand{\\command}[1]{\\par{\\texttt{\\$ #1}}}\n\\newcommand{\\file}[1]{{\\texttt{#1}}}\n\\newcommand{\\sperre}{\\,\\rule{1ex}{2ex}}\n\\newcommand{\\mycomment}[2]{\\sperre{\\textem{#1: #2}}\\sperre}\n\n\\lstloadlanguages{[Visual]C++,[ISO]C++,Python}\n\\lstset{language=[ISO]C++}\n\\lstdefinelanguage{C++}{morekeywords={RVector,RMatrix,ModellingBase}}\n%\\lstset{numbers=left,numberstyle=\\tiny}\n%\\lstset{basicstyle=\\small,keywordstyle=\\color{red}}\n\\lstset{basicstyle=\\sffamily\\small,keywordstyle=\\bfseries}\n\\lstset{frame=shadowbox,commentstyle=\\color{blue}}\n\\lstset{morekeywords={RVector,RMatrix,ModellingBase,RSparseMapMatrix,SparseMatrix}}\n\n\\begin{document}\n\\maketitle\n\\begin{abstract}\nGIMLi is a C++ class library for solving inverse and forward problems in geophysics.\nIt was build in order to make inversion available to various forward modelling routines.\nTemplate programming algorithms are used to create a purely mathematical framework for solving physics problems.\nThe inversion can apply various minimisation and regularization schemes, different transformation functions a region approach for sophisticated regularization and the chance to incorporate parametric and structural inversion.\n\nIn this tutorial we like to show the programmer how to work with GIMLi by means of different examples.\nA simple curve-fitting is used to show how different forward operators can be incorporated.\nSome small 1d examples demonstrate the use of different parameterisation and the partitioning of data and model.\nThe region technique can be used for different target parameters or geological units.\n\nJoining different inversion runs is one of the key issues of ongoing research.\nWe show three different joint inversion (JI) types: one-parameter JI, petrophysical JI and structural JI.\nFinally the time-lapse inversion framework is presented and applied to ERT data using different algorithms.\n\\end{abstract}\n\n\\clearpage\n\\tableofcontents\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\include{introduction}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\include{firstexample}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\include{concepts}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\include{enhanced}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\include{jointinversion}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\section{Inversion templates}\nThere are certain tasks that go beyond a classical inversion scheme but still are method-independent.\nThey can be formulated more generally in order to be applied to a wider range of applications.\nThere are several cases\n\\begin{description}\n\\item[Roll-along inversion:] Geophysical data are often acquired along profiles. Since numerical work usually goes by $N^2$, it can be much more efficient to do the work piece-wise. However, the continuity must be ensured.\n\\item[Joint inversion:] As described above, the different joint inversions do not have to be programmed individually. Furthermore, more than two methods can be coupled.\n\\item[Time-lapse inversion:] Although there are several approaches for efficient inversion along the time axis, they are method-independent and can be formulated generally.\n\\end{description}\n\n\\subsection{Laterally constrained inversion}\nThis type is used when several 1d soundings along a line needed to be inverted together.\nThe forward modelling just combines the results of several soundings in a long vector.\nThey are individually connected to local 1d models, i.e. columns of a 2d model, which is regularized like a 2d model to achieve similarity between neighbouring models.\nAccordingly, the Jacobian matrices are blocks in a block-diagonal matrix, for which an own matrix type is used.\n\n\\sperre{TO BE IMPLEMENTED}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Roll-along inversion}\n\\sperre{BLA}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Joint inversion}\nAssume we have inversions invA, invB and invC, which (or parts of which) are to be coupled.\n\n\\subsubsection*{Block inversion}\nBlock inversion: mesh1d containing thickness and several parameters.\n\n\\sperre{TO BE IMPLEMENTED}\n\n\\subsubsection*{Structural coupling}\nAs described in section \\ref{sec:structjoint}, the structural coupling consists mainly some preparation steps and a main iteration for the coupling that does individual runs and coupling.\n\nGenerally, there can be two possibilities for each inversion: (i) to couple the whole inversion model (as above) or (ii) to couple only one specified region.\nFor example, structures in an aquifer are to be imaged by cross-hole ERT and GPR. Whereas for the latter it is sufficient to restrict to the aquifer, for ERT the unsaturated zone and a clay layer must be taken into account.\n\nFor more than 2 inversions the coupling must be generalized: One can imaging a chain (or ring) or a star scheme coupling. \nWhereas in the first the inversions are coupled pair-wise, in the latter the constraint weights are mixed. \n\n\\begin{lstlisting}\nSCCInversion SCC;\nSCC.append( invA );\nSCC.append( invB, regionnumber );\nSCC.run(); \n\\end{lstlisting}\n\nOptions: type of coupling, e.g. IRLS scheme or self-defined function. Ring or star connection. Terminating criterion.\n\n\\sperre{TO BE IMPLEMENTED}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\subsection{Time lapse inversion}\\label{sec:timelapse}\n\\subsubsection*{Strategies}\\label{sec:tlstrategies}\n\\subsubsection*{Example}\n%DC1d infiltration??\n\n\\bibliography{gimli} \n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\begin{appendix}\n\\include{appendix}\n\\end{appendix}\n\n\\end{document}\n", "meta": {"hexsha": "1e6e0ddd080115a2d89b1ab4a905557158af607e", "size": 6380, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/tutorial/gimli-tutorial.tex", "max_stars_repo_name": "mjziebarth/gimli", "max_stars_repo_head_hexsha": "196ac4d6dd67e0326cccc44a87b367f64051e490", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-07-10T00:56:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-17T12:43:38.000Z", "max_issues_repo_path": "doc/tutorial/gimli-tutorial.tex", "max_issues_repo_name": "ivek1312/gimli", "max_issues_repo_head_hexsha": "5fafebb7c96dd0e04e2616df402fa27a01609d63", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/tutorial/gimli-tutorial.tex", "max_forks_repo_name": "ivek1312/gimli", "max_forks_repo_head_hexsha": "5fafebb7c96dd0e04e2616df402fa27a01609d63", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-29T04:28:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T04:28:40.000Z", "avg_line_length": 46.231884058, "max_line_length": 225, "alphanum_fraction": 0.7136363636, "num_tokens": 1445, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381372136563, "lm_q2_score": 0.3106943704494217, "lm_q1q2_score": 0.16986846134228648}} {"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 {algorithmic}\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{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\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 11} } \n\n\\begin{centering}\n\\section*{Radix Sort and Wrap-Up}\n\\end{centering}\n\nToday, we will continue our discussion of non-comparison-based sorts, such as Counting Sort and Radix Sort. We will wrap-up our discussion by providing motivation for the study of specialized data structures, such as balanced binary trees.\n\n\\section{Counting Sort} \nRecall that our sorting lower bounds applied to the class of algorithms that can only evaluate the values being sorted via \\textit{comparison queries}, namely via asking whether a given element is greater than, less than, or equal to some other element. For such algorithms, it's been proven that any correct algorithm (even a randomized one!) will require $\\Omega(n \\log n)$ such queries on some input. As with any lower-bound that we prove in a restricted model, it is fruitful to ask ``is it possible to have an algorithm that does not fall in this class, and hence is not subject to the lowerbound?'' For sorting, the answer is ``yes''.\n\nWe start by looking at a very simple non-comparison-based sorting algorithm called Counting Sort. Since it is not comparison-based, it is not restricted by the $\\Omega(n \\log n)$ lower bound for sorting. For a given input of $n$ objects, each with a corresponding key (or value) in the range $\\{0, 1, \\cdots, r - 1\\}$, Counting Sort will sort the objects by their keys: \n\n\\begin{enumerate}\n \\item Create an array $A$ of $r$ buckets where each bucket contains a linked list. \n \\item For each element in the input array with key $k$, concatenate the element to the end of the linked list $A[k]$. \n \\item Concatenate all the linked lists: $A[0], \\cdots , A[r - 1]$.\n\\end{enumerate}\n\nThe algorithm correctly sorts the $n$ elements by their keys because the elements are placed into buckets by key where bucket $i$ (containing elements with key = $i$) will come before bucket $j$ (containing elements with key = $j$) in A for $i < j$. Therefore, when the algorithm concatenates the buckets, all elements with key = $i$ will come before elements with key = $j$. The worst case run time of Counting sort is $O(n+r)$ since it performs $O(1)$ passes over the $n$ input elements and $O(1)$ passes over the $r$ buckets of $A$. This is great if the size of the range $r$ is small, but we pay dearly in the running time (and space) if $r$ is large. The algorithm we discuss in the next section builds on Counting Sort and fixes this issue (that Counting Sort\nbehaves poorly if the range of values $r$ is very large).\n\nAn important property (which we will use in the next section) is that the algorithm described above is \\textit{stable}: If two input elements $x, y$ have the same key, and $x$ appears before $y$ in the input array, $x$ will appear before $y$ in the output.\n\n\\section{Radix Sort}\nRadix Sort is another non-comparison-based sorting algorithm that will use Counting Sort as a subroutine. Assuming that the input array contains $d$-digit numbers where each digit ranges from $0$ to $r - 1$, Radix Sort sorts the array digit-by-digit (or field-by-field for non-numerical\ninputs). The algorithm works on input array A as follows:\n\n\\begin{enumerate}\n \\item For $j = 1, \\cdots, d$:\n \\item Apply Counting Sort to $A$ using the $j$th digit as the key.\n\\end{enumerate}\n\nNote that we refer to the least significant digit as the first digit. Hence, the algorithm calls Counting Sort first using the least significant digit as the key, then again using the second least significant digit, until the most significant digit. \n\nWe will show that Radix Sort correctly sorts an input list of $n$ numbers via induction on the iterations of the loop.\n\n\\textbf{Inductive Hypothesis:} At the end of the $j^{\\text{th}}$ iteration, the elements in $A$ are sorted when considering only the $j$ least significant digits of each element.\n\n\\textbf{Base case}: $(j = 1)$ Radix Sort correctly sorts the numbers by the first digit as it uses Counting Sort to sort the numbers using the least significant digit as a key. (Note: we could have used $j = 0 $as the base case as well).\n\n\\textbf/{Inductive case}: We will prove that, if the inductive hypothesis for $j = k -1$ is true, then the inductive hypothesis for $j = k$ is true as well.\nBy the inductive hypothesis for $j = k - 1$, by the end of iteration $k - 1$, the input numbers have been sorted by the $k - 1$ least significant digits. After we run Counting Sort on the elements using digit $k$ as the key, the numbers are sorted by their $j^{\\text{th}}$ digit. Since Counting Sort is stable, the elements in each bucket keep their original order, and by the induction hypothesis, they are ordered by their $k - 1$ least significant digits. Since \\textbf{the elements are ordered first by their $k^{\\text{th}}$ digit, and then by their $k -1$ least significant digits}, we conclude that they are ordered by their $k$ least significant digits.\n\nTo provide more detail for the bolded text in that last sentence, we could consider any two numbers $x$ and $y$ in the input and separately consider two cases as we did in lecture: case (i) where $x$ and $y$ have different $k$th least significant digits, and case (ii) where $x$ and $y$ have\nidentical $k$th least significant digits. In both cases, we could establish that, in the output,x and y are ordered by their least k significant digits. Since this is true for every pair of\nnumbers x and y in the input, this means that the output of this iteration is correctly sorted by the $k$ least significant digits.\n\nBy induction, the inductive hypothesis is true for all $j \\in \\{1, \\cdots , d\\}$. Applying the inductive hypothesis for $j = d$, we conclude that at the end of iteration $d$, the numbers are in sorted order (since the input consists of $d$-digit numbers). In other words, Radix Sort correctly sorts the input.\n\nThe worst case running time of Radix Sort is $O(d(n + r ))$ since we are calling Counting Sort on $n$ elements with $r$ possible keys once for each digit in the input numbers. If $r = O(n)$ and $d = O(1)$, then this takes $O(n)$ time.\n\nAs we did in lecture, we could consider varying the base $r$ in which we write our numbers and running radix sort (with the Counting Sort in the inner loop using $r$ buckets). Now the maximum number of digits is a function of the maximum size of the numbers in the input and our choice of base $r$. If we have an input consisting of $n$ numbers of value at most $M$, then the number of digits $d = \\lfloor log_r (M)\\rfloor + 1$. (verify this yourself!) Thus the running time for Radix Sort with base $r$ is $O(d(n + r ))$ which is $O((\\lfloor \\log_r (M)\\rfloor + 1) \\cdot (n + r )).$\n\nHow should we choose $r$? One reasonable choice is $r = n$ to balance the two values $n$ and $r$ in the term $(n +r)$ in the expression for the running time. For this choice of r, the running time for Radix sort is $O(n \\cdot (\\lfloor\\log_r (M)\\rfloor + 1))$. (Why didn’t we drop the $+1$ term in the expression\nfor the asymptotic running time?) Note that we might make a different choice of $r$ if it was also important to optimize the space required to run Radix Sort.\n\nSo the running time of Radix Sort (in terms of $n$) depends on how large the numbers in the input are as a function of $n$. If the upper bound $M \\leq n^c$ for some constant $c$, then the running time is $O(n)$. In this regime, Radix Sort beats MergeSort and Quicksort. On the other hand, if $M = 2^n$ , then the running time is $O(n^2/\\log n)$. In this regime, we would not use Radix Sort.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\\end{document}\n\n", "meta": {"hexsha": "b83bb3d1fb6f41e4733ab4ebea8a3f98b929a372", "size": 9102, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "assets/lectures/lecture11.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/lecture11.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/lecture11.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": 70.0153846154, "max_line_length": 765, "alphanum_fraction": 0.7351131619, "num_tokens": 2449, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4726834914771176, "lm_q2_score": 0.35936414516010196, "lm_q1q2_score": 0.1698654988459667}} {"text": "\n\\typeout{new file: Using_RADCAL_Chapter.tex}\n\n\\chapter{Using RadCal}\n\\label{chap::using_RADCAL}\n\nThis chapter describes in details how to compile RadCal, how to write an input file using the namelist formatting, how to run RadCal, and describes the output files. Important modifications were brought to the code since it last release in 1993 \\cite{Grosshandler1993}. In particular, the input file has been completely upgraded and the user who wishes to use this new version of the code must rewrite the old RadCal input file to comply with the new syntax.\n\n\\section{Compiling RadCal}\n\nThis new version of RadCal is a Fortran 2008 written software, written following modular paradigm. A complete description of the code is presented in Chapter~\\ref{chap:Code}. The source code is contained in the file \\verb=RADCAL.f90=. It includes the RADCAL module and the main program.\n\nThe file \\verb=Makefile= is the make file to compile \\verb=RADCAL.f90= and to generate the executable \\verb=RADCAL.x=. It is made for Linux machine using the Intel Fortran compiler (\\verb=ifort=). It has a couple of flags. Typing \\verb'make DEBUG=0' will compile RADCAL using the compiler optimization flags. Typing \\verb'make DEBUG=1' will compile the code in debugging mode. This is useful to detect any error or bug when the source file is modified. In debug mode, the code displays additional data on the screen. It prints the pressure (in atm), physical length (in cm), the temperature (in K) of each segment that composes the domain. It also prints on screen the values contained of the Lorentz half-width at half-maximum $\\gamma_c$ vector for each species included in RadCal. Furthermore, it also prints characteristics pertaining to $\\rm CO_2$ if this species is included in the calculation and if the wavenumber $3600~\\rm cm^{-1}$ is included in the user defined spectrum. It is recommended to use RadCal with the optimizing flag as it is slightly faster than the debugging mode.\n\nIn addition to the optimization flag, a second flag enabling the compilation of the code with \\verb=OpenMP= (for loop parallelization) has been implemented. To compile the code with \\verb=OpenMP=, just type \\verb'make DEBUG=0 PARALL=1' (for optimization version) or \\verb'make DEBUG=1 PARALL=1' for the debugging \\verb=OpenMP= version. Note that the \\verb=OpenMP= version does not improve much the performances, but it was included there for experimentation.\n\n\\section{Input file}\n\nThe input file is named \\verb=RADCAL.in=. The input file format has changed since the last RADCAL version. It now uses the Fortran \\verb=namelist= formalism, which is more convenient. What is needed is the knowledge, for each segment along the line of sight, of the local temperature (\\verb=T=), distance (\\verb=LENGTH=), pressure (\\verb=PRESSURE=), soot volume fraction (\\verb=Fv=), and species mole fraction, (\\verb=X=).\n\\textbf{It is very important that the sum of all the species mole fraction over a given segment is equal to 1}. Otherwise the code will not compute and will return an error message in the output file \\verb=RADCAL.out=.\n\nA list of all the RadCal available species is included in the code and is printed in a automatically generated \\verb=RADCAL.in= in the case the user did not provide any input file. Unlike the old version, you can now solve the radiative Transfer Equation for any mixture of fuels and products of combustion.\n\n\\subsection{Example}\\label{sec:input_file}\nBelow is an example of input file \\verb=RADCAL.in=, automatically generated by RadCal in the case that RadCal is started without an existing input file. The header prints automatically the list of species present in RadCal.\n\n\\begin{lstlisting}\n#-----------------------------------------------------------------------\n# Generic RADCAL input file\n# Created automatically\n# List of species currently available:\n#-----------------------------------------------------------------------\n# ! \n# CO2 ! (gas) Carbon dioxide\n# H2O ! (gas) Water\n# CO ! (gas) Carbon monoxide\n# CH4 ! (gas) Methane\n# C2H4 ! (gas) Ethylene\n# C2H6 ! (gas) Ethane\n# C3H6 ! (gas) Propylene\n# C3H8 ! (gas) Propane\n# C7H8 ! (gas) Toluene\n# C7H16 ! (gas) n-Heptane\n# CH3OH ! (gas) Methanol\n# MMA ! (gas) MMA, C5H8O2\n# Fv ! (solid) Soot. Defined by its soot volume fraction, Fv\n# N2 ! (gas) Nitrogen does not participate to the radiative transfer\n# but is needed for collision broadening\n# CH4_OLD ! (gas) Former Methane data\n# O2 ! (gas) Oxygen does not participate to the radiative transfer\n# but is needed for collision broadening\n#-----------------------------------------------------------------------\n#\n# How to use:\n# 1) Discretize the line of sight into isothermal, homogeneous\n# segments\n# 2) Define each segment temperature (variable \"T\", in Kelvin) and\n# length (variable \"LENGTH\", in meters)\n# 3) Enter the pressure of each segment (variable \"PRESSURE\", in\n# atmosphere)\n# 4) Enter the composition of the mixture, in mole fraction for\n# gas phase species (variable \"X\")\n# Important: make sure the sum of species mole fraction is\n# equal to 1\n# 5) Define bounds of the spectrum OMMIN/OMMAX in wavenumber\n# (1/cm)\n# 6) Do not forget to enter the temperature of the surrounding,\n# which is represented by a wall at an infinite distance at its\n# blackbody temperature (variable \"TWALL\" in Kelvin)\n#-----------------------------------------------------------------------\nExample:\n&HEADER TITLE=\"Example\" CHID=\"Example\" /\n\n&BAND\n OMMIN = 50.0\n OMMAX = 10000.0 /\n&WALL TWALL = 500.0 /\n\n&Path_Segment ! Define a homogeneous segment\n T = 300.0 ! Temperature in Kelvin\n LENGTH = 0.3175 ! Length of the segment in meters\n PRESSURE = 1.0 ! Pressure in atm\n XC2H4 = 0.01 ! Mole fraction of Ethylene\n XCO2 = 0.0033 ! Mole fraction of CO2\n XH2O = 0.01 ! Mole fraction of H2O\n XO2 = 0.21 ! Mole fraction of O2\n XN2 = 0.7667 ! Mole fraction of N2\n Fv = 1.0e-7/! Soot volume fraction\n#-----------------------------------------------------------------------\n\\end{lstlisting}\n\n\\subsection{Input file structure}\n\nEach line starting with a character \\verb=#= is a comment. The comments on the header in the above input file are generated automatically.\n\nEach namelist name is preceded by a \\verb=&= character. The needed namelist are:\n\\verb=HEADER=, \\verb=BAND=, \\verb=WALL=, \\verb=Path_Segment=. These namelist names are not case-sensitive.\n\nEach namelist has a set of parameters you may provide. Parameters not provided have their values taken by default. They are presented below and in the input file.\nA \"slash\" character '\\verb=/=' is needed after providing the parameters of each namelist.\n\nThe name of the case is defined by assigning a value to \\verb'&HEADER TITLE=\"\"' and \\verb'CHID=\"\"'.\n\nThe band limit, in cm$^{-1}$, is defined with the keyword \\verb=OMMIN= and \\verb=OMMAX=.\n\n\\subsection{Naming the case: the \\texorpdfstring{{\\tt HEADER}}{HEADER} namelist group}\n\nthe namelist \\verb=HEADER= defines the case title with the parameter \\verb=TITLE= and the CASEID with the parameter \\verb=CHID=.\nThis parameter are of type \\verb=string=. The title of the case \\verb=TITLE= is just used for the user own organization. The parameter \\verb=CHID= is used to name the Tecplot output file: \\verb=.tec=.\n\n\\subsection{Defining the integration bounds: the \\texorpdfstring{{\\tt BAND}}{BAND} namelist group}\n\nThe namelist \\verb=BAND= defines the lower bound wavenumber, $\\om_{min}$ of the spectrum with the parameter \\verb=OMMIN= and the upper bound wavenumber, $\\om_{max}$ of the spectrum with the parameter \\verb=OMMAX=. Units are in cm$^{-1}$.\n\n\\subsection{Defining the surrounding blackbody temperature: the \\texorpdfstring{{\\tt WALL}}{WALL} namelist group}\n\nThe surrounding temperature is given by \\verb=TWALL= (given in Kelvin). This defines the temperature of an emitting blackbody located at one extremity of the path (the observer is located on the other side). This corresponds to the temperature of $T_{w}$ in the Eq.~\\ref{eq::RTE_Wavenumber}.\n\n\\subsection{Characterizing the homogeneous pathlength segment: the \\texorpdfstring{{\\tt Path\\_Segment}}{Path_Segment} namelist group}\n\nAny homogeneous segment can be defined by using the keyword \\verb=&Path_Segment=. For each path segment, the user needs to define the local temperature (in Kelvin) using the parameter \\verb=T=, the length of the segment (in meters) with \\verb=LENGTH=, the segment total pressure (in atm) with \\verb=PRESSURE=, the mole fraction of any species present in the segment with the parameter \\verb=X=, and the volume fraction of soot (if any) with the parameter \\verb=Fv=. Values omitted are set internally to zero. The user does not need to enter a value for a species not present in the segment.\n\nIt is very important that the sum of mole fraction \\verb=X= is equal to 1 otherwise the segment will be dismissed.\n\nEach segment definition is terminated with a \"slash\" character \\verb=/=.\n\nIf there is more than one segment, the user should add other segments by adding and defining extra \\verb=&Path_Segment= keywords. There is no restriction on the number of segment considered. The segments are to be entered from the closest to the observer, \\textit{i.e.} closest to where the incident intensity is calculated (variable $s$ in Eq,~\\ref{eq::RTE_Wavenumber}), to the furthest (defined as $s = 0$ in Eq.~\\ref{eq::RTE_Wavenumber}). It is assumed that the furthest point is bounded by an emitting blackbody wall of temperature specified by \\verb=TWALL=.\n\n\\section{Output files}\n\nRadCal generates two output files: \\verb=RADCAL.out= which contains a summary of the case run and the integrated quantities presented in Section~\\ref{sec::Output}, and a Tecplot file of name \\verb=.tec=, where \\verb=CHID= is the value entered by the user. The Tecplot file prints the spectral transmissivity along the whole line of sight (quantity $\\bar{\\tau}(\\om_0; 0 \\rightarrow s) $ in Eq.~\\ref{eq::RTE_Wavenumber}) expressed in \\%, and the incident spectral intensity $I_{\\om_0}(s)$, given in $\\rm W/m^{2}/str/cm^{-1}$, as calculated using either Eq.~\\ref{eq::RTE_wavenumber_H}, against the wavenumber, given in $\\rm cm^{-1}$.\n\nIf \\verb=RADCAL.in= was not provided, the code will print in \\verb=RADCAL.out= the following message:\n\\begin{lstlisting}\nWARNING ! RADCAL.in was NOT provided.\nCreating Default RADCAL.in for illustration purposes.\n\\end{lstlisting}\n\nThe output file generated by RadCal using the input file \\verb=RADCAL.in= presented in Subsection~\\ref{sec:input_file} is given below as an example:\n\\begin{lstlisting}\n CASEID: Example TITLE: Example\n-------------------------------------------------------------\n Calculation completed.\n Total path length (m): 0.317500000000000\n Amean (cm-1): 4.079920581529569E-003\n Planck mean absorption (cm-1): 9.468434716110452E-003\n Total Emissivity: 0.121498337093312\n Received Flux (W/m2/str): 1008.60961294274\n Total Transmissivity: 0.878725505722343\n-------------------------------------------------------------\nVersion: $Revision: 51 $\nVersion created on: $Date: 2014-06-05 14:56:35 -0400 (Thu, 05 Jun 2014) $\nVersion built on: Thu Jun 12 18:08:23 EDT 2014\nExecution time (ms): 1.85840E+01\n\\end{lstlisting}\nThe first line recalls the case title and the caseid. On the fourth line, RadCal recalls the total length of the line of sight (\\textit{i.e.} the sum of all the segments \\verb=LENGTH=). The value is given in meters. The fifth line prints the effective absorption coefficient as calculated by Eq.~\\ref{eq:effective_epsilon}. The sixth line prints the Planck mean absorption coefficient as defined by Eq.~\\ref{eq::planck_mean}. The seventh line prints the total emissivity, as calculated from Eq.~\\ref{eq:total_emissivity}. The total received flux as calculated by Eq.~\\ref{eq::received_flux} is given on the eighth line. Finally, the ninth line prints the value of the total transmissivity, calculated using Eq.~\\ref{eq::total_transmissivity}.\nThe last four lines of \\verb=RADCAL.out= recall the version of the code, the date at which this version was created, the date and time at which the code was compiled. The last line indicates the duration of code execution.\n\n\\section{Python script}\n\nA Python script has been written to facilitate the visualization of the data present in the Tecplot file. The Python script, named \\verb=Start_Radcal.py=, executes RadCal, reads the output Tecplot file and \\verb=RADCAL.out=, and displays the plots of $\\bar{\\tau}(\\om_0; 0 \\rightarrow s) $ against the wavenumber $\\om$ on the top window, and the spectral evolution of the incident intensity $I_{\\om_0}(s)$ against the wavenumber $\\om$ on the bottom window. The script also prints some integrated quantities and generates automatically a \\verb=pdf= file. In order to use this script, beside Python, the \\verb=matplotlib= library, Ref.~\\cite{Hunter:2007}, is needed. Figure~\\ref{fig:EXAMPLE} plots the spectral transmissivity and the incident spectral intensity for the case given as an example in Subsection~\\ref{sec:input_file} as generated by the \\verb=Start_Radcal.py= script.\n\n\\begin{figure}\n\\includegraphics[width=\\textwidth]{Figures/Example.pdf}\n\\caption{Top: Spectral transmissivity of the medium, in \\%, using the input file given in Subsection~\\ref{sec:input_file}. Bottom: Associated incident spectral intensity, $I_{\\om_0}(s)$, given in $\\rm W/m^{2}/str/cm^{-1}$.\\label{fig:EXAMPLE}}\n\\end{figure}\n", "meta": {"hexsha": "e6818ffdd8cabafe945ff9511796072bf201737f", "size": 13829, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Documentation/Using_RADCAL_Chapter.tex", "max_stars_repo_name": "mcgratta/radcal", "max_stars_repo_head_hexsha": "83cb42ec8f43f243fe3b0b7640f62071b8482129", "max_stars_repo_licenses": ["Linux-OpenIB"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Documentation/Using_RADCAL_Chapter.tex", "max_issues_repo_name": "mcgratta/radcal", "max_issues_repo_head_hexsha": "83cb42ec8f43f243fe3b0b7640f62071b8482129", "max_issues_repo_licenses": ["Linux-OpenIB"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Documentation/Using_RADCAL_Chapter.tex", "max_forks_repo_name": "mcgratta/radcal", "max_forks_repo_head_hexsha": "83cb42ec8f43f243fe3b0b7640f62071b8482129", "max_forks_repo_licenses": ["Linux-OpenIB"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 82.8083832335, "max_line_length": 1088, "alphanum_fraction": 0.7176946995, "num_tokens": 3525, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.297469948832931, "lm_q1q2_score": 0.16951403905847937}} {"text": "% !TEX root = ../00_thesis.tex\n\n\\section{Overview of \\DRP}\n\\label{sec:design_overview}\n\n\\afterpage{\n\\begin{figure}\n \\centering\n \\includegraphics[scale=1]{dpp}\n \\caption{Conceptual view of the DPP, based one the \\bolt processor interconnect. %\n \\capt{%\n Using functions \\emph{\\opwrite}, \\emph{\\opread}, and \\emph{\\opflush}, the application (\\ap) and communication (\\cp) processors can asynchronously exchange messages with predictable latency.\n The \\AP executes application tasks (\\eg sensing, actuation, control, \\etc) while the \\CP is dedicated to radio communication.}}\n \\label{fig:bolt_logical}\n\\end{figure}\n}\n\nThis chapter presents the \\DRPLong (\\DRP), a solution to provide end-to-end real-time guarantees between distributed applications.\nBefore delving into details, this section provides an overview of \\DRP's principles.\n\nThe system model of \\DRP divides the end-to-end communication between local and wireless parts~(\\cref{fig:DRP_sysmodel}):\n\\pagebreak\n\\begin{description}\n \\item[\\AP $\\boldsymbol{\\leftrightarrow}$ \\CP]\n Applications run on dedicated application processors (\\APs) which are isolated from the rest of the network by their attached communication processor (\\CP).\n Local communication between \\APs and \\CPs takes place over the \\bolt interconnect~\\cite{sutton2015Bolt}, which provides asynchronous message passing with bounded delays.\n This device architecture, called the Dual-Processor Platform (\\DPP), is illustrated in \\cref{fig:bolt_logical} (more details in \\cref{ch:introduction}).\n\n \\item[\\CP $\\boldsymbol{\\leftrightarrow}$ \\CP]\n The \\CPs exchange messages over a multi-hop wireless network using the \\blink real-time protocol~\\cite{zimmerling2017Blink}.\n \\blink is adaptive to dynamic changes in traffic demands, energy efficient, and delivers messages in real-time.\n\\end{description}\n\nThe \\DPP and \\blink are key building blocks to fulfill the \\feature{Reliability}, \\feature{Adaptability}, \\feature{Composability}, and \\feature{Efficiency} requirements.\nHowever, two major issues remain in order to achieve \\feature{Timeliness}.\n\n\\squarepar{%}\n First, the communication between \\APs and \\CPs cannot be completely asynchronous: to guarantee end-to-end deadlines, both processors must look for incoming messages with some minimal rate.\n %\n Second, \\blink assumes a periodic release of messages at the network interfaces (\\ie the \\CPs); since our flow model is not periodic but sporadic with jitter~(\\cref{sec:problem}), messages may be delayed in \\CPs buffer until they can be transmitted over the network.%\n}\n\n\\DRP strikes a balance between \\feature{Composability} and \\feature{Efficiency}; that is, between\n\\linebreak\n\\inlineitem decoupling the execution of \\APs, \\CPs, and Blink, \\\\\n\\inlineitem supporting short the end-to-end deadlines between the \\APs.\\\\\nThe idea behind \\DRP is to split the responsibility of meeting end-to-end deadlines between (i)~the source node $n^s_i$ and \\blink, and (ii)~the destination node $n^d_i$;\nIf the source does not write too many messages, \\blink guarantees every message will meet a given network deadline $D$, in turns, the destination commits to read its \\bolt queue sufficiently often to meet the flow's end-to-end deadlines \\deadlineany.\n\n\\squarepar{%}\n \\DRP formalizes these ``commitments'' into \\emph{contracts} between the different entities. The challenge is to define, given the current network state and an end-to-end deadline \\deadlineany to satisfy, what must be\n % \\begin{itemize}\n % \\item\n (i)~the network deadline $D$ requested to \\blink and\n % \\item\n (ii)~the minimal reading rate at the destination node.\n % \\end{itemize}\n The goal is to make these contracts minimally restrictive, such that \\APs, \\CPs, and Blink can operate as much as possible independently from each other (\\feature{Composability}).%\n}\n", "meta": {"hexsha": "ce1b0eed5367714620220ef08e20a56fd111cfdc", "size": 3838, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "40_DRP/4_design.tex", "max_stars_repo_name": "romain-jacob/doctoral-theis", "max_stars_repo_head_hexsha": "fd21e9f0cddeda91821eb061c9ab12df9f610da9", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "40_DRP/4_design.tex", "max_issues_repo_name": "romain-jacob/doctoral-theis", "max_issues_repo_head_hexsha": "fd21e9f0cddeda91821eb061c9ab12df9f610da9", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "40_DRP/4_design.tex", "max_forks_repo_name": "romain-jacob/doctoral-theis", "max_forks_repo_head_hexsha": "fd21e9f0cddeda91821eb061c9ab12df9f610da9", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 63.9666666667, "max_line_length": 269, "alphanum_fraction": 0.7665450756, "num_tokens": 943, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3311197330283893, "lm_q1q2_score": 0.16943946553583705}} {"text": "\\section{Higgs boson processes}\n%\\label{sec:higgs}\n\nIn this section, the set-up of the current ATLAS samples for Higgs boson production in gluon--gluon fusion, \nvector-boson fusion and Higgs-strahlung processes is described.\n\n\\subsection{$H$ via gluon--gluon fusion}\n%\\label{sec:higgs-ggH}\n\n\\subsubsection*{\\texorpdfstring{\\POWPY[8]}{Powheg+Pythia8} samples}\n%\\label{sec:higgs-ggH-samples}\n\n%HGam: https://twiki.cern.ch/twiki/bin/view/Sandbox/RuggeroTurraSandbox\n%ZZ: https://twiki.cern.ch/twiki/bin/view/AtlasProtected/HZZllllRun2MCSamplesMC16#mc16\n%WW: https://twiki.cern.ch/twiki/bin/view/AtlasProtected/HWWMC\n%Hlep:https://twiki.cern.ch/twiki/bin/view/AtlasProtected/HSG4MCrequests2015\n%Hbb: https://twiki.cern.ch/twiki/bin/view/AtlasProtected/HbbMC\n\nThe descriptions below correspond to the samples in Table~\\ref{tab:higgs-ggH-samples}.\n\\begin{table}[!htbp]\n\\begin{center}\n\\caption{\\POWHEG Higgs gluon--gluon fusion samples with \\POWPY[8] for different Higgs boson decay channels.} \\label{tab:higgs-ggH-samples}\n\\begin{tabular}{ l | l | l}\n\\hline\nDSID & Decay channel & Additional comment \\\\\n\\hline\n343981 & $H\\to\\gamma\\gamma$& \\\\\n345316 & $H\\to Z\\gamma$ & \\\\\n345060 & $H\\to ZZ^{*} \\to 4\\ell $ & $\\ell=e,\\mu,\\tau$ \\\\\n345324 & $H\\to WW^{*} \\to 2\\ell2\\nu $ & $p_{{\\textrm T},\\ell1} > 15$~\\GeV\\ and $p_{{\\textrm T},\\ell2} > 5$~\\GeV \\\\\n308284 & $H\\to ZZ^{*}\\to 4\\nu$ & $E_\\text{T}^\\text{miss} > 75$~\\GeV\\\\\n345342 & $H\\to b \\bar{b}$ & \\\\\n345097 & $H\\to\\mu\\mu$ & \\\\\n345120 & $H\\to\\tau\\tau\\to \\ell^{+}\\ell^{-}$ & $p_{{\\textrm T},\\ell1} > 13$~\\GeV\\ and $p_{{\\textrm T},\\ell2} > 7$~\\GeV \\\\\n345121 & $H\\to\\tau\\tau\\to h^{+}\\ell^{-}$ & $p_{{\\textrm T},\\ell} > 15$~\\GeV\\ and $p_{{\\textrm T},h} > 20$~\\GeV\\\\\n345122 & $H\\to\\tau\\tau\\to \\ell^{+}h^{-}$ & $p_{{\\textrm T},\\ell} > 15$~\\GeV\\ and $p_{{\\textrm T},h} > 20$~\\GeV\\\\\n345123 & $H\\to\\tau\\tau\\to h^{+}h^{-}$ & $p_{{\\textrm T},h1} > 30$~\\GeV\\ and $p_{{\\textrm T},h2} > 20$~\\GeV \\\\\n345124 & $H\\to\\tau\\tau\\to \\mu\\tau$ &\\\\ %$p_{\\textrm T},h1 > 30$~GeV and $p_{\\textrm T},h2 > 20$~GeV \n345125 & $H\\to\\tau\\tau\\to e \\tau$ & \\\\ %$p_{\\textrm T},h1 > 30$~GeV and $p_{\\textrm T},h2 > 20$~GeV \n\\hline\n\\end{tabular}\n\\end{center}\n\\end{table}\n\n\n\n\n\n\n\\paragraph{Short description:}\n\nHiggs boson production via gluon--gluon fusion was simulated at next-to-next-to-leading-order (NNLO) accuracy in \nQCD using \\POWHEGBOX[v2]~\\cite{Hamilton:2013fea,Hamilton:2015nsa,Alioli:2010xd,Nason:2004rx,Frixione:2007vw}. \nThe simulation achieved NNLO accuracy for arbitrary inclusive $gg\\to H$ observables by reweighting the Higgs boson \nrapidity spectrum in \\textsc{Hj}-\\MINLO~\\cite{Hamilton:2012np,Campbell:2012am,Hamilton:2012rf} to that of HNNLO~\\cite{Catani:2007vq}.\n%The transverse momentum spectrum of the Higgs boson obtained with this sample was found to be compatible with the fixed-order HNNLO calculation and the Hres2.3 calculation~\\cite{Bozzi:2005wk,deFlorian:2011xf} performing resummation at next-to-next-to- leading-logarithm accuracy matched to a NNLO fixed-order calculation (NNLL+NNLO).\nThe \\PDFforLHC[15nnlo] PDF set~\\cite{Butterworth:2015oua} and the \\AZNLO tune~\\cite{STDM-2012-23} \nof \\PYTHIA[8]~\\cite{Sjostrand:2014zea} were used.\n\nThe gluon--gluon fusion prediction from the Monte Carlo samples was normalised to the \nnext-to-next-to-next-to-leading-order cross-section in QCD plus electroweak corrections \nat next-to-leading order \n(NLO)~\\cite{deFlorian:2016spz,Anastasiou:2016cez,Anastasiou:2015ema,Dulat:2018rbf,Harlander:2009mq,Harlander:2009bw,Harlander:2009my,Pak:2009dg,Actis:2008ug,Actis:2008ts,Bonetti:2018ukf,Bonetti:2018ukf}. The decays of bottom and charm hadrons\nwere performed by \\EVTGEN~\\cite{Lange:2001uf}.\nThe normalisation of all Higgs boson\nsamples accounts for the decay branching ratio calculated with HDECAY~\\cite{Djouadi:1997yw,Spira:1997dg,Djouadi:2006bz}\nand \\PROPHECY~\\cite{Bredenstein:2006ha,Bredenstein:2006rh,Bredenstein:2006nk}.\n\n\n\\paragraph{Long description:}\n\nHiggs boson production via gluon--gluon fusion was simulated at next-to-next-to-leading-order (NNLO) accuracy in QCD using \n\\POWHEGBOX[v2]~\\cite{Hamilton:2013fea,Hamilton:2015nsa,Alioli:2010xd,Nason:2004rx,Frixione:2007vw}. The simulation achieved NNLO\naccuracy for arbitrary inclusive $gg\\to H$ observables by reweighting the Higgs boson rapidity spectrum \nin \\textsc{Hj}-\\MINLO~\\cite{Hamilton:2012np,Campbell:2012am,Hamilton:2012rf} to that of HNNLO~\\cite{Catani:2007vq}. The transverse momentum\nspectrum of the Higgs boson obtained with this sample was found to be compatible with the fixed-order HNNLO calculation and the\n\\HRES[2.3] calculation~\\cite{Bozzi:2005wk,deFlorian:2011xf} performing resummation at next-to-next-to-leading-logarithm accuracy\nmatched to a NNLO fixed-order calculation (NNLL+NNLO). \nTop- and bottom-quark mass effects were included up to next-to-leading order (NLO).\n\nThe renormalisation and factorisation scales were set to half of the Higgs boson mass and the \\PDFforLHC[15nnlo] PDF\nset~\\cite{Butterworth:2015oua} was used. The matrix elements were matched to the parton shower of \\PYTHIA[8]~\\cite{Sjostrand:2014zea}\nwhich uses the AZNLO tune~\\cite{STDM-2012-23}. The decays of bottom and charm hadrons\nwere performed by \\EVTGEN~\\cite{Lange:2001uf}.\n\nThe QCD scale uncertainties were obtained using nine-point scale variations of the NLO renormalisation and factorisation scales and applying the NNLO reweighting to those variations, including up and down variations of $\\muR=\\muF$ around the central value for the NNLO part, yielding a total of 27 scale variations.\nPDF and \\alphas uncertainties were estimated using the \\PDFforLHC[15nlo] set of eigenvectors.\nThe envelope of the resulting 27 scale variations was taken to estimate the QCD scale uncertainty. \nUncertainties were also provided for switching off bottom- and top-quark mass effects.\n%From YR4\n\nThe prediction from the Monte Carlo samples was normalised to the next-to-next-to-next-to-leading-order \ncross-section in QCD in the infinite top-quark mass \nlimit~\\cite{deFlorian:2016spz,Anastasiou:2016cez,Anastasiou:2015ema,Dulat:2018rbf,Aglietti:2004nj} and including exact \ncorrections for all finite quark-mass effects at NLO in QCD as well as NLO electroweak \neffects~\\cite{Actis:2008ug,Bonetti:2018ukf}. Additionally, corrections to the inverse of the top-quark mass were taken \ninto account at NNLO~\\cite{Harlander:2009mq,Harlander:2009bw,Harlander:2009my,Pak:2009dg}. \nThe normalisation of all Higgs boson samples accounts for the decay branching ratio calculated with \nHDECAY~\\cite{Djouadi:1997yw,Spira:1997dg,Djouadi:2006bz}\nand \\PROPHECY~\\cite{Bredenstein:2006ha,Bredenstein:2006rh,Bredenstein:2006nk}.\n\n\n\\subsection{$H$ via vector-boson fusion}\n%\\label{sec:higgs-VBF}\n\n\\subsubsection*{\\texorpdfstring{\\POWPY[8]}{Powheg+Pythia8} samples}\n%\\label{sec:higgs-VBF-samples}\nThe descriptions below correspond to the samples in Table~\\ref{tab:higgs-VBF-samples}.\n\\begin{table}[!htbp]\n\\begin{center}\n\\caption{\\POWPY[8] Higgs vector-boson fusion samples for different Higgs boson decay channels.} \\label{tab:higgs-VBF-samples}\n\\begin{tabular}{ l | l | l}\n\\hline\nDSID & Decay channel & Additional comment \\\\\n\\hline\n346317 & $H\\to$ all & \\\\\n346214 & $H\\to\\gamma\\gamma$& \\\\\n345833 & $H\\to Z\\gamma$ & $Z\\to \\ell^{+}\\ell^{-}$\\\\\n345834 & $H\\to \\gamma\\gamma^{*}$ & $\\gamma^{*}\\to \\ell^{+}\\ell^{-}$\\\\\n346228 & $H\\to ZZ^{*} \\to 4\\ell $ & $\\ell=e,\\mu$ \\\\\n450576 & $H\\to ZZ^{*} \\to 2\\ell2b $ & \\\\\n345948& $H\\to WW^{*} \\to 2\\ell2\\nu $ & $p_{{\\textrm T},\\ell1} > 15$~\\GeV\\ and $p_{{\\textrm T},\\ell2} > 5$~\\GeV \\\\\n346600& $H\\to ZZ^{*}\\to 4\\nu$ & $\\MET>75$~\\GeV\\\\\n345949 & $H\\to b \\bar{b}$ & \\\\\n% & $H\\to\\mu\\mu$ & \\\\\n346190& $H\\to\\tau\\tau\\to \\ell^{+}\\ell^{-}$ & $p_{{\\textrm T},\\ell1} > 13$~\\GeV\\ and $p_{{\\textrm T},\\ell2} > 7$~\\GeV \\\\\n346191 & $H\\to\\tau\\tau\\to h^{+}\\ell^{-}$ & $p_{{\\textrm T},\\ell} > 15$~\\GeV\\ and $p_{{\\textrm T},h} > 20$~\\GeV\\\\\n346192 & $H\\to\\tau\\tau\\to \\ell^{+}h^{-}$ & $p_{{\\textrm T},\\ell} > 15$~\\GeV\\ and $p_{{\\textrm T},h} > 20$~\\GeV\\\\\n346193 & $H\\to\\tau\\tau\\to h^{+}h^{-}$ & $p_{{\\textrm T},h1} > 30$~\\GeV\\ and $p_{{\\textrm T},h2} > 20$~\\GeV \\\\\n346194 & $H\\to\\tau\\tau\\to e\\tau$ & \\\\%$p_{\\textrm T},l1 > 10$~GeV and $p_{\\textrm T},h1 > 20$~GeV \\\\\n346195 & $H\\to\\tau\\tau\\to \\mu\\tau$ & \\\\%$p_{\\textrm T},l1 > 10$~GeV and $p_{\\textrm T},h1 > 20$~GeV \\\\\n\\hline\n\\end{tabular}\n\\end{center}\n\\end{table}\n\n\n\\paragraph{Short description:}\nHiggs boson production via vector-boson fusion was simulated with\n\\POWHEGBOX[v2]~\\cite{Nason:2009ai,Alioli:2010xd,Nason:2004rx,Frixione:2007vw} \nand interfaced with \\PYTHIA[8]~\\cite{Sjostrand:2014zea} for parton shower and non-perturbative effects,\nwith parameters set according to the \\AZNLO tune~\\cite{STDM-2012-23}.\nThe \\POWHEGBOX prediction is accurate to next-to-leading order (NLO) and uses\nthe \\PDFforLHC[15nlo] PDF set~\\cite{Butterworth:2015oua}. \n%It was tuned to match calculations with effects due to finite heavy-quark masses \n%and soft-gluon resummation up to NNLL.\nIt was normalised to an approximate-NNLO QCD cross-section \nwith NLO electroweak corrections~\\cite{Ciccolini:2007jr,Ciccolini:2007ec,Bolzoni:2010xr}.\nThe decays of bottom and charm hadrons were performed by \\EVTGEN~\\cite{Lange:2001uf}.\nThe normalisation of all Higgs boson samples accounts for the decay branching ratio calculated \nwith \\textsc{HDECAY}~\\cite{Djouadi:1997yw,Spira:1997dg,Djouadi:2006bz} \nand \\PROPHECY~\\cite{Bredenstein:2006ha,Bredenstein:2006rh,Bredenstein:2006nk}.\n\n\n\n\n\\paragraph{Long description:}\nHiggs boson production via vector-boson fusion was simulated with\n\\POWHEGBOX[v2]~\\cite{Nason:2009ai,Alioli:2010xd,Nason:2004rx,Frixione:2007vw}. A factorised approximation, where cross-talk between the\nfermion lines is neglected, was used. The implementation is based on the respective NLO QCD calculations for genuine $W/Z$ vector-boson\nfusion topologies (VBF approximation). Quark--antiquark annihilation and interference contributions \nbetween $t$- and $u$-channel contributions were disregarded.\n%External fermion masses are neglected throughout. For the choice of renormalisation andfactorisation scales, various options are available. For this report, fixed scales,μF=μR=MW, areused, and contributions from external bottom and top quarks are entirely disregarded.\n\nThe renormalisation and factorisation scales were set to the $W$ boson mass and the \\PDFforLHC[15nlo] PDF set~\\cite{Butterworth:2015oua}\nwas used. The matrix elements were matched to the parton shower of \\PYTHIA[8]~\\cite{Sjostrand:2014zea} which uses the \\AZNLO\ntune~\\cite{STDM-2012-23}. A dipole-recoil strategy was used for the parton shower.The decays of bottom and charm hadrons\nwere performed by \\EVTGEN~\\cite{Lange:2001uf}.%, which provides a better agreement than other recoil schemes with the NNLO predictions of proVBFH (not included in the HiggsReference twiki). % cite https://arxiv.org/pdf/1710.00391.pdf ?,\n\n\n%The samples include weight variations evaluated on-the-fly for the estimation of QCD scale, PDF- and \\alphas-induced uncertainties. \nThe QCD scales \\muR and \\muF were varied independently by factors of 0.5 and 2.0, both in the matrix element \nand in the parton shower.\n\nThe prediction from the \\POWHEGBOX sample was normalised to the next-to-next-to-leading-order cross-section in QCD \nusing the VBF approximation~\\cite{Ciccolini:2007jr,Ciccolini:2007ec,Bolzoni:2010xr}. Relative \nnext-to-leading-order electroweak corrections were also taken into account for the $t$- and $u$-channel contribution \nconsidered in the VBF approximation. The normalisation of all Higgs boson samples accounts for the decay branching \nratio calculated with \\textsc{HDECAY}~\\cite{Djouadi:1997yw,Spira:1997dg,Djouadi:2006bz} and \n\\PROPHECY~\\cite{Bredenstein:2006ha,Bredenstein:2006rh,Bredenstein:2006nk}. \n\n\n\\subsection{$VH$}\n%\\label{sec:higgs-VH}\n\nThis section describes the generation details of nominal samples for Higgs-strahlung production.\n\n\\subsubsection*{\\texorpdfstring{\\POWPY[8]}{Powheg+Pythia8} samples}\n%\\label{sec:higgs-VH-samples}\nThe descriptions below correspond to the samples in Tables~\\ref{tab:higgs-ZH-samples} to \\ref{tab:higgs-ggZH-samples}.\n\n\\begin{table}[!htbp]\n\\begin{center}\n\\caption{\\POWPY[8] samples of Higgs boson production in association with a $Z$ boson for different Higgs boson decay channels} \n\\label{tab:higgs-ZH-samples}\n\\begin{tabular}{ l | l | l}\n\\hline\nDSID & Decay channel & Additional comment \\\\\n\\hline\n345038 & $H\\to ZZ^{*} \\to 4\\ell$ & $Z\\to$ all\\\\\n345319 & $H\\to \\gamma\\gamma$ & $Z\\to$ all\\\\\n345322 & $H\\to Z\\gamma$ & $Z\\to$ all\\\\\n345103 & $H\\to\\mu\\mu$ & $Z\\to$ all\\\\ \n345217 & $H\\to\\tau\\tau$& $Z\\to$ all\\\\ \n345218 & $H\\to e\\tau$ &$Z\\to$ all\\\\\n345219 & $H\\to \\mu\\tau$&$Z\\to$ all\\\\\n345445 &$H\\to WW^{*} \\to 2\\ell2\\nu $ & $Z\\to$ all \\\\\n345876 & $H\\to ee$ &$Z\\to$ all \\\\\n345965 & $H\\to \\gamma\\gamma^{*}$ & $\\gamma^{*}\\to \\ell^{+}\\ell^{-}$; $Z\\to$ all\\\\\n346310 & $H\\to$ all&$Z\\to$ all\\\\\n346607 & $H\\to ZZ^{*} \\to 4\\nu $ &$Z\\to \\ell^{+}\\ell^{-}$ \\\\\n345055 & $H\\to b\\bar{b}$ & $p_{{\\textrm T},Z}$ enhancement; $Z\\to \\ell^{+}\\ell^{-}$\\\\\n345111 & $H\\to c\\bar{c}$ & $p_{{\\textrm T},Z}$ enhancement; $Z\\to \\ell^{+}\\ell^{-}$\\\\\n345337 & $H\\to WW^{*} \\to 2\\ell2\\nu $ &$p_{{\\textrm T},Z}$ enhancement; $Z\\to \\ell^{+}\\ell^{-}$\\\\\n346326 & $H\\to\\tau\\tau$& $p_{{\\textrm T},Z}$ enhancement; $Z\\to \\ell^{+}\\ell^{-}$\\\\\n346693 & $H\\to ZZ^{*} \\to 4\\nu $ & $p_{{\\textrm T},Z}$ enhancement; $Z\\to \\ell^{+}\\ell^{-}$\\\\\n345056 & $H\\to b\\bar{b}$ & $p_{{\\textrm T},Z}$ enhancement; $Z\\to \\nu\\bar{\\nu}$\\\\\n345112 & $H\\to c\\bar{c}$ & $p_{{\\textrm T},Z}$ enhancement; $Z\\to \\nu\\bar{\\nu}$\\\\\n345445 & $H\\to WW^{*} \\to 2\\ell2\\nu$ & $p_{{\\textrm T},Z}$ enhancement; $Z\\to \\nu\\bar{\\nu}$\\\\\n\\hline\n\\end{tabular}\n\\end{center}\n\\end{table}\n\n\n\\begin{table}[!htbp]\n\\begin{center}\n\\caption{ \\POWPY[8] samples of Higgs boson production in association with a $W^{+}$ boson for different Higgs boson decay channels} \n%\\label{tab:higgs-WpH-samples}\n\\begin{tabular}{ l | l | l}\n\\hline\nDSID & Decay channel & Additional comment \\\\\n\\hline\n345039 & $H\\to ZZ^{*} \\to 4\\ell$ & $W^{+}\\to$ all\\\\\n345318 & $H\\to \\gamma\\gamma$ & $W^{+}\\to$ all\\\\\n345104 & $H\\to \\mu\\mu$ & $W^{+}\\to$ all\\\\\n345212 & $H\\to \\tau\\tau$ & $W^{+}\\to$ all\\\\\n345214 & $H\\to e \\tau $ & $W^{+}\\to$ all\\\\\n345216 & $H\\to \\mu \\tau $ & $W^{+}\\to$ all\\\\\n345321 & $H\\to Z\\gamma$ & $W^{+}\\to$ all\\\\\n345325 & $H\\to WW^{*} \\to 2\\ell2\\nu $ & $W^{+} \\to q\\bar{q}$ \\\\\n345877 & $H\\to e^{+}e^{-}$ & $W^{+}\\to$ all\\\\\n345964 & $H\\to \\gamma\\gamma^{*}$ & $\\gamma^{*}\\to \\ell^{+}\\ell^{-}$; $W^{+}\\to$ all\\\\\n346311 & $H\\to$ all & $W^{+}\\to$ all\\\\ \n346605 & $H\\to ZZ^{*} \\to 4\\nu $ & $W^{+}\\to$ all\\\\\n346699 & $H \\to 4\\ell$ & interfaced to PROPHECY4F \\\\\n346705 & $H \\to 4\\ell$ & interfaced to Hto4l \\\\\n345054 & $H\\to b\\bar{b}$ & $p_{{\\textrm T},W}$ enhancement; $W^{+}\\to \\ell^{+}\\nu$ \\\\\n345110 & $H\\to c\\bar{c}$ & $p_{{\\textrm T},W}$ enhancement; $W^{+}\\to \\ell^{+}\\nu$ \\\\\n345327 & $H\\to WW^{*} \\to 2\\ell2\\nu$ & $p_{{\\textrm T},W}$ enhancement; $W^{+}\\to \\ell^{+}\\nu$ \\\\ \n346561 & $H\\to WW^{*} \\to q\\bar{q}\\ell\\nu$ & $p_{{\\textrm T},W}$ enhancement; $W^{+}\\to \\ell^{+}\\nu$ \\\\\n346325 & $H\\to \\tau\\tau$ & $p_{{\\textrm T},W}$ enhancement; $W^{+}\\to \\ell^{+}\\nu$ \\\\\n346729 & $H\\to ZZ^{*} \\to 4\\nu$ & $p_{{\\textrm T},W}$ enhancement; $W^{+}\\to \\ell^{+}\\nu$ \\\\\n\\hline\n\\end{tabular}\n\\end{center}\n\\end{table}\n\n\\begin{table}[!htbp]\n\\begin{center}\n\\caption{\\POWPY[8] samples of Higgs boson production in association with a $W^{-}$ boson for different Higgs boson decay channels} \n%\\label{tab:higgs-WmH-samples}\n\\begin{tabular}{ l | l | l}\n\\hline\nDSID & Decay channel & Additional comment \\\\\n\\hline\n345040 & $H\\to ZZ^{*} \\to 4\\ell$ & $W^{-}\\to$ all\\\\\n345317 & $H\\to \\gamma\\gamma$ & $W^{-}\\to$ all\\\\\n345105 & $H\\to \\mu\\mu$ & $W^{-}\\to$ all\\\\\n345211 & $H\\to \\tau\\tau$ & $W^{-}\\to$ all\\\\\n345213 & $H\\to e \\tau $ & $W^{-}\\to$ all\\\\\n345215 & $H\\to \\mu \\tau $ & $W^{-}\\to$ all\\\\\n345320 & $H\\to Z\\gamma$ & $W^{-}\\to$ all\\\\\n345333 & $H\\to WW^{*} \\to 2\\ell2\\nu $ & $W^{-} \\to q\\bar{q}$ \\\\\n345878 & $H\\to e^{+}e^{-}$ & $W^{-}\\to$ all\\\\\n345963 & $H\\to \\gamma\\gamma^{*}$ & $\\gamma^{*}\\to \\ell^{+}\\ell^{-}$; $W^{-}\\to$ all\\\\\n346312 & $H\\to$ all & $W^{-}\\to$ all\\\\ \n346606 & $H\\to ZZ^{*} \\to 4\\nu $ & $W^{-}\\to$ all\\\\\n346700 & $H \\to 4\\ell$ & interfaced to PROPHECY4F \\\\\n346706 & $H \\to 4\\ell$ & interfaced to Hto4l \\\\\n345053 & $H\\to b\\bar{b}$ & $p_{{\\textrm T},W}$ enhancement; $W^{-}\\to \\ell^{-}\\bar{\\nu}$ \\\\\n345109 & $H\\to c\\bar{c}$ & $p_{{\\textrm T},W}$ enhancement; $W^{-}\\to \\ell^{-}\\bar{\\nu}$ \\\\\n345326 & $H\\to WW^{*} \\to 2\\ell2\\nu$ & $p_{{\\textrm T},W}$ enhancement; $W^{-}\\to \\ell^{-}\\bar{\\nu}$ \\\\\n346560 & $H\\to WW^{*} \\to q\\bar{q}\\ell\\nu$ & $p_{{\\textrm T},W}$ enhancement; $W^{-}\\to \\ell^{-}\\bar{\\nu}$ \\\\\n346324 & $H\\to \\tau\\tau$ & $p_{{\\textrm T},W}$ enhancement; $W^{-}\\to \\ell^{-}\\bar{\\nu}$ \\\\\n346730 & $H\\to ZZ^{*} \\to 4\\nu$ & $p_{{\\textrm T},W}$ enhancement; $W^{-}\\to \\ell^{-}\\bar{\\nu}$ \\\\\n\\hline\n\\end{tabular}\n\\end{center}\n\\end{table}\n\n\\begin{table}[!htbp]\n\\begin{center}\n\\caption{\\POWPY[8] samples of loop-induced Higgs boson production in association with a $Z$ boson for different\nHiggs boson decay channels} \n\\label{tab:higgs-ggZH-samples}\n\\begin{tabular}{ l | l | l}\n\\hline\nDSID & Decay channel & Additional comment \\\\\n\\hline\n345061 & $H\\to \\gamma\\gamma$ & $Z\\to$ all \\\\\n345066 & $H\\to ZZ^{*} \\to 4\\ell$ & $Z\\to$ all \\\\\n345098 & $H\\to \\mu\\mu$ & $Z\\to$ all \\\\\n345596 & $H\\to ZZ^{*} \\to 4\\nu$ & $Z\\to$ all \\\\\n346524 & $H\\to WW^{*} \\to 2\\ell2\\nu $ & $Z\\to$ all \\\\\n346697 & $H\\to ZZ^{*} \\to 4\\nu$ & interfaced to PROPHECY4F \\\\\n346703 & $H\\to ZZ^{*} \\to 4\\nu$ & interfaced to Hto4l \\\\\n345057 & $H\\to b\\bar{b}$ & $Z\\to \\ell^{+}\\ell^{-}$\\\\ \n345113 & $H\\to c\\bar{c}$ & $Z\\to \\ell^{+}\\ell^{-}$\\\\\n345446 & $H\\to WW^{*} \\to 2\\ell2\\nu$ & $Z\\to \\ell^{+}\\ell^{-}$\\\\\n346329 & $H\\to \\tau\\tau$ & $Z\\to \\ell^{+}\\ell^{-}$\\\\\n346694 & $H\\to ZZ^{*} \\to 4\\nu$ & $Z\\to \\ell^{+}\\ell^{-}$\\\\\n345058 & $ H\\to b\\bar{b}$ & $Z\\to \\nu\\bar{\\nu}$\\\\\n345114 & $ H\\to c\\bar{c}$ & $Z\\to \\nu\\bar{\\nu}$\\\\\n\\hline\n\\end{tabular}\n\\end{center}\n\\end{table}\n\n\n\n\n\n\\paragraph{Short description:}\n\nHiggs boson production in association with a vector boson was simulated using\n\\POWHEGBOX[v2]~\\cite{Nason:2009ai,Alioli:2010xd,Nason:2004rx,Frixione:2007vw} and interfaced with \\PYTHIA[8]~\\cite{Sjostrand:2014zea} for\nparton shower and non-perturbative effects. The \\POWHEGBOX prediction is accurate to next-to-leading order for $VH$ boson plus one-jet production. \nThe loop-induced $gg\\to ZH$ process was generated separately at leading order. The \\PDFforLHC[15nlo] PDF\nset~\\cite{Butterworth:2015oua} and the \\AZNLO tune~\\cite{STDM-2012-23} of \\PYTHIA[8]~\\cite{Sjostrand:2014zea} were used. The decays of bottom and charm hadrons\nwere performed by \\EVTGEN~\\cite{Lange:2001uf}. The Monte Carlo\nprediction was normalised to cross-sections calculated at NNLO in QCD with NLO electroweak corrections for $q\\bar{q}/qg \\to VH$ and at NLO\nand next-to-leading-logarithm accuracy in QCD for $gg \\to\nZH$~\\cite{Ciccolini:2003jy,Brein:2003wg,Brein:2011vx,Altenkamp:2012sx,Denner:2014cla,Brein:2012ne,Harlander:2014wda}. The\nnormalisation of all Higgs boson samples accounts for the decay branching ratio calculated with \nHDECAY~\\cite{Djouadi:1997yw,Spira:1997dg,Djouadi:2006bz} and \\PROPHECY~\\cite{Bredenstein:2006ha,Bredenstein:2006rh,Bredenstein:2006nk}.\n\n\n\n\\paragraph{Long description:}\nHiggs boson production in association with a vector boson was simulated using\n\\POWHEGBOX[v2]~\\cite{Nason:2009ai,Alioli:2010xd,Nason:2004rx,Frixione:2007vw}. The computation was carried out using the\n\\MINLO~\\cite{Luisoni:2013cuh} prescription, which achieves NLO accuracy for the $VH$ and $VH$ boson plus one-jet production\ninclusive distributions and dictates the choice of renormalisation and factorisation scales. Virtual amplitudes were constructed\nthrough the interface to the \\GOSAM package~\\cite{Cullen:2011ac}. The loop-induced $gg\\to ZH$ process was generated separately at\nleading order with \\POWHEGBOX. In all cases, the \\PDFforLHC[15nlo] PDF set~\\cite{Butterworth:2015oua} was used.\n\nThe matrix elements were matched to the parton shower of \\PYTHIA[8]~\\cite{Sjostrand:2014zea} which uses the \\AZNLO\ntune~\\cite{STDM-2012-23}. The decays of bottom and charm hadrons were performed by \\EVTGEN~\\cite{Lange:2001uf}.\n%The samples include weight variations evaluated on-the-fly for the estimation of QCD scale, PDF- and \\alphas-induced uncertainties. \nThe QCD scales \\muR and \\muF were varied independently by factors of 0.5 and 2.0 to account for their uncertainties.\n\nThe predictions from \\POWHEGBOX were normalised to the best available theoretical prediction. The $q\\bar{q}/qg \\to VH$ cross-sections\nwere calculated at NNLO in QCD with NLO electroweak corrections and the $gg \\to ZH$ cross-sections were calculated at NLO and \nnext-to-leading-logarithm accuracy~\\cite{Ciccolini:2003jy,Brein:2003wg,Brein:2011vx,Altenkamp:2012sx,Denner:2014cla,Brein:2012ne,Harlander:2014wda}. \nThe normalisation of the $q\\bar{q}\\to ZH$ samples was extracted from the subtraction of the latter from the former. \nDifferential NLO EW corrections were available from the \\textsc{HAWK} program~\\cite{Denner:2014cla} to be applied to \n$q\\bar{q}$-initiated $VH$ production as a function of the vector boson's transverse momentum.\nThe normalisation of all Higgs boson samples accounts for the decay branching ratio calculated with\n\\textsc{HDECAY}~\\cite{Djouadi:1997yw,Spira:1997dg,Djouadi:2006bz} and \n\\PROPHECY~\\cite{Bredenstein:2006ha,Bredenstein:2006rh,Bredenstein:2006nk}.\n\n\n", "meta": {"hexsha": "87872c60b3ecaf8ac20f5f5e3f3494afcdf3231a", "size": 21588, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "template/MC_snippets/Higgs.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/Higgs.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/Higgs.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": 59.3076923077, "max_line_length": 334, "alphanum_fraction": 0.6962201223, "num_tokens": 8170, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.3174262720448507, "lm_q1q2_score": 0.1686198110653126}} {"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% This work is licensed under the Creative Commons Attribution 4.0 International %\n% License. To view a copy of this license, visit %\n% http://creativecommons.org/licenses/by/4.0/. %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\documentclass[11pt]{article}\n\\usepackage[cm]{fullpage}\n%%AVC PACKAGES\n\\usepackage{avcgreek}\n\\usepackage{avcfonts}\n\\usepackage{avcmath}\n\\usepackage[numberby=section,skip=9pt plus 2pt minus 5pt]{avcthm}\n\\usepackage{qcmacros}\n\\usepackage{goldstone}\n%%MACROS FOR THIS DOCUMENT\n\\numberwithin{equation}{section}\n\\usepackage[\n margin=1.5cm,\n includefoot,\n footskip=30pt,\n headsep=0.2cm,headheight=1.3cm\n]{geometry}\n\\usepackage{fancyhdr}\n\\pagestyle{fancy}\n\\fancyhf{}\n\\fancyhead[LE,RO]{Quiz 6, Handout 1: Perturbation Theory}\n\\fancyfoot[CE,CO]{\\thepage}\n\\usepackage{url}\n\\makeatother\n\\newcommand{\\resolventline}[2][1]{\n \\tikz[overlay]{\n \\draw[thick,flexdotted] (0,-1ex) to ++(0,#1*4.5ex) node[above,inner sep=1pt] {#2};\n }\n}\n\n\\begin{document}\n\n\n\\setcounter{section}{5}\n\\section{Perturbation theory}\n\n\\begin{dfn}\n\\thmtitle{Model Hamiltonian}\nThe electronic Hamiltonian\\footnote{For the sake of brevity I will here refer to $H_\\mr{c}$ as ``the electronic Hamiltonian''. We could also use $H=E_0+H_\\mr{c}$, which will simply shift some of the equations by a constant.} can be expressed as the sum of a \\textit{zeroth order} or \\textit{``model''~Hamiltonian} $H_0$ and a \\textit{perturbation} $V_\\mr{c}$, known as the \\textit{fluctuation potential}.\nFor well-behaved electronic systems, a common choice for the model Hamiltonian is the diagonal part of the Fock operator.\n\\begin{align}\n\\label{eq:diagonal-fock-model-hamiltonian}\n H_0\n\\equiv\n f_p^p\n \\tl{a}^p_p\n&&\n V_\\mr{c}\n\\equiv\n f_p^q\n (\n 1\n -\n \\d_p^q\n )\n \\tl{a}^p_q\n+\n \\tfr{1}{4}\n \\ol{g}_{pq}^{rs}\n \\tl{a}^{pq}_{rs}\n\\end{align}\nThis choice of $H_0$ brings the advantage that its eigenbasis is the standard basis of determinants.\n\\begin{align}\n\\label{eq:model-problem}\n H_0\n \\F\n=\n 0\\,\n \\F\n&&\n H_0\n \\F_{i_1\\cd i_k}^{a_1\\cd a_k}\n=\n \\mc{E}_{i_1\\cd i_k}^{a_1\\cd a_k}\n \\F_{i_1\\cd i_k}^{a_1\\cd a_k}\n&&\n \\mc{E}_{q_1\\cd q_k}^{p_1\\cd p_k}\n\\equiv\n \\sum_{r=1}^k\n f_{p_r}^{p_r}\n-\n \\sum_{r=1}^k\n f_{q_r}^{q_r}\n\\end{align}\nIn general the model Hamiltonian is chosen to make the matrix representation of $H_\\mr{c}$ in the model eigenbasis diagonally dominant.\\footnote{See \\url{https://en.wikipedia.org/wiki/Diagonally_dominant_matrix}.}\nOur choice of $H_0$ is appropriate for \\textit{weakly correlated systems}, where the reference determinant can be chosen to satisfy $\\ip{\\F|\\Y}\\gg \\ip{\\F_{i_1\\cd i_k}^{a_1\\cd a_k}|\\Y}$ for all substituted determinants.\nIn this context it is convenient to employ intermediate normalization for the wavefunction, which will be assumed from here on out.\n\\end{dfn}\n\n\n\\begin{dfn}\n\\thmtitle{Perturbation theory}\n\\textit{Perturbation theory} analyzes the polynomial order with which the wavefunction and its observables depend on the fluctuation potential.\nFor this purpose, we define a continuous series of Hamiltonians\n$\n H(\\la)\n\\equiv\n H_0\n+\n \\la\n V_\\mr{c}\n$\nparametrized by a \\textit{strength parameter} $\\la$ that smoothly toggles between the model Hamiltonian at $\\la=0$ to the exact one at $\\la=1$.\nThe \\textit{$m\\eth$-order contribution} to a quantity $X$ is then defined as the $m\\eth$ coefficient in its Taylor series about $\\la=0$, denoted $X\\ord{m}$.\nIn particular, the wavefunction and correlation energy can be expanded as follows.\n\\begin{align}\n\\label{eq:series-schrodinger-equation}\n \\Y\n=\n \\sum_{m=0}^\\infty\n \\Y\\ord{m}\n&&\n E_\\mr{c}\n=\n \\sum_{m=0}^\\infty\n E_\\mr{c}\\ord{m}\n&&\n \\Y\\ord{m}\n\\equiv\n \\fr{1}{m!}\n \\left.\n \\pd{^m\\Y(\\la)}{\\la^m}\n \\right|_{\\la=0}\n&&\n E_\\mr{c}\\ord{m}\n\\equiv\n \\fr{1}{m!}\n \\left.\n \\pd{^mE(\\la)}{\\la^m}\n \\right|_{\\la=0}\n&&\n H(\\la)\n \\Y(\\la)\n=\n E(\\la)\n \\Y(\\la)\n\\end{align}\nThe order(s) at which a term contributes to the wavefunction or energy provides one measure of its relative importance.\n\\end{dfn}\n\n\\begin{rmk}\nProjecting the Schr\\\"odinger equation by $\\F$ and using eq~\\ref{eq:model-problem}, along with intermediate normalization, implies\n\\begin{align}\n E_\\mr{c}\n=\n \\ip{\\F|V_\\mr{c}|\\Y}\n\\hspace{20pt}\n\\implies\n\\hspace{20pt}\n E_\\mr{c}\\ord{m+1}\n=\n \\ip{\\F|V_\\mr{c}|\\Y\\ord{m}}\n\\end{align}\nwhere the equation on the right follows from generalizing the energy expression to\n$\n E(\\la)\n=\n \\ip{\\F|\\la V_\\mr{c}|\\Y(\\la)}\n$.\nIn words, this says that the $m\\eth$-order wavefunction contribution determines the $(m+1)\\eth$-order energy contribution.\nThis immediately identifies the first-order energy as\n$\n E_\\mr{c}\\ord{1}\n=\n \\ip{\\F|V_\\mr{c}|\\F}\n=\n 0\n$,\nsince $V_\\mr{c}$ consists of $\\F$-normal-ordered operators.\n\\end{rmk}\n\n\\begin{dfn}\n\\thmtitle{Model space projection operator}\nThe projection onto the reference determinant, $P=\\kt{\\F}\\br{\\F}$, is termed the \\textit{model space projection operator}.\nIts complement is the \\textit{orthogonal space projection operator}.\\footnote{$1_n\\equiv 1|_{\\mc{F}_n}$ is the identity on $\\mc{F}_n$, which is equivalent to a projection onto this subspace. For our purposes, this is the identity.}\n\\begin{align}\n\\label{eq:orthogonal-space-projection-operator}\n Q\n\\equiv\n 1_n\n-\n P\n=\n \\sum_k\n \\pr{\n \\tfr{1}{k!}\n }^2\n \\sum_{\\substack{a_1\\cd a_k\\\\i_1\\cd i_k}}\n \\kt{\\F_{i_1\\cd i_k}^{a_1\\cd a_k}}\n \\br{\\F_{i_1\\cd i_k}^{a_1\\cd a_k}}\n\\end{align}\nNote that $P$ and $Q$ satisfy the following relationships, which are characteristic of complementary projection operators.\n\\begin{align}\n P\n+\n Q\n=\n 1_n\n&&\n P^2\n=\n P\n&&\n Q^2\n=\n Q\n&&\n PQ\n=\n QP\n=\n 0\n\\end{align}\nDue to intermediate normalization, we also have that\n$\n P\\Y\n=\n \\F\n$\nand\n$\n Q\\Y\n=\n \\Y\n-\n \\F\n$.\n\\end{dfn}\n\n\\begin{samepage}\n\\begin{dfn}\n\\thmtitle{Resolvent}\nThe \\textit{resolvent},\n$\n R_0\n\\equiv\n (-H_0)^{-1}Q\n$, is the negative\\footnote{The annoying sign factor is required for consistency with $R(\\zeta)\\equiv(\\zeta-H_0)^{-1}Q$, which is a more general definition of the resolvent.} inverse of $H_0$ in the orthogonal space.\\footnote{Note that this implies $R_0P=0$ and $R_0Q=R_0$.}\n\\begin{align}\n\\label{eq:resolvent-spectral-decomposition}\n R_0\n \\F\n=\n 0\n \\F\n&&\n R_0\n \\F_{i_1\\cd i_k}^{a_1\\cd a_k}\n=\n (\\mc{E}_{a_1\\cd a_k}^{i_1\\cd i_k})^{-1}\n \\F_{i_1\\cd i_k}^{a_1\\cd a_k}\n&&\n R_0\n=\n \\sum_k\n \\pr{\\tfr{1}{k!}}^2\n \\sum_{\\substack{a_1\\cd a_k\\\\i_1\\cd i_k}}\n \\fr{\n \\kt{\\F_{i_1\\cd i_k}^{a_1\\cd a_k}}\n \\br{\\F_{i_1\\cd i_k}^{a_1\\cd a_k}}\n }{\n \\mc{E}_{a_1\\cd a_k}^{i_1\\cd i_k}\n }\n\\end{align}\nThe equation on the right is the spectral decomposition of the resolvent.\\footnote{This follows from the eigenvalue equations, but you can derive it explicitly by substituting equation~\\ref{eq:orthogonal-space-projection-operator} into $R_0=(-H_0)^{-1}Q$.}\nRestriction to the orthogonal space is necessary because $H_0$ is singular in the model space, which means that $H_0^{-1}$ does not exist there.\n\\end{dfn}\n\\end{samepage}\n\n\\begin{samepage}\n\\begin{rmk}\n\\thmtitle{A recursive solution to the Schr\\\"odinger equation}\nOperating $R_0$ on $H(\\la)\\Y(\\la)=E(\\la)\\Y(\\la)$ gives\\footnote{This follows from $R_0H_0\\Y=-Q\\Y=-\\Y+\\F$.}\n\\begin{align}\n\\label{eq:lambda-dependent-recursive-series}\n \\Y(\\la)\n=\n \\F\n+\n R_0\n (\n \\la V_\\mr{c}\n -\n E(\\la)\n )\n \\Y(\\la)\n\\end{align}\nwhich provides a recursive equation for $\\Y(\\la)$ that can be used to solve for wavefunction contributions order by order.\n\\end{rmk}\n\\end{samepage}\n\n\\begin{ex}\nThe first two derivatives of equation~\\ref{eq:lambda-dependent-recursive-series} are given by\n\\begin{align*}\n \\pd{\\Y(\\la)}{\\la}\n=&\n R_0\n \\pr{\n V_\\mr{c}\n -\n \\pd{E(\\la)}{\\la}\n }\n \\Y(\\la)\n+\n R_0\n (\n \\la V_\\mr{c}\n -\n E(\\la)\n )\n \\pd{\\Y(\\la)}{\\la}\n\\\\\n \\pd{^2\\Y(\\la)}{\\la^2}\n=&\n-\n R_0\n \\pd{^2E(\\la)}{\\la^2}\n \\Y(\\la)\n+\n 2\n R_0\n \\pr{\n V_\\mr{c}\n -\n \\pd{E(\\la)}{\\la}\n }\n \\pd{\\Y(\\la)}{\\la}\n+\n R_0\n (\n \\la V_\\mr{c}\n -\n E(\\la)\n )\n \\pd{^2\\Y(\\la)}{\\la^2}\n\\end{align*}\nwhich can be used to determine the first- and second-order wavefunction contributions.\n\\begin{align}\n\\label{eq:first-and-second-order-principal-terms}\n \\Y\\ord{1}\n=\n \\left.\n \\pd{\\Y(\\la)}{\\la}\n \\right|_{\\la=0}\n=\n R_0\n V_\\mr{c}\n \\F\n&&\n \\Y\\ord{2}\n=\n \\left.\n \\fr{1}{2}\n \\pd{^2\\Y(\\la)}{\\la^2}\n \\right|_{\\la=0}\n=\n R_0\n V_\\mr{c}\n \\Y\\ord{1}\n=\n R_0\n V_\\mr{c}\n R_0\n V_\\mr{c}\n \\F\n\\end{align}\nHere we have used $E_\\mr{c}\\ord{0}=E_\\mr{c}\\ord{1}=0$ and $R_0\\F=0$ to simplify the result.\n\\end{ex}\n\n\\begin{ex}\n\\label{ex:first-order-wavefunction-expansion-unsimplified}\nPlugging in the spectral decomposition for $R_0$ allows us to expand $\\Y\\ord{1}$ in the determinant basis.\n\\begin{align}\n\\label{eq:first-order-wavefunction-expansion-unsimplified}\n \\Y\\ord{1}\n=\n R_0\n V_\\mr{c}\n \\F\n=\n \\sum_{\\substack{a\\\\i}}\n \\F_i^a\n \\fr{\\ip{\\F_i^a|V_\\mr{c}|\\F}}{\\mc{E}_a^i}\n+\n (\\tfr{1}{2!})^2\n \\sum_{\\substack{ab\\\\ij}}\n \\F_{ij}^{ab}\n \\fr{\\ip{\\F_{ij}^{ab}|V_\\mr{c}|\\F}}{\\mc{E}_{ab}^{ij}}\n\\end{align}\nThe expansion truncates at double excitations because the maximum excitation level of $V_\\mr{c}$ is $+2$.\n\\end{ex}\n\n\\begin{ex}\nThe numerators in example~\\ref{ex:first-order-wavefunction-expansion-unsimplified} are easily evaluated using Slater's rules, which leads to the following.\n\\begin{align*}\n\\label{eq:first-order-wavefunction-expansion}\n \\Y\\ord{1}\n=\n \\sum_{\\substack{a\\\\i}}\n \\F_i^a\n \\fr{f_a^i}{\\mc{E}_a^i}\n+\n (\\tfr{1}{2!})^2\n \\sum_{\\substack{ab\\\\ij}}\n \\F_{ij}^{ab}\\,\n \\fr{\\ol{g}_{ab}^{ij}}{\\mc{E}_{ab}^{ij}}\n\\hspace{20pt}\n\\implies\n\\hspace{20pt}\n E_\\mr{c}\\ord{2}\n=\n \\ip{\\F|V_\\mr{c}|\\Y\\ord{1}}\n=\n \\sum_{\\substack{a\\\\i}}\n \\fr{f_i^af_a^i}{\\mc{E}_a^i}\n+\n (\\tfr{1}{2!})^2\n \\sum_{\\substack{ab\\\\ij}}\n \\fr{\\ol{g}_{ij}^{ab}\\,\\ol{g}_{ab}^{ij}}{\\mc{E}_{ab}^{ij}}\n\\end{align*}\nNote that the singles contribution vanishes for canonical Hartree-Fock references, since $f_a^i=0$.\nThese extra terms are required for non-canonical orbitals, such as those obtained from restricted open-shell Hartree-Fock (ROHF) theory.\n\\end{ex}\n\n\\begin{dfn}\\label{dfn:resolvent-line}\n\\thmtitle{Resolvent line}\nWe can generalize our previous definition of the \\textit{resolvent line} as follows\n\\begin{align}\n \\,\\resolventline[0.7]{}\\,\n Y\n\\equiv\n \\sum_k\n \\pr{\\tfr{1}{k!}}^2\n \\sum_{\\substack{a_1\\cd a_k\\\\i_1\\cd i_k}}\n \\fr{y_{a_1\\cd a_k}^{i_1\\cd i_k}}{\\mc{E}_{a_1\\cd a_k}^{i_1\\cd i_k}}\n \\tl{a}^{a_1\\cd a_k}_{i_1\\cd i_k}\n&&\n Y\n=\n Y_{n\\rightarrow n}\n+\n Y_{n\\not\\rightarrow n}\n&&\n Y_{n\\rightarrow n}\n=\n y_0\n+\n \\sum_k\n \\pr{\\tfr{1}{k!}}^2\n \\sum_{\\substack{p_1\\cd p_k\\\\q_1\\cd q_k}}\n y_{p_1\\cd p_k}^{q_1\\cd q_k}\n \\tl{a}^{p_1\\cd p_k}_{q_1\\cd q_k}\n\\end{align}\nwhere $Y$ is an arbitrary operator.\nThe last equation is the Wick expansion of $Y_{n\\rightarrow n}$, which denotes the purely particle-number-conserving part\\footnote{The component that maps $\\mc{F}_n\\rightarrow\\mc{F}_n$ for all $n$, which can always be written as a linear combination of excitation operators.} of $Y$.\nThis definition immediately implies\n$\n \\,\\resolventline[0.7]{}\\,\\,\n \\kt{\\Y}\n=\n R_0\n \\kt{\\Y}\n$\nfor all $\\Y$.\\footnote{Since any $\\kt{\\Y}$ can be written as $Y\\kt{\\F}$, this follows from applying eq~\\ref{eq:resolvent-spectral-decomposition} to each term in the Wick expansion of $Y$ in $R_0Y\\kt{\\F}$.}\nOther expressions are defined by giving resolvent lines priority in the order of operations, with maximum priority given to the rightmost resolvent.\n\\begin{align}\n Y_1\n \\,\\resolventline[0.7]{}\\,\n Y_2\n \\cd\n \\,\\resolventline[0.7]{}\\,\n Y_n\n\\equiv\n Y_1\n \\pr{\n \\,\\resolventline[0.7]{}\\,\n Y_2\n \\pr{\n \\cd\n \\pr{\n \\,\\resolventline[0.7]{}\\,\n Y_n\n \\vphantom{Y_Y^Y}\n }\\cd}}\n&&\n\\gno{\\ol{\n Y_1\n \\,\\resolventline[0.8]{}\\,\n Y_2\n \\cd\n \\,\\resolventline[0.8]{}\\,\n Y_n\n}}\n\\equiv\n\\gno{\\ol{\n \\,\\,\n Y_1\n \\pr{\n \\,\\resolventline[0.7]{}\\,\n Y_2\n \\pr{\n \\cd\n \\pr{\n \\,\\resolventline[0.7]{}\\,\n Y_n\n \\vphantom{Y_Y^Y}\n }\\cd}}\n}}\n\\end{align}\nThis definition also specifies the interpretation rule for a graphs with resolvent lines, which are formally defined below.\n\\end{dfn}\n\n\\begin{cor}\\label{cor:wicks-theorem-for-pt}\n\\thmtitle{Wick's theorem for perturbation theory}\n\\thmstatement{\n$\n YR_0Y_1\\cd R_0 Y_m\n \\kt{\\F}\n=\n \\pr{\n \\gno{\n Y\n \\,\\resolventline[0.8]{}\\,\n Y_1\n \\cd\n \\,\\resolventline[0.8]{}\\,\n Y_m\n }\n +\n \\gno{\\ol{\n Y\n \\,\\resolventline[0.8]{}\\,\n Y_1\n \\cd\n \\,\\resolventline[0.8]{}\\,\n Y_m\n }}\n }\n \\kt{\\F}\n$%\n}%\n\\vspace{5pt}\n\\thmproof{\n This follows directly from Wick's theorem and definition~\\ref{dfn:resolvent-line}.\n}\n\\end{cor}\n\n\\begin{dfn}\\label{dfn:resolvent-graph}\n\\thmtitle{Resolvent graph}\nA \\textit{resolvent graph} represents a normal-ordered product of operators and resolvents.\nGraphs with disconnected parts that don't share any resolvent lines are considered products of separate resolvent graphs.\nVertical spaces between resolvent lines in a resolvent graph are termed \\textit{levels}, which are numbered from bottom with zero indexing.\nTherefore, an operator lies in the $k\\eth$ level if there are $k$ resolvent lines below it.\nFormally, then, an \\textit{$m$-level resolvent graph} $G(\\rh,m)\\equiv(G,\\rh,m)$ associates each operator $o$ in $G$ with a specific level $\\rh(o)=\\rh_o$ in $\\mb{Z}_m=\\{0,1,\\ld,m-1\\}$ through the \\textit{level map} $\\rh$.\\,\\footnote{\n Note that an $m$-level resolvent graph contains $m-1$ resolvents.\n}\nTherefore, each line $l$ in $G$ crosses resolvents\n$\n \\mr{min}(\\rh_{h(l)},\\rh_{t(l)}) + 1\n$\nthrough\n$\n \\mr{max}(\\rh_{h(l)},\\rh_{t(l)})\n$.\n\\end{dfn}\n\n\\begin{ex}\nIn diagram notation, $\\Y\\ord{1}$ and $E_\\mr{c}\\ord{2}$ can be expressed as follows.\n\\begin{align}\n \\Y\\ord{1}\n=\n\\diagram[bottom]{\n \\draw\n (0,-0.5)\n node[circlep] {}\n to\n ++(0.5,0)\n node[ddot] (f1) {};\n \\draw[->-]\n (f1)\n to\n ++(-0.25,1);\n \\draw[-<-]\n (f1)\n to\n ++(+0.25,1);\n \\draw[thick,flexdotted] (0.2,+0.25) to ++(0.6,0);\n}\n+\n\\diagram[bottom]{\n \\interaction{2}{g}{(0,-0.5)}{ddot}{sawtooth};\n \\draw[->-]\n (g1)\n to\n ++(-0.25,1);\n \\draw[-<-]\n (g1)\n to\n ++(+0.25,1);\n \\draw[->-]\n (g2)\n to\n ++(-0.25,1);\n \\draw[-<-]\n (g2)\n to\n ++(+0.25,1);\n \\draw[opacity=0] (0.5,-0.5) circle (0.125cm);\n \\draw[thick,flexdotted] (-0.3,+0.25) to ++(1.6,0);\n}\n&&\n E_\\mr{c}\\ord{2}\n=\n\\diagram{\n %top\n \\draw\n (0,+0.5)\n node[circlep] {}\n to\n ++(0.5,0)\n node[ddot] (1f1) {};\n %bottom\n \\draw\n (0,-0.5)\n node[circlep] {}\n to\n ++(0.5,0)\n node[ddot] (2f1) {};\n \\draw[->-=0.4,bend left ] (2f1) to (1f1);\n \\draw[-<-=0.6,bend right] (2f1) to (1f1);\n \\draw[thick,flexdotted] (0.2,0) to ++(0.6,0);\n}\n+\n\\diagram{\n %top\n \\interaction{2}{1g}{(0,+0.5)}{ddot}{sawtooth};\n %bottom\n \\interaction{2}{2g}{(0,-0.5)}{ddot}{sawtooth};\n %lines\n \\draw[->-=0.4,bend left ] (2g1) to (1g1);\n \\draw[-<-=0.6,bend right] (2g1) to (1g1);\n \\draw[->-=0.4,bend left ] (2g2) to (1g2);\n \\draw[-<-=0.6,bend right] (2g2) to (1g2);\n \\draw[thick,flexdotted] (-0.3,0) to ++(1.6,0);\n}\n\\end{align}\n\\end{ex}\n\n\\begin{ex}\nThe expansion for $\\Y\\ord{2}$ can be evaluated using \\cref{cor:wicks-theorem-for-pt}.\nAssuming Brillouin's theorem for simplicity,\n\\begin{align}\n\\nonumber\n \\Y\\ord{2}\n=\n R_0\n V_\\mr{c}\n R_0\n V_\\mr{c}\n \\kt{\\F}\n=&\\\n\\nonumber\n\\diagram[bottom]{\n \\interaction{2}{1g}{(0,-0.5)}{ddot}{sawtooth};\n \\node[ddot] (2g2) at (1,0) {};\n \\draw[-<-] (1g1) to ++(-0.25,+1);\n \\draw[->-=0.25,->-=0.75] (1g1) to node[midway,ddot] (2g1) {} ++(+0.25,+1);\n \\draw[sawtooth] (2g1) to (2g2);\n \\draw[->-,bend left =45] (1g2) to (2g2);\n \\draw[-<-,bend right=45] (1g2) to (2g2);\n \\draw[thick,flexdotted] (-0.3,-0.27) to ++(1.6,0);\n \\draw[thick,flexdotted] (-0.3,+0.35) to ++(0.7,0);\n \\draw[opacity=0] (0.5,-0.5) circle (0.125cm);\n}\n+\n\\diagram[bottom]{\n \\interaction{2}{1g}{(0,-0.5)}{ddot}{sawtooth};\n \\node[ddot] (2g2) at (1,0) {};\n \\draw[->-] (1g1) to ++(-0.25,+1);\n \\draw[-<-=0.25,-<-=0.75] (1g1) to node[midway,ddot] (2g1) {} ++(+0.25,+1);\n \\draw[sawtooth] (2g1) to (2g2);\n \\draw[->-,bend left =45] (1g2) to (2g2);\n \\draw[-<-,bend right=45] (1g2) to (2g2);\n \\draw[thick,flexdotted] (-0.3,-0.27) to ++(1.6,0);\n \\draw[thick,flexdotted] (-0.3,+0.35) to ++(0.7,0);\n \\draw[opacity=0] (0.5,-0.5) circle (0.125cm);\n}\n+\n\\diagram[bottom]{\n \\interaction{2}{t}{(0,-0.5)}{ddot}{sawtooth};\n \\draw[->-=0.25,->-=0.75] (t1) to node[midway,ddot] (g1) {}\n ++(-0.25,1);\n \\draw[-<-=0.7] (t1) to ++(+0.25,1);\n \\draw[->-=0.25,->-=0.75] (t2) to node[midway,ddot] (g2) {}\n ++(-0.25,1);\n \\draw[-<-=0.7] (t2) to ++(+0.25,1);\n \\draw[sawtooth] (g1)--(g2);\n \\draw[thick,flexdotted] (-0.3,-0.27) to ++(1.6,0);\n \\draw[thick,flexdotted] (-0.4,+0.35) to ++(1.8,0);\n \\draw[opacity=0] (0.5,-0.5) circle (0.125cm);\n}\n+\n\\diagram[bottom]{\n \\interaction{2}{t}{(0,-0.5)}{ddot}{sawtooth};\n \\draw[-<-=0.25,-<-=0.75] (t1) to node[midway,ddot] (g1) {}\n ++(-0.25,1);\n \\draw[->-=0.7] (t1) to ++(+0.25,1);\n \\draw[-<-=0.25,-<-=0.75] (t2) to node[midway,ddot] (g2) {}\n ++(-0.25,1);\n \\draw[->-=0.7] (t2) to ++(+0.25,1);\n \\draw[sawtooth] (g1)--(g2);\n \\draw[thick,flexdotted] (-0.3,-0.27) to ++(1.6,0);\n \\draw[thick,flexdotted] (-0.4,+0.35) to ++(1.8,0);\n \\draw[opacity=0] (0.5,-0.5) circle (0.125cm);\n}\n+\n\\diagram[bottom]{\n \\interaction{2}{t}{(0,-0.5)}{ddot}{sawtooth};\n \\interaction{2}{g}{(1,+0.0)}{ddot}{sawtooth};\n \\draw[->-] (t1) to ++(-0.25,1);\n \\draw[-<-] (t1) to ++(+0.25,1);\n \\draw[->-,bend left] (t2) to (g1);\n \\draw[-<-,bend right] (t2) to (g1);\n \\draw[->-] (g2) to ++(-0.25,0.5);\n \\draw[-<-] (g2) to ++(+0.25,0.5);\n \\draw[thick,flexdotted] (-0.3,-0.27) to ++(1.6,0);\n \\draw[thick,flexdotted] (-0.4,+0.35) to ++(2.8,0);\n \\draw[opacity=0] (0.5,-0.5) circle (0.125cm);\n}\n\\\\&\\\n\\label{eq:second-order-wavefunction-graphical}\n+\n\\diagram[bottom]{\n \\interaction{2}{1g}{(0,-0.5)}{ddot}{sawtooth};\n \\interaction{2}{2g}{(1.125,0)}{ddot}{sawtooth};\n \\draw[-<-] (1g1) to ++(-0.25,1);\n \\draw[->-] (1g1) to ++(+0.25,1);\n \\draw[-<-] (1g2) to ++(-0.25,1);\n \\draw[->-=0.25,->-=0.75] (1g2) to ++(+0.25,1);\n \\draw[-<-] (2g2) to ++(-0.25,0.5);\n \\draw[->-] (2g2) to ++(+0.25,0.5);\n \\draw[thick,flexdotted] (-0.4,-0.27) to ++(2.9,0);\n \\draw[thick,flexdotted] (-0.4,+0.35) to ++(2.9,0);\n \\draw[opacity=0] (0.5,-0.5) circle (0.125cm);\n}\n+\n\\diagram[bottom]{\n \\interaction{2}{1g}{(0,-0.5)}{ddot}{sawtooth};\n \\interaction{2}{2g}{(1.125,0)}{ddot}{sawtooth};\n \\draw[->-] (1g1) to ++(-0.25,1);\n \\draw[-<-] (1g1) to ++(+0.25,1);\n \\draw[->-] (1g2) to ++(-0.25,1);\n \\draw[-<-=0.25,-<-=0.75] (1g2) to ++(+0.25,1);\n \\draw[->-] (2g2) to ++(-0.25,0.5);\n \\draw[-<-] (2g2) to ++(+0.25,0.5);\n \\draw[thick,flexdotted] (-0.4,-0.27) to ++(2.9,0);\n \\draw[thick,flexdotted] (-0.4,+0.35) to ++(2.9,0);\n \\draw[opacity=0] (0.5,-0.5) circle (0.125cm);\n}\n+\n\\diagram[bottom]{\n \\interaction{2}{1g}{(0,-0.5)}{ddot}{sawtooth};\n \\interaction{2}{2g}{(2,0)}{ddot}{sawtooth};\n \\draw[-<-] (1g1) to ++(-0.25,1);\n \\draw[->-] (1g1) to ++(+0.25,1);\n \\draw[-<-] (1g2) to ++(-0.25,1);\n \\draw[->-] (1g2) to ++(+0.25,1);\n \\draw[-<-] (2g1) to ++(-0.25,0.5);\n \\draw[->-] (2g1) to ++(+0.25,0.5);\n \\draw[-<-] (2g2) to ++(-0.25,0.5);\n \\draw[->-] (2g2) to ++(+0.25,0.5);\n \\draw[thick,flexdotted] (-0.3,-0.27) to ++(1.6,0);\n \\draw[thick,flexdotted] (-0.4,+0.35) to ++(3.9,0);\n \\draw[opacity=0] (0.5,-0.5) circle (0.125cm);\n}\n\\\\\n=&\\\n \\tfr{1}{2}\n \\sum_{\\substack{abc\\\\ij}}\n \\F_i^a\\,\n \\fr{\n \\ol{g}_{aj}^{bc}\n \\ol{g}_{bc}^{ij}\n }{\n \\mc{E}_a^i\n \\mc{E}_{bc}^{ij}\n }\n-\n \\tfr{1}{2}\n \\sum_{\\substack{ab\\\\ijk}}\n \\F_i^a\n \\fr{\n \\ol{g}_{jk}^{ib}\n \\ol{g}_{ab}^{jk}\n }{\n \\mc{E}_a^i\n \\mc{E}_{ab}^{jk}\n }\n+\n \\tfr{1}{2^3}\n \\sum_{\\substack{abcd\\\\ij}}\n \\F_{ij}^{ab}\n \\fr{\n \\ol{g}_{ab}^{cd}\n \\ol{g}_{cd}^{ij}\n }{\n \\mc{E}_{ab}^{ij}\n \\mc{E}_{cd}^{ij}\n }\n+\n \\tfr{1}{2^3}\n \\sum_{\\substack{ab\\\\ijkl}}\n \\F_{ij}^{ab}\n \\fr{\n \\ol{g}_{kl}^{ij}\n \\ol{g}_{ab}^{kl}\n }{\n \\mc{E}_{ab}^{ij}\n \\mc{E}_{ab}^{kl}\n }\n\\nonumber\n\\\\&\\\n+\n \\sum_{\\substack{abc\\\\ijk}}\n \\F_{ij}^{ab}\n \\fr{\n \\ol{g}_{ac}^{ik}\n \\ol{g}_{kb}^{cj}\n }{\n \\mc{E}_{ab}^{ij}\n \\mc{E}_{ac}^{ik}\n }\n+\n \\tfr{1}{2^2}\n \\sum_{\\substack{abcd\\\\ijk}}\n \\F_{ijk}^{abc}\n \\fr{\n \\ol{g}_{ad}^{ij}\n \\ol{g}_{bc}^{dk}\n }{\n \\mc{E}_{abc}^{ijk}\n \\mc{E}_{ad}^{ij}\n }\n-\n \\tfr{1}{2^2}\n \\sum_{\\substack{abc\\\\ijkl}}\n \\F_{ijk}^{abc}\n \\fr{\n \\ol{g}_{ab}^{il}\n \\ol{g}_{lc}^{jk}\n }{\n \\mc{E}_{abc}^{ijk}\n \\mc{E}_{ab}^{il}\n }\n+\n \\tfr{1}{2^4}\n \\sum_{\\substack{abcd\\\\ijkl}}\n \\F_{ijkl}^{abcd}\n \\fr{\n \\ol{g}_{ab}^{ij}\n \\ol{g}_{cd}^{kl}\n }{\n \\mc{E}_{abcd}^{ijkl}\n \\mc{E}_{ab}^{ij}\n }\n\\end{align}\nwhere the operators in the final diagram do not form an equivalent pair because they pass through different resolvent lines.\nThe third-order contribution to the correlation energy can be evaluated as the complete contractions of $V_\\mr{c}R_0V_\\mr{c}R_0V_\\mr{c}$\n\\begin{align}\n E_\\mr{c}\\ord{3}\n\\,{=}\\,\n\\diagram{\n %top\n \\interaction{2}{1g}{(0,+0.5)}{ddot}{sawtooth};\n %bottom\n \\interaction{2}{2g}{(0,-0.5)}{ddot}{sawtooth};\n \\draw[->-=0.25,->-=0.75, bend left]\n (2g1)\n to\n node[midway,ddot] (g1) {}\n (1g1);\n \\draw[-<-=0.65,bend right] (2g1) to (1g1);\n \\draw[->-=0.25,->-=0.75, bend left]\n (2g2)\n to\n node[midway,ddot] (g2) {}\n (1g2);\n \\draw[-<-=0.65,bend right] (2g2) to (1g2);\n \\draw[sawtooth] (g1)--(g2);\n \\draw[thick,flexdotted] (-0.3,-0.3) to ++(1.6,0);\n \\draw[thick,flexdotted] (-0.3,+0.3) to ++(1.6,0);\n \\draw[opacity=0] (0.5,-0.5) circle (0.125cm);\n}\n{+}\n\\diagram{\n %top\n \\interaction{2}{1g}{(0,+0.5)}{ddot}{sawtooth};\n %bottom\n \\interaction{2}{2g}{(0,-0.5)}{ddot}{sawtooth};\n \\draw[-<-=0.25,-<-=0.75, bend left]\n (2g1)\n to\n node[midway,ddot] (g1) {}\n (1g1);\n \\draw[->-=0.65,bend right] (2g1) to (1g1);\n \\draw[-<-=0.25,-<-=0.75, bend left]\n (2g2)\n to\n node[midway,ddot] (g2) {}\n (1g2);\n \\draw[->-=0.65,bend right] (2g2) to (1g2);\n \\draw[sawtooth] (g1)--(g2);\n \\draw[thick,flexdotted] (-0.3,-0.3) to ++(1.6,0);\n \\draw[thick,flexdotted] (-0.3,+0.3) to ++(1.6,0);\n \\draw[opacity=0] (0.5,-0.5) circle (0.125cm);\n}\n{+}\n\\diagram{\n %top\n \\draw[sawtooth]\n (0,+0.5)\n node[ddot] (1g1) {}\n to\n ++(2,0)\n node[ddot] (1g2) {};\n %middle\n \\interaction{2}{g}{(1,+0.0)}{ddot}{sawtooth};\n %bottom\n \\interaction{2}{2g}{(0,-0.5)}{ddot}{sawtooth};\n \\draw[->-,bend left ] (2g1) to (1g1);\n \\draw[-<-,bend right] (2g1) to (1g1);\n \\draw[->-,bend left ] (2g2) to (g1);\n \\draw[-<-,bend right] (2g2) to (g1);\n \\draw[->-,bend left ] (g2) to (1g2);\n \\draw[-<-,bend right] (g2) to (1g2);\n \\draw[thick,flexdotted] (-0.3,-0.3) to ++(1.6,0);\n \\draw[thick,flexdotted] (-0.3,+0.3) to ++(2.6,0);\n \\draw[opacity=0] (0.5,-0.5) circle (0.125cm);\n}\n{=}\n \\tfr{1}{2^3}\n \\sum_{\\substack{abcd\\\\ij}}\n \\fr{\n \\ol{g}_{ij}^{ab}\n \\ol{g}_{ab}^{cd}\n \\ol{g}_{cd}^{ij}\n }{\n \\mc{E}_{ab}^{ij}\n \\mc{E}_{cd}^{ij}\n }\n{+}\n \\tfr{1}{2^3}\n \\sum_{\\substack{ab\\\\ijkl}}\n \\fr{\n \\ol{g}_{ij}^{ab}\n \\ol{g}_{kl}^{ij}\n \\ol{g}_{ab}^{kl}\n }{\n \\mc{E}_{ab}^{ij}\n \\mc{E}_{ab}^{kl}\n }\n{+}\n \\sum_{\\substack{abc\\\\ijk}}\n \\fr{\n \\ol{g}_{ij}^{ab}\n \\ol{g}_{ac}^{ik}\n \\ol{g}_{kb}^{cj}\n }{\n \\mc{E}_{ab}^{ij}\n \\mc{E}_{ac}^{ik}\n }\n\\end{align}\nwhich is equivalent to contracting the doubles contributions to $\\Y\\ord{2}$ with $\\tfr{1}{4}\\ol{g}_{ij}^{ab}\\tl{a}^{ij}_{ab}$.\nNote that $E_\\mr{c}\\ord{m+1}$ always only depends on the doubles contribution to $\\Y\\ord{m}$, but that the doubles coefficients themselves may involve triples, quadruples and higher contributions from wavefunction components of order less than $m$.\n\\end{ex}\n\n\\begin{ex}\nUsing\n${}\\ord{m}c_{ab\\cd}^{ij\\cd}=\\ip{\\F_{ij\\cd}^{ab\\cd}|\\Y\\ord{m}}$, the second order CI coefficients can be determined from eq~\\ref{eq:second-order-wavefunction-graphical} by contracting a bare excitation operator with the top of each diagram.\nInterpreting these graphs gives the following.\n\\begin{align*}\n {}\\ord{2}c_a^i\n&=\n \\tfr{1}{2}\n \\sum_{\\substack{bc\\\\j}}\n \\fr{\n \\ol{g}_{aj}^{bc}\n \\ol{g}_{bc}^{ij}\n }{\n \\mc{E}_a^i\n \\mc{E}_{bc}^{ij}\n }\n-\n \\tfr{1}{2}\n \\sum_{\\substack{b\\\\jk}}\n \\fr{\n \\ol{g}_{jk}^{ib}\n \\ol{g}_{ab}^{jk}\n }{\n \\mc{E}_a^i\n \\mc{E}_{ab}^{jk}\n }\n\\\\\n {}\\ord{2}c_{ab}^{ij}\n&=\n \\tfr{1}{2}\n \\sum_{\\substack{cd}}\n \\fr{\n \\ol{g}_{ab}^{cd}\n \\ol{g}_{cd}^{ij}\n }{\n \\mc{E}_{ab}^{ij}\n \\mc{E}_{cd}^{ij}\n }\n+\n \\tfr{1}{2}\n \\sum_{\\substack{kl}}\n \\fr{\n \\ol{g}_{kl}^{ij}\n \\ol{g}_{ab}^{kl}\n }{\n \\mc{E}_{ab}^{ij}\n \\mc{E}_{ab}^{kl}\n }\n+\n \\op{P}_{(a/b)}^{(i/j)}\n \\sum_{\\substack{c\\\\k}}\n \\fr{\n \\ol{g}_{ac}^{ik}\n \\ol{g}_{kb}^{cj}\n }{\n \\mc{E}_{ab}^{ij}\n \\mc{E}_{ac}^{ik}\n }\n\\\\\n {}\\ord{2}c_{abc}^{ijk}\n&=\n \\op{P}_{(a/bc)}^{(ij/k)}\n \\sum_{\\substack{d}}\n \\fr{\n \\ol{g}_{ad}^{ij}\n \\ol{g}_{bc}^{dk}\n }{\n \\mc{E}_{abc}^{ijk}\n \\mc{E}_{ad}^{ij}\n }\n-\n \\op{P}_{(ab/c)}^{(i/jk)}\n \\sum_{\\substack{l}}\n \\fr{\n \\ol{g}_{ab}^{il}\n \\ol{g}_{lc}^{jk}\n }{\n \\mc{E}_{abc}^{ijk}\n \\mc{E}_{ab}^{il}\n }\n\\\\\n {}\\ord{2}c_{abcd}^{ijkl}\n&=\n \\op{P}_{(ab/cd)}^{(ij/kl)}\n \\fr{\n \\ol{g}_{ab}^{ij}\n \\ol{g}_{cd}^{kl}\n }{\n \\mc{E}_{abcd}^{ijkl}\n \\mc{E}_{ab}^{ij}\n }\n\\end{align*}\nNote that the second order quadruples coefficient is disconnected.\nProp.~\\ref{prop:second-order-c4} shows that the second-order quadruples operator is actually a simple product of first-order doubles operators.\nThis fact was an early motivation for coupled-pair many-electron theory,\\footnote{This is the original name for coupled-cluster doubles.} since it justifies approximating\n$\n \\Y_\\mr{CIDQ}\n=\n (1+C_2+C_4)\\F\n$\nby\n$\n \\Y_\\mr{CPMET}\n=\n (1 + C_2 + \\tfr{1}{2}C_2^2)\\F\n$.\n\\end{ex}\n\n\\begin{prop}\n\\label{prop:second-order-c4}\n\\thmstatement{\n$\n {}\\ord{2} C_4\n=\n \\tfr{1}{2}\n {}\\ord{1} C_2^2\n$\n}\n\\thmproof{\nThis follows from rearranging the resolvent denominator.\n\\begin{align*}\n \\fr{1}{\\mc{E}_{abcd}^{ijkl}\\mc{E}_{ab}^{ij}}\n+\n \\fr{1}{\\mc{E}_{abcd}^{ijkl}\\mc{E}_{cd}^{kl}}\n=\n \\fr{\n \\mc{E}_{cd}^{kl} + \\mc{E}_{ab}^{ij}\n }{\n \\mc{E}_{abcd}^{ijkl}\n \\mc{E}_{ab}^{ij}\n \\mc{E}_{cd}^{kl}\n }\n=\n \\fr{\n 1\n }{\n \\mc{E}_{ab}^{ij}\n \\mc{E}_{cd}^{kl}\n }\n\\implies\n {}\\ord{2}C_4\n=\n \\pr{\\tfr{1}{2}}^4\n \\sum_{\\substack{abcd\\\\ijkl}}\n \\tl{a}^{abcd}_{ijkl}\n \\fr{\n \\ol{g}_{ab}^{ij}\n \\ol{g}_{cd}^{kl}\n }{\n \\mc{E}_{abcd}^{ijkl}\n \\mc{E}_{ab}^{ij}\n }\n=\n \\tfr{1}{2}\\cdot\n \\pr{\\tfr{1}{2}}^4\n \\sum_{\\substack{abcd\\\\ijkl}}\n \\tl{a}^{abcd}_{ijkl}\n \\fr{\n \\ol{g}_{ab}^{ij}\n \\ol{g}_{cd}^{kl}\n }{\n \\mc{E}_{ab}^{ij}\n \\mc{E}_{cd}^{kl}\n }\n=\n \\tfr{1}{2}\n {}\\ord{1}C_2^2\n\\end{align*}\n}\n\\end{prop}\n\n\\begin{lem}\\label{lem:energy-substitution}\n\\thmtitle{The Energy Substitution Lemma}\n\\thmstatement{\n $\\Y\\ord{m}$ equals the sum of a ``principal term''\n $(R_0V_\\mr{c})^m\\F$\n plus all possible substitutions of adjacent factors $(R_0V_\\mr{c})^{r_i}$ in the principal term by $R_0E_\\mr{c}\\ord{r_i}$.\n Each term in the sum is weighted by a sign factor $(-)^k$, where $k$ is the number of substitutions.\n}\n\\thmproof{\n See \\cref{app:linked-diagram-theorem}.\n}\n\\end{lem}\n\n\\begin{ex}\nLemma~\\ref{lem:energy-substitution} is consistent with equation~\\ref{eq:first-and-second-order-principal-terms} because substitution of the rightmost factors in the principal term leaves a resolvent acting on the reference determinant and because the first-order energy contribution equals zero.\nThe first non-trivial examples of the energy substitution lemma begin at third order.\n\\begin{align}\n\\label{eq:energy-substitution-psi-3}\n \\Y\\ord{3}\n=&\\\n R_0V_\\mr{c}R_0V_\\mr{c}R_0V_\\mr{c}\\F\n-\n R_0E_\\mr{c}\\ord{2}R_0V_\\mr{c}\\F\n\\\\\n\\label{eq:energy-substitution-psi-4}\n \\Y\\ord{4}\n=&\\\n R_0V_\\mr{c}R_0V_\\mr{c}R_0V_\\mr{c}R_0V_\\mr{c}\\F\n-\n R_0E_\\mr{c}\\ord{2}R_0V_\\mr{c}R_0V_\\mr{c}\\F\n-\n R_0V_\\mr{c}R_0E_\\mr{c}\\ord{2}R_0V_\\mr{c}\\F\n-\n R_0E_\\mr{c}\\ord{3}R_0V_\\mr{c}\\F\n\\\\\n\\nonumber\n \\Y\\ord{5}\n=&\\\n R_0V_\\mr{c}R_0V_\\mr{c}R_0V_\\mr{c}R_0V_\\mr{c}R_0V_\\mr{c}\\F\n-\n R_0E_\\mr{c}\\ord{2}R_0V_\\mr{c}R_0V_\\mr{c}R_0V_\\mr{c}\\F\n-\n R_0V_\\mr{c}R_0E_\\mr{c}\\ord{2}R_0V_\\mr{c}R_0V_\\mr{c}\\F\n\\\\&\\\n\\nonumber\n-\n R_0V_\\mr{c}R_0V_\\mr{c}R_0E_\\mr{c}\\ord{2}R_0V_\\mr{c}\\F\n+\n R_0E_\\mr{c}\\ord{2}R_0E_\\mr{c}\\ord{2}R_0V_\\mr{c}\\F\n-\n R_0E_\\mr{c}\\ord{3}R_0V_\\mr{c}R_0V_\\mr{c}\\F\n\\\\&\\\n\\label{eq:energy-substitution-psi-5}\n-\n R_0V_\\mr{c}R_0E_\\mr{c}\\ord{3}R_0V_\\mr{c}\\F\n-\n R_0E_\\mr{c}\\ord{4}R_0V_\\mr{c}\\F\n\\end{align}\n\\end{ex}\n\n\\begin{thm}\\label{thm:bracketing-theorem}\n\\thmtitle{The Bracketing Theorem}\n\\thmstatement{\n $\\Y\\ord{m}$ equals the principal term plus all possible insertions of nested brackets into the principal term.\n Each term in the sum is weighted by $(-)^k$ where $k$ is the total number of brackets.\\footnote{\n The ``brackets'' here are reference expectation values: $\\ip{W}\\equiv\\ip{\\F|W|\\F}$.\n}\n}\n\\thmproof{\n See \\cref{app:linked-diagram-theorem}.\n}\n\\end{thm}\n\n\n\\begin{ex}\nEquations~\\ref{eq:energy-substitution-psi-3} and~\\ref{eq:energy-substitution-psi-4} are clearly consistent with \\cref{thm:bracketing-theorem}, since $E_\\mr{c}\\ord{2}{=}\\,\\ip{V_\\mr{c}R_0V_\\mr{c}}$ and $E_\\mr{c}\\ord{3}{=}\\,\\ip{V_\\mr{c}R_0V_\\mr{c}R_0V_\\mr{c}}$.\n\\begin{align}\n\\label{eq:bracketing-psi-3}\n \\Y\\ord{3}\n=&\\\n R_0V_\\mr{c}R_0V_\\mr{c}R_0V_\\mr{c}\\F\n-\n R_0\\ip{V_\\mr{c}R_0V_\\mr{c}}R_0V_\\mr{c}\\F\n\\\\\n \\Y\\ord{4}\n=&\\\n R_0V_\\mr{c}R_0V_\\mr{c}R_0V_\\mr{c}R_0V_\\mr{c}\\F\n-\n R_0\\ip{V_\\mr{c}R_0V_\\mr{c}}R_0V_\\mr{c}R_0V_\\mr{c}\\F\n-\n R_0V_\\mr{c}R_0\\ip{V_\\mr{c}R_0V_\\mr{c}}R_0V_\\mr{c}\\F\n-\n R_0\\ip{V_\\mr{c}R_0V_\\mr{c}R_0V_\\mr{c}}R_0V_\\mr{c}\\F\n\\\\\n\\intertext{\nThe first non-vanishing terms with nested brackets appear at fifth-order\n}\n\\nonumber\n \\Y\\ord{5}\n=&\\\n R_0V_\\mr{c}R_0V_\\mr{c}R_0V_\\mr{c}R_0V_\\mr{c}R_0V_\\mr{c}\\F\n-\n R_0\\ip{V_\\mr{c}R_0V_\\mr{c}}R_0V_\\mr{c}R_0V_\\mr{c}R_0V_\\mr{c}\\F\n-\n R_0V_\\mr{c}R_0\\ip{V_\\mr{c}R_0V_\\mr{c}}R_0V_\\mr{c}R_0V_\\mr{c}\\F\n\\\\&\\\n\\nonumber\n-\n R_0V_\\mr{c}R_0V_\\mr{c}R_0\\ip{V_\\mr{c}R_0V_\\mr{c}}R_0V_\\mr{c}\\F\n+\n R_0\\ip{V_\\mr{c}R_0V_\\mr{c}}R_0\\ip{V_\\mr{c}R_0V_\\mr{c}}R_0V_\\mr{c}\\F\n-\n R_0\\ip{V_\\mr{c}R_0V_\\mr{c}R_0V_\\mr{c}}R_0V_\\mr{c}R_0V_\\mr{c}\\F\n\\\\&\\\n-\n R_0V_\\mr{c}R_0\\ip{V_\\mr{c}R_0V_\\mr{c}R_0V_\\mr{c}}R_0V_\\mr{c}\\F\n-\n R_0\\ip{V_\\mr{c}R_0V_\\mr{c}R_0V_\\mr{c}R_0V_\\mr{c}}R_0V_\\mr{c}\\F\n+\n R_0\\ip{V_\\mr{c}R_0\\ip{V_\\mr{c}R_0V_\\mr{c}}R_0V_\\mr{c}}R_0V_\\mr{c}\\F\n\\end{align}\nwhich follows from substituting equation~\\ref{eq:bracketing-psi-3} into $E\\ord{4}=\\ip{\\F|V_\\mr{c}|\\Y\\ord{3}}$ in the energy substitution expansion of $\\Y\\ord{5}$.\n\\end{ex}\n\n\n\\begin{ex}\nAssuming Brillouin's theorem, the simplest non-vanishing term with an inserted bracket appears in $\\Y\\ord{3}$.\n\\begin{align*}\n R_0\n \\ip{V_\\mr{c}R_0V_\\mr{c}}\n R_0\n V_\\mr{c}\n \\F\n=\n\\diagram{\n \\interaction{2}{1g}{(0,-0.5)}{ddot}{sawtooth};\n \\draw[->-] (1g1) to ++(-0.25,1);\n \\draw[-<-] (1g1) to ++(+0.25,1);\n \\draw[->-] (1g2) to ++(-0.25,1);\n \\draw[-<-] (1g2) to ++(+0.25,1);\n \\interaction{2}{2g}{(2,-0.5)}{ddot}{sawtooth};\n \\interaction{2}{3g}{(2,+0.5)}{ddot}{sawtooth};\n \\draw[->-=0.4,bend left ] (2g1) to (3g1);\n \\draw[-<-=0.6,bend right] (2g1) to (3g1);\n \\draw[->-=0.4,bend left ] (2g2) to (3g2);\n \\draw[-<-=0.6,bend right] (2g2) to (3g2);\n \\draw[thick,flexdotted] (-0.3,-0.25) to ++(1.6,0);\n \\draw[thick,flexdotted] (-0.4,+0.35) to ++(1.8,0);\n \\draw[opacity=0] (0.5,-0.5) circle (0.125cm);\n \\draw[thick,flexdotted] (1.7,0) to ++(1.6,0);\n \\padborder{5pt};\n \\draw[double, thick] (current bounding box.south west)--(current bounding box.south east);\n \\node at (0.5,-1) {remainder};\n \\node at (2.5,-1) {insertion};\n \\node[inner sep=0pt] at (-1.5,0) {\n \\begin{tabular}{c}\n level of the\\\\insertion\n \\end{tabular}\n };\n \\draw[->] (-2.5,0) to (-0.3,0);\n \\node[inner sep=0pt] at (+4,+0.4) {$1\\rst$\\,level};\n \\node[inner sep=0pt] at (+4,-0.3) {$0\\eth$\\,level};\n}\n\\end{align*}\n\\end{ex}\n\n\\begin{prop}\n\\thmtitle{Wigner's (2n+1) rule}\n\\end{prop}\n\n\n\n\n\\newpage\n\\appendix\n\\section{Proof of the Linked-Diagram Theorem}\\label{app:linked-diagram-theorem}\n\n\\begin{ntt}\\label{ntt:operator-combinations}\nLet\n``$Y^m$ choose $Z^k$'', denoted ${}^mC_k(Y:Z)$,\nrefer to a sum over the $m$ choose $k$ permutations of $Y^{m-k}Z^k$,\\,\\footnote{For example,\n$\n {}^4C_2(Y:Z)\n=\n Y^2Z^2\n+\n YZYZ\n+\n YZ^2Y\n+\n ZY^2Z\n+\n ZYZY\n+\n Z^2Y^2\n$.\n}\nwhere $Y$ and $Z$ are operators that may or may not commute.\\,\\footnote{\n If they do commute, then ${}^mC_k(Y:Z)={n\\choose k}Y^{m-k}Z^k$.\n}\nThis defines a generalization of the binomial theorem.\n\\begin{align}\n\\label{eq:generalized-binomial-theorem}\n (\n Y\n +\n Z\n )^m\n=\n \\sum_{k=0}^m\n {}^mC_k(Y:Z)\n\\end{align}\nFurthermore, let\n$\n {}^mC(Y:Z_1,\\ld,Z_k)\n$\nbe a sum over permutations of\n$\n Y^{m-k}\n Z_1\\cd Z_k\n$ that preserve the ordering of the $Z_i$'s.\\,\\footnote{\n For example,\n$\n {}^4C(Y:Z_1,Z_2)\n=\n Y^2Z_1Z_2\n+\n YZ_1YZ_2\n+\n YZ_1Z_2Y\n+\n Z_1Y^2Z_2\n+\n Z_1YZ_2Y\n+\n Z_1Z_2Y^2\n$.\n}\nWhen all of the $Z_i$'s equal $Z$, we can write\n$\n {}^mC(Y:Z_1,\\ld,Z_k)\n=\n {}^mC_k(Y:Z)\n$.\n\\end{ntt}\n\n\\begin{prop}\n\\label{prop:wavefunction-infinite-recursion}\n\\thmstatement{\n$\\ds{\n \\Y(\\la)\n=\n \\sum_{m=0}^\\infty\n \\pr{\n R_0\n (\\la V_\\mr{c} - E(\\la))\n }^m\n \\F\n}$\n}\n\\thmproof{\n This follows by infinite recursion of equation~\\ref{eq:lambda-dependent-recursive-series} with the assumption\n $\\ds{\n \\lim_{m\\rightarrow\\infty}\n \\pr{\n R_0\n (\\la V_\\mr{c} - E(\\la))\n }^m\n \\Y(\\la)\n =\n 0\n }$.\n}\n\\end{prop}\n\n\\begin{dfn}\\label{dfn:integer-compositions}\n\\thmtitle{Integer compositions}\nThe \\textit{compositions} of an integer $m$ are the ways of writing $m$ as a sum of positive integers.\nThe full set of integer compositions of $m$ is given by\n$\n \\mc{C}(m)\n=\n \\mc{C}_1(m)\n \\cup\n \\mc{C}_2(m)\n \\cup\n \\cd\n \\cup\n \\mc{C}_m(m)\n$\nwhere\n$\n \\mc{C}_k(m)\n=\n \\{\n (r_1,\\ld,r_k)\\in\\mb{N}_0^k\n \\,|\\,\n r_1+\\cd+r_k\n =\n m\n \\}\n$\nare the integer compositions of $m$ into $k$ parts.\n\\end{dfn}\n\n\\begin{lem}\n\\label{lem:energy-substitution-proof}\n\\thmtitle{The Energy Substitution Lemma}\n\\thmstatement{\n $\\Y\\ord{m}$ equals the sum of a ``principal term''\n $(R_0V_\\mr{c})^m\\F$\n plus all possible substitutions of adjacent factors $(R_0V_\\mr{c})^{r_i}$ in the principal term by $R_0E_\\mr{c}\\ord{r_i}$.\n Each term in the sum is weighted by a sign factor $(-)^k$, where $k$ is the number of substitutions.\n}\\vspace{5pt}\n\\thmproof{\nUsing equation~\\ref{eq:generalized-binomial-theorem} and a double sum identity\\footnote{\n Reverse double-sum reduction:\n $\\ds{\n \\sum_{m=0}^\\infty\n \\sum_{k=0}^m\n t_{m-k,k}\n =\n \\sum_{k'=0}^\\infty\n \\sum_{k=0}^\\infty\n t_{k',k}\n }$.\n See\n \\url{http://functions.wolfram.com/GeneralIdentities/12/}.\n} in the infinite recursion formula for $\\Y(\\la)$ gives the following.\n{\\footnotesize\n\\begin{align*}\n \\Y(\\la)\n=\n \\sum_{m=0}^\\infty\n (\n R_0\n (\n \\la V_\\mr{c}\n -\n E(\\la)\n )\n )^m\n \\F\n=\n \\sum_{m=0}^\\infty\n \\sum_{k=0}^m\n \\la^{m-k}\n (-)^k\\,\\,\n {}^mC_k\n (\n R_0V_\\mr{c}:\n R_0E(\\la)\n )\n \\F\n=\n \\sum_{k'=0}^\\infty\n \\sum_{k=0}^\\infty\n \\la^{k'}\n (-)^{k}\\,\\,\n {}^{k'+k}\\hspace{-1pt}C_k\n (\n R_0V_\\mr{c}:\n R_0E(\\la)\n )\n \\F\n\\end{align*}}%\nThe $k'=0$ term has no operators separating $\\F$ from the resolvent and vanishes.\nTaylor expansion of the energies gives\n{\\footnotesize\n\\begin{align*}\n \\Y(\\la)\n=&\\\n \\sum_{k=0}^\\infty\n \\sum_{k'=1}^\\infty\n {\\sum_{p_1=1}^\\infty}\n \\cd\n {\\sum_{p_k=1}^\\infty}\n \\la^{k' + p_1 + \\cd + p_k}\n (-)^{k}\\,\\,\n {}^{k'+k}\\hspace{-1pt}C\n (\n R_0V_\\mr{c}:\n R_0E_\\mr{c}\\ord{p_1},\\ld,\n R_0E_\\mr{c}\\ord{p_k}\n )\n \\F\n\\\\\n=&\\\n \\sum_{m=1}^\\infty\n \\sum_{k=0}^{m-1}\n \\sum_{(r_1,\\ld,r_{k+1})}^{\\mc{C}_{k+1}(m)}\n \\la^m\n (-)^k\\,\\,\n {}^{k+r_1}\\hspace{-1pt}C\n (\n R_0V_\\mr{c}:\n R_0E_\\mr{c}\\ord{r_2},\\ld,\n R_0E_\\mr{c}\\ord{r_{k+1}}\n )\n \\F\n\\end{align*}}%\nwhere we have grouped powers of $\\la$ using a multi-sum reduction.\nWriting the inner sums as a sum over $\\mc{C}(m)$ we find\n\\begin{align}\n \\Y\\ord{m}\n=\n \\left.\n \\fr{1}{m!}\n \\pd{^m\\Y(\\la)}{\\la^m}\n \\right|_{\\la=0}\n=\n \\sum_{(r_1,\\ld,r_{k+1})}^{\\mc{C}(m)}\n (-)^k\\,\\,\n {}^{k+r_1}\\hspace{-1pt}C\n (\n R_0V_\\mr{c}:\n R_0E_\\mr{c}\\ord{r_2},\\ld,\n R_0E_\\mr{c}\\ord{r_{k+1}}\n )\n \\F\n\\end{align}\nwhich, given \\cref{ntt:operator-combinations} and definition~\\ref{dfn:integer-compositions}, is an algebraic statement of the proposition, completing the proof.\n}\n\\end{lem}\n\n\\begin{thm}\n\\thmtitle{The Bracketing Theorem}\n\\thmstatement{\n $\\Y\\ord{m}$ equals the principal term plus all possible insertions of nested brackets into the principal term.\n Each term in the sum is weighted by $(-)^k$ where $k$ is the total number of brackets.\n}\\vspace{5pt}\n\\thmproof{\n The proposition holds for $m=1$ because\n $\\Y\\ord{1}=R_0V_\\mr{c}\\F$ and there are no possible bracketings.\n Assume it holds for $m-1$.\n Then by the energy substitution lemma it also holds for $m$ because $E_\\mr{c}\\ord{r_i}$\n equals\n $\\ip{\\F|V_\\mr{c}|\\Y\\ord{r_i}}$\n which, by our inductive assumption, equals\n $\\ip{V_\\mr{c}(R_0V_\\mr{c})^{r_i}}$\n plus all nested bracketings weighted by appropriate sign factors.\n}\n\\end{thm}\n\n\n\\end{document}\n", "meta": {"hexsha": "e780f598e8349a138d8ed24367174b2b44699df9", "size": 37168, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "2017/tex/6q-1h-perturbation-theory.tex", "max_stars_repo_name": "GQCG-edu/chem-8950", "max_stars_repo_head_hexsha": "a5f58a5feacbae16b02fddd2c74723da1486b8d2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 18, "max_stars_repo_stars_event_min_datetime": "2017-09-29T20:25:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T17:40:32.000Z", "max_issues_repo_path": "2017/tex/6q-1h-perturbation-theory.tex", "max_issues_repo_name": "GQCG-edu/chem-8950", "max_issues_repo_head_hexsha": "a5f58a5feacbae16b02fddd2c74723da1486b8d2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-07-13T12:11:58.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-13T15:31:47.000Z", "max_forks_repo_path": "2017/tex/6q-1h-perturbation-theory.tex", "max_forks_repo_name": "GQCG-edu/chem-8950", "max_forks_repo_head_hexsha": "a5f58a5feacbae16b02fddd2c74723da1486b8d2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2017-09-10T10:33:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-05T07:39:50.000Z", "avg_line_length": 23.2445278299, "max_line_length": 405, "alphanum_fraction": 0.5903196298, "num_tokens": 16575, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.33458944788835565, "lm_q1q2_score": 0.16860168738486064}} {"text": "\\chapter{De-Entanglement by additional Divergences - Case study with Emphatic Speech Synthesis}\n\n\nsection{Problem Motivation and Introduction}\nHumans exhibit both coarse as well as fine grained explicit control over how they speak an utterance. This targeted control on speech - often manifested in the form of prosodic constructions - allows us to effectively convey our intent in a conversation. Examples of controlled speech generation include simple prosodic manipulations such as implying specific meaning, highlighting or expressing interest in something as well as various communication strategies such as contradiction, contrast, complaints or grudging admiration\\citep{nigel_ward_prosodic_patterns}. Further, such manipulation in prosody has been shown effective in\napplications such as Infant Behavior Programs \\citep{parental_prosody_changes_mediate_infant_language_production}, improving language acquisition\\citep{prosody_functionwords_acquisition} and promoting rapport\\citep{rapport_dialogsystems}. It seems natural to employ generative models of speech\\citep{tacotron_original,deepvoice2,clarinet,parrotron} to assist in such scenarios \\citep{does_tts_help_comprehension}. However, although there has been tremendous progress in the neural generative models for speech in the context of vocoder fidelity\\citep{waveglow,wavenet_original}, the notion of controllability in such models is not yet fully evolved. While there have been works towards models aimed at controlling prosody\\citep{ tacotron_hierarchical,tacotron_stylefacoruncovering}, the exerted control is still global or coarse grained in terms of styles of speech\\citep{tacotron_prosodycontrol,tacotron_styletokens}, etc. In this work, we propose an approach that allows both global as well as local control over the prosodic variation in the generated speech. \n\nTypically TTS is formulated as a conditional generative modeling problem. In our approach, we propose to instead formulate it as a conditional variational auto-encoder and incorporate automatically derivable information from speech data into the model architecture. This is motivated by the understanding that the utterances themselves do not always contain all the information needed to comprehend the appropriate prosody information. The missing information is either part of background knowledge about the world - implicit to humans but not annotated in the data - or is provided by accompanying context of the utterance. Formulating the task using variational inference allows us to efficiently capture the distribution of prosody thereby avoiding the averaging effect observed in a typical TTS system due to prosody marginalization. To illustrate this, consider an example sentence: `\\textit{You do not have a pet shark}'. Most prosodic constructions for this sentence involve sarcasm since it is not commonplace to have sharks as pets - world knowledge. Similarly consider the sentence: `\\textit{I dont want to be a nun}'. The linguistic unit subject to realization of prosodic stress in this sentence depends on the context information. Finally, consider the example of a TTS system deployed in a screenreader to assist visually impaired students comprehend math equations. Human voice talent would almost certainly place appropriate prosodic cues that help in comprehension of $x^{(y+z)}$ as opposed to ($x^y + z$). Our formulation allows the model to leverage prosodic information available from the speech signal and capture prosodic distribution. \n\nTo accomplish local as well as global prosody control, we incorporate inductive biases into the model architecture in the form of fundamental frequency($F_0$). Specifically, we quantize $F_0$ into multiple bins and constrain the latent space to disentangle these quantized values from acoustics at the level of phonemes. Our model is explained in detail in section \\ref{proposed_approach}. During inference, the prosody distribution can be utilized to control and generate variability in the output speech. In short, our contributions from this work are: (1) We present EDITH, a hierarchical model that disentangles prosodic features in the form of $F_0$ enabling explicit global as well as local control. (2) We show that EDITH captures reliable representation of local prosody by generating speech with desired variations at the chosen linguistic level. \n\nsection{Emphasis by Disentangling Tonal Heuristics(EDITH)}\n\\label{proposed_approach}\n\n% This is the main section of the paper. This is where the technical novelty of your paper should be clearly explained and motivated. Whenever possible, take the time to remind people how your proposed model/approaches address the challenges highlighted in the introduction. Also, make sure that the novelty of your new approaches is highlighted (i.e., what part was already done vs. what part is novel). You can divide this into two parts - model description and learning. (1) Model Description: formalize mathematically your proposed model or approach. This should include the mathematical definition of the variables involved in your problem (e.g., input variable x and labels y). You should also include an objective function describing what you are modeling (e.g., P(y|x)). While this section may be relatively short (e.g., half a page), you should be consistent with your notation later in the paper. (2) Learning: Describe how you are learning the parameters of your model. State clearly your loss function and the learning algorithm used in your experiments. If you have enough space, give derivation of your gradient, at least for some of the main model parameters.\n\n\n\n\n%In our approach, we propose to incorporate automatically derivable information from speech data into the model architecture so as to enable to Seq2Seq architectures better model prosody. This is motivated by the understanding that the utterances themselves do not always contain all the information needed to comprehend the appropriate prosody information. The missing information is either part of background knowledge about the world - implicit to humans but not annotated in the data - or is provided by accompanying context of the utterance. Consider an example sentence: `\\textit{You do not have a pet shark}'. Most prosodic constructions for this sentence involve sarcasm since it is not commonplace to have sharks as pets - world knowledge. Similarly consider the sentence: `\\textit{I dont want to be a nun}'. The linguistic unit subject to realization of prosodic stress in this sentence depends on the context information. While it is possible to include context information in long form content generation such as audiobooks, there are scenarios where we do not have access to the context or the the available context is ambiguous. Consider the example of a TTS system deployed to assist visually impaired students comprehend math equations. There is not sufficient signal in the text to demarcate between $x^{(y+z)}$ and $x^y + z$. However, human voice talent would almost certainly place appropriate prosodic cues that help in comprehension in such cases. Therefore, we believe that it is helpful to leverage information from the speech signal and incorporate biases into the model architecture during the training itself to help the model accomplish the desired synthesis. \n\n\n\\begin{figure}[t]\n\\centering\n\\includegraphics[scale=0.2]{images/EDITH_arch.png}\n\\caption{\\textit{Architecture of EDITH. Circles denote LSTM cells, rectangles represent vectors and pentagons represent global latent vectors. (Best viewed in color)}} \n\\label{edith_architecture}\n\\end{figure} \n\nEDITH learns the joint distribution between pairs of temporal sequences \\{\\textbf{x}, \\textbf{y}\\} where \\textbf{x} denotes the features and \\textbf{y} denotes the acoustic parameters. Let Ti and To denote the lengths of input and output sequences respectively. Input features \\textbf{x} consist of both linguistic features denoted as \\textbf{$x_{linguistic}^{1:Ti}$} as well as features extracted from the acoustic signal denoted as \\textbf{$x_{acoustic}^{1:To}$}. The output features \\textbf{y} consist of linear feature representation \\textbf{$y_{linear}^{1:To}$} as well as mel features \\textbf{$y_{mel}^{1:To}$}. It has to be noted that \\textbf{$x_{acoustic}^{1:To}$} = \\textbf{$y_{mel}^{1:To}$}. To efficiently model varying prosody and prevent the averaging effect, we incorporate a variational layer. Therefore, EDITH is a conditional variational auto-encoder. During inference, we discard the encoder part of our model. Our model can be summarized by the following set of equations: \n\n%section{EDITH: Model Description}\n\n\n%We are interested in incorporating inductive biases into the architecture of Seq2Seq TTS enabling explicit control over prosody. Ideally, we desire the priors to push model towards learning and exploiting latent representations that can generate different prosodic events. In addition, we also desire the learnt representations to be generalized so that the approach can be extended to different speakers as well as languages or language combinations such as code mixing. While there are many other parameters associated with prosody, $F_0$ can be considered one of the most important attributes. Based on this, we have chosen to incorporate priors in terms of $F_0$. To accomplish this, we have extracted fundamental frequency using SPTK toolkit\\citep{sptk2009speech} and then quantized it into multiple bins with each bin spanning 25 Hz. In other words, continuous $F_0$ values were mapped to their discrete bin indices, resulting in ordinal $F_0$ values for each utterance. We then incorporated these values into the model architecture. We have investigated two ways of incorporating $F_0$ priors: (1) Explicit labeling by directly adding the ordinal $F_0$ as additional input to the model and (2) Implicit incorporation by adding prediction of ordinal $F_0$ as a secondary task in the model. The predicted $F_0$ is used as conditioning information to the decoder along with the input from soft attention. \n\n%\\begin{flalign*}\n\\begin{equation} \\label{eq1}\n\\begin{split}\nencoded ={}& \\textbf{H}^{Encoder}(x_{linguistic}, x_{acoustic}) \\\\\nz_{g}, z_{l} ={}& \\textbf{VI}(encoded) \\\\\n\\hat{y}_{mel} ={}& \\textbf{H}^{Decoder}(x_{linguistic},z_{g}, z_{l}) \\\\\n\\hat{y}_{linear} ={}& \\textbf{H}^{postnet}(\\hat{y}_{mel})\n\\end{split}\n\\end{equation}\n%\\end{flalign*}\n\n\\iffalse\n\\begin{equation} \\label{eq1}\n\\centering\n\\begin{split}\ne_{1:T_{input}} & = Encoder(x_{1:T_{input}}) \\\\\nz_{global}, z_{local} = VI(e_{1:T_{input}}) \\\\\n\\alpha_{i} & = Attention( e_{1:T_{input}}, d_{i-1}) \\\\\ne^1_i &= \\sum_j \\alpha_{ij} e_j \\\\\nd_i &= Decoder(e^1_i, s)\n\\end{split}\n\\end{equation}\nWe imagine the generative process as follows:\n\n\\begin{itemize}\n \\item We sample a global prosody embedding for the utterance.\n \\item Conditioned on the sampled embedding and the textual input, we predict local prosody embedding at time $t0$\n \\item The predicted prosody embedding is combined with the textual embedding to generate frame level acoustic representation at $t0$.\n \\item The process continues.\n\\end{itemize}\n\nsection{Model Components}\n\n\\subsubsection{EDITH Encoder}\n\n- clockwork hierarchical LSTM for prosodic features \\\\\n- Vanilla LSTM for linguistic features \\\\\n- Both reset at phone boundaries \\\\\n\n\n\\subsubsection{EDITH Variational Layer}\n\n- Vector Quantization. \\\\\n- Stop Gradient \\\\\n- Commitment Loss \\\\\n- Normalization of latent vectors\n\n\\subsubsection{EDITH Decoder}\n\n- Dot product Attention \\\\\n- 5 frames at once \\\\\n- No masking of outputs to enable better end of sentence prediction.\n\\fi\n\nDesign of our encoder is inpired by the encoder from \\citep{chive}. We use clockwork hierarchical LSTM to encode \\textbf{$x_{linguistic}^{1:Ti}$} and \\textbf{$x_{acoustic}^{1:To}$}. However, our models are clocked at the rate of phones as opposed to syllables. In addition, we do not incorporate any features from word or sentence levels in our encoder to keep the architecture compact. Our variational layer is derived from \\citep{vqvae} and is employed to generate global and local latent variables $z_{g}$, $z_{l}$ respectively. Our decoder is similar to a typical attention based acoustic decoder\\citep{tacotron_original} and includes a postnet. While similar in formulation, EDITH has an important difference from \\citep{chive} in that our local latent variables follow the rate of input as opposed to output as in \\citep{chive}. This allows us to exercise more control over the generated prosodic variations. \n\n% In \\citep{chive}, authors employ clockwork hierarchical decoding for this step. We employ a vanilla architecture instead.\n\n\\textbf{Optimization and Learning}: $x_{acoustic}$ is passed through phone rate LSTM. This is shown as block 1 in figure \\ref{edith_architecture}. $x_{linguistic}$ is passed through phone LSTM. The representations are concatenated and passed through EDITH Encoder. This is shown as block 2. Outputs from the encoder are passed through the variational layer where vector quantization is performed to pick the most suitable global latent prosodic vector. Conditioned on encoder outputs and the global latent prosodic vector, we predict Ti local prosodic vectors corresponding to predicted local prosodic features. \nWe constrain the local latent variables to correspond to quantized $F_0$ by modeling their prediction as a classification task. These local latent variables thus capture the local variations in prosody while global latent variable is reserved for capturing sentence level variations. Ground truth quantized values for classification are obtained by selecting the maximum bin within the duration of phoneme. This is shown as block 3 in the figure. We then employ dot product attention in our decoder. \\textbf{$y_{mel}$} is generated by decoder conditioned on local, global latent variables and the encoded $x_{linguistic}$. A postnet is employed to generate \\textbf{$y_{linear}$} conditioned on \\textbf{$y_{mel}$}. EDITH is optimized to minimize two \\textit{L1} losses one each for \\textbf{$y_{mel}$} and \\textbf{$y_{linear}$} and one classification loss for local latent variables. Additionally, to train the vector quantization layer, we minimize encoder commitment loss for $z_g$ and vector quantization loss following \\cite{vqvae} for both $z_g$ and $z_l$. This can be expressed as below:\n\n\\begin{equation} \\label{eq1}\n\\begin{split}\n\\textit{L} = \\lambda_{linear} \\sum_{t=0}^{To} \\| y_{linear}^t - \\hat{y}_{linear}^t \\| \\\\\n+ \\lambda_{mel} \\sum_{t=0}^{To} \\| y_{mel}^t - \\hat{y}_{mel}^t \\| \\\\\n+ \\lambda_{qF_0} \\sum_{t=0}^{Ti} Div(qF_0, \\hat{qF_0}) + \\lambda_{e} L_{e} + L_{VQ}\\\\\n\\end{split}\n\\end{equation}\n\n\n%The weight for the encoder commitment loss is linearly increased to reach 0.2 at update \n\n\n\\iffalse\n\\begin{itemize}\n\n \\item $x_{prosodic}$ is passed through phone rate LSTM. This is shown as block 1 in figure \\ref{edith_architecture}. Following the approach in \\citep{chive}, we reset the state of LSTM after every phoneme boundary.\n \\item $x_{linguistic}$ is passed through phone rate LSTM. This is shown as block 2 in figure \\ref{edith_architecture}.\n \\item The representations are concatenated and passed through EDITH encoder\n \\item Outputs from the encoder are passed through the variational layer where vector quantization happens to pick the most suitable global latent prosodic vector. This is shown as block 3 in figure \\ref{edith_architecture}.\n \\item Conditioned on encoder outputs and the global latent prosodic vector, we predict T local prosodic vectors corresponding to predicted local prosodic features. This is not shown for brevity in the figure.\n \\item Global and local latent vectors are then employed in addition to the attention outputs to generate the frame level acoustic features.\n \\item Loss Terms : (1) Mel Acoustic feature reconstruction (2) Linear Acoustic feature reconstruction (3) Prosodic Feature Reconstruction (3) Embedding Loss from latent space (4) Encoder commitment loss from latent space \n \n\\end{itemize}\n\n\\fi\n\n\nsection{Model Interpretation}\nThis approach can be interpreted as VQVAE\\citep{vqvae}. It can also be seen as GST\\citep{tacotron_styletokens} based encoding but our approach has two differences:(1) We do not use a different encoder for spectral information and (2) We explicitly constrain the latent classes to correspond to the quantized $F_0$s. We divide the model into individual blocks or modules. Therefore, it can be seen as an extension to Neural Module Networks\\cite{neural_module_networks}. In \\cite{chive}, authors introduce clockwork hierarchical VAE to predict $F_0$, duration and $C_0$. Our approach of incorporating $F_0$ information at the output of encoder in the form of additional task can be seen similar to this work. However, we use quantized $F_0$s, do not employ clockwork structure in our model and do not explicitly model duration or $C_0$.\n\n\nsection{Experimental Setup}\n\\label{experimental_setup}\n\n% Start this section by clearly stating what your main research questions are. Whenever possible, try to design experiments to test specific research hypotheses or questions. If you claimed that components A and B are the main novelties of your model, then you should have ablation experiments that compare your model with and without A (and similarly for B). Your experiments should also include comparison with baseline models (from your midterm report). Furthermore, the experiments should give the reader an understanding of the effect of your model hyper-parameters. For example, plot performance of your model with different regularization factors. Finally, make sure to write the experimental setup method in such a way that a person not familiar with your work would be able to reproduce your model just by reading the paper. Describe the dataset you are using for this project. Describe the input modalities and annotations available in this dataset. Describe your experimental methodology for evaluating the baseline model(s). This should include the way you split your dataset for training, validation and testing. It should also include any details about the hyper-parameters and the evaluation metrics. If space is too short, you can move some of the implementation details in the supplementary material, but the main design decision should be explained in the main paper.\n\n\n\n\\textbf{Data}: We have used data from LJSpeech dataset\\citep{ljspeech_dataset} to build our systems. We have used all of the 13100 sentences. The text was normalized manually to convert non standard forms (for ex. 1993) to written forms (nineteen ninety three).\n\n\n\\iffalse\nsection{Baseline}\n\nOur acoustic model is based on Tacotron\\cite{tacotron_original} Seq2Seq speech synthesis system and is built using PyTorch. We have used phones as the input instead of characters. We have not performed masking of padded frames as is typically done in Seq2Seq models. We found that not masking helps model better predict end of sentence as mentioned in \\cite{tacotron_original}. Since adjacent frames seem to be correlated, our decoder predicts 3 frames per timestep. We have used a batch size of 64 to train the baseline model. \n\\fi\n%Our vocoder is based on WaveNet\\cite{wavenet_original}. Speech signal was power normalized and squashed to the range (-1,1). We have used 16 bit mulaw quantization to encode individual samples. Instead of transposed convolutions we have employed linear interpolation to upsample the acoustic frames to match the time resolution of speech samples. To optimize the model, we use discretized Mixture of Logistics loss\\cite{salimans2017pixelcnn++,juvela2019waveform} with 12 logistic classes. \n\n\n\\textbf{Baselines}: Our acoustic model is based on Tacotron\\cite{tacotron_original} Seq2Seq speech synthesis system is built using PyTorch\\citep{pytorch}. We have not performed masking of padded frames as is typically done in Seq2Seq models. We found that not masking helps model better predict end of sentence as mentioned in \\cite{tacotron_original}. Since adjacent frames seem to be correlated, our decoder predicts 5 frames per timestep. Our model has three deviations from the original implementation: (1) Phones are used as the input instead of characters. (2) CBHG module in the encoder and postnet has been replaced with with three LSTM layers. (3) We use all the predicted frames at a time step as input to the decoder(as opposed to only the last time step) while predicting the next frames. We have used a batch size of 64 to train the baseline model. To enable control of prosody, we employ quantized $F_0$ values as additional inputs to this baseline model. For this, we first extract $F_0$ values for the dataset and quantize them into multiple bins each spanning 25 \\textit{Hz} without any overlap. These quantized $F_0$ values are embedded and added as additional inputs to the baseline model. In other words, this is a conditional generative model with phones and quantized $F_0$s as inputs. Additionally, we also build a model that uses word level prosodic features extracted using AuToBI\\citep{rosenberg2010autobi}. We refer to this system as \\textbf{AuToBI}.\n\n\\textbf{EDITH Hyperparameters}: The encoders of both $x_{acoustic}$ and $x_{linguistic}$ are realized using bidirectional LSTMs. We have used 256 as the hidden dimensions for both these encoders. Both our global and local latent variables are of 256 dimensions. We employ 10 global latent classes. The network to predict local latent variables is implemented using bidirectional LSTMs that takes 512 dimensional input and outputs 256 dimensional vectors. Encoder weight $\\lambda_e$ was linearly increased to 0.2 till 10K timesteps and remained constant after that. For quantization of $F_0$, we have followed the same procedure as in Baseline. 25 Hz was chosen as the size of bin. This effectively resulted in a total of 14 bins and thus 14 local latent classes. After every update step, we normalize the local latent variables by the norm. Since these classes correspond to ordinal data in terms of quantized $F_0$s, we believe that normalizing places the vectors on a unit circle.\n\n\\textbf{SubUtterance Models}: Long utterances present in audiobooks are rich in prosodic variations but also lead to computational overhead in terms of processing speed. Therefore, we have built systems that have access to only part of the utterance by selecting aligned segments of text and acoustics within a full sentence. We note that such an approach is already used for vocoding: Typical vocoders the authors are aware of are trained using aligned chunks of acoustic vectors and corresponding speech samples as opposed to full utterances. Encouraged by this, we build sub utterance based models for both baseline as well as proposed approach. To distinguish from the full sentence models, we refer to these systems as Sub Utterance Baseline(\\textit{SUB}) and Sub Utterance EDITH(\\textit{SUE}) while referring to the full sentence models as Full Utterance Baseline(\\textit{FUB}) and Full Utterance EDITH(\\textit{FUE}) respectively.\n\n%We have built multiple variants to compare the performance of the proposed approach. Extending our baseline, we have built systems that employ quantized F0 in their architectures. Additionally, we have also built models trained with access to only part of the full sentence. We refer to these systems as Full Sentence Quantized F0 (FSQ) and Sub Sentence Quantized F0 (SSQ) respectively. For each of the above systems, we have incorporated the prior information about F0 either at the input or as an additional loss term after the encoder. We refer to these systems with subscripts. For instance, the system employing full sentences for training with quantized F0 as inputs in addition to phoneme embeddings is referred to as $FSQ_i$. Similarly, the system employing sub sentence training but with additional loss term is referred to as $SSQ_l$. In addition to the proposed approaches, we have also built systems that employ AuToBI\\cite{rosenberg2010autobi} labels. We have not built a sub sentence variant in this approach and refer to the full sentence variant as AUTOBI. We have utilized 1300 sentences as validation data to tune our hyperparameters.\n\n\\begin{table}[t]\n\\centering\n\\caption{\\textit{Results from Preference and MOS Tests for Emphasis generation. The entries for the preference portion(columns 2 through 6)indicate preference values obtained by the systems in the first column against every other system in the subsequent columns.}} \n\\small\n\\setlength\\tabcolsep{2pt}\n\\begin{tabular}{|c|c|c|c|c|c|| c| }\n \\hline\n Config & $FUB$ & $FUE$ & $SUB$ & $SUE$ & AUToBI & MOS\\\\\n \\hline\n $FUB$ & - & 92 & 396 & 363 & \\textbf{441} & 4.0\\\\\n \\hline\n $FUE$(ours) & \\textbf{345} & - & \\textbf{424} & \\textbf{378} & \\textbf{477} & 4.0 \\\\\n \\hline\n $SUB$ & 91 & 86 & - & 235 & \\textbf{278} & 3.4 \\\\\n \\hline\n $SUE$(ours) & 64 & 86 & 243 & - & 227 & 3.6 \\\\\n \\hline\n AUToBI & 47 & 19 & 219 & 256 & - & 3.9 \\\\\n \\hline\n\\end{tabular}\n\\label{table_results_quantvsautobi}\n\\end{table}\n\n\\textbf{Evaluation}:\nEvaluation was performed in the form of listening tests using \\citep{testvox_parlikar}. We have conducted two types of listening tests: (1) Rating the naturalness in terms of Mean Opinion Score (MOS) on a scale of 1(least natural) to 5(highly natural) and (2) ABX Preference test on Emphasis where the users need to mention their preference towards either of the systems or state that they prefer neither. For the preference evaluation we have manually curated 50 sentences where the meaning was implied based on prosody. Participants were shown the entire sentence and its implication in parenthesis. An example sentence from our testset is `\\textit{It looks like a starfish} (but it really is not).' Every system was used to generate this test set\\footnote{in the mentioned example, the systems generated just the part '\\textit{It looks like a starfish}' and not the part in parenthesis}. For baseline and proposed approaches, the phonemes to be emphasized are rendered with embedding vector corresponding to bin 12 while others are rendered with bin 8 The participants are to mention their preference to the system that faithfully generates prosody in line with the information in parenthesis. We had 25 listeners and each participant rated 20 random sentences giving us a total of 500 ratings per pair of systems.\n\n\n\\begin{figure}[t]\n\\centering\n\\includegraphics[scale=0.25]{images/f0_manipulation.png}\n\\caption{\\textit{Plot of Fundamental Frequency($F_0$) trajectories obtained from generated waves using proposed approach \\textit{FUE}. Variants of the sentence `John loves Mary' are generated with emphasis on individual words(captialized). The blue trajectory corresponds to $F_0$ when no emphasis was applied to any word. The plot highlights that the proposed approach allows explicit local control at the desired level in the generated speech. We have submitted the generated wavefiles as supplementary material.}} \n\\label{plot_overview}\n% These and other samples are attached in the supplementary material for reference.\n\\end{figure} \n\n\n\n\\textbf{Discussion}: The preference evaluation results for the proposed approaches are presented in table \\ref{table_results_quantvsautobi}. We have excluded the \\textit{No Preference} values from this table for brevity. However, they can be estimated based on the values in the table. The full utterance based systems seem to outperform sub utternace as well as AuToBI based systems consistently. Within the full sentence systems, our proposed approach(\\textit{FUE}) outperforms the baseline conditional generative model(\\textit{FUB}). A sample output generated by conditioning the local latent variables to emphasize individual linguistic units(words) from our approach can be examined in figure \\ref{plot_overview}. An informal listening test in the scenarios where full sentence models were not preferred revealed an interesting finding: All these scenarios were when the emphasized word was the first in the sentence. We hypothesize that this might be due to the canonical word order(\\textbf{SVO}) in English. One approach to handle this could be to incorporate a suitable weighting to consider this effect and we plan to investigate this further. The sub utterance based approaches seem to match the performance of AUToBI systems while clearly under performing their full utterance counterparts. Informal listening evaluations revealed that the sub utterance models seem to have repetition of phoneme units within the generated sentence. We attribute this to the errors in alignment and phoneme boundary estimation and plan to investigate approaches to circumvent this behavior in future work. \n\n%Some listeners have expressed that they felt multiple words were focused in the sentence but nevertheless the intended word more or less stood out from the rest except when it was the first word in sentence. We hypothesize that this might be due to the data distribution and plan to investigate this further. \n\nsection{Conclusion}\n\nIn this case study, we have proposed an approach to obtain local and fine grained control over prosody in neural generative models for speech. For this we quantize fundamental frequency, which is highly correlated with prosody information, into multiple bins. We infer this information employing hierarchical global and local latent variables in the model architecture. We show that our approach generates appropriate emphasis at word level and significantly outperforms AuToBI in terms of flexibility. \n", "meta": {"hexsha": "6b94f60a39aac3015551761a9a6bffa7d039d08a", "size": 29610, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "quarterly_stuff/2020Q2/chapters/deentanglement_by_additional_divergences.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_additional_divergences.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_additional_divergences.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": 148.05, "max_line_length": 1689, "alphanum_fraction": 0.7976359338, "num_tokens": 6684, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792043, "lm_q2_score": 0.3311197264277872, "lm_q1q2_score": 0.16814652557691473}} {"text": "\n\\chapter{Managing resources}\n\\label{sec:resourcesManagement}\n\nThis chapter focuses on the resource storage architecture of \\emph{HyCube} and describes individual DHT operations. Possible operations on the resources in \\emph{HyCube} include inserting resources to the DHT (PUT) and retrieving resources (GET). Additionally, \\emph{HyCube} supports refreshing resources (REFRESH) - updating resource expiration times, removing resources from the DHT (DELETE), and resource replication among nodes. In \\emph{HyCube}, the nature of resources, as well as the way of calculating the resource key depends at the application - \\emph{HyCube} provides generic support for any resource type. The key (hash) is expected to be within the node identifier space - $(d \\cdot l)$-bit number ($d$ - the number of dimensions, $l$ - the number of levels of the hierarchical hypercube), and the node responsible for resources with the hash value $key$ is the closest node to $key$ (Euclidean metric) among all nodes existing in the system. However, to increase the availability and provide load balancing, the resource may be replicated to other nodes (certain number of closest nodes to $key$).\n\nThere are two main approaches for storing resources - one is based on storing the actual resources (for example files) by the DHT nodes to which the resource keys are mapped, while the second approach is based on storing pointers by the DHT nodes - the information where individual resources are stored (for example from which nodes particular files may be downloaded). The technique adopted by \\emph{HyCube} is universal and the choice which approach is used is made at the application level. The resource entries in \\emph{HyCube} (stored by nodes) consist of a resource descriptor (metadata) and resource data. However, the data may be empty, and the pointer to the actual data might be stored within the resource descriptor, or within the data field. The resource descriptor consists of a certain number of key-value pairs (both keys and values are text strings). There are four predefined keys for resource descriptors:\n\n\\pagebreak\n\n\\begin{itemize}\n\t\\renewcommand{\\labelitemi}{$\\bullet$}\n\t\\item \\emph{\\textbf{resourceId}}\t- should be a unique identifier of the resource, allowing to unambiguously distinguish it from any other resource\n\t\\item \\emph{\\textbf{resourceUrl}}\t- determines the location of the resource, allowing to unambiguously locate the resource copy among possible multiple copies/instances of the same resource (having the same value of resourceId)\n\t\\item \\emph{\\textbf{resourceName}}\t- the name of the resource\n\t\\item \\emph{\\textbf{resourceType}}\t- resource type (possible values, as well as the way the type is used, are application-specific)\n\\end{itemize}\n\nSpecifying values for \\emph{resourceId} and \\emph{resourceUrl} is mandatory, because these values are used by the resource management algorithms (storing, refreshing, getting, deleting and replication). A resource key may theoretically be the same for multiple different resources (usually it is the result of a hash function on the resource name or content), and \\emph{resourceId} is essential to unambiguously distinguish the resources. If the resource entries stored in the DHT are used only as references to nodes storing actual resources, \\emph{resourceUrl} value should make it possible to uniquely locate the resource copy that the entry points. Depending on a system parameter value, nodes may store multiple copies of the same resource if the \\emph{resourceUrl} values are different.\n\nIn addition to four predefined resource descriptor keys, at the application level, additional keys may be defined. The resource metadata might then be used to apply additional query criteria on the resources returned by nodes - only resources matching all criteria specified in queries (GET) would be returned to the requesting node. The criteria might also be used when deleting resources from the DHT.\n\nThe following sections describe the operations supported by \\emph{HyCube} DHT. The discussion focuses on operations on resource entries and assumes that they contain the resource data. If the data is, in fact, located somewhere else, and resource entries are only pointers, it is assumed that the actual data insertion, retrieval and deletion is handled by the external application, beyond the scope of \\emph{HyCube}.\n\n\n\n\n\\section{Storing resources in the DHT}\n\nThe PUT operation allows a node to store a resource in the distributed hash table. A node initiating a PUT operation routes a PUT message containing the resource descriptor (and data) specifying the resource key as the message recipient. The message is routed to the closest node to the specified key (until no further routing is possible), which saves the resource in its local storage and sends the status of the operation (PUT\\_REPLY message containing the information whether the resource was saved in the node's local storage or not) directly to the requesting node. Before storing the resource, the closest node checks whether it is one of the $k_{store}$ closest nodes to the specified key ($k_{store}$ is the system parameter). Based on this check, the node decides whether the resource should be accepted or not. The check is made based on analyzing the local neighborhood set. For that purpose, a local estimation of the network ``density'' $\\rho$ (the author's definition) is calculated as follows:\n\n\\begin{equation}\n\\rho = \\frac{\\sum_{i=0}^{t} \\rho_i}{t+1}\n\\end{equation}\n\n\\noindent\nwhere $\\rho_i$ is defined as follows:\n\n\\begin{equation}\n\\rho_i = \\frac{\\left|\\{N \\in NS : dist(N) \\leq dist(N_i)\\}\\right|}{dist(N_i)^d}\n\\end{equation}\n\n\\noindent\nwhere $NS$ is the neighborhood set, $dist(N)$ denotes the distance to node $N$, $d$ is the number of dimensions of the hierarchical hypercube, and $t \\in [0, |NS|-1]$ is the node index (in the neighborhood set ordered ascending by distances) calculated as follows:\n\n\\begin{equation}\nt = \\max \\big(0, \\mathop{\\mathrm{round}}(\\varphi \\cdot |NS|) - 1 \\big)\n\\end{equation}\n\n\\noindent\nwhere $\\varphi \\in (0,1]$ is a system parameter - the quantile function threshold, determining what number of closest neighborhood set nodes should be taken into account for calculating the density. Each density $\\rho_i$ represents the number of nodes in a unit $d$-sphere calculated based on $(i+1)$-th node (the value $dist(N_i)^d$ in the denominator is proportional to the volume ($d$-dimensional volume) of a unit $d$-sphere, so $\\rho_i$ is proportional to the real local density). $\\rho$ is the average density - based on all $t+1$ nodes. Calculating the average value makes the density estimation less vulnerable to fluctuations of single node distances.\n\nBased on $\\rho$, it is possible to estimate the number of nodes in the system in a $d$-sphere of any given radius $r$:\n\n\\begin{equation}\nn = \\rho \\cdot r^d\n\\end{equation}\n\n\\noindent\nThus, the estimated radius of the $d$-sphere containing $k$ closest nodes to any given key may be calculated as:\n\n\\begin{equation}\nr_k = \\left(\\frac{k}{\\rho}\\right)^{\\frac{1}{d}}\n\\end{equation}\n\nHaving calculated $r_k$ for $k = k_{store}$, it is possible to estimate whether the node is one of the $k_{store}$ closest nodes to any given key - the node should check if the distance to the key is less than or equal to $r_k$. However, such en estimation might not be accurate enough. The radius used for the density calculation is the minimum radius covering the number of nodes considered (distance to $N_i$), which may cause nodes to incorrectly estimate the density, resulting in the number of nodes accepting resources being smaller than $k_{store}$. Taking this problem into account, it is necessary to scale the estimated value $r_k$, and the node should rather check whether the following condition is met:\n\n\\begin{equation}\ndist(key) \\leq r_k \\cdot \\xi\n\\end{equation}\n\n\\noindent\n$\\xi$ is the system parameter - estimated distance coefficient. The value should be adjusted for the chosen value of $\\varphi$. The higher is the value of this parameter, the more nodes will accept resources, considering themselves as one of $k_{store}$ closest nodes to the resource key. The value should be large enough to ensure that resources will be accepted by at least $k_{store}$ nodes in the system, regardless of their key. Because for certain nodes, the locally calculated density may be smaller than the average density, for certain keys, more nodes than $k_{store}$ could potentially accept the resource. This is however not a serious issue, meaning that the resource will be more likely to be accepted in less dense areas, which would have positive impact on replication under churn (replication is discussed in Section \\ref{sec:replication}).\n\nWhen the neighborhood set nodes selection forces the diversity of directions in which the nodes are located, the most distant neighbors might not reflect the real closest existing nodes (omitting some close nodes). In such a case the real density could be higher than estimated. Performed simulations showed that, in such a case, the numbers of nodes accepting resources start growing rapidly for $\\varphi > 0.5$. Because forcing uniform distribution of neighborhood set nodes is the default behavior in \\emph{HyCube}, $\\varphi$ should be given a value smaller than 1 to achieve better accuracy (skipping the most distant nodes). However, too small values of $\\varphi$ would cause the density to be calculated taking only a very small number of nodes into account. Although the density estimation may skip some close nodes even for smaller values of $\\varphi$, the performed simulations indicated that the value $\\varphi=0.5$ provides good and relatively stable density estimation (relatively small variance of the numbers of accepting nodes).\n\nThe simulation results indicated that, for $\\varphi=0.5$, the values of $\\xi \\geq 1.1$ allow resources to be accepted by at least $k_{store}$ nodes for great majority of randomly generated keys. For values $\\xi \\geq 1.2$, almost for all tests, at least 8 nodes accepted the resources. $\\xi$ should be given a higher value if the nodes should be accepted by more than $k_{store}$ nodes, for example to force accepting resources by each of $k_{store}$ closest nodes to the key (which is a different condition than accepting resources by any $k_{store}$ nodes\\footnote{Because the local density may be different in the proximity of the estimating node, and the resource key, certain more distant nodes may accept the resource, while some close nodes may reject the resource.}). It may, however, cause resources to be potentially accepted by a larger number of nodes. When resources are required to be accepted by a certain number of closest nodes (by all of the closest nodes) with high probability, it may also be ensured by increasing the value of $k_{store}$, leaving the value $\\xi$ equal to 1.1 or 1.2, which would also cause the resources to be accepted by more nodes, at the same time, increasing the probability of accepting resources by the closest nodes to the resource keys. The values of these parameters should be adjusted to actual needs, depending on the application.\n\nWhen a node accepts a resource, it stores the resource in its local storage, making it accessible for other nodes to retrieve (GET). Because potentially, there might be many resource entries with the same key, but not representing the same resource (different \\emph{resourceId}), such resources are considered separate entities and are stored separately. Furthermore, it is possible for a node (depending on the value of a system parameter) to store multiple resources with the same \\emph{resourceId}, but having different values of \\emph{resourceUrl}. Such resource entries represent the same resource located physically in different locations. The maximum number of resource entries stored for any \\emph{resourceId} is determined by the value of another system parameter.\n\nWhen resources are being stored by nodes, they are assigned expiration times (the resource validity time is determined by a system parameter). After the expiration time elapses for any resource, the resource is deleted from node's local storage.\n\n\n\n\\section{Refreshing resources in the DHT}\n\nAs described in the previous section, every resource is given an expiration time, and the resource entry contains the last refresh time. After the expiration time (\\emph{refreshTime} + \\emph{expirationTime}), the resource is deleted from the storing node's local storage. To prevent deleting resources, the node placing the resource in the DHT may send a REFRESH\\_PUT message to the node storing the resource, which would renew its refresh time. The new refresh time is sent within the refresh message. However, if the refresh time received is greater than the current local time, the new refresh time is given the value of the current local time. To avoid problems caused by two nodes potentially located in different time zones, the refresh time should always be converted to the UTC (Coordinated Universal Time). The REFRESH\\_PUT message is routed towards the resource key, and when no next hop is found (closest node was reached), a check is made whether the resource with the specified \\emph{resourceId} and \\emph{resourceUrl} is present in the local storage and whether the node is one of the $k_{store}$ closest nodes to the resource key. If both conditions are met, the node updates the refresh time for the resource entry and sends a REFRESH\\_PUT\\_REPLY message directly to the requesting node. The REFRESH\\_PUT\\_REPLY contains the status of the operation. If at least one of the checks fails, a negative response is sent.\n\nThis mechanism is supposed to prevent maintaining resources inserted to the DHT when they are no longer current. Nodes publishing resources in the DHT should therefore periodically refresh their validity time, and the refresh interval should be smaller than the resource expiration time.\n\n\n\n\n\\section{Retrieving resources from the DHT}\n\nIn order to retrieve (GET) resources from the DHT, a node sends a GET message containing the requested key and additional criteria, specifying the requested key as the message recipient. Depending on the value of the request parameter \\emph{GetFromClosest}, the message is either routed to the node closest to the resource key, which searches its local storage for the resources according to the specified criteria, or the resource(s) are returned by the first node on the route that is able to return the resource(s). The returning node sends back (directly) a GET\\_REPLY message containing the results, or an empty result, depending whether the resources were found or not. If \\emph{GetFromClosest} equals \\emph{false} (the resource is supposed to be returned by the first node on the route storing it), every node on the route (including the initiating node itself) first makes a check, whether the node is one of $k_{store}$ closest nodes to the resource key, and whether the resource requested is stored in the local storage. If both conditions are met, the result is immediately returned directly to the requesting node. Otherwise, the node tries to route the message. If, however, the message cannot be routed because no next hop is found in the routing tables (the closest node is reached), the node returns the results found locally (if any), even it is not one of the $k_{store}$ closest nodes to the resource key. This method of retrieving resources yields very good properties in terms of load balancing if the resource is replicated to multiple nodes (Section \\ref{sec:replication}). When the message reaches one of the $k_{store}$ closest nodes, this node is likely to contain all published copies of the resource, while if the route is broken before one of the nodes maintaining the resource (considering itself as one of the $k_{store}$ closest nodes) is reached, this node may return only partial result or not return anything at all (resources might have been stored in that node in the past, and, in some cases, resources may be replicated to more than $k_{store}$ nodes).\n\nEvery GET request, in addition to the resource key, contains additional resource search criteria (key-value pairs). The criteria key set should be a subset of the resource descriptor key set. Before returning the GET result, nodes filter out the resources, and only resources matching the criteria are returned (matching resource descriptor values for all the keys specified in the criteria).\n\n\n\n\n\n\n\\section{Resource removal from the DHT}\n\nIn certain applications, it would be desirable to allow nodes to remove (DELETE) resources that have been earlier inserted into the distributed hash table. \\emph{HyCube} provides such a possibility. A node willing to delete a resource should send a DELETE message addressed to that node (or to the resource key, in which case the message would be routed to the node closest to the resource key), specifying the exact criteria for deletion - key-value pairs (the key set should be a subset of the resource descriptor key set: \\emph{resourceId}, \\emph{resourceUrl}, \\ldots). The resource entry should be deleted only when all key-value pairs specified within the criteria match those of the resource entry descriptor. For instance, a node might decide to delete a resource copy published by itself, while still leaving other copies of the resource accessible. In this case, the node would specify the \\emph{resourceId} and \\emph{resourceUrl}, which unambiguously identifies that particular instance of the resource. Every node processing a DELETE message is supposed to send a DELETE\\_REPLY message directly to the requestor, containing the status of the operation (\\emph{true} is the resource was deleted, \\emph{false} otherwise).\n\nWhen a resource is removed from one node's local storage, it may still be accessible through other nodes, and may be again inserted to the node that removed it through the replication mechanism. That is why the resource being removed should be deleted from all nodes storing the resource at the same time. It is however never guaranteed that the resource is entirely deleted from the DHT, as it is difficult to track to which nodes the resource was replicated. All resources are however assigned the expiration time (mentioned earlier), which causes resources to be deleted after certain amount of time if they are not refreshed. This mechanism is able to eventually remove outdated resources from the DHT completely.\n\n\n\n\n\n\n\\section{Storage access control}\n\nBy default, in \\emph{HyCube}, it is possible to perform PUT, REFRESH\\_PUT, GET and DELETE operations on any resource by any node. In many cases, this behavior might not be desirable. The design of \\emph{HyCube} allows introducing an additional (application defined) component that would control which operations are allowed and which are not, based on the resource descriptor and the node performing the operation. For example, such a mechanism might be enabled to allow REFRESH\\_PUT and DELETE operations to be performed only by the nodes that originally put the resource in the DHT. Such a check could be based for example on the \\emph{resourceUrl} value. Another example could be limiting access for resources for certain nodes based on the resource metadata.\n\n\n\n\n%\\section{Exact versus routed resource operations}\n\\section{Routing requests vs sending requests directly to nodes}\n\nAs described in the previous sections, PUT, REFRESH\\_PUT, GET and DELETE messages are routed towards the resource key, and the responses are returned directly to the requesting node. However, another approach may be taken if the request should be sent to a certain exact node (known to the requesting node). In such a case, this exact node's ID should be set as the recipient of the message and the message should be sent directly to the recipient. The message would then not be routed further, even if it is not the closest node to the resource key. Specifying the exact recipient for resource operation messages allows placing resources in multiple nodes, updating the refresh time (REFRESH) for resources stored in multiple nodes, and retrieving the resources from several nodes at a time. Usually, to increase resource availability, the resource is stored in several nodes - the closest nodes to the resource key. Moreover, as already mentioned, the DELETE operation would successfully remove a resource from the DHT only if the resource is removed from all the nodes storing it. To determine the set of closest nodes, the search procedure may be performed, and the messages may then be sent directly to the nodes found. Depending on the application, other techniques may be employed - for instance, if the resource should be put to only one node (for example allocation of subtasks in a distributed computing system), a node lookup might be used to find the node closest to a certain identifier.\n\nIn majority of applications, the resources are stored by multiple nodes, and the PUT operation should usually be preceded by the search locating the closest nodes, to which the resources are then inserted. However, retrieving the resources from the DHT, in most cases, may be done more efficiently, without the use of the search procedure. In the routing approach (towards the resource key), it is possible to limit the number of messages exchanged between nodes to the minimum, finding the resource with high probability in the closest node to the resource key. If additionally, the value of the option \\emph{GetFromClosest} is set to \\emph{false}, the check is made by all nodes on the route, increasing the probability of finding the resource requested. Furthermore, such a way of retrieving resources would provide simple, but effective load balancing - the first node containing the resource would be different depending on the path (direction from which the request comes).\n\n\n\n\n\n\n\n\\section{Resource replication and load balancing}\n\\label{sec:replication}\n\nIt was already mentioned that, to increase availability of resources, they may me replicated to multiple nodes. In \\emph{HyCube}, resources are replicated among a certain number of nodes (let us denote this number by $k_{rep}$) that are the closest ones to the resource keys ($k_{rep}$ is a system parameter). However, in dynamic systems, the set of $k_{rep}$ closest nodes may change very quickly, making resources difficult to locate. At one extreme, all nodes responsible for some resource key may leave the system, making the resources unavailable. Therefore, it is crucial that the resources get constantly replicated among $k_{rep}$ currently closest nodes. $k_{rep}$ may be larger than $k_{store}$, but in this case, some nodes may not return the replica when receiving a GET message (with the \\emph{GetFromClosest} option set to \\emph{false}) - instead they would route the message further towards the resource key. \n\nThe replication procedure is run periodically by all nodes. Every node sends information about all resources it maintains to all the nodes in its neighborhood set (REPLICATE messages). To keep the message sizes at reasonable levels, the resources stored for different keys should be sent in separate REPLICATE messages. The number of nodes to which the replication information is sent may be limited to a certain maximum number of nodes by setting the value of the system parameter \\emph{maxReplicationNSNodesNum}, in which case the REPLICATE messages will be sent only to \\emph{maxReplicationNSNodesNum} closest nodes in the neighborhood set. However, to allow resources to be replicated towards all directions in the Euclidean space, the value of this parameter should not be too low. The replication information contains only the resource descriptors (metadata) and the last resource refresh time. Upon receiving a REPLICATE message, for every replicated resource, the receiving node should check if it is one of the $k_{rep}$ closest nodes to the resource key. If the node is one of the closest nodes, for each resource corresponding to that key, the node should check if it maintains this resource in its local storage. If the resource is already stored (\\emph{resourceId} and \\emph{resourceUrl} are compared), the refresh time of the resource should be updated (if the refresh time for the resource in the replication message is greater than the local refresh time). If the resource is, however, not stored in the local storage, the node should perform the GET operation (GET messages routed towards the resource key, the value of \\emph{GetFromClosest} flag used in replication is set by a system parameter), and, upon receiving the GET\\_REPLY, insert the resource to its local storage, setting the refresh time to the one received in the REPLICATE message. However, if the refresh time received is greater than the current local time, the refresh time is set to the current time.\n\nThe replication mechanism of \\emph{HyCube}, in addition to increasing resource availability, also provides load balancing for most popular resources. \\emph{HyCube} is designed to realize this approach by allowing an external (application-specific) module, implementing an appropriate interface, to be registered - a replication spread manager, which may analyze all PUT, REFRESH\\_PUT, GET and DELETE operations and calculate the replication spread factor $\\psi$ for each resource stored. Based on $\\psi$, the node performing the replication calculates to how many nodes the resource should be replicated:\n\n\\begin{equation}\nk_{rep} = \\psi \\cdot k_{rep}\n\\end{equation}\n\n\\noindent\nwhere $k_{bal}$ is the default number of replication nodes. The value of $k_{bal}$ for every resource is included in the REPLICATE messages sent to nodes. The nodes receiving replication information, accept the replicas only when they determine that they are within $k_{bal}$ closest nodes to the resource key. For more popular resources, the replication spread manager may increase the value of $\\psi$, which would cause the resource to be replicated to more nodes. When combined with retrieving (getting) resources with \\emph{GetFromClosest} option set to \\emph{false}, such a replication mechanism provides very good load balancing - in a multidimensional space, the increase of the replication radius would cause more nodes handling GET requests coming from different directions. As already mentioned, the value of $k_{rep}$ (and thus $k_{bal}$) may be greater than the system parameter $k_{store}$. However, in this case, some nodes, although accepting the replica, would not return the resource when receiving a GET message with the \\emph{GetFromClosest} option set to \\emph{false}. The implementation of the replication spread manager is application-dependent and is beyond the scope of \\emph{HyCube}. The default implementation returns the value $\\psi = 1$ for every resource.\n\nOne more remark should be made regarding replication and updating refresh times for resources. Whenever there is a time difference between any two nodes, the refresh time sent within a REPLICATE message may be inadequate when the message is received by another node. That could potentially cause the refresh time to be automatically increased just by the replication process, which is not a desired behavior. However, the new refresh time assigned to resources is always the smaller of the two values - the refresh time received and the current local time, meaning that the refresh time will never be increased by exchanging REPLICATE messages to a larger value than the current local time. The refresh time may also be increased as a result of receiving a REFRESH\\_PUT message, when a larger refresh time value is specified by the refreshing node. Although there is also a possibility that the refreshing node's time is shifted (relatively to the node receiving the refresh request), the refresh time will never be set to a greater value than the receiving node's local time. Thus, the only potentially problematic situation may occur when both, the refreshing and the refreshed node have their local clocks going faster. In such a case, the refreshed node would potentially send a wrong refresh time in replicate messages (potentially far in future). However, as other nodes would then set the refresh time to their current local time value, and the replicating node (the one with the clock going faster) would stop replicating the resource after it is outdated according to its local time, the excess storing time at the whole DHT level would, at one extreme, be equal to the resource expiration time (the worst case), and the resource would then be considered outdated and removed by all other nodes.\n\nThe replication mechanism employed by \\emph{HyCube} is able to maintain replica availability in the presence of many node failures, as well as under high rates of churn. Although in such situations, it may happen that certain resources are replicated to more nodes than needed, this anomaly would be only temporary - the excess replicas would be removed after their expiration time (the resources stored by the excess nodes would not be refreshed).\n\nAlthough replicating resources is performed every certain time interval, the algorithm does not introduce much overhead, because only a small number of REPLICATE messages are exchanged, and nodes physically transfer the resources only when it is needed.\n\n\n\n\n\n\n\n\n% ex: set tabstop=4 shiftwidth=4 softtabstop=4 noexpandtab fileformat=unix filetype=tex encoding=utf-8 fileencodings= fenc= spelllang=pl,en spell:\n\n", "meta": {"hexsha": "96d006f30e745cbb93ec4a3b7e1fc8f077444211", "size": 29519, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "src/documentation/protocol_doc_tex/tex/resources-management.tex", "max_stars_repo_name": "arturolszak/hycube", "max_stars_repo_head_hexsha": "e7dc0bc7ff5d7c1d406bfee952398515f3f6b6c8", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2018-07-18T14:05:13.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-18T02:15:36.000Z", "max_issues_repo_path": "src/documentation/protocol_doc_tex/tex/resources-management.tex", "max_issues_repo_name": "suhasagg/hycube", "max_issues_repo_head_hexsha": "e7dc0bc7ff5d7c1d406bfee952398515f3f6b6c8", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2016-10-02T14:25:30.000Z", "max_issues_repo_issues_event_max_datetime": "2016-11-27T18:10:58.000Z", "max_forks_repo_path": "src/documentation/protocol_doc_tex/tex/resources-management.tex", "max_forks_repo_name": "suhasagg/hycube", "max_forks_repo_head_hexsha": "e7dc0bc7ff5d7c1d406bfee952398515f3f6b6c8", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-10T16:08:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-10T16:08:30.000Z", "avg_line_length": 176.7604790419, "max_line_length": 2091, "alphanum_fraction": 0.7973169823, "num_tokens": 6201, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526660244838, "lm_q2_score": 0.29421495978593415, "lm_q1q2_score": 0.16765917921830087}} {"text": "\\section{UTxO}\n\\label{sec:utxo}\n\nA key constraint that must always be satisfied as a result and precondition of\na valid ledger state transition is called the \\textit{general accounting\nproperty}, or the \\textit{preservation of value} condition. Every piece of\nsoftware that is a part of the implementation of the\nCardano cryptocurrency must function in such a way as to not result in\na violation of this rule.\nIf this condition is not satisfied, it is an indicator of\nincorrect accounting, potentially due to\nmalicious disruption or a bug.\n\nThe preservation of value is expressed as an equality that uses values in\nthe ledger state and the environment, as well as the values in the body of\nthe signal transaction.\nWe have defined the rules of the delegation protocol in a way that should\nconsistently satisfy the preservation of value. In the future, we hope to\ngive a formally-verified proof that every \\textit{valid} ledger state satisfies\nthis property.\n\nIn this section, we discuss the relevant accounting that needs to be done\nas a result of processing a transaction, i.e.~the deposits for all certificates,\ntransaction fees, transaction withdrawals and refunds for individual\nderegistration, so that we may keep track of whether the preservation of\nvalue is satisfied. Stake pool retirement refunds are not triggered by a\ntransaction (but rather, happen at the epoch boundary) and are therefore\nnot considered in our state change rules invoked due to a signal transaction.\n\nNote that when a transaction is issued by a wallet to be applied to the ledger\nstate (i.e.~processed), the rules in this section are defined in such a way that it is impossible to\napply only some parts of a transaction (e.g.~only certain certificates).\nEvery part of the transaction must be valid and it must be live, otherwise\nit is ignored entirely. It is the wallet's responsibility to inform the user\nthat a transaction failed to be processed.\n\n\\subsection{UTxO Transitions}\n\\label{sec:utxo-trans}\n\nFigure~\\ref{fig:functions:utxo} defines functions needed for the UTxO transition system.\nSee Figure~\\ref{fig:defs:utxo-shelley} for most of the definitions used in the transition system.\n\n\\begin{itemize}\n\n \\item\n The function $\\fun{outs}$ creates unspent outputs generated by a transaction, so that\n they can be added to the ledger state. For each output in the transaction,\n $\\fun{outs}$ maps the transaction id and output index to the output.\n\n \\item\n The $\\fun{ubalance}$ function calculates sum total of all the coin in a given UTxO.\n \\item\n The $\\fun{wbalance}$ function calculates the total sum of all the reward withdrawals in a\n transaction.\n\n \\item The calculation $\\fun{consumed}$ gives the value consumed by the\n transaction $\\var{tx}$ in the context of the protocol parameters, the\n current UTxO on the ledger and the registered stake credentials. This\n calculation is a sum of all coin in the inputs of $\\var{tx}$, reward\n withdrawals and stake credential deposit refunds. Some of the definitions\n used in this function will be defined in Section~\\ref{sec:deps-refunds}. In particular,\n $\\fun{keyRefunds}$ is defined in Figure~\\ref{fig:functions:deposits-refunds}.\n\n \\item The calculation $\\fun{produced}$ gives the value produced by the transaction $\\var{tx}$\n in the context of the protocol parameters and the registered stake pools.\n This calculation is a sum of all coin in the outputs of $\\var{tx}$,\n the transaction fee and all needed deposits.\n Some of the definitions used in this function will be defined in\n Section~\\ref{sec:deps-refunds}.\n In particular, $\\fun{totalDeposits}$ is defined in Figure~\\ref{fig:functions:deposits-refunds}.\n\\end{itemize}\n\nFor a transaction and a given ledger state, the preservation of value property holds\nexactly when the results of $\\fun{consumed}$ equal the results of $\\fun{produced}$.\nMoreover, when the property holds, value is only moved between transaction outputs,\nthe reward accounts, the fee pot and the deposit pot.\n\nNote that the $\\fun{produced}$ function takes the registered stake pools ($\\var{poolParams}$)\nas a parameter only in order to determine which pool registration certificates are\nnew (and thus require a deposit) and which ones are updates.\nRegistration will be discussed more in Section~\\ref{sec:delegation-shelley}.\n\n\\begin{figure}[htb]\n \\begin{align*}\n & \\fun{outs} \\in \\TxBody \\to \\UTxO\n & \\text{tx outputs as UTxO} \\\\\n & \\fun{outs} ~ \\var{tx} =\n \\left\\{\n (\\fun{txid} ~ \\var{tx}, \\var{ix}) \\mapsto \\var{txout} ~\n \\middle|\n \\var{ix} \\mapsto \\var{txout} \\in \\txouts{tx}\n \\right\\}\n \\nextdef\n & \\fun{ubalance} \\in \\UTxO \\to \\Coin\n & \\text{UTxO balance} \\\\\n & \\fun{ubalance} ~ utxo = \\sum_{(~\\wcard ~ \\mapsto (\\wcard, ~c)) \\in \\var{utxo}} c\n \\nextdef\n & \\fun{wbalance} \\in \\Wdrl \\to \\Coin\n & \\text{withdrawal balance} \\\\\n & \\fun{wbalance} ~ ws = \\sum_{(\\wcard\\mapsto c)\\in\\var{ws}} c\n \\nextdef\n & \\fun{consumed} \\in \\PParams \\to \\UTxO \\to \\TxBody \\to \\Coin\n & \\text{value consumed} \\\\\n & \\consumed{pp}{utxo}{tx} = \\\\\n & ~~\\ubalance{(\\txins{tx} \\restrictdom \\var{utxo})} +\n \\fun{wbalance}~(\\fun{txwdrls}~{tx}) \\\\\n & ~~ + \\keyRefunds{pp}{tx} \\\\\n \\nextdef\n & \\fun{produced} \\in \\PParams \\to (\\KeyHash_{pool}\\mapsto\\PoolParam) \\to \\TxBody \\to \\Coin\n & \\text{value produced} \\\\\n & \\fun{produced}~\\var{pp}~\\var{poolParams}~\\var{tx} = \\\\\n &~~\\ubalance{(\\outs{tx})}\n + \\txfee{tx} + \\totalDeposits{pp}{poolParams}{(\\txcerts{tx})}\\\\\n \\end{align*}\n\n \\caption{Functions used in UTxO rules}\n \\label{fig:functions:utxo}\n\\end{figure}\n\n\\clearpage\n\n\nThe types for the UTxO transition are given in Figure~\\ref{fig:ts-types:utxo-shelley}.\nThe environment, $\\UTxOEnv$, consists of:\n\n\\begin{itemize}\n \\item The current slot.\n \\item The protocol parameters.\n \\item The registered stake pools\n (also explained in Section~\\ref{sec:delegation-shelley},\n Figure~\\ref{fig:delegation-defs}).\n \\item The genesis key delegation mapping.\n\\end{itemize}\nThe current slot and registrations are needed for the refund calculations\ndescribed in Section~\\ref{sec:deps-refunds}.\n\nThe state needed for the UTxO transition $\\UTxOState$, consists of:\n\n\\begin{itemize}\n \\item The current UTxO.\n \\item The deposit pot.\n \\item The fee pot.\n \\item Proposed updates (see Section~\\ref{sec:update}).\n\\end{itemize}\nThe signal for the UTxO transition is a transaction.\n\n\\begin{figure}[htb]\n \\emph{UTxO environment}\n \\begin{equation*}\n \\UTxOEnv =\n \\left(\n \\begin{array}{r@{~\\in~}lr}\n \\var{slot} & \\Slot & \\text{current slot}\\\\\n \\var{pp} & \\PParams & \\text{protocol parameters}\\\\\n \\var{poolParams} & \\KeyHash_{pool}\\mapsto\\PoolParam & \\text{stake pools}\\\\\n \\var{genDelegs} & \\GenesisDelegation & \\text{genesis key delegations} \\\\\n \\end{array}\n \\right)\n \\end{equation*}\n %\n \\emph{UTxO States}\n \\begin{equation*}\n \\UTxOState =\n \\left(\n \\begin{array}{r@{~\\in~}lr}\n \\var{utxo} & \\UTxO & \\text{UTxO}\\\\\n \\var{deposits} & \\Coin & \\text{deposits pot}\\\\\n \\var{fees} & \\Coin & \\text{fee pot}\\\\\n \\var{pup} & \\PPUpdateState & \\text{proposed updates}\\\\\n \\end{array}\n \\right)\n \\end{equation*}\n %\n \\emph{UTxO transitions}\n \\begin{equation*}\n \\_ \\vdash\n \\var{\\_} \\trans{utxo}{\\_} \\var{\\_}\n \\subseteq \\powerset (\\UTxOEnv \\times \\UTxOState \\times \\Tx \\times \\UTxOState)\n \\end{equation*}\n %\n \\caption{UTxO transition-system types}\n \\label{fig:ts-types:utxo-shelley}\n\\end{figure}\n\nThe UTxO transition system is given in Figure~\\ref{fig:rules:utxo-shelley}.\nRule~\\ref{eq:utxo-inductive-shelley} specifies the conditions under which a transaction can\nbe applied to a particular $\\UTxOState$ in environment $\\UTxOEnv$:\n\nThe transition contains the following predicates:\n\n\\begin{itemize}\n \\item\n The transaction is live (the current slot is less than its time to live).\n \\item\n The transaction has at least one input.\n The global uniqueness of transaction inputs prevents replay attacks.\n By requiring that all transactions spend at least one input,\n the entire transaction is safe from such attacks.\n A delegation certificate by itself, for example, does not have this property.\n \\item\n The fee paid by the transaction has to be greater than or equal to the minimum fee,\n which is based on the size of the transaction.\n A user or wallet might choose to create a fee larger than necessary\n in exchange for a faster processing time.\n \\item\n Each input spent in the transaction must be in the set of unspent\n outputs.\n \\item\n The \\textit{preservation of value} property must hold.\n In other words, the amount of value produced by the transaction must be the same as\n the amount consumed.\n \\item\n The $\\mathsf{PPUP}$ transition is successful.\n \\item\n The coin value of each new output must be at least as large as the\n minimum value specified by the protocol parameter $\\var{minUTxOValue}$.\n \\item\n The transaction size must be below the allowed maximum.\n Note that there is an implicit max transaction size given by the max block size,\n and that if we wished to allow a transaction to be as large as will fit in a block, this\n check would not be needed.\n Being able to limit the size below that of the block, however, gives us some\n control over how transactions will be packed into the blocks.\n\\end{itemize}\nIf all the predicates are satisfied, the state is updated as follows:\n\n\\begin{itemize}\n \\item Update the UTxO:\n \\begin{itemize}\n \\item Remove from the UTxO all the $(\\var{txin}, \\var{txout})$ pairs\n associated with the $\\var{txins}$'s in the $\\var{inputs}$ list of\n the transaction body $\\var{txb}$.\n \\item Add all the $\\var{outputs}$ of $\\var{tx}$ to the\n UTxO, associated with the $\\fun{txid}$ of the transaction body $\\var{txb}$\n \\end{itemize}\n \\item Add all new deposits to the deposit pot and subtract all deposit refunds.\n \\item Add the transaction fee to the fee pot.\n \\item Update the current update proposals.\n\\end{itemize}\n\nThe accounting for the reward withdrawals is not done in this transition system.\nThe rewards are tracked with the delegation state and will\nbe removed in the final delegation transition, see ~\\ref{eq:delegs-base}.\n\nNote here that output entries for both the deposit refunds and the rewards\nwithdrawals must be included in the body of the transaction\ncarrying the deregistration certificates (requesting these refunds) and the\nreward requests. It is the job\nof the wallet to calculate the value of these refunds and withdrawals and\ngenerate the correct outputs to include in the outputs list of $\\var{tx}$ such\nthat applying this transaction results in a\nvalid ledger update adding correct amounts of coin to the right addresses.\n\nThe approach of including refunds and rewards directly in the $outputs$ gives\ngreat flexibility to the management of the coin value obtained from these\naccounts, i.e.~it can be directed to any address. However, it means there is no\ndirect link between the $wdrls$ requests (similarly for the key deregistration\ncertificate addresses and refund amounts) and the $outputs$. We verify that\nthe included outputs are correct and authorized through the preservation of value condition\nand witnessing the transaction. The combination of the\npreservation of value and witnessing, described in Section~\\ref{sec:witnesses-shelley},\nassures that the ledger state is updated correctly.\n\nThe main difference, however, in how rewards and refunds work is that refunds\ncome from a $\\var{deposits}$ pool, which is a single coin value indicating\nthe total decayed amount of all the deposits ever made, while rewards come from individual\naccounts where a reward is accumulated to a specific address.\n\n\\begin{figure}[htb]\n \\begin{equation}\\label{eq:utxo-inductive-shelley}\n \\inference[UTxO-inductive]\n { \\var{txb}\\leteq\\txbody{tx}\n & \\txttl txb \\geq \\var{slot}\n \\\\ \\txins{txb} \\neq \\emptyset\n & \\minfee{pp}{tx} \\leq \\txfee{txb}\n & \\txins{txb} \\subseteq \\dom \\var{utxo}\n \\\\\n \\consumed{pp}{utxo}~{txb} = \\produced{pp}{poolParams}~{txb}\n \\\\\n ~\n \\\\\n {\n \\begin{array}{r}\n \\var{slot} \\\\\n \\var{pp} \\\\\n \\var{genDelegs} \\\\\n \\end{array}\n }\n \\vdash \\var{pup} \\trans{\\hyperref[fig:rules:pp-update]{ppup}}{\\fun{txup}~\\var{tx}} \\var{pup'}\n \\\\\n ~\n \\\\\n \\forall (\\wcard\\mapsto (\\wcard,~c)) \\in \\txouts{txb}, c \\geq (\\fun{minUTxOValue}~\\var{pp})\n \\\\\n \\forall (\\wcard\\mapsto (a,~\\wcard)) \\in \\txouts{txb}, a \\in \\AddrBS \\to \\fun{bootstrapAttrsSize}~a \\leq 64\n \\\\\n \\forall (\\wcard\\mapsto (a,~\\wcard)) \\in \\txouts{txb}, \\fun{netId}~a =\\NetworkId\n \\\\\n \\forall (a\\mapsto\\wcard) \\in \\txwdrls{txb}, \\fun{netId}~a =\\NetworkId\n \\\\\n \\fun{txsize}~{tx}\\leq\\fun{maxTxSize}~\\var{pp}\n \\\\\n ~\n \\\\\n \\var{refunded} \\leteq \\keyRefunds{pp}{txb}\n \\\\\n \\var{depositChange} \\leteq\n \\totalDeposits{pp}{poolParams}{(\\txcerts{txb})} - \\var{refunded}\n }\n {\n \\begin{array}{r}\n \\var{slot}\\\\\n \\var{pp}\\\\\n \\var{poolParams}\\\\\n \\var{genDelegs}\\\\\n \\end{array}\n \\vdash\n \\left(\n \\begin{array}{r}\n \\var{utxo} \\\\\n \\var{deposits} \\\\\n \\var{fees} \\\\\n \\var{pup}\\\\\n \\end{array}\n \\right)\n \\trans{utxo}{tx}\n \\left(\n \\begin{array}{r}\n \\varUpdate{(\\txins{txb} \\subtractdom \\var{utxo}) \\cup \\outs{txb}} \\\\\n \\varUpdate{\\var{deposits} + \\var{depositChange}} \\\\\n \\varUpdate{\\var{fees} + \\txfee{txb}} \\\\\n \\varUpdate{pup'}\\\\\n \\end{array}\n \\right)\n }\n \\end{equation}\n \\caption{UTxO inference rules}\n \\label{fig:rules:utxo-shelley}\n\\end{figure}\n\nThe UTXO rule has ten predicate failures:\n\\begin{itemize}\n\\item In the case of any input not being valid, there is a \\emph{BadInput}\n failure.\n\\item In the case of the current slot being greater than the time-to-live of the\n current transaction, there is an \\emph{Expired} failure.\n\\item In the case that the transaction is too large,\n there is a \\emph{MaxTxSize} failure.\n\\item In the case of an empty input set, there is a \\emph{InputSetEmpty} failure,\n in order to prevent replay attacks.\n\\item If the fees are smaller than the minimal transaction fees, there is a\n \\emph{FeeTooSmall} failure.\n\\item If the transaction does not correctly conserve the balance, there is a\n \\emph{ValueNotConserved} failure.\n\\item If the transaction creates any outputs with the wrong network ID,\n there is a \\emph{WrongNetwork} failure.\n\\item If the transaction contains any withdrawals with the wrong network ID,\n there is a \\emph{WrongNetworkWithdrawal} failure.\n\\item If the transaction creates an output below the allowed minimum value,\n there is a \\emph{OutputTooSmall} failure.\n\\item If the transaction creates any boostrap outputs whose attributes have\n size bigger than 64, there is a \\emph{OutputBootAddrAttrsTooBig} failure.\n\\end{itemize}\n\n\\clearpage\n\n\\subsection{Deposits and Refunds}\n\\label{sec:deps-refunds}\n\nDeposits are described in appendix B.2 of the delegation design document\n\\cite{delegation_design}. These deposit functions were used above in the UTxO\ntransition,~\\ref{sec:utxo-trans}. Deposits are used for stake credential\nregistration and pool registration certificates, which will be explained in\nSection~\\ref{sec:delegation-shelley}. In particular, the function\n$\\cwitness{}$, which gets the certificate witness from a certificate, will be\ndefined later. Figure~\\ref{fig:functions:deposits-refunds} defines the deposit\nand refund functions.\n\\begin{itemize}\n \\item The function $\\fun{totalDeposits}$ returns the total deposits that have to be\n made by a transaction. This calculation uses two protocol parameters, namely\n the key deposit value and the pool deposit value.\n Note that those certificates which are\n updates of stake pool parameters of already registered pool keys should not\n (and are, in fact, not allowed to) make a deposit.\n \\item The function $\\fun{keyRefunds}$, calculates the total amount of returned\n deposits from stake key deregistration certificates.\n\n Note that $\\fun{keyRefunds}$ uses the \\textit{current} protocol parameters.\n This means that any deposits made prior to a change in the deposit values\n will be refunded with the current value, not the one originally paid.\n\n The protocol parameters are not\n expected to change often and using the current ones for the calculation\n is a deliberate simplification choice, which does not introduce any inconsistencies\n into the system rules or properties. In particular, the general accounting\n property is not violated.\n\\end{itemize}\n\n\\begin{figure}[htb]\n \\begin{align*}\n & \\fun{totalDeposits} \\in \\PParams \\to (\\KeyHash_{pool}\\mapsto\\PoolParam) \\\\\n & ~~~~\\to \\seqof{\\DCert} \\to \\Coin\n & \\text{total deposits for transaction} \\\\\n & \\totalDeposits{pp}{poolParams}{certs} = \\\\\n & ~~~ (\\fun{keyDeposit}~pp)\\cdot|\\var{certs}\\cap\\DCertRegKey| \\\\\n & ~~~~~ + (\\fun{poolDeposit}~pp)\\cdot|\\var{newPools}| \\\\\n & ~~~\\where \\\\\n & ~~~~~~~ \\var{newPools} = \\{\\var{certs}\\cap\\DCertRegPool ~\\mid~ \\cwitness{c}\\notin \\var{poolParams}\\}\n \\nextdef\n & \\fun{keyRefunds} \\in \\PParams \\to \\TxBody \\to \\Coin\n & \\text{key refunds for a transaction} \\\\\n & \\keyRefunds{pp}{tx} = (\\fun{keyDeposit}~\\var{pp})\\cdot|\\txcerts{tx} \\cap \\DCertDeRegKey|\\\\\n \\end{align*}\n \\caption{Functions used in Deposits - Refunds}\n \\label{fig:functions:deposits-refunds}\n \\end{figure}\n\n\\clearpage\n\n\\subsection{Witnesses}\n\\label{sec:witnesses-shelley}\n\nThe purpose of witnessing is make sure that the intended action is authorized by\nthe holder of the signing key, providing replay protection as a consequence.\nReplay prevention is an inherent property of UTxO type accounting\nsince transaction IDs are unique and we require all transaction to\nconsume at least one input.\n\nA transaction is witnessed by a signature and a verification key corresponding\nto this signature. The witnesses, together with the transaction body, form a\nfull transaction. Every witness in a transaction signs the transaction body.\nMoreover, the witnesses are represented as finite maps from verification keys to\nsignatures, so that any key that is required to sign a transaction only provides\na single witness. This means that, for example, a transaction which includes a\ndelegation certificate and a reward withdrawal corresponding to the same stake\ncredential still only includes one signature.\n\nFigure~\\ref{fig:functions-witnesses} defines the function which\ngathers all the (hashes of) verification keys needed to witness a given transaction.\nThis consists of:\n\\begin{itemize}\n \\item payment keys for outputs being spent\n \\item stake credentials for reward withdrawals\n \\item stake credentials for delegation certificates (except \\DCertMir{} and \\DCertRegKey{})\n \\item delegates of the genesis keys for any protocol parameter updates\n \\item stake credentials for the pool owners in a pool registration certificate\n\\end{itemize}\n\n\\begin{figure}[htb]\n \\begin{align*}\n & \\fun{propWits} \\in \\Update \\to \\GenesisDelegation \\to \\powerset{\\KeyHash}\n & \\text{hashkeys for proposals} \\\\\n & \\fun{propWits}~(\\var{pup},~\\wcard)~\\var{genDelegs} = \\\\\n & ~~\\left\\{\n \\var{kh}\n \\mid\n \\var{gkh}\\mapsto(\\var{kh},~\\wcard)\\in\n \\left(\\dom{\\var{pup}}\\restrictdom\\var{genDelegs}\\right)\n \\right\\}\n \\end{align*}\n\n \\begin{align*}\n & \\hspace{-0.8cm}\\fun{certWitsNeeded} \\Tx \\to \\powerset{\\Credential}\n & \\text{certificates with witnesses} \\\\\n & \\hspace{-0.8cm}\\fun{certWitsNeeded}~\\var{tx} = \\\\\n & \\bigcup\\{\\cwitness{c} \\mid c \\in \\txcerts{tx} \\setminus (\\DCertRegKey\\cup\\DCertMir)\\}\n \\end{align*}\n\n \\begin{align*}\n & \\hspace{-0.8cm}\\fun{witsVKeyNeeded} \\in \\UTxO \\to \\Tx \\to (\\KeyHashGen\\mapsto\\VKey) \\to\n \\powerset{\\KeyHash}\n & \\text{required key hashes} \\\\\n & \\hspace{-0.8cm}\\fun{witsVKeyNeeded}~\\var{utxo}~\\var{tx}~\\var{genDelegs} = \\\\\n & ~~\\{ \\fun{paymentHK}~a \\mid i \\mapsto (a, \\wcard) \\in \\var{utxo},~i\\in\\fun{txinsVKey}~{tx} \\} \\\\\n \\cup & ~~\n \\{\\fun{stakeCred_r}~a\\mid a\\mapsto \\wcard \\in \\AddrRWDVKey\n \\restrictdom \\txwdrls{tx}\\}\\\\\n \\cup & ~~(\\AddrVKey \\cap \\fun{certWitsNeeded}~{tx}) \\\\\n \\cup & ~~\\fun{propWits}~(\\fun{txup}~\\var{tx})~\\var{genDelegs} \\\\\n \\cup & ~~\\bigcup_{\\substack{c \\in \\txcerts{tx} \\\\ ~c \\in\\DCertRegPool}} \\fun{poolOwners}~{c}\n \\end{align*}\n \\begin{align*}\n & \\hspace{-1cm}\\fun{scriptsNeeded} \\in \\UTxO \\to \\Tx \\to\n \\powerset{\\HashScr}\n & \\text{required script hashes} \\\\\n & \\hspace{-1cm}\\fun{scriptsNeeded}~\\var{utxo}~\\var{tx} = \\\\\n & ~~\\{ \\fun{validatorHash}~a \\mid i \\mapsto (a, \\wcard) \\in \\var{utxo},\\\\\n & ~~~~~i\\in\\fun{txinsScript}~{(\\fun{txins~\\var{tx}})}~{utxo}\\} \\\\\n \\cup & ~~\\{ \\fun{stakeCred_{r}}~\\var{a} \\mid a \\in \\dom (\\AddrRWDScr\n \\restrictdom \\fun{txwdrls}~\\var{tx}) \\} \\\\\n \\cup & ~~(\\AddrScr \\cap \\fun{certWitsNeeded}~{tx})\n \\end{align*}\n \\caption{Functions used in witness rule}\n \\label{fig:functions-witnesses}\n\\end{figure}\n\nThe UTxOW transition system adds witnessing to the previous UTxO transition system.\nFigure~\\ref{fig:ts-types:utxow-shelley} defines the type for this transition.\n\n\\begin{figure}\n \\emph{UTxO with witness transitions}\n \\begin{equation*}\n \\var{\\_} \\vdash\n \\var{\\_} \\trans{utxow}{\\_} \\var{\\_}\n \\subseteq \\powerset (\\UTxOEnv \\times \\UTxOState \\times \\Tx \\times \\UTxOState)\n \\end{equation*}\n \\caption{UTxO with witness transition-system types}\n \\label{fig:ts-types:utxow-shelley}\n\\end{figure}\n\nFigure~\\ref{fig:rules:utxow-shelley} defines UTxOW transition.\nIt has six predicates:\n\\begin{itemize}\n \\item Every signature in the transaction is a valid signature of the transaction body.\n \\item The set of (hashes of) verification keys given by the transaction is a subset of\n the set of needed (hashes of) verification keys.\n \\item Every multisignature script is valid.\n \\item The set of scripts given by the transaction is equal to the set of required scripts.\n \\item Any instantaneous reward certificates have quorum agreement from the genesis nodes delegates.\n \\item Either the transaction metadata hash and the transaction metadata are both absent,\n or the hash present in the body is actually equal to the hash of the metadata.\n\\end{itemize}\nIf the predicates are satisfied, the state is transitioned by the UTxO transition rule.\n\n\\begin{figure}\n \\begin{equation}\n \\label{eq:utxo-witness-inductive-shelley}\n \\inference[UTxO-wit]\n {\n (utxo, \\wcard, \\wcard, \\wcard) \\leteq \\var{utxoSt} \\\\\n \\var{witsKeyHashes} \\leteq \\{\\fun{hashKey}~\\var{vk} \\vert \\var{vk} \\in\n \\dom (\\txwitsVKey{tx}) \\}\\\\~\\\\\n \\forall \\var{hs} \\mapsto \\var{validator} \\in \\fun{txwitsScript}~{tx},\\\\\n \\fun{hashScript}~\\var{validator} = \\var{hs} \\wedge\n \\fun{validateScript}~\\var{validator}~\\var{tx}\\\\~\\\\\n \\fun{scriptsNeeded}~\\var{utxo}~\\var{tx} = \\dom (\\fun{txwitsScript}~{tx})\n \\\\~\\\\\n \\var{txbodyHash}\\leteq\\fun{hash}~(\\txbody{tx}) \\\\\n \\forall \\var{vk} \\mapsto \\sigma \\in \\txwitsVKey{tx},\n \\mathcal{V}_{\\var{vk}}{\\serialised{txbodyHash}}_{\\sigma} \\\\\n \\fun{witsVKeyNeeded}~{utxo}~{tx}~{genDelegs} \\subseteq witsKeyHashes\n \\\\~\\\\\n genSig \\leteq\n \\left\\{\n \\var{genDelegate}~\\vert~(\\var{genDelegate},~\\wcard) \\in\\range{genDelegs}\n \\right\\}\n \\cap\n \\var{witsKeyHashes}\n \\\\\n \\left\\{\n c\\in\\txcerts{tx}~\\cap\\DCertMir\n \\right\\} \\neq\\emptyset \\implies \\vert genSig\\vert \\geq \\Quorum\n \\\\~\\\\\n \\var{mdh}\\leteq\\fun{txMDhash}~\\var{tx}\n &\n \\var{md}\\leteq\\fun{txMD}~\\var{tx}\n \\\\\n (\\var{mdh}=\\Nothing \\land \\var{md}=\\Nothing)\n \\lor\n (\\var{mdh}=\\fun{hashMD}~\\var{md})\n \\\\~\\\\\n {\n \\begin{array}{r}\n \\var{slot}\\\\\n \\var{pp}\\\\\n \\var{poolParams}\\\\\n \\var{genDelegs}\\\\\n \\end{array}\n }\n \\vdash \\var{utxoSt} \\trans{\\hyperref[fig:rules:utxo-shelley]{utxo}}{tx}\n \\var{utxoSt'}\\\\\n }\n {\n \\begin{array}{r}\n \\var{slot}\\\\\n \\var{pp}\\\\\n \\var{poolParams}\\\\\n \\var{genDelegs}\\\\\n \\end{array}\n \\vdash \\var{utxoSt} \\trans{utxow}{tx} \\varUpdate{\\var{utxoSt'}}\n }\n \\end{equation}\n \\caption{UTxO with witnesses inference rules}\n \\label{fig:rules:utxow-shelley}\n\\end{figure}\n\nThe UTXOW rule has eight predicate failures:\n\\begin{itemize}\n\\item In the case of an incorrect witness,\n there is a \\emph{InvalidWitnesses} failure.\n\\item In the case of a missing witness,\n there is a \\emph{MissingVKeyWitnesses} failure.\n\\item In the case of missing scripts,\n there is a \\emph{MissingScriptWitnesses} failure.\n\\item In the case of an invalid script,\n there is a \\emph{ScriptWitnessNotValidating} failure.\n\\item In the case of a lack of quorum on an instantaneous reward certificate,\n there is a \\emph{MIRInsufficientGenesisSigs} failure.\n\\item In the case the transaction contains metadata,\n but the transaction body does not contain a metadata hash,\n there is a \\emph{MissingTxBodyMetaDataHash} failure.\n\\item In the case that the transaction body contains a metadata hash,\n but there is no metadata outside the body,\n there is a \\emph{MissingTxMetaData} failure.\n\\item In the case that the metadata hash in the transaction body\n is not equal to the hash of the metadata outside the body,\n there is a \\emph{ConflictingMetaDataHash} failure.\n\\end{itemize}\n\n\\clearpage\n", "meta": {"hexsha": "6718a79a4207891b7848f0c9146e01764981465c", "size": 25743, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "shelley/chain-and-ledger/formal-spec/utxo.tex", "max_stars_repo_name": "fsancheziohk/cardano-ledger-specs", "max_stars_repo_head_hexsha": "8d836e61bb88bda4a6a5c00694735928390067a1", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "shelley/chain-and-ledger/formal-spec/utxo.tex", "max_issues_repo_name": "fsancheziohk/cardano-ledger-specs", "max_issues_repo_head_hexsha": "8d836e61bb88bda4a6a5c00694735928390067a1", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "shelley/chain-and-ledger/formal-spec/utxo.tex", "max_forks_repo_name": "fsancheziohk/cardano-ledger-specs", "max_forks_repo_head_hexsha": "8d836e61bb88bda4a6a5c00694735928390067a1", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.1325695581, "max_line_length": 112, "alphanum_fraction": 0.695179272, "num_tokens": 7581, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.3106943895971202, "lm_q1q2_score": 0.16745906275464995}} {"text": "\\documentclass[nofootinbib,amssymb,amsmath]{revtex4}\n\\usepackage{mathtools}\n\\usepackage{amsthm}\n\\usepackage{algorithm}\n\\usepackage{algpseudocode}\n\\usepackage{lmodern}\n\\usepackage{graphicx}\n\\usepackage{color}\n\n%Put an averaged random variable between brackets\n\\newcommand{\\ave}[1]{\\left\\langle #1 \\right\\rangle}\n\\newcommand{\\HC}{\\texttt{HaplotypeCaller}}\n\\newcommand{\\Mutect}{\\texttt{Mutect}}\n\\newcommand{\\code}[1]{\\texttt{#1}}\n\\newcommand{\\mc}[1]{\\mathcal{#1}}\n\n\n\\newtheorem{lemma}{Lemma}\n\\newtheorem{corollary}{Corollary}\n\n\\def\\SL#1{{\\color [rgb]{0,0,0.8} [SL: #1]}}\n\\def\\DB#1{{\\color [rgb]{0,0.8,0} [DB: #1]}}\n\n\\begin{document}\n\n\\title{Inferring variants from assembled haplotypes in HaplotypeCaller and Mutect}\n\\author{David Benjamin\\footnote{The author took no part in development of the methods described below -- credit belongs to several others on the GATK team. }}\n\\email{davidben@broadinstitute.org}\n\\affiliation{Broad Institute, 75 Ames Street, Cambridge, MA 02142}\n\n\\date{\\today}\n\n\\begin{abstract}\nDespite its name, \\HC does not actually call haplotypes. Rather, it generates haplotypes as an intermediate step to discover variants at individual loci. Here we describe how the GATK engine determines which alt alleles exist in locally assembled haplotypes.\n\\end{abstract}\n\n\\maketitle\n\n\\section{Forward pass}\nThe first step is to align each assembled haplotype to the reference haplotype using the Smith-Waterman algorithm. Although the GATK's implementation is not complicated, it is also not a completely direct translation of the method into code. As it incurs a non-trivial computational cost, we describe it in detail here.\n\nOur implementation has four score parameters, $w_{\\rm match}$ and $w_{\\rm mismatch}$ for equal and unequal reference and alternate bases, $w_{\\rm open}$ for opening a gap (that is, starting an indel), and $w_{\\rm extend}$ for extending a gap. Note the absence of a scoring matrix treating each possible type of match and mismatch differently. Although the idea of a score seems like a heuristic, the algorithm is equivalent to finding the maximum likelihood path in a hidden Markov model in which the scores are log transition and emission probabilities. \n\nAs in our pair-HMM probabilistic alignment, we fill a matrix $M$, the rows and columns of which correspond to bases of the reference and alternate haplotypes, from top to bottom and left to right. $M_{ij}$ is the best score of alignments ending at the $i$th reference base and $j$th alternate base that do not end in a gap\\footnote{That is, it includes alignments that have gaps somewhere earlier, just not at this position.}. We also keep track of two arrays pertaining to the last row of our traversal. $D_j$ is the best score of alignments ending at the previous reference base (ie the $(i-1)$th base when we are at the $i$th base in traversal) and the $j$th alternate base that end in a ``downward'' gap, i.e. a deletion with respect to the reference. $S^d_j$ is the size of the gap in this best-scoring alignment. We also fill a backtrack matrix $B$, where $B_{ij}$ is an instruction (see below) for reconstructing the best path after we fill $M$.\n\nFirst we initialize the zeroth row and column as $M_{0,0}$ = 0, $M_{0,1} = M_{1,0} = w_{\\rm open}$, $M_{0,2} = M_{2,0} = w_{\\rm open} + w_{\\rm extend}$ etc. The zeroth row and column correspond to one base before the reference and alternate starts and this initialization penalizes leading indels. That is, this is a global alignment\\footnote{The GATK assembly graph merges all alternate paths into the reference, hence alternate haplotypes start and end coincident with the reference and global alignment is appropriate.}.\n\nThen, for each row $1 \\le i \\le {\\rm length(reference)}$ we loop over all columns $1 \\le j \\le {\\rm length(alternate)}$ and do the following:\n\n\\begin{itemize}\n\\item Update deletion scores: The score for opening a downward gap is $M_{i-1,j} + w_{\\rm open}$. The score for extending an existing deletion is $D_j + w_{\\rm extend}$, where $D_j$ at this point still pertains to the $previous$ row $i - 1$. We set $D_j$ (modifying it in-place) to the greater of these values. If the gap-opening score is greater than the gap-extending score, we set $S^d_j = 1$, otherwise we increment $S^d_j$ by 1.\n\\item Update insertion scores: When we begin traversing row $i$ we initialize the current best score for alignments ending in a ``rightward'' gap (i.e. an insertion) as $R = -\\infty$ and we initialize the length of the terminal gap in this best-scoring alignment as $S^r = 0$. Note that these values are local to the inner loop over $j$ and thus do not need to be arrays\\footnote{In the code, they \\textit{are} arrays, but in the $i$th iteration of the loop over rows, only their $i$th elements are used. Thus the elements are effectively scalars whose scope is the loop over $j$.}. At each stage in the loop over $j$ the score for opening a rightward gap is $M_{i,j - 1} + w_{\\rm open}$ and score for extending one is $R + w_{\\rm extend}$, where $R$ still pertains to the previous column $j - 1$. We set $R$ (modifying it in-place) to the greater of these values. If the gap-opening score is greater than the gap-extending score, we set $S^r_j = 1$, otherwise we increment $S^r_j$ by 1.\n\\item Record backtrack: The score for no gap, i.e. a match \\textit{alignment} (as opposed to matching bases), is $M_{i-1,j-1}$ plus $w_{\\rm match}$ if the $i$th reference base and $j$th alternate base agree or $w_{\\rm mismatch}$ if they do not. We now compare this score to the indel scores $D_j$ and $R$. We set $B_{ij}$ to 0 if the match score is greatest, $S^d_j$ if the downward gap score is greatest, and $-S^r$ if the rightward gap score is greatest. This convention essentially uses the sign as an enum in order to encode whether the optimal path has an insertion, deletion or match.\n\\end{itemize}\n\n\\section{Backward pass}\nAfter the forward pass the backtrack matrix $B$ is full. We begin backtracking from the $(i,j)$ that is the maximum among the bottom row and rightmost column of $M$. If this maximum is in the rightmost column that means all alternate haplotype bases are used and nothing special must be done. If, however the maximum is on the bottom row it means that the more alternate bases remain. In this case, we record a soft clip (S) CIGAR element with length equal to the number of remaining bases at the end of the alignment\\footnote{The code behaves differently for different values of the \\code{OverhangStrategy} enum, but this strategy is hard-coded to \\code{SOFTCLIP}, which results in the behavior we describe here.}. Then, from this $(i,j)$ we iterate the following procedure until reaching $i = 0$ or $j = 0$ (recall that these correspond to immediately \\textit{before} the start of the corresponding haplotypes): If $B_{ij} = 0$ add a match (M) CIGAR element to the left end of the alignment and move to $i,j \\rightarrow i - 1, j - 1$. If $B_{ij} = k > 0$ add a length-$k$ deletion (D) CIGAR element to the left of the alignment and move to $i,j \\rightarrow i - k, j$. If $B_{ij} = -k < 0$ add a length-$k$ insertion (I) CIGAR element to the left of the alignment and move to $i,j \\rightarrow i, j - k$. \n\nSimilar to the initial step, if we end at $j = 0$ nothing more needs to be done because all alternate bases are accounted for. Otherwise, add a length-$j$ leading soft clip.\n\n\\section{Making variants}\nFor each haplotype from assembly it is easy to create variant alleles from the alignments found above. Starting from the beginning of the haplotype and its starting reference position, traverse every element in the CIGAR string, advance $k$ bases in the reference for every length-$k$ element. When we encounter a deletion element or insertion element we record a corresponding allele from the reference and alternate bases. When we encounter a match element we compare the matched reference and alternate sub-haplotypes base-by-base and record a SNV allele whenever they disagree.\n\nTaking all the unique start positions and variant alleles from all haplotypes give an initial set of variants to genotype but we are not quite done. If multiple haplotypes have different variant alleles at the same position we may need to reconcile the representations. For example, we may have a single deletion $AA \\rightarrow A$ and a double deletion $AAA \\rightarrow A$, which need to be merged as $AAA \\rightarrow A, AA$. Fortunately, this is essentially the canonical example and there are no edge cases to deal with. That is, all we need to do is find the allele with the longest reference, and pad the other alleles with whatever of these extra reference bases they were missing.\n\n\\end{document}", "meta": {"hexsha": "d90742dc4e72b1e43b4521f70b8858d8a617f9f3", "size": 8724, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "docs/variants_from_haplotypes.tex", "max_stars_repo_name": "sunboy0523/gatk", "max_stars_repo_head_hexsha": "f06971ac0824ad7da38b878334df377c30457a23", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1273, "max_stars_repo_stars_event_min_datetime": "2015-10-13T18:11:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T09:25:13.000Z", "max_issues_repo_path": "docs/variants_from_haplotypes.tex", "max_issues_repo_name": "sunboy0523/gatk", "max_issues_repo_head_hexsha": "f06971ac0824ad7da38b878334df377c30457a23", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 6471, "max_issues_repo_issues_event_min_datetime": "2015-10-08T02:31:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T17:55:25.000Z", "max_forks_repo_path": "docs/variants_from_haplotypes.tex", "max_forks_repo_name": "sunboy0523/gatk", "max_forks_repo_head_hexsha": "f06971ac0824ad7da38b878334df377c30457a23", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 598, "max_forks_repo_forks_event_min_datetime": "2015-10-14T19:16:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T10:03:03.000Z", "avg_line_length": 132.1818181818, "max_line_length": 1313, "alphanum_fraction": 0.757221458, "num_tokens": 2309, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.310694383214554, "lm_q1q2_score": 0.16745905931455385}} {"text": "\\SecDef{intro}{Introduction}\n\nWith the advent of the Internet of Things (IoT), a myriad of devices are being connected one to another in order to exchange information. This information has to be secured. Symmetric cryptography can ensure that the data those devices share remains confidential, that it is properly authenticated and that it has not been tampered with.\n\nAs such objects have little computing power---and even less so that is dedicated to information security---the cost of the algorithms ensuring these properties has to be as low as possible. To answer this need, the NIST has called for the design of authenticated ciphers and hash functions providing a sufficient security level at as small an implementation cost as possible.\n\nWe present a suite of algorithms that answer this call. All our algorithms are built using the same core, namely the \\aCipher{} family of permutations. The authenticated ciphers, \\aead{}, provide confidentiality of the plaintext as well as both integrity and authentication for the plaintext and for additional public associated data. The hash functions, \\hash{}, are (second) preimage and collision resistant. Our aim for our algorithms is to use as little CPU cycles as possible to perform their task while retaining strong security guarantees and a small implementation size. This speed will allow devices to use much fewer CPU cycles than what is currently needed to ensure the protection of their data. To give one of many very concrete applications of this gain, the energy demanded by cryptography for a battery-powered micro-controller will be decreased.\n\nThe parameters of instances of \\hash{} and \\aead{} are summarized in \\TabRef{instances}.\n\n\\begin{table}\n \\resizebox{\\linewidth}{!}{\n \\begin{tabular}{cccccc}\n \\toprule\n \\multirow{2}{*}{Type} & \\multirow{2}{*}{Name} & Internal state size & Data block size & Security level \\\\\n & & (bytes) & (bytes) & (bits) \\\\\n \\midrule\n \\multirow{2}{*}{Hash function}\n & \\hash{256} & 48 & 16 & 128 \\\\\n & \\hash{384} & 64 & 16 & 192 \\\\\n \\midrule\n % \\multirow{4}{*}{AEAD} \n & \\aeadversion{128}{128} & 32 & 16 & 120 \\\\\n Authenticated & \\aeadversion{256}{128} & 48 & 32 & 120 \\\\\n encryption & \\aeadversion{192}{192} & 48 & 24 & 184 \\\\\n & \\aeadversion{256}{256} & 64 & 32 & 248 \\\\\n \\bottomrule\n \\end{tabular}\n \\TabDef{instances}{Algorithms in the lightweight cryptographic suite.}\n }\n\\end{table}\n\n\\subsection*{Permutation \\aCipher{}}\n\n\\aCipher{} is a family of cryptographic permutations built on the ARX paradigm. Its name comes from the block cipher \\sparx{}~\\cite{OurSPARX}, which \\aCipher{} is closely related to, hence its name:\n\\begin{center}\n \\textbf{SPAR}x, but \\textbf{K}ey \\textbf{LE}ss.\n\\end{center}\n\nWe provide three versions corresponding to three block sizes, namely \\aCipher{256}, \\aCipher{384}, and \\aCipher{512}. The number of steps used varies with the use case.\n\n\n\\subsection*{Hash Function \\hash{}}\n\nA \\emph{hash function} takes a message of arbitrary length and outputs a digest with a fixed length. It should provide the cryptographic security notions of \\emph{preimage resistance}, \\emph{second preimage resistance} and \\emph{collision resistance}. \nThe main instance of \\hash{} is \\hash{256} which produces a 256-bit digest, offering a security level of 128 bits with regard to the above mentioned security goals. It is based on the permutation family \\aCipher{384}. We also provide the member \\hash{384} based on the permutation family \\aCipher{512}, which produces a 384-bit digest and offers a security level of 192 bits.\n\nThe name \\hash{} stands for\n\\begin{center}\n \\textbf{E}fficient, \\textbf{S}ponge-based, and \\textbf{C}heap \\textbf{H}ashing.\n\\end{center}\n\n\n\\subsection*{Authenticated Cipher \\aead{}}\n\nA scheme for \\emph{authenticated encryption with associated data (AEAD)} takes a key and a nonce of fixed length, as well as a message and associated data of arbitrary size. The encryption procedure outputs a ciphertext of the message as well as a fixed-size authentication tag. The decryption procedure takes the key, nonce, associated data and the ciphertext and tag as input and outputs the decrypted message if the tag is valid, otherwise a symbolic error $\\bot$.\nAn AEAD scheme should fulfill the security notions of \\emph{confidentiality} and \\emph{integrity}. Users are expected to \\emph{not} reuse nonces for processing messages in a fixed-key instance.\n\nThe main instance of \\aead{} is \\aeadversion{256}{128} which takes a 256-bit nonce, a 128-bit key and outputs a 128-bit authentication tag. It achieves a security level of 120 bits with regard to confidentiality and integrity.\nWe further provide three other instances, i.e., \\aeadversion{128}{128}, \\aeadversion{192}{192}, and \\aeadversion{256}{256} which differ in the length of key, nonce and tag and in the achieved security level.\n\nThe name \\aead{} stands for\n\\begin{center}\n \\textbf{S}ponge-based \\textbf{C}ipher for\n \\\\\n \\textbf{H}ardened but \\textbf{W}eightless \\textbf{A}uthenticated \\textbf{E}ncryption \\\\\n on \\textbf{M}any~\\textbf{M}icrocontrollers\n\\end{center}\n\n\n\\subsection*{Outline}\nThis chapter is structured as follows. First, in \\SecRef{spec}, I briefly describe the specification of \\aCipher{},\\hash{} and \\aead{} families. In the following sections, I describe the security analysis that I performed on this suite.\n\nIn \\SecRef{lineariz}, I describe attempts to linearize the S-boxes used in \\aCipher{}, which we call ARX-boxes, by finding all inputs that inflict no carries during the ARX computations. The problem requires a solution of a system of quadratic equations. I describe a simple heuristics for a guess-and-determine algorithm that allows to solve the problems in a reasonable time. The results suggest that ARX-boxes are resistant against such linearization.\n\nIn \\SecRef{truncated}, I describe a truncated differential analysis of \\aCipher{}. I propose a generic method for truncated trail analysis based on the binary matrix representation of the linear layer. The results show that \\aCipher{} has a strong resistance against structural truncated differential trails.\n\nIn \\SecRef{division}, I use the division property technique to find integral characteristics of \\aCipher{}. First, the best characteristics of maximum dimension are found using MILP-aided bit-based division property. Then, I optimize them and prove by a pen-and-paper argument and the classical division property.\n\nFinally, in \\SecRef{cryptanalysis}, I describe several attacks on reduced-round variants of \\aead{}. They are based on a technique that I call birthday-differential attacks. It is a variant of known-plaintext attack where particular differences can be found from a relatively small pool of data by the birthday paradox.", "meta": {"hexsha": "a2808432afc18cb133901ffa79060f96e7b2d7bc", "size": 6837, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "thesis-source/9deSPARKLE/0intro.tex", "max_stars_repo_name": "hellman/thesis", "max_stars_repo_head_hexsha": "6ba1c2b241e63c07cf76108481c1b67f21a50f12", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 19, "max_stars_repo_stars_event_min_datetime": "2019-05-16T19:55:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-31T15:36:12.000Z", "max_issues_repo_path": "thesis-source/9deSPARKLE/0intro.tex", "max_issues_repo_name": "hellman/thesis", "max_issues_repo_head_hexsha": "6ba1c2b241e63c07cf76108481c1b67f21a50f12", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-08-09T11:26:45.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-09T11:26:45.000Z", "max_forks_repo_path": "thesis-source/9deSPARKLE/0intro.tex", "max_forks_repo_name": "hellman/thesis", "max_forks_repo_head_hexsha": "6ba1c2b241e63c07cf76108481c1b67f21a50f12", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-08-05T19:40:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-05T19:40:16.000Z", "avg_line_length": 85.4625, "max_line_length": 862, "alphanum_fraction": 0.7596899225, "num_tokens": 1639, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.32423541204073586, "lm_q1q2_score": 0.16718223583086145}} {"text": "\\subsection{Forum}\n\\label{sec:forum}\n\\label{sec:hasModerator}\n\nA \\tForum is a meeting point where people post \\tMessages.\nThere exists three categories of \\tForums:\nWall ($\\eForum_\\textsf{w}$),\nAlbum ($\\eForum_\\textsf{a}$),\nand Group ($\\eForum_\\textsf{g}$).\nEach \\tForum has a set of \\tPersons connected via \\tHasMember edges, a set of \\tTags connected via \\tHasTag edges, a single moderator connected by a \\tHasModerator edge and a set of \\tMessages (discussed in Section \\ref{sec:message}).\nFor all \\tForums the outgoing \\tHasTag edges get their creation date and deletion date from $\\varc{\\eForum}$ and $\\vard{\\eForum}$, respectively.\n\n\\subsubsection{Groups}\nGroups are public places for people that share interests, any \\tPerson can create a Group $\\eForum_\\textsf{g}$ during their lifespan. A Group can be deleted anytime after it was created.\n\\begin{itemize}\n \\item $\\varc{\\eForum}_{\\mathsf{g}} \\in \\interval{\\varc{\\ePerson} + \\Delta}{\\min (\\vard{\\ePerson}, \\xSE)}$\n \\item $\\vard{\\eForum}_{\\mathsf{g}} \\in \\interval{\\varc{\\eForum}_{\\mathsf{g}} + \\Delta}{\\xNC}$\n\\end{itemize}\n\n\\paragraph{Group Moderator}\nThe initial \\tHasModerator $\\eHasModerator_{\\mathsf{g}}$ is the Group creator. If the moderator leaves the Group, the Group will have no moderator (this is allowed in the schema of version 0.4.0+, see \\autoref{fig:schema}).\n\\begin{itemize}\n\\item $\\varc{\\eHasModerator}_{\\mathsf{g}} \\in \\interval{\\varc{\\eForum}_{\\mathsf{g}} + \\Delta}{\\min (\\vard{\\eForum}_{\\mathsf{g}}, \\vard{\\ePerson}, \\xSE)}$\n\\item $\\vard{\\eHasModerator}_{\\mathsf{g}} \\in \\interval{ \\varc{\\eHasModerator}_{\\mathsf{g}} + \\Delta}{\\min (\\vard{\\eForum}_{\\mathsf{g}}, \\vard{\\ePerson})}$\n\\end{itemize}\n\n\\paragraph{Group Membership}\nAny \\tPerson $\\ePerson$ can become a member of a given group. The \\tHasMember $\\eHasMember_{\\mathsf{g}}$ creation is generated from the interval in which the \\tPerson and \\tForum lifespans overlap. The deletion date is generated from the interval between the membership creation date (incremented by $\\Delta$) and the minimum of the \\tPerson and \\tForum deletion dates.\n\\begin{itemize}\n \\item $\\varc{\\eHasMember}_{\\mathsf{g}} \\in \\interval{\\max ( \\varc{\\eForum}_{\\mathsf{g}}, \\varc{\\ePerson}) + \\Delta}{\\min (\\vard{\\eForum}, \\vard{\\ePerson}, \\xSE)} $\n \\item $\\vard{\\eHasMember}_{\\mathsf{g}} \\in \\interval{\\varc{\\eHasMember}_{\\mathsf{g}} + \\Delta}{\\min (\\vard{\\eForum}_{\\mathsf{g}}, \\vard{\\ePerson})}$\n\\end{itemize}\n\n\\subsubsection{Walls}\nEvery \\tPerson $\\ePerson$, has a Wall $\\eForum_\\textsf{w}$ which is created when the \\tPerson joins the social network. The wall is deleted when the \\tPerson is deleted.\n\\begin{itemize}\n \\item $\\varc{\\eForum}_{\\mathsf{w}} = \\varc{\\ePerson} + \\Delta$\n \\item $\\vard{\\eForum}_{\\mathsf{w}} = \\vard{\\ePerson}$\n\\end{itemize}\n\n\\paragraph{Wall Moderator}\nEach \\tPerson has a \\tHasModerator $\\eHasModerator_{\\mathsf{w}}$ edge to their wall, which gets the creation date (incremented by $\\Delta$) and deletion date from $\\eForum_\\textsf{w}$.\nNote, only the moderator can create \\tPost nodes on the wall and the connecting \\tTag nodes are set based on the interest of the moderator.\n\\begin{itemize}\n \\item $\\varc{\\eHasModerator}_{\\mathsf{w}} = \\varc{\\eForum}_{\\mathsf{w}} + \\Delta$\n \\item $\\vard{\\eHasModerator}_{\\mathsf{w}} = \\vard{\\eForum}_{\\mathsf{w}}$\n\\end{itemize}\n\n\\paragraph{Wall Membership}\nFor a \\tPerson $p_i$, all their friends $p_j$ (\\tPerson nodes connected via a \\tKnows edge) become members of $\\eForum_\\textsf{w}$ at the time the \\tKnows edge is created. Hence, a \\tHasMember $\\eHasMember_{\\mathsf{w}}$ edge gets the creation date of \\tKnows incremented by $\\Delta$. The deletion date is derived from the minimum of the \\tForum deletion date and \\tKnows deletion date.\n\\begin{itemize}\n \\item $\\varc{\\eHasMember}_{\\mathsf{w}} = \\varc{\\eKnows_{i,j}} + \\Delta$\n \\item $\\vard{\\eHasMember}_{\\mathsf{w}} = \\min(\\vard{\\eForum}_{\\mathsf{w}}, \\vard{\\eKnows_{i,j}})$\n\\end{itemize}\n\n\\subsubsection{Albums}\nA \\tPerson can create multiple Albums ($\\eForum_\\textsf{a}$) containing a set of \\tPhotos{}. Albums can be created and then deleted at any point during the lifespan of the \\tPerson.\n\\begin{itemize}\n \\item $\\varc{\\eForum}_\\textsf{a} \\in \\interval{\\varc{\\ePerson} + \\Delta}{\\min (\\vard{\\ePerson}, \\xSE)}$\n \\item $\\vard{\\eForum}_\\textsf{a} \\in \\interval{ \\varc{\\eForum}_\\textsf{a} + \\Delta}{\\vard{\\ePerson}}$\n\\end{itemize}\n\n\\paragraph{Album Moderator}\nThe \\tPerson is the moderator for any Album they create. Album ownership cannot change hence \\tHasModerator $\\eHasModerator_{\\mathsf{a}}$ gets the creation date (incremented by $\\Delta$) and deletion date from $\\varc{\\eForum}_\\textsf{a}$ and $\\vard{\\eForum}_\\textsf{a}$ respectively.\n\\begin{itemize}\n\\item $\\varc{\\eHasModerator}_{\\mathsf{a}} = \\varc{\\eForum}_{\\mathsf{a}} + \\Delta$\n\\item $\\vard{\\eHasModerator}_{\\mathsf{a}} = \\vard{\\eForum}_{\\mathsf{a}}$\n\\end{itemize}\n\n\\paragraph{Album Membership}\nOnly friends $\\ePerson_i$ of a \\tPerson $\\ePerson_j$ can become members of Albums created by $\\ePerson_j$. The \\tHasMember $\\eHasMember_{\\mathsf{a}}$ edge creation date is derived from the Album and $\\type{knows}$ creation dates. The deletion is derived from the $\\type{Forum}$ and $\\type{knows}$ deletion dates.\n\\begin{itemize}\n \\item $\\varc{\\eHasMember}_\\textsf{a} = \\max ( \\varc{\\eForum}_\\textsf{a}, \\varc{\\eKnows}_{i,j} ) + \\Delta $\n \\item $\\vard{\\eHasMember}_{\\mathsf{w}} = \\min ( \\vard{\\eForum}_\\textsf{a}, \\vard{\\eKnows}_{i,j} ) $\n\\end{itemize}\n\n\\subsection{Message}\n\\label{sec:message}\n\nA \\tMessage is an abstract entity that represents a message created by a \\tPerson.\nThere are two \\tMessage subtypes: \\tPost and \\tComment.\nA \\tPost is created in a \\tForum and a \\tComment represents a comment made by a \\tPerson to an existing \\tMessage (either a \\tPost or a \\tComment).\nIn a \\tForum the set of \\tMessage nodes form a \\emph{tree} with a \\tPost node at the root and \\tComment nodes for the rest.\n\n\\subsubsection{Post}\n\nA \\tPost can be created by a \\tPerson in a \\tForum.\nOnly the moderator (\\ie owner) can post on a Wall or in an Album (\\tHasModerator),\nwhereas all members including the moderator (\\tHasMember/\\tHasModerator) can post in a Group.\nThese relationships are captured with the $\\eHasMember$ variable in the formulas.\n\\tPosts are divided in three categories, \\emph{regular posts}, \\emph{photos}, and \\emph{flashmob posts}.\n\n\\paragraph{Regular Posts and Photos}\n\nRegular posts capture the standard daily activity in a Group or on a Wall.\nPhotos are created in Albums. (Interaction with Photos is limited to \\tLikes, see details in \\autoref{sec:likes}). The creation date for these is determined as follows:\n$$\\varc{\\ePost} \\in \\interval{\\varc{\\eHasMember} + \\Delta}{\\min (\\vard{\\eHasMember}, \\xSE) }$$\n\n\\paragraph{Flashmob Posts}\n\nFlashmob posts are generated around events that attract significant interest\n(such as elections) that result in a spike in activity.\nThese events span a $2\\phi$-hour time window centered around a specific event time, flashmob event $\\eFlashmobEvent$, in the middle of the window; there are $\\phi$ hours each side of the specific event time.\n$$\n\\varc{\\ePost} \\in \\interval{\\max(\\varc{\\eHasMember} + \\Delta,\\eFlashmobEvent - \\phi\\textrm{\\,h})}{\\min (\\vard{\\eHasMember},\\eFlashmobEvent + \\phi\\textrm{\\,h},\\xSE)}\n$$\n\nThe deletion dates for all categories of \\tPosts are determined as:\n$$\\vard{\\ePost} \\in \\interval{\\varc{\\ePost} + \\Delta}{\\vard{\\eHasMember}}$$\n\n\\paragraph{containerOf edge}\n\nEach \\tPost node has an incoming $\\type{containerOf}$ edge which gets the same lifespan attributes as the \\tPost.\n\n\\subsubsection{Comment}\n\nA \\tComment $\\eComment$ is created by \\tPerson $\\ePerson$ as a reply to \\tMessage $\\eMessage$. \\tComments are only made in Walls and Groups. \\tComment always occur within $\\gamma$~days of their parent message following a power-law distribution with mean 6.85 hours.\n\n\\begin{itemize}\n \\item $\\varc{\\eComment} \\in \\interval{\\max (\\varc{\\eMessage}, \\varc{\\eHasMember}) + \\Delta}{\\min (\\vard{\\eMessage}, \\vard{\\eHasMember}, \\varc{\\eMessage} + \\gamma\\textrm{\\,d}, \\xSE)}$\n \\item $\\vard{\\eComment} \\in \\interval{\\varc{\\eComment} + \\Delta}{\\min (\\vard{\\eMessage}, \\vard{\\eHasMember})}$\n\\end{itemize}\n\n\\paragraph{replyOf edge}\n\n\\tComments always have an outgoing \\tReplyOf edge with containment semantics, \\ie the target \\tMessage contains the \\tComment. These edges get the same lifespan as their source \\tComment.\n\n\\subsubsection{likes}\n\\label{sec:likes}\n\nA \\tLikes edge $\\eLikes$ can exist between \\tPerson $\\ePerson$ and \\tMessage $\\eMessage$. Messages can only receive likes during a $\\mu$-day window after their creation at which point no more activity is generated.\n\n\\begin{itemize}\n \\item $\\varc{\\eLikes} \\in \\interval{\\max(\\varc{\\ePerson}, \\varc{\\eMessage}) + \\Delta}{\\min (\\vard{\\ePerson}, \\vard{\\eMessage}, \\varc{\\eMessage} + \\mu\\textrm{\\,d}, \\xSE)}$\n \\item $\\vard{\\eLikes} \\in \\interval{\\varc{\\eLikes} + \\Delta}{\\min (\\vard{\\ePerson}, \\vard{\\eMessage})}$\n\\end{itemize}\n", "meta": {"hexsha": "bbb2a84de8911d38a3f2588efa9aa93595e7d948", "size": 8997, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "albums-walls.tex", "max_stars_repo_name": "isabella232/ldbc_snb_docs", "max_stars_repo_head_hexsha": "3519d834f1373e695ed797dce6f3caee82a40d7e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 32, "max_stars_repo_stars_event_min_datetime": "2015-02-16T13:59:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-21T06:15:39.000Z", "max_issues_repo_path": "albums-walls.tex", "max_issues_repo_name": "isabella232/ldbc_snb_docs", "max_issues_repo_head_hexsha": "3519d834f1373e695ed797dce6f3caee82a40d7e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 121, "max_issues_repo_issues_event_min_datetime": "2015-01-27T14:09:47.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-16T00:03:14.000Z", "max_forks_repo_path": "albums-walls.tex", "max_forks_repo_name": "isabella232/ldbc_snb_docs", "max_forks_repo_head_hexsha": "3519d834f1373e695ed797dce6f3caee82a40d7e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2016-01-05T17:52:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T19:58:23.000Z", "avg_line_length": 65.6715328467, "max_line_length": 385, "alphanum_fraction": 0.7184617095, "num_tokens": 2789, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.3106943895971202, "lm_q1q2_score": 0.16625207965652325}} {"text": "\\IEEEPARstart{A}{udio} localization in stereophonic recording focuses on balancing the pressure level and time difference cues that inform audio localization through interaural time differences (ITD) and interaural level differences (ILD). Within the stereophonic recording praxis, it is understood that the weighting of ITD and ILD cues contributes to varying desirable qualities within the resultant soundfield. Stereophonic microphone arrays are also chosen to account for the desired balance of direct sound and reflected sound and to accommodate the recording angle of the perceptual \"soundstage\" and translate it to audio reproduction systems with minimal angular distortion.\n\nThis is, however, at odds with typical stereophonic localization practice within the application of audio signal processors; which tend to prioritize localization solely through ILD cues. In certain contexts this can lead to a situation where recorded signals that are being mixed together during post-production can be localized using different perceptual locative cues, yet with the intent of producing a coherent, and qualitatively consistent perceptual soundstage.\n\nBy modelling the time and level relationships between a sound source and the microphones in a stereophonic recording array, a monophonically recorded sound can be localized within the perceptual soundstage using the time and level cues appropriate to the modeled array. This paper will outline an algorithm and discuss and implementation for abstracting these relationships in to a CPU-efficient model, and exposing the appropriate parameters to the user.\n\n\\subsection{A Review of Localization in Stereo Recording}\n\nWithin the context of localization, it is understood that a relative dominance of time-domain cues creates a greater perceived sense of stereophonic width/envelopment, whereas a greater relative preponderance of level-based cues increases the sense of locative precision. Microphones, as pressure transducers, encode local changes in atmospheric pressure into changes in electrical pressure, and can be practically thought of as sampled points in space. Additionally, microphones have varying types of directivity -- represented by a polar plot -- that represent how efficiently they transduce sound based on the sound-wave angle of arrival relative to the microphone's orientation. For directional microphones with cardioid-style polar patterns, the amount of attenuation tends to increase as the sound-wave's direction of arrival moves further away from the oriented \"front\" of the microphone\\footnote{There is some complexity with this as the directivity pattern value increases past a pure-cardioid, with an inverse-phase area beginning to present at the rear of the microphone and increasing until the directivity approaches a bidirectional pattern}.\n\nBy positioning two directional microphones in the same location and facing in two different directions, any sound-wave captured by them will be increasingly less attenuated as it approaches the front of one microphone and more attenuated as it approaches the other. If the sound wave approaches from an angle that equiangular to both microphones, then it will be equally attenuated. This equal attenuation, during reproduction, will have the perceptual effect of placing the sound at the center of the virtual sound-stage. \n\nSimilarly, by positioning two nondirectional microphones in to locations within the space, the distance between them will create differences in the time of arrival based on the speed of propagation of the sound-wave (the speed of sound). As the direction of arrival shifts away from being perpendicular to an imaginary line drawn from one microphone to the other, there will be an increasing time delay between when the sound is captured in the closer microphone and when it is captured in the further microphone. As with the level-based cues, when the time of arrival is equal (i.e. there is no delay in one microphone) then the perceptual effect during reproduction is one of the sound being centered in the perceptual soundstage. As the delay increases in one microphone, the sound will appear to come from the direction in which it arrives first\\footnote{This phenomenon is known as the \"precedence effect\"}.\n\nThese level and time-based principles can be freely combined, creating a spectrum of options for recording engineers to choose from. More advanced methodologies will add in a center microphone (such as the popular \"Decca-Tree\" configuration), and/or will also add flanking/outrigger microphones as well. The combined effect of these various microphone set-ups yields a complex interplay of time and level cues.\n\n\\subsection{Signal-Processing Panning Methods}\n\nCurrent methods in stereophonic panning within digital audio workstations (DAW) typically focus on the manipulation of level differences. These level differences tend to follow either a sine-cosine (see \\ref{threedB}) or a linear curve (see \\ref{sixdB}).\n\nFor $\\{p \\: | \\: 0 \\leq p \\leq 1\\}$ to represent the range of the user input value for stereophonic panning, then the normal panning functions can be found as:\n\n\\begin{equation} \\label{threedB}\n\\begin{bmatrix}L \\\\ R \\end{bmatrix} = x * \\begin{bmatrix} \\cos{\\frac{p\\pi}{2}} \\\\ \\sin{\\frac{p\\pi}{2}} \\end{bmatrix}\n\\end{equation}\n\n\\begin{equation}\\label{sixdB}\n\\begin{bmatrix}L \\\\ R \\end{bmatrix} = x * \\begin{bmatrix} p \\\\ 1 - p \\end{bmatrix}\n\\end{equation}\n\nInterestingly, there is not as accepted standard functionality for DAWs to perform panning based on time-domain cues. Multiple reasons can be found for this, though the two that arguably stand out are: lack of monophonic compatibility due to phase distortions, and tradition from analogue mixing consoles which were unable to provide the delay lines necessary. Additionally, the usage of computer memory for the circular-buffer delay-lines needed may have also been a consideration against memory availability in early computers.\n\nThe use of time-domain cue is either implemented through a stereo \"widener\\footnote{The implementation of stereo widening techniques varies from processor to processor, not all will use the same methods. Any given widener may not actually use time-based cues, relying instead solely on frequency-domain adjustments or dynamics range processing.}\" or by manual implementation through simple or purpose-built delay audio plug-ins in a technique known as the \"Haas Trick\\footnote{after Helmut Haas, who studied the psychoacoustical implications of the precedence effect in his Ph.D. thesis.}.\"\n\n\\subsection{Purpose}\n\nThis paper will describe an algorithm for modeling the interplay of the microphones within a stereophonic recording array; and discuss an audio plug-in that implements this algorithm. This algorithm and the accompanying audio processor were developed as an entry to the AES/MATLAB Plugin Competition in 2020. As such, the processor developed was designed to work within the limits of the competition -- most specifically the two-channel input/output requirement, and the goal to solve a specific use-case scenario. Theoretically, this algorithm could be applied to any arbitrary microphone set-up and source placement within a virtual space.\n\nThe immediate use-cases intended to be addressed with this specific implementation are: 1. the placement of monophonically recorded sources into a stereophonic microphone array, and 2. the addition of time-domain cues through a UI that is intuitive and effective, and yields natural and predictable results.\n\n\\subsubsection{Blending monophonic encoded sources}\n\nWhen recording acoustic ensembles, recording engineers will frequently employ both a main stereo array and area/spot microphones. These spot microphones are used to accentuate various parts of the ensemble to difference logistical and aesthetic ends. Drawing from previous sections, stereo recording praxis and panning implementation in DAWs do not agree on how to encode stereophonic localization cues. This can quickly lead to a situation where the sound of an instrument recorded in an ensemble with both a stereo array and spot microphone will have a mixture of time/level cues in the main array signal, but only be localized with level cues in the panned signal from the spot microphone. Due to the differences in the perceptual effect of time and level cues, this can lead to inconsistencies in the quality of the soundfield as the dominance of the source of the instrument in the audio mix changes between the main array and the spot microphones; this may also cause inconsistency in instruments that are around the spot microphone. The use of this processor will encode the monophonic sound with time and level cues that closely match that of the main array, meaning that its localization and sense of envelopment will not change based on the dominance of the source.\n\nFollowing this, another context for this application of the processor is in blending a monophonic recorded source into a recording that was taken of an ensemble using a stereophonic microphone array. \"Distributed recording\" is not uncommon -- especially in music for media. It is not uncommon for sections of an ensemble to be recorded independently and then put together during post-production. This processor would allow for independently recorded instruments to be better blended into a larger ensemble by encoding them with the same localization cues, creating a greater qualitative unity in the resultant soundfield.\n\nThis also has implications for sample-based music production and the common practice of laying samples of the same instrument family that come from different sample libraries. Commercial sample libraries each have their own recording and staging procedures, and different instruments and sections can be localized using different combinations of level and time-domain cues. The use of this processor on the spot microphone or monophonic summed options will allow for the sounds to be spatialized together in a more consistent manner.\n\nFinally, this processor can also be used in conjunction with standard post-processing artificial reverberation techniques to manufacture a sense of unity from completely independently recorded instruments by encoding them onto a virtual soundstage using natural level and time-domain cues. \n\n\\subsubsection{Time-domain cues in panning}\n\nA secondary use for this processor is in presenting an intuitive method of adding time-domain cues into panning. Rather than relying on an arbitrary implementation of the Haas trick, a user of this processor can -- through the familiar metaphor of a stereophonic microphone pair -- creating a consistent, repeatable, and intuitive panning plan for components of their audio mixdown that includes both time and level perceptual components. \n\n", "meta": {"hexsha": "c486cb44c0e9baf1ebc1dd3a213e5cf0611801f1", "size": 10800, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Technical Documentation/overview.tex", "max_stars_repo_name": "jmclark85/StereoPairsEmulator", "max_stars_repo_head_hexsha": "a78161b4b99b50e481c133ba8a5049d548561954", "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": "Technical Documentation/overview.tex", "max_issues_repo_name": "jmclark85/StereoPairsEmulator", "max_issues_repo_head_hexsha": "a78161b4b99b50e481c133ba8a5049d548561954", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-08-26T18:24:14.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-26T18:24:14.000Z", "max_forks_repo_path": "Technical Documentation/overview.tex", "max_forks_repo_name": "jmclark85/StereoPairsEmulator", "max_forks_repo_head_hexsha": "a78161b4b99b50e481c133ba8a5049d548561954", "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": 196.3636363636, "max_line_length": 1275, "alphanum_fraction": 0.8202777778, "num_tokens": 2104, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.31742627204485063, "lm_q1q2_score": 0.16614737007527225}} {"text": "\\documentclass{article}\n\\usepackage[utf8]{inputenc}\n\\usepackage{amsmath,amssymb}\n\\usepackage{hyperref}\n\n\\newcommand{\\func}[1]{\\mathsf{#1}}\n\n\\title{Haven Protocol code notes}\n\\author{Cypher Stack\\thanks{\\url{https://cypherstack.com}}}\n\\date{\\today}\n\n\\begin{document}\n\n\\maketitle\n\n\n\\section{Introduction}\n\nThis document describes technical information relevant to Haven Protocol.\nIt reflects a snapshot of the codebase repository\\footnote{\\url{https://github.com/haven-protocol-org/haven-main/tree/v2.0.0-rc3}}, but its findings and observations may be superseded by later changes.\nAs with any code review, this analysis is limited and cannot capture all use cases or unintended behaviors of the codebase in all circumstances; it reflects a best-effort approach of the author to determine the extent to which relevant portions of the codebase reflect verification operations in the transaction protocol description\\footnote{\\url{https://github.com/cypherstack/haven-protocol-review/releases/tag/final}} approved by its designers.\nIt does not specifically address the scope of best-practice secure C\\texttt{++} design principles, for which the authors recommend further detailed review.\nThe author asserts no warranty and disclaims liability for its use.\nThe author further expresses no endorsement of Haven Protocol or its associated entities.\n\n\n\\section{Structure}\n\nIn this section, we describe the structural similarities and differences between the protocol description and its implementation.\n\n\\subsection{Transaction types}\n\nThe protocol description describes two types of transactions: \\textit{transfer} and \\textit{conversion}.\nTransfer transactions consume and generate assets of a single type, where balance is asserted if the combined value of spent inputs is equal to the combined value of generated outputs.\nConversion transactions consume assets of a single type, and generate assets of the consumed type and a single additional type.\nIn this case, balance is asserted if the combined value of spent input inputs is equal to the combined value of generated outputs after applying a scaling factor produced by a pricing oracle.\n\nThe protocol description requires that transfer transactions generate at least two outputs, which mitigates analysis based on knowledge of commitment masks or values.\nIt requires that conversion transactions generate at least one output of each of the two required types, but discussions with the designers indicate the intent is to require at least two source- and destination-type generated outputs.\n\nThe implementation differs from the protocol in further delineating transaction types based on specific asset types.\nTransaction types are defined in \\texttt{cryptonote::transaction\\_type}, and are inferred from given source and destination strings in \\texttt{cryptonote::get\\_tx\\_type}:\n\\begin{itemize}\n\t\\item \\texttt{UNSET}: no type has been specified\n\t\\item \\texttt{TRANSFER}: source and destination types are both \\texttt{XHV}\n\t\\item \\texttt{OFFSHORE\\_TRANSFER}: source and destination types are both \\texttt{XUSD}\n\t\\item \\texttt{XASSET\\_TRANSFER}: source and destination types are the same, but neither \\texttt{XHV} nor \\texttt{XUSD}\n\t\\item \\texttt{OFFSHORE}: source type is \\texttt{XHV} and destination type is \\texttt{XUSD}\n\t\\item \\texttt{ONSHORE}: source type is \\texttt{XUSD} and destination type is \\texttt{XHV}\n\t\\item \\texttt{XUSD\\_TO\\_XASSET}: source type is \\texttt{XUSD} and destination type is neither \\texttt{XHV} nor \\texttt{XUSD}\n\t\\item \\texttt{XASSET\\_TO\\_XUSD}: source type is neither \\texttt{XHV} nor \\texttt{XUSD}, and destination type is \\texttt{XUSD}\n\\end{itemize}\nAny other combination of source and destination strings is rejected.\n\n\n\\subsection{Asset types}\n\nSource and destination asset type strings for a transaction are established in \\texttt{cryptonote::get\\_tx\\_asset\\_types}, where protocol consistency rules are applied based on the structure of consumed and generated transaction outputs:\n\\begin{enumerate}\n\t\\item The transaction must consume only a single asset type, which is defined to be the source asset type.\n\t\\item If the transaction is a miner transaction, the destination asset type is defined to be the base \\texttt{HXV} asset type, and no source transaction type is specifically defined.\n\t\\item If the transaction is not a miner transaction and generates a single asset type, it must match the source asset type and is defined to be the destination asset type.\n\t\\item If the transaction is not a miner transaction and generates two asset types, exactly one of them must match the source asset type; both are defined to be the destination asset types.\n\t\\item If the transaction is not a miner transaction, it may not generate outputs of more than two asset types.\n\t\\item All source and destination asset types must belong to the static list defined in \\texttt{offshore:ASSET\\_TYPES}.\n\\end{enumerate}\nThese rules differ from the protocol description.\nMiner transactions, which are part of the parent transaction protocol, are not specifically defined in the scoped transaction protocol, but are restricted in implementation to the base asset; notably, miner transaction output types are not checked in this function to be of the base asset type; the destination asset type is set manually.\nSource and destination types default to an empty string, which is not specifically defined as either an asset type nor an indicated error condition.\n\n\n\\subsection{Transfer transaction balance}\n\nThe balance logic for transfer transactions of the types \\texttt{OFFSHORE\\_TRANSFER}, \\texttt{TRANSFER}, and \\texttt{XASSET\\_TRANSFER} is established and checked in the function \\texttt{rct::verRctSemanticsSimple2}.\nThis function assumes prior establishment of source and destination asset type strings, which are checked against the static list of valid types.\nIn the case of transfer transactions, the source and destination type are identical.\nThe function is intended to process transfer and conversion transactions, and so we must ensure that the common logic applies to the specific protocol requirements of transfer transactions.\nUsing the notation of the protocol description, the following is computed and checked:\n$$\\sum_{u=0}^{w-1} C_u' - \\func{Com}(f,0) - \\func{Com}(f',0) - \\sum_{j=0}^{t-1} \\overline{C}_j = 0$$\nHere $f$ is the transaction fee and $f'$ is the \\textit{offshore fee} as noted in code comments.\nThe offshore fee is not captured by the protocol description, but is handled in the same manner as the transaction fee.\nTransactions of type \\texttt{TRANSFER} have the logic applied as the result of a default condition of a conditional block that checks against possible types; if another transaction type were presented that was not of the types in this block, it would evaluate using the transfer logic.\n\n\n\\subsection{Conversion transaction balance}\n\nThe balance logic for conversion transactions of the types \\texttt{OFFSHORE}, \\texttt{ONSHORE}, \\texttt{XUSD\\_TO\\_XASSET}, and \\texttt{XASSET\\_TO\\_XUSD} is also established and checked in the same function.\nIn these cases, the source and destination asset type strings are different, but checked against the static list of valid types.\nUsing the notation of the protocol description, the following is computed and checked:\n$$\\sum_{u=0}^{w-1} C_u' - \\func{Com}(f,0) - \\func{Com}(f',0) - \\sum_{j=0}^{n_T-1} \\overline{C}_j - \\frac{1}{r} \\sum_{n_T}^{t-1} \\overline{C}_j = 0$$\nHere, the value of $r$ is scaled by an atomic unit factor $\\texttt{COIN}$ depending on whether \\texttt{XUSD} is a source or destination asset type.\nAs with transfer transactions, the offshore fee is not captured by the protocol description.\nFurther, atomic unit conversions to and from \\texttt{XUSD} type are not captured by the protocol description.\n\n\n\\subsection{Burn amount verification}\n\nThe conversion burn amount verification check required by the protocol also takes place in \\texttt{rct::verRctSemanticsSimple2}.\nThis is intended to confirm a plaintext amount sum for the source asset type corresponds validly to the associated commitments presented in the transaction.\nAccording to the protocol description, this is asserted by the following check:\n$$\\sum_{u=0}^{w-1} C_u' - \\sum_{j=0}^{n_T-1} \\overline{C}_j - \\func{Com}(f,0) - \\func{Com}(0,a_T - \\overline{a}_T) - \\func{Com}(y_T,0) = 0$$\nThe check performed in the implementation differs in its commitment construction, performing this check:\n$$\\sum_{u=0}^{w-1} C_u' - \\sum_{j=0}^{n_T-1} \\overline{C}_j + \\func{Com}(0,\\overline{a}_T) = \\func{Com}(y_T - f'',a_T) = 0$$\nHere $f''$ is defined in the code as a scaled \\textit{burn fee} computed from the offshore fee, which is not captured by the protocol description.\nNote that while the commitments constructed in the implementation differ from the construction method in the protocol, they are algebraically equivalent (aside from the burn fee).\n\n\n\\subsection{Mint amount verification}\n\nThe conversion mint amount verification check required by the protocol takes place in the function \\texttt{rct::checkBurntAndMinted}, which is called from the function \\texttt{tx\\_memory\\_pool::add\\_tx2}.\nThis is intended to check a claimed plaintext amount sum for the destination asset type.\nAs noted in the protocol description, this is not checked against commitments presented in the transaction.\nIt appears that a user generating such a transaction could simply provide a plaintext minted amount sum satisfying the check without any particular correspondence to commitments; however, we argue in the protocol description that security is not reduced by removing this check altogether.\nThe verifier can produce the value on its own if needed, and avoid relying on the value provided in the transaction.\n\n\n\\subsection{Linkable ring signature}\n\nBoth transfer and conversion transactions require a linkable ring signature on each consumed source asset.\nThe protocol description assumes the use of CLSAG signatures for this use.\nThe implementation uses the CLSAG implementation from its parent codebase, where verification of signatures is performed within \\texttt{rct::verRctCLSAGSimple}, which binds an arbitrary message into the signature.\nThe implementation of \\texttt{rct::verRctCLSAGSimple} appears to be correctly ported from the parent codebase.\nWhile the protocol description does not specify the format of the message bound to each CLSAG signature, it should be checked that this message includes any replay-specific mitigations relevant to transactions that may differ from the parent codebase.\n\n\n\\subsection{Range proofs}\n\nGenerated outputs in both transfer and conversion transactions require one or more range proofs to assert committed values are within a protocol-specified range.\nThe protocol description assumes the use of the Bulletproofs range proving system for this use.\nThe implementation uses the Bulletproofs implementation from its parent codebase, where verification of aggregated proofs is performed within \\texttt{rct::verBulletproof}.\nThe implementation of the verification wrapper \\texttt{rct::verBulletproof} (and its underlying direct verification function) appears to be correct as unchanged from its parent repository.\nAtomic unit conversion is not performed prior to range proof verification, as this is done for balance purposes separately.\n\n\n\\section{Observations}\n\nIn this section, we describe findings and observations within the Haven Protocol codebase relevant to verification in the transaction protocol, and note possible suggestions for improvement where appropriate.\n\n\n\\subsection{Pricing oracles}\n\nThe protocol relies heavily on a single pricing oracle that is assumed to securely provide responses to queries for asset conversion rates.\nNo checks are assumed to be made about the consistency of its responses.\nThe implementation relies on a set of hardcoded oracles \\texttt{config::ORACLE\\_URLS} defined for the live network and test networks; for each network, the oracles share a single verification public key.\n\nOracle queries are performed in \\texttt{Blockchain::get\\_pricing\\_record}.\nThis function shuffles the oracle list (presumably for load balancing reasons), and then queries the shuffled list until a response is returned.\nThe query includes a network version flag and encoded block timestamp.\nOn receipt of a response, the function verifies a response signature against the hardcoded public key.\nIf verification fails or no response is received from any oracle, an empty response is constructed that instantiates with zero values.\nThe result is used to populate a pricing record on each supported asset type.\n\nThe oracle implementation currently deployed returns JSON data consisting of asset types with integer-valued conversion rates, a timestamp, an encoded signature, and unused auxiliary data.\nTo verify the signature, a JSON string is reconstructed with all asset types, corresponding conversion rates, and timestamp (if nonzero).\nSignature values are decoded using a method that is not documented.\nThe algorithm used to verify the signature is not made explicit, as it appears to be inferred from the encoded public key.\nBased on limited comments in the code, it may be ECDSA, but this is not confirmed.\n\nAll hardcoded mainnet oracles accept HTTPS queries on port 443, reject HTTP queries on port 80, and reject HTTP queries on port 443.\nOracles are hardcoded by domain and not IP, appear to defer to the user's chosen DNS provider for IP resolution, and appear to defer to the user's local certificate authority for server authentication.\n\n\n\\subsection{Pricing record inversion}\n\nIn balance computation, pricing record values are converted to scalar field elements and may be multiplicatively inverted.\nThe inversion algorithm is only guaranteed to succeed on nonzero input; there is a check within the \\texttt{invert} function that will fail on zero input, but it only runs on the presence of a debugging flag.\nThe pricing record values in balance computation are not tested within \\texttt{verRctSemanticsSimple2} to assert they are nonzero.\nPricing oracle queries may return zero values, or the entire query may fail and result in a zero-default pricing record instantiation.\nThere exists a check in \\texttt{tx\\_memory\\_pool::add\\_tx2} against zero-value specific entries within pricing records.\nA safer additional guard is to enable the inversion check on production builds; the operation is extremely efficient, and is the most direct guarantee that the algorithm succeeded.\nAnother safe option is to test input scalars to the inversion function to assert they are nonero; this check would also be extremely efficient.\n\n\n\\subsection{Common key type}\n\\label{obs:common-key-type}\n\nThe codebase, like that of its upstream parent, uses a single byte array type \\texttt{rct::key} to represent two underlying mathematical types: elliptic curve group elements and elements of this group's scalar field.\nBoth element types have canonical 32-byte representations, but they are not directly algebraically compatible.\nA comprehensive codebase update might use separate byte array types for curve group and scalar elements in order to reduce confusion and the likelihood of errors in algorithm design or implementation; however, this common type is widely used throughout the implementation, implying risk in such a wide-ranging change that would need to be carefully considered.\n\n\n\\subsection{Inconsistent key initialization}\n\\label{obs:key-initialization}\n\nRelated to Observation \\ref{obs:common-key-type}, group and scalar elements are occasionally initialized inconsistently.\nThe zero scalar is defined using the \\texttt{rct::zero()} function, which returns a constant byte array \\texttt{(0x00,...,0x00)} as its canonical byte representation.\nThe zero (identity) group element is defined using the \\texttt{rct::identity()} function, which returns as its canonical byte representation a constant byte array \\texttt{(0x01,0x00,...,0x00)}.\nHowever, several locations in \\texttt{rctSigs.cpp} initialize group elements unexpectedly using \\texttt{rct::zero()} or \\texttt{memwipe}, which could have unintended behavior if these values are not later set directly or by appropriate function calls to other algorithms or operations.\n\nExamples of this behavior include:\n\\begin{itemize}\n\t\\item \\texttt{rctSigs.cpp}, lines 933-935\n\t\\item \\texttt{rctSigs.cpp}, line 1328\n\t\\item \\texttt{rctSigs.cpp}, line 1584\n\\end{itemize}\nRelying on later function calls or algorithms to reset group elements to another value is not robust, and may lead to unsafe results.\nCare should be taken to initialize group and scalar elements correctly when using \\texttt{rct::key}, as it is not always obvious from context which element type is intended.\n\n\n\\subsection{Inconsistent asserts}\n\\label{obs:asserts}\n\nLow-level balance verification in \\texttt{verRctSemanticsSimple2} performs computations on input and output data based on transaction and asset types discussed previously.\nFor this reason, it is essential that these types are valid and consistent.\nThe asserts contained in the low-level balance verification check that source and destination asset types are valid by their inclusion in \\texttt{offshore::ASSET\\_TYPES}.\nLater, the balance computation sorts outputs by asset type, and then uses the transaction type to complete the computation.\nHowever, this does not account for the required consistency between output asset types, source and destination asset type strings, and transaction type provided as function arguments.\nRather, these consistency checks are offloaded.\nFor this reason, the inclusion of one consistency check for valid source and destination asset type strings appears inconsistent, as it is also performed prior to the function being called.\nIt may be useful to standardize the validity and consistency checks between transaction types and asset types to improve reliability and efficiency, and reduce the possibility of error.\nIn particular, if these validity checks are not intended to be used in other parts of the protocol, it may be safest to call them directly from \\texttt{verRctSemanticsSimple2} (to ensure they are run whenever this verification takes place), or to document carefully the requirements and assumptions on the function arguments.\n\n\n\\subsection{Underspecified transaction type check}\n\\label{obs:transaction-type-check}\n\nWhen performing the balance check in \\texttt{verRctSemanticsSimple2}, the transaction type is crucially used to identify the scaling and outputs to be used in the calculation.\nThis is done by building the sum-to-zero element \\texttt{Zi} in a way that is dependent on the transaction type.\nGeneric \\texttt{TRANSFER} transactions are not specifically checked by the conditional in balance verification, instead being the result of a default condition.\n\nWhile this does not pose a problem if possible valid transaction types are not added, it would be safest to reject transactions not meeting the expected type, as there may be unintended behavior resulting from attempting to complete the computation and balance validity check on an unexpected transaction type.\n\n\n\\subsection{Unnecessary identity computations}\n\nAs noted in Observation \\ref{obs:key-initialization}, the elliptic curve group identity element can be obtained via a call to \\texttt{rct::identity()}, which returns a constant byte array consisting of the canonical representation of this element.\n\nIn several locations in \\texttt{rctSigs.cpp}, the identity group element is computed by computing the scalar-group multiplication \\texttt{scalarmultH(d2h(0))}, which is unnecessary and less efficient.\n\nExamples of this behavior include:\n\\begin{itemize}\n\t\\item \\texttt{rctSigs.cpp}, line 1327\n\t\\item \\texttt{rctSigs.cpp}, line 1583\n\t\\item \\texttt{rctSigs.cpp}, line 1866\n\t\\item \\texttt{rctSigs.cpp}, line 1869\n\t\\item \\texttt{rctSigs.cpp}, line 1870\n\t\\item \\texttt{rctSigs.cpp}, line 1871\n\\end{itemize}\nAll such function calls can safely be replaced with \\texttt{rct::identity()} calls for clarity and speed.\n\n\n\\subsection{Fee ranges}\n\nThe protocol description requires that fees be checked to lie within a protocol-specified range.\nBecause fees are presented in the clear, they do not come equipped with range proofs.\nHowever, fees are used in the verification function \\texttt{verRctSemanticsSimple2} to produce commitments that may overflow the balance check if not asserted to be within the required range.\nAll fees, including those outside of the scope of the protocol description, should be carefully checked to ensure they cannot overflow the balance check.\nOne way to ensure this is by suitable truncation encoding that is properly re-encoded to a scalar value for commitment computation.\n\n\n\\subsection{Undocumented signature verification}\n\nAs noted previously, pricing oracle responses come equipped with a signature that is verified prior to acceptance using \\texttt{pricing\\_record::verifySignature}.\nHowever, the details of this verification process are not clearly documented.\n\nIn particular, the signature algorithm intended to be used for the public key appears to be inferred from the key type, which is not specified in the code.\nSecond, a comment indicates that the decoded signature is reformatted to match an OpenSSL format, but the details of the formatting operation are unclear, so it is not possible to properly assess.\nFinally, the verification algorithm is unspecified at the time of verification (related, presumably, to the key type as noted above).\n\nBecause price oracle response validity is crucial to the safe operation of the protocol, the methods used to verify oracle signatures should be clearly documented.\n\nA separate option (if reliance on OpenSSL functionality is not desired) may be to use a Schnorr signature on the oracle response, which could take advantage of structures and functions already present in the codebase, including those for deseralizing keys and signatures.\nHowever, this change could introduce additional implementation risk and complexity.\n\n\n\\end{document}\n", "meta": {"hexsha": "ad8c9c4633576cdf3f4e6c39a188de71a70ab85d", "size": 21997, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "main.tex", "max_stars_repo_name": "AaronFeickert/haven-code-review", "max_stars_repo_head_hexsha": "66650628c2eef314e6aa9333626d6d89f6d2d9b7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "main.tex", "max_issues_repo_name": "AaronFeickert/haven-code-review", "max_issues_repo_head_hexsha": "66650628c2eef314e6aa9333626d6d89f6d2d9b7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "main.tex", "max_forks_repo_name": "AaronFeickert/haven-code-review", "max_forks_repo_head_hexsha": "66650628c2eef314e6aa9333626d6d89f6d2d9b7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-12-04T20:09:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-10T03:35:32.000Z", "avg_line_length": 82.3857677903, "max_line_length": 447, "alphanum_fraction": 0.8067918353, "num_tokens": 4745, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3242353924510608, "lm_q1q2_score": 0.1659166341499794}} {"text": "\n\\section{Free Energy of Conformational Change Calculations}\n\\label{section:fenergy}\n\n\\NAMD\\ incorporates methods for performing free energy of conformational change perturbation calculations.\nThe system is efficient if only a few coordinates, either of individual atoms or centers of mass of groups of atoms, are needed.\nThe following configuration parameters are used to enable free energy perturbation:\n\n\\begin{itemize}\n\n\\item\n\\NAMDCONFWDEF{freeEnergy}{is free energy perturbation active?}{{\\tt on} or {\\tt off}}{{\\tt off}}\n{Specifies whether or not free energy perturbation is active. If it \nis set to {\\tt off}, then no free energy perturbation is performed. \nIf it is set to {\\tt on}, then the free energy perturbation calculation specified in\n{\\tt freeEnergyConfig} parameters is executed.}\n\n\\item\n\\NAMDCONF{freeEnergyConfig}{free energy perturbation script}{file or \\{script\\}}\n{Must contain either the name of a free energy perturbation script file or the script \nitself between \\{ and \\} (may include multiple lines).\nThis parameter may occur multiple times and scripts will be executed\nin order of appearance.\nThe format of the free energy perturbation script is described below.\n}\n\n\\end{itemize}\n\nThe following sections describe the format of the free energy perturbation script.\n\n% Free energy perturbation parameters\n% Free energy perturbation parameters, included into usage description\n\n\\subsection{User-Supplied Conformational Restraints}\n\nThese restraints extend the scope of the available restraints beyond that\nprovided by the harmonic position restraints. Each restraint is imposed with\na potential energy term, whose form depends on the type of the\nrestraint.\\medskip\n\n{\\bf Fixed Restraints}\n\n{\\em Position restraint (1 atom):} force constant $K_{f}$, and reference\nposition $\\overrightarrow{r_{ref}}$\n\n$\\qquad \\qquad \\qquad \\qquad E=\\left( K_{f}/2\\right) \\left( \\left| \n\\overrightarrow{r_{i}}-\\overrightarrow{r_{ref}}\\right| \\right) ^{2}$\n\n{\\em Stretch restraint (2 atoms):} force constant $K_{f}$, and reference\ndistance $d_{ref}$\n\n$\\qquad \\qquad \\qquad \\qquad E=\\left( K_{f}/2\\right) \\left(\nd_{i}-d_{ref}\\right) ^{2}$\n\n{\\em Bend restraint (3 atoms):} force constant $K_{f}$, and reference angle $\n\\theta _{ref}$\n\n$\\qquad \\qquad \\qquad \\qquad E=\\left( K_{f}/2\\right) \\left( \\theta\n_{i}-\\theta _{ref}\\right) ^{2}$\n\n{\\em Torsion restraint (4 atoms):} energy barrier $E_{0}$, and reference\nangle $\\chi _{ref}$\n\n$\\qquad \\qquad \\qquad \\qquad E=\\left( E_{0}/2\\right) \\left\\{ 1-\\cos \\left(\n\\chi _{i}-\\chi _{ref}\\right) \\right\\} $\n\n{\\bf Forcing restraints}\n\n{\\em Position restraint (1 atom):} force constant $K_{f}$, and two reference\npositions $\\overrightarrow{r_{0}}$ and $\\overrightarrow{r_{1}}$\n\n$\\qquad \\qquad \\qquad \\qquad E=\\left( K_{f}/2\\right) \\left( \\left| \n\\overrightarrow{r_{i}}-\\overrightarrow{r_{ref}}\\right| \\right) ^{2}$\n\n$\\qquad \\qquad \\qquad \\qquad \\overrightarrow{r_{ref}}$ $=\\lambda \n\\overrightarrow{r_{1}}+\\left( 1-\\lambda \\right) $ $\\overrightarrow{r_{0}}$\n\n{\\em Stretch restraint (2 atoms):} force constant $K_{f}$, and two reference\ndistances $d_{0}$ and $d_{1}$\n\n$\\qquad \\qquad \\qquad \\qquad E=\\left( K_{f}/2\\right) \\left(\nd_{i}-d_{ref}\\right) ^{2}$\n\n$\\qquad \\qquad \\qquad \\qquad d_{ref}=d_{1}+\\left( 1-\\lambda \\right) d_{0}$\n\n{\\em Bend restraint (3 atoms):} force constant $K_{f}$, and two reference\nangles $\\theta _{0}$ and $\\theta _{1}$\n\n$\\qquad \\qquad \\qquad \\qquad E=\\left( K_{f}/2\\right) \\left( \\theta\n_{i}-\\theta _{ref}\\right) ^{2}$\n\n$\\qquad \\qquad \\qquad \\qquad \\theta _{ref}=\\lambda \\theta _{1}+\\left(\n1-\\lambda \\right) \\theta _{0}$\n\n{\\em Torsion restraint (4 atoms):} energy barrier E$_{0}$, and two reference\nangles $\\chi _{0}$ and $\\chi _{1}$\n\n$\\qquad \\qquad \\qquad \\qquad E=\\left( E_{0}/2\\right) \\left\\{ 1-\\cos \\left(\n\\chi _{i}-\\chi _{ref}\\right) \\right\\} $\n\n$\\qquad \\qquad \\qquad \\qquad \\chi _{ref}=\\lambda \\chi _{1}+\\left( 1-\\lambda\n\\right) \\chi _{0}$\n\nThe forcing restraints depend on the coupling parameter, $\\lambda $,\nspecified in a conformational forcing calculation. For example, the\nrestraint distance, $d_{ref}$, depends on $\\lambda $, and as $\\lambda $\nchanges two atoms or centers-of-mass are forced closer together or further\napart. In this case $K_{f}$ = $K_{f,0}$, the value supplied at input.\n\nAlternatively, the value of $K_{f}$ may depend upon the coupling parameter\n$\\lambda$ according to:\n\n$K_{f}$ = $K_{f,0} \\lambda$\n\n{\\bf Bounds}\n\n\\begin{tabular}{ll}\n{\\em Position bound (1 atom):} & Force constant $K_{f}$, reference position $\n\\overrightarrow{r_{ref}}$, \\\\ \n& and upper or lower reference distance, $d_{ref}$\n\\end{tabular}\n\n\\qquad Upper bound:\n\n$\\qquad \\qquad \\qquad \\qquad E=\\left( K_{f}/2\\right) \\left(\nd_{i}-d_{ref}\\right) ^{2}$ for $d_{i}>d_{ref}$, else $E=0$.\n\n\\qquad Lower bound:\n\n$\\qquad \\qquad \\qquad \\qquad E=\\left( K_{f}/2\\right) \\left(\nd_{i}-d_{ref}\\right) ^{2}$ for $d_{i}$ $<$ $d_{ref}$, else $E=0$.\\smallskip\n\n$\\qquad \\qquad \\qquad \\qquad d_{i}^{2}=\\left( \\left| \\overrightarrow{r_{i}}-\n\\overrightarrow{r_{ref}}\\right| \\right) ^{2}\\medskip \\medskip $\n\n\\begin{tabular}{ll}\n{\\em Distance bound (2 atoms):} & Force constant $K_{f}$, \\\\ \n& and upper or lower reference distance, $d_{ref}$\n\\end{tabular}\n\n\\qquad Upper bound:\n\n$\\qquad \\qquad \\qquad \\qquad E=\\left( K_{f}/2\\right) \\left(\nd_{ij}-d_{ref}\\right) ^{2}$ for $d_{ij}>d_{ref}$, else $E=0$.\n\n\\qquad Lower bound:\n\n$\\qquad \\qquad \\qquad \\qquad E=\\left( K_{f}/2\\right) \\left(\nd_{ij}-d_{ref}\\right) ^{2}$ for $d_{ij}\\theta _{ref},$ else $E=0$.\n\n\\qquad Lower bound:\n\n$\\qquad \\qquad \\qquad \\qquad E=\\left( K_{f}/2\\right) \\left( \\theta -\\theta\n_{ref}\\right) ^{2}$ for $\\theta <\\theta _{ref},$ else $E=0.\\medskip \\medskip\n\\medskip $\n\n\\begin{tabular}{ll}\n{\\em Torsion bound (4 atoms):} & An upper and lower bound must be provided\ntogether. \\\\ \n& Energy gap $E_{0}$, lower AND upper reference angles, $\\chi _{1}$ and $\n\\chi _{2}$, \\\\ \n& and angle~interval, $\\Delta \\chi .$\n\\end{tabular}\n\n\\qquad \\qquad \n\\begin{tabular}{llll}\n$\\chi _{1}$ & $<\\chi $ & $<\\chi _{2}$ : & $E=0$ \\\\ \n$\\left( \\chi _{1}-\\Delta \\chi \\right) $ & $<\\chi $ & $<\\chi _{1}$ : & $\nE=\\left( G/2\\right) \\left\\{ 1-\\cos \\left( \\chi -\\chi _{1}\\right) \\right\\} $\n\\\\ \n$\\chi _{2}$ & $<\\chi $ & $\\left( \\chi _{2}+\\Delta \\chi \\right) $: & $\nE=\\left( G/2\\right) \\left\\{ 1-\\cos \\left( \\chi -\\chi _{2}\\right) \\right\\} $\n\\\\ \n$\\left( \\chi _{2}+\\Delta \\chi \\right) ~$ & $<\\chi $ & $\\left( \\chi\n_{1}-\\Delta \\chi +2\\pi \\right) $ : & $E=G$\n\\end{tabular}\n\n$\\qquad \\qquad G=E_{0}/\\left\\{ 1-\\cos \\left( \\Delta \\chi \\right) \\right\\}\n\\bigskip $\n\nBounds may be used in pairs, to set a lower and upper bound. Torsional\nbounds always are defined in pairs.\n\n\\subsection{Free Energy Calculations}\n\n{\\bf Conformational forcing / Potential of mean force}\n\nIn conformational forcing calculations, structural parameters such as atomic\npositions, inter-atomic distances, and dihedral angles are forced to change\nby application of changing restraint potentials. For example, the distance\nbetween two atoms can be restrained by a potential to a mean distance that\nis varied during the calculation. The free energy change (or potential of\nmean force, pmf) for the process can be estimated during the simulation.\n\nThe potential is made to depend on a coupling parameter, $\\lambda $, whose\nvalue changes during the simulation. In potential of mean force\ncalculations, the reference value of the restraint potential depends on $\n\\lambda $. Alternately, the force constant for the restraint potential may\nchange in proportion to the coupling parameter. Such a calculation gives the\nvalue of a restraint free energy, i.e., the free energy change of the\nsyste\\bigskip m due to imposition of the restraint potential.\n\n{\\bf Methods for computing the free energy}\n\nWith conformational forcing (or with molecular transformation calculations)\none obtains a free energy difference for a process that is forced on the\nsystem by changing the potential energy function that determines the\ndynamics of the system. One always makes the changing potential depend on a\ncoupling parameter, $\\lambda $. By convention, $\\lambda $ can have values\nonly in the range from $0$ to $1$, and a value of $\\lambda =0$ corresponds\nto one defined state and a value of $\\lambda =1$ corresponds to the other\ndefined state. Intermediate values of $\\lambda $ correspond to intermediate\nstates; in the case of conformational forcing calculations these\nintermediate states are physically realizable, but in the case of molecular\ntransformation calculations they are not.\n\nThe value of $\\lambda $ is changed during the simulation. In the first\nmethod provided here, the change in $\\lambda $ is stepwise, while in the\nsecond method it is virtually continuous.\\medskip\n\n{\\em Multi-configurational thermodynamic integration (MCTI).}\n\nIn MCTI one accumulates $\\,\\left\\langle \\partial U/\\partial \\lambda\n\\right\\rangle $ at several values of $\\lambda $, and from these averages\nestimates the integral\n\n\\qquad \\qquad \\qquad \\qquad $-\\Delta A=\\int \\,\\left\\langle \\partial U/\n\\partial \\lambda \\right\\rangle d\\lambda $\n\nWith this method, the precision of each $\\left\\langle \\partial U/\\partial \n\\lambda \\right\\rangle $ can be estimated from the fluctuations of the time\nseries of $\\partial U/\\partial \\lambda $.\\bigskip \n\n{\\em Slow growth.}\n\nIn slow growth, $\\lambda $ is incremented by $\\delta \\lambda =\\pm 1/N_{step}$\nafter each dynamics integration time-step, and the pmf is estimated as\n\n\\qquad \\qquad \\qquad \\qquad $-\\Delta A=\\Sigma $ $\\left( \\partial U/\\partial\n\\lambda \\right) $ $\\delta \\lambda $\n\nTypically, slow growth is done in cycles of: equilibration at $\\lambda =0$,\nchange to $\\lambda =1$, equilibration at $\\lambda =1$, change to $\\lambda =0$\n. It is usual to estimate the precision of slow growth simulations from the\nresults of successive cycles.\n\n\\subsection{Options for Conformational Restraints}\n\n{\\bf User-supplied restraint and bounds specifications}\n\n\\qquad \\qquad urestraint $\\{$\n\n\\qquad \\qquad \\quad n * (restraint or bound specification)\\qquad \\qquad //\nsee below\n\n\\qquad \\qquad $\\}\\medskip $\n\n{\\bf Restraint Specifications (not coupled to pmf calculations)}\n\n\\qquad \\qquad \n\\begin{tabular}{llll}\nposi & ATOM & kf = KF & ref = (X Y Z) \\\\ \ndist & 2 x ATOM & kf = KF & ref = D \\\\ \nangle & 3 x ATOM & kf = KF & ref = A \\\\ \ndihe & 4 x ATOM & barr = B & ref = A\n\\end{tabular}\n\\bigskip \n\n{\\bf Bound Specifications (not coupled to pmf calculations)}\n\n\\qquad \\qquad \n\\begin{tabular}{llll}\nposi bound & ATOM & kf = KF & [low = (X Y Z D) or hi = (X Y Z D)] \\\\ \ndist bound & 2 x ATOM & kf = KF & [low = D or hi = D] \\\\ \nangle bound & 3 x ATOM & kf = KF & [low = A or hi = A] \\\\ \ndihe bound & 4 x ATOM & gap = E & low = A0\\quad hi = A1\\quad delta = A2\n\\end{tabular}\n\\bigskip \n\n{\\bf Forcing Restraint Specifications (coupled to pmf calculations)}\n\n\\qquad \\qquad \n\\begin{tabular}{llll}\nposi pmf & ATOM & kf=KF & low = (X0 Y0 Z0)\\quad hi = (X1 Y1 Z1) \\\\ \ndist pmf & 2 x ATOM & kf=KF & low = D0\\quad hi = D1 \\\\ \nangle pmf & 3 x ATOM & kf=KF & low = A0\\quad hi = A1 \\\\ \ndihe pmf & 4 x ATOM & barr=B & low = A0\\quad hi = A1\n\\end{tabular}\n\\bigskip \n\n{\\bf Units}\n\n\\qquad \\qquad \n\\begin{tabular}{|c|c|}\n\\hline\nInput item & Units \\\\ \\hline\nE, B & kcal/mol \\\\ \nX, Y, Z, D & %TCIMACRO{\\UNICODE{0xc5}{}}\n\\\\ \nA & degrees \\\\ \n$K_{f}$ & kcal/(mol %TCIMACRO{\\UNICODE{0xc5}{}}\n$^{2}$) or kcal/(mol rad$^{2}$) \\\\ \\hline\n\\end{tabular}\n\n\\subsection{Options for ATOM Specification}\n\nThe designation ATOM, above, stands for one of the following forms:\\medskip\n\n{\\bf A single atom}\n\n(segname, resnum, atomname)\n\n{\\em Example:} (insulin, 10, ca)\\medskip \n\n{\\bf All atoms of a single residue}\n\n(segname, resnum)\n\n{\\em Example:} (insulin, 10)\\medskip \n\n{\\bf A list of atoms}\n\ngroup $\\{$ (segname, resnum, atomname), (segname, resnum, atomname), $\\ldots \n$ $\\}$\n\n{\\em Example:} group $\\{$ (insulin, 10, ca), (insulin, 10, cb), (insulin,\n11, cg) $\\}\\medskip $\n\n{\\bf All atoms in a list of residues}\n\ngroup $\\{$ (segname, resnum), (segname, resnum), $\\ldots $ $\\}$\n\n{\\em Example:} group $\\{$ (insulin, 10), (insulin, 12), (insulin, 14) $\n\\}\\medskip $\n\n{\\bf All atoms in a range of residues}\n\ngroup $\\{$ (segname, resnum) to (segname, resnum) $\\}$\n\n{\\em Example:} group $\\{$ (insulin, 10) to (insulin, 12) $\\}\\medskip $\n\n{\\bf One or more atomnames in a list of residues}\n\n\\begin{tabular}{l}\ngroup $\\{$ atomname: (segname, resnum), (segname, resnum), $\\ldots $ $\\}$ \\\\ \ngroup $\\{$ (atomname, atomname, $\\ldots $ ): (segname, resnum), (segname,\nresnum), $\\ldots $ $\\}$\n\\end{tabular}\n\n\\begin{tabular}{ll}\n{\\em Examples:} & group $\\{$ ca: (insulin, 10), (insulin, 12), (insulin, 14) \n$\\}$ \\\\ \n& group $\\{$ (ca, cb, cg): (insulin, 10), (insulin, 12), (insulin, 14) $\\}$\n\\\\ \n& group $\\{$ (ca, cb): (insulin, 10), (insulin, 12) cg: (insulin, 11),\n(insulin, 12) $\\}\\smallskip $\n\\end{tabular}\n\\medskip \n\n{\\em Note: }Within a group, atomname is in effect until a new atomname is\nused, or the keyword all is used. atomname will not carry over from group to\ngroup. This note applies to the paragraph below.\\medskip \n\n{\\bf One or more atomnames in a range of residues}\n\n\\begin{tabular}{l}\ngroup $\\{$ atomname: (segname, resnum) to (segname, resnum) $\\}$ \\\\ \ngroup $\\{$ (atomname, atomname, $\\ldots $ ): (segname, resnum) to (segname,\nresnum) $\\}$\n\\end{tabular}\n\n\\begin{tabular}{ll}\n{\\em Examples:} & group $\\{$ ca: (insulin, 10) to (insulin, 14) $\\}$ \\\\ \n& group $\\{$ (ca, cb, cg): (insulin, 10) to (insulin, 12) $\\}$ \\\\ \n& group $\\{$ (ca, cb): (insulin, 10) to (insulin, 12) all: (insulin, 13) $\\}$\n\\end{tabular}\n\n\\subsection{Options for Potential of Mean Force Calculation}\n\nThe pmf and mcti blocks, below, are used to simultaneously control all\nforcing restraints specified in urestraint above. These blocks are performed\nconsecutively, in the order they appear in the config file. The pmf block is\nused to either a) smoothly vary $\\lambda $ from 0 $\\rightarrow $1 or 1 $\n\\rightarrow $0, or b) set lambda. The mcti block is used to vary $\\lambda $\nfrom 0 $\\rightarrow $1 or 1 $\\rightarrow $0 in steps, so that $\\lambda $ is\nfixed while $dU/d\\lambda $ is accumulated.\\medskip\n\n{\\bf Lamba control for slow growth}\n\npmf $\\{$\n\n~~task = [up, down, stop, grow, fade, or nogrow]\n\n~~time = T [fs, ps, or ns] (default = ps)\n\n~~lambda = Y (value of $\\lambda $; only needed for stop and nogrow)\n\n~~lambdat = Z (value of $\\lambda _{t}$; only needed for grow, fade, and\nnogrow) (default = 0)\n\n~~print = P [fs, ps, or ns] or noprint (default = ps)\n\n$\\}\\medskip $\n\n\\begin{tabular}{ll}\nup, down, stop: & $\\lambda $ is applied to the reference values. \\\\ \ngrow, fade, nogrow: & $\\,\\lambda $ is applied to $K_{f}$. A fixed value, $\n\\lambda _{t}$, is used to determine the ref. values. \\\\ \nup, grow: & $\\lambda $ changes from 0 $\\rightarrow $1. (no value of $\n\\,\\lambda $ is required) \\\\ \ndown, fade: & $\\lambda $ changes from 1 $\\rightarrow $0. (no value of $\n\\,\\lambda $ is required) \\\\ \nstop, nogrow: & dU/d$\\lambda $ is accumulated (for single point\nMCTI)\\medskip \\smallskip\n\\end{tabular}\n\\bigskip\n\n{\\bf Lambda control for automated MCTI}\n\nmcti $\\{$\n\n~~task = [stepup, stepdown, stepgrow, or stepfade]\n\n~~equiltime = T1 [fs, ps, or ns] (default = ps)\n\n~~accumtime = T2 [fs, ps, or ns] (default = ps)\n\n~~numsteps = N\n\n~~lambdat = Z (value of $\\lambda _{t}$; only needed for stepgrow, and\nstepfade) (default = 0)\n\n~~print = P [fs, ps, or ns] or noprint (default = ps)\n\n$\\}\\medskip $\n\n\\begin{tabular}{ll}\nstepup, stepdown: & $\\lambda $ is applied to the reference values. \\\\ \nstepgrow, stepfade: & $\\lambda $ is applied to $K_{f}$. A fixed value, $\n\\lambda _{t}$, is used to determine the ref. values. \\\\ \nstepup, stepgrow: & $\\lambda $ changes from 0 $\\rightarrow $1. (no value of $\n\\lambda $ is required) \\\\ \nstepdown, stepfade: & $\\lambda $ changes from 1 $\\rightarrow $0. (no value\nof $\\lambda $ is required)\\medskip\n\\end{tabular}\n\nFor each task, $\\lambda $ changes in steps of (1.0/N) from 0 $\\rightarrow $1\nor 1 $\\rightarrow $0. At each step, no data is accumulated for the initial\nperiod T1, then dU/d$\\lambda $ is accumulated for T2. Therefore, the total\nduration of an mcti block is (T1+T2) x N.\n\n\\subsection{Examples}\n\n{\\bf Fixed restraints}\n\n\\begin{tabular}{l}\n{\\footnotesize // 1. restrain the position of the ca atom of residue 0.} \\\\ \n{\\footnotesize // 2. restrain the distance between the ca's of residues 0\nand 10 to 5.2\\AA } \\\\ \n{\\footnotesize // 3. restrain the angle between the ca's of residues 0-10-20\nto 90}$^{o}${\\footnotesize \\ .} \\\\ \n{\\footnotesize // 4. restrain the dihedral angle between the ca's of\nresidues 0-10-20-30 to 180}$^{o}${\\footnotesize \\ .} \\\\ \n{\\footnotesize // 5. restrain the angle between the centers-of-mass of\nresidues 0-10-20 to 90}$^{o}${\\footnotesize \\ .}\n\\end{tabular}\n\nurestraint $\\{$\n\n~~posi (insulin, 0, ca) kf=20 ref=(10, 11, 11)\n\n~~dist (insulin, 0, ca) (insulin, 10, ca) kf=20 ref=5.2\n\n~~angle (insulin, 0, ca) (insulin, 10, ca) (insulin, 20, ca) kf=20 ref=90\n\n~~dihe (insulin, 0, ca) (insulin, 10, ca) (insulin, 20, ca) (insulin, 30,\nca) barr=20 ref=180\n\n~~angle (insulin, 0) (insulin, 10) (insulin, 20) kf=20 ref=90\n\n$\\}\\bigskip $\n\n\\begin{tabular}{ll}\n{\\footnotesize // 1. } & {\\footnotesize restrain the center of mass of three\natoms of residue 0.} \\\\ \n{\\footnotesize // 2.} & {\\footnotesize restrain the distance between (the\nCOM of 3 atoms of residue 0) to (the COM of 3 atoms of residue 10).} \\\\ \n{\\footnotesize // 3.} & {\\footnotesize \\ restrain the dihedral angle of\n(10,11,12)-(15,16,17,18)-(20,22)-(30,31,32,34,35) to 90}$^{o}$ \\\\ \n{\\footnotesize //} & {\\footnotesize ( (ca of 10 to 12), (ca, cb, cg of 15 to\n18), (all atoms of 20 and 22), (ca of 30, 31, 32, 34, all atoms of 35) ).}\n\\end{tabular}\n\nurestraint $\\{$\n\n~~posi group $\\{$(insulin, 0, ca), (insulin, 0, cb), (insulin, 0, cg)$\\}$\nkf=20 ref=(10, 11, 11)\n\n~~\n\\begin{tabular}{ll}\ndist & group $\\{$(insulin, 0, ca), (insulin, 0, cb), (insulin, 0, cg)$\\}$ \\\\ \n& group $\\{$(insulin, 10, ca), (insulin, 10, cb), (insulin, 10, cg)$\\}$\nkf=20 ref=6.2\n\\end{tabular}\n\n~~\n\\begin{tabular}{ll}\ndihe & group $\\{$ca: (insulin, 10) to (insulin, 12)$\\}$ \\\\ \n& group $\\{$(ca, cb, cg): (insulin, 15) to (insulin, 18)$\\}$ \\\\ \n& group $\\{$(insulin, 20), (insulin, 22)$\\}$ \\\\ \n& group $\\{$ca: (insulin, 30) to (insulin, 32), (insulin, 34), all:\n(insulin, 35)$\\}$ barr=20 ref=90\n\\end{tabular}\n\n$\\}$\n\n{\\bf Bound specifications}\n\n\\begin{tabular}{ll}\n{\\footnotesize // 1. } & {\\footnotesize impose an upper bound if an atom's\nposition strays too far from a reference position.} \\\\ \n{\\footnotesize // } & {\\footnotesize (add an energy term if the atom is more\nthan 10\\AA\\ {}from (2.0, 2.0, 2.0) ).} \\\\ \n{\\footnotesize // 2\\&3.} & {\\footnotesize \\ impose lower and upper bounds on\nthe distance between the ca's of residues 5 and 15.} \\\\ \n{\\footnotesize //} & {\\footnotesize (if the separation is less than 5.0\\AA\\ \n{}or greater than 12.0\\AA\\ {}add an energy term).} \\\\ \n{\\footnotesize // 4.} & {\\footnotesize \\ impose a lower bound on the angle\nbetween the centers-of-mass of residues 3-6-9.} \\\\ \n{\\footnotesize //} & {\\footnotesize (if the angle goes lower than 90}$^{o}$\n{\\footnotesize \\ apply a restraining potential).}\n\\end{tabular}\n\nurestraint $\\{$\n\n~~posi bound (insulin, 3, cb) kf=20 hi = (2.0, 2.0, 2.0, 10.0)\n\n~~dist bound (insulin, 5, ca) (insulin, 15, ca) kf=20 low = 5.0\n\n~~dist bound (insulin, 5, ca) (insulin, 15, ca) kf=20 hi = 12.0\n\n~~angle bound (insulin, 3) (insulin, 6) (insulin, 9) kf=20 low=90.0\n\n$\\}\\bigskip $\n\n\\begin{tabular}{l}\n{\\footnotesize // torsional bounds are defined as pairs. this example\nspecifies upper and lower bounds on the} \\\\ \n{\\footnotesize // dihedral angle, }$\\chi ${\\footnotesize {}, separating the\nplanes of the 1-2-3 residues and the 2-3-4 residues.}\n\\end{tabular}\n\n%\\begin{Body Text}\n\\begin{tabular}{llll}\n{\\footnotesize // The energy is 0 for:} & {\\footnotesize -90}$^{o}$ & \n{\\footnotesize < }$\\chi $ & {\\footnotesize <\\ 120}$\n^{o}$ \\\\ \n{\\footnotesize // The energy is 20 kcal/mol for:} & {\\footnotesize 130}$^{o}$\n& {\\footnotesize <\\ }$\\chi $ & {\\footnotesize <\\\n260}$^{o}$\n\\end{tabular}\n\n\\begin{tabular}{l}\n{\\footnotesize // Energy rises from 0 }$\\rightarrow ${\\footnotesize \\ 20\nkcal/mol as }$\\chi ${\\footnotesize \\ {}increases from 120}$^{o}\\rightarrow $\n{\\footnotesize \\ 130}$^{o}${\\footnotesize \\ , and decreases from --90}$\n^{o}\\rightarrow ${\\footnotesize \\ --100}$^{o}${\\footnotesize .}\n\\end{tabular}\n%\\end{Body Text}\n\nurestraint $\\{$\n\n~~dihe bound (insulin 1) (insulin 2) (insulin 3) (insulin 4) gap=20 low=-90\nhi=120 delta=10\n\n$\\}$\n\n{\\bf Forcing restraints}\n\n\\begin{tabular}{l}\n{\\footnotesize // a forcing restraint will be imposed on the distance\nbetween the centers-of-mass of residues (10 to 15) and} \\\\ \n{\\footnotesize // residues (30 to 35). low=20.0, hi=10.0, indicates that the\nreference distance is 20.0%TCIMACRO{\\UNICODE{0xc5}{}}\nat }$\\lambda ${\\footnotesize =0, and 10.0%TCIMACRO{\\UNICODE{0xc5}{}}\nat }$\\lambda ${\\footnotesize =1.}\n\\end{tabular}\n\nurestraint $\\{$\n\n~~\n\\begin{tabular}{ll}\ndist pmf & group $\\{$ (insulin, 10) to (insulin, 15) $\\}$ \\\\ \n& \\hspace{0pt}group $\\{$ (insulin, 30) to (insulin, 35) $\\}$ kf=20,\nlow=20.0, hi=10.0\n\\end{tabular}\n\n$\\}\\medskip $\n\n\\begin{tabular}{l}\n{\\footnotesize // 1. during the initial 10 ps, increase the strength of the\nforcing restraint to full strength: 0 }$\\rightarrow $ {\\footnotesize 20\nkcal/(mol %TCIMACRO{\\UNICODE{0xc5}{}}\n}$^{2}${\\footnotesize )} \\\\ \n{\\footnotesize // 2. next, apply a force to slowly close the distance from\n20 %TCIMACRO{\\UNICODE{0xc5}{}}\nto 10 %TCIMACRO{\\UNICODE{0xc5}{}}\n(}$\\lambda ${\\footnotesize \\ changes from 0 }$\\rightarrow ${\\footnotesize \\\n1)} \\\\ \n{\\footnotesize // 3. accumulate dU/d}$\\lambda ${\\footnotesize \\ for another\n10 ps. ( stays fixed at 1)} \\\\ \n{\\footnotesize // 4. force the distance back to its initial value of 20 \n%TCIMACRO{\\UNICODE{0xc5}{}}\n( changes from 1 }$\\rightarrow $ {\\footnotesize 0)}\n\\end{tabular}\n\npmf $\\{$\n\n~~task = grow\n\n~~time = 10 ps\n\n~~print = 1 ps\n\n$\\}$\n\npmf $\\{$\n\n~~task = up\n\n~~time = 100 ps\n\n$\\}$\n\npmf $\\{$\n\n~~task = stop\n\n~~time = 10 ps\n\n$\\}$\n\npmf $\\{$\n\n~~task = down\n\n~~time = 100 ps\n\n$\\}\\medskip $\n\n\\begin{tabular}{ll}\n{\\footnotesize // 1. } & {\\footnotesize force the distance to close from 20 \n%TCIMACRO{\\UNICODE{0xc5}{}}\nto 10 %TCIMACRO{\\UNICODE{0xc5}{}}\nin 5 steps. (}$\\lambda ${\\footnotesize \\ changes from 0 }$\\rightarrow $\n{\\footnotesize \\ 1: ~~0.2, 0.4, 0.6, 0.8, 1.0)} \\\\ \n{\\footnotesize // } & {\\footnotesize at each step equilibrate for 10 ps,\nthen collect dU/d}$\\lambda ${\\footnotesize \\ for another 10 ps.} \\\\ \n{\\footnotesize //} & {\\footnotesize ref = 18, 16, 14, 12, 10 \n%TCIMACRO{\\UNICODE{0xc5}{}}\n, duration = (10 + 10) x 5 = 100 ps.} \\\\ \n{\\footnotesize // 2.} & {\\footnotesize \\ reverse the step above (}$\\lambda $\n{\\footnotesize \\ changes from 1 }$\\rightarrow $ {\\footnotesize 0: ~~0.8,\n0.6, 0.4, 0.2, 0.0)}\n\\end{tabular}\n\nmcti $\\{$\n\n~~task = stepup\n\n~~equiltime = 10 ps\n\n~~accumtime = 10 ps\n\n~~numsteps = 5\n\n~~print = 1 ps\n\n$\\}$\n\nmcti $\\{$\n\n~~task = stepdown\n\n$\\}$\n\n\\subsection{Appendix}\n\n{\\bf Gradient for position restraint}\n\n$E=\\left( K_{f}/2\\right) \\left( \\left| \\overrightarrow{r_{i}}-\n\\overrightarrow{r_{ref}}\\right| \\right) ^{2}$\n\n$E=\\left( K_{f}/2\\right) \\left\\{ \\left( x_{i}-x_{ref}\\right) ^{2}+\\left(\ny_{i}-y_{ref}\\right) ^{2}+\\left( z_{i}-z_{ref}\\right) ^{2}\\right\\} $\n\n$\\nabla (E)=K_{f}\\left\\{ \\left( x_{i}-x_{ref}\\right) \\overrightarrow{i}\n+\\left( y_{i}-y_{ref}\\right) \\overrightarrow{j}+\\left( z_{i}-z_{ref}\\right) \n\\overrightarrow{k}\\right\\} $\n\n{\\bf Gradient for stretch restraint}\n\n$E=\\left( K_{f}/2\\right) \\left( d_{i}-d_{ref}\\right) ^{2}$\n\n$d_{i}=\\left\\{ \\left( x_{2}-x_{1}\\right) ^{2}+\\left( y_{2}-y_{1}\\right)\n^{2}+\\left( z_{2}-z_{1}\\right) ^{2}\\right\\} ^{1/2}$\n\n$\\nabla (E)=K_{f}\\left( d_{i}-d_{ref}\\right) \\cdot \\nabla (di)\\medskip $\n\n{\\em for atom 2 moving, and atom 1 fixed}\n\n$\\nabla (d_{i})=1/2\\left\\{ \\left( x_{2}-x_{1}\\right) ^{2}+\\left(\ny_{2}-y_{1}\\right) ^{2}+\\left( z_{2}-z_{1}\\right) ^{2}\\right\\}\n^{-1/2}\\left\\{ 2\\left( x_{2}-x_{1}\\right) +2\\left( y_{2}-y_{1}\\right)\n+2\\left( z_{2}-z_{1}\\right) \\right\\} $\n\n$\\nabla (d_{i})=\\left\\{ \\left( x_{2}-x_{1}\\right) \\overrightarrow{i}+\\left(\ny_{2}-y_{1}\\right) \\overrightarrow{j}+\\left( z_{2}-z_{1}\\right) \n\\overrightarrow{k}\\right\\} /d_{i}$\n\n$\\nabla (E)=K_{f}\\left\\{ \\left( d_{i}-d_{ref}\\right) /d_{i}\\right\\} \\left\\{\n\\left( x_{2}-x_{1}\\right) \\overrightarrow{i}+\\left( y_{2}-y_{1}\\right) \n\\overrightarrow{j}+\\left( z_{2}-z_{1}\\right) \\overrightarrow{k}\\right\\} $\n\n{\\bf Gradient for bend restraint}\n\n$E=\\left( K_{f}/2\\right) \\left( \\theta _{i}-\\theta _{ref}\\right) ^{2}$\n\nAtoms at positions A-B-C\n\ndistances: (A to B) = c; (A to C) = b; (B to C) = a;\n\n$\\theta _{i}=\\cos ^{-1}(u)=\\cos ^{-1}\\left\\{ \\left( a^{2}+c^{2}-b^{2}\\right)\n/\\left( 2ac\\right) \\right\\} $\n\n$\\nabla (E)=K_{f}\\left( \\theta _{i}-\\theta _{ref}\\right) \\cdot \\nabla\n(\\theta _{i})$\n\n$\\nabla (\\theta _{i})=\\frac{-1}{\\sqrt{1-u^{2}}}\\cdot \\nabla (u)\\medskip $\n\n{\\em for atom A moving, atoms B \\& C fixed (distances b and c\nchange)}\n\n$\\nabla (u)=\\left\\{ -b/\\left( ac\\right) \\right\\} \\cdot \\nabla (b)+\\left\\{\n-a/\\left( 2c^{2}\\right) +1/\\left( 2a\\right) +b^{2}/\\left( 2ac^{2}\\right)\n\\right\\} \\cdot \\nabla (c)$\n\n$\\nabla (b)=\\left\\{ \\left( x_{A}-x_{C}\\right) \\overrightarrow{i}+\\left(\ny_{A}-y_{C}\\right) \\overrightarrow{j}+\\left( z_{A}-z_{C}\\right) \n\\overrightarrow{k}\\right\\} /b$\n\n$\\nabla (c)=\\left\\{ \\left( x_{A}-x_{B}\\right) \\overrightarrow{i}+\\left(\ny_{A}-y_{B}\\right) \\overrightarrow{j}+\\left( z_{A}-z_{B}\\right) \n\\overrightarrow{k}\\right\\} /c\\medskip $\n\n{\\em for atom B moving, atoms A \\& C fixed (distances a and c\nchange)}\n\n$\\nabla (u)=\\left\\{ 1/(2c)+-c/(2a^{2})+b^{2}/(2a^{2}c)\\right\\} \\cdot \\nabla\n(a)+\\left\\{ -a/\\left( 2c^{2}\\right) +1/(2a)+b^{2}/\\left( 2ac^{2}\\right)\n\\right\\} \\cdot \\nabla (c)$\n\n$\\nabla (a)=\\left\\{ (x_{B}-x_{C})\\overrightarrow{i}+(y_{B}-y_{C})\n\\overrightarrow{j}+(z_{B}-z_{C})\\overrightarrow{k}\\right\\} /a$\n\n$\\nabla (c)=\\left\\{ (x_{B}-x_{A})\\overrightarrow{i}+(y_{B}-y_{A})\n\\overrightarrow{j}+(z_{B}-z_{A})\\overrightarrow{k}\\right\\} /c\\medskip $\n\n{\\em for atom C moving, atoms A \\& B fixed (distances a and b\nchange)}\n\n$\\nabla (u)=\\left\\{ -b/\\left( ac\\right) \\right\\} \\cdot \\nabla (b)+\\left\\{\n-c/\\left( 2a^{2}\\right) +1/(2c)+b^{2}/\\left( 2ac^{2}\\right) \\right\\} \\cdot \n\\nabla (a)$\n\n$\\nabla (b)=\\left\\{ (x_{C}-x_{A})\\overrightarrow{i}+(y_{C}-y_{A})\n\\overrightarrow{j}+(z_{C}-z_{A})\\overrightarrow{k}\\right\\} /b$\n\n$\\nabla (a)=\\left\\{ (x_{C}-x_{B})\\overrightarrow{i}+(y_{C}-y_{B})\n\\overrightarrow{j}+(z_{C}-z_{B})\\overrightarrow{k}\\right\\} /a $\n\n{\\bf Gradient for dihedral angle restraint}\n\n$E=(E_{0}/2)\\left\\{ 1-\\cos \\left( \\chi _{i}-\\chi _{ref}\\right) \\right\\} $\n\nAtoms at positions A-B-C-D\n\n$\\chi _{i}=\\cos ^{-1}(u)=$ $\\cos ^{-1}\\left( \\frac{\\overrightarrow{(CD}\n\\times \\overrightarrow{CB})\\bullet (\\overrightarrow{BC}\\times \n\\overrightarrow{BA})}{\\left| \\overrightarrow{CD}\\times \\overrightarrow{CB}\n\\right| \\left| \\overrightarrow{BC}\\times \\overrightarrow{BA}\\right| }\\right)\n\\qquad $AND\n\n$\\chi _{i}=\\sin ^{-1}(v)=$ $\\sin ^{-1}\\left( \\frac{\\overrightarrow{(CD}\n\\times \\overrightarrow{CB})\\times (\\overrightarrow{BC}\\times \\overrightarrow{\nBA})}{\\left| \\overrightarrow{CD}\\times \\overrightarrow{CB}\\right| \\left| \n\\overrightarrow{BC}\\times \\overrightarrow{BA}\\right| }\\bullet \\frac{\n\\overrightarrow{CB}}{\\left| \\overrightarrow{CB}\\right| }\\right) $\n\n$\\nabla (E)=(E_{0}/2)\\left\\{ \\sin \\left( \\chi _{i}-\\chi _{ref}\\right)\n\\right\\} \\cdot \\nabla (\\chi _{i})$\n\n$\\nabla (\\chi _{i})=\\frac{-1}{\\sqrt{1-u^{2}}}\\cdot \\nabla (u)\\smallskip\n\\medskip $\n\n\\begin{tabular}{ll}\n$\\overrightarrow{CD}\\times \\overrightarrow{CB}$ $=$ & $\n((y_{D}-y_{C})(z_{B}-z_{C})-(z_{D}-z_{C})(y_{B}-y_{C}))\\overrightarrow{i}+$\n\\\\ \n& $((z_{D}-z_{C})(x_{B}-x_{C})-(x_{D}-x_{C})(z_{B}-z_{C}))\\overrightarrow{j}+\n$ \\\\ \n& $((x_{D}-x_{C})(y_{B}-y_{C})-(y_{D}-y_{C})(x_{B}-x_{C}))\\overrightarrow{k}$\n\\\\ \n\\multicolumn{1}{c}{$=$} & $p_{1}\\overrightarrow{i}+p_{2}\\overrightarrow{j}\n+p_{3}\\overrightarrow{k}$\n\\end{tabular}\n\\medskip \\medskip \n\n\\begin{tabular}{ll}\n$\\overrightarrow{BC}\\times \\overrightarrow{BA}=$ & $\n((y_{C}-y_{B})(z_{A}-z_{B})-(z_{C}-z_{B})(y_{A}-y_{B}))\\overrightarrow{i}+$\n\\\\ \n& $((z_{C}-z_{B})(x_{A}-x_{B})-(x_{C}-x_{B})(z_{A}-z_{B}))\\overrightarrow{j}+\n$ \\\\ \n& $((x_{C}-x_{B})(y_{A}-y_{B})-(y_{C}-y_{B})(x_{A}-x_{B}))\\overrightarrow{k}$\n\\\\ \n\\multicolumn{1}{c}{$=$} & $p_{4}\\overrightarrow{i}+p_{5}\\overrightarrow{j}\n+p_{6}\\overrightarrow{k}$\n\\end{tabular}\n\\medskip \\medskip \n\n$u=\\frac{p_{1}p_{4}+p_{2}p_{5}+p_{3}p_{6}}{\\sqrt{\np_{1}^{2}+p_{2}^{2}+p_{3}^{2}}\\sqrt{p_{4}^{2}+p_{5}^{2}+p_{6}^{2}}}\\medskip\n\\medskip $\n\n\\begin{tabular}{ll}\n$\\nabla (u)=$ & $\\frac{p_{1}\\cdot \\nabla (p_{4})+p_{2}\\cdot \\nabla\n(p_{5})+p_{3}\\cdot \\nabla (p_{6})}{\\sqrt{p_{1}^{2}+p_{2}^{2}+p_{3}^{2}}\\sqrt{\np_{4}^{2}+p_{5}^{2}+p_{6}^{2}}}$ $+$ \\\\ \n& $\\frac{p_{1}p_{4}+p_{2}p_{5}+p_{3}p_{6}}{\\sqrt{\np_{1}^{2}+p_{2}^{2}+p_{3}^{2}}}$ $\\left( -1/2\\left(\np_{4}^{2}+p_{5}^{2}+p_{6}^{2}\\right) ^{-3/2}\\left( 2p_{4}\\cdot \\nabla\n(p_{4})+2p_{5}\\cdot \\nabla (p_{5})+2p_{6}\\cdot \\nabla (p_{6})\\right) \\right) \n$ $+$ \\\\ \n& $\\frac{p_{1}p_{4}+p_{2}p_{5}+p_{3}p_{6}}{\\sqrt{\np_{4}^{2}+p_{5}^{2}+p_{6}^{2}}}$ $\\left( -1/2\\left(\np_{1}^{2}+p_{2}^{2}+p_{3}^{2}\\right) ^{-3/2}\\left( 2p_{1}\\cdot \\nabla\n(p_{1})+2p_{2}\\cdot \\nabla (p_{2})+2p_{3}\\cdot \\nabla (p_{3})\\right) \\right) \n$\n\\end{tabular}\n\n{\\em for atom A moving, atoms B, C, \\& D fixed}\n\n\\begin{tabular}{lrrr}\n$\\nabla (p_{1})=$ & $(0.0)\\overrightarrow{i}+$ & $(0.0)\\overrightarrow{j}+$\n& $(0.0)\\overrightarrow{k}$ \\\\ \n$\\nabla (p_{2})=$ & $(0.0)\\overrightarrow{i}+$ & $(0.0)\\overrightarrow{j}+$\n& $(0.0)\\overrightarrow{k}$ \\\\ \n$\\nabla (p_{3})=$ & $(0.0)\\overrightarrow{i}+$ & $(0.0)\\overrightarrow{j}+$\n& $(0.0)\\overrightarrow{k}$ \\\\ \n$\\nabla (p_{4})=$ & $(0.0)\\overrightarrow{i}+$ & $(z_{B}-z_{C})\n\\overrightarrow{j}+$ & $(y_{C}-y_{B})\\overrightarrow{k}$ \\\\ \n$\\nabla (p_{5})=$ & $(z_{C}-z_{B})\\overrightarrow{i}+$ & $(0.0)\n\\overrightarrow{j}+$ & $(x_{B}-x_{C})\\overrightarrow{k}$ \\\\ \n$\\nabla (p_{6})=$ & $(y_{B}-y_{C})\\overrightarrow{i}+$ & $(x_{C}-x_{B})\n\\overrightarrow{j}+$ & $(0.0)\\nolinebreak \\bigskip \\overrightarrow{k}$\n\\end{tabular}\n\\bigskip \n\n{\\em for atom B moving, atoms A, C, \\& D fixed}\n\n\\begin{tabular}{lrrr}\n$\\nabla (p_{1})=$ & $(0.0)\\overrightarrow{i}+$ & $(z_{C}-z_{D})\n\\overrightarrow{j}+$ & $(y_{D}-y_{C})\\overrightarrow{k}$ \\\\ \n$\\nabla (p_{2})=$ & $(z_{D}-z_{C})\\overrightarrow{i}+$ & $(0.0)\n\\overrightarrow{j}+$ & $(x_{C}-x_{D})\\overrightarrow{k}$ \\\\ \n$\\nabla (p_{3})=$ & $(y_{C}-y_{D})\\overrightarrow{i}+$ & $(x_{D}-x_{C})\n\\overrightarrow{j}+$ & $(0.0)\\overrightarrow{k}$ \\\\ \n$\\nabla (p_{4})=$ & $(0.0)\\overrightarrow{i}+$ & $(z_{C}-z_{A})\n\\overrightarrow{j}+$ & $(y_{A}-y_{C})\\overrightarrow{k}$ \\\\ \n$\\nabla (p_{5})=$ & $(z_{A}-z_{C})\\overrightarrow{i}+$ & $(0.0)\n\\overrightarrow{j}+$ & $(x_{C}-x_{A})\\overrightarrow{k}$ \\\\ \n$\\nabla (p_{6})=$ & $(y_{C}-y_{A})\\overrightarrow{i}+$ & $(x_{A}-x_{C})\n\\overrightarrow{j}+$ & $(0.0)\\overrightarrow{k}$\n\\end{tabular}\n\n{\\bf Gradient for forcing position restraint}\n\n$E=(K_{f}/2)\\left( \\left| \\overrightarrow{r_{i}}-\\overrightarrow{r_{ref}}\n\\right| \\right) ^{2}$\n\n$r_{ref}=\\lambda \\overrightarrow{r_{1}}+\\left( 1-\\lambda \\right) \n\\overrightarrow{r_{0}}$\n\n\\begin{tabular}{lll}\n$dE/d\\lambda =$ & $K_{f}\\times $ & $\\left( \\left( x_{i}-x_{ref}\\right)\n^{2}+\\left( y_{i}-y_{ref}\\right) ^{2}+\\left( z_{i}-z_{ref}\\right)\n^{2}\\right) ^{1/2}\\times $ \\\\ \n& & $1/2\\left( \\left( x_{i}-x_{ref}\\right) ^{2}+\\left( y_{i}-y_{ref}\\right)\n^{2}+\\left( z_{i}-z_{ref}\\right) ^{2}\\right) ^{-1/2}\\times $ \\\\ \n& & $\\left( 2\\left( x_{i}-x_{ref}\\right) \\left( x_{0}-x_{1}\\right) +2\\left(\ny_{i}-y_{ref}\\right) \\left( y_{0}-y_{1}\\right) +2\\left( z_{i}-z_{ref}\\right)\n\\left( z_{0}-z_{1}\\right) \\right) $\n\\end{tabular}\n\n$dE/d\\lambda =K_{f}\\times \\left( \\left( x_{i}-x_{ref}\\right) \\left(\nx_{0}-x_{1}\\right) +\\left( y_{i}-y_{ref}\\right) \\left( y_{0}-y_{1}\\right)\n+\\left( z_{i}-z_{ref}\\right) \\left( z_{0}-z_{1}\\right) \\right) \\bigskip $\n\n{\\bf Gradient for forcing stretch restraint}\n\n$E=\\left( K_{f}/2\\right) \\left( d_{i}-d_{ref}\\right) ^{2}$\n\n$d_{ref}=\\lambda d_{1}+\\left( 1-\\lambda \\right) d_{0}$\n\n$dE/d\\lambda =K_{f}~\\times ~\\left( d_{i}-d_{ref}\\right) ~\\times ~\\left(\nd_{0}-d_{1}\\right) \\bigskip $\n\n{\\bf Gradient for forcing bend restraint}\n\n$E=\\left( K_{f}/2\\right) \\left( \\theta _{i}-\\theta _{ref}\\right) ^{2}$\n\n$\\theta _{ref}=\\lambda \\theta _{1}+\\left( 1-\\lambda \\right) \\theta _{0}$\n\n$dE/d\\lambda =K_{f}~\\times ~\\left( \\theta _{i}-\\theta _{ref}\\right) ~\\times \n~\\left( \\theta _{0}-\\theta _{1}\\right) \\bigskip $\n\n{\\bf Gradient for forcing dihedral restraint}\n\n$E=\\left( E_{0}/2\\right) \\left( 1-\\cos \\left( \\chi _{i}-\\chi _{ref}\\right)\n\\right) $\n\n$\\chi _{ref}=\\lambda \\chi _{1}+\\left( 1-\\lambda \\right) \\chi _{0}$\n\n$dE/d\\lambda =\\left( E_{0}/2\\right) ~\\times ~\\sin \\left( \\chi _{i}-\\chi\n_{ref}\\right) ~\\times ~\\left( \\chi _{0}-\\chi _{1}\\right) $\n\n", "meta": {"hexsha": "09dbab486a5cc389cddcc9e7720c324fd4c6c392", "size": 33120, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "ug/ug_fenergy.tex", "max_stars_repo_name": "gwli/namd", "max_stars_repo_head_hexsha": "a2ce2a1bfe68350cde94a72d32192ad8f1ffa175", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2022-02-18T09:57:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-18T09:58:14.000Z", "max_issues_repo_path": "ug/ug_fenergy.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_fenergy.tex", "max_forks_repo_name": "gwli/namd", "max_forks_repo_head_hexsha": "a2ce2a1bfe68350cde94a72d32192ad8f1ffa175", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-09-20T23:21:39.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-20T23:21:39.000Z", "avg_line_length": 34.8998946259, "max_line_length": 128, "alphanum_fraction": 0.6421799517, "num_tokens": 12373, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.30735801686526387, "lm_q1q2_score": 0.16566081383421946}} {"text": "\\chapter{\\acro{rtn} Support}\n\n\\label{sec:openfstrtn}\n\n%\\section{Two Distinct Flavors of \\acro{rtn} Support}\n\n% See saprtn.tex.notrack\n%Kleene is currently being expanded to provide support for two distinct\n%flavors of Recursive Transition Networks or \\acro{rtn}s. This is work in\n%progress.\n\n%This section describes the Kleene support for \\acro{rtn}s\n%compatible with the off-the-shelf functions from the OpenFst library.\n%\\acro{sap} linguists creating pattern networks for the \\acro{sap}\n%\\acro{rtn} pattern-matching runtime code should ignore this section and\n%proceed immediately to section~\\ref{sec:saprtn} starting on\n%page~\\pageref{sec:saprtn}.\n\n\\section{OpenFst Recursive Transition Networks (\\acro{rtn}s)}\n\n\\subsection{Status}\n\n[KRB 2013-04] WORK IN PROGRESS: There is currently no runtime-code support for\n\\init{rtn}s. This chapter has not be reviewed recently.\n\nKleene supports the building of Recursive Transition Networks\n(\\acro{rtn}s) that are compatible with the OpenFst \\texttt{Replace()} and\n\\texttt{ReplaceFst()} operations. An \\acro{rtn} contains arc labels that\nare to be interpreted as ``references'' to subnetworks; and compatible\n\\acro{rtn}-savvy runtime code, when applying a network to data, will\nrecognize such a reference and ``push'' to the referenced subnetwork to\ncontinue the matching, and then ``pop'' back to the calling network when\nthe subnetwork has successfully matched. The references to subnetworks\ncan also be thought of as non-terminal labels.\n\n\\acro{rtn}s, containing references to subnetworks, are often smaller than\nfull-sized networks that must contain a full copy of each subnetwork\nwherever it is needed. However, \\acro{rtn}s can denote context-free\nlanguages, and so can go beyond regular power; a special subclass of\n\\acro{rtn}s remain regular. The recognition/parsing of context-free\nlanguages requires memory, in particular a push-down stack, and so any\nruntime code to apply \\acro{rtn}s must include such a stack.\n\nAt the time of writing (13 October 2010) there are hints that the\n\\acro{rtn} conventions currently required in OpenFst might change, and\nthere is new library support for mathematically equivalent Pushdown\nAutomata (\\acro{pda}s) that we have not yet tested. Kleene support for\nOpenFst \\acro{rtn}s and \\acro{pda}s will necessarily evolve along with\nthe library.\n\n\\subsection{Syntax for Creating an OpenFst \\acro{rtn}}\n\nFor the programmer, there needs to be a Kleene syntax to denote a\nreference to a subnetwork, and it needs to be distinct from the syntax\nthat causes a copy of a network to be inserted. For example, in this\nexample\n\n\\begin{Verbatim}[fontsize=\\small]\n$vowel = [aeiou] ;\n$net = k $vowel t $vowel b $vowel ;\n\\end{Verbatim}\n\n\\noindent\nthe \\verb!$vowel! network will be copied three times into \\verb!$net!.\nIn real-life applications, a subnetwork might encode something much\nlarger, such as nouns or even noun phrases in a natural language, and\nmultiple copies could easily cause the final network to become very\nlarge, or even too large to compute.\n\nKleene currently supports a wired-in function \\verb!$^sub($s)! that\nprogrammers can use to denote a reference to a subnetwork \\verb!$s!.\\footnote{I'm\nnot tied to \\verb!$^sub($s)! and would be comfortable with alternatives such\nas \\verb!$^ref($s)! or \\verb!$^push($s)!, or even some special syntax like\n\\verb!>$s>$s!.} \n\nTo continue with our trivial example, \n\n\\begin{Verbatim}[fontsize=\\small]\n$vowel = [aeiou] ;\n$rtn = k $^sub($vowel) t $^sub($vowel) b $^sub($vowel) ;\n\\end{Verbatim}\n\n\\noindent\nwould result in an \\verb!$rtn! network that contains three compact\none-label references to \\verb!$vowel! rather than three full copies of\nit. In real-life applications, the savings in memory can be very\nsignificant.\n\n\\subsection{What does a Reference Look Like in an OpenFst \\acro{rtn}?}\n\nOpenFst networks consist of states and arcs, and each arc has two labels,\nan input label, and an output label.\\footnote{The terminology of\n\\emph{input} and \\emph{output} labels is that of the OpenFst tradition.\nIn the Xerox tradition, they are called \\emph{upper} and \\emph{lower}, or\nsometimes \\emph{lexical} and \\emph{surface}.} In the actual network, the\nlabels are really integers, and all Unicode characters, such as \\emph{a},\n\\emph{b}, \\emph{c}, etc.\\@ are represented using their standard Unicode\ncode point values. Multichar symbols are stored using code point values\nselected at random from a Unicode Private Use Area.\n\nTo maximize compatibility with the off-the-shelf OpenFst\n\\texttt{Replace()} and \\texttt{ReplaceFst()} operations, the integer\nrepresenting a reference to a subnetwork must currently appear on the\n\\emph{output} side of an arc. In Kleene, multichar symbol names\nrepresenting a call to a subnetwork \\verb!$s! are spelled \\verb!__$s!,\nwith two initial underscores, and the syntax \\verb!$^sub($s)! currently\nyields the following network.\n\n% see images/README for converting .ps files to .pdf and cropping them\n\\begin{center}\n\\includegraphics{images/reference.pdf}\n\\end{center}\n\n\\noindent\nCurrently in OpenFst, the symbol \\verb!__$s! could in fact appear also on\nthe input side. Of course, in the real network, the labels are really\njust integers, 0 for epsilon, and some arbitrary value from the Private\nUse Area for the multichar symbol.\n\nKleene programmers should use the wired-in \\verb!$^sub()! function to\ndenote references to subnetworks and should not try to specify special\nsymbols like \\verb!__$s! directly. For example, the following statement\nis illegal and will cause an exception to be thrown.\n\n\\begin{Verbatim}[fontsize=\\small]\n$rtn = \"\":'__$foo' ; // raises an exception\n\\end{Verbatim}\n\n\\noindent\nThe use of \\verb!$^sub()! at the programming level will also make it easy\nfor Kleene to adapt to any changes to \\acro{rtn} representations that\nmight be made in the underlying OpenFst library.\n\n\\subsection{Embedding Subnetworks in an OpenFst \\acro{rtn}}\n\nThe \\verb!$^embedRtnSubnets($rtn)! function takes an OpenFst \\acro{rtn}\nargument, i.e.\\@ a network that contains OpenFst-format references to\nsubnetworks, and returns a network that consists of the original network\nunioned with a prefixed copy of each referred-to subnetwork. For each\nreferred-to network \\verb!$s!, the prefix consists of the special symbol\n\\verb!__SUBNETWORKS! followed by the special symbol \\verb!__$s!. Thus\nfrom the following code\n\n\\begin{Verbatim}[fontsize=\\small]\n$p = p ;\n$q = q ;\n$rtn = a $^sub($p) b $^sub($q) ;\n\\end{Verbatim}\n\n\\noindent\nthe result \\verb!$rtn! is this network containing two references to subnetworks\n\n\\begin{center}\n\\includegraphics[width=\\textwidth]{images/twoReferences.pdf}\n\\end{center}\n\n\\noindent\nbut the three referred-to networks remain separate. After the following\ncall to \\verb!$^embedRtnSubnets($rtn)!, \n\n\\begin{Verbatim}[fontsize=\\small]\n$embedded = $^embedRtnSubnets($rtn) ;\n\\end{Verbatim}\n\n\n\\noindent\nthe resulting \\verb!$embedded! network looks like this\n\n\\begin{center}\n\\includegraphics[width=\\textwidth]{images/embedded.pdf}\n\\end{center}\n\n\\noindent\nThe embedded network can be saved to file as a single network and could be\napplied by \\acro{rtn}-savvy runtime code (not yet written) that knows the prefix convention.\n\nThe unioning of the base network with the subnetworks also guarantees that\nthe meaning of OTHER, if present, is standardized throughout all the\nnetworks.\n\n\\subsection{Expanding an OpenFst \\acro{rtn} into a Full Normal Network}\n\nIn some cases, it may also be useful to take an OpenFst \\acro{rtn} and replace\neach reference to a subnetwork with an actual copy of that subnetwork,\nexpanding the \\acro{rtn} into a full normal network. This is mathematically and\ncomputationally possible only if the \\acro{rtn} is regular. Using the same\n\\verb!$rtn! example, a call to \\verb!$^expandRtn()!\n\n\\begin{Verbatim}[fontsize=\\small]\n$expanded = $^expandRtn($rtn) ;\n\\end{Verbatim}\n\n\\noindent\nproduces the following \\verb!$expanded! network\n\n\\begin{center}\n\\includegraphics[width=\\textwidth]{images/expanded.pdf}\n\\end{center}\n\n\\noindent\nIn real-life \\acro{rtn}s, with multiple references to the same\nsubnetwork, the expanded network will be significantly bigger than the\noriginal. \n\nIf the \\acro{rtn} contains cyclic references to subnetworks, it is\ncontext-free in power (i.e.\\@ no longer regular in power), and its\nexpansion would result in an infinite network. The\n\\verb!$^expandRtn($rtn)! function checks for cyclic references and throws\nan exception if the \\verb!$rtn! is not regular.\\footnote{In the OpenFst\nlibrary, the \\verb!ReplaceFst()! operation provides a convenient method\nthat checks for cyclic references, and \\verb!$^expandRtn()! invokes this\nmethod.}\n\n\n\n", "meta": {"hexsha": "16908254cabca90a7270053df7def7eb0dff7b42", "size": 8677, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/user/kleene/chapt12.tex", "max_stars_repo_name": "cscott/kleene-lang", "max_stars_repo_head_hexsha": "938beb074bcf3706852630881da15e5badb730d5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2015-01-13T05:56:54.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-08T04:23:09.000Z", "max_issues_repo_path": "doc/user/kleene/chapt12.tex", "max_issues_repo_name": "cscott/kleene-lang", "max_issues_repo_head_hexsha": "938beb074bcf3706852630881da15e5badb730d5", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/user/kleene/chapt12.tex", "max_forks_repo_name": "cscott/kleene-lang", "max_forks_repo_head_hexsha": "938beb074bcf3706852630881da15e5badb730d5", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2017-06-20T03:29:18.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-24T12:16:26.000Z", "avg_line_length": 40.1712962963, "max_line_length": 92, "alphanum_fraction": 0.7688141063, "num_tokens": 2358, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3276683008207139, "lm_q1q2_score": 0.1651140786703367}} {"text": "\\section{UTxO}\n\\label{sec:utxo}\n\nSome of the functions related to scripts, datums and collateral need\nto be adjusted for the new features. Most of these adjustments are\nself-explanatory. Note that the new $\\fun{collOuts}$ function\ngenerates a single output with an index $| \\txouts{txb} |$. This is to\navoid potential confusion for transactions spending that output.\n\n\\begin{figure*}[htb]\n \\emph{Functions}\n %\n \\begin{align*}\n & \\fun{isTwoPhaseScriptAddress} : \\Tx \\to \\hldiff{\\UTxO} \\to \\Addr \\to \\Bool \\\\\n & \\fun{isTwoPhaseScriptAddress}~tx~\\hldiff{utxo}~a = \\\\\n &\\quad\\begin{cases}\n \\True & a \\in \\AddrScr \\land \\fun{validatorHash}~a \\mapsto s \\in \\fun{txscripts}~tx~\\hldiff{utxo} \\land s \\in \\ScriptPhTwo \\\\\n \\False & \\text{otherwise}\n \\end{cases}\n \\nextdef\n & \\fun{collBalance} : \\TxBody \\to \\UTxO \\to \\Value \\\\\n & \\fun{collBalance}~txb~utxo = \\fun{ubalance}~(\\var{utxo}|_{\\fun{collInputs}~{txb}}) -\n \\begin{cases}\n 0 & \\fun{collRet}~txb = \\Nothing \\\\\n \\fun{collRet}~txb & \\text{otherwise}\n \\end{cases}\n \\nextdef\n & \\fun{collOuts} : \\TxBody \\to \\UTxO \\\\\n & \\fun{collOuts}~txb =\n \\begin{cases}\n \\emptyset & \\fun{collRet}~txb = \\Nothing \\\\\n \\{ (\\txid{txb}, | \\txouts{txb} |) \\mapsto \\fun{collRet}~txb \\} & \\text{otherwise}\n \\end{cases}\n \\nextdef\n & \\fun{feesOK} : \\PParams \\to \\Tx \\to \\UTxO \\to \\Bool \\\\\n & \\fun{feesOK}~\\var{pp}~tx~utxo = \\\\\n &~~ \\minfee{pp}{tx} \\leq \\txfee{tx} \\wedge (\\fun{txrdmrs}~tx \\neq \\Nothing \\Rightarrow \\\\\n &~~~~~~((\\forall (a, \\wcard, \\wcard) \\in \\fun{range}~(\\fun{collInputs}~tx \\restrictdom \\var{utxo}), a \\in \\AddrVKey) \\\\\n &~~~~~~\\wedge \\fun{adaOnly}~\\var{balance} \\\\\n &~~~~~~\\wedge \\var{balance} \\geq \\hldiff{\\lceil \\txfee{txb} * \\fun{collateralPercent}~pp / 100 \\rceil} \\\\\n &~~~~~~\\wedge \\hldiff{(\\fun{txcoll}~tx \\neq \\Nothing) \\Rightarrow \\var{balance} = \\fun{txcoll}~tx} \\\\\n &~~~~~~\\wedge \\fun{collInputs}~{tx} \\neq \\emptyset) \\\\\n &~~ \\where \\\\\n & ~~~~~~~ \\var{balance}=\\hldiff{\\fun{collBalance}~tx~utxo}\n \\end{align*}\n \\caption{Functions related to fees and collateral}\n \\label{fig:functions:utxo}\n\\end{figure*}\n\n\\begin{figure*}\n \\begin{align*}\n & \\fun{getDatum} : \\Tx \\to \\UTxO \\to \\ScriptPurpose \\to \\seqof{\\Datum} \\\\\n & \\fun{getDatum}~{tx}~{utxo}~{sp} =\n \\begin{cases}\n [\\var{d}] & \\var{sp} \\in \\TxIn, (\\_, \\_, h, \\_) \\in \\var{utxo}~\\var{sp},~ \\var{d}\\in\\fun{txdats}~(\\fun{txwits}~tx)~\\var{h} \\\\\n [\\var{d}] & \\hldiff{\\var{sp} \\in \\TxIn, (\\_, \\_, d, \\_) \\in \\var{utxo}~\\var{sp},~ \\var{d} \\in \\Datum} \\\\\n \\epsilon & \\text{otherwise}\n \\end{cases}\n \\nextdef\n & \\fun{txscripts} : \\Tx \\to \\hldiff{\\UTxO} \\to \\powerset{\\Script} \\\\\n & \\fun{txscripts}~tx~utxo = \\fun{txwitscripts}~tx \\cup \\hldiff{\\{ \\fun{hash}~s \\mapsto s \\mid (\\_, \\_, \\_, s) \\in \\var{utxo}~(\\fun{spendInputs}~tx \\cup \\fun{refInputs}~tx)\\}}\n \\nextdef\n & \\fun{languages} : \\Tx \\to \\UTxO \\to \\powerset{\\Language} \\\\\n & \\fun{languages}~tx~utxo =\n \\{\\fun{language}~s \\mid s \\in \\range (\\fun{txscripts}~tx~utxo) \\cap \\ScriptPhTwo\\}\n \\nextdef\n & \\fun{allowedLanguages} : \\Tx \\to \\UTxO \\to \\powerset{\\Language} \\\\\n & \\fun{allowedLanguages}~tx~utxo = \\\\\n & \\begin{cases}\n \\emptyset & \\text{if}~\\exists (a, \\_, \\_, \\_) \\in os, a \\in \\AddrBS \\\\\n \\{ \\PlutusVII \\} & \\text{if}~\\exists (\\_, \\_, d, s) \\in os, d \\in \\Datum \\lor s \\neq \\Nothing \\lor \\fun{refInputs}~tx \\neq \\emptyset \\\\\n \\{ \\PlutusVI, \\PlutusVII \\} & \\text{otherwise}\n \\end{cases} \\\\\n & \\where \\var{os} = \\range \\txouts{tx} \\cup \\var{utxo}~(\\fun{spendInputs}~tx \\cup \\fun{refInputs}~tx)\n \\end{align*}\n \\caption{Functions related to scripts}\n \\label{fig:functions:data}\n\\end{figure*}\n\n\\begin{figure}[htb]\n \\begin{equation}\n \\inference[Scripts-Yes]\n {\n \\var{txb}\\leteq\\txbody{tx} &\n \\var{sLst} := \\fun{collectTwoPhaseScriptInputs}~\\var{pp}~\\var{tx}~\\var{utxo}\n \\\\\n ~\n \\\\\n \\fun{isValid}~\\var{tx} = \\fun{evalScripts}~\\var{tx}~\\var{sLst} = \\True\n \\\\~\\\\\n {\n \\begin{array}{r}\n \\var{slot} \\\\\n \\var{pp} \\\\\n \\var{genDelegs} \\\\\n \\end{array}\n }\n \\vdash \\var{pup} \\trans{\\hyperref[fig:rules:update]{ppup}}{\\fun{txup}~\\var{tx}} \\var{pup'}\n \\\\~\\\\\n \\var{refunded} \\leteq \\keyRefunds{pp}{txb}\n \\\\\n \\var{depositChange} \\leteq\n (\\fun{totalDeposits}~{pp}~\\var{poolParams}~\\txcerts{txb})~-~\\var{refunded}\n }\n {\n \\begin{array}{l}\n \\var{slot}\\\\\n \\var{pp}\\\\\n \\var{poolParams}\\\\\n \\var{genDelegs}\\\\\n \\end{array}\n \\vdash\n \\left(\n \\begin{array}{r}\n \\var{utxo} \\\\\n \\var{deposits} \\\\\n \\var{fees} \\\\\n \\var{pup} \\\\\n \\end{array}\n \\right)\n \\trans{utxos}{tx}\n \\left(\n \\begin{array}{r}\n \\varUpdate{\\var{(\\fun{spendInputs}~txb \\subtractdom \\var{utxo}) \\cup \\outs{txb}}} \\\\\n \\varUpdate{\\var{deposits} + \\var{depositChange}} \\\\\n \\varUpdate{\\var{fees} + \\txfee{txb}} \\\\\n \\varUpdate{\\var{pup'}} \\\\\n \\end{array}\n \\right) \\\\\n }\n \\end{equation}\n \\begin{equation}\n \\inference[Scripts-No]\n {\n \\var{txb}\\leteq\\txbody{tx} &\n \\var{sLst} := \\fun{collectTwoPhaseScriptInputs}~\\var{pp}~\\var{tx}~\\var{utxo} \\\\\n \\hldiff{\\var{collateralFees} := \\fun{valueToCoin}~(\\fun{collBalance}~txb~utxo)}\n \\\\\n ~\n \\\\\n \\fun{isValid}~\\var{tx} = \\fun{evalScripts}~\\var{tx}~\\var{sLst} = \\False\n }\n {\n \\begin{array}{l}\n \\var{slot}\\\\\n \\var{pp}\\\\\n \\var{poolParams}\\\\\n \\var{genDelegs}\\\\\n \\end{array}\n \\vdash\n \\left(\n \\begin{array}{r}\n \\var{utxo} \\\\\n \\var{deposits} \\\\\n \\var{fees} \\\\\n \\var{pup} \\\\\n \\end{array}\n \\right)\n \\trans{utxos}{tx}\n \\left(\n \\begin{array}{r}\n \\varUpdate{\\var{(\\fun{collInputs}~{txb} \\subtractdom \\var{utxo})} \\cup \\hldiff{\\fun{collOuts}~txb}} \\\\\n \\var{deposits} \\\\\n \\varUpdate{\\var{fees} + \\hldiff{\\var{collateralFees}}} \\\\\n \\var{pup} \\\\\n \\end{array}\n \\right)\n }\n \\end{equation}\n \\caption{State update rules}\n \\label{fig:rules:utxo-state-upd}\n\\end{figure}\n\n\\begin{figure}[htb]\n \\begin{equation}\n \\inference[UTxO-inductive]\n {\n \\var{txb}\\leteq\\txbody{tx} &\n \\fun{ininterval}~\\var{slot}~(\\fun{txvldt}~{txb}) &\n \\var{(\\wcard, i_f)}\\leteq\\fun{txvldt}~{tx} \\\\~\\\\\n \\Nothing \\notin \\{\\fun{txrdmrs}~\\var{tx}, i_f\\} \\Rightarrow \\fun{epochInfoSlotToUTCTime}~\\mathsf{EI}~\\mathsf{SysSt}~i_f \\neq \\Nothing \\\\\n \\fun{spendInputs}~txb \\neq \\emptyset\n & \\fun{feesOK}~pp~tx~utxo\n \\\\\n \\fun{spendInputs}~txb \\cup \\fun{collInputs}~txb \\cup \\hldiff{\\fun{refInputs}~{tx}} \\subseteq \\dom \\var{utxo} \\\\\n \\consumed{pp}{utxo}{txb} = \\produced{pp}{poolParams}~{txb}\n \\\\~\\\\\n \\mathsf{adaID}\\notin \\supp {\\fun{mint}~tx} \\\\~\\\\\n \\forall txout \\in \\txouts{txb}, \\\\\n \\fun{getValue}~txout \\geq \\fun{inject}~(\\hldiff{\\lceil\\fun{serSize}~txout * \\fun{coinsPerUTxOWord}~pp/8\\rceil}) \\\\~\n \\\\\n \\forall txout \\in \\txouts{txb},\\\\\n \\fun{serSize}~(\\fun{getValue}~txout) \\leq \\fun{maxValSize}~pp \\\\~\n \\\\\n \\forall (\\wcard\\mapsto (a,~\\wcard)) \\in \\txouts{txb}, a \\in \\AddrBS \\Rightarrow \\fun{bootstrapAttrsSize}~a \\leq 64 \\\\\n \\forall (\\wcard\\mapsto (a,~\\wcard)) \\in \\txouts{txb}, \\fun{netId}~a = \\NetworkId\n \\\\\n \\forall (a\\mapsto\\wcard) \\in \\txwdrls{txb}, \\fun{netId}~a = \\NetworkId \\\\\n (\\fun{txnetworkid}~\\var{txb} = \\NetworkId) \\vee (\\fun{txnetworkid}~\\var{txb} = \\Nothing)\n \\\\~\\\\\n \\fun{txsize}~{tx}\\leq\\fun{maxTxSize}~\\var{pp} \\\\~\\\\\n \\fun{totExunits}~{tx} \\leq \\fun{maxTxExUnits}~{pp} & \\| \\fun{collInputs}~{tx} \\| \\leq \\fun{maxCollateralInputs}~{pp}\n \\\\\n ~\n \\\\\n {\n \\begin{array}{c}\n \\var{slot}\\\\\n \\var{pp}\\\\\n \\var{poolParams}\\\\\n \\var{genDelegs}\\\\\n \\end{array}\n }\n \\vdash\n {\n \\left(\n \\begin{array}{r}\n \\var{utxo} \\\\\n \\var{deposits} \\\\\n \\var{fees} \\\\\n \\var{pup}\\\\\n \\end{array}\n \\right)\n }\n \\trans{utxos}{\\var{tx}}\n {\n \\left(\n \\begin{array}{r}\n \\var{utxo'} \\\\\n \\var{deposits'} \\\\\n \\var{fees'} \\\\\n \\var{pup'}\\\\\n \\end{array}\n \\right)\n }\n }\n {\n \\begin{array}{l}\n \\var{slot}\\\\\n \\var{pp}\\\\\n \\var{poolParams}\\\\\n \\var{genDelegs}\\\\\n \\end{array}\n \\vdash\n \\left(\n \\begin{array}{r}\n \\var{utxo} \\\\\n \\var{deposits} \\\\\n \\var{fees} \\\\\n \\var{pup}\\\\\n \\end{array}\n \\right)\n \\trans{utxo}{tx}\n \\left(\n \\begin{array}{r}\n \\varUpdate{\\var{utxo'}} \\\\\n \\varUpdate{\\var{deposits'}} \\\\\n \\varUpdate{\\var{fees'}} \\\\\n \\varUpdate{\\var{pup'}}\\\\\n \\end{array}\n \\right)\n }\n \\end{equation}\n \\caption{UTxO inference rules}\n \\label{fig:rules:utxo-babbage}\n\\end{figure}\n\nTo the UTXOW rule, in addition to the changes required by the new\nfeatures, we add a check that all scripts and datums involved in the\ntransaction are well-formed. Also, we forbid transactions that use the\nnew features and try to use $\\PlutusVI$ scripts.\n\n\\begin{figure}\n \\begin{equation}\n \\label{eq:utxo-witness-inductive-babbage}\n \\inference[UTxO-witG]\n {\n \\var{txb}\\leteq\\txbody{tx} &\n \\var{txw}\\leteq\\fun{txwits}~{tx} \\\\\n (utxo, \\wcard, \\wcard, \\wcard) \\leteq \\var{utxoSt} \\\\\n \\var{witsKeyHashes} \\leteq \\{\\fun{hashKey}~\\var{vk} \\vert \\var{vk} \\in\n \\dom (\\txwitsVKey{txw}) \\}\\\\\n \\var{inputHashes}\\leteq \\left\\{ h \\,\\middle|\n {\n \\begin{array}{l}\n (a, \\_, h) \\in \\range(\\var{utxo}|_{\\fun{spendInputs}~tx}) \\\\\n \\fun{isTwoPhaseScriptAddress}~tx~\\hldiff{utxo}~a \\\\\n \\end{array}\n }\n \\right\\} \\cap \\hldiff{\\DataHash} \\\\~\\\\\n \\forall \\var{s} \\in \\range (\\fun{txscripts}~txw~\\hldiff{utxo}) \\cap \\ScriptPhOne,\n \\fun{validateScript}~\\var{s}~\\var{tx}\\\\~\\\\\n \\{ h \\mid (\\_, h) \\in \\fun{scriptsNeeded}~\\var{utxo}~txb\\} = \\dom (\\fun{txscripts}~txw~\\hldiff{utxo}) \\\\~\\\\\n \\var{inputHashes} \\subseteq \\dom (\\fun{txdats}~{txw}) \\\\~\\\\\n \\dom (\\fun{txdats}~{txw}) \\subseteq \\var{inputHashes} \\cup \\{h \\mid (\\wcard, \\wcard, h)\\in\\fun{txouts}~{tx} \\cup \\hldiff{\\var{utxo}~(\\fun{refInputs}~{tx})}\\}\n \\\\~\\\\\n \\dom (\\fun{txrdmrs}~tx) = \\left\\{ \\fun{rdptr}~txb~sp \\,\\middle|\n {\n \\begin{array}{l}\n (sp,h) \\in \\fun{scriptsNeeded}~\\var{utxo}~txb \\\\\n \\fun{txscripts}~{txw}~\\hldiff{utxo}~h \\in \\ScriptPhTwo\n \\end{array}\n } \\right\\}\n \\\\~\\\\\n \\var{txbodyHash}\\leteq\\fun{hash}~(\\txbody{tx}) \\\\\n \\forall \\var{vk} \\mapsto \\sigma \\in \\txwitsVKey{tx},\n \\mathcal{V}_{\\var{vk}}{\\serialised{txbodyHash}}_{\\sigma} \\\\\n \\fun{witsVKeyNeeded}~{utxo}~{tx}~{genDelegs} \\subseteq witsKeyHashes\n \\\\~\\\\\n genSig \\leteq\n \\left\\{\n \\fun{hashKey}~gkey \\vert gkey \\in\\dom{genDelegs}\n \\right\\}\n \\cap\n \\var{witsKeyHashes}\n \\\\\n \\left\\{\n c\\in\\txcerts{txb}~\\cap\\DCertMir\n \\right\\} \\neq\\emptyset \\implies \\vert genSig\\vert \\geq \\Quorum \\wedge\n \\fun{d}~\\var{pp} > 0\n \\\\~\\\\\n \\var{adh}\\leteq\\fun{txADhash}~\\var{txb}\n &\n \\var{ad}\\leteq\\fun{auxiliaryData}~\\var{tx}\n \\\\\n (\\var{adh}=\\Nothing \\land \\var{ad}=\\Nothing)\n \\lor\n (\\var{adh}=\\fun{hashAD}~\\var{ad})\n \\\\~\\\\\n \\hldiff{\\forall x \\in \\range (\\fun{txdats}~txw) \\cup \\range (\\fun{txwitscripts}~txw) \\cup \\bigcup_{(\\_, \\_, d, s) \\in \\txouts{tx}} \\{s, d\\},} \\\\\n \\hldiff{x \\in \\Script \\cup \\Datum \\Rightarrow \\fun{isWellFormed}~x}\n \\\\~\\\\\n \\fun{languages}~tx~\\hldiff{utxo} \\subseteq \\dom(\\fun{costmdls}~pp) \\cap \\fun{allowedLanguages}~tx~utxo \\\\\n \\fun{scriptIntegrityHash}~{txb} =\n \\fun{hashScriptIntegrity}~\\var{pp}~(\\fun{languages}~{txw})~(\\fun{txrdmrs}~{txw})~(\\fun{txdats}~{txw})\n \\\\~\\\\\n {\n \\begin{array}{r}\n \\var{slot}\\\\\n \\var{pp}\\\\\n \\var{poolParams}\\\\\n \\var{genDelegs}\\\\\n \\end{array}\n }\n \\vdash \\var{utxoSt} \\trans{\\hyperref[fig:rules:utxo-shelley]{utxo}}{tx}\n \\var{utxoSt'}\\\\\n }\n {\n \\begin{array}{r}\n \\var{slot}\\\\\n \\var{pp}\\\\\n \\var{poolParams}\\\\\n \\var{genDelegs}\\\\\n \\end{array}\n \\vdash \\var{utxoSt} \\trans{utxow}{tx} \\varUpdate{\\var{utxoSt'}}\n }\n \\end{equation}\n \\caption{UTxO with witnesses inference rules for Tx}\n \\label{fig:rules:utxow-babbage}\n\\end{figure}\n", "meta": {"hexsha": "3fe2b99a646848aadff81dd2b453120a8e5870d7", "size": 12811, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "eras/babbage/formal-spec/utxo.tex", "max_stars_repo_name": "RoyLL/cardano-ledger", "max_stars_repo_head_hexsha": "c5f3e9db1c22af5d284885ddb1785f1bd7755c67", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "eras/babbage/formal-spec/utxo.tex", "max_issues_repo_name": "RoyLL/cardano-ledger", "max_issues_repo_head_hexsha": "c5f3e9db1c22af5d284885ddb1785f1bd7755c67", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "eras/babbage/formal-spec/utxo.tex", "max_forks_repo_name": "RoyLL/cardano-ledger", "max_forks_repo_head_hexsha": "c5f3e9db1c22af5d284885ddb1785f1bd7755c67", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.487534626, "max_line_length": 178, "alphanum_fraction": 0.5378971197, "num_tokens": 4974, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011397337391, "lm_q2_score": 0.28140561345566495, "lm_q1q2_score": 0.16465074516038158}} {"text": "\\chapter{Mesh and Element Configuration} \\label{chap:meshconfig}\n\n \\NOTE{This description has not been updated for ViennaGrid 1.1.0 yet!}\n\n\nA mesh and all its topological elements as well as the underlying geometric space are specified in a common configuration class.\nThe setup of such a configuration class is explained in detail in Section \\ref{sec:config-class}.\n\nEven though mathematically all $n$-cells of a mesh are well defined and available on paper, it may not make sense to store explicit representations of these elements in memory.\nAs discussed in the Introduction, a particular algorithm may not require the storage of edges and/or facets of a mesh, thus keeping these elements in memory can be a considerable waste of resources.\nSection \\ref{sec:customizing-storage} explains how the underlying storage scheme of {\\ViennaGrid} can be adjusted to the library user's requirements and to be as memory-efficient as possible.\n\n\n\\section{The Configuration Class} \\label{sec:config-class}\nA valid configuration class for {\\ViennaGrid} is any class that provides the following three public member types:\n\\begin{center}\n\\begin{tabular}{|l|p{8cm}|}\n\\hline\n \\lstinline|numeric_type| & The underlying scalar type of the geometric space. \\\\\n\\hline\n \\lstinline|coordinate_system_tag| & A tag specifying the underlying coordinate system.\\\\\n\\hline\n \\lstinline|cell_tag| & A tag that identifies the cell type inside the mesh.\\\\\n\\hline\n\\end{tabular}\n\\end{center}\n\nMore details on the types are given in the following:\n\\begin{itemize}\n \\item \\lstinline|numeric_type|: This refers to the type of the coordinates of a point in the geometric space. In most cases, one may want to use \\lstinline|double|. However, it may also be the case that the user prefers to use integer coordinates, or high-precision floating point libraries such as ARPREC \\cite{arprec}.\n\n \\item \\lstinline|coordinate_system_tag|: Any of the following predefined classes from namespace \\lstinline|viennagrid| can be defined as \\lstinline|coordinate_system_tag| to select the coordinate system of the underlying geometric space:\n \\begin{center}\n \\begin{tabular}{|l|l|}\n \\hline\n \\lstinline|cartesian_cs| & Cartesian coordinate system of dimension \\lstinline|dim| \\\\\n \\hline\n \\lstinline|polar_cs| & Polar coordinate system in two dimensions \\\\\n \\hline\n \\lstinline|spherical_cs| & Spherical coordinates in three dimensions \\\\\n \\hline\n \\lstinline|cylindrical_cs| & Cylindrical coordinates in three dimensions \\\\\n \\hline\n \\end{tabular}\n \\end{center}\n\n \\item \\lstinline|cell_tag|: A tag that specifies the type of the elements with maximum topological dimension in the mesh. The following two families of topological elements are provided with {\\ViennaGrid} in namespace \\lstinline|viennagrid|:\n \\begin{center}\n \\begin{tabular}{|l|l|}\n \\hline\n \\lstinline|simplex| & Refers to an $n$-simplex \\\\\n \\hline\n \\lstinline|hypercube| & Refers to an $n$-hypercube \\\\\n \\hline\n \\end{tabular}\n \\end{center}\n It should be noted that \\lstinline|simplex<1>| and \\lstinline|hypercube<1>| both refer to a line segment. Typical examples from these families for common values of $n$ are as follows:\n\\begin{center}\n \\begin{tabular}{|l|c|c|}\n \\hline\n & {\\ViennaGrid} tag type & Convenience \\lstinline|typedef| \\\\\n \\hline\n Vertex & \\lstinline|point_tag| & - \\\\\n \\hline\n Line & \\lstinline|simplex_tag<1>| & \\lstinline|line_tag| \\\\\n Line & \\lstinline|hypercube_tag<1>| & - \\\\\n \\hline\n Triangle & \\lstinline|simplex_tag<2>| & \\lstinline|triangle_tag| \\\\\n Quadrilateral & \\lstinline|hypercube_tag<2>| & \\lstinline|quadrilateral_tag| \\\\\n \\hline\n Tetrahedron & \\lstinline|simplex_tag<3>| & \\lstinline|tetrahedron_tag| \\\\\n Hexahedron & \\lstinline|hypercube_tag<3>| & \\lstinline|hexahedron_tag| \\\\\n \\hline\n \\end{tabular}\n\\end{center}\n The reference orientations of these cells can be found in Appendix \\ref{chap:orientations}.\n\\end{itemize}\n\nAll geometric and topological types inside the mesh are then derived from the configuration class. To this end, {\\ViennaGrid} provides\na number of meta-functions that reside in namespace \\lstinline|viennagrid::result_of|. The naming follows the conventions in the Boost libraries \\cite{boost}.\nFor a configuration class \\lstinline|Config|, the respective types are obtained as follows:\n\\begin{lstlisting}\n using namespace viennagrid;\n\n typedef result_of::mesh::type MeshType;\n typedef result_of::segment::type SegmentType;\n typedef result_of::ncell::type VertexType;\n typedef result_of::ncell::type EdgeType;\n\\end{lstlisting}\nIn particular, the type of any $n$-cell in the mesh is obtained as\n\\begin{lstlisting}\n typedef result_of::ncell::type ElementType;\n\\end{lstlisting}\nwhere $n$ has to be replaced with the respective value. This allows to formulate algorithms such as a mesh boundary detection in a very general manner and can be used for recursively iterating through the $n$-cells of different dimension. In order to obtain the types of cells and facets, one should use the topological dimension from the cell tag:\n\\begin{lstlisting}\n typedef Config::cell_tag CellTag;\n typedef result_of::ncell::type FacetType;\n typedef result_of::ncell::type CellType;\n\\end{lstlisting}\n\n\\TIP{Please note that in template classes and template functions one needs to add an extra \\lstinline|typename| after each \\lstinline|typedef| keyword in the code snippets above.}\n\n{\\ViennaGrid} ships with a number of default configurations, which can directly be used without the need for setting up a separate config class:\n\\begin{center}\n \\begin{tabular}{|l|l|}\n \\hline\n Class Name & Description \\\\\n \\hline\n \\lstinline|line_1d| & one-dimensional mesh \\\\\n \\lstinline|line_2d| & mesh of lines in 2d \\\\\n \\lstinline|line_3d| & mesh of lines in 3d \\\\\n \\lstinline|triangular_2d| & triangular mesh in 2d \\\\\n \\lstinline|triangular_3d| & triangular mesh in 3d \\\\\n \\lstinline|tetrahedral_3d| & tetrahedral mesh in 2d \\\\\n \\lstinline|quadrilateral_2d| & quadrilateral mesh in 2d \\\\\n \\lstinline|quadrilateral_3d| & quadrilateral mesh in 3d \\\\\n \\lstinline|hexahedral_3d| & hexahedral mesh in 2d \\\\\n \\hline\n \\end{tabular}\n\\end{center}\nThe classes reside in namespace \\lstinline|viennagrid::config| and in the files \\lstinline|simplex.hpp| and \\lstinline|others.hpp| (for non-simplex meshes) in the \\lstinline|viennagrid/config| folder.\nEach of these configurations uses a numeric type \\lstinline|double| and a Cartesian coordinate system.\n\n\\section{Customizing Storage of $n$-Cells} \\label{sec:customizing-storage}\nOne of the outstanding features of {\\ViennaGrid} over other libraries related to grid handling is the possibility to customize the internal storage of elements. By default, all $n$-cells of a mesh are stored explicitly inside the mesh. In addition, each $n$-cell stores links to its boundary $k$-cells, with $k\n struct bndcell_handling{\n typedef no_handling_tag type;\n };\n\n template \n struct bndcell_handling{\n typedef no_handling_tag type;\n };\n} }\n\\end{lstlisting}\nThe third macro explained for method 1 results in the same code as the first macro, with the exception that \\lstinline|no_handling_tag| is replaced with \\lstinline|full_handling_tag|.\n\nFinally, we wish to point at a potential pitfall when disabling $n$-cells that are neither $0$-cells, $N-1$-cells, nor $N$-cells: Consider the case of disabling edges for a tetrahedron. Using the line\n \\begin{lstlisting}\nVIENNAGRID_DISABLE_BOUNDARY_NCELL(MyConfig,\n viennagrid::tetrahedron_tag, 1)\n \\end{lstlisting}\nonly disables the edges for the tetrahedron, but still edges are pushed and stored inside the mesh, because the triangular facets of the tetrahedron store pointers to their edges. Thus, to completely disable the storage of any edges, one also has to disable the storage of edges for triangles. As a check, one should verify that the number of edges stored inside a mesh \\lstinline|my_mesh| and obtained by\n \\begin{lstlisting}\n viennagrid::ncells<1>(my_mesh).size()\n \\end{lstlisting}\nis zero.\n\n\\TIP{Have a look at \\texttt{examples/tutorial/slim\\_mesh.cpp} and selectively enable or disable the storage of elements to see the impact on total memory consumption. Note that the bytes per object may differ from Tab.~\\ref{tab:full-mesh-memory} and Tab.~\\ref{tab:slim-mesh-memory} depending on the use of local-to-global-orienters and the eventual use of integral IDs.}\n\n\\subsection{Local Orientations} \\label{subsec:customize-local-orientations}\n\\begin{figure}[tb]\n\\centering\n \\includegraphics[width=0.5\\textwidth]{figures/interface-tets.eps}\n \\caption{Boundary $n$-cells have different orientations with respect to different cells.}\n \\label{fig:orientation-boundary-ncells}\n\\end{figure}\n\nIn cases where $n$-cells store boundary $k$-cells, $k\n struct bndcell_orientation\n { typedef no_handling_tag type; };\n} }\n \\end{lstlisting}\nUsing the type \\lstinline|full_handling_tag| instead of \\lstinline|no_handling_tag| enables the storage of local orientations.\n\\end{itemize}\n\n\\TIP{If the storage of boundary $k$-cells is disabled (cf.~Sec.~\\ref{subsec:boundary-ncells-storage}), there are automatically no local orientations for boundary $k$-cells stored. The local orientations do not need to be disabled explicitly in this case.}\n\n\\subsection{$n$-Cell IDs} \\label{subsec:ncell-ids}\nIt is often convenient to have enumerated $n$-cells within a mesh such that every $n$-cell is aware of its index inside the random access container it resides in. This allows for some algorithms to use fast random-accesses with $\\LandauO(1)$ costs rather than searching trees with $\\LandauO(\\log N)$ costs or linked lists with $\\LandauO(N)$ costs, where $N$ here denotes the number of $n$-cells inside the mesh. Conversely, if $\\LandauO(\\log N)$ access times are acceptable, then the memory for storing the container index (which we refer to in the following as \\emph{$n$-cell ID}) is wasted. To accommodate for these two scenarios, {\\ViennaGrid} allows to selectively enable or disable the storage of $n$-cell IDs. By default, $n$-cell IDs are stored, since they have negligible impact on the total memory consumption as soon as other boundary $k$-cells are stored for an $n$-cell.\n\nAs for the storage of boundary $k$-cells and local orientations, there are two possibilities for customizing the storage of IDs:\n\\begin{itemize}\n \\item \\textbf{Method 1}: Using the provided macros. To disable the storage of IDs for tetrahedrons inside a mesh with configuration \\lstinline|MyConfig|, the line\n \\begin{lstlisting}\nVIENNAGRID_DISABLE_NCELL_ID(viennagrid::config::tetrahedral_3d,\n viennagrid::tetrahedron_tag)\n \\end{lstlisting}\n is sufficient. The second argument denotes the element tag for which the storage of IDs should be disabled.\n\n To globally disable the storage of IDs for tetrahedrons, use\n \\begin{lstlisting}\nVIENNAGRID_GLOBAL_DISABLE_NCELL_ID(viennagrid::tetrahedron_tag)\n \\end{lstlisting}\n To selectively enable the storage of IDs for certain configuration classes in a globally disabled setting, one can use\n \\begin{lstlisting}\nVIENNAGRID_ENABLE_NCELL_ID(viennagrid::config::tetrahedral_3d,\n viennagrid::tetrahedron_tag)\n \\end{lstlisting}\n\n \\item \\textbf{Method 2}:\nThe macros from the first method expand to\n\\begin{lstlisting}\ntemplate <>\nstruct element_id_handler\n{ typedef pointer_id type; };\n\\end{lstlisting}\nfor the configuration class \\lstinline|MyConfig|, and to\n\\begin{lstlisting}\ntemplate \nstruct element_id_handler\n{ typedef pointer_id type; };\n\\end{lstlisting}\nfor globally disabling the storage of IDs. To selectively enable IDs, \\lstinline|integral_id| should be used instead of \\lstinline|pointer_id|.\n\n\n\\end{itemize}\n\n\n\n\\TIP{Have a look at \\texttt{examples/tutorial/slim\\_mesh.cpp} and selectively enable or disable the storage of elements, local orientations and IDs to see the impact on total memory consumption. Note that the bytes per object may differ from Tab.~\\ref{tab:full-mesh-memory} and Tab.~\\ref{tab:slim-mesh-memory} depending on the use of local orientations and integral IDs.}\n\n\\NOTE{Disabling $n$-cell IDs eliminates the possibility to store and access data for the respective $n$-cells with $\\LandauO(1)$ costs, see Chapter \\ref{chap:data}.}\n\n\\end{itemize}\n\n", "meta": {"hexsha": "0f373a59d75e0759fe733c1977cf3aa9f8d8e729", "size": 19929, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/manual/meshconfig.tex", "max_stars_repo_name": "viennagrid/viennagrid-dev", "max_stars_repo_head_hexsha": "6e47c8d098a0b691d6b9988f2444cd11d440f4c2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2015-09-13T03:50:58.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-27T14:24:49.000Z", "max_issues_repo_path": "doc/manual/meshconfig.tex", "max_issues_repo_name": "viennagrid/viennagrid-dev", "max_issues_repo_head_hexsha": "6e47c8d098a0b691d6b9988f2444cd11d440f4c2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/manual/meshconfig.tex", "max_forks_repo_name": "viennagrid/viennagrid-dev", "max_forks_repo_head_hexsha": "6e47c8d098a0b691d6b9988f2444cd11d440f4c2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2015-07-03T07:14:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-20T00:51:58.000Z", "avg_line_length": 62.278125, "max_line_length": 882, "alphanum_fraction": 0.7504641477, "num_tokens": 5149, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.32423540551084407, "lm_q1q2_score": 0.16465058573778557}} {"text": "\\chapter{Introduction}\n\nThe \\numbers\\ program is a shell program which reads and stores data\nfrom a finite element model described in the \\exo\\ database\nformat~\\cite{EXODUS}.\nWithin this shell program are several utility routines which calculate\ninformation about the finite element model. The utilities currently\nimplemented in \\numbers\\ allow the analyst to determine:\n\\begin{itemize}\n\\item the volume and coordinate limits of each of the materials in the model;\n\\item the mass properties of the model;\n\\item the minimum, maximum, and average element volumes for each material;\n\\item the volume and change in volume of a cavity;\n\\item the nodes or elements that are within a specified distance from a\nuser-defined point, line, or plane;\n\\item an estimate of the explicit central-difference timestep for each\nmaterial;\n\\item the validity of contact surfaces or slidelines, that is, whether\ntwo surfaces overlap at any point; and\n\\item the distance between two surfaces.\n\\end{itemize}\n\nThese utilities have been developed to automate and simplify some of the\ntasks normally performed during an analysis. The \\numbers\\ program\nreads the finite element model and results from a file written in the\n\\exo\\ binary file format which is used in the Engineering\nAnalysis Department at \\SNLA.\n\nThe capabilities of \\numbers\\ have evolved during the past eighteen\nmonths. Originally, it was written solely to calculate the mass\nproperties of a body. However, once the basic function of reading and\nstoring an \\exo\\ database was in place, it was realized that several\ntasks that were usually performed manually could easily be implemented\nin \\numbers. Tasks such as determining node and element numbers,\nverifying contact surfaces, and others, are now performed more\nefficiently and, hopefully, more accurately since the code performs the\nrepetitive calculations automatically.\n\nAlthough the original reason for developing \\numbers\\ was to simply\ncalculate mass properties, the code now functions as an \\exo\\ shell that\ncan be easily extended by analysts who require specific calculations or\nneed to create information not currently available. The analyst can\nsimply write a subroutine to perform their function, and insert it into\n\\numbers\\ without worrying about the details of reading an \\exo\\\ndatabase and providing a user interface. For most cases, adding a\nfunction to \\numbers\\ requires only writing the function subroutine,\nadding the command name to the table of valid commands, and adding a few\nstatements to call the routine.\n\nThe remainder of this report is organized as follows.\nChapter~\\ref{c:numerics} describes the numerical algorithms used by the\nutility functions in \\numbers. A list of the commands and the command\nsyntax are presented in Chapter~\\ref{c:commands}.\nChapter~\\ref{c:examples} gives several examples of the use of the\nutilities, and Chapter~\\ref{c:conclude} concludes the report. Three\nappendixes are included. Appendix~\\ref{a:cmdsum} is a summary of the\ncommand syntax for each of the commands.\n\nThe descriptions in the following chapters assume that the reader is\nfamiliar with the \\gen\\ and \\exo\\ file formats and with the analysis,\npreprocessing, and postprocessing codes used in the Engineering Analysis\nDepartment at \\SNLA. Readers not familiar with these can check the\nreferences at the end of this report for a list of the documentation for\nthese codes and file formats.\n", "meta": {"hexsha": "086423f4d206757d35762ddb6f08a85332d2d5b3", "size": 3409, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "packages/seacas/doc-source/numbers/intro.tex", "max_stars_repo_name": "tokusanya/seacas", "max_stars_repo_head_hexsha": "54d9c3b68508ca96e3db1fd00c5d84a810fb330b", "max_stars_repo_licenses": ["Zlib", "NetCDF", "MIT", "BSL-1.0", "X11", "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": "packages/seacas/doc-source/numbers/intro.tex", "max_issues_repo_name": "tokusanya/seacas", "max_issues_repo_head_hexsha": "54d9c3b68508ca96e3db1fd00c5d84a810fb330b", "max_issues_repo_licenses": ["Zlib", "NetCDF", "MIT", "BSL-1.0", "X11", "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": "packages/seacas/doc-source/numbers/intro.tex", "max_forks_repo_name": "tokusanya/seacas", "max_forks_repo_head_hexsha": "54d9c3b68508ca96e3db1fd00c5d84a810fb330b", "max_forks_repo_licenses": ["Zlib", "NetCDF", "MIT", "BSL-1.0", "X11", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 52.4461538462, "max_line_length": 77, "alphanum_fraction": 0.8063948372, "num_tokens": 730, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3140505578320071, "lm_q1q2_score": 0.16438045256407635}} {"text": "\\documentclass[a4paper]{article}\r\n\r\n\\usepackage[margin=2cm]{geometry}\t\t% For desired margins\r\n\\usepackage{fontspec}\t\t\t\t\t% utf-8 support\r\n\\usepackage{enumitem}\t\t\t\t\t% Continuous enumerations\r\n\\usepackage{float}\t\t\t\t\t\t% Floating images\r\n\\usepackage[dvipsnames]{xcolor}\t\t\t% Colors\r\n\\usepackage{pgfplots}\t\t\t\t\t% Custom plots\r\n\\usepackage{listings}\t\t\t\t\t% Code highlighting\r\n\\usepackage[hidelinks]{hyperref}\t\t% Hyper links\r\n\\usepackage{graphicx}\t\t\t\t\t% To include images\r\n\\usepackage{tikz}\t\t\t\t\t\t% To draw images\r\n\\usepackage{pgfplots}\t\t\t\t\t% To draw graphs\r\n\\usepackage[dvipsnames]{xcolor\t}\r\n\\usepackage{subcaption}\r\n\r\n\\pgfplotsset{compat=1.13}\r\n\\usetikzlibrary{positioning}\r\n\r\n\\setlength{\\parindent}{0pt}\r\n\\setlength{\\parskip}{1em}\r\n\r\n\\title{PAR: Laboratory 5 \\\\\r\n\t\t\\texttt{\\large par4201}}\r\n\\author{Joan Marcè i Igual \\and Es6teve Tarragó i Sanchis}\r\n\r\n\\newenvironment{questionenum}{%\r\n\\setlist[enumerate]{resume}\r\n\\restartlist{enumerate}\r\n\\newcommand{\\question}[1]{\r\n\\begin{enumerate}\r\n\t\\item\\bfseries ##1\r\n\\end{enumerate}\r\n}}{%\r\n}\r\n\r\n\\lstset{\r\n\tbasicstyle=\\small\\ttfamily,\r\n\tshowspaces=false,\r\n\tshowstringspaces=false,\r\n\ttabsize=4,\r\n\tnumbers=left,\r\n\tnumbersep=5pt,\r\n\tstringstyle=\\color{orange},\r\n\tcommentstyle=\\color{OliveGreen},\r\n\tkeywordstyle=\\color{blue},\r\n\tnumberstyle=\\color{Gray},\r\n\tframe=single\r\n}\r\n\r\n\\begin{document}\r\n\\maketitle\r\n\\tableofcontents\r\n\r\n\\section{Analysis with Tareador}\r\n\r\n\\begin{questionenum}\r\n\t\\question{Include the relevant parts of the modified \\texttt{solver-tareador.c} code and comment where the calls to the Tareador API have been placed. Comment also about the task graph generated and the causes of the dependencies that appear in the two solvers: \\emph{Jacobi} and \\emph{Gauss-Seidel}. How will you protect them in the parallel \\texttt{OpenMP} code.}\r\n\\end{questionenum}\r\n\r\n\\begin{center}\t\r\n\t\\begin{minipage}{0.8\\textwidth}\r\n\\begin{lstlisting}[language=C, title=\\texttt{heat-tareador.c}]\r\nswitch( param.algorithm ) {\r\n\tcase 0: // JACOBI\r\n\t\ttareador_start_task(\"relax_jacobi\");\r\n\t\tresidual = relax_jacobi(param.u, param.uhelp, np, np);\r\n\t\ttareador_end_task(\"relax_jacobi\");\r\n\t\t// Copy uhelp into u\r\n\t\ttareador_start_task(\"Copy_mat\");\r\n\t\tcopy_mat(param.uhelp, param.u, np, np);\r\n\t\ttareador_end_task(\"Copy_mat\");\r\n\t\tbreak;\r\n\tcase 1: // GAUSS\r\n\t\ttareador_start_task(\"relax_gauss\");\r\n\t\tresidual = relax_gauss(param.u, np, np);\r\n\t\ttareador_end_task(\"relax_gauss\");\r\n\t\tbreak;\r\n}\r\n\t\t\\end{lstlisting}\r\n\t\\end{minipage}\r\n\t\r\n\t\\begin{minipage}{0.8\\textwidth}\r\n\t\t\\begin{lstlisting}[language=C, title=\\texttt{solver-tareador.c}]\r\n// Set tareador task\r\ntareador_start_task(\"jacobi_relax\");\r\n// Disable sum object for better parallelization potential\r\ntareador_disable_object(&sum);\r\nutmp[i*sizey+j]= 0.25 * ( u[ i*sizey + (j-1) ]+ // left\r\nu[ i*sizey + (j+1) ]+ // right\r\nu[ (i-1)*sizey + j ]+ // top\r\nu[ (i+1)*sizey + j ]); // bottom\r\ndiff = utmp[i*sizey+j] - u[i*sizey + j];\r\nsum += diff * diff;\r\n\r\n// Reenable sum object\r\ntareador_enable_object(&u);\r\n\r\n// End of tareador task\r\ntareador_end_task(\"jacobi_relax\");\r\n\t\t\\end{lstlisting}\r\n\t\\end{minipage}\r\n\\end{center}\r\n\r\n\\section{OpenMP parallelization and execution analysis: \\emph{Jacobi}}\r\n\\begin{questionenum}\r\n\t\\question{Describe the data decomposition strategy that is applied to solve the problem, including a picture with the part of the data structure that is assigned to each processor.}\r\n\t\r\n\tThe decomposition strategy used is giving each thread a different part of the matrix by rows. This can be seen in the \\autoref{fig:jacobi-data} where each thread has a different block of rows of the matrix to be computed. \r\n\t\r\n\t\\begin{figure}[H]\r\n\t\t\\centering\r\n\t\t\\includegraphics[width=0.5\\textwidth]{images/jacobi/data}\r\n\t\t\\caption{Figure describing the data decomposition, each thread has one color}\r\n\t\t\\label{fig:jacobi-data}\r\n\t\\end{figure}\r\n\t\r\n\t\\question{Include the relevant portions of the parallel code that you implemented to solve the heat equation using the \\emph{Jacobi} solver, commenting whatever necessary. Including captures of Paraver windows to justify your explanations and the differences observed in the execution.}\r\n\t\r\n\tThe heat computation part can be optimized in the following way with \\texttt{OpenMP}. \r\n\t\\begin{center}\r\n\t\t\r\n\t\\begin{minipage}{0.9\\textwidth}\r\n\t\t\\begin{lstlisting}[language=C, title=\\texttt{solver-tareador.c}]\r\ndouble relax_jacobi (double *u, double *utmp, unsigned sizex, unsigned sizey)\r\n{\r\n\tdouble diff, sum=0.0;\r\n\t\r\n\t// In this part max threads is used instead of get_num_threads() beacuse \r\n\t// there's only one thread at this point.\r\n\tint howmany = omp_get_max_threads();\r\n\t\t\r\n\t// Parallelize by blocks, assigning each block to one different thread\r\n\t#pragma omp parallel for reduction(+:sum) private(diff)\r\n\tfor (int blockid = 0; blockid < howmany; ++blockid) {\r\n\t\tint i_start = lowerb(blockid, howmany, sizex);\r\n\t\tint i_end = upperb(blockid, howmany, sizex);\r\n\t\tfor (int i=max(1, i_start); i<= min(sizex-2, i_end); i++) {\r\n\t\t\tfor (int j=1; j<= sizey-2; j++) {\r\n\t\t\t\tutmp[i*sizey+j]= 0.25 * ( u[ i*sizey + (j-1) ]+ // left\r\n\t\t\t\tu[ i*sizey + (j+1) ]+ // right\r\n\t\t\t\tu[ (i-1)*sizey + j ]+ // top\r\n\t\t\t\tu[ (i+1)*sizey + j ]); // bottom\r\n\t\t\t\tdiff = utmp[i*sizey+j] - u[i*sizey + j];\r\n\t\t\t\tsum += diff * diff;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\t\r\n\treturn sum;\r\n}\r\n\t\t\\end{lstlisting}\r\n\t\\end{minipage}\r\n\t\\end{center}\r\n\t\r\n\tAlso there's another complementary way to optimize. The \\texttt{copy\\_mat()} function can be parallelized to allow a better way of copying the matrix.\r\n\t\r\n\t\\begin{center}\r\n\t\t\\begin{minipage}{0.8\\textwidth}\r\n\t\t\t\\begin{lstlisting}[language=C, title=\\texttt{solver-tareador.c}]\r\n#pragma omp parallel for collapse(2)\r\nfor (int i=1; i<=sizex-2; i++)\r\n\tfor (int j=1; j<=sizey-2; j++)\r\n\t\tv[ i*sizey+j] = u[ i*sizey+j ];\r\n\t\t\t\\end{lstlisting}\r\n\t\t\\end{minipage}\r\n\t\\end{center}\r\n\r\n\tAnother way to attack the problem is avoiding the matrix copy part and only swapping the pointers of the matrix. This can be done in the \\texttt{heat-omp.c} file between the iterations.\r\n\t\r\n\t\\begin{center}\r\n\t\t\\begin{minipage}{0.8\\textwidth}\r\n\t\t\t\\begin{lstlisting}[language=C, title=\\texttt{heat-omp.c}]\r\nresidual = relax_jacobi(param.u, param.uhelp, np, np);\r\n// Swap the pointers to avoid copying the matrix\r\ndouble *temp = param.u;\r\nparam.u = param.uhelp;\r\nparam.uhelp = temp;\r\n\r\n// Disable the matrix copy\r\n//copy_mat(param.uhelp, param.u, np, np);\r\n\t\t\t\\end{lstlisting}\r\n\t\t\\end{minipage}\r\n\t\\end{center}\r\n\t\r\n\t\\begin{figure}[H]\r\n\t\t\\centering\r\n\t\t\\includegraphics[width=\\textwidth]{images/jacobi/paraver-8}\r\n\t\t\\caption{Capture of \\texttt{paraver} using 8 processors}\r\n\t\t\\label{fig:jacobi-paraver}\r\n\t\\end{figure}\r\n\r\n\t\\begin{figure}[H]\r\n\t\t\\centering\r\n\t\t\\includegraphics[width=\\textwidth]{images/jacobi/paraver-8-zoom}\r\n\t\t\\caption{Zoom of \\texttt{paraver} capture to show that the processor 0 is still doing work}\r\n\t\t\\label{fig:jacobi-paraver-zoom}\r\n\t\\end{figure}\r\n\t\r\n\tAs it can be seen in the \\autoref{fig:jacobi-paraver} all processors are working so the work is properly shared between all the processors. It seems that the processor 0 is only doing synchronizations but actually it's working too as it can be seen in the \\autoref{fig:jacobi-paraver-zoom}.\r\n\t\r\n\t\\question{Include the speed-up (strong scalability) plots that have been obtained for the different numbers of processors. Reason about the performance that is observed.}\r\n\t\r\n\t\\begin{figure}[H]\r\n\t\t\\begin{subfigure}[t]{0.49\\textwidth}\r\n\t\t\t\\begin{tikzpicture}\r\n\t\t\t\t\\begin{axis}[\r\n\t\t\t\t\t\twidth = \\textwidth,\r\n\t\t\t\t\t\txmin = 1, xmax = 12,\r\n\t\t\t\t\t\tdomain = 0:12,\r\n\t\t\t\t\t\txlabel = number of processors,\r\n\t\t\t\t\t\tylabel = execution time,\r\n\t\t\t\t\t\tenlarge x limits = 0.05,\r\n\t\t\t\t\t]\r\n\t\t\t\t\t\\addplot table[x = P, y = T]{data/jacobi/elapsed.csv};\r\n\t\t\t\t\t\\addplot[dashed, mark = none] {4.5/x};\r\n\t\t\t\t\\end{axis}\r\n\t\t\t\\end{tikzpicture}\r\n\t\t\t\\caption{Elapsed time for each number of processors}\r\n\t\t\t\\label{fig:jacobi-elapsed}\r\n\t\t\\end{subfigure}\r\n\t\t\\hfill\r\n\t\t\\begin{subfigure}[t]{0.49\\textwidth}\t\t\r\n\t\t\t\\begin{tikzpicture}\r\n\t\t\t\t\\begin{axis}[\r\n\t\t\t\t\t\twidth = \\textwidth,\r\n\t\t\t\t\t\txmin = 1, xmax = 12,\r\n\t\t\t\t\t\tymin = 0, ymax = 12,\r\n\t\t\t\t\t\tdomain = 0:12,\r\n\t\t\t\t\t\txlabel = number of processors,\r\n\t\t\t\t\t\tylabel = speedup,\r\n\t\t\t\t\t\tenlarge x limits = 0.05,\r\n\t\t\t\t\t]\r\n\t\t\t\t\t\\addplot[dashed, mark=none]{x};\r\n\t\t\t\t\t\\addplot table[x = P, y = S]{data/jacobi/speedup.csv};\r\n\t\t\t\t\\end{axis}\r\n\t\t\t\\end{tikzpicture}\r\n\t\t\t\\caption{Speedup obtained for each number of processors}\r\n\t\t\t\\label{fig:jacobi-speedup}\r\n\t\t\\end{subfigure}\r\n\t\\caption{Comparison between speedup and elapsed time by number of processors in the Jacobi solution}\r\n\t\\end{figure}\r\n\\end{questionenum}\r\n\r\nAs it can bee seen in the \\autoref{fig:jacobi-speedup} the speedup increases and then it remains nearly constant. This is due to the overhead caused by \\texttt{OpenMP} as the number of processors increases. If the data is divided by many processors there's more time spend during the synchronization than computing the value and that's why the speedup is not increasing anymore.\r\n\r\n\\section{OpenMP parallelization and the execution analysis: \\emph{Gauss-Seidel}}\r\n\\begin{questionenum}\r\n\t\\question{Include the relevant portions of the parallel code that implements the \\emph{Gauss-Seidel} solver, commenting how you implemented the synchronization between threads.}\r\n\t\r\n\t\\begin{center}\r\n\t\t\\begin{minipage}{0.8\\textwidth}\r\n\t\t\t\\begin{lstlisting}[language=C, title=\\texttt{solver-omp-gauss.c}]\r\ndouble relax_gauss (double *u, unsigned sizex, unsigned sizey)\r\n{ \r\n\tint howmany = omp_get_max_threads();\r\n\tint numblocks = howmany;\r\n\tint blocksfinished[numblocks];\r\n\tfor(int i =0; i < numblocks; ++i) blocksfinished[i]=-1;\r\n\tdouble unew, diff, sum=0.0;\r\n\t\r\n\t#pragma omp parallel for reduction(+:sum) private(diff,unew)\r\n\tfor (int blockid = 0; blockid < numblocks; ++blockid) {\r\n\t\tfor (int blockidcol = 0; blockidcol < numblocks; ++blockidcol){\r\n\t\t\tif (blockid > 0) {\r\n\t\t\t\t// Added block waiting\r\n\t\t\t\twhile( blocksfinished[blockid-1] < blockidcol ) {\r\n\t\t\t\t#pragma omp flush(blocksfinished)\r\n\t\t\t}\r\n\t\t}\r\n\t\tint i_start = lowerb(blockid, numblocks, sizex);\r\n\t\tint i_end = upperb(blockid, numblocks, sizex);\r\n\t\tint j_start = lowerb(blockidcol,numblocks, sizey);\r\n\t\tint j_end = upperb(blockidcol, numblocks,sizey);\r\n\t\tfor (int i=max(1, i_start); i<= min(sizex-2, i_end); i++) {\r\n\t\t\tfor (int j=max(1, j_start); j<= min(sizey-2, j_end); j++) {\r\n\t\t\t\tunew = 0.25 * (\r\n\t\t\t\t\tu[ i*sizey \t\t+ (j-1) ]+ // left\r\n\t\t\t\t\tu[ i*sizey\t\t+ (j+1) ]+ // right\r\n\t\t\t\t\tu[ (i-1)*sizey\t+ j ]+ // top\r\n\t\t\t\t\tu[ (i+1)*sizey\t+ j ]); // bottom\r\n\t\t\t\tdiff = unew - u[i*sizey+ j];\r\n\t\t\t\tsum += diff * diff;\r\n\t\t\t\tu[i*sizey+j]=unew;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t// Finish block\r\n\t\t\tblocksfinished[blockid] = blockidcol;\r\n\t\t\t#pragma omp flush(blocksfinished)\r\n\t\t}\r\n\t}\r\n\t\r\n\treturn sum;\r\n}\r\n\t\t\t\\end{lstlisting}\r\n\t\t\\end{minipage}\r\n\t\\end{center}\r\n\t\r\n\tFor the synchronization we use the array \\texttt{blocksfinished [row]} in which we store the last column achieved by the row. A row can only start a block if the previous row has already been calculated.\r\n\t\r\n\tIn order to synchronize the variable \\texttt{blocksfinished} we use the \\texttt{flush} sentence. We are also using \\texttt{reduction} in order to join the result.\r\n\t\r\n\t\\question{Include the speed-up (strong-scalability) plot that has been obtained for the different numbers of processors. Reason about the performance that is observed, including captures of Paraver windows to justify your explanations.}\r\n\t\r\n\t\\begin{figure}[H]\r\n\t\t\\begin{subfigure}{0.49\\textwidth}\r\n\t\t\t\\centering\r\n\t\t\t\\begin{tikzpicture}\r\n\t\t\t\t\\begin{axis}[\r\n\t\t\t\t\t\txmin = 1, xmax = 12,\r\n\t\t\t\t\t\tdomain = 1:12,\r\n\t\t\t\t\t\tenlarge x limits = 0.05,\r\n\t\t\t\t\t\txlabel = number of processors,\r\n\t\t\t\t\t\tylabel = execution time,\r\n\t\t\t\t\t\twidth = \\textwidth\r\n\t\t\t\t\t]\r\n\t\t\t\t\t\\addplot table[x=P, y=T]{data/gauss/elapsed.csv};\r\n\t\t\t\t\t\\addplot[dashed, mark = none]{6.5/x};\r\n\t\t\t\t\\end{axis}\r\n\t\t\t\\end{tikzpicture}\r\n\t\t\\end{subfigure}\r\n\t\t\\hfill\r\n\t\t\\begin{subfigure}{0.49\\textwidth}\r\n\t\t\t\\centering\r\n\t\t\t\\begin{tikzpicture}\r\n\t\t\t\t\\begin{axis}[\r\n\t\t\t\t\t\txmin = 1, xmax = 12,\r\n\t\t\t\t\t\tdomain = 1:12,\r\n\t\t\t\t\t\tenlarge x limits = 0.05,\r\n\t\t\t\t\t\txlabel = number of processors,\r\n\t\t\t\t\t\tylabel = speedup,\r\n\t\t\t\t\t\twidth = \\textwidth\r\n\t\t\t\t\t]\r\n\t\t\t\t\t\\addplot table[x=P, y=S] {data/gauss/speedup.csv};\r\n\t\t\t\t\t\\addplot[dashed, mark=none]{x};\r\n\t\t\t\t\\end{axis}\r\n\t\t\t\\end{tikzpicture}\r\n\t\t\\end{subfigure}\r\n\t\\end{figure}\r\n\r\n\tWe can see that the synchronizations costs are more than linear. This is due to the number of blocks which is quadratic in the number of threads and a flush is need in each region.\r\n\t\r\n\t\\question{Explain how did you obtain the optimum value for the ration computation/synchronization in the parallelization of this solver for 8 threads.}\r\n\\end{questionenum}\r\n\r\n\r\n\t\\begin{figure}[H]\r\n\t\t\\centering\r\n\t\t\\begin{tikzpicture}\r\n\t\t\t\\begin{axis}[\r\n\t\t\t\t\txmin = 4, xmax = 16,\r\n\t\t\t\t\tymin = 0, ymax = 7,\r\n\t\t\t\t\txlabel = Number of blocks,\r\n\t\t\t\t\tylabel = Time,\r\n\t\t\t\t\tenlarge x limits = 0.05,\r\n\t\t\t\t]\r\n\t\t\t\t\\addplot table[x=N, y=T]{data/gauss/optimum.csv};\r\n\t\t\t\\end{axis}\r\n\t\t\\end{tikzpicture}\r\n\t\\end{figure}\r\n\r\nWe can see that the optimum value is 8, which mean 8 rows with 8 columns each. With a lower number there are threads with no job and with a higher value we are increasing the synchronization cost.\r\n\r\n\r\n\\end{document}", "meta": {"hexsha": "67a9e0b05173d2f44b4bae70056569ce7ac70ac7", "size": 13218, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "lab5/LaTex/lab5.tex", "max_stars_repo_name": "jmigual/par2016", "max_stars_repo_head_hexsha": "a419dd21eaa0d9c8581cb28db994432db93b9ba6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lab5/LaTex/lab5.tex", "max_issues_repo_name": "jmigual/par2016", "max_issues_repo_head_hexsha": "a419dd21eaa0d9c8581cb28db994432db93b9ba6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lab5/LaTex/lab5.tex", "max_forks_repo_name": "jmigual/par2016", "max_forks_repo_head_hexsha": "a419dd21eaa0d9c8581cb28db994432db93b9ba6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.1147540984, "max_line_length": 379, "alphanum_fraction": 0.6787713724, "num_tokens": 4061, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.411110869232168, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.1643669111536764}} {"text": "\\documentclass{article}\n\n\\usepackage{fancyhdr}\n\\usepackage{extramarks}\n\\usepackage{amsmath}\n\\usepackage{amsthm}\n\\usepackage{amsfonts}\n\\usepackage{amssymb}\n\\usepackage{tikz}\n\\usepackage{physics}\n\\usepackage[plain]{algorithm}\n\\usepackage{algpseudocode}\n\n\\usetikzlibrary{automata,positioning}\n\n%\n% Basic Document Settings\n%\n\n\\topmargin=-0.45in\n\\evensidemargin=0in\n\\oddsidemargin=0in\n\\textwidth=6.5in\n\\textheight=9.0in\n\\headsep=0.25in\n\n\\linespread{1.1}\n\n\\pagestyle{fancy}\n\\lhead{\\hmwkAuthorName}\n\\chead{\\hmwkClass\\ (\\hmwkClassInstructor\\ \\hmwkClassTime): \\hmwkTitle}\n\\rhead{\\firstxmark}\n\\lfoot{\\lastxmark}\n\\cfoot{\\thepage}\n\n\\renewcommand\\headrulewidth{0.4pt}\n\\renewcommand\\footrulewidth{0.4pt}\n\n\\setlength\\parindent{0pt}\n\n%\n% Create Problem Sections\n%\n\n\\newcommand{\\enterProblemHeader}[1]{\n \\nobreak\\extramarks{}{Problem \\arabic{#1} continued on next page\\ldots}\\nobreak{}\n \\nobreak\\extramarks{Problem \\arabic{#1} (continued)}{Problem \\arabic{#1} continued on next page\\ldots}\\nobreak{}\n}\n\n\\newcommand{\\exitProblemHeader}[1]{\n \\nobreak\\extramarks{Problem \\arabic{#1} (continued)}{Problem \\arabic{#1} continued on next page\\ldots}\\nobreak{}\n \\stepcounter{#1}\n \\nobreak\\extramarks{Problem \\arabic{#1}}{}\\nobreak{}\n}\n\n\\setcounter{secnumdepth}{0}\n\\newcounter{partCounter}\n\\newcounter{homeworkProblemCounter}\n\\setcounter{homeworkProblemCounter}{1}\n\\nobreak\\extramarks{Problem \\arabic{homeworkProblemCounter}}{}\\nobreak{}\n\n%\n% Homework Problem Environment\n%\n% This environment takes an optional argument. When given, it will adjust the\n% problem counter. This is useful for when the problems given for your\n% assignment aren't sequential. See the last 3 problems of this template for an\n% example.\n%\n\\newenvironment{homeworkProblem}[1][-1]{\n \\ifnum#1>0\n \\setcounter{homeworkProblemCounter}{#1}\n \\fi\n \\section{Problem \\arabic{homeworkProblemCounter}}\n \\setcounter{partCounter}{1}\n \\enterProblemHeader{homeworkProblemCounter}\n}{\n \\exitProblemHeader{homeworkProblemCounter}\n}\n\n%\n% Homework Details\n% - Title\n% - Due date\n% - Class\n% - Section/Time\n% - Instructor\n% - Author\n%\n\n\\newcommand{\\hmwkTitle}{Homework\\ \\#2}\n\\newcommand{\\hmwkDueDate}{February 12, 2014}\n\\newcommand{\\hmwkClass}{Calculus}\n\\newcommand{\\hmwkClassTime}{}\n\\newcommand{\\hmwkClassInstructor}{Professor Isaac Newton}\n\\newcommand{\\hmwkAuthorName}{\\textbf{Aditya Vijaykumar}}\n\n%\n% Title Page\n%\n\n\\title{\n %\\vspace{2in}\n \\textmd{\\textbf{\\hmwkClass:\\ \\hmwkTitle}}\\\\\n \\normalsize\\vspace{0.1in}\\small{\\hmwkDueDate\\ }\\\\\n% \\vspace{3in}\n}\n\n\\author{\\hmwkAuthorName}\n\\date{}\n\n\\renewcommand{\\part}[1]{\\textbf{\\large Part \\Alph{partCounter}}\\stepcounter{partCounter}\\\\}\n\n%\n% Various Helper Commands\n%\n\n% Useful for algorithms\n\\newcommand{\\alg}[1]{\\textsc{\\bfseries \\footnotesize #1}}\n\n% For derivatives\n\\newcommand{\\deriv}[1]{\\frac{\\mathrm{d}}{\\mathrm{d}x} (#1)}\n\n% For partial derivatives\n\\newcommand{\\pderiv}[2]{\\frac{\\partial}{\\partial #1} (#2)}\n\n% Integral dx\n\\newcommand{\\dx}{\\mathrm{d}x}\n\n% Alias for the Solution section header\n\\newcommand{\\solution}{\\textbf{\\large Solution}}\n\n% Probability commands: Expectation, Variance, Covariance, Bias\n\\newcommand{\\E}{\\mathrm{E}}\n\\newcommand{\\Var}{\\mathrm{Var}}\n\\newcommand{\\Cov}{\\mathrm{Cov}}\n\\newcommand{\\Bias}{\\mathrm{Bias}}\n\n\\begin{document}\n\n\\maketitle\n\n%\\pagebreak\n\n\\begin{homeworkProblem}\n Give an appropriate positive constant \\(c\\) such that \\(f(n) \\leq c \\cdot\n g(n)\\) for all \\(n > 1\\).\n\n \\begin{enumerate}\n \\item \\(f(n) = n^2 + n + 1\\), \\(g(n) = 2n^3\\)\n \\item \\(f(n) = n\\sqrt{n} + n^2\\), \\(g(n) = n^2\\)\n \\item \\(f(n) = n^2 - n + 1\\), \\(g(n) = n^2 / 2\\)\n \\end{enumerate}\n\n \\textbf{Solution}\n\n We solve each solution algebraically to determine a possible constant\n \\(c\\).\n \\\\\n\n \\textbf{Part One}\n\n \\[\n \\begin{split}\n n^2 + n + 1 &=\n \\\\\n &\\leq n^2 + n^2 + n^2\n \\\\\n &= 3n^2\n \\\\\n &\\leq c \\cdot 2n^3\n \\end{split}\n \\]\n\n Thus a valid \\(c\\) could be when \\(c = 2\\).\n \\\\\n\n \\textbf{Part Two}\n\n \\[\n \\begin{split}\n n^2 + n\\sqrt{n} &=\n \\\\\n &= n^2 + n^{3/2}\n \\\\\n &\\leq n^2 + n^{4/2}\n \\\\\n &= n^2 + n^2\n \\\\\n &= 2n^2\n \\\\\n &\\leq c \\cdot n^2\n \\end{split}\n \\]\n\n Thus a valid \\(c\\) is \\(c = 2\\).\n \\\\\n\n \\textbf{Part Three}\n\n \\[\n \\begin{split}\n n^2 - n + 1 &=\n \\\\\n &\\leq n^2\n \\\\\n &\\leq c \\cdot n^2/2\n \\end{split}\n \\]\n\n Thus a valid \\(c\\) is \\(c = 2\\).\n\n\\end{homeworkProblem}\n\n\\pagebreak\n\n\\begin{homeworkProblem}\n Let \\(\\Sigma = \\{0, 1\\}\\). Construct a DFA \\(A\\) that recognizes the\n language that consists of all binary numbers that can be divided by 5.\n \\\\\n\n Let the state \\(q_k\\) indicate the remainder of \\(k\\) divided by 5. For\n example, the remainder of 2 would correlate to state \\(q_2\\) because \\(7\n \\mod 5 = 2\\).\n\n \\begin{figure}[h]\n \\centering\n \\begin{tikzpicture}[shorten >=1pt,node distance=2cm,on grid,auto]\n \\node[state, accepting, initial] (q_0) {$q_0$};\n \\node[state] (q_1) [right=of q_0] {$q_1$};\n \\node[state] (q_2) [right=of q_1] {$q_2$};\n \\node[state] (q_3) [right=of q_2] {$q_3$};\n \\node[state] (q_4) [right=of q_3] {$q_4$};\n \\path[->]\n (q_0)\n edge [loop above] node {0} (q_0)\n edge node {1} (q_1)\n (q_1)\n edge node {0} (q_2)\n edge [bend right=-30] node {1} (q_3)\n (q_2)\n edge [bend left] node {1} (q_0)\n edge [bend right=-30] node {0} (q_4)\n (q_3)\n edge node {1} (q_2)\n edge [bend left] node {0} (q_1)\n (q_4)\n edge node {0} (q_3)\n edge [loop below] node {1} (q_4);\n \\end{tikzpicture}\n \\caption{DFA, \\(A\\), this is really beautiful, ya know?}\n \\label{fig:multiple5}\n \\end{figure}\n\n \\textbf{Justification}\n \\\\\n\n Take a given binary number, \\(x\\). Since there are only two inputs to our\n state machine, \\(x\\) can either become \\(x0\\) or \\(x1\\). When a 0 comes\n into the state machine, it is the same as taking the binary number and\n multiplying it by two. When a 1 comes into the machine, it is the same as\n multipying by two and adding one.\n \\\\\n\n Using this knowledge, we can construct a transition table that tell us\n where to go:\n\n \\begin{table}[ht]\n \\centering\n \\begin{tabular}{c || c | c | c | c | c}\n & \\(x \\mod 5 = 0\\)\n & \\(x \\mod 5 = 1\\)\n & \\(x \\mod 5 = 2\\)\n & \\(x \\mod 5 = 3\\)\n & \\(x \\mod 5 = 4\\)\n \\\\\n \\hline\n \\(x0\\) & 0 & 2 & 4 & 1 & 3 \\\\\n \\(x1\\) & 1 & 3 & 0 & 2 & 4 \\\\\n \\end{tabular}\n \\end{table}\n\n Therefore on state \\(q_0\\) or (\\(x \\mod 5 = 0\\)), a transition line should\n go to state \\(q_0\\) for the input 0 and a line should go to state \\(q_1\\)\n for input 1. Continuing this gives us the Figure~\\ref{fig:multiple5}.\n\\end{homeworkProblem}\n\n\\begin{homeworkProblem}\n Write part of \\alg{Quick-Sort($list, start, end$)}\n\n \\begin{algorithm}[]\n \\begin{algorithmic}[1]\n \\Function{Quick-Sort}{$list, start, end$}\n \\If{$start \\geq end$}\n \\State{} \\Return{}\n \\EndIf{}\n \\State{} $mid \\gets \\Call{Partition}{list, start, end}$\n \\State{} \\Call{Quick-Sort}{$list, start, mid - 1$}\n \\State{} \\Call{Quick-Sort}{$list, mid + 1, end$}\n \\EndFunction{}\n \\end{algorithmic}\n \\caption{Start of QuickSort}\n \\end{algorithm}\n\\end{homeworkProblem}\n\n\\pagebreak\n\n\\begin{homeworkProblem}\n Suppose we would like to fit a straight line through the origin, i.e.,\n \\(Y_i = \\beta_1 x_i + e_i\\) with \\(i = 1, \\ldots, n\\), \\(\\E [e_i] = 0\\),\n and \\(\\Var [e_i] = \\sigma^2_e\\) and \\(\\Cov[e_i, e_j] = 0, \\forall i \\neq\n j\\).\n \\\\\n\n \\part\n\n Find the least squares esimator for \\(\\hat{\\beta_1}\\) for the slope\n \\(\\beta_1\\).\n \\\\\n\n \\solution\n\n To find the least squares estimator, we should minimize our Residual Sum\n of Squares, RSS:\n\n \\[\n \\begin{split}\n RSS &= \\sum_{i = 1}^{n} {(Y_i - \\hat{Y_i})}^2\n \\\\\n &= \\sum_{i = 1}^{n} {(Y_i - \\hat{\\beta_1} x_i)}^2\n \\end{split}\n \\]\n\n By taking the partial derivative in respect to \\(\\hat{\\beta_1}\\), we get:\n\n \\[\n \\pderiv{\n \\hat{\\beta_1}\n }{RSS}\n = -2 \\sum_{i = 1}^{n} {x_i (Y_i - \\hat{\\beta_1} x_i)}\n = 0\n \\]\n\n This gives us:\n\n \\[\n \\begin{split}\n \\sum_{i = 1}^{n} {x_i (Y_i - \\hat{\\beta_1} x_i)}\n &= \\sum_{i = 1}^{n} {x_i Y_i} - \\sum_{i = 1}^{n} \\hat{\\beta_1} x_i^2\n \\\\\n &= \\sum_{i = 1}^{n} {x_i Y_i} - \\hat{\\beta_1}\\sum_{i = 1}^{n} x_i^2\n \\end{split}\n \\]\n\n Solving for \\(\\hat{\\beta_1}\\) gives the final estimator for \\(\\beta_1\\):\n\n \\[\n \\begin{split}\n \\hat{\\beta_1}\n &= \\frac{\n \\sum {x_i Y_i}\n }{\n \\sum x_i^2\n }\n \\end{split}\n \\]\n\n \\pagebreak\n\n \\part\n\n Calculate the bias and the variance for the estimated slope\n \\(\\hat{\\beta_1}\\).\n \\\\\n\n \\solution\n\n For the bias, we need to calculate the expected value\n \\(\\E[\\hat{\\beta_1}]\\):\n\n \\[\n \\begin{split}\n \\E[\\hat{\\beta_1}]\n &= \\E \\left[ \\frac{\n \\sum {x_i Y_i}\n }{\n \\sum x_i^2\n }\\right]\n \\\\\n &= \\frac{\n \\sum {x_i \\E[Y_i]}\n }{\n \\sum x_i^2\n }\n \\\\\n &= \\frac{\n \\sum {x_i (\\beta_1 x_i)}\n }{\n \\sum x_i^2\n }\n \\\\\n &= \\frac{\n \\sum {x_i^2 \\beta_1}\n }{\n \\sum x_i^2\n }\n \\\\\n &= \\beta_1 \\frac{\n \\sum {x_i^2 \\beta_1}\n }{\n \\sum x_i^2\n }\n \\\\\n &= \\beta_1\n \\end{split}\n \\]\n\n Thus since our estimator's expected value is \\(\\beta_1\\), we can conclude\n that the bias of our estimator is 0.\n \\\\\n\n For the variance:\n\n \\[\n \\begin{split}\n \\Var[\\hat{\\beta_1}]\n &= \\Var \\left[ \\frac{\n \\sum {x_i Y_i}\n }{\n \\sum x_i^2\n }\\right]\n \\\\\n &=\n \\frac{\n \\sum {x_i^2}\n }{\n \\sum x_i^2 \\sum x_i^2\n } \\Var[Y_i]\n \\\\\n &=\n \\frac{\n \\sum {x_i^2}\n }{\n \\sum x_i^2 \\sum x_i^2\n } \\Var[Y_i]\n \\\\\n &=\n \\frac{\n 1\n }{\n \\sum x_i^2\n } \\Var[Y_i]\n \\\\\n &=\n \\frac{\n 1\n }{\n \\sum x_i^2\n } \\sigma^2\n \\\\\n &=\n \\frac{\n \\sigma^2\n }{\n \\sum x_i^2\n }\n \\end{split}\n \\]\n\n\\end{homeworkProblem}\n\n\\pagebreak\n\n\\begin{homeworkProblem}\n Prove a polynomial of degree \\(k\\), \\(a_kn^k + a_{k - 1}n^{k - 1} + \\hdots\n + a_1n^1 + a_0n^0\\) is a member of \\(\\Theta(n^k)\\) where \\(a_k \\hdots a_0\\)\n are nonnegative constants.\n\n \\begin{proof}\n To prove that \\(a_kn^k + a_{k - 1}n^{k - 1} + \\hdots + a_1n^1 +\n a_0n^0\\), we must show the following:\n\n \\[\n \\exists c_1 \\exists c_2 \\forall n \\geq n_0,\\ {c_1 \\cdot g(n) \\leq\n f(n) \\leq c_2 \\cdot g(n)}\n \\]\n\n For the first inequality, it is easy to see that it holds because no\n matter what the constants are, \\(n^k \\leq a_kn^k + a_{k - 1}n^{k - 1} +\n \\hdots + a_1n^1 + a_0n^0\\) even if \\(c_1 = 1\\) and \\(n_0 = 1\\). This\n is because \\(n^k \\leq c_1 \\cdot a_kn^k\\) for any nonnegative constant,\n \\(c_1\\) and \\(a_k\\).\n \\\\\n\n Taking the second inequality, we prove it in the following way.\n By summation, \\(\\sum\\limits_{i=0}^k a_i\\) will give us a new constant,\n \\(A\\). By taking this value of \\(A\\), we can then do the following:\n\n \\[\n \\begin{split}\n a_kn^k + a_{k - 1}n^{k - 1} + \\hdots + a_1n^1 + a_0n^0 &=\n \\\\\n &\\leq (a_k + a_{k - 1} \\hdots a_1 + a_0) \\cdot n^k\n \\\\\n &= A \\cdot n^k\n \\\\\n &\\leq c_2 \\cdot n^k\n \\end{split}\n \\]\n\n where \\(n_0 = 1\\) and \\(c_2 = A\\). \\(c_2\\) is just a constant. Thus the\n proof is complete.\n \\end{proof}\n\\end{homeworkProblem}\n\n\\pagebreak\n\n%\n% Non sequential homework problems\n%\n\n% Jump to problem 18\n\\begin{homeworkProblem}[18]\n Evaluate \\(\\sum_{k=1}^{5} k^2\\) and \\(\\sum_{k=1}^{5} (k - 1)^2\\).\n\\end{homeworkProblem}\n\n% Continue counting to 19\n\\begin{homeworkProblem}\n Find the derivative of \\(f(x) = x^4 + 3x^2 - 2\\)\n\\end{homeworkProblem}\n\n% Go back to where we left off\n\\begin{homeworkProblem}[6]\n Evaluate the integrals\n \\(\\int_0^1 (1 - x^2) \\dx\\)\n and\n \\(\\int_1^{\\infty} \\frac{1}{x^2} \\dx\\).\n\\end{homeworkProblem}\n\n\\end{document}\n", "meta": {"hexsha": "c949cd762f5d52f8b600c677b673ca66370cb5bd", "size": 13677, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "homework.tex", "max_stars_repo_name": "adivijaykumar/latex-homework-template", "max_stars_repo_head_hexsha": "aba269ee6d716931a2f4437d090cf1e2f1862f6c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "homework.tex", "max_issues_repo_name": "adivijaykumar/latex-homework-template", "max_issues_repo_head_hexsha": "aba269ee6d716931a2f4437d090cf1e2f1862f6c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "homework.tex", "max_forks_repo_name": "adivijaykumar/latex-homework-template", "max_forks_repo_head_hexsha": "aba269ee6d716931a2f4437d090cf1e2f1862f6c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.280961183, "max_line_length": 116, "alphanum_fraction": 0.5059589091, "num_tokens": 4478, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4804786631694601, "lm_q2_score": 0.34158248603300034, "lm_q1q2_score": 0.16412309625123678}} {"text": "\\documentstyle{article}\n\\begin{document}\n\n\\title{API for plane-waves in NWChem}\n\n\\author{Arthur Smith}\n\n\\date{\\today}\n\\maketitle\n\n\\section{General outline}\nThere are two general features of plane-wave basis sets which justify\na substantially different treatment from, for example, Gaussian basis\nsets. First, the basis set is not linked to the actual atomic positions,\nother than to the size of the periodic cell in which the atoms are contained,\n(in fact, for plane waves each individual basis element extends throughout\nthis cell). Second, the basis sets tend to be very large while calculations\ninvolving a single basis element (overlaps for example) are essentially\ntrivial, so the computational challenges differ considerably. For plane-wave\ndensity-functional theory with separable non-local pseudopotentials,\nall calculations can be accomplished in a time linear (or $N \\log(N)$) in\nthe basis-set size (there are further dependences on the number of atoms\nand orbitals, of course).\n\nBoth of these features (independence of atomic positions, and large\nsize with mostly trivial overlaps) can also be said to apply to\nother types of basis sets that we may wish to implement in the future: \npure real-space grid methods (the plane-wave technique already does\nmuch of the computation on a real-space grid), multi-grid methods,\nmixed-basis techniques, or even wavelets. I believe the API should\nbe designed in such a way that programmers will need to make only minimal\nmodifications to a higher-level application code in order to utilize\na new basis set when/if one becomes available.\n\n\\section{Pre-requisites}\n\nPlane-wave basis sets are only directly applicable to periodic systems -\nsolids in particular, although other systems can be readily treated\nby super-cell methods. Thus the application must have previously\nspecified a periodically repeated cell of some sort.\n\nIn addition,\nparticularly for relative small periodic cells, a collection of\nspecial {\\bf k}-points must be specified (selected according to the\ncell symmetry) which will be used to approximate the integration of\nquantities over the Brillouin zone of the cell with a weighted sum\nover these {\\bf k}-points.\n\nFor large systems or for molecules/clusters treated in the supercell\napproximation, it is often appropriate to just use the single point\n{\\bf k = 0}. In any case, the code should assume the {\\bf k}-points\nhave been previously specified.\n\n\\section{Handling the basis sets}\n\nThere is then a slightly different plane-wave basis set for each\n{\\bf k}-point, and another (usually larger one) for the charge density.\nThese are specified by the dimensions of the periodic\ncell of the system, and by some sort of cutoff - generally the requirement\nthat:\n\\begin{equation}\n\\hbar^2|{\\bf k + G}|^2/2m < E_{cut}\n\\end{equation}\nfor the wavefunction basis sets and:\n\\begin{equation}\n\\hbar^2 |{\\bf G}|^2/2m < d \\cdot E_{cut}\n\\end{equation}\nfor the charge density, where the parameter $d$ is between 1 and 4 and\ndetermines the degree to which the charge density completely reproduces \nall oscillations in the wavefunctions.\n\nThe reciprocal lattice vectors {\\bf G} are simply integer linear combinations\n\\begin{equation}\n{\\bf G}^{\\alpha} = n^{\\alpha}_1 {\\bf b}_1 + n^{\\alpha}_2 {\\bf b}_2 +\n\t\t\tn^{\\alpha}_3 {\\bf b}_3\n\\end{equation}\nof the fundamental reciprocal lattice vectors ${\\bf b}_i$, which satisfy\n\\begin{equation}\n{\\bf b}_i \\cdot {\\bf a}_j = 2 \\pi \\delta_{ij}\n\\end{equation}\nand where the ${\\bf a}_j$ are the fundamental lattice vectors specifying\nthe periodic cell of the system.\n\nThe {\\bf G} values used (and the corresponding $n^{\\alpha}_i$ triplets)\nare specified by spherical (ellipsoidal) regions surrounding the origin for\nthe charge density and {\\bf k = 0} wavefunctions, or by similar regions\nsurrounding points close to the origin for ${\\bf k} \\neq {\\bf 0}$.\n\nIn order to apply Fast-Fourier-Transform (FFT) techniques to allow\ntransformations between the plane-wave basis set and a real-space grid on\nwhich charge density and potential calculations are performed,\nthe triplets $n^{\\alpha}_i$ must be mapped to corresponding points in\na three-dimensional integer rectangular grid $N_1 \\times N_2 \\times N_3$.\nEach of the $N_i$ must be greater than twice the largest absolute value\nof all the $n_i$, and for most library FFTs must be a power of two. After\napplying the FFT, the resulting data is associated with a real-space grid\nat the points:\n\\begin{equation}\n{\\bf r}_{ijk} = {i \\over N_1} {\\bf a}_1 + {j \\over N_2} {\\bf a}_2 +\n\t\t{k \\over N_3} {\\bf a}_3\n\\end{equation}\n\nNote that the point i, j, k in the $N_1 \\times N_2 \\times N_3$ reciprocal\nspace array is associated with a triplet $n^{\\alpha}_l$ close to the\norigin as follows:\n\\begin{equation}\n{\\rm if\\ \\ } i < N_1/2 {\\rm\\ \\ then\\ \\ } n^{\\alpha}_1 = i\n\\end{equation}\n\\begin{equation}\n{\\rm if\\ \\ } i > N_1/2 {\\rm\\ \\ then\\ \\ } n^{\\alpha}_1 = i - N_1\n\\end{equation}\nand similarly for j and k.\n\n\n\\subsection{Data distribution}\nUtilizing these FFT methods, the application of the Hamiltonian to\na wavefunction involves diagonal operators or products of diagonal\noperators (see the section on applying H to $\\psi_i$ below). One\nnice aspect of a diagonal operator on a parallel computer is that\nhowever the vectors involved are distributed on the machine, application\nof the operator involves no communication (as long as the components\nof the operator itself are either distributed in the same way as the\nvectors, or are calculated when needed). In other words, calculation of\n\\begin{equation}\n\tg_i ({\\bf r}) = f({\\bf r}) \\psi_i({\\bf r})\n\\end{equation}\nis a local operation, no matter where the components $\\psi_i({\\bf r})$\nactually reside.\n\nHowever, communication {\\it is}\\ required during the FFT operations\nif $\\psi_i({\\bf r})/\\psi_i({\\bf G})$ is distributed in {\\bf r}/{\\bf G},\nand extensive communication\nis also required during orthogonalization and similar inner-product\noperations if $\\psi_i({\\bf r})/\\psi_i({\\bf G})$ is distributed in the\nindex $i$. In addition, since we are thinking of data-decomposition and not\ntask-decomposition here, steps must be taken to ensure that every\nprocess carries roughly the same number of coefficients $\\psi_i({\\bf G})$,\nwhich is best accomplished by some form of interleaving. Note that\n$\\psi_i({\\bf r})$ will naturally be evenly distributed in {\\bf r} under most\ndecompositions because the {\\bf r} lie on a rectangular grid, while\nthe relevant {\\bf G} values lie within a sphere, for which block\ndecompositions may leave some processors with few or no {\\bf G}-vectors.\n\nA further complication in the {\\bf k = 0} situation is that the\ncoefficients for {\\bf G} and {\\bf -G} are complex conjugates, and therefore\nnearly a factor of two in memory and speed can be gained by keeping only\none of the two coefficients. But that means in the data decomposition,\n{\\bf G} and {\\bf -G} should be covered by the same process, requiring\na reversed interleaving for negative values of the $n_i$.\n\n\\subsection{The initialization API}\nThus the fundamental information needed to initialize a particular plane-wave\nbasis set is:\n\\begin{enumerate}\n\\item The periodic cell vectors ${\\bf a}_i$\n\\item The {\\bf k}-vectors used.\n\\item The energy cutoff $E_{cut}$\n\\item The charge density basis parameter $d$.\n\\item Some information about number of processes, preferred data\ndecomposition, and possibly process communication topology, in order\nto determine the distribution of G and R vectors among nodes.\n\\item Preferred values of $N_1, N_2, N_3$ (optional)\n\\item The vectors ${\\bf b}_i$ (optional - might be useful\nfor modularization).\n\\end{enumerate}\n\nReturned from the initialization will be:\n\\begin{enumerate}\n\\item The size of the basis set for each k-point, and for the charge\ndensity, including total size, and number allocated to this process.\n\\item Some form of listing of the G-vectors: at least the $n^{\\alpha}_i$,\npreferably also the actual vectors {\\bf G} and their (squared?) magnitudes.\n\\item The output values of $N_1, N_2, N_3$ for the whole space and\nfor the sub-blocks (or other arrangement) allocated to this process.\n\\item Optionally, the ${\\bf b}_i$ vectors.\n\\end{enumerate}\n\n\\subsection{The allocation API}\nTypically, we'll be allocating some number $n_{orbitals}$ of\ncomplex coefficients of the $ng({\\bf k})$ plane waves for each of\nthe {\\bf k}. In addition, there will be several auxiliary arrays\nindividually of approximate size $ng$, including arrays to handle\nthe charge density and components of the potential. And we also need\na few complex and real arrays on the $N_1\\times N_2 \\times N_3$\nreal-space grid.\n\nThese would presumably be allocated with GA routines or something\nsimilar - for example in our hybrid decomposition approach, the first\nset of coefficient arrays would be distributed across all the processors. The\nsecond set, of auxiliary arrays, would be distributed across the processors\nwithin a group (the spatial decomposition subgroups) but duplicated (sometimes\nwith identical data) in all such groups, in order to eliminate all\ncommunications except during FFT and orthogonalization (and global operation)\nroutines.\n\nInputs then to an allocator would be:\n\\begin{enumerate}\n\\item A tag specifying the basis set (previously initialized).\n\\item The data type of the coefficients (real or complex, or something else?)\n\\item The number of ($ng$ arrays) of this type to be\nallocated ($n_{orbitals}$ for example.\n\\item Optionally: A flag indicating whether the data should be\ninitialized with random values or with zeroes.\n\\end{enumerate}\n\nOutput would be a tag specifying the coefficient matrix, similar to\nGA matrix allocation, maybe?\n\n\\subsection{API for basis set operations}\n\nOnce we have the basis set specifications, there are a number of\noperations we'll need to do anything with them:\n\\begin{enumerate}\n\\item Copy\n\\item Scale or AXPY\n\\item application of a diagonal operator (GBMV?)\n\\item Inner product\n\\item Send and receive, or get and put to a different process\n\\item Transformation between basis sets\n\\item Computation of basis set overlaps for different basis sets\n\\end{enumerate}\n\nMost of these are straightforward: probably only the last two\nwill require much thought. We'll want to do more complicated\nthings with the charge density (at least in calculation of\nthe exchange-correlation energy), but that is probably a special\ncase that can be dealt with separately.\n\nThere are a couple of transformations between basis sets we\nmight want to consider implementing initially: within a G-space\nrepresentation, changing form one cutoff energy to a different\none is trivial in principle (just chop, or zero-pad) but\nnot necessarily in practice where reading in a starting configuration\nfrom an old basis set may misplace coefficients if you are not\ncareful (we have not yet successfully implemented this using\nour current code, for example). Transformations between G-space and\nreal-space are essential to computation of the charge density and\nevaluation of the real-space potentials, and this can be viewed\nas one kind of general basis-set transformation (implemented\nthrough fast Fourier transforms).\n\nI think computation of overlaps will not be necessary until\nmixed Gaussian and plane-wave bases are being considered, but\nit might be worth-while thinking about how to do it now.\n\n\\section{Applying H to $\\psi_i$}\n\nWe can use various minimization techniques to isolate the\nlowest $n_{occupied}$ eigenstates of H. Because $ng$ is so much\nlarger, we never want to construct the full $ng\\times ng$ matrix,\nso most of these techniques start from the residual\n\\begin{equation}\nH \\psi_i - \\epsilon_i \\psi_i.\n\\end{equation}\nand the most computationally intensive part of the code is\ngoing to be evaluation of the Hamiltonian-vector product H$\\psi_i$.\n\n\\subsection{Kinetic energy}\n\nThe kinetic energy operator is evaluated in the reciprocal space\nrepresentation:\n\\begin{equation}\nT \\psi_i({\\bf G}) = {\\hbar^2|{\\bf k + G}|^2 \\over 2m} \\psi_i({\\bf G})\n\\end{equation}\n\nThe values of $|{\\bf k + G}|^2$ should be pre-stored (possibly\nreturned from the initialization routine above) and so this is\na straightforward operation. However, since this is peculiar to\nthe plane-wave basis, it might be a good idea to define a kinetic\nenergy API (for example, for pure real-space grids, the kinetic energy\ncould be evaluated using finite-difference techniques). For such\nan API the input is a basis-set specifier and the coefficient matrix\n(with an integer specifying how many orbitals to work on at once)\nand output is the matrix of result vectors (placed in a work area provided).\n\n\\subsection{The real-space potentials}\n\nThese are comprised of the local pseudopotential, the Hartree\n(electron-electron Coulomb) potential and the exchange-correlation potential.\nThe potentials themselves are evaluated as follows:\n\\begin{equation}\nV_{local}({\\bf G}) = \\sum_{is} u_{is}({\\bf G}) S_{is}({\\bf G})\n\\end{equation}\nwhere $is$ is an index counting the atomic species in the system,\n$u_{is}$ is the potential from a single atom of this species, and\n$S_{is}$ is a structure factor for the species:\n\\begin{equation}\nS_{is}({\\bf G}) = \\sum_{ia} \\exp(i {\\bf G}\\cdot {\\bf r}_{ia})\n\\end{equation}\nwhere $ia$ runs over all atoms of species $is$. $u_{is}$ and $S_{is}$\nwould be distributed in the same fashion as the {\\bf G}'s, but with\nall species $is$ together (not distributed), and so duplicated\nin the same fashion as $V_{local}({\\bf G})$ itself: among processes with the\nsame {\\bf G}'s but different collections of orbitals. So this computation\ninvolves no communication, except for the FFT required in the end\nto produce a real-space potential.\n\nThe electron-electron direct Coulomb interaction is easily evaluated:\n\\begin{equation}\nV_{Hartree}({\\bf G}) = 4\\pi \\rho(G)/G^2\n\\end{equation}\nexcept for ${\\bf G} = {\\bf 0}$ where the corresponding term is\na constant that is added to the constant electrostatic energy of the\nperiodic system usually evaluated by Ewald summation. Similarly, the\nonly communication required here is the final FFT, although there\nwill be duplication if the orbitals are distributed.\n\nBoth $V_{local}$ and $V_{Hartree}$ are then FFT'd to real space, and\ncan be added to the exchange correlation potential:\n\\begin{equation}\nV_{xc}({\\bf r}) = V_{xc}(\\rho({\\bf r}), \\nabla \\rho({\\bf r}), ...)\n\\end{equation}\nwhich requires no communication at all, except in the\nevaluation of the charge density and gradients:\n\nThe charge density $\\rho({\\bf r})$ is calculated as the sum\n\\begin{equation}\n\\rho({\\bf r}) = \\sum_{i} |\\psi_i({\\bf r})|^2\n\\end{equation}\nand the gradient is:\n\\begin{equation}\n\\nabla\\rho({\\bf r}) = FFT \\bigl\\{ i {\\bf G} \\rho({\\bf G}) \\bigr\\}\n\\end{equation}\nand similarly for higher derivatives.\n\nThe duplication discussed could be eliminated at the expense of\nmore communication: we should probably study this at some point. In\nparticular since the gradient-dependent exchange correlation potential \ncannot be done by table-lookup (because it depends on more than one\nparameter, unlike the LDA) the computation involved may be sufficient\nto justify distributing it.\n\nAn API for a set of subroutine calls to evaluate these potentials\nseems appropriate - what is needed on input is quite a variety of\nthings: for the charge density calculation we probably want to\npass the basis set information and the G-space coefficient matrix,\nand the output would be either the charge density on the real-space\ngrid, or else the fitted charge-density in G-space (or both).\nFor the local potential we need to pass in geometry information and\ninformation about the pseudopotential, as well as the basis set - output\nis the G-space representation of that potential. For the Hartree potential\nwe pass in the charge density and basis set info, output is the G-space\npotential. For the gradients calculation pass in the G-space charge\ndensity, return the real-space charge density and gradients to be\npassed to an exchange-correlation subroutine, or else just return the\nreal-space exchange-correlation potential.\n\nWe also need an initialization API for the pseudopotential to\ngenerate the $u_{is}({\\bf G})$, and\nfor the exchange-correlation potentials (at least to allow\nchoices between the possibilities, and also possibly to allow\nsetting some of their parameters). More on the pseudopotential below...\n\n\\subsection{The non-local pseudopotential}\nUsing the Kleinman-Bylander separable decomposition, the non-local\npseudopotential (for each species $is$!) can be evaluated in\nreciprocal space as follows (from memory, so bear with me if I\nmissed a minus sign or something):\n\\begin{eqnarray}\nV_{nl}^{lm} \\psi_i ({\\bf G}) = C^l\n\t\t&\\sum_{ia} U_{nl}^l({\\bf k+G})Y_{lm}^*({\\bf k + G})\n\t\t\\exp(i {\\bf G}\\cdot{\\bf r}_{ia}) \\cdot \\cr\n\t\t&\\sum_{{\\bf G}'} U_{nl}^l({\\bf k + G}')Y_{lm}({\\bf k + G}')\n\t\t\\exp(-i {\\bf G}'\\cdot{\\bf r}_{ia})\n\t\t\\psi_i({\\bf G}')\\cr\n\\end{eqnarray}\nwhere $ia$ is an index over all the atoms of species $is$, and $l$, $m$ are\nstandard angular momentum quantum numbers. The $U_{nl}^l$ and $Y_{lm}$\ncan be computed at initialization and are $O(N)$ in size so not too bad.\nThis would then be summed over $l$, $m$, and species $is$.\n\nOne big potential problem data and\ncommunication-wise here is the $\\exp(i {\\bf G}\\cdot {\\bf r}_{ia})$ matrix,\nwhich if precomputed and stored is $O(N^2)$ in size, and yet needs to be present\nfor {\\bf all} the orbitals (note that non-local calculation is an $O(N^3)$\noperation and thus one of the major time-consuming parts of the computation\nfor large systems). What we do is evaluate the matrix only for {\\bf G}\nvectors along the principal axes ${\\bf b}_i$, and then compute the product\nof three complex numbers to get the final value when needed - this means\nwe need to only store a matrix $O(N^{4/3})$ in size, but we need to\nensure the correct sort of data-locality for that matrix.\n\nThere are other ways of doing the nonlocal pseudopotentials: real-space only\nevaluations for example, or taking advantage of possible redundancy if a part\nof the system has a shorter periodicity (for example, the bulk portion of\na surface problem) or other symmetry, or using complicated hybrids like\nthe ultra-soft Vanderbilt pseudopotentials, and presumably other methods\nwill come along.\n\nSo I think two (or possibly three) subroutine calls would be involved\nthat could be standardized on: initialization of the pseudopotential\n(calculation of the $U_{nl}({\\bf k+ G})$ and local $u({\\bf G})$ values)\nand of other needed quantities ($Y_{lm}({\\bf k + G})$ and the\n$\\exp(i {\\bf G}\\cdot {\\bf r}_{ia})$ matrix); and application of\nthe pseudopotential to a set of orbitals (either with an ion force\ncalculation, or with forces calculated separately).\n\n\\subsection{Dealing with the pseudopotentials}\n\nThere may be several types of pseudopotentials we would want to\nhandle - for example, it might be worth testing the Gaussian-derived\nECP's with plane waves (maybe not?) Anyway, we must initially\nread in some representation of the pseudopotentials about each species\nof atom in the system, and the input format we currently use most\noften is a simple radial grid. These then need to be converted to\nthe local $u({\\bf G})$ and nonlocal $U_{nl}({\\bf k+G})$ forms needed in\nthe actual application of the pseudopotentials.\n\nThus there needs to be some specification of the input representation\nof the pseudopotentials, and an initialization routine for converting\nthat representation to one appropriate for the basis set. The associated\nAPI would have as input the input representation and specification\nof the (plane-wave) basis set, and as output the converted pseudopotential\nvalues.\n\n\\section{Achieving self-consistency}\n\nWith plane-wave basis sets the central problem of converging to\na self-consistent charge-density (represented by a collection of\noccupied Kohn-Sham eigenfunctions) is fundamentally the same as for\ndensity functional theory with other basis sets. However, the principal\nconstraint imposed by the large size of the plane-wave basis set is\nthat we never know the full matrix $H$, only matrix-vector products\n$H \\psi_i$, meaning that direct diagonalization cannot be performed,\nand instead iterative approaches are needed. In addition, of course,\n$H$ itself changes with each iteration because the charge density\nis changing. Among a wide variety of possibilities there are basically\ntwo iterative schemes that have become adopted in plane-wave basis-set\nmethods: Car-Parrinello ``molecular-dynamics'' type iterations, and\nTeter-Payne-Allen preconditioned gradient iterations (often\nmisnamed ``conjugate gradient'' iterations because the first implementation\nhappened to use a multiple conjugate gradients updating scheme that\nhas since proved inefficient compared to just using a single preconditioned\ngradient).\n\nThe Car-Parrinello approach is to treat the energy gradient $H\\psi$ as\na force on the coefficients of $\\psi$, so that in a ``time-step'' $\\tau$,\n\\begin{equation}\n\\psi_i(t + \\tau) = \\psi_i(\\tau) - {\\tau^2 \\over 2 m_{eff}} H\\psi_i(tau),\n\\end{equation}\nafter which the new $\\psi_i$ are orthogonalized to one another.\nWhen doing real dynamics a velocity term may also be included - as stated\nthis is effectively just a steepest-descents algorithm. As such it\nis simple but rather inefficient for getting self-consistency, but\non the other hand it is rather robust (always converging to the lowest\noccupied subspace, if you wait long enough) and in fact when coupled\nwith atomic dynamics can be competitive with the Born-Oppenheimer\napproach required when using the preconditioned gradient methods.\n\nThe preconditioned gradient methods have the following iterative step:\n\\begin{enumerate}\n\\item Generate residual vectors: $ R_i = (H - \\epsilon_i) \\psi_i$\n\\item Apply a preconditioner: $B_i = P R_i$. As with the\nDavidson method, the preconditioner should be close to an inverse\nof the Hamiltonian. In practice, a rational function of the kinetic\nenergy (approaching 1/K.E. for high energy) works well with a\nplane-wave basis set.\n\\item Orthogonalize the $B$'s to one another and to the $\\psi's$.\n\\item Generate $ H B_i $ and the subspace matrix $ $ where\n$V_i$ is $\\psi_i$ for $i < n$ and $B_{i - n}$ for $i >= n$.\n\\item Diagonalize within the subspace, and let the new $\\psi$ vectors\nbe the lowest $n$ eigenvectors.\n\\item Generate the new charge density (generally by mixing in some\nof the old, otherwise instabilities arise) and the resulting new\nHamiltonian, and repeat.\n\\end{enumerate}\nThese methods (there are variants based on whether you let $n = 1$ and\nhave an outer loop over bands, or else let $n =$ all states, or else\nwith different preconditioners) tend to be much faster than the\nsteepest-descent approach to obtain a self-consistent set of electronic\nstates. On the other hand they require more computation per step\n(twice as many Hamiltonian-vector operations, for example) and experience\nshows they tend to be less robust.\n\nBoth methods could be implemented with no knowledge of the\nunderlying basis sets or data decomposition, as long as the\nfollowing subroutine calls were available:\n\\begin{enumerate}\n\\item Application of $H$ to $\\psi$-type vectors\n\\item Application of a preconditioner to $\\psi$-type vectors\n\\item AXPY operations on $\\psi$-type vectors and $\\rho$-type vectors\n\\item Inner products on $\\psi$-type vectors (at least for\ngenerating the $$ matrix, possibly also for orthogonalization unless\nthat was a separate subroutine call)\n\\item Generating $\\rho$ from $\\psi_i$, and modifying $V_{xc}$ and $V_{Hartree}$\naccordingly, to complete the self-consistent loop.\n\\end{enumerate}\nIn addition, a diagonalization routine for $2 n\\times 2 n$ matrices is\nneeded, and probably should be done in parallel in accordance with\nthe orbital decomposition of the data.\n\n\\section{Energy and forces}\n\nAt the highest level, an API that calls on the electronic\nenergy minimization to generate the energy and forces for a particular\nconfiguration of atoms might be workable, and would certainly be\nuseful. This would facilitate rapid comparison of different methods\nfor a particular problem, in addition to providing a natural interface\nfor standard molecular dynamics codes.\n\nInput to such a high level API would include:\n\\begin{enumerate}\n\\item Geometry - atomic configuration\n\\item Basis set, pseudopotential specifications (data decomp?)\n\\item (Optionally) Trial set of orbitals\n\\item Convergence parameters: iteration method, maximum number of\niterations, tolerance on the final numbers\n\\end{enumerate}\n\nOutput would of course be energy and forces, as well as\n(optionally) a final set of orbitals for restarting, and a flag\nspecifying whether the convergence tolerance was actually reached.\n\nIn addition, I think it would be important to have callable\nroutines that estimate (or at least keep track of) memory usage\nand time per iteration, to allow analysis of resource utilization\nby the calling program. To do the estimate means having some kind\nof performance model of the code - we do already have such a thing\nfor the memory usage, but have never tried it for timing...\n\n\\end{document}\n\\bye\n", "meta": {"hexsha": "2d4f57e44c875128e9f25a60cbdf28578bededbb", "size": 25080, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/plnwv_API.tex", "max_stars_repo_name": "dinisAbranches/nwchem", "max_stars_repo_head_hexsha": "21cb07ff634475600ab687882652b823cad8c0cd", "max_stars_repo_licenses": ["ECL-2.0"], "max_stars_count": 317, "max_stars_repo_stars_event_min_datetime": "2017-11-20T21:29:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T11:48:24.000Z", "max_issues_repo_path": "doc/plnwv_API.tex", "max_issues_repo_name": "dinisAbranches/nwchem", "max_issues_repo_head_hexsha": "21cb07ff634475600ab687882652b823cad8c0cd", "max_issues_repo_licenses": ["ECL-2.0"], "max_issues_count": 356, "max_issues_repo_issues_event_min_datetime": "2017-12-05T01:38:12.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T02:28:21.000Z", "max_forks_repo_path": "doc/plnwv_API.tex", "max_forks_repo_name": "dinisAbranches/nwchem", "max_forks_repo_head_hexsha": "21cb07ff634475600ab687882652b823cad8c0cd", "max_forks_repo_licenses": ["ECL-2.0"], "max_forks_count": 135, "max_forks_repo_forks_event_min_datetime": "2017-11-19T18:36:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T02:28:49.000Z", "avg_line_length": 47.9541108987, "max_line_length": 80, "alphanum_fraction": 0.7718500797, "num_tokens": 6193, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.29746994883293104, "lm_q1q2_score": 0.1637891448528029}} {"text": "\\chapter{The Theory of Alignment}\r\n\\label{sec:alignTheory}\r\n\r\nWhenever a new detector is built, people are careful to mount it as close to the correct location as they can. In order to check this, survey measurements are\r\nperformed to check the position with a precision of $\\SI{100}{\\micro\\metre}$.\r\nTo achieve an even greater precision, \\textit{software alignment} is performed.\r\n\r\nThe reason why alignment is of great importance is that a misaligned detector\r\nyields worse momentum resolutions, low reconstruction efficiencies and biased mass estimations and mass peak resolutions.\r\nThe most prominent area of misalignment for a spectrometer are asymmetries.\r\nIn general, asymmetries in data, including unexpected trigger inefficiencies, can be reduced when the misalignment is found and corrected.\r\n% references\r\n\r\n\\section{Clustering of SciFi hits}\r\n\\label{sec:clustering}\r\n\r\nThe signals generated by the SiPMs are read out by a specifically developed integrated circuit, the \\textit{PACIFIC}\\footnote{(low Power Asic for the sCIntillating Fibres traCker}\\cite{readout}.\r\nIt performs the shaping, integration and digitization of the signal. An effect called spillover caused by the propagation delay of photons inside the fibres and the recovery time of the SiPMs. This leads to the signal not being completely inside of its 25-ns timeslot for the bunch crossing. The \\textit{PACIFIC} shapes the signal from the SiPM to reduce the spillover and suppress the signal tails\\cite{techreport}. Afterwards, the signal is integrated over the 25-ns timeslot and a 2-bit analog-digital converter (ADC) digitizes the signal.\r\nThree comparators implement the ADC and can be set individually for each channel, as seen in figure \\ref{fig:pac}.\r\n\r\n\\begin{figure}\r\n \\centering\r\n \\includegraphics[width=0.8\\textwidth]{plots/pacific.png}\r\n \\caption{Figure of the PACIFIC chip. From left to right, an amplifier, a shaper and an integrator are build in. The Signal the is digitized and the Clustering is performed to the 2-bit output on the far right.}\r\n \\label{fig:pac}\r\n\\end{figure}\r\n\r\nTo achieve a reduction in data rate and suppress the signal noise, clusterization is performed. A diagram of the clusterization is shown in Figure \\ref{fig:tikz_cluster}\r\n\r\n\\input{plots/clusters.tex}\r\n\r\nDuring the digitization the specific thresholds are set. The second comparator sets the \\textit{seeding threshold} which marks channels exceeding said threshold as cluster candidates. Up to three more neighboring channels can be added to the cluster if they pass the threshold set by the first comparator (\\textit{neighboring threshold}).\r\nThe third comparator sets the \\textit{high threshold}. A cluster can be form by just one channel if it exceeds this threshold.\r\nThe cluster position is the weighted mean of the contributing channels to this cluster. The cluster resolution can be better than $\\SI{100}{\\micro\\metre}$ \\cite{techreport}. In the next section, the way that clusters are combined to reconstruct tracks is described.\r\n\r\n\\section{Track Reconstruction}\r\n\\label{sec:kalman}\r\n\r\nIn order for LHCb to be used for physics, all of the detector hit information has to be converted into tracks, which is a challenging task.\r\nThe track reconstruction algorithm needs to find the correct hits from each sub detector to build the track. This can be problematic just because of the amount of tracks per event (roughly 100).\r\nThe aim is to have the track efficiency as high as possible. in order to estimate the track parameters, such as the curvature parameter and track slopes ($t_x$, $t_y$), as accurately as possible.\r\nA good track fit is needed in order to find to best estimates for the track parameters and covariances. The estimates are used in the event reconstruction to find the correct tracks for each particle and the decay products. The information provided is used in the RICH rings, ECAL and HCAL and muon detectors. With these information, particle and track parameters such as the invariant mass can be measured and vertex origins of particle decays can be found.\r\nThere are several track models that can be used. In general, a track is built from numerous segments which are either straight or curved because of an active magnetic field. Depending on the environment of the track either model is good.\r\nThe track segments are called track states and are defined by a position in $x$ and $y$ at a given distance $z$ where the hit was located, then a slopes $t_{x,y}$ at the hit position and a momentum parameter obtained from the track curvature inside the magnetic field\\cite{VanTilburg}.\r\n\r\nIn order to correctly reconstruct the track it is important to know where the hit is localized and for the upcoming hits, where to particle track came from. From the momentum measurement of the track curvature caused by the magnetic field, the parameter $q/p$ is also added where $q$ stands for the charge of the track that is determined from the direction into which of the track bends.\r\n\r\n\\begin{align*}\r\n \\vec{r} = \\left(\\begin{array}{c} x \\\\ y \\\\ t_x \\\\ t_y \\\\ \\frac{q}{p}\\end{array}\\right) &\\,\\, t_x = \\frac{\\partial x}{\\partial z} & t_y = \\frac{\\partial y}{\\partial z}\r\n\\end{align*}\r\n\r\nThe uncertainty of the five-component state vector is a $5\\times5$ covariance matrix $C$.\r\nA track state can be anywhere on the trajectory but is easier to choose it at real detection points. Combining the track state with a real measurement point is called \\textit{node}.\r\nThe propagation from node $k-1$ to node $k$ is described by a propagation function\r\n\r\n\\begin{equation*}\r\n \\vec{r}_k = f_k(\\vec{r}_{k_{-1}}) + \\vec{w}_k\\,.\r\n\\end{equation*}\r\n\r\nThis means node $k$ is acquired by propagating node $k-1$ through the propagation function $f_k$ and shifting it by the \\textit{process noise} $\\vec{w}_k$.\r\n\r\nLHCb uses process noise to model the scattering caused by particle interactions with the detector material.\r\nDepending on the type of propagation, linear or curved, a different propagation function is used.\r\nfor a linear extrapolation, $f_k$ results in\r\n\\begin{equation*}\r\n f_k \\left(\\vec{r}_{k-1}\\right) = F_k \\vec{r}_{k-1}\r\n\\end{equation*}\r\nwith the transport matrix $F_k$\r\n\\begin{gather*}\r\n F_K = \\begin{pmatrix}\r\n 1 & 0 & \\Delta z & 0 & 0 \\\\\r\n 0 & 1 & 0 & \\Delta z & 0 \\\\\r\n 0 & 0 & 1 & 0 & 0 \\\\\r\n 0 & 0 & 0 & 1 & 0 \\\\\r\n 0 & 0 & 0 & 0 & 1 \\\\\r\n \\end{pmatrix}\r\n\\end{gather*}\r\nand $\\Delta z$ being the difference in z between the nodes\r\n\\begin{equation*}\r\n \\Delta z = z_k - z_{k-1}\r\n\\end{equation*}\r\n\r\nTrajectory information for each node is provided by the real measurement where the relation between measurement $m_k$ and track state at a given node $k$ is defined as\r\n\r\n\\begin{equation*}\r\n m_k = h_k(\\vec{r}_k) + \\epsilon_k\r\n\\end{equation*}\r\n\r\nwith the projection function $h_k$ and \\textit{measurement noise} $\\epsilon_k$.\r\nSo if the detector only measures the $y$ coordinate of state, the projection function\r\nwill be\r\n\\begin{equation*}\r\n h_k(\\vec{r}_k) = H_k \\vec{r}_k\r\n\\end{equation*}\r\nwith\r\n\\begin{gather*}\r\n H_k = \\begin{pmatrix}\r\n 0 & 1 & 0 & 0 & 0 \\\\\r\n \\end{pmatrix}\\,.\r\n\\end{gather*}\r\n\r\nWhen measuring more parameters the measurement matrix $H_k$ and projection matrix have dimension $n\\times5$ with $n$ being the numbers of parameters measured.\r\n\r\nWith this track model, $\\epsilon_k$ and $w_k$ are random and unknown and have an expectation value of zero.\r\n\r\n\\section{The Kalman filter method}\r\nIn general a track is an ensemble of measurements and track states and the Kalman filter method\\cite{VanTilburg} is used to fit tracks.\r\nThe idea of the Kalman filter is, to have a starting node and add measurements one by one. In between the addition of measurements, the local track state is updated with the new information.\r\nThe Kalman filter method is a $\\chi^2$ minimising problem for the measurement of the track. Because of the iterative nature of the method, it is fast and also used in other fields than physics, for example GPS and meteorology.\r\nThe three steps of the Kalman filter will be briefly outlined and later described in further detail.\r\n\r\nThe first step is the $\\symbf{Prediction}$: The next track state of the trajectory is predicted based on the track state at the previous node.\r\nThe second step is the $\\symbf{Filter}$ procedure: By using filter equations, the prediction is updated with measurement information in this node. The prediction and filter are repeated for each measurement. With more measurements added, the estimate for the best trajectory is the track state after each filter step.\r\nThe final step is called $\\symbf{Smoother}$: When the trajectory is complete, smoother equations are applied from the last node to the previous node. Therefore the information from all measurements is used in both forward- and back-propagation which results in a more\r\ndefined track.\r\n\r\n\\subsection{First Step: Prediction}\r\nFor a given state vector at node \\textit{k-1}, the prediction for the $k^{\\text{th}}$ state vector and its covariance matrix results from the propagation relations\r\n\r\n\\begin{align*}\r\n \\vec{r}_p^{k-1} &= f_p\\left( \\vec{r}_{k-1} \\right) \\\\\r\n \\text{Cov}_k^{k-1} &= F_k C_{k-1} F_k^T + Q_k\r\n\\end{align*}\r\n\r\nThe superscript of the state vector shows the amount of information used in the estimate.\r\nThat means $\\vec{r}_k^n$ is the smoothed state vector which used all information,\r\n$\\vec{r}_k^k-1$ is the predicted state vector and $\\vec{r}_k^k \\equiv \\vec{r}_k$ is the filtered state.\r\n\r\n$Q_k$ is the process noise in matrix form and it is part of the predicted\r\ncovariance matrix $C_k^{k-1}$.\r\nBecause the first state cannot take measurements from the previous state, an initial prediction is taken from the track finding algorithm instead.\r\nThe predicted residual between the measurement, $m_k$ and the state vector results in\r\n\\begin{equation*}\r\n \\text{res}_k^{k-1} = m_k - h_k\\left( \\vec{r}_k^{k-1} \\right)\r\n\\end{equation*}\r\nand the corresponding covariance matrix is defined as\r\n\\begin{equation*}\r\n \\text{Cov}_{\\text{res},k}^{k-1} = V_k + H_k C_k^{k-1} H_k^T\\,.\r\n\\end{equation*}\r\n\r\nHere, $V_k$ is the measurement variance. With these metrics the minimal $\\chi^2$ for the optimal track states can be calculated via\r\n\\begin{equation*}\r\n \\left( \\chi^2 \\right)_k^{k-1} =\r\n \\text{res}_k^{k-1} \\left(\\text{Cov}_{\\text{res},k}^{k-1}\\right)^{-1} \\text{res}_k^{k-1}\r\n\\end{equation*}\r\n\r\n\\subsection{Second Step: Filter}\r\nDuring the filter step, the track state is updated with the measurement information.\r\nIteratively, each measurement is added and the filtered state $\\vec{r}_k$ and the corresponding covariance matrix is calculated via\r\n\\begin{align*}\r\n \\vec{r}_k &= \\vec{r}_k^{k-1} + G_p \\text{res}+k^{k-1} \\\\\r\n \\text{Cov}_k &= \\left(\\mathbb{1} - G_k H_k\\right) \\text{Cov}_k^{k-1}\\,,\r\n\\end{align*}\r\nwhere $G_k$ is the gain matrix of dimension $5\\times1$ and is defined as\r\n\\begin{equation*}\r\n G_k = C_k^{k-1} H_k^T \\left( \\text{Cov}_{\\text{res},k}^{k-1} \\right)^{-1}\r\n\\end{equation*}\r\n\r\nAfterwards the residuals and its covariance matrix are calculated and the filtered total $\\chi^2$ is defined as\r\n\\begin{equation*}\r\n \\left( \\chi^2_{\\text{filter}} \\right)_k = \\text{res}_k \\text{Cov}_{\\text{res},k}^{-1} \\text{res}_k\\,.\r\n\\end{equation*}\r\n\r\nThe prediction and filter procedure is continued for all measurements until the track is fully reconstructed.\r\nBecause the last node at $k \\, = \\, n$ has the most information in it, a backward update is performed to infuse the previous nodes with the same information as in last node.\r\nThis is called \\textit{smoother}-step.\r\n\r\n\\subsection{Third Step: Smoother}\r\nThe smoother function returns the best possible estimate for track states at\r\nthe previous nodes. The method used is called \\textit{Rauch-Tung-Striebel}-smoother\\cite{RTS}.\r\nThe idea is to use backward information and construct a smoothed state vector and covariance matrix\r\n\\begin{align*}\r\n \\tilde{r}_k^n &= \\vec{r}_k + S_k \\left( \\vec{r}_{k+1}^n - \\vec{r}_{k+1}^k \\right) \\\\\r\n \\tilde{C}_k^n &= C_k\r\n\\end{align*}\r\nand the Smoother-matrix $S_k$ of dimension $5\\times5$\r\n\\begin{equation*}\r\n S_k = C_k F_{k+1}^T \\left( C_{k+1}^p \\right)^{-1}\\,.\r\n\\end{equation*}\r\n\r\nIn order to calculate the smoothed $\\chi^2$ the residual and corresponding covariance matrix are\r\n\\begin{align*}\r\n \\text{res}_k &= m_k - h_k \\vec{h}_k^n \\\\\r\n \\text{Cov}_{\\text{res},k}^n &= V_k - H_k C_k^n H_k^T\r\n\\end{align*}\r\n\r\nThe $\\chi^2$ is calculated analogously to the one during the filter step with the difference being the new residuals and covariances.\r\n\r\n\\section{Alignment with Kalman filter track fit}\r\n\\label{sec:derivatives}\r\n\r\nIn principle, minimizing the track residuals is the obvious way to align a detector.\r\nThe residual $\\vec{\\text{res}}_k$ is defined by the difference between a real detector hit and the expected hit position\r\n\r\n\\begin{equation}\r\n \\text{res}_k = m_k - h_k(\\vec{r},\\vec{\\alpha})\r\n\\end{equation}\r\n\r\nwhere $\\symbf{h}$ is the measurement model, $\\vec{r}$ are the track parameters and $\\vec{\\alpha}$ are the alignment parameters.\r\nAligning the SciFi by minimizing the track $\\chi^2$ with the same model as used for reconstruction is an advantage. The idea is to use a global covariance matrix in the track fit with the kalman filter.\r\n%Then part of the alignment can be performed just by fitting the tracks\r\nThis approach will be used as the type of alignment for the SciFi in this thesis.\r\nIn the following paragraph this form of alignment is briefly described\\cite{HULSBERGEN1}.\r\n\r\nBecause of the similarity to the kalman filter method a short revisit of the minimum $\\chi^2$ formalism is presented.\r\nThe track $\\chi^2$ is defined as\r\n\\begin{equation}\r\n \\chi^2 = \\vec{\\text{res}}^T V^{-1} \\vec{\\text{res}}\\,,\r\n \\label{eqn:chi}\r\n\\end{equation}\r\n\r\nwhere $V$ is the track covariance matrix. Equation \\eqref{eqn:chi} is a matrix expression since $m$ and $h$ are vectors and $V$ a symmetric matrix. For a linear expansion of the measurement model for an initial estimate $x_0$ of the track parameters.\r\n\r\n\\begin{equation*}\r\n h(x) = h(x_0) + H(x - x_0)\r\n\\end{equation*}\r\n\r\nwith $H$, the projection matrix, being defined as\r\n\\begin{equation*}\r\n H = \\frac{\\partial h(x)}{\\partial x}\\vert_{x_0}\\,.\r\n\\end{equation*}\r\n\r\nThe minimal $\\chi^2$ condition with respect to $x$ can be written as\r\n\r\n\\begin{equation*}\r\n \\frac{\\symup{d}\\chi^2}{\\symup{d}x} = 0\r\n = -2 H^T V{-1} \\left( m - h(x_0) - H(x - x_0) \\right)\\,.\r\n\\end{equation*}\r\n\r\nThe solution to this equation is the known expression of the least-square estimator defined as\r\n\r\n\\begin{equation}\r\n x = x_0 - C H^T V^{-1} \\left( m - h(x_0) \\right)\r\n \\label{eqn:lsq}\r\n\\end{equation}\r\n\r\nwith $C$ being the covariance matrix regarding $x$.\r\n\r\n\\begin{equation}\r\n C = \\left( H^T V^{-1} H \\right)^{-1}\r\n \\label{eqn:cov}\r\n\\end{equation}\r\n\r\nThe non-linear case for the measurement model ($x$ dependency of $H$) the solution in equation \\eqref{eqn:lsq} is of iterative nature and can be applied until convergence is achieved. That can be the minimum change in $\\chi^2$ for which the first and second derivative are needed so the change in the current estimate $x_0$ is defined as\r\n\r\n\\begin{equation*}\r\n x - x_0 = -\\left( \\frac{\\symup{d}^2\\chi^2}{\\symup{d}x^2}\\vert_{x_0} \\right)^{-1} \\frac{\\symup{d}\\chi^2}{\\symup{d}x}\\vert_{x_0}\\,.\r\n\\end{equation*}\r\n\r\nExpanding the model by alignment parameters $\\alpha$.\r\nThe condition for $\\chi^2$ to be minimal with respect to a track model $h(x,\\alpha)$ with track parameters $x_k$ and alignment parameters $\\alpha_k$ are\r\n\r\n\\begin{equation}\r\n \\frac{\\partial\\sum_k\\chi^2_k}{\\partial \\alpha} = 0\r\n\\end{equation}\r\n\r\n and\r\n\r\n \\begin{equation}\r\n \\forall_k \\frac{\\partial\\chi^2_k}{\\partial x_k} = 0\\,.\r\n \\end{equation}\r\n\r\nThe subscript $j$ denotes the track not the vector component. For a single track the subscript can be left out. The more number of tracks, the more number of parameters in the minimizing problem.\r\nFor a large number of tracks a similar expression as in equation \\eqref{eqn:lsq} for the least squares estimator is used and the computation is performed in two steps since the inverse matrix is computationally too expensive to use a least squares expression.\r\nThe first step is to estimate track parameters for a starting set of calibration parameters called $\\alpha_0$. The second step is to minimize the total $\\chi^2$ with respect to $\\alpha$ while also taking $x_j$ and $\\alpha$ into account.\r\n\r\nThe total derivative reads\r\n\\begin{equation}\r\n \\frac{\\symup{d}}{\\symup{d}\\alpha} = \\frac{\\partial}{\\partial\\alpha} +\r\n \\frac{\\symup{d}x}{\\symup{d}\\alpha}\\frac{\\partial}{\\partial x}\\,.\r\n\\end{equation}\r\n\r\n$\\frac{\\symup{d}x}{\\symup{d}\\alpha}$ is a derivative matrix and results from the minimal track $\\chi^2$ condition and can be expressed by\r\n\r\n\\begin{equation}\r\n \\frac{\\symup{d}}{\\symup{d}\\alpha}\\frac{\\partial \\chi^2}{\\partial x} = 0\r\n\\end{equation}\r\n\r\ntherefore the derivative matrix is defined as\r\n\\begin{equation}\r\n \\frac{\\symup{d}x}{\\symup{d}\\alpha} = -\\frac{\\partial^2\\chi^2}{\\partial\\alpha\\partial x} \\left( \\frac{\\partial^2\\chi^2}{\\partial x^2} \\right)^{-1}\\,.\r\n\\end{equation}\r\n\r\nThe total $\\chi^2$ for a sample of tracks is minimal with respect to $\\alpha$ and $x$ can the be described as\r\n\\begin{equation}\r\n \\frac{\\symup{d}\\chi^2}{\\symup{d}\\alpha} = 0\\,.\r\n\\end{equation}\r\n\r\nFor $N$ alignment parameters a system with $N$ coupled non-linear equations is defined.\r\nLinearizing the minimum $\\chi^2$ condition around the starting values $\\alpha_0$ and solving the linear system for $\\Delta\\alpha$ yields the solution.\r\n\\begin{equation}\r\n \\frac{\\symup{d}^2\\chi^2}{\\symup{d}\\alpha^2}\\vert_{\\alpha_0} \\Delta\\alpha =\r\n -\\frac{\\symup{d}\\chi^2}{\\symup{d}\\alpha}\\vert_{\\alpha_0}\r\n\\end{equation}\r\n\r\nNow, with enough constraints inside the alignment the second derivative matrix is invertable and the covariance matrix for $\\alpha$ reads\r\n\r\n\\begin{equation*}\r\n \\text{Cov}(\\alpha) = 2 \\left( \\frac{\\symup{d}^2\\chi^2}{\\symup{d}\\alpha^2} \\right)^{-1}\\,.\r\n\\end{equation*}\r\n\r\nHigher order derivatives in $\\alpha$ are neglected here. The difference in the total $\\chi^2$ resulting from a change in $\\Delta\\alpha$ is given by\r\n\r\n\\begin{equation*}\r\n \\Delta_{\\chi^2} = \\frac{1}{2} \\left( \\frac{\\symup{d}\\chi^2}{\\symup{d}\\alpha} \\right)^T \\Delta\\alpha = -\\Delta\\alpha^T \\text{Cov}(\\alpha)^{-1}\\Delta\\alpha\r\n\\end{equation*}\r\n\r\nThe change in total $\\chi^2$ is equivalent to the significance of the alignment correction and $\\Delta_{\\chi^2}$ is used to follow the convergence of an alignment.\r\n", "meta": {"hexsha": "8a7cb55fd96f7b0405417c7f26dd4b56eef4d03c", "size": 18503, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "content/alignment_theory.tex", "max_stars_repo_name": "NilBre/MASTER_thesis", "max_stars_repo_head_hexsha": "3e1f5d70871b647de26644ad4031a9c57ccad2c5", "max_stars_repo_licenses": ["MIT"], "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/alignment_theory.tex", "max_issues_repo_name": "NilBre/MASTER_thesis", "max_issues_repo_head_hexsha": "3e1f5d70871b647de26644ad4031a9c57ccad2c5", "max_issues_repo_licenses": ["MIT"], "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/alignment_theory.tex", "max_forks_repo_name": "NilBre/MASTER_thesis", "max_forks_repo_head_hexsha": "3e1f5d70871b647de26644ad4031a9c57ccad2c5", "max_forks_repo_licenses": ["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.8802588997, "max_line_length": 543, "alphanum_fraction": 0.7303140031, "num_tokens": 5156, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.2974699426047947, "lm_q1q2_score": 0.16378914142354517}} {"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 {algorithmic}\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{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\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 15} } \n\n\\begin{centering}\n\\section*{Graph Representations and Depth-First Search}\n\\end{centering}\n\n\\section{Graphs}\nA graph is a set of vertices and edges connecting those vertices. Formally, we define a graph $G$ as $G = (V, E)$ where $E \\subseteq V \\times V$ . For ease of analysis, the variables $n$ and $m$ typically stand for the number of vertices and edges, respectively. Graphs can come in two flavors, directed or undirected. If a graph is undirected, it must satisfy the property that $(i, j) \\in E \\iff (j, i) \\in E$ (i.e., all edges are bidirectional). In undirected graphs, $m \\leq \\frac{n(n-1)}{2}$ . In directed graphs, $m \\leq n(n - 1)$. Thus, $m = O(n^2)$ and $\\log m = O(\\log n)$. A connected graph is a graph in which for any two nodes $u$ and $v$ there exists a path from $u$ to $v$ . For an undirected connected graph $m \\geq n - 1$. A sparse graph is a graph with few edges (for example, $\\Theta(n)$ edges) while a dense graph is a graph with many edges (for example, $m = \\Theta(n^2)$).\n\n\\subsection{Representation} \n\nA common issue is the topic of how to represent a graph's edges in memory. There are two standard methods for this task. \n\nAn \\textbf{adjacency matrix} uses an arbitrary ordering of the vertices from $1$ to $|V|$. The matrix consists of an $n \\times n$ binary matrix such that the $(i, j)$-th element is $1$ if $(i, j)$ is an edge in the graph, $0$ otherwise. \n\nAn \\textbf{adjacency list} consists of an array $A$ of $|V |$ lists, such that $$A[u]$$ contains a linked list of vertices $v$ such that $(u, v) \\in E$ (the neighbors of $u$). In the case of a directed graph, it's also helpful to distinguish between outgoing and ingoing edges by storing two different lists at $A[u]$: a list of $v$ such that $(u, v ) \\in E$ (the out-neighbors of $u$) as well as a list of $v$ such that $(v, u) \\in E$ (the in-neighbors of $u$). \n\nWhat are the tradeoffs between these two methods? To help our analysis, let deg($v$) denote the \\textbf{degree} of $v$, or the number of vertices connected to $v$. In a directed graph, we can distinguish between out-degree and in-degree, which respectively count the number of outgoing and incoming edges.\n\n\\begin{itemize}\n \\item The adjacency matrix can check if $(i, j)$ is an edge in $G$ in constant time, whereas the adjacency list representation must iterate through up to deg($i$) list entries.\n \\item The adjacency matrix takes $\\Theta(n^2)$ space, whereas the adjacency list takes $\\Theta(m + n)$ space.\n \\item The adjacency matrix takes $\\Theta(n)$ operations to enumerate the neighbors of a vertex v since it must iterate across an entire row of the matrix. The adjacency list takes deg($v $) time.\n\\end{itemize}\n \nWhat's a good rule of thumb for picking the implementation? One useful property is the sparsity of the graph's edges. If the graph is \\textbf{sparse}, and the number of edges is considerably less than the max ($m \\ll n^2$ ), then the adjacency list is a good idea. If the graph is dense and the number of edges is nearly $n^2$ , then the matrix representation makes sense because it speeds up lookups without too much space overhead. Of course, some applications will have lots of space to spare, making the matrix feasible no matter the structure of the graphs. Other applications may prefer adjacency lists even for dense graphs. Choosing the appropriate structure is a balancing act of requirements and priorities.\n\n\\section{Depth First Search (DFS)} \n\nGiven a starting vertex, it's desirable to find all vertices reachable from the start. There are many algorithms to do this, the simplest of which is depth-first search. As the name implies, DFS enumerates the deepest paths, only backtracking when it hits a dead end or an already-explored section of the graph. DFS by itself is fairly simple, so we introduce some augmentations to the basic algorithm. \n\n\\begin{itemize}\n \\item To prevent loops, DFS keeps track of a ``color'' attribute for each vertex. Unvisited vertices are white by default. Vertices that have been visited but still may be backtracked to are colored gray. Vertices which are completely processed are colored black. The algorithm can then prevent loops by skipping non-white vertices\n \\item Instead of just marking visited vertices, the algorithm also keeps track of the tree generated by the depth-first traversal. It does so by marking the ``parent'' of each visited vertex, aka the vertex that DFS visited immediately prior to visiting the child.\n \\item The augmented DFS also marks two auto-incrementing timestamps $d$ and $f$ to indicate when a node was first discovered and finished.\n\\end{itemize}\n\nThe algorithm takes as input a start vertex $s$ and a starting timestamp $t$, and returns the timestamp at which the algorithm finishes. Let $N(s)$ denote the neighbors of $s$; for a directed graph, let $N_{\\text{out}}(s)$ denote the out-neighbors of $s$.\n\n\\begin{algorithm}\n\\caption{\\texttt{init}(G)}\n\\label{alg:init_G}\n\\begin{algorithmic}\n\\FOR {$v \\in G$}\n\\STATE color($v$) $\\gets$ white\n\\STATE d($v$), f($v$) $\\gets \\infty$ \n\\STATE p($v$) $\\gets$ nil\n\\ENDFOR\n\\end{algorithmic}\n\\end{algorithm}\n\n\\begin{algorithm}\n\\caption{\\texttt{DFS}(s, t): $s \\in V$ is white, $t =$ time}\n\\label{alg:DFS_s_t}\n\\begin{algorithmic}\n\\STATE color(s) $\\gets$ gray\n\\STATE \\texttt{// d(s) is the discovery time of s}\n\\STATE $d(s) \\gets t$\n\\STATE $t \\gets t+1$\n\\FOR {$v \\in N(s)$}\n \\IF {$color(v) = white$}\n \\STATE $p(v) \\gets s$\n \\STATE \\texttt{// Update t to be the finish time of DFS starting at v}\n \\STATE $t \\gets DFS(v,t)$\n \\STATE $t \\gets t + 1$\n \\ENDIF\n\\ENDFOR\n\\STATE \\texttt{Finish time:}\n\\STATE $f(s) \\gets t$\n\\STATE \\texttt{// s is finished}\n\\STATE color($s$) $\\gets$ black\n\\end{algorithmic}\n\\end{algorithm}\n\nThere are multiple ways we can search using DFS. One way is to search from some source node $s$, which will give us a set of black nodes reachable from $s$ and white nodes unreachable from $s$.\n\n\\begin{algorithm}\n\\caption{\\texttt{DFS}(s): DFS from a source node $s$}\n\\label{alg:DFS_s}\n\\begin{algorithmic}\n\\STATE init($G$)\n\\STATE DFS($s, 1$)\n\\end{algorithmic}\n\\end{algorithm}\n\nAnother way to use DFS is to search over the entire graph, choosing some white node and finding everything we can reach from that node, and repeating until we have no white nodes remaining. In an undirected graph this will give us all of the connected components.\n\n\\begin{algorithm}\n\\caption{\\texttt{DFS}(G): DFS on an entire graph $G$}\n\\label{alg:DFS_G}\n\\begin{algorithmic}\n\\STATE init($G$)\n\\STATE $t \\gets 1$\n\\FOR {$ v \\in G$}\n \\IF {$color(v) = white$}\n \\STATE $t \\gets$ DFS($v,t$)\n \\STATE $t \\gets t+1$\n \\ENDIF\n\\ENDFOR\n\\end{algorithmic}\n\\end{algorithm}\n\n\\subsection{Runtime of DFS} \n\nWe will now look at the runtime for the standard DFS algorithm (\\ref{alg:DFS_s_t}). \n\nEverything above the loop runs in $O(1)$ time per node visit. Excluding the recursive call, everything inside of the for loop takes $O(1)$ time every time an edge is scanned. Everything after the for loop also runs in $O(1)$ time per node visit. \n\nWe can express the runtime of DFS as $O(\\#\\text{ of node visits }+ \\# \\text{ of edge scans})$. Assume we have a graph with $n$ nodes and $m$ edges. We know that the \\# of node visits is $\\leq n$, since we only visit white nodes and whenever we visit a node we change its color from white to gray and never change it back to white again. We also know that an edge $(u, v)$ is scanned only when $u$ or $v$ is visited. Since every node is visited at most once, we know that an edge $(u, v)$ is scanned at most twice (or only once for directed graphs). Thus, \\# of edges scanned is $O(m)$, and the overall runtime of DFS is $O(m + n)$.\n\n\\subsection{DFS Example}\nWe will now try running DFS on the example graph below.\n\\begin{center}\n\\begin{tikzpicture}[scale=0.4]\n\\tikzstyle{every node}+=[inner sep=0pt]\n\\draw [black] (17.4,-25.8) circle (3);\n\\draw (17.4,-25.8) node {$b$};\n\\draw [black] (22,-18.6) circle (3);\n\\draw (22,-18.6) node {$a$};\n\\draw [black] (28.8,-22.8) circle (3);\n\\draw (28.8,-22.8) node {$c$};\n\\draw [black] (36.7,-27.5) circle (3);\n\\draw (36.7,-27.5) node {$d$};\n\\draw [black] (37.4,-19.6) circle (3);\n\\draw (37.4,-19.6) node {$e$};\n\\draw [black] (44.9,-24.3) circle (3);\n\\draw (44.9,-24.3) node {$f$};\n\\draw [black] (20.38,-21.13) -- (19.02,-23.27);\n\\fill [black] (19.02,-23.27) -- (19.87,-22.87) -- (19.02,-22.33);\n\\draw [black] (20.3,-25.04) -- (25.9,-23.56);\n\\fill [black] (25.9,-23.56) -- (25,-23.28) -- (25.25,-24.25);\n\\draw [black] (26.25,-21.22) -- (24.55,-20.18);\n\\fill [black] (24.55,-20.18) -- (24.97,-21.02) -- (25.5,-20.17);\n\\draw [black] (31.38,-24.33) -- (34.12,-25.97);\n\\fill [black] (34.12,-25.97) -- (33.69,-25.13) -- (33.18,-25.99);\n\\draw [black] (34.59,-20.65) -- (31.61,-21.75);\n\\fill [black] (31.61,-21.75) -- (32.54,-21.94) -- (32.19,-21.01);\n\\draw [black] (39.94,-21.19) -- (42.36,-22.71);\n\\fill [black] (42.36,-22.71) -- (41.95,-21.86) -- (41.41,-22.71);\n\\end{tikzpicture}\n\\end{center}\n\nWe mark all of the nodes as unvisited and start at a white node, in our case node a.\n\\begin{center}\n\\begin{tikzpicture}[scale=0.4,every text node part/.style={align=center}]\n\\tikzstyle{every node}+=[inner sep=0pt]\n\\draw [black] (17.4,-25.8) circle (3);\n\\draw (17.4,-25.8) node {$b$ \\\\ unvisited};\n\\draw [black] (22,-18.6) circle (3);\n\\draw (22,-18.6) node {$a$ \\\\ $(1,$};\n\\draw [black] (28.8,-22.8) circle (3);\n\\draw (28.8,-22.8) node {$c$ \\\\ unvisited};\n\\draw [black] (36.7,-27.5) circle (3);\n\\draw (36.7,-27.5) node {$d$ \\\\ unvisited};\n\\draw [black] (37.4,-19.6) circle (3);\n\\draw (37.4,-19.6) node {$e$ \\\\ unvisited};\n\\draw [black] (44.9,-24.3) circle (3);\n\\draw (44.9,-24.3) node {$f$ \\\\ unvisited};\n\\draw [black] (20.38,-21.13) -- (19.02,-23.27);\n\\fill [black] (19.02,-23.27) -- (19.87,-22.87) -- (19.02,-22.33);\n\\draw [black] (20.3,-25.04) -- (25.9,-23.56);\n\\fill [black] (25.9,-23.56) -- (25,-23.28) -- (25.25,-24.25);\n\\draw [black] (26.25,-21.22) -- (24.55,-20.18);\n\\fill [black] (24.55,-20.18) -- (24.97,-21.02) -- (25.5,-20.17);\n\\draw [black] (31.38,-24.33) -- (34.12,-25.97);\n\\fill [black] (34.12,-25.97) -- (33.69,-25.13) -- (33.18,-25.99);\n\\draw [black] (34.59,-20.65) -- (31.61,-21.75);\n\\fill [black] (31.61,-21.75) -- (32.54,-21.94) -- (32.19,-21.01);\n\\draw [black] (39.94,-21.19) -- (42.36,-22.71);\n\\fill [black] (42.36,-22.71) -- (41.95,-21.86) -- (41.41,-22.71);\n\\end{tikzpicture}\n\\end{center}\n\nFrom node $a$ we will visit all of $a$'s children, namely node $b$.\n\n\\begin{center}\n\\begin{tikzpicture}[scale=0.4,every text node part/.style={align=center}]\n\\tikzstyle{every node}+=[inner sep=0pt]\n\\draw [black] (17.4,-25.8) circle (3);\n\\draw (17.4,-25.8) node {$b$ \\\\ $(2,$};\n\\draw [black] (22,-18.6) circle (3);\n\\draw (22,-18.6) node {$a$ \\\\ $(1,$};\n\\draw [black] (28.8,-22.8) circle (3);\n\\draw (28.8,-22.8) node {$c$ \\\\ unvisited};\n\\draw [black] (36.7,-27.5) circle (3);\n\\draw (36.7,-27.5) node {$d$ \\\\ unvisited};\n\\draw [black] (37.4,-19.6) circle (3);\n\\draw (37.4,-19.6) node {$e$ \\\\ unvisited};\n\\draw [black] (44.9,-24.3) circle (3);\n\\draw (44.9,-24.3) node {$f$ \\\\ unvisited};\n\\draw [black] (20.38,-21.13) -- (19.02,-23.27);\n\\fill [black] (19.02,-23.27) -- (19.87,-22.87) -- (19.02,-22.33);\n\\draw [black] (20.3,-25.04) -- (25.9,-23.56);\n\\fill [black] (25.9,-23.56) -- (25,-23.28) -- (25.25,-24.25);\n\\draw [black] (26.25,-21.22) -- (24.55,-20.18);\n\\fill [black] (24.55,-20.18) -- (24.97,-21.02) -- (25.5,-20.17);\n\\draw [black] (31.38,-24.33) -- (34.12,-25.97);\n\\fill [black] (34.12,-25.97) -- (33.69,-25.13) -- (33.18,-25.99);\n\\draw [black] (34.59,-20.65) -- (31.61,-21.75);\n\\fill [black] (31.61,-21.75) -- (32.54,-21.94) -- (32.19,-21.01);\n\\draw [black] (39.94,-21.19) -- (42.36,-22.71);\n\\fill [black] (42.36,-22.71) -- (41.95,-21.86) -- (41.41,-22.71);\n\\end{tikzpicture}\n\\end{center}\n\nWe now visit b's child, node c.\n\n\\begin{center}\n\\begin{tikzpicture}[scale=0.4,every text node part/.style={align=center}]\n\\tikzstyle{every node}+=[inner sep=0pt]\n\\draw [black] (17.4,-25.8) circle (3);\n\\draw (17.4,-25.8) node {$b$ \\\\ $(2,$};\n\\draw [black] (22,-18.6) circle (3);\n\\draw (22,-18.6) node {$a$ \\\\ $(1,$};\n\\draw [black] (28.8,-22.8) circle (3);\n\\draw (28.8,-22.8) node {$c$ \\\\ $(3,$};\n\\draw [black] (36.7,-27.5) circle (3);\n\\draw (36.7,-27.5) node {$d$ \\\\ unvisited};\n\\draw [black] (37.4,-19.6) circle (3);\n\\draw (37.4,-19.6) node {$e$ \\\\ unvisited};\n\\draw [black] (44.9,-24.3) circle (3);\n\\draw (44.9,-24.3) node {$f$ \\\\ unvisited};\n\\draw [black] (20.38,-21.13) -- (19.02,-23.27);\n\\fill [black] (19.02,-23.27) -- (19.87,-22.87) -- (19.02,-22.33);\n\\draw [black] (20.3,-25.04) -- (25.9,-23.56);\n\\fill [black] (25.9,-23.56) -- (25,-23.28) -- (25.25,-24.25);\n\\draw [black] (26.25,-21.22) -- (24.55,-20.18);\n\\fill [black] (24.55,-20.18) -- (24.97,-21.02) -- (25.5,-20.17);\n\\draw [black] (31.38,-24.33) -- (34.12,-25.97);\n\\fill [black] (34.12,-25.97) -- (33.69,-25.13) -- (33.18,-25.99);\n\\draw [black] (34.59,-20.65) -- (31.61,-21.75);\n\\fill [black] (31.61,-21.75) -- (32.54,-21.94) -- (32.19,-21.01);\n\\draw [black] (39.94,-21.19) -- (42.36,-22.71);\n\\fill [black] (42.36,-22.71) -- (41.95,-21.86) -- (41.41,-22.71);\n\\end{tikzpicture}\n\\end{center}\n\nNode c has two children that we must visit. When we try to visit node a we find that node a has already been visited (and would be colored gray, as we are in the process of searching a's children), so we do not continue searching down that path. We will next search c's second child, node d.\n\n\\begin{center}\n\\begin{tikzpicture}[scale=0.4,every text node part/.style={align=center}]\n\\tikzstyle{every node}+=[inner sep=0pt]\n\\draw [black] (17.4,-25.8) circle (3);\n\\draw (17.4,-25.8) node {$b$ \\\\ $(2,$};\n\\draw [black] (22,-18.6) circle (3);\n\\draw (22,-18.6) node {$a$ \\\\ $(1,$};\n\\draw [black] (28.8,-22.8) circle (3);\n\\draw (28.8,-22.8) node {$c$ \\\\ $(3,$};\n\\draw [black] (36.7,-27.5) circle (3);\n\\draw (36.7,-27.5) node {$d$ \\\\ $(4,$};\n\\draw [black] (37.4,-19.6) circle (3);\n\\draw (37.4,-19.6) node {$e$ \\\\ unvisited};\n\\draw [black] (44.9,-24.3) circle (3);\n\\draw (44.9,-24.3) node {$f$ \\\\ unvisited};\n\\draw [black] (20.38,-21.13) -- (19.02,-23.27);\n\\fill [black] (19.02,-23.27) -- (19.87,-22.87) -- (19.02,-22.33);\n\\draw [black] (20.3,-25.04) -- (25.9,-23.56);\n\\fill [black] (25.9,-23.56) -- (25,-23.28) -- (25.25,-24.25);\n\\draw [black] (26.25,-21.22) -- (24.55,-20.18);\n\\fill [black] (24.55,-20.18) -- (24.97,-21.02) -- (25.5,-20.17);\n\\draw [black] (31.38,-24.33) -- (34.12,-25.97);\n\\fill [black] (34.12,-25.97) -- (33.69,-25.13) -- (33.18,-25.99);\n\\draw [black] (34.59,-20.65) -- (31.61,-21.75);\n\\fill [black] (31.61,-21.75) -- (32.54,-21.94) -- (32.19,-21.01);\n\\draw [black] (39.94,-21.19) -- (42.36,-22.71);\n\\fill [black] (42.36,-22.71) -- (41.95,-21.86) -- (41.41,-22.71);\n\\end{tikzpicture}\n\\end{center}\n\nSince node d has no children, we return back to its parent node, c, and continue to go back up the path we took, marking nodes with a finish time when we have searched all of their children.\n\n\\begin{center}\n\\begin{tikzpicture}[scale=0.4,every text node part/.style={align=center}]\n\\tikzstyle{every node}+=[inner sep=0pt]\n\\draw [black] (17.4,-25.8) circle (3);\n\\draw (17.4,-25.8) node {$b$ \\\\ $(2,7)$};\n\\draw [black] (22,-18.6) circle (3);\n\\draw (22,-18.6) node {$a$ \\\\ $(1,8)$};\n\\draw [black] (28.8,-22.8) circle (3);\n\\draw (28.8,-22.8) node {$c$ \\\\ $(3,6)$};\n\\draw [black] (36.7,-27.5) circle (3);\n\\draw (36.7,-27.5) node {$d$ \\\\ $(4,5)$};\n\\draw [black] (37.4,-19.6) circle (3);\n\\draw (37.4,-19.6) node {$e$ \\\\ unvisited};\n\\draw [black] (44.9,-24.3) circle (3);\n\\draw (44.9,-24.3) node {$f$ \\\\ unvisited};\n\\draw [black] (20.38,-21.13) -- (19.02,-23.27);\n\\fill [black] (19.02,-23.27) -- (19.87,-22.87) -- (19.02,-22.33);\n\\draw [black] (20.3,-25.04) -- (25.9,-23.56);\n\\fill [black] (25.9,-23.56) -- (25,-23.28) -- (25.25,-24.25);\n\\draw [black] (26.25,-21.22) -- (24.55,-20.18);\n\\fill [black] (24.55,-20.18) -- (24.97,-21.02) -- (25.5,-20.17);\n\\draw [black] (31.38,-24.33) -- (34.12,-25.97);\n\\fill [black] (34.12,-25.97) -- (33.69,-25.13) -- (33.18,-25.99);\n\\draw [black] (34.59,-20.65) -- (31.61,-21.75);\n\\fill [black] (31.61,-21.75) -- (32.54,-21.94) -- (32.19,-21.01);\n\\draw [black] (39.94,-21.19) -- (42.36,-22.71);\n\\fill [black] (42.36,-22.71) -- (41.95,-21.86) -- (41.41,-22.71);\n\\end{tikzpicture}\n\\end{center}\n\nOnce we reach our first source node a we find that we have searched all of its children, so we look in the graph to see if there are any unvisited nodes remaining. For our example, we start with a new source node e and run DFS to completion.\n\n\n\\begin{center}\n\\begin{tikzpicture}[scale=0.4,every text node part/.style={align=center}]\n\\tikzstyle{every node}+=[inner sep=0pt]\n\\draw [black] (17.4,-25.8) circle (3);\n\\draw (17.4,-25.8) node {$b$ \\\\ $(2,7)$};\n\\draw [black] (22,-18.6) circle (3);\n\\draw (22,-18.6) node {$a$ \\\\ $(1,8)$};\n\\draw [black] (28.8,-22.8) circle (3);\n\\draw (28.8,-22.8) node {$c$ \\\\ $(3,6)$};\n\\draw [black] (36.7,-27.5) circle (3);\n\\draw (36.7,-27.5) node {$d$ \\\\ $(4,5)$};\n\\draw [black] (37.4,-19.6) circle (3);\n\\draw (37.4,-19.6) node {$e$ \\\\ $(9,12)$};\n\\draw [black] (44.9,-24.3) circle (3);\n\\draw (44.9,-24.3) node {$f$ \\\\ $(10,11)$};\n\\draw [black] (20.38,-21.13) -- (19.02,-23.27);\n\\fill [black] (19.02,-23.27) -- (19.87,-22.87) -- (19.02,-22.33);\n\\draw [black] (20.3,-25.04) -- (25.9,-23.56);\n\\fill [black] (25.9,-23.56) -- (25,-23.28) -- (25.25,-24.25);\n\\draw [black] (26.25,-21.22) -- (24.55,-20.18);\n\\fill [black] (24.55,-20.18) -- (24.97,-21.02) -- (25.5,-20.17);\n\\draw [black] (31.38,-24.33) -- (34.12,-25.97);\n\\fill [black] (34.12,-25.97) -- (33.69,-25.13) -- (33.18,-25.99);\n\\draw [black] (34.59,-20.65) -- (31.61,-21.75);\n\\fill [black] (31.61,-21.75) -- (32.54,-21.94) -- (32.19,-21.01);\n\\draw [black] (39.94,-21.19) -- (42.36,-22.71);\n\\fill [black] (42.36,-22.71) -- (41.95,-21.86) -- (41.41,-22.71);\n\\end{tikzpicture}\n\\end{center}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\\end{document}\n\n\n", "meta": {"hexsha": "208440219ede08080830f3d7953857df4945705a", "size": 19457, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "assets/lectures/lecture15.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/lecture15.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/lecture15.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": 47.2257281553, "max_line_length": 893, "alphanum_fraction": 0.6356581179, "num_tokens": 7225, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48438008427698437, "lm_q2_score": 0.3380771308191988, "lm_q1q2_score": 0.1637578291183246}} {"text": "\\documentclass[12pt]{article}%iopart\n\n%%\n%% Use \\documentclass[boxit]{JAC2003}\n%% to draw a frame with the correct margins on the output.\n%%\n%% Use \\documentclass[acus]{JAC2003}\n%% for US letter paper layout\n%%\n\n\\usepackage{graphicx}\n\\usepackage{listings}\n\\usepackage{color}\n\\usepackage{amssymb,amsmath,pdfpages}\n\\usepackage{bm}\n\n\n\\definecolor{codegreen}{rgb}{0,0.6,0}\n\\definecolor{codegray}{rgb}{0.5,0.5,0.5}\n\\definecolor{codepurple}{rgb}{0.58,0,0.82}\n\\definecolor{backcolour}{rgb}{0.95,0.95,0.92}\n\n\\lstdefinestyle{mystyleh5}{\n backgroundcolor=\\color{backcolour},\n commentstyle=\\color{codegreen},\n keywordstyle=\\color{magenta},\n numberstyle=\\tiny\\color{codegray},\n stringstyle=\\color{codepurple},\n basicstyle=\\footnotesize,\n breakatwhitespace=false,\n breaklines=true,\n captionpos=b,\n keepspaces=true,\n numbers=none,\n numbersep=5pt,\n showspaces=false,\n showstringspaces=false,\n showtabs=false,\n tabsize=2\n}\n\n\\lstdefinestyle{mystyle}{\n backgroundcolor=\\color{backcolour},\n commentstyle=\\color{codegreen},\n keywordstyle=\\color{magenta},\n numberstyle=\\tiny\\color{codegray},\n stringstyle=\\color{codepurple},\n basicstyle=\\footnotesize,\n breakatwhitespace=false,\n breaklines=true,\n captionpos=b,\n keepspaces=true,\n numbers=left,\n numbersep=5pt,\n showspaces=false,\n showstringspaces=false,\n showtabs=false,\n tabsize=2\n}\n\n\\lstset{style=mystyleh5}\n\n\\linespread{1.3}\n\n%\\usepackage[a4paper,%total={145mm,220mm},\n%top=20mm, left=40mm,bottom=40mm, right=25mm, includefoot]{geometry}\n\n\\begin{document}\n\n\\title{Puffin Manual}\n\n\\maketitle\n\n\\newpage\n\n\\tableofcontents\n\n\\newpage\n\n\\section{Introduction}\n\nPuffin (Parallel Unaveraged Fel INtegrator) simulates a Free Electron Laser (FEL). Puffin is a massively parallel numerical solver for an unaveraged, 3D FEL system of equations, and is written mostly in Fortran 90, using MPI and OpenMP.\n\nThe initial publication describing the first version of the code is in \\cite{puffin}. The code has undergone many improvements and extended its functionality since then. It no longer uses an external linear solver package, and the only external package now required is FFTW v3.3.x onwards.\n\nPuffin is a so-called 'unaveraged' FEL code - meaning it is absent of the slowly varying envelope approximation (SVEA) and wiggler period averaging approximations. It does not utilize a 'slicing' model of the beam phase space and radiation field, and instead utilizes an algorithm which is much more similar to a Particle-In-Cell (PIC) code methodology.\n\nIn addition, some accelerator components are included for simulation of the 'realistic' undulator line, and together with the lack of restrictions, means it may model:\n\n\\begin{itemize}\n\\item The full, broad bandwidth frequency spectrum, limited only by the Niquist frequency of the mesh\n\\item Full electron beam transport\n\\item Transport of large energy spread beams through the undulator, and the radiation emitted from these beams\n\\item Tapered undulators\n\\item Fully 3D undulators, including modelling of the wiggler entries/exits and natural focusing\n\\item Interleaved undulator-chicane lattices\n\\item Variably polarized undulators\n\\item Tuning of each undulator module\n\\end{itemize}\n\nIt presently does not include the effects of space charge, and ignores emission of the backwards wave from the e-beam.\n\n\\begin{figure*}\n\\centering\n\\includegraphics[width=60mm]{visit0032.png}\n\\includegraphics[width=60mm]{visit0033.png}\n\\includegraphics[width=100mm]{visit0035.png}\n\\caption{Radiated spontaneous field from Puffin in the first few undulator periods - $x$ (top left) and $y$ (top right) polarized fields, and instantaneous intensity (bottom), at $y=0$. Radiation is propagating in the negative $z$ direction (the vertical axis). One can see the noisy phase of the radiation in both transverse (x) and temporal (z) directions, which is due to the shot-noise of the electron beam. }\n\\label{bbd1}\n\\end{figure*}\n\n\n\n\n\\begin{figure*}\n\\centering\n\\includegraphics[width=100mm]{visit0036.png}\n\\includegraphics[width=100mm]{visit0037.png}\n\\caption{Radiated field from Puffin after amplification in the undulator - x polarized field (top). Radiated energy vs scaled distance through the undulator is on the bottom. Observe the noise from the previous figure has disappeared; the amplification process cause the electrons to align and radiate in phase. }\n\\label{bbd2}\n\\end{figure*}\n\n\\newpage\n\n\\section{Overview}\n\nA Free Electron Laser (FEL) is a device in which an ultra-fast electron beam, travelling close to the speed of light, is made to wiggle from side to side by passing it through a magnetic device known as an undulator, which enables it to amplify a co-propagating radiation field by many orders of magnitude. The FEL is the world's premier source of coherent X-Rays, with national facilites in the U.S., Germany, Japan, Switzerland and more fully booked by physicists and chemists trying to understand matter on the ultra-fast, ultra-small scale.\n\nThe `usual' way of doing FEL theory and numerical codes involves a number of approximations, including:\n\n\\begin{itemize}\n\\item Averaging out the fast wiggle motion of the electrons\n\\item Assuming the radiation field varies slowly over one radiation wavelength (Slowly Varying Envelope Approximation, or SVEA)\n\\item Confining the electrons within self-contained slices (usually a radiation wavelength long) with periodic boundary conditions\n\\end{itemize}\n\nThe above approximations are usually perfectly valid, but there are some regimes in which they may not be applied, or, at least, the application of them is questionable. Puffin, being a so-called `unaveraged' FEL code, has been written to allow investigation into these somewhat esoteric modes of operation, and to test concepts that other FEL codes cannot. Lack of the above restrictions results in the capability of modelling the full radiation and electron bandwidth, with the drawback of increased computation time, necessitating a need for parallel computation on large HPC clusters for fully temporal 3D runs. Puffin is not free of all assumptions, however: we still neglect the backwards propagating wave in the system, we make the paraxial approximation, and neglect space-charge and wakefields.\n\nDue to the nature of the code, and the likely use cases for such a code, we have attempted to create a resource which is a flexible tool for numerical scientific research, while still containing enough `realistic' components to enable reasonable modelling of a current or future facility.\n\n\n\n\nThe main Puffin algorithm solves the FEL system in a scaled reference frame - see section \\ref{puff-eqns} for a description. Data I/O may be in either SI or the Puffin scaled variables.\n\n\n\n\n\\subsection{Input Files}\n\nAt a minimum, one must specify 2 files for use in Puffin - a main input file, and a beam input file. The main file sets up the system scaling, the field mesh, the integration step sizes, and other simulation options. A simple, single undulator system can be setup here. It also specifies the names of the other input files, including the beam file.\n\nThe beam file specifies the electron beam parameters - there are 3 different types of beam input, detailed later in section \\ref{beamfls}. Multiple beams can be specified, each with different characteristics, such as energies, lengths, charges, current profiles, etc.\n\nOptionally, one may also supply a radiation seed file, to describe an injected radiation seed into the FEL with the electron beam. Similarly to the beam file, many radiation seeds can be specified here, at different frequencies, intensity profiles, \\textit{etc}.\n\nIn addition, one may also supply a lattice file, which describes the layout of undulator modules, focusing quadrupoles, chicanes, drifts \\textit{etc}. If this is not supplied, then a single undulator is set up as detailed in the main input file. If it is supplied, the wiggler in the main input file is ignored. Undulators can have independently variable polarizations, magnetic field strengths, etc. A description of available 3D undulator types is available in section \\ref{und-fields}.\n\nThe main input file sets the frequency of data dumps from Puffin. Additionally, a `write file' can be supplied to give more flexibility and specify exactly when the data is written.\n\nPuffin can be resumed from a previous run - if your cluster crashes, for instance. You could even resume from a previous run to extend or change undulator parameters, for instance.\n\nFigure \\ref{inputs1} shows a schematic of the Puffin input decks. Puffin comes with a few example input decks for reference.\n\n\\begin{figure*}\n\\centering\n\\includegraphics[width=120mm]{InputFiles.png}\n\\caption{Schematic of input files - dashed lines indicate optional files.}\n\\label{inputs1}\n\\end{figure*}\n\n\n\n\\subsection{To scale or not to scale?}\n\nAlthough the Puffin algorithm uses scaled variables, the beam and radiation field parameters may be input in either SI units or the scaled units. Use the variable {\\bf qscaled} in the main input file to specify whether scaled or SI units are being used. If $=$ {\\bf .true.}, then Puffin expects scaled variables are being used. % If SI units are used, then the input parameters will be scaled according automatically to the scaling values specified in the main input file.\n\nThe main algorithm in Puffin utilizes the scaled variables above to make the numbers `nicer' to work with. The system saturates with scaled intensity $\\sim 1$, the scaled perpindicular momentum of the beam in the wiggler oscillates between $-1$ and $1$, and so forth. The distance through the wiggler is given in units of a (1D) gain length, and the beam coordinate in the radiation frame is in units of the cooperation length, so that a reference electron slips $1l_c$ through the radiation field in $1$ gain length. The scaling defines a frame of reference which normalises the quantities not only to numerically more manageable numbers, but to \\textit{characteristic} variables.\n\nThe two dominant variables for the scaling are $\\rho$ and $\\eta$. $\\eta$ is a function of the wiggler parameters $a_u$ and $\\lambda_u$, and reference beam energy $\\gamma_r$, and is calculated in Puffin from the input values of these 3 variables. It defines the velocity of the `reference' electron in the scaled radiation frame. The $\\bar{z}_2$ coordinate is in the scaled frame travelling with the field (at velocity $c$) - $\\eta$ determines how quickly the electrons slip back through this frame, such that an electron with energy $\\gamma_r$, travelling in a wiggler with parameters $a_u$ and $\\lambda_u$, slips back with scaled velocity $p_2 \\equiv \\dfrac{d \\bar{z}_2}{d\\bar{z}} = 1$.\n\nThe $\\rho$ parameter is dependent on the peak electron beam number density, amongst other things, and as far as the discussion of the scaling parameters in Puffin goes, defines a reference for the amplification characteristics. A beam, or indeed, sections of an electron beam with peak number density giving a smaller `localised' $\\rho$ will amplify the beam more slowly with respect to the reference beam specified by $\\rho$.\n\nThat is to say, that they are only \\textit{scaling} parameters. The FEL parameter as input by the user does not have to correspond to the beam or wiggler being input for the results to be correct. The scaled parameters will behave `nicely' if it does, but it is not necessary for the result to be physically correct. When the result is unscaled, the result will still be correct. The user may input in SI units, and get output in SI units. If using scaled units as input, the user must scale the lengths appropriately, but still, no beam input needs to satisfy the conditions to actually give the $\\rho$ input by the user.\n\n\n\n\n\n\n\\begin{table}\n\\centering\n\\caption[Input Units]{Input Dimensions and Units for Beam and Radiation Field}\n\\begin{tabular}{| c | c | c |}\n\\hline\nUnscaled & units & unscaled equivalent (dimensionless) \\\\\n\\hline\n$x$ & metres (m) & $\\bar{x}$ \\\\\n\\hline\n$y$ & metres (m) & $\\bar{y}$ \\\\\n\\hline\n$dx/dz$ & dimensionless & $\\bar{p}_x$ \\\\\n\\hline\n$dy/dz$ & dimensionless & $\\bar{p}_y$ \\\\\n\\hline\n$t$ & seconds (s) & $\\bar{z}_2$ \\\\\n\\hline\n\\end{tabular}\n\\label{table}\n\\vspace*{-\\baselineskip}\n\\end{table}\n\n\n\n\\subsection{3D Magnetic Fields}\n\n\\label{und-fields}\n\n\\subsubsection{Main Undulator Models}\n\nThe undulator is modelled analytically, and the model must include the fast wiggle motion. Puffin may be modified in the future to allow a map of the undulator field to be input. For now, there are a few generic undulator models employed. The undulator magnetic fields are chosen with the {\\bf zundType} string in the main input file.\n\nAvailable options for use in Puffin are `helical', `planepole' - corresponding to a planar wiggler with flat pole faces with natural focusing only in one direction, `curved' - correspnding to a planar undulator with curved, or canted, pole faces providing natural focusing in both transverse directions equally, and the default Puffin undulator, chosen with a blank string (`'), where the transverse polarization is chosen with the {\\bf sux, suy} inputs, controlling the relative magnitudes of the peak magnetic fields in $x$ and $y$, respectively. These may vary between $0$ and $1$, allowing a general elliptic field to be described.\n\nAll of the undulator fields have an associated `natural' focusing channel, which arises from from the off-axis variation in the magnetic fields. This motion arises naturally when numerically solving the equations, and is not super-imposed artificially upon the electron motion.\n\n\\subsubsection{Undulator Ends}\n\nThe undulators also include entry and exit tapers, and they may be switched on or off in the input file with the flag {\\bf qUndEnds}. Setting this to true will model a smooth taper up and down of the undulator magnetic fields in the first and last 2 periods of the undulator, taking the form of a $\\cos^2$. If they are switched off, the beam is artificially initialized with an `expected' initial condition in the transverse coordinates for that undulator. Including these ends will model a more realistic and natural entry and exit from the undulator, and will reduce CSE effects from the shape of the wiggler.\n\n\n\n\\subsubsection{Natural Undulator Focusing}\n\nEach undulator type has an associated natural focusing wavenumber. In the helical case, the natural betatron wavenumber is\n\\begin{align}\n\\bar{k}_{\\beta n x} = \\bar{k}_{\\beta n y} = \\frac{a_w}{2 \\sqrt{2} \\rho \\gamma_0},\n\\end{align}\nwith $\\gamma_0$ being the average energy of the electron beam (and not necessarily = $\\gamma_r$, which only sets the scaling of the system.)\n\nIn the planar case,\n\\begin{align}\n\\bar{k}_{\\beta n y} = 0, \\\\\n\\bar{k}_{\\beta n y} = \\frac{a_w}{2 \\sqrt{2} \\rho \\gamma_0}.\n\\end{align}\n\nIn the canted pole case,\n\\begin{align}\n\\bar{k}_{\\beta n x,y} = \\frac{a_w \\bar{k}_{x,y}}{\\sqrt{2 \\eta} \\gamma_0},\n\\end{align}\nwhere $\\bar{k}_{x,y}$ describe the hyperbolic variation in the transverse directions (see eqns (\\ref{cp1} - \\ref{cp3})), and must obey\n\\begin{align}\n\\bar{k}_x^2 + \\bar{k}_y^2 = \\frac{\\eta}{4 \\rho^2}\n\\end{align}\nto be physically valid. They determine the focusing strength in the $\\bar{x}$ and $\\bar{y}$ dimensions. For the case of equal focusing, then,\n\\begin{align}\n\\bar{k}_{\\beta n x} = \\bar{k}_{\\beta n y} = \\frac{a_w }{ 4 \\rho \\gamma_0}.\n\\end{align}\n\n\n\n\\subsubsection{Strong Beam Focusing}\n\nIn addition to the natural focusing channel, a constant, `strong' focussing channel may be utilized, to focus the beam to a smaller transverse area. This is a magnetic field super-imposed upon the wiggler. It may be switched on or off with the flag {\\bf qFocussing} in the main input file, and is specified through the use of the variables {\\bf sKBetaXSF} and {\\bf sKBetaYSF}. It is probably highly artificial - it may be thought of as physically similar to an ion channel. Nevertheless it allows one to obtain strong focusing without using a lattice. It is defined very simply as\n\\begin{align}\nb_x = \\sqrt{\\eta} \\frac{\\bar{k}_{\\beta y}^2}{\\kappa}\\bar{y}_j, \\\\\nb_y = - \\sqrt{\\eta} \\frac{\\bar{k}_{\\beta x}^2}{\\kappa}\\bar{x}_j\n\\end{align}\n\nIf either {\\bf sKBetaXSF} or {\\bf sKBetaYSF} are not specified, then no focusing channel will be added for that dimension, even if the {\\bf qFocussing} flag is true.\n\nMagnetic quads between modules can be specified in the lattice file. See section \\ref{latt-file}.\n\n\n\\subsubsection{Auto beam-matching}\n\nThe beam, when specified by the `simple' method (see below) may be matched to the focusing channel of the undulator automatically with the flag {\\bf qMatched\\_A} in the beam file - the option can be set for each beam. (Note this is for the natural or enhanced \\textit{undulator} focusing, and matching is not performed for a FODO lattice!) In the scaled notation,\n\\begin{align}\n\\bar{\\sigma}_{x,y} = \\sqrt{ \\frac{ \\rho \\bar{\\epsilon}_{x,y} }{\\bar{k}_{\\beta x,y} } }\n\\end{align}\nwhere $\\bar{\\epsilon}_{x,y} = \\epsilon_{x,y} / (\\lambda_r / 4\\pi)$ are the transverse emittances scaled to the so-called Kim criterion.\n\n%If we define $\\bar{a}_w$ as the $rms$ undulator parameter, so that $\\bar{a}_w = a_w$ in the helical case, and $\\bar{a}_w = a_w / sqrt{2}$ in the planar and canted pole case, then we can write a general expression\n\n\nThe spread in the transverse momentum directions is then given by\n\\begin{align}\n\\bar{\\sigma}_{px, py} = \\frac{\\sqrt{\\eta}}{2 \\kappa} \\Bigl< \\frac{\\Gamma}{1+\\eta p_{2}} \\Bigr> \\frac{ \\bar{\\epsilon}_{x,y} }{\\bar{ \\sigma}_{x,y}}. \\label{tmtch_spd}\n\\end{align}\nwhere angular brackets indicate the ensemble average of the beam.\n\nIf {\\bf qFocussing} is true and the strong betatron wavenumber is given, then the strong betatron wavenumber is used to match the beam. Otherwise the beam is auto-matched to the natural focusing channel of the undulator. As this matching is done only for the in-undulator focusing, and not for the FODO lattice, the Twiss ($\\alpha_x, \\alpha_y$) input parameters will be ignored if {\\bf qMatched\\_A = .true.} in the input. If one wishes to use a FODO lattice, the matching must be done by the user - the matched Twiss parameters are not calculated by Puffin. See section \\ref{section-twiss} for how to input Twiss parameters.\n\n\n\n\\subsubsection{Twiss Parameters}\n\n\\label{section-twiss}\n\nOne can use Twiss parameters to provide a transverse phase-space `tilt' for the electron beam. In the simple beam case, the user can specify the \\textit{r.m.s.} $\\bar{\\sigma}_x, \\bar{\\sigma}_{px}$ (or the S.I. equivalents $\\sigma_x, \\sigma_{x}'$) for the electron beam, along with the usual $\\alpha_x$ for the slope of the $x-x'$ correlation. Using this method, the supplied \\textit{r.m.s.} $\\sigma_{x}'$ should be the standard deviation at $x=0$. If the emittance is supplied by using {\\bf emitx}, then the input $\\bar{\\sigma}_{px}$ is ignored, and is instead calculated from $\\sigma_x$, the emittance, and $\\alpha_x$. The intended method is to input the emittances, so that the transverse momenta parameters given by the user are over-written/ignored.\n\n% In general, giving the emittances over-writes the transverse momenta given in the beam file, whether using the\n\n\n\n\n%%% Beam energy - what is the unscaled input?\n%%% Have to explain the 'mean' beam energy and\n%%% the rms width in energy are in what units...??\n\n\n\n\n\n\n\n\n\n\n\\subsection{Beam Initialization}\n\\label{beamfls}\nThere are 3 different ways of defining and initializing the electron beam in Puffin:\n\n\\subsubsection{Simple}\n\nThe beam is described in terms of a homogeneous Gaussian function in every dimension. Some simple correlations in energy can be achieved by specifying an oscillation in the beam energy as a function of $\\bar{z}_2$, or as a simple linear energy chirp in $\\bar{z}_2$. Twiss parameters may be used to tilt the beam for matching to a FODO lattice (Puffin does not calculate the matched Twiss parameters - this must be done separate to Puffin). The beam is generated in Puffin according to this description.\n\nIn general, the correct noise statistics are added to the beam with the method described in \\cite{noise1}. This method, like other beam noise algorithms for FELs, requires a quiet beam to add the noise to. We include two methods of generating the beam - one with the correct noise in all dimensions, and one with the correct noise only in the temporal/$\\bar{z}_2$ dimension. In both methods, the beam is initially quiet in the temporal dimension before adding the noise, with an equispaced layout of the particles in this dimension. The beam MUST be created to appropriately sample the wavelength of emission/amplification - so at least 10 equispaced particles per resonant wavelength. The methods are:-\n\n% qSI - input in SI units - so x, y, z, px, py and gamma - system is then scaled to rho\n% Rho and charge are decoupled - so the simulation will always be correct. For the scaled notation to make sense, the rho must be approximately correct for the given beam charge.\n% qEqui = .false. by default.\n\n\n\n{\\bf Equispaced Grid in Every Dimension}\n\nWhen using this option, the beam is intialized on an equispaced 6D grid. This requires very many particles to appropriately sample every dimension, and you may find it very easy to have more macroparticles than real electrons while loading the beam this way. However, we leave it up to the user to decide if this is appropriate - for some extreme dispersion situation with high charge it may be necessary to create the beam in this way. This can be activated by setting {\\bf qEquiXY $=$ .true.} in the beam input. {\\bf qEquiXY} is actually an array of size nbeams, with a seperate value for each beam if multiple beams are desired. {\\bf qEquiXY $=$ .false.} by default.\n\n{\\bf Equispaced grid ONLY in $\\bar{z}_2$}\n\nIf qEquiXY is false, then the beam is intially generated as a 1D beam, with equispaced macroparticles. Each macroparticle is then split into many particles in the other 5 dimensions, with coordinates generated by a quasi-random sequence in each dimension. The SAME SEQUENCE is used for each particle in z2 - the creates a series of beamlets in the $\\bar{z}_2$ dimension, giving a quiet start in $\\bar{z}_2$. Because random sequences are used, the other 5-dimensions require orders of magnitude less particles to adequately fill the phase space than in the equispaced case. This is the default option, so if not specified, {\\bf qEquiXY $=$ .false.}.\n\nBoth of the above methods may, of course, be replicated and modified by the user to suit a particular situation. The creation of the beam with the correct statistics, while still retaining the sampling necessary for the FEL interaction, is still an area of ongoing research, and is quite controversial, especially when including large velocity disperion in the beam dynamics. We ultimately leave it to the user to ensure the beam is appropriately initialized for their situation. The methods above can probably be replicated with just a few lines of \\textit{e.g.} Python. The generated beam can then be input into Puffin.\n\nTo use this, set the option dtype = `simple' in the nblist namelist in the beam file. The parameters for the distribution are then set in the blist namelist in the same file.\n\n\\subsubsection{Dist input}\n\nThe input is composed of a description of temporal slices along the bunch, describing a Gaussian mean and standard deviation in every other dimension, along with Twiss $\\alpha$ parameter, for each temporal slice. This information is used to generate the electron beam in Puffin. The slices must be spaced finely enough to sample the radiation field wavelength being amplified - so \\textit{e.g} at least 10 per wavelength.\n\n\\subsubsection{Beam input}\n\nThis method allows one to read in the 6D scaled particle coordinates from an HDF5 file or a text file. The HDF5 file should be in the same format as the Puffin output. The text input is not recommended, especially for 3D runs, since the reading in is very inefficient, and the files are usually huge for 3D data. The beam is generated externally, and the user is then responsible for ensuring the sampling and the noise in the pulse are correct - it is not added by Puffin in this method.\n\n\n\\subsection{Field Mesh}\n\n\nThe radiation field in Puffin is modelled by a simple cartesian mesh, with equispaced nodes in each of the 3 spatial dimensions. Each node samples a value of the $x$ and $y$ polarized radiation field (the $z$ component of the electric field is not modelled). The scaled $\\bar{z}_2$ coordinate frame is such that the back of the system is with increasing $\\bar{z}_2$ - \\textit{i.e.} to the right in figure \\ref{lgmsh}. Recall that $\\bar{z}_2$ is the stationary radiation frame, so that as the beam propagates through the undulator, the beam slips back through the radiation field, moving to the right in figure \\ref{lgmsh}.\n\nThis mesh must be large enough to contain the beam through the entire propagation distance through the wiggler.\n\nIt must also be large enough to contain the beam in the transverse plane, see figure \\ref{trmsh}. The radiation field is calculated from the driving electron beam by linear interpolants, so the field must adequately sample the area which the beam occupies. The radiation also diffracts outwards from the beam, so the field mesh must extend to adequately model this diffracting radiation to avoid numerical problems at the boundaries of the grid. There are absorbing boundaries in the outer 16 nodes in the mesh in $x$ and $y$ to mitigate this issue, but an absorbing boundary which works well for the full range of frequencies modelled by Puffin is difficult to realise, and the absorbing boundary should not be relied upon to absorb everything which propagates to the outer reaches of the mesh.\n\n\\subsubsection{Fixing the Radiation Mesh}\n\nOne may use the variables {\\bf iRedNodesX, iRedNodesY} to fix the mesh around the beam when initializing a simple beam - see figure \\ref{trmsh}. These variables define an inner set (`reduced' set) of nodes which the beam width will occupy. So the mesh length in $x$ and $y$ will be set up such that the inner set of nodes defined by {\\bf iRedNodesX, iRedNodesY} will contain the beam. In this case, the {\\bf sFModelLengthX, sFModelLengthY} inputs will be ignored.\n\n\n\\begin{figure*}\n\\centering\n\\includegraphics[width=150mm]{long_mesh.png}\n\\caption{Showing the longitudinal setup of the radiation mesh. The beam is indicated in red. The scaled $\\bar{z}_2$ coordinate is defined so that the front of the radiation and beam is to the left. This is the constant radiation frame, so the beam slips backwards through the field from left to right. In the lab frame, the beam and radiation propagates from right to left. The full length of the mesh must be large enough to contain the beam through propagation.}\n\\label{lgmsh}\n\\end{figure*}\n\n\n\\begin{figure*}\n\\centering\n\\includegraphics[width=150mm]{trans_mesh2.png}\n\\caption{Transverse mesh to model the radiation field - the beam is indicated in red. The mesh may be `matched' to the transverse beam profile initially by specifying the iRedNodes parameters - these specify an inner set of nodes such that the mesh will be setup so that the beam is contained within this number of nodes (when using the simple beam input type only). This is only an initial condition, but can aid in setting up the mesh.}\n\\label{trmsh}\n\\end{figure*}\n\n\n\n\\subsection{Lattice Input}\n\n\\label{latt-file}\n\nA lattice file may be supplied in the main input file with the variable `lattFile'. This is the name of the lattice file, containing details of the undulator module lattice layout. If blank, then a single undulator as specified in the main input file will be used.\n\nThe lattice file is a plain text file, where each line beginning with one of the two-letter identifiers below, and in table \\ref{tableLat}, represents a lattice element. There are five supported lattice element types, being undulators, quads, chicanes, drifts, and modulations. These are specified in the lattice file by the first 2 characters of each line, followed by (on the same line) the options for the element. Any line not beginning with one of these identifiers is ignored.\n\n\n\\begin{table}\n\\centering\n\\caption[Input in Lattice File]{Accelerator components for use in lattice file}\n\\begin{tabular}{| c | c |}\n\\hline\nComponent & ID Initials \\\\\n\\hline\nUndulator & {\\bf UN} \\\\\n\\hline\nQuadrupole & {\\bf QU} \\\\\n\\hline\nChicane & {\\bf CH} \\\\\n\\hline\nDrift & {\\bf DR} \\\\\n\\hline\nModulation & {\\bf MO} \\\\\n\\hline\n\\end{tabular}\n\\label{tableLat}\n\\vspace*{-\\baselineskip}\n\\end{table}\n\n\n\n\n%Undulator - UN\n\n%Quadrupole - QU\n\n%Chicane - CH\n\n%Drift - DR\n\n%Modulation - MO\n\nEach entry must be followed by the options specifying that lattice element, on the same line, delimited by spaces.\n\n{\\bf UN} - Undulator Module\n\nFor the undulator, one must specify the undulator type, the number of wiggler periods $N_w$, the undulator parameter relative to the base undulator parameter in the main input file $\\alpha$, the linear taper $\\dfrac{d \\alpha}{d \\bar{z}}$, the polarization $u_x$ and $u_y$ (ignored for the non-variable polarized undulator types), a logical specifying if undulator ends are being used for this module, another logical spcifying if a strong focusing channel is being used in the undulator, and the strong focusing strengths $\\bar{k}_{\\beta x}$ and $\\bar{k}_{\\beta y}$, and the number of integration steps per period to be used in this module.\n\n\n{\\bf QU} - Quadrupole\n\n\nFor the quad, we must specify $\\bar{F}_x$ and $\\bar{F}_y$. These are scaled transverse components of the transform matrix for the quad. The quad is only a point transform, currently, and does not have a length, so the length must be included in a drift section. The transforms for the quad, in S.I. units, are defined as\n\\begin{align}\n\\frac{d x_j}{d z} \\bigg|_{new} = \\frac{d x_j}{d z} \\bigg|_{old} + \\frac{1}{F_x} x_j \\\\\n\\frac{d y_j}{d z} \\bigg|_{new} = \\frac{d y_j}{d z} \\bigg|_{old} + \\frac{1}{F_y} y_j\n\\end{align}\nwhich in the scaled notation becomes:\n\\begin{align}\n\\frac{d \\bar{p}_{xj}}{d \\bar{z}} \\bigg|_{new} = \\frac{d \\bar{p}_{xj}}{d \\bar{z}} \\bigg|_{old} +\\frac{\\sqrt{\\eta}}{2\\rho\\kappa} \\frac{\\bar{x}_j}{\\bar{F}_x} \\\\\n\\frac{d \\bar{p}_{yj}}{d \\bar{z}} \\bigg|_{new} = \\frac{d \\bar{p}_{yj}}{d \\bar{z}} \\bigg|_{old} +\\frac{\\sqrt{\\eta}}{2\\rho\\kappa} \\frac{\\bar{y}_j}{\\bar{F}_y}\n\\end{align}\nwhere $\\bar{F}_{x,y} = \\dfrac{F_{x,y}}{l_g}$.\n\nIn $x$ (unscaled) focal length is taken as\n\\begin{align}\n\\frac{1}{F_x} = \\frac{g L_Q}{B\\rho},\n\\end{align}\nwhere $g$ is the quad magnetic field gradient in $Tm^{-1}$, $L_Q$ is the length of the quad, and $B\\rho = \\beta E_0 / 0.2998$ is the so-called magnetic rigidity in $Tm$, with the beam energy $E_0$ in $GeV$ (corresponding to the scaling energy defined in the input file).\n\n{\\bf CH} - Chicane\n\nFor the chicane, one must specify physical length, slippage length, and dispersion enhancement (scaled R56). The length is the physical length of the device in undulator periods, and is used to calculate the diffraction properly. The slippage length tells how many wavelengths to delay the beam by relative to the radiation field in resonant radiation wavelengths - be careful, this should not be $\\leq 0$, or the beam will then be faster than light speed! Similarly, it is left up to the user to decide what is appropriate to delay the beam by with respect to the physical length of the device. The dispersive enhancement, $D$, is the scaled R56 of the device - using $\\gamma_r$ in the main input as the mean $\\gamma$ for the chicane, so that\n\\begin{align}\n\\bar{z}_{2} = \\bar{z}_{20} - 2D \\left( \\frac{\\gamma - \\gamma_r}{\\gamma_r} \\right),\n\\end{align}\nand $D = k_r \\rho R_{56}$.\n\nThis approach of being able to vary the 3 parameters above is quite flexible, but at the expense of easy automatic checking of the physical relevance of the parameters. For example, one can disperse the beam 'in place', without shifting it w.r.t. the resonant wavelength, which is obviously unphysical. However, this may be useful for a quick setup of the beam for EEHG at the beginning of the undulator, for instance. If one is not sure of the physical length of the actual device, but knows the length between modules and the desired slippage (e.g. for mode locking the FEL), then one can specify the spatial drift between modules using a drift section, and then specify a chicane with zero physical length, but with the desired delay and R56. In this way the radiation diffraction will still be modelled correctly.\n\n{\\bf DR} - Drift\n\nFor the drift, one must specify length in units of the number of undulator periods.\n\n{\\bf MO} - Modulation\n\nFor the modulation section, one may add an energy modulation to the beam specified by $\\bar{k}_M = \\dfrac{2 \\pi}{\\bar{\\lambda}_M}$ and $\\dfrac{\\Delta \\gamma}{\\gamma_r}$.\n\n\n\\newpage\n\n\\section{Numerical Model}\n\n\\newpage\n\n\\section{Data Output and Post-Processing}\n\n\\subsection{Data Output}\n\nData output is classified as either `full' or `integrated' (reduced) data. The full data dumps consist of the $x$ and $y$ field values on the field mesh, and the macroparticle coordinates in 6D phase space. In a 3D run, this data can easily be $>100$GB's per dump, so it is advisable to limit the frequency of the dumps, which is controlled in the main input file by the variable {\\bf iWriteNthSteps}.\n\nOn the other hand, the reduced data sizes are much smaller, and typically can be written every undulator period. It can still be quite large, depending on the modelled FEL and length of the run, but it will always be significantly smaller than the full data dumps for 3D runs. Integrated data includes quantities like radiation power, bunching, energy spread, current, emittance, beam radius \\textit{etc} as functions of $\\bar{z}_2$ or $ct-z$. Frequency of the integrated dumps is controlled with {\\bf iWriteIntNthSteps} in the main input file.\n\n\\subsection{Output Format}\n\nWhen running Puffin, a few different files will be produced besides the data output files. A *.log file provides any information on errors. A rec.out file tracks the step number the simulation is at in the main integration loop (this is also printed to standard out, but on some job submission systems the stdout will not be visible till AFTER the job has finished. rec.out should be available as the job is running to track the job progress).\n\nThe data output is usually in the HDF5 file format, or optionally in the SDDS format. Currently, SDDS support is quite limited, and full data dumps and only the radiation power of the integrated data is output. Much more integrated data is output in the HDF5 files.\n\n\\subsubsection{HDF5}\n\nThe HDF5 file naming convention in Puffin is: $<$basename$>\\_<$type$>\\_<$step$>$.h5, where basename is the input file basename (i.e.the input file name without the postfix `.in')\n\nThe output type can be integrated, aperp, or electrons, corresponding to reduced (or integrated) data, a full dump of the field mesh (x and y polarised fields), and a full dump of the electron macroparticle coordinates $+$ charge weight, respectively. These are described individually in more detail below. Due to the possible extremely large size of the full dumps, one should be careful how often the data is being written.\n\nOne may simply choose which steps to write out through use of the {\\bf iWriteNthSteps} and {\\bf iWriteIntNthSteps} parameters in the main input file. The former controls the frequency of the full dumps, and the latter specifies the frequency of the integrated data writes.\n\nIn addition, one may activate the {\\bf qDumpEnd} flag to write a full dump at the end of the simulation - this is {\\bf .true.} by defualt, but may be switched off.\n\nMore useful is the write file. This allows one to specify the exact step numbers at which to write out the full dumps. This will be done in addition to the regular write intervals specified above. The file is pointed to from the main input file by the string {\\bf wr\\_file}. In this plain text file, specify each step to write at with a line beginning with {\\bf WR}, followed by a space (or multiple spaces) and then the step number. Any line not beginning with {\\bf WR} will be ignored.\n\n\\subsection{Output Format Specification}\n\nPuffin uses primarily hdf5 for output, although sdds dumps can be made if desired. The sdds outputs do not contain the integrated data, except power.\n\nFor input filename $=$ {\\bf basename.in}, then outputs are as described:\n\n\\subsubsection{Full Dumps}\n\nTwo files for each step written out - one for the field mesh, and one for the macroparticle positions.\n\n{\\bf Field Mesh}\n\nNamed {\\bf \\textit{basename}\\_aperp\\_\\textit{stepnum}.h5}, where {\\bf stepnum} is the integration step number the data was written out at. The file has internal hdf5 structure:\n\n\\begin{lstlisting}[language=python, caption=Structure of HDF5 field output file produced by Puffin]\n/ (RootGroup)\n/aperp (Array(2, nz2, ny, nx))\n/globalLimits (Group)\n/intensityScaled (Group)\n/meshScaled (Group)\n/runInfo (Group)\n/time (Group)\n\\end{lstlisting}\n\nThe {\\bf aperp} dataset contains the values of the field at each field node. {\\bf nz2}, {\\bf ny} and {\\bf nx} are the number of nodes in the equispaced field mesh in $\\bar{z}_2$, $\\bar{y}$, and $\\bar{x}$, respectively. The data {\\bf aperp(1,:,:,:)} contains the values of the x-polarized field, and {\\bf aperp(2,:,:,:)} is the \\textit{negative} y-polarized field. It also contains some data about the run itself (some of this data is also in the runInfo group in the file). An example of the data is:-\n\n\\begin{lstlisting}[language=python]\n iChic_cr := 1,\n iCsteps := 0,\n iDrift_cr := 1,\n iL := 0,\n iModulation_cr := 1,\n iQuad_cr := 1,\n iUnd_cr := 1,\n istep := 0,\n numSpatialDims := 3,\n time := 0.0,\n vsAxisLabels := 'xbar,ybar,z2bar',\n vsCentering := 'nodal',\n vsIndexOrder := 'compMajorF',\n vsLabels := 'aperp_real, aperp_imaginary',\n vsLimits := 'globalLimits',\n vsMesh := 'meshScaled',\n vsNumSpatialDims := 3,\n vsTimeGroup := 'time',\n vsType := 'variable',\n zInter := 0.0,\n zLocal := 0.0,\n zTotal := 0.0,\n zbarInter := 0.0,\n zbarLocal := 0.0,\n zbarTotal := 0.0\n\\end{lstlisting}\n\nThe integers ending in `cr' are counters for the lattice elements which may be present - {\\bf iChic} is for the chicane, {\\bf iQuad} is for the quads, {\\bf iUnd} is for the undulator modules, {\\bf iModulation} is for the beam modulator sections, and {\\bf iDrift} is for the drift sections. The counter number indicates that the beam has been been completely through the counter number $-1$ (so in the example shown, it has been through no components yet.)\n\n{\\bf istep} is the number of completed integration steps through the current undulator module. It is local to the module being integrated through when the data was written.\n\n{\\bf iCsteps} is the number of \\textit{total} (cumulative) integration steps completed through the entire undulator line, including all previous undulators.\n\nThe {\\bf zInter, zLocal} and {\\bf zTotal} values are distances through the machine, in metres. {\\bf Inter} indicates the \\textit{interaction} distance through the machine - that is, the distance of undulators only, discounting the drifts, chicanes, etc. {\\bf Local} is the distance through the local undulator module. {\\bf Total} is the total distance through the machine when the data was written.\n\n{\\bf zbarInter, zbarLocal} and {\\bf zbarTotal} correspond to {\\bf zInter, zLocal} and {\\bf zTotal}, scaled to $L_g$, the 1D gain length.\n\n\nThe {\\bf intensityScaled} group is a VizSchema derived variable, which tells Visit how to calculate the intensity from the scaled field data.\n\nThe {\\bf meshScaled}, {\\bf globalLimits} and {\\bf time} groups are VizSchema metadata for \\textit{e.g.} Visit.\n\n{\\bf runInfo} is a group containing data about the run the data is from. It includes data about the physical parameters, the scaling and the mesh sizes, amongst other things. A listing of the metadata in this group is here:\n\n\\begin{lstlisting}[language=python]\n Lc := 1.5887624436132764e-06,\n Lg := 0.43767608132326558,\n aw := 1.0121808999999999,\n eta := 3.6299960436719031e-06,\n gamma_r := 456.39999999999998,\n iChic_cr := 1,\n iDrift_cr := 1,\n iModulation_cr := 1,\n iQuad_cr := 1,\n iUnd_cr := 1,\n kappa := 0.22177495617879053,\n lambda_r := 9.9824891200977331e-08,\n lambda_w := 0.0275,\n nSteps := 870,\n nX := 120,\n nY := 120,\n nZ2 := 161939,\n npk_bar := 302255429.89145231,\n rho := 0.0050000000000000001,\n sLengthOfElmX := 0.033613445378151259,\n sLengthOfElmY := 0.033613445378151259,\n sLengthOfElmZ2 := 0.0033069325981203339,\n sStepSize := 0.002094395160675049,\n vsBeamFile := 'beam_file',\n vsBuildConfigDate := '2017-02-07 20:04',\n vsBuildHost := 'crb101',\n vsBuildHostType := 'Linux-2.6.32-642.4.2.el6.x86_64',\n vsCommandLine := '/gpfs/stfc/local/HCP084/bwm06/ltc84-bwm06/bin/puffin-fftw3/bin/puffin test1.in',\n vsFCompiler := 'ifort',\n vsFCompilerFlags := ' -open',\n vsFCompilerVersion := '15.0.2',\n vsInputFile := 'test1',\n vsRunDate := '2017-02-12 18:29:48.648 -0000',\n vsRunHost := 'nxb3b04',\n vsSeedFile := 'seed_file',\n vsSoftware := 'PUFFIN',\n vsSwRevision := 'dev-twiss : 0e2c73483f1dd246a26363292f932946cd1917c8',\n vsSwVersion := '1.8.0',\n vsType := 'runInfo',\n vsUser := 'root',\n vsVsVersion := '3.0'\n\\end{lstlisting}\n\n{\\bf sLengthOfElmX}, {\\bf sLengthOfElmY} and {\\bf sLengthOfElmZ2} are the distances between field nodes in the respective directions in the field mesh, in scaled notation. The other data should be self-explanatory.\n\n\n\n{\\bf Beam Dump}\n\nThe electron beam files are named {\\bf \\textit{basename}\\_electrons\\_\\textit{stepnum}.h5}. The structure of the file is\n\n\\begin{lstlisting}[language=python]\n/ (RootGroup)\n/electrons (Array(numMacroParticles, 7))\n/electrons_chargeSI (Group)\n/electrons_gammaSI (Group)\n/electrons_numPhysicalParticles (Group)\n/electrons_pxSI (Group)\n/electrons_pySI (Group)\n/electrons_xSI (Group)\n/electrons_ySI (Group)\n/electrons_zSI (Group)\n/globalLimits (Group)\n/phi_lamda (Group)\n/runInfo (Group)\n/slice_nom_lamda (Group)\n/time (Group)\n\\end{lstlisting}\n\nThe main data is the {\\bf electrons} dataset, where the each column corresponds to the macroparticle $\\bar{x}$, $\\bar{y}$, $\\bar{z}_2$, $\\bar{p}_x$, $-\\bar{p}_y$, and $\\Gamma$ coordinates, and the macroparticle weight, respectively (note the negative sign in the $\\bar{p}_y$ data). The weight $= N_e / \\bar{n}_p$, where $N_e$ is the number of real electrons the macroparticle represents, and $\\bar{n}_p$ is the peak number density of the electron beam required to get the input value of $\\rho$. $\\bar{n}_p$ is in the {\\bf runInfo} group in the file.\n\nThe {\\bf ...SI} groups are VizSchema derived datasets, allowing visit to calulate the SI quantities from the scaled data in the file.\n\nThe {\\bf runInfo} group is as specified in the field dump file.\n\n\\subsubsection{Integrated Data Files}\n\nThe integrated data files are named {\\bf \\textit{basename}\\_integrated\\_\\textit{stepnum}.h5}. They contain the following data:\n\n\\begin{lstlisting}[language=python]\n/ (RootGroup) ''\n/beamCurrent (Array(8525,)) ''\n/beamCurrentSI (Array(8525,)) ''\n/bunching2ndHarmonic (Array(8524,)) ''\n/bunching2ndHarmonicSI (Array(8524,)) ''\n/bunching3rdHarmonic (Array(8524,)) ''\n/bunching3rdHarmonicSI (Array(8524,)) ''\n/bunching4thHarmonic (Array(8524,)) ''\n/bunching4thHarmonicSI (Array(8524,)) ''\n/bunching5thHarmonic (Array(8524,)) ''\n/bunching5thHarmonicSI (Array(8524,)) ''\n/bunchingFundamental (Array(8524,)) ''\n/bunchingFundamentalSI (Array(8524,)) ''\n/emittanceX (Array(8524,)) ''\n/emittanceXSI (Array(8524,)) ''\n/emittanceY (Array(8524,)) ''\n/emittanceYSI (Array(8524,)) ''\n/meanDeltaGamma (Array(8524,)) ''\n/meanDeltaGammaSI (Array(8524,)) ''\n/meanGamma (Array(8524,)) ''\n/meanGammaSI (Array(8524,)) ''\n/meanMomentumX (Array(8524,)) ''\n/meanMomentumXSI (Array(8524,)) ''\n/meanMomentumY (Array(8524,)) ''\n/meanMomentumYSI (Array(8524,)) ''\n/meanPosX (Array(8524,)) ''\n/meanPosXSI (Array(8524,)) ''\n/meanPosY (Array(8524,)) ''\n/meanPosYSI (Array(8524,)) ''\n/power (Array(161939,)) ''\n/powerSI (Array(161939,)) ''\n/sigmaX (Array(8524,)) ''\n/sigmaXSI (Array(8524,)) ''\n/sigmaY (Array(8524,)) ''\n/sigmaYSI (Array(8524,)) ''\n/sigmapX (Array(8524,)) ''\n/sigmapXSI (Array(8524,)) ''\n/sigmapY (Array(8524,)) ''\n/sigmapYSI (Array(8524,)) ''\n/sliceCharge (Array(8524,)) ''\n/sliceChargeSI (Array(8524,)) ''\n/globalLimits (Group) ''\n/globalLimitsSI (Group) ''\n/intFieldMeshSI (Group) ''\n/intFieldMeshSc (Group) ''\n/intPtclMeshSI (Group) ''\n/intPtclMeshSc (Group) ''\n/runInfo (Group) ''\n/time (Group) ''\n\\end{lstlisting}\n\nData with an appended {\\bf SI} indicate the measurement is in SI units. Otherwise, the data is in the scaled notation.\n\n\\subsection{Post-processing}\n\nThe powPrep.py script will process the power data in the integrated data files to produce a file named basename-integrated-all.vsh5, which contains the power data normalised and formatted for use as a surface plot in Visit, to show the evolution of the temporal power profile as a function of distance through the undulator, see figure. It also contains the energy and peak power data for plotting.\n\nBefore viewing in VisIt, if desired (see below), the field dumps need to be processed by the `ReorderColMajorFtoColMinorC.py' script, since there is currently a bug in VisIt which prevents the data being opened in the native fortran ordering. The field files can easily be 10's to 100's of GB's (or even larger) - so you may wish to process them anyway before attempting to view them.\n\n\\subsection{Viewing the Data}\n\nUsers are free to choose their favourite visualisation method, and none is `officially' supported by Puffin. Nevertheless, the data output itself has vizSchema metadata to tell \\textit{e.g.} Visit how to display the data. VisIt allows the ability to plot the data in client-server mode while the data is on a cluster, which is useful when doing large runs.\n\nThere are example Python scripts to subselect portions of the field mesh. For example, you may wish to select only a central portion of the field mesh in the transverse or temporal directions, or you may wish to select portions at a a time to average over, etc.\n\nIn addition, there are some scripts supplied to give examples of how to access, manipulate and plot the data in Matlab and Python/matplotlib. Feel free to modify these for your own purposes - we expect each project to require its own bespoke processing just due to the nature of the code.\n\n\n\\newpage\n\n\\section{Analytic Equations Solved by Puffin}\n\n\\label{puff-eqns}\n\nThe system of equations solved by Puffin have been altered from those described in \\cite{puffin}. They are now:\n\\begin{align}\n\\Bigl[\\frac{1}{2}\\Bigl(\\frac{\\partial^2}{\\partial\\bar{x}^2} + \\frac{\\partial^2}{\\partial\\bar{y}^2}\\Bigr) - \\frac{\\partial^2}{\\partial\\bar{z}\\partial\\bar{z}_2}\\Bigr]A_{\\bot} & = -\\frac{1}{\\bar{n}_p}\\frac{\\partial}{\\partial \\bar{z}_2}\\sum_{j=1}^{N} \\frac{\\bar{p}_{\\bot j}}{\\Gamma_j} (1+\\eta p_{2j}) \\delta^3(\\bar{x}_j,\\bar{y}_j,\\bar{z}_{2j}) \\label{fieldeq2} \\\\\n\\frac{d \\bar{p}_{\\bot j}}{d \\bar{z}} = & \\frac{1}{2\\rho}\\Bigl[ i \\alpha b_{\\bot} - \\frac{\\eta p_{2j}}{\\kappa^2}A_{\\bot} \\Bigr] - i\\kappa \\frac{ \\bar{p}_{\\bot j}}{\\Gamma_j} (1 + \\eta p_{2j}) \\alpha b_z \\label{pperpeqn2} \\\\\n\\frac{d \\Gamma_{j}}{d \\bar{z}} &= - \\rho \\frac{(1 + \\eta p_{2j})}{\\Gamma_j} (\\bar{p}_{\\bot j} A^*_{\\bot j} + c.c.) \\label{gameqn} \\\\\n\\frac{d\\bar{z}_{2j}}{d\\bar{z}}& = p_{2j} \\label{z2eqgen2} \\\\\n\\frac{d\\bar{x}_j}{d\\bar{z}} &= \\frac{2 \\rho \\kappa}{\\sqrt{\\eta} \\Gamma_j} (1 + \\eta p_{2j}) \\Re(\\bar{p}_{\\bot j}) \\label{xeqgen2} \\\\\n\\frac{d\\bar{y}_j}{d\\bar{z}} &= - \\frac{2 \\rho \\kappa}{\\sqrt{\\eta} \\Gamma_j} (1 + \\eta p_{2j}) \\Im(\\bar{p}_{\\bot j}). \\label{yeqgen2}\n\\end{align}\n%where $\\kappa = \\dfrac{a_u}{2 \\rho \\gamma_r}$, which is actually the scaled natural focussing wavenumber $\\kappa = \\sqrt{2} \\bar{k}_\\beta$.\n\n\n\nScaled parameters are:-\n\n\n%\\begin{align}\n%\\eta = \\frac{\\lambda_r}{\\lambda_w} = \\frac{k_w}{k_r}\n%\\end{align}\n\n\n\n\n\\begin{align}\n\\bar{z}_{2j} &= \\frac{ct_j - z}{l_c}, &\\bar{z} &= \\frac{z}{l_g}, \\nonumber \\\\\n\\bar{p}_{\\bot} &= \\frac{p_{\\bot}}{mc a_u},\n&A_{\\bot}&=\\frac{e \\kappa l_g}{\\gamma_0 mc^2 }E_{\\bot}, \\nonumber \\\\\n(\\bar{x},\\bar{y}) &= \\frac{(x,y)}{\\sqrt{l_g l_c}}, &l_g &= \\frac{\\lambda_w}{4\\pi\\rho}, \\nonumber \\\\\nl_c &= \\frac{\\lambda_r}{4\\pi\\rho}, & \\Gamma_j& = \\frac{\\gamma_j}{\\gamma_0}, \\nonumber \\\\\n\\rho &=\\frac{1}{\\gamma_0}\\left(\\frac{a_u \\omega_p}{4ck_u}\\right)^{2/3},\n&a_u & =\\frac{eB_0}{mck_u}, \\nonumber \\\\\n\\kappa & = \\frac{a_u}{2 \\rho \\gamma_0}, & b_{\\bot} & = b_x - i b_y, \\nonumber\n\\end{align}\n\n$B_0$ is the peak magnetic field in the wiggler.\n$\\omega_p = \\sqrt{e^2 n_p / \\epsilon_0 m}$ is the (non-relativistic) plasma frequency, and $n_p$ is the peak spatial number density of the electron beam $(N_e / \\delta_x \\delta_y \\delta_z)$.\n$E_\\bot = E_x - i E_y$ are the $x$ and $y$ radiation electric field vectors. $\\gamma_0$ is the reference energy (Lorentz factor), which is usually taken as the mean beam energy.\n\nThe scaled reference velocity,\n\\begin{align}\n\\eta = \\frac{1 - \\beta_{zr}}{\\beta_{zr}} = \\frac{\\lambda_r}{\\lambda_u} = \\frac{l_c}{l_g},\n\\end{align}\nwhere $\\beta_{zr}$ is some reference velocity scaled to $c$, which is sensible (but not, strictly speaking, necessary) to take as the mean longitudinal electron velocity in the wiggler, so that\n\\begin{align}\n\\beta_{zr} = \\sqrt{ 1 - \\frac{1}{\\gamma_0^2}\\Bigl(1 + \\bar{a}_u^2\\Bigr)},\n\\end{align}\nwhere $\\bar{a}_u$ is the $rms$ undulator parameter.\nThis defines the velocity at which the electrons travel in the scaled $\\bar{z}_2$ frame. More generally, $\\eta$ describes an *ideal* resonance condition - electrons resonant with wavelength $\\lambda_r$ will travel with velocity $p_2=1$ through the $\\bar{z}_2$ frame.\n\n\n\n\n$p_{2j}$ may be worked out analytically from\n\\begin{align}\np_{2j} = \\frac{1}{\\eta}\\Bigl[ \\Bigl( 1 - \\frac{(1 + a_u^2 | \\bar{p}_{\\bot j} |^2)}{\\gamma_r^2 \\Gamma^2_j} \\Bigr)^{-1/2} - 1 \\Bigr]\n\\end{align}\nat each step. It is NOT output from Puffin.\n\nOutputs from Puffin are classed as either `integrated' data or a full `dump.' The integrated data includes things like the power, beam radius, current, bunching, emittance, etc, as a function of temporal coordinate. The full data dump is the raw data, including the values of the scaled radiation field $A_\\bot$ mesh, and the $6$D electron macroparticle phase space coords ($\\bar{x}, \\bar{y}, \\bar{z}_2, \\bar{p}_\\bot, \\Gamma$) and the macroparticle charge weights. Data is in hdf5 format by default, with vizschema metadata for viewing in Visit.\n\nCompared to the original Puffin paper \\cite{puffin}, now the peak magnetic fields are used to scale the system of eqns (as opposed to the $rms$ values used previously). Previously (\\textit e.g. as described in \\cite{puffin}), the energy exchange was modelled through the scaled longitudinal velocity $p_2$. This was problematic in multiple ways from a computational point of view, since $p_2$ is a function of the energy, $p_x$ and $p_y$, so that the same quantity was essentially being calculated twice, leading to large errors in some cases. The energy exchange is instead now modelled directly through the scaled variable $\\Gamma_j = \\gamma_j / \\gamma_r$, meaning smaller numerical errors and enabling a significantly larger step size.\n\nThe formalism for including a variation in the magnetic undulator field, so that $B_0(\\bar{z})$ now varies, was included in \\cite{2col}, and is varied using the parameter $\\alpha(\\bar{z}) = \\dfrac{B_0(\\bar{z})}{B_0(\\bar{z}=0)}$.\n\n\n\n\n\n\n\\subsection{Full Magnetic Undulator Field Analytic Description}\n\nThe analytic description of the undulator fields are based on those discussed in \\cite{scharlemann1}, which in the scaled notation here are:-\n\n{\\bf helical}\n\\begin{align}\nb_x & = \\cos({\\bar{z}/2\\rho}) \\\\\nb_y & = \\sin({\\bar{z}/2\\rho}) \\\\\nb_z & = \\frac{\\sqrt{\\eta}}{2\\rho} (-\\bar{x}\\sin({\\bar{z} / (2 \\rho)}) + \\bar{y}\\cos({\\bar{z} / (2 \\rho)}))\n\\end{align}\n\n\n{\\bf plane-pole}\n\\begin{align}\nb_x & = 0 \\\\\nb_y & = \\cosh((\\sqrt{\\eta}/{2\\rho}) \\bar{y}) \\sin({\\bar{z}/2\\rho}) \\\\\nb_z & = \\sinh((\\sqrt{\\eta}/{2\\rho}) \\bar{y}) \\cos({\\bar{z} / (2 \\rho)}\n\\end{align}\n\n\n\n\n{\\bf canted-pole}\n\\begin{align}\nb_x & = \\frac{\\bar{k}_{\\beta x}}{\\bar{k}_{\\beta y}} \\sinh(\\bar{k}_{\\beta x} \\bar{x} ) \\sinh( \\bar{k}_{\\beta y} \\bar{y} ) \\sin({\\bar{z}/2\\rho}) \\label{cp1} \\\\\nb_y & = \\cosh(\\bar{k}_{\\beta x} \\bar{x} ) \\cosh( \\bar{k}_{\\beta y} \\bar{y} ) \\sin({\\bar{z}/2\\rho}) \\label{cp2}\\\\\nb_z & = \\frac{\\sqrt{\\eta}}{2\\rho \\bar{k}_{\\beta x}} \\cosh(\\bar{k}_{\\beta x} \\bar{x} ) \\sinh( \\bar{k}_{\\beta y} \\bar{y} ) \\cos({\\bar{z}/2\\rho}) \\label{cp3}\n\\end{align}\n\n\n{\\bf variably polarized elliptical}\n\\begin{align}\nb_x & = u_x \\cos({\\bar{z}/2\\rho}) \\\\\nb_y & = u_y \\sin({\\bar{z}/2\\rho}) \\\\\nb_z & = \\frac{\\sqrt{\\eta}}{2\\rho} (u_x \\bar{x}\\sin({\\bar{z} / (2 \\rho)}) + u_y \\bar{y}\\cos({\\bar{z} / (2 \\rho)}))\n\\end{align}\n\n\nIn the $1$D approximation, $b_z = 0$.\n\nAll of the above have an associated `natural' focusing channel, which arises from from the off-axis variation in the magnetic fields. This motion arises naturally when numerically solving the equations, and is not super-imposed upon the electron motion.\n\n\\subsubsection{Magnetic Undulator Field Ends}\n\n\n\\begin{figure*}\n\\centering\n\\includegraphics[width=120mm]{bx-field.png}\n\\includegraphics[width=120mm]{by-field.png}\n\\caption{Schematic of undulator field ends. The magnetic poles are increased linearly over the first 2 periods as shown. }\n\\label{ends1}\n\\end{figure*}\n\n\n\nFigure \\ref{ends1} shows the entry tapers. The $x$ field envelope inceases more rapidly so that the first `pole' is at full strength. The $x$ field is symmetric, and the $y$ field is antisymmetric. The ends of the $x$ field shift the beam off-center by a small amount in the $y$ plane. The $x$ plane motion is not off-set by the $y$ field. Neither causes a velocity offset (or spatial drift) along the undulator. Note that the symmetry of the $x$ field technically results in an extra half-period of full-strength field oscillation in that direction.\n\nThese same entry/exit tapers are used for all of the undulator types in Puffin.\n\n% The precise description of the undulator ends are as follows. Note the presence of corrective terms in addition to the main $\\cos^2$ term, which ensure the beam oscillates close to the axis. (Note also the very small non-zero initial $z-$magnetic field in each case, which we find has no noticable deleterious effects in practice.)\n\n%{\\bf Helical Front}\n\n%\\begin{align}\n%b_x = \\frac{1}{4}\\sin(\\bar{z}/16\\rho) & \\cos(\\bar{z}/16\\rho) \\sin(\\bar{z}/2\\rho) + \\sin^2(\\bar{z} / 16\\rho) \\cos(\\bar{z}/2\\rho) \\\\\n%b_y = - \\frac{1}{4}\\sin(\\bar{z}/16\\rho) & \\cos(\\bar{z}/16\\rho) \\cos(\\bar{z}/2\\rho) + \\sin^2(\\bar{z} / 16\\rho) \\sin(\\bar{z}/2\\rho)\\\\\n%b_z = \\frac{\\sqrt{\\eta}}{2\\rho} \\Bigl[ \\bar{x}\\Bigl(& \\frac{1}{32}\\cos( \\bar{z}/8\\rho )\\sin(\\bar{z}/2\\rho) +\n% \\frac{1}{4}\\sin(\\bar{z}/8\\rho)\\cos(\\bar{z}/2\\rho) \\nonumber \\\\\n% & - \\sin^2(\\bar{z}/16\\rho)\\sin(\\bar{z}/2\\rho) \\Bigr) \\nonumber \\\\\n% \\bar{y}\\Bigl(& -\\frac{1}{32}\\cos( \\bar{z}/8\\rho )\\cos(\\bar{z}/2\\rho) +\\frac{1}{4}\\sin(\\bar{z}/8\\rho)\\sin(\\bar{z}/2\\rho) \\nonumber \\\\\n% & + \\sin^2(\\bar{z}/16\\rho)\\cos(\\bar{z}/2\\rho) \\Bigr) \\Bigr]\n%\\end{align}\n\n\n%{\\bf Helical Back}\n\n%\\begin{align}\n%b_x = -\\frac{1}{4}\\cos(\\bar{z}/16\\rho) & \\sin(\\bar{z}/16\\rho) \\sin(\\bar{z}/2\\rho) + \\cos^2(\\bar{z} / 16\\rho) \\cos(\\bar{z}/2\\rho) \\\\\n%b_y = \\frac{1}{4}\\cos(\\bar{z}/16\\rho) & \\sin(\\bar{z}/16\\rho) \\cos(\\bar{z}/2\\rho) + \\cos^2(\\bar{z} / 16\\rho) \\sin(\\bar{z}/2\\rho)\\\\\n%b_z = \\frac{\\sqrt{\\eta}}{2\\rho} \\Bigl[ \\bar{x}\\Bigl(& -\\frac{1}{32}\\cos( \\bar{z}/8\\rho )\\sin(\\bar{z}/2\\rho) -\n% \\frac{1}{4}\\sin(\\bar{z}/8\\rho)\\cos(\\bar{z}/2\\rho) \\nonumber \\\\\n% & - \\cos^2(\\bar{z}/16\\rho)\\sin(\\bar{z}/2\\rho) \\Bigr) \\nonumber \\\\\n% \\bar{y}\\Bigl(& \\frac{1}{32}\\cos( \\bar{z}/8\\rho )\\cos(\\bar{z}/2\\rho) - \\frac{1}{4}\\sin(\\bar{z}/8\\rho)\\sin(\\bar{z}/2\\rho) \\nonumber \\\\\n% & + \\cos^2(\\bar{z}/16\\rho)\\cos(\\bar{z}/2\\rho) \\Bigr) \\Bigr]\n%\\end{align}\n\n\n\n%{\\bf Plane-Pole Front}\n\n%\\begin{align}\n%b_x = 0, & \\\\\n%b_y = \\cosh(\\sqrt{\\eta}\\bar{y} / 2\\rho)\\Bigl[ -\\frac{1}{4}& \\sin(\\bar{z}/16\\rho) \\cos(\\bar{z}/16\\rho) \\cos(\\bar{z} / 2\\rho) + \\sin^2(\\bar{z}/16\\rho) \\sin(\\bar{z} / 2\\rho) \\Bigr], \\\\\n%b_z = \\sinh(\\sqrt{\\eta}\\bar{y} / 2\\rho) \\Bigl[ -\\frac{1}{32} & \\cos(\\bar{z}/8\\rho) \\cos(\\bar{z}/2\\rho) + \\nonumber \\\\\n% &\\frac{1}{4} \\sin(\\bar{z}/8\\rho)\\sin(\\bar{z}/2\\rho) + \\sin^2 (\\bar{z}/16\\rho) \\cos(\\bar{z}/2\\rho) \\Bigr],\n%\\end{align}\n\n%{\\bf Plane-Pole Back}\n\n%\\begin{align}\n%b_x = 0, & \\\\\n%b_y = \\cosh(\\sqrt{\\eta}\\bar{y} / 2\\rho)\\Bigl[ \\frac{1}{4}& \\sin(\\bar{z}/16\\rho) \\cos(\\bar{z}/16\\rho) \\cos(\\bar{z} / 2\\rho) + \\cos^2(\\bar{z}/16\\rho) \\sin(\\bar{z} / 2\\rho) \\Bigr], \\\\\n%b_z = \\sinh(\\sqrt{\\eta}\\bar{y} / 2\\rho) \\Bigl[ \\frac{1}{32} & \\cos(\\bar{z}/8\\rho) \\cos(\\bar{z}/2\\rho) - \\nonumber \\\\\n% &\\frac{1}{4} \\sin(\\bar{z}/8\\rho)\\sin(\\bar{z}/2\\rho) + \\cos^2 (\\bar{z}/16\\rho) \\cos(\\bar{z}/2\\rho) \\Bigr].\n%\\end{align}\n\n\n\n%{\\bf Curved-Pole Front}\n\n\n%\\begin{align}\n%b_x = \\frac{\\bar{k}_{\\beta x}}{\\bar{k}_{\\beta y}} \\sinh(\\bar{k}_{\\beta x} \\bar{x})\\sinh(\\bar{k}_{\\beta y} \\bar{y}) \\Bigl[ -\\frac{1}{8}& \\sin(\\bar{z}/8\\rho) \\cos(\\bar{z} / 2\\rho) + \\sin^2(\\bar{z}/16\\rho) \\sin(\\bar{z} / 2\\rho) \\Bigr], & \\\\\n%b_y = \\cosh(\\bar{k}_{\\beta x} \\bar{x})\\cosh(\\bar{k}_{\\beta y} \\bar{y}) \\Bigl[ -\\frac{1}{8}& \\sin(\\bar{z}/8\\rho) \\cos(\\bar{z} / 2\\rho) + \\sin^2(\\bar{z}/16\\rho) \\sin(\\bar{z} / 2\\rho) \\Bigr], \\\\\n%b_z = \\frac{\\sqrt{\\eta}}{2 \\rho \\bar{k}_{\\beta y}} \\cosh(\\bar{k}_{\\beta x} \\bar{x})\\sinh(\\bar{k}_{\\beta y} \\bar{y}) \\Bigl[ -\\frac{1}{32} & %\\cos(\\bar{z}/8\\rho) \\cos(\\bar{z}/2\\rho) + \\nonumber \\\\\n% &\\frac{1}{4} \\sin(\\bar{z}/8\\rho)\\sin(\\bar{z}/2\\rho) + \\sin^2 (\\bar{z}/16\\rho) \\cos(\\bar{z}/2\\rho) \\Bigr] .\n%\\end{align}\n\n%{\\bf Curved-Pole Back}\n\n%\\begin{align}\n%b_x = \\frac{\\bar{k}_{\\beta x}}{\\bar{k}_{\\beta y}} \\sinh(\\bar{k}_{\\beta x} \\bar{x})\\sinh(\\bar{k}_{\\beta y} \\bar{y}) \\Bigl[ \\frac{1}{8}& \\sin(\\bar{z}/8\\rho) \\cos(\\bar{z} / 2\\rho) + \\cos^2(\\bar{z}/16\\rho) \\sin(\\bar{z} / 2\\rho) \\Bigr], & \\\\\n%b_y = \\cosh(\\bar{k}_{\\beta x} \\bar{x})\\cosh(\\bar{k}_{\\beta y} \\bar{y}) \\Bigl[ \\frac{1}{8}& \\sin(\\bar{z}/8\\rho) \\cos(\\bar{z} / 2\\rho) + \\cos^2(\\bar{z}/16\\rho) \\sin(\\bar{z} / 2\\rho) \\Bigr], \\\\\n%b_z = \\frac{\\sqrt{\\eta}}{2 \\rho \\bar{k}_{\\beta y}} \\cosh(\\bar{k}_{\\beta x} \\bar{x})\\sinh(\\bar{k}_{\\beta y} \\bar{y}) \\Bigl[ \\frac{1}{32} & \\cos(\\bar{z}/8\\rho) \\cos(\\bar{z}/2\\rho) - \\nonumber \\\\\n% &\\frac{1}{4} \\sin(\\bar{z}/8\\rho)\\sin(\\bar{z}/2\\rho) + \\cos^2 (\\bar{z}/16\\rho) \\cos(\\bar{z}/2\\rho) \\Bigr] .\n%\\end{align}\n\n\n\n\n\\newpage\n\n\\section{Parameters}\n\n\nBelow is an exhaustive list of parameters, for each input file type. Some options are only really useful for investigating runtime errors or strange behaviour. The parameter list for each file is loosely sorted from most to least useful to the average user (default values are in square brackets after the description).\n\n\n\\subsection{Main Input File}\n\n%\\begin{lstlisting}[language=fortran]\n%sRho\n%\\end{lstlisting}\n\nAll parameters in the main input file are in a single namelist, called {\\bf mdata}. They are grouped together below for organisational purposes only.\n\n\\subsubsection{Scaling Parameters}\n\nThese parameters define the scaling frame used by the Puffin algorithm. The reference wavelength and energies referred to in other parameter descriptions are defined by or derived from these parameters.\n\n{\\bf sRho}\n\n$\\rho$, the FEL parameter. This specifies the scaling of the system. It does {\\bf not} have to be strictly correct - it only descibes the scaling. The simulation can be performed, and the system may be scaled back to SI units, and the result should be correct. If the supplied $\\rho$ is correct, however (meaning, it has been calculated from the beam and undulator parameters input), then the scaled notation becomes physically relevant. For an ideal, 1D system, the system should saturate at intensity $|A|^2 \\approx 1$, and the system should be firmly in the high or exponential gain regime at $\\bar{z} \\approx 2-3$. This allows one to quickly see how efficiently the system is lasing w.r.t its ideal case. [$0.01$]\n\n{\\bf saw}\n\n$a_u$, the undulator parameter defined with the peak on-axis magnetic field. [$1.0$]\n\n{\\bf sgamma\\_r}\n\n$\\gamma_0$, the reference (usually the mean) beam energy. [$100$]\n\n{\\bf lambda\\_w}\n\n$\\lambda_u$, the undulator, or wiggler, period. [0.04]\n\n{\\bf zundType}\n\nAllows one to select from a choice of undulators. Choices are `curved', `planepole', and `helical', described analytically below. If neither of these are chosen, then the default elliptical undulator is chosen, with polarization specified by $u_x$ and $u_y$. [`' (blank - corresponding to the generic variably polarized undulator]\n\n{\\bf sux, suy}\n\n$u_x$ and $u_y$ - the relative peak magnetic field of the undulator in each transverse polarization. Usually, at least one should be $=1$, and the other between $0$ (planar) and $1$ (helical). If they are not defined, the default is helical, $u_x=u_y=1$. Ignored if the undulator type is specified as either `helical', `planepole' or `curvedpole'. [($u_x = u_y = 1.0$)]\n\n\n\\subsubsection{Radiation Mesh}\n\n{\\bf meshType}\n\nInteger, selecting the mesh type to be used. $= 0$ for fully temporal mesh, $=1$ for periodic mode. [0]\n\n{\\bf sperwaves}\n\nLength of the periodic mesh, expressed as the number of reference resonant wavelengths. If {\\bf meshType} $=1$ (periodic), and this is defined, then it will be used rather than the more direct {\\bf sFModelLengthZ2}. If {\\bf meshType} $=1$ then this is ignored. [- (not used by default)] \n\n{\\bf nodesPerLambdar}\n\nNumber of nodes in the field mesh to use in the longitudinal dimension per reference resonant wavelength. The reference resonant wavelength is defined from the reference energy {\\bf sgamma\\_r}, the undulator period {\\bf lambda\\_w} and the base or reference undulator parameter {\\bf saw} in the usual way. [17]\n\n{\\bf sFModelLengthZ2}\n\nThe full length of the field mesh in the longitudinal or temporal dimension. This must be long enough to contain the entire beam as it propagates through the undulator. It is auto-checked at the start of the simulation for the simple beam case only, and the check is only an estimate. [4.0]\n\n{\\bf sFModelLengthX}, {\\bf sFModelLengthY}\n\nThe full length of the field mesh in the x and y (transverse) dimensions. This must be long enough to contain the entire beam as it propagates through the undulator. It is auto-checked at the start of the simulation for the simple beam case only, and the check is only an estimate. [1.0, 1.0]\n\n{\\bf iNumNodesX, iNumNodesY}\n\nNumber of nodes in the field mesh in the $x$ and $y$ transverse dimensions, respectively. [129,129]\n\n{\\bf iRedNodesX, iRedNodesY}\n\nIf {\\bf qFixMesh} $=$ {\\bf .true.}, then the mesh size in $x$ and $y$ will be altered in the initialization stage so that the inner {\\bf iRedNodesX} $\\times$ {\\bf iRedNodesY} nodes in the transverse plane contain the beam. Only works for the simple beam input type. [20,20 (won't be fixed)]\n\n{\\bf nspinDX, nspinDY}\n\nInner set of transverse nodes to be used in the MPI process updates, which should contain the full transverse beam - auto-calculated in Puffin if wrong. [20,20]\n\n{\\bf seed\\_file}\n\nString - name of the radiation seed input file. [`' (blank string)]\n\n\\subsubsection{Electron Beam}\n\n\n{\\bf beam\\_file}\n\nString - name of the electron beam input file. [`beam\\_file.in']\n\n{\\bf sElectronThreshold}\n\nWhen using the simple beam generation, any macroparticles generated with weight below the threshold will be removed. The threshold is defined using this variable, which expresses the threshold as a percentage of the mean particle weight. [0.05]\n\n\n\\subsubsection{Undulator Lattice}\n\n{\\bf lattFile}\n\nThe name of the lattice file, if required. If not required, supply a blank string (enter {\\bf `'}). [`' (blank string)]\n\n{\\bf nPeriods}\n\nNumber of undulator periods in the single (non-lattice) undulator case. If a lattice file is suppiled, then this is ignored. [8]\n\n{\\bf taper}\n\nTaper in the single, simple undulator case, $\\dfrac{d\\alpha}{d \\bar{z}}$. Ignored if a lattice file is supplied. [$0.0$]\n\n{\\bf sKBetaXSF, sKBetaYSF}\n\nBetatron wavenumber for energy $\\gamma_r$ of the applied strong focussing channel over the wiggler. Ignored if {\\bf qFocussing} is {\\bf .false.}. Both $=0$ if not specified. Remember this will be applied on top of wiggler field, which has it's own natural focussing. [0.0, 0.0]\n\n\\subsubsection{Data Writing Options}\n\nThese options control the frequency of the writing of the output data files.\n\n{\\bf iWriteNthSteps}\n\nSteps at which to write the full data dumps at. This sets the periodicity of the data dumps, in integration steps. [$30$]\n\n{\\bf iWriteIntNthSteps}\n\nSteps at which to write the integrated data at. This sets the periodicity of the writes, in integration steps. [$30$]\n\n{\\bf qInitWrLat}\n\nLogical. If true, there will be a full particle and field mesh dump at the end of each undulator module in the lattice, and the writing counter will be reset. [.false.]\n\n{\\bf qDumpEnd}\n\nLogical. If true, write a full data dump at the end of the simulation, even if it does not occur at an integer number of {\\bf iWriteNthSteps}. [.true.]\n\n\n\n\n\\subsubsection{Options}\n\n{\\bf qOneD}\n\nLogical. If {\\bf .true.}, Puffin will be run in 1D mode. Default is {\\bf .true.}, since this is the least computationally expensive option. [.true.]\n\n{\\bf qFieldEvolve}\n\nLogical. If = {\\bf .false.}, then the radiation field evolution will be switched off. This is obviously artificial and very rarely used, but can be useful for debugging in some instances. Default is = {\\bf .true}. [.true.]\n\n{\\bf qElectronsEvolve}\n\nLogical. If = {\\bf .false.}, then the electron equations are not solved in the integration steps. Like the case when qFieldEvolve= {\\bf .false.}, this is obviously artificial and very rarely used, but can be useful for debugging in some instances. Default is = {\\bf .true.}. [.true.]\n\n{\\bf qElectronFieldCoupling}\n\nLogical. If = {\\bf .false.}, then the radiation field feedback onto the electrons is switched off by setting the field terms in the electron evolution equations = 0, and so switches off the amplification of the radiation from the electrons. This is unphysical, but is used more often than when qFieldEvolve and qElectronsEvolve ={\\bf .false.} . It can often be used to check for gain in the FEL in low gain situations, or to check whether amplification has occurred rather than coherent emission (CSE) effects due to \\textit{e.g.} fine structure in the beam. When ={\\bf .false.}, this will give the purely spontaneous emission (coherent or incoherent) from the electrons in the wiggler. If there is no appreciable difference between the qElectronFieldCoupling=true and false cases, then there has been negligible FEL amplification. [.true.]\n\n{\\bf qFocussing}\n\nAllows one to switch the strong focussing channel on or off. If ={bf .true.}, the strong focusing is switched on with calues specified by sKBetaXSF and sKBetaYSF. If qFocussing={\\bf .true.}, yet no focussing strength is specified (sKBetaXSF or sKBetaYSF), then strong focusing is effectively switched off in that dimension. Default = {\\bf .false.}. [.false.]\n\n{\\bf qDiffraction}\n\nSwitches modelling of diffraction of the radiation field on or off. If ={\\bf .true.}, field diffraction is modelled. This can be useful to switch off only really for debugging purposes. Default ={\\bf .true.}. [.true.]\n\n{\\bf qFMesh\\_G}\n\nWhether fixing the field mesh in the transverse plane to contain the beam within the inner {\\bf iRedNodesX} $\\times$ {\\bf iRedNodesY} nodes. Valid when using a `simple' beam only - otherwise it is ignored. [.true.]\n\n{\\bf qUndEnds}\n\nSwitch on/off proper modelling of the wiggler module ends. If true, then the first and last 2 periods of the wiggler will be tapered up/down with a $\\sin^2$ function. [.false.]\n\n{\\bf q\\_Noise}\n\nIf adding the statistical shot-noise to the beam in the simple beam case. [.true.]\n\n{\\bf qsdds}\n\nSwitch on/off ouput of particle and field mesh dumps in sdds format. [.false.]\n\n{\\bf qhdf5}\n\nSwitch on/off output of particle and field mesh dumps in vizSchema compliant hdf5 format. [.true.]\n\n{\\bf qScaled}\n\nLogical turning on/off the input of scaled units into Puffin. If {\\bf .true.}, input is assumed to be in the scaled units. [.true.]\n\n{\\bf qFilter}\n\nLogical turning on/off the filtering of low frequency content during the siffraction step. The high-pass filter cut-off is defined by {\\bf sFiltFrac}. If true, the low frequency content is set $=0$. If false, the low frequency content is not manipulated/diffracted. [.true.]\n\n{\\bf ioutinfo}\n\nInteger. Controls the verbosity of information on the simulation progress written to stdout, from levels $0$ to $3$. $=0$ results in no information being written to standard out, and $3$ gives updates after every single integration step, and some more additional info helful for debugging.\n\n{\\bf qWriteA, qWriteZ2, qWritePperp, qWriteP2, qWriteX, qWriteY, qWriteZ}\n\nLogicals to switch on/off the writing of field, electron phase space coordinates ($\\bar{z}_2$, $\\bar{p}_\\bot$, $\\Gamma$, $\\bar{x}$, $\\bar{y}$), and propagation distance, respectively, in the sdds full data dumps. (Deprecated) (Only used when {\\bf qsdds = .true.})\n\n{\\bf qSeparateFiles}\n\n(Now no longer used, does nothing - only there for compatibility issues. Will be removed completely soon.)\n\nIf each rank is writing its own file for the hdf5 files. If = true, then the files will need to be gathered together in post for analysis. Depending on the file system, this may be faster or slower for you. There are some post-processing python scripts to show how you might stitch the files together in post. (Deprecated) [.false.]\n\n\n\\subsubsection{Numerical Integration}\n\nThese parameters control the numerical integration methods.\n\n{\\bf stepsPerPeriod}\n\nNumber of integration steps for the electron beam and field source term per undulator period. Should usually be $\\gtrsim$ {\\bf nodesPerLambdar} for a beam with energy and wiggler parameter close to the reference parameters. [30]\n\n{\\bf sDiffFrac}\n\nLength of the diffraction step, in units of the undulator period. Usually $=1$. [1.0]\n\n{\\bf sFiltFrac}\n\nDuring the field diffraction step, the lower frequencies are filtered out. This sets the cutoff for the high-pass filter, in units of the reference resonant frequency - (so should usually be $\\leq 0.3$). [0.3]\n\n{\\bf sBeta}\n\nAbsorption coefficient for the absorbing boundaries on the transverse grid. [1.0]\n\n{\\bf sRedistLen, iRedistStp}\n\nParallel tuning parameters, controlling the buffer length needed by each MPI process, and the number of steps per redistribution stage, respectively. [4.0, 60]\n\n\\newpage\n\n\\subsection{Beam Input File}\n\nAs noted in section \\ref{beamfls}, the electron beam can be specified in 3 different forms - either a `simple', `dist' or `particle'.\n\nThe beam file must contain $2$ namelists. One to choose the method, and the other to choose the options particular to that method. To choose which method to use, the beam file first of all contains a namelist titled {\\bf nblist} with the following parameters.\n\n\\subsubsection{Namelist: nblist}\n\n{\\bf dtype}\n\nString, specifying type of beam input. Can be either {\\it simple}, {\\it dist} or {\\it h5} (for particle input type)\n\n{\\bf nbeams}\n\nInteger. The number of electron beams to set up. For a simple beam, multiple beam can be setup. For the dist type input, multiple electron beam dist files can be used. For the particle input, this parameter is ignored.\n\nIf {\\bf dtype} $=$ {\\it simple}, then a namelist called {\\bf blist} must be used, if {\\bf dtype} $=$ {\\it dist} the namelist {\\bf bdlist} must be entered, and if {\\bf dtype} $=$ {\\it h5} the namelist {\\bf bh5list} must be entered.\n\n\\subsubsection{Namelist: blist}\n\nFor the simple beam file, one can set up a beam with a simple homogeneous distribution in every dimension. Some additional manipulation can be made to this simple beam with the supplied options - Twiss parameters can be used, or a simple beam energy modulation or chirp. The beam is assumed to have either a Gaussian or flat-top distribution profile in each dimension. The beam is therefore specified by giving the widths and so forth of the beam.\n\n{\\bf sSigmaE}\n\nThe \\textit{r.m.s.} Gaussian $\\sigma$ in each dimension, in order $\\bar{x}, \\bar{y}, \\bar{z}_2, \\bar{p}_x, \\bar{p}_y, \\Gamma$, or alternatively, in unscaled, S.I. units, $x,y,t,\\frac{dx}{dz}, \\frac{dy}{dz}, \\Gamma$. When multiple beams are used, put all the consecutive $x$ values together, followed by all of the $y$ values, and so forth, \\textit{e.g.} $\\sigma_{x1}, \\sigma_{x2}, \\sigma_{y1}, \\sigma_{y2}$ ... \\textit{etc.} A flat-top distribution is specified by using a very large value here, \\textit{e.g.} 1E8.\n\n{\\bf sLenE}\n\nThe total length used to model the beam in each dimension, in order, similarly to {\\bf sSigmaE}, $\\bar{x}, \\bar{y}, \\bar{z}_2, \\bar{p}_x, \\bar{p}_y, \\Gamma$, or alternatively, in unscaled, S.I. units, $x,y,t,\\frac{dx}{dz}, \\frac{dy}{dz}, \\Gamma$. Again, for multiple beams, specify the $x$ values for each consecutive beam, then the consecutive $y$ values, and so on. This length should be large enough to ensure a smooth distribution out to the edges. If Gaussian, then usually a length of $\\sim 8\\sigma$ is enough to remove spurious effects from the very edge of the tails. If flat-top, then the charge will be equally distributed over this total length in a given dimension. Gaussian tails can be used on each end of a flat-top distribution to remove CSE from the unphysical sharp edges in charge density, using variables {\\bf qRndEj\\_G, sSigEj\\_G}, see below.\n\n{\\bf bcenter}\n\nArray of reals of size {\\bf nbeams}, specifying the center of the $i^{th}$ beam, in the frame of the mesh, in $\\bar{z}_2$ (scaled), or $t$ (SI). Defaults to 0. If between $0$ and {\\bf sLenE($i$,3)} $/ 2$, then the beam will be initialized with the head of the beam aligned with the head of the mesh, at $\\bar{z}_2 = 0$. Otherwise, {\\bf bcenter} will behave as expected.\n\n\n{\\bf chirp}\n\nArray of reals of size {\\bf nbeams}, containing the gradient of a linear energy chirp in the $i^{th}$ beam. In scaled units this should be specified as $\\frac{d\\gamma}{d\\bar{z}_2}$, in unscaled units, $\\frac{1}{\\gamma_r c} \\frac{d\\gamma}{dt}$. [0.0]\n\n\n{\\bf gammaf}\n\nArray of reals of size {\\bf nbeams}. Describes the mean energy of the beam a fraction of the central energy {\\bf sgamma\\_r} in the main input file. (So you are inputting the mean $\\gamma / \\gamma_r$ of the beam.) [$1.0$]\n\n\n{\\bf mag}\n\nReal array of size {\\bf nbeams}. Magnitude of a sinusoidal oscillation on the beam energy, in units of $\\gamma / \\gamma_r$. [$0.0$]\n\n{\\bf fr}\n\nReal array of size {\\bf nbeams}. Wavenumber of the beam oscillation in $\\bar{z}_2$. [$1.0$]\n\n\n{\\bf qRndEj\\_G}\n\nArray of logicals of size {\\bf nbeams}. If $=$ {\\bf .true.}, and if a flat-top current distribution is specified in {\\bf sSigmaE}, then the hard edges will be rolled off with Gaussian tails to avoid Coherent Spontaneous Emission (CSE). [{\\bf .true.}]\n\n{\\bf sSigEj\\_G}\n\nArray of reals of size {\\bf nbeams}. Specifies the $r.m.s.$ width of the Gaussian tails used when {\\bf qRndEj\\_G} $=$ {\\bf .true.} and a flat-top current distribution is specified in {\\bf sSigmaE}. Ignored otherwise. [$0.02$]\n\n\n{\\bf qMatched\\_A}\n\nArray of logicals of size {\\bf nbeams}. If $=$ {\\bf .true.}, then the radius of the $i^{th}$ beam will be matched to either the `natural' focusing channel of the undulator, or the `strong' intra-undulator focusing if specified. (Please note, this does not match to a focusing lattice as specified in the lattice file! This, unfortunately, must be done manually and the matched parameters used in {\\bf alphax, alphay, emitx, emity} below) [{\\bf .false.}]\n\n{\\bf qFixCharge}\n\nArray of logicals of size {\\bf nbeams}. If $=$ {\\bf .true.}, the charge as input will be ignored, and recalculated from the scaling parameters $\\rho, a_u, \\lambda_u$ and $\\gamma_r$ specified in the main input file, so that the beam (if it has zero energy spread, and ignoring diffraction and emittance effects on the gain) will lase with the usual $1$D gain length $L_g = \\lambda_u / 4 / \\pi / \\rho$.\n\n{\\bf alphax}\n\nArray of reals of size {\\bf nbeams}. Twiss parameter $\\alpha_x$ of the $i^{th}$ beam.\n\n{\\bf alphay}\n\nArray of reals of size {\\bf nbeams}. Twiss parameter $\\alpha_y$ of the $i^{th}$ beam.\n\n{\\bf emitx}\n\nArray of reals of size {\\bf nbeams}. Emittance (in $x$) of the $i^{th}$ beam. If {\\bf qscaled = .true.}, then this is the scaled emittance. Otherwise it is the geometric (unnormalised) emittance (in $m rad$).\n\n{\\bf emity}\n\nArray of reals of size {\\bf nbeams}. Emittance (in $y$) of the $i^{th}$ beam. If {\\bf qscaled = .true.}, then this is the scaled emittance. Otherwise it is the geometric (unnormalised) emittance (in $m rad$).\n\n\n\n{\\bf TrLdMeth}\n\nArray of integers of size {\\bf nbeams}. This chooses the beam loading algorithm. Choose from random ($=1$) or Halton ($=2$) sequences to fill the $5$-D, non-temporal phase space, and for the equal shifts in $\\bar{z}_2$. Use $3$ for random sequences with visible, equidistant slices in $\\bar{z}_2$ (so, without additional shifts in $\\bar{z}_2$), and $4$ for Halton sequences with slices in $\\bar{z}_2$. If $=0$, then the macroparticles will be generated on an equispaced grid in {\\bf every} dimension. For options $1-4$, use the below described variables {\\bf iMPsZ2PerWave} and {\\bf nseqparts} to specify the macroparticle numbers, and for the $=0$ option, use {\\bf iNumMPs}. [$1$]\n\n\n{\\bf iMPsZ2PerWave}\n\nArray of integers of size {\\bf nbeams}, describing the number of macroparticle `slices' per resonant wavelength to use for each beam. In the case of {\\bf TrLdMeth} $= 0$ (equispaced loading method), the resultant total number of macroparticles will overwrite the value in the $\\bar{z}_2$ segment of iNumMPs. [$4$]\n\n{\\bf nseqparts}\n\nArray of integers of size {\\bf nbeams}. If {\\bf qEquiXY} $=$ {\\bf .false.}, this specifies the length of the $5$ pseudo/semi-random sequences, and thus the number of macroparticles per `slice', to use for each equispaced temporal coordinate (in $\\bar{z}_2$). [$1000$]\n\n{\\bf iNumMPs}\n\nArray of integers of size {\\bf nbeams} $\\times$ {\\bf 6}. Specifies the number of macroparticles used to model the beam in each dimension, in order $\\bar{x}, \\bar{y}, \\bar{z}_2, \\bar{p}_x, \\bar{p}_y, \\Gamma$. For multiple beams, specify the $x$ values for each consecutive beam, then the consecutive $y$ values, and so on. In 1D, only the $\\bar{z}_2$ and $\\Gamma$ values are used, no matter what beam loading method is used, and the rest are ignored, although they must be present. In 3D, all values are used only if the variable {\\bf qEquiXY = .true.} (see page ??). Otherwise, the random sequences will be used.\n\n\n\n{\\bf qEquiXY}\n\n{\\bf DEPRECATED - USE TrLdMeth INSTEAD}. Array of logicals of size {\\bf nbeams}. If {\\bf .true.}, then the beam macroparticles will be loaded into an equispaced, $6$-D hypercube, as a `crystal' beam, with the number of macroparticles in each dimension given in {\\bf iNumMPs} above. Initialization and shot-noise are as described in \\cite{noise1}, giving the correct shot-noise in every dimension (at the start of the simulation). If {\\bf .false.}, then the beam will be initialized as equispaced only in the temporal coordinate $\\bar{z}_2$, and random or Halton sequences will be used to fill the other $5$ dimensions ({\\bf TrLdMeth} $= 1$ or $2$, respectively, see below), giving the correct noise in the temporal coordinate only, but with less macroparticles needed to fill the phase space, the simulation is much faster. [{\\bf \\.false.}]\n\n\n\n\n\n% simple params:\n%\n%sSigmaE, sLenE, iNumElectrons, &\n% sEmit_n, sQe, bcenter, gammaf, &\n% chirp, mag, fr, qRndEj_G, sSigEj_G, &\n% qMatched_A, qEquiXY, nseqparts, qFixCharge, &\n% alphax, alphay, emitx, emity, TrLdMeth, fillFact\n\n\n\n\n\\subsubsection{Namelist: bdlist}\n\nIf {\\bf dtype} $=$ {\\it dist} the namelist {\\bf bdlist} must be present in the beam file, which contains one or a number of Puffin distribution files.\n\n{\\bf dist\\_f}\n\nArray of strings, of size {\\bf nbeams}. Contains the name of the dist files to be read in and loaded in Puffin.\n\n{\\bf nseqparts}\n\nArray of integers of size {\\bf nbeams}. This specifies the length of the $5$ pseudo/semi-random sequences, and thus the number of macroparticles, to use for each equispaced temporal coordinate (in $\\bar{z}_2$). [$1000$]\n\n{\\bf inmpsGam}\n\nNumber of macroparticles to use in the energy dimension, for the `crystal' beam case, in $1$D mode only.\n\n\n\\subsubsection{Namelist: bh5list}\n\nIf {\\bf dtype} $=$ {\\it particle} the namelist {\\bf bh5list} must be present in the beam file, which contains one or a number of Puffin particle files.\n\n{\\bf dist\\_f}\n\nArray of strings, of size {\\bf nbeams}. Contains the name of the particle files to be read in by Puffin.\n\n\n\n\\newpage\n\n\\subsection{Radiation Seed Input File}\n\nThe seed file can be in 2 forms - one describing a homogeneous seed of Gaussian or flat top profiles in each of the 3 spatial directions, or a list of hdf5 files containing the values of the $x$ and $y$ fields at the nodes of the radiation mesh.\n\nAs with the beam file, the seed file contains 2 namelists - one specifying which of the 2 input methods is being used and the number of seeds, and the other containing the specification for the selected method. The namelist {\\bf nslist} tells Puffin which of these options to expect.\n\nPlease note that the mesh is only imported as is. It is unfortunately not processed or interpolated onto the Puffin mesh. It is read as-is.\n\n\n\\subsubsection{Namelist: nslist}\n\n{\\bf dtype}\n\nString, specifying type of radiation input. Can be either {\\it simple} or {\\it h5} (for importing a full mesh)\n\n{\\bf nseeds}\n\nInteger. The number of electron beams to set up. For a simple beam, multiple seeds can be setup. For the mesh/h5 input, this parameter is ignored.\n\nIf {\\bf dtype} $=$ {\\it simple}, then a namelist called {\\bf slist} must be used, and if {\\bf dtype} $=$ {\\it h5} the namelist {\\bf sh5list} must be entered.\n\n\\subsubsection{Namelist: slist}\n\nFor the simple seed file, one can set up a seed with a simple homogeneous distribution in every dimension. The radiation seed is assumed to have either a Gaussian or flat-top distribution profile in each dimension. The beam is therefore specified by giving the widths and so forth of the beam. Multiple radiation seeds can be defined, so each parameter is an array, with the $i^{th}$ element describing the $i^{th}$ radiation seed.\n\n\n{\\bf freqf}\n\nThe frequency of each seed, as a fraction of the reference resonant frequency calculated in the scaled frame parameters in the main input file.\n\n{\\bf ph\\_sh}\n\nThe phase of each seed ($0-2\\pi$).\n\n{\\bf sA0\\_X}\n\nThe peak intensity of the $x$-polarized field vector. In dimensionless scaled units of $|A|^2$ ($\\sim 1$ for FEL steady-state saturation for an electron beam with properties determined by the scaled frame), and in $Wm^{-2}$ for unscaled (SI) units.\n\n{\\bf sA0\\_Y}\n\nThe peak intensity of the $y$-polarized field vector. In dimensionless scaled units of $|A|^2$ ($\\sim 1$ for FEL steady-state saturation for an electron beam with properties determined by the scaled frame), and in $Wm^{-2}$ for unscaled (SI) units.\n\n{\\bf sSigmaF}\n\nThe standard deviation $\\sigma$ of the intensity profile of the seed in each dimension, in the order $x, y, z2$. For multiple seeds, specify all of the $x$ values first, then all the $y$ values, then all the $\\bar{z}_2$ values. If a flat top distribution is specified (see {\\bf qFlatTop} below), then this is the radius \\textit{i.e.} half the total length of the radiation seed in $\\bar{z}_2$. The profile in the transverse $x$ and $y$ directions is always Gaussian. In scaled $\\bar{x}, \\bar{y}, \\bar{z}_2$ (dimensionless) units for {\\bf qScaled $=$ .true.} in the main input file, if {\\bf .false.} then must be specified in meters for $x$ and $y$, and in seconds for the third $t$ dimension.\n\n\n{\\bf qFlatTop}\n\nArray of logicals of size {\\bf nseeds}, describing whether the intensity/power distribution in the longditudinal/temporal direction is flat-top ($=${\\bf .true.}) or Gaussian ($=${\\bf .false.}).\n\n\n{\\bf meanZ2}\n\nThe mean of the seed power profile in the temporal dimension. If outside the left edge of the mesh ($\\bar{z}_2 = 0$), then the front edge of the seed is shifted to the front edge of the mesh. So if {\\bf meanZ2} is undefined or $=0$, then the seed mean will be recalculated so that the front of the seed is aligned with the front of the mesh.\n\n\n\n{\\bf qRndFj\\_G}\n\nIf {\\bf qFlatTop} $=$ {\\bf .true.}, then this controls whether the flat top profile is rounded off smoothly at the edges with a Gaussian. See {\\bf sSigFj\\_G} below to control the width of the gaussian tails. If {\\bf qFlatTop} $=$ {\\bf .false.}, then this is ignored.\n\n\n{\\bf sSigFj\\_G}\n\nRMS width of the Gaussian tails, in the case of a flat top radiation seed pulse.\n\n{\\bf qMatchS\\_G}\n\nIf {\\bf .true.}, then the value for the \\textit{rms} $\\sigma$ of the transverse field distributions above will be ignored, and instead the field distribution in the transverse plane will be matched to the electron beam transverse charge distribution.\n\n\n\n\\newpage\n\n\\subsection{Lattice File}\n\nThe main input file allows one to descibe a single undulator. The lattice file instead allows one to construct a more sophisticated layout for the FEL beam line, incuding multiple undulator modules, focussing quadrupoles, drift sections, simple beam modulator sections and chicanes. If the lattice file is given, the single undulator in the main input file is ignored.\n\nAn example of a lattice file is given below. Each lattice element is described by a single line of the lattice file. For a line to be read as a lattice element, it must begin with a two letter (all caps) identifier corresponding to a lattice element. Any line not beginning with a legal identifier is ignored.\n\n\\lstset{style=mystyle}\n\\begin{lstlisting}[language=fortran, caption=Example lattice file.]\n!Module file for Puffin\n!CLARA lattice v3 - reduced for example\n!This is for using undulator ends to give\n!25 'active' undulator periods.\n!The drift is calculated to give a strict 1.25m\n!distance between quads\n!A small (currently dispersionless) phase shifter is used to knock the beam\n!back to the correct phase after the drift.\n\nQU -4.78 4.78\n\nUN 'planepole' 29 1.0 0.0 30 1.0 1.0 0.0 0.0\nDR 16.4545455\nCH 0.0 0.966 0.0\nQU 2.39 -2.39\n\nUN 'planepole' 29 1.0 0.0 30 1.0 1.0 0.0 0.0\nDR 16.4545455\nCH 0.0 0.966 0.0\nQU -2.39 2.39\n\nUN 'planepole' 29 1.0 0.0 30 1.0 1.0 0.0 0.0\nDR 16.4545455\nCH 0.0 0.966 0.0\nQU 2.39 -2.39\n\nUN 'planepole' 29 1.0 0.0 30 1.0 1.0 0.0 0.0\nDR 16.4545455\nCH 0.0 0.966 0.0\nQU -2.39 2.39\n\nUN 'planepole' 29 1.0 0.0 30 1.0 1.0 0.0 0.0\nDR 16.4545455\nCH 0.0 0.966 0.0\nQU 2.39 -2.39\n\n\\end{lstlisting}\n\nEach identifier is then followed by a series of parameters to specify the element's variables. For the undulator element:\n\n\\begin{lstlisting}[language=fortran, caption=Undulator identifier and specification]\nUN 'planepole' 29 1.0 0.0 30 1.0 1.0 0.0 0.0\n! The parameters following the identifier are:\nzundtype, nw, mf, taper, nperlam, ux_arr, uy_arr, kbnx_arr, kbny_arr\n!\n! zundtype is a string describing the undulator type. Choose from 'helical', 'planepole', 'curved', or '' (blank string)\n!\n! nw is an integer giving the number of periods in this undulator\n!\n! alpha is a float giving the initial undulator tuning for this module aw/aw0,\n!\n! taper is the undulator magnetic field taper d/dz of alpha (float)\n!\n! nperlam is an integer specifying the number of integration steps per undulator period to be used in this undulator\n!\n! ux and uy - relative magnetic field strengths in x and y, respectively (float)\n!\n! kbnx_arr and kbny_arr - betatron wavenumber (k_beta = 2pi / lambda_beta)\n! of constant 'strong' focusing channel applied over undulator (float)\n\\end{lstlisting}\n\nFocusing quads are modelled as a simple point transform, see section \\ref{latt-file}.\n\n\\begin{lstlisting}[language=fortran, caption=Quadrupole identifier and specification]\nQU 2.39 -2.39\n! Parameters being \\bar{F}_x and \\bar{F}_y, which are F_x / lg and Fy / lg, respectively. (F_x being -1/R21 of\n! the quad transport matrix, and F_y being -1/R43).\n\n\\end{lstlisting}\n\n\n\n%! zundtype_arr, nw, mf, tapers, nperlam, ux_arr, uy_arr, kbnx_arr, kbny_arr\n%!\n%! ...being...\n%!\n%! undulator type, number of periods (integer), initial tuning alpha = aw/aw0,\n%! taper d/dz alpha, number of integration steps per undulator period (integer),\n%! ux and uy - relative magnetic field strengths in x and y, respectively\n%! kbnx_arr and kbny_arr - betatron wavenumber (k_beta = 2pi / lambda_beta)\n%! of constant 'strong' focusing channel applied over undulator\n\n\\newpage\n\n\\subsection{Write File}\n\nThe seed file can be in 2 forms - one describing a homogeneous seed of Gaussian or flat top profiles in each of the 3 spatial directions, or a list of hdf5 files containing the values of the $x$ and $y$ fields at the nodes of the radiation mesh.\n\nAs with the beam file, the seed file contains 2 namelists - one specifying which of the 2 input methods is being used and the number of seeds, and the other containing the specification for the selected method.\n\n\n\n\\newpage\n\n\\begin{thebibliography}{10}\n\n\\bibitem{puffin}\nL.T. Campbell and B.W.J. McNeil, Physics of Plasmas {\\bf 19}, 093119 (2012)\n\\bibitem{2col}\nL T Campbell, B.W.J. McNeil and S. Reiche, New J. Phys. {\\bf 16} 103019 (2014)\n\\bibitem{scharlemann1}\nE.T. Scharlemann, in High Gain, High Power FELs (edited by R. Bonifacio \\textit{et al} ) (1989)\n\\bibitem{noise1}\nB. W. J. McNeil, M. W. Poole, and G. R. M. Robb, Phys. Rev. ST Accel. Beams {\\bf 6}, 070701 (2003)\n\n\n\\end{thebibliography}\n\n\\end{document}\n", "meta": {"hexsha": "844bef89f550502598fbcc29a9fc845c1fa434fe", "size": 90488, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/manual.tex", "max_stars_repo_name": "mightylorenzo/Puffin", "max_stars_repo_head_hexsha": "6631eb91a5d98d8bc3d40fe9f09b90932f20776a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 15, "max_stars_repo_stars_event_min_datetime": "2017-08-29T10:50:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-14T07:21:49.000Z", "max_issues_repo_path": "doc/manual.tex", "max_issues_repo_name": "mightylorenzo/Puffin", "max_issues_repo_head_hexsha": "6631eb91a5d98d8bc3d40fe9f09b90932f20776a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 27, "max_issues_repo_issues_event_min_datetime": "2017-06-20T09:40:33.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-18T22:35:47.000Z", "max_forks_repo_path": "doc/manual.tex", "max_forks_repo_name": "mightylorenzo/Puffin", "max_forks_repo_head_hexsha": "6631eb91a5d98d8bc3d40fe9f09b90932f20776a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 15, "max_forks_repo_forks_event_min_datetime": "2017-06-21T21:00:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-16T02:15:59.000Z", "avg_line_length": 59.7280528053, "max_line_length": 863, "alphanum_fraction": 0.7278202635, "num_tokens": 25917, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.28776780354463427, "lm_q1q2_score": 0.16288191063893337}} {"text": "\\documentclass[11pt]{article}\n\n\\input{preamble}\n\n%\\usepackage{tikz}\n%\\usepackage{tikz-qtree}\n\\usepackage{qtree}\n\\usepackage{xfrac}\n\n\\title{week 3: ROC curves, Normalization and PCA}\n\\author{\\url{http://mlvu.github.io}}\n\\begin{document}\n\n\\maketitle\n\\section{Exam questions}\n\nAt this point in the course, it's a good idea to have a look at the practice exam. The homework prepares you for the exam, but the format of the homework questions is different from that of the exam questions. Here are some questions you should be able to answer based on the material covered so far. You can find two complete practice exams on Canvas.\n\n\\begin{enumerate}\n\\item What is the advantage of gradient descent over random search?\n\\choicesv{In gradient descent, parallel searches are allowed to communicate.}{Gradient descent is less likely to get stuck in local minima.}{Gradient descent computes the direction of steepest descent, random search approximates it.\\an}{Gradient descent is easier to parallelise.}\n\n% 12 R\n\\item Why is accuracy a bad loss function to use in gradient descent?\n\\choicesv{It is expensive to compute.}{It makes the gradient zero almost everywhere. \\an}{It is unreliable in situations with high class imbalance.}{The confidence interval is high on small test sets.}\n\n% 11 R\n\\item I'm performing spam classification. I represent each email by three numbers: how often the word \\emph{pill} occurs, how often the word \\emph{hello} occurs and how often the word \\emph{congratulations} occurs. What are these three attributes called?\n\\choicesv{The instances}{The classes}{The features \\an}{The principal components}\n\\end{enumerate}\n\n\\noindent Here we see the derivation of the gradient of the squared-error loss for linear regression.\n\n\\begin{align}\n\\frac{\\kp \\frac{1}{2}\\sum_i \\left(f(x_i) - y_i\\right)^2}{\\kp b}\t&= \\frac{1}{2}\\frac{\\kp \\sum_i \\left(x_iw + b - y_i\\right)^2}{\\kp b} \\label{line:zero}\\\\\n&= \\frac{1}{2}\\sum_i \\frac{\\kp \\left(x_iw + b - y_i\\right)^2}{\\kp b} \\label{line:sum}\\\\\n&= \\frac{1}{2}\\sum_i \\frac{\\kp \\left(x_iw + b - y_i\\right)^ 2}{\\kp \\left(x_iw + b - y_i\\right)} \\frac{\\kp \\left(x_iw + b - y_i\\right)}{\\kp b} \\label{line:chain}\\\\\n&= \\sum_i \\left(x_iw + b - y_i\\right) \\frac{\\kp \\left(x_iw + b - y_i\\right)}{\\kp b} \\label{line:exp}\\\\\n&= \\ans{\\sum_i\\left ( x_iw + b - y_i\\right)}{...} \\label{line:final}\n\\end{align}\n\n\\begin{enumerate}[resume]\n\n% 12 A\n\\item To get from line (\\ref{line:zero}) to line (\\ref{line:sum}), we use the \n\\choices{Chain rule}{Product rule}{Exponent rule}{Sum rule \\an}\n\n%12 A\n\\item To get from line (\\ref{line:sum}) to line (\\ref{line:chain}), we use the \n\\choices{Chain rule \\an}{Product rule}{Exponent rule}{Sum rule}\n\n\\item In line \\ref{line:final}, the correct result is \n\\choicesv{$\\sum_i \\left({x_i}^2w + b - y_i\\right)$}{$\\sum_i x_i \\left(x_iw + b - y_i\\right)$}{$\\sum_i \\left( x_iw + b - y_i\\right)$ \\an}{$\\sum_i \\left(x_iw + b - y_i\\right)^2$}\n\n\\end{enumerate}\n\n\\section{ROC Curves and confusion matrices}\n\nIn this section, we'll look at evaluation metrics. This section covers the lecture ``Methodology 1'' and section 2.2 of Peter Flach's \\emph{Machine Learning} (see the PDF on Canvas).\n\nAs a running example, we will use the following classification dataset:\n\n\\begin{center}\n\t\\begin{tabular}{c c c c}\n\t\t& ${x_1}$ & ${x_2}$ & label\\\\\n\t\t\\hline\n\t\t\\kc{a} & 1 & 0 & \\rc{Neg} \\\\\n\t\t\\kc{b} & 2 & 0 & \\bc{Pos} \\\\\n\t\t\\kc{c} & 3 & 0 & \\bc{Pos} \\\\\n\t\t\\kc{d} & $\\sfrac{1}{2}$ & 1 & \\bc{Pos} \\\\\n\t\t\\kc{e} & 2 & 2 & \\bc{Pos} \\\\\n\t\t\\kc{f} & 0 & 3 & \\rc{Neg} \\\\\n\t\t\\kc{g} & 1 & 3 & \\rc{Neg} \\\\\n\t\t\\kc{h} & 2 & 3 & \\rc{Neg} \\\\\n\t\t\\hline\n\t\\end{tabular}\n\\end{center}\nIf you have trouble with the exercises below, we recommend drawing the data in its feature space, and drawing the decision boundary of each classifier.\n\n\\subsection{A linear classifier}\n\n\\qu As a first classifier, $c_\\text{\\oc{lin}}$, we will use a diagonal line crossing all the points where $x_1 = x_2$. Points above this line will be classified as \\rc{Neg}, points below or on the line as \\bc{Pos}. How do we describe this classifier mathematically? Fill in the blanks:\n\t\\[\n\tc_\\text{\\oc{lin}}(x_1, x_2) = \\begin{cases} \\text{\\bc{Pos}} & \\text{ if } \\ans{x_1 \\geq x_2}{\\ldots} \\\\ \\text{\\rc{Neg}} & \\text{otherwise}\\end{cases}\\p\n\t\\]\t\n\\ans{The diagonal that the question asks for (the decision boundary) is the set of points where $x_1 = x_2$. If $x_1 > x_2$, we're above this line, so we should classify the point as \\bc{Pos}.}{}\n\n\\noindent $c_\\text{lin}$ is a simple classifier. Let's try a more complex one before we move on. \n\n\\qu Let $c_\\oc{2}$ be the classifier whose decision boundary crosses the points $(0, 1)$ and $(1, 1.5)$, with the class \\emph{Neg} above the line. Draw this line first. How do we define this classifier?\n\t\\[\n\tc_\\oc{2}(x_1, x_2) = \\begin{cases} \\text{\\bc{Pos}} & \\text{ if } \\ans{- 0.5 x_1 + x_2 - 1 < 0}{\\ldots} \\\\ \\text{\\rc{Neg}} & \\text{otherwise}\\end{cases}\n\t\\]\n\\ans{\n\nWe could fill the given values in to the equation $ax_1 + bx_2 + c = 0$ and solve for zero. But that would give us two problems: it's a lot of work, and we have two equations for three variables. There are infinitely many pairs $a$ and $b$ that would give us this decision boundary. Let's make things easier by assuming that $b$ is 1, and rewriting to $x_2 = -ax_1 - c$. This is just the familiar function for a line in the plane: $-a$ is the slope, and $-c$ is the bias.\n\nThe given points tell us that the line crosses the $x_2$ axis at 1, and the slope should be $0.5$. Thus, $-a = 0.5$ and $-c = 1$. A quick check tells us that for a point below the line, $(0,0)$, the quantity $- 0.5 x_1 + x_2 - 1$ is negative, so such points should be classified as \\bc{Pos}.\n\nHere is a diagram of the data and the boundaries for the two classifiers:\n\n{\\centering\n\\includegraphics[width=0.7\\linewidth]{{w3.linear}.pdf}\n}\n\n}{}\t\n\t\n\\qu We will compare the linear classifier $c_\\text{\\oc{lin}}$ with a \\emph{decision tree} classifier, $c_\\text{\\oc{tree}}$. Here is the decision tree:\n\n\\Tree[.{$x_2 > 1.5$?} [.{$x_1 > 0.5$?} [.{\\ans{\\bc{Pos}}{\\oc{A}}} ][.{\\ans{\\bc{Pos}}{\\oc{B}}} ] ][.{$x_1 > 1.5$?} [.{\\ans{\\rc{Neg}}{\\oc{C}}} ][.{\\ans{\\bc{Pos}}{\\oc{D}}} ] ] ]\n\n\\noindent If the inequality on the node is true, move right, otherwise move left.\n\nThis tree divides the feature space into four \\textbf{segments} (\\oc{A}, \\oc{B}, \\oc{C} and \\oc{D}). To each segment we assign the majority class in that segment (using \\bc{Pos} for a draw). Label the leaves \\oc{A}, \\oc{B}, \\oc{C} and \\oc{D} with classes.\n\n\\ans{Here is a diagram of the data and the boundaries for the tree classifier:\n\n{\\centering\n\\includegraphics[width=0.7\\linewidth]{{w3.tree}.pdf}\n}\n\n}{}\n\n\\qu In this exercise we don't do any training (we just evaluate the given classifiers), so we'll evaluate all metrics on a single given dataset.\n\nIf you do train, you would \\emph{split} your dataset. You would compute your evaluation metrics on the \\ans{validation data}{\\ldots} during hyperparameter selection and on the \\ans{test data}{\\ldots} during final testing.\n\n\nEvaluating on the training data is the worst sin you can commit in Machine Learning. Can you think of a situation when you would still want to \\emph{compute} the training loss?\n\n\\ans{Getting good training loss, but poor validation loss is a sure sign of overfitting. If overfitting is likely (as it is in decision trees and neural networks), you may want to compare the training loss to the validation loss to see if overfitting explains the poor performance.}{}\n\n\\qu Give the \\emph{confusion matrices} for classifiers $c_\\text{\\oc{lin}}$ and $c_\\text{\\oc{tree}}$. \n\\ans{\n\n\\begin{center}\n\\begin{tabular}{c c | c c}\n$c_\\text{\\oc{lin}}$ & & predicted & \\\\\n & & Pos & Neg \\\\\n\\hline \ntrue & Pos & 3 & 1 \\\\\n & Neg & 1 & 3 \\\\\n\\end{tabular}\n\\end{center}\n\n\\begin{center}\n\\begin{tabular}{c c | c c}\n$c_\\text{\\oc{tree}}$ & & predicted & \\\\\n & & Pos & Neg \\\\\n\\hline \ntrue & Pos & 4 & 0 \\\\\n & Neg & 2 & 2 \\\\\n\\end{tabular}\n\\end{center}\n}{}\n\n\\qu From the confusion matrices, we can compute several metrics. Compute the accuracy, precision, recall, true positive rate and false positive rate\n\n\\ans{\nWe compute these metrics from the four values of the confusion matrix: the number of true positives (TP), true negatives (TN), false positives (FP) and false negatives(FN):\n\n\\begin{center}\n\\begin{tabular}{c c | c c}\n & & predicted & \\\\\n & & \\bc{Pos} & \\rc{Neg} \\\\\n\\hline \ntrue & \\bc{Pos} & T\\bc{P} & F\\rc{N} \\\\\n & \\rc{Neg} & F\\bc{P} & T\\rc{N} \\\\\n\\end{tabular}\n\\end{center}\n\n\\begin{center}\n\\bgroup\n\\def\\arraystretch{2}\n\\begin{tabular}{r c c c}\n& & $c_\\text{\\oc{lin}}$ & $c_\\text{\\oc{tree}}$\t \\\\\n\\hline\naccuracy & $\\frac{T\\bc{P} + T\\rc{N}}{\\text{total}}$ & $\\sfrac{3}{4}$ & $\\sfrac{3}{4}$ \\\\\nprecision & $\\frac{T\\bc{P}}{T\\bc{P} + F\\bc{P}}$ & $\\sfrac{3}{4}$ & $\\sfrac{2}{3}$\\\\\nrecall & $\\frac{T\\bc{P}}{T\\bc{P} + F\\rc{N}}$ & $\\sfrac{3}{4}$ & $1$ \\\\\ntrue positive rate & $\\frac{T\\bc{P}}{T\\bc{P} + F\\rc{N}}$ & $\\sfrac{3}{4}$ & $1$ \\\\\nfalse positive rate & $\\frac{F\\bc{P}}{T\\rc{N} + F\\bc{P}}$ & $\\sfrac{1}{4}$ & $\\sfrac{1}{2}$\\\\\n\\end{tabular}\n\\egroup\n\\end{center}\n\nMost of these are pretty intuitive, if you work out the meaning of the various sums. For instance, the false positive rate is the proportion of actual negatives, that were predicted to be positive.\n\n}{}\n\n\\noindent To plot a ROC and precision/recall curves, and to compute AUC metrics, we need to turn our simple binary classifier into a \\emph{ranking} classifier. That is, we don't just want classifications, we want it to rank the data from most \\rc{Neg} to most \\bc{Pos}. How we do this depends on the classifier. \n\n\\qu How do we turn a linear classifier into a ranking classifier? Give the ranking that $c_\\text{lin}$ assigns to the training data.\n\n\\ans{We compute the distance to the classification boundary (the negative distance on one side, and the positive on the other), and rank points by this distance. For this course (the homework and the exam), you don't actually need to compute the distance, it's fine to draw the dataset and ``measure'' the distances. We'll make sure that all examples allow this approach.\n\nHere's the sort of diagram you should end up with:\n\n{\\centering\n\\includegraphics[width=0.9\\linewidth]{{w3.ranking}.pdf}\n}\n\n\n\nSo, for $c_\\text{\\oc{lin}}$ the ranking from negative to positive is\n\\[\n\\bf{\\rc{f}~\\rc{g}~\\rc{h}~\\bc{d}~\\bc{e}~\\rc{a}~\\bc{b}~\\bc{c}}~\\text{.}\n\\]}{}\n\n\\qu\nHow do we turn a decision tree classifier into a ranking classifier? Give the ranking that $c_\\text{tree}$\n assigns to the training data.\n\n\\ans{\nWe group the points by the way the decision tree segments the feature space. We then assign each segment a class probability based on the relative frequencies of \\emph{training} data points. We sort the groups by class probability. Points within the same group are ranked equal.\n\nFor $c_\\text{\\oc{tree}}$ the ranking from negative to positive is\n\\[\n(\\rc{\\bf{f}}~\\rc{\\bf{g}})~(\\rc{\\bf{h}}~\\bc{\\bf{e}})~(\\rc{\\bf{a}}~\\bc{\\bf{b}}~\\bc{\\bf{c}})~(\\bc{\\bf{d}}) \\text{.}\n\\]\nBrackets indicate equal rank.\n}{}\n\nWe can't tell whether our ranking is perfect, because the training data doesn't give us a correct \\emph{ranking}, only a correct \\emph{labeling}. But for some pairs of instances we \\emph{do} know how they should be ranked: all pairs of positive and negative examples. \n\n\nWe can visualize this in a matrix with \\rc{negative} instances on the horizontal axis, and \\bc{positive} instances on the vertical, both sorted with the most positive (according to the classifier's ranking) in the bottom left corner. The matrix is usually colored \\gc{green} for pairs that are ranked correctly, \\rc{red} for pairs ranked incorrectly, and \\yc{yellow} for pairs that are ranked equal.\n\n\\qu\n\n\\begin{enumerate}\n\\item Draw the coverage matrices of $c_\\text{\\oc{lin}}$ and $c_\\text{\\oc{tree}}$.\n\n\\ans{\n\n\\begin{center}\n\\begin{tabular}{c | c c c c}\n\t\\bc{d} & \\cellcolor{DarkRed} & \\cellcolor{DarkGreen} & \\cellcolor{DarkGreen} & \\cellcolor{DarkGreen} \\\\\n\t\\bc{e} & \\cellcolor{DarkRed} & \\cellcolor{DarkGreen} & \\cellcolor{DarkGreen} & \\cellcolor{DarkGreen} \\\\\n\t\\bc{b} & \\cellcolor{DarkGreen} & \\cellcolor{DarkGreen} & \\cellcolor{DarkGreen} & \\cellcolor{DarkGreen} \\\\\n\t\\bc{c} & \\cellcolor{DarkGreen} & \\cellcolor{DarkGreen} & \\cellcolor{DarkGreen} & \\cellcolor{DarkGreen} \\\\\n\t\\hline\n\t$c_\\text{\\oc{lin}}$ & \\rc{a} & \\rc{h} & \\rc{g} & \\rc{f} \\\\\t\n\\end{tabular}\t\n\\end{center}\n\n\\begin{center}\n\\begin{tabular}{c | c c c c}\n\t\\bc{e} & \\cellcolor{DarkRed} & \\cellcolor{DarkOrange} & \\cellcolor{DarkGreen} & \\cellcolor{DarkGreen} \\\\\n\t\\bc{c} & \\cellcolor{DarkOrange} & \\cellcolor{DarkGreen} & \\cellcolor{DarkGreen} & \\cellcolor{DarkGreen} \\\\\n\t\\bc{b} & \\cellcolor{DarkOrange} & \\cellcolor{DarkGreen} & \\cellcolor{DarkGreen} & \\cellcolor{DarkGreen} \\\\\n\t\\bc{d} & \\cellcolor{DarkGreen} & \\cellcolor{DarkGreen} & \\cellcolor{DarkGreen} & \\cellcolor{DarkGreen} \\\\\n\t\\hline\n\t$c_\\text{\\oc{tree}}$ & \\rc{a} & \\rc{h} & \\rc{f} & \\rc{g} \\\\\t\n\\end{tabular}\t\n\\end{center}\n\n}{}\n\n\\item How many ranking errors does each classifier make on the training data? \n\\ans{$c_\\text{lin}$ makes 2 ranking errors. $c_\\text{tree}$ makes 2.5, counting each tie as half a ranking error.}{}\n\n\\item If we have class imbalance (one class has more instances than the other), how can we tell by the coverage matrix?\n\n\\ans{It will be non-square. The more stretched out, the higher the class imbalance.}{}\n\n\\end{enumerate}\n\n\\qu How do we convert a coverage matrix to an \\textbf{ROC plot}? How does the green area in a coverage matrix relate to the ROC plot? How do they differ?\n\n\\ans{We can convert the coverage matrix to ROC space by normalizing the axes. That is, if we have a green cell at $(2, 3)$, counting from the bottom left, we can draw a point in ROC space at $(\\sfrac{2}{4}, \\sfrac{3}{4})$. That is, we know we have a classifier that can achieve a true positive rate of $\\sfrac{3}{4}$ and a false negative rate of $\\sfrac{2}{4}$.\n\n\n{\\centering\n\\includegraphics[width=0.9\\linewidth]{{w3.roc}.pdf}\n}\n\nThe green area gives us an estimate of the probability of a ranking error. The same is true of the \\emph{Area Under the Curve}. For the latter, we draw the convex hull of all achievable classifiers, and compute the area.\n\nAn important difference is that the green area in a coverage matrix may be \\emph{concave}. For instance:\n\n\\begin{center}\n\\begin{tabular}{c | c c c c}\n\te & \\cellcolor{DarkRed} & \\cellcolor{DarkRed} & \\cellcolor{DarkRed} & \\cellcolor{DarkGreen} \\\\\n\tc & \\cellcolor{DarkRed} & \\cellcolor{DarkRed} & \\cellcolor{DarkRed} & \\cellcolor{DarkGreen} \\\\\n\tb & \\cellcolor{DarkRed} & \\cellcolor{DarkRed} & \n\t \\cellcolor{DarkRed} & \\cellcolor{DarkGreen} \\\\\n\td & \\cellcolor{DarkGreen} & \\cellcolor{DarkGreen} & \\cellcolor{DarkGreen} & \\cellcolor{DarkGreen} \\\\\n\t\\hline\n\t$c_\\text{poor}$ & a & h & f & g \\\\\t\n\\end{tabular}\t\n\\end{center}\n\nThe corresponding ROC curve is convex (it covers the bottom right half of the ROC space).\n\nSince a classifier with AUC below 0.5 is pretty useless, we don't usually worry about this. The differences between the (normalized) coverage matrix and the ROC space are not important for reasonable classifiers and large datasets.\n\n}{}\n\n\\section{Whitening}\n\n\\paragraph{Basis systems} The \\emph{standard basis system} (in 2D) is just the vectors $b_1 =\\begin{pmatrix}1 \\\\0\\end{pmatrix}$ and $b_2 = \\begin{pmatrix}0 \\\\1\\end{pmatrix}$. When a point has coordinates $(x, y)$, that just means that we can get to the point by adding $x$ times the $b_1$ vector to $y$ times the $b_2$ vector.\n\nFor the standard basis, we just end up at the point $\\begin{pmatrix}x \\\\y\\end{pmatrix}$. But we can also use a nonstandard basis. If a point $p$ has coordinates $(x, y)$ in the coordinate system with basis vectors $b_1$, $b_2$, it means that $p$ has coordinates $xb_1 + yb_2$ in the standard basis system. \n\n\\qu Convert the following points to a representation in the standard basis system.\n\n\\begin{enumerate}\n\t\\item The point $\\begin{pmatrix}1 \\\\1\\end{pmatrix}$ expressed in the coordinate system with basis vectors $b_1 = \\begin{pmatrix}2 \\\\0\\end{pmatrix}$, $b_2 = \\begin{pmatrix}0 \\\\2\\end{pmatrix}$. \\ans{$x = 1, y=1$, so we get to the standard basis point by computing $1 \\cdot b_1 + 1 \\cdot b_1 = \\begin{pmatrix}2 \\\\2\\end{pmatrix}$}{}\n\t\\item The point $\\begin{pmatrix}5 \\\\3 \\end{pmatrix}$ expressed in the coordinate system with basis vectors $b_1 = \\begin{pmatrix}0 \\\\1\\end{pmatrix}$, $b_2 = \\begin{pmatrix}1 \\\\0\\end{pmatrix}$. \\ans{$\\begin{pmatrix}3 \\\\5 \\end{pmatrix}$}{}\n\t\\item The point $\\begin{pmatrix}1 \\\\2 \\end{pmatrix}$ expressed in the coordinate system with basis vectors $b_1 = \\begin{pmatrix}1 \\\\2\\end{pmatrix}$, $b_2 = \\begin{pmatrix}3 \\\\4\\end{pmatrix}$. \\ans{$\\begin{pmatrix} 7\\\\ 10\\end{pmatrix}$}{}\n\\end{enumerate}\n\n\\qu A basis system is \\textbf{orthonormal} if two conditions hold:\n\\begin{enumerate}\n\t\\item \\ans{The basis vectors all have norm (i.e. length) 1. (normality)}{\\ldots}\n\t\\item \\ans{The angles between any two basis vectors are $90\\deg$. (orthogonality) }{\\ldots}\n\\end{enumerate}\nConsider the following three bases: \n\\[\n\t\\A = \\begin{pmatrix}0 & 1\\\\1 & 1\\end{pmatrix} \\;\\;\n\t\\B = \\begin{pmatrix}1 & -1\\\\1 & 1\\end{pmatrix} \\;\\;\n\t\\bm{C} = \\sqrt{\\sfrac{1}{2}}\\begin{pmatrix}1 & -1\\\\1 & 1\\end{pmatrix}\n\\]\nThe columns of each matrix are the basis vectors (it may help to draw them in standard coordinates). Which of these have orthogonal basis vectors? Which one is orthonormal?\n\\ans{The columns of $\\A$ are neither normal nor orthogonal. Matrix $\\B$ has orthogonal columns, but they are not unit vectors (vectors of length one). Matrix $\\C$ represents an orthonormal basis.}{}\n\n\\qu Why is it useful to have an orthonormal basis?\n\\ans{Matrices representing an orthonormal basis are \\emph{orthogonal}. This means that $\\C^{-1} = \\C^T$. This means that we can easily transform from and to the basis without having to compute an expensive matrix inverse.}\n\n\\paragraph{Covariance and normal distributions}\n\nPCA is closely related to the normal distribution. We can think of PCA as a basis transformation that makes it look like the data was sampled from a standard multivariate normal distribution: it makes the variance 1 in every dimension, and the covariance 0 for every pair of dimensions.\n\n\\qu Here is some data.\n\n\\begin{tabular}{c c}\n$x_1$ & $x_2$ \\\\\n\\hline\n0 & 2 \\\\\n2 & 0 \\\\\n0 & 2 \\\\\n2 & 0 \\\\\n\\hline\n\\end{tabular}\n\n\\noindent Compute the sample covariance.\n\n\\ans{\nWe first compute the sample mean: $\\bm{m} = \\begin{pmatrix} 1 \\\\ 1\\end{pmatrix}$. \n\nSubtracting the sample mean, and arranging the data in a matrix (with instances as columns), we get\n\\[\n\\X = \\begin{pmatrix} -1 & 1 & -1 & 1 \\\\ 1 & -1 & 1 & -1 \\end{pmatrix} \\p\n\\]\n\nThe sample covariance is\n\\begin{align*}\n\\bm{S} = \\frac{1}{n-1} \\X\\X^T = \\frac{1}{3}\\begin{pmatrix} 4 & -4 \\\\ -4 & 4 \\end{pmatrix}\n\\end{align*}\n}{}\n\n\\noindent Let $\\y = \\A\\x + \\bt$ be an \\emph{affine} transformation (a linear transformation $\\A$ followed by a translation $\\bt$). We draw $\\x$ from a standard normal distribution\n\\[\nN(\\mathbf{0}, \\mathbf{I}) = N\\left( \\begin{pmatrix}0 \\\\ 0\\end{pmatrix}, \\begin{pmatrix}1 & 0 \\\\ 0 & 1\\end{pmatrix} \\right)\n\\]\nand compute $\\y$. This is equivalent to sampling from a normal distribution with mean $\\bm{\\mu} = \\bt$ and covariance $\\bm{\\Sigma} = \\A\\A^T $.\n\n\\qu Let \n\\[\n\\mathbf{A} = \\begin{pmatrix} 1 & 0 \\\\ 0 & 2\\end{pmatrix}, \\mathbf{t} = \\begin{pmatrix} 1 \\\\ 1\\end{pmatrix}\n\\]\nSampling $\\x$ from $N(\\bm{0}, \\bm{I})$ is easy: we just sample $x_1$ and $x_2$ independently from a \\emph{uni}variate standard normal distributions. Here are some \\href{https://goo.gl/Jw7Hjm}{standard normally distributed numbers}:\n\\[\n0.5, 1.1, 0.1, 0.9, -0.2, 1.3\n\\]\n\n\\noindent Turn these into three samples from $N(\\bm{0}, \\bm{I})$ and transform them to samples from $N(\\bm{\\mu},\\bm{\\Sigma})$.\n\n\\ans{\nUsing samples\n\\[\n\\x^1 = \\ma{0.5, & 1.1}^T, \\;\\; \\x^2 = \\ma{0.1, & 0.9}^T \\;\\; \\x^3 = \\ma{-0.2, & 1.3}^T\n\\]\nand computing $\\y^1 = \\A\\x^1 + \\bt$, we get:\n\\[\n\\y^1 = \\ma{1.5, & 3.2}^T, \\;\\; \\y^2= \\ma{1.1, & 2.8}^T \\;\\; \\y^3 = \\ma{0.8, & 3.6}^T\\p\n\\]\n}{}\n\n\n\\paragraph{Bonus question:} Compute the sample covariance of the resulting data, and the actual covariance $\\Sigma$.\n\n\\ans{For the sample covariance, follow the same procedure as in the previous question. After a bit of calculating, we get:\n\\[\n\\bf{S} \\approx \\ma{0.123 & 0.06\\\\0.06 & 0.16}\n\\]\n\nThe true covariance we get by computing $\\bf{\\Sigma} =\\A\\A^T = \\ma{1 & 0 \\\\ 0 & 4}$. They're quite different at the moment. If we increase the size of the sample, $\\bf{S}$ will converge to $\\bf{\\Sigma}$.\n}{}\n%\n%\\paragraph{Singular value decomposition}\n%\\emph{These questions may be a little challenging if you're new to Linear Algebra. If you're struggling, have another look at the slides from the \\emph{Methodology 2} lecture. If you can't work it out, read the answer, and see if you can repeat the process on another matrix.}\n%\n%\\begin{Exercise}\n%Let $\\A$ be a linear transformation. This transformation has two eigenvectors, which are aligned with the standard basis vectors. The eigenvalue along the horizontal axis is $3$, and along the vertical axis is $2$. What is $\\A$?\n%\n%\\ans{$\\A$ is a \\emph{scaling matrix}. That means it's a diagonal matrix, with the eigenvalues on the diagonal: \n%\\[\n%\\begin{pmatrix} 3 & 0 \\\\ 0 & 2 \\end{pmatrix}\n%\\]\n%}{}\n%\\end{Exercise}\n%\n%Let $\\B$ be a linear transformation. $\\B$ has two eigenvectors, one points in the direction of the horizontal axis rotated by 45 degrees, and the other in the direction of the vertical axis rotated by 45 degrees.\n%The eigenvalue for the first is 5, and for the second is 2. What is $\\B$?\n%\\ans{\n%If the eigenvectors were axis-aligned (as with $\\A$), $\\B$ would be \n%\\[\n%\\bm{Z} = \\begin{pmatrix} 5 & 0 \\\\ 0 & 2 \\end{pmatrix}\n%\\]\n%We can use this by decomposing $\\B$ in three steps: rotating by -45 degrees to align the axes to the eigenvectors, applying $\\bm{Z}$ and rotating back. The rotation matrix for a 45 degree rotation is\n%\\[\n%\\U = \\sqrt{\\sfrac{1}{2}}\\begin{pmatrix} 1 & -1 \\\\ 1 & 1\\end{pmatrix} \\p\n%\\]\n%Since $\\U$ is orthogonal (its columns form an orthonormal basis), we can take the transpose $\\U^T$ to rotate back. Putting all this together, we get\n%\\[\n%\\B\\x = \\U\\Z\\U^T\\x \\p\n%\\]\n%\n%This is the eigenvalue decomposition of $\\B$. This gives us\n%\n%\\begin{align*}\n%\\B = \\U\\Z\\U^T &= \\sqrt{\\sfrac{1}{2}}\\begin{pmatrix}1 & -1\\\\1 & 1\\end{pmatrix}\\begin{pmatrix} 5 & 0 \\\\ 0 & 2\\end{pmatrix}\\sqrt{\\sfrac{1}{2}}\\begin{pmatrix}1 & 1\\\\-1 & 1\\end{pmatrix}\\\\\n%&= \\frac{1}{2}\\begin{pmatrix}1 & -1\\\\1 & 1\\end{pmatrix}\\begin{pmatrix} 5 & 0 \\\\ 0 & 2\\end{pmatrix}\\begin{pmatrix}1 & 1\\\\-1 & 1\\end{pmatrix}\\\\\n%&= \\frac{1}{2}\\begin{pmatrix}5 & -2\\\\5 & 2\\end{pmatrix}\\begin{pmatrix}1 & 1\\\\-1 & 1\\end{pmatrix} \\\\\n%&= \\frac{1}{2}\\begin{pmatrix}7 & 3\\\\3 & 7\\end{pmatrix} = \\begin{pmatrix}3.5 & 1.5\\\\1.5 & 3.5\\end{pmatrix}\n%\\end{align*}\n%\n%%As usual, we can check with \\href{https://goo.gl/v8d4Yg}{Wolfram Alpha} to see we haven't made any mistakes. You may get $-\\U$ instead of $\\U$. The negatives cancel out, so the SVD can work out both ways.\n%}{}\n\n\\end{document}", "meta": {"hexsha": "c95e17415e7755b828f3507732d7488d49451c82", "size": 23055, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "week3.tex", "max_stars_repo_name": "mlvu/homework", "max_stars_repo_head_hexsha": "2183b91c2a355279fbe958b1bbc8bd13ea956615", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-02-27T13:25:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-07T07:04:26.000Z", "max_issues_repo_path": "week3.tex", "max_issues_repo_name": "mlvu/homework", "max_issues_repo_head_hexsha": "2183b91c2a355279fbe958b1bbc8bd13ea956615", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "week3.tex", "max_forks_repo_name": "mlvu/homework", "max_forks_repo_head_hexsha": "2183b91c2a355279fbe958b1bbc8bd13ea956615", "max_forks_repo_licenses": ["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.0428893905, "max_line_length": 471, "alphanum_fraction": 0.6863153329, "num_tokens": 7601, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47657965106367595, "lm_q2_score": 0.34158249943831703, "lm_q1q2_score": 0.1627912683917714}} {"text": "This is implementation of efficient and simple model for simulation of\nHigh-resolution atomic force microscopy (AFM), scanning probe microscopy (STM)\nand inelastic tunneling microscopy (IETS) images using classical forcefileds. \n\nThere are two versions of the code:\n\n\\begin{enumerate}\n \\item currently developed Python/C++ version in PyProbe\\_nonOrtho (branch master\n );\n to get quick esence of this model you can also try web interface hostet here: http://nanosurf.fzu.cz/ppr/\n for more details see wikipage:\n https://github.com/ProkopHapala/ProbeParticleModel/wiki\n \\item Legacy fortran version in SHTM\\_springTip2 (branch fortran );\n more detailed description o the fortran version is here:\n http://nanosurf.fzu.cz/wiki/doku.php?id=probe\\_particle\\_model \n\\end{enumerate}\n\\cite{phapalamechhighresol}\n\\cite{phapalaoriginhighresol}\n\n\n\\section{C++ \\& Python version}\n\n\\subsection{Examples of results}\n\n\n\\subsection{How it works}\n\n\\begin{itemize}\n\n \\item Pauli-repulsion ( currently approximated by repulsive part of\n Lenard-Jones potential $r^{-12}$ )\n \\item van der Waals attraction ( currently approximated by attractive part\n of Lenard-Jones potentia $r^{-6}$ )\n \\item electrostatic ( currently can be computed as coulomb pairwise\n interaction between PP and point charges in centers of atoms of sample, or\n by reading electrostatic force-field obtained by derivative of sample\n Hartree potential as described in supplementary of this paper\n \\cite{phapalaoriginhighresol}.\n\n\\end{itemize}\n\nThe computation of images is divided into two parts:\n\\begin{enumerate}\n \\item Precompute vector Forcefield ( Fx(x,y,z), Fy(x,y,z), Fz(x,y,z) ) over\n sample and store it on a 3D-grid. ( see getLenardJonesFF and getCoulombFF\n functions for more details ). After individial components of forcefiled are\n sampled ( i.e. Lenard-Jones and electrostatic ) they are summed up to form\n one single total effective forcefield in which Probe-Particle moves.\n \n \\item relax Probe-Particle attached to the tip under influence of the total\n effective forcefield. The relaxation of Probe-Particle is done using \"Fast\n Inertial Realxation Engine\" (FIRE) algorithm\n \\cite{ebitzekstructrelaxmadesimple}. implemented in\n FIRE:move() function. In each step of relaxation the forcefield on the grid\n is interpolated in interpolate3DvecWrap function, considering periodic\n boundary condition. From python the relaxation is called as relaxTipStroke\n function providing 1D-array of tip positions, and obtaining back 1D-array of\n Probe-Particle position after the relaxation and of force between tip\n ProbePartcile and sample at that position. The lateral scan in (x,y) to\n obtained stack of images is done by calling relaxTipStroke at different\n (x,y) position of tip, where each call of relaxTipStroke does one approach\n along z-direction.\n\n\\end{enumerate}\n\n\\subsection{Why it is splitted like this ?}\n\nThis splitting of computation ( first sampling of forcefiled on the grid, and\nthan relaxation using interpolation) has several advantages over strightforward\ncomputation of interaction on the fly during relaxation process.\n\n\n\\begin{itemize}\n\n \\item \\textbf{It is faster} - if there is ~100 atoms of sample, summing over\n each pairwise Lennard-Jones interactions, is much slower, than just\n interpolating the forcefield from the grid. Because force evaluation is done\n several-times for each voxel of the 3D scanning grid, it is more efficient\n to precompute it just once for each voxel, and then interpolate.\n\n \\item \\textbf{It is more flexible and general} - Decoupling of relaxation\n process and computation of forcefiled allows us to plug-in any forcefield.\n The original motivation was to used electrostatic forcefield obtained from\n Hartree potential from DFT calculation. However, it is not limited to that.\n We can plug in e.g. a derivative of potential energy of probe peraticle\n (i.e. Xe or CO ) obtained by scanning it in DFT code, in similar way as Guo\n did in \\cite{chshguohighresolmodel} . The only limitation here is computational cost of obtaining\n such potential from ab-initio calculation.\n\\end{itemize}\n\n\n\n\\subsection{Code structure}\nThe code is divided into Python and C++, where performance intensive\ncomputations are done in C++ and python is used as convenient scripting\ninterface for doing tasks like file I/O, plotting, memory management. For\nbinding of Python and C++ is used python ctypes library. \n\n\n\\subsubsection{Dependencies:}\n\\begin{itemize}\n \\item \\textbf{C++} : g++ ( tested with g++ (Ubuntu 4.8.1-2ubuntu1~12.04) 4.8.1 )\n \\item \\textbf{Python} : python ( 2.7.3 ), numpy (1.9.2), matplotlib ( 1.4.3 ), ctypes\n ( 1.1.0 )\n\\end{itemize}\n\n\\subsubsection{C++ source:}\n\\begin{itemize}\n \\item ProbeParticle.cpp - implementation of all performance intensive\n ProbeParticle model as dynamic library which can be called dynamically from\n python.\n \\item Vec3.cpp,Mat3.cpp math subroutines for operations with 3D vectors and\n metrices\n\\end{itemize}\n\n\\subsubsection{Python source:}\n\\begin{itemize}\n \\item ProbeParticle.py - Interface between C++ core and python ising\n C-types. Here are also defined some python rutines like: \n \\begin{itemize}\n \\item conversion from Force to frequency shift ( Fz2df ),\n \\item evaluation of Lenard-Jones coeffitints ( getAtomsLJ )\n \\item copy sample geometry to simulate periodic boundary condition (\n PBCAtoms )\n \\item automatic setup of imagining area acroding to geometry of\n nonperiodic sample ( autoGeom )\n \\item default parameters of simulation ( params ) with subroutine to\n read this parameters from a file ( loadParams )\n \\end{itemize}\n\n\n \\item test2.py, testServer2.py - two examples of python scripts with run\n actual computations using ProbeParticle library. The idea is that this files\n can be modified by user to match particular task\n \\item basUtils.py - routines for loading of molecule geometry from\n xyz-format, ( loadAtoms ), finding bonds and other.\n \\item Element.py and elements.py contains just parameters of atoms form\n periodic table ( like effective raidus, color for visualization etc. ). It\n is used by basUtils.py\n\n \n\n\\end{itemize}\n\n", "meta": {"hexsha": "836fff8341850de9793820fef328a046b79010a4", "size": 6380, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/intro/intro.tex", "max_stars_repo_name": "eimrek/ProbeParticleModel", "max_stars_repo_head_hexsha": "31494db595cdc1763de5fb73b2f63dfe8280e7fe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 26, "max_stars_repo_stars_event_min_datetime": "2015-10-21T21:02:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-17T11:40:28.000Z", "max_issues_repo_path": "doc/intro/intro.tex", "max_issues_repo_name": "eimrek/ProbeParticleModel", "max_issues_repo_head_hexsha": "31494db595cdc1763de5fb73b2f63dfe8280e7fe", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2015-10-26T14:11:25.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-23T10:04:11.000Z", "max_forks_repo_path": "doc/intro/intro.tex", "max_forks_repo_name": "eimrek/ProbeParticleModel", "max_forks_repo_head_hexsha": "31494db595cdc1763de5fb73b2f63dfe8280e7fe", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20, "max_forks_repo_forks_event_min_datetime": "2015-07-13T14:39:59.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-03T12:52:36.000Z", "avg_line_length": 44.0, "max_line_length": 113, "alphanum_fraction": 0.7456112853, "num_tokens": 1560, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.30404166235418484, "lm_q1q2_score": 0.1626922157627471}} {"text": "% !TEX root = collhdl_ICRA_17.tex\n\n\\section{Evaluation and Case Studies}\n\\label{sec:simu}\n\n\\subsection{General Simulation Setup}\n\\label{sec:setup}\nThe simulative setup is as follows.\nWe apply our collision detection, isolation and identification algorithm in simulation to an \\emph{Atlas} robot consisting of cylinders and cuboids as collision geometry from \\cite{DRCSim}.\nWe assume perfect measurements of the generalized joint forces and the force/torque sensors unless stated differently, meaning all sensors measure the true value without noise or delay.\nForce/torque sensors are placed at the end-effectors (feet and hands), before the first arm and leg joints and at the upper torso after the three back joints (see Fig.~\\ref{fig:coll_singlecontact_overview}).\nFurthermore, all acting external forces comply with the assumption of a pushing force and the line of action of the forces is chosen such that it does not intersect with any other collision body before the contact point.\nThe robot pose (see Fig.~\\ref{fig:coll_singlecontact_overview}) has been chosen in such a way that the whole body Jacobian has full rank.\nThe robot is modeled in free space, meaning there are no other external forces acting on the robot than the collision forces.\nThe simulation is done on a standard Core i7-3770 PC and the algorithm is run as compiled Matlab functions.\nWith the current implementation, the majority of the runtime for all contact cases is spent on the not yet optimized intersection algorithm.\n\n\\subsection{Ideal Analysis of Single Contacts}\n\\label{sec:eval_single_static}\nWe compare the ideal performance of the isolation based on estimated generalized external forces $\\hat{\\bm{\\tau}}_\\epsilon$ only (Sec.~\\ref{sec:isolation}) to the isolation based only on force/torque sensor measurements $\\hat{\\bm{\\mathcal{F}}}_{\\mathrm{ext},S}$ (from (\\ref{eqn:cmp})) for a single contact.\nDynamic effects due to the observer and load compensation are neglected for sake of clarity.\nThe contact points are distributed randomly and equally over the robot surface.\nFigure~\\ref{fig:coll_singlecontact_overview} depicts the results of the isolation procedures with some representative samples of the 3000 tested points.\nWith both methods, the contact points are isolated correctly up to rounding errors, if possible.\nThe contacts at the pelvis cannot be seen by any force/torque sensor and can therefore only be isolated with the generalized external forces acting on the base.\nThe maximum and mean execution times for the isolation of the one contact in this experiment were 0.67~ms and 0.25~ms using force/torque sensors as well as 0.57~ms and 0.17~ms using joint torque measurements only.\n\\begin{figure}\n\\begin{center}\n\\begin{overpic}{figures/collest_single_allresults_nosim/coll_est_sc_all_nosim}\n\\put(82,54){\\line(-1,-2){7}}\n\\put(56,11){\\line(1,2){11}}\n\\put(67,35){F/T sensor}\n\\end{overpic}\n\\end{center}\n\\caption{Distribution of true ($\\bm{r}_\\mathrm{C}$) and estimated contact locations using two different methods.\nThe points $\\hat{\\bm{r}}_C(\\hat{\\bm{\\tau}}_\\epsilon)$ are isolated using only generalized external forces and the points $\\hat{\\bm{r}}_C(\\hat{\\bm{\\mathcal{F}}}_{\\mathrm{ext,S}})$ are isolated using the force/torque sensor measurements only.\nFor the pelvis (base link) and first torso links, no force measurement is available. Therefore contact points at these links cannot be found with the latter method.\nAll overlying points are identical up to rounding errors.}\n\\vspace*{-0.8cm}\n\\label{fig:coll_singlecontact_overview}\n\\end{figure}\n\n\\subsection{Ideal Analysis of Multiple Contacts}\n\\label{sec:eval_multi_static}\nIn the following, we analyze multiple contacts of the type specified in Sec.~\\ref{sec:eval_single_static}.\n\n\\subsubsection{Two Contacts at different links}\n\nThe considered contact points are located at different links, since two contacts at the same link cannot be located in our setup. In order to be able to do so, one would need two force/torque sensors in the same link.\n5000 random combinations were examined.\n\nThe algorithm using generalized forces is able to isolate all two contact point coordinates up to rounding errors if the rank of the Jacobian in (\\ref{eqn:force_identification}) is sufficiently high, e.g. $\\mathrm{rank}(\\bm{J})=12$ for $N_\\mathrm{C}=2$ contact points.\nFigure~\\ref{fig:coll_multicontact_rankJ} shows the success of the isolation for different contact links, which is equivalent to the plot of the rank deficit\n\\begin{equation}\nRD=6N_\\mathrm{C}-\\mathrm{rank}(\\bm{J}).\n\\label{eqn:rank_deficit}\n\\end{equation}\nFor example, a contact at the pelvis (torso chain link 1) and another contact at the left lower leg (left leg chain link 4) does only produce 10 nonzero columns in the stacked Jacobian and the isolation fails (see corresponding entry in Fig.~\\ref{fig:coll_multicontact_rankJ}).\nIf instead the foot on the left leg chain (link 6) is in contact, then 12 nonzero columns exist and the isolation succeeds.\n\nFor a rank deficit, the isolation method minimizes the Cartesian error of the stacked identified wrenches and finds contact points on the entire following kinematic chain. \nThe distribution of errors for different ranks of the Jacobian is shown in Fig.~\\ref{fig:hist_rank_err_2coll}.\nAn error $\\leq$ 25~cm occurs in about 80\\% of the cases with the joint configuration from Fig.~\\ref{fig:coll_singlecontact_overview}.\nPlease note that in case of a rank deficit, the algorithm may accidentally estimate an additional contact point, which would be located close to the base.\nThe error is then calculated between the real contact points and the ones estimated in the same kinematic chain.\nThe maximum and mean execution times for the isolation in this experiment were 0.75~ms and 0.28~ms using force/torque sensors as well as 31.8~ms and 3.6~ms using joint torque measurements only.\n\n\\begin{figure}\n\\begin{center}\n\\includegraphics[width=\\columnwidth]{figures/collest_multi_stat_2coll_rankmat/rankmat_fig_2coll_Modus2}\n\\end{center}\\vspace*{-0.3cm}\n\\caption{Overview of success and failure for the isolation of two simultaneous contacts.\nThe $x$-axis gives the first contact link and the $y$-axis the second one.\nThe second and the last body of the torso chain have no collision body in the model, the according columns are therefore left empty.\nA green upward triangle marks the successful isolation of both contact points for the given combination.\nA red downward triangle marks a combination for which it was impossible to isolate the contacts correctly due to rank loss of the combined Jacobian in (\\ref{eqn:multi_iso}).\nIn some fields, green and red triangles are plotted meaning that for this combination, the isolation was only partly correct.\nFor the combination of the fifth link in the right leg and the first link of the right arm, this is due to the fact, that for some contacts, the joint torque threshold for the last joint is not exceeded and the algorithm is therefore started with a loss of rank in the Jacobian.\nHowever, when reducing the joint torque threshold or starting the algorithm with the correct contact links, this could not be observed anymore.\nIn the other cases, the contact point was estimated correctly by accident with a rank deficient Jacobian.\nOverall 5000 combinations were tested.}\\vspace*{-0.5cm}\n\\label{fig:coll_multicontact_rankJ}\n\\end{figure}\n\n\\begin{figure}\n\\vspace*{-0cm}\n\\begin{center}\n% Um die Prozentangaben für Overpic zu generieren: Skript histogram_error_rank.m im Bildordner ausführen und aus Textausgaben entnehmen.\n\\begin{overpic}{figures/collest_multi_stat_2coll_error_rank/hist_rank_err_2coll}\n\\put(50,78){\\line(2,0){10}}\n\\put(63,76){$100\\%$}\n\n\\put(49,47){\\line(2,3){8}}\n\\put(56,61){$34\\%$}\n\n\\put(43,35){\\line(1,1){15}}\n\\put(55,52){$21\\%$}\n\n\\put(55,36){\\line(2,1){7}}\n\\put(55,40){$11\\%$}\n\n\\put(68,17){\\line(1,1){15}}\n\\put(80,34){$2\\%$}\n\\end{overpic}\n\\end{center}\n\\caption{Histogram of the maximum point estimation error for two contacts with different random contact configurations. Read: ``34\\% of the results for $\\mathrm{rank}(\\bm{J})=11$ lie between 15 and 25~cm.''}\n\\label{fig:hist_rank_err_2coll}\n\\vspace*{-0.3cm}\n\\end{figure}\n\n\\subsubsection{Contacts at four end-effectors}\n\nFor the considered 30~DoF humanoid, it is possible to detect and isolate up to $N_\\mathrm{C}=5$ contacts, if the rank deficit $RD$ is zero.\nThis is the case for four contacts at the end-effectors of every kinematic chain (feet, hands) and an additional contact located at the torso or first shoulder link, which is the typical manipulation scenario from Fig~\\ref{fig:manip}.\nThe distribution of position errors for this case are depicted in Fig.~\\ref{fig:error_rank_manipcoll} with markers for different rank deficits $RD$.\n\nWithout rank deficit, the isolation is successful in all but 5 of the 5000 examined points, where there was no rank deficit.\nThe errors occur in situations, where the joint torque threshold for the last joint in at least one chain is not exceeded.\nThis leads to a Jacobian with rank-deficit for the first iteration step of the algorithm, making it in a few cases impossible to find the correct contact link.\nHowever, if the threshold is reduced to $10^{-5}$~N or Nm (for all $\\lVert\\bm{f}_{\\mathrm{ext},i}\\rVert<1$), or the algorithm is started with perfect information about the contact links, no errors are observed.\nThe maximum and mean execution times for the isolation in this experiment were 0.92~ms and 0.52~ms using force/torque sensors as well as 43.2~ms and 11.0~ms using joint torque measurements only.\n\n\\begin{figure*}\n\\begin{center}\n\\includegraphics{figures/collest_multi_stat_manipcoll_error/error_rank_manipcoll_hist_breit}\n\\end{center}\\vspace*{-0.4cm}\n\\caption{Distribution of the isolation position error based on joint torques only with contacts at all end-effectors for different rank deficits $RD$ of the Jacobian.\nThe position error distributions are drawn over the location for a fifth contact.\nThe fifth contact location can be none (only four contacts) or any of the links, which are not an end-effector link.\nTherefore the four columns of the end-effectors are left empty.\nThe columns of the second and the last torso chain link are left empty, because their model does not have any contact bodies, making it impossible to place contacts at these links.\nMarkers in the lines denote the mean errors of all contact points including this link.\nThe distribution lines are normalized to the highest corresponding value of the distribution.}\\vspace*{-0.7cm}\n\\label{fig:error_rank_manipcoll}\n\\end{figure*}\n\n\\subsubsection{Benefits of additional force/torque sensors}\n\nThe results show the benefits of supplementary force/torque sensors, see Table~\\ref{tab:sensor_benefits}.\nWithout force/torque sensors, up to five contacts can be detected, isolated and identified correctly under certain conditions.\nWith force/torque sensors in the distal links, at least the generalized external manipulation and locomotion forces can be found and further contacts can be isolated by additional force/torque sensors (max. one per sensor) or the first method (up to 5 in theory).\n%\n\\begin{table}\n\\caption{Possibilities of collision detection, isolation and identification with different numbers of force/torque sensors in the kinematic tree. The sensors are meant to be added up down the lines of the table.}\\label{tab:sensor_benefits}\n\\begin{tabular}{|p{2.8cm}|p{5cm}|}\n\\hline\nsensors & possibilities\\\\\\hline\nonly joint torque and base movement sensors & identify ground contact and manipulation contacts, detect single collision, isolate and identify single collision under certain conditions (see Fig.~\\ref{fig:error_rank_manipcoll})\\\\\\hline\ndistal force/torque sensors & full elimination of ground contact and manipulation forces, detection isolation and identification of single collisions, multiple collisions can be detected, isolated and identified in many cases\\\\\\hline\nadditional force/torque sensors in the kinematic chains & detect isolate and identify one additional contact wrench per additional sensor\\\\\\hline\n\\end{tabular}\\vspace*{-0.3cm}\n\\end{table}\n\n\\subsection{Time Series Analysis of a Single Contact}\nThe influence of the observer dynamics on the isolation and identification is investigated by using generalized external forces including observer dynamics.\nThe external force acts over a sinus half wave with an amplitude of one and a cycle time of 40~ms.\nThe observer is run at a sample frequency of 1000~Hz and $K_O=500$ as suggested in \\cite{Haddadin2014}.\nIn this simulation, the observer error and the error in acceleration estimation for the force/torque sensor compensation are assumed to follow the dynamics presented in (\\ref{eqn:obs_dynamic}) and (\\ref{eqn:qDD_dyn}) respectively.\n%\n\\begin{figure}\n\\begin{center}\n\\includegraphics{figures/colltest_single_filter/colltest_single_filter_f}\n\\end{center}\\vspace*{-0.4cm}\n\\caption{The $x$-component of the external force $\\bm{f}_\\mathrm{ext}$, the external force estimated with force/torque sensors $\\hat{\\bm{f}}_{\\mathrm{ext}}(\\hat{\\bm{\\mathcal{F}}}_{\\mathrm{ext,S}})$ according to (\\ref{eqn:cmp}) and (\\ref{eqn:cmp_ext_vorher}) as well as the external force estimated with the observed generalized forces $\\hat{\\bm{f}}_{\\mathrm{ext}}(\\hat{\\tau}_\\epsilon)$ according to (\\ref{eqn:force_identification}) is depicted over time for a collision of 20~ms.\nWhen using the generalized forces for identification, the estimated external force is a first order filtered version of the real force with time constant $K_O^{-1}$.\nUsing compensated force/torque sensors, the estimated force follows the real force without any delay.}\\vspace*{-0.6cm}\n\\label{fig:coll_singlecontact_filter}\n\\end{figure}\n%\nWith both methods described before, the contact point is isolated correctly up to numerical errors.\nIf the observed generalized joint forces are used for isolation, there is a delay of one time step, as the filtered generalized forces are still zero for the first time step of the collision.\n\nFig.~\\ref{fig:coll_singlecontact_filter} shows the external forces over the collision time and the forces identified with and without the use of force/torque sensors.\nIt can be seen that if no force/torque sensors are used, the contact force is estimated with a delay of approximately 3~ms.\nIt has to be noted, that the collision will be seen about 10~ms longer with the observer dynamics taken into account.\nThis timespan depends on the thresholds for the generalized external forces, which was here chosen to be 0.001~N or 0.001~Nm, respectively and the filter frequency $1/K_O$.\nFurthermore, when using force/torque sensors, smaller delay but larger error in the estimated external force can be observed.\nAs the error of $\\hat{\\ddot{\\bm{q}}}$ is driven by $\\bm{\\tau}_\\mathrm{ext}$ and $\\bm{M}(\\bm{q})$ is nearly constant for the robot at standstill, the contact point can still be estimated correctly with the compensated force/torque sensor.\n\n", "meta": {"hexsha": "7ff548001912fc6c701659383fedb158888b6ea9", "size": 14941, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "paper/sec_evaluation.tex", "max_stars_repo_name": "SchapplM/robotics-paper_icra2017", "max_stars_repo_head_hexsha": "ef5a744aec97654d622be93a6c5924719f2ed270", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-28T13:48:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-28T13:48:25.000Z", "max_issues_repo_path": "paper/sec_evaluation.tex", "max_issues_repo_name": "SchapplM/robotics-paper_icra2017", "max_issues_repo_head_hexsha": "ef5a744aec97654d622be93a6c5924719f2ed270", "max_issues_repo_licenses": ["MIT"], "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_evaluation.tex", "max_forks_repo_name": "SchapplM/robotics-paper_icra2017", "max_forks_repo_head_hexsha": "ef5a744aec97654d622be93a6c5924719f2ed270", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 83.0055555556, "max_line_length": 481, "alphanum_fraction": 0.7914463557, "num_tokens": 3625, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3174262720448507, "lm_q1q2_score": 0.1624322941746917}} {"text": "\\documentclass{article}\n\n%----------------------------------------------------------------------------------------\n\n\\usepackage{listings} % Required for inserting code snippets\n\\usepackage{geometry}\n\\geometry{margin=0.7in}\n\\usepackage[usenames,dvipsnames]{color} % Required for specifying custom colors and referring to colors by name\n\\usepackage{amssymb}\n\\usepackage{amsmath}\n\\usepackage{mathtools}\n\\usepackage{tikz}\n\\usepackage{enumerate}\n\\usepackage[T1]{fontenc}\n\n\\delimitershortfall-1sp\n\\newcommand\\abs[1]{\\left|#1\\right|}\n\n\\definecolor{DarkGreen}{rgb}{0.0,0.4,0.0} % Comment color\n\\definecolor{highlight}{RGB}{255,251,204} % Code highlight color\n\n%----------------------------------------------------------------------------------------\n\n\\begin{document}\n\n%----------------------------------------------------------------------------------------\n\n\\section*{Problem 1}\n\\begin{flushleft}\n\\textit{Several useful inequalities involving absolute values can be derived from the triangle inequality by a judicious choice for a and b.}\n\\begin{enumerate}[(a)]\nFor any of these examples, we can redefine $x$ and $y$ to be $a$ and $b$, which will help us reduce to the following variants of the triangle inequalities. For each of the following inequalities, I use the following format $\\abs{a} + \\abs{b} \\leq \\abs{a+b}$.\n\n\\item $\\abs{x} - \\abs{y} \\leq \\abs{x-y}$ \\\\\n\\vspace{.3cm}\nHere we will let $a=(x-y)$ and $b=y$. Then, we see that \\\\\n\\begin{center}\n$\\abs{x-y+y} \\leq \\abs{x-y} + \\abs{y} \\implies \\abs{x} \\leq \\abs{x-y} + \\abs{y} \\implies \\abs{x} - \\abs{y} \\leq \\abs{x-y}$\n\\end{center}\n\n\\item $\\abs{x} - \\abs{y} \\leq \\abs{x+y}$ \\\\\n\\vspace{.3cm}\nHere we will let $a=(x+y)$ and $b=-y$. Then, we see that \\\\\n\\begin{center}\n$\\abs{x+y+(-y)} \\leq \\abs{x+y} + \\abs{-y} \\implies \\abs{x} \\leq \\abs{x+y} + \\abs{y} \\implies \\abs{x} - \\abs{y} \\leq \\abs{x+y}$ \n\\end{center}\n\n\\item $\\abs{x} + \\abs{y} \\geq \\abs{x-y}$ \\\\\n\\vspace{.3cm}\nHere we will let $a=x$ and $b=-y$. Then, we see that \\\\\n\\begin{center}\n$\\abs{x+(-y)} \\leq \\abs{x} + \\abs{-y} \\implies \\abs{x-y} \\leq \\abs{x} + \\abs{y}$ \n\\end{center}\n\n\\item $\\abs{\\abs{x} - \\abs{y}} \\leq \\abs{x-y}$ \\\\\n\\vspace{.5cm}\nTo prove this, we will set up 2 different equations. \\\\\n\\begin{center}\n\\begin{tabular}{c c}\n(1) $\\abs{y-x+x} \\leq \\abs{y-x} + \\abs{x}$ &\n(2) $\\abs{x-y+y} \\leq \\abs{x-y} + \\abs{y}$ \\\\\n\\end{tabular}\n\\end{center}\n(1) We can move the $\\abs{x}$ from the left side to the right side and take negative one out of the left hand side, \\\\\nwhich gives us $-(\\abs{x}-\\abs{y}) \\leq \\abs{y-x} $. \\\\\n(2) We can move the $\\abs{y}$ from the left side to the right side, which gives us $\\abs{x}-\\abs{y} \\leq \\abs{x-y}$. \\\\\n\\vspace{0.5cm}\nFrom the properties of absolute values, we know $\\abs{x-y} = \\abs{y-x}$ and if $x \\geq a$ and $x \\geq -a$ then $x \\geq \\abs{a}$. \\\\\n\nFrom the combination of these two facts, we now have $\\abs{\\abs{x}-\\abs{y}} \\leq \\abs{x-y}$.\n\\end{enumerate}\n\\end{flushleft}\n\n\\section*{Problem 2}\n\\begin{flushleft}\nRecall the definition of what it means for $S \\subset \\mathbb{R}$ to be \\textit{bounded above, bounded below} and just \\textit{bounded}. Prove that $S$ is bounded if and ony if there is a real number $M > 0$ such that\n\\begin{center}\n$\\forall s \\in S, \\abs{s} \\leq M$\n\\end{center}\n\n\\textbf{Proof} \\\\\n\\vspace{.3cm}\n\nLet's assume $S \\subset \\mathbb{R}$, then $\\abs{s} \\leq M$ means that $-M < s < M$, $\\forall s \\in S$. $S$ is bounded above if there exists some $X \\in \\mathbb{R}$ such that $\\forall s \\in S$, $s < X$. Likewise, $S$ is bounded below if there exists some $x \\in \\mathbb{R}$ such that $\\forall s \\in S$, $x < s$. Thus, we see that $M$ is in fact an upper bound for $S$ because $s < M$, $\\forall s \\in S$ and that $-M$ is in fact a lower bound for $S$ because $-M < s$, $\\forall s \\in S$. Therefore, since $S$ is bounded above and below, $S$ is, by definition, bounded.\n\\end{flushleft}\n\n\\section*{Problem 3}\n\\begin{flushleft}\nWe say that a function f is \\textit{invertible} if $f^{-1} = \\{ (b,a) : (a,b) \\in f \\}$ is also a function, in which case we call it the inverse function to $f$. Notice that \\\\\n\\begin{center}\n$f^{-1}(b) = (a) \\leftrightarrow b = f(a)$,\n\\end{center}\nassuming that $f^{-1}$ is a function.\n\\begin{enumerate}[(a)]\n\\item If $f$ is invertible, what are the domain and range of $f^{-1}$? \\\\\n\\item Which of the following functions are invertible? For those that are invertible, give the inverse. \\\\\n\\end{enumerate}\n\\begin{center}\n\\begin{tabular}{l l}\n$l = \\{(x,y) \\in \\mathbb{R}^2 : y = 2x + 1\\}$ & Inverse: $y=\\frac{x-1}{2}$, Domain: $\\mathbb{R}$, Range: $\\mathbb{R}$ \\\\\n\\vspace{.2cm}\n$c = \\{(x,y) \\in \\mathbb{R}^2 : y \\geq 0, x^2 + y^2 = 1\\}$ & Not invertible \\\\\n\\vspace{.2cm}\n$s = \\{(x,y) \\in \\mathbb{R}^2 : y = x^2\\}$ & Not invertible\\\\\n\\vspace{.2cm}\n$ \\sqrt = (x,y) \\in \\mathbb{R}^2 : y \\geq 0, y^2 = x\\}$ & Inverse: $y=x^2$, Domain: $\\mathbb{R}$, Range: $[0, \\infty)$ \\\\\n\\vspace{.2cm}\n$sin = \\{(x,y) \\in \\mathbb{R}^2 : y = sin(x)\\}$ & Not invertible \\\\\n\\end{tabular}\n\\end{center}\n\\end{flushleft}\n\n\\section*{Problem 4}\n\\begin{flushleft}\nAssume that $g$ is bounded function, that is, $\\abs{g(x)} < B$ for all $x \\in \\mathbb{R}$. Prove that\n$\\displaystyle \\lim_{x \\to 0} x \\cdot g(x) = 0$. \\\\\n\n\\vspace{.5cm}\n\n\\begin{center}\n$c=0$, $L=0$, $f(x)=x \\cdot g(x)$\n\\end{center}\n\n$\\abs{f(x) - L} < \\epsilon \\implies \\abs{x \\cdot g(x) - 0} < \\epsilon \\implies \\abs{x \\cdot g(x)} < \\epsilon$. \\\\\n\\vspace{.2cm}\nAt its max, $g(x)$ can be no greater than $B$. Thus, we know $B$ is an upper bound for $f(x)$. We can rewrite $f(x)$ as $\\abs{x \\cdot B}$. Thus, $\\abs{x \\cdot B} < \\epsilon \\implies -\\epsilon < x \\cdot B < \\epsilon$. By dividing by $B$ on both sides, we have $\\frac{-\\epsilon}{B} < x < \\frac{\\epsilon}{B}$. \\\\\n\n\\subsection*{Proof}\nLet $\\delta_\\epsilon = \\frac{\\epsilon}{B}$. Then $\\abs{x - 0} < \\delta_\\epsilon \\implies \\delta_\\epsilon < x - 0 < \\delta_\\epsilon$. \\\\\n\\begin{center}\n$\\frac{-\\epsilon}{B} < x < \\frac{\\epsilon}{B}$ \\\\\n\\vspace{.2cm}\n$-\\epsilon < x \\cdot B < \\epsilon$ \\\\\n\\vspace{.2cm}\n$\\abs{x \\cdot B} < \\epsilon$\n\\end{center}\n\nSince we said $g(x) < B$, $\\forall x \\in \\mathbb{R}$, we know the following inequality to be true: $x \\cdot g(x) < \\abs{x \\cdot B} < \\epsilon$. This completes the proof.\n\\end{flushleft}\n\n\\section*{Problem 5}\n\\begin{flushleft}\nUsing the \\textquotedbl$\\epsilon - \\delta$\\textquotedbl \\hspace{.01cm} definition to prove that \\\\\n\\begin{enumerate}[(a)]\n\\item $\\displaystyle \\lim_{x \\to 2} (4x+1) = 9$\n\n\\begin{center}\n$\\abs{f(x) - L} < \\epsilon \\implies \\abs{(4x+1) - 9} < \\epsilon \\implies \\abs{4x-8} < \\epsilon \\implies \\abs{4(x-2)} \\implies \\abs{x-2} < \\frac{\\epsilon}{4}$ \\\\\n\\end{center}\n\n\\subsection*{Proof}\n\nLet $\\delta_\\epsilon \\implies \\frac{\\epsilon}{4}$. Then, $0 < \\abs{x-2} < \\frac{\\epsilon}{4} \\implies -\\frac{\\epsilon}{4} < x-2 < \\frac{\\epsilon}{4}$. \\\\\n\\begin{center}\n\\vspace{.2cm}\n$\\frac{\\epsilon}{4} < x-2 < \\frac{\\epsilon}{4}$ \\\\\n\\vspace{.2cm}\n$-\\epsilon < 4(x-2) < \\epsilon$ \\\\\n\\vspace{.2cm}\n$-\\epsilon < 4x-8 < \\epsilon$ \\\\\n\\vspace{.2cm}\n$-\\epsilon < (4x+1)-9 < \\epsilon$ \\\\\n\\vspace{.2cm}\n$\\abs{(4x+1)-9} < \\epsilon$ \\\\\n\\end{center}\n\nThis completes the proof because we showed $\\abs{f(x) - L} < \\epsilon$ for a specific $\\delta$. \\\\\n\n\\item $\\displaystyle \\lim_{x \\to 5} \\sqrt{x + 4} = 3$\n\n\\begin{center}\n$\\abs{f(x) - L} < \\epsilon \\implies \\abs{\\sqrt{x + 4} - 3} < \\epsilon$ implies \\\\\n\\vspace{.3cm}\n$-\\epsilon < \\sqrt{x + 4} - 3 < \\epsilon$ \\\\\n\\vspace{.2cm}\n$-\\epsilon + 3< \\sqrt{x + 4} < \\epsilon + 3$ \\\\\n\\vspace{.2cm}\n$(-\\epsilon + 3)^2 < x + 4 < (\\epsilon + 3)^2$ \\\\\n\\vspace{.2cm}\n$(-\\epsilon + 3)^2 - 9 < x - 5 < (\\epsilon + 3)^2 - 9$ \\\\\n\\end{center}\n\nYou can see that we subtracted 9 to both sides at the end. That is because our $\\abs{x-p}$ value is $\\abs{x-5}$. \\\\\n\n\\subsection*{Proof}\nLet $\\delta_\\epsilon = (\\epsilon + 3)^2 - 9$. Then, $0 < \\abs{x-5} < (\\epsilon + 3)^2 + 9$ implies \\\\\n\\begin{center}\n\\vspace{.2cm}\n$(-\\epsilon + 3)^2 - 9 < x - 5 < (\\epsilon + 3)^2 - 9$ \\\\\n\\vspace{.2cm}\n$(-\\epsilon + 3)^2 < x + 4 < (\\epsilon + 3)^2$ \\\\\n\\vspace{.2cm}\n$-\\epsilon + 3< \\sqrt{x + 4} < \\epsilon + 3$ \\\\\n\\vspace{.2cm}\n$-\\epsilon < \\sqrt{x + 4} - 3 < \\epsilon$ \\\\\n\\end{center}\n\nThis completes the proof because we showed $\\abs{f(x) - L} < \\epsilon$ for a specific $\\delta$. \\\\\n\n\\item $\\displaystyle \\lim_{x \\to 3} \\frac{1}{8 - 4x} = \\frac{1}{4}$\n\n\n\\begin{center}\n$\\abs{f(x) - L} < \\epsilon \\implies \\abs{\\frac{1}{8 - 4x} - \\frac{1}{4}} < \\epsilon$ implies \\\\\n\\vspace{.3cm}\n$-\\epsilon < \\frac{1}{8 - 4x} - \\frac{1}{4} < \\epsilon$ \\\\\n\\vspace{.2cm}\n$-\\epsilon + \\frac{1}{4} < \\frac{1}{-4(x-2)} < \\epsilon + \\frac{1}{4}$ \\\\\n\\vspace{.2cm}\n$4\\epsilon - 1 > \\frac{1}{x-2} > -4\\epsilon - 1$ \\\\\n\\vspace{.2cm}\n$\\frac{1}{4\\epsilon - 1} > x-2 > \\frac{1}{-4\\epsilon - 1}$ \\\\\n\\vspace{.2cm}\n$\\frac{1}{4\\epsilon - 1} - 1> x-3 > \\frac{1}{-4\\epsilon - 1} - 1$ \\\\\n\\end{center}\n\nYou can see that we subtracted 1 to on sides at the end. That is because our $\\abs{x-p}$ value is $\\abs{x-3}$. \\\\\n\n\\subsection*{Proof}\n\nLet $\\delta_\\epsilon = \\frac{1}{-4\\epsilon - 1} - 1$. Then, $0 < \\abs{x-3} < \\frac{1}{-4\\epsilon - 1} - 1$ implies \\\\\n\\begin{center}\n\\vspace{.2cm}\n$\\frac{1}{4\\epsilon - 1} - 1 > x - 3 > \\frac{1}{-4\\epsilon - 1} - 1$ \\\\\n\\vspace{.2cm}\n$\\frac{1}{4\\epsilon- 1} > x - 2 > \\frac{1}{-4\\epsilon - 1}$ \\\\\n\\vspace{.2cm}\n$4\\epsilon - 1 > \\frac{1}{x - 2} > -4\\epsilon - 1$ \\\\\n\\vspace{.2cm}\n$-\\epsilon + \\frac{1}{4} < \\frac{1}{-4(x-2)} < \\epsilon + \\frac{1}{4}$ \\\\\n\\vspace{.2cm}\n$-\\epsilon < \\frac{1}{-4(x-2)} - \\frac{1}{4} < \\epsilon$ \\\\\n\\vspace{.2cm}\n$-\\epsilon < \\frac{1}{8-4x} - \\frac{1}{4} < \\epsilon$ \\\\\n\\end{center}\n\nThis completes the proof because we showed $\\abs{f(x) - L} < \\epsilon$ for a specific $\\delta$. \\\\\n\n\\end{enumerate}\n\\end{flushleft}\n\n%----------------------------------------------------------------------------------------\n\n\\end{document}\n", "meta": {"hexsha": "af48e0437fecaba53683697ae6d16c87bf61b681", "size": 9813, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "elementary-analysis/homework-4/homework_4.tex", "max_stars_repo_name": "jShiohaha/math-classes", "max_stars_repo_head_hexsha": "72711363cf0b58863ffb193ee79ff40244e517eb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "elementary-analysis/homework-4/homework_4.tex", "max_issues_repo_name": "jShiohaha/math-classes", "max_issues_repo_head_hexsha": "72711363cf0b58863ffb193ee79ff40244e517eb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "elementary-analysis/homework-4/homework_4.tex", "max_forks_repo_name": "jShiohaha/math-classes", "max_forks_repo_head_hexsha": "72711363cf0b58863ffb193ee79ff40244e517eb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.0530612245, "max_line_length": 567, "alphanum_fraction": 0.5831040457, "num_tokens": 3701, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4882833952958347, "lm_q2_score": 0.33111974622959367, "lm_q1q2_score": 0.16168027393848117}} {"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{R.Brun,F.Bruyant,A.McPherson}\n\\Submitted{01.11.83} \\Revised{18.11.93}\n\\Version{Geant 3.16}\\Routid{GEOM199}\n\\Makehead{The volume data structure -- JVOLUM}\n\n\\section{The data structure {\\tt JVOLUM} and {\\tt JGPAR}}\n\nThe meaning of the variables in the data structure {\\tt JVOLUM} shown\nin fig. \\ref{fg:geom199-1}\nis the following:\n\n\\begin{DLtt}{MMMMMMMM}\n\\item[ISEARC] search flag {\\tt [GEOM400], [GEOM410]}:\n\\begin{DLtt}{MMMM}\n\\item[$=$0] volume positioning order or ordering by \\Rind{GSNEXT}/\\Rind{GSNEAR};\n\\item[$<$0] binary search as defined by \\Rind{GSORD};\n\\item[$>$0] user ordering \\Rind{GSUNEA}/\\Rind{GUNEAR};\n\\end{DLtt}\n\\item[ISHAPE] system shape number (see {\\tt [GEOM050]};\n\\item[NIN] number of volumes contained in the mother volume --\nif negative the volume is divided;\n\\item[NMED] medium number for the volume;\n\\item[NPAR] number of shape parameters;\n\\item[NATT] number of attributes;\n\\item[PAR] array of shape parameters;\n\\item[IAT] array of attributes;\n\\item[IAXIS] direction of the division (see {\\tt [GEOM130]});\n\\item[IVO] system volume number;\n\\item[NDIV] number of divisions ({\\tt -NDVMX}, if computed dynamically,\nsee {\\tt [GEOM140]});\n\\item[C0] coordinate value at which the division starts;\n\\item[STEP] coordinate step for the division;\n\\item[NR] user copy number;\n\\item[IROT] rotation matrix number defining the orientation of the volume\nwith respect to the mother reference system;\n\\item[X,Y,Z] position of the volume with respect to the mother reference\nsystem;\n\\item[KONLY] {\\tt ONLY/MANY} flag, see {\\tt [GEOM110]} for more information;\n\\end{DLtt}\n \n\\begin{figure}[hbt]\n \\centering\n \\epsfig{file=eps/geom199-1.eps,width=14cm}\n \\caption{Example of geometrical tree structure}\n \\label{fg:geom199-1}\n\\end{figure}\n", "meta": {"hexsha": "59ec3ee3c414207ccf6c4ac8c36d6be8fad725fc", "size": 2386, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "geant/geom199.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/geom199.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/geom199.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.6071428571, "max_line_length": 80, "alphanum_fraction": 0.5783738474, "num_tokens": 611, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.32082130731838393, "lm_q1q2_score": 0.1616638363949401}} {"text": "\n\\section{Operational Semantics}\n\n\\subsection{Notation}\n\nThe state of the evaluator, $\\sigma$, is the tuple consisting of \\\\\npacket, $\\pi$\\\\\naction\\_list, $\\alpha$ \\\\\nstored\\_action\\_list, $\\Lambda$ \\\\\ncontext, $\\Gamma$, which is the tuple: \\\\\n$\\langle ingress\\_port, \\ egress\\_port, \\ physical\\_port, \\ key, \\ meta, \\ header\\_offset, \\ table \\rangle$ \\\\ \\\\\nCompactly, $\\sigma = \\langle \\pi, \\alpha, \\Lambda, \\Gamma \\rangle$\n\\\\ \\\\\nWe can examine the status of $\\pi$ or $\\Gamma$ by using the index operator, []. The index itself is context-sensitive: $\\pi$ is indexed by some \\textit{field}, $\\Gamma$ is indexed by one of its substructures. We will use the assignment operator, $\\leftarrow$, within the index operator to assign a bitfield to a value or the value of another bitfield.\nA field in $\\pi$ can be set to a literal value or copied from a bitfield or register. For example:\n\\begin{equation}\n \\pi[\\textit{field} \\leftarrow \\textit{value}]\n\\end{equation}\n\\begin{equation}\n \\pi[\\textit{field} \\leftarrow \\mathct{r}]\n\\end{equation}\n\\begin{equation}\n \\pi[\\textit{field} \\leftarrow \\textit{bitfield}]\n\\end{equation}\nA variable in $\\Gamma$ is accessed similarly, but uses the dot operator, ., to access its substructures within the index operator. Example:\n\\begin{equation}\n \\Gamma[\\Gamma.\\mathct{key} \\leftarrow \\textit{bitfield}]\n\\end{equation}\nOne should not confuse the range operator, [), with the index operator. To avoid ambiguity, the range operator \\textit{always} appears inside\nof the index operator, []. Example:\n\\begin{equation}\n \\pi[field_1 \\leftarrow field_2[0, 10)]\n\\end{equation}\n\nComments:\n\\begin{enumerate}\n\\item Field \\textit{field} with a packet, $\\pi$, is set to some literal value, \\textit{value}.\n\\item The value of register $\\mathct{r}$ is copied into \\textit{field}.\n\\item The value of some bitfield, \\textit{bitfield} is copied into \\textit{field}.\n\\item The value of the $\\mathct{key}$ register in $\\Gamma$ is set to the value of \\textit{bitfield}\n\\item The bits of $field_1$ in $\\pi$ are set to the bits 0, up to but not including 10, in $field_2$.\n\\end{enumerate}\n\n\n\\subsection{Operational Semantics 5-Tuple}\nTurbak and Gifford define operational semantics for a language as the 5-Tuple, $\\langle CF, \\Rightarrow, FC, IF, OF \\rangle$. CF is the set of all possible configurations that an abstract machine may be in. $\\Rightarrow$ is the transition relation, a function that transitions from one configuration to another. FC is the set of all final configurations, the possible ending configurations of the machine. IF is the input function, a function that translates an input into the beginning state of the machine. Finally, OF is the output function, or the transition of the final state into some useful value or domain \\cite{Turbak2008}. In Pip, we define the 5-tuple as follows:\\\\\npip = $\\langle IF, \\ CF, \\ \\Rightarrow, \\ FC, \\ OF \\rangle$\\\\\nIF = $\\textrm{program} \\times \\pi \\rightarrow CF$ \\\\\nCF = $\\alpha \\times \\Gamma \\times \\pi \\times Lambda$ \\\\\n$\\Rightarrow$ = Defined in section ``Transition Relation''. \\\\\nFC = $(\\Lambda = \\varnothing) \\times (\\alpha = \\varnothing) \\times \\pi \\times \\Gamma[egress\\_port \\neq 0]$ \\\\\nOF = $FC \\rightarrow$ \\texttt{serialization}\n\n\\texttt{serialization} is the output state of Pip: a textual logging of all states that the machine entered.\n\\subsection{Transition Relation}\n\\setlength{\\mathindent}{0pt}\n\n\\begin{mdframed}\n\\begin{gather*}\n (\\mathct{advance}~n \\cdot \\bar\\alpha), \\langle \\pi, \\Lambda, \\Gamma \\rangle\n \\Rightarrow\n (\\bar\\alpha), \\langle \\pi, \\Lambda, \\Gamma[\\mathct{header}\n \\leftarrow \\mathct{header} + n] \\rangle\n\\\\\n (\\mathct{clear} \\cdot \\bar\\alpha), \\langle \\pi, \\Lambda, \\Gamma \\rangle\n \\Rightarrow\n (\\bar\\alpha), \\langle \\pi, \\varnothing, \\Gamma \\rangle\n\\\\\n (\\mathct{drop} \\cdot \\bar\\alpha), \\langle \\pi, \\Lambda, \\Gamma \\rangle\n \\Rightarrow\n \\varnothing, \\langle \\pi, \\varnothing, \\Gamma [\\mathct{out} \\leftarrow 0] \\rangle\n\\\\\n (\\mathct{write} \\ \\textit{action} \\cdot \\bar\\alpha), \\langle \\pi, \\Lambda,\n \\Gamma \\rangle\n \\Rightarrow\n (\\bar\\alpha), \\langle \\pi, \\Lambda \\cdot \\textit{action}, \\Gamma \\rangle\n\\\\\n (\\mathct{goto} \\ T \\cdot \\bar\\alpha),\n \\langle \\pi, \\Lambda, \\Gamma \\rangle\n \\Rightarrow\n (\\bar\\alpha), \\langle \\pi, \\Lambda,\n \\Gamma[\\mathct{current\\_table} \\leftarrow T] \\rangle\n\\\\\n (\\mathct{set} \\ \\textit{field} \\ \\textit{value} \\cdot \\bar\\alpha), \\langle \\pi,\n \\Lambda, \\Gamma \\rangle\n \\Rightarrow\n (\\bar\\alpha), \\langle \\pi', \\Lambda, \\Gamma' \\rangle\n\\\\\n (\\mathct{output} \\ \\mathct{port} \\ n \\cdot \\bar \\alpha), \\langle \\pi, \\Lambda,\n \\Gamma \\rangle\n \\Rightarrow\n (\\bar\\alpha), \\langle \\pi, \\Lambda, \\Gamma[\\mathct{egress\\_port}\n \\leftarrow \\mathct{port} \\ n] \\rangle\n\\\\\n (\\mathct{copy} \\ as_1 \\ src \\ as_2 \\ dst \\cdot \\bar\\alpha), \\langle \\pi,\n \\Lambda, \\Gamma \\rangle\n \\Rightarrow\n (\\bar\\alpha), \\langle \\pi', \\Lambda, \\Gamma' \\rangle\n\\end{gather*}\n\\end{mdframed}\n\nThe $\\mathct{advance}$ command advances the header offset by \\textit{n} bits.\nThis can be used by a programmer to adjust the decoding offset relative to a\npacket header.\nThe $\\mathct{clear}$ command clears the stored action list. This can be used\nby a program reset any accumulated actions if certain conditions are detected\nduring packet analysis (e.g., filtering flows based on UDP packet content).\nThe $\\mathct{drop}$ command truncates both the action list and stored action list,\nand sets the output port to 0 (the null port). \nThe effect of this to cause the program to terminate such that the execution \nenvironment will not forward the packet.\nThe \\mathct{write} command appends an action to the stored action list. This is\nthe only way to write to the stored action list, allowing for some action to be\ntaken upon egress, providing the packet is not dropped.\nThe \\mathct{goto} command jumps from the current match table to a new table. The\nkey register is cleared and rewritten based on the new table's rules. This can\nbe used as a rudimentary control structure.\nThe \\mathct{set} command sets a bitfield, \\textit{field} to some value \\textit{value}.\nThis is used to set fields to a literal value.\nThe \\mathct{output} action outputs to the specified \\mathct{port}, \\textit{n}, beginning\negress processing.\nThe \\mathct{copy} action copies from one bitfield, \\textit{src} to another bitfield, \\textit{dst}.\nA bitfield can be copied from any address space to any other address space, except for key registers,\nwhich cannot be used as a source.\n\nDefinition of copy function:\n\\begin{mdframed}\n\\begin{gather*}\n (\\mathct{copy} \\ meta \\ src \\ packet \\ dst \\ n)\n \\rightarrow\n \\langle \\pi[dst \\leftarrow \\Gamma.\\mathct{meta}[dst, dst + n)],\n \\Lambda, \\Gamma \\rangle\n\\\\\n (\\mathct{copy} \\ meta \\ src \\ header \\ dst \\ n)\n \\rightarrow\n \\langle \\pi[dst + \\mathct{hoff} \\leftarrow \\Gamma.meta[dst, dst + n)],\n \\Lambda, \\Gamma \\rangle\n\\\\\n (\\mathct{copy} \\ meta \\ src \\ key \\ dst \\ n)\n \\rightarrow\n \\langle \\pi, \\Lambda, \\Gamma[\\Gamma.\\mathct{key} \\leftarrow\n \\Gamma.\\mathct{meta}[meta, meta + n)] \\rangle\n\\\\\n (\\mathct{copy} \\ packet \\ src \\ packet \\ dst \\ n)\n \\rightarrow\n \\langle \\pi[dst \\leftarrow \\pi[src, src + n)], \\Lambda, \\Gamma \\rangle\n\\\\ \n (\\mathct{copy} \\ packet \\ src \\ header \\ dst \\ n)\n \\rightarrow\n \\langle \\pi[dst + \\mathct{hoff} \\leftarrow\n \\pi[src, src + n)],\n \\Lambda, \\Gamma \\rangle\n\\\\ \n (\\mathct{copy} \\ packet \\ src \\ key \\ dst \\ n)\n \\rightarrow\n \\langle \\pi, \\Lambda, \\Gamma[\\Gamma.\\mathct{key} \\leftarrow \\pi[src, src + n)]\n \\rangle\n\\\\\n (\\mathct{copy} \\ header \\ src \\ header \\ dst \\ n)\n \\rightarrow\n \\langle \\pi[dst + \\mathct{hoff} \\leftarrow\n \\pi[src + \\mathct{hoff}, src + \\mathct{hoff} + n)],\n \\Lambda, \\Gamma \\rangle\n\\\\\n (\\mathct{copy} \\ header \\ src \\ packet \\ dst \\ n)\n \\rightarrow\n \\langle \\pi[dst \\leftarrow\n \\pi[src + \\mathct{hoff}, src +\n \\mathct{hoff} + n)], \\Lambda, \\Gamma \\rangle\n\\\\\n (\\mathct{copy} \\ header \\ src \\ key \\ dst \\ n)\n \\rightarrow\n \\langle \\pi, \\Lambda, \\Gamma[\\Gamma.\\mathct{key}[dst] \\leftarrow\n \\pi[src + \n \\mathct{hoff}, src + \\mathct{hoff} + n)] \\rangle\n\\\\\n (\\mathct{copy} \\ header \\ src \\ meta \\ dst \\ n)\n \\rightarrow\n \\langle \\pi, \\Lambda, \\Gamma[\\Gamma.\\mathct{meta}[dst] \\leftarrow\n \\pi[src + \n \\mathct{hoff}, src + \\mathct{hoff} + n)] \\rangle\n\\end{gather*}\n\\end{mdframed}\n\nDefintion of set function:\n\\begin{mdframed}\n\\begin{gather*}\n (\\mathct{set} \\ (meta \\ field \\ n) \\ value)\n \\rightarrow\n \\langle \\pi, \\Lambda, \\Gamma[\\Gamma.\\mathct{meta}[field, field + n) \\leftarrow value] \\rangle\n \\\\\n (\\mathct{set} \\ (key \\ field \\ n) \\ value)\n \\rightarrow\n \\langle \\pi, \\Lambda, \\Gamma[\\Gamma.\\mathct{key}[field, field + n) \\leftarrow value] \\rangle\n \\\\\n (\\mathct{set} \\ (packet \\ field \\ n) \\ value)\n \\rightarrow\n \\langle \\pi, \\Lambda, \\Gamma[\\Gamma.\\mathct{packet}[field, field + n) \\leftarrow value] \\rangle\n \\\\\n (\\mathct{set} \\ (header \\ field \\ n) \\ value)\n \\rightarrow\n \\langle \\pi, \\Lambda, \\Gamma[\\Gamma.\\mathct{packet}[field + \\mathct{hoff},\n field + \\mathct{hoff} + n) \\leftarrow value] \\rangle\n \\\\\n\\end{gather*}\n\\end{mdframed}\n\\textit{Note:} the context variable $\\mathct{header\\_offset}$ is abbreviated to $\\mathct{hoff}$ for brevity.\n", "meta": {"hexsha": "efead4d4a5d97055e74cedb650ca0755b3bf8420", "size": 9170, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/operation.tex", "max_stars_repo_name": "flowgrammable/pip", "max_stars_repo_head_hexsha": "b3a4ebb2d01c6f81400840be6a60b55f20aab8af", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-03-05T06:07:31.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-05T06:07:31.000Z", "max_issues_repo_path": "doc/operation.tex", "max_issues_repo_name": "flowgrammable/pip", "max_issues_repo_head_hexsha": "b3a4ebb2d01c6f81400840be6a60b55f20aab8af", "max_issues_repo_licenses": ["MIT"], "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/operation.tex", "max_forks_repo_name": "flowgrammable/pip", "max_forks_repo_head_hexsha": "b3a4ebb2d01c6f81400840be6a60b55f20aab8af", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-03-05T06:07:34.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-05T06:07:34.000Z", "avg_line_length": 44.0865384615, "max_line_length": 677, "alphanum_fraction": 0.6905125409, "num_tokens": 2846, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.290980853917813, "lm_q1q2_score": 0.16134028936639194}} {"text": "\\documentclass{article}\n\\usepackage[utf8]{inputenc}\n\\usepackage{tikz}\n\\usepackage{tkz-graph}\n\\usepackage{float}\n\\usepackage{amsmath}\n\\GraphInit[vstyle = Shade]\n\n\\title{Assignment 2}\n\\author{Jason Fantl, Jacob Tuttle}\n\\date{November 2019}\n\n\\begin{document}\n\n\\maketitle\n\n\\section{Theory vs. Practice}\n\n3 reasons why asymptotic analysis may be misleading with respect to actual performance in practice:\n\\begin{itemize}\n \\item Because asymptotic analysis ignores constants, it can lead to misrepresenting which algorithm is more efficient for specific situations. For example, if one algorithm runs in O(n) time and another runs in O($n^2$) time, you would assume the O(n) algorithm is more efficient. But if you also know that constants are included, and that the linear time algorithm would run in $10000n$ time, and the other in $n^2$ time, the more efficient algorithm depends on your input size, not just asymptotic time complexity.\n \\item In practice there are always restrictions on both memory and time, and asymptotic analysis only considers how well an algorithm scales, not how well it will fit within the given conditions. This could lead to using an algorithm that scales very well but fails to complete the task at all within the available constraints. For example, if an algorithm were to rely on a large volume of memory access, when run on a computer with very efficient memory access techniques, these actions would have little effect on the runtime; however, if it were run on a device with much less efficient memory access, the execution time would balloon as a result that has nothing to do with the $O$ complexity.\n \\item While asymptotic analysis will provide information about how the algorithm will behave in the abstract sense, it says nothing about how the code will run on a specific machine. Even if one were to run the algorithm on one machine, and use this data to extrapolate the runtimes for various input sizes, that information would mean nothing if the algorithm were run on another machine. The asymptotic runtime of an algorithm says very little about the true execution time for an algorithm, and it provides even less information when considering the differences of running on different machines.\n\\end{itemize}\n\nGiven a binary search tree with $1,000$ elements and a measured time of $5$ seconds to access one of those elements, we could use asymptotic analysis to predict how long it would take to find in element in a binary search tree with $10,000$ elements.\nWe know the time complexity of a searching in a binary search tree is $O(log(n))$. We can find the ratio of time it should take between different trees using this fact. The ratio of time between a tree with $1,000$ elements and a tree with $10,000$ should be $log_2(1,000)/log_2(10,000) = 0.75$. Using this calculation and the fact that the $1,000$ element tree took $5$ seconds, we predict it should take $\\frac{5}{0.75} = 6.67$ seconds to find an element.\n\nIf the measured time of the two binary search trees doesn't match our prediction, here are three reasons why that might have happened:\n\\begin{itemize}\n \\item Since $O$ only describes the highest order term, disregarding constants and lower order terms, one of these discarded terms may have been much larger than was initially considered. If one of these constants or lower order terms were to be quite large, increasing the input size could change the run time more significantly than calculations indicate.\n \\item Depending on what form the input binary tree takes, the worst case time complexity of searching can be $O(n)$. It's possible the first execution, the $5$ second one, ran on an average or best case tree and the second execution ran on a worst case input. This would result in a much larger execution time since the worst case takes asymptotically more time than the average case.\n \\item If the algorithm were run on different computers, then even if one were to run the same algorithm on the same tree, different run times could be produced. When run on a slower computer, this difference would be even more pronounced and could result in the difference between calculated and observed run times discussed in this problem.\n\\end{itemize}\n\n\\section{Graph Properties}\n\n\nDefinitions:\n\\begin{itemize}\n\\item Isomorphic: G1 = (V1, E1) is isomorphic to G2 = (V2, E2) if there is a\none-to-one and onto function $f : V1 \\rightarrow V2$ such that\n$(u, v) \\in E1 \\iff (f(u), f(v)) \\in E2$\n\\item Completely connected: A graph is completely connected if there exists an edge between every pair of vertices.\n\\item One-to-One function: A function f is one-to-one if for all x and y f(x) = f(y) then x = y.\n\\item Onto function: A function f is onto if for all y in the range of f there exists an x such that f(x) = y\n\\end{itemize}\n\n%Theorem: If two graphs A and B have the same number of nodes and are completely connected, they are isomorphic.\n\n%Proof:\n%We have a completely connected graph G1 = (V1, E1), and a completely connected graph G2 = (V2, E2) both with x vertices. We will label each vertex of graph G1 from V1 to Vx since it has x vertices. Then for each vertex, it has x edges since a completely connected graph connects every pair of vertices, and there are x vertices. For each edge edge coming out of vertex Vn, connecting to Vm, we will label that edge as En,m. Since G2 has the same number of vertices and is also completely connected, we will label all of its vertices and edges in the same exact way. Now there exists a simple function f which takes an edge or vertex and returns the same vertex or edge, that is f(u) = u and f(v) = v. This function is one-to-one since for all Pn and Qm where Pn and Qm are arbitrary vertices or edges, if f(Pn) = f(Qm) then Pn = Qm by the definition of f. f is also onto since for any value I in the range of f we pick a new value J = I, then f(J) = I by the definition of f. \n\n%To be continued \\\\\n\nTheorem: If two graphs A and B have the same number of nodes and are completely connected, they are isomorphic. \\\\\n\nProof: Let $A$ and $B$ be two graphs that are completely connected and have the same number of nodes. By the definition of two completely connected graphs, we can define $A$ as a set of vertices $V_A$ labeled $a_1, a_2, \\hdots a_n$ and a set of edges $E_A : (a_1, a_2), (a_1, a_3), \\hdots (a_1, a_n), (a_2, a_3), (a_2, a_4), \\hdots (a_2, a_n), \\hdots (a_{n-1}, a_n)$. Likewise, $B$ is defined in a similar fashion with vertices $V_B : b_1, b_2, \\hdots b_n$ and edges $E_B : (b_1, b_2), (b_1, b_3), \\hdots (b_1, b_n), (b_2, b_3), (b_2, b_4), \\hdots (b_2, b_n), \\hdots (b_{n-1}, b_n)$. For these two graphs to be isomorphic, there must be a one-to-one and onto function $f: V1 \\rightarrow V2$ such that $(u, v) \\in E_A \\iff (f(u), f(v)) \\in E_B$ \\\\\n\nIf we can find this bijection, $f$, such that $(u, v) \\in E_A \\iff (f(u), f(v)) \\in E_B$ then it will be shown that $A$ and $B$ are isomorphic. Let $f$ be defined as the function such that:\n\\begin{align*}\n f(a_1) &= b_1 \\\\\n f(a_2) &= b_2 \\\\\n &\\vdots \\\\\n f(a_n) &= b_n\n\\end{align*}\n\n$f$ is onto and one-to-one as we have defined it because every node in $V_A$ can be mapped by $f$ to a single corresponding node in $V_B$.\n\nUsing this function, it can be shown that every edge in $A$ corresponds to the same edge $(f(a_i), f(a_j)) = (b_i, b_j)$ for all $i, j \\leq n$. Therefore, $A$ and $B$ are isomorphic. \\\\\n\n% Old proof that is added \n%Theorem: If two graphs A and B are isomorphic they do not need to be completely connected.\n\n%Proof: Let there be graphs G1 and G2 such that both have 3 vertices, called A1, B1, and C1 for G1, and A2, B2, and C2 for G2. Let G1 only have edges from A1 to B1 called AB1 and B1 to C1 called BC1, and let G2 only have edges from A2 to B2 called AB2 and B2 to C2 called BC2. Neither of these graphs are fully connected since there isn't an edge from A1 to C1 and there isn't an edge from A2 to C2. These graphs are isomorphic since the edge AB1 can be mapped to AB2 and BC1 mapped to BC2, and the edge and AB2 can be mapped to AB1 and BC2 mapped to BC1. This exhaustively finds a mapping between the sets of edges. By this example, we have found two graphs which are isomorphic and not fully connected, proving the theorem.*/\n\nTheorem: If two graphs $A$ and $B$ are isomorphic, they do not need to be completely connected. \\\\\n\nProof: Let $A$ and $B$ be the graphs by Figure 1 and Figure 2 respectively and be defined as: \n\n\\begin{align*}\n A &= (V_A, E_A) \\\\\n V_A &= \\{a, b, c\\} \\\\\n E_A &= \\{(a, c), (c, b)\\} \\\\\n B &= (V_B, E_B) \\\\\n V_B &= \\{x, y, z\\} \\\\\n E_B &= \\{(x, y), (y, z)\\}\n\\end{align*}\n\n\\begin{figure}[H]\n \\centering\n \\begin{tikzpicture}[shorten >=1pt, auto, node distance=3cm]\n \n % draw nodes\n \\foreach [count=\\i] \\x/\\y/\\t in {0/0/c, 0/3/a, 2/2/b}\n \\node [circle, draw]\n (v\\t) at (\\x, \\y) {\\t};\n \n % draw edges\n \\foreach \\i/\\j in {a/c, c/b}\n \\draw (v\\i) edge[post] (v\\j);\n \n \\end{tikzpicture}\n \\caption{Graph $A$}\n \\label{fig:graph_a}\n\\end{figure}\n\\begin{figure}[H]\n \\centering\n \\begin{tikzpicture}[shorten >=1pt, auto, node distance=3cm]\n \n % draw nodes\n \\foreach [count=\\i] \\x/\\y/\\t in {0/0/x, 3/0/y, 6/0/z}\n \\node [circle, draw]\n (v\\t) at (\\x, \\y) {\\t};\n \n % draw edges\n \\foreach \\i/\\j in {x/y, y/z}\n \\draw (v\\i) edge[post] (v\\j);\n \n \\end{tikzpicture}\n \\caption{Graph $B$}\n \\label{fig:graph_b}\n\\end{figure}\nLet $f$ be a one-to-one and onto bijection from $A \\rightarrow B$ such that:\n\\begin{align*}\n f(a) &= x \\\\\n f(b) &= z \\\\\n f(c) &= y\n\\end{align*}\nUsing the definitions above, it can be seen that all edges are mapped from $E_A$ to $E_B$ by $f$ and $f$ is one-to-one and onto from $A \\rightarrow B$. Furthermore, in graph $A$ nodes $a$ and $b$ are not connected and in graph $B$ nodes $x$ and $z$ are not connected; therefore, the graphs are not completely connected. These graphs satisfy the theorem as two graphs that are isomorphic and not completely connected; therefore two graphs do not need to be completely connected to be isomorphic.\n\n\\section{Ford-Fulkerson --- Augmenting Paths}\nCode solutions to this problem are provided in: \\\\ \\texttt{Ford-Fulkerson\\_Augmenting\\_Paths.js}\n\n\\section{Ford-Fulkerson Algorithm }\n\nResidual graph, iteration 1:\n\n\\begin{tikzpicture}[shorten >=1pt, auto, node distance=3cm]\n\n \\foreach [count=\\i] \\x/\\y/\\t in {0/0/S, 0/4/B, 3/4/C, 3/2/D, 10/0/E, 7/4/F, 10/4/T}\n \\node [circle,draw]\n (v\\t) at (\\x,\\y) {\\t};\n\n \\foreach \\i/\\j/\\t in {S/B/8, S/D/2, S/E/3, B/C/1, D/C/3, D/F/9, D/E/4, E/F/2, E/T/1, C/F/5, F/T/7}\n \\draw (v\\i) edge[post] node{\\t} (v\\j);\n\\end{tikzpicture}\n\n\nResidual graph, iteration 2:\n\n\\begin{tikzpicture}[shorten >=1pt, auto, node distance=3cm]\n\n \\foreach [count=\\i] \\x/\\y/\\t in {0/0/S, 0/4/B, 3/4/C, 3/2/D, 10/0/E, 7/4/F, 10/4/T}\n \\node [circle,draw]\n (v\\t) at (\\x,\\y) {\\t};\n\n \\foreach \\i/\\j/\\t in {S/B/8, S/D/2, B/C/1, D/C/3, D/F/9, D/E/4, E/F/2, T/E/1, C/F/5, F/T/7}\n \\draw (v\\i) edge[post] node{\\t} (v\\j);\n \\foreach \\i/\\j/\\t in {S/E/2, E/S/1}\n \\draw (v\\i) edge[post, bend right=10] node{\\t} (v\\j);\n \n\\end{tikzpicture}\n\nResidual graph, iteration 3:\n\n\\begin{tikzpicture}[shorten >=1pt, auto, node distance=3cm]\n\n \\foreach [count=\\i] \\x/\\y/\\t in {0/0/S, 0/4/B, 3/4/C, 3/2/D, 10/0/E, 7/4/F, 10/4/T}\n \\node [circle,draw]\n (v\\t) at (\\x,\\y) {\\t};\n\n \\foreach \\i/\\j/\\t in {S/B/8, S/D/2, B/C/1, D/C/3, D/F/9, D/E/4, F/E/2, T/E/1, C/F/5, E/S/3}\n \\draw (v\\i) edge[post] node{\\t} (v\\j);\n \\foreach \\i/\\j/\\t in {F/T/5, T/F/2}\n \\draw (v\\i) edge[post, bend left=10] node{\\t} (v\\j);\n \n\\end{tikzpicture}\n\nResidual graph, iteration 4:\n\n\\begin{tikzpicture}[shorten >=1pt, auto, node distance=3cm]\n\n \\foreach [count=\\i] \\x/\\y/\\t in {0/0/S, 0/4/B, 3/4/C, 3/2/D, 10/0/E, 7/4/F, 10/4/T}\n \\node [circle,draw]\n (v\\t) at (\\x,\\y) {\\t};\n\n \\foreach \\i/\\j/\\t in {S/B/8, D/S/2, B/C/1, D/C/3, D/E/4, F/E/2, T/E/1, C/F/5, E/S/3}\n \\draw (v\\i) edge[post] node{\\t} (v\\j);\n \\foreach \\i/\\j/\\t in {F/T/3, T/F/4, D/F/7, F/D/2}\n \\draw (v\\i) edge[post, bend left=10] node{\\t} (v\\j);\n \n\\end{tikzpicture}\n\nResidual graph, iteration 5:\n\n\\begin{tikzpicture}[shorten >=1pt, auto, node distance=3cm]\n\n \\foreach [count=\\i] \\x/\\y/\\t in {0/0/S, 0/4/B, 3/4/C, 3/2/D, 10/0/E, 7/4/F, 10/4/T}\n \\node [circle,draw]\n (v\\t) at (\\x,\\y) {\\t};\n\n \\foreach \\i/\\j/\\t in {D/S/2, C/B/1, D/C/3, D/E/4, F/E/2, T/E/1, E/S/3}\n \\draw (v\\i) edge[post] node{\\t} (v\\j);\n \\foreach \\i/\\j/\\t in {S/B/7, B/S/1, C/F/4, F/C/1, F/T/2, T/F/5, D/F/7, F/D/2}\n \\draw (v\\i) edge[post, bend left=10] node{\\t} (v\\j);\n \n\\end{tikzpicture}\n\nOriginal graph: Max flow of 6\n\n\\begin{tikzpicture}[shorten >=1pt, auto, node distance=3cm]\n\n \\foreach [count=\\i] \\x/\\y/\\t in {0/0/S, 0/4/B, 3/4/C, 3/2/D, 10/0/E, 7/4/F, 10/4/T}\n \\node [circle,draw]\n (v\\t) at (\\x,\\y) {\\t};\n\n \\foreach \\i/\\j/\\f/\\t in {S/B/1/8, S/D/2/2, S/E/3/3, B/C/1/1, D/C/0/3, D/F/2/9, D/E/0/4, E/F/2/2, E/T/1/1, C/F/1/5, F/T/5/7}\n \\draw (v\\i) edge[post] node{\\f/\\t} (v\\j);\n\n\\end{tikzpicture}\n\n\\section{Kruskal’s Algorithm }\nMinimum spanning tree, iteration 1:\n\n\\begin{tikzpicture}[shorten >=1pt, auto, node distance=3cm]\n\n \\foreach [count=\\i] \\x/\\y/\\t in {0/0/A, 0/4/B}\n \\node [circle,draw]\n (v\\t) at (\\x,\\y) {\\t};\n\n \\foreach \\i/\\j/\\t in {A/B/1}\n \\draw (v\\i) edge node{\\t} (v\\j);\n \n\\end{tikzpicture}\n\nMinimum spanning tree, iteration 2:\n\n\\begin{tikzpicture}[shorten >=1pt, auto, node distance=3cm]\n\n \\foreach [count=\\i] \\x/\\y/\\t in {0/0/A, 0/4/B, 10/0/E, 7/4/F}\n \\node [circle,draw]\n (v\\t) at (\\x,\\y) {\\t};\n\n \\foreach \\i/\\j/\\t in {A/B/1, E/F/2}\n \\draw (v\\i) edge node{\\t} (v\\j);\n \n\\end{tikzpicture}\n\nMinimum spanning tree, iteration 3:\n\n\\begin{tikzpicture}[shorten >=1pt, auto, node distance=3cm]\n\n \\foreach [count=\\i] \\x/\\y/\\t in {0/0/A, 0/4/B, 3/4/C, 3/2/D, 10/0/E, 7/4/F}\n \\node [circle,draw]\n (v\\t) at (\\x,\\y) {\\t};\n\n \\foreach \\i/\\j/\\t in {A/B/1, E/F/2, A/E/3, D/C/3}\n \\draw (v\\i) edge node{\\t} (v\\j);\n \n\\end{tikzpicture}\n\nMinimum spanning tree, iteration 4:\n\n\\begin{tikzpicture}[shorten >=1pt, auto, node distance=3cm]\n\n \\foreach [count=\\i] \\x/\\y/\\t in {0/0/A, 0/4/B, 3/4/C, 3/2/D, 10/0/E, 7/4/F, 10/4/G}\n \\node [circle,draw]\n (v\\t) at (\\x,\\y) {\\t};\n\n \\foreach \\i/\\j/\\t in {A/B/1, E/F/2, A/E/3, D/C/3, E/G/4, D/E/4}\n \\draw (v\\i) edge node{\\t} (v\\j);\n \n\\end{tikzpicture}\n\nMinimum spanning tree, iteration 5:\n\n\\begin{tikzpicture}[shorten >=1pt, auto, node distance=3cm]\n\n \\foreach [count=\\i] \\x/\\y/\\t in {0/0/A, 0/4/B, 3/4/C, 3/2/D, 10/0/E, 7/4/F, 10/4/G, 7/2/H}\n \\node [circle,draw]\n (v\\t) at (\\x,\\y) {\\t};\n\n \\foreach \\i/\\j/\\t in {A/B/1, E/F/2, A/E/3, D/C/3, E/G/4, D/E/4, D/H/9}\n \\draw (v\\i) edge node{\\t} (v\\j);\n \n\\end{tikzpicture}\n\\end{document}\n", "meta": {"hexsha": "2b470d913092d803295efada46b13d025c282d98", "size": 14994, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "undergrad/cosc3020/hw/02/main.tex", "max_stars_repo_name": "andey-robins/school", "max_stars_repo_head_hexsha": "a3bf98dd2fdcbdea9eeecc524a7c31125e82fd77", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "undergrad/cosc3020/hw/02/main.tex", "max_issues_repo_name": "andey-robins/school", "max_issues_repo_head_hexsha": "a3bf98dd2fdcbdea9eeecc524a7c31125e82fd77", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "undergrad/cosc3020/hw/02/main.tex", "max_forks_repo_name": "andey-robins/school", "max_forks_repo_head_hexsha": "a3bf98dd2fdcbdea9eeecc524a7c31125e82fd77", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 51.8823529412, "max_line_length": 977, "alphanum_fraction": 0.6575296785, "num_tokens": 5160, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.411110869232168, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.16129393528179342}} {"text": "\\section{UTxO}\n\\label{sec:utxo}\n\n\n\\begin{figure*}[htb]\n \\emph{Derived types}\n %\n \\begin{equation*}\n \\begin{array}{r@{~\\in~}l@{\\qquad=\\qquad}lr}\n \\var{uin}\n & \\UTxOIn\n & \\TxId \\times \\Ix\n% & \\text{transaction output preference}\n \\\\\n \\var{uout}\n & \\UTxOOut\n & (\\TxOutND \\uniondistinct \\TxOutP) \\times \\Slot\n% & \\text{transaction outputs}\n \\\\\n \\var{utxo}\n & \\UTxO\n & \\UTxOIn \\mapsto \\UTxOOut\n% & \\text{unspent tx outputs}\n \\\\\n \\var{cur}\n & \\ScriptPurpose\n & \\PolicyID \\uniondistinct \\UTxOIn \\uniondistinct \\AddrRWD \\uniondistinct \\DCert\n% & \\text{item the script is validated for}\n \\end{array}\n \\end{equation*}\n \\caption{Definitions used in the UTxO transition system}\n \\label{fig:defs:utxo-shelley-1}\n\\end{figure*}\n\n\nWe make a number of changes to the Shelley UTxO model~\\ref{XX} to support the Goguen Extended UTxO model\n(see Figure~\\ref{fig:defs:utxo-shelley-1}).\n\n\\begin{itemize}\n\\item\n $\\UTxO$ entries are stored in the finite map $\\UTxOIn\\mapsto \\UTxOOut$.\n\n\\item\n $\\UTxOIn$ is the same type as $\\TxIn$ in Shelley, but we have changed\n the name because the types of transaction inputs and UTxO keys\n differ in Goguen.\n\n\\item\n $\\UTxOOut$ is the type of UTxO entries.\n Note that, like in the case of the type of transaction inputs,\n this type differs from the type of the output of a transaction.\n Goguen UTxO entries include a slot number for each output\n that indicates when the output was created.\n This will be used for future functionality.\n\n\\item\n $\\ScriptPurpose$ is the type of the items that scripts can validate.\n\n\\end{itemize}\n\n\\subsection{UTxO Transitions}\n\\label{sec:utxo-trans}\n\nWe have added several functions that deal with transaction and UTxO inputs and\noutputs as shown in Figure \\ref{fig:functions:insouts}. These are used in the definition of the UTxO transition system.\n\n\\begin{itemize}\n \\item The function $\\fun{txinputs_{vf}}$ returns only those transaction inputs\n that were selected to pay transaction fees (we call these ``fee-marked'' inputs).\n These inputs may only contain Ada.\n \\begin{note}\n Make it more obvious that we check that the fee inputs only contain Ada, maybe mention it elsewhere. Also, what does vf stand for?\n \\end{note}\n \\item The predicate $\\fun{feesOK}$ checks whether the transaction is\n paying the necessary fees, and that it does it correctly. That is, it checks that:\n \\begin{enumerate}[label=({\\roman*})]\n \\item the fee-marked inputs are not locked by non-native scripts;\n \\item all the fee-marked inputs contain strictly Ada and no other kinds of token;\n \\item the fee-marked inputs are sufficient to cover the fee amount that is stated\n in the transaction; and\n \\item the fee amount that the transaction states it is paying suffices to cover\n the minimum fee that the transaction is obligated to pay.\n \\end{enumerate}\n \\item The function $\\fun{getOut}$ selects the data from a transaction output that\n will be stored in the UTxO, i.e. a $\\UTxOOut$ without the slot number.\n \\item The function $\\fun{txins}$ returns the UTxO keys of transaction inputs.\n\\end{itemize}\n\nNote that when creating a transaction, the wallet is responsible for\ndetermining the fees. Thus, it also has to execute the non-native scripts\nand include the fees for their execution.\n\\begin{figure}[htb]\n \\begin{align*}\n & \\fun{txinputs_{vf}} \\in \\TxBody \\to \\powerset{\\TxId \\times \\Ix} \\\\\n & \\fun{txinputs_{vf}} ~txb~= \\\\\n &~~\\{ (txid,ix)~\\vert~(txid,ix,\\var{isfee}) \\in\n \\fun{txinputs} ~txb,~\n \\var{isfee} = \\True\\}\n \\nextdef\n & \\fun{feesOK} \\in \\N \\to \\PParams \\to \\GoguenTx \\to \\UTxO \\to \\Bool \\\\\n & \\fun{feesOK} ~n~\\var{pp}~tx~utxo~= \\\\\n &~~\\fun{range}~(\\fun{txinputs_{vf}}~{txb} \\restrictdom \\var{utxo}) \\subseteq \\TxOutND ~ \\\\\n &~~\\wedge~ \\var{balance} \\in \\Coin \\\\\n &~~ \\wedge~ \\var{balance} \\geq \\txfee{txb} ~ \\\\\n &~~ \\wedge~ \\minfee~n~{pp}~{tx} \\leq \\txfee{txb} \\\\\n &~~ \\where \\\\\n & ~~~~~~~ \\var{txb}~=~\\txbody{tx} \\\\\n & ~~~~~~~ \\var{balance}~=~\\fun{ubalance}~(\\fun{txinputs_{vf}}~{txb} \\restrictdom \\var{utxo})\n \\nextdef\n & \\fun{getOut} \\in \\TxOut \\to \\TxOutND \\uniondistinct \\TxOutP \\\\\n & \\fun{getOut} ~{txout}~= \\begin{cases}\n \\var{txout} & \\text{if~} \\var{txout} \\in \\TxOutND \\\\\n (\\fun{getAddr}~\\var{txout}, \\fun{getValue}~\\var{txout},\n \\fun{getDataHash}~\\var{txout}) & \\text{otherwise}\n \\end{cases}\n \\nextdef\n & \\fun{txins} \\in \\TxBody \\to \\powerset{\\TxId \\times \\Ix} \\\\\n & \\fun{txins} ~\\var{txb} = \\{(txid,ix) \\mid ((txid,ix),\\wcard)\\in\\fun{txinputs} ~txb\\}\n \\end{align*}\n \\caption{Functions on Tx Inputs and Outputs.}\n \\label{fig:functions:insouts}\n\\end{figure}\n%\nFigure~\\ref{fig:functions:utxo} defines the functions that are needed for the UTxO transition system.\nThe changes that are needed for Plutus integration are:\n\n\\begin{itemize}\n\n \\item The $\\fun{getCoin}$ function sums all the Ada in a given output and returns it as a\n $\\Coin$ value.\n\n \\item The function $\\fun{outs}$ discards the $\\HasDV$ tag from a\n transaction output and adds the slot number of the block in which the transaction is\n included.\n\n \\item $\\fun{txscriptfee}$ calculates the fee that a transaction must pay for script\n execution based on the amount of $\\ExUnits$ it has budgeted, and the prices in the current protocol parameters\n for each component of $\\ExUnits$.\n\n \\item The minimum fee calculation, $\\fun{minfee}$, includes the script\n fees that the transaction is obligated to pay in order to run its scripts.\n\n \\item The $\\fun{produced}$ calculation requires the current slot number as an argument -- this is\n needed to construct the correct UTxO outputs.\n\\end{itemize}\n\nSince the $\\Tx$ type combines both $\\ShelleyTx$ and $\\GoguenTx$, and\nthere was already a way of computing an ID from a Shelley transaction, there\nis potential for confusion how the ID of a transaction is\ncomputed. Here, $\\TxId$ is always computed from values of type $\\Tx$,\n\\emph{and never from the underlying $\\ShelleyTx$ or $\\GoguenTx$}. That is, there is a \\emph{canonical} ID for each Goguen transaction,\nand this is not necessarily the same as the corresponding ID in the underlying Shelley or Goguen transaction type.\n\n\\begin{figure}[htb]\n \\emph{Helper Functions}\n \\begin{align*}\n & \\fun{getCoin} \\in \\UTxOOut \\to \\Coin \\\\\n & \\fun{getCoin}~{\\var{out}} ~=~\\sum_{\\mathsf{adaID} \\mapsto tkns \\in \\fun{getValue}~out}\n (\\sum_{q \\in \\range~{tkns}} \\fun{co}~q)\n \\end{align*}\n %\n \\emph{Main Calculations}\n \\begin{align*}\n & \\fun{outs} \\in \\Slot \\to \\TxBody \\to \\UTxO \\\\\n & \\fun{outs} ~ \\var{slot}~\\var{txb} =\n \\left\\{\n (\\fun{txid} ~ \\var{txb}, \\var{ix}) \\mapsto (\\fun{getOut}~\\var{txout},\\var{slot}) ~\n \\middle|~\n \\var{ix} \\mapsto \\var{txout} \\in \\txouts{txb}\n \\right\\}\n \\nextdef\n & \\fun{txscriptfee} \\in \\N \\to \\Prices \\to \\ExUnits \\to \\Coin \\\\\n & \\fun{txscriptfee}~n~ (\\var{pr_{init}, pr_{mem}, pr_{steps}})~ (\\var{mem, steps})\n = \\var{pr_{init}}*n + \\var{pr_{mem}}*\\var{mem} + \\var{pr_{steps}}*\\var{steps}\n \\nextdef\n &\\fun{minfee} \\in \\N \\to \\PParams \\to \\GoguenTx \\to \\Coin \\\\\n &\\fun{minfee} ~n~\\var{pp}~\\var{tx} = \\\\\n &~~(\\fun{a}~\\var{pp}) \\cdot \\fun{txSize}~\\var{tx} + (\\fun{b}~\\var{pp}) +\n \\fun{txscriptfee}~n~(\\fun{prices}~{pp})~(\\fun{txexunits}~(\\fun{txbody}~{tx}))\n \\nextdef\n & \\fun{produced} \\in \\Slot \\to \\PParams \\to \\StakePools \\to \\TxBody \\to \\Value \\\\\n & \\fun{produced}~\\var{slot}~\\var{pp}~\\var{stpools}~\\var{txb} = \\\\\n &~~\\ubalance{(\\outs{slot}~{txb})} + \\fun{coinToValue}(\\txfee{txb} + \\deposits{pp}{stpools}~{(\\txcerts{txb})})\n \\end{align*}\n \\caption{Functions used in UTxO rules}\n \\label{fig:functions:utxo}\n\\end{figure}\n\n\\subsection{Combining Scripts with Their Inputs}\n\\label{sec:scripts-inputs}\n\nFigure~\\ref{fig:functions:script1} shows the helper functions that are needed to\nretrieve all the data that is relevant to Plutus script validation.\nThese include:\n\n\\begin{itemize}\n\\item\n $\\fun{indexof}$ finds the index of a given certificate, value, input, or\n withdrawal in a list, finite map, or set of such objects.\n This function assumes there is some ordering on each of these structures.\n% This function is abstract because it assumes there is some ordering rather\n% than giving it explicitly.\n \\begin{note}\n $\\fun{indexof}$ might need an actual implementation. Also, some\n restructuring in related functions might make it easier.\n Sets and maps don't really have indexes, of course.\n \\end{note}\n\\item\n $\\fun{indexedScripts}$ and $\\fun{indexedDats}$ create finite maps from sets of the corresponding object.\n The finite maps are indexed by the hashes of the objects that they contain.\n%\n% wherein, respectively, all the scripts\n% and datums that a transaction carries as sets, are indexed by their hashes.\n\\item\n $\\fun{findRdmr}$ finds the redeemer in a Goguen transaction\n that corresponds to a given item in the indexed redeemer structure, if it exists.\n\\end{itemize}\n\n\n\\begin{figure}[htb]\n %\n \\emph{Abstract functions}\n \\begin{align*}\n &\\fun{indexof} \\in \\DCert \\to \\seqof{\\DCert} \\to \\Ix\\\\\n &\\fun{indexof} \\in \\AddrRWD \\to \\Wdrl \\to \\Ix\\\\\n &\\fun{indexof} \\in \\UTxOIn \\to \\powerset{\\TxIn} \\to \\Ix\\\\\n &\\fun{indexof} \\in \\PolicyID \\to \\Value \\to \\Ix\\\\\n & \\text{get the index of an item in an ordered representation}\n \\end{align*}\n %\n \\emph{Helper functions}\n \\begin{align*}\n &\\fun{indexedScripts} \\in \\GoguenTx \\to (\\ScriptHash \\mapsto \\Script) \\\\\n &\\fun{indexedScripts}~{tx} ~=~ \\{ h \\mapsto s ~\\vert~ \\fun{hashScript}~{s}~=~h,\n s\\in~\\fun{txscripts}~(\\fun{txwits}~{tx})\\}\n \\nextdef\n &\\fun{indexedDats} \\in \\GoguenTx \\to (\\DataHash \\mapsto \\Data)\\\\\n &\\fun{indexedDats}~{tx} ~=~ \\{ h \\mapsto d ~\\vert~ \\fun{hashData}~{d}~=~h,\n d\\in~\\fun{txdats}~(\\fun{txwits}~{tx})\\}\n \\nextdef\n &\\fun{toRdmrPtr} \\in \\GoguenTx \\to \\ScriptPurpose \\to \\RdmrPtr \\\\\n &\\fun{toRdmrPtr}~{tx}~{it} ~=~\n \\begin{cases}\n (\\mathsf{certTag},\\fun{indexof}~\\var{it}~(\\fun{txcerts}~{txb})) & \\var{it}~\\in~\\DCert \\\\\n (\\mathsf{wdrlTag},\\fun{indexof}~\\var{it}~(\\fun{txwdrls}~{txb})) & \\var{it}~\\in~\\AddrRWD \\\\\n (\\mathsf{forgeTag},\\fun{indexof}~\\var{it}~(\\fun{forge}~{txb})) & \\var{it}~\\in~\\PolicyID \\\\\n (\\mathsf{inputTag},\\fun{indexof}~\\var{it}~(\\fun{txinputs}~{txb})) & \\var{it}~\\in~\\UTxOIn\n \\end{cases} \\\\\n & ~~\\where \\\\\n & ~~~~~~~ \\var{txb}~=~\\txbody{tx}\n \\nextdef\n &\\fun{findRdmr} \\in \\GoguenTx \\to (\\ScriptPurpose \\mapsto \\Data)\\\\\n & \\fun{findRdmr}~{tx} ~=~ \\{ \\var{it} \\mapsto \\var{d} ~|~\n \\var{it} \\in \\ScriptPurpose,~ \\fun{toRdmrPtr}~{tx}~{it} \\mapsto \\var{d} \\in \\fun{txrdmrs}~(\\fun{txwits}~{tx}) \\}\n \\end{align*}\n \\caption{Combining Script Validators and their Inputs}\n \\label{fig:functions:script1}\n\\end{figure}\n\n\n\\textbf{Plutus Script Validation}\nFigure~\\ref{fig:defs:functions-valid} shows the abstract functions that are used for script validation.\n\n\\begin{itemize}\n\\item\n $\\fun{valContext}$ constructs the validation context.\n This includes all the necessary transaction and chain state data that needs to be passed to the script interpreter.\n It has a $\\UTxO$ as its argument to recover the full information of the inputs of the transaction,\n but only the inputs of the transaction are provided to scripts.\n\\item\n $\\fun{hashScript},~ \\fun{hashData}$ are abstract hashing functions.\n\\item\n $\\fun{runMSigScript}$ validates multi-signature scripts, exactly as in the Shelley ledger specification (where it is called $\\fun{evaluateScript}$).\n\\item\n $\\fun{runPLCScript}$ validates Plutus scripts. It takes the following\n arguments:\n \\begin{itemize}\n \\item A cost model, that is used to calculate the $\\ExUnits$ that are needed for script execution;\n \\item A list of terms of type $\\Data$ that will be passed to the script; %is given access to.\n \\item The execution unit budget.\n \\end{itemize}\n It outputs a pair of the validation result (as a Boolean)\n and the remaining execution units (subtracting those that are used for script execution).\n Note that script execution stops if the full budget has been spent before validation is complete.\n\\end{itemize}\n\\begin{note}\n Maybe rename runPLCScript.\n\\end{note}\n\n\\begin{note}\n \\textbf{Know your contract arguments}\n A Plutus validator script may receive either a list of three terms of type $\\Data$, in case it validates the spending of script outputs\n or two terms (redeemer and context, with no datum), for all other uses.\n Script authors must keep this in mind when writing scripts, since the ledger call to the interpreter is oblivious to what\n arguments are required.\n\\end{note}\n\n\\begin{figure*}[htb]\n \\emph{Abstract Script Validation Functions}\n %\n \\begin{align*}\n &\\fun{hashScript} \\in ~\\Script\\to \\ScriptHash \\\\\n &\\text{Compute script hash} \\\\~\\\\\n &\\fun{hashData} \\in ~\\Data \\to \\DataHash \\\\\n &\\text{Compute hash of data} \\\\~\\\\\n &\\fun{valContext} \\in \\UTxO \\to \\GoguenTx \\to \\ScriptPurpose \\to \\Data \\\\\n &\\text{Build Validation Data} \\\\~\\\\\n &\\fun{runMSigScript} \\in\\ScriptMSig\\to \\GoguenTx \\to \\IsValidating \\\\\n &\\text{Validate a multi-signature script} \\\\~\\\\\n &\\fun{runPLCScript} \\in \\CostMod \\to\\ScriptPlutus \\to\n \\seqof{\\Data} \\to \\ExUnits \\to (\\IsValidating \\times \\ExUnits) \\\\\n &\\text{Validate a Plutus script, taking resource limits into account}\n \\end{align*}\n %\n \\emph{Notation}\n %\n \\begin{align*}\n \\llbracket \\var{script_v} \\rrbracket_{\\var{cm},\\var{exunits}}~\\var{d}\n &=& \\fun{runPLCScript} ~{cm}~\\var{script_v}~\\var{d}~\\var{exunits}\n \\end{align*}\n \\caption{Script Validation, cont.}\n \\label{fig:defs:functions-valid}\n\\end{figure*}\n\nNote that no ``checks'' are performed within the functions that match the\nscripts with their inputs. Missing validators, missing inputs, incorrect hashes, the wrong type of script etc,\nare caught during the application of the UTXOW rule (before these functions are ever applied).\n%\nVarious items of data are involved in building the inputs for script validation:\n\n\\begin{itemize}\n\\item The hash of the validator script;\n\n\\item The hash of the required datum, if any;\n\n\\item The corresponding full validator and datum object, which are looked up in the finite map\nconstructed by $\\fun{indexedScripts}$ and $\\fun{indexedDats}$, respectively;\n\n\\item The redeemer, which is contained in the transaction's indexed redeemer structure\nand which is located using the $\\fun{findRdmr}$ function; and\n\n\\item the validation data, built using the UTxO, the transaction itself,\nand the current item being validated.\n\\end{itemize}\n\n\n\\begin{figure}[htb]\n \\begin{align*}\n & \\fun{getData} \\in \\GoguenTx \\to \\UTxO \\to \\ScriptPurpose \\to \\seqof{\\Data} \\\\\n & \\fun{getData}~{tx}~{utxo}~{it}~=~\n \\begin{cases}\n [\\var{d}] & \\var{it} \\mapsto ((a,\\_),h_d, \\_) \\in \\var{utxo}, \\var{h_d}\\mapsto \\var{d} \\in \\fun{indexedDats}~{tx} \\\\\n \\epsilon & \\text{otherwise}\n \\end{cases}\n \\nextdef\n & \\fun{mkPLCLst} \\in \\PParams \\to \\GoguenTx \\to \\UTxO \\to \\seqof{(\\ScriptPlutus \\times \\seqof{\\Data} \\times \\CostMod)} \\\\\n & \\fun{mkPLCLst} ~\\var{pp}~\\var{tx}~ \\var{utxo} ~=~ \\\\\n & ~~\\fun{toList} \\{ (\\var{script}, (r; \\fun{valContext}~\\var{utxo}~\\var{tx}~\\var{cur}; \\fun{getData}~{tx}~{utxo}~{cur}), \\var{cm}) \\mid \\\\\n & ~~~~(\\var{cur}, \\var{scriptHash}) \\in \\fun{scriptsNeeded}~{tx}~{utxo}, \\\\\n & ~~~~\\var{cur} \\mapsto \\var{r} \\in \\fun{findRdmr}~{tx}, \\\\\n & ~~~~\\var{scriptHash}\\mapsto \\var{script}\\in \\fun{indexedScripts}~{tx}, \\\\\n & ~~~~\\fun{language}~{script} \\mapsto \\var{cm} \\in \\fun{costmdls}~{pp} \\}\n \\end{align*}\n \\caption{Scripts and their Arguments}\n \\label{fig:functions:script2}\n\\end{figure}\n\n\\subsection{Two-Phase Transaction Validation for Non-Native Scripts}\n\\label{sec:two-phase}\n\n\\begin{note}\n Make it more obvious somewhere where native vs non-native scripts are processed.\n\\end{note}\n\nThe costs of processing native scripts (those that involve only executing standard ledger rules) are included in the standard transaction fees.\nIn order to ensure that users pay for the computational resources that are needed to validate non-native scripts, even\nif transactions are invalid, transactions are validated in two phases:\nthe first phase consists of every aspect of transaction validation apart from executing the non-native scripts; and\nthe second phase involves actually executing those scripts.\n%\nOur validation approach uses four transition systems, each with different responsibilities. We\ngive the details of each below, but to summarize, when a transction is processed,\nthe processing is done\nin the following order:\n\n\n\\begin{tabular}{lp{12cm}}\n \\textbf{(UTXOW):} & Verifies that all the necessary witnessing information is present, including\n VKey witnesses, scripts, and all the script input data. It also performs\n key witness checks and runs multisig scripts. It then applies the state changes that are\n computed by the UTXO transition.\n \\\\\n \\textbf{(UTXO):} & Verifies that a transaction satisfies all the accounting requirements\n (including the general accounting property, correct fee payment, etc.),\n and applies the state changes that are computed by the UTXOS transition.\n \\\\\n \\textbf{(UTXOS):} & Performs the appropriate UTxO state changes, based on the\n value of the $\\IsValidating$ tag, which it checks using the SVAL transition.\n \\\\\n \\textbf{(SVAL):} & Runs the scripts, verifying that the $\\IsValidating$ tag\n is applied correctly.\n\\end{tabular}\n\nIn general, there is no way to check that the budget that has been supplied is sufficient for the transaction,\nexcept by running the scripts. To avoid over-spending the budget, we run them sequentially,\nstopping whenever one does not validate, and charging the transaction the corresponding\nfees. From the point of view of the ledger, there is no difference\nbetween a script running out of $\\ExUnits$ during validation, or not validating.\nIf a transaction contains an invalid script, the only change to the ledger\nas a result of applying this transaction is the fees.\n\nTwo-phase validation requires a new transition system\n(see Figure \\ref{fig:ts-types:utxos}) to sequentially run\nscripts and to track spent execution units as part of its state\n($\\var{remExU}$). The signal here is a sequence of pairs of a validator\nscript and the corresponding input data.\n\nNote that there is one state variable in the SVAL transition system. The reason\nfor this is that in the second, script-running validation phase, we separate\nthe UTxO state update from sequentially running scripts. This transition\nsystem is strictly for running the scripts, and a transition of this type\nwill be used by another rule to perform the correct UTxO update.\n\nRunning scripts sequentially\nto verify that they all validate in the allotted $\\ExUnits$ budget only requires\nthe amount of remaining $\\ExUnits$ to be included in the state, and nothing else.\nIn the environment, we need the protocol parameters and the\ntransaction being validated. All other data needed\nto run the scripts comes from the signal.\n\n\\begin{figure}[htb]\n \\emph{Validation environment}\n \\begin{equation*}\n \\ValEnv =\n \\left(\n \\begin{array}{r@{~\\in~}lr}\n \\var{pp} & \\PParams & \\text{protocol parameters}\\\\\n \\var{tx} & \\GoguenTx & \\text{transaction being processed} \\\\\n \\end{array}\n \\right)\n \\end{equation*}\n %\n \\emph{Validation state}\n \\begin{equation*}\n \\ValState =\n \\left(\n \\begin{array}{r@{~\\in~}lr}\n \\var{remExU} & \\ExUnits & \\text{exunits remaining to spend on validation} \\\\\n \\end{array}\n \\right)\n \\end{equation*}\n %\n \\emph{Script transitions}\n \\begin{equation*}\n \\_ \\vdash\n \\var{\\_} \\trans{sval}{\\_} \\var{\\_}\n \\subseteq \\powerset (\\ValEnv \\times \\ValState \\times \\seqof{(\\ScriptPlutus\\times\\seqof{\\Data}\\times\\CostMod)} \\times \\ValState)\n \\end{equation*}\n %\n \\caption{UTxO script validation types}\n \\label{fig:ts-types:utxos}\n\\end{figure}\n\nThe rules for the second-phase script validation SVAL are given in\nFigure~\\ref{fig:rules:utxo-scrval}. Again, no UTxO state update\nis done in this rule. Its purpose is to verify that the\nvalidation tag ($\\fun{txvaltag}$) is applied correctly by the creater of\nthe block. It does this by running all the scripts.\n\nNote that following the Shelley ledger specification approach, every function\nthat we define and use in the preconditions or calculations that are used in the ledger rules is\nnecessarily total.\nIn this way, all the errors (validation failures) that we encounter always come from\nrule applications, i.e. a precondition of a rule is not met.\nWe mention this here because the SVAL rule looks as if it could be\nsimply a function. However, we want the incorrect application of the\nvalidation tag to be an error, so this must be an error that comes form\nan unmet precondition of a rule.\n\nThere are three transition rules.\nThe first rule, $\\mathsf{Scripts\\mbox{-}Val}$, applies when:\n\n\\begin{enumerate}\n\\item There\nare no scripts left to validate in the signal list (i.e. this is the base case of\ninduction when all the scripts have validated) -- note that there could be $\\ExUnits$ left over; and\n\\item The validation tag is applied correctly (it is $\\True$).\n\\end{enumerate}\n\nThe $\\mathsf{Scripts\\mbox{-}Stop}$ rule applies when:\n\n\\begin{enumerate}\n \\item The current script-input pair does not validate;\n (either because the transaction ran out of $\\ExUnits$ or for any other reason); and\n \\item The validation tag is correct ($\\False$ in this case).\n\\end{enumerate}\n\nThese first two rules require no state change.\nThe $\\mathsf{Scripts\\mbox{-}Ind}$ rule applies when:\n\n\\begin{enumerate}\n \\item The current script being validated has been validated;\n \\item There is a non-negative fee which remains to pay for validating\n the rest of the scripts in the list; and\n \\item Transition rules apply for the rest of the list (without the current script).\n\\end{enumerate}\n\nThe only state change in this rule is of the variable $\\var{remExU}$.\nIt is decreased by subtracting the cost of the execution of the\ncurrent script from its current value.\nWe use this variable to keep track of the remaining funds for\nscript execution. If the transaction is overpaying ($\\fun{txscriptfee}~{tx}$\nis too big), then the whole fee is still taken.\n\nIt is always in the interest of the slot leader to have the new block validate,\nand for it to contain only valid transactions. This motivates the\nslot leader to:\n\n\\begin{enumerate}\n \\item Correctly apply the $\\IsValidating$ tag;\n \\item Include all transactions that validate,\n \\textit{even in case of a 2nd step script validation failure};\n \\item Exclude any transactions that are invalid in some way \\textit{other than 2nd step script validation failure}.\n\\end{enumerate}\n\nWe want to\ndiscard the blocks which have transactions with these tags\napplied incorrectly.\nOne of the reasons for having the correct validation tag added by the slot leader\nto a transaction is that re-applying blocks would not require repeat\nexecution of scripts in the transactions inside a block. In fact, when replaying\nblocks, all the witnessing information can be thrown away.\nWe also rely on the correct use of tags in other rules (at this time, only in\nthe rules that are shown in Figure \\ref{fig:rules:ledger}).\n\n\n\\textbf{Non-integral calculations within the Plutus interpreter.} At present, all Plutus calculations use integral types. If there\nwill be any future non-integral calculations (e.g. from the Actus contracts that are implemented using\nthe Marlowe interpreter), these should\nbe performed exactly as in the Shelley ledger (as described in~\\cite{non_int}). This is a matter of\nensuring deterministic script validation outcomes: inconsistent rounding, for example, could\nresult in different validation outcomes running the same script on the same\narguments.\n\n\n\\begin{figure}[htb]\n \\begin{equation}\n \\inference[Scripts-Val]\n {\n \\fun{txvaltag}~\\var{tx} = \\True &\n \\var{remExU}~\\geq~0\n }\n {\n \\begin{array}{l}\n \\var{pp}\\\\\n \\var{tx}\\\\\n \\end{array}\n \\vdash\n \\left(\n \\begin{array}{r}\n \\var{remExU}\\\\\n \\end{array}\n \\right)\n \\trans{sval}{\\epsilon}\n \\left(\n \\begin{array}{r}\n \\var{remExU}\\\\\n \\end{array}\n \\right) \\\\\n }\n \\end{equation}\n \\begin{equation}\n \\inference[Scripts-Stop]\n { \\\\~\\\\\n (\\var{isVal},\\var{remExU'})~:=~ \\llbracket sc \\rrbracket_\n {cm,\\var{remExU}} dt \\\\\n (sc, dt, cm) := s\n \\\\\n ~\n \\\\\n \\fun{txvaltag}~\\var{tx} = \\False &\n (\\var{remExU'}~<~0 ~ \\lor ~ \\var{isVal} = \\False)\n }\n {\n \\begin{array}{l}\n \\var{pp}\\\\\n \\var{tx}\\\\\n \\end{array}\n \\vdash\n \\left(\n \\begin{array}{r}\n \\var{remExU}\\\\\n \\end{array}\n \\right)\n \\trans{sval}{\\Gamma;s}\n \\left(\n \\begin{array}{r}\n \\var{remExU}\\\\\n \\end{array}\n \\right)\n }\n \\end{equation}\n \\begin{equation}\n \\inference[Scripts-Ind]\n {\n {\n \\begin{array}{l}\n \\var{pp}\\\\\n \\var{tx}\\\\\n \\end{array}\n }\n \\vdash\n \\left(\n {\n \\begin{array}{r}\n \\var{remExU}\\\\\n \\end{array}\n }\n \\right)\n \\trans{sval}{\\Gamma}\n \\left(\n {\n \\begin{array}{r}\n \\var{remExU'}\\\\\n \\end{array}\n }\n \\right) \\\\\n (\\var{isVal},\\var{remExU''})~:=~ \\llbracket sc \\rrbracket\n _{cm,\\var{remExU'}} dt \\\\\n (sc, dt, cm) := s & \\var{remExU''}~\\geq~0\n }\n {\n \\begin{array}{l}\n \\var{pp}\\\\\n \\var{tx}\\\\\n \\end{array}\n \\vdash\n \\left(\n \\begin{array}{r}\n \\var{remExU}\\\\\n \\end{array}\n \\right)\n \\trans{sval}{\\Gamma;s}\n \\left(\n \\begin{array}{r}\n \\varUpdate{remExU''}\\\\\n \\end{array}\n \\right)\n }\n \\end{equation}\n \\caption{Script validation rules}\n \\label{fig:rules:utxo-scrval}\n\\end{figure}\n\n\n\\subsection{Updating the UTxO State}\n\\label{sec:utxo-state-trans}\n\nWe have defined a separate transition system, UTXOS, to represent the two distinct\nUTxO state changes, one resulting from all scripts in a transaction validating,\nthe other - from at least one failing to validate. Its transition types\nare all the same as for the for the UTXO transition, see Figure\n\\ref{fig:ts-types:utxo-scripts}.\n\n\\begin{figure}[htb]\n \\emph{State transitions}\n \\begin{equation*}\n \\_ \\vdash\n \\var{\\_} \\trans{utxo, utxos}{\\_} \\var{\\_}\n \\subseteq \\powerset (\\UTxOEnv \\times \\UTxOState \\times \\GoguenTx \\times \\UTxOState)\n \\end{equation*}\n %\n \\caption{UTxO and UTxO script state update types}\n \\label{fig:ts-types:utxo-scripts}\n\\end{figure}\n\nThere are two rules, corresponding to the two possible state changes of the\nUTxO state in the UTXOS transition system (Figure~\\ref{fig:rules:utxo-state-upd}).\n%\nIn both cases, the SVAL transition is called upon to verify that the $\\IsValidating$\ntag has been applied correctly. The function $\\fun{mkPLCLst}$ is used to build\nthe signal list $\\var{sLst}$ for the SVAL transition.\n%\nThe first rule\napplies when the validation tag is $\\True$.\nIn this case, the states of the UTxO, fee\n and deposit pots, and updates are updated exactly as in the current Shelley\n ledger spec.\n%\n The second rule\n applies when the validation tag is $\\False$.\n In this case, the UTxO state changes as follows:\n\n \\begin{enumerate}\n \\item All the\n UTxO entries corresponding to the transaction inputs selected for covering\n script fees are removed;\n\n \\item The sum total of the value of the marked UTxO entries\n is added to the fee pot.\n \\end{enumerate}\n\n\n\\begin{figure}[htb]\n \\begin{equation}\n \\inference[Scripts-Yes]\n {\n \\var{txb}\\leteq\\txbody{tx} &\n \\fun{txvaltag}~\\var{tx} = \\True\n \\\\\n ~\n \\\\\n \\var{sLst} := \\fun{mkPLCLst}~\\var{pp}~\\var{tx}~\\var{utxo}\n \\\\~\\\\\n {\n \\left(\n \\begin{array}{r}\n \\var{pp} \\\\\n \\var{tx} \\\\\n \\end{array}\n \\right)\n }\n \\vdash\n \\var{\\fun{txexunits}~{tx}}\n \\trans{sval}{sLst}\\var{remExU}\n \\\\~\\\\\n {\n \\left(\n \\begin{array}{r}\n \\var{slot} \\\\\n \\var{pp} \\\\\n \\var{genDelegs} \\\\\n \\end{array}\n \\right)\n }\n \\vdash \\var{ups} \\trans{\\hyperref[fig:rules:update]{up}}{\\fun{txup}~\\var{tx}} \\var{ups'}\n \\\\~\\\\\n \\var{refunded} \\leteq \\keyRefunds{pp}{stkCreds}~{txb}\n \\\\\n \\var{depositChange} \\leteq\n (\\deposits{pp}~{stpools}~{(\\txcerts{txb})}) - \\var{refunded}\n }\n {\n \\begin{array}{l}\n \\var{slot}\\\\\n \\var{pp}\\\\\n \\var{stkCreds}\\\\\n \\var{stpools}\\\\\n \\var{genDelegs}\\\\\n \\end{array}\n \\vdash\n \\left(\n \\begin{array}{r}\n \\var{utxo} \\\\\n \\var{deposits} \\\\\n \\var{fees} \\\\\n \\var{ups} \\\\\n \\end{array}\n \\right)\n \\trans{utxos}{tx}\n \\left(\n \\begin{array}{r}\n \\varUpdate{\\var{(\\txins{txb} \\subtractdom \\var{utxo}) \\cup \\outs{slot}~{txb}}} \\\\\n \\varUpdate{\\var{deposits} + \\var{depositChange}} \\\\\n \\varUpdate{\\var{fees} + \\txfee{txb}} \\\\\n \\varUpdate{\\var{ups'}} \\\\\n \\end{array}\n \\right) \\\\\n }\n \\end{equation}\n \\begin{equation}\n \\inference[Scripts-No]\n {\n \\var{txb}\\leteq\\txbody{tx} &\n \\fun{txvaltag}~\\var{tx} = \\False\n \\\\\n ~\n \\\\\n \\var{sLst} := \\fun{mkPLCLst}~\\var{pp}~\\var{tx}~\\var{utxo}\n \\\\~\\\\\n {\n \\left(\n \\begin{array}{r}\n \\var{pp} \\\\\n \\var{tx} \\\\\n \\end{array}\n \\right)\n }\n \\vdash\n \\var{\\fun{txexunits}~{tx}}\n \\trans{sval}{sLst}\\var{remExU}\n }\n {\n \\begin{array}{l}\n \\var{slot}\\\\\n \\var{pp}\\\\\n \\var{stkCreds}\\\\\n \\var{stpools}\\\\\n \\var{genDelegs}\\\\\n \\end{array}\n \\vdash\n \\left(\n \\begin{array}{r}\n \\var{utxo} \\\\\n \\var{deposits} \\\\\n \\var{fees} \\\\\n \\var{ups} \\\\\n \\end{array}\n \\right)\n \\trans{utxos}{tx}\n \\left(\n \\begin{array}{r}\n \\varUpdate{\\var{\\fun{txinputs_{vf}}~{txb} \\subtractdom \\var{utxo}}} \\\\\n \\var{deposits} \\\\\n \\varUpdate{\\var{fees} + \\fun{ubalance}~(\\fun{txinputs_{vf}}~{txb}\\restrictdom \\var{utxo})} \\\\\n \\var{ups} \\\\\n \\end{array}\n \\right)\n }\n \\end{equation}\n \\caption{State update rules}\n \\label{fig:rules:utxo-state-upd}\n\\end{figure}\n\nFigure \\ref{fig:rules:utxo-shelley} shows the $\\type{UTxO-inductive}$\ntransition rule for the UTXO transition type. Note that the\nsignal for this transition is specifically of type $\\GoguenTx$, so it does not\nwork with Shelley transactions. Thus, the UTXOW rule needs to convert a $\\Tx$ into\na $\\GoguenTx$ to invoke the UTXO rule.\nThis rule has the following preconditions (plus the relevant ones\nfrom the original Shelley specification):\n\n\\begin{enumerate}\n \\item The transaction is being processed within its validity interval;\n\n \\item The transaction has at least one input;\n\n \\item All inputs in a transaction correspond to UTxO entries;\n\n \\item The general accounting property holds;\n\n \\item The transaction pays fees correctly;\n\n \\item The transaction is not forging any Ada;\n\n \\item All outputs of the transaction contain only non-negative quantities;\n\n \\item The transaction size does not exceed the maximum limit;\n\n \\item The execution units budget that a transaction gives does not exceed the maximum\n permitted number of units;\n\n \\item The UTXOS state transition is valid.\n\\end{enumerate}\n\nThe resulting state transition is defined entirely by the application of the\nUTXOS rule.\n\n\\begin{figure}[htb]\n \\begin{equation}\\label{eq:utxo-inductive-shelley}\n \\inference[UTxO-inductive]\n {\n \\var{txb}\\leteq\\txbody{tx} &\n \\var{txw}\\leteq\\fun{txwits}~{tx} \\\\\n \\fun{txfst}~txb \\leq \\var{slot}\n & \\fun{txttl}~txb \\geq \\var{slot}\n \\\\\n \\txins{txb} \\neq \\emptyset\n & \\txins{txb} \\subseteq \\dom \\var{utxo}\n \\\\\n \\consumed{pp}{utxo}{stkCreds}{rewards}~{txb} = \\produced{slot}~{pp}~{stpools}~{txb}\n \\\\~\\\\\n \\fun{feesOK}~(\\vert~ \\fun{txscripts}~{tx} \\cap \\ScriptPlutus ~\\vert) ~pp~tx~utxo \\\\\n \\\\\n ~\n \\\\\n \\mathsf{adaID}~\\notin \\dom~{\\fun{forge}~tx} \\\\\n \\forall txout \\in \\txouts{txb}, ~ \\fun{getValue}~txout ~\\geq ~ 0 \\\\~\n \\forall txout \\in \\txouts{txb}, ~ \\fun{getCoin}~txout ~\\geq \\\\\n \\fun{valueSize}~(\\fun{getValue}~txout) * \\fun{minUTxOValue}~pp \\\\~\n \\\\\n \\fun{txsize}~{tx}\\leq\\fun{maxTxSize}~\\var{pp} \\\\\n \\fun{txexunits}~{txb} \\leq \\fun{maxTxExUnits}~{pp}\n \\\\\n ~\n \\\\\n {\n \\begin{array}{c}\n \\var{slot}\\\\\n \\var{pp}\\\\\n \\var{stkCreds}\\\\\n \\var{stpools}\\\\\n \\var{genDelegs}\\\\\n \\end{array}\n }\n \\vdash\n {\n \\left(\n \\begin{array}{r}\n \\var{utxo} \\\\\n \\var{deposits} \\\\\n \\var{fees} \\\\\n \\var{ups}\\\\\n \\end{array}\n \\right)\n }\n \\trans{utxos}{\\var{tx}}\n {\n \\left(\n \\begin{array}{r}\n \\var{utxo'} \\\\\n \\var{deposits'} \\\\\n \\var{fees'} \\\\\n \\var{ups'}\\\\\n \\end{array}\n \\right)\n }\n }\n {\n \\begin{array}{l}\n \\var{slot}\\\\\n \\var{pp}\\\\\n \\var{stkCreds}\\\\\n \\var{stpools}\\\\\n \\var{genDelegs}\\\\\n \\end{array}\n \\vdash\n \\left(\n \\begin{array}{r}\n \\var{utxo} \\\\\n \\var{deposits} \\\\\n \\var{fees} \\\\\n \\var{ups}\\\\\n \\end{array}\n \\right)\n \\trans{utxo}{tx}\n \\left(\n \\begin{array}{r}\n \\varUpdate{\\var{utxo'}} \\\\\n \\varUpdate{\\var{deposits'}} \\\\\n \\varUpdate{\\var{fees'}} \\\\\n \\varUpdate{\\var{ups'}}\\\\\n \\end{array}\n \\right)\n }\n \\end{equation}\n \\caption{UTxO inference rules}\n \\label{fig:rules:utxo-shelley}\n\\end{figure}\n\n\\subsection{Witnessing}\n\\label{sec:wits}\n\nBecause of two-phase transaction validation, Plutus script validation is not part of transaction witnessing.\nHowever, native script validation does remain part of transaction witnessing.\nWhen witnessing a transaction, we therefore need to validate only the native scripts.\nWe have consequently changed the definition of the function\n$\\fun{scriptsNeeded}$, see Figure~\\ref{fig:functions-witnesses} to include both multi-signature and Plutus scripts, plus the scripts that are used for any\nvalidation purpose (forging, outputs, certificates, withdrawals).\n\n\\begin{figure}[htb]\n \\begin{align*}\n & \\hspace{-1cm}\\fun{scriptsNeeded} \\in \\UTxO \\to \\GoguenTx \\to \\powerset (\\ScriptPurpose \\times \\ScriptHash) \\\\\n & \\hspace{-1cm}\\fun{scriptsNeeded}~\\var{utxo}~\\var{tx} = \\\\\n & ~~\\{ (\\var{i}, \\fun{validatorHash}~a) \\mid i \\mapsto (a, \\wcard) \\in \\var{utxo},\\\\\n & ~~~~~i\\in\\fun{txinsScript}~{(\\fun{txins~\\var{txb}})}~{utxo}\\} \\\\\n \\cup & ~~\\{ (\\var{a}, \\fun{stakeCred_{r}}~\\var{a}) \\mid a \\in \\dom (\\AddrRWDScr\n \\restrictdom \\fun{txwdrls}~\\var{txb}) \\} \\\\\n \\cup & ~~\\{ (\\var{cert}, \\var{c}) \\mid \\var{cert} \\in (\\DCertDeleg \\cup \\DCertDeRegKey)\\cap\\fun{txcerts}~(\\txbody{tx}), \\\\\n & ~~~~~~\\var{c} \\in \\cwitness{cert} \\cap \\AddrScr\\} \\\\\n \\cup & ~~\\{ (\\var{pid}, \\var{pid}) \\mid \\var{pid} \\in \\supp~(\\fun{forge}~\\var{txb}) \\} \\\\\n & \\where \\\\\n & ~~~~~~~ \\var{txb}~=~\\txbody{tx}\n \\end{align*}\n \\caption{Scripts Needed}\n \\label{fig:functions-witnesses}\n\\end{figure}\n\nIn the Goguen era, we must be able to validate both Shelley transactions\nand Goguen transactions. To do this, we transform any Shelley transactions\ninto Goguen ones, filling any missing data fields with default values.\nThe only time that we need the original Shelley transaction is to check the signatures\nin the hash of the original transaction body, as shown in\nFigure~\\ref{fig:rules:utxow-goguen}. In addition to the Shelley UTXOW preconditions\nthat still apply, we have made the following changes and additions:\n\n\\begin{itemize}\n\n \\item All the multi-signature scripts in the transaction validate;\n\n \\item The transaction contains exactly those scripts that are required for witnessing and no\n additional ones (this includes all languages of scripts, for all purposes);\n\n \\item The transaction contains a redeemer for every item that needs to be validated\n by a Plutus script;\n\n \\item The only certificates that are allowed to have scripts as witnesses\n are delegation de-registration certificates;\n\n \\item The transaction has a datum for every Plutus script output that it spends;\n\n \\item The transaction has a datum for every Plutus script output that is\n marked with the $\\True$ tag for $\\HasDV$;\n\n \\item\n The hash of the subset of protocol parameters in the transaction body is equal to\n the hash of the same subset of protocol parameters that are currently on the ledger;\n\n \\item The hash of the indexed redeemer structure that is attached to the transaction is\n the same as $\\fun{rdmrsHash}~{tx}$ (the hash value that is contained in the signed body of\n the transaction).\n\n\\end{itemize}\n\nIf these conditions are all satisfied, then the resulting UTxO state change is fully determined\nby the UTXO transition (the application of which is also part of the conditions).\n\n\\begin{figure}[htb]\n \\emph{State transitions}\n \\begin{equation*}\n \\_ \\vdash\n \\var{\\_} \\trans{utxow}{\\_} \\var{\\_}\n \\subseteq \\powerset (\\UTxOEnv \\times \\UTxOState \\times \\Tx \\times \\UTxOState)\n \\end{equation*}\n %\n \\caption{UTxO with witnesses state update types}\n \\label{fig:ts-types:utxo-witness}\n\\end{figure}\n\n\\begin{figure}\n \\begin{equation}\n \\label{eq:utxo-witness-inductive-goguen}\n \\inference[UTxO-witG]\n {\n \\var{tx}~\\leteq~\\fun{toGoguenTx}~{tx}_o \\\\~\\\\\n \\var{txb}\\leteq\\txbody{tx} &\n \\var{txw}\\leteq\\fun{txwits}~{tx} &\n \\var{tx}~\\in~\\GoguenTx \\\\\n (utxo, \\wcard, \\wcard, \\wcard) \\leteq \\var{utxoSt} \\\\\n \\var{witsKeyHashes} \\leteq \\{\\fun{hashKey}~\\var{vk} \\vert \\var{vk} \\in\n \\dom (\\txwitsVKey{txw}) \\}\\\\~\\\\\n \\forall \\var{validator} \\in \\fun{txscripts}~{txw} \\cap \\ScriptMSig,\\\\\n \\fun{runMSigScript}~\\var{validator}~\\var{tx}\\\\~\\\\\n \\{ h \\mid (\\wcard, h) \\in \\fun{scriptsNeeded}~\\var{utxo}~\\var{tx}\\} ~=~ \\dom (\\fun{indexedScripts}~{tx}) \\\\\n \\forall (\\var{purp}, h) \\in ~\\fun{scriptsNeeded}~\\var{utxo}~\\var{tx}, ~h\\mapsto s~\\in~\\fun{indexedScripts}~{tx},\\\\\n s \\in \\ScriptPlutus~\\Leftrightarrow \\exists r, \\var{purp} \\mapsto r \\in \\fun{findRdmr}~{tx}\n \\\\~\\\\\n \\forall \\var{cert}~\\in~\\fun{txcerts}~{txb}, \\fun{regCred}~{cert}\\in \\PolicyID \\Leftrightarrow\n \\var{cert} \\in~ \\DCertDeRegKey \\\\~\\\\\n \\forall~\\var{txin}\\in\\fun{txinputs}~{txb},\n \\var{txin} \\mapsto \\var{(\\wcard,\\wcard,h_d)} \\in \\var{utxo},\n \\var{h_d} ~\\in \\fun{dom}(\\fun{indexedDats}~{tx})\n \\\\\n ~\n \\\\\n \\forall~ix \\mapsto (a,v,d_h,\\True) ~\\in~\\fun{txouts}~{txb}, \\\\\n \\var{d_h}\\in \\fun{dom}~ (\\fun{indexedDats}~{tx})\n \\\\\n ~\n \\\\\n \\fun{ppHash}~{txb}~=~\\fun{hashLanguagePP}~\\var{pp}~(\\fun{cmlangs}~(\\fun{txscripts}~\\var{txw})) \\\\~\\\\\n \\fun{txrdmrs}~\\var{txw} ~=~ \\emptyset \\Leftrightarrow \\fun{rdmrsHash}~{txb}~=~\\Nothing \\\\\n \\fun{txrdmrs}~\\var{txw} ~\\neq~ \\emptyset \\Leftrightarrow\n \\fun{hash}~(\\fun{txrdmrs}~\\var{txw})~ =~ \\fun{rdmrsHash}~{txb} \\\\\n \\\\~\\\\\n \\forall \\var{vk} \\mapsto \\sigma \\in \\txwitsVKey{txw},\n \\mathcal{V}_{\\var{vk}}{\\serialised{tx_{o}}}_{\\sigma} \\\\\n \\fun{witsVKeyNeeded}~{utxo}~{tx}~{genDelegs} \\subseteq \\var{witsKeyHashes}\n \\\\~\\\\\n genSig \\leteq\n \\left\\{\n \\fun{hashKey}~gkey \\vert gkey \\in\\dom{genDelegs}\n \\right\\}\n \\cap\n \\var{witsKeyHashes}\n \\\\\n \\left\\{\n c\\in\\txcerts{txb}~\\cap\\DCertMir\n \\right\\} \\neq\\emptyset \\implies \\vert genSig\\vert \\geq \\Quorum \\wedge\n \\fun{d}~\\var{pp} > 0\n \\\\~\\\\\n \\var{mdh}\\leteq\\fun{txMDhash}~\\var{txb}\n &\n \\var{md}\\leteq\\fun{txMD}~\\var{tx}\n \\\\\n (\\var{mdh}=\\Nothing \\land \\var{md}=\\Nothing)\n \\lor\n (\\var{mdh}=\\fun{hashMD}~\\var{md})\n \\\\~\\\\\n {\n \\begin{array}{r}\n \\var{slot}\\\\\n \\var{pp}\\\\\n \\var{stkCreds}\\\\\n \\var{stpools}\\\\\n \\var{genDelegs}\\\\\n \\end{array}\n }\n \\vdash \\var{utxoSt} \\trans{\\hyperref[fig:rules:utxo-shelley]{utxo}}{tx}\n \\var{utxoSt'}\\\\\n }\n {\n \\begin{array}{r}\n \\var{slot}\\\\\n \\var{pp}\\\\\n \\var{stkCreds}\\\\\n \\var{stpools}\\\\\n \\var{genDelegs}\\\\\n \\end{array}\n \\vdash \\var{utxoSt} \\trans{utxow}{{tx}_o} \\varUpdate{\\var{utxoSt'}}\n }\n \\end{equation}\n \\caption{UTxO with witnesses inference rules for GoguenTx}\n \\label{fig:rules:utxow-goguen}\n\\end{figure}\n", "meta": {"hexsha": "5d45206e919e0e19320f9c4607ad6dc34e4daadd", "size": 40872, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "goguen/formal-spec/utxo.tex", "max_stars_repo_name": "michaelpj/cardano-ledger-specs", "max_stars_repo_head_hexsha": "d371ad2ebf5d1ddff93776fac2dfd1045aa6b06c", "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": "goguen/formal-spec/utxo.tex", "max_issues_repo_name": "michaelpj/cardano-ledger-specs", "max_issues_repo_head_hexsha": "d371ad2ebf5d1ddff93776fac2dfd1045aa6b06c", "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": "goguen/formal-spec/utxo.tex", "max_forks_repo_name": "michaelpj/cardano-ledger-specs", "max_forks_repo_head_hexsha": "d371ad2ebf5d1ddff93776fac2dfd1045aa6b06c", "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": 36.623655914, "max_line_length": 154, "alphanum_fraction": 0.6519622235, "num_tokens": 12999, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.3007455914759599, "lm_q1q2_score": 0.160928493415167}} {"text": "\n% ==============\n%\n% --------------\n%-----\n\\section{Parallel Scaling of the EMG Model Using High Performance Computing}\\label{sec:hpc_emg}\n% in opendihu 2021 paper\n\nAfter the parallel scaling of the multi-scale model has been investigated in moderately parallel scenarios with up to 27 processes in the previous sections, we now study the parallel scalability in High Performance Computing scenarios with larger degrees of parallelism.\nWe simulate the fiber based electrophysiology model consisting of a 0D subcellular model, the 1D electric conduction problem and the 3D bidomain equation, as described in \\cref{sec:model_equations}.\nWe conduct these studies on the supercomputer Hawk at the High Performance Computing Center Stuttgart (HLRS). The system contains a total of 5632 compute nodes. Each compute node consists of two AMD EPYC 7742 processors with 64 cores each, a clock frequency of \\SI{2.25}{\\giga\\hertz} and \\SI{256}{\\giga\\byte} memory per node.\n\nIn the following, \\cref{sec:weak_scaling_hawk} presents a weak scaling study, which scales the problem size up to a realistic number of \\num{270000} muscle fibers in a biceps muscle.\nThen, \\cref{sec:mpi_rank_placement} shows measurements of the scaling behavior for the 1D model solver and gives details on MPI rank placement policies.\n\n\\subsection{Weak Scaling of the Fiber Based Electrophysiology Model}\\label{sec:weak_scaling_hawk}\n\nWe simulate the fiber based electrophysiology model with EMG values on the muscle surface and the subcellular model of Hodgkin and Huxley \\cite{Hodgkin1952}.\nCorresponding simulation results of this scenario, also for the highly parallel runs, are presented in \\cref{sec:effects_of_the_mesh_width_emg}.\n\nIn this weak scaling study, the number of fibers and number of processes is varied while their relation is kept approximately constant. The scenarios are constructed such that there are approximately 10 fibers per process, while maintaining a cube partitioning scheme in the 3D domain. The 0D subcellular and the 1D electric conduction problems on the fibers are solved with the \\code{FastMonodomainSolver} class and the \\code{`vc`} optimization type, which is the fastest available option in OpenDiHu. The Strang operator splitting scheme with Heun's method and the implicit Euler scheme are used. The 3D problem is solved using the conjugate gradient solver of PETSc and a relative tolerance on the residual norm of \\num{1e-5}. \n\nThe used timestep widths are $\\dt_\\text{0D}=\\SI{1e-3}{\\milli\\second}$, $\\dt_\\text{1D}=\\dt_\\text{splitting}=\\SI{2e-3}{\\milli\\second}$ and $\\dt_\\text{3D}=\\SI{1}{\\milli\\second}$. Because only the scaling behavior is of interest in this study, the simulation end time is set to $t_\\text{end}=\\SI{2}{\\milli\\second}$.\n\n% Hawk weak scaling\n\\begin{figure}[H]\n \\centering%\n \\includegraphics[width=\\textwidth]{images/results/studies/hawk_weak_scaling.pdf}%\n \\caption{Weak scaling of the fiber based electrophysiology model on the supercomputer Hawk simulating up to more than \\num{270000} muscle fibers.}%\n \\label{fig:hawk_weak_scaling}%\n\\end{figure}\n\n\\Cref{fig:hawk_weak_scaling} presents the resulting runtimes for the different parts of the simulation program: the solvers of the 0D, 1D and 3D models, the runtime for initialization and the runtime for the communication in the \\code{FastMonodomainSolver}, as explained in \\cref{sec:improved_parallel_solver_for_fiber_based}.\nTo relate the initialization runtime to the runtime of the solvers in a realistic scenario with longer simulation times, all runtimes except for the initialization are scaled to a simulation end time of $\\SI{1}{\\second}$.\n\nThe results show perfect weak scaling properties of the 0D and the 1D solver, given by the yellow and red lines. This is expected due to the construction of the algorithm and the parallel partitioning. The 0D problems are \\say{embarrassingly parallel} and are solved independently of each other. In the 1D problem solver, the values are transferred to a dedicated process, where the serial Thomas algorithm is employed for each fiber as a whole. Thus, the solution of all 1D problems is also performed independently of each other, but an additional communication step is required, before and after running the solver in each implicit time step of the 1D problem.\nThe plot shows a very small runtime for this communication even for higher parallelism, which is given by the orange dashed line.\n\nThe initialization of the computation involves parsing the Python script, which for the last data point requires \\SI{35.1}{\\s}, parallel file access and read operations of the mesh file, assembly of the 3D stiffness matrix and solution of the potential flow problem to obtain the fiber directions in the 3D mesh, which contains approximately \\num{1e8} dofs for the last data point, code generation, compilation, linking and loading of the shared library for the subcellular problem, and initialization of all internal data structures.\n\nLoading the mesh input file from the file system is the part of the initialization, which requires the most runtime.\nThe dotted light blue line in \\cref{fig:hawk_weak_scaling} shows that the initialization time increases to a maximum value of \\SI{839}{\\s} for the largest problem size.\n\nThe runtime of the 3D model is shown by the blue line in \\cref{fig:hawk_weak_scaling}. This part of the model is responsible for the highest portion of the total runtime starting from the scenario with \\num{7744} fibers and \\num{76729} processes. This increase is two-fold: first, the communication cost increases for a larger number of processes. Second, the number of iterations in the conjugate gradient solver increases for a larger number of unknowns.\n\n\\begin{table}\n \\centering%\n \\begin{tabular}{|r|r|r|r|r|r|r|r|r|}\n \\hline\n \\# processes & 18 & 64 & 144 & 448 & 1152 & 3600 & 7744 & \\num{26912}\\\\\\hline\n \\# iterations & 72 & 115 & 176 & 339 & 561 & 1056 & 1636 & 2807\\\\\n \\hline\n \\end{tabular}\n \\caption{Scaling study of the fiber based muscle model: Number of iterations of the conjugate gradient solver for the 3D bidomain model in the weak scaling study presented in \\cref{fig:hawk_weak_scaling}.}%\n \\label{tab:cg_solver_iterations}%\n\\end{table}\n\nIn this weak scaling study, the number of conjugate gradient solver iterations increases from 72 for the first data point to \\num{2807} for the last data point, as listed in \\cref{tab:cg_solver_iterations}. The 3D problem of the last data point has \\num{1e8} dofs. The exact numbers of dofs are also listed in \\cref{tab:emg_study_parameters} in \\cref{sec:effects_of_the_mesh_width_emg}.\nCurrently, the solution of the 3D problem uses no preconditioner. In future work, a multigrid solver could be employed for preconditioning, which could improve the weak scaling for large problem sizes.\n\nIn summary, the solution of the multi-scale model for fiber based electrophysiology without fat layer exhibits a very good weak scalability for up to \\num{35000} fibers. For larger problem sizes, the solution of the 3D problem dominates and the weak scaling behavior deteriorates. However, the solution times are still feasible, as such large problems have been successfully solved in \\cref{sec:effects_of_the_mesh_width_emg} of this work.\n\n\n% n_it\n% nRanks \n% 18 72\n% 64 115\n% 144 176\n% 448 339\n% 1152 561\n% 3600 1056\n% 7744 1636\n% 26912 2807\n\n% partitioning 2* 2* 1= 4 7^2= 49 fibers, fibers/rank: 12.250000, need 1 nodes\n% partitioning 3* 3* 2= 18 13^2= 169 fibers, fibers/rank: 9.388889, need 1 nodes\n% partitioning 4* 4* 4= 64 25^2= 625 fibers, fibers/rank: 9.765625, need 1 nodes\n% partitioning 6* 6* 4= 144 37^2= 1369 fibers, fibers/rank: 9.506944, need 3 nodes\n% partitioning 7* 8* 8= 448 67^2= 4489 fibers, fibers/rank: 10.020089, need 7 nodes\n% partitioning 12*12* 8= 1152 109^2= 11881 fibers, fibers/rank: 10.313368, need 18 nodes\n% partitioning 15*15*16= 3600 187^2= 34969 fibers, fibers/rank: 9.713611, need 57 nodes\n% partitioning 22*22*16= 7744 277^2= 76729 fibers, fibers/rank: 9.908187, need 121 nodes\n% partitioning 24*24*32=18432 427^2=182329 fibers, fibers/rank: 9.891981, need 288 nodes\n% partitioning 29*29*32=26912 523^2=273529 fibers, fibers/rank: 10.163830, need 421 nodes\n% partitioning 40*40*32=51200 523^2=273529 fibers, fibers/rank: 5.342363, need 800 nodes\n% subdomains user total comp. 0D 1D bidomain duration_init write mem n_it n\n% scenarioName nRanks \n% hawk_weak_scaling_endtime_1.0_1 18 [3, 3, 2] 100.216111 2.346004 1.289333 0.128295 0.007430 97.870107 0.0 0.203 GB 72 18\n% 64 [4, 4, 4] 134.937500 2.893596 1.765827 0.175330 0.113093 132.043904 0.0 0.315 GB 115 64\n% 144 [6, 6, 4] 219.409583 2.850457 1.473133 0.146266 0.245577 216.559126 0.0 0.341 GB 176 144\n% 448 [7, 8, 8] 48.533839 2.428730 1.463591 0.145278 0.308863 46.105109 0.0 0.584 GB 339 448\n% 1152 [12, 12, 8] 295.241211 3.548350 1.489827 0.148680 1.321491 291.692861 0.0 0.385 GB 561 2304\n% 3600 [15, 15, 16] 80.168103 4.069231 1.471832 0.146008 1.033123 76.098872 0.0 0.955 GB 1056 3600\n% 7744 [22, 22, 16] 205.599181 7.422947 1.524253 0.151227 2.725283 198.176234 0.0 1.001 GB 1636 7744\n% 18432 [24, 24, 32] 823.224210 51.681839 1.714082 0.165388 23.903565 771.542371 0.0 1.921 GB 0 18432\n% 26912 [29, 29, 32] 982.392875 143.146126 1.739032 0.161190 99.627309 839.246749 0.0 2.066 GB 2807 26912\n\n%-----\n\\subsection{Weak Scaling of the 1D Solver and MPI Rank Placement}\\label{sec:mpi_rank_placement}\n\n\n% performance/opendihu/08_0D1D_better_implementation\nNext, we compare the different approaches to solve the 1D electric conduction part of the monodomain equation on the fibers in a High Performance Computing setting.\n\\Cref{fig:hazel_hen_rank_placement} shows a similar weak scaling study to the one in the last section with slightly different process counts. The study was carried out on the supercomputer Hazel Hen, a Cray XC30 system, which was installed until 2020 as the predecessor to Hawk at the High Performance Computing Center Stuttgart. The same problem as in the last section is solved, and, again, the relation between fibers and processes is 10:1. The partitionings were chosen in accordance with the compute nodes of Hazel Hen, which had 24 cores. The detailed problem sizes and partitionings can be found in \\cite{Maier2019}.\n\n\\Cref{fig:hazel_hen_rank_placement} shows the runtimes of the same 0D and 1D solvers as in the last section by the solid yellow line for the 0D problem, the solid red line below for the 1D problem and the solid orange line for the communication. The perfect weak scaling for these parts is in line with the previous observations.\n\n\\begin{figure}\n \\centering%\n \\includegraphics[width=\\textwidth]{images/results/studies/Comparisonof0D-1Dcomputationschemes.pdf}%\n \\caption{Scaling study of the fiber based muscle model: Weak scaling behavior of solvers for the 1D problem. Runtimes for the 1D solver with different rank placement strategy (dotted and dashed red lines) and the optimized runtimes of the \\code{FastMonodomainSolver}, which combines the solution of the 0D and 1D problem (yellow and solid red lines, respectively).}% \n \\label{fig:hazel_hen_rank_placement}%\n\\end{figure}\n\nIn addition, we compare the weak scaling of the 1D solution, if a parallel conjugate gradient solver of PETSc is used for the problem on every fiber, instead of the serial Thomas algorithm. This setup corresponds to the \\code{vc-aovs} scenario presented in \\cref{sec:evaluation_of_code_gen}. As already noted earlier, the performance of this approach is worse. The dashed and dotted lines in \\cref{fig:hazel_hen_rank_placement} present the runtimes of this approach for two different MPI rank placement strategies, but for the identical program. It can be seen that the runtimes increase with higher numbers of processes in both curves. This effect is the result of the 1D fiber problems being distributed to more processes, as the total number of processes increases. \n\nFor example, in the scenarios with 1200 and 3468 processes, all fibers are distributed to 12 different processes. For the last three data points of the dashed curve, all fibers are distributed to 24 processes. As a result, the runtime to solve the 1D problems in the measurements with 1200 and 3468 processes is approximately equal, but lower than the runtime for the last three data points, where twice the amount of processors takes part in the solution of a single 1D problem.\n\nThe difference between the dotted and the dashed red curves is a different strategy to place the processes on the compute nodes. The dashed curve with the lower runtime corresponds to a placement of all fiber sharing processes on the same compute node. As the subdomain indices in the $n_x \\times n_y \\times n_z$ partitioning increase fastest in $x$-direction, then in $y$-direction and then in $z$-direction, and the fibers are aligned with the $z$ direction, the set of processes on a compute node contains MPI ranks that are offset with a constant stride of $n_x\\,n_y$. This has to be ensured in the job scripts on the supercomputers by explicit MPI rank pinning.\n\nIf no such measures are taken, the default placement of MPI ranks on the compute nodes proceeds consecutively by filling the compute nodes in the order of the MPI ranks. This corresponds to a round-robin placement of the fibers on the compute nodes, which is the worst possible way of distributing MPI ranks to compute nodes. All processes that compute a fiber are potentially located on different nodes and have to communicate over compute node boundaries.\n\\Cref{fig:hazel_hen_rank_placement} shows the resulting runtimes by the upper, dotted red curve. The difference in runtime increases to one order of magnitude for the highest number of cores.\n\nThus, it is important to properly handle MPI rank placement on compute clusters with multiple compute nodes. As a consequence, we also configured rank placement on the supercomputer Hawk accordingly in all our studies on this system.\n\n% ------------\n%\n% f===========\n\n\n\\section{Performance Studies of the Solid Mechanics Solver}\\label{sec:performance_solid_mechanics}\n\n%(BM TODO read)\n\nNext, we address the performance of the solid mechanics solver. \nIts runtime in OpenDiHu is given by the call to the nonlinear solver of PETSc. PETSc, in turn, calls two functions in OpenDiHu, which evaluate the nonlinear function to be solved and the Jacobian of the nonlinear function for a given vector of unknowns.\nIn the following, \\cref{sec:analytic_numeric_jacobian} compares an analytic and a numerical computation scheme for the Jacobian, and \\cref{sec:vectorization_analytic_jacobian} studies the impact of vectorization in this computation.\n\n\\subsection{Analytic and Numerical Computations of the Jacobian}\\label{sec:analytic_numeric_jacobian}\n\nThe computation of the Jacobian can be done in two ways. The first possibility is done by PETSc, which uses finite differences to numerically estimate the value of the Jacobian. The second possibility is to evaluate the respective analytic formulation within OpenDiHu. This analytic formulation is derived in \\cref{sec:discretization_mechanics} and uses the SEMT library \\cite{semt} to differentiate the mechanics model given by a strain energy function at compile time.\n\n\\begin{figure}\n \\centering%\n %\\includegraphics[width=0.4\\textwidth]{images/results/studies/mechanic_scenario.png}%\n \\def\\svgwidth{0.6\\textwidth}\n \\input{images/results/studies/mechanic_scenario.pdf_tex}%\n \\caption{Scaling study for solid mechanics: Visualization of the solid mechanics problem used in the weak scaling studies. The box is extended by a surface load at the right end. The wireframe shows the reference configuration, the colored mesh shows the current configuration where the color corresponds to the displacements $u_y$ in vertical direction.}%\n \\label{fig:mechanic_scenario}%\n\\end{figure}\n\nTo compare both approaches, we simulate a tension test, where a cuboid domain is extended by an applied force. \nThe box is shown in \\cref{fig:mechanic_scenario} and has physical dimensions $\\SI{2}{\\cm} \\times \\SI{2}{\\cm} \\times \\SI{5}{\\cm}$. The left face of the box is fixed at $z=0$ and the two edges of the left face at $x=0$ and $y=0$ are also fixed to prevent rotation of the body. On the right face, a constant surface load with a total force of $10$ is applied.\nThe material model is the incompressible transversely isotropic Mooney-Rivlin description given in \\cref{eq:transiso_mooney_rivlin}, which is also used for the muscle tissue. However, no active stress is considered. The material parameters are chosen as $c_1=2, c_2=3, b = 4$ and $d = 5$. The fiber direction lies in the $y-z$ plane and has an angle of $\\SI{40}{\\degree}$ to the $z$ axis.\nAs a result, the box slightly bends in negative $y$ direction, as can be seen in \\cref{fig:mechanic_scenario}. In this figure, the volume of the deformed object is colored according to the displacement in $y$ direction.\n\nWe solve the problem using the Newton solver of PETSc with a secant line search over the $L_2$ norm of the function. The absolute and relative residual tolerances are set to \\SI{1e-5}, which leads to approximately 5 Newton iterations. The parallel direct solver of the MUMPS package \\cite{Mumps2017} is used to solve the linear system in every Newton iteration.\n\nWe compare the runtimes of numerically and analytically computing the Jacobian in this problem. We vary the number of processes and the problem size in a weak scaling setting, such that there are exactly 8 3D elements per process. A dual-socket AMD EPYC 7742 64-core processor with clock speed of \\SI{2.25}{\\giga\\hertz}, a total core count of 128 and \\SI{1.96}{\\tera\\byte} RAM is used. We vary the number of processes between one and 256 processes. For more than 128 processes, hyperthreading is used.\n\n\\Cref{fig:numeric_analytic} shows the runtimes to solve the nonlinear system by the orange and purple lines in a double logarithmic plot. An increasing runtime for higher process counts is observed for both computation approaches. The curves have a higher slope for more than 128 processes, when the computation uses more processes than physical cores in the processor.\n\nThe computation of the Jacobian requires $\\O(n)$ non-zero entries to be calculated as the matrix has a banded sparsity structure, where $n$ is the number of degrees of freedom or elements in the 3D mesh. The number of non-zero Jacobian entries is, thus, constant in the weak scaling setup.\nHowever, \\cref{fig:numeric_analytic} shows a linearly increasing runtime for the numerical computation of the Jacobian, which can be seen by the comparison with the plotted linear function. \nThe finite difference scheme of PETSc has no information about the sparsity pattern and estimates all $\\O(n^2)$ matrix entries.\n\nThe runtimes for the analytic computation are only slightly increasing in the weak scaling, which is as expected. This approach only computes the non-zero entries of the Jacobian. Moreover, the values of the material elasticity tensor $\\C$ can be computed once and reused for every entry of the Jacobian.\n\nThe comparison between the approaches shows lower computation times for the analytic approach by factors between \\num{6.2} for one process and \\num{450} for 192 processes. \nIn conclusion, the analytic formula for the Jacobian, which is implemented in OpenDiHu, allows us to speed up the mechanics computations and to compute larger problem sizes in feasible runtimes.\n%[2, 3, 4, 5], # c1, c2, b1, d1\n\n%performance/opendihu/22_solid_mechanics_vectorization\n\\begin{figure}\n \\centering%\n \\includegraphics[width=0.7\\textwidth]{images/results/studies/numeric_analytic.pdf}%\n \\caption{Weak scaling of the nonlinear mechanics solver. The runtime to solve the nonlinear system equation is given for the numerical and for the analytic computation approaches for the Jacobian matrix.}%\n \\label{fig:numeric_analytic}%\n\\end{figure}\n %user duration_init write nonlin mem n\n%scenarioName nRanks \n%not_vectorized 1 1.790000 0 0.0 1.242300 0.096 GB 1\n %2 2.255000 0 0.0 1.685440 0.128 GB 2\n %3 2.190000 0 0.0 1.574477 0.129 GB 3\n %4 2.295000 0 0.0 1.660710 0.129 GB 4\n %6 2.830000 0 0.0 2.152498 0.133 GB 6\n %12 3.502500 0 0.0 2.658058 0.156 GB 12\n %16 4.000000 0 0.0 3.130890 0.162 GB 16\n %24 4.463750 0 0.0 3.586197 0.165 GB 24\n %36 5.309167 0 0.0 4.027296 0.160 GB 36\n %54 6.746852 0 0.0 5.433671 0.175 GB 54\n %96 12.793854 0 0.0 9.704076 0.255 GB 96\n %128 17.626562 0 0.0 13.354177 0.279 GB 128\n %144 22.389931 0 0.0 17.560908 0.295 GB 144\n %192 28.981458 0 0.0 22.698083 0.336 GB 192\n %256 38.794062 0 0.0 29.661437 0.403 GB 256\n%vectorized 1 1.200000 0 0.0 0.774613 0.100 GB 1\n %2 1.620000 0 0.0 1.197025 0.134 GB 2\n %3 1.536667 0 0.0 1.083777 0.134 GB 3\n %4 1.632500 0 0.0 1.175385 0.134 GB 4\n %6 2.130000 0 0.0 1.612840 0.139 GB 6\n %12 2.848333 0 0.0 2.151758 0.161 GB 12\n %16 3.383125 0 0.0 2.691964 0.167 GB 16\n %24 3.762083 0 0.0 3.028075 0.169 GB 24\n %36 4.418889 0 0.0 3.323164 0.165 GB 36\n %54 6.148889 0 0.0 5.048258 0.179 GB 54\n %96 12.345937 0 0.0 9.352379 0.260 GB 96\n %128 16.575547 0 0.0 12.661745 0.285 GB 128\n %144 20.970833 0 0.0 16.276117 0.299 GB 144\n %192 27.397344 0 0.0 21.641200 0.345 GB 192\n %256 38.021875 0 0.0 29.648075 0.414 GB 256\n\n\n\\subsection{Vectorization of the Analytic Jacobian Computations}\\label{sec:vectorization_analytic_jacobian}\n\nIn the assembly of finite element system matrices of any kind, contributions are computed on an element level and then combined to form a global system matrix. In OpenDiHu, this algorithm can be vectorized by performing analog but independent computations for multiple elements concurrently in multiple SIMD lanes. This vectorization uses the \\emph{Vc} library, similar to the optimizations of the subcellular model solver presented in \\cref{sec:performance_studies_of_the_e}. As this vectorization significantly increases compilation times, the feature is turned off by default and has to be enabled before compilation.\n\nIn this section, we evaluate the effect of vectorized system matrix computations for the Jacobian matrix of the nonlinear solid mechanics solver. We conduct a similar weak scaling study as before using the same scenario, but an eight times larger number of elements for each measurement. We compare the runtime to solve the nonlinear problem using analytic Jacobian computations with disabled and enabled vectorization.\n\n\\begin{figure}\n \\centering%\n \\includegraphics[width=0.8\\textwidth]{images/results/studies/vectorized.pdf}%\n \\caption{Scaling Study for the solid mechanics solver: Weak scaling study to evaluate vectorization in the computation of the Jacobian.}%\n \\label{fig:vectorized_jacobian}%\n\\end{figure}\n\n\\Cref{fig:vectorized_jacobian} presents the resulting runtimes for the entire nonlinear solver. \nThe vectorized computation shows speedups from \\num{1.6} for one process to \\num{1.06} for 128 processes. The theoretically possible speedup is four, as the processor supports the AVX2 instruction set with a vector register length of four double-precision values. The measured speedups are lower, because the computation of the Jacobian is only one portion of the computations in the nonlinear solver. \n%For some operations during the computation of the Jacobian, the individual values have to be unpacked from the vector registers, e.g., for the check if the jacobian\n\nIn summary, the vectorized computation of Jacobian matrices can reduce runtimes for the nonlinear solver. A runtime reduction of \\SI{38}{\\percent} (corresponding to the speedup of \\num{1.6}) was observed for the serial scenario. The performance gain is largest for small problem sizes and small numbers of processes, and gets less prominent for larger degrees of parallelism.\n %user duration_init write nonlin mem n\n%scenarioName nRanks \n%not_vectorized 1 1.830000 0 0.0 1.254970 0.095 GB 1\n %2 2.295000 0 0.0 1.690225 0.127 GB 2\n %3 2.170000 0 0.0 1.565473 0.130 GB 3\n %4 2.275000 0 0.0 1.664090 0.130 GB 4\n %6 2.838333 0 0.0 2.155187 0.134 GB 6\n %12 3.481667 0 0.0 2.625879 0.156 GB 12\n %16 3.996250 0 0.0 3.150559 0.162 GB 16\n %24 4.477917 0 0.0 3.582378 0.164 GB 24\n %36 6.520278 0 0.0 3.237879 0.140 GB 36\n %54 6.417222 0 0.0 3.185654 0.140 GB 54\n %96 11.051667 0 0.0 9.128967 0.210 GB 96\n %128 14.289687 0 0.0 11.515929 0.230 GB 128\n %144 18.201042 0 0.0 10.828896 0.215 GB 288\n %192 22.485521 0 0.0 13.421127 0.257 GB 192\n %256 27.934727 0 0.0 17.611625 0.336 GB 256\n%vectorized 1 1.210000 0 0.0 0.769704 0.101 GB 1\n %2 1.615000 0 0.0 1.192770 0.133 GB 2\n %3 1.533333 0 0.0 1.088080 0.134 GB 3\n %4 1.630000 0 0.0 1.172938 0.134 GB 4\n %6 2.153333 0 0.0 1.618572 0.139 GB 6\n %12 2.712500 0 0.0 2.095109 0.161 GB 12\n %16 3.403125 0 0.0 2.707476 0.168 GB 16\n %24 3.792500 0 0.0 3.024117 0.168 GB 24\n %36 5.683056 0 0.0 2.602400 0.145 GB 36\n %54 5.753148 0 0.0 2.663889 0.145 GB 54\n %96 10.421667 0 0.0 8.659787 0.215 GB 96\n %128 13.699063 0 0.0 11.105826 0.236 GB 128\n %144 16.196667 0 0.0 9.629186 0.220 GB 288\n %192 20.471302 0 0.0 12.320687 0.264 GB 192\n %256 26.646992 0 0.0 17.193776 0.345 GB 256\n\n\\begin{reproduce_no_break}\n The scripts to run the studies in this scenario and to create the plots of \\cref{fig:numeric_analytic,fig:vectorized_jacobian} are available in the repository at \\href{https://github.com/dihu-stuttgart/performance}{github.com/dihu-stuttgart/performance}\n in the directory \\code{opendihu/22_solid_mechanics_vectorization}.\n\\end{reproduce_no_break}\n% --------------------t\n%\n% ======================\n\n% numerical investigations\n\\section{Numerical Studies}\\label{sec:numerical_studies}\n\nNext, we perform numerical studies to evaluate mesh resolutions and linear solvers. \n\\Cref{sec:action_potential_velocity} addresses the mesh width of the 1D problem. \\Cref{sec:multidomain_solvers} evaluates different numerical solver choices for the multidomain model.\n\\subsection{Effect of the Mesh Width on the Action Potential Propagation Velocity}\\label{sec:action_potential_velocity}\n\nThe numerical parameters of a simulation scenario such as mesh widths and timestep widths should be chosen, such that the resulting numerical errors are balanced between all model components. In the simulation of activated muscle fibers, the propagation velocity of the action potentials is an important quantity, which also influences the macroscopic outcome of the EMG recordings. Thus, we investigate the effect of numerical parameters on the propagation velocity.\n\n%performance/opendihu/02_propagation_velocity\n\\begin{figure}%\n \\centering%\n \\begin{subfigure}[t]{0.45\\textwidth}%\n \\centering%\n \\includegraphics[width=\\textwidth]{images/results/studies/propagation_velocity.pdf}%\n \\caption{Propagation velocities over spatial resolution of the 1D mesh.}%\n \\label{fig:propagation_velocity_comparison}%\n \\end{subfigure}\n \\,\n \\begin{subfigure}[t]{0.45\\textwidth}%\n \\centering%\n \\includegraphics[width=\\textwidth]{images/results/studies/propagation_velocity_rel_error.pdf}%\n \\caption{Relative error of the propagation velocities over spatial resolution of the 1D mesh.}%\n \\label{fig:propagation_velocity_rel_error}%\n \\end{subfigure} \n \\caption{Influence of the mesh width on the propagation velocity of the action potential for the subcellular models of Shorten and Hodgkin-Huxley in the fiber-based electrophysiology simulation. This study is used to determine the 1D mesh width.}%\n \\label{fig:propagation_velocity}%\n\\end{figure}%\n\nIn the first study, we consider a single fiber given by a 1D mesh, where the monodomain equation \\cref{eq:monodomain} is used.\nWe measure the error of the propagation velocity depending on the mesh width. A fiber with a physical length of \\SI{4}{\\cm} is used and discretized by different numbers of 1D elements. We stimulate the fiber at its center at the beginning of the simulation and run the simulation until an end time of \\SI{28}{\\ms}. An action potential propagates along the fiber. We determine the location of the propagating peak at the end and compute the propagation velocity.\n\n\\Cref{fig:propagation_velocity_comparison} shows the resulting values of the propagation velocity for the Hodgkin-Huxley and Shorten subcellular models for varying mesh resolutions. It can be seen that the velocities level out at a constant value for finer mesh discretizations. The absolute value of the propagation velocity is different for the two subcellular models and depends on various model parameters.\n\nFor a quantitative evaluation, we examine the error of the propagation velocity, which is estimated by comparing each run with the value from the finest simulation. \nOne issue with comparing propagation velocities on discretized meshes is that the measured velocity can only be calculated as number of elements traversed per time interval. Thus, the measurements for different mesh resolutions have different accuracies, not only due to the usual discretization error in the finite element approach. This issue can be reduced if a long enough time is simulated, such that the action potential propagates a large enough distance in terms of multiples of the element width.\n\n\\Cref{fig:propagation_velocity_rel_error} shows the resulting relative error of the propagation velocity. It can be seen that, for the Hodgkin Huxley model, the error gets close to zero for 100 elements per centimeter of fiber length. For the Shorten model, this mesh resolution also exhibits a low relative error. However, the error increases again for higher mesh resolutions before decreasing again starting at approximately 750 elements per centimeter. \n\nAs a result, we use a 1D mesh resolution of 100 elements per centimeter for all muscle fibers in all our simulations. For a biceps muscle of \\SI{14.8}{\\cm} length, this leads to muscle fiber discretizations with 1480 elements and 1481 nodes.\n\n%performance/opendihu/03_dx_dt_dependence\n%\\begin{figure}\n% \\centering%\n% \\includegraphics[width=0.8\\textwidth]{images/results/studies/hh_cn_error_propagation_velocity_3d.pdf}%\n% \\caption{Error of the action potential propagation velocity for varying mesh width and timestep width.}% \n% \\label{fig:hh_cn_error_propagation_velocity_3d}%\n%\\end{figure}\n%Remove \\cref{fig:hh_cn_error_propagation_velocity_3d} as not so clear.\n\n\\begin{reproduce_no_break}\n The scripts for this study are available in the repository at \\href{https://github.com/dihu-stuttgart/performance}{github.com/dihu-stuttgart/} \\href{https://github.com/dihu-stuttgart/performance}{performance} in the directory \\code{opendihu/02_propagation_velocity}:\n \\begin{lstlisting}[columns=fullflexible,breaklines=true,postbreak=\\mbox{\\textcolor{gray}{$\\hookrightarrow$}\\space}]\n ./run.sh\n ./plot_propagation_velocity.py\n \\end{lstlisting}\n\\end{reproduce_no_break}\n\n%-----\n\\subsection{Linear Solvers for the Multidomain Problem}\\label{sec:multidomain_solvers}\n\n% in opendihu 2021 paper\n% selected multidomain solvers\n\\begin{figure}[H]\n \\centering%\n \\includegraphics[width=\\textwidth]{images/results/studies/multidomain_solvers_selected.pdf}%\n \\caption{Evaluation of preconditioners for the multidomain model. The system is solved with a GMRES solver and different preconditioners. The upper plots shows the remaining number of iterations in the GMRES solver, the lower plot measures the total runtime of preconditioning and solution. Three different preconditioners given by orange, green and red lines are compared to the blue reference curve of using no preconditioner.}%\n \\label{fig:multidomain_solver}%\n\\end{figure}\n\nIn the next study, we investigate the parallel weak scaling behavior for the multidomain model\nwith a particular focus on the total runtimes for different choices of the preconditioner that is used in the solution of the linear system of equations. Our goal is to select the fastest solver-preconditioner combination to speed up the computation of the multidomain model.\n\nIn contrast to classical weak scaling, we increase the number of MUs with the number of processes, i.e., the size of the blocks in the resulting block structured matrix remains constant, whereas the number of blocks increases.\n\nWe simulate the multidomain model with a fat domain as given in \\cref{sec:discretization_body_domain} and with the subcellular model of Shorten et al. \\cite{Shorten2007}. \nThe model is discretized by a Strang operator splitting with Heun's method for the subcellular model and an implicit Euler scheme for the multidomain equations. The timestep widths of all schemes are $\\dt_\\text{0D}=\\dt_\\text{multidomain}=\\dt_\\text{splitting}=\\SI{5e-4}{\\milli\\second}$, and an end time of \\SI{1e-1}{\\milli\\second} is used, corresponding to 200 invocations of the linear solver.\n\nWe partition the 3D computational domain, consisting of the muscle mesh with \\num{50024} nodes and the fat layer mesh with \\num{37000} nodes, to 24, 36, 48, 60 and 72 subdomains. In a weak scaling setup, we correspondingly simulate 4,6,8,10 and 12 MUs.\nAs the square-shaped system matrix contains one row of blocks for every MU plus one row of blocks for the fat mesh, the total number of rows does not scale exactly linearly with the number of MUs. In consequence, the system matrices in the five scenarios contain \\num{279720}, \\num{379768}, \\num{479816}, \\num{579864} and \\num{679912} rows and columns. Thus, the problem size per process is only approximately constant in this weak scaling study.\n\n% n dofs\n% 24: 279720\n% 36: 379768\n% 48: 479816\n% 60: 579864 \n% 72: 679912\n\nWe solve the linear system of the multidomain equations by a GMRES solver, because the system matrix is non-symmetric.\nThe stopping threshold on the residual norm is set to \\num{1e-15} and the specified maximum number of iterations is \\num{1e4}. \nDifferent preconditioners are applied and the resulting number of GMRES iterations and the total runtime for preconditioner and solver are measured.\n\\Cref{fig:multidomain_solver} shows the number of GMRES iterations in the upper plot and the total runtimes in the lower plot.\n\nFor every preconditioner, the preconditioning is either performed based on the non-symmetric system matrix (solid lines) or based on a symmetric matrix that is obtained by taking all diagonal blocks of the system matrix (dashed lines), as described in \\cref{sec:multidomain_diagonal_matrix}.\n\nThe reference measurement is given by the GMRES solver without any preconditioner, visualized by the blue lines in both plots.\nThe upper plot of \\cref{fig:multidomain_solver} indicates the maximum number of \\num{1e4} iterations for all measurements of the GMRES solver without preconditioner. This means that the specified tolerance of \\num{1e-15} is not reached in the given number of iterations. Thus, a preconditioner is required to obtain an accurate solution.\n\nThe first examined preconditioner is the block Jacobi scheme.\nA block Jacobi preconditioner divides the system matrix into blocks on the diagonal, yielding smaller problems that can each be solved individually.\nThe scheme is an iterative solver, which starts with an initial solution $\\bfx^{(0)}$ and successively computes approximations $\\bfx^{(i+1)} = \\Phi(\\bfx^{(i)})$ of the solution until the residual norm reaches the specified threshold.\n%The system matrix is approximated by its diagonal.\n\nFor a model problem $A\\,\\bfx = \\bfb$, where the system matrix $A=D+L+U$ is decomposed into a matrix $D$ with blocks on the diagonal and lower and upper triangular block matrices $L$ and $U$, respectively, the preconditioning is based on the following iterative computation scheme $\\Phi: \\bfx^{(i)} \\mapsto \\bfx^{(i+1)}$:\n\\begin{align}\\label{eq:jacobi_iteration}\n D\\,\\bfx^{(i+1)} = \\bfb - (L+U)\\bfx^{(i)}.\n\\end{align}\nBecause of the structure of the block diagonal matrix $D$, the system is decoupled and every process can solve its own linear system of equations using the respective diagonal block as system matrix. If the symmetric option for the system matrix used in the preconditioner is chosen, the matrices $L$ and $U$ vanish and the solution of \\cref{eq:jacobi_iteration} is trivial.\n\nThe preconditioner is constructed using the reordered matrix layout described in \\cref{sec:structure_multidomain_system_matrix} and the symmetric matrix is obtained as discussed in \\cref{sec:multidomain_diagonal_matrix}. The remaining blocks on the matrix diagonal belong to the subdomains of the parallel partitioning. Each block corresponds to a part of the mesh for all MU compartments.\n\nTwo versions of block Jacobi preconditioners provided by the PETSc library are evaluated.\nThe first variant, shown by the orange lines in \\cref{fig:multidomain_solver}, employs a GMRES solver for the resulting smaller linear systems of equations in \\cref{eq:jacobi_iteration}.\nThe second variant, shown by the green lines in \\cref{fig:multidomain_solver}, uses a SOR (successive over-relaxation) solver with over-relaxation parameter \n$\\omega=1$, i.e., a Gauß-Seidel scheme.\n\nThe upper plot in \\cref{fig:multidomain_solver} shows that the number of GMRES solver iterations is reduced more for the GMRES solver than for the Gauß-Seidel solver, as the constant number of GMRES iterations in the preconditioner yields a better approximation to the solution than the same number of Gauß-Seidel iterations. The lower plot shows a smaller total runtime for the block Jacobi scheme with Gauß-Seidel solver than for the block Jacobi scheme with GMRES solver. This means that the lower runtime of the Gauß-Seidel solver in the preconditioner outweighs the larger number of GMRES iterations in the solver, compared to the GMRES preconditioning scheme. For both preconditioners, the total runtime for the variant with the symmetric matrix is lower than for the variant with the full system matrix.\n\nAnother solver is \\emph{Euclid} \\cite{euclid} from the HYPRE package, shown by the red lines in \\cref{fig:multidomain_solver}. It is a parallel implementation of incomplete LU factorization using graph partitioning and a two-level ordering strategy.\n\nThe plots in \\cref{fig:multidomain_solver} show a low number of remaining GMRES iterations after the preconditioner has been applied, similar to the block Jacobi scheme with GMRES solver. However, the total runtime of Euclid is significantly lower than the runtime of the GMRES-block Jacobi scheme. If the symmetric system matrix is used for preconditioning, the total runtime is the lowest of all measured preconditioner combinations.\n\nRegarding the parallel weak scaling, the lower plot in \\cref{fig:multidomain_solver} shows overall good scaling properties for all considered preconditioners. The runtimes slightly decrease from the first to the second data points, as the system matrix size per process also slightly decreases. Then, a trend of slightly increasing runtimes in the weak scaling setup can be seen, which indicates that the preconditioners and the GMRES solver perform slightly more computations and communication for larger problem sizes. The accuracy of the preconditioning step is not affected by the overall problem size, as can be seen by the constant numbers of GMRES iterations in the upper plot of \\cref{fig:multidomain_solver}.\n\nAs a result, we use the combination of Euclid preconditioner and GMRES solver in all solutions of the multidomain model in this work, because this is the fastest of the tested combinations. Apart from the three presented preconditioners, more available choices in the software packages PETSc and HYPRE were tested, but yielded worse performance. These include the \\emph{Parallel Incomplete Factorization preconditioner} (PILUT) from the HYPRE package and the combinations of the block Jacobi scheme with an algebraic multigrid method or the Euclid preconditioner for the subproblems. Tests with the parallel algebraic multigrid method \\emph{BoomerAMG} from the HYPRE package also showed promising results with even lower total runtimes than the Euclid preconditioner, but suffered from occasional long runtimes and divergence in a non-deterministic fashion. However, the full set of possible parameters such as different coarsening and interpolation options and settings for the smoother have not yet been evaluated and, after fine-tuning, corresponding performance improvements could be possible in future work.\n\n\\begin{reproduce_no_break}\n The script for this study is available in the repository at \\href{https://github.com/dihu-stuttgart/performance}{github.com/dihu-stuttgart/} \\href{https://github.com/dihu-stuttgart/performance}{performance} in the directory \\code{opendihu/07_multidomain_solver}:\n \\begin{lstlisting}[columns=fullflexible,breaklines=true,postbreak=\\mbox{\\textcolor{gray}{$\\hookrightarrow$}\\space}]\n ./run_mu.sh\n \\end{lstlisting}\n\\end{reproduce_no_break}\n\n% scenarioName nRanks \n% gmres_bjacobi_dt0.0005_atol1e-15_rtol1e-15_theta1.0_symFalse_lumpFalse_10mus 60 [6, 1, 10] 4444.074833 4472.546500 13.081118 4458.698333 -28.471667 0.0 226.0 0.997 GB 60\n% gmres_bjacobi_dt0.0005_atol1e-15_rtol1e-15_theta1.0_symFalse_lumpFalse_12mus 72 [6, 1, 12] 4953.106806 4992.944583 14.215069 4977.854306 -39.837778 0.0 263.0 1.026 GB 72\n% gmres_bjacobi_dt0.0005_atol1e-15_rtol1e-15_theta1.0_symFalse_lumpFalse_4mus 24 [4, 1, 6] 5050.243750 5081.276667 11.882062 5068.834583 -31.032917 0.0 255.0 1.389 GB 24\n% gmres_bjacobi_dt0.0005_atol1e-15_rtol1e-15_theta1.0_symFalse_lumpFalse_6mus 36 [4, 1, 9] 3234.057500 3248.998333 12.351108 3235.983889 -14.940833 0.0 161.0 0.841 GB 36\n% gmres_bjacobi_dt0.0005_atol1e-15_rtol1e-15_theta1.0_symFalse_lumpFalse_8mus 48 [6, 1, 8] 4328.314167 4374.314375 12.322344 4361.300417 -46.000208 0.0 270.0 1.087 GB 48\n% gmres_bjacobi_dt0.0005_atol1e-15_rtol1e-15_theta1.0_symTrue_lumpFalse_10mus 60 [6, 1, 10] 2088.741667 2122.034500 13.006847 2108.233667 -33.292833 0.0 305.0 1.074 GB 60\n% gmres_bjacobi_dt0.0005_atol1e-15_rtol1e-15_theta1.0_symTrue_lumpFalse_12mus 72 [6, 1, 12] 2549.413056 2589.060139 14.305833 2573.819167 -39.647083 0.0 318.0 1.120 GB 72\n% gmres_bjacobi_dt0.0005_atol1e-15_rtol1e-15_theta1.0_symTrue_lumpFalse_4mus 24 [4, 1, 6] 2478.502500 2493.367083 11.744517 2481.051667 -14.864583 0.0 300.0 1.542 GB 24\n% gmres_bjacobi_dt0.0005_atol1e-15_rtol1e-15_theta1.0_symTrue_lumpFalse_6mus 36 [4, 1, 9] 1299.019722 1301.245000 12.244350 1288.295833 -2.225278 0.0 152.0 0.827 GB 36\n% gmres_bjacobi_dt0.0005_atol1e-15_rtol1e-15_theta1.0_symTrue_lumpFalse_8mus 48 [6, 1, 8] 1801.928542 1830.392917 12.377065 1817.272500 -28.464375 0.0 293.0 1.069 GB 48\n% gmres_euclid_dt0.0005_atol1e-15_rtol1e-15_theta1.0_symFalse_lumpFalse_10mus 60 [6, 1, 10] 2489.941833 2471.670167 13.204272 2457.642167 18.271667 0.0 179.0 0.510 GB 60\n% gmres_euclid_dt0.0005_atol1e-15_rtol1e-15_theta1.0_symFalse_lumpFalse_12mus 72 [6, 1, 12] 2914.482639 2895.433472 14.660654 2879.770000 19.049167 0.0 189.0 0.551 GB 72\n% gmres_euclid_dt0.0005_atol1e-15_rtol1e-15_theta1.0_symFalse_lumpFalse_4mus 24 [4, 1, 6] 1974.359167 1954.868333 11.758821 1942.513750 19.490833 0.0 212.0 0.473 GB 24\n% gmres_euclid_dt0.0005_atol1e-15_rtol1e-15_theta1.0_symFalse_lumpFalse_6mus 36 [4, 1, 9] 2366.323333 2349.646111 12.330914 2336.598333 16.677222 0.0 217.0 0.437 GB 36\n% gmres_euclid_dt0.0005_atol1e-15_rtol1e-15_theta1.0_symFalse_lumpFalse_8mus 48 [6, 1, 8] 1963.516458 1945.901875 12.508950 1932.620625 17.614583 0.0 169.0 0.471 GB 48\n% gmres_euclid_dt0.0005_atol1e-15_rtol1e-15_theta1.0_symTrue_lumpFalse_10mus 60 [6, 1, 10] 506.561333 486.702183 13.177800 472.658200 19.859150 0.0 187.0 0.470 GB 60\n% gmres_euclid_dt0.0005_atol1e-15_rtol1e-15_theta1.0_symTrue_lumpFalse_12mus 72 [6, 1, 12] 577.824583 558.374014 14.584994 542.841681 19.450569 0.0 185.0 0.518 GB 72\n% gmres_euclid_dt0.0005_atol1e-15_rtol1e-15_theta1.0_symTrue_lumpFalse_4mus 24 [4, 1, 6] 509.154167 487.713333 11.844267 475.261125 21.440833 0.0 201.0 0.448 GB 24\n% gmres_euclid_dt0.0005_atol1e-15_rtol1e-15_theta1.0_symTrue_lumpFalse_6mus 36 [4, 1, 9] 480.553056 462.281917 12.279769 449.267556 18.271139 0.0 214.0 0.409 GB 36\n% gmres_euclid_dt0.0005_atol1e-15_rtol1e-15_theta1.0_symTrue_lumpFalse_8mus 48 [6, 1, 8] 469.558750 450.701521 12.482108 437.435708 18.857229 0.0 186.0 0.433 GB 48\n% gmres_none_dt0.0005_atol1e-15_rtol1e-15_theta1.0_symFalse_lumpFalse_10mus 60 [6, 1, 10] 8697.286500 8841.893667 14.195788 8826.917167 -144.607167 0.0 10000.0 2.184 GB 60\n% gmres_none_dt0.0005_atol1e-15_rtol1e-15_theta1.0_symFalse_lumpFalse_12mus 72 [6, 1, 12] 10342.686111 10501.216667 15.572006 10484.729167 -158.530556 0.0 10000.0 2.536 GB 72\n% gmres_none_dt0.0005_atol1e-15_rtol1e-15_theta1.0_symFalse_lumpFalse_4mus 24 [4, 1, 6] 9229.770417 9675.692083 14.665854 9660.403333 -445.921667 0.0 10000.0 2.006 GB 24\n% gmres_none_dt0.0005_atol1e-15_rtol1e-15_theta1.0_symFalse_lumpFalse_6mus 36 [4, 1, 9] 7886.560833 7975.463611 13.603492 7961.178056 -88.902778 0.0 10000.0 1.982 GB 36\n% gmres_none_dt0.0005_atol1e-15_rtol1e-15_theta1.0_symFalse_lumpFalse_8mus 48 [6, 1, 8] 7728.828542 7876.260625 13.214875 7862.334583 -147.432083 0.0 10000.0 2.145 GB 48\n% gmres_sor_dt0.0005_atol1e-15_rtol1e-15_theta1.0_symFalse_lumpFalse_10mus 60 [6, 1, 10] 1064.128667 1056.613667 13.017858 1042.770333 7.515000 0.0 805.0 0.514 GB 60\n% gmres_sor_dt0.0005_atol1e-15_rtol1e-15_theta1.0_symFalse_lumpFalse_12mus 72 [6, 1, 12] 1282.427083 1274.231389 14.543176 1258.699861 8.195694 0.0 959.0 0.572 GB 72\n% gmres_sor_dt0.0005_atol1e-15_rtol1e-15_theta1.0_symFalse_lumpFalse_4mus 24 [4, 1, 6] 1314.639167 1366.876250 15.078050 1351.132917 -52.237083 0.0 705.0 0.470 GB 24\n% gmres_sor_dt0.0005_atol1e-15_rtol1e-15_theta1.0_symFalse_lumpFalse_6mus 36 [4, 1, 9] 703.937778 691.388333 12.411444 678.247556 12.549444 0.0 793.0 0.433 GB 36\n% gmres_sor_dt0.0005_atol1e-15_rtol1e-15_theta1.0_symFalse_lumpFalse_8mus 48 [6, 1, 8] 972.381875 963.809000 12.346906 950.696875 8.572875 0.0 849.0 0.511 GB 48\n% gmres_sor_dt0.0005_atol1e-15_rtol1e-15_theta1.0_symTrue_lumpFalse_10mus 60 [6, 1, 10] 869.906333 862.904083 13.149073 848.941350 7.002250 0.0 1042.0 0.553 GB 60\n% gmres_sor_dt0.0005_atol1e-15_rtol1e-15_theta1.0_symTrue_lumpFalse_12mus 72 [6, 1, 12] 1606.299028 1628.942917 17.998925 1609.921528 -22.643889 0.0 1070.0 0.575 GB 72\n% gmres_sor_dt0.0005_atol1e-15_rtol1e-15_theta1.0_symTrue_lumpFalse_4mus 24 [4, 1, 6] 917.225833 896.343042 14.958108 880.731083 20.882792 0.0 893.0 0.495 GB 24\n% gmres_sor_dt0.0005_atol1e-15_rtol1e-15_theta1.0_symTrue_lumpFalse_6mus 36 [4, 1, 9] 552.407222 540.981389 12.264922 527.989472 11.425833 0.0 794.0 0.452 GB 36\n% gmres_sor_dt0.0005_atol1e-15_rtol1e-15_theta1.0_symTrue_lumpFalse_8mus 48 [6, 1, 8] 739.617708 732.262771 12.567985 718.927312 7.354937 0.0 1055.0 0.526 GB 48\n\n\n% ==============\n%\n% --------------\n%-----\n%\\section{Parallel in Time master thesis}\n%maybe\n%-----\n%-----\n%\\section{Output file sizes}\n%no\n%-----\n%\\section{Mesh convergence, stochastic with different MU assignments}\n%-----\n%\\section{dx-dt dependencies} \n%no\n%-----\n%\\section{Load balancing bachelor thesis}\n%no\n%-----\n%\\section{Application of opendihu within the field of robotics} \n%no\n\n% ------------\n%\n% f===========\n\n", "meta": {"hexsha": "859a8528e2e95cb7ff0a9e95a09bbd7442c8a6df", "size": 51513, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "document/08_results_2c.tex", "max_stars_repo_name": "maierbn/phd_thesis_source", "max_stars_repo_head_hexsha": "babee64f01f15d93cb75140eb8c8424883b33c6c", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-05T19:00:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-05T19:00:04.000Z", "max_issues_repo_path": "document/08_results_2c.tex", "max_issues_repo_name": "maierbn/phd_thesis_source", "max_issues_repo_head_hexsha": "babee64f01f15d93cb75140eb8c8424883b33c6c", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "document/08_results_2c.tex", "max_forks_repo_name": "maierbn/phd_thesis_source", "max_forks_repo_head_hexsha": "babee64f01f15d93cb75140eb8c8424883b33c6c", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 109.6021276596, "max_line_length": 1112, "alphanum_fraction": 0.7185564809, "num_tokens": 15221, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.30074556640652333, "lm_q1q2_score": 0.16092848000055088}} {"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{PHYS431}\n\\Submitted{12.03.82} \\Revised{16.12.93}\n\\Makehead{Ionisation processes for heavy ions}\n\n\\section{Subroutines}\n\nFor a description of the subroutines used to calculate the energy\nloss tables for protons, see {\\tt [PHYS430]}.\n\n\\Shubr{GTHION}{}\n\n\\Rind{GTHION} transports heavy ions ($A,Z > 1$, particle\ntype 8). For the moment the\nonly discrete processes activated are $\\delta$-ray and \\v{C}erenkov\nphoton generation.\n\n\\section{Method}\n\nThe mean energy loss of the heavy ions can be expressed as:\n\\begin{equation}\n\\Delta E = Q^{2} S_{p} \\left ( \\frac{T}{A} \\right ) \\rho t\n\\end{equation}\nwhere\n\\begin{DLtt}{MMMMMMMMM}\n\\item[$Q$] charge of the ion;\n\\item[$\\displaystyle S_{p} \\left ( \\frac{T}{A} \\right )$]\nenergy loss by the a proton with kinetic energy $T_{p} = T/A$;\n\\item[$T,A$] kinetic energy and mass number of the ion;\n\\item[$\\rho$] density of the medium;\n\\item[$t$] step length\n\\end{DLtt}\n\nThis formula is used to calculate the ionisation loss for all the charged\nhadrons.\n\n\nIn the case of ions, the charge of the ion makes the problem more difficult.\nElectron-exchange processes with the atoms change the\ncharge as the ion traverses the medium. The main features of this \nprocess can be summarised as follows:\n\\begin{itemize}\n\\item $Q$ loses the dependence on the initial ion charge after a\nvery short initial step, usually $\\ll 1\\mu$ for condensed media;\n\\item $Q$ does depend on the velocity of the ion;\n\\item even in the case of constant velocity, $Q$ fluctuates around\na mean value;\n\\item $Q$ features a small dependence on the medium, especially for\nsmall values of $T$.\n\\end{itemize}\n\\begin{table}\n\\begin{centering}\n\\begin{tabular}{|c|c|c|}\n\\hline\nT/A & He ions & Pb ions \\\\\nMeV & error (\\%) & error (\\%) \\\\\n\\hline\n10 & 3 & 1 \\\\\n5 & 4 & 3 \\\\\n3 & 10 & 4 \\\\\n\\hline\n\\end{tabular}\n\\caption{Comparison of the measured and calculated $\\Delta$E for 10 MeV/A\nions in Pb}\n\\end{centering}\n\\label{tb:phys431-1}\n\\end{table}\n\nIf we want to calculate the energy loss of the ion, we need a good\nparametrisation for the quantity $Q=Q_{eff}$. We give here a \nrelatively simple parametrisation~\\cite{bib-ANZI,bib-ANZ1}:\n\\begin{eqnarray}\n\\label{eq:phys431-2}\nQ_{eff} & = & Z_{I} \\left [ 1- \\left ( 1.034 - 0.1777 e^{-0.08114\\;Z_{I}}\n\\right ) e^{-v} \\right ] \\\\\nv & = & 121.4139 \\frac{\\beta}{Z_{I}^{2/3}} + 0.0378\n\\sin \\left ( 190.7165 \\frac{\\beta}{Z_{I}^{2/3}} \\right ) \\nonumber\n\\end{eqnarray}\nwhere $\\beta$ is the velocity and $Z_{I}$ the atomic number of the ion\n(i.e. the charge of the bare nucleus).\n\n\\begin{table}\n\\begin{centering}\n\\begin{tabular}{|r|rr|rr|r|r|rr|rr|r|r|}\n\\hline\n\\multicolumn{1}{|c|}{T (MeV)} & \\multicolumn{6}{c|}{417 $\\mu$g cm$^{-2}$}\n& \\multicolumn{6}{c|}{110 $\\mu$g cm$^{-2}$} \\\\[0.1cm]\n& \\multicolumn{4}{c|}{MC (keV)} & \\multicolumn{2}{c|}{data (keV)} &\n\\multicolumn{4}{c|}{MC (keV)} & \\multicolumn{2}{c|}{data (keV)} \\\\\n& $\\Delta$E & dif & FWHM & dif & $\\Delta$E & FWHM & \n$\\Delta$E & dif & FWHM & dif & $\\Delta$E & FWHM \\\\\n\\hline\n4.88 & & & & & & & 785 & 8 & 59 & -23 & 725 & 77 \\\\\n9.85 & 3600 & 14 & 138 & -33 & 3150 & 206 & 816 & 8 & 67 & -26 & 756 & 91 \\\\\n19.79 & 3090 & 3 & 142 & -35 & 2990 & 218 & 719 & 3 & 70 & -32 & 699 & 103 \\\\\n29.27 & 2660 & 1 & 141 & -31 & 2630 & 204 & & & & & & \\\\\n29.75 & & & & & & & 620 & 4 & 69 & -26 & 598 & 93 \\\\\n39.70 & 2320 & 1 & 138 & -28 & 2300 & 191 & 550 & 4 & 68 & -24 & 528 & 90 \\\\\n\\hline\n\\end{tabular}\n\\caption{Comparison of the measured and calculated $\\Delta$E and FWHM\nfor O ions in Al; errors are in percent.}\n\\end{centering}\n\\label{tb:phys431-2}\n\\end{table}\n\nIt can be seen that (\\ref{eq:phys431-2}) neglects the (small) medium\ndependence of $Q_{eff}$. For very high energies ($\\beta \\rightarrow 1$)\n$Q_{eff} \\rightarrow Z_{I}$. For very low energies ($T/A \\sim$ few keV)\nthe formula breaks down. $Q_{eff}$ can even become negative for $T/A <\n20$ keV and $Z_{I} > 20$. However this is not a serious source of\nerror when calculating $\\Delta E$, since in this case the range of\nthe ion is very small, and it can almost be said that it stops\n{\\it immediately}.\n\nThe calculation of the energy loss straggling (fluctuations) differs\nfrom that of {\\it normal} charged hadrons. For the charged hadrons\nthe fluctuations come from the statistical nature of the \nprojectile-atom interactions; for the ions there is another process which\nbroadens the energy loss distribution: the fluctuation of the charge.\nFor heavier ions this process dominates the energy loss straggling\nfor $T/A \\leq 10$ MeV.\n\n\\begin{figure}[hbt]\n \\centering\n \\epsfig{file=eps/phys431-1.eps,width=14cm}\n \\caption{Stopping powers in Carbon}\n \\label{fg:phys431-1}\n\\end{figure}\n\nThe heavy ions are in the {\\it Gaussian regime} (see {\\tt [PHYS332]})\nof the collisional fluctuations even in the case of very thin absorbers.\nIf $T/A$ is not too high, the $\\sigma^{2}$ of the distribution:\n\\begin{equation}\n\\label{eq:phys431-3}\n\\sigma^{2}_{coll} = D \\frac{Q_{eff}^{2} Z}{A} \\rho \\; t \\; m\n\\left [ 1 + \\frac{T_{A}}{M_{u}} + \\frac{1}{2} \\left ( \\frac{T_{A}}{M_{u}}\n\\right ) ^{2} \\right ]\n\\end{equation}\nwhere\n\\begin{DLtt}{MMMMMMMM}\n\\item[$D$] $\\displaystyle 0.307 \\frac{\\mbox{MeV cm$^{2}$}}{\\mbox{g}}$;\n\\item[$T_{A}$] $\\displaystyle \\frac{T}{A}$;\n\\item[$M_{u}$] atomic mass unit;\n\\item[$Z$] atomic number of the medium;\n\\item[$A$] mass number of the medium.\n\\end{DLtt}\n\n\\begin{table}\n\\begin{centering}\n\\begin{tabular}{|r|rr|r|rr|r|rr|r|}\n\\hline\n& \\multicolumn{9}{c|}{Pb ions in gas (energies in MeV)} \\\\\n& \\multicolumn{3}{c|}{N$_{2}$} & \n\\multicolumn{3}{c|}{Ar} & \n\\multicolumn{3}{c|}{Xe} \\\\\n& \\multicolumn{2}{c}{MonteCarlo} & \\multicolumn{1}{c|}{data} &\n\\multicolumn{2}{c}{MonteCarlo} & \\multicolumn{1}{c|}{data} &\n\\multicolumn{2}{c}{MonteCarlo} & \\multicolumn{1}{c|}{data} \\\\\nt (cm) & \n$\\Delta$E & FWHM & FWHM & $\\Delta$E & FWHM & FWHM & $\\Delta$E & FWHM & FWHM \\\\\n\\hline\n0.2 & 25.9 & 1.15 & 1.1 & 25.4 & 1.30 & 1.4 & 51.1 & 2.26 & 2.5 \\\\\n0.4 & 53.6 & 1.62 & 1.5 & 52.4 & 1.84 & 1.9 & 107.0 & 3.22 & 3.3 \\\\\n0.8 & 112.0 & 2.25 & 2.0 & 111.0 & 2.59 & 2.6 & 236.0 & 4.51 & \\\\\n1.2 & 162.0 & 2.37 & 2.0 & 168.0 & 2.95 & 2.8 & & & \\\\\n\\hline\n\\end{tabular}\n\\caption{Comparison of the measured and calculated and FWHM\nfor 1.4 MeV/A Pb ions in gas.}\n\\end{centering}\n\\label{tb:phys431-3}\n\\end{table}\n\nAnalysing the experimental straggling data it is possible to find that\nthe electron-exchange charge fluctuations can be described by a Gaussian\nwith width:\n\\begin{equation}\n\\label{eq:phys431-4}\n\\sigma^{2}_{ch} = D \\frac{Q_{eff}^{2} Z}{A} \\rho \\; t \\; m \\frac{C}{2}\n\\left ( 1 - \\frac{Q_{eff}}{Z_{I}} \\right )\n\\end{equation}\nwhere the parameter $C \\sim 2.5$ has been derived\nfrom the experimental straggling data.\n\nIf $Q_{eff} \\rightarrow Z_{I}$, which is the case for high energy\nheavy ions and for few MeV/A He ions, then $\\sigma^{2}_{ch} \\rightarrow 0$.\n\n\nComparing equations (\\ref{eq:phys431-3}) and (\\ref{eq:phys431-4}) it can be \nseen that for heavy ions and for $T/A \\ll M_{u}$ $\\sigma^{2}_{ch}\n> \\sigma^{2}_{coll}$. The total energy loss fluctuation can be\ndescribed by a Gaussian distribution with:\n\\begin{equation}\n\\sigma^{2} = \\sigma^{2}_{ch} + \\sigma^{2}_{coll}\n\\end{equation}\n\nThe mean energy loss and energy loss fluctuation calculation is performed\nin the routine \\Rind{GTHION}, making use of the proton energy loss tables.\n\n{\\bf Note:} The Gaussian fluctuation gives too broad a distribution for\nhigh energy in the case of thin absorbers. A correction has been introduced\nin \\Rind{GTHION} which cures this discrepancy. In the absence of high\nenergy straggling data for ions, the correction has been tuned using \nhigh energy $\\pi$ energy loss data, where the $\\pi$ has been tracked\nby \\Rind{GTHION}.\n\n\\section{Comparison with data}\n\n\\subsection{Mean energy loss and range}\n\nA test has been made against the distributions reported in~\\cite{bib-HEIN}\nfor He ions at 1 and 10 MeV/A and for O and Pb ions at 1, 10 and\n100 MeV/A in carbon and the results were found\nto be correct within $5\\%$ both for the energy loss and the range.\n\n\\begin{figure}[hbt]\n \\centering\n \\epsfig{file=eps/phys431-2.eps,width=14cm}\n \\caption{Stopping powers in Lead}\n \\label{fg:phys431-2}\n\\end{figure}\n\nAnother comparison has been made with the tables of~\\cite{bib-HUBE} \nfor 10 MeV/A ions in lead, with\nthe results shown in table~\\ref{tb:phys431-1}.\nAnother comparison with the same tables is shown in Figs.~\\ref{fg:phys431-1}\nand \\ref{fg:phys431-2}.\n\nA comparison with the tables in~\\cite{bib-ANZI,bib-ANZ1} for T/A $<$ 1 MeV/A\ngives an error on $(dE/dx) \\leq 10-20\\%$.\n\n\\begin{table}\n\\begin{centering}\n\\begin{tabular}{|r|rr|r|}\n\\hline\n\\multicolumn{4}{|c|}{He ions in Ar (energies in keV)} \\\\\n& \\multicolumn{2}{c}{MonteCarlo} & \\multicolumn{1}{c|}{data} \\\\\nt (cm) & \n$\\Delta$E & FWHM & FWHM \\\\\n\\hline\n0.5 & 444 & 38 & $\\sim$40 \\\\\n1.0 & 913 & 53 & $\\sim$60 \\\\\n2.0 & 1940 & 78 & $\\sim$80 \\\\\n\\hline\n\\end{tabular}\n\\caption{Comparison of the measured and calculated and FWHM\nfor 1.4 MeV/A He ions in gas.}\n\\end{centering}\n\\label{tb:phys431-4}\n\\end{table}\n\n\\subsection{Comparison of FWHM}\n\nA comparison has been made with \nlow energy data ($0.3 \\leq T/A \\leq 2.5$ MeV/A) in very\nthin absorbers (1,7 $\\mu$m, 0.4 $\\mu$m). Data are taken from\nthe tables in~\\cite{bib-TSCH} for\nenergy loss of O ions in Al, and the\nresults are reported in table~\\ref{tb:phys431-2}. The quoted experimental \nerror for these data is $1\\%$ statistical + $5\\%$ systematic for \n417 $\\mu$g cm$^{-2}$ data and $2\\%$ statistical + $10\\%$ systematic for\n110 $\\mu$g cm$^{-2}$ data. \n\nPlots of energy deposition distributions of 1.4 MeV/A lead and helium\nions in gases can be found in~\\cite{bib-GEIS}. \nFrom these we have measured the FWHM and compared them with the ones given\nby the MonteCarlo. The results can be seen in table~\\ref{tb:phys431-3}\nand ~\\ref{tb:phys431-4}. It\nshould be noted that the absorber thickness of, for example, Ar compares\nwith that of the preceding case (0.2 cm Ar = 356 $\\mu$g cm$^{-2}$ and\n1.2 cm Ar = 2136 $\\mu$g cm$^{-2}$).\n\n\nSimilar comparison has been made for C ions of energies 17.1 and 39.4 MeV in \nisobuthane~\\cite{bib-SCHM} and the agreement between data and {\\tt GEANT}\nfor FWHM is within 30\\%.\n", "meta": {"hexsha": "f0d1d72295de40d81767dff007e4fe92b75f78f5", "size": 10800, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "geant/phys431.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/phys431.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/phys431.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": 37.6306620209, "max_line_length": 78, "alphanum_fraction": 0.6460185185, "num_tokens": 3762, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.3140505321516081, "lm_q1q2_score": 0.1607048720181572}} {"text": "%!TEX root = ../dissertation.tex\n\\begin{savequote}[75mm]\nScience may be described as the art of systematic over-simplification.\n\\qauthor{Karl Popper}\n\\end{savequote}\n\n\\chapter{Previous Work}\n\\label{chap:previous_work}\n\\newthought{Several works have addressed tasks that involve CV and NLP}, such as object detection based on natural language expressions \\cite{hu_natural_2015}\\cite{guadarrama_understanding_2016}, image captioning \\cite{hendricks_deep_2015}\\cite{gan_semantic_2016}\\cite{johnson_densecap:_2016}\\cite{yang_review_2016} and visual question answering (VQA) \\cite{goyal_making_2016}\\cite{zhu_visual7w:_2015}\\cite{krishna_visual_2016}\\cite{agrawal_vqa:_2015}\\cite{teney_graph-structured_2016}. Nevertheless, the standard way of processing both types of information jointly has never been clearly established, since visual and linguistic data have properties that make them fundamentally different, \\textit{i.e.} the former has spatial meaning and no sequentiality while the latter does not contemplate space but has a sequential nature. Hence, each work in this sub-field has proposed a particular way of addressing each task.\n\nOn this chapter, we intend to describe three model architectures that mix both language referring expressions and vision inputs to produce a segmentation mask. While two of them \\cite{hu2016segmentation} \\cite{liu2017segmentation} try to solve the task by merging language and vision representations by defining a new, synthetic entity that describes the relation between both, the third one \\cite{li2017cvpr} tr aims to map one domain to the other \\textit{i.e.,} map language features to the visual filter space to accomplish object tracking on videos based on referring expressions.\n\n\\section{Segmentation from Natural Language Expressions}\nOn this work \\cite{hu2016segmentation}, the authors process visual and natural language information through separate neural networks: a CNN extracts visual features from the image while an LSTM is applied to the natural language query. Strided convolutions and pooling operations in the CNN progressively downsample the feature maps to a low resolution output while producing a large receptive field size for neurons in the final layers.\n\nThus, the authors use a modified pre-trained VGG-16 \\cite{DBLP:journals/corr/SimonyanZ14a} as a feature extractor whose last three fully-connected layers were replaced by three convolutional layers. Given an image of height \\textit{H} and width \\textit{W}, the output of such a fully convolutional network (FCN) is a spatial feature map of dimensions $h$ and $w$ with $D$ channels at each spatial location. The strided convolutions and pooling operations, while reducing the size of the image to $h = \\frac{H}{32}$ and $w = \\frac{W}{32}$, also provide the units of the final response map with a large receptive field. At each spatial location, $\\ell^2$-normalization is applied in search for a \\textit{more robust feature representation}. \n\nAdditionally, to explicitly model localization in the network (\\textit{i.e.} help the network reason about queries containing localization information), relative coordinates are concatenated at each spatial location in the feature map obtained by the CNN, thus obtaining a final visual feature map, with $D + 8$ channels. \n\nOn the other hand, language information is processed by tokenizing each word with a Word Embedding (WE) and passing each of these through a Long Short-Term Memory (LSTM) cell until the end of the sentence is reached. The last hidden state of the LSTM, which is expected to hold an overall representation of the expression's concept, is $\\ell^2$-normalized and concatenated along the channel axis at \\textit{each spatial location} of the feature representation that was obtained from the FCN module. If the hidden state of the LSTM is of length $L$, the concatenation of the linguistic and visual representation is of shape $(L + D + 8) \\times h \\times w$. Merging of visual and natural language information is done by concatenating the output of the LSTM to the visual feature map at each spatial location.\n\nFinally, two $1\\times1$ convolution layers with ReLU nonlinearities in between are applied for final classification. The ground truth mask is downsampled to have the same dimensions as the output, so that they can be directly compared. The loss function is defined as the average over the per-pixel weighed logistic regression loss, where weights for foreground and background counteracting the class imbalance are empirically determined to produce faster convergence. \n\nThis low resolution architecture is trained with standard backpropagation and Stochastic Gradient Descent (SGD) with momentum until convergence. Training is thus done in two stages: a low resolution stage and a high resolution stage that trains a deconvolution layer to upsample the low resolution output with deconvolution to yield the final segmentation mask. The deconvolution layer is initialized with weights from bilinear interpolation.\n\n\n\n\\section{Recurrent Multimodal Interaction}\nIn \\cite{liu2017segmentation}, the authors argue that segmenting the image based only on a final, memorized representation of the sentence does not fully take advantage of the sequential nature of language. This is done by not only including spatial coordinates as extra-channels for the image representation (as in the previous work by \\cite{hu2016segmentation}) but also including the linguistic information at \\textit{each} time step. This way, the sequential property of natural language is claimed to be exploited, and an analogy can be made so that image segmentation is understood as a sequential process.\n\nThe initial processing for the image itself is similar to that in \\cite{hu2016segmentation}: the output of a FCN is $\\ell^2$-normalized along the channel-axis and mesh grids representing spatial information are concatenated. Again, the FCN reduces the size of the input image and delivers a large receptive field for the units in the final layers ($h = \\frac{H}{32}$ and $w = \\frac{W}{32}$, in this case).\n\nConsequently, they propose to perform segmentation multiple times in the pipeline. Such multimodal representation is obtained by concatenating the visual features at every spatial location of the visual representation with the hidden state of the LSTM. The segmentation mask is obtained by applying a multimodal LSTM (mLSTM) to the multimodal representation and then performing regular convolution to combine the channels that were produced by the mLSTM. The definition of the mLSTM is a convolutional LSTM that shares weights both across spatial location and time step, and is implemented as a $1\\times1$ convolution that merges all these types of information. \n\nThe sequential property of natural language is thus exploited, and an analogy can be made so that image segmentation is understood as a sequential process. It should be mentioned that the hidden state of this mLSTM is not one-dimensional, like that of a conventional LSTM, but rather three dimensional, resembling an image. \n\nAt the final time step, when the last hidden state of the mLSTM is generated, a convolution is applied to it, yielding an output with only one channel. In the training process, although the network's output is a downsized version of its input, no upsampling is performed. The loss is defined exactly as in \\cite{hu2016segmentation} and the network is trained with backpropagation, Adam optimizer with a fixed learning rate of $0.00025$, batch size of $1$ and weight decay to $0.0005$.\n\nAt test time, bilinear upsampling is performed to the net's output to produce a mask with the same dimensions of the ground-truth mask. Additionally, as a way of making the output less coarse, a Dense Conditional Random Field (DenseCRF) \\cite{DBLP:journals/corr/abs-1210-5644} is applied for refinement.\n\n\n\\section{Tracking by Natural Language Specification}\nIn \\cite{li2017cvpr}, the main task is not precisely segmentation based on a natural language, but object tracking in a video sequences. One of the usual approaches for specifying the target to be tracked in a video, is to mark it with a bounding box in the first frame. However, this approach has the issue that, for the duration of the video, the object may change much of its appearance and location, rendering the initial bounding box useless in some cases. Their main idea is about providing an alternative to this approach, by noting that \\textit{(i)} the semantic meaning of the object being marked does not vary, for the duration of the video, as much as the appearance, and \\textit{(ii)} this semantic meaning may be more enclosed by a linguistic expression.\n\nThis way of understanding the task brings the two problems close from the CV perspective. However, the approach taken in \\cite{li2017cvpr} is substantially different, since visual and linguistic information is never merged \\textit{per se} (as in the previous two methods), but rather the linguistic information is mapped to a space in which it can be thought of as having visual meaning.\n\nThe visual input is processed by a modified VGG-16 whose final three fully connected layers were replaced by convolutional ones, meaning that the network yields a feature map as in the previous methods. The linguistic input consisting of $T$ words is represented, word by word, with a WE, to which an LSTM is recursively applied. The main contribution of this approach is employing a single layer perceptron (SLP) with sigmoid activation function to the last hidden state of the LSTM ($h_T$), generating a \\textit{dynamic convolutional visual filter}, $f$. Essentially, $f$ is a vector that is produced as a function of the last hidden state of the LSTM, and its dimensions are such that it can be thought of as filter for a 2D convolution that is to be performed on the feature map produced by the modified VGG. It is denominated as a \\textit{dynamically} generated filter because it is specialized and fine-tuned for the semantics of the visual specification \\cite{li2017cvpr}. \n\nThe main idea is that the filter produced as a function of an expression, will produce a strong response to the elements being referred to in such expression, and a weak response to those \\textit{not} being referred to. This response is thought of as \\textit{scores} for the referring expression, so that a segmentation can be output.\n\nOnce the filter is generated, convolution is applied to the feature map, and a response map is obtained. After this, a deconvolution layer of stride 32 is applied to produce a response map of the same size of the input image.\n\n% For an example of a full page figure, see Fig.~\\ref{fig:myFullPageFigure}.\n\n\n\n\n%% Requires fltpage2 package\n%%\n% \\begin{FPfigure}\n% \\includegraphics[width=\\textwidth]{figures/fullpage}\n% \\caption[Short figure name.]{This is a full page figure using the FPfigure command. It takes up the whole page and the caption appears on the preceding page. Its useful for large figures. Harvard's rules about full page figures are tricky, but you don't have to worry about it because we took care of it for you. For example, the full figure is supposed to have a title in the same style as the caption but without the actual caption. The caption is supposed to appear alone on the preceding page with no other text. You do't have to worry about any of that. We have modified the fltpage package to make it work. This is a lengthy caption and it clearly would not fit on the same page as the figure. Note that you should only use the FPfigure command in instances where the figure really is too large. If the figure is small enough to fit by the caption than it does not produce the desired effect. Good luck with your thesis. I have to keep writing this to make the caption really long. LaTex is a lot of fun. You will enjoy working with it. Good luck on your post doctoral life! I am looking forward to mine. \\label{fig:myFullPageFigure}}\n% \\end{FPfigure}\n% \\afterpage{\\clearpage}\n\n", "meta": {"hexsha": "bbc6d5beed4849cebe89d7a49bf94b195b0ad07d", "size": 11990, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "chapters/chapter1.tex", "max_stars_repo_name": "andfoy/bsc-dissertation", "max_stars_repo_head_hexsha": "2fd181fc7958ea58fe31cc6d13a19237bfc1757c", "max_stars_repo_licenses": ["MIT"], "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/chapter1.tex", "max_issues_repo_name": "andfoy/bsc-dissertation", "max_issues_repo_head_hexsha": "2fd181fc7958ea58fe31cc6d13a19237bfc1757c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapters/chapter1.tex", "max_forks_repo_name": "andfoy/bsc-dissertation", "max_forks_repo_head_hexsha": "2fd181fc7958ea58fe31cc6d13a19237bfc1757c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 181.6666666667, "max_line_length": 1142, "alphanum_fraction": 0.8034195163, "num_tokens": 2613, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.31069438321455395, "lm_q1q2_score": 0.1602002116887026}} {"text": "\\documentclass{beamer}\n\\usefonttheme[onlymath]{serif}\n\\usepackage[english]{babel}\t\t\t\t\t\t\t%For internationalization\n\\usepackage[utf8]{inputenc}\t\t\t\t\t\t\t%For character encoding\n\\usepackage{amsmath}\t\t\t\t\t\t\t\t%For mathematical typesetting\n\\usepackage{amssymb}\t\t\t\t\t\t\t\t%For mathematical typesetting\n\\usepackage{graphicx}\t\t\t\t\t\t\t\t%For handling graphics\n\\usepackage{listings}\n\n\\newcommand{\\be}{\\begin{equation}}\n\\newcommand{\\bea}{\\begin{equation*}}\n\\newcommand{\\ben}[1]{\\begin{equation}\\label{#1}}\n\\newcommand{\\ee}{\\end{equation}}\n\\newcommand{\\eea}{\\end{equation*}}\n\\newcommand{\\aq}{\\overset{\\sim}{q}}\n\n\\title\n{An Introduction to Discontinuous Galerkin Methods}\n\\subtitle{Module 3A: To Higher-Orders - Solution Approximation}\n\\author[Bevan] % (optional, for multiple authors)\n{J.~Bevan}\n\\institute[UMass Lowell]\n{\n Department of Mechanical Engineering, Grad Student\\\\\n University of Massachusetts at Lowell\n}\n\\date[Fall 2014]\n{}\n\\subject{Discontinuous Galerkin}\n\n\\begin{document}\n\\frame{\\titlepage}\n\\frame{\\frametitle{Module 3A: To Higher-Orders - Solution Approximation}\\tableofcontents}\n\n%NEW SECTION\n\\section{Weak Form- Revisited}\n\\subsection{Approximation Space} \n\\frame{\\frametitle{\\textbf{\\secname}: \\subsecname}\n\\be \\int_{\\Omega} \\frac{\\partial q}{\\partial t} \\phi_j \\,dx + \\int_{\\Omega} \\frac{\\partial f(q)}{\\partial x} \\phi_j \\,dx = 0 \\ee\n\\begin{itemize}\n\\item Let's revisit the weak form in greater detail, we glossed over some important details.\n\\item To get a flexible method, we'd like to be able to generate an arbitrary order solution approximation. How do we do this in code?\n\\item We glossed over the construction of the bases, we can think in terms of nodal or modal\n\\be \\aq(x) = \\sum_{i=0}^M a_i \\psi_i(x) \\ee\n\\end{itemize}\n}\n\n\\subsection{$L^2$ Projection: Minimize norm} \n\\frame{\\frametitle{\\subsecname}\n\\begin{itemize}\n\\item Where does the weak form come from? Approximate sol'n doesn't satisfy the PDE exactly, left with some residual\n\\be \\frac{\\partial \\aq}{\\partial t} \\,dx + \\frac{\\partial f(\\aq)}{\\partial x}\\,dx = R(x) \\ee\n\\item A projection finds the \"closest\" fit on a vector space compared to the original. An orthogonal projection does just this.\n\\item Minimizes the $L^2$ norm wrt the space projected upon\n\\end{itemize}\n}\n\n\\subsection{The Galerkin Condition} \n\\frame{\\frametitle{\\subsecname}\n\\begin{itemize}\n\\item An orthogonal projection means that the difference between the original and the projection should be orthogonal to the space projected upon, so for each basis $\\phi \\in V_h$\n\\be \\int (f-f_h) \\, \\phi \\,dx =0 = \\int R(x) \\phi \\,dx\\ee\n\\item The projected space doesn't have to be the same space as the solution approximation, but if we do choose them to be the same we have the Bubnov-Galerkin approach\n\\item We could choose the two spaces to be different, this is a Petrov-Galerkin approach. As an example, a weight space of delta functions yields a collocation method\n\\end{itemize}\n}\n\n%NEW SECTION\n\\section{Arbitrary Order Basis: Monomials?} \n\\frame{\\frametitle{\\textbf{\\secname}}\n\\begin{itemize}\n\\item Let's continue with the choice of polynomials for our basis functions.\n\\item The easy and obvious choice is the monomials $\\psi_i(x) = a_i x^i$ so the arbitrary order solution approximation is\n\\be \\aq(x) = \\sum_{i=0}^M a_i \\psi_i(x)= \\sum_{i=0}^M a_i x^i \\ee\n\\item Can you think of why this a poor choice for a vector basis? Remember a basis needs to be complete and linearly independent. Let's see two separate ways why this is a poor choice.\n\\end{itemize}\n}\n\n\\subsection{Linear Dependence} \n\\frame{\\frametitle{\\subsecname}\n\\begin{itemize}\n\\item Normalize the basis wrt to the $L^2$ norm $\\vert g \\vert = \\sqrt{\\int g^2}$ so $\\bar{\\psi}_i=\\sqrt{2i+1}x^i$ \n\\item Consider the inner product of two adjacent basis functions\n\\be \\int \\bar{\\psi}_{i-1} \\bar{\\psi}_{i} \\,dx = \\sqrt{1-\\frac{1}{4i^2}} \\ee\n\\item Linearly independent vectors are orthogonal, that is their inner product is zero. But for our monomials, even moderate values of $i$ give an inner product of close to 1\n\\item Very nearly dependent basis vectors mean small perturbations can lead to trouble finding the correct solution\n\\end{itemize}\n}\n\n\\subsection{The ill-conditioned Hilbert matrix} \n\\frame{\\frametitle{\\subsecname}\n\\begin{itemize}\n\\item The alternate way to consider this is to look at the mass matrix for a monomial basis\n\\item $1$\n\\item $x$\n\\item $x^2$\n\\item $x^3$\n\\item When we integrate from 0 to 1 it is easy to see the pattern of values, this is a Hilbert matrix\n\\item It is ill-conditioned, let's see why this is a problem in Matlab\n\\end{itemize}\n}\n\n%NEW SECTION\n\\section{[Recall] Lagrange Interpolation} \n\\frame{\\frametitle{\\textbf{\\secname}}\n\\begin{itemize}\n\\item Instead of a monomial basis, what if we were to use a Lagrange basis (commonly used for interpolation)\n\\item Recall, the Lagrange basis is zero at all interp nodes except the basis node, which it is 1 at\n\\item It has the form\n\\be L_q(x) = \\prod_{p=1,p\\neq q}^{Np} \\frac{x-x_p}{x_q-x_p} \\ee\n\\item We can compactly represent this as\n\\textit{nn=elim(nd(1:N)',nd(1:N)',[1 3 2]);\\\\\nLag= @(x,nv) prod(bsxfun(@rdivide,bsxfun(@minus,x,nn(nv,:,:)),...\\\\\nbsxfun(@minus,nd(nv),nn(nv,:,:))),3)}\n\\end{itemize}\n}\n\n%NEW SECTION\n\\section{Lagrange Spatial Approximation} \n\\frame{\\frametitle{\\textbf{\\secname}}\n\\begin{itemize}\n\\item We can now represent our arbitrary order sol'n approximation\n\\be \\aq(x) = \\sum_{i=0}^M a_i \\psi_i(x)= \\sum_{i=0}^M q(x_i) L_i(x) \\ee\n\\item Where we must choose a collection of points to use as our interpolation nodes\n\\end{itemize}\n}\n\n%NEW SECTION\n\\section{Interpolation Points: Equispaced?} \n\\frame{\\frametitle{\\textbf{\\secname}}\n\\begin{itemize}\n\\item It would seem logical that equispaced points are a good choice. They evenly cover the domain and are simple to calculate positions for.\n\\item Indeed these points work well for low $Np$, so one would expect the accuracy to increase as $Np$ increases\n\\item Let's see how it behaves at large $Np$\n\\end{itemize}\n}\n\n%NEW SECTION\n\\section{Runge's Phenomenon} \n\\frame{\\frametitle{\\textbf{\\secname}}\n\\begin{itemize}\n\\item The divergence of the interpolation is a result of Runge's phenomenon\n\\item Why this fails is explainable in terms of two relations: the Bernstein and Markov Inequalities. For a polynomial $P^N \\in [-1, 1]$\n\\be |P^{\\prime}(x)| \\leq \\frac{N}{\\sqrt{1-x^2}}\\| P \\| _{\\infty} \\ee\n\\item The singularity in the Bernstein inequality can be bounded by the Markov inequality\n\\be \\| P^{\\prime} \\| {\\infty} \\leq N^2 \\| P \\|_ {\\infty} \\ee\n\\item With the overall being\n\\be |P^{\\prime}(x)| \\leq \\min \\left(\\frac{N}{\\sqrt{1-x^2}},N^2\\right)\\| P \\|_ {\\infty} \\ee\n\n\\end{itemize}\n}\n\n%NEW SECTION\n\\section{Interpolation Points: Legendre Roots} \n\\frame{\\frametitle{\\textbf{\\secname}}\n\\begin{itemize}\n\\item The overall inequality implies we'd like quadratic spacing near the element boundaries.\n\\item Though it may seem arbitrary, the roots of the Legendre polynomials have a favorable spacing that matches out needs\n\\item They avoid Runge's phenomenon, and have several other very nice features we shall see in the next module\n\\begin{figure}\n\\centering\n\\includegraphics[width=2in]{LegPolys.PNG}\n\\end{figure}\n\\centering\n\\tiny http://en.wikipedia.org/wiki/File:Legendrepolynomials6.svg\n\\end{itemize}\n}\n\n\\end{document}", "meta": {"hexsha": "d9aab7e62d4d3d7c7cdbb18a2b6aca6d945eb540", "size": 7259, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Module 3A/22_6xx-Module3A.tex", "max_stars_repo_name": "sconde/22_6xx-DG-for-PDEs", "max_stars_repo_head_hexsha": "34527e2fa77a193a58bd2f47f781833d70c59315", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 31, "max_stars_repo_stars_event_min_datetime": "2016-03-15T11:40:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T00:41:34.000Z", "max_issues_repo_path": "Module 3A/22_6xx-Module3A.tex", "max_issues_repo_name": "LuciaZhang9/22_6xx-DG-for-PDEs", "max_issues_repo_head_hexsha": "e9463ab6faee98af26102949e04ab8be75405154", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2016-03-15T11:50:32.000Z", "max_issues_repo_issues_event_max_datetime": "2016-03-20T08:48:32.000Z", "max_forks_repo_path": "Module 3A/22_6xx-Module3A.tex", "max_forks_repo_name": "userjjb/22_6xx-DG-for-PDEs", "max_forks_repo_head_hexsha": "34527e2fa77a193a58bd2f47f781833d70c59315", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 22, "max_forks_repo_forks_event_min_datetime": "2016-04-30T00:20:42.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-14T09:03:21.000Z", "avg_line_length": 42.9526627219, "max_line_length": 184, "alphanum_fraction": 0.7382559581, "num_tokens": 2198, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4571367168274948, "lm_q2_score": 0.34864514210180597, "lm_q1q2_score": 0.15937849559827497}} {"text": "% 20201005\n\\documentclass[env.tex]{subfiles}\n\n\\newcommand{\\aq}{aquatic}\n\\newcommand{\\te}{terrestrial}\n\\newcommand{\\mL}{mixed layer}\n\\newcommand{\\hg}{homogeneous}\n\\newcommand{\\thl}{theoretical}\n\\newcommand{\\sP}{subarctic Pacific}\n\\newcommand{\\sgs}{Sargasso Sea}\n\\newcommand{\\nA}{N. Atlantic}\n\\newcommand{\\ds}{density}\n\\newcommand{\\pl}{population size}\n\\newcommand{\\mC}{molar Concentration}\n\\newcommand{\\ct}{continuous}\n\\newcommand{\\y}{yes}\n\\newcommand{\\n}{no}\n\\newcommand{\\ft}{fluctuation}\n\\newcommand{\\sd}{steady}\n\n\\begin{document}\n\\subsection{Features comparison between models}\n\n\\begin{table}[H]\n \\centering\n \\caption[Model features comparison]{Table of features comparison (16 features) between model in this project with aquatic slab models (22 models) and two terrestrial nutrient cycle models}\n \\label{modComp}\n\\end{table}\n\n\\begin{landscape}\n\\begin{longtable}{p{2cm}|p{.05\\linewidth}p{.07\\linewidth}p{.1\\linewidth}p{.1\\linewidth}p{.13\\linewidth}p{.06\\linewidth}p{.14\\linewidth}p{.1\\linewidth}}\\hline\n model & year & system & structure & condition & location & element & unit & time-frame \\\\\\hline\n this study & 2020 & \\aq & CPB & \\mL & \\thl & C & \\ds & \\ct \\\\\n \\parencite{evans1985model} & 1985 & \\aq & NPZ & \\mL & \\sP & n.a. & \\pl & spring \\\\\n \\parencite{frost1987grazing} & 1987 & \\aq & NP(Z) & \\mL & \\sP & n.a. & \\pl & \\ct \\\\\n \\parencite{fasham1990nitrogen} & 1990 & \\aq & 2NPZDB(DOM) & \\hg & \\sgs & N & \\mC & \\ct \\\\\n \\parencite{robinson1993simulated} & 1993 & \\aq & P2Z & \\mL & upwell Pacific & C & \\ds & by-year \\\\\n \\parencite{fasham1995use} & 1995 & \\aq & 2NPZDB(DOM) & - & \\sP & - & - \\\\\n \\parencite{matear1995parameter} & 1995 & \\aq & 2NP2ZDB(DOM) & \\mL & \\sP & n.a. & \\pl & \\ct \\\\\n \\parencite{hurtt1996pelagic} & 1996 & \\aq & 2NPR & \\mL & \\sgs & N & \\mC & \\ct \\\\\n \\parencite{xiao1996relative} & 1996 & \\te & CNP & dual cycles & \\thl & C, N & \\ds & \\ct \\\\\n \\parencite{popova1997chaotic} & 1997 & \\aq & NPZD & \\mL & \\thl & N & \\mC & \\ct \\\\\n \\parencite{anderson1998modelling} & 1998 & \\aq & 2NPZDB(DOM) & slab & Engligh Channel & N & \\mC & \\ct \\\\\n \\parencite{spitz1998data} & 1998 & \\aq & 2NPZDB(DOM) & \\mL & \\sgs & N & \\mC & \\ct \\\\\n \\parencite{fennel2001testing} & 2001 & \\aq & NPZD & \\mL & \\sgs & N & \\mC & \\ct \\\\\n \\parencite{natvik2001weak} & 2001 & \\aq & NPZ & - & Flemish Cap & - & - & - \\\\\n \\parencite{schartau2001parameter} & 2001 & \\aq & NPZ & \\mL & \\sgs & N & \\mC & \\ct \\\\\n \\parencite{spitz2001configuring} & 2001 & \\aq & 2NPZDB(DOM) & \\mL & \\sgs & N & \\mC & \\ct \\\\\n \\parencite{ito2002simulation} & 2002 & \\te & CP & \\hg & \\thl & C & \\ds & no \\\\\n \\parencite{hemmings2004split} & 2004 & \\aq & NPZ & - & \\nA & - & - & - \\\\\n \\parencite{onitsuka2005differences} & 2005 & \\aq & NPZD, 2N2P3Z(DOM) & slab & Japan sea & N & \\mC & \\ct \\\\\n \\parencite{findlay2006modelling} & 2006 & \\aq & NP & \\mL & \\thl & hypo & \\mC & \\ct \\\\\n \\parencite{mitra2007accounting} & 2007 & \\aq & 2NPZDB(DOM) & \\hg & \\nA & N & \\mC & short \\\\\n \\parencite{mitra2009closure} & 2009 & \\aq & 2NPZDB(DOM) & \\hg & \\nA & N & \\mC & \\ct \\\\\n \\parencite{llebot2010role} & 2010 & \\aq & 2N2PD(DOM) & \\hg & Mediterranean Bay & N & \\mC & \\ct \\\\\n \\parencite{kidston2013phytoplankton} & 2013 & \\aq & NPZD & \\mL & Southern Ocean & N & \\mC & \\ct \\\\\n \\parencite{anderson2015empower} & 2015 & \\aq & NPZD & \\mL & \\thl & N & \\mC & \\ct \\\\\n\\hline\\end{longtable}\n\n\\begin{longtable}{p{2cm}|p{.07\\linewidth}p{.1\\linewidth}p{.1\\linewidth}p{.1\\linewidth}p{.1\\linewidth}p{.1\\linewidth}p{.1\\linewidth}p{.1\\linewidth}}\\hline\n model & thermocline & density-depend motality & trophic levels (main level + decomposer) & explicit players & sunlight & system setting & respiration & resource allocation \\\\\\hline\n this study & \\n & \\phy & 1+1 & \\y & \\n & \\ft & \\y & \\y \\\\\n \\parencite{evans1985model} & \\y & \\n & 1+0 & \\y & \\y & \\sd & \\n & \\n \\\\\n \\parencite{frost1987grazing} & \\y & \\n & 2+0 & \\n & \\y & \\sd & \\n & \\n \\\\\n \\parencite{fasham1990nitrogen} & \\y & \\n & 2+1 & \\y & \\n & \\sd & \\n & \\n \\\\\n \\parencite{robinson1993simulated} & \\y & unknown & 3+0 & no equations & \\y & \\ft & \\n & \\n \\\\\n \\parencite{fasham1995use} & - & - & - & model 03 & - & - & \\n & \\n \\\\\n \\parencite{matear1995parameter} & \\y & \\n & 2+0 & \\y & \\y & \\ft & \\n & \\n \\\\\n \\parencite{hurtt1996pelagic} & \\y & \\n & 1+0 & model 03 & \\n & \\sd & \\n & \\n \\\\\n \\parencite{xiao1996relative} & \\n & \\n & 1+1 & \\y & \\y & \\sd & \\y & \\y \\\\\n \\parencite{popova1997chaotic} & \\y & \\n & 2+0 & \\y & \\y & \\ft & \\n & \\n \\\\\n \\parencite{anderson1998modelling} & \\y & \\n & 2+1 & \\n & \\y & \\ft & \\n & \\n \\\\\n \\parencite{spitz1998data} & \\y & \\n & 2+1 & \\y & \\y & \\ft & \\n & \\n \\\\\n \\parencite{fennel2001testing} & \\y & \\n & 2+0 & \\y & \\y & \\ft & \\n & \\n \\\\\n \\parencite{natvik2001weak} & - & - & - & no equations & - & - & \\n & \\n \\\\\n \\parencite{schartau2001parameter} & \\y & \\n & 2+0 & \\n & \\y & \\ft & \\n & \\n \\\\\n \\parencite{spitz2001configuring} & \\y & \\n & 2+1 & model 11 & \\n & \\ft & \\n & \\n \\\\\n \\parencite{ito2002simulation} & \\n & \\n & 1+0 & \\y & \\n & \\sd & \\n & \\n \\\\\n \\parencite{hemmings2004split} & - & - & - & statistical & - & - & \\n & \\n \\\\\n \\parencite{onitsuka2005differences} & \\y & \\n & 2+0 & \\y & \\n & \\ft & \\n & \\n \\\\\n \\parencite{findlay2006modelling} & \\y & \\n & 1+0 & \\n & \\n & \\ft & \\n & \\n \\\\\n \\parencite{mitra2007accounting} & \\n & \\n & 2+1 & \\n & \\n & perturbation & \\n & \\n \\\\\n \\parencite{mitra2009closure} & \\n & \\n & 2+1 & \\y & \\n & cannibalism & \\n & \\n \\\\\n \\parencite{llebot2010role} & \\n & \\n & 2+0 & \\y & \\y & \\sd & \\n & \\n \\\\\n \\parencite{kidston2013phytoplankton} & \\y & \\phy & 2+0 & \\y & \\y & \\sd & \\n & \\n \\\\\n \\parencite{anderson2015empower} & \\y & \\phy & 2+1 & \\y & \\y & \\ft & \\n & \\n \\\\\n\\hline\\end{longtable}\n\\end{landscape}\n\n\\end{document}", "meta": {"hexsha": "14cc1e8422e6211a7aa2c4a330935f0c880c08d9", "size": 5831, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "p_paper/sec/sup1.tex", "max_stars_repo_name": "ph-u/PhyBac_C-Capture", "max_stars_repo_head_hexsha": "f1134050fddc48b64bdaf8d5444a99b8fc52451d", "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": "p_paper/sec/sup1.tex", "max_issues_repo_name": "ph-u/PhyBac_C-Capture", "max_issues_repo_head_hexsha": "f1134050fddc48b64bdaf8d5444a99b8fc52451d", "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": "p_paper/sec/sup1.tex", "max_forks_repo_name": "ph-u/PhyBac_C-Capture", "max_forks_repo_head_hexsha": "f1134050fddc48b64bdaf8d5444a99b8fc52451d", "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.7888888889, "max_line_length": 192, "alphanum_fraction": 0.5736580346, "num_tokens": 2501, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011397337391, "lm_q2_score": 0.27202454519235225, "lm_q1q2_score": 0.15916187142759733}} {"text": "\\section{Basic Analysis}\n\\label{891_2:sec:anal}\n\nTo quantify uncertainties in our full spectrum galaxy fits we will\ntest different methods of fitting spectra and interpreting the\nresults. In this section we describe the basic, high-level methodology\nthat is common to all fitting methods. We also detail preparatory\nanalysis that is required before these methods can be applied to our\ndata, namely determining the velocity of each aperture and correcting\nfor Balmer emission.\n\n%+++++++++++++++++++++++++++\n%% {\\bf MAB: Itemize (not in bullets, in sentences, clauses) the detailed\n%% preparatory analysis you will be describing. ``running the data\n%% through full spectrum fitting'' should be re-worded.\n\n%------------------------\n%% You should also have some preliminary discussion about why you are\n%% laying the basics on the ``SSP fitting methodology.'' (I would call it\n%% SPS not SSP, i.e., your SPS involves adding together SSPs.) For\n%% example, there are the issues of degeneracies between age, metallicity\n%% and extinction. There is also the issue of assumptions about the SFH\n%% on $\\tau_L$ and $Z_L$ for which the data cannot offer resolution,\n%% i.e., the data does not allow you to know about the detailed SFH for\n%% the older stellar populations. In other words, what is going to lead\n%% you ultimately to the DFK approach. Foreshadow this.}\n\n\\subsection{SSP fitting methodology}\n\\label{891_2:sec:SSP_method}\n\nOur fitting method involves minimizing differences between measured\nNGC 891 spectra and synthetic galaxy spectra constructed from the\nsuperposition of simple stellar populations (SSPs, see\n\\S\\ref{891_2:sec:SSP_sets}). Fits are performed with\nMPFITFUN\\footnote{available at \\url{http://purl.com/net/mpfit}}\n\\citep{Markwardt09}, an IDL implementation of the MINPACK Levenberg\nMarquardt minimization algorithm \\citep{More78}. The model galaxy\nspectra are defined as\n\\begin{equation}\n\\label{891_2:eq:SSP_galaxy}\ng(\\lambda) = R(\\lambda,\\tau_V) \\sum_{i,j} M(\\Delta t_i,Z_j)\nf(\\lambda,\\Delta t_i, Z_j),\n\\end{equation}\nwhere $f(\\lambda, \\Delta t_i, Z_j)$ is the spectrum of an SSP with\nmetallicity $Z_j$ formed over time interval $\\Delta t_i$, $M(\\Delta\nt_i,Z_j)$ quantifies the strength of the contribution of each SSP, and\n$R(\\lambda, \\tau_V)$ governs the total extinction in the galaxy. All of our\nSSPs are normalized to \\val{1}{\\sol{M}} so the strength of each SSP is\nsimply\n\\begin{equation}\n\\label{891_2:eq:fit_weight}\nM(\\Delta t_i,Z_j) = \\int_{\\Delta t_i} \\psi(t, Z_j) dt,\n\\end{equation}\nwhere $\\psi(t, Z_j)$ describes the mass of stars formed at time $t$\nwith metallicity $Z_j$ (i.e., the star formation rate). In other\nwords, $M(\\Delta t_i,Z_j)$ is the total mass in stars formed during\nthe time interval, $\\Delta t_i$, associated with a particular SSP. The\nextinction, $R(\\lambda, \\tau_V)$, is parametrized by a single\nvariable, $\\tau_V$ and, importantly, does not depend on SSP age\n($t_i$) or metallicity ($Z_j$). In \\S\\ref{891_2:sec:extinction} we\ndiscuss the details of $R(\\lambda, \\tau_V)$ and the limitations of\nthis simplification. During fitting the free parameters are the SSP\nweights ($M(\\Delta t_i,Z_j)$) a single extinction term (\\tauV), and the\nsystematic velocity.\n\n%+++++++++++++++++++++++++++++\n%% {\\bf MAB: You should reference Levenberg Marquardt but I do not think\n%% you need to describe your coding language or the implementation in\n%% MPFITFUN. Concerning equation (1), you need to mention here what is\n%% being assumed given the placement of R. You can discuss it more\n%% later (in 3.3), but you should at least note the implications here\n%% and point to that later discussion here.}\n\nFor each aperture our primary values of interest are the age,\nmetallicity, and extinction. We measure extinction directly as $A_V =\n1.086\\ \\tauV$, but age and metallicity depend on assumptions made\nduring fitting (i.e., priors in the SSP library) and during subsequent\nanalysis.\n\nAs shown in Equation \\ref{891_2:eq:fit_weight} the fit weights describe the\nintegral of a particular star formation history (SFH), but it is\nuseful to reduce a SFH down to single values for age and\nmetallicity. To do this we define a pair of light-weighted\nquantities. The mean, light-weighted age is\n\\begin{equation}\n\\label{891_2:eq:MLWA}\n\\tau_L = \\frac{\\sum_{i,j} W_{L,i,j}\\times t_i}{\\sum_{i,j} W_{L,i,j}}\n\\end{equation}\nwhere $t_i$ is the age associated with each SSP and $W_L$ is the\n``light weight'', defined as\n\\begin{equation}\n\\label{891_2:eq:light_weight}\nW_{L,i,j} = M(\\Delta t_i,Z_j)\\sum_k S(\\lambda_k) R(\\lambda_k, \\tau_V)\nf(\\lambda_k, \\Delta t_i, Z_j),\n\\end{equation}\nwhere $S(\\lambda_k)$ defines a bandpass over which the light weight is\ncomputed. We set $S(\\lambda_k)$ to be flat over \\val{5450}{\\AA}\n$\\leq\\lambda\\leq$ \\val{5550}{\\AA} and zero everywhere else. The choice\nof $t_i$ depends on assumptions about the SFH and in this work we make\nthe simple assumption that star formation is constant across the\nlifetime of each SSP ($\\Delta t_i$) so that $t_i$ is simply the\nmidpoint of each $\\Delta t_i$. In \\S\\ref{891_2:sec:sys_err} we discuss\nand quantify the systematics that arise from such an assumption. We\nnote that Equation \\ref{891_2:eq:light_weight} also describes a\nconversion from mass-weights (i.e., $M(\\Delta t_i, Z_j)$) to\nlight-weights that is simply a constant that is independent of the\nspecific mix of SSPs (but does depend on the overall extinction).\n\nSimilarly to $\\tau_L$ we also define the mean, light-weighted\nmetallicity as\n\\begin{equation}\n\\label{891_2:eq:MLWZ}\nZ_L = \\frac{\\sum_{i,j} W_{L,i,j}\\times Z_j}{\\sum_{i,j} W_{L,i,j}}.\n\\end{equation}\n\n%+++++++++++++++++++++++\n%% {\\bf MAB: In eqn (4) move M outside of the sum since it does not\n%% depend on wavelength to clearly indicate that the factor between the\n%% light weight and the mass (weight) is a contant factor that depends\n%% on age and metallicity for a given band-pass. And say as much.}\n\n\\subsection{Velocities}\n\\label{891_2:sec:vel}\n\nThe systemic velocities of our model galaxies do not depend on the\nshape of the spectra (i.e., the SSP mix) and thus we can reduce the\nnumber of free parameters in our SSP fits by measuring the velocities\nonce and then keeping them fixed for all subsequent analysis. The\nvelocity values we use are a combination of velocity estimates from\ntwo sources: the ``fit'' velocities that result from SSP fitting, and\nvelocities measured from the centers of bright emission lines.\n\n%++++++++++++++++++++++\n%% {\\bf MAB: Do you mean ``systematic velocities'' or do you mean\n%% ``systemic velocities'' or ``line of sight velocities'' ? At the end\n%% of the paragraph enumerate in words what the following two\n%% subsubsections are.}\n\n\\subsubsection{Fit velocities}\nDuring full spectrum fitting the velocity can be a free parameter of\nthe model, and this fit provides the first estimate of the velocity of\neach aperture. The first step is to run a fully unconstrained fit\nwhere all SSP weights, the velocity, and the extinction are allowed to\nvary (see \\S\\ref{891_2:sec:SSP_method}). This produces a ``best fit''\nonly in the sense that the resulting model spectrum matches the data\nwell in a $\\chi^2$ sense; to determine velocities the details of the\nastrophysical assumptions behind each model are unimportant. The\nreported fit uncertainties on these velocities is on the order of\n\\val{\\asim10}{\\kms}, depending on \\GP fiber size (see Chapter\n\\ref{chap:891_1}), which is slightly better that 10\\% of the\ninstrumental resolution (again, depending on fiber size).\n\n%++++++++++++++++++\n%% {\\bf MAB: Discuss the centroiding accuracy in terms of the\n%% instrumental resolution.}\n\nOnce the ``best fit'' spectrum is determined we run a second iteration\nof the fitting routine with the SSP weights and extinction fixed to\nthe best fit values. This keeps the shape of the model spectrum the\nsame and causes $\\chi^2$ minimization to be driven only by the\nvelocity offset between the model and the data. When fitting these\nvelocities we used only the range of wavelengths that lie within the\nregion spanned by arc lamp lines ($\\val{4100}{\\AA} \\leq\\lambda\\leq\n\\val{6600}{\\AA}$). This avoids wavelengths that could be affected by\nextrapolation of the wavelength solution (see Chapter\n\\ref{chap:891_1}). In the majority of apertures this ``refined''\nvelocity was within \\val{\\asim 10}{\\kms} of the original fit velocity,\nwhich is similar to the precision of the fits and indicates that this\nsecond iteration is perhaps not necessary.\n\n%+++++++++++++++=\n%% {\\bf MAB: How important is this iteration? Again, compare amplitude of\n%% the change in the iteration to the instrumental resolution.\n%% Refer to Paper-I concerning the wavelengths spanned by arcs (at the end of\n%% the last sentence of the par.\n%% }\n\nThe results of these fits produce what we call the ``fit\nvelocities''. The final fit values were found to be stable to a wide\n(\\val{\\asim 100}{\\kms}) range of starting velocity values. These\nvelocity fits are driven mainly by regions of the spectrum that\ndeviate significantly from the continuum level, which in our case are\nthe Balmer absorption series, the MgI absorption band, and the G\nband. Many apertures show moderate to strong \\Ha emission, but we\nmasked this feature (and [OIII]) during fits because our model SSPs do\nnot have nebular emission. For this reason the $\\chi^2$ velocities can\nbe though of as the ``stellar'' velocity values.\n\n%% {\\bf MAB: Do you mask the upper Balmer series, including H-beta? I\n%% would have thought this would be important, and I thought you did.}\n\n%% Comment for MAB: we actually didn't mask \\HB. In retrospect maybe we\n%% should have, but it is a rare aperture indeed that has strong enough\n%% \\HB emission to really mess with the residuals. Besides, the other\n%% strong absorption features are certainly enough to simply fit a\n%% centroid.\n\n\\begin{figure*}[t]\n \\centering\n \\includegraphics[width=\\textwidth]{891_2/figs/Swat_vel.pdf}\n \\caption[Comparison of measure stellar and gas velocities to HI\n velocity data]{\\fixspacing\\label{891_2:fig:Swat_vel}Comparison of\n HI velocity envelope (from \\citet{Swaters97}) to \\emph{left:}\n measured H$\\alpha$ centroids, \\emph{middle:} best fit velocities\n from SSP models, and \\emph{right:} best fit stellar velocities\n with a constant offset to minimize median difference between gas\n and stars.}\n\\end{figure*}\n\n\\subsubsection{Emission line velocities}\n\nAs a check on the velocities found above we also measure the velocity\nof nebular emission lines, namely \\Ha. Centroids were computed using\nthe IRAF task FITPROFS which allows us to deblend the \\Ha, [NII]\ncomplex. We focus only on the \\Ha velocities, which are then compared\nto known HI velocities from \\citet{Swaters97}, as shown in the left\npanel of Figure \\ref{891_2:fig:Swat_vel}. We call the velocities measured in\n\\Ha ``gas velocities''.\n\n%+++++++++++++++=\n%% {\\bf MAB: While I am ok with us comparing to Swaters+97 in Figure 1,\n%% are you taking into account in all of this analysis the trend in the\n%% HI tangential speed with height found in Oosterloo+07? This is\n%% essential I think. Last sentence are you measuring \\Ha velocities or\n%% \\Ha+[NII] velocities?}\n\nThe center panel of Figure \\ref{891_2:fig:Swat_vel} shows the\n``stellar velocities'' compared to known HI velocities and our\nmeasured \\Ha velocities. Clearly there is a systematic offset between\nthe stellar and gas velocities and we find that this offset is\nconstant in magnitude and sign across both sides of the galaxy. This\nfact rules out an offset caused by asymmetric drift\n\\citep{Binney87}. Furthermore, many of the stellar velocities are\nunphysical in the sense that they lie outside of the HI envelope. We\ntherefore conclude that this offset is caused by systematic\nmeasurement uncertainty (likely arising from uncertainty in our\nwavelength solution) and compute a constant velocity ``correction''\nthat is applied to the stellar velocities. This offset is computed to\nminimize the median difference between stellar and gas\nvelocities. While we do expect the stellar tangential speed to lag\nbehind the gas the fact that we measure both sides of the galaxy\nmeans, the median difference between gas and stars should be, to first\norder, zero.\n\n%+++++++++++++++++++++\n%% {\\bf MAB: I made a few edits in the above par. As part of or before\n%% the sentence beginning ``Clearly, ...'', add a description of what\n%% you see in Figure 1 that is clearly unphysical, i.e., the negative\n%% velocities in the middle panel below the gas. More broadly, discuss\n%% first the distribubtion of the ionized gas velocity w.r.t. the\n%% envelop from HI. This envelop should be noted in the text and the\n%% figure caption. Explain why we might expect the ionized gas to lie\n%% below the HI envelop, i.e., we are measuring a centroid. What should\n%% the reader make of the few points in the upper part of the left\n%% panel that are above the HI envelope? Are these bad measuremets? Add\n%% error bars?\n\n%% Define AD -- you can reference Binney \\& Tremaine.\n\n%% Discuss what the soures of possible uncertainty could be in the\n%% stellar velocities. Is this a problem with the wavelength solution\n%% -- something that you come to in the next paragraph, or something\n%% else? Did you check that the wavelength solution and the BC03\n%% templates were either both in vacuum or air?\n\n%---------------------\n%% Lastly, concerning the use of the median, yes, maybe to to zeroth\n%% order the median difference should be zero, but not to a \\kms\n%% level. The median difference is going to depend on at least the\n%% number of points on the positive and negative sides of the galazy to\n%% zeroth order. To first order it will depend on the radial\n%% distribution particularly near the center where the projected\n%% velocity is small. Can you address this?}\n\n\\begin{figure}[t]\n \\centering\n \\includegraphics[width=\\columnwidth]{891_2/figs/SG_diff.pdf}\n \\caption[Offset between stellar and gas\n velocities]{\\fixspacing\\label{891_2:fig:SG_offset}Difference\n between stellar and gas velocities after applying a constant\n \\val{74}{\\kms} offset to the stars. A median of 1 corresponds to\n no average offset between the two population \\emph{across both\n sides of the galaxy}.}\n\\end{figure}\n\nFigure \\ref{891_2:fig:SG_offset} shows the relation between stellar\nand gas velocities after applying an offset of \\val{74}{\\kms}. This\noffset minimizes the global difference between gas and stellar\nvelocities across both sides of the galaxy. Based on these results,\nthe final velocity of each aperture is fixed as the velocity measured\nduring $\\chi^2$ fitting (``stellar velocity'') plus a constant offset\nof \\val{74}{\\kms}. The right hand panel of Figure\n\\ref{891_2:fig:Swat_vel} shows the final velocities used. We note that\nthe systematic correction of \\val{74}{\\kms} is within the total\nuncertainty in our velocity as dictated by uncertainties in the\nwavelength solution (\\val{120}{\\kms}, see Chapter \\ref{chap:891_1}).\n\n%+++++++++++++++++++=\n%% {\\bf MAB: The standard is km s$^{-1}$ not \\kms. At the end here you\n%% want to discuss the difference between the stars and gas in the left\n%% and right panels compared to each other and the HI envelop. For\n%% example, the asymmetry in the stars is not seen in the gas.}\n\n\\subsection{Extinction Model}\n\\label{891_2:sec:extinction}\n\nDuring all steps of full spectral fitting\n(\\S\\ref{891_2:sec:SSP_method}) we assume the extinction model of\n\\citet{Charlot00}, which is described by\n\\begin{equation}\nR(\\lambda) = e^{-\\tauV \\left(\\lambda/\\val{5500}{\\AA}\\right)^{-0.7}}.\n\\end{equation}\nThis model has a steeper slope than a simple foreground dust screen,\nbut the authors show it accurately reproduces the ratio of\nfar-infrared to ultraviolet luminosities, the ratio of \\Ha to \\HB\nluminosities, the \\Ha equivalent width, and the ultraviolet spectral\nslope of nearby starburst galaxies. We retain the functional\ndependence of $\\tau \\propto \\lambda^{-0.7}$ and define two\nnormalizations, one for gas emission and one for stellar\ncontinuum. Thus, the total optical depth to a particular species is\neither\n\\begin{equation}\n\\tau_{{\\rm cont}}(\\lambda) = \\tauV \\left(\\frac{\\lambda}{\\val{5500}{\\AA}}\\right)^{-0.7}\n\\end{equation}\nor\n\\begin{equation}\n\\label{891_2:eq:tauVB}\n\\tau_{{\\rm em}}(\\lambda) = \\tauVB \\left(\\frac{\\lambda}{\\val{5500}{\\AA}}\\right)^{-0.7},\n\\end{equation}\nwhere \\tauV and \\tauVB are the normalization factors for stellar continuum and\ngas emission, respectively.\n\nAs described in \\S\\ref{891_2:sec:SSP_method}, \\tauV is a free\nparameter of the SSP models that essentially measures the slope of the\ncontinuum. To measure \\tauVB (which we need to compute emission\ncorrections a la \\S\\ref{891_2:sec:emission_corr}) we use the ratio of\nmeasured \\Ha/\\HB flux and compare it to the expected value of 2.86\nfrom \\citet{Osterbrock89}, assuming case B recombination in a\n\\val{10^4}{K} gas. Under these assumptions, and given the extinction\nlaw in equation \\ref{891_2:eq:tauVB}, we compute\n\\begin{equation}\n\\label{891_2:eq:Balmer_extinction}\n\\tauVB = 4.84 \\ln \\left(\\frac{\\Ha/\\HB}{2.86}\\right).\n\\end{equation}\n\nThe \\Ha and \\HB line fluxes were measured using the IRAF task FITPROFS\nwhich allows us to deblend the \\Ha/[NII] emission feature. Before\nfitting the emission lines a ``best fit'' galaxy model is\nsubtracted. As in \\S\\ref{891_2:sec:vel} the detailed astrophysics of the\nbest fit model are unimportant; we only require that the model\naccurately match the stellar continuum so that it can be subtracted\nfrom the data. Once the continuum is subtracted the data are smoothed\nwith a 3 pixel (\\val{\\asim 350}{\\kms}) wide moving average. To\nmitigate the impact of bad continuum fits the centroid fitting window\nis constrained to be only $\\sim 4\\sigma$ wide, where $\\sigma$ is the\naverage spectral width (standard deviation) of bright sky emission\nlines.\n\n%++++++++++++++++++==\n%% {\\bf MAB: In the first sentence above do you mean SSP or SPS? I think\n%% the latter. Concerning the 600 \\kms wide moving average, is this\n%% equivalent to a boxcar of xx pixels? If so, you might say ``the data\n%% are smoothed with a 600 km s$^{-1}$ (XX pixel) wide moving average,\n%% or boxcar.'' Again, modify \\kms to km s$^{-1}$. However, I am not\n%% sure I understand the need for this smoothing and how it reduces the\n%% impact of bad continuum fits. Why? It seems to me you will make the\n%% NII+Ha blending worse which also sounds like it is a problem.}\n\nThe relative strength of the two [NII] lines in the \\Ha/[NII] complex\nis governed by quantum mechanics and we expect the flux ratio\n[NII]$_{6585}$/[NII]$_{6549} = 3$. When measuring the \\Ha/[NII] lines,\nhowever, we often find [NII]$_{6585}$/[NII]$_{6549} > 3$, which\nindicates that the line fit is attributing some of the [NII]$_{6549}$\nflux to \\Ha and causing the \\Ha flux to be overestimated. This is\nlikely due to an incorrect de-blending of the \\Ha and [NII]$_{6549}$\nlines. We correct for this effect by using the flux of [NII]$_{6585}$\nas a ``calibration'' flux (reasonable given its isolation, away from\nblending issues of \\Ha and [NII]$_{6549}$) and define an \\Ha\ncorrection,\n\\begin{equation}\n \\label{891_2:eq:balmer_corr}\n \\Delta\\Ha = \\mathrm{[NII]}_{6549} - \\frac{\\mathrm{[NII]}_{6585}}{3},\n\\end{equation}\nwhich is added to the measured \\Ha flux.\n\nAs mentioned above, measuring \\Ha and \\HB emission requires first correcting\nfor \\Ha and \\HB absorption present in the stellar continuum. In practice the\nentire process is iterative because fitting SSPs accurately requires accurate\nemission corrections (\\S\\ref{891_2:sec:emission_corr}), which, in turn, requires\naccurate extinction values. We find that the measured Balmer fluxes\nand derived emission corrections are stable after only a single\niteration.\n\n%+++++++++++++++\n%% {\\bf MAB: I would like to understand the issue with the imperfect\n%% continuum subtraction (in the sentence ``This is likely due...'')\n%% and how it alters the NII ratio. In this paragraph, leading up to\n%% the motivation for eqn 10 you want to say that the concept here is\n%% to trust the 6585 NII line because of its greater wavelength\n%% separation from Ha. However, you also need to address wy you think\n%% the continuum subtraction is better for 6585, i.e., why for some\n%% reason the baseline for this line isn't what is causing the problems\n%% with the ratio not equalling 3. \n\n%-----------------\n%% Further, you need to provide the\n%% amplitude of the correction which I expect will vary significatly\n%% with Ha line-strength and height (NII/Ha changes). So I'd like to\n%% know the \\% correction to the Ha flux in the mean (and/or median),\n%% and the trends with height, e.g., numbers for 0-0.4 kpc, 0.4-1 kpc,\n%% $>$1 kpc.}\n\n\\subsection{Emission Corrections}\n\\label{891_2:sec:emission_corr}\n\nMany of our apertures show moderate to strong Balmer emission that is\nnot present in the SSP libraries underlying our galaxy models and\ntherefore must be subtracted before accurate analyses can be made. To\ndo this we construct a model spectrum containing only emission from\n\\Ha, \\HB, \\Hg, \\Hd, and \\He. \n\nThe basic idea is to first construct a model galaxy produced from fits\nwhere the cores of the Balmer lines were masked. These fits will be\ngood first guesses of the stellar continuum in the absence Balmer\nemission. We then use these fits to remove the stellar continuum and\nisolate this emission. Then the two strongest emission lines (\\Ha and\n\\HB) can be used to construct a model containing emission from the\nhigher-order lines. Based on the results of \\citet{Osterbrock89}, and\nassuming case B recombination in a \\val{10^4}{K} gas, the ratios of\nfluxes for the Balmer series is \\mbox{1 : 0.350 : 0.164 : 0.087 :\n 0.056} (\\Ha : \\HB : \\Hg : \\Hd : \\He), thus if we know the flux in a\nsingle Balmer line we can construct a model containing all of these\nBalmer lines. In our emission models the width of each line is\ndictated by the instrumental resolution measured at the line location\n(see Chapter \\ref{chap:891_1}), with apertures made from different\nsized \\GP fibers having different widths.\n\n%++++++++++++++++++++=\n%% {\\bf MAB: First sentence: I think you mean SPS models (that use\n%% SSPs). I'd like you to explain the notion behind the approach in an\n%% explicit way. The notion is an important idea. The kernel of it is\n%% that Hydrogen Balmer Case B emission strength decreases sigificantly\n%% with higher order, e.g., by more than a factor of 10 between\n%% H$\\alpha$ and H$\\delta$. In contrast, the equivalent width of the\n%% Hydrogen Balmer absorption in stellar photospheres does not display\n%% this trend, and indeed H$\\alpha$ absorption EW is weaker than\n%% H$\\beta$. This contrast can be used to our advantage in an iterative\n%% scheme that first masks the cores of the Balmer absorption lines\n%% where the emission is present to provide a first-order estimate the\n%% continuuum. Once subtracted, only the two strongest emission lines\n%% are used to estimate the normalization of the emission and the\n%% attenuation, from which the remaining line-emission is estimated.}\n\n\\begin{figure}\n \\centering\n \\includegraphics[width=\\columnwidth]{891_2/figs/TauV_balm.pdf}\n \\caption[Height dependence of\n \\tauVB]{\\fixspacing\\label{891_2:fig:tauVB_height}Measured values\n of \\tauVB as a function of distance from the midplane. The error\n bars show the uncertainties reported by IRAF from 100 Monte Carlo\n noise iterations. The black shows a linear fit described in\n Equation \\ref{891_2:eq:tauVbalm}.}\n\\end{figure}\n\nThis idealized Balmer emission model is then extincted using Equation\n\\ref{891_2:eq:Balmer_extinction} based on the value of \\tauVB as measured in\nsection \\ref{891_2:sec:extinction}. To minimize the impact of aberrant\nextinction calculations we compute a height-dependent \\tauVB by\nfitting a line to the data from all apertures (and thus from all\nradii), as shown in Figure \\ref{891_2:fig:tauVB_height}. From these data it\nis clear that the radial dependence to the vertical trend in \\tauVB is\nminimal so our grouping of all radii is valid. We find for NGC 891\n\\begin{equation}\n\\label{891_2:eq:tauVbalm}\n \\tauVB (z) = -0.91 z + 4.15,\n\\end{equation}\nwhich allows us to compute the extinction in our Balmer emission\nmodels at any height above the midplane.\n\n%----------------------\n%% {\\bf MAB: Concerning Figure 3: Yuck. I can't tell if the line is a\n%% good fit to the data and whether there is a radial dependence. (You\n%% should say ``a radial dependence to the vertical trend.'') Clearly\n%% we see a radial trend in the stellar absorption later so this result\n%% is somewhat puzzling without some thought and\n%% interpretation. Regarding the figure itself, I'd like to see a\n%% version w/o the error bars. The error bars must be wrong because\n%% they are far larger than the scatter. I would also like to see\n%% moving averages for all pointings as well as for individual\n%% pointings.}\n\n\\begin{figure}\n \\centering\n \\includegraphics[width=\\columnwidth]{891_2/figs/emission_comp_zoom.pdf}\n \\caption[Spectra before and after Balmer emission\n correction]{\\fixspacing\\label{891_2:fig:emission_comp}An example\n of Balmer emission correction. The red and blue spectra show an\n aperture with strong Balmer emission (aperture P4.6) before and\n after the Balmer emission model described in\n \\S\\ref{891_2:sec:emission_corr} is applied.}\n\\end{figure}\n\nFinally, the emission model is scaled so the \\Ha flux matches the \\Ha\nflux measured in each individual aperture. The data spectra are then\ncorrected by subtracting the corresponding emission model. Figure\n\\ref{891_2:fig:emission_comp} shows an example of a spectrum with strong \\HB\nemission before and after subtracting the Balmer emission model.\n\nIn many apertures the blending of the \\Ha/[NII] complex causes\nimperfect subtraction in this region (as it should, our emission model\ndoes not contain [NII] emission), and in subsequent analysis we do not\nfit (i.e., mask) data within \\val{\\pm 500}{\\kms} of \\Ha (which\nincludes both [NII] lines). In addition to \\Ha/[NII] we mask other\nstrong sources of nebular emission ([OIII]$_{4959}$, [OIII]$_{5007}$,\nand S2) and sky lines with strong residuals ([OI]$_{6300}$, NaD, and\nOI$_{5577}$).\n\n%++++++++++++++++===\n%% {\\bf MAB: Itemize the lines that you mask -- all of them -- and give\n%% equivalent pixels to 500 \\kms at the wavelength extrama. For Figure\n%% 4 I can't see anything in this figure so I recommend you show\n%% blow-ups in wave for the Balmer lines from $\\alpha$ to $\\epsilon$.}\n\nAs mentioned above, the best-fit, extinction-value, emission-model\nanalysis steps are interconnected and at least one iteration is\nrequired to find the ``final'' values.\n\n\n", "meta": {"hexsha": "858490ab416a2490ae61896fca5030ef5942b4e6", "size": 26856, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "891_2/basic_anal.tex", "max_stars_repo_name": "eigenbrot/eigenbrot-thesis", "max_stars_repo_head_hexsha": "113dfb95996777e2b36785d7ee80a824a671ab09", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "891_2/basic_anal.tex", "max_issues_repo_name": "eigenbrot/eigenbrot-thesis", "max_issues_repo_head_hexsha": "113dfb95996777e2b36785d7ee80a824a671ab09", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "891_2/basic_anal.tex", "max_forks_repo_name": "eigenbrot/eigenbrot-thesis", "max_forks_repo_head_hexsha": "113dfb95996777e2b36785d7ee80a824a671ab09", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 50.7674858223, "max_line_length": 86, "alphanum_fraction": 0.7443029491, "num_tokens": 7131, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.30404168757891037, "lm_q1q2_score": 0.1591416062037421}} {"text": "% BEGIN LICENSE BLOCK\n% Version: CMPL 1.1\n%\n% The contents of this file are subject to the Cisco-style Mozilla Public\n% License Version 1.1 (the \"License\"); you may not use this file except\n% in compliance with the License. You may obtain a copy of the License\n% at www.eclipse-clp.org/license.\n% \n% Software distributed under the License is distributed on an \"AS IS\"\n% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See\n% the License for the specific language governing rights and limitations\n% under the License. \n% \n% The Original Code is The ECLiPSe Constraint Logic Programming System. \n% The Initial Developer of the Original Code is Cisco Systems, Inc. \n% Portions created by the Initial Developer are\n% Copyright (C) 2006 Cisco Systems, Inc. All Rights Reserved.\n% \n% Contributor(s): \n% \n% END LICENSE BLOCK\n\n\\chapter{The Eplex Library}\n\\label{chapeplex}\n%HEVEA\\cutdef[1]{section}\n\n\\section{Introduction}\n\nThe eplex library allows an external Mathematical Programming solver to be\nused by {\\eclipse}. It is designed to allow the external solver to be seen\nas another solver for {\\eclipse}, possibly in co-operation with\nthe existing `native' solvers of {\\eclipse} such as the {\\it ic\\/} solver. It is\nnot specific to a given external solver, with the differences between\ndifferent solvers (largely) hidden from the user, so that the user can\nwrite the same code and it will run on the different solvers.\n\nThe exact types of problems that can be solved (and methods to solve them)\nare solver dependent, but currently linear programming, mixed integer\nprogramming and quadratic programming problems can be solved.\n\nThe rest of this chapter is organised as follows: the remainder of this\nintroduction gives a very brief description of Mathematical Programming, which\ncan be skipped if the reader is familiar with the concepts. \nSection~\\ref{mpmodelling} demonstrates the modelling of an MP problem, and the\nfollowing section discusses some of the more advanced features of the library\nthat are useful for hybrid techniques.\n\n\\subsection{What is Mathematical Programming?}\n\\label{whatmp}\n\n\\index{Mathematical Programming (MP)}\n\\index{Linear Programming (LP)}\n\\index{Mixed Integer Programming (MIP)}\n\\index{optimisation (numerical)}\n\\index{objective function}\n\nMathematical Programming (MP) (also known as numerical optimisation) is the study of optimisation using\nmathematical/numerical techniques. A problem is modelled\nby a set of simultaneous equations: an\nobjective function that is to be minimised or maximised, subject to a set of\nconstraints on the problem variables, expressed as equalities and\ninequalities. \n\nMany subclasses of MP problems have found important practical\napplications. In particular, Linear Programming (LP)\nproblems and Mixed Integer Programming (MIP) problems are perhaps the most\nimportant. LP problems have both a linear objective function and linear\nconstraints. MIP problems are LP problems where some or all of the\nvariables are constrained to take on only integer values. \n\nIt is beyond the scope of this chapter to cover MP in\nany more detail. However, for most usages of the eplex library, the user\nneed not know the details of MP -- it can be treated as a black-box\nsolver.\n\n\\See{For more information on Mathematical Programming, you can read a\ntextbook on the subject such as H.~P.~Williams' {\\it Model Building in\nMathematical Programming} \\cite{Williams99}.}\n\n\\quickref{Classification of MP problems}{\n\n\\begin{itemize}\n\\item Linear Programming (LP) problems: linear constraints and objective\nfunction, continuous variables.\n\\item Mixed Integer Programming (MIP) problems: LP problems with some or\nall variables restricted to taking integral values.\n\\end{itemize}\n\n}\n\n\\subsection{Why interface to Mathematical Programming solvers?}\n\\label{whymp}\n\nMuch research effort has been devoted to developing efficient ways of\nsolving the various subclasses of MP problems for over 50 years. The\nexternal solvers are state-of-the-art implementations of some of these\ntechniques. The eplex library allows the user to model an MP problem in\nECLiPSe, and then solve the problem using the best available MP tools.\n\nIn addition, the eplex library allows for the user to write programs that\ncombines MP's global algorithmic solving techniques with the local\npropagation techniques of Constraint Logic\nProgramming. \n\n\\subsection{Example formulation of an MP Problem} \n\\begin{figure}\n\\begin{center}\n\\resizebox{0.5\\textwidth}{!}{\\includegraphics{tpprob.ps}}\n\\end{center}\n\\caption{An Example MP Problem}\n\\label{tpprob}\n\\end{figure}\n\nFigure~\\ref{tpprob} shows an example of an MP problem.\nIt is a transportation problem where \nseveral plants (1-3) have varying product producing capacities that must\nbe transported to various clients (A-D), each requiring various amounts of\nthe product. The per-unit cost of transporting the product to\nthe clients also varies. The problem is to minimise the transportation\ncost whilst satisfying the demands of the clients. \n\nTo formulate the problem, we define the amount of product transported from\na plant $N$ to a client $p$ as the variable $Np$, e.g.\\ $A1$\nrepresents the cost of transporting to plant $A$ from client $1$. There are\ntwo kinds of constraints:\n\n\\begin{itemize}\n\\item The amount of product delivered from all the plants to a client must be equal to the\nclient's demand, e.g.\\ for client A, which can recieve products from plants\n1-3: \\( A1 + A2 + A3 = 21 \\)\n\n\n\\item The amount of product sent by a plant must not be more than its\ncapacity, e.g. for plant 1, which can send products to plants A-D:\n\\(A1 + B1 + C1 + D1 \\leq 50 \\)\n\n\\end{itemize}\n\nThe objective is to minimise the transportation cost, thus the objective\nfunction is to minimise the combined costs of transporting the product to\nall 4 clients from the 3 plants.\n\n\nPutting everything\ntogether, we have the following formulation of the problem:\n\nObjective function:\n{\\small\n\\[\n\\min (10A1 + 7A2 + 200A3 + 8B1 + 5B2 + 10B3 + 5C1 + 5C2 + 8C3 + 9D1 + 3D2 + 7D3) \n\\]\n}\n\nConstraints:\n\n\\begin{eqnarray*}\nA1 + A2 + A3 & = & 21\\\\\nB1 + B2 + B3 & = & 40\\\\\nC1 + C2 + C3 & = & 34\\\\\nD1 + D2 + D3 & = & 10\\\\\nA1 + B1 + C1 + D1 & \\leq & 50\\\\\nA2 + B2 + C2 + D2 & \\leq & 30\\\\\nA3 + B3 + C3 + D3 & \\leq & 40\\\\\n\\end{eqnarray*}\n\n\\section{How to load the library}\n\nTo use the library, you must have an MP solver that eplex can use. This\ncan be an open-source solver such as the COIN-OR project's CLP/CBC solvers,\nwhich is distributed with ECLiPSe, or a commercial solver such as \nXPRESS-MP or CPLEX. Your {\\eclipse} should be configured to load in a\n`default' solver if there is more than one available. \n\n\\See{See the library\nmanual's Eplex chapter for details for how to install the solver.} \n\nWhen configured properly, the library can be loaded with the directive:\n\n\\begin{code}\n:- lib(eplex).\n\\end{code}\n\n\\noindent\nThis will load the library with the default external MP solver.\n\nYou probably need a valid license in order to use an external commercial solver.\n\n\\section{Modelling MP problems in {\\eclipse}}\n\\label{mpmodelling}\n\n\\subsection{Eplex instance}\n\nThe simplest way to model an eplex problem is through an {\\it eplex\ninstance}. Abstractly, it can be viewed as a solver module that is\ndedicated to one MP problem. MP constraints can be posted to the instance \nand the problem solved with respect to an objective function by the\nexternal solver.\n\nDeclaratively, an eplex instance can be\nseen as a compound constraint consisting of all the variables and\nconstraints of its eplex problem. Like normal constraints, different eplex\ninstances can share variables, although the individual MP constraints in\nan eplex instance do not necessarily have to be consistent with those in\nanother. \n\n\\quickref{Eplex Instance}{\n\nAn {\\bf eplex instance} represents a single MP problem in a\nmodule. Constraints for the problem are posted to the module. The\nproblem is solved with respect to an objective function.\n}\n\n\\subsection{Example modelling of an MP problem in {\\eclipse}}\n\n\\index{modelling, LP problem}\nThe following code models (and solves) the transportation problem of\nFigure~\\ref{tpprob}, using an eplex instance:\n\n{\\small\n\\begin{code}\n:- lib(eplex).\n\n:- eplex_instance(prob). % a. declare an eplex instance\n\nmain1(Cost, Vars) :-\n % b. create the problem variables and set their range\n Vars = [A1,A2,A3,B1,B2,B3,C1,C2,C3,D1,D2,D3], \n prob: (Vars \\$:: 0.0..1.0Inf),\n\n % c. post the constraints for the problem to the eplex instance\n prob: (A1 + A2 + A3 \\$= 21),\n prob: (B1 + B2 + B3 \\$= 40),\n prob: (C1 + C2 + C3 \\$= 34),\n prob: (D1 + D2 + D3 \\$= 10),\n\n prob: (A1 + B1 + C1 + D1 \\$=< 50),\n prob: (A2 + B2 + C2 + D2 \\$=< 30),\n prob: (A3 + B3 + C3 + D3 \\$=< 40),\n\n % d. set up the external solver with the objective function\n prob: eplex_solver_setup(min(\n 10*A1 + 7*A2 + 200*A3 + \n 8*B1 + 5*B2 + 10*B3 +\n 5*C1 + 5*C2 + 8*C3 + \n 9*D1 + 3*D2 + 7*D3)),\n\n %------------------------------- End of Modelling code\n\n prob: eplex_solve(Cost). % e. Solve problem using external solver\n\n\\end{code}\n}\n\nTo use an eplex instance, it must first be declared with \\verb'eplex_instance/1'. \nThis is usually done with a directive, as in line \\verb'a'.\nOnce\ndeclared, an eplex instance can be referred to using its name like a module\nqualifier.\n\nWe first create the problem\nvariables and set their range to be non-negative, as is conventional in MP.\nNote that the bounds are posted to our eplex instance, using \\verb'$::/2'.\n\\Note{The default bounds for variables is -1.0Inf..1.0Inf. Bounds posted to\n an eplex instance are specific to that eplex instance.}\n\nNext, we set up the MP constraints for the\nproblem by posting them to the eplex instance. \nThe MP constraints accepted by eplex are the arithmetic equalities and \ninequalities:\n\\verb'$=/2', \\verb'$==/2'.\n\\Note{The arithmetic constraints can be linear expressions on both\nsides. The restriction to linear\nexpressions originates from the external solver.}\n\\index{\\$=/2!eplex}\n\\index{\\$>=/2!eplex}\n\\index{\\$==/2, \\$== RelaxedCost), % RelaxedCost is lower bound \n\\end{code}}\n\\begin{figure}\n\\begin{center}\n\\resizebox{0.35\\textwidth}{!}{\\includegraphics{mipnode.ps}}\n\\end{center}\n\\caption{Labelling a variable at a MIP tree node}\n\\label{mipnode}\n\\end{figure}\nIn general, this initial LP solution contains non-integer assignments\nto integer variables. The objective value of this LP is a lower bound on\nthe actual MIP objective value.\nThe task of the search is to find integer assignments\nfor the integer variables that optimises the objective function. \nEach node of the\nsearch-tree solves the problem with extra bound constraints on these\nvariables. At each node, a particular variable is `labelled' as shown in\nFigure~\\ref{mipnode}. The integer variable in this case has been assigned\nthe non-integer value of 4.2. In the subsequent nodes of the tree, we\nconsider two alternate problems, which creates two branches in the search. In one\nproblem, we impose the bound constraint $X \\leq 4$, and in the other, $X\n\\geq 5$: these are the two nearest integer values to 4.2. In each branch,\nthe problem is solved\nagain as an LP problem with its new bound for the variable:\n\n{\\small\n\\begin{code}\nbranching(IntVars) :-\n ....\n % for each integer variable X which violates the integer constraint\n mip: eplex_var_get(X, solution, XVal),\n ...\n Split is floor(XVal),\n % choice: branch on the two ranges for X\n (mip: (X \\$=< Split) ; mip: (X \\$>= Split + 1)),\n mip: eplex_solve(RelaxedCost),\n ...% repeat until there are no integer violations\n\\end{code}}\n\nA choice-point for the two alternative branchings is created in the above\ncode, the problem is solved with one of the branchings (\\verb'X $=< Split').\nThe program then proceeds to further labelling of the variables. The\nalternative branch is left to be tried on backtracking.\n\n\nEventually, if the problem has a solution, all the integer\nvariables will be `labelled' with integer values, resulting in a solution to the\nMIP problem. However, this will generally not be optimal, and so the program\nneeds to backtrack into the tree to search for a better solution by trying\nthe other branches for the variables, using the\nexisting solution value as a bound.\nThis `branch-and-bound' search technique is implemented in {\\tt\nlib(branch_and_bound)}.\n\n\\quickref{Reminder: use {\\eclipse} libraries!}{Remember that {\\eclipse} provides\nlibraries that make some programming tasks much easier. There is no\nneed to write your own code when you can use what is\nprovided by an {\\eclipse} library.}\n\n\\begin{sloppypar}\nIn the code, the external solver is invoked explicitly at every node. This\nhowever may not be necessary as the imposed bound may already be satisfied.\nAs stated at the start of this section, the invocation of the solver could be done in a\ndata-driven way, more like a normal constraint.\nThis is done with \\verb'eplex_solver_setup/4':\n\\verb'eplex_solver_setup(+Obj,-ObjVal,+Options,+Trigs)', a more\npowerful version of \\verb'eplex_solver_setup/1' for setting up a\nsolver. The \\verb'Trigs' argument specifies a list of `trigger\nmodes' for triggering the solver. \\See{See the {\\eclipse} reference manual for a\ncomplete description of the predicate.}\n\\end{sloppypar}\n\n\\index{eplex\\_solver\\_setup/4}\nFor our example, we add a bound constraint at each node to exclude a\nfractional solution value for a variable. The criterion we want to use is\nto invoke the solver only if this old solution value is excluded by the new\nbounds (otherwise the external solver will solve the same problem\nredundantly). This is done by\nspecifying \\verb'deviating_bounds' in the trigger modes.\nThe full code that\nimplements a MIP solution for the\nexample transportation problem is given below: \n{\\small\n\\begin{code}\n:- lib(eplex).\n:- lib(branch_and_bound).\n\n:- eplex_instance(mip).\n\nmain6(Cost, Vars) :-\n % b. create the problem variables and set their range\n Vars = [A1,A2,A3,B1,B2,B3,C1,C2,C3,D1,D2,D3], \n mip: (Vars :: 0.0..1.0Inf),\n\n % c. post the constraints for the problem to the eplex instance\n mip: (A1 + A2 + A3 \\$= 21),\n mip: (B1 + B2 + B3 \\$= 40),\n mip: (C1 + C2 + C3 \\$= 34),\n mip: (D1 + D2 + D3 \\$= 10),\n\n mip: (A1 + B1 + C1 + D1 \\$=< 50),\n mip: (A2 + B2 + C2 + D2 \\$=< 30),\n mip: (A3 + B3 + C3 + D3 \\$=< 40),\n mip: (A1 \\$= A2),\n\n % j. post the objective function as a constraint \n ObjFunc = 10*A1 + 7*A2 + 200*A3 + \n 8*B1 + 5*B2 + 10*B3 +\n 5*C1 + 5*C2 + 8*C3 + \n 9*D1 + 3*D2 + 7*D3,\n mip: (ObjFunc \\$= Cost),\n\n % k. this is a more flexible method for setting up a solver.\n % [deviating_bounds] specifies that the external solver should be\n % invoked when any solution value is outside the variable bounds \n mip: eplex_solver_setup(min(ObjFunc), Cost, [], [deviating_bounds]),\n\n % l. Use the branch_and_bound library to do the branch and bound\n bb_min(( branching(Vars), \n mip: eplex_get(cost, Cost)\n (foreach(V, Vars) do mip: eplex_var_get(V,solution,V))\n ), Cost, _).\n\nbranching(IntVars) :-\n % Find a variable X which does not have an integer solution value\n (integer_violation(IntVars, X, XVal) ->\n % m. try the closer integer range first\n Split is round(XVal),\n (Split > XVal ->\n (mip: (X \\$>= Split) ; mip: (X \\$=< Split - 1))\n ;\n (mip: (X \\$=< Split) ; mip: (X \\$>= Split + 1))\n ),\n branching(IntVars)\n ;\n % cannot find any integer violations; found a solution\n true\n ).\n\n% returns Var with solution value Val which violates the integer constraint\ninteger_violation([X|Xs], Var, Val) :-\n mip: eplex_var_get(X, solution, RelaxedSol),\n % m. we are dealing with floats here, so need some `margin' for a\n % float value to be considered integer (1e-5 on either side)\n (abs( RelaxedSol - round(RelaxedSol) ) >= 1e-5 ->\n Var = X, Val = RelaxedSol\n ;\n integer_violation(Xs, Var, Val)\n ).\n\n\\end{code}}\n\nThe setup of the solver is done in line \\verb'k', with the use of the\n\\verb'deviating_bounds' trigger mode. There are no explicit calls to trigger the\nsolver -- it is triggered automatically. In addition, the first call to\n\\verb'eplex_solve/1' for an initial solution\nis also not required, because when trigger modes are specified, then\nby default, \\verb'eplex_solver_setup/4' will invoke the solver once the\nproblem is setup. \n\n\\begin{sloppypar}\nBesides the \\verb'deviating_bounds'\ntrigger condition, the other argument of interest in our use of\n\\verb'eplex_solver_setup/4' is the second argument,\nthe objective value of the problem (\\verb'Cost' in the example): \nrecall that this was returned previously by \\verb'eplex_solve/1'.\nUnlike in \\verb'eplex_solve/1', the variable is {\\it not\\/}\ninstantiated when the solver returns. Instead, one of the bounds (lower\nbound in the case of minimise) is updated\nto the optimal value, reflecting the range the objective value can take,\nfrom suboptimal to the `best' value at optimal. The variable is therefore\nmade a problem variable by posting of the objective as a constraint in line\n\\verb'j'. This informs the external solver needs to be informed\nthat the \\verb'Cost' variable is the objective value.\n\n\\end{sloppypar}\n\nIn line \\verb'm', the branch choice is created by the posting of the bound\nconstraint, which may trigger the external solver. Here, we use a\nsimple heuristic to decide which of the two branches to try first: the\nbranch with the integer range closer to the relaxed solution value.\nFor example, in the situation of Figure~\\ref{mipnode}, the branch with\n\\verb'X $=< 4' is tried first since the solution value of 4.2 is\ncloser to 4 than 5.\n\nBy using {\\it lib(branch_and_bound)\\/}'s \\verb'bb_min/3' predicate in \\verb'm', \nthere is no need to explicitly write our own branch-and-bound routine. However, \nthis predicate requires the cost variable to be instantiated, so we call\n\\verb'eplex_get(cost, Cost)' to instantiate \\verb'Cost' at the end of\neach labelling of the variables. We also get the solution values for the\nvariables, so that the branch-and-bound routine will remember it.\nThe final value returned in \\verb'Cost' (and {\\tt Vars} for the solution\nvalues) \nis the optimal value after the branch-and-bound search, i.e.\\ the\noptimal value for the MIP problem.\n\n\\quickref{More advanced modelling in eplex}{\n\\begin{itemize}\n\\item Use {\\bf\nInstance:eplex_solver_setup(+Obj,-ObjVal,+Opts,+Trigs)} to\nset up an external solver state for instance Instance. Trigs specifies a\nlist of trigger conditions to automatically trigger the external solver.\n\\item {\\bf Instance:eplex_var_get(+Var,+What,-Value)} can be used to obtain\ninformation for the variable {\\bf Var} in the eplex instance.\n\\item {\\bf Instance:eplex_get(+Item, -Value)} can be used to retrieve\ninformation about the eplex instance's solver state.\n\\end{itemize}\n}\n\\index{eplex\\_get/2}\n\nOf course, in practice, we do not write our own MIP solver, but \nuse the MIP solver provided with the external solvers instead. These\nsolvers are highly optimised and tightly coupled to their own LP solvers. \nThe techniques of solving relaxed subproblems described here are however\nvery useful for combining the external solver with other solvers in a\nhybrid fashion. \\See{See chapter~\\ref{chaphybrid} for more details on hybrid techniques.}\n\n\\section{Exercise}\n\nA company produces two types of products T1 and T2, which requires the\nfollowing resources to produce each unit of the product:\n\n\\vspace{3mm}\n\\begin{center}\n\\begin{tabular}{|r||r|r|}\\hline\nResource & T1 & T2\\\\ \\hline\nLabour (hours) & 9 & 6\\\\ \\hline\nPumps (units) & 1 & 1\\\\ \\hline\nTubing (m) & 12 & 16\\\\ \\hline\n\\end{tabular}\n\\end{center}\n\\vspace{3mm}\n\nThe amount of profit per unit of products are:\n\n\\begin{description}\n\\item[T1] \\pounds350\n\\item[T2] \\pounds300\n\\end{description}\n\nThey have the following resources available: 1566 hours of labour, 200\npumps, and 2880 metres of tubing.\n\n\n\n\\begin{enumerate}\n\\item Write a program to maximise the profit for the company, using eplex\nas a black box solver. Write a predicate that returns the profit and the\n values for T1 and T2.\n\n\\item What program change is required to answer this question:\n What profit can be achieved if exactly 150 units of T1 are required?\n\n\\item What would the profit be if fractional numbers of refrigerators could\n be produced?\n\n\\item Rewrite the program from (1) without optimize/2, using\n eplex_solver_setup/1, eplex_solve/1, and eplex_var_get/3.\n\n\\item In the program from (4), remove the integrality constraints (so that eplex\n only sees an LP problem). Solve the integer problem by interleaving\n solving of the LP problem with a rounding heuristic:\n\n\\begin{itemize}\n \\item solve the continuous relaxation\n \\item round the solution for T1 to the nearest integer and instantiate it\nInitially just return the maximum profit value.\n \\item re-solve the new continuous relaxation\n \\item round the solution for T2 to the nearest integer and instantiate it\n \\item re-solve the new continuous relaxation\n\\end{itemize}\n\n What is the result in terms of T1, T2 and Profit?\n \n\\item Rewrite the program from (5) using eplex_solver_setup/4 and automatic\n triggering of the solver instead of explicit calls to eplex_solve/1.\n The solver should be triggered whenever variables get instantiated.\n\\end{enumerate}\n\n%HEVEA\\cutend\n\n", "meta": {"hexsha": "913382391b832911cf1fa41513ecaaadca91def8", "size": 31629, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "usr/eclipseclp/documents/tutorial/eplex.tex", "max_stars_repo_name": "lambdaxymox/barrelfish", "max_stars_repo_head_hexsha": "06a9f54721a8d96874a8939d8973178a562c342f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 111, "max_stars_repo_stars_event_min_datetime": "2015-02-03T02:57:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T23:57:09.000Z", "max_issues_repo_path": "usr/eclipseclp/documents/tutorial/eplex.tex", "max_issues_repo_name": "lambdaxymox/barrelfish", "max_issues_repo_head_hexsha": "06a9f54721a8d96874a8939d8973178a562c342f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12, "max_issues_repo_issues_event_min_datetime": "2016-03-22T14:44:32.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-18T13:30:29.000Z", "max_forks_repo_path": "usr/eclipseclp/documents/tutorial/eplex.tex", "max_forks_repo_name": "lambdaxymox/barrelfish", "max_forks_repo_head_hexsha": "06a9f54721a8d96874a8939d8973178a562c342f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 55, "max_forks_repo_forks_event_min_datetime": "2015-02-03T05:28:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T05:00:03.000Z", "avg_line_length": 38.8085889571, "max_line_length": 119, "alphanum_fraction": 0.7206677416, "num_tokens": 8418, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44167299096624174, "lm_q2_score": 0.3593641451601019, "lm_q1q2_score": 0.15872143683888887}} {"text": "\\documentstyle[a4wide,12pt]{article}\n\n\\begin{document}\n\\section*{Introduction to numerical projects}\n\nHere follows a brief recipe and recommendation on how to write a report for each\nproject.\n\\begin{itemize}\n\\item Give a short description of the nature of the problem and the eventual \nnumerical methods you have used.\n\\item Describe the algorithm you have used and/or developed. Here you may find it convenient\nto use pseudocoding. In many cases you can describe the algorithm\nin the program itself.\n\n\\item Include the source code of your program. Comment your program properly.\n\\item If possible, try to find analytic solutions, or known limits\nin order to test your program when developing the code.\n\\item Include your results either in figure form or in a table. Remember to\n label your results. All tables and figures should have relevant captions\n and labels on the axes.\n\\item Try to evaluate the reliabilty and numerical stability/precision\nof your results. If possible, include a qualitative and/or quantitative\ndiscussion of the numerical stability, eventual loss of precision etc. \n\n\\item Try to give an interpretation of you results in your answers to \nthe problems.\n\\item Critique: if possible include your comments and reflections about the \nexercise, whether you felt you learnt something, ideas for improvements and \nother thoughts you've made when solving the exercise.\nWe wish to keep this course at the interactive level and your comments can help\nus improve it.\n\\item Try to establish a practice where you log your work at the \ncomputerlab. You may find such a logbook very handy at later stages\nin your work, especially when you don't properly remember \nwhat a previous test version \nof your program did. Here you could also record \nthe time spent on solving the exercise, various algorithms you may have tested\nor other topics which you feel worthy of mentioning.\n\\end{itemize}\n\n\n\n\\section*{Format for electronic delivery of report and programs}\n%\nThe preferred format for the report is a PDF file. You can also\nuse DOC or postscript formats. \nAs programming language we prefer that you choose between C/C++ and Fortran90/95.\nYou could also use Java or Python as programming languages. \nMatlab/Maple/Mathematica/IDL are not allowed as programming\nlanguages for the handins, but you can use them to check your results where possible.\nThe following prescription should be followed when preparing the report:\n\\begin{itemize}\n\\item Use Classfronter to hand in your projects, log in at \nblyant.uio.no and choose 'fellesrom fys3150 og fys4150'.\nThereafter you will see an icon to the left with 'hand in' or 'innlevering'.\nClick on that icon and go to the given project. \nThere you can load up the files within the deadline.\n\\item Upload {\\bf only} the report file and the source code file(s) you have developed.\nThe report file should include all of your discussions and a list of the codes you have developed. \nDo not include library files which are available at the course homepage, unless you have\nmade specific changes to them.\n\\item Comments from us on your projects, approval or not, corrections to be made \netc can be found under\nyour Classfronter domain and are only visible to you and the teachers of the course.\n \n\\end{itemize}\nFinally, \nwe do prefer that you work two and two together. Optimal working groups consist of \n2-3 students. You can then hand in a common report. \n\n\\section*{Project 1, deadline 19 september 12pm (midnight)}\n\nThe aim of this project is to get familiar with various matrix operations,\nfrom dynamic memory allocation to the usage of programs in the library\npackage of the course. \nFor Fortran users memory handling and most matrix and vector operations\nare included in the ANSI standard of Fortran 90/95. For C++ user however,\nthere are three possible options\n\\begin{enumerate}\n\\item Make your own functions for dynamic memory allocation of a \nvector and a matrix. Use then the \nlibrary package lib.cpp with its header file \nlib.hpp for obtaining LU-decomposed matrices, solve linear equations\netc.\n\\item Use the library package lib.cpp with its header file \nlib.hpp which includes a function \\verb?matrix? for dynamic memory\nallocation. This program package includes all the other functions\ndiscussed during the lectures for solving systems of linear equations,\nobatining the determinant, getting the inverse etc.\n\\item Finally, we provide on the web-page of the course a library package\nwhich uses Blitz++'s classes for array handling. You could then, since\nBlitz++ is installed on all machines at the lab, use these classes for handling\narrays.\n\\end{enumerate}\n\nYour program, whether it is written in C++ or Fortran 90/95, should include\ndynamic memory handling of matrices and vectors. \n\\begin{enumerate}\n\\item[(a)] \nConsider the linear system of equations \n%\n\\begin{eqnarray}\n a_{11}x_1 +a_{12}x_2 +a_{13}x_3 =&w_1 \\nonumber \\\\\na_{21}x_1 + a_{22}x_2 + a_{23}x_3=&w_2 \\nonumber \\\\\na_{31}x_1 + a_{32}x_2 + a_{33}x_3=&w_3. \\nonumber \n\\end{eqnarray}\nThis can be written in matrix form as\n\\[\n {\\bf Ax}={\\bf w}.\n\\]\nUse the included programs for LU decomposition to solve the system of equations\n\\begin{eqnarray}\n -x_1 +x_2 -4x_3 =&0 \\nonumber \\\\\n 2x_1 + 2x_2 =&1 \\nonumber \\\\\n3x_1 + 3x_2 + 2x_3=&\\frac{1}{2}. \\nonumber \n\\end{eqnarray}\nUse first standard Gaussian elimination and compute the result\nanalytically. Compare thereafter your analytical results with\nthe numerical ones obtained using the LU programs in the program library.\n\n\\item[(b)] \nConsider now the $4\\times 4$ linear system of equations \n%\n\\begin{eqnarray}\na_{11}x_1 +a_{12}x_2 +a_{13}x_3 + a_{14}x_4=&w_1 \\nonumber \\\\\na_{21}x_1 + a_{22}x_2 + a_{23}x_3 + a_{24}x_4=&w_2 \\nonumber \\\\\na_{31}x_1 + a_{32}x_2 + a_{33}x_3 + a_{34}x_4=&w_3 \\nonumber \\\\\na_{41}x_1 + a_{42}x_2 + a_{43}x_3 + a_{44}x_4=&w_4. \\nonumber\n\\end{eqnarray}\nwith \n\\begin{eqnarray}\n x_1 +2x_3 +x_4 =&2 \\nonumber \\\\\n4x_1 -9x_2 + 2x_3 + x_4=&14 \\nonumber \\\\\n8x_1 + 16x_2 + 6x_3 + 5x_4=&-3 \\nonumber \\\\\n2x_1 + 3x_2 + 2x_3 + x_4=&0. \\nonumber\n\\end{eqnarray}\nUse again standard Gaussian elimination and compute the result\nanalytically. Compare thereafter your analytical results with\nthe numerical ones obtained using the programs in the program library.\n\n\n\\item[(c)] If the matrix $A$ is real, symmetric and positive definite, then\nit has a unique factorization (called Cholesky factorization)\n\\[\n A = LU = LL^T\n\\]\nwhere $L^T$ is the upper matrix, implying that\n\\[\n L^T_{ij} = L_{ji}.\n\\]\nThe algorithm for the Cholesky decomposition\nis a special case of the general LU-decomposition algorithm.\nThe algorithm of this decomposition is as follows\n\\begin{itemize}\n\\item Calculate the diagonal element $L_{ii}$ by setting up a loop \nfor $i=0$ to $i=n-1$ (C++ indexing of matrices and vectors)\n\\begin{equation}\n L_{ii} = \\left(A_{ii} - \\sum_{k=0}^{i-1}L_{ik}^2\\right)^{1/2}.\n\\end{equation}\n%\n\\item within the loop over $i$, introduce a new loop which goes \nfrom $j=i+1$ to $n-1$ and calculate \n%\n\\begin{equation}\n L_{ji} =\n \\frac{1}{L_{ii}}\\left(A_{ij}-\\sum_{k=0}^{i-1}L_{ik}l_{jk}\\right).\n\\end{equation}\n\\end{itemize}\nFor the Cholesky algorithm we have always that $L_{ii} > 0$ and the problem\nwith exceedingly large matrix elements does not appear and hence there is no\nneed for pivoting.\nWrite a function which performs the Cholesky decomposition.\nTest your program against the standard LU decomposition by using the matrix\n\\begin{equation}\n {\\bf A} =\n \\left( \\begin{array}{ccc} 6 & 3 & 2 \\\\\n 3 & 2 & 1 \\\\\n 2 & 1 & 1 \n \\end{array} \\right)\n\\end{equation}\n\\item[(d)] Finally, use the Cholesky method to solve\n\\begin{eqnarray}\n 0.05x_1 +0.07x_2+0.06x_3 +0.05x_4 =&0.23 \\nonumber \\\\\n0.07x_1 +0.10x_2 + 0.08x_3 + 0.07x_4=&0.32 \\nonumber \\\\\n0.06x_1 + 0.08x_2 + 0.10x_3 + 0.09x_4=&0.33 \\nonumber \\\\\n0.05x_1 + 0.07x_2 + 0.09x_3 + 0.10x_4=&0.31 \\nonumber\n\\end{eqnarray}\nYou can also use the LU codes for linear equations to check the results. \n\\end{enumerate}\n\n\n\\end{document}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "3f2fcc61bca99c893707fb4a321a6cc5045bf4c1", "size": 8078, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/Projects/2015/Project1/FormerYears/project1.tex", "max_stars_repo_name": "kimrojas/ComputationalPhysicsMSU", "max_stars_repo_head_hexsha": "a47cfc18b3ad6adb23045b3f49fab18c0333f556", "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/2015/Project1/FormerYears/project1.tex", "max_issues_repo_name": "dnhdang94/ComputationalPhysicsMSU", "max_issues_repo_head_hexsha": "16990c74cf06eb5b933982137f0536d669567259", "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/2015/Project1/FormerYears/project1.tex", "max_forks_repo_name": "dnhdang94/ComputationalPhysicsMSU", "max_forks_repo_head_hexsha": "16990c74cf06eb5b933982137f0536d669567259", "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": 37.7476635514, "max_line_length": 99, "alphanum_fraction": 0.7458529339, "num_tokens": 2306, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. YES", "lm_q1_score": 0.30404167496654744, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.1579561329071493}} {"text": "\\documentclass[12pt,letterpaper]{article}\r\n\r\n%Packages\r\n\\usepackage{amsmath}\r\n\\usepackage{amsthm}\r\n\\usepackage{amsfonts}\r\n\\usepackage{amssymb}\r\n\\usepackage{amscd}\r\n\\usepackage{dsfont}\r\n\\usepackage{enumerate}\r\n\\usepackage{fancyhdr}\r\n\\usepackage{mathrsfs}\r\n\\usepackage{bbm}\r\n\\usepackage{framed}\r\n\\usepackage{mdframed}\r\n\\usepackage{cancel}\r\n\\usepackage{float}\r\n\\usepackage{mathtools}\r\n%\\usepackage[]{mcode}\r\n\\usepackage{graphicx}\r\n\\usepackage{tikz}\r\n\r\n%Page formatting\r\n\\usepackage[letterpaper,voffset=-.5in,bmargin=3cm,footskip=1cm]{geometry}\r\n\\setlength{\\parindent}{0.0in}\r\n\\setlength{\\parskip}{0.1in}\r\n\\allowdisplaybreaks\r\n\\headheight 15pt\r\n\\headsep 10pt\r\n\r\n% Common Commands\r\n\\newcommand\\N{\\mathbb N}\r\n\\newcommand\\Z{\\mathbb Z}\r\n\\newcommand\\R{\\mathbb R}\r\n\\newcommand\\Q{\\mathbb Q}\r\n\\newcommand\\lcm{\\operatorname{lcm}}\r\n\\newcommand\\setbuilder[2]{\\ensuremath{\\left\\{#1\\;\\middle|\\;#2\\right\\}}}\r\n\\newcommand\\E{\\operatorname{E}}\r\n\\newcommand\\V{\\operatorname{V}}\r\n\\newcommand\\Pow{\\ensuremath{\\operatorname{\\mathcal{P}}}}\r\n\r\n\\DeclarePairedDelimiter\\ceil{\\lceil}{\\rceil}\r\n\\DeclarePairedDelimiter\\floor{\\lfloor}{\\rfloor}\r\n\r\n% 22 style\r\n\\newcommand\\hint[1]{\\textbf{Hint}: #1}\r\n\\newcommand\\note[1]{\\textbf{Note}: #1}\r\n\\newenvironment{22enumerate}{\\begin{enumerate}[a.]\\itemsep0em}{\\end{enumerate}}\r\n\\newenvironment{22itemize}{\\begin{itemize}\\itemsep0em}{\\end{itemize}}\r\n\\fancypagestyle{firstpagestyle} {\r\n \\renewcommand{\\headrulewidth}{0pt}%\r\n \\lhead{\\textbf{CSCI 0220}}%\r\n \\chead{\\textbf{Discrete Structures and Probability}}%\r\n \\rhead{Klivans}%\r\n}\r\n\r\n\\pagestyle{fancyplain}\r\n\r\n\\newcommand\\EX{\\mathds{E}}\r\n\\newcommand\\PR{\\mathds{P}}\r\n\\newcommand\\zlam{Z_\\lambda}\r\n\\DeclareMathOperator*{\\argmin}{arg\\,min}\r\n\r\n%%%%%%%%%%%%%%%% COMPILE WITH \\soltrue or \\solfalse %%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\\newif\\ifsol\r\n\\soltrue % SOLUTIONS\r\n\\solfalse % NO SOLUTIONS\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n\r\n%%%%%%%%%%%%%%%% solution help %%%%%%%%%%%%%%%%%%%%%\r\n\\newcommand{\\solu}[2]{ \\begin{mdframed} \\ifsol #2 \\else \\vspace{#1} \\fi \\end{mdframed} }\r\n\\newcommand{\\solt}{ \\ifsol (T) \\fi }\r\n\\newcommand{\\solf}{ \\ifsol (F) \\fi }\r\n\\newcommand{\\solm}[1]{\\ifsol \\textit{(#1)} \\fi}\r\n\r\n\\begin{document}\r\n \\thispagestyle{firstpagestyle}\r\n \\begin{center}\r\n {\\large \\textbf{Recitation 4}}\r\n \r\n {\\large Induction and Algorithms}\r\n \\end{center}\r\n \r\n \\section*{Review}\r\n\r\n We will review the template for an inductive proof.\r\n\r\n For example, say we are trying to prove that $\\sum_{i=0}^n i = \\frac{n(n+1)}{2}$ is true for all $n \\in \\N$. \r\n\r\n \\begin{enumerate}\r\n \\item Define the predicate $P(n)$.\r\n\r\n \\textit{Let $P(n)$ be the predicate that $\\sum_{i=0}^n i = \\frac{n(n+1)}{2}$.}\r\n\r\n \\item Show that the base case is true.\r\n\r\n \\textit{We will first show $P(0)$ is true. $\\sum_{i=0}^0 i = 0$ and $\\frac{0(0+1)}{2} = 0$ so they are equal as needed.}\r\n\r\n \\item Assume the inductive hypothesis is true. If you are using stardard induction then you will assume \r\n\t\t\t$P(k)$ is true for some integer $k$. If you are using strong induction then you will assume $P(i)$ is true for all $i \\leq k$.\r\n\r\n \\textit{Assume $P(k)$ is true for some integer $k$.}\r\n\r\n \\item Show that $P(k+1)$ is true given the inductive hypothesis.\r\n\r\n\t\t\\textit{We will now show that $\\sum_{i=0}^{k+1} i = \\frac{(k+1)(k+2)}{2}$}.\r\n\r\n \t\\textit{We know that $\\sum_{i=0}^{k+1} i = \\left( \\sum_{i=0}^{k} i \\right)+ (k+1)$.}\r\n\r\n\t\t\\textit{By our inductive hypothesis $\\sum_{i=0}^k i = \\frac{k(k+1)}{2}$.}\r\n\r\n \\textit{Therefore}\r\n\t\t\\begin{align*}\r\n\t\t\t\\sum_{i=0}^{k+1} i &= \\left( \\sum_{i=0}^{k} i \\right)+ (k+1) \\\\\r\n\t\t\t&= \\frac{k(k+1)}{2} + (k+1) \\\\\r\n\t\t\t&= \\frac{k(k+1) + 2(k+1)}{2} \\\\\r\n\t\t\t&= \\frac{(k+1)(k+2)}{2}\r\n\t\t\\end{align*}\r\n\t\t\\textit{as needed.}\\qed\r\n\r\n\t\\subsection*{Warm-up}\r\n\r\n \\begin{22enumerate}\r\n\r\n \\item\r\n Prove by induction that for all positive integers $n$, there exists a \r\n positive integer $m$ such that:\r\n \\[m^2 \\leq n < (m + 1)^2\\]\r\n\r\n\t\\hint{The inductive step may contain two cases.}\r\n\r\n\t\\solu{17cm}{ Let $P(k)$ denote the property that there exists a positive integer \r\n $m$ such that $m^2 \\leq k < (m + 1)^2$. \r\n\r\n Construct a proof by induction.\r\n\r\n \\textbf{Base Case:} Consider $k = 1$.\r\n\r\n Let $m = 1$. Then $m^2 = 1$ and $(m + 1)^2 = 4$, so \r\n $m^2 \\leq k <(m + 1)^2$. Thus $P(1)$ holds.\r\n\r\n \\textbf{Inductive Hypothesis:}\r\n\r\n Assume $P(k)$ is true for some positive integer $k$.\r\n\r\n \\textbf{Inductive Step:} Consider $n = k+1$. \r\n\r\n By the inductive hypothesis, there exists a positive integer $m$ \r\n such that $m^2 \\leq k < (m + 1)^2$. \r\n\r\n There are two cases:\r\n \\begin{22enumerate}\r\n\r\n \\item \\textbf{Case 1:} $k + 1 < (m + 1)^2$. Then we can define \r\n $m_* = m$, and it holds that $m_*^2 \\leq k + 1 < (m_* + 1)^2$. \r\n\r\n \\item \\textbf{Case 2:} $k + 1 = (m + 1)^2$. Then we can define \r\n $m_* = m + 1$. Then $k + 1 = (m + 1)^2 < ((m + 1) + 1)^2$, so \r\n $k + 1 < (m_* + 1)^2$.\r\n Since $k + 1 = (m + 1)^2$, $k + 1 = m_*^2$, so it is true that \r\n $m_*^2 \\leq k + 1 < (m_* + 1)^2$.\r\n\r\n \\end{22enumerate}\r\n\r\n Because $k < (m + 1)^2$ and $k$ and $m$ are integers, then \r\n $k + 1 \\ngtr (m + 1)^2$, so these are the only two cases.\r\n\r\n In either case, we found an integer $m_*$ such that \r\n $m_*^2 \\leq k + 1 < (m_* + 1)^2$. Thus $P(k + 1)$ is correct.\r\n\r\n Thus $P(k)$ implies $P(k + 1)$.\r\n\r\n Since $P(1)$ is true, and since for all positive integers $k$, \r\n $P(k)$ implies $P(k+1)$, then by standard induction, $P(n)$ is true for \r\n all positive integers $n$.\r\n\r\n Thus, for all positive integers $n$, there exists a positive integer \r\n $m$ such that $m^2 \\leq n < (m + 1)^2$.}\r\n\t\r\n\t\t\\pagebreak\r\n\r\n \\item\r\n Prove by contradiction that there exists a \\textbf{unique} such $m$.\r\n\r\n\t \\solu{17cm}{ We prove by contradiction. Assume that for some positive integer \r\n $n$, there exist two unique positive integer solutions \r\n $m_1 \\neq m_2$ such that $m^2 \\leq n < (m + 1)^2$. Without loss \r\n of generality, assume $m_2 > m_1$. Then $m_2 \\geq m_1 + 1$. \r\n Because both sides of the equation are non-negative, we can square \r\n both sides of this equation to get $m_2^2 \\geq (m_1 + 1)^2$.\r\n\r\n By our assumption, we also know that $m_2^2 \\leq n$ and that \r\n $n < (m_1 + 1)^2$. $m_2^2 \\leq n < (m_1 + 1)^2$, so \r\n $m_2^2 < (m_1 + 1)^2$. \r\n\r\n But this is a contradiction, because $m_2^2 \\geq (m_1 + 1)^2$. Thus \r\n our assumption was false.\r\n\r\n Thus, for all positive integers $n$, there can exist only one unique \r\n integer $m$ such that $m^2 \\leq n < (m + 1)^2$. \r\n\r\n From part a, we know that a solution exists for all positive \r\n integers $n$. Thus, for all positive integers $n$, there exists \r\n exactly one unique integer $m$ such that $m^2 \\leq n < (m + 1)^2$.}\r\n\r\n \\end{22enumerate}\r\n\r\n\t\\textbf{Checkpoint - Call a TA over}\r\n\r\n \\end{enumerate}\r\n\r\n\t\\section*{Section Lesson - Algorithms}\r\n\r\n\t\\subsection*{Why does induction work?}\r\n\r\n\tYou can think of induction as a ladder. We want to prove that we can reach every step of the ladder.\r\n\r\n\tThe base case says that we can reach the first step of the ladder.\r\n\r\n\tThe inductive hypothesis says that we can get to the $k^{\\text{th}}$ step of the ladder.\r\n\r\n\tThe inductive step says that if we can get to the $k^{\\text{th}}$ step of the ladder, then we can get to step $k+1$. \r\n\r\n\tTherefore, once we get to step 1, we can get to step 2. Once we get to step 2, we can get to step 3. And so on for all steps of the ladder.\r\n\r\n\t\\subsection*{Induction for algorithms}\r\n\t\r\n\tInduction can also be used to prove the correctness of algorithms. An algorithm is simply a series of steps. \r\n\r\n\tConsider the following $SORT$ algorithm which operates on a list of length $n$.\r\n\t\\begin{enumerate}\r\n\t\t\\item If $n=1$ do nothing as the list is already sorted.\r\n\t\t\\item Find the smallest element in the list and remove it.\r\n\t\t\\item Run the $SORT$ algorithm on the remaining $n-1$ elements.\r\n\t\t\\item Put the smallest element at the begining of the list. \r\n\t\\end{enumerate}\r\n\r\n\tWe can now prove that $SORT$ correctly sorts a list of size $n$ for $n \\geq 1$. \r\n\t\r\n\r\n \\textit{Base case: $SORT$ does nothing on a list of size 1, which is already sorted.} \r\n\r\n \\textit{Inductive hypothesis: Assume $SORT$ correctly sorts a list of size $k$.}\r\n\r\n\t \\textit{Inductive step: We will now show that $SORT$ correctly sorts a list of size $k+1$. In step 3, we are left with a list of size $k$. By our inductive hypothesis, $SORT$ correctly sorts this sublist. Therefore, when we put the smallest element (which we have removed) at the begining, our list is completely sorted as needed.}\\qed\r\n\r\nYour turn.\r\n\r\n\\textbf{Given a stack of pancakes, you can stick your spatula in between any two\r\npancakes, and flip the stack of pancakes above the spatula upside-down. Find an algorithm\r\nto sort $n$ pancakes from largest to smallest, using at most $2n$ flips. Prove it is correct.}\r\n\r\n\\solu{18cm}{The algorithm is to always find the largest pancake, flip it to the top, then flip the whole stack so the largest pancake is on the bottom. After this proceed recursively on all but the largest pancake. The proof for why this is correct is identical to the proof for $SORT$ given above.}\r\n\r\n\\textbf{Checkpoint - Call a TA over}\r\n\r\n\\pagebreak\r\n\r\n\\textbf{Consider the following inductive proof}\r\n\r\n\r\n\r\nClaim: All $n$ people in the room have the same eye color.\r\n\\begin{proof} \r\n\r\nBase case: When $n=1$ clearly everyone in the room has the same eye color as there is only one person in the room.\r\n\r\nInductive Hypothesis: Assume that in a room of $k$ people, everyone in the room has the same eye color.\r\n\r\nInductive Step: We will now show that in a room of $k+1$ people everyone has the same eye color.\r\n\r\nWe know from our inductive step that the first $k$ people in the room have the same eye color, and that the last $k$ people in the room have the same eye color. Since there is some overlap between the first $k$ people and the last $k$ people, everyone in the room must have the same eye color.\r\n\\end{proof}\r\n\r\n\\textbf{Can you find the flaw in this proof?}\r\n\r\n\\solu{10cm}{The inductive step does not work for 2 people.}\r\n\r\n\\pagebreak\r\n\r\n\\textbf{Challlenge 1:}\r\n100 dragons are sitting in a circle so that every dragon can see every other dragon.\r\n\r\nEvery dragon has green eyes, but the dragons don't know this. No dragon knows its own eye color, and the dragons cannot talk.\r\n\r\nBen comes and tells the circle of dragons that at least one of them has green eyes. \r\n\r\nIf a dragon knows it has green eyes, it will turn into a human at midnight. \r\n\r\nProve that on night 100, all dragons will turn into humans at once. \r\n\r\n\\hint{Use induction! What is the base case? Ignore the number 100 and instead consider $n$ dragons and show they turn into humans on the $n^{\\text{th}}$ night.}\r\n\r\n\r\n\\solm{If there is only one dragon, it takes her one night to turn into a human. Now assume it takes $k$ nights for $k$ dragons. Consider the case where there is $k+1$ dragons and consider what one individual dragon is thinking. This one dragon sees $k$ dragons with green eyes. Therefore, if this dragon does not have green eyes, she would expect the other dragons to turn into humans after $k$ night since they can see her. Since they don't, this dragon realizes that she also has green and turns into a dragon on night $k+1$.}\r\n\r\n\\vspace{6cm} \r\n\\textbf{Challenge 2:}\r\nWe say that an infinite set $S$ is countable if there exists a bijection from $\\N$ to $S$. Giventhat $\\N \\times \\N$ is countable, prove by induction that $\\N^k$ is countable where $k \\in \\N$.\r\n\r\n\\solm{$\\N^k$ is countable so there exists a bijection $f_k$. We can now make a bijection $g_{k+1}$ from $\\N^{k+1}$ to $\\N \\times \\N$. $g_{k+1} ((x_1,...,x_{k+1})) = (f_k(x_1,...,x_k),x_{k+1})$.}\r\n \r\n\r\n\\end{document}", "meta": {"hexsha": "730e6700caca9c04d876da2cc1c8614e67d05446", "size": 12113, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "assets/notes/cs22/s3_induction_and_algorithms/induction_and_algorithms.tex", "max_stars_repo_name": "mitchellnw/mitchellnw.github.io", "max_stars_repo_head_hexsha": "4bbfa50bebd29e804ff45794a888abd9aadd41c8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "assets/notes/cs22/s3_induction_and_algorithms/induction_and_algorithms.tex", "max_issues_repo_name": "mitchellnw/mitchellnw.github.io", "max_issues_repo_head_hexsha": "4bbfa50bebd29e804ff45794a888abd9aadd41c8", "max_issues_repo_licenses": ["MIT"], "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/notes/cs22/s3_induction_and_algorithms/induction_and_algorithms.tex", "max_forks_repo_name": "mitchellnw/mitchellnw.github.io", "max_forks_repo_head_hexsha": "4bbfa50bebd29e804ff45794a888abd9aadd41c8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.8453947368, "max_line_length": 529, "alphanum_fraction": 0.6369190126, "num_tokens": 3796, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4416730056646256, "lm_q2_score": 0.35577487985229833, "lm_q1q2_score": 0.15713616052433566}} {"text": "%\\subsection{DFT-based transfer integrals using DIPRO}\n\\label{sec:dft}\n\\index{electronic coupling!DFT}\n% While the use of the semiempirical ZINDO method provides an efficient on-the-fly technique to determine electronic coupling elements, it is not generally applicable to all systems. For instance, its predictive capacity with regards to atomic composition and localization behavior of orbitals within more complex structures is reduced. Moreover, transition- or semi-metals are often not even parametrized. In this case, {\\it ab-initio} based approaches, e.g., density-functional theory can remedy the situation~\\cite{huang_intermolecular_2004,huang_validation_2005,valeev_effect_2006,yin_balanced_2006,yang_theoretical_2007,baumeier_density-functional_2010}. \n\nThe calculation of one electronic coupling element requires the overlap matrix of atomic orbitals $\\matr{\\mathcal{S}}$, the expansion coefficients for monomer $\\vctr{\\boldsymbol{\\lambda}}_{(k)} = \\{ \\lambda_\\alpha^{(k)}\\}$ and dimer orbitals $\\vctr{D}_{(n)} = \\{ D^{(n)}_{\\alpha} \\}$, as well as the orbital energies $E_{n}$ of the dimer are required as input. In practical situations, performing self-consistent quantum-chemical calculations for each individual monomer and one for the dimer to obtain this input data is extremely demanding. Several simplifications can be made to reduce the computational effort, such as using non-Counterpoise basis sets for the monomers (thereby decoupling the monomer calculations from the dimer run) and performing only a single SCF step in a dimer calculation starting from an initial guess formed from a superposition of monomer orbitals. This ''noCP+noSCF'' variant of \\dipro is shown in \\fig{dipro_scheme}(a) and recommended for production runs. \nA detailed comparative study of the different variants can be found in~\\cite{baumeier_density-functional_2010}.\n\nThe code currently contains supports evaluation of transfer integrals from quantum-chemical calculations performed with the \\gaussian, \\turbomole, and \\nwchem packages. The interfacing procedure consists of three main steps: generation of input files for monomers and dimers, performing the actual quantum-chemical calculations, and calculating the transfer integrals. \n\n\\subsubsection{Monomer calculations}\n\\label{sec:edft}\nFirst, \\slink{sec:segments}{hopping sites} and a \\slink{sec:neighborlist}{neighbor list} need to be generated from the atomistic topology and trajectory and written to the \\sqlstate file. Then the parallel \\calc{edft} \\calculator manages the calculation of the monomer properties required for the determination of electronic coupling elements. Specifically, the individual steps it performs are:\n%\n\\begin{enumerate}\n\\item Creation of a job file containing the list of molecules to be calculated with DFT \n\\votcacommand{Writing job file for \\calc{edft}}{\\ctpparallel \\opt \\xmloptions \\sql \\sqlstate \\exe \\calc{edft} \\job \\wrt }\n\\item Running of all jobs in job file \n\\votcacommand{Running all \\calc{edft} jobs}{\\ctpparallel \\opt \\xmloptions \\sql \\sqlstate \\exe \\calc{edft} \\job \\run }\nwhich includes\n\\begin{itemize}\n\\item creating the input files for the DFT calculation (using the package specified in \\xmloptions) in the directory \n\\begin{verbatim}\nOR_FILES/package/frame_F/mol_M\n\\end{verbatim}\nwhere {\\tt F} is the index of the frame in the trajectory, {\\tt M} is the index of a molecule in this frame,\n\\item executing the DFT run, and\n\\item after completion of this run, parsing the output (number of electrons, basis set, molecular orbital expansion coefficients), and saving it in compressed form to \n\\begin{verbatim}\n OR_FILES/molecules/frame_F/molecule_M.orb \n\\end{verbatim}\n\\end{itemize}\n\\end{enumerate}\n\n\n\\subsubsection{Calculating the transfer integrals}\n\\label{sec:idft}\nAfter the momomer calculations have been completed successfully, the respective runs for dimers from the neighborlist can be performed using the parallel \\calc{idft} \\calculator, which manages the DFT runs for the hopping pairs and determines the coupling element using \\dipro. Again, several steps are required:\n\\begin{enumerate}\n\\item Creation of a job file containing the list of pairs to be calculated with DFT \n\\votcacommand{Writing job file for \\calc{idft}}{\\ctpparallel \\opt \\xmloptions \\sql \\sqlstate \\exe \\calc{idft} \\job \\wrt }\n\\item Running of all jobs in job file \n\\votcacommand{Running all \\calc{idft} jobs}{\\ctpparallel \\opt \\xmloptions \\sql \\sqlstate \\exe \\calc{idft} \\job \\run }\nwhich includes\n\\begin{itemize}\n\\item creating the input files (including the merged guess for a noSCF calculation, if requested) for the DFT calculation (using the package specified in \\xmloptions) in the directory \n\\begin{verbatim}\nOR_FILES/package/frame_F/pair_M_N\n\\end{verbatim}\nwhere {\\tt M} and {\\tt N} are the indices of the molecules in this pair,\n\\item executing the DFT run, and\n\\item after completion of this run, parsing the output (number of electrons, basis set, molecular orbital expansion coefficients and energies, atomic orbital overlap matrix), and saving the pair information in compressed form to\n\\begin{verbatim}\n OR_FILES/pairs/frame_F/pair_M_N.orb \n\\end{verbatim}\n\\item loading the monomer orbitals from the previously saved {\\tt *.orb files}.\n\\item calculating the coupling elements and write them to the job file\n\\end{itemize}\n\\item Reading the coupling elements from the job file and saving them to the \\sqlstate file\n\\votcacommand{Saving \\calc{idft} results from job file to \\sqlstate}{\\ctpparallel \\opt \\xmloptions \\sql \\sqlstate \\exe \\calc{idft} \\job \\rd }\n\\end{enumerate}\n\n\n\n\n", "meta": {"hexsha": "6587234483d7712aa707c48d5f8faa4f9da6539a", "size": 5576, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "manual/theory/dft.tex", "max_stars_repo_name": "jimbach/ctp", "max_stars_repo_head_hexsha": "e5b33f074f81c6e6859dfaacada1b6c992c67c2b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "manual/theory/dft.tex", "max_issues_repo_name": "jimbach/ctp", "max_issues_repo_head_hexsha": "e5b33f074f81c6e6859dfaacada1b6c992c67c2b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "manual/theory/dft.tex", "max_forks_repo_name": "jimbach/ctp", "max_forks_repo_head_hexsha": "e5b33f074f81c6e6859dfaacada1b6c992c67c2b", "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.4848484848, "max_line_length": 989, "alphanum_fraction": 0.7944763271, "num_tokens": 1380, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.29746995506106744, "lm_q1q2_score": 0.15686082251267816}} {"text": "% Define document class\n\\documentclass[twocolumn]{aastex63}\n\\DeclareRobustCommand{\\Eqref}[1]{Eq.~\\ref{#1}}\n\\DeclareRobustCommand{\\Figref}[1]{Fig.~\\ref{#1}}\n\\DeclareRobustCommand{\\Tabref}[1]{Tab.~\\ref{#1}}\n\\DeclareRobustCommand{\\Secref}[1]{Sec.~\\ref{#1}}\n\\newcommand{\\todo}[1]{{\\large $\\blacksquare$~\\textbf{\\color{red}[#1]}}~$\\blacksquare$}\n% \\usepackage{cuted}\n\\usepackage{flushend}\n\\usepackage{amsmath}\n\\graphicspath{{./figures/}}\n\n\\begin{document}\n\n% Title\n\\title{Pair-instability mass loss for top-down compact object mass calculations}\n\n\\author[0000-0002-6718-9472]{M.~Renzo}\n\\affiliation{Center for Computational Astrophysics, Flatiron Institute, New York, NY 10010, USA}\n\\affiliation{Department of Physics, Columbia University, New York, NY 10027, USA}\n\n\\author[0000-0002-8717-6046]{D.~D.~Hendriks}\n\\affiliation{Department of Physics, University of Surrey, Guildford, GU2 7XH, Surrey, UK}\n\n\\author[0000-0001-5484-4987]{L.~A.~C.~van~Son}\n\\affiliation{Center for Astrophysics $|$ Harvard $\\&$ Smithsonian,60 Garden St., Cambridge, MA 02138, USA}\n\\affiliation{Anton Pannekoek Institute for Astronomy, University of Amsterdam, Science Park 904, 1098XH Amsterdam, The Netherlands}\n\\affiliation{Max-Planck-Institut für Astrophysik, Karl-Schwarzschild-Straße 1, 85741 Garching, Germany}\n\n\\author[0000-0003-3441-7624]{R.~Farmer}\n\\affiliation{Max-Planck-Institut für Astrophysik, Karl-Schwarzschild-Straße 1, 85741 Garching, Germany}\n\n\\begin{abstract}\n \\noindent\n Population synthesis relies on semi-analytic formulae to determine\n masses of compact objects from the (helium or carbon-oxygen) cores\n of collapsing stars. Such formulae are combined across mass ranges\n that span different explosion mechanisms, potentialy introducing\n artificial features in the compact object mass distribution. Such\n artifacts impair the interpretation of gravitational-wave\n observations. We propose a ``top-down'' remnant mass prescription\n where we remove mass from the star for each possible mass-loss\n mechanism, instead of relying on the fallback onto a\n ``proto-compact-object'' to get the final mass. For one of these\n mass-loss mechanisms, we fit the metallicity-dependent mass lost to\n pulsational-pair instability supernovae from numerical\n simulations. By imposing no mass loss in the absence of pulses, our\n approach recovers the existing compact object masses at the low mass\n end and ensures continuity across the\n core-collapse/pulsational-pair-instability regime. % Our remnant mass\n % prescription can be extended\n % to include other mass-loss mechanisms at the final collapse.\\\\\n\\end{abstract}\n\n\\section{Introduction}\n\nStellar and binary population synthesis calculations are necessary to\npredict event rates and population statistics of astrophysical\nphenomena, including those involving neutron stars (NS) and\nblack holes (BH). Typically, at the end of the evolution (carbon\ndepletion) the mass of the core is mapped to a compact object mass, using a\n$M_\\mathrm{comp.\\ obj}\\equiv M_\\mathrm{comp.\\ obj}(M_\\mathrm{core})$\ninformed by core-collapse (CC) simulations (e.g., \\citealt{fryer:12,\n spera:15, mandel:20, couch:20}, see also \\citealt{zapartas:21,\n patton:21}) and/or (pulsational) pair instability (PPI) simulations\n(e.g., \\citealt{belczynski:16, woosley:17, spera:17, stevenson:19,\n marchant:19, farmer:19, breivik:20, renzo:20csm, costa:21}).\n\nThe most commonly adopted algorithms to obtain compact object masses\nin the CC regime are the ``rapid'' and ``delayed'' prescriptions of\n\\cite{fryer:12}. In both cases, the compact object is built from the\n``bottom-up'', starting from a proto-NS mass and adding the amount of\nfallback expected in the (possibly failed) explosion. However, the\nproto-NS mass and information about the core structure relevant to\ncalculate the fallback are usually not available\n\\citep[e.g.,][]{patton:20}. Instead, the total final mass of the star\nis arguably easier to constrain in population synthesis models.\n\nAt the transition between CC and PPI (roughly at carbon-oxygen cores\nof $\\sim{}35\\,M_\\odot$, \\citealt{woosley:17, marchant:19, farmer:19,\n renzo:20csm, costa:21}), a mismatch between commonly adopted fitting\nformulae exists, and impairs the\ninterpretation of gravitational-wave data \\citep[as pointed out in\nFig.~5 of][]{vanson:21}. While it is possible that the BH mass\nfunction is discontinuous at the onset of the PPI regime (e.g.,\n\\citealt{renzo:20conv,costa:21}, Hendriks et al., in prep.), the\nlocation and amplitude of a putative discontinuity should not be\ngoverned by a mismatch between the fitting formulae.\n\n\n\\section{Top-down compact object masses}\n\nIn contrast with the ``bottom up'' approach of \\cite{fryer:12}, we\npropose a ``top-down'' compact object mass calculation. Starting from\nthe total stellar mass, we remove the amount of mass lost due to all\nof the processes associated with the (possibly failed) explosion:\n\n\\begin{widetext}\n \\begin{equation}\n \\label{eq:mass}\n M_\\mathrm{comp.\\ obj} =\n M_\\mathrm{pre-CC} - \\left(\\Delta M_\\mathrm{SN} + \\Delta M_{\\nu, \\mathrm{core}} + \\Delta M_\\mathrm{env} + \\Delta M_\\mathrm{PPI} + \\cdots \\right)\n \\end{equation}\n\\end{widetext}\n\n% where all masses are in $M_\\odot$,\nwhere $M_\\mathrm{pre-CC}$ is the total mass at the onset of CC, and\neach term in parenthesis corresponds to a potential mass-loss\nmechanism: $\\Delta M_\\mathrm{SN}$ for the CC ejecta,\n$\\Delta M_{\\nu, \\mathrm{core}}$ the change in gravitational mass of\nthe core due to the neutrino losses, $\\Delta M_\\mathrm{env}$ the loss\nof the envelope that can occur even in red supergiant ``failed''\ncore-collapse due to % the change in\n% gravitational mass corresponding to\n$\\Delta M_{\\nu, \\mathrm{core}}$\n\\citep{nadezhin:80, lovegrove:13, piro:13, fernandez:18, ivanov:21},\nand $\\Delta M_\\mathrm{PPI}$ the pulsational mass loss due to\npair-instability. Each term may be a function of the progenitor\nproperties, and may be theoretically or observationally informed\n(e.g., $\\Delta M_\\mathrm{SN}$ could be derived from the light curves of a\nlarge sample of observed SNe). \\Eqref{eq:mass} can be extended by\nadding additional mass-loss mechanisms in the parenthesis (e.g., disk\nwinds).\n\nIn the CC regime, the previous approach from \\cite{fryer:12} can be recovered by setting\n$\\Delta M_\\mathrm{SN} + \\Delta M_{\\nu, \\mathrm{core}} = M_\\mathrm{pre-CC} - M_\\mathrm{comp.\\ obj}^\\mathrm{Fryer+12}$,\nwhere the last term is the compact object mass as predicted by\n\\cite{fryer:12} and ignoring the other mass loss terms,\nsuch as $\\Delta M_\\mathrm{PPI}$ and $\\Delta M_\\mathrm{env}$.\n\n\\begin{figure}[tbp]\n \\begin{centering}\n \\includegraphics[width=0.75\\linewidth]{fit_DM_PPI.pdf}\n \\caption{Each panel shows our fitting formula \\Eqref{eq:fit} for\n the PPI induced mass-loss as a function of carbon-oxygen core\n mass at each metallicity $Z$. The crosses show the values from\n Tab.~1 \\cite{farmer:19}.}\n % This label tells showyourwork that the script `figures/fit_DM_PPI.py'\n % generates the PDF included above\n \\label{fig:fit_DM_PPI}\n \\end{centering}\n\\end{figure}\n\n\\section{New fit for PPI ejecta}\n\n\nImposing $\\Delta M_\\mathrm{PPI}=0$ at the edge of the PPI regime,\n\\Eqref{eq:mass} produces a smooth BH mass distribution.\n\\Eqref{eq:fit} provides a fit (in $M_\\odot$ units) to naked helium\nstar models from \\cite{farmer:19} for\n$\\Delta M_\\mathrm{PPI} \\equiv \\Delta M_\\mathrm{PPI}(M_\\mathrm{CO},Z)$.\nWhile the fit of \\cite{farmer:19} provides the BH mass after PPI, this\nis only an estimate because of other mass loss processes that might\noccur at CC \\citep[e.g.,][]{renzo:20csm, powell:21, rahman:22}. Here,\nwe fit the mass removed by PPI (crosses in \\Figref{fig:fit_DM_PPI}),\nwhich is what is directly computed in \\cite{farmer:19}.\n\n% Each panel of \\Figref{fig:fit_DM_PPI} shows\n% % The dashed curves in each panel of \\Figref{fig:fit_DM_PPI} show the\n% % fit \\Eqref{eq:fit} for each\n% one metallicity computed in\n% \\cite{farmer:19}.\nWe neglect the (weak) metallicity dependence of the minimum core mass\nfor PPI, and we fit the data for initial helium core masses between\n$38-60\\,M_\\odot$. We emphasize that \\cite{farmer:19} only simulated\nhelium cores. In the presence of a H-rich envelope at the onset of\nPPI, if it is extended and red it can be easily removed by the first\npulse \\citep[][]{woosley:17,renzo:20csm}. Thus the H-rich mass of red\nsupergiants should be added to the $\\Delta M_\\mathrm{PPI}$ provided\nhere. It is unclear what occurs in cases when the envelope is compact\nand blue \\citep[e.g.,][]{dicarlo:19, renzo:20merger, costa:21}.\n\n\\input{fit_DM_PPI.tex} %% generated by src/figures/fit_DM_PPI.py\n\nThe mass lost in PPI is sensitive to convection\n\\citep{renzo:20conv} and nuclear physics \\citep{farmer:19,\n farmer:20, costa:21, woosley:21, mehta:21}, which can introduce\nuncertainties up to $\\sim{}20\\%$ on the maximum BH mass. The accuracy\nof our fit is comparable to these uncertainties.\n\n\\vspace*{-10pt}\n\n% \\section*{Acknowledgements}\n% MR is grateful to R.~Luger for help with showyourwork\n% \\citep{luger:21}. The code associated to this paper is publicly\n% available at\n% \\url{https://github.com/mathren/top_down_compact_obj_mass} and the\n% input data are loaded from \\url{https://zenodo.org/record/3346593}. LvS\n% acknowledges partial financial support from the National Science\n% Foundation under Grant No. (NSF grant number 2009131), the Netherlands\n% Organisation for Scientific Research (NWO) as part of the Vidi\n% research program BinWaves with project number 639.042.728 and the\n% European Union’s Horizon 2020 research and innovation program from the\n% European Research Council (ERC, Grant agreement No. 715063).\n\n\n\\newpage\n\\bibliography{./top_down_comp_obj_mass.bib}\n\\end{document}\n\n%%% Local Variables:\n%%% mode: latex\n%%% TeX-master: t\n%%% End:\n", "meta": {"hexsha": "701df9bbdcdf21f47b0b97a0064b92d7b70869c3", "size": 9824, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "src/top_down_DM_PPI.tex", "max_stars_repo_name": "mathren/top_down_compact_obj_mass", "max_stars_repo_head_hexsha": "f4da69e6d0022b34001db7c46d5c44510f93f080", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2022-01-21T18:14:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-31T22:25:22.000Z", "max_issues_repo_path": "src/top_down_DM_PPI.tex", "max_issues_repo_name": "mathren/top_down_compact_obj_mass", "max_issues_repo_head_hexsha": "f4da69e6d0022b34001db7c46d5c44510f93f080", "max_issues_repo_licenses": ["MIT"], "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/top_down_DM_PPI.tex", "max_forks_repo_name": "mathren/top_down_compact_obj_mass", "max_forks_repo_head_hexsha": "f4da69e6d0022b34001db7c46d5c44510f93f080", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.9219512195, "max_line_length": 149, "alphanum_fraction": 0.7552931596, "num_tokens": 2838, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.30404168757891037, "lm_q1q2_score": 0.1567699493257212}} {"text": "% !TEX TS-program = pdflatex\r\n% !TEX encoding = UTF-8 Unicode\r\n\r\n% This is a simple template for a LaTeX document using the \"article\" class.\r\n% See \"book\", \"report\", \"letter\" for other types of document.\r\n\r\n\\documentclass[11pt]{article} % use larger type; default would be 10pt\r\n\r\n\\usepackage[utf8]{inputenc} % set input encoding (not needed with XeLaTeX)\r\n\r\n%%% Examples of Article customizations\r\n% These packages are optional, depending whether you want the features they provide.\r\n% See the LaTeX Companion or other references for full information.\r\n\r\n%%% PAGE DIMENSIONS\r\n\\usepackage{geometry} % to change the page dimensions\r\n\\geometry{a4paper} % or letterpaper (US) or a5paper or....\r\n\\geometry{margin=1in} % for example, change the margins to 2 inches all round\r\n% \\geometry{landscape} % set up the page for landscape\r\n% read geometry.pdf for detailed page layout information\r\n\r\n\\usepackage{graphicx} % support the \\includegraphics command and options\r\n\\usepackage{amsmath}\r\n\\usepackage{amsfonts}\r\n% \\usepackage[parfill]{parskip} % Activate to begin paragraphs with an empty line rather than an indent\r\n\r\n%%% PACKAGES\r\n\\usepackage{booktabs} % for much better looking tables\r\n\\usepackage{array} % for better arrays (eg matrices) in maths\r\n\\usepackage{paralist} % very flexible & customisable lists (eg. enumerate/itemize, etc.)\r\n\\usepackage{verbatim} % adds environment for commenting out blocks of text & for better verbatim\r\n\\usepackage{subfig} % make it possible to include more than one captioned figure/table in a single float\r\n% These packages are all incorporated in the memoir class to one degree or another...\r\n\r\n%%% HEADERS & FOOTERS\r\n\\usepackage{fancyhdr} % This should be set AFTER setting up the page geometry\r\n\\pagestyle{fancy} % options: empty , plain , fancy\r\n\\renewcommand{\\headrulewidth}{0pt} % customise the layout...\r\n\\lhead{}\\chead{}\\rhead{}\r\n\\lfoot{}\\cfoot{\\thepage}\\rfoot{}\r\n\r\n%%% SECTION TITLE APPEARANCE\r\n\\usepackage{sectsty}\r\n\\allsectionsfont{\\sffamily\\mdseries\\upshape} % (See the fntguide.pdf for font help)\r\n% (This matches ConTeXt defaults)\r\n\r\n%%% ToC (table of contents) APPEARANCE\r\n\\usepackage[nottoc,notlof,notlot]{tocbibind} % Put the bibliography in the ToC\r\n\\usepackage[titles,subfigure]{tocloft} % Alter the style of the Table of Contents\r\n\\renewcommand{\\cftsecfont}{\\rmfamily\\mdseries\\upshape}\r\n\\renewcommand{\\cftsecpagefont}{\\rmfamily\\mdseries\\upshape} % No bold!\r\n\r\n%%% END Article customizations\r\n\r\n%%% The \"real\" document content comes below...\r\n\r\n\\title{Homework 2}\r\n\\author{Alireza Shafaei\\\\78428133}\r\n%\\date{} % Activate to display a given date or no date (if empty),\r\n % otherwise the current date is printed \r\n\r\n\\begin{document}\r\n\\maketitle\r\n\r\n\\section*{Problem 1}\r\nLet G(X) be the woman that is paired with man X by the Gale-Shapley proposal algorithm. Prove that there is no stable pairing P such that X prefers P(X) (his partner in pairing P) to G(X).\\\\\r\n\\textbf{Proof.}\r\nLet's say there's a stable pairing $P$ such that $X$ prefers $P(X)$ to $G(X)$. This means $P(X)$ has to appear before $G(X)$ in $X$'s preference list. If so, according to the Gale-Shapley proposal algorithm, $X$ must've proposed to $P(X)$ before $G(X)$. Given that the final stable marriage of $X$ is $G(X)$, then there must exist a $Y$ such that $P(X)$ preferes to $X$, and $P(X)$ is the first available preference in $Y$'s list, resulting in a break up of $X$ and $P(X)$; thus no such stable marriage $P$ can exist.\r\n\r\n\\section*{Problem 2}\r\nProve that the expectation of a sum of random variables is the sum of the expectation of these random variables.\\\\\r\n\\textbf{Proof.} I demonstrate this feature using two random variables. Through induction, it could be generalized for $n$ random variables.\r\n\r\n\\begin{gather}\r\n\\mathbb{E}[X+Y] = \\sum_{\\omega_1 \\in \\Omega} \\sum_{\\omega_2 \\in \\Omega} (X(\\omega_1)+Y(\\omega_2))\\mathbb{P}(\\omega_1,\\omega_2) \\\\\r\n\\Rightarrow \\mathbb{E}[X+Y] = \t\\sum_{\\omega_1 \\in \\Omega}X(\\omega_1) \\sum_{\\omega_2 \\in \\Omega}\\mathbb{P}(\\omega_1,\\omega_2) +\r\n\t\t\t\t\t\\sum_{\\omega_2 \\in \\Omega}Y(\\omega_2) \\sum_{\\omega_1 \\in \\Omega}\\mathbb{P}(\\omega_1,\\omega_2) \\\\\r\n\\Rightarrow \\mathbb{E}[X+Y] = \t\\sum_{\\omega_1 \\in \\Omega}X(\\omega_1) \\sum_{\\omega_2 \\in \\Omega}\\mathbb{P}(\\omega_1|\\omega_2)\\mathbb{P}(\\omega_2) +\r\n\t\t\t\t\t\\sum_{\\omega_2 \\in \\Omega}Y(\\omega_2) \\sum_{\\omega_1 \\in \\Omega}\\mathbb{P}(\\omega_2|\\omega_1)\\mathbb{P}(\\omega_1)\\\\\r\n\\Rightarrow \\mathbb{E}[X+Y] = \t\\sum_{\\omega_1 \\in \\Omega}X(\\omega_1) \\mathbb{P}(\\omega_1)+\r\n\t\t\t\t\t\\sum_{\\omega_2 \\in \\Omega}Y(\\omega_2) \\mathbb{P}(\\omega_2)\\\\\r\n\\Rightarrow \\mathbb{E}[X+Y] = \t\\mathbb{E}[X]+\\mathbb{E}[Y]\r\n\\end{gather}\r\n\r\n\\section*{Problem 3}\r\n Prove that the expectation of a product of independent random variables is the product of the expectation of these random variables.\\\\\r\n\\textbf{Proof.} I demonstrate this feature using two independent random variables. Through induction, it could be generalized for $n$ independent random variables.\r\n\\begin{gather}\r\n\\mathbb{E}[XY] = \\sum_{\\omega_1 \\in \\Omega} \\sum_{\\omega_2 \\in \\Omega} X(\\omega_1)Y(\\omega_2)\\mathbb{P}(\\omega_1,\\omega_2) \\\\\r\nX \\perp Y \\Rightarrow \\mathbb{E}[XY] = \\sum_{\\omega_1 \\in \\Omega} \\sum_{\\omega_2 \\in \\Omega} X(\\omega_1)Y(\\omega_2)\\mathbb{P}(\\omega_1)\\mathbb{P}(\\omega_2) \\\\\r\n\\Rightarrow \\mathbb{E}[XY] = \\sum_{\\omega_1 \\in \\Omega} X(\\omega_1)\\mathbb{P}(\\omega_1)\\sum_{\\omega_2 \\in \\Omega} Y(\\omega_2)\\mathbb{P}(\\omega_2) \\\\\r\n\\Rightarrow \\mathbb{E}[XY] = \\mathbb{E}[X]\\mathbb{E}[Y]\r\n\\end{gather}\r\n\r\n\\section*{Problem 4}\r\nUse the previous two results to prove that the variance of a sum of pairwise independent random variables is the sum of the variances of these random variables.\\\\\r\n\\textbf{Proof.} I demonstrate this feature using two independent random variables. Through induction, it could be generalized for $n$ pairwise independent random variables.\r\n\\begin{gather}\r\nVar[X+Y] = \\mathbb{E}[(X+Y)^2] - (\\mathbb{E}[X+Y])^2\\\\\r\n\\Rightarrow Var[X+Y] = \\mathbb{E}[X^2+Y^2+2YX] - (\\mathbb{E}[X]+\\mathbb{E}[Y])^2\\\\\r\n\\Rightarrow Var[X+Y] = \\mathbb{E}[X^2]+\\mathbb{E}[Y^2]+\\mathbb{E}[2YX] - (\\mathbb{E}[X])^2-(\\mathbb{E}[Y])^2-(2\\mathbb{E}[X]\\mathbb{E}[Y])\\\\\r\n\\Rightarrow Var[X+Y] = \\mathbb{E}[X^2]+\\mathbb{E}[Y^2]+2\\mathbb{E}[Y]\\mathbb{E}[X] - (\\mathbb{E}[X])^2-(\\mathbb{E}[Y])^2-(2\\mathbb{E}[X]\\mathbb{E}[Y])\\\\\r\n\\Rightarrow Var[X+Y] = \\mathbb{E}[X^2]- (\\mathbb{E}[X])^2+\\mathbb{E}[Y^2]-(\\mathbb{E}[Y])^2\\\\\r\n\\Rightarrow Var[X+Y] = Var[X]+Var[Y]\r\n\\end{gather}\r\n\r\n\\section*{Problem 4}\r\nSuppose I have a sequence of $n$ different numbers. I reorder the sequence randomly (each ordering equally likely) and give you the numbers one at a time in this random order. You are interested in determining the maximum number in the sequence.\r\n\r\n\\begin{itemize}\r\n\t\\item An obvious approach is to keep the maximum of the numbers given so far, updating this maximum as needed. What is the expected number of times you update the maximum (as a function of $n$)?\\\\\r\n\\textbf{Answer.} Let's say we have seen $i$ numbers so far, the probability that $(i+1)_{th}$ number is the biggest in a series of $i+1$ numbers will be $\\frac{1}{i+1}$, since the biggest number could be any of $i+1$ numbers. Let $X_i$ denote whether we updated upon seeing $i_{th}$ number. The expected value of updates will be calculated as follows:\r\n\r\n\\begin{gather}\r\n\\mathbb{E}[X_i] = 1.\\frac{1}{i}+0.\\frac{i-1}{i}=\\frac{1}{i}\\\\\r\nY = X_1+X_2+X_3+\\ldots+X_n\\\\\r\n\\mathbb{E}[Y]=\\sum_{i=1}^{n}\\mathbb{E}[X_i] = \\sum_{i=1}^{n}\\frac{1}{i} = H_n\r\n\\end{gather}\r\nSo the answer will be $H_n$.\r\n\r\n\\item Suppose after you see each number, I ask ``Is this the maximum of all n numbers?'' If you say ``no'' then I give you the next number. If you say ``yes'' then you win if the number truly is the maximum number in the sequence, otherwise you lose.\\\\\r\nDescribe an algorithm for you to follow that results in a probability of winning that is at least 1/4. Note that your algorithm knows n from the start.\\\\\r\n\\textbf{Answer.} If we have seen $i$ numbers so far, it means there are $n-i$ numbers that we haven't seen. On updating max with $i_{th}$ number, the probability of $i_{th}$ number being the biggest number will be $\\frac{i}{n}$. Let's call probability of wining after update on $i_{th}$ number, $P_{i}$, we'd have:\r\n\r\n\\begin{gather}\r\n\tP_{i} = \\frac{i}{n}\\\\\r\n\tP_i \\geq \\frac{1}{4} \\Rightarrow \\frac{i}{n} \\geq \\frac{1}{4}\\\\\r\n\t\\Rightarrow i \\geq \\frac{n}{4}\r\n\\end{gather}\r\nMeaning that after seeing at least $n/4$ numbers, if the maximum was updated, we should say yes. In other words, if an update on max occured after seeing at least $n/4$ numbers, we're at least $1/4$ sure that this is the biggest number.\r\n\\end{itemize}\r\n\r\n\\end{document}\r\n", "meta": {"hexsha": "d903a629bcd0214b96e0e368ed7de929bf25b173", "size": 8663, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "homework/my_solutions/sources/HW2.tex", "max_stars_repo_name": "ashafaei/UBC-CPSC-500-Friedman-Condon-Evans-Kirkpatrick", "max_stars_repo_head_hexsha": "84b501b43ec36d49c402c9eceaee1f57eeae803e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-07-22T05:11:15.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-22T05:11:15.000Z", "max_issues_repo_path": "homework/my_solutions/sources/HW2.tex", "max_issues_repo_name": "ashafaei/UBC-CPSC-500-Friedman-Condon-Evans-Kirkpatrick", "max_issues_repo_head_hexsha": "84b501b43ec36d49c402c9eceaee1f57eeae803e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "homework/my_solutions/sources/HW2.tex", "max_forks_repo_name": "ashafaei/UBC-CPSC-500-Friedman-Condon-Evans-Kirkpatrick", "max_forks_repo_head_hexsha": "84b501b43ec36d49c402c9eceaee1f57eeae803e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2015-05-08T11:19:01.000Z", "max_forks_repo_forks_event_max_datetime": "2018-09-27T15:34:13.000Z", "avg_line_length": 64.6492537313, "max_line_length": 518, "alphanum_fraction": 0.7043749279, "num_tokens": 2786, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3702253925955866, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.1564219442975378}} {"text": "\\section{Reaction initial state simulation.}\n\n\\subsection{Allowed projectiles and bombarding energy range for interaction \nwith nucleon and nuclear targets.}\n\\hspace{1.0em}\nThe GEANT4 kinetic model is capable to predict final states (produced \nhadrons \nwhich belong to the pseudoscalar meson nonet and the baryon (antibaryon) \noctet) of reactions on nucleon and nuclear targets \nwith a large variety of hadron (the same types as final state hadrons) and \nnuclear projectiles. The allowed bombarding kinetic energy in \nthe hadron--nucleon, \n hadron--nucleus and nucleus--nucleus collisions \n is recommended to be more than \n 20 MeV in the laboratory frame.\n The upper limit of initial \n kinetic energy is approximately $10$ GeV per initial particle. \n \n This model is also able to predict\nfinal states in the photon--nucleon and photon--nucleus inelastic \ncollisions as well as the nuclear absorption of the \nstopping $\\pi^{-}$, $K^{-}$ and $\\bar{p}$. \n The last cases are described in the \nseparate chapters.\n\n There are also needs\n to simulate hadron\nkinetics after the \"parton string\" stage of nuclear interaction, taking\naccount secondary hadron rescatterings.\n\n\\subsection{MC initialization procedure for a nucleus}\n\\hspace{1.0em}The initialization of each nucleus, consisting from $A$\nnucleons and $Z$ protons ($N=A-Z$ neutrons) \nwith coordinates $\\mathbf{r}_i$ and momenta\n$\\mathbf{p}_i$, where $i = 1,2,...,A$ is performed.\nFor the hadron kinetic model the MC initialization procedure for a nucleus is \nsimilar as for the \nparton string model except of some peculiarities, which are taken into \naccount:\n\\begin{itemize}\n\\item Nucleon radii $r_i$ are selected randomly in the rest of nucleus according \nto proton or neutron density $\\rho(r_i)$. \nFor heavy nuclei with $A > 16$ \\cite{GLMP91} normalized on unity \nnucleon density is\n\\begin{equation}\n\\label{KNIS1}\\rho(r_i) = \n \\frac{\\rho_0}{1 + \\exp{[(r_i - R)/a]}}\n\\end{equation}\nwhere\n\\begin{equation}\n\\label{KNIS2}\\rho_0 \\approx \\frac{3}{4\\pi R^3}(1+\\frac{a^2\\pi^2}{R^2})^{-1}.\n\\end{equation} \nHere $R=r_0 A^{1/3}$ \\ fm and $r_0=1.16(1-1.16A^{-2/3})$ \\ fm and $a\n\\approx 0.545$ fm. For light nuclei with $A < 17$ normalized on unity \nnucleon density is\ngiven by a harmonic oscillator shell model \\cite{Elton61}, e. g.\n\\begin{equation}\n\\label{KNIS3} \\rho(r_i) = (\\pi R^2)^{-3/2}\\exp{(-r_i^2/R^2)},\n\\end{equation}\nwhere $R^2 = 2/3 = 0.8133 A^{2/3}$ \\ fm$^2$ or \n\\begin{equation}\n\\label{KNIS4} \\rho(r_i) =\n\\frac{4}{\\pi^{3/2}R^3}[1+\\frac{A-4}{6}(\\frac{r_i}{R})^2]\n\\exp{(-r_i^2/R^2)},\n\\end{equation}\nwhere\n\\begin{equation}\n\\label{KNIS5} R^2=(\\frac{5}{2}-\\frac{4}{A})^{-1}(_{A}- \n_{p})\n\\end{equation}\nThe mean squared charge radii of the nucleus $_{A}$ and proton\n$_{p}$ are taken from the measurements of lepton-nucleus\nscattering experiments \\cite{BJ77}. To take into account nucleon\nrepulsive core it is assumed that internucleon distance $d > 0.8$ \\ fm;\n\n\\item The initial momenta of the nucleons are randomly choosen between $0$ and \n$p^{max}_F$, where \nthe maximal momenta of nucleons (in the local Thomas-Fermi \napproximation \\cite{DF74}) depends from\nthe proton or neutron density $\\rho_{Z,N}$ according to \n\\begin{equation}\n\\label{KNIS6} p^{max}_F = \\hbar c(3\\pi^2 \\rho_{Z,N})^{1/3}\n\\end{equation}\nwith $\\hbar c = 197.327$ MeVfm. \n\n\\item To obtain coordinate and momentum components, it\n is assumed that nucleons are distributed isotropicaly in configuration\n and momentum spaces;\n\nWe assume \\cite{URQMD97}\nthat nucleons are not points in configuration space\nand they are represented by Gaussian shaped density distributions (c = 1):\n\\begin{equation}\n\\label{KNIS7}\\phi({\\bf x_i}, t) = (\\frac{2\\alpha}{\\pi})^{3/4}\n\\exp{\\{-\\alpha ({\\bf x_i}\n- {\\bf r_i} (t))^2 + \\frac{i}{\\hbar}{\\bf p_i} (t) {\\bf x_i}\\}}, \n\\end{equation}\nwhere $\\alpha=0.25$ \\ fm$^{-2}$ is a model parameter.\nIt gives us a possibility to take into account \nthe Pauli blocking (the Pauli blocking procedure is decsribed below), \ni. e. if the phase space of $i$-th nucleon is already occupied by other\nnucleons, its sampling is deserted;\n\n\\item Then perform shifts of nucleon coordinates ${\\bf r_i^{\\prime}}\n= {\\bf r_i} - 1/A \\sum_i {\\bf r_i}$ and momenta ${\\bf p_i^{\\prime}}\n= {\\bf p_i} - 1/A \\sum_i {\\bf p_i}$ \nof nucleon momenta. The nucleus must be centered in configuration space around\n$\\mathbf{0}$, \\textit{i. e.} $\\sum_i {\\mathbf{r}_i} = \\mathbf{0}$ and\n the nucleus must be at rest, i. e. $\\sum_i {\\bf p_i} = \\bf 0$ and\n$\\sum_i {\\bf r_i} \\times {\\bf p_i}={\\bf 0}$;\n\n\\item We compute energy per nucleon $e = E/A = m_{N} + B(A,Z)/A$, \nwhere $m_N$ is nucleon mass and the nucleus binding energy $B(A,Z)$ is given \nby the Bethe-Weizs\\\"acker formula\\cite{BM69}:\n\\begin{equation}\n\\begin{array}{c}\n\\label{KNIS8} B(A,Z) = \\\\\n= -0.01587A + 0.01834A^{2/3} + 0.09286(Z- \\frac{A}{2})^2 +\n0.00071 Z^2/A^{1/3},\n\\end{array}\n\\end{equation} \n and find the effective mass of each nucleon $m^{eff}_i = \n\\sqrt{(E/A)^2 - p^{2\\prime}_i}$.\n\\end{itemize}\n\n\\subsection{Lorentz boost of nucleon longitudinal momenta and energies.}\n\n\\hspace{1.0em}In the case of fast moving nucleus with initial momentum\nper nucleon ${\\bf P_0}= \\{0, 0, P_{z0}\\}$ one should perform Lorentz\ntransformation of the nucleon longitudinal momenta\n\\begin{equation}\n\\label{KNIS9} p_{zi} \\rightarrow \\gamma_i (p_{zi} - \\beta_i e_{i})\n\\end{equation}\nand the nucleon energies \n\\begin{equation}\n\\label{KNIS10} e_{i} \\rightarrow \\gamma_i (e_{i} - \\beta_i p_{zi}),\n\\end{equation}\nwhere $\\beta_{i}$ is defined as\n\\begin{equation}\n\\label{KNIS11} \\beta_{i} = \\frac{P_{z0}}{\\sqrt{P_{z0}^2 + m^{eff2}_i}}\n\\end{equation}\nand $\\gamma_i$ is given by \n\\begin{equation}\n\\label{KNIS12}\\gamma_i = \\frac{1}{\\sqrt{1 - \\beta_i^2}}.\n\\end{equation}\n\n\\subsection{Lorentz contraction of the fast moving nucleus.}\n\\hspace{1.0em}For this case one need also to perform the Lorentz\ncontraction of the nucleus, \\textit{i. e.}\n\\begin{equation}\n\\label{KNIS13} r_{zi} \\rightarrow r_{zi}/ \\gamma_{i}.\n\\end{equation}\n\\subsection{Random choice of the impact parameter.}\n\n\\hspace{1.0em}The impact parameter $0 \\leq b \\leq R_p + R_t$ is randomly\nselected according to the probability:\n\\begin{equation}\n\\label{KNIS14}P({\\bf b})d{\\bf b} = b d{\\bf b},\n\\end{equation}\nwhere $R_p$ and $R_t$ are the target and projectile radius,\nrespectively. In the case of nuclear projectile or target the nuclear radius is\ndetermined from condition:\n\\begin{equation}\n\\label{KNIS15}\\frac{\\rho(R)}{\\rho(0)} = 0.01.\n\\end{equation}\n Then one should update the transversal components of\nnucleon coordinates:\n\\begin{equation}\n\\label{KNIS16} r_{xi} \\rightarrow r_{xi} + b_x\n\\end{equation}\nand\n\\begin{equation}\n\\label{KNIS17} r_{yi} \\rightarrow r_{yi} + b_y.\n\\end{equation}\nFinaly, for target nucleus, if a projectile is centered around $0$, one\nshould perform a shift of the nucleon longitudinal coordinates:\n\\begin{equation}\n\\label{KNIS18} r_{zi} \\rightarrow r_{zi} + \\Delta r_z/\\gamma_{i},\n\\end{equation}\nwhere $\\Delta r_z = R_p + 1.5 \\ fm + R_t + 1.5 \\ fm$ is taken.\n\nIn the case of hadron--nucleus collision we determine the initial \nangular momentum \nof target nucleus:\n\\begin{equation}\n\\label{KNIS19} \\vec{L}_0= \\vec{p}_0 \\times \\vec{r}_0,\n\\end{equation}\nwhere $\\vec{p}_0$ and $\\vec{r}_0$ are initial momentum and radius vector \nof incoming hadron enter point in the target nucleus rest frame.\n", "meta": {"hexsha": "859092a491a711f155564d87d135fa4f7b6df609", "size": 7373, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "geant4/hadronic/theory_driven/HadronKinetic/ReactionInitialStateHKM.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/ReactionInitialStateHKM.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/ReactionInitialStateHKM.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": 38.8052631579, "max_line_length": 81, "alphanum_fraction": 0.7120575071, "num_tokens": 2497, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.30074558520860073, "lm_q1q2_score": 0.15624374399882807}} {"text": "\n% JuliaCon proceedings template\n\\documentclass{juliacon}\n\\usepackage[ruled,vlined]{algorithm2e}\n\\setcounter{page}{1}\n\n\\keywords{landscape ecology , computational ecology, julia programming language}\n\n\\makeatletter\n\\newcommand{\\removelatexerror}{\\let\\@latex@error\\@gobble}\n\\makeatother\n\n\\begin{document}\n\n\\input{header}\n\\maketitle\n\n\\begin{abstract}\nConnectivity across landscapes influences a wide range of conservation-relevant ecological processes, including species movements, gene flow, and the spread of wildfire, pests, and diseases. The computational demands of the next generation of connectivity models and the availability of increasingly fine grained remote sensing data drive the need for faster software for connectivity modelling. To address this, we upgraded the widely-used Circuitscape connectivity package to the Julia programming language. The Julia package, Circuitscape.jl, can now solve much larger problems up to an order of magnitude faster, with improved solvers and parallel computing features. We demonstrate scaling up to problems of size 437 million grid cells, with speedups of up to 1800\\% over the previous version. These improvements increase the pace of interaction between scientists and key stakeholders, facilitating faster policy decisions. \n\n\\end{abstract}\n\n\\section{Introduction}\nConnectivity models provide important insights into ecological processes that involve variation in movement or flow patterns across heterogeneous environments \\cite{crooks2006}. In applied conservation, connectivity maps are incorporated into a wide range of resource evaluations and risk assessments, informing decisions on how to sustain population dynamics and genetic diversity in plant and animal populations \\cite{kareiva1995connecting}, how to most effectively prevent infectious disease spread or reduce risks from wildfire \\cite{gray2016applying}, and choices of where to invest in land protection or restoration to help support species range shifts under a changing climate \\cite{heller2009biodiversity, littlefield2017connecting, keeley2017habitat}. \n\nA common requirement for modeling connectivity is a gridded depiction of the landscape in which values for each cell represent some relative value of “resistance” to movement. These resistance grids are developed through several different methods, often involving iterative processes for categorizing resistance weights for different types of barriers based on expert opinion and information on species’ life histories and movement behaviors \\cite{spear2010use, zeller2012estimating}. This grid can then be abstracted as a graph \\cite{urban2001landscape}, providing a way to quantify ecological distance measures via graph-theoretic metrics. \n\nThe range of mathematical approaches and software tools used for modeling connectivity reflect differences in theoretical approaches, and in the underlying assumptions about how movement proceeds. The classical isolation by distance model (IBD) posits that the least cost distance across the landscape graph acts as a good proxy for ecological distance \\cite{wright1943isolation}. Tools based on this approach typically identify a single “best” route between focal locations, an important result, but one that is highly dependent upon the choice of start and end points, and has limited application if one’s goal is to compare potential options for restoration or protection across a landscape with multiple habitat patches and pathways. As reviewed in \\cite{dickson2019circuit}, from 2006-08, three seminal papers by the late Brad McRae built upon earlier work by \\cite{doyle1984random} to demonstrate that isolation by resistance (IBR)\\cite{mcrae2006isolation}, which operationalizes the potential for genes and individuals to follow “random walks” across multiple pathways in the same way that electrical current can spread across multiple resistors, can provide an effective tool for considering connectivity potential across landscapes. These insights and McRae’s interest in informing conservation applications inspired the Circuitscape software package \\cite{mcrae2008using}, which calculates effective resistance and “current flow,” a measure of net movement probability, across heterogeneous landscapes \\cite{dickson2019circuit}. This approach has evolved into a very flexible set of tools that allow users to vary the resistance grid and identification of what can be connected, enabling modelers to address a wide range of questions related to structural (ability of a landscape to support movement) and functional (modeling that is tailored to species-specific traits) connectivity. \nOver the past decade Circuitscape has emerged as the most cited landscape connectivity tool in the world \\cite{dickson2019circuit}. In the last year alone, Circuitscape has been cited 129 times, and in the past three years, 480 times. Dickson et al. (2019) reviews 277 applications of the software, in fields ranging from gene flow and animal movement to fire, water, and disease spread, and also describes how outputs are being used to inform conservation decisions. \n\n\n\\begin{figure*}\n \\centering\n \\includegraphics[width=\\textwidth]{res.pdf}\n \\caption{\\textbf{An illustration of the impact of coarsening the resistance grid to address computational limitations.} For this agricultural area along the border of Illinois and Indiana, USA, we show current flow derived from a resistance grid coarsened to 900m (left), compared to a higher-resolution map (180m cells, right). Both resistance grids were derived from the 2011 NLCD (30m), and run with a “wall-to-wall” application of Circuitscape to evaluate landscape structural connectivity. All “natural” terrestrial land cover types in the NLCD were assigned low resistance values, with pasture, roads, row crops, etc., assigned higher resistances. The 900m resolution map misses many narrow bands of natural land cover with high current flow (dark blue) indicating high connectivity value along streams and rivers. Analyses and maps by Melissa Clark, to support work in \\cite{baldwin2018future}. \n}\n \\label{fig:my_label}\n\\end{figure*}\n\n\n\n\\section{Circuitscape in Julia}\n\\label{sec:documentclass}\n%\nThe goal of increasing the computational power of Circuitscape has been addressed multiple times by developers Brad McRae and Viral Shah. McRae’s first version was written in Java, before being ported to MATLAB, to improve ease of development. Then, in collaboration with Tanmay Mohapatra, it was translated to Python for flexible scripting, platform independence and release under an open source license. This package makes heavy use of the numpy \\cite{van2011numpy}, scipy \\cite{jones2014scipy} and pyamg \\cite{bell2015pyamg} numerical libraries and solves problems of up to tens of millions of nodes, but connectivity analysis increasingly finer resolution databases often scaled to hundreds of millions of nodes and dozens of focal node pairs, a workload size well beyond its capacity. Circuitscape needed to be upgraded to support the newer demands of user community. \n\nTo address these demands, McRae and Shah collaborated on a project called GFLOW \\cite{leonard2017gflow}, a software tool for conducting circuit-theory based analyses on supercomputers. Written in the C programmming language and making use of solver libraries such as PetSc \\cite{balay2004petsc} and BoomerAMG \\cite{yang2002boomeramg}, GFLOW yields state of the art performance on large clusters and supercomputers. However, this performance comes at the cost of accessibility (does not work on the Windows operating system, which the majority of Circuitscape users use), composability (ability to integrate with other software libraries) as well as a tangible difficulty in shipping binaries because of their complicated build processes. For many practitioners and researchers, these constraints are a key barrier, as they prevent GFLOW from being supported on the Windows operating system, and limit integration into a decision support tool or workflow with other tools. \n\nAs the maintainers of the Circuitscape, we saw the need for an open-source implementation that is easy to maintain, is high performance, is accessible to our user base and works well on every platform. We decided to use the Julia programming language \\cite{bezanson2017julia}. Julia is an open source dynamic programming language which combines the readability of scripting languages such as R or Python, with the performance of a statically compiled language such as C or Fortran. With relatively little development effort via a straight reimplementation of the algorithm, Julia allowed us to not only significantly improve the package's computational capacity, but provide new user-facing features for free. For example, Julia's first class sparse matrix library and factorization support allowed us to support multiple solvers. Its modern Just in Time (JIT) compiler enables programmers to write generic code, and then generate specialized code for desired precision, index types and hardware platform. This makes maintenance of the code base simple. Our upgrade, \"Circuitscape.jl\", is a registered Julia package and is already being used by the community to solve the next generation of connectivity problems. \n\nThe rest of this paper is organized as follows: we present an overview of the algorithm in Section 3, before describing the numerical methods and software packages in Section 4. Section 5 then briefly describe the new features introduced in the upgrade and then present benchmarks both on synthetic problems as well as real user data. We then round off this work with a discussion on how speed improvements enable increased collaboration between computer scientists and ecologists enable improved collaboration between ecologists and conservation managers and other stakeholders. \n\n\\section{The Algorithm}\n\\begin{figure}\n\\removelatexerror\n\\centering\n\\begin{algorithm}[H]\n\\SetAlgoLined\n\\LinesNumbered\n\\KwResult{Current (probability) maps $C$, nodal voltages $V$, pairwise resistances}\n Read input raster grid \\;\n Read focal nodes \\;\nConstruct undirected, weighted graph connecting neighboring cells\\;\nCompute graph Laplacian $G$ \\;\n\\For{all pairs of focal nodes}{\n Set up $I$\\;\n Solve linear system $GV = I$ \\;\n Compute effective resistance $r$\\;\n Write nodal voltages $V$ to disk\\;\n Compute nodal currents from $I$ and write current map C to disk\\\n}\n\n \\caption{Circuitscape - Pairwise Mode }\n\\end{algorithm}\n\\end{figure}\n\n\\begin{figure*}\n \\centering\n \\includegraphics[width=0.5\\textwidth]{flow.png}\n \\caption{\\textbf{Stages of computation and inputs/outputs}. The input raster grid to is usually assembled and produced using a GIS software package, and the output current maps are often exported to a GIS software package for postprocessing.}\n \\label{fig:flow}\n\\end{figure*}\n\nCircuitscape takes as input a raster grid, and a list of points which are potential starting and ending points for animal migration. Selecting these points (or focal nodes) on the landscape is often context dependent. For example, they could be two different national parks, or points on the landscape which share important climate properties. The raster grid is a spatial discretization of a heterogeneous landscape where each cell is assigned a value. Each value represents varying qualities of habitat, dispersal routes, or movement barriers. These “resistance” values are often problem specific, and are either empirically derived based on movement or genetic data, or derived via expert opinion. The following content has been summarized in Figure \\ref{fig:flow}. This grid can then be represented as a graph, with nodes representing grid cells and edge weights proportional to the movement probabilities or number of migrants exchanged. Other inputs include a list of focal points, which represent points on the landscape of interest to the practitioner. These include habitat patches, protected areas, or populations to connect. These can be specified either through a raster grid with numerical labels for each focal point, or a text file with a list of coordinates. Once the graph is constructed, we then compute its laplacian, which is an alternate representation of the landscape. We then solve for Ohm’s law using the computed graph laplacian as the conductance matrix and the node locations of the focal points as current sources and sinks. On solving the system, we obtain a list of nodal voltages, which are then used to compute branch currents, which represent movement probabilities along branches of the graph. The ecological significance of these various quantities are summarized in related works \\cite{mcrae2008using}. The branch currents are then accumulated on each node as nodal currents, which are then written to disk as a raster ASCII grid, for easy import into a geographic information system (GIS). \n\n\n\\section{Numerical Methods}\nThe vast majority of the computation in Circuitscape is applying Ohm’s law and Kirchoff’s law over very large resistive grids, and solving a large sparse linear system: \n$$\nGV = I\n$$\nwhere $G$ is the graph laplacian representation of the landscape is stored as a large sparse matrix, $I$ are the current sources, and $V$ are the nodal voltages. We provide two solver options to the user: one based on the choleksy factorization and a preconditioned iterative method. The Cholesky factorization \\cite{higham2009cholesky} is efficient for applications with smaller study areas and a large number of focal nodes. The sparse matrix is factored once and the solution to multiple pairs is computed via back substitution. Since the cost for backsubstitution is polynomially smaller than the cost of factorization, problems with a large number of focal pairs scale efficiently. The solver that scales to large problems is a preconditioned conjugate gradient (PCG) \\cite{trefethen1997numerical}, with an algebraic multigrid preconditioner (AMG) \\cite{vanvek1996algebraic}. We leverage Julia implementations of these methods from open source packages IterativeSolvers.jl and AlgebraicMultigrid.jl.\n\n\\subsection{Preconditioner Implementation}\nMultigrid preconditioners are often used in problems solved across large spatial domains. In general, they take the original grid and generate a hierarchy of coarser grids, via predefined or algebraically derived restriction and interpolation operators. Large problems are solved by restricting quantities down to the coarsest level, obtaining a fast solution, and then interpolating the solution back to the original size. This procedure is often referred to as a “V” cycle. The efficacy of a good multigrid preconditioner is to with obtaining good restriction and interpolation operators. Usually, these operators are derived from the structure of the underlying problem. However, one can also estimate these operators algebraically, from the numerical values at each grid cell. This procedure is often referred to as Algebraic Multigrid (AMG). There are several variants of AMG, which are summarized in \\cite{stuben2001review}. We use a variant called the Smoothed Aggregation AMG, which is known to work well for solving matrices generated by elliptic partial differential equations, such as Laplace’s equation. Laplacian matrices are structurally identical to the laplacians of planar graphs that are generated in Circuitscape.\n\n\n\\section{New Features}\n\n\\subsection{New Solver Mode}\n\nCircuitscape now supports a new solver based on the Cholesky factorization of the graph laplacian representation of the landscape. We use the SuperNodal sparse cholesky factorization implemented in the CHOLMOD library \\cite{chen2008algorithm}. The Julia programming language has first class sparse matrix library and matrix factorization support, which makes it easy to use this solver with a single function call.This solver mode also enables new approaches that divide the landscape into tiles and process them independently \\cite{pelletier2014applying}or analyses that move sliding windows across the landscape \\cite{mcrae2016conserving}, both of which yield fine scale and localized results. The obvious limitation of this solver, as is of most sparse direct solvers, is that they work very well for relatively small matrices and run out of memory for larger ones. This exponential growth in memory is a by product of the factorization itself, as factors are often less sparse than the original matrix. \n\n\\subsection{Generic Programming}\n\nJulia supports the development of generic code while relying on the compiler to generate specialized code for different platforms and precision required. Generic programs are powerful tools for our users, and can be made to adapt to their requirements. For example, the python package had a 32-bit integer type for indexing matrices hardcoded throughout the package, which limited the size of the computation the package ran. This led to crashes when running simulations for hundreds of millions of nodes. One such dataset studying the Mojave desert tortoise \\cite{gray2019} used a resistance surface of 437 million pixels. This crashed the old version of Circuitscape, while the upgrade ran smoothly to completion. Circuitscape.jl defaults to a 32-bit integer type for cache efficiency, but provide users with a runtime flag to switch to 64-bit integer to index sparse matrices on the order of hundreds of millions. Since our Julia code was written generically, and this feature came for free without any additional programming effort. Upgrading the python package to support this feature would require significant effort. \n\n\\subsection{Improved Parallel Computations}\n\n%Circuitscape.jl introduces support for parallelism on the Windows operating system. This was not possible with the Python package.\n\nParallel computing in Circuitscape.jl is inherently faster, because the preconditioner can be serialized as a byte stream and sent over the network to other processes. This is not possible in the python code, as the python multiprocessing module internally uses the package pickle to serialize objects, and pyamg objects, implemented in C++, are not “pickle-able” \\cite{pydoc}. The ability to serialize native Julia objects significantly reduced the amount of effort to parallelize Circuitscape.\nIn addition to faster parallel processing, we also extend parallelism support for more problem types in Circuitscape. In the benchmarks section, a dataset which received speed improvements from these new features. The Julia version also lets the user call Circuitscape itself in parallel. As users aim to run Circuitscape over entire countries or continents, landscape are often divided into multiple tiles \\cite{pelletier2014applying}. This feature allows users to process (a batch of) these tiles by running different Circuitscape problem instances on each tile in parallel. These parallel features work on all platforms: Linux, MacOS and Windows. \n\n\\section{Benchmarks}\n\n\\subsection{Experimental Setup}\nWe conducted our experiments on an Intel(R) Xeon(R) Silver 4114 CPU @ 2.20GHz with 384 GB of RAM. We used Julia v1.1.0 and Circuitscape v5.5.0, and compared against Circuitscape v4.0.5 \n\n\\subsection{Standard Benchmarks}\nWe benchmarked Circuitscape on standard synthetic problems. These benchmarks represent the most commonly used configuration and mode (Raster Pairwise) but with different problem sizes. These datasets can be found at \\url{https://github.com/Circuitscape/BigTests/}. The benchmark results are summarized in Figure \\ref{fig:csbench}. \n\n\\begin{figure*}\n \\centering\n \\includegraphics[width=0.5\\textwidth]{bench.pdf}\n \\caption{\\textbf{Results on the standard Circuitscape benchmark suite (smaller is better)}. The red column standards for the Julia package run under the AMG solver and green column stands for the Julia package run with the Cholesky-based CHOLMOD solver. Note that we benchmark only up to size 24M because at higher sizes the CHOLMOD solver runs out of memory and the Python version takes much, much longer. In summary, this chart demonstrates that Julia-CHOLMOD is the right choice for smaller problem sizes and Julia-CGAMG is the right choice for large problem sizes.}\n \\label{fig:csbench}\n\\end{figure*}\n\n\\subsection{Benchmarks on Data from Existing Studies}\n\nWe ran the Python and Julia version of Circuitscape on a dataset used to model connectivity in the Sonoran desert \\cite{drake2017using} (SONORAN). We used to all-to-one scenario \\cite{mcrae2009circuitscape}, which models species migrating across the landscape from many different areas to one area. When the researcher used the old version of Circuitscape, this mode did not support parallelism, and the entire computation took over 2 days to run. Parallelism was trivial to support in the Julia version, which reduced execution time to less than 3 hours, resulting in a speedup of nearly 18x. We also benchmarked against a new range-wide model of connectivity for the endangered Mojave desert tortoise \\cite{gray2019}(MOJAVE). We found that the Python version crashed, but the Julia package was able to scale effectively. The benchmark results are summarized in Figure \\ref{table:bench}. \n\n\\begin{figure*}\n%\\begin{table*}[]\n\\begin{tabular}{|l|l|l|l|l|}\n\\hline\n\\textbf{Benchmark} & \\textbf{Size} & \\textbf{Number of Solves} & \\textbf{Time (Python)} & \\textbf{Time (Julia)} \\\\ \\hline\nSONORAN & 3339832 & 6002 & 56.62 hrs & 2.838 hrs \\\\ \\hline\nMOJAVE & 437 million & 1 & Crashed & 3.385 hrs \\\\ \\hline\n\\end{tabular}\n\\centering\n%\\end{table*}\n\\caption{\\textbf{Benchmarks on data from two conservation studies}. Two metrics determine the execution time of a Circuitscape run: the size of the problem and the number of linear system solves. Our package scales desirably in both directions. }\n\\label{table:bench}\n\\end{figure*}\n\n\\section{Discussion}\n\nThe growth in popularity of circuit theory to model ecological processes has to lead to widespread adoption of the Circuitscape software package. \\cite{mcrae_shah_mohapatra_anantharaman}. The Circuitscape project has always evolved with the demands of the users and this upgrade to the Julia programming language seeks to drive the next generation of compute-intensive connectivity models, by shortening execution time from weeks to days and from days to hours. Users no longer have to coarsen their analysis due to computational limitations \\cite{drake2017using}. Faster results often enhance stakeholder engagement, improve the feedback loop with policy makers and result in faster turnaround time for conservation decisions. Julia is already being used by ecologists to model ecological networks \\cite{timothee_poisot_2018_1438428} and bioenergetic food webs \\cite{delmas_eva_2019_2584373} and we see a strong role for it in other areas of computational ecology and conservation science. Its high level mathematical syntax is accessible to scientists while its speed allows them to simulate large, intricate models that capture complexity. We hope to see more ecologists and practitioners use and adopt Julia. \n\n% While connectivity tools typically focus in variation across space, questions related to temporal variability in connectivity, and simulations of how connectivity might change through habitat loss or restoration, would be of great interest as well.\n\n\\section{Conclusion}\nWe present an upgrade to the Circuitscape package, which will allow researchers to analyze ecological processes over large landscapes at fine resolutions. Our upgrade in the high performance Julia programming language presents upto a 1800\\% improvement in computation time and the ability to solve landscapes with hundreds of millions (and potentially billions) of grid cells. Julia’s sophisticated compiler allows for faster parallelism, generic programming and composability with other software packages. Circuitscape.jl is open source and is available at \\url{https://github.com/Circuitscape/Circuitscape.jl} under the MIT license. Binaries are available on \\url{https://circuitscape.org/downloads/}. It can also be installed using the Julia package manager by starting Julia, and entering \\texttt{using Pkg; Pkg.add(\"Circuitscape\")}. \n\n\\section{Acknowledgement}\nThe work to update Circuitscape to the Julia computing language was funded through a grant from NASA’s Ecological Forecasting Program (16-ECO4CAST0018), and a grant from the Wilburforce Foundation. The authors also wish to acknowledge the Wilburforce Foundation’s long-term investment in Circuitscape and related tools through several previous awards to Dr. Brad McRae. We thank all of the Circuitsape users who have shared datasets, reported issues, and provided feedback on various versions of these tools, and look forward to continued collaboration with the user community. \n\n\\input{bib.tex}\n%\\bibliography{ref} %%% Remove comment to use the external .bib file (using bibtex).\n\n\\end{document}\n\n% Inspired by the International Journal of Computer Applications template\n", "meta": {"hexsha": "edb837e398e89f0819147595faf5e5c8d879ca24", "size": 25097, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "paper/paper.tex", "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/Circuitscape.jl-2b7a1792-8151-5239-925d-e2b8fdfa3201", "max_stars_repo_head_hexsha": "7e2974efe165b39a338f74851a311eb6cd0ecab8", "max_stars_repo_licenses": ["MIT"], "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": "UnofficialJuliaMirrorSnapshots/Circuitscape.jl-2b7a1792-8151-5239-925d-e2b8fdfa3201", "max_issues_repo_head_hexsha": "7e2974efe165b39a338f74851a311eb6cd0ecab8", "max_issues_repo_licenses": ["MIT"], "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": "UnofficialJuliaMirrorSnapshots/Circuitscape.jl-2b7a1792-8151-5239-925d-e2b8fdfa3201", "max_forks_repo_head_hexsha": "7e2974efe165b39a338f74851a311eb6cd0ecab8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 151.186746988, "max_line_length": 2028, "alphanum_fraction": 0.8112523409, "num_tokens": 5276, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3040416686603661, "lm_q1q2_score": 0.15558317037547137}} {"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 {algorithmic}\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{listings}\n\\usepackage{xcolor}\n\\lstset { %\n language=C++,\n backgroundcolor=\\color{black!5}, % set backgroundcolor\n basicstyle=\\footnotesize,% basic font setting\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{\\LARGE \\textbf {COMP 285 (NC A\\&T, Spr `22)}\\hfill \\textbf {Lecture 4} } \n\\vspace {1em} \n\\begin {Instruction} \n\nAdapted From Virginia Williams' lecture notes. Additional credits: J. Su, W. Yang, Gregory Valiant, Mary Wootters, Aviad Rubinstein, Sami Alsheikh.\n\\end {Instruction} \n\n\\begin{centering}\n\\section*{MergeSort and Introduction to Recurrence Relations}\n\\end{centering}\n\n\\section{MergeSort Cont.}\n\nFrom last lecture, we will continue our implementation of MergeSort, and go over some of the details regarding correctness and running time.\n\n\\subsection{Correctness of MergeSort}\nLet's focus on the first question first. As before, we'll proceed by induction. This time, we'll maintain a \\textit{recursion invariant} that any time \\texttt{MergeSort} returns, it returns a sorted array.\n\n\\begin{itemize}\n \\item \\textbf{Inductive Hypothesis.} Whenever \\texttt{MergeSort} returns an array of size $\\leq i$, that array is sorted.\n \\item \\textbf{Base case.} Suppose that $i = 1$. Then whenever \\texttt{MergeSort} returns an array of length $0$ or length $1$, that array is sorted. (Since all array of length $0$ and $1$ are sorted). So the Inductive Hypothesis holds for $i = 1$.\n \\item \\textbf{Inductive step.} We need to show that if \\texttt{MergeSort} always returns a sorted array on inputs of length $leq i - 1$, then it always does for length $\\leq i$. Suppose that \\texttt{MergeSort} has an input of length $i$. Then $L$ and $R$ are both of length $\\leq i - 1$, so by induction, $L$ and $R$ are both sorted. Thus, the inductive step boils down to the statement: \n\n ``When Merge takes as inputs two sorted arrays $L$ and $R$, then it returns a sorted array containing all of the elements of $L$, along with all of the elements of $R$.''\n\n This statement is intuitively true, although proving it rigorously takes a bit of bookkeeping. In fact, it takes another proof by induction! Check out CLRS Section 2.3.1 for a rigorous treatment.\n \\item \\textbf{Conclusion.} By induction, the Inductive hypothesis holds for all $i$. In particular, given an array of any length $n$, \\texttt{MergeSort} returns a sorted version of that array.\n\\end{itemize}\n\n\\subsection{Running time of MergeSort}\nFinally, we get to our first question in this lecture where the answer may not be intuitively obvious. What is the running time of \\texttt{MergeSort}? In the next few lectures, we'll see a few principled ways of analyzing the runtime of a recursive algorithm. Here, we'll just go through one of the ways, which is called the \\texttt{recursion tree} method.\n\nThe idea is to draw a tree representing the computation (see the slides for the visuals). Each node in the tree represents a subproblem, and its children represent the subproblems we need to solve to solve the big sub-problem. The recursion tree for \\texttt{MergeSort} looks something like\nthis:\n\n\\begin{figure}[h!]\n\\centering{}\n\\includegraphics[scale=0.75]{mergesort_tree.png}\n\\end{figure}\n\nAt the top (zeroth) level is the whole problem, which has size $n$. This gets broken into two sub-problems, each of size $n/2$, and so on. At the $t$'th level, there are $2^t$ problems, each of size $n/2^t$\n. This continues until we have $n$ problems of size $1$, which happens at the $log(n)$'th level.\n\n\\textbf{Some notes:}\n\n\\begin{itemize}\n\\item In this class, logarithms will \\textbf{always} be base $2$, unless otherwise noted.\n\\item We are being a bit sloppy in the picture above: what if $n$ is not a power of $2$? Then $n/2^j$ might not be an integer. In the pseudocode above, we actually break a problem of size n into problems of size $\\lfloor n/2 \\rfloor$ and $\\lceil n/2 \\rceil$. Keeping track of this in our analysis will be messy, and it won't add much, so we will ignore it, and for now we will assume that $n$ is a power of $2$ \\footnote{To formally justify the assumption that $n$ is a power of $2$, notice that we can always sort a \\textit{longer} list of length $n' = 2^{\\lceil log_2(n) \\rceil}$. That is, we'll add extra entries, whose values are $\\infty$, to the list. Then we sort the new list of length $n'$, and return the first $n$ values. Since $n' \\leq 2n$ (why?) this won't affect the asymptotic running time. Also see CLRS Section 4.6.2 for a rigorous analysis of the original algorithm with floors and ceilings.}\n\\end{itemize}\n\nIn order to figure out the total amount of work, we will figure out how much work is done at each node in the tree, and add it all up. To that end, we tally up the work that is done in a particular node in the tree—that is, in a particular call to \\texttt{MergeSort}. There are three things:\n\n\\begin{enumerate}\n \\item Checking the base case\n \\item Making recursive calls (but we don't count the work actually done in those recursive calls; that will count in other nodes)\n \\item Running Merge.\n\\end{enumerate}\n\nLet's analyze each of these. Suppose that our input has size $m$ (so that $m = n/2^j$ for some $j$).\n\n\\begin{enumerate}\n \\item Checking the base case doesn't take much time. For concreteness, let us say that it takes one operation to retrieve the length of $A$, and other operation to compare this length to $1$, for a total of two operations.\\footnote{Of course, there's no reason that the ``operation'' of getting the length of $A$ should take the same amount of time as the ``operation'' of comparing two integers. This disconnect is one of the reasons we use big-Oh notation.}\n \\item Making the recursive calls should also be fast. If we implemented the pseudocode well, it should also take a constant number of operations.\n\n \\textbf{Aside:} This is a good point to talk about how we interpret pseudocode in this class. Above, we've written \\texttt{MergeSort(A[:n/2])} as an example of a recursive call. This makes it clear that we are supposed to recurse on the first half of the list, but it's not clear how we actually implement that. Our ``pseudocode'' above is in fact working Python code, and in Python, this implementation, while clear, is a bit inefficient. That is, written this way, Python will actually copy the first $n/2$ elements of the list before sending them to the recursive call. A much better way would be to instead just pass in pointers to the $0$'th and $n/2 - 1$'st index in the list. This would result in a faster algorithm, but kludgier pseudocode. In this class, we generally will opt for cleaner pseudocode, as long as it does not hurt the asymptotic running time of the algorithm. In this case, our simple-but-slower pseudocode turns out not to affect the asymptotic running time, so we'll stick with this.\n\n In light of the above Aside, let's suppose that this step takes $m + 2$ operations, $m/2$ to copy each half of the list over, and 2 operations to store the results. Of course, a better implementation of this step would only take a constant number (say, four) operations.\n \\item The third thing is the tricky part. We claim that the Merge step also takes about $m$ operations.\n\n Consider a single call to Merge, where we'll assume the total size of $A$ is $m$ numbers. How long will it take for Merge to execute? To start, there are two initializations for $i$ and $j$. Then, we enter a for loop which will execute $m$ times. Each loop will require one comparison, followed by an assignment to $S$ and an increment of $i$ or $j$. Finally, we'll need to increment the counter in the for loop $k$. If we assume that each operation costs us a certain amount of time, say $Cost_a$ for assignment, $Cost_c$ for comparison, $Cost_i$ for incrementing a counter, then we can express the total time of the Merge subroutine as follows:\n\n $$\n 2Cost_a + m(Cost_a + Cost_c + 2Cost_i)\n $$\n This is a precise, but somewhat unruly expression for the running time. In particular, it seems difficult to keep track of lots of different constants, and it isn't clear which costs will be more or less expensive (especially if we switch programming languages or machine architectures). To simplify our analysis, we choose to assume that there is some global constant $c_{op}$ which represents the cost of an operation. You may think of $c_{op}$ as $\\max\\{Cost_a, Cost_c , Cost_i, \\dots\\}$. We can then bound the amount of running time for Merge as\n $$\n 2c_{op} + 4c_{op}m = 2 + 4m \\text{ operations}\n $$\n\\end{enumerate}\n\nThus, the total number of operations is at most\n$$\n2 + (m+2) + 4m + 2 \\leq 11m\n$$\n\nusing the assumption that $m \\geq 1$. This is a very loose bound; for larger $m$ this will be much closer to $5m$ than it is to $11m$. But, as we'll discuss more below, the difference between $5$ and $11$ won't matter too much to us, so much as the linear dependence on $m$.\n\nNow that we understand how much work is going on in one call where the input has size $m$, let's add it all up to obtain a bound on the number of operations required for \\texttt{MergeSort}. In a Merge of $m$ numbers, we want to translate this into a bound on the number of operations required for \\texttt{MergeSort}. At first glance, the pessimist in you may be concerned that at each level of recursive calls, we're spawning an exponentially increasing number of copies of\n\\texttt{MergeSort} (because the number of calls at each depth doubles). Dual to this, the optimist in you will notice that at each level, the inputs to the problems are decreasing at an exponential rate (because the input size halves with each recursive call). Today, the optimists win out.\n\n\\textbf{Claim 3.} MergeSort \\textit{requires at most $11n \\log n + 11n$ operations to sort $n$ numbers}.\n\nBefore we go about proving this bound, let’s first consider whether this running time bound is good. We covered in last lecture that more obvious methods of sorting, like \\texttt{InsertionSort}, required roughly $n^2$ operations. How does $n^2 = n \\cdot n$ compare to $n \\cdot \\log n$? An intuitive definition of $\\log n$ is the following: ``Enter n into your calculator. Divide by $2$ until the total is $\\leq 1$. The number of times you divided is the logarithm of $n$.'' This number in general will be significantly smaller than $n$. In particular, if $n = 32$, then $\\log n = 5$; if $n = 1024$, then $\\log n = 10$. Already, to sort arrays of $\\approx 103$ numbers, the savings of $n \\log n$ as compared to $n^2$ will be orders of magnitude. At larger problem instances of $10^6, 10^9$, etc. the difference will become even more pronounced! $n \\log n$ is much closer to growing linearly (with $n$) than it is to growing quadratically (with $n^2$).\n\nOne way to argue about the running time of recursive algorithms is to use recurrence relations. A recurrence relation for a running time expresses the time it takes to solve an input of size $n$ in terms of the time required to solve the recursive calls the algorithm makes. In particular, we can write the running time $T(n)$ for \\texttt{MergeSort} on an array of n numbers as the following\nexpression.\n\n\\begin{align*}\nT(n) &= T(n/2) + T(n/2) + T(Merge(n)) \\\\\n&\\leq 2\\cdot T(n/2) + 11n\n\\end{align*}\n\nThere are a number of sophisticated and powerful techniques for solving recurrences. We will cover many of these techniques in the coming lectures. Today, we can actually analyze the running time directly.\n\n\\textit{Proof of Claim 3} Consider the recursion tree of a call to \\texttt{MergeSort} on an array of $n$ numbers. Assume for simplicity that $n$ is a power of $2$. Let’s refer to the initial call as Level $0$, the proceeding recursive calls as Level $1$, and so on, numbering the level of recursion by its depth in the tree. How deep is the tree? At each level, the size of the inputs is divided in half, and there are no recursive calls when the input size is $\\leq 1$ element. By our earlier ``definition'', this means the bottom level will be Level $\\log n$. Thus, there will be a total of $\\log n + 1$ levels.\n\nWe can now ask two questions: (1) How many subproblems are there at Level $i$? (2) How large are the individual subproblems at Level $i$? We can observe that at the $i$th level, there will be $2^i$ subproblems, each with inputs of size $n/2^i$.\n\nWe’ve already worked out that each sub-problem with input of size $n/2^\ni$ takes at most $11n/2^i$ operations. Now we can add this up:\n\n\\begin{align*}\n \\text{Work at Level }i &= (\\text{number of subproblems}) \\cdot (\\text{work per subproblem}) \\\\\n &\\leq 2^i \\cdot 11 \\left( \\frac{n}{2^i} \\right) \\\\\n &= 11n \\text{ operations.}\n\\end{align*}\n\nImportantly, we can see that the work done at Level $i$ is independent of $i - i$. It only depends on $n$ and is the same for every level. This means we can bound the total running time as follows:\n\n\n\\begin{align*}\n \\text{Total number of operations } &= (\\text{operations per level}) \\cdot (\\text{number of levels}) \\\\\n &\\leq (11n)\\cdot (\\log n + 1) \\\\\n &= 11n \\log n + 11n\n\\end{align*}\nThis proves the claim, and we’re done!\n\n\\end{document}", "meta": {"hexsha": "68fac7a2738e4a7e0acea308699372e3dff380f9", "size": 14230, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "assets/lectures/lecture4.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/lecture4.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/lecture4.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": 85.7228915663, "max_line_length": 1017, "alphanum_fraction": 0.7359100492, "num_tokens": 3872, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46490157137338844, "lm_q2_score": 0.334589441253186, "lm_q1q2_score": 0.1555511570035502}} {"text": "%% LyX 2.3.4.3 created this file. For more info, see http://www.lyx.org/.\n%% Do not edit unless you really know what you are doing.\n\\documentclass[12pt,english]{article}\n\\usepackage{amsmath}\n\\usepackage{amssymb}\n\\usepackage{fontspec}\n\\usepackage{geometry}\n\\geometry{verbose,tmargin=2.5cm,bmargin=2.5cm,lmargin=2.5cm,rmargin=2.5cm}\n\\usepackage{stackrel}\n\n\\makeatletter\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% User specified LaTeX commands.\n\\usepackage{sourcecodepro}\n\\usepackage[parfill]{parskip}\n\\usepackage{enumitem}\n\\setlist[itemize]{leftmargin=*}\n\\usepackage{minted}\n\\usepackage{mdframed}\n\\definecolor{bg}{rgb}{0.95,0.95,0.95}\n\\usepackage{hyperref}\n\\hypersetup{\n colorlinks,\n citecolor=black,\n filecolor=black,\n linkcolor=black,\n urlcolor=black\n}\n\n\\makeatother\n\n\\usepackage{polyglossia}\n\\setdefaultlanguage[variant=american]{english}\n\\begin{document}\n\\UseRawInputEncoding\n\\begin{titlepage} \t\n\\centering \t\n\\vspace{1cm} \t\n{\\scshape\\LARGE VkFFT - Vulkan/CUDA/HIP/OpenCL Fast Fourier Transform library \\par} \t\t\n\\vspace{1.5cm} \t\n{\\huge\\bfseries API guide with examples\\par} \t\n\\vspace{2cm} \t\n{\\Large Dmitrii Tolmachev\\par} \t\n\t\n\\vspace{1cm} \t\n{\\large December 2021, version 1.2.15\\par} \n\\end{titlepage}\n\n\\newpage{}\n\n\\tableofcontents{}\n\n\\newpage{}\n\n\\section{Introduction}\n\nThis document describes VkFFT - Vulkan/CUDA/HIP/OpenCL Fast Fourier\nTransform library. It describes the features and current limitations\nof VkFFT, explains the API and compares it to other FFT libraries\n(like FFTW and cuFFT) on the set of examples. It is by no means the\nfinal version, so if there is something unclear - feel free to contact\nme (dtolm96@gmail.com), so I can update it. \n\n\\newpage{}\n\n\\section{Using the VkFFT API}\n\nThis chapter will cover the basics of VkFFT. Fourier transform of\na sequence is called Discrete Fourier Transform (DFT). It is defined\nby the following formula:\n\\begin{equation}\nX_{k}=\\stackrel[n=0]{N-1}{\\sum}x_{n}e^{-\\frac{2\\pi i}{N}nk}=\\mathrm{DFT}{}_{N}(x_{n},k),\\label{eq:dft}\n\\end{equation}\n\nwhere $x_{n}$is the input sequence, $N$ is the length of the input\nsequence and $k\\in[0,N-1],k\\in\\mathbb{Z}$is the output index, corresponding\nto frequency in Fourier space. Corresponding to that, inverse DFT\nis defined as following:\n\\begin{equation}\nx_{n}=\\stackrel[k=0]{\\mathrm{N-1}}{\\sum}X_{k}e^{\\frac{2\\pi i}{N}nk}=\\mathrm{iDFT}{}_{N}(X_{k},n)\n\\end{equation}\n\nVkFFT follows the same definitions as FFTW and cuFFT - forward FFT\nhas the exponent sign $-1$, while the inverse has the exponent sign\n$1$. Note, that inverse transform by default is unnormalized, so\nto get the input sequence after FFT + iFFT, the user has to divide\nthe result by $N$.\n\n\\subsection{Installing VkFFT}\n\nVkFFT is distributed as a header-only library. The installation process\nconsists of the following steps:\n\\begin{enumerate}\n\\item \\begin{flushleft}\nCopy vkFFT.h file into one of the directories included in the user's\nproject.\n\\par\\end{flushleft}\n\\item Define VKFFT\\_BACKEND as a number corresponding to the API used in\nthe user's project: 0 - Vulkan, 1 - CUDA, 2 - HIP, 3 - OpenCL. Definition\nis done like:\\begin{mdframed}[backgroundcolor=bg]\n\\begin{minted}[tabsize=4,obeytabs,breaklines]{make}\n-DVKFFT_BACKEND=X\n\\end{minted}\n\\end{mdframed} in GCC or as \\begin{mdframed}[backgroundcolor=bg]\n\\begin{minted}[tabsize=4,obeytabs,breaklines]{cmake}\nset(VKFFT_BACKEND 1 CACHE STRING \"0 - Vulkan, 1 - CUDA, 2 - HIP, 3 - OpenCL\")\n\\end{minted}\n\\end{mdframed}in CMake.\n\\item Depending on the API backend, the project must use additional libraries\nfor run-time compilation:\n\\begin{enumerate}\n\\item Vulkan API: SPIRV, glslang and Vulkan. Define VK\\_API\\_VERSION to\nthe available Vulkan version. Sample CMakeLists can look like this:\\begin{mdframed}[backgroundcolor=bg]\n\\begin{minted}[tabsize=4,obeytabs,breaklines]{cmake}\nfind_package(Vulkan REQUIRED)\ntarget_compile_definitions(${PROJECT_NAME} PUBLIC -DVK_API_VERSION=11)#10 - Vulkan 1.0, 11 - Vulkan 1.1, 12 - Vulkan 1.2 \ntarget_include_directories(${PROJECT_NAME} PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/glslang-master/glslang/Include/) \nadd_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/glslang-master)\n\ntarget_include_directories(${PROJECT_NAME} PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/vkFFT/)\nadd_library(VkFFT INTERFACE)\ntarget_compile_definitions(VkFFT INTERFACE -DVKFFT_BACKEND=0)\n\ntarget_link_libraries(${PROJECT_NAME} PUBLIC SPIRV glslang Vulkan::Vulkan VkFFT)\n\\end{minted}\n\\end{mdframed}\n\\item CUDA API: CUDA and NVRTC. Sample CMakeLists can look like this:\\begin{mdframed}[backgroundcolor=bg]\n\\begin{minted}[tabsize=4,obeytabs,breaklines]{cmake}\nfind_package(CUDA 9.0 REQUIRED) \t\nenable_language(CUDA) \t\nset_property(TARGET ${PROJECT_NAME} PROPERTY CUDA_ARCHITECTURES 35 60 70 75 80 86) \t\ntarget_compile_options(${PROJECT_NAME} PUBLIC \"$<$:SHELL: \t\n\t-DVKFFT_BACKEND=${VKFFT_BACKEND} \t\n\t-gencode arch=compute_35,code=compute_35\n\t-gencode arch=compute_60,code=compute_60\n\t-gencode arch=compute_70,code=compute_70\n\t-gencode arch=compute_75,code=compute_75\n\t-gencode arch=compute_80,code=compute_80\n\t-gencode arch=compute_86,code=compute_86>\")\nset_target_properties(${PROJECT_NAME} PROPERTIES CUDA_SEPARABLE_COMPILATION ON)\nset_target_properties(${PROJECT_NAME} PROPERTIES CUDA_RESOLVE_DEVICE_SYMBOLS ON)\n\nfind_library(CUDA_NVRTC_LIB libnvrtc nvrtc HINTS \"${CUDA_TOOLKIT_ROOT_DIR}/lib64\" \"${LIBNVRTC_LIBRARY_DIR}\" \"${CUDA_TOOLKIT_ROOT_DIR}/lib/x64\" /usr/lib64 /usr/local/cuda/lib64)\n\ntarget_include_directories(${PROJECT_NAME} PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/vkFFT/)\nadd_library(VkFFT INTERFACE)\ntarget_compile_definitions(VkFFT INTERFACE -DVKFFT_BACKEND=1)\n\ntarget_link_libraries(${PROJECT_NAME} PUBLIC ${CUDA_LIBRARIES} cuda ${CUDA_NVRTC_LIB} VkFFT)\n\\end{minted}\n\\end{mdframed}\n\\item HIP API: HIP and HIPRTC. Sample CMakeLists can look like this:\\begin{mdframed}[backgroundcolor=bg]\n\\begin{minted}[tabsize=4,obeytabs,breaklines]{cmake}\nlist(APPEND CMAKE_PREFIX_PATH /opt/rocm/hip /opt/rocm)\nfind_package(hip)\n\ntarget_include_directories(${PROJECT_NAME} PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/vkFFT/)\nadd_library(VkFFT INTERFACE)\ntarget_compile_definitions(VkFFT INTERFACE -DVKFFT_BACKEND=2)\n\ntarget_link_libraries(${PROJECT_NAME} PUBLIC hip::host VkFFT)\n\\end{minted}\n\\end{mdframed}\n\\item OpenCL API: OpenCL. Sample CMakeLists can look like this:\\begin{mdframed}[backgroundcolor=bg]\n\\begin{minted}[tabsize=4,obeytabs,breaklines]{cmake}\nfind_package(OpenCL REQUIRED)\n\ntarget_include_directories(${PROJECT_NAME} PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/vkFFT/)\nadd_library(VkFFT INTERFACE)\ntarget_compile_definitions(VkFFT INTERFACE -DVKFFT_BACKEND=3)\n\ntarget_link_libraries(${PROJECT_NAME} PUBLIC OpenCL::OpenCL VkFFT)\n\\end{minted}\n\\end{mdframed}\n\\end{enumerate}\n\\end{enumerate}\n\n\\subsection{Fourier Transform Setup}\n\nVkFFT follows a plan structure like FFTW/cuFFT with a notable difference\n- there is a unified interface to all transforms. This means that\nthere are no separate functions like fftPlan1D/fftPlan2D/fftPlanMany/etc.\nThe initialization is done through a single configuration struct -\nVkFFTConfiguration. Each parameter of it will be covered in detail\nin this document. Plans in VkFFT are called VkFFTApplication and they\nare created with a unified initializeVkFFT call. \n\nAs the code is written in C, don't forget to zero-initialize used\nstructs!\n\nDuring the initializeVkFFT(VkFFTApplication{*} app, VkFFTConfiguration\ninputLaunchConfiguration) call VkFFT performs kernel generation and\ncompilation from scratch (kernel reuse may be added later). The overall\nprocess of initialization looks like this:\n\\begin{enumerate}\n\\item Get device parameters, perform default initialization of internal\ncopy of configuration struct inside the VkFFTApplication, then fill\nin user-defined parameters from inputLaunchConfiguration.~VkFFTApplication\nis passed as a pointer, so initializeVkFFT modifies the user-provided\napplication.\n\\item By default, there are two internal FFT plans created - inverse and\nforward. Multidimensional FFT is done as a combination of 1D FFTs\nin each axis direction. For each axis, the VkFFTPlanAxis function\nis called.\n\\item VkFFTPlanAxis configures parameters for each axis. It may perform\nadditional memory allocations (see: memory allocated by VkFFT).\n\\item shaderGenVkFFT generates corresponding to the axis code in a char\nbuffer (each axis may require more than one kernel: see Four-step\nFFT, Bluestein's algorithm for FFT). \n\\item Code is then compiled with the run-time compiler of the specified\nbackend.\n\\end{enumerate}\nOnce the plan is no longer need, a call to the deleteVkFFT function\nfrees all the allocated resources. There are no processes launched\nthat continue to work outside of the VkFFT related function calls.\n\n\\subsection{Fourier Transform types and their definitions}\n\nVkFFT supports commonly used Complex to complex (C2C), real to complex\n(R2C), complex to real (C2R) transformations and real to real (R2R)\nDiscrete Cosine Transformations of types II, III and IV. VkFFT uses\nthe same definitions as FFTW, except for the multidimensional FFT\naxis ordering: in FFTW dimensions are ordered with the decrease in\nconsecutive elements stride, while VkFFT does the opposite - the first\naxis is the non-strided axis (the one that has elements located consecutively\nin memory with no gaps, usually named as the X-axis). So, in FFTW\ndimensions are specified as ZYX and in VkFFT as XYZ. This felt more\nlogical to me - no matter if there are 1, 2 or 3 dimensions, the user\ncan always find the axis with the same stride at the same position.\nThis choice doesn't require any modification in the user's data management\n- just provide the FFT dimensions in the reverse order to VkFFT. \n\nIn addition to up to the 3 dimensions of FFT, VkFFT supports two forms\nof batching: the number of coordinates and the number of systems.\nThe choice of two distinct batching ways is made to support matrix-vector\nconvolutions, where the kernel is presented as a matrix. Overall,\nthe layout of VkFFT can be described as WHDCN - width, height, depth,\ncoordinate and number of systems (in order of increasing strides,\nstarting with 1 for width). Coordinate and number of systems can be\n1, if the user has 1 as one of the FFT dimensions, the user can omit\nit from setup altogether as FFT of size 1 produces the same number\nas the input. Often, the coordinate part of the layout is not used,\nso the main batching is done by specifying N.\n\nVkFFT assumes that complex numbers are stored consecutively in memory:\nRIRIRI... where R denotes the real part of the complex number and\nI denotes the imaginary part. There is no difference between using\na float2/double2/half2 container or access memory as float/double/half\nas long as the byte order remains the same.\n\nThis section and the next one will cover the basics of VkFFT data\nlayouts and memory management. \n\n\\subsubsection{C2C transforms}\n\nThe base FFT algorithm - C2C in VkFFT has the same definition as FFTW.\nForward FFT has the exponent sign $-1$, while the inverse has the\nexponent sign $1$. By default, the inverse transform is unnormalized.\n$N_{x}N_{y}N_{z}$ complex numbers map to $N_{x}N_{y}N_{z}$ complex\nnumbers and no additional padding is required. The resulting data\norder will be the same as in FFTW/cuFFT, unless special parameters\nare provided in configuration (see: advanced memory management)\n\n\\subsubsection{R2C/C2R transforms}\n\nR2C/C2R transforms can be explained as C2C transforms with imaginary\npart set to zero. They exploit Hermitian symmetry of the result: $X_{k}=X_{N-k}^{*}$\non the non-strided axis (the one that has elements located consecutively\nin memory with no gaps). This results in s reduction of required memory\nto store the complex result - we may only store $floor(\\frac{N_{x}}{2})+1$\ncomplex numbers instead of $N_{x}$. However, this results in memory\nrequirements mismatch between input and output in R2C: $floor(\\frac{N_{x}}{2})+1$\ncomplex elements will require $N_{x}+2$ real numbers worth of memory\nfor even $N_{x}$ and $N_{x}+1$ real numbers worth of memory for\nodd $N_{x}$. For C2R the situation is reversed. There are two approaches\nto this problem: pad each sequence of the non-strided axis with zeros\nto the required length or use out-of-place mode. More information\non how to do this will be given in the next section.\n\n\\subsubsection{R2R (DCT) transforms}\n\nR2R transforms in VkFFT are implemented in the form of Discrete cosine\ntransforms of types I, II, III and IV. Their definitions and transforms\nresults match FFTW:\n\\begin{enumerate}\n\\item DCT-I: $X_{k}=x_{0}+(-1)^{k}x_{N-1}+2\\stackrel[n=1]{N-2}{\\sum}x_{n}cos(\\frac{\\pi}{N-1}nk)$,\ninverse of DCT-I (itself)\n\\item DCT-II: $X_{k}=2\\stackrel[n=1]{N-1}{\\sum}x_{n}cos(\\frac{\\pi}{N}(n+\\frac{1}{2})k)$,\ninverse of DCT-III\n\\item DCT-III: $X_{k}=x_{0}+2\\stackrel[n=1]{N-1}{\\sum}x_{n}cos(\\frac{\\pi}{N}n(k+\\frac{1}{2}))$,\ninverse of DCT-II\n\\item DCT-IV: $X_{k}=2\\stackrel[n=0]{N-1}{\\sum}x_{n}cos(\\frac{\\pi}{N}(n+\\frac{1}{2})(k+\\frac{1}{2}))$,\ninverse of DCT-IV (itself)\n\\end{enumerate}\nR2R transforms are performed by redefinition of them to the C2C transforms\n(internal C2C sequence length can be different from the input R2R\nsequence length). R2R transform performs a one-to-one mapping between\nreal numbers, so they don't require stride management, unlike R2C/C2R.\n\n\\subsection{Memory management, data layouts for different transforms}\n\n\\subsubsection{VkFFT buffers}\n\nVkFFT allows for explicit control over the data flow, which makes\nboth in-place and out-of-place transforms possible. Buffers are passed\nto VkFFT as VkBuffer pointer in Vulkan, as double void pointers in\nCUDA/HIP and as cl\\_mem pointer in OpenCL. This is done to maintain\na uniform data pattern because some of the buffers can be allocated\nautomatically. \n\nThe main buffer is called buffer and it always has to be provided,\neither during the plan creation or when the plan is executed. All\ncalculations are performed in this buffer and it is always overwritten.\nTo do calculations out-of-place, VkFFT provides an option to specify\ninputBuffer/outputBuffer buffer. The logic behind their usage is fairly\nsimple - the user specifies inputBuffer if the input data has to be\nread from a buffer, different from the main buffer. As the data is\nread only once and nothing is written back to the inputBuffer, this\nallows doing truly out-of-place transformations. The same logic applies\nto outputBuffer with the difference that it is responsible for the\nabsolute last write of the VkFFT. It is possible to use all three\nbuffers to create complex data management paths.\n\nIt must be noted, that sometimes FFT can not be done inside one buffer\n(see: Four-Step FFT algorithm, Bluestein's algorithm). To compute\nFFT in these cases, there exists tempBuffer buffer and data is transferred\nbetween the main buffer and tempBuffer during the FFT execution. The\nordering of transfers between the main buffer and tempBuffer is done\nin such a way, so the initial data read and final data write are obeying\nthe configuration from the previous paragraph. Users can allocate\ntempBuffer themselves of some memory that does not have any useful\ninformation at the time of FFT execution (the tempBuffer size can\ndepend on the configuration, so this is a rather advanced operation\n- read more in the advanced memory management section) or allow VkFFT\nto manage tempBuffer allocation itself (tempBuffer will be freed at\nthe deleteVkFFT call).\n\nTo compute convolutions and cross-correlations, a kernel buffer has\nto be specified. It must have the same layout as the result of the\nFFT transform.\n\n\\subsubsection{VkFFT buffers strides. A special case of R2C/C2R transforms}\n\nTo have better control of memory, the user can specify the strides\nbetween consecutive elements of different axis for H (height), D (depth)\nand C (coordinate) parts of the WHDCN layout (W (width) stride is\nfixed to be 1, N (number of systems) stride will be consecutive of\nC in memory if C is used, otherwise N will propagate the previous\nnon-uniform stride multiplied by the corresponding axis length). Strides\nare specified not in bytes, but in the element type used - similar\nto the way how the user would access the corresponding element in\nthe array. If all elements are consecutive in C2C, stride for H will\nbe equal to the FFT length of W axis, stride for D will be multiplication\nof first two FFT axis lengths, stride for C will be multiplication\nof first three FFT axis lengths, etc. These are the default values\nof C2C and R2R strides if they are not explicitly specified.\n\nOne of the main use-cases of strides comes to solve the R2C/C2R Hermitian\nsymmetry H stride mismatch - for real space, it is equal to $N_{x}$\nreal elements and for the frequency space it is equal to $floor(\\frac{N_{x}}{2})+1$\ncomplex numbers. So, with strides it is possible to use a buffer,\npadded to $2\\cdot(floor(\\frac{N_{x}}{2})+1)$ real elements in H stride\n(all elements between $N_{x}$ and $2\\cdot(floor(\\frac{N_{x}}{2})+1)$\nwill not be read so it does not matter what data is there before the\nwrite stage). All other strides are done as a multiplication between\nthe previous stride and the number of elements in the previous axis.\nThese are the default values of R2C/C2R strides in in-place mode if\nthey are not explicitly specified.\n\nIt is possible to specify separate sets of strides for all user-defined\nbuffers: bufferStride for the main buffer, inputStride for input buffer,\noutputStride for output buffer (kernel stride is assumed to be the\nsame as bufferStride, tempBuffer strides are configured automatically). \n\nFor an out-of-place R2C FFT, there is no need to pad buffer with real\nnumbers, so VkFFT uses natural H stride as default there - $N_{x}$\nreal elements for real space and $floor(\\frac{N_{x}}{2})+1$ complex\nnumbers for the frequency space.\n\nAn out-of-place C2R FFT is a more tricky transform. In the multidimensional\ncase, the main buffer will be written to and read from multiple times.\nThe intermediate stores have a complex layout, which requires more\nspace than the output real layout, so in order not to modify the input\ndata, there exist two options. First, pad the real data layout has\nto $2\\cdot(floor(\\frac{N_{x}}{2})+1)$ real elements in H stride (complex\nbuffer will be used as inputBuffer, real buffer as buffer). Second,\nuse the third buffer, so both input and output buffers have their\noriginal layouts (complex buffer will be used as inputBuffer, the\nmain buffer for calculations is buffer and output real buffer as outputBuffer).\n\n\\subsection{VkFFT algorithms}\n\nVkFFT implements a wide range of algorithms to compute different types\nof FFTs but all of them can be reduced to a mixed-radix Cooley-Tukey\nFFT algorithm in the Stockham autosort form. The main idea behind\nit is to decompose the sequence as a set of primes, for each of which\nFFT can be written down exactly. As of now, VkFFT has radix implementations\nfor primes up to 13, so all C2C sequences decomposable into a multiplication\nof such primes will be done purely with the Stockham algorithm. Below\nadditional algorithms and their use-cases are described.\n\n\\subsubsection{Bluestein's algorithm}\n\nA complex algorithm that is used in cases where the sequence is not\ndecomposable with implemented radix butterflies (currently - primes\nup to 13). It is derived by replacing $nk=\\left(n^{2}+k^{2}-(n-k)^{2}\\right)/2$\nin \\ref{eq:dft}:\n\n\\begin{align}\nX_{k} & =\\left(e^{-\\pi i\\frac{k^{2}}{N}}\\right)\\stackrel[n=0]{N-1}{\\sum}\\left(x_{n}e^{-\\pi i\\frac{n^{2}}{N}}\\right)\\left(e^{\\pi i\\frac{\\left(k-n\\right)^{2}}{N}}\\right)=b_{k}^{\\ast}\\stackrel[n=0]{N-1}{\\sum}a_{n}b_{k-n}\\label{eq:dft-1}\\\\\na_{n} & =x_{n}b_{n}^{\\ast}\\\\\nb_{n} & =e^{\\pi i\\frac{n^{2}}{N}}\n\\end{align}\n\nHere FFT is represented as a convolution between two sequences: $a_{n}$\nand $b_{n}$, which can be performed by the means of convolution theorem:\n\n\\begin{equation}\nF\\{a\\ast b\\}=F\\{a\\}\\cdot F\\{b\\}\n\\end{equation}\n\nBy padding $a_{n}$ and $b_{n}$ to a sequence length decomposable\nwith implemented radix butterflies with a size of at least $2N-1$\n(because the length of $b_{n}$ is $2N-1$), we can perform FFT of\nany length. FFT of $b_{n}$ can be precomputed, so overall this algorithm\nrequires at least 4x the computations and more memory transfers. This\nalgorithm can be combined with all other algorithms implemented in\nVkFFT. If an FFT can not be done in a single upload, a tempBuffer\nhas to be allocated (because the logical FFT buffer size is bigger\nthan the original system).\n\n\\subsubsection{The Four-Step FFT algorithm}\n\nGPUs and CPUs have a hierarchical memory model - the closer memory\nto the unit that performs the computations, the faster its speed and\nthe lower the size. So it is advantageous to split FFTs, not to the\nlowest primes, but to some bigger multiplication of those primes,\nthen upload this subsequence to the closest cache level to the cores\nand do the final prime split there. The absolute lowest level is the\nregister file, however, it does not allow for thread communications\noutside the warp. For this purpose, modern GPUs employ shared memory\n- a fast memory with a bank structure that is visible to all threads\nin a thread block. The usual sizes of it change on a scale from 16KB\nto 192KB and it is often beneficial to use it fully. However, if the\nfull sequence can not fit inside the shared memory, FFT has to be\ndone in multiple uploads - with the Four Step FFT algorithm. The main\nidea behind it is to represent a big 1D sequence as a 2D (or 3D for\nthe three-upload scheme) FFT - we first do FFT along the columns,\nthen the rows, then transpose the result and multiply by a special\nset of phase vectors. Similar decomposition idea as the main Cooley-Tukey\nalgorithm. However, performing transpositions in-place is a complicated\ntask - especially for a non-trivial ratio between dimensions. It will\nalso require an additional read/write stage, as it can not be merged\nwith the last write of the FFT algorithm. The easiest and the most\nperformant solution is to use a tempBuffer (it is the main reason\nfor having this functionality, actually) and store intermediate FFT\nresults out-of-place. This way the last transposition step can be\nmerged with the write step, as we can overwrite the output buffer\nwithout losing data.\n\nTo estimate if your sequence size is single upload or not, divide\nthe amount of available shared memory (48KB - Nvidia GPUs with Vulkan/OpenCL\nAPI, 64KB - AMD GPUs, 100KB - Nvidia GPUs in CUDA API) by the complex\nsize used for calculations (8 byte - single precision, 16 byte - double\nprecision). For 64KB of shared memory, we get 8192 as max single upload\nsingle-precision non-strided FFT, 4096 for double precision. For strided\naxes (H and D parts of the layout) these numbers have to be divided\nby 4 and 2 respectively to achieve coalescing, resulting in 2048 length\nfor single upload in both precisions. For more information on coalescing\nsee: coalescing API reference.\n\nIn the case of the Four-Step FFT algorithm, tempBuffer size has to\nbe at least the same as the default main buffer size. It does not\nmatter how many uploads are in the Four Step FFT algorithm - only\na single tempBuffer is required. In this document, all systems that\ncan fit in the shared memory entirely and be done without the Four\nStep FFT algorithm (and multiple uploads) are called single upload\nsystems.\n\nIf the last transposition is not required (the output data is allowed\nto be in not unshuffled form) it can be disabled during the configuration\nphase. This way tempBuffer will not be needed and all computations\nwill be done in-place (unless Bluestein's algorithm is used). An example\nuse-case of this is convolutions - if the kernel is computed with\nthe same operation ordering, point-wise multiplication in the frequency\ndomain is not dependent on the correct data ordering and the inverse\nFFT will restore the original layout.\n\n\\subsubsection{R2C/C2R FFTs}\n\nA typical approach to a single upload R2C/C2R system is to just set\nthe imaginary part to zero inside the shared memory and do a simple\nC2C transform. This doesn't affect the amount of memory transferred\nfrom VRAM and is not a bad approach as FFT is a memory-bound algorithm,\nhowever, this can be improved in multidimensional (in HDCN part of\nthe layout) case by the composition of a single C2C sequence from\ntwo real sequences and some write for R2C/read for C2R post-processing.\nBoth of these algorithms are implemented in VkFFT. Note, that R2C/C2R\nonly affects the non-strided axis (W). All strided axes are still\ndone as C2C.\n\n\\subsubsection{R2C/C2R multi-upload FFT algorithm}\n\nFor even sequences there exists an easy mapping between R2C/C2R FFTs\nand the C2C of half the size. In this case, all even indices (starting\nfrom 0) are read as the real values of a complex number and all odd\nindices are read as the imaginary values. This C2C sequence can be\ndone with the help of the Four-Step FFT algorithm. When FFT is done,\nseparate post-processing for R2C/pre-processing for C2R is applied.\n\n\\subsubsection{R2R Discrete Cosine Transforms}\n\nThere exist many different mappings between DCT and FFT. As of now,\nVkFFT has the following algorithms implemented (all single-upload\nfor now):\n\\begin{itemize}\n\\item DCT-I - mapping between R2R and C2C of the $2N-2$ length. For non-strided\naxis can use an optimization similar to the R2C/C2R multidimensional\ncase (setting the imaginary part to the next FFT sequence).\n\\item DCT-II/DCT-III - mapping between R2R and C2C of the same length. For\nnon-strided axis can use an optimization similar to the R2C/C2R multidimensional\ncase (setting the imaginary part to the next FFT sequence).\n\\item DCT-IV - for even sizes, mapping between R2R and C2C sequence of half-length.\nFor odd sizes mapping to the FFT of the same length (for non-strided\naxis can use an optimization similar to the R2C/C2R multidimensional\ncase (setting the imaginary part to the next FFT sequence)).\n\\end{itemize}\n\n\\subsubsection{Register overutilization}\n\nNot an FFT algorithm by itself, but an optimization to do bigger sequences\nin a single upload instead of switching to the Four Step FFT algorithm.\nThe main idea behind it is to use a register file (which is often\nbigger than the amount of shared memory) to store the sequence and\nuse shared memory only as a communication buffer. This is useful in\nVulkan and OpenCL APIs on Nvidia GPU, as they are only allowed to\nallocate 48KB of shared memory with a register file having the size\nof 256KB.\n\n\\subsubsection{Zero padding}\n\nNot an FFT algorithm by itself, but a memory management optimization.\nIf the user's system has parts that are known to be zero - for example,\nwhen an open system is modeled, to avoid a circular part of the FFT\nsystem has to be padded with zeros up to 2x in each direction. VkFFT\ncan omit sequences full of zeros and don't perform the corresponding\nmemory transfers and computations, as the output result will be zero.\nThis way it is possible to get up to two times speed increase in the\n2D case and up to 3x increase in the 3D case. \n\n\\subsubsection{Convolution and cross-correlation support}\n\nWith the help of the Convolution theorem, which states that the Fourier\ntransform of a convolution is the pointwise product of signals Fourier\ntransforms, it is possible to perform convolution with $NlogN$ complexity,\ncompared to $N^{2}$ complexity of the simple multiplication approach.\nThis is extremely useful for kernels spanning more than 50 elements\nin size. VkFFT can merge the last step FFT, kernel multiplication\nin the Fourier domain and the first step of inverse FFT to provide\nsubstantial memory transfer savings. Moreover, FFTs of big sequences\ncan be performed without data reordering, which results in a better\nlocality. \n\n\\subsection{VkFFT accuracy}\n\nTo measure how VkFFT (single/double/half precision) results compare\nto cuFFT/rocFFT (single/double/half precision) and FFTW (double precision),\nmultiple sets of systems covering full supported C2C/R2C+C2R/R2R FFT\nrange are filled with random complex data on the scale of {[}-1,1{]}\nand one transform was performed on each system. Samples 11(single),\n12(double), 13(half), 14(non-power of 2 C2C, single), 15(R2C+C2R,\nsingle), 16(DCT-I/II/III/IV, single), 17(DCT-I/II/III/IV, double),\n18(non-power of 2 C2C, double) are available in VkFFT Benchmark Suite\nto perform VkFFT verification on any of the target platforms. Overall,\nthe Cooley-Tukey algorithm (Stockham autosort) exhibits logarithmic\nrelative error scaling, similar to those of other GPU FFT libraries.\nTypically, the more computationally expensive algorithm is - the worse\nits precision is. So, Bluestein's algorithm has lower accuracy than\nStockham autosort algorithm.\n\nSingle precision in VkFFT supports two modes of calculation - by using\nthe on-chip Special Function Units that can compute sines and cosines\non the go or by using the precomputed on CPU look-up tables. For Nvidia\nand AMD GPUs, SFU provide great precision, while Intel iGPUs and mobile\nGPUs must use LUT to perform FFTs correctly.\n\nDouble precision in VkFFT also supports two modes of calculation -\nby using polynomial sincos approximation and computing them on-chip\nor by using precomputed LUT as well. The second option is the better\none, as polynomial sincos approximation is too compute-heavy for modern\nGPUs. It is selected by default on all devices.\n\nHalf precision is currently only supported in the Vulkan backend and\nis often experiencing precision problems with the first number of\nthe resulting FFT sequence, which is the sum of all input numbers.\nHalf precision is implemented only as a memory trick - all on-chip\ncomputations are done in single precision, but this doesn't help with\nthe first number problem. Half precision can use SFU or LUT as well.\n\nVkFFT also supports mixed-precision operations, where memory storing\nis done at lower precision, compared to the on-chip calculations.\nFor example, it is possible to read data in single precision, do calculations\nin double and store data back in single precision. \n\n\\subsection{VkFFT additional memory allocations}\n\nIn this section, all GPU memory allocations that are done by VkFFT\nare described. There are up to three situations when VkFFT allocates\nmemory. All of the VkFFT allocated memory is freed at the deleteVkFFT\ncall.\n\n\\subsubsection{LUT allocations}\n\nThis memory is used to store precomputed twiddle factors and phase\nvectors used during the computation. This buffer can have:\n\\begin{itemize}\n\\item twiddle factors for each radix stage of Stockham FFT calculation\n\\item phase vectors used in the Four Step FFT algorithm between stages\n\\item phase vectors used in DCT-II/III/IV to perform a mapping between R2R\nand C2C\n\\end{itemize}\nVkFFT manages LUT allocations by itself and they are performed during\nthe initializeVkFFT call. LUT are allocated per axis, though some\nof them can be reused if the axes have the same LUT. Inverse and forward\nFFT plans share the same LUT (conjugation is performed on-chip).\n\n\\subsubsection{The Four-Step FFT algorithm - tempBuffer allocation}\n\nTo perform the merging of the transposition with the last upload of\nan axis, VkFFT requires additional memory to mimic an out-of-place\nexecution. This memory is located in tempBuffer and has to be of at\nleast the same size as the main buffer. It is possible for the users\nto allocate it themselves, though if this is not done, VkFFT can do\nthe allocation automatically (the size of the tempBuffer will be the\nsame as the main buffer, unless the logical dimensions of FFT are\nbigger than user-defined - then, it will allocate the system with\nthe minimal size, that can cover maximal logical system size used\nin any of the axes - see next subsection).\n\n\\subsubsection{Bluestein's buffers allocation}\n\nTo do Bluestein's FFT algorithm, precomputed sequences $b_{n}=e^{\\pi i\\frac{n^{2}}{N}}$,\n$FFT(b_{n})$ and $iFFT(b_{n})$ are required. For each axis, they\ncan be different and are computed separately (unless VkFFT can determine\nthat they match, then the buffers are allocated only once). Notably,\nas Bluestein's algorithm pads the sequence length to at least $2N-1$,\nif it can not be done in a single upload and the Four Step algorithm\nhas to be used, the intermediate storage required will be bigger than\nthe main buffer size. In this case, tempBuffer must always be allocated.\nAs the padded sequence can be different for each of the dimensions,\nthe required size of the tempBuffer will also vary. VkFFT determines\nthe biggest size needed among axes and allocated tempBuffer of this\nsize.\n\n\\newpage{}\n\n\\section{VkFFT API Reference}\n\nThis section covers error codes, API functions that can be used by\nthe user and configuration parameters.\n\n\\subsection{Return value VkFFTResult}\n\nAll VkFFT Library return values except for VKFFT\\_SUCCESS are used\nin case of a failure and provide information on what has gone wrong.\nVkFFTResult is unified among different backends, though some of its\nvalues may not be used in specific backends. Possible return values\nof VkFFTResult are defined as following:\n\n\\begin{mdframed}[backgroundcolor=bg]\n\\begin{minted}[tabsize=4,obeytabs,breaklines]{C}\ntypedef enum VkFFTResult { \t\nVKFFT_SUCCESS = 0,\t// The VkFFT operation was successful\nVKFFT_ERROR_MALLOC_FAILED = 1,\t// Some malloc call inside VkFFT has failed. Report this to the GitHub repo\nVKFFT_ERROR_INSUFFICIENT_CODE_BUFFER = 2,\t// Generated kernel is bigger than default kernel array. Increase it with maxCodeLength parameter of configuration.\nVKFFT_ERROR_INSUFFICIENT_TEMP_BUFFER = 3,\t// Temporary string used in kernel generation is bigger than default temporary string array. Increase it with maxTempLength parameter of configuration.\nVKFFT_ERROR_PLAN_NOT_INITIALIZED = 4,\t// Code attempts to use uninitialized plan (it is zero inside VkFFTApplication)\t\t\nVKFFT_ERROR_NULL_TEMP_PASSED = 5,\t// Internal kernel generation error\nVKFFT_ERROR_INVALID_PHYSICAL_DEVICE = 1001,\t// No physical device is provided (Vulkan API)\nVKFFT_ERROR_INVALID_DEVICE = 1002,\t// No device is provided (All APIs)\nVKFFT_ERROR_INVALID_QUEUE = 1003,\t// No queue is provided (Vulkan API)\nVKFFT_ERROR_INVALID_COMMAND_POOL = 1004,\t// No command pool is provided (Vulkan API)\nVKFFT_ERROR_INVALID_FENCE = 1005,\t// No fence is provided (Vulkan API)\nVKFFT_ERROR_ONLY_FORWARD_FFT_INITIALIZED = 1006,\t// VkFFT tries to access inverse FFT plan, when appliction is created with makeForwardPlanOnly flag\nVKFFT_ERROR_ONLY_INVERSE_FFT_INITIALIZED = 1007,\t// VkFFT tries to access forward FFT plan, when appliction is created with makeInversePlanOnly flag\nVKFFT_ERROR_INVALID_CONTEXT = 1008,\t// No context is provided (OpenCL API)\nVKFFT_ERROR_INVALID_PLATFORM = 1009,\t// No platform is provided (OpenCL API)\nVKFFT_ERROR_EMPTY_FFTdim = 2001,\t// Number of dimensions is not provided in the configuration\nVKFFT_ERROR_EMPTY_size = 2002,\t// Array of dimensions is not provided in the configuration\nVKFFT_ERROR_EMPTY_bufferSize = 2003,\t// Buffer size has to be provided during the application creation\nVKFFT_ERROR_EMPTY_buffer = 2004,\t// Buffer has te be specified either at the application creation stage or during launch through VkFFTLaunchParams struct\nVKFFT_ERROR_EMPTY_tempBufferSize = 2005,\t// Same error as VKFFT_ERROR_EMPTY_bufferSize if userTempBuffer is enabled\nVKFFT_ERROR_EMPTY_tempBuffer = 2006,\t// Same error as VKFFT_ERROR_EMPTY_buffer if userTempBuffer is enabled\nVKFFT_ERROR_EMPTY_inputBufferSize = 2007,\t// Same error as VKFFT_ERROR_EMPTY_bufferSize if isInputFormatted is enabled\nVKFFT_ERROR_EMPTY_inputBuffer = 2008,\t// Same error as VKFFT_ERROR_EMPTY_buffer if isInputFormatted is enabled\nVKFFT_ERROR_EMPTY_outputBufferSize = 2009,\t// Same error as VKFFT_ERROR_EMPTY_bufferSize if isOutputFormatted is enabled\nVKFFT_ERROR_EMPTY_outputBuffer = 2010,\t// Same error as VKFFT_ERROR_EMPTY_buffer if isOutputFormatted is enabled\nVKFFT_ERROR_EMPTY_kernelSize = 2011,\t// Same error as VKFFT_ERROR_EMPTY_bufferSize if performConvolution is enabled\nVKFFT_ERROR_EMPTY_kernel = 2012,\t// Same error as VKFFT_ERROR_EMPTY_buffer if performConvolution is enabled\nVKFFT_ERROR_UNSUPPORTED_RADIX = 3001,\t// VkFFT has encountered unsupported radix (more than 13) during decomposition and Bluestein's FFT fallback did not work\nVKFFT_ERROR_UNSUPPORTED_FFT_LENGTH = 3002,\t// VkFFT can not do this sequence length currently - it requires mor than three-upload Four step FFT\nVKFFT_ERROR_UNSUPPORTED_FFT_LENGTH_R2C = 3003,\t// VkFFT can not do this sequence length currently - odd multi-upload R2C/C2R FFTs\nVKFFT_ERROR_UNSUPPORTED_FFT_LENGTH_DCT = 3004,\t// VkFFT can not do this sequence length currently - multi-upload R2R transforms, odd DCT-IV transforms\nVKFFT_ERROR_UNSUPPORTED_FFT_OMIT = 3005,\t// VkFFT can not omit sequences in convolution calculations and R2C/C2R case\nVKFFT_ERROR_FAILED_TO_ALLOCATE = 4001,\t// VkFFT failed to allocate GPU memory\nVKFFT_ERROR_FAILED_TO_MAP_MEMORY = 4002,\t// 4002-4052 are handlers for errors of used backend APIs. They may indicate a driver failure. If they are thrown - report to the GitHub repo\nVKFFT_ERROR_FAILED_TO_ALLOCATE_COMMAND_BUFFERS = 4003,\nVKFFT_ERROR_FAILED_TO_BEGIN_COMMAND_BUFFER = 4004,\nVKFFT_ERROR_FAILED_TO_END_COMMAND_BUFFER = 4005,\nVKFFT_ERROR_FAILED_TO_SUBMIT_QUEUE = 4006,\nVKFFT_ERROR_FAILED_TO_WAIT_FOR_FENCES = 4007,\nVKFFT_ERROR_FAILED_TO_RESET_FENCES = 4008,\nVKFFT_ERROR_FAILED_TO_CREATE_DESCRIPTOR_POOL = 4009,\nVKFFT_ERROR_FAILED_TO_CREATE_DESCRIPTOR_SET_LAYOUT = 4010,\nVKFFT_ERROR_FAILED_TO_ALLOCATE_DESCRIPTOR_SETS = 4011,\nVKFFT_ERROR_FAILED_TO_CREATE_PIPELINE_LAYOUT = 4012,\nVKFFT_ERROR_FAILED_SHADER_PREPROCESS = 4013,\nVKFFT_ERROR_FAILED_SHADER_PARSE = 4014,\nVKFFT_ERROR_FAILED_SHADER_LINK = 4015,\nVKFFT_ERROR_FAILED_SPIRV_GENERATE = 4016,\nVKFFT_ERROR_FAILED_TO_CREATE_SHADER_MODULE = 4017,\nVKFFT_ERROR_FAILED_TO_CREATE_INSTANCE = 4018,\nVKFFT_ERROR_FAILED_TO_SETUP_DEBUG_MESSENGER = 4019,\nVKFFT_ERROR_FAILED_TO_FIND_PHYSICAL_DEVICE = 4020,\nVKFFT_ERROR_FAILED_TO_CREATE_DEVICE = 4021,\nVKFFT_ERROR_FAILED_TO_CREATE_FENCE = 4022,\nVKFFT_ERROR_FAILED_TO_CREATE_COMMAND_POOL = 4023,\nVKFFT_ERROR_FAILED_TO_CREATE_BUFFER = 4024,\nVKFFT_ERROR_FAILED_TO_ALLOCATE_MEMORY = 4025,\nVKFFT_ERROR_FAILED_TO_BIND_BUFFER_MEMORY = 4026,\nVKFFT_ERROR_FAILED_TO_FIND_MEMORY = 4027,\nVKFFT_ERROR_FAILED_TO_SYNCHRONIZE = 4028,\nVKFFT_ERROR_FAILED_TO_COPY = 4029,\nVKFFT_ERROR_FAILED_TO_CREATE_PROGRAM = 4030,\nVKFFT_ERROR_FAILED_TO_COMPILE_PROGRAM = 4031, \nVKFFT_ERROR_FAILED_TO_GET_CODE_SIZE = 4032,\nVKFFT_ERROR_FAILED_TO_GET_CODE = 4033,\nVKFFT_ERROR_FAILED_TO_DESTROY_PROGRAM = 4034,\nVKFFT_ERROR_FAILED_TO_LOAD_MODULE = 4035,\nVKFFT_ERROR_FAILED_TO_GET_FUNCTION = 4036,\nVKFFT_ERROR_FAILED_TO_SET_DYNAMIC_SHARED_MEMORY = 4037,\nVKFFT_ERROR_FAILED_TO_MODULE_GET_GLOBAL = 4038,\nVKFFT_ERROR_FAILED_TO_LAUNCH_KERNEL = 4039,\nVKFFT_ERROR_FAILED_TO_EVENT_RECORD = 4040,\nVKFFT_ERROR_FAILED_TO_ADD_NAME_EXPRESSION = 4041,\nVKFFT_ERROR_FAILED_TO_INITIALIZE = 4042,\nVKFFT_ERROR_FAILED_TO_SET_DEVICE_ID = 4043,\nVKFFT_ERROR_FAILED_TO_GET_DEVICE = 4044,\nVKFFT_ERROR_FAILED_TO_CREATE_CONTEXT = 4045,\nVKFFT_ERROR_FAILED_TO_CREATE_PIPELINE = 4046,\nVKFFT_ERROR_FAILED_TO_SET_KERNEL_ARG = 4047,\nVKFFT_ERROR_FAILED_TO_CREATE_COMMAND_QUEUE = 4048,\nVKFFT_ERROR_FAILED_TO_RELEASE_COMMAND_QUEUE = 4049,\nVKFFT_ERROR_FAILED_TO_ENUMERATE_DEVICES = 4050,\nVKFFT_ERROR_FAILED_TO_GET_ATTRIBUTE = 4051,\nVKFFT_ERROR_FAILED_TO_CREATE_EVENT = 4052\n} VkFFTResult;\n\\end{minted}\n\\end{mdframed}\n\n\\subsection{VkFFT application management functions}\n\nVkFFT has a unified plan management model - all different transform\ntypes/ dimensionalities/ precision use the same calls with configuration\ndone through VkFFTConfiguration struct. This section shows how to\ninitialize/use/free VkFFT with this unified model, while the next\none will go into how to configure VkFFTConfiguration correctly. All\nof the functions operate on VkFFTApplication and VkFFTConfiguration\nassuming they have been zero-initialized before usage, so do not forget\nto do this when initializing:\n\n\\begin{mdframed}[backgroundcolor=bg]\n\\begin{minted}[tabsize=4,obeytabs,breaklines]{C}\nVkFFTConfiguration configuration = {};\nVkFFTApplication app = {};\n\\end{minted}\n\\end{mdframed}\n\n\\subsubsection{Function initializeVkFFT()}\n\n\\begin{mdframed}[backgroundcolor=bg]\n\\begin{minted}[tabsize=4,obeytabs,breaklines]{C}\nVkFFTResult initializeVkFFT(VkFFTApplication* app, VkFFTConfiguration inputLaunchConfiguration)\n\\end{minted}\n\\end{mdframed}\n\nCreates an FFT application (collection of forward and inverse plans).\nAs forward and inverse FFTs may have different memory layouts, can\nhave different normalizations - they are done as separate internal\nplans inside VkFFTApplication. This call assumes the application to\nbe zero-initialized, so can be only done once on a particular application,\nuntil it is deleted.\n\nIf the initializeVkFFT call fails, it frees all allocated by VkFFT\nCPU/GPU resources and sets the application to zero. VkFFTResult is\nreturned with an error code corresponding to what went wrong.\n\nIn case of success, VkFFTApplication will contain initialized plans\nwith compiled kernels ready for execution with VKFFT\\_SUCCESS returned.\n\n\\subsubsection{Function VkFFTAppend()}\n\n\\begin{mdframed}[backgroundcolor=bg]\n\\begin{minted}[tabsize=4,obeytabs,breaklines]{C}\nVkFFTResult VkFFTAppend(VkFFTApplication* app, int inverse, VkFFTLaunchParams* launchParams)\n\\end{minted}\n\\end{mdframed}\n\nPerforms FFT in the int inverse direction (-1 for forward FFT, 1 for\ninverse FFT). FFT plans are selected from the VkFFTApplication collection\nautomatically. VkFFTApplication must be initialized with initializeVkFFT\ncall before. VkFFTLaunchParams struct allows for pre-launch configuration\nof some parameters, namely:\n\\begin{itemize}\n\\item buffer - similar to how FFTW/cuFFT expects input/output data pointers\nin {*}execC2C (and other) function calls, VkFFT allows specifying\nmemory used for computations at launch. It must have the same size/layout/strides\nas defined during the application creation.\n\\item inputBuffer/outputBuffer/tempBuffer/kernel - other buffers can also\nbe specified at launch. In addition to them having the same size/layout/strides\nas defined during the application creation, the application must be\ncreated with flags enabling the corresponding buffer usage: isInputFormatted/isOutputFormatted/userTempBuffer/performConvolution\nrespectively.\n\\item bufferOffset/tempBufferOffset/inputBufferOffset/outputBufferOffset/kernelOffset\n- specify if VkFFT has to offset the first element position inside\nthe corresponding buffer. In bytes. Default 0. specifyOffsetsAtLaunch\nparameter must be enabled during the initializeVkFFT call before. \n\\end{itemize}\nDepending on the API, the execution model may vary and require additional\ninformation at launch:\n\\begin{itemize}\n\\item Vulkan API: VkFFT appends a sequence of vkCmdDispatch calls to the\nuser-defined VkCommandBuffer (with respective push constants/descriptor\nsets/pipelines/memory barriers bindings). VkCommandBuffer must be\nprovided as a pointer in VkFFTLaunchParams. VkCommandBuffer must be\nin the writing stage, started with vkBeginCommandBuffer call. After\nVkFFTAppend has finished, provided VkCommandBuffer will contain a\nsequence of operations performing FFT. The first call of the sequence\nhas no input memory barrier, the last call has one, ensuring FFT has\nfinished execution.\n\\item CUDA/HIP API: if the user wants to use streams, they have to be provided\nduring the application configuration stage. VkFFTAppend performs a\nseries of cuLaunchKernel, which are sequential if appended to one\nstream and synchronized if appended to multiple streams.\n\\item OpenCL API: similar to Vulkan, VkFFT appends a sequence of clEnqueueNDRangeKernel\ncalls to user-defined cl\\_command\\_queue. Currently, they are all\nassumed to be sequential. cl\\_command\\_queue must be provided as a\npointer in VkFFTLaunchParams. \n\\end{itemize}\nIf VkFFT fails during the VkFFTAppend call, it will not free the application\nand allocated there resources - use a separate call for that.\n\n\\subsubsection{Function deleteVkFFT()}\n\n\\begin{mdframed}[backgroundcolor=bg]\n\\begin{minted}[tabsize=4,obeytabs,breaklines]{C}\nvoid deleteVkFFT(VkFFTApplication* app)\n\\end{minted}\n\\end{mdframed}\n\nPerforms deallocation of resources used in the provided application.\nReturns application to the zero-initialized state.\n\n\\subsubsection{Funcion VkFFTGetVersion()}\n\n\\begin{mdframed}[backgroundcolor=bg]\n\\begin{minted}[tabsize=4,obeytabs,breaklines]{C}\nint VkFFTGetVersion()\n\\end{minted}\n\\end{mdframed}\n\nReturns the version of the VkFFT library in the X.XX.XX format (without\ndots).\n\n\\subsection{VkFFT configuration}\n\nThis section will cover all the parameters that can be specified in\nthe VkFFTConfiguration struct. It will start with a short description\nof the struct (intended to be used as a cheat sheet), then go for\neach field in detail.\n\n\\begin{mdframed}[backgroundcolor=bg]\n\\begin{minted}[tabsize=4,obeytabs,breaklines]{C}\ntypedef struct {\n// Required parameters: \t\nuint64_t FFTdim;\t// FFT dimensionality (1, 2 or 3)\nuint64_t size[3];\t// WHD - system dimensions\n#if(VKFFT_BACKEND==0) //Vulkan API\nVkPhysicalDevice* physicalDevice;\t// Pointer to Vulkan physical device, obtained from vkEnumeratePhysicalDevices\nVkDevice* device;\t// Pointer to Vulkan device, created with vkCreateDevice\nVkQueue* queue;\t// Pointer to Vulkan queue, created with vkGetDeviceQueue\nVkCommandPool* commandPool;\t// Pointer to Vulkan command pool, created with vkCreateCommandPool\nVkFence* fence;\t// Pointer to Vulkan fence, created with vkCreateFence\nuint64_t isCompilerInitialized;\t// Specify if glslang compiler has been intialized before (0 - off, 1 - on). Default 0 \n#elif(VKFFT_BACKEND==1) //CUDA API\nCUdevice* device;\t// Pointer to CUDA device, obtained from cuDeviceGet \t\ncudaStream_t* stream;\t// Pointer to streams (can be more than 1), where to execute the kernels. Deafult 0\nuint64_t num_streams;\t// Try to submit CUDA kernels in multiple streams for asynchronous execution. Default 1 \n#elif(VKFFT_BACKEND==2) //HIP API\nhipDevice_t* device;\t// Pointer to HIP device, obtained from hipDeviceGet\nhipStream_t* stream;\t// Pointer to streams (can be more than 1), where to execute the kernels. Deafult 0\nuint64_t num_streams;\t// Try to submit HIP kernels in multiple streams for asynchronous execution. Default 1 \n#elif(VKFFT_BACKEND==3) //OpenCL API\ncl_platform_id* platform;\t// Pointer to OpenCL platform, obtained from clGetPlatformIDs\ncl_device_id* device;\t// Pointer to OpenCL device, obtained from clGetDeviceIDs\ncl_context* context;\t// Pointer to OpenCL context, obtained from clCreateContext\n#endif\n\n// Data parameters (buffers can be specified at launch):\nuint64_t userTempBuffer;\t// Buffer allocated by app automatically if needed to reorder Four step algorithm. Setting to non zero value enables manual user allocation (0 - off, 1 - on)\nuint64_t bufferNum;\t// Multiple buffer sequence storage is Vulkan only. Default 1\nuint64_t tempBufferNum;\t// Multiple buffer sequence storage is Vulkan only. Default 1, buffer allocated by app automatically if needed to reorder Four step algorithm. Setting to non zero value enables manual user allocation \t\nuint64_t inputBufferNum;\t// Multiple buffer sequence storage is Vulkan only. Default 1, if isInputFormatted is enabled \nuint64_t outputBufferNum;\t// Multiple buffer sequence storage is Vulkan only. Default 1, if isOutputFormatted is enabled \nuint64_t kernelNum;\t// Multiple buffer sequence storage is Vulkan only. Default 1, if performConvolution is enabled\nuint64_t* bufferSize;\t// Array of buffers sizes in bytes\nuint64_t* tempBufferSize;\t// Array of temp buffers sizes in bytes. Default set to bufferSize sum, buffer allocated by app automatically if needed to reorder Four step algorithm. Setting to non zero value enables manual user allocation \nuint64_t* inputBufferSize;\t// Array of input buffers sizes in bytes, if isInputFormatted is enabled\nuint64_t* outputBufferSize;\t// Array of output buffers sizes in bytes, if isOutputFormatted is enabled\nuint64_t* kernelSize;\t// Array of kernel buffers sizes in bytes, if performConvolution is enabled\n#if(VKFFT_BACKEND==0) //Vulkan API\nVkBuffer* buffer;\t// Pointer to array of buffers (or one buffer) used for computations\nVkBuffer* tempBuffer;\t// Needed if reorderFourStep is enabled to transpose the array. Same sum size or bigger as buffer (can be split in multiple). Default 0. Setting to non zero value enables manual user allocation\nVkBuffer* inputBuffer;\t// Pointer to array of input buffers (or one buffer) used to read data from if isInputFormatted is enabled\nVkBuffer* outputBuffer;\t// Pointer to array of output buffers (or one buffer) used to write data to if isOutputFormatted is enabled\nVkBuffer* kernel;\t// Pointer to array of kernel buffers (or one buffer) used to read kernel data from if performConvolution is enabled\n#elif(VKFFT_BACKEND==1) //CUDA API\nvoid** buffer;\t// Pointer to device buffer used for computations\nvoid** tempBuffer;\t// Needed if reorderFourStep is enabled to transpose the array. Same size as buffer. Default 0. Setting to non zero value enables manual user allocation \nvoid** inputBuffer;\t// Pointer to device buffer used to read data from if isInputFormatted is enabled\nvoid** outputBuffer;\t// Pointer to device buffer used to write data to if isOutputFormatted is enabled\nvoid** kernel;\t// Pointer to device buffer used to read kernel data from if performConvolution is enabled \n#elif(VKFFT_BACKEND==2) //HIP API\nvoid** buffer;\t// Pointer to device buffer used for computations\nvoid** tempBuffer;\t// Needed if reorderFourStep is enabled to transpose the array. Same size as buffer. Default 0. Setting to non zero value enables manual user allocation\nvoid** inputBuffer;\t// Pointer to device buffer used to read data from if isInputFormatted is enabled\nvoid** outputBuffer;\t// Pointer to device buffer used to write data to if isOutputFormatted is enabled\nvoid** kernel;\t// Pointer to device buffer used to read kernel data from if performConvolution is enabled \n#elif(VKFFT_BACKEND==3) //OpenCL API\ncl_mem* buffer;\t// Pointer to device buffer used for computations\ncl_mem* tempBuffer;\t// Needed if reorderFourStep is enabled to transpose the array. Same size as buffer. Default 0. Setting to non zero value enables manual user allocation\ncl_mem* inputBuffer;\t// Pointer to device buffer used to read data from if isInputFormatted is enabled\ncl_mem* outputBuffer;\t// Pointer to device buffer used to write data to if isOutputFormatted is enabled\ncl_mem* kernel;\t// Pointer to device buffer used to read kernel data from if performConvolution is enabled\n#endif\nuint64_t bufferOffset;\t// Specify if VkFFT has to offset the first element position inside the buffer. In bytes. Default 0\nuint64_t tempBufferOffset;\t// Specify if VkFFT has to offset the first element position inside the temp buffer. In bytes. Default 0\nuint64_t inputBufferOffset;\t// Specify if VkFFT has to offset the first element position inside the input buffer. In bytes. Default 0\nuint64_t outputBufferOffset;\t// Specify if VkFFT has to offset the first element position inside the output buffer. In bytes. Default 0\nuint64_t kernelOffset;\t// Specify if VkFFT has to offset the first element position inside the kernel. In bytes. Default 0\nuint64_t specifyOffsetsAtLaunch;\t// Specify if offsets will be selected with launch parameters VkFFTLaunchParams (0 - off, 1 - on). Default 0\n\n// Optional: (default 0 if not stated otherwise)\nuint64_t coalescedMemory;\t// In bytes, for Nvidia and AMD is equal to 32, Intel is equal 64, scaled for half precision. Going to work regardless, but if specified by user correctly, the performance will be higher.\nuint64_t aimThreads;\t// Aim at this many threads per block. Default 128\nuint64_t numSharedBanks;\t// How many banks shared memory has. Default 32\nuint64_t inverseReturnToInputBuffer;\t// return data to the input buffer in inverse transform (0 - off, 1 - on). isInputFormatted must be enabled\nuint64_t numberBatches;\t// N - used to perform multiple batches of initial data. Default 1\nuint64_t useUint64;\t// Use 64-bit addressing mode in generated kernels\nuint64_t omitDimension[3];\t// Disable FFT for this dimension (0 - FFT enabled, 1 - FFT disabled). Default 0. Doesn't work for R2C for now. Doesn't work with convolutions.\nuint64_t fixMaxRadixBluestein;\t// Controls the padding of sequences in Bluestein convolution. If specified, padded sequence will be made of up to fixMaxRadixBluestein primes. Default: 2 for up to 1048576 combined dimension FFT system, 7 after. Min = 2, Max = 13.\nuint64_t performBandwidthBoost; // Try to reduce coalsesced number by a factor of X to get bigger sequence in one upload for strided axes. Default: -1 for DCT, 2 for Bluestein's algorithm (or -1 if DCT), 0 otherwise \nuint64_t doublePrecision;\t// Perform calculations in double precision (0 - off, 1 - on).\nuint64_t halfPrecision;\t// Perform calculations in half precision (0 - off, 1 - on)\nuint64_t halfPrecisionMemoryOnly;\t// Use half precision only as input/output buffer. Input/Output have to be allocated as half, buffer/tempBuffer have to be allocated as float (out-of-place mode only). Specify isInputFormatted and isOutputFormatted to use (0 - off, 1 - on)\nuint64_t doublePrecisionFloatMemory;\t// Use FP64 precision for all calculations, while all memory storage is done in FP32.\nuint64_t performR2C;\t// Perform R2C/C2R decomposition (0 - off, 1 - on)\nuint64_t performDCT;\t// Perform DCT transformation (X - DCT type, 1-4)\nuint64_t disableMergeSequencesR2C;\t// Disable merging of two real sequences to reduce calculations (0 - off, 1 - on) \nuint64_t normalize;\t// Normalize inverse transform (0 - off, 1 - on)\nuint64_t disableReorderFourStep;\t// Disables unshuffling of Four step algorithm. Requires tempbuffer allocation (0 - off, 1 - on)\nuint64_t useLUT;\t// Switches from calculating sincos to using precomputed LUT tables (0 - off, 1 - on). Configured by initialization routine\nuint64_t makeForwardPlanOnly;\t// Generate code only for forward FFT (0 - off, 1 - on)\nuint64_t makeInversePlanOnly;\t// Generate code only for inverse FFT (0 - off, 1 - on)\nuint64_t bufferStride[3];\t// Buffer strides - default set to x - x*y - x*y*z values\nuint64_t isInputFormatted;\t// Specify if input buffer is padded - 0 - padded, 1 - not padded. For example if it is not padded for R2C if out-of-place mode is selected (only if numberBatches==1 and numberKernels==1)\nuint64_t isOutputFormatted;\t// Specify if output buffer is padded - 0 - padded, 1 - not padded. For example if it is not padded for R2C if out-of-place mode is selected (only if numberBatches==1 and numberKernels==1)\nuint64_t inputBufferStride[3];\t// Input buffer strides. Used if isInputFormatted is enabled. Default set to bufferStride values\nuint64_t outputBufferStride[3];\t// Output buffer strides. Used if isInputFormatted is enabled. Default set to bufferStride values\nuint64_t considerAllAxesStrided;\t// Will create plan for non-strided axis similar as a strided axis - used with disableReorderFourStep to get the same layout for Bluestein kernel (0 - off, 1 - on)\nuint64_t keepShaderCode;\t// Will keep shader code and print all executed shaders during the plan execution in order (0 - off, 1 - on)\nuint64_t printMemoryLayout;\t// Will print order of buffers used in shaders (0 - off, 1 - on) \n\nuint64_t saveApplicationToString;\t// Will save all compiled binaries to VkFFTApplication.saveApplicationString (will be allocated by VkFFT, deallocated with deleteVkFFT call). VkFFTApplication.applicationStringSize will contain size of binary in bytes. (0 - off, 1 - on)\nuint64_t loadApplicationFromString;\t// Will load all binaries from loadApplicationString instead of recompiling them (must be allocated by user, must contain what saveApplicationToString call generated previously in VkFFTApplication.saveApplicationString). (0 - off, 1 - on). Mutually exclusive with saveApplicationToString\nvoid* loadApplicationString;\t// Memory array (uint32_t* for Vulkan/HIP, char* for CUDA/OpenCL) through which user can load VkFFT binaries, must be provided by user if loadApplicationFromString = 1. \n\n// Optional zero padding control parameters: (default 0 if not stated otherwise)\nuint64_t performZeropadding[3];\t// Don't read some data/perform computations if some input sequences are zeropadded for each axis (0 - off, 1 - on)\nuint64_t fft_zeropad_left[3];\t// Specify start boundary of zero block in the system for each axis\nuint64_t fft_zeropad_right[3];\t// Specify end boundary of zero block in the system for each axis\nuint64_t frequencyZeroPadding;\t// Set to 1 if zeropadding of frequency domain, default 0 - spatial zeropadding\n\n// Optional convolution control parameters: (default 0 if not stated otherwise)\nuint64_t performConvolution;\t// Perform convolution in this application (0 - off, 1 - on). Disables reorderFourStep parameter\nuint64_t coordinateFeatures;\t// C - coordinate, or dimension of features vector. In matrix convolution - size of a vector\nuint64_t matrixConvolution;\t// If equal to 2 perform 2x2, if equal to 3 perform 3x3 matrix-vector convolution. Overrides coordinateFeatures\nuint64_t symmetricKernel;\t// Specify if kernel in 2x2 or 3x3 matrix convolution is symmetric\nuint64_t numberKernels;\t// N - only used in convolution step - specify how many kernels were initialized before. Expands one input to multiple (batched) output\nuint64_t kernelConvolution;\t// Specify if this application is used to create kernel for convolution, so it has the same properties. performConvolution has to be set to 0 for kernel creation\n\n// Register overutilization (experimental): (default 0 if not stated otherwise)\nuint64_t registerBoost;\t// Specify if register file size is bigger than shared memory and can be used to extend it X times (on Nvidia 256KB register file can be used instead of 32KB of shared memory, set this constant to 4 to emulate 128KB of shared memory). Defaults: Nvidia - 4 in Vulkan/OpenCL, 1 in CUDA backend; AMD - 2 if shared memory >= 64KB, else 4 in Vulkan/OpenCL backend, 1 in HIP backend; Intel - 1 if shared memory >= 64KB, else 2 in Vulkan/OpenCL backend; Default 1\nuint64_t registerBoostNonPow2;\t// Specify if register overutilization should be used on non power of 2 sequences (0 - off, 1 - on)\nuint64_t registerBoost4Step;\t// Specify if register file overutilization should be used in big sequences (>2^14), same definition as registerBoost. Default 1\n//not used techniques:\nuint64_t swapTo3Stage4Step;\t// Specify at which power of 2 to switch from 2 upload to 3 upload 4-step FFT, in case if making max sequence size lower than coalesced sequence helps to combat TLB misses. Default 0 - disabled. Must be at least 17\nuint64_t devicePageSize;\t// In KB, the size of a page on the GPU. Setting to 0 disables local buffer split in pages\nuint64_t localPageSize;\t// In KB, the size to split page into if sequence spans multiple devicePageSize pages\n\n// Automatically filled based on device info (still can be reconfigured by user):\nuint64_t maxComputeWorkGroupCount[3];\t// maxComputeWorkGroupCount from VkPhysicalDeviceLimits\nuint64_t maxComputeWorkGroupSize[3];\t// maxComputeWorkGroupCount from VkPhysicalDeviceLimits\nuint64_t maxThreadsNum;\t// Max number of threads from VkPhysicalDeviceLimits\nuint64_t sharedMemorySizeStatic;\t// Available for static allocation shared memory size, in bytes\nuint64_t sharedMemorySize;\t// Available for allocation shared memory size, in bytes\nuint64_t sharedMemorySizePow2;\t// Power of 2 which is less or equal to sharedMemorySize, in bytes\nuint64_t warpSize;\t// Number of threads per warp/wavefront.\nuint64_t halfThreads;\t// Intel fix\nuint64_t allocateTempBuffer;\t// Buffer allocated by app automatically if needed to reorder Four step algorithm. Parameter to check if it has been allocated\nuint64_t reorderFourStep;\t// Unshuffle Four step algorithm. Requires tempbuffer allocation (0 - off, 1 - on). Default 1.\nint64_t maxCodeLength;\t// Specify how big can be buffer used for code generation (in char). Default 1000000 chars. \nint64_t maxTempLength;\t// Specify how big can be buffer used for intermediate string sprintfs be (in char). Default 5000 chars. If code segfaults for some reason - try increasing this number.\n#if(VKFFT_BACKEND==0) //Vulkan API\nVkDeviceMemory tempBufferDeviceMemory;\t// Filled at app creation\nVkCommandBuffer* commandBuffer;\t// Filled at app execution\nVkMemoryBarrier* memory_barrier;\t// Filled at app creation\n#elif(VKFFT_BACKEND==1) //CUDA API\ncudaEvent_t* stream_event;\t// Filled at app creation\nuint64_t streamCounter;\t// Filled at app creation\nuint64_t streamID;\t// Filled at app creation\n#elif(VKFFT_BACKEND==2) //HIP API\nhipEvent_t* stream_event;\t// Filled at app creation\nuint64_t streamCounter;\t// Filled at app creation\nuint64_t streamID;\t// Filled at app creation\n#elif(VKFFT_BACKEND==3) //OpenCL API\ncl_command_queue* commandQueue;\t// Filled at app creation\n#endif\n} VkFFTConfiguration;\n\\end{minted}\n\\end{mdframed}\n\n\\subsubsection{Driver API parameters}\n\nIn order to work, VkFFT needs some structures that are provided by\nthe driver. They are backend API-dependent. VkFFT will return corresponding\nVkFFTResult if one of these structures are not provided (value equal\nto zero) unless it is stated that there is a default value assigned.\nVkFFT will not modify provided values directly.\n\nVulkan API will need the following information:\n\\begin{itemize}\n\\item VkPhysicalDevice{*} physicalDevice - Pointer to Vulkan physical device,\nobtained from vkEnumeratePhysicalDevices()\n\\item VkDevice{*} device - Pointer to Vulkan device, created with vkCreateDevice()\n\\item VkQueue{*} queue - Pointer to Vulkan queue, created with vkGetDeviceQueue()\n\\item VkCommandPool{*} commandPool - Pointer to Vulkan command pool, created\nwith vkCreateCommandPool()\n\\item VkFence{*} fence - Pointer to Vulkan fence, created with vkCreateFence()\n\\item uint64\\_t isCompilerInitialized - Specify if glslang compiler has\nbeen intialized before (0 - off, 1 - on). Default 0 - VkFFT will call\nglslang\\_initialize\\_process() at initializeVkFFT() and glslang\\_finialize\\_process()\nat deleteVkFFT() calls.\n\\end{itemize}\nCUDA API will need the following information:\n\\begin{itemize}\n\\item CUdevice{*} device - Pointer to CUDA device, obtained from cuDeviceGet()\n\\item cudaStream\\_t{*} stream - Pointer to streams (can be more than 1),\nwhere to execute the kernels. Default 0. Streams must be associated\nwith the provided device. There is no real benefit in having more\nthan one, however. \n\\item uint64\\_t num\\_streams - Try to submit CUDA kernels in multiple streams\nfor asynchronous execution. Default 1 \n\\end{itemize}\nHIP API will need the following information:\n\\begin{itemize}\n\\item hipDevice\\_t{*} device - Pointer to HIP device, obtained from hipDeviceGet()\n\\item hipStream\\_t{*} stream - Pointer to streams (can be more than 1),\nwhere to execute the kernels. Default 0. Streams must be associated\nwith the provided device. There is no real benefit in having more\nthan one, however. \n\\item uint64\\_t num\\_streams - Try to submit HIP kernels in multiple streams\nfor asynchronous execution. Default 1 \n\\end{itemize}\nOpenCL API will need the following information:\n\\begin{itemize}\n\\item cl\\_platform\\_id{*} platform - Pointer to OpenCL platform, obtained\nfrom clGetPlatformIDs() \n\\item cl\\_device\\_id{*} device - Pointer to OpenCL device, obtained from\nclGetDeviceIDs()\n\\item cl\\_context{*} context - Pointer to OpenCL context, obtained from\nclCreateContext()\n\\end{itemize}\n\n\\subsubsection{Memory management parameters}\n\nThere are five buffer types user can provide to VkFFT: \n\\begin{itemize}\n\\item the main buffer (buffer)\n\\item temporary buffer used for calculations requiring out-of-place writes\n(tempBuffer)\n\\item separate input buffer, from which initial read is performed (inputBuffer)\n\\item separate output buffer, to which final write is performed (outputBuffer)\n\\item kernel buffer, used for calculation of convolutions and cross-correlations\n(kernel)\n\\end{itemize}\nThese buffers must be passed by a pointer: in Vulkan API they are\nprovided as VkBuffer{*}, in CUDA and HIP they are provided as void{*}{*},\nin OpenCL, they are provided as cl\\_mem{*}. Even though the underlying\nstructure (VkBuffer, void{*}, cl\\_mem) is not a memory but just a\nnumber that the driver can use to access corresponding allocated memory\non the GPU, passing them by a pointer allows for the user to query\nmultiple GPU allocated buffers for VkFFT to use. Currently, it is\nonly supported in Vulkan API - each of five buffer types can be made\nout of multiple separate memory allocations. For example, it is possible\nto combine multiple small unused at the point of FFT calculation buffers\nto form a tempBuffer. This option also allows Vulkan API to overcome\nthe limit of 4GB for a single memory allocation - due to the fact\nthat Vulkan can only use 32-bit numbers for addressing (other APIs\nsupport 64-bit addressing). \n\nTo use the buffers other than the main buffer, the user has to specify\nthis in configuration at the application creation stage (set to zero\nby default, optional parameters): \n\\begin{itemize}\n\\item uint64\\_t userTempBuffer - enables manual temporary buffer allocation\n(otherwise it is managed by VkFFT)\n\\item uint64\\_t isInputFormatted - specifies that initial read is performed\nfrom a separate buffer (inputBuffer)\n\\item uint64\\_t isOutputFormatted - specifies that final write is performed\nto a separate buffer (outputBuffer)\n\\item uint64\\_t performConvolution - enables convolution calculations, which\nrequires precomputed kernel (kernel)\n\\end{itemize}\nBuffer sizes (bufferSize/tempBufferSize/inputBufferSize/outputBufferSize/kernelSize)\nare provided as a uint64\\_t pointer to an array, where each element\ncorresponds to the buffer size of the buffer with the same placement\nin the buffer array. Buffer sizes have to be provided in Vulkan API\n(due to the stricter memory management model and multiple buffer support)\nand are optional in other backends (they can be useful to determine\nwhen to switch for 64-bit addressing).\n\nBuffer number (bufferNum/tempBufferNum/inputBufferNum/outputBufferNum/kernelNum)\ncorresponds to how many elements are in the buffer and buffer size\narray. By default it is set to 1 and is not required to be provided\nby the user. Non-Vulkan backends currently don't support values other\nthan default. Optional parameter.\n\nBuffer offset (bufferOffset/ tempBufferOffset/ inputBufferOffset/\noutputBufferOffset/ kernelOffset) specifies offset from the start\nof the buffer sequence. It must be specified in bytes and must be\ndivisible by the number type size used in the corresponding array\n(otherwise, the offset will be truncated). It is provided as a single\nuint64\\_t value. Can be provided at launch time, if specifyOffsetsAtLaunch\nparameter is enabled during initialization call. Optional parameters.\n\nUser can provide custom dimension strides for buffer/inputBuffer/outputBuffer\nbuffers - uint64\\_t{[}3{]} array. Strides are specified in elements\nused in the array (not bytes). The first element corresponds to the\nstride between elements in the H direction, the second corresponds\nto the D direction and the third to C (or N, if the number of elements\nin C is 1). The first axis is assumed to be non-strided. Must be at\nleast of the same size as default strides, otherwise the behavior\nis undefined. Optional parameters.\n\nuint64\\_t inverseReturnToInputBuffer - an option that allows setting\nthe final output buffer of the inverse transform to the same buffer,\ninitial read of forward transform is performed from (inputBuffer,\nif isInputFormatted enabled). Optional parameter.\n\n\\subsubsection{General FFT parameters }\n\nThis section describes part of the configuration structure responsible\nfor FFT specification. \n\nuint64\\_t FFTdim - dimensionality of the transform (1, 2 or 3). Required\nparameter.\n\nuint64\\_t size{[}3{]} - WHD dimensions of the transform. Required\nparameter.\n\nuint64\\_t numberBatches - N parameter of the transform. By default,\nit is set to 1. Optional parameter.\n\nuint64\\_t performR2C - perform R2C/C2R decomposition. performDCT must\nbe set to 0. Default 0, set to 1 to enable. Optional parameter.\n\nuint64\\_t performDCT - perform DCT transformation. performR2C must\nbe set to 0. Default 0, set to X for DCT-X (currently supported X:\n1, 2, 3 and 4). Optional parameter.\n\nuint64\\_t normalize - enabling this parameter will make the inverse\ntransform divide the result by the FFT length. Default 0, set to 1\nto enable. Optional parameter.\n\n\\subsubsection{Precision parameters (and some things that can affect it):}\n\nuint64\\_t doublePrecision - perform calculations in double precision.\nDefault 0, set to 1 to enable. In Vulkan/OpenCL your device must support\ndouble-precision functionality. Optional parameter.\n\nuint64\\_t doublePrecisionFloatMemory - perform calculations in double\nprecision, but all intermediate and final storage in float. Input/Output/main\nbuffers must have single-precision layout. doublePrecision must be\nset to 0. This option increases precision, but not that much to be\nrecommended for actual use. Default 0, set to 1 to enable. In Vulkan/OpenCL\nyour device must support double-precision functionality. Experimental\nfeature. Optional parameter.\n\nuint64\\_t halfPrecision - half-precision in VkFFT is implemented only\nas memory optimization. All calculations are done in single precision\n(similar way as doublePrecisionFloatMemory works for double and single\nprecision). Default 0, set to 1 to enable. Works only in Vulkan API\nnow, experimental feature (half precision seems to have bad precision\nfor the first FFT element). Optional parameter.\n\nuint64\\_t halfPrecisionMemoryOnly - another way of performing half-precision\nin VkFFT, it will use half-precision only for initial and final memory\nstorage in input/output buffer. Input/Output have to be allocated\nas half, buffer/tempBuffer have to be allocated as float (out-of-place\nmode only). Specify isInputFormatted and isOutputFormatted to use.\nSo, for example, intermediate storage between axes FFTs in the multidimensional\ncase will be done in single precision, as opposed to half-precision\nin the base halfPrecision case. halfPrecision must be set to 1. Default\n0, set to 1 to enable. Works only in Vulkan API now, experimental\nfeature. Optional parameter.\n\nuint64\\_t useLUT - switches from calculating sines and cosines (via\nspecial function units in single precision or as a polynomial approximation\nin double precision) to using precomputed Look-Up Tables. Default\n0 in single precision, 1 in double precision, set to 1 to enable.\nSet to 1 by default for Intel GPUs. If you have issues with single-precision\naccuracy on your GPU, try enabling this parameter (mobile GPUs may\nbe affected). Optional parameter.\n\n\\subsubsection{Advanced parameters (code will work fine without using them)}\n\nuint64\\_t omitDimension{[}3{]} - parameter, that disables the FFT\ncalculation for a particular axis (WHD). Note, that omitted dimensions\nstill need to be included in FFTdim and size. This parameter simply\nworks as a switch during execution - by not executing the particular\ndimension code. It doesn't work with the non-strided axis (W) of R2C/C2R\nmode. It doesn't work with convolution calculations. Default 0, set\nto 1 to enable. Optional parameter.\n\nuint64\\_t useUint64 - forces VkFFT to use 64-bit addressing in generated\nkernels. It is automatically enabled if the estimated buffer size\nis more than 4GB. Doesn't work with the Vulkan backend. By default,\nit is set to 0. Optional parameter.\n\nuint64\\_t coalescedMemory - number of bytes to coalesce per one transaction.\nFor Nvidia and AMD is equal to 32, Intel is equal to 64. Going to\nwork regardless, but if specified by the user correctly, the performance\nwill be higher. Default 64 for other GPUs. For half-precision should\nbe multiplied by two. Should be a power of two. Optional parameter.\n\nuint64\\_t numSharedBanks - configure the number of shared banks on\nthe target GPU. Default 32. Minor performance boost as it solves shared\nmemory conflicts for the power of two systems. Optional parameter.\n\nuint64\\_t aimThreads - try to aim all kernels at this amount of threads.\nGains/losses are not predictable, just a parameter to play with (it\nis not guaranteed that the target kernel will use that many threads).\nDefault 128. Optional parameter.\n\nuint64\\_t useUint64 - forces 64-bit addressing in generated kernels.\nShould be enabled automatically for systems spanning more than 4GB,\nbut it is better to have an option to force it as a failsafe. Doesn't\nwork in Vulkan API (use multiple buffer binding). Default 0, set to\n1 to enable. Optional parameter.\n\nuint64\\_t fixMaxRadixBluestein - controls the padding of sequences\nin Bluestein convolution. If specified, the padded sequence will be\nmade of up to fixMaxRadixBluestein primes. Default: 2 for up to 1048576\ncombined dimension FFT system, 7 after. Min = 2, Max = 13. Optional\nparameter.\n\nuint64\\_t performBandwidthBoost - try to reduce coalsesced number\nby a factor of X to get bigger sequence in one upload for strided\naxes. Default: -1(inf) for DCT, 2 for Bluestein's algorithm (or -1\nif DCT), 0 otherwise \n\nuint64\\_t disableMergeSequencesR2C - disable the optimization that\nperforms merging of two real sequences to reduce calculations (in\nR2C/C2R and R2R). If enabled, calculations will be performed by simply\nsetting the imaginary component to zero. Default 0, set to 1 to enable.\nOptional parameter.\n\nuint64\\_t disableReorderFourStep - disables unshuffling of the Four\nStep FFT algorithm (last transposition of data). With this option\nenabled, tempBuffer will not be needed (unless it is required by Bluestein's\nmulti-upload FFT algorithm). Default 0, set to 1 to enable. Automatically\nenabled for convolution calculations and Bluestein's algorithm. Optional\nparameter.\n\nuint64\\_t makeForwardPlanOnly - generate code only for forward FFT.\nDefault 0, set to 1 to enable. Mutually exclusive with makeInversePlanOnly.\nOptional parameter.\n\nuint64\\_t makeInversePlanOnly - generate code only for inverse FFT.\nDefault 0, set to 1 to enable. Mutually exclusive with makeForwardPlan.\nOptional parameter.\n\nuint64\\_t considerAllAxesStrided - will create a plan for a non-strided\naxis similar to a strided axis (used with disableReorderFourStep to\nget the same layout for Bluestein kernel). Default 0, set to 1 to\nenable. Optional parameter.\n\nuint64\\_t keepShaderCode - debugging option, will keep shader code\nand print all executed shaders during the plan execution in order.\nDefault 0, set to 1 to enable. Optional parameter.\n\nuint64\\_t printMemoryLayout - debugging option, will print order of\nbuffers used in kernels. Default 0, set to 1 to enable. Optional parameter. \n\nuint64\\_t saveApplicationToString - will save all compiled binaries\nto VkFFTApplication.saveApplicationString (will be allocated by VkFFT,\ndeallocated with deleteVkFFT call). VkFFTApplication.applicationStringSize\nwill contain size of binary in bytes. Default 0, set to 1 to enable.\nOptional parameter.\n\nuint64\\_t loadApplicationFromString - will load all binaries from\nloadApplicationString instead of recompiling them (loadApplicationString\nmust be allocated by user, must contain what saveApplicationToString\ncall generated previously in VkFFTApplication.saveApplicationString).\nDefault 0, set to 1 to enable. Optional parameter. Mutually exclusive\nwith saveApplicationToString \n\nvoid{*} loadApplicationString - memory array (uint32\\_t{*} for Vulkan\nand HIP, char{*} for CUDA/OpenCL) through which user can load VkFFT\nbinaries, must be provided by user if loadApplicationFromString =\n1. \n\n\\subsubsection{Zero padding parameters}\n\nuint64\\_t performZeropadding{[}3{]} - do not read/write some data/perform\ncomputations if some part of the sequence is known to have zeros.\nSet separately for each axis (WHD). If enabled, all 1D sequences in\nthis direction will be considered padded (independent of other zero-padded\naxes). Default 0, set to 1 to enable. Optional parameter. \n\nuint64\\_t fft\\_zeropad\\_left{[}3{]} - specify start boundary of zero\nblock in the system for each axis. Default 0, set to the value between\n0 and size{[}X{]}-1. Optional parameter.\n\nuint64\\_t fft\\_zeropad\\_right{[}3{]} - specify end boundary of zero\nblock in the system for each axis. Default 0, set to the value between\nfft\\_zeropad\\_left{[}X{]} and size{[}X{]}-1. Optional parameter.\n\nuint64\\_t frequencyZeroPadding - enables zero padding of the frequency\ndomain, so the first read of inverse FFT will consider the parts of\nthe system from fft\\_zeropad\\_left to fft\\_zeropad\\_right as zero.\nDefault 0 - spatial zero padding, set to 1 to enable. Optional parameter. \n\n\\subsubsection{Convolution parameters}\n\nuint64\\_t performConvolution - main parameter that enables convolutions\nin the application. If enabled, you must specify kernel buffer, number\nof kernel buffers and kernel sizes (in Vulkan API). Disables reordering\nof the Four Step FFT algorithm. Default 0, set to 1 to enable. Optional\nparameter. \n\nuint64\\_t conjugateConvolution - default 0, set to 1 to enable enables\nconjugation of the sequence FFT is currently done on, 2 to enable\nconjugation of the convolution kernel. Optional parameter. \n\nuint64\\_t crossPowerSpectrumNormalization - normalize the FFT {*}\nkernel multiplication in frequency domain. Default 0, set to 1 to\nenable. Optional parameter. \n\nuint64\\_t coordinateFeatures - max coordinate (C), or dimension of\nthe features vector. In matrix convolution - the size of the vector.\nThe main purpose is to support Matrix-Vector convolutions. Use numberBatches\nparameter in tasks, not requiring two separate coordinate-like enumerations\nof data. Default 1. Optional parameter.\n\nuint64\\_t matrixConvolution - set to 2 to perform 2x2, set to 3 to\nperform 3x3 matrix-vector convolution. Matrix-vector convolution is\na form of point-wise multiplication in the Fourier space, used by\nthe convolution theorem, where multiplication takes the form of Matrix-vector\nmultiplication. Overrides coordinateFeatures during execution. Default\n0. Optional parameter. \n\nuint64\\_t symmetricKernel - specify if kernel in 2x2 or 3x3 matrix\nconvolution is symmetric. You need to store data as xx, xy, yy (upper-triangular)\nif enabled and as xx, xy, yx, yy (along rows then along columns, from\nleft to right) if disabled. Default 0, set to 1 to enable. Optional\nparameter. \n\nuint64\\_t numberKernels - specify how many kernels were initialized\nbefore performing one input/multiple output convolutions. Overwrites\nnumberBatches (N). Only used in convolution step and the following\ninverse transforms. Default 1. Optional parameter. \n\nuint64\\_t kernelConvolution - specify if this application is used\nto create kernel for convolution, so it has the same properties/memory\nlayout. performConvolution has to be set to 0 for the kernel creation.\nDefault 0, set to 1 to enable. Optional parameter, but it is a required\nparameter for kernel generation.\n\n\\subsubsection{Register overutilization}\n\nOnly works in C2C mode, without convolution support. Enabled in Vulkan\nand OpenCL APIs only (it works in other APIs, but worse). Experimental\nfeature.\n\nuint64\\_t registerBoost - specify if the register file size is bigger\nthan shared memory and can be used to extend it X times (on Nvidia\n256KB register file can be used instead of 32KB of shared memory,\nset this constant to 4 to emulate 128KB of shared memory). Default\n1 - no overutilization. In Vulkan and OpenCL it is set to 4 on Nvidia\nGPUs, to 2 if the driver shows 64KB or more of shared memory on AMD,\nto 2 if the driver shows less than 64KB of shared memory on AMD, to\n1 if the driver shows 64KB or more of shared memory on Intel, to 2\nif the driver shows less than 64KB of shared memory on Intel. Optional\nparameter.\n\nuint64\\_t registerBoostNonPow2 - specify if register overutilization\nshould be used on non-power of 2 sequences. Default 0, set to 1 to\nenable. Optional parameter.\n\nuint64\\_t registerBoost4Step - specify if register file overutilization\nshould be used in big sequences (>2\\textasciicircum 14), same definition\nas registerBoost. Default 1. Optional parameter.\n\n\\subsubsection{Extra advanced parameters (filled automatically)}\n\nuint64\\_t maxComputeWorkGroupCount{[}3{]} - how many workgroups can\nbe launched at one dispatch. Automatically derived from the driver,\ncan be artificially lowered. Then VkFFT will perform a logical split\nand extension of the number of workgroups to cover the required range.\n\nuint64\\_t maxComputeWorkGroupSize{[}3{]} - max dimensions of the workgroup.\nAutomatically derived from the driver. Can be modified if there are\nsome issues with the driver (as there were with ROCm 4.0, when it\nreturned 1024 for maxComputeWorkGroupSize and actually supported only\nup to 256 threads).\n\nuint64\\_t maxThreadsNum - max number of threads per block. Similar\nto maxComputeWorkGroupSize, but aggregated. Automatically derived\nfrom the driver.\n\nuint64\\_t sharedMemorySizeStatic - available for static allocation\nshared memory size, in bytes. Automatically derived from the driver.\nCan be controlled by the user, if desired.\n\nuint64\\_t sharedMemorySize - available for allocation shared memory\nsize, in bytes. VkFFT uses dynamic shared memory in CUDA/HIP as it\nallows for bigger allocations. Automatically derived from the driver.\nCan be controlled by the user, if desired.\n\nuint64\\_t sharedMemorySizePow2 - the power of 2 which is less or equal\nto sharedMemorySize, in bytes. Automatically computed.\n\nuint64\\_t warpSize - number of threads per warp/wavefront. Automatically\nderived from the driver, but can be modified (can increase performance,\nthough unpredictable as defaults have good values). Must be a power\nof two.\n\nuint64\\_t halfThreads - Intel GPU fix, tries to reduce the amount\nof dispatched threads in half to solve performance degradation in\nthe Four Step FFT algorithm. Default 0 for other GPUs, try enabling\nit if performance degrades in the Four Step FFT algorithm for your\nGPU as well. \n\nint64\\_t maxCodeLength - specify how big can the buffer used for code\ngeneration be (in char). Default 1000000 chars. \n\nint64\\_t maxTempLength - specify how big can the buffer used for intermediate\nstring sprintf's be (in char). Default 5000 chars. If code segfaults\nfor some reason - try increasing this number.\n\n\\newpage{}\n\n\\section{VkFFT Benchmark/Precision Suite and utils\\_VkFFT helper routines}\n\nThe only licensed (MIT) part of the VkFFT repository is the VkFFT\nheader file - core library. Other files are either external helper\nlibraries (half, glslang, with their respective licenses) or unlicensed\ncode that is intended for simple copy-pasting (benchmark\\_scripts,\nutils\\_VkFFT.h). It is the easiest way to understand how to use VkFFT\nby taking the provided scripts and tinker them to the particular task.\nThe current version of the benchmark and precision verification suite\nhas the following codes available:\n\\begin{itemize}\n\\item user\\_benchmark\\_VkFFT - generalization of the main configuration\nparameters that can be used to launch simplest in-place transforms\nfor the most important supported functionality\n\\item Sample 0 - FFT + iFFT C2C benchmark 1D batched in single precision\n\\item Sample 1 - FFT + iFFT C2C benchmark 1D batched in double precision\n\\item Sample 2 - FFT + iFFT C2C benchmark 1D batched in half precision\n\\item Sample 3 - FFT + iFFT C2C multidimensional benchmark in single precision\n\\item Sample 4 - FFT + iFFT C2C multidimensional benchmark in single precision,\nnative zeropadding\n\\item Sample 5 - FFT + iFFT C2C benchmark 1D batched in single precision,\nno reshuffling\n\\item Sample 6 - FFT + iFFT R2C / C2R benchmark, in-place.\n\\item Sample 7 - FFT + iFFT C2C Bluestein benchmark in single precision\n\\item Sample 8 - FFT + iFFT C2C Bluestein benchmark in double precision\n\\item Sample 10 - multiple buffers (4 by default) split version of benchmark\n0\n\\item Sample 11 - VkFFT / xFFT / FFTW C2C precision test in single precision\n(xFFT can be cuFFT or rocFFT)\n\\item Sample 12 - VkFFT / xFFT / FFTW C2C precision test in double precision\n(xFFT can be cuFFT or rocFFT)\n\\item Sample 13 - VkFFT / cuFFT / FFTW C2C precision test in half precision\n\\item Sample 14 - VkFFT / FFTW C2C radix 3 / 5 / 7 / 11 / 13 / Bluestein\nprecision test in single precision\n\\item Sample 15 - VkFFT / xFFT / FFTW R2C+C2R precision test in single precision,\nout-of-place. (xFFT can be cuFFT or rocFFT)\n\\item Sample 16 - VkFFT / FFTW R2R DCT-I, II, III and IV precision test\nin single precision\n\\item Sample 17 - VkFFT / FFTW R2R DCT-I, II, III and IV precision test\nin double precision\n\\item Sample 18 - VkFFT / FFTW C2C radix 3 / 5 / 7 / 11 / 13 / Bluestein\nprecision test in double precision\n\\item Sample 50 - convolution example with identity kernel\n\\item Sample 51 - zero padding convolution example with identity kernel\n\\item Sample 52 - batched convolution example with identity kernel\n\\item Sample 100 - VkFFT FFT + iFFT R2R DCT multidimensional benchmark in\nsingle precision\n\\item Sample 101 - VkFFT FFT + iFFT R2R DCT multidimensional benchmark in\ndouble precision\n\\item Sample 1000 - FFT + iFFT C2C benchmark 1D batched in single precision:\nall supported systems from 2 to 4096\n\\item Sample 1001 - FFT + iFFT C2C benchmark 1D batched in single precision:\nall supported systems from 2 to 4096\n\\item Sample 1003 - FFT + iFFT C2C benchmark 1D batched in single precision:\nall supported systems from 2 to 4096\n\\end{itemize}\n\n\\subsection{utils\\_VkFFT helper routines}\n\nLaunching even the simplest Vulkan application can be a non-trivial\ntask. To help with this, utils\\_VkFFT contains the routines that can\nhelp to create the simplest Vulkan application, allocate memory, record\ncommand buffers and launch them. Code has some comments explaining\nwhat is going on at each step. It also has some useful struct defines\n(like vkGPU) that keep the most important handles used in Vulkan Compute.\nThis section may be expanded in the future to the proper step-by-step\nguide on Vulkan Compute simple application creation. I also encourage\nto check https://github.com/DTolm/VulkanComputeSamples-Transposition\nrepository for another example of a compute algorithm (matrix transposition)\nimplemented with Vulkan API.\n\nutils\\_VkFFT also has a routine that prints the list of available\ndevices.\n\nvkGPU struct has the following definition:\n\n\\begin{mdframed}[backgroundcolor=bg]\n\\begin{minted}[tabsize=4,obeytabs,breaklines]{C}\ntypedef struct {\n#if(VKFFT_BACKEND==0) //Vulkan API\nVkInstance instance; //a connection between the application and the Vulkan library\nVkPhysicalDevice physicalDevice; //a handle for the graphics card used in the application\nVkPhysicalDeviceProperties physicalDeviceProperties; //bastic device properties\nVkPhysicalDeviceMemoryProperties physicalDeviceMemoryProperties; //basic memory properties of the device\nVkDevice device; //a logical device, interacting with physical device\nVkDebugUtilsMessengerEXT debugMessenger; //extension for debugging\nuint64_t queueFamilyIndex; //if multiple queues are available, specify the used one\nVkQueue queue; //a place, where all operations are submitted\nVkCommandPool commandPool; //an opaque objects that command buffer memory is allocated from\nVkFence fence; //a vkGPU->fence used to synchronize dispatches\nstd::vector enabledDeviceExtensions;\nuint64_t enableValidationLayers;\n#elif(VKFFT_BACKEND==1) //CUDA API\nCUdevice device;\nCUcontext context;\n#elif(VKFFT_BACKEND==2) //HIP API\nhipDevice_t device;\nhipCtx_t context;\n#elif(VKFFT_BACKEND==3) //OpenCL API\ncl_platform_id platform;\ncl_device_id device;\ncl_context context;\ncl_command_queue commandQueue;\n#endif\nuint64_t device_id; //an id of a device, reported by devices_list call\n} VkGPU;\n\\end{minted}\n\\end{mdframed}\\newpage{}\n\n\\section{VkFFT Code Examples}\n\nThis section will provide some simple pseudocode for VkFFT usage,\nwhich will once again outline important steps required to launch FFT\nwith VkFFT. More information (and fully working code) can be found\nin this folder of the VkFFT repository:\n\n/benchmark\\_samples/vkFFT\\_scripts/src/\n\n\\subsection{Driver initializations}\n\nBefore launching VkFFT, do not forget to do all necessary driver initializations.\nThe following code specifies them for all the supported backends,\nthough the final implementation may be different depending on the\nparticular user's configuration.\n\n\\begin{mdframed}[backgroundcolor=bg]\n\\begin{minted}[tabsize=4,obeytabs,breaklines]{C}\n#if(VKFFT_BACKEND==0) //Vulkan API\nVkResult res = VK_SUCCESS;\n//create instance - a connection between the application and the Vulkan library\nres = createInstance(vkGPU, sample_id);\nif (res != 0) {\n\t//printf(\"Instance creation failed, error code: %\" PRIu64 \"\\n\", res);\n\treturn VKFFT_ERROR_FAILED_TO_CREATE_INSTANCE;\n} \t\n//set up the debugging messenger\nres = setupDebugMessenger(vkGPU);\nif (res != 0) {\n//printf(\"Debug messenger creation failed, error code: %\" PRIu64 \"\\n\", res);\n\treturn VKFFT_ERROR_FAILED_TO_SETUP_DEBUG_MESSENGER;\n}\n//check if there are GPUs that support Vulkan and select one\nres = findPhysicalDevice(vkGPU);\nif (res != 0) {\n//printf(\"Physical device not found, error code: %\" PRIu64 \"\\n\", res);\n\treturn VKFFT_ERROR_FAILED_TO_FIND_PHYSICAL_DEVICE;\n}\n//create logical device representation\nres = createDevice(vkGPU, sample_id);\nif (res != 0) {\n//printf(\"Device creation failed, error code: %\" PRIu64 \"\\n\", res);\n\treturn VKFFT_ERROR_FAILED_TO_CREATE_DEVICE;\n}\n//create fence for synchronization\nres = createFence(vkGPU);\nif (res != 0) {\n//printf(\"Fence creation failed, error code: %\" PRIu64 \"\\n\", res);\n\treturn VKFFT_ERROR_FAILED_TO_CREATE_FENCE;\n}\n//create a place, command buffer memory is allocated from\nres = createCommandPool(vkGPU);\nif (res != 0) {\n\t//printf(\"Fence creation failed, error code: %\" PRIu64 \"\\n\", res);\n\treturn VKFFT_ERROR_FAILED_TO_CREATE_COMMAND_POOL;\n}\nvkGetPhysicalDeviceProperties(vkGPU->physicalDevice, &vkGPU->physicalDeviceProperties);\nvkGetPhysicalDeviceMemoryProperties(vkGPU->physicalDevice, &vkGPU->physicalDeviceMemoryProperties);\nglslang_initialize_process();\n//compiler can be initialized before VkFFT\n\n#elif(VKFFT_BACKEND==1) //CUDA API\nCUresult res = CUDA_SUCCESS;\ncudaError_t res2 = cudaSuccess;\nres = cuInit(0);\nif (res != CUDA_SUCCESS) return VKFFT_ERROR_FAILED_TO_INITIALIZE;\nres2 = cudaSetDevice((int)vkGPU->device_id);\nif (res2 != cudaSuccess) return VKFFT_ERROR_FAILED_TO_SET_DEVICE_ID;\nres = cuDeviceGet(&vkGPU->device, (int)vkGPU->device_id);\nif (res != CUDA_SUCCESS) return VKFFT_ERROR_FAILED_TO_GET_DEVICE;\nres = cuCtxCreate(&vkGPU->context, 0, (int)vkGPU->device);\nif (res != CUDA_SUCCESS) return VKFFT_ERROR_FAILED_TO_CREATE_CONTEXT;\n#elif(VKFFT_BACKEND==2) //HIP API\nhipError_t res = hipSuccess;\nres = hipInit(0);\nif (res != hipSuccess) return VKFFT_ERROR_FAILED_TO_INITIALIZE;\nres = hipSetDevice((int)vkGPU->device_id);\nif (res != hipSuccess) return VKFFT_ERROR_FAILED_TO_SET_DEVICE_ID;\nres = hipDeviceGet(&vkGPU->device, (int)vkGPU->device_id);\nif (res != hipSuccess) return VKFFT_ERROR_FAILED_TO_GET_DEVICE; \nres = hipCtxCreate(&vkGPU->context, 0, (int)vkGPU->device);\nif (res != hipSuccess) return VKFFT_ERROR_FAILED_TO_CREATE_CONTEXT;\n#elif(VKFFT_BACKEND==3) //OpenCL API\ncl_int res = CL_SUCCESS;\ncl_uint numPlatforms;\nres = clGetPlatformIDs(0, 0, &numPlatforms);\nif (res != CL_SUCCESS) return VKFFT_ERROR_FAILED_TO_INITIALIZE;\ncl_platform_id* platforms = (cl_platform_id*)malloc(sizeof(cl_platform_id) * numPlatforms);\nif (!platforms) return VKFFT_ERROR_MALLOC_FAILED;\nres = clGetPlatformIDs(numPlatforms, platforms, 0);\nif (res != CL_SUCCESS) return VKFFT_ERROR_FAILED_TO_INITIALIZE;\nuint64_t k = 0;\nfor (uint64_t j = 0; j < numPlatforms; j++) {\n\tcl_uint numDevices;\n\tres = clGetDeviceIDs(platforms[j], CL_DEVICE_TYPE_ALL, 0, 0, &numDevices);\n\tcl_device_id* deviceList = (cl_device_id*)malloc(sizeof(cl_device_id) * numDevices);\n\tif (!deviceList) return VKFFT_ERROR_MALLOC_FAILED;\n\tres = clGetDeviceIDs(platforms[j], CL_DEVICE_TYPE_ALL, numDevices, deviceList, 0);\n\tif (res != CL_SUCCESS) return VKFFT_ERROR_FAILED_TO_GET_DEVICE;\n\tfor (uint64_t i = 0; i < numDevices; i++) {\n\t\tif (k == vkGPU->device_id) {\n\t\t\tvkGPU->platform = platforms[j];\n\t\t\tvkGPU->device = deviceList[i];\n\t\t\tvkGPU->context = clCreateContext(NULL, 1, &vkGPU->device, NULL, NULL, &res);\n\t\t\tif (res != CL_SUCCESS) return VKFFT_ERROR_FAILED_TO_CREATE_CONTEXT;\n\t\t\tcl_command_queue commandQueue = clCreateCommandQueue(vkGPU->context, vkGPU->device, 0, &res);\n\t\t\tif (res != CL_SUCCESS) return VKFFT_ERROR_FAILED_TO_CREATE_COMMAND_QUEUE;\n\t\t\tvkGPU->commandQueue = commandQueue;\n\t\t\tk++;\n\t\t}\n\t\telse {\n\t\t\tk++;\n\t\t}\n\t}\n\tfree(deviceList);\n}\nfree(platforms);\n#endif\n\\end{minted}\n\\end{mdframed}\n\n\\subsection{Simple FFT application example: 1D (one dimensional) C2C (complex\nto complex) FP32 (single precision) FFT}\n\nThis example performs the simplest case of FFT. It shows all the necessary\nfields that the user must fill during the configuration and the submission\nprocess. Other samples will build on this one, as driver parameters\ninitialization and code execution commands are the same for all configurations\n(except for the launch parameters that can be configured after application\ncreation).\n\n\\begin{mdframed}[backgroundcolor=bg]\n\\begin{minted}[tabsize=4,obeytabs,breaklines]{C}\n//zero-initialize configuration + FFT application\nVkFFTConfiguration configuration = {};\nVkFFTApplication app = {};\n\nconfiguration.FFTdim = 1; //FFT dimension, 1D, 2D or 3D\nconfiguration.size[0] = Nx; //FFT size\nuint64_t bufferSize = (uint64_t)sizeof(float) * 2 * configuration.size[0];\n\n//Device management + code submission\nconfiguration.device = &vkGPU->device; \n\n#if(VKFFT_BACKEND==0) //Vulkan API\t\t\nconfiguration.queue = &vkGPU->queue;\nconfiguration.fence = &vkGPU->fence; \t\t\t\nconfiguration.commandPool = &vkGPU->commandPool; \t\t\t\nconfiguration.physicalDevice = &vkGPU->physicalDevice; \t\t\t\nconfiguration.isCompilerInitialized = isCompilerInitialized; //glslang compiler can be initialized before VkFFT plan creation. if not, VkFFT will create and destroy one after initialization \n#elif(VKFFT_BACKEND==3) //OpenCL API\t\t\nconfiguration.platform = &vkGPU->platform; \t\t\t\nconfiguration.context = &vkGPU->context; \n#endif\n\nallocateBuffer(buffer, bufferSize); //Pseudocode for buffer allocation, differs between APIs\ntransferDataFromCPU(buffer, cpu_buffer); //Pseudocode for data transfer from CPU to GPU, differs between APIs\n\n#if(VKFFT_BACKEND==0) //Vulkan API needs bufferSize at initialization\t\nconfiguration.bufferSize = &bufferSize; \n#endif\n\nVkFFTResult resFFT = initializeVkFFT(&app, configuration);\n\nVkFFTLaunchParams launchParams = {};\nlaunchParams.buffer = &buffer;\n#if(VKFFT_BACKEND==0) //Vulkan API \nlaunchParams.commandBuffer = &commandBuffer;\n#elif(VKFFT_BACKEND==3) //OpenCL API\nlaunchParams.commandQueue = &commandQueue;\n#endif\nresFFT = VkFFTAppend(app, -1, &launchParams);\n\n//add synchronization relevant to your API - vkWaitForFences/cudaDeviceSynchronize/hipDeviceSynchronize/clFinish\ntransferDataToCPU(cpu_buffer, buffer); //Pseudocode for data transfer from GPU to CPU, differs between APIs\n\nfreeBuffer(buffer, bufferSize); //Pseudocode for buffer deallocation, differs between APIs\n\ndeleteVkFFT(&app);\n\\end{minted}\n\\end{mdframed} \n\n\\subsection{Advanced FFT application example: ND, C2C/R2C/R2R, different precisions,\nbatched FFT}\n\nThis example shows how to configure the main parameters of interest\nin the VkFFT library: multidimensional case, different types of transforms,\ndifferent precision, perform batched transforms.\n\nIn the code below X, Y and Z are the dimensions of FFT, B - number\nof batches, R2C - real to complex mode 0 or 1 (on/off), DCT - 0, 1,\n2, 3 or 4 (off/DCT type), P - precision (0 - single, 1 - double, 2\n- half).\n\n\\begin{mdframed}[backgroundcolor=bg]\n\\begin{minted}[tabsize=4,obeytabs,breaklines]{C}\n//zero-initialize configuration + FFT application\nVkFFTConfiguration configuration = {};\nVkFFTApplication app = {};\n\nconfiguration.FFTdim = 1; //FFT dimension, 1D, 2D or 3D\nconfiguration.size[0] = X;\nconfiguration.size[1] = Y;\nconfiguration.size[2] = Z;\nif (Y > 1) configuration.FFTdim++;\nif (Z > 1) configuration.FFTdim++;\nconfiguration.numberBatches = B;\nconfiguration.performR2C = R2C;\nconfiguration.performDCT = DCT;\nif (P == 1) configuration.doublePrecision = 1; \nif (P == 2) configuration.halfPrecision = 1;\n\nuint64_t bufferSize = 0;\n\nif (R2C) {\n\tbufferSize = (uint64_t)(storageComplexSize / 2) * (configuration.size[0] + 2) * configuration.size[1] * configuration.size[2] * configuration.numberBatches;\n}\nelse {\n\tif (DCT) {\n\t\tbufferSize = (uint64_t)(storageComplexSize / 2) * configuration.size[0] * configuration.size[1] * configuration.size[2] * configuration.numberBatches;\n\t}\n\telse {\n\t\tbufferSize = (uint64_t)storageComplexSize * configuration.size[0] * configuration.size[1] * configuration.size[2] * configuration.numberBatches;\n\t}\n} // storageComplexSize - 4/8/16 for FP16/FP32/FP64 respectively.\n\n//Device management + code submission - code is identical to the previous example\n\\end{minted}\n\\end{mdframed}\n\n\\subsection{Advanced FFT application example: out-of-place R2C FFT with custom\nstrides}\n\nIn this example, VkFFT is configured to calculate a 3D out-of-place\nR2C FFT of a system with custom strides. VkFFT reads data from the\ninputBuffer and produces the result in the buffer. \n\n\\begin{mdframed}[backgroundcolor=bg]\n\\begin{minted}[tabsize=4,obeytabs,breaklines]{C}\n//zero-initialize configuration + FFT application\nVkFFTConfiguration configuration = {};\nVkFFTApplication app = {};\n\nconfiguration.FFTdim = 3; //FFT dimension, 1D, 2D or 3D\nconfiguration.size[0] = Nx;\nconfiguration.size[1] = Ny;\nconfiguration.size[2] = Nz;\n\nconfiguration.performR2C = 1;\n\n//out-of-place - we need to specify that input buffer is separate from the main buffer\nconfiguration.isInputFormatted = 1;\nconfiguration.inputBufferStride[0] = configuration.size[0];\nconfiguration.inputBufferStride[1] = configuration.inputBufferStride[0] * configuration.size[1];\nconfiguration.inputBufferStride[2] = configuration.inputBufferStride[1] * configuration.size[2];\n\t\t\t\nconfiguration.bufferStride[0] = (uint64_t) (configuration.size[0] / 2) + 1;\nconfiguration.bufferStride[1] = configuration.bufferStride[0] * configuration.size[1];\nconfiguration.bufferStride[2] = configuration.bufferStride[1]* configuration.size[2];\n\nuint64_t inputBufferSize = (uint64_t)sizeof(float) * configuration.size[0] * configuration.size[1] * configuration.size[2];\n\nuint64_t bufferSize = (uint64_t)sizeof(float) * 2 * (configuration.size[0]/2+1) * configuration.size[1] * configuration.size[2];\n\n//Device management + code submission - code is identical to the first example, except that you need to allocate two buffers (and provide them in the launch configuration).\n\n\\end{minted}\n\\end{mdframed}\n\n\\subsection{Advanced FFT application example: 3D zero-padded FFT}\n\nIn this example, VkFFT is configured to calculate a 3D FFT of a system.\nThe meaningful data is located in the first octant of the buffer,\nthe rest is padded with zeros. This configuration removes the circular\npart of the convolution and allows modelling of open systems.\n\n\\begin{mdframed}[backgroundcolor=bg]\n\\begin{minted}[tabsize=4,obeytabs,breaklines]{C}\n//zero-initialize configuration + FFT application\nVkFFTConfiguration configuration = {};\nVkFFTApplication app = {};\n\nconfiguration.FFTdim = 3; //FFT dimension, 1D, 2D or 3D\nconfiguration.size[0] = Nx;\nconfiguration.size[1] = Ny;\nconfiguration.size[2] = Nz;\n\nconfiguration.performZeropadding[0] = 1; //Perform padding with zeros on GPU. Still need to properly align input data (no need to fill padding area with meaningful data) but this will increase performance due to the lower amount of the memory reads/writes and omitting sequences only consisting of zeros.\nconfiguration.performZeropadding[1] = 1;\nconfiguration.performZeropadding[2] = 1;\nconfiguration.fft_zeropad_left[0] = (uint64_t)ceil(configuration.size[0] / 2.0);\nconfiguration.fft_zeropad_right[0] = configuration.size[0];\nconfiguration.fft_zeropad_left[1] = (uint64_t)ceil(configuration.size[1] / 2.0);\nconfiguration.fft_zeropad_right[1] = configuration.size[1];\nconfiguration.fft_zeropad_left[2] = (uint64_t)ceil(configuration.size[2] / 2.0);\nconfiguration.fft_zeropad_right[2] = configuration.size[2];\n\nuint64_t bufferSize = (uint64_t)storageComplexSize * configuration.size[0] * configuration.size[1] * configuration.size[2];\n\n\n//Device management + code submission - code is identical to the first example\n\n\\end{minted}\n\\end{mdframed}\n\n\\subsection{Convolution application example: 3x3 matrix-vector convolution in\n1D}\n\nIn this example, VkFFT is configured to calculate a kernel, represented\nby a 3x3 matrix and a system, represented by a 3D vector. Their convolution\nis a matrix-vector multiplication in the frequency domain.\n\n\\begin{mdframed}[backgroundcolor=bg]\n\\begin{minted}[tabsize=4,obeytabs,breaklines]{C}\n//zero-initialize configuration + FFT application, we need two - one for kernel calculation\nVkFFTConfiguration kernel_configuration = {};\nVkFFTConfiguration convolution_configuration = {};\nVkFFTApplication app_kernel = {};\nVkFFTApplication app_convolution = {};\n\n\nkernel_configuration.FFTdim = 1; //FFT dimension, 1D, 2D or 3D\nkernel_configuration.size[0] = Nx; //FFT size\n\nuint64_t bufferSize = (uint64_t)sizeof(float) * 2 * kernel_configuration.size[0];\n\n//configure kernel \nkernel_configuration.kernelConvolution = 1; //specify if this plan is used to create kernel for convolution\nkernel_configuration.coordinateFeatures = 9; //Specify dimensionality of the input feature vector (default 1). Each component is stored not as a vector, but as a separate system and padded on it's own according to other options (i.e. for x*y system of 3-vector, first x*y elements correspond to the first dimension, then goes x*y for the second, etc).\n//coordinateFeatures number is an important constant for convolution. If we perform 1x1 convolution, it is equal to number of features, but matrixConvolution should be equal to 1. For matrix convolution, it must be equal to matrixConvolution parameter. If we perform 2x2 convolution, it is equal to 3 for symmetric kernel (stored as xx, xy, yy) and 4 for nonsymmetric (stored as xx, xy, yx, yy). Similarly, 6 (stored as xx, xy, xz, yy, yz, zz) and 9 (stored as xx, xy, xz, yx, yy, yz, zx, zy, zz) for 3x3 convolutions. \nkernel_configuration.normalize = 1;\n\n//Initialize app_kernel and perform a single forward FFT like in examples before. You pass kernel as a buffer for the preparation stage.\n\nconvolution_configuration = kernel_configuration;\nconvolution_configuration.kernelConvolution = 0;\nconvolution_configuration.performConvolution = 1;\nconvolution_configuration.symmetricKernel = 0;//Specify if convolution kernel is symmetric. In this case we only pass upper triangle part of it in the form of: (xx, xy, yy) for 2d and (xx, xy, xz, yy, yz, zz) for 3d.\nconvolution_configuration.matrixConvolution = 3;//we do matrix convolution, so kernel is 9 numbers (3x3), but vector dimension is 3\nconvolution_configuration.coordinateFeatures = 3;//equal to matrixConvolution size\n\n//Initialize app_convolution and perform a single forward FFT like in examples before. You pass kernel as kernel and system to be convolved with it as buffer\n\n\\end{minted}\n\\end{mdframed}\n\n\\subsection{Convolution application example: R2C cross-correlation between two\nsets of N images}\n\nIn this example, VkFFT is configured to calculate a kernel, represented\nby three 2D vectors (RGB values of a pixel) and a system, also represented\nby three 2D vectors. There are N kernels and N systems. Their cross-correlation\nis a conjugate convolution in the frequency domain. Images are usually\nstored as real, not complex numbers, so code uses R2C optimization\nas well.\n\n\\begin{mdframed}[backgroundcolor=bg]\n\\begin{minted}[tabsize=4,obeytabs,breaklines]{C}\n//zero-initialize configuration + FFT application, we need two - one for kernel calculation\nVkFFTConfiguration kernel_configuration = {};\nVkFFTConfiguration convolution_configuration = {};\nVkFFTApplication app_kernel = {};\nVkFFTApplication app_convolution = {};\n\n\nkernel_configuration.FFTdim = 2; //FFT dimension, 1D, 2D or 3D\nkernel_configuration.size[0] = Nx;\nkernel_configuration.size[1] = Ny; \nkernel_configuration.coordinateFeatures = 3;\nkernel_configuration.numberBatches = N;\nkernel_configuration.performR2C = 1;\nkernel_configuration.normalize = 1;\n\nuint64_t bufferSize = (uint64_t)sizeof(float) * 2 * (kernel_configuration.size[0]/2+1) * kernel_configuration.size[1] * kernel_configuration.coordinateFeatures * kernel_configuration.numberBatches; \n\t\nkernel_configuration.kernelConvolution = 1; //specify if this plan is used to create kernel for convolution\n\n//Initialize app_kernel and perform a single forward FFT like in examples before. Pad in-place R2C system like this:\n\nfor (uint64_t n = 0; n < kernel_configuration.numberBatches; n++) {\n\tfor (uint64_t c = 0; c < kernel_configuration.coordinateFeatures; c++) {\n\t\tfor (uint64_t j = 0; j < kernel_configuration.size[1]; j++) {\n\t\t\tfor (uint64_t i = 0; i < kernel_configuration.size[0]; i++) {\n\t\t\t\tkernel_padded_GPU[i + j * 2 * (kernel_configuration.size[0]/2 + 1) + c * 2 * (kernel_configuration.size[0]/2 + 1) * kernel_configuration.size[1] + n * 2 * (kernel_configuration.size[0]/2 + 1) * kernel_configuration.size[1] * kernel_configuration.coordinateFeatures] = kernel_input[i + j * kernel_configuration.size[0] + c * kernel_configuration.size[0] * kernel_configuration.size[1] + n * kernel_configuration.size[0] * kernel_configuration.size[1] * kernel_configuration.coordinateFeatures];\n\t\t\t}\n\t\t}\n\t}\n}\nconvolution_configuration = kernel_configuration;\nconvolution_configuration.kernelConvolution = 0;\nconvolution_configuration.performConvolution = 1;\nconvolution_configuration.conjugateConvolution = 1;\n\n//Initialize app_convolution and perform a single forward FFT like in examples before. Pad the system in the same way as the kernel\n\n\\end{minted}\n\\end{mdframed}\n\n\\subsection{Simple FFT application binary reuse application}\n\nThis example shows how to save/load binaries generated by VkFFT. This\ncan reduce time taken by initializeVkFFT call by removing RTC components\nfrom it. Be sure that rest of the configuration stays the same to\nreuse the binary.\n\n\\begin{mdframed}[backgroundcolor=bg]\n\\begin{minted}[tabsize=4,obeytabs,breaklines]{C}\nVkFFTConfiguration configuration = {};\nVkFFTApplication app = {};\n\n//configuration is initialized like in other examples\nconfiguration.saveApplicationToString = 1;\n//configuration.loadApplicationFromString = 1; //choose one to save/load binary file\n\nif (configuration.loadApplicationFromString) {\n\tFILE* kernelCache;\n\tuint64_t str_len;\n#if(VKFFT_BACKEND==0)\n\tkernelCache = fopen(\"VkFFT_binary\", \"rb\"); //Vulkan and HIP backends load data as a uint32_t sequence\n#else\n\tkernelCache = fopen(\"VkFFT_binary\", \"r\"); \n#endif\n\tfseek(kernelCache, 0, SEEK_END);\n\tstr_len = ftell(kernelCache);\n\tfseek(kernelCache, 0, SEEK_SET);\n\tconfiguration.loadApplicationString = malloc(str_len);\n\tfread(configuration.loadApplicationString, str_len, 1, kernelCache);\n\tfclose(kernelCache);\n}\n\nresFFT = initializeVkFFT(&app, configuration);\nif (resFFT != VKFFT_SUCCESS) return resFFT;\n\nif (configuration.loadApplicationFromString)\n\tfree(configuration.loadApplicationString);\n\nif (configuration.saveApplicationToString) {\n\tFILE* kernelCache;\n#if(VKFFT_BACKEND==0)\n\tkernelCache = fopen(\"VkFFT_binary\", \"wb\"); //Vulkan and HIP backends save data as a uint32_t sequence\n#else\n\tkernelCache = fopen(\"VkFFT_binary\", \"w\"); \n#endif\n\tfwrite(app.saveApplicationString, app.applicationStringSize, 1, kernelCache);\n\tfclose(kernelCache);\n}\n\n//application is launched like in other examples\n\\end{minted}\n\\end{mdframed} \n\\end{document}\n", "meta": {"hexsha": "7afef0bea26547a04d95deecb92846257af5752b", "size": 107549, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "documentation/VkFFT_API_guide.tex", "max_stars_repo_name": "xfong/VkFFT", "max_stars_repo_head_hexsha": "b951b37b75533bb5078e1d38166ba3b42f3590bd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2022-01-21T20:18:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-01T19:53:26.000Z", "max_issues_repo_path": "documentation/VkFFT_API_guide.tex", "max_issues_repo_name": "krakenrf/VkFFT", "max_issues_repo_head_hexsha": "4d581d411fb494a07c5356cf48b49f7392552646", "max_issues_repo_licenses": ["MIT"], "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/VkFFT_API_guide.tex", "max_forks_repo_name": "krakenrf/VkFFT", "max_forks_repo_head_hexsha": "4d581d411fb494a07c5356cf48b49f7392552646", "max_forks_repo_licenses": ["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.8756145526, "max_line_length": 519, "alphanum_fraction": 0.7935917582, "num_tokens": 27039, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4843800842769844, "lm_q2_score": 0.32082129433083023, "lm_q1q2_score": 0.15539944558581878}} {"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{PHYS440}\n\\Submitted{26.10.84} \\Revised{16.12.93}\n\\Makehead{Total cross-section and energy loss for bremsstrahlung by\nMuons}\n\\section{Subroutines}\n\\Shubr{GBRELA}{}\n{\\tt GBRELA} fills the tables for continuous energy loss of electrons,\npositrons and muons due to bremsstrahlung during initialisation time.\nThe energy binning is determined by\nthe array {\\tt ELOW} (common \\FCind{/CGMULO/}) in the\nroutine \\Rind{GPHYSI}. In the tables, the $dE/dx$ due to bremsstrahlung\nis summed with that due to the ionisation. For energy loss\nof muons, \\Rind{GBRELA} calls the function \\Rind{GDRELM}.\nThe following pointers are used:\n\\begin{DLtt}{MMMMMMMMMMMMMMMMMM}\n\\item[JMA = LQ(JMATE-I)] pointer to the I$^{th}$ material;\n\\item[JEL1 = LQ(JMA-1)] pointer to dE/dx for electrons;\n\\item[JEL1+NEK1] pointer to dE/dx for positrons;\n\\item[JEL2 = LQ(JMA-2)] pointer to dE/dx for electrons.\n\\end{DLtt}\n\\Rind{GBRELA} is called by \\Rind{GPHYSI}.\n\\Sfunc{GBRELM}{VALUE = GBRELM(Z,T,BCUT)}\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[BCUT] ({\\tt REAL}) {\\it soft} bremsstrahlung cut.\n\\end{DLtt}\n\\Rind{GBRELM} calculates the muon energy loss due to bremsstrahlung\nof photons with energy below {\\tt BCUT}, (variable {\\tt BCUTM} in the\ncommon \\FCind{/GCCUTS/}).\nAbove this value, the bremsstrahlung process is simulated\nexplicitly (see {\\tt [PHYS441]}) and the energy lost by the muons is\nnot included in the tables. \nIn the tables, the $dE/dx$ due to bremsstrahlung is summed with\nthe energy lost coming from ionisation, pair production and nuclear interaction.\n\\Rind{GBRELM} is called by \\Rind{GBRELA}.\n\\Shubr{GBRSGA}{}\n{\\tt GBRSGA} calculates the total cross-section for bremsstrahlung.\nIt tabulates the mean free path\nin cm as a function of the medium and the energy. The energy\nbinning is determined by the array {\\tt ELOW} (common \\FCind{/CGMULO/}).\nThe following pointers are used:\n\\begin{DLtt}{MMMMMMMMMMMMMMMMMM}\n\\item[JMA = LQ(JMATE-I)]pointer to the I$^{th}$ material;\n\\item[JBREM = LQ(JMA-9)]pointer to bremsstrahlung cross-sections;\n\\item[JBREM ]pointer for \\Pem;\n\\item[JBREM+NEK1 ]pointer for \\Pep;\n\\item[JBREM+2*NEK1 ]pointer for $\\mu^+/\\mu^-$.\n\\end{DLtt}\n\\Rind{GBRSGA} is called during initialisation by \\Rind{GPHYSI}.\n\\Sfunc{GBRSGM}{VALUE = GBRSGM(Z,T,BCUT)}\n\\begin{DLtt}{MMMMMMMM}\n\\item[Z] ({\\tt REAL}) atomic number of the materian;\n\\item[T] ({\\tt REAL}) kinetic energy of the muon;\n\\item[BCUT] ({\\tt REAL}) {\\it soft} bremsstrahlung cut.\n\\end{DLtt}\n\\Rind{GBRSGM} calculates the total bremsstrahlung cross-section for\nmuons when the emitted photon has an energy greater than {\\tt BCUT}, \n(variable {\\tt BCUTM} in the common \\FCind{/GCCUTS/}). It is called\nby \\Rind{GBRSGA}.\n\\section{Method}\n \nThe mean value of the energy lost by the muon due to bremsstrahlung of\nphotons of energy $ k_c $ is\n\\begin {equation}\n\\label{eq:phys440-2}\n \\sigma (Z,T,k_c ) = \\int_{k_c}^{T}\n \\frac{d \\sigma (Z,T,k)} {dk} dk\n\\end{equation}\nAccurate cross-section formula for the high energy ($T \\geq 1$ GeV)\nmuon bremsstrahlung can be found in \\cite{bib-LOHM}.\n\n\\subsection{Parameterisation of energy loss and total cross-section}\nThe cross-sections from \\cite{bib-LOHM} have been used to calculate \n{\\it data} points for (\\ref{eq:phys440-1}) and (\\ref{eq:phys440-2}).\nThese have been parameterised as:\n\\[ \\begin{array}{LcLl}\n \\sigma (Z,T,k_c)& =& Z[Z+ \\xi_{\\sigma}(1+ \\gamma \\ln Z)]\n \\left[\\ln \\frac{k_{max}}{k_c}\\right]^{\\alpha}\n F_{\\sigma}(Z,X,Y) & \\mbox{ in barn} \\\\\n E_{loss}^{brem} (Z,T,k_c) & = & Z[Z+\\xi_l(1+\\delta\\ln Z)]\n \\left[\\ln\\frac {k_c} {E} \\right]^{\\beta}\n F_l(Z,X,Y) & \\mbox{ in GeV barn}\n\\end{array} \\]\n\\[ \\begin{array}{LcL@{\\hspace{2cm}}LcL}\nk_{max} & = & E-0.75 \\sqrt {e}m_{\\mu}Z^{1/3} & X & = & \\ln \\frac{E}{m_{\\mu}} \\\\\nY & = & \\ln \\frac{k_c}{m_{\\mu}} & E & = & T+m_{\\mu}\n\\end{array} \\]\nwhere $k_{max}$ is the maximum\npossible value of the photon energy.\nThe functions $F_i(Z,X,Y)$ ($i=\\sigma ,l$) are polynomials:\n\\begin{eqnarray}\n\\label{eq:phys440-3}\nF_i(Z,X,Y) & = & (C_1+C_2X+\\cdots +C_6X^5)+(C_7+C_8X+\\cdots+C_{12}X^5)Y\n\\nonumber \\\\\n & + & \\cdots + (C_{31}+C_{32}X+\\cdots+C_{36}X^5)Y^5\n\\nonumber \\\\\n & + & Z[(C_{37}+C_{38}X+\\cdots+C_{40}X^3)+(C_{41}+C_{42}X+\n \\cdots+C_{44}X^3)Y \\nonumber \\\\\n & + & \\cdots + (C_{48}+C_{49}X+\\cdots+C_{52}X^3)Y^3)]\n\\end{eqnarray}\nA least-squares fit has been performed on more than 2000 points for\n$Z = 1, 6, 13, 26, 50, 82, 92$ and 1 GeV $\\leq T \\leq $ 10 TeV and\n10 keV $\\leq k_c \\leq T $. The resulting values of \n$\\xi_{\\sigma,l}$, $\\gamma$, $\\alpha$ ,$C_i$, $\\xi_l$, $\\delta$ and $\\beta$\ncan be found in the {\\tt DATA} statements within the functions\n\\Rind{GBRSGM} and \\Rind{GBRELM} which\ncompute formulae (\\ref{eq:phys440-1}) and (\\ref{eq:phys440-2}) respectively.\n \nThe accuracy of the fit can be estimated as:\\\\\n \n\\[ \\begin{array}{LcL}\n\\frac{\\Delta \\sigma}{\\sigma} & = & \\left \\{\n\\begin{array}{p{2cm}lL}\n$\\displaystyle 10-12\\%$ & \\mbox{if} & T \\leq 5 \\: \\mbox{GeV} \\\\\n$\\displaystyle \\leq 4\\%$ & \\mbox{if} & T > 5 \\: \\mbox{GeV}\n\\end{array} \\right . \\\\ [0.5cm]\n\\frac{\\Delta E_{loss}^{brem}}{E_{loss}^{brem}} & = & \\left \\{\n\\begin{array}{p{2cm}lL}\n$\\displaystyle 10\\%$ & \\mbox{if} & T \\leq 5 \\: \\mbox{GeV} \\\\\n$\\displaystyle \\leq 3\\%$ & \\mbox{if} & T > 5 \\: \\mbox{GeV}\n\\end{array} \\right .\n\\end{array} \\]\n \nThe contribution of the bremsstrahlung to the total energy loss of\nthe muons is less than 1\\% for $ T \\leq$ 5 GeV.\n \nWhen $k_{c} \\geq k_{max}$, a parameterisation different from \n(\\ref{eq:phys440-3}) can be used for the total muon energy loss due to \nbremsstrahlung:\n\\begin{eqnarray} \n\\label{eq:phys440-4}\nE_{loss}^{brem} (Z,T) & = & E_{loss}^{brem}(Z,T,k=k_{max}) \n\\nonumber\\\\\n& = & Z(Z+1) k_{max}[d_1+(d_2X+d_3Y) + (d_4X^2+d_5 XY+d_6 Y^2) \\nonumber \\\\\n& + & \\cdots+(d_{22}X^6+d_{23}X^5 Y+\\cdots+d_{28}Y^6)]\n\\end{eqnarray}\nwhere $Y=Z^{1/3}$. \nThe accuracy of the formula (\\ref{eq:phys440-4}) for $1 \\leq Z \\leq 100$\nis rather good:\n\\[\n\\frac{\\Delta E_{loss}^{brem}}{E_{loss}^{brem}} = \\left \\{\n\\begin{array}{LlL}\n\\leq 1.5\\% & \\mbox{if} & T > 1 \\; \\mbox{GeV} \\\\\n\\leq 1\\% & \\mbox{if} & T > 5 \\; \\mbox{GeV}\n\\end{array} \\right .\n\\]\n", "meta": {"hexsha": "a53f14fda12128fe646f2f4435e589e9c10b2206", "size": 7145, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "geant/phys440.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/phys440.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/phys440.tex", "max_forks_repo_name": "berghaus/cernlib-docs", "max_forks_repo_head_hexsha": "76048db0ca60708a16661e8494e1fcaa76a83db7", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.303030303, "max_line_length": 80, "alphanum_fraction": 0.6174947516, "num_tokens": 2623, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269796369905, "lm_q2_score": 0.2782567937024021, "lm_q1q2_score": 0.15535827519133533}} {"text": "\\documentclass[11 pt]{scrartcl}\n\\usepackage[header, margin, koma, stylish]{tyler}\n\n\\newcommand{\\hwtitle}{Discussion 3B Recap}\n\n\\pagestyle{fancy}\n\\fancyhf{}\n\\fancyhead[l]{\\hwtitle{}}\n\\fancyhead[r]{Tyler Zhu}\n\\cfoot{\\thepage}\n\n\\begin{document} \n\\title{\\Large \\hwtitle{}}\n\\author{\\large Tyler Zhu}\n\\date{\\large\\today}\n\n\\maketitle \n\n\\section{Quiz Review}\nWe went over the following problem in discussion. \n\\begin{problem}\n If all vertices of an undirected graph have degree 4, the graph must be the complete graph on five vertices, $K_5$. \n\\end{problem}\nThe answer is no, and there are \\emph{many} examples (in fact, a whole class of graphs called the \\href{https://en.wikipedia.org/wiki/Regular_graph}{4-regular graphs}). These counter-examples are all quite instructive: \n\\itemnum\n \\ii $K_{4,4}$, the complete bipartite graph on two sets of 4 vertices\n \\ii $H_4$, the 4-dimensional hypercube (in scope) \n \\ii $K_5\\cup K_5$, the union of two $K_5$'s (albeit disconnected) \n \\ii The double of any 3-regular graph (see Homework 3). \n \\ii \\dots and many more\n\\itemend\n\nIn our proof that all trees with at least 2 vertices are bipartite, we used the following fact:\n\\begin{fact}\n Every tree has at least 2 leaves, or vertices of degree 1. \n\\end{fact}\nI'll present two proofs of this fact, one constructive and one not (but only for the existence of one leaf). \n\\begin{proof}[Extremal Proof]\n Take any longest path in the tree. The two endpoints of this path must be leaves, as otherwise I could further traverse them and create a longer path, contradiction.\n\\end{proof}\n\nHere's the second proof, which I actually got from one of my students. It only shows that there is one leaf, but that's all we need for our proof actually. \n\n\\begin{proof}[Non-constructive Proof]\n We use the following fact: \n \\begin{fact}\n A graph with $k$ edges and $n$ vertices has a vertex of degree at most $2k/n$.\n \\end{fact}\n The proof is exactly the same as Problem 2(a), since some number must be $\\leq$ the average. But a tree has $n-1$ edges and $n$ vertices, so there is a vertex of degree $2(n-1)/n < 2$, which means there exists a vertex of degree 1. \n\\end{proof}\n\n\nIn our first proof, we made use of the \\emph{Extremal Principle}, which is just a fancy way of saying to look at the extreme cases. Here's one cute example, and one slightly harder exercise. \n\n\\begin{exercise}\n There are $n$ students standing in a field such that the distance between each pair is distinct. Each student is holding a ball, and when the teacher blows a whistle, each student throws their ball to the nearest student. Prove that there is a pair of students that throw their balls to each other.\n\\end{exercise}\n\\begin{exercise}\n Suppose $n$ people are attending a banquet, and each of them has at least $m$\nfriends $(2 \\leq m \\leq n)$, where friendship is mutual. Prove that we can put at least $m + 1$ of the attendants on the same round table, so that each person sits next to his or her friends on both sides.\n\\end{exercise}\n\n\\section{Fermat's Little Theorem}\n\\begin{theorem}[Fermat's Little Theorem]\n For all prime $p$ with $\\gcd(a,p) = 1$, $a^{p-1} \\equiv 1 \\pmod{p}$. \n\\end{theorem}\n\nUse this theorem to help you reduce arbitrary powers more easily. For example, the theorem makes $23^{36}\\equiv 1 \\pmod{37}$ obvious immediately. Combined with CRT, powers become a piece of cake. \n\n\\section{Bijections}\nA \\emph{function} maps inputs from a set $A$ to elements in a set $B$. We denote them as $f: A\\to B$. You've already seen many examples of functions. In fact, any mod operator like $f(x) = x\\pmod{m}$ is also a function (what are $A$ and $B$?). \n\nThere are two main types of functions that we're interested in (fix a function $f:A\\to B$): \n\\itemnum\n \\ii $f$ is \\textbf{onto} (surjective) if $\\forall b\\in B, \\exists a\\in A$ s.t. $f(a) = b$\n \\itemnum\n \\ii i.e. every $b\\in B$ has a pre-image.\n \\itemend\n \\ii $f$ is \\textbf{one-to-one} (injective) if $\\forall a,a' \\in A, f(a) = f(a') \\implies a = a'$.\n \\itemnum\n \\ii i.e. different inputs map to different outputs, \n \\itemend\n\\itemend\n\n If $f$ is both onto and one-to-one, we say that $f$ is \\textbf{bijective}. Bijections are useful because they have formalize what it means for a function to be invertible. \n\n\\begin{theorem}\n A function $f:A\\to B$ is a bijection if and only if it has an inverse, i.e. there exists a bijection $g: B\\to A$ for which $\\forall a\\in A, g(f(a)) = a$ and $\\forall b\\in B, f(g(b)) = b$.\n\\end{theorem}\n\nHere's a helpful graphic illustrating the differences between all of these functions. \n\\begin{figure}[!htb]\n \\centering\n \\includegraphics[scale=0.75]{function-mapping.png}\n \\caption{Examples of the four types of functions, and a non-function. Source: Math is Fun.}\n\\end{figure}\n\nOne interesting observation you might make is that for $f:A\\to B$ to be injective, $|A| \\leq |B|$ must hold. Similarly, if $f:A\\to B$ is surjective, $|A| \\geq |B|$ must hold. Therefore if $f$ is bijective, $|A| = |B|$ must be true. For finite sets this isn't so remarkable, but later on in the course we will see how this gives us a method of comparing sets that are infinite in size! \n\n\\section{Chinese Remainder Theorem}\n\nI will first begin with the formal statement of the theorem. \n\\begin{theorem}[Chinese Remainder Theorem] \n Let $m_1, \\dots, m_k$ be pairwise\\footnote{Every pair of integers is relatively prime, as opposed to being relatively prime as a whole.} relatively prime positive integers, and let\n \\[ M = m_1 \\dots m_k.\\]\n Then for every $k$-tuple $(x_1, \\dots, x_k)$ of integers, there is exactly one residue class $x \\pmod{M}$ such that\n \\begin{align*}\n x &\\equiv x_1 \\pmod{m_1} \\\\ \n x &\\equiv x_2 \\pmod{m_2} \\\\ \n &\\vdots \\\\\n x &\\equiv x_k \\pmod{m_k}.\n \\end{align*}\n\\end{theorem}\n\nWe call this a theorem, but it's really just a formalization of an intuition you should have. In other words, every integer mod $M$ can be uniquely identified by its values mod $m_1$, mod $m_2$, and so on. \n\nFor example, knowing that $x\\equiv 10 \\pmod{15}$ is equivalent to knowing that $x\\equiv 1\\pmod{3}$ and $x \\equiv 0 \\pmod{5}$. The first condition restricts the possibilities to 5 different values (1, 4, 7, 10, 13), and the second condition tells you exactly which of these 5 the number is (10, being the only multiple of 5). You should expect this to happen in general.\n\n\\begin{example}\n Suppose we're trying to determine $8^{39} \\pmod{15}$. Without using CRT, we're pretty much stuck with hand computation. But let's break this down mod 3 and mod 5. We have that \n \\[ 8^{39} \\equiv (-1)^{39} \\equiv -1 \\equiv 2 \\pmod{3} \\] \n and \n \\[ 8^{39} \\equiv 3^{39} \\equiv 3\\cdot 9^{19} \\equiv 3\\cdot (-1)^{19} \\equiv 2\\pmod{5} \\] \n so by CRT, $8^{39}\\equiv 2 \\pmod{15}$. \n\\end{example}\n\nExtending the previous analogy, we can interpret this equivalence as understanding $x$ mod $M$ in terms of its basis vectors (1 mod $m_1$), (1 mod $m_2$), $\\cdots$, (1 mod $m_k$). Each one specifies $x$'s value along that dimension (or that mod space). Then all we need to do is find out the correct coefficients to multiply each of the vectors by to create a linear combination that produces $x$ mod $M$. \n\nLet's create a general method for finding $x\\mod{M}$ based on its values mod $m_1, \\dots,$ mod $m_k$. Throughout this section, we will be using a fact that you have seen already, so we will refer to it by its common name. \n\n\\begin{theorem}[Bezout's Lemma]\n Let $a,b$ be integers with $\\gcd(a,b) = d$. Then there exists integers $x,y$ such that $ax+by = d$. Furthermore, all integers of the form $ax+by$ are multiples of $d$. \n\\end{theorem}\n\nFirst we will do a short, concrete example. \n\n\\begin{example}[Dis 3B \\#3]\n Let's find the $x$ for which \n \\begin{align*}\n x&\\equiv 3 \\pmod{11} \\\\ \n x&\\equiv 7 \\pmod{13}.\n \\end{align*}\n Recall that since $\\gcd(11,13) = 1$, by Bezout's Lemma there are integers $a,b$ so that\n \\[ x = 11a + 13b.\\]\n We just need to pick them so that $x$ satisfies our above constraints (which will be unique mod 143 by CRT). First, let's take our equation mod 11 and use our constraint; this gives \n \\[ 3\\equiv x \\equiv 13b \\pmod{11}.\\] \n So $b = 13^{-1}\\times 3 \\equiv 6\\times 3 \\equiv 7 \\pmod{11}$. Now let's take our equation mod 13 and use the other constraint to get \n \\[ 7\\equiv x \\equiv 11a \\pmod{13}.\\] \n So $a = 11^{-1}\\times 7 \\equiv 6\\times 7 \\equiv 3\\pmod{13}$. Putting this all together, we find that \n \\[ x = 11a + 13b = 11\\times 3 + 13\\times 7 = 33 + 91 \\implies \\boxed{x \\equiv 124 \\pmod{143}}.\\] \n\\end{example}\n\nWith this example in mind, let's see how we would carry out these steps in general. Suppose we have just two equations\n \\begin{align*}\n x &\\equiv x_1 \\pmod{m_1} \\\\ \n x &\\equiv x_2 \\pmod{m_2}.\n \\end{align*}\n\n Since $\\gcd(m_1, m_2) = 1$, by Bezout's Lemma there are integers $c_1, c_2$ for which \n \\[ x = c_1m_1 + c_2m_2\\] \n unique up to mod $m_1m_2$. Taking this mod $m_1$, we find \n \\[ x_1 \\equiv x \\equiv c_2m_2 \\pmod{m_1} \\implies c_2 \\equiv m_2^{-1} x_1 \\pmod{m_1}.\\]\n\n Taking the equation mod $m_2$, we also get \n \\[ x_2 \\equiv x \\equiv c_1m_1 \\pmod{m_2} \\implies c_1 \\equiv m_1^{-1} x_2 \\pmod{m_2}.\\]\n\n Putting this together, we find that \n\n \\[ \\boxed{x \\equiv (m_1)^{-1}_{m_2}m_1 x_2 + (m_2)^{-1}_{m_1}m_2 x_1 \\pmod{m_1m_2}}\\] \n\n where $(a)^{-1}_m$ denotes $a^{-1}$ mod $m$. \n\n This looks complicated, but remember that what we did was pretty natural. We simply had a system of equations with some constraints, and using those constraints we found out what each of the required coefficients are. \n\n Having seen the case of two moduli, we can proceed with the general case. Let $M = m_1\\dots m_k$ be a product of pairwise coprime integers, and suppose we have the system \n \\begin{align*}\n x &\\equiv x_1 \\pmod{m_1} \\\\ \n x &\\equiv x_2 \\pmod{m_2} \\\\ \n &\\vdots \\\\\n x &\\equiv x_k \\pmod{m_k}.\n \\end{align*}\n \n Fix an $m_i$. Since $\\gcd(M/m_i, m_i) = 1$, by Bezout's Lemma, there are integers $C_i, c_i$ for which \n \\[ x = C_i \\left(\\dfrac{M}{m_i}\\right) + c_i m_i.\\] \n\n Taking this mod $m_i$, we find that \n\n \\[ x_i \\equiv x \\equiv C_i \\left(\\dfrac{M}{m_i}\\right) \\implies C_i \\equiv \\left(\\dfrac{M}{m_i}\\right)^{-1} x_i \\pmod{m_i}.\\] \n\n I claim that these coefficients create a solution for $x$, i.e. that \n \\[ x = \\sum_{i = 1}^k C_i \\left(\\dfrac{M}{m_i}\\right) \\equiv \\sum_{i=1}^k \\left(\\dfrac{M}{m_i}\\right)^{-1}_{m_i} \\left(\\dfrac{M}{m_i}\\right) x_i \\pmod{M}.\\] \n\n If I took this expression mod $m_i$, every term that's not the $x_i$ term would be 0 as $\\frac{M}{m_j}$ would contain $m_i$. The $i$th term would cancel out to just $x_i$, which is precisely what we wanted. \n\n In a sense, these coefficients are our ``basis coefficients'' which are always 1 mod $m_i$ and 0 otherwise, so that $x$ mod $m_i$ is always $x_i$. When we study Lagrange Interpolation, you will see a deep connection between these two concepts, as they are essentially the same idea applied in two different contexts. \n\n\n\\subsection{Quick Remark}\nHere's a quick and dirty way to solve Question 3. \n\\begin{example}[Very, Very Fast]\n Let's find the $x$ for which \n \\begin{align*}\n x&\\equiv 3 \\pmod{11} \\\\ \n x&\\equiv 7 \\pmod{13}.\n \\end{align*}\n The second equation tells us that $x = 7 + 13k$ for some $k\\in \\ZZ$. If we take this equation mod 11, we know it must be equivalent to 3, so \n \\[ 3 \\equiv x \\equiv 7 + 2k \\implies 2k \\equiv 7\\pmod{11}\\] \n from which it's easy to tell that $k = 9$. Thus, $x = 7 + 13\\cdot 9 \\equiv 128 \\pmod{143}$ is our answer.\n\\end{example}\n\n\\end{document}\n", "meta": {"hexsha": "beec37bfe266f1fa6971be91ba2c9548d55cf52b", "size": 11789, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "CS70/recap3b/recap3b.tex", "max_stars_repo_name": "cbugwadia32/course-notes", "max_stars_repo_head_hexsha": "cc269a2606bab22a5c9b8f1af23f360fa291c583", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2021-07-20T19:22:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-07T01:19:16.000Z", "max_issues_repo_path": "CS70/recap3b/recap3b.tex", "max_issues_repo_name": "cbugwadia32/course-notes", "max_issues_repo_head_hexsha": "cc269a2606bab22a5c9b8f1af23f360fa291c583", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CS70/recap3b/recap3b.tex", "max_forks_repo_name": "cbugwadia32/course-notes", "max_forks_repo_head_hexsha": "cc269a2606bab22a5c9b8f1af23f360fa291c583", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-10-13T08:41:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-07T17:21:17.000Z", "avg_line_length": 55.608490566, "max_line_length": 406, "alphanum_fraction": 0.6794469421, "num_tokens": 3788, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.31069438321455395, "lm_q1q2_score": 0.15534719160727697}} {"text": "\\section{A stateless forging policy language}\n\\label{sec:fps-language}\n\nThe domain-specific language for forging policies strikes a balance between expressiveness and simplicity. It particular, it is stateless and of bounded computational complexity. Nevertheless, it is sufficient to support the applications described in Section~\\ref{sec:applications}.\n\n\\paragraph{Semantically meaningful token names.}\n\nThe policy ID is associated with a policy script (it is the hash of it),\nso it has a semantic meaning that is identified with that of the script.\nIn the clauses of our language, we give semantic meaning\nto the names of the tokens as well. This allows us to make some\njudgements about them in a programmatic way, beyond confirming that the\npreservation of value holds, or\nwhich ones are fungible with each other.\nFor example, the $\\texttt{FreshTokens}$ constructor gives us a way to programmatically generate\ntoken names which, by construction, mean that these tokens are unique, without\never checking the global ledger state.\n\n\\paragraph{Forging policy scripts as output-locking scripts.}\n\nAs with\ncurrency in the non-digital world, it is a harder problem to control the transfer of assets once\nthey have come into circulation (see also Section~\\ref{sec:discussion}). We can, however,\nspecify directly in the forging policy that the assets being forged must\nbe locked by an output script of our choosing.\nMoreover, since both output addresses and policies are hashes of scripts,\nwe can use the asset policy ID and the address interchangeably.\nThe $\\texttt{AssetToAddress}$ clause is used for this purpose.\n\n\\begin{figure}[t]\n \\begin{lstlisting}\n $\\llbracket$JustMSig(msig)$\\rrbracket$(h, tx, utxo) = checkMultiSig(msig, tx)\n\n $\\llbracket$SpendsOutput(o)$\\rrbracket$(h, tx, utxo) = o $\\in $ { i.outputRef : i $\\in $ tx.inputs }\n\n $\\llbracket$TickAfter(tick1)$\\rrbracket$(h, tx, utxo) = tick1 $\\leq$ min(tx.validityInterval)\n\n $\\llbracket$Forges(tkns)$\\rrbracket$(h, tx, utxo) = (h $\\mapsto$ tkns $\\in$ tx.forge) && (h $\\mapsto$ tkns $\\geq$ 0)\n\n $\\llbracket$Burns(tkns)$\\rrbracket$(h, tx, utxo) = (h $\\mapsto$ tkns $\\in$ tx.forge) && (h $\\mapsto$ tkns $\\leq$ 0)\n\n $\\llbracket$FreshTokens$\\rrbracket$(h, tx, utxo) =\n $\\forall$ pid $\\mapsto$ tkns $\\in$ tx.forge, pid == h $\\Rightarrow$\n $\\forall$ t $\\mapsto$ q $\\in$ tkns,\n t == hash(indexof(t, tkns), tx.inputs) && q == 1\n\n $\\llbracket$AssetToAddress(addr)$\\rrbracket$(h, tx, utxo) =\n $\\forall$ pid $\\mapsto$ tkns $\\in$ utxo.balance, pid == h $\\Rightarrow$\n addr == _ $\\Rightarrow$ (h, pid $\\mapsto$ tkns) $\\in$ utxo\n $\\wedge$ addr $\\neq$ _ $\\Rightarrow$ (addr, pid $\\mapsto$ tkns) $\\in$ utxo\n\n $\\llbracket$DoForge$\\rrbracket$(h, tx, utxo) = h $\\in$ supp(tx.forge)\n\n $\\llbracket$SignedByPIDToken$\\rrbracket$(h, tx, utxo) =\n $\\forall$ pid $\\mapsto$ tkns $\\in$ utxo.balance, pid == h $\\Rightarrow$\n $\\forall$ s $\\in$ tx.sigs, $\\exists$ t $\\in$ supp(tkns),\n isSignedBy(tx, s, t)\n\n $\\llbracket$SpendsCur(pid)$\\rrbracket$(h, tx, utxo) =\n pid == _ $\\Rightarrow$ h $\\in$ supp(utxo.balance)\n $\\wedge$ pid $\\neq$ _ $\\Rightarrow$ pid $\\in$ supp(utxo.balance)\n \\end{lstlisting}\n \\caption{Forging Policy Language}\n \\label{figure:fps-language}\n\\end{figure}\n%\n\\paragraph{Language clauses.}\n%\nThe various clauses of the validator and forging policy language are as described below, with their formal semantics as in Figure~\\ref{figure:fps-language}. In this figure, we use the notation\n$\\texttt{x}\\mapsto \\texttt{y}$ to represent a single key-value pair of a finite map.\nRecall form Rule~\\ref{rule:all-mps-validate} that the arguments passed to the validation\nfunction $\\llbracket \\texttt{s} \\rrbracket$ $\\texttt{h}$ are: the hash of the forging (or output\nlocking) script being validated, the transaction $\\texttt{tx}$ being validated,\nand the ledger outputs which the transaction $\\texttt{tx}$ is spending (we denote\nthese $\\texttt{utxo}$ here).\n%\n\\begin{itemize}\n \\item \\texttt{JustMSig(msig)}\n verifies that the $m$-out-of-$n$ signatures required by $s$ are in the\n set of signatures provided by the transaction. We do not give the\n multi-signature script evaluator details as this is a common concept, and\n assume a procedure \\texttt{checkMultiSig} exists.\n\n \\item \\texttt{SpendsOutput(o)} checks that the transaction spends\n the output referenced by $\\texttt{o}$ in the \\UTXO.\n\n \\item \\texttt{TickAfter(tick1)} checks that the validity interval\n of the current transaction starts after time $\\texttt{tick1}$.\n\n \\item \\texttt{Forges(tkns)} checks that the transaction forges exactly\n $\\texttt{tkns}$ of the asset with the policy ID that is being validated.\n\n \\item \\texttt{Burns(tkns)} checks that the transaction burns exactly\n $\\texttt{tkns}$ of the asset with the policy ID that is being validated.\n\n \\item \\texttt{FreshTokens}\n checks that all tokens of the asset being forged are non-fungible.\n\n This script must check that the names of the tokens in this token bundle\n are generated by hashing some unique data. This data must be unique to both\n the transaction itself and the token within the asset being forged.\n In particular, we can hash a pair of\n %\n \\begin{enumerate}\n \\item some \\emph{output} in the \\UTXO\\ that the\n transaction consumes, and\n \\item the \\emph{index} of the token name in (the\n list representation of) the map of tokens being\n forged (under the specific policy, by this transaction). We denote the\n function that gets the index of a key in a key-value map by $\\texttt{indexof}$.\n \\end{enumerate}\n\n \\item \\texttt{AssetToAddress(addr)}\n checks that all the tokens associated with the policy ID that\n is equal to the hash of the script being run are output\n to an \\UTXO\\ with the address $\\texttt{addr}$. In the case that no $\\texttt{addr}$ value is\n provided (represented by $\\_$), we use the $\\texttt{addr}$ value passed to the evaluator as\n the hash of the policy of the asset being forged.\n\n \\item \\texttt{DoForge}\n checks that this transaction forges tokens in the bundle controlled by the policy ID that is passed\n to the FPS script evaluator (here, again, we make use of the separate passing of\n the FPS script and the policy ID).\n\n \\item \\texttt{SignedByPIDToken(pid)} verifies the hash of every key that has signed the transaction.\n\n \\item \\texttt{SpendsCur(pid)}\n verifies that the transaction is spending assets in the token bundle with policy\n ID $\\texttt{pid}$ (which is specified as part of the \\emph{constructor}, and may be different\n than the policy ID passed to the evaluator).\n\n\\end{itemize}\n", "meta": {"hexsha": "3065c506f892a5ebd37887eff874ed6f3d6568a1", "size": 6661, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "papers/utxoma/mps-language.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/utxoma/mps-language.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/utxoma/mps-language.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": 50.0827067669, "max_line_length": 282, "alphanum_fraction": 0.7224140519, "num_tokens": 1827, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.30074557894124154, "lm_q1q2_score": 0.1550704100677525}} {"text": "\\PassOptionsToPackage{pdfpagelabels=false}{hyperref}\n\\documentclass[fleqn,usenatbib,usedcolumn]{mnras}\n%==============================================================================%\n\\usepackage[british]{babel} % British English hyphenation\n\\usepackage{txfonts} % Good fonts\n% Use vector fonts, so it zooms properly in on-screen viewing software\n% Don't change these lines unless you know what you are doing\n%\\usepackage[T1]{fontenc}\n%\\usepackage{ae,aecompl}\n%%%%% AUTHORS - PLACE YOUR OWN PACKAGES HERE %%%%%\n\\usepackage{graphicx}\t% Including figure files\n\\usepackage{hyperref} % hyperlinks\n\\usepackage{natbib}\n\\usepackage{aastexmacros}\n\\usepackage{tikz}\n\\usepackage[caption=false]{subfig}\n\\usepackage[mediumspace,mediumqspace,Grey,squaren]{SIunits}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%%%%% AUTHORS - PLACE YOUR OWN COMMANDS HERE %%%%%\n\\usetikzlibrary{shapes,arrows,calc,positioning}\n\n\\renewcommand{\\vec}[1]{\\mathbf{#1}}\n% \\newcommand{\\text}{\\mathrm}\n\\newcommand{\\jansky}{\\text{Jy}}\n\\newcommand{\\cheng}[1]{ {\\color{teal}[{\\bf Cheng TODO:~{#1}}]} }\n\\newcommand{\\matthew}[2]{ {\\color{white!20!violet}[{\\bf TODO(#1):~{#2}}]} }\n\\newcommand{\\todo}[1]{ {\\color{red}[{\\bf TODO:~{#1}}]} }\n\n\n\\newcommand{\\underset}[2]{\\mathop{#2}\\limits_{#1}}\n\n\\let\\subsectionautorefname\\sectionautorefname\n\\let\\subsubsectionautorefname\\sectionautorefname\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%%%%%%%%%%%%%%%%%%% TITLE PAGE %%%%%%%%%%%%%%%%%%%\n\n\\title[Supplement: ML for radio X-id]{Supplement to Radio Galaxy Zoo: Machine learning methods for radio source host galaxy cross-identification}\n\n\\author[Alger et al.]{\n M.~J.~Alger$^{1}$,\n J.~K.~Banfield$^{2, 1}$,\n C.~S.~Ong$^{3, 4}$,\n O.~I.~Wong$^{5, 2}$,\n L.~Rudnick$^{6}$,\n R.~P.~Norris$^{7, 8}$, others\n\\\\\n% List of institutions\n$^{1}$Research School of Astronomy and Astrophysics, The Australian National University, Canberra, ACT 2611, Australia\\\\\n$^{2}$ARC Centre of Excellence for All-Sky Astrophysics (CAASTRO)\\\\\n$^{3}$Data61, CSIRO, Canberra, ACT 2601, Australia\\\\\n$^{4}$Research School of Computer Science, The Australian National University, Canberra, ACT 2601, Australia\\\\\n$^{5}$International Centre for Radio Astronomy Research-M468, The University of Western Australia, 35 Stirling Hwy, Crawley, WA 6009, Australia\\\\\n$^{6}$Minnesota Institute for Astrophysics, University of Minnesota, 116 Church St. SE, Minneapolis, MN 55455\\\\\n$^{7}$Western Sydney University, Locked Bag 1797, Penrith South, NSW 1797, Australia\\\\\n$^{8}$CSIRO Astronomy \\& Space Science, PO Box 76, Epping, NSW 1710, Australia\n}\n\n% These dates will be filled out by the publisher\n\\date{Accepted XXX. Received XXX}\n\n% Enter the current year, for the copyright statements etc.\n\\pubyear{2017}\n\n% Don't change these lines\n\\begin{document}\n\\label{firstpage}\n\\pagerange{\\pageref{firstpage}--\\pageref{lastpage}}\n\\maketitle\n\n\n \\section{Classifiers}\\label{sec:classifiers}\n\n We use three different classifiers as our binary classification model:\n logistic regression, convolutional neural networks, and random forests.\n\n \\subsection{Logistic Regression}\n \\label{sec:logistic-regression}\n Logistic regression is a binary classification model. It is linear in the\n feature space and outputs the probability that the input has a positive\n label. The model is \\citep{bishop06ml}:\n\n \\begin{equation}\n f(\\vec x) = \\sigma(\\vec w \\cdot \\vec x + b) \\,\\,\\,\\,,\n \\end{equation}\n where $\\vec w \\in \\mathbb{R}^D$ is a weight vector,\n $b \\in \\mathbb{R}$ is a bias term, $\\vec x \\in \\mathbb{R}^D$ is the\n feature representation of a candidate host, and $\\sigma$ is the\n logistic sigmoid function: \\begin{equation}\n \\sigma(a) = (1 + \\mathrm{exp}(-a))^{-1}\\,\\,\\,\\,.\n \\end{equation}%\n The logistic regression model is fully differentiable, and the weight\n vector $\\vec w$ can therefore be learned using gradient methods.\n\n \\subsection{Convolutional neural networks}\n \\label{sec:convolutional-neural-networks}\n\n Convolutional neural networks (CNN) are a biologically-inspired\n prediction model for prediction with image inputs. The input image is\n convolved with a number of filters to produce output images called\n feature maps. These feature maps can then be convolved again with other\n filters on subsequent layers, producing a network of convolutions. The\n whole network is differentiable with respect to the values of the\n filters and the filters can be learned using gradient methods. The final\n layer of the network is logistic regression, with the convolved outputs\n as input features. For more detail, see \\citet[subsection\n II.A][]{lecun98}. We use \\textsc{Keras} \\citep{chollet15keras} to\n implement our CNN.\n\n \\begin{figure}\n \\includegraphics[width=\\linewidth]{images/cnn_model_graph}\n \\caption{Architecture of our CNN. The concatenate layer flattens the\n output of the previous layer and adds the 10 features derived from\n the candidate host in SWIRE, i.e. the flux ratios, stellarity\n indices, and distance. The dropout layer randomly sets $25\\%$ of its\n inputs to zero during training to prevent overfitting. Diagram based\n on \\url{ https://github.com/dnouri/nolearn}.}\n \\label{fig:cnn}\n \\end{figure}\n\n CNNs have recently produced good results on large image-based datasets\n in astronomy \\citep[e.g.][; Lukic et al. in prep]{dieleman15cnn}. We\n employ only a simple CNN model in this paper as a proof of concept that\n CNNs may be used for class probability prediction on radio images. The\n model architecture we use is shown in \\autoref{fig:cnn}.\n\n \\subsection{Random Forests}\n \\label{sec:random-forests}\n\n Random forests are an ensemble of decision\n trees~\\citep{breiman01random-forest}. It considers multiple subsamples\n of the training set, where each bootstrap subsample is sampled with\n replacement from the training set. For each subsample a decision tree\n classifier is constructed by repeatedly making axis-parallel splits\n based on individual features. In a random forest the split decision is\n taken based on a random subset of features. To classify a new data\n point, the random forest takes the weighted average of all\n classifications produced by each decision tree.\n\n%%%%%%%%%%%%%%%%%%%% REFERENCES %%%%%%%%%%%%%%%%%%\n\\bibliographystyle{mnras}\n\\bibliography{rgz-cdfs-ms}\n\n\n% Don't change these lines\n\\bsp\t% typesetting comment\n\\label{lastpage}\n\\end{document}\n", "meta": {"hexsha": "4a553457fa0daeb25bfd9ab4d5f5ce00bb7ea431", "size": 6637, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "ATLAS-CDFS/rgz-cdfs-supp.tex", "max_stars_repo_name": "chengsoonong/crowdastro-projects", "max_stars_repo_head_hexsha": "a80adf4764d09e003818cbc595f9c7eb3960df7b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ATLAS-CDFS/rgz-cdfs-supp.tex", "max_issues_repo_name": "chengsoonong/crowdastro-projects", "max_issues_repo_head_hexsha": "a80adf4764d09e003818cbc595f9c7eb3960df7b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2016-08-22T00:02:19.000Z", "max_issues_repo_issues_event_max_datetime": "2017-07-17T05:41:28.000Z", "max_forks_repo_path": "ATLAS-CDFS/rgz-cdfs-supp.tex", "max_forks_repo_name": "chengsoonong/crowdastro-projects", "max_forks_repo_head_hexsha": "a80adf4764d09e003818cbc595f9c7eb3960df7b", "max_forks_repo_licenses": ["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.9536423841, "max_line_length": 145, "alphanum_fraction": 0.6873587464, "num_tokens": 1753, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.30735802320985245, "lm_q1q2_score": 0.15487960445706497}} {"text": "\\chapter{Techniques I: Disequality Constraints}\\label{diseqchapter}\n\nIn this chapter we naively translate a Scheme program to miniKanren,\nand observe that the miniKanren relation exhibits undesirable\nbehavior. This behavior is due to our inability to express negation\nin core miniKanren. We improve our miniKanren relation through the use of\ndisequality constraints, which can express a limited form of negation.\n\nThis chapter is organized as follows. In\nsection~\\ref{translaterember} we translate the Scheme function \n\\mbox{\\scheme|rember|} into the miniKanren relation \\mbox{\\scheme|rembero|}.\nIn section~\\ref{remberotrouble} we observe that\n\\mbox{\\scheme|rembero|} produces unexpected answers that do not\ncorrespond to answers produced by \\mbox{\\scheme|rember|}. In\nsection~\\ref{reconsiderrember} we show that the unexpected answers are\ndue to our failure to translate implicit tests in the\n\\mbox{\\scheme|rember|} function. Section~\\ref{diseqsection}\nintroduces disequality constraints, which allow us to express a\nlimited form of negation. In section~\\ref{fixingrembero} we fix our\ndefinition of \\mbox{\\scheme|rembero|} by adding a disequality\nconstraint, thereby eliminating the unexpected answers. Finally in\nsection~\\ref{diseqlimits} we point out several disadvantages of\ndisequality constraints, and discuss when these constraints should be\nused.\n\n\\section{Translating {\\rembersymbol} into miniKanren}\\label{translaterember}\n\nWe begin by naively translating the \\scheme|rember| function into\nminiKanren. \\mbox{\\scheme|rember|} takes two arguments: a symbol \\scheme|x| and a\nlist of symbols \\scheme|ls|, and removes the first occurrence of\n\\scheme|x| from \\scheme|ls|.\n\n\\wspace\n\n\\noindent\\mbox{\\scheme|(rember 'b '(a b c b d)) => |}\\mbox{\\schemeresult|`(a c b d)|}\n\n\\wspace\n\n\\noindent\\mbox{\\scheme|(rember 'd '(a b c)) => |}\\mbox{\\schemeresult|`(a b c)|}\n\n%\\wspace\n\n\\newpage\n\nHere is \\mbox{\\scheme|rember|}\n\n\\schemedisplayspace\n\\begin{schemedisplay}\n(define rember\n (lambda (x ls)\n (cond\n ((null? ls) '())\n ((eq? (car ls) x) (cdr ls))\n (else (cons (car ls) (rember x (cdr ls)))))))\n\\end{schemedisplay}\n\nTo translate \\mbox{\\scheme|rember|} into the miniKanren relation\n\\mbox{\\scheme|rembero|} we add a third argument \\mbox{\\scheme|out|},\nchange \\mbox{\\scheme|cond|} to \\mbox{\\scheme|conde|}, and replace uses\nof \\mbox{\\scheme|null?|}, \\mbox{\\scheme|eq?|}, \\mbox{\\scheme|cons|},\n\\mbox{\\scheme|car|}, and \\mbox{\\scheme|cdr|} with calls to\n\\mbox{\\scheme|==|}. We also unnest the recursive call, using a\ntemporary variable \\mbox{\\scheme|res|} to hold the ``output'' value of\nthe recursive call.\n\n\\schemedisplayspace\n\\begin{schemedisplay}\n(define rembero\n (lambda (x ls out)\n (conde\n ((== '() ls) (== '() out))\n ((exist (a d)\n (== `(,a . ,d) ls)\n (== a x)\n (== d out)))\n ((exist (a d res)\n (== `(,a . ,d) ls)\n (== `(,a . ,res) out)\n (rembero x d res))))))\n\\end{schemedisplay}\n\n\\section{The Trouble with {\\remberosymbol}}\\label{remberotrouble}\n\nFor simple tests, it may seem that \\mbox{\\scheme|rembero|} works as\nexpected, mimicking the behavior of \\mbox{\\scheme|rember|}.\n\n\\wspace\n\n\\noindent\\mbox{\\scheme|(run1 (q) (rembero 'b '(a b c b d) q)) => |} \\mbox{\\schemeresult|`((a c b d))|}\n\n\\wspace\n\n\\noindent\\mbox{\\scheme|(run1 (q) (rembero 'd '(a b c) q)) => |} \\mbox{\\schemeresult|`((a b c))|}\n\n\\wspace\n\n\\noindent However, we notice a problem if we replace the \\mbox{\\scheme|run1|}\nwith \\mbox{\\scheme|run*|}.\n\n\\wspace\n\n\\noindent\\mbox{\\scheme|(run* (q) (rembero 'b '(a b c b d) q)) => |} \\mbox{\\schemeresult|`((a c b d) (a b c d) (a b c b d))|}\n\n\\wspace\n\n\\noindent Now there are multiple answers. The first answer is expected, but in\nthe second answer \\mbox{\\scheme|rembero|} removes the second\noccurrence of \\mbox{\\scheme|`b|} rather than the first occurrence. The\nlast answer is even worse---\\mbox{\\scheme|rembero|} does not remove\neither \\mbox{\\scheme|`b|}, as is evidenced by the \\mbox{\\scheme|run|}\nexpression\n\n\\wspace\n\n\\noindent\\mbox{\\scheme|(run* (q) (rembero 'b '(b) '(b))) => |} \\mbox{\\schemeresult|`(_.0)|}\n\n\\section{Reconsidering {\\rembersymbol}}\\label{reconsiderrember}\n\nWhere did we go wrong? Is our miniKanren translation not faithful to\nthe original Scheme program?\n\nNot quite. The problem is that \\mbox{\\scheme|cond|} tries its clauses\nin order, stopping at the first clause whose test evaluates to a true\nvalue, while \\mbox{\\scheme|conde|} tries every possible clause. But\nisn't there only one \\mbox{\\scheme|cond|} clause that matches any\ngiven values of \\mbox{\\scheme|x|} and \\mbox{\\scheme|ls|}? Actually,\nno.\n\nLet us examine the definition of \\mbox{\\scheme|rember|} once again.\n\n\\schemedisplayspace\n\\begin{schemedisplay}\n(define rember\n (lambda (x ls)\n (cond\n ((null? ls) '())\n ((eq? (car ls) x) (cdr ls))\n (else (cons (car ls) (rember x (cdr ls)))))))\n\\end{schemedisplay}\n\n\\noindent Consider the call \\mbox{\\scheme|(rember 'a '(a b c))|}.\nClearly the \\mbox{\\scheme|null?|} test keeps the first clause from\nreturning an answer, while the \\mbox{\\scheme|eq?|} test allows the\nsecond clause to produce an answer. But the test of the final clause,\nthe ``always-true'' \\mbox{\\scheme|else|} keyword, \nis equivalent to the trivial \\mbox{\\scheme|#t|} test.\n\n\\schemedisplayspace\n\\begin{schemedisplay}\n(define rember\n (lambda (x ls)\n (cond\n ((null? ls) '())\n ((eq? (car ls) x) (cdr ls))\n (#t (cons (car ls) (rember x (cdr ls)))))))\n\\end{schemedisplay}\n\n\\noindent If it were not for the second clause, the third clause would produce\nan answer for the call \\mbox{\\scheme|(rember 'a '(a b c))|}. In fact,\nif we swap the last two clauses\n\n\\schemedisplayspace\n\\begin{schemedisplay}\n(define rember\n (lambda (x ls)\n (cond\n ((null? ls) '())\n (#t (cons (car ls) (rember x (cdr ls))))\n ((eq? (car ls) x) (cdr ls)))))\n\\end{schemedisplay}\n\n\\noindent the call \\mbox{\\scheme|(rember 'a '(a b c))|} returns\n\\mbox{\\scheme|`(a b c)|} rather than \\mbox{\\scheme|`(b c)|}.\n\nWhat does the \\mbox{\\scheme|else|} test really mean in the original\ndefinition of \\scheme|rember|? It means that the tests in all the above\nclauses must evaluate to \\mbox{\\scheme|#f|}. Similar reasoning holds\nfor the \\mbox{\\scheme|eq?|} test of the second clause---the test\nimplies that the \\mbox{\\scheme|null?|} test in the first clause\nreturned \\mbox{\\scheme|#f|}. We can therefore redefine\n\\mbox{\\scheme|rember|} to make the implicit tests explicit.\n\n\\newpage\n\n%\\schemedisplayspace\n\\begin{schemedisplay}\n(define rember\n (lambda (x ls)\n (cond\n ((null? ls) '())\n ((and (not (null? ls)) (eq? (car ls) x))\n (cdr ls))\n ((and (not (null? ls)) (not (eq? (car ls) x)))\n (cons (car ls) (rember x (cdr ls)))))))\n\\end{schemedisplay}\n\n\\mbox{\\scheme|rember|} now produces the same answers no matter how we\nreorder the clauses; the clauses are now \\emph{non-overlapping},\nsince only a single clause can produce an answer for any specific call\nto \\mbox{\\scheme|rember|}\\footnote{Throughout this dissertation we strive to write programs that adhere to the \\emph{non-overlapping principle}, to avoid duplicate or misleading answers. Such programs are similar to the guarded command programs described in \\citet{guardedcommands,disciplineprog}.}.\n\n\\schemedisplayspace\n\\begin{schemedisplay}\n(define rember\n (lambda (x ls)\n (cond\n ((and (not (null? ls)) (not (eq? (car ls) x)))\n (cons (car ls) (rember x (cdr ls))))\n ((and (not (null? ls)) (eq? (car ls) x))\n (cdr ls))\n ((null? ls) '()))))\n\\end{schemedisplay}\n\n\\noindent Even though we have reordered the \\scheme|cond| clauses,\n\\scheme|rember| works as expected.\n\n\\wspace\n\n\\noindent\\mbox{\\scheme|(rember 'a '(a b c)) => |}\\mbox{\\schemeresult|`(b c)|}\n\n\\section{Disequality Constraints}\\label{diseqsection}\n\nNow we can reconsider our definition of \\mbox{\\scheme|rembero|},\nadding the equivalent of the explicit tests to make our\n\\mbox{\\scheme|conde|} clauses non-overlapping\\footnote{More than one\n \\mbox{\\scheme|conde|} clause may succeed if \\mbox{\\scheme|rembero|}\n is passed fresh variables. However, only one clause will succeed if\n the first two arguments to \\mbox{\\scheme|rembero|} are fully\n ground.}.\n\nUnfortunately, we do not have a way to express negation in core\nminiKanren\\footnote{The impure operators \\scheme|conda| and\n \\scheme|condu| from section~\\ref{impureoperatorssection} can be used to express\n ``negation as failure'', as is commonly done in Prolog programs, but\n we eschew this non-declarative approach.}. However, we do not need\nfull negation to express the test \\mbox{\\scheme|(not (null? ls))|},\nsince if \\mbox{\\scheme|ls|} is not null it must be a\npair\\footnote{This assumes, of course, that the second argument to\n \\mbox{\\scheme|rembero|} can be unified with a proper list. Passing\n in \\mbox{\\scheme|5|} as the \\mbox{\\scheme|ls|} argument makes no\n more sense for \\mbox{\\scheme|rembero|} than it does for\n \\mbox{\\scheme|rember|}.}. In fact, we are already expressing the\n\\mbox{\\scheme|(not (null? ls))|} test implicitly, through the\nunification \\mbox{\\scheme|(== `(,a . ,d) ls)|} that appears in the\nlast two \\mbox{\\scheme|conde|} clauses.\n\nThe only remaining test is \\mbox{\\scheme|(not (eq? (car ls) x))|} in\nthe last clause. How might we express that the car of\n\\mbox{\\scheme|ls|} is not \\mbox{\\scheme|x|}? We could attempt to\nunify the car of \\mbox{\\scheme|ls|} with every symbol other than\n\\mbox{\\scheme|x|}. Even if \\mbox{\\scheme|x|} were instantiated, to the\nsymbol \\mbox{\\scheme|`a|} for example, we would have to unify\n\\mbox{\\scheme|x|} with every symbol \\emph{other} than\n\\mbox{\\scheme|`a|}, of which there are infinitely many. Clearly this\nis problematic: enumerating an infinite domain can easily lead to\ndivergent behavior\\footnote{It is possible to enumerate some infinite\n domains using a finite number of cases, through the use of clever\n data representation. For example, using the binary list notation\n from Chapter~\\ref{arithchapter} we can express that a natural number\n \\mbox{\\scheme|x|} is not \\mbox{\\scheme|5|} by unifying\n \\mbox{\\scheme|x|} with the patterns \\mbox{\\scheme|`()|},\n \\mbox{\\scheme|`(1)|}, \\mbox{\\scheme|`(,a 1)|}, \\mbox{\\scheme|`(0 ,a 1)|}, \n \\mbox{\\scheme|`(1 1 1)|}, and \\mbox{\\scheme|`(,a ,b ,c ,d . ,rest)|}. Although this\n approach avoids divergence, it requires us to know the domain and\n representation of \\mbox{\\scheme|x|}. Furthermore, this approach may result in\n duplicate answers even for programs that adhere to the\n non-overlapping principle, which can be a problem even when\n enumerating finite domains.}.\n\nCompare the tests in the second and third \\mbox{\\scheme|rember|} clauses: \\mbox{\\scheme|(eq? (car ls) x)|} and \\mbox{\\scheme|(not (eq? (car ls) x))|}. We use \\mbox{\\scheme|(== a x)|} to express that\nthe car of \\mbox{\\scheme|ls|} (which is \\mbox{\\scheme|a|}) is equal to \\mbox{\\scheme|x|}. What we need is the ability\nto express the \\emph{disequality constraint}\\footnote{As opposed to an \\emph{equality constraint}, such as \\mbox{\\scheme|(== a x)|}. Disequality is also known as \\emph{disunification}.} \\mbox{\\scheme|(=/= a x)|}\\footnote{We may also wish to introduce an operator \\mbox{\\scheme|=/=-no-check|} that performs \\emph{unsound} disunification, to avoid the cost of the occurs check.}, which\nasserts that \\mbox{\\scheme|a|} and \\mbox{\\scheme|x|} are not equal, and can never be made equal\nthrough unification.\n\nBefore we add a disequality constraint to \\mbox{\\scheme|rembero|}, let us examine some\nsimple uses of \\mbox{\\scheme|=/=|}.\nIn the first example, we unify \\mbox{\\scheme|q|} with\n\\mbox{\\scheme|5|}, then specify that \\mbox{\\scheme|q|} can never be\n\\mbox{\\scheme|5|}. As expected, the call to \\mbox{\\scheme|=/=|}\nfails.\n\n\\wspace\n\n\\noindent\\mbox{\\scheme|(run* (q) (== 5 q) (=/= 5 q)) => |} \\mbox{\\schemeresult|`()|}\n\n\\wspace\n\nIf we swap the goals, the program behaves the same.\n\n\\wspace\n\n\\noindent\\mbox{\\scheme|(run* (q) (=/= 5 q) (== 5 q)) => |} \\mbox{\\schemeresult|`()|}\n\n\\wspace\n\n\\mbox{\\scheme|=/=|} can take arbitrary expressions, as shown in the next two examples.\n\n\\wspace\n\n\\noindent\\mbox{\\scheme|(run* (q) (=/= (+ 2 3) 5)) => |} \\mbox{\\schemeresult|`()|}\n\n\\wspace\n\n\\noindent\\mbox{\\scheme|(run* (q) (=/= (* 2 3) 5)) => |} \\mbox{\\schemeresult|`(_.0)|}\n\n\\wspace\n\nIn this \\mbox{\\scheme|run*|} expression we assert that\n\\mbox{\\scheme|q|} can never be \\mbox{\\scheme|5|} or \\mbox{\\scheme|6|}.\nWe express the latter constraint indirectly, by constraining\n\\mbox{\\scheme|x|}.\n\n\\schemedisplayspace\n\\begin{schemedisplay}\n(run* (q)\n (exist (x)\n (=/= 5 q)\n (== x q)\n (=/= 6 x))) =>\n\\end{schemedisplay}\n\\nspace\n\\begin{schemeresponse}\n`((_.0 : (never-equal ((_.0 . 5)) ((_.0 . 6)))))\n\\end{schemeresponse}\n\n\\noindent The answer includes two reified constraints indicating that the output\nvariable (\\mbox{\\scheme|q|}) can never be \\mbox{\\scheme|5|} or \\mbox{\\scheme|6|}.\n\n\\newpage\n\nConsider this \\mbox{\\scheme|run*|} expression.\n\n\\schemedisplayspace\n\\begin{schemedisplay}\n(run* (q)\n (exist (y z)\n (=/= `(,y . ,z) q))) =>\n\\end{schemedisplay}\n\\nspace\n\\begin{schemeresponse}\n`(_.0)\n\\end{schemeresponse}\n\n\\noindent It may seem that the constraint on \\mbox{\\scheme|q|} should\nbe reified. However, this constraint can only be violated if\n\\mbox{\\scheme|q|} is unified with \\mbox{\\scheme|`(,y . ,z)|}. Since\n\\mbox{\\scheme|y|} and \\mbox{\\scheme|z|} are not reified, the\nconstraint is not \\emph{relevant} and is therefore not reified.\n\nTo reify a constraint, we must reify all of the variables involved in the constraint.\n\n\\schemedisplayspace\n\\begin{schemedisplay}\n(run* (q)\n (exist (x y z)\n (=/= `(,y . ,z) x)\n (== `(,x ,y ,z) q))) =>\n\\end{schemedisplay}\n\\nspace\n\\begin{schemeresponse}\n`(((_.0 _.1 _.2) : (never-equal ((_.0 _.1 . _.2)))))\n\\end{schemeresponse}\n\n\\noindent The constraint is easier to interpret if we remember that \n\\mbox{\\scheme|`(never-equal ((_.0 _.1 . _.2)))|} is equivalent to \n\\mbox{\\scheme|`(never-equal ((_.0 . (_.1 . _.2))))|}.\n\nHere is a slightly more complicated example of \\mbox{\\scheme|=/=|}.\n\n\\schemedisplayspace\n\\begin{schemedisplay}\n(run* (q)\n (exist (x y z)\n (== `(,y . ,z) x)\n (=/= '(5 . 6) x)\n (== 5 y)\n (== `(,x ,y ,z) q))) =>\n\\end{schemedisplay}\n\\nspace\n\\begin{schemeresponse}\n`((((5 . _.0) 5 _.0) : (never-equal ((_.0 . 6)))))\n\\end{schemeresponse}\n\nHere is the same program, but with \\mbox{\\scheme|(== 6 y)|} instead of \\mbox{\\scheme|(== 5 y)|}.\n\n\\schemedisplayspace\n\\begin{schemedisplay}\n(run* (q)\n (exist (x y z)\n (== `(,y . ,z) x)\n (=/= '(5 . 6) x)\n (== 6 y)\n (== `(,x ,y ,z) q))) =>\n\\end{schemedisplay}\n\\nspace\n\\begin{schemeresponse}\n`(((6 . _.0) 6 _.0))\n\\end{schemeresponse}\n\n\\noindent Since \\mbox{\\scheme|y|} cannot be \\mbox{\\scheme|5|}, \\mbox{\\scheme|(=/= '(5 . 6) x)|} cannot be violated and is\ntherefore discarded.\n\nWe end this section with a final example, to demonstrate how to interpret more complicated reified constraints.\n\n\\newpage\n\n%\\schemedisplayspace\n\\begin{schemedisplay}\n(run* (q)\n (exist (x y z)\n (=/= 5 x)\n (=/= 6 x)\n (=/= `(,y 1) `(2 ,z))\n (== `(,x ,y ,z) q))) =>\n\\end{schemedisplay}\n\\nspace\n\\begin{schemeresponse}\n`(((_.0 _.1 _.2) : (never-equal ((_.1 . 2) (_.2 . 1)) ((_.0 . 6)) ((_.0 . 5)))))\n\\end{schemeresponse}\n\n\\noindent The constraints \\mbox{\\scheme|`((_.0 . 6))|} and\n\\mbox{\\scheme|`((_.0 . 5))|} are independent of each other, and\nindicate that \\mbox{\\scheme|x|} can never be \\mbox{\\scheme|5|} or\n\\mbox{\\scheme|6|}. However, \\mbox{\\scheme|`((_.1 . 2) (_.2 . 1))|}\nrepresents a \\emph{single} constraint, indicating that\n\\mbox{\\scheme|y|} cannot be \\mbox{\\scheme|2|} if \\mbox{\\scheme|z|} is\n\\mbox{\\scheme|1|}\\footnote{Reifying constraints in a friendly manner\n is non-trivial, as we will see in Chapter~\\ref{diseqimplchapter}.}.\n\n\\section{Fixing {\\remberosymbol}}\\label{fixingrembero}\n\\enlargethispage{2em}\n\n\nNow that we understand \\mbox{\\scheme|=/=|}, and how to interpret reified constraints,\nwe are ready to add the disequality constraint \\mbox{\\scheme|(=/= a x)|} to the last\nclause of \\mbox{\\scheme|rembero|}.\n\n\\schemedisplayspace\n\\begin{schemedisplay}\n(define rembero\n (lambda (x ls out)\n (conde\n ((== '() ls) (== '() out))\n ((exist (a d)\n (== `(,a . ,d) ls)\n (== a x)\n (== d out)))\n ((exist (a d res)\n (== `(,a . ,d) ls)\n (=/= a x)\n (== `(,a . ,res) out)\n (rembero x d res))))))\n\\end{schemedisplay}\n\nIf we re-run the programs from section~\\ref{remberotrouble} we see\nthat \\mbox{\\scheme|rembero|}'s behavior is consistent with that of \\mbox{\\scheme|rember|}.\n\n\\wspace\n\n\\noindent\\mbox{\\scheme|(run* (q) (rembero 'b '(a b c b d) q)) => |} \\mbox{\\schemeresult|`((a c b d))|}\n\n\\wspace\n\n\\noindent\\mbox{\\scheme|(run* (q) (rembero 'b '(b) '(b))) => |} \\mbox{\\schemeresult|`()|}\n\n\\wspace\n\nOf course, \\mbox{\\scheme|rembero|} is more flexible than \\mbox{\\scheme|rember|}.\n\n\\schemedisplayspace\n\\begin{schemedisplay}\n(run* (q)\n (exist (x out)\n (rembero x '(a b c) out)\n (== `(,x ,out) q))) =>\n\\end{schemedisplay}\n\\nspace\n\\begin{schemeresponse}\n`((a (b c))\n (b (a c))\n (c (a b))\n ((_.0 (a b c)) : (never-equal ((_.0 . c)) ((_.0 . b)) ((_.0 . a)))))\n\\end{schemeresponse}\n\nThe final answer indicates that removing a symbol \\mbox{\\scheme|x|}\nfrom the list \\mbox{\\scheme|`(a b c)|} results in the original list,\nprovided that \\mbox{\\scheme|x|} is not \\mbox{\\scheme|`a|},\n\\mbox{\\scheme|`b|}, or \\mbox{\\scheme|`c|}.\n\n\n\\section{Limitations of Disequality Constraints}\\label{diseqlimits}\n\nDisequality constraints add expressive power to core\nminiKanren\\footnote{It seems that disequality constraints were present\n in a very early version of Prolog~\\cite{birthofprolog}, although\n they were apparently removed after several years. Prolog\n II~\\cite{prologtenfigs} reintroduced disequality constraints, which\n are now standard in most Prolog systems.}, allowing us to express a\nlimited form of negation. However, disequality constraints have\nseveral limitations and disadvantages.\n\nFirst, the \\mbox{\\scheme|=/=|} operator can only express that two\nterms are never the same. This is much more limited than the ability\nto express full negation. For example, consider the test\n\\mbox{\\scheme|(and (not (null? ls)) (not (eq? (car ls) x)))|} from the\nversion of \\mbox{\\scheme|rember|} in section~\\ref{reconsiderrember}.\nBy de Morgan's law, this test is logically equivalent to\n\\mbox{\\scheme|(not (or (null? ls) (eq? (car ls) x)))|}. We can use\ndisequality constraints to express the first version of the test, but\nnot the second.\n\nAnswers containing reified disequality constraints can be more\ndifficult to interpret than answers without constraints. Also, it is\nnot always obvious why a constraint was \\emph{not} reified (whether it\nwas not relevant or could not be violated).\n\nDisequality constraints also complicate the implementation of the\nunifier, and especially the reifier. Disequality constraints can also\nbe expensive, since every constraint must be checked after each\nsuccessful unification.\n\nBecause of these disadvantages, it is preferable to use\n\\mbox{\\scheme|==|} rather than \\mbox{\\scheme|=/=|} whenever practical.\nFor example, it is better to express the test \\mbox{\\scheme|(not (null? ls))|} \nas \\mbox{\\scheme|(== `(,a . ,d) ls)|} rather than as\n\\mbox{\\scheme|(=/= '() ls)|}.\n\nStill, disequality constraints add expressive power to core miniKanren, and are\ngenerally preferable to enumerating infinite (or even finite) domains.\n\n\n\n\n\n\n% [membero example]\n\n% [rembero (Scheme -> mk translation)\n% duplicate answers\n\n% simplest example of CLP\n\n% implicit negation in cond lines\n\n% Dijkstra guard\n\n% must be able to swap cond clauses in Scheme\n\n% tagging (for application expressions in lambda calculus, for example)]\n\n% [surpriseo]\n\n% [an arithmetic example---some number is not 5]\n\n% can represent infinitely many terms using a single constraint---useful\n% in avoiding divergence\n\n% only relevant constraints are printed\n\n% pairs\n\n% constraint simplification\n\n% [look at test programs from =/= test cases]\n\n% [all-different]\n", "meta": {"hexsha": "bc860a690050204b8b782a899783e7b4786fa93b", "size": 20081, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "diseq.tex", "max_stars_repo_name": "holtzermann17/dissertation-single-spaced", "max_stars_repo_head_hexsha": "aca0e56a33916596c98709308342d9ccabd4718b", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 50, "max_stars_repo_stars_event_min_datetime": "2015-01-11T21:22:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-10T12:49:11.000Z", "max_issues_repo_path": "diseq.tex", "max_issues_repo_name": "holtzermann17/dissertation-single-spaced", "max_issues_repo_head_hexsha": "aca0e56a33916596c98709308342d9ccabd4718b", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-08-08T18:10:18.000Z", "max_issues_repo_issues_event_max_datetime": "2018-08-09T02:33:25.000Z", "max_forks_repo_path": "diseq.tex", "max_forks_repo_name": "holtzermann17/dissertation-single-spaced", "max_forks_repo_head_hexsha": "aca0e56a33916596c98709308342d9ccabd4718b", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2017-07-29T13:58:01.000Z", "max_forks_repo_forks_event_max_datetime": "2018-09-14T05:01:31.000Z", "avg_line_length": 35.3538732394, "max_line_length": 384, "alphanum_fraction": 0.682336537, "num_tokens": 6453, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4921881357207955, "lm_q2_score": 0.31405055141190724, "lm_q1q2_score": 0.15457195542151447}} {"text": "% !TEX root = ../../main.tex\n\\chapter{Results}\n\\label{ch:results}\n\nThe results after performing the statistical analysis outlined in \\Ch{\\ref{ch:stats}} are presented in this chapter. In~\\Sect{\\ref{sec:results:bkgonly}}, a background-only fit is performed to the data. Signal region $m(\\ell\\nu J)$ distributions, event yields for observed data and all fitted SM backgrounds, and the fitted normalizations for the \\Wjets and \\ttbar backgrounds are presented. In~\\Sect{\\ref{sec:limits}}, model-dependent fits are performed using the profile likelihood ratio to set upper limits on the expected and observed cross sections times branching ratio to $WV$, for the selected benchmark signal models. The systematic uncertainties (\\Ch{\\ref{ch:syst}}) with the largest impact on the signal strength fits are discussed. Event displays showcasing signal region events with the highest invariant mass are presented in \\App{\\ref{ch:eventDisplay}}.\n\n\n%%\n\\section{Background-Only Fit} \n\\label{sec:results:bkgonly}\nNo significant excesses above the SM prediction are observed after the simultaneous binned likelihood fit to the data with the background-only hypothesis (fixed signal strength $\\mu=0$). The post-fit $m(\\ell\\nu J)$ distributions for the VBF selection are shown for the HP and LP regions in~\\Fig{\\ref{fig:pf_hp_vbf}} and~\\Fig{\\ref{fig:pf_lp_vbf}}, respectively. The corresponding distributions for the ggF selection are shown for the HP and LP regions in~\\Fig{\\ref{fig:pf_hp_ggf}} and~\\Fig{\\ref{fig:pf_lp_ggf}}, respectively. Pre-fit signal distributions for $m=2\\,\\TeV$\\, ($m=1.2\\,\\TeV$) are overlaid for the ggF (VBF) selection regions. The total post-fit uncertainty, accounting for both statistical uncertainties and systematic uncertainties, is included. \n\n% Post fit plots\n\\begin{figure}[htb]\n\\centering\n\\subfloat[]{\\includegraphics[width=.48\\textwidth]{figures/Results/new/final_pf/postFit_VBF_HVTWW_1000_SRWW_HP}\\label{fig:pf_hp_vbf:a}}\n\\subfloat[]{\\includegraphics[width=.48\\textwidth]{figures/Results/new/final_pf/postFit_VBF_HVTWZ_1000_SRWZ_HP}\\label{fig:pf_hp_vbf:b}}\\\\\n\\subfloat[]{\\includegraphics[width=.48\\textwidth]{figures/Results/new/final_pf/postFit_VBF_HVTWW_1000_WCR_HP}\\label{fig:pf_hp_vbf:c}}\n\\subfloat[]{\\includegraphics[width=.48\\textwidth]{figures/Results/new/final_pf/postFit_VBF_HVTWW_1000_TCR_HP}\\label{fig:pf_hp_vbf:d}}\n\\caption[Post-fit $m(\\ell\\nu J)$ distribution for high purity, vector boson fusion selection]{The post-fit $m(\\ell\\nu J)$ distributions for the HP VBF selection in \\protect\\subref{fig:pf_hp_vbf:a} the $WW$ SR, \\protect\\subref{fig:pf_hp_vbf:b} the $WZ$ SR, \\protect\\subref{fig:pf_hp_vbf:c} the \\Wjets CR, and \\protect\\subref{fig:pf_hp_vbf:d} the \\ttbar CR. The pre-fit HVT (VBF production) signal prediction for $m=1.2\\,\\TeV$\\, is overlaid. The shaded band denotes the total post-fit statistical and systematic uncertainty on the background. The ratio of the observed data to SM background prediction is shown in the lower panel. All overflow events are included in the final bin. }\n\\label{fig:pf_hp_vbf}\n\\end{figure}\n\n\\begin{figure}[htb]\n\\centering\n\\subfloat[]{\\includegraphics[width=.48\\textwidth]{figures/Results/new/final_pf/postFit_VBF_HVTWW_1000_SRWW_LP}\\label{fig:pf_lp_vbf:a}}\n\\subfloat[]{\\includegraphics[width=.48\\textwidth]{figures/Results/new/final_pf/postFit_VBF_HVTWZ_1000_SRWZ_LP}\\label{fig:pf_lp_vbf:b}}\\\\\n\\subfloat[]{\\includegraphics[width=.48\\textwidth]{figures/Results/new/final_pf/postFit_VBF_HVTWW_1000_WCR_LP}\\label{fig:pf_lp_vbf:c}}\n\\subfloat[]{\\includegraphics[width=.48\\textwidth]{figures/Results/new/final_pf/postFit_VBF_HVTWW_1000_TCR_LP}\\label{fig:pf_lp_vbf:d}}\n\\caption[Post-fit $m(\\ell\\nu J)$ distribution for low purity, vector boson fusion selection]{The post-fit $m(\\ell\\nu J)$ distributions for the LP VBF selection in \\protect\\subref{fig:pf_lp_vbf:a} the $WW$ SR, \\protect\\subref{fig:pf_lp_vbf:b} the $WZ$ SR, \\protect\\subref{fig:pf_lp_vbf:c} the \\Wjets CR, and \\protect\\subref{fig:pf_lp_vbf:d} the \\ttbar CR. The pre-fit HVT (VBF production) signal prediction for $m=1.2\\,\\TeV$\\, is overlaid. The shaded band denotes the total post-fit statistical and systematic uncertainty on the background. The ratio of the observed data to SM background prediction is shown in the lower panel. All overflow events are included in the final bin.}\n\\label{fig:pf_lp_vbf}\n\\end{figure}\n\n\\begin{figure}[htb]\n\\centering\n\\subfloat[]{\\includegraphics[width=.48\\textwidth]{figures/Results/new/final_pf/postFit_HVTWW_2000_SRWW_HP}\\label{fig:pf_hp_ggf:a}}\n\\subfloat[]{\\includegraphics[width=.48\\textwidth]{figures/Results/new/final_pf/postFit_HVTWZ_2000_SRWZ_HP}\\label{fig:pf_hp_ggf:b}}\\\\\n\\subfloat[]{\\includegraphics[width=.48\\textwidth]{figures/Results/new/final_pf/postFit_HVTWW_2000_WCR_HP}\\label{fig:pf_hp_ggf:c}}\n\\subfloat[]{\\includegraphics[width=.48\\textwidth]{figures/Results/new/final_pf/postFit_HVTWW_2000_TCR_HP}\\label{fig:pf_hp_ggf:d}}\n\\caption[Post-fit $m(\\ell\\nu J)$ distribution for high purity, gluon-gluon fusion selection]{The post-fit $m(\\ell\\nu J)$ distributions for the HP ggF selection in \\protect\\subref{fig:pf_hp_ggf:a} the $WW$ SR, \\protect\\subref{fig:pf_hp_ggf:b} the $WZ$ SR, \\protect\\subref{fig:pf_hp_ggf:c} the \\Wjets CR, and \\protect\\subref{fig:pf_hp_ggf:d} the \\ttbar CR. The pre-fit HVT (qqF production) signal prediction for $m=2.0\\,\\TeV$\\, is overlaid. The shaded band denotes the total post-fit statistical and systematic uncertainty on the background. The ratio of the observed data to SM background prediction is shown in the lower panel. All overflow events are included in the final bin.}\n\\label{fig:pf_hp_ggf}\n\\end{figure}\n\n\\begin{figure}[htb]\n\\centering\n\\subfloat[]{\\includegraphics[width=.48\\textwidth]{figures/Results/new/final_pf/postFit_HVTWW_2000_SRWW_LP}\\label{fig:pf_lp_ggf:a}}\n\\subfloat[]{\\includegraphics[width=.48\\textwidth]{figures/Results/new/final_pf/postFit_HVTWZ_2000_SRWZ_LP}\\label{fig:pf_lp_ggf:b}}\\\\\n\\subfloat[]{\\includegraphics[width=.48\\textwidth]{figures/Results/new/final_pf/postFit_HVTWW_2000_WCR_LP}\\label{fig:pf_lp_ggf:c}}\n\\subfloat[]{\\includegraphics[width=.48\\textwidth]{figures/Results/new/final_pf/postFit_HVTWW_2000_TCR_LP}\\label{fig:pf_lp_ggf:d}}\n\\caption[Post-fit $m(\\ell\\nu J)$ distribution for low purity, gluon-gluon fusion selection]{The post-fit $m(\\ell\\nu J)$ distributions for the LP ggF selection in \\protect\\subref{fig:pf_lp_ggf:a} the $WW$ SR, \\protect\\subref{fig:pf_lp_ggf:b} the $WZ$ SR, \\protect\\subref{fig:pf_lp_ggf:c} the \\Wjets CR, and \\protect\\subref{fig:pf_lp_ggf:d} the \\ttbar CR. The pre-fit HVT (qqF production) signal prediction for $m=2.0\\,\\TeV$\\, is overlaid. The shaded band denotes the total post-fit statistical and systematic uncertainty on the background. The ratio of the observed data to SM background prediction is shown in the lower panel. All overflow events are included in the final bin.}\n\\label{fig:pf_lp_ggf}\n\\end{figure}\n\n\\clearpage\nAcross all SRs and CRs, the fitted background distributions agree well with the observed data distributions, within the total estimated uncertainty. The shape of the $m(\\ell\\nu J)$ distribution is modeled well, with no apparent trends in the ratio plots in the lower panels. \n%Several bins show small fluctuations outside the estimated uncertainty bands; however, these fluctuations are mostly accompanied by nearby fluctuations in the opposite direction. \nThe strong agreement in the CRs, where no signal leak is expected, lends confidence to the estimation and modeling of the two principal backgrounds, \\Wjets and \\ttbar. \n\n\nThe \\Wjets and \\ttbar normalization factors, defined as the ratio of the number of simulated events after the fit to the number of simulated events before the fit, are shown in~\\Tab{\\ref{tab:bkg_norms}}. The values were constrained by the simultaneous fit to the SRs and dedicated CRs, but allowed to float. Fitted normalization factors close to unity indicate accurate modeling of the cross sections of the respective background processes. All normalization factors are consistent with unity, within approximately one standard deviation of the measured value. The uncertainty on the normalization factor includes statistical and systematic uncertainties.\n\nFor each of the four fits, the event yields for the observed data and the post-fit simulated SM backgrounds are calculated for the HP SR and CRs, and the LP SR and CRs. In~\\Tab{\\ref{tab:yields_VBFWW}}, the event yields are shown for the $WW$ and $WZ$ channel fits, with VBF selection. In~\\Tab{\\ref{tab:yields_WW}}, the event yields are shown for the $WW$ and $WZ$ channel fits, with ggF selection. The numbers of observed data events are listed without uncertainty. The SM background event yields include statistical and systematic uncertainties. Event yields for each individual background process, and the total background prediction, are included. Correlations between the SM backgrounds are taken into account; therefore, the quoted uncertainty for the total background prediction does not necessarily correspond to the sum in quadrature of each individual background uncertainty. For each region, the observed number of data events matches the total SM prediction within the estimated uncertainty. \n\n% Normalization factors\n\\begin{table}[tb]\n\\centering\n\\caption[Normalization factors for the \\Wjets and $\\ttbar$ backgrounds]{Normalization factors for the \\Wjets and \\ttbar backgrounds for the $WW$ and $WZ$ channels, separated into ggF and VBF selections. The normalization factor is the ratio between the number of fitted events from simulation to the number of predicted events from simulation. The uncertainties include both statistical and systematic uncertainties.}\n\\begin{tabular}{r|cc|cc}\n\\hline\\hline\nBkg. & \\multicolumn{2}{c|}{$WW$ Selection} & \\multicolumn{2}{c}{$WZ$ Selection}\\\\\\cline{2-5}\nNorm. & ggF & VBF & ggF & VBF \\\\\\hline\n\\Wjets&$0.95\\pm0.06$&$0.89\\pm0.18$&$0.97\\pm0.06$&$0.84\\pm0.16$\\\\\\hline\n\\ttbar&$1.03\\pm0.06$&$1.21\\pm0.18$&$1.00\\pm0.06$&$1.10\\pm0.17$\\\\\\hline\\hline\n\\end{tabular}\n\\label{tab:bkg_norms}\n\\end{table}\n\n% Yields\n\\input{tex/data/yields/VBFWW_yields.tex}\n%\\input{figures/Results/new/VBFWZ_yields.tex}\n\\input{tex/data/yields/WW_yields.tex}\n%\\input{figures/Results/new/WZ_yields.tex}\n\n\n%%\n\\clearpage\n\\section{Expected and Observed Upper Limits} \n\\label{sec:limits}\n\nWith no significant excesses above the SM background prediction observed, the fit is performed again with the signal plus background hypothesis (signal with strength $\\mu$ not fixed at zero). In~\\Tab{\\ref{tab:NPranks}}, the top five systematic uncertainties after the fit are listed. The dominant systematic uncertainties for the ggF (VBF) selection are evaluated for the fit performed with the 2\\,\\TeV\\, (1.2\\,\\TeV) signal mass hypothesis, where the search has a high sensitivity. Additionally, the contributions to the total uncertainty from data statistics and total systematic uncertainties are provided. The uncertainty from data statistics is estimated using a conditional fit, with all the NPs fixed to their best-fit values, $\\hat{\\theta}$.\n%, while the total uncertainty on the signal strength, $\\Delta\\mu_{\\rm tot}$, is estimated from the unconstrained fit where all NPs are floated. \n%The uncertainties listed for each NP, $\\Delta\\hat{\\mu}$, represent the uncertainty on the best-fit signal strength when all the NPs are floated, except the NP in question which is fixed to it's best-fit value.\n%, subtracted in quadrature from the total uncertainty: $\\Delta\\mu_{NP}=\\sqrt{(\\Delta\\mu_{\\rm tot})^2-(\\Delta\\mu_{\\rm tot}^{NP {\\rm\\, fixed}})}$. \nThe impact on signal strength is calculated by fixing only the selected NP at its best-fit value, $\\hat{\\theta}$, and then performing the fit again.\n%, varying the NP by its post-fit uncertainty, $\\pm\\sigma_{\\hat{\\theta}}$. \nThe change in the signal strength from its best-fit value is denoted $\\Delta\\hat{\\mu}$, and indicates how sensitive the signal strength is to the specified NP.\n\nData statistics are a dominant source of uncertainty in the high mass region, while in the lower mass region, systematic uncertainties related to large-R jet kinematics dominate. Most of the leading systematic uncertainties are due to modeling of the \\Wjets and \\ttbar backgrounds. The relatively conservative uncertainty placed on the SM diboson cross section increases its impact on the signal strength uncertainty. \nThe systematic uncertainties related to the large-R jet mass resolution and $D_2^{\\beta=1}$ resolution also have significant contributions. As discussed in~\\Sect{\\ref{ch:syst:largerjets}}, both of these systematic uncertainties have a conservative estimation. \n%For the VBF selection, the \\ttbar background comprises a larger percentage of the total SM background with respect to the ggF selection. Consequently, the sensitivity of the signal strength to $b$-tagging increases in this region.\n\n% Systematic uncertainty impact\n\\begin{table}[tb]\n\\centering\n\\caption[Leading systematic uncertainties after the combined fit]{Relative change in signal strength ($\\Delta \\hat{\\mu}$) with respect to the best-fit value after the fit to data. The five dominant uncertainty sources are presented for the ggF and VBF selections, along with the effect of the data statistical uncertainties. These are evaluated from the 2\\,\\TeV\\, (1.2\\,\\TeV) mass point for the ggF (VBF) selection. To evaluate the impact on $\\mu$, the production cross section is assumed the be the expected upper limit at the mass point.}\n\\vspace{7pt}\n\\label{tab:NPranks}\n\\resizebox{\\textwidth}{!}{%\n\\begin{tabular}{cc|cc}\n\\hline\n\\hline\n %\\multicolumn{2}{c|}{ggF Selection (Fractional uncertainties)} & \\multicolumn{2}{c}{VBF Selection (Fractional uncertainties)} \\\\\n%\\hline\n%Source & $\\Delta \\mu_{\\rm NP} / \\Delta \\mu_{\\rm total}$ (\\%) & Source & $\\Delta \\mu_{\\rm NP} / \\Delta \\mu_{\\rm total}$ (\\%) \\\\\n%& $m(WZ) =$ 2000 \\GeV& & $m(WW) =$ 1200 \\GeV \\\\\n%\\hline\n%Simulation statistics & 28 & Simulation statistics & 34 \\\\\n%$W$+jets modeling \\textsc{MadGraph}& 20 & \\Wjets PDF & 12 \\\\\n%$W$+jets normalization & 13 & \\Wjets $\\alpha_s$ & 9 \\\\\n%SM diboson normalization & 11 & \\Wjets normalization & 9 \\\\\n%$W$+jets modeling scale & 8 & Top modeling radiation & 7 \\\\\n%Top modeling \\textsc{MC@NLO} & 8 & $b$-tagging & 7 \\\\\n%\\hline\n%Total systematic uncertainties & 41 & Total systematic uncertainties & 45 \\\\\n%Data statistics & 91 & Data statistics & 89 \\\\\n%\\hline\\hline\n %\\multicolumn{4}{c}{}\\\\\n %\\multicolumn{4}{c}{}\\\\\n%\\hline\\hline\n \\multicolumn{2}{c|}{ggF Selection (Impact on $\\mu$)} & \\multicolumn{2}{c}{VBF Selection (Impact on $\\mu$)} \\\\\\hline\n%Source & $\\Delta \\mu_{\\rm NP} / \\mu$ (\\%) & Source & $\\Delta \\mu_{\\rm NP} / \\mu$ (\\%) \\\\\nSource & $\\Delta \\hat{\\mu} / \\mu$ (\\%) & Source & $\\Delta \\hat{\\mu} / \\mu$ (\\%) \\\\\n& $m(WZ) =$ 2000 \\GeV& & $m(WW) =$ 1200 \\GeV \\\\\n\\hline\n$W$+jets modeling \\textsc{MadGraph} & 8 & Large-$R$ jets mass resolution & 5 \\\\\n$W$+jets modeling scale & 5 & \\Wjets PDF & 5 \\\\\nSM diboson normalization & 4 & Top modeling \\textsc{Herwig} & 5 \\\\\nLarge-$R$ jets mass resolution & 4 & $W$+jets normalization & 5 \\\\\nLarge-$R$ jets D$_{2}$ resolution & 4 & Top modeling radiation & 4 \\\\\n\\hline\nTotal systematic uncertainties & 20 & Total systematic uncertainties & 24 \\\\\nData statistics & 50 & Data statistics & 52 \\\\\n\\hline \\hline\n\\end{tabular}\n}\n\\end{table}\n\n\nFor each simulated mass point of the selected benchmark signal models, the test statistic $\\tilde{q}_{\\mu}$, based on the profile log likelihood ratio, is used to set upper limits on the production cross section times branching ratio to $WV$. The $CL_s$ method is used to determine the 95\\,\\% CL upper limits. The expected upper limit corresponds to the value of $\\mu$ such that $\\tilde{q}_{\\mu}$ is the median of the background-only hypothesis (i.e. evaluated from the distribution, $f(\\tilde{q}_{\\mu}|\\mu=0)$, of the test statistic), and produces a $p$-value at the given threshold (i.e $0.05$ for 95\\,\\% CL) for the signal plus background hypothesis (i.e. evaluated from the distribution, $f(\\tilde{q}_{\\mu}|\\mu)$, of the test statistic). This is evaluated with the so-called ``Asimov'' dataset\\footnote{\n\tThe Asimov dataset, or ``representative'' dataset, is determined by suppressing all statistical fluctuations, and setting all observed values to their expected values, and all NPs to their nominal values. \n} in the asymptotic limit, and with pseudo-experiments for signal masses above $1.6\\,\\TeV$\\,($1.0\\,\\TeV$) for fits with ggF (VBF) selection. Due to statistical fluctuations in data, the measured upper limit may not correspond to the median expected value, even if the true signal strength is zero. Thus, uncertainty bands corresponding to $\\pm 1\\sigma$ and $\\pm 2\\sigma$ for the expected upper limits are estimated and overlaid. \n\nThe expected and observed upper limits on the cross section times branching ratio for the RS $G^*\\ra WW$ benchmark signal model are shown in~\\Fig{\\ref{fig:lim_RSGWW}}, for $k/\\overline{M}_{\\rm Pl}=1.0$ and $k/\\overline{M}_{\\rm Pl}=0.5$. The theoretical cross sections are overlaid. In~\\Fig{\\ref{fig:lim_HVT}}, the expected and observed upper limits on the cross section times branching ratio are shown for the HVT $W'\\ra WZ$ and HVT $Z'\\ra WW$ signal models, with the ggF selection. As discussed in~\\Sect{\\ref{ch:anstrat:sm}}, the HVT signal samples are generated in the NWA, thus model-A ($g_v=1$) samples are used for the interpretation of both model-A and model-B ($g_v=3$). The theoretical cross sections for both model-A and model-B are overlaid. \n\n\nFor VBF and scalar signal models, no theoretical cross sections are provided; thus, only the expected and observed upper limits on the production cross section times branching ratio to $WV$ are presented. In~\\Fig{\\ref{fig:lim_VBF_HVT}}, the upper limits are shown for the HVT $W'jj\\ra WZjj$ and HVT $Z'jj\\ra WWjj$ signal models, with the VBF selection. The VBF topology is denoted by the two VBF-tagged small-R jets, ``jj''. Finally, in~\\Fig{\\ref{fig:lim_scalar}}, the upper limits are shown for the heavy neutral Higgs model, for both the ggF and VBF selections.\n\n\n% Upper limits\n\\clearpage\n\\begin{figure}[H]\n\\centering\n\\subfloat[]{\\includegraphics[width=0.8\\textwidth]{figures/Results/new/final_lim/RSGWW_LPHP_ggF}\\label{fig:lim_RSGWW:a}}\\\\\n\\subfloat[]{\\includegraphics[width=0.8\\textwidth]{figures/Results/new/final_lim/RSGWW_ReWeight_LPHP_ggF}\\label{fig:lim_RSGWW:b}}\\\\\n\\caption[Observed and expected upper limits for RS $G^*$ model (gluon-gluon fusion selection)]{The observed and expected 95\\,\\% CL upper limits on cross section times branching ratio for RS $G* \\rightarrow WW$ in the combined LP and HP signal regions, for the ggF selection, are shown for \\protect\\subref{fig:lim_RSGWW:a} $k/\\overline{M}_{\\rm Pl}=1.0$ and \\protect\\subref{fig:lim_RSGWW:b} $k/\\overline{M}_{\\rm Pl}=0.5$. The theoretical cross sections for the signal models are overlaid. Limits are calculated with an asymptotic approximation for mass points below 1.6\\,\\TeV, and with pseudo-experiments above 1.6\\,\\TeV.}\n\\label{fig:lim_RSGWW}\n\\end{figure}\n\\begin{figure}[H]\n\\centering\n\\subfloat[]{\\includegraphics[width=0.8\\textwidth]{figures/Results/new/final_lim/HVTWW_LPHP_ggF}\\label{fig:lim_HVT:a}}\\\\\n\\subfloat[]{\\includegraphics[width=0.8\\textwidth]{figures/Results/new/final_lim/HVTWZ_LPHP_ggF}\\label{fig:lim_HVT:b}}\\\\\n\\caption[Observed and expected upper limits for HVT $Z'$ and $W'$ model (gluon-gluon fusion selection)]{The observed and expected 95\\,\\% CL upper limits on cross section times branching ratio for \\protect\\subref{fig:lim_HVT:a} HVT $Z' \\rightarrow WW$ and \\protect\\subref{fig:lim_HVT:b} HVT $W' \\rightarrow WZ$, in the combined LP and HP signal regions, for the ggF selection. The theoretical cross sections for model-A ($g_V=1$) and model-B ($g_V=3$) are overlaid. Limits are calculated with an asymptotic approximation for mass points below 1.6\\,\\TeV, and with pseudo-experiments above 1.6\\,\\TeV.}\n\\label{fig:lim_HVT}\n\\end{figure}\n\\begin{figure}[H]\n\\centering\n\\subfloat[]{\\includegraphics[width=0.8\\textwidth]{figures/Results/new/final_lim/VBF_HVTWW_LPHP_VBF}\\label{fig:lim_VBF_HVT:a}}\\\\\n\\subfloat[]{\\includegraphics[width=0.8\\textwidth]{figures/Results/new/final_lim/VBF_HVTWZ_LPHP_VBF}\\label{fig:lim_VBF_HVT:b}}\\\\\n\\caption[Observed and expected upper limits for HVT $Z'$ and $W'$ model (vector boson fusion selection)]{The observed and expected 95\\,\\% CL upper limits on cross section times branching ratio for \\protect\\subref{fig:lim_VBF_HVT:a} HVT $Z' jj\\rightarrow WWjj$ and \\protect\\subref{fig:lim_VBF_HVT:b} HVT $W'jj \\rightarrow WZjj$, in the combined LP and HP signal regions, for the VBF selection. The mass region greater than 1.5\\,\\TeV\\, is covered by two bins in the final discriminant, while the observed limit markers represent the tested signal points. Limits are calculated with an asymptotic approximation for mass points below 1.0\\,\\TeV, and with pseudo-experiments above 1.0\\,\\TeV.}\n\\label{fig:lim_VBF_HVT}\n\\end{figure}\n\\begin{figure}[H]\n\\centering\n\\subfloat[]{\\includegraphics[width=0.8\\textwidth]{figures/Results/new/final_lim/ggHWWNWA_LPHP_ggF}\\label{fig:lim_scalar:a}}\\\\\n\\subfloat[]{\\includegraphics[width=0.8\\textwidth]{figures/Results/new/final_lim/VBFWWNWA_LPHP_VBF}\\label{fig:lim_scalar:b}}\\\\\n\\caption[Observed and expected upper limits for narrow, heavy Higgs model (gluon-gluon fusion and vector boson fusion selection)]{The observed and expected 95\\,\\% CL upper limits on cross section times branching ratio for a neutral heavy scalar (NWA) in the combined LP and HP signal regions, for the \\protect\\subref{fig:lim_scalar:a} ggF selection and \\protect\\subref{fig:lim_VBF_HVT:b} VBF selection. Signal samples generated with ggF (VBF) production are used for the ggF selection (VBF selection). The mass region greater than 1.5\\,\\TeV\\, is covered by two bins in the final discriminant, while the observed limit markers represent the tested signal points. For the ggF (VBF) selection, limits are calculated with an asymptotic approximation for mass points below $1.6\\,\\TeV$\\, ($1.0\\,\\TeV$), and with pseudo-experiments above $1.6\\,\\TeV$\\,($1.0\\,\\TeV$).}\n\\label{fig:lim_scalar}\n\\end{figure}\n\nThe largest discrepancy between the expected and observed upper limits occur for signal models with VBF production, for masses between approximately $1.5-2.0\\,\\TeV$. The local $p$-values for the background-only hypothesis are shown in~\\Fig{\\ref{fig:p0}}, for the tested HVT $W'$ and $Z'$ signal models with VBF production. For the $Z'$ model, the maximum local significance, which does not take into account the look-elsewhere effect, is approximately $2.6\\sigma$ for the fit at $m(W')=1.7\\,\\TeV$. In the post-fit plot for the HP SR with VBF selection (\\Fig{\\ref{fig:pf_hp_vbf}}), there are three events observed in the bin at 1.7\\,\\TeV, with less than one expected in the $WW$ channel. In the $WZ$ channel (which has a large overlap), three events are observed in the bin at 1.7\\,\\TeV\\, as well, but the background expectation is slightly higher at $\\sim1.5$ events. With only two bins covering the region $m(\\ell\\nu J)>1.5\\,\\TeV$, the larger than expected upper limits for tested mass points in this region are mostly due to the entries in this single bin.\n\n\n\\begin{figure}[H]\n\\centering\n\\subfloat[]{\\includegraphics[width=0.49\\textwidth]{figures/Results/new/final_lim/VVM_p0_VBF_HVTWW_VBF}\\label{fig:p0:a}}\n\\subfloat[]{\\includegraphics[width=0.49\\textwidth]{figures/Results/new/final_lim/VVM_p0_VBF_HVTWZ_VBF}\\label{fig:p0:b}}\n\\caption[Local $p$-value for HVT signal (vector boson fusion selection)]{Local $p$-value for the tested \\protect\\subref{fig:p0:a} HVT $W'$ and \\protect\\subref{fig:p0:b} HVT $Z'$ signal models. The mass region greater than 1.5\\,\\TeV\\, is covered by two bins in the final discriminant. }\n\\label{fig:p0}\n\\end{figure}\n\n%Excluded Masses\n%\\afterpage{\\clearpage}\n\\section{Comparison with Previous Results}\n\nSignal masses for which the theoretical cross section is larger than the observed cross section can be excluded at 95\\,\\% CL. The expected and observed excluded masses are shown in~\\Tab{\\ref{tab:excluded}}. The most recent CMS result~\\cite{CMS_diboson_run2} included up to $2.7\\,\\ifb$\\,of $pp$ data with center-of-mass energy $\\sqrt{s}=13\\,\\TeV$, and excluded $W'$ and $Z'$ resonance masses below $2.3\\,\\TeV$\\,($2.4\\,\\TeV$) for HVT model-A (model-B). The most recent ATLAS result~\\cite{diboson_comb_2016} included $3.2\\,\\ifb$\\, of $pp$ data with center-of-mass energy $\\sqrt{s}=13\\,\\TeV$, and excluded $W'$ and $Z'$ resonance masses below $2.35\\,\\TeV$\\,($2.6\\,\\TeV$) for HVT model-A (model-B). This thesis extends the excluded mass range from the ATLAS result by $450\\,\\GeV$\\,($390\\,\\GeV$) for $W'$ resonances and by $380\\,\\GeV$\\,($400\\,\\GeV$) for $Z'$ resonances in model-A (model-B).\n\nThe most recent ATLAS result excluded bulk RS graviton masses below $1.1\\,\\TeV$ for $k/\\overline{M}_{\\rm Pl}=1.0$, while this thesis extends the excluded mass range by $650\\,\\GeV$. Upper limits on production cross section times branching ratio to $VV=WW/ZZ$\\footnote{\n\t For heavy scalar models (NWA) and bulk RS $G^{*}$ models, the most recent results present upper limits on the cross section times branching ratio to $VV=WW/ZZ$. For comparison, the ratio of the $WW:ZZ$ decay is approximately $2:1$. Thus, upper limits for the $VV$ combined channel are approximately 1.5 times the upper limits for $WW$ channel presented here. \n} for a bulk RS $G^{*}$ with $k/\\overline{M}_{\\rm Pl}=0.5$ were set by CMS ranging from $1.2\\,$pb ($600\\,\\GeV$) to $3\\,$fb ($4\\,\\TeV$). This thesis improves upon those results and sets upper limits on cross section times branching ratio to $WW$ ranging from $0.5\\,$pb (500\\,\\GeV) to $0.6\\,$fb (5\\,\\TeV), and presents the first excluded mass range for a bulk RS graviton with $k/\\overline{M}_{\\rm Pl}=0.5$. \n\nATLAS set upper limits on production cross section times branching ratio to $VV=WW/ZZ$ for a narrow scalar resonance ranging from $1\\,$pb at $500\\,\\GeV$\\,to $6\\,$fb at $3\\,\\TeV$~\\cite{diboson_comb_2016}. This thesis improves upon those results and sets upper limits on production cross section times branching ratio to $WW$ for a narrow scalar resonance ranging from $0.2\\,$pb at $500\\,\\GeV$\\,(model with VBF production) to $1.8\\,$fb at $3\\,\\TeV$\\,(model with ggF production). Finally, the first upper limits on production cross section times branching ratio to $WV$ are set for HVT $W'$ and $Z'$ resonances with VBF production.\n%\n% Excluded Masses\n\\begin{table}[htb]\n\\centering\n\\begin{tabular}{l|c|c}\n\\hline\\hline\n\\textbf{Signal Model}\\quad\\quad\\quad\\quad\\,&\\multicolumn{2}{c}{\\textbf{Excluded Masses at 95\\,\\% CL}}\\\\\\hline%\\cline{2-3}\n$WZ$ Selection&Expected [\\GeV]&Observed [\\GeV]\\\\\\hline\n%&&\\\\\n\\rule{0pt}{2.5ex}\\,\\,\\,HVT $W'$&&\\\\\n\\,\\hfill Model A ($g_v=1$)&$<2880$&$<2800$\\\\\n\\,\\hfill Model B ($g_v=3$)&$<3220$&$<2990$\\\\\\hline\n\\multicolumn{3}{c}{\\,}\\\\\\hline\n$WW$ Selection\\quad\\quad\\quad\\quad\\,&Expected [\\GeV]&Observed [\\GeV]\\\\\\hline\n\\rule{0pt}{2.5ex}\\,\\,\\,HVT $Z'$&&\\\\\n\\,\\hfill Model A ($g_v=1$)&$<2830$&$<2730$\\\\\n\\,\\hfill Model B ($g_v=3$)&$<3170$&$<3000$\\\\\n\\rule{0pt}{2.5ex}\\,\\,\\,RS $G^*$&&\\\\\n\\,\\hfill $k/\\overline{M}_{\\rm Pl}=1.0$&$<1740$&$<1750$\\\\\n\\,\\hfill $k/\\overline{M}_{\\rm Pl}=0.5$&$<1250$&$<980$ and $1020-1350$\\\\\n\\hline\\hline\n\\end{tabular}\n\\caption[Observed and expected excluded masses at 95\\,\\% confidence level]{Observed and expected excluded masses at 95\\,\\% CL for HVT $W'$, HVT $Z'$, and RS $G^*$ signal models.}\n\\label{tab:excluded}\n\\end{table}\n\n\n\\clearpage\n\n\n", "meta": {"hexsha": "4c517e3f0017698609538f151fa9ef8ba8bdd073", "size": 27802, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "tex/data/results.tex", "max_stars_repo_name": "rynecarbone/Thesis_lvJ", "max_stars_repo_head_hexsha": "46ba8b142e945d5f3103a364630f661da3405479", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2017-09-29T22:35:55.000Z", "max_stars_repo_stars_event_max_datetime": "2017-09-30T22:25:37.000Z", "max_issues_repo_path": "tex/data/results.tex", "max_issues_repo_name": "rynecarbone/Thesis_lvJ", "max_issues_repo_head_hexsha": "46ba8b142e945d5f3103a364630f661da3405479", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tex/data/results.tex", "max_forks_repo_name": "rynecarbone/Thesis_lvJ", "max_forks_repo_head_hexsha": "46ba8b142e945d5f3103a364630f661da3405479", "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": 114.8842975207, "max_line_length": 1059, "alphanum_fraction": 0.7458815913, "num_tokens": 8064, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.26894141551050293, "lm_q1q2_score": 0.154285882948089}} {"text": " \n\\subsection{One-Dimensional Discriminants}\n\nThis section contains overlayed plots of the one-dimensional (1D) $s$-channel\nand $t$-channel discriminants evaluated on signal and background events. The events in\nthe plots come from the combination of the eight analysis channels \\{$e$,$\\mu$ $\\oplus$ 1,2 tags $\\oplus$ 2,3 jets \\}. Figures~\\ref{disc_wbb} and \\ref{disc_wjets} show good\ndiscrimination between signal and $W$+jets and multijets backgrounds.\nHowever, the discrimination is poorer between signal and $\\dilepton$\nand $\\lepjets$ events as shown in Fig.~\\ref{disc_ttbar}. The lack of\ndiscrimination power for $\\ttbar$ events is due to the fact that the analysis does not yet include a $\\ttbar$\nprobability density function in the definition of the discriminant\\footnote{The $\\ttbar$ matrix element takes much longer to integrate because\nthere are six partons in the final state while there are four in the\nsingle top and $W$+jets matrix elements. Adding a $\\ttbar$ matrix\nelement is envisioned as a future improvement for this analysis.}.\n\n\\begin{figure}[!h!tbp]\n\\includegraphics[width=0.49\\textwidth]\n{eps/MatrixElement/performance/tb_Discriminant__schannel_wbb}\n\\includegraphics[width=0.49\\textwidth]\n{eps/MatrixElement/performance/tb_Efficiency__schannel_wbb}\n\\includegraphics[width=0.49\\textwidth]\n{eps/MatrixElement/performance/tb_Discriminant__schannel_wcc}\n\\includegraphics[width=0.49\\textwidth]\n{eps/MatrixElement/performance/tb_Efficiency__schannel_wcc}\n\\includegraphics[width=0.49\\textwidth]\n{eps/MatrixElement/performance/tq_Discriminant__tchannel_wbb}\n\\includegraphics[width=0.49\\textwidth]\n{eps/MatrixElement/performance/tq_Efficiency__tchannel_wbb}\n\\includegraphics[width=0.49\\textwidth]\n{eps/MatrixElement/performance/tq_Discriminant__tchannel_wcc}\n\\includegraphics[width=0.49\\textwidth]\n{eps/MatrixElement/performance/tq_Efficiency__tchannel_wcc}\n\\caption{Discriminant plots and efficiency curves for:\nfirst row, $tb$ vs. $Wbb$, second row, $tb$ vs. $Wcc$, third row, $tq$\nvs. $Wbb$, and fourth row, $tq$ vs. $Wcc$. The numbers in the\nefficiency curves (right column) represent the fraction of signal or\nbackground the remains after a discriminant cut of 0.8.}\n\\label{disc_wbb}\n\\end{figure}\n\n\\begin{figure}[!h!tbp]\n\\includegraphics[width=0.49\\textwidth]\n{eps/MatrixElement/performance/tb_Discriminant__schannel_wjj}\n\\includegraphics[width=0.49\\textwidth]\n{eps/MatrixElement/performance/tb_Efficiency__schannel_wjj}\n\\includegraphics[width=0.49\\textwidth]\n{eps/MatrixElement/performance/tb_Discriminant__schannel_qcd}\n\\includegraphics[width=0.49\\textwidth]\n{eps/MatrixElement/performance/tb_Efficiency__schannel_qcd}\n\\includegraphics[width=0.49\\textwidth]\n{eps/MatrixElement/performance/tq_Discriminant__tchannel_wjj}\n\\includegraphics[width=0.49\\textwidth]\n{eps/MatrixElement/performance/tq_Efficiency__tchannel_wjj}\n\\includegraphics[width=0.49\\textwidth]\n{eps/MatrixElement/performance/tq_Discriminant__tchannel_qcd}\n\\includegraphics[width=0.49\\textwidth]\n{eps/MatrixElement/performance/tq_Efficiency__tchannel_qcd}\n\\caption{Discriminant plots and efficiency curves for:\nfirst row, $tb$ vs. $Wjj$, second row, $tb$ vs. multijets, third row,\n$tq$ vs. $Wjj$, and fourth row, $tq$ vs. multijets. The numbers in the\nefficiency curves (right column) represent the fraction of signal or\nbackground the remains after a discriminant cut of 0.8.}\n\\label{disc_wjets}\n\\end{figure}\n\n\\begin{figure}[!h!tbp]\n\\includegraphics[width=0.49\\textwidth]\n{eps/MatrixElement/performance/tb_Discriminant__schannel_dilepton}\n\\includegraphics[width=0.49\\textwidth]\n{eps/MatrixElement/performance/tb_Efficiency__schannel_dilepton}\n\\includegraphics[width=0.49\\textwidth]\n{eps/MatrixElement/performance/tb_Discriminant__schannel_lepjets}\n\\includegraphics[width=0.49\\textwidth]\n{eps/MatrixElement/performance/tb_Efficiency__schannel_lepjets}\n\\includegraphics[width=0.49\\textwidth]\n{eps/MatrixElement/performance/tq_Discriminant__tchannel_dilepton}\n\\includegraphics[width=0.49\\textwidth]\n{eps/MatrixElement/performance/tq_Efficiency__tchannel_dilepton}\n\\includegraphics[width=0.49\\textwidth]\n{eps/MatrixElement/performance/tq_Discriminant__tchannel_lepjets}\n\\includegraphics[width=0.49\\textwidth]\n{eps/MatrixElement/performance/tq_Efficiency__tchannel_lepjets}\n\\caption{Discriminant plots and efficiency curves for:\nfirst row, $tb$ vs. $\\dilepton$, second row, $tb$ vs. $\\lepjets$,\nthird row, $tq$ vs. $\\dilepton$, and fourth row, $tq$\nvs. $\\lepjets$. The numbers in the efficiency curves (right column)\nrepresent the fraction of signal or background the remains after a\ndiscriminant cut of 0.8.}\n\\label{disc_ttbar}\n\\end{figure}\n\n\\subsection{Two-Dimensional Discriminants}\n\nThis analysis uses a two-dimensional (2D) discriminant as the final output where one axis is the $s$-channel discriminant and the other axis is the $t$-channel discriminant value for the event. The 2D discriminant is more powerful than either 1D\nprojection because it selects events with both $s$ and $t$-channel\ncharacteristics, which helps to further reduce the $W$+jets and\n$\\ttbar$ background which may have either characteristic but not\nnecessarily both. Figures~\\ref{wbbwccwjj} and \\ref{qcdtt} show the 2D discriminants\nfor single top quark signals and for all the backgrounds. The\nplots are normalized to unit volume.\n\n\\clearpage\n\n\\begin{figure}[!h!tbp]\n\\includegraphics[width=0.49\\textwidth]\n{eps/MatrixElement/performance/2D-Discriminant_schannel}\n\\includegraphics[width=0.49\\textwidth]\n{eps/MatrixElement/performance/2D-Discriminant_tchannel}\n\\vspace{-0.1in}\n\\caption{2D-discriminant templates for: left, $tb$, and\nright, $tqb$ Monte Carlo events.}\n\\label{tbtqb}\n\\end{figure}\n\n\\begin{figure}[!h!tbp]\n\\includegraphics[width=0.49\\textwidth]\n{eps/MatrixElement/performance/2D-Discriminant_wbb}\n\\includegraphics[width=0.49\\textwidth]\n{eps/MatrixElement/performance/2D-Discriminant_wcc}\n\\includegraphics[width=0.49\\textwidth]\n{eps/MatrixElement/performance/2D-Discriminant_wjj}\n\\vspace{-0.1in}\n\\caption{2D-discriminant templates for: left,\n$Wbb$, middle, $Wcc$, and right, $Wjj$ Monte Carlo events.}\n\\label{wbbwccwjj}\n\\end{figure}\n\n\\begin{figure}[!h!tbp]\n\\includegraphics[width=0.49\\textwidth]\n{eps/MatrixElement/performance/2D-Discriminant_qcd}\n\\includegraphics[width=0.49\\textwidth]\n{eps/MatrixElement/performance/2D-Discriminant_dilepton}\n\\includegraphics[width=0.49\\textwidth]\n{eps/MatrixElement/performance/2D-Discriminant_lepjets}\n\\vspace{-0.1in}\n\\caption{2D-discriminant templates for: left,\nmultijets events, middle, $\\dilepton$, and right, $\\lepjets$ Monte\nCarlo events.}\n\\label{qcdtt}\n\\end{figure}\n\n\n\n\\section{Cross-Check Samples}\n\\label{crosscheck}\n\nBefore a measurement of the single top quark cross section is made, the output of the matrix element analysis is compared between data and background in a region where the signal content is negligible. If the agreement between data and background is good in this sample, there is more confidence that the background is well-modeled in the signal region. In this analysis two background-dominated control\nsamples are defined, and a comparison between the 1D discriminants in\ndata and the background model is performed.\n\nThese two control samples are selected by applying the nominal event\nselection, and requiring in addition cut on the total transverse energy $H_{T}$ defined as\n\n\\begin{equation}\nH_{T} = p^{\\rm{lepton}}_{T} + \\rm{M}E_{T} + \\sum_{\\rm{jets}} p^{jet}_{T}\n\\end{equation}\n\nThe first sample selects events with $H_T<175$~GeV and the second sample selects events with $H_T>300$~GeV,\nrespectively. The control samples defined with $H_{T}<175$~GeV is referred to as the ``soft $W$+jets'' sample and the sample with $H_{T}>300$~GeV is referred to as the ``hard $W$+jets'' sample. In the case of three-jet events, the ``hard $W$+jets'' sample also contains a\nsignificant fraction of $\\ttbar$.\n\nThe ``soft $W$+jets'' sample selects low momentum $W$+jets and\nmultijets events and almost no top-quark events.\nFigures~\\ref{wjets-cross-2jet} and \\ref{wjets-cross-3jet} compare the\n$s$-channel and $t$-channel discriminants between data and the background model for\nevents with two and three jets respectively.\n\nThe ``hard $W$+jets'' sample selects mainly $\\ttbar$ and high momentum\n$W$+jets events. Figures~\\ref{ttbar-cross-2jet} and\n\\ref{ttbar-cross-3jet} compare the $s$-channel and $t$-channel discriminants between\ndata and the background model for events with two and three jets.\n\n\\clearpage\n\\begin{figure}[!h!tbp]\n\\includegraphics[width=0.49\\textwidth]\n{eps/MatrixElement/cross_check/combined/2jet/Wjets_tb_Discriminant}\n\\includegraphics[width=0.49\\textwidth]\n{eps/MatrixElement/cross_check/combined/2jet/Wjets_tb_Discriminant_Zoom}\n\\includegraphics[width=0.49\\textwidth]\n{eps/MatrixElement/cross_check/combined/2jet/Wjets_tq_Discriminant}\n\\includegraphics[width=0.49\\textwidth]\n{eps/MatrixElement/cross_check/combined/2jet/Wjets_tq_Discriminant_Zoom}\n\\vspace{-0.1in}\n\\caption{``Soft $W$+jets'' cross-check plots in two-jet\nevents for the $tb$ discriminant (upper row) and the $tq$ discriminant\n(lower row). The left column shows the full discriminant region while\nthe right column shows the high discriminant region above 0.7.}\n\\label{wjets-cross-2jet}\n\\end{figure}\n\n\\clearpage\n\\begin{figure}[!h!tbp]\n\\includegraphics[width=0.49\\textwidth]\n{eps/MatrixElement/cross_check/combined/3jet/Wjets_tb_Discriminant}\n\\includegraphics[width=0.49\\textwidth]\n{eps/MatrixElement/cross_check/combined/3jet/Wjets_tb_Discriminant_Zoom}\n\\includegraphics[width=0.49\\textwidth]\n{eps/MatrixElement/cross_check/combined/3jet/Wjets_tq_Discriminant}\n\\includegraphics[width=0.49\\textwidth]\n{eps/MatrixElement/cross_check/combined/3jet/Wjets_tq_Discriminant_Zoom}\n\\vspace{-0.1in}\n\\caption{``Soft $W$+jets'' cross-check plots in three-jet\nevents for the $tb$ discriminant (upper row) and the $tq$ discriminant\n(lower row). The left column shows the full discriminant region while\nthe right column shows the high discriminant region above 0.7.}\n\\label{wjets-cross-3jet}\n\\end{figure}\n\n\\clearpage\n\\begin{figure}[!h!tbp]\n\\includegraphics[width=0.49\\textwidth]\n{eps/MatrixElement/cross_check/combined/2jet/TTbar_tb_Discriminant}\n\\includegraphics[width=0.49\\textwidth]\n{eps/MatrixElement/cross_check/combined/2jet/TTbar_tb_Discriminant_Zoom}\n\\includegraphics[width=0.49\\textwidth]\n{eps/MatrixElement/cross_check/combined/2jet/TTbar_tq_Discriminant}\n\\includegraphics[width=0.49\\textwidth]\n{eps/MatrixElement/cross_check/combined/2jet/TTbar_tq_Discriminant_Zoom}\n\\vspace{-0.1in}\n\\caption{``Hard $W$+jets'' cross-check plots in two-jet\nevents for the $tb$ discriminant (upper row) and the $tq$ discriminant\n(lower row). The left column shows the full discriminant region while\nthe right column shows the high discriminant region above 0.7.}\n\\label{ttbar-cross-2jet}\n\\end{figure}\n\n\\clearpage\n\\begin{figure}[!h!tbp]\n\\includegraphics[width=0.49\\textwidth]\n{eps/MatrixElement/cross_check/combined/3jet/TTbar_tb_Discriminant}\n\\includegraphics[width=0.49\\textwidth]\n{eps/MatrixElement/cross_check/combined/3jet/TTbar_tb_Discriminant_Zoom}\n\\includegraphics[width=0.49\\textwidth]\n{eps/MatrixElement/cross_check/combined/3jet/TTbar_tq_Discriminant}\n\\includegraphics[width=0.49\\textwidth]\n{eps/MatrixElement/cross_check/combined/3jet/TTbar_tq_Discriminant_Zoom}\n\\vspace{-0.1in}\n\\caption{``Hard $W$+jets'' cross-check plots in three-jet\nevents for the $tb$ discriminant (upper row) and the $tq$ discriminant\n(lower row). The left column shows the full discriminant region while\nthe right column shows the high discriminant region above 0.7.}\n\\label{ttbar-cross-3jet}\n\\end{figure}\n\n\\clearpage\n\\section{Matrix Element Discriminants}\n\\label{matrixelementresults}\n\nThis section presents the matrix element discriminants for all events in each analysis channel. Figures~\\ref{e21_2j} and~\\ref{e21_3j} show the $tb$ and $tqb$\ndiscriminants for the combined $e$,$\\mu$ w/ $\\geq1$ $B$-tag events for two-jet\nand three-jet events where the data distributions may be compared to\nthe background model. The SM prediction for single top quark\nproduction has been added to the background sum in the plots. The\nindividual channel plots for the 1D discriminants are shown in\nAppendix~\\ref{Channel}.\n\n\\vspace{-0.05in}\n\\begin{figure}[!h!tbp]\n\\includegraphics[width=0.49\\textwidth]\n{eps/MatrixElement/output/2jet/All_tb_Discriminant.eps}\n\\includegraphics[width=0.49\\textwidth]\n{eps/MatrixElement/output/2jet/All_tb_Discriminant_Zoom.eps}\n\\includegraphics[width=0.49\\textwidth]\n{eps/MatrixElement/output/2jet/All_tq_Discriminant.eps}\n\\includegraphics[width=0.49\\textwidth]\n{eps/MatrixElement/output/2jet/All_tq_Discriminant_Zoom.eps}\n\\vspace{-0.1in}\n\\caption{Discriminant plots for the e+$\\mu$ channel with two jets and\n$\\geq$~1 $B$~tag. Upper row: $tb$ discriminant; lower row: $tq$\ndiscriminant. Left column: full output range; right column: close-up\nof the high end of the distributions.}\n\\label{e21_2j}\n\\end{figure}\n\n\\vspace{-0.05in}\n\\begin{figure}[!h!tbp]\n\\includegraphics[width=0.49\\textwidth]\n{eps/MatrixElement/output/3jet/All_tb_Discriminant.eps}\n\\includegraphics[width=0.49\\textwidth]\n{eps/MatrixElement/output/3jet/All_tb_Discriminant_Zoom.eps}\n\\includegraphics[width=0.49\\textwidth]\n{eps/MatrixElement/output/3jet/All_tq_Discriminant.eps}\n\\includegraphics[width=0.49\\textwidth]\n{eps/MatrixElement/output/3jet/All_tq_Discriminant_Zoom.eps}\n\\vspace{-0.1in}\n\\caption{Discriminant plots for the e+$\\mu$ channel with three jets\nand $\\geq$~1 $b$~tag. Upper row: $tb$ discriminant; lower row: $tq$\ndiscriminant. Left column: full output range; right column: close-up\nof the high end of the distributions.}\n\\label{e21_3j}\n\\end{figure}\n\nAfter the matrix element discriminant has been calculated, it is\npossible to place a cut on this value to select events in data and\nMonte Carlo to see if they are consistent with single top quark\nproduction. For this section, an event is considered very single top\nquark like if both the $s$-channel and $t$-channel discriminants are\ngreater than 0.7. Similarly, an event is considered background like if\nboth discriminants are less than 0.4. Figure~\\ref{top-mass} shows the\ninvariant mass of the lepton, neutrino, and tagged jet before and\nafter the discriminant cut, and Fig.~\\ref{q-eta} shows the\nlepton-charge times pseudorapidity of the untagged jet.\n\n\\begin{figure}[!h!tbp]\n\\includegraphics[width=0.49\\textwidth]\n{eps/MatrixElement/topovars/BTaggedTopMass_0.eps}\n\\includegraphics[width=0.49\\textwidth]\n{eps/MatrixElement/topovars/BTaggedTopMass_-0.4.eps}\n\\includegraphics[width=0.49\\textwidth]\n{eps/MatrixElement/topovars/BTaggedTopMass_0.7.eps}\n\\vspace{-0.1in}\n\\caption{Invariant mass of the lepton, neutrino, and tagged\njet for all events (upper left plot), for events with $D < 0.4$ (upper right plot), and events with $D > 0.7$ (bottom left plot).}\n\\label{top-mass}\n\\end{figure}\n\n%\\vspace{0.1in}\n\\begin{figure}[!h!tbp]\n\\includegraphics[width=0.49\\textwidth]\n{eps/MatrixElement/topovars/QTimesEta_0.eps}\n\\includegraphics[width=0.49\\textwidth]\n{eps/MatrixElement/topovars/QTimesEta_-0.4.eps}\n\\includegraphics[width=0.49\\textwidth]\n{eps/MatrixElement/topovars/QTimesEta_0.7.eps}\n\\vspace{-0.1in}\n\\caption{Lepton charge times the pseudorapidity of the untagged\njet for all events (upper left plot), for events with $D < 0.4$ (upper right\nplot), and events with $D > 0.7$ (bottom left plot). The number of observed\nevents is different from the $b$-tagged top mass plot because this\nvariable is only defined for events with at least one untagged jet.}\n\\label{q-eta}\n\\end{figure}\n", "meta": {"hexsha": "b472a01731cda391d6cc6f0f03cb063cdc694564", "size": 15496, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "MEtemp.tex", "max_stars_repo_name": "tgadf/thesis", "max_stars_repo_head_hexsha": "19d4a6bc7f7ac8660fce582322703d50e0d6bd31", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "MEtemp.tex", "max_issues_repo_name": "tgadf/thesis", "max_issues_repo_head_hexsha": "19d4a6bc7f7ac8660fce582322703d50e0d6bd31", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MEtemp.tex", "max_forks_repo_name": "tgadf/thesis", "max_forks_repo_head_hexsha": "19d4a6bc7f7ac8660fce582322703d50e0d6bd31", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.5345345345, "max_line_length": 403, "alphanum_fraction": 0.7987222509, "num_tokens": 4691, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984434543458, "lm_q2_score": 0.2877678218692626, "lm_q1q2_score": 0.15398411355848984}} {"text": "\\begin{chapter}{\\LaTeX}\n\nProducing high quality mathematical documents that show equations, figures and references clearly is very difficult in standard word processing packages. Instead the standard is to use \\LaTeX, a ``document prepartion language''. Most notes, such as these, and mathematical papers, use \\LaTeX.\n\n\\section{What is \\LaTeX}\n\n\\LaTeX\\ takes a plain text file and converts it into a document, often in PDF format, containing all the equations, figures and cross-references. In this sense it's similar to Python: you start from a plain text file and \\emph{build} it to produce a result.\n\n\\LaTeX\\ documents are often complex, but many are available online. A standard technique is to find a \\LaTeX document that does what you want online, and take the key commands from that.\n\n\\section{Installing or finding}\n\\label{sec:installing}\n\n\\LaTeX\\ is free software and there's lots of available implementations. As with Python, a \\LaTeX\\ document is plain text and can be written using any text editor. However, specific \\LaTeX\\ editors can help in rapidly writing documents with fewer errors.\n\n\\subsection{University machines}\n\nUse the search function to look for \\texttt{TeXnicCentre}. When first running, choose all the default options. Some of the instructions below on building a document are specific to TeXnicCentre, as it's provided on the university machines, but similar methods should work in all editors.\n\n\\subsection{Personal machines}\n\nIf using a Linux or Mac, \\LaTeX\\ should be installed automatically. There are many editors you can use -- \\href{http://www.xm1math.net/texmaker/}{TeXMaker} is one example -- and you can experiment with which you prefer. If using a Windows machine, you can freely download \\href{http://www.texniccenter.org/}{TeXnicCentre} which will install \\LaTeX\\ for you, or use TeXMaker as above.\n\n\\subsection{Online}\n\nThere are browser-based \\LaTeX\\ editors which can be used, such as \\href{https://www.overleaf.com/}{Overleaf} and \\href{https://www.sharelatex.com/}{ShareLaTeX}. There are obvious advantages -- there's no need to install anything, it's backed up externally, and it builds the document for you. The balancing disadvantages are also there -- needs a network connection, the online editor isn't as full featured as special desktop versions, and keeping your work private requires paying.\n\nOverleaf also \\href{https://www.overleaf.com/latex/learn/free-online-introduction-to-latex-part-1}{hosts an online tutorial on \\LaTeX} that works through the essential points.\n\n\\subsection{\\LaTeX\\ in other formats}\n\nA full \\LaTeX\\ document can be very complex as it controls \\emph{every} aspect of the document appearance. Many simpler document formats have been written, often based around \\href{http://daringfireball.net/projects/markdown/}{Markdown} (see also \\href{https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet}{this cheatsheet}). To typeset mathematics within these document formats, \\LaTeX\\ \\emph{syntax} is used: one particular example is \\href{https://www.authorea.com}{Authorea} where a simple Markdown-based document format can be mixed with \\LaTeX\\ syntax to create documents both for online and offline use. We have already seen how \\LaTeX\\ syntax can be used within, e.g., \\texttt{matplotlib}.\n\n\\section{Getting Started}\n\n\\subsection{A basic document}\n\nDownload a simple \\LaTeX\\ document \\href{https://raw.githubusercontent.com/IanHawke/maths-with-python/master/latex/BasicLatex.tex}{from this link}. Open it in whichever editor you are using, and build it so you can see the output (which should look like \\href{https://github.com/IanHawke/maths-with-python/raw/master/latex/BasicLatex.pdf}{this pdf file}). If using TeXnicCentre on the University machines, you should be able to do this by running ``Build and View'' from the ``Build'' menu.\n\nYou should compare the document with the built PDF file. In particular note, as stated in the document,\n%\n\\begin{itemize}\n \\item that anything before the ``\\verb|\\begin{document}|'' (the \\emph{preamble}) doesn't show explicitly, but changes global properties of the document,\n \\item how whitespace works,\n \\item how anything ``special'' starts ``\\verb|\\|'',\n \\item how quote characters behave (compare with ''this''),\n \\item how curly braces \\verb|{| and \\verb|}| are used without\n appearing,\n \\item how \\emph{environments} always \\verb|\\begin| and\n \\verb|\\end|,\n \\item and how the \\verb|\\section| command works.\n\\end{itemize}\n%\nYou should edit and re-build the document so that you can see the effects of adding standard text, new sections (or subsections), and so on.\n\n\\subsection{Mathematics and references}\n\nNow download \\emph{both} \\href{https://raw.githubusercontent.com/IanHawke/maths-with-python/master/latex/BasicLatexBibtex.tex}{this \\LaTeX\\ document} and \\href{https://raw.githubusercontent.com/IanHawke/maths-with-python/master/latex/nummeth.bib}{this bibliography file}. The bibliography file must be saved in the same directory as the \\LaTeX\\ document, must have a \\texttt{.bib} extension, and (in this case) should be called \\texttt{nummeth.bib}. Again, build this document and view the results.\n\n\\subsubsection{The build process}\n\nSome editors will (or will let you) build the document one step at a time. In this case you may have perform multiple build steps. For example, the first build step will produce a document that \\href{https://raw.githubusercontent.com/IanHawke/maths-with-python/master/latex/BasicLatexBibtex_pass1.pdf}{looks like this}. At this point none of the cross-references are correct, but appear as ``\\textbf{?}'', and there is no bibliography. The second build step will create the bibliography, but will not change the document. The third build step will produce a document that \\href{https://raw.githubusercontent.com/IanHawke/maths-with-python/master/latex/BasicLatexBibtex_pass2.pdf}{looks like this}. At this point cross-references to sections and equations are correct, and the bibliography is included. However, the cross-references to the bibliography are not correct. A fourth build step will produce a document that \\href{https://raw.githubusercontent.com/IanHawke/maths-with-python/master/latex/BasicLatexBibtex_pass3.pdf}{looks like this}, with all references correct.\n\n\\subsubsection{Mathematics}\n\nTo include mathematical notation inline, commands should be placed between dollar signs, \\verb|$...$|, so that \\verb|$\\pi$| gives $\\pi$. To create a \\emph{displayed} equation, use the \\texttt{equation} environment, as in\n%\n\\begin{verbatim}\n\\begin{equation}\n \\label{eq:label_example}\n x = y + z.\n\\end{equation}\n\\end{verbatim}\n%\nwhich gives\n%\n\\begin{equation}\n \\label{eq:label_example}\n x = y + z.\n\\end{equation}\n%\nNote that the ``\\verb|\\label{...}|'' command allows the equation to be cross-referenced using the ``\\verb|\\ref{...}|'' command, giving equation \\ref{eq:label_example}.\n\nAs seen above, Greek characters in mathematics are the letter preceded by the backslash, so \\verb|$\\theta$| gives $\\theta$. To produce subscripts, use the underscore \\verb|_|, and for superscripts the caret \\verb|^|. So \\verb|$x_1^2$| gives $x_1^2$. To group characters together, use the curly braces \\verb|{}|. You need to do this, for example, if you want more than one character to appear in sub- or superscripts. Hence \\verb|$F_n-2$| gives $F_n-2$, but \\verb|$F_{n-2}$| gives $F_{n-2}$.\n\nStandard mathematical commands and symbols are also preceded by backslashes, such as \\verb|$\\int$| ($\\int$), \\verb|$\\sum$| ($\\sum$), and \\verb|$\\infty$| ($\\infty$). A more complete list \\href{https://en.wikibooks.org/wiki/LaTeX/Mathematics}{can be found online}, and for more obscure symbols the online \\href{http://detexify.kirelabs.org/classify.html}{handwriting recognition trick} is very useful.\n\n\\subsection{Cross-referencing and bibliographies}\n\nWe saw above how the \\texttt{equation} environment could include a \\verb|\\label| which allowed it to be cross-referenced using the \\verb|\\ref| command. This can be done for any environment which takes a number; for example, the section on installing \\LaTeX\\ above has the label \\verb|\\label{sec:installing}|, and can be cross-referenced using \\verb|\\ref{sec:installing}|, giving section~\\ref{sec:installing}.\n\nFor citing references -- books, papers, websites etc.\\ -- we instead use the \\verb|\\cite| command. This looks for the article within the \\emph{Bibtex} file that has the specific \\emph{key}. In the document here, the command \\verb|\\cite{godunov}| tells \\LaTeX\\ that the key is ``\\verb|godunov|'', and the command \\verb|\\bibliography{nummeth}| tells it that the Bibtex file is in \\texttt{nummeth.bib}.\n\nThe structure of the Bibtex file can look complex. There are many shortcuts -- for example, by searching for the reference on Google Scholar, and then clicking on the ``Cite'' link, it will give the Bibtex entry that you can simply copy and paste into your file. For alternatives, see section~\\ref{sec:Citations}.\n\n\n\\LaTeX\\ is most useful for creating long documents (journal articles, theses, etc.) containing substantial mathematics. Sectioning, cross-referencing and bibliographies we have already seen. There are a number of additional features to make the creation of long documents easier.\n\nThese are gathered in a logical order below, but for most purposes the discussion of commands (section~\\ref{sec:commands}), provided packages (section~\\ref{sec:packages_provided}), and modularity (section~\\ref{sec:modularity}) will be of most use.\n\n\\section{Commands}\n\\label{sec:commands}\n\n\\subsection{Defining commands}\n\\label{sec:commands_defn}\n\nFirstly, user-defined commands can replace long sequences with a short, or more memorable, version. For example, a simple partial derivative\n%\n\\begin{equation}\n \\label{eq:example_pd_1}\n \\frac{\\partial y}{\\partial x}\n\\end{equation}\n%\ncan be written \\verb|\\frac{\\partial y}{\\partial x}|. The equivalent shorthand\n%\n\\begin{equation}\n \\label{eq:example_pd_2}\n \\pda{y}{x}\n\\end{equation}\n%\ncan be written, for example, \\verb|\\pda{y}{x}|. This is both clearer and shorter.\n\nThe command \\verb|\\pda| is defined in the \\emph{document preamble}: after the \\verb|\\documentclass| command but before the \\verb|\\begin{document}| statement. The definition used here is\n%\n\\begin{center}\n \\verb|\\newcommand{\\pda}[2]{\\frac{\\partial {#1}}{\\partial {#2}}}|\n\\end{center}\n%\nwhich requires some explanation:\n\\begin{itemize}\n\\item Obviously \\verb|\\newcommand{\\pda}| defines the new command\n \\verb|\\pda|.\n\\item The statement \\verb|[2]| says that the command has two arguments\n (in the example \\verb|\\pda{y}{x}| the arguments are \\verb|y| and\n \\verb|x| respectively). For commands that take no arguments (e.g.\\\n where you are just defining a shorthand, such as the command\n \\verb|\\uos| defined at the start of this document which expands to\n \\uos) this part is absent.\n\\item The rest of the line defines the command, and is enclosed in\n braces \\verb|{...}| for safety. The arguments are referred to by the\n \\verb|#| statements; e.g., in the example above \\verb|#1|\n corresponds to \\verb|y| and \\verb|#2| to \\verb|x|. Again, the\n arguments are typically enclosed in braces \\verb|{...}| for safety.\n\\end{itemize}\n\n\\subsection{Redefining commands}\n\\label{sec:commands_redefn}\n\nSometimes a command already exists with the shorthand name that you want to use, but does not do what you expect or want. In this case it can be redefined using the command \\verb|\\renewcommand|. This works in exactly the same way as \\verb|\\newcommand|, except the command must already exist (note that if the command already exists then trying to (re)define it with \\verb|\\newcommand| will give an error).\n\nThe classic example is typesetting vectors using the \\LaTeX\\ command \\verb|\\vec|. By default this puts an arrow above the argument, similar to (but smaller than) the command \\verb|\\overrightarrow| which produces, e.g., $\\overrightarrow{AB}$. Many people typeset vectors use bold fonts, which can be done using e.g.\\\n%\n\\begin{center}\n \\verb|\\renewcommand{\\vec}[1]{\\mathbf{#1}}|\n\\end{center}\n%\nwhich produces the output $\\vec{a}$.\n\n\\section{Environments}\n\\label{sec:environments}\n\nAs we have seen, commands are not the only things that \\LaTeX\\ provides. It also provides \\emph{environments} which are enclosed within \\verb|\\begin{...}| and \\verb|\\end{...}| statements. Standard environments are \\verb|equation| and \\verb|document|.\n\nJust as with commands it is possible to define new environments (using the \\verb|\\newenvironment| command in the document preamble) or redefine old ones (using the \\verb|\\renewenvironment| command). The usage is similar to that of \\verb|\\newcommand| as well: the main difference is that instead of defining what the command does, you define what should happen before entering and after exiting the environment.\n\nA simple example is\n%\n\\begin{verbatim}\n\\newenvironment{solution}[1]{%\n \\begin{center}\n \\rule{#1}{.1pt}\n \\end{center}\n}{%\n \\begin{center}\n \\rule{0.9\\textwidth}{.1pt}\n \\end{center}\n}\n\\end{verbatim}\n%\nwhich defines a \\verb|solution| environment.\n\nThe explanation of each piece is as follows:\n\\begin{itemize}\n\\item \\verb|\\newenvironment{solution}|: the definition of the name of the new environment.\n\\item \\verb|[1]|: the number of arguments pass in (here 1).\n\\item \\verb|{\\begin{center} \\rule{#1}{.1pt} \\end{center} }|: in the definition these are spaced using carriage returns and comment markers for clarity, but by matching the curly braces this can be seen to be just one argument. These are the commands issued before entering the environment. \\verb|#1| is the first argument passed in.\n\\item \\verb|{\\begin{center} \\rule{\\rule{0.9\\textwidth}{.1pt} \\end{center} }|: again this was spaced for clarity in the definition. These are the commands issued after exiting the environment. No arguments can be used at this point.\n\\end{itemize}\n\nThis environment, used as\n%\n\\begin{verbatim}\n\\begin{solution}{0.9\\textwidth}\n This is the solution.\n\\end{solution}\n\\end{verbatim}\n%\nproduces the output\n%\n\\begin{solution}{0.9\\textwidth}\n This is the solution.\n\\end{solution}\n%\n\n\\section{Packages}\n\\label{sec:packages}\n\nIn essence a package is just a file containing a number of useful commands and environments, as explained in sections~\\ref{sec:commands} and \\ref{sec:environments}. So, rather than hand-defining a large number of commands you can import them all by including code such as\n%\n\\begin{verbatim}\n\\usepackage{amsmath}\n\\end{verbatim}\n%\nin the document preamble.\n\nThis is particularly important when producing journal articles. Many journals require (or strongly encourange) you to submit articles fitting in with their in-house style. Many scientific journals will therefore provide a \\LaTeX\\ package to use in the production of your article.\n\n\\subsection{Useful packages}\n\\label{sec:packages_provided}\n\nMost \\LaTeX\\ distributions will include the following packages which are extremely useful:\n\\begin{itemize}\n\\item \\texttt{graphicx} or \\texttt{graphics}: commands to import and manipulate graphics files.\n\\item \\texttt{amsmath} (and \\texttt{amssymb} and \\texttt{amsthm}): The American Mathematical Society \\LaTeX\\ package. A large number of useful commands, especially for aligning equations (see \\verb|\\align| and related).\n\\item \\texttt{fancyhdr}, \\texttt{enumerate}, \\texttt{caption}, \\texttt{geometry}: control the document layout and appearance in a more transparent fashion. \\texttt{fancyhdr} in particular is useful for producing headers for theses.\n\\item \\texttt{babel}: if you want to typeset anything in a language other than English, this package provides a lot of support.\n\\item \\texttt{hyperref}: transforms citations and cross-references into hyperlinks. Particularly useful when compiling direct to PDF.\n\\item \\texttt{natbib} or \\texttt{biblatex}: most will find the default citation styles sufficient (or, for articles, journals will frequently provide their own). If you require something more controllable then these packages give you that power (\\texttt{natbib} is much older and practically obsolete, but has lots of examples and is in widespread use. \\texttt{biblatex} is much newer and very powerful but with far fewer examples and requires a modern \\LaTeX\\ distribution).\n\\end{itemize}\n\n\\subsection{Creating packages}\n\\label{sec:packages_creating}\n\nAt its heart a package just contains the commands you would have placed in the document preamble. However, there are a few additional commands and points to be careful of.\n\n\\begin{itemize}\n\\item \\verb|\\ProvidesPackage{}[]|: this command defines the name of the package \\verb|| (which should match its filename) and an optional description \\verb||.\n\\item \\verb|\\RequirePackage{}|: instead of putting \\verb|\\usepackage{}| inside a package, this command allows \\LaTeX\\ to check if \\verb|| has already been loaded, and if not, does so.\n\\item \\verb|\\DeclareOption|, \\verb|ExecuteOptions|, \\verb|\\ProcessOptions|: allows you to pass options to the package (and hence options to commands in the package).\n\\end{itemize}\n\nPackage files should have a \\verb|.sty| extension.\n\n\\section{Modularity}\n\\label{sec:modularity}\n\nLong documents are typically composed of many chapters and sections using a variety of data. Working on a single long document is inefficient and confusing. It is better to split the document into multiple chunks corresponding to the structure of the document. \\LaTeX\\ has two ways of doing this.\n\n\\subsection{Input}\n\\label{sec:modularity_input}\n\nThe command \\verb|\\input| simply imports a file, as if it were ``cut and paste'' into the current document. This could be done right here, with a file imported into the middle of a paragraph. The \\verb|\\input| command takes the name of the file to be imported without the \\texttt{.tex} extension. Once the file is imported the document continues as normal.\n\nThe \\verb|\\input| command is somewhat inflexible. My personal viewpoint is that its main use is for importing data produced by or stored in external formats. For example, if you have a code that produces a table with 50 entries, it will be safer to make your code output the results directly into a \\LaTeX\\ table format which can then be \\verb|\\input| into a document, rather than trying to copy all the data by hand.\n\n\\subsection{Include}\n\\label{sec:modularity_include}\n\nThe alternative to the \\verb|\\input| command is the \\verb|\\include| command. Its use is exactly the same as the \\verb|\\input| command -- the only argument is the name of the file to be included, without the \\texttt{.tex} extension. There are two main differences.\n\nThe first difference, as is clear from this document, is that the text imported via the \\verb|\\include| command always starts on a new page, and there will be a new page inserted (via a page break) after the included content as well. For this reason the \\verb|\\include| statement is typically used in long documents -- reports or theses -- where each included file contains a full chapter.\n\nThe second difference is the main advantage of the \\verb|\\include| command. You can selectively include only certain files whilst leaving all the \\verb|\\include| statements in place. For example, consider an outline document\n%\n\\begin{verbatim}\n\\documentclass{book}\n\n\\includeonly{chapter2}\n\n\\begin{document}\n\n\\include{chapter1}\n\\include{chapter2}\n\\include{chapter3}\n\n\\end{document}\n\\end{verbatim}\n%\nThis document should consist of three chapters. If we are working just on chapter 2 then we can concentrate solely on that by using the \\verb|\\includeonly| command to produce only the output for that chapter. However, all cross-references to the other chapters will still be correctly resolved (provided that they have been compiled at least once).\n\n\\section[Additional commands]{Additional commands for long documents}\n\\label{sec:additional}\n\nThis contains a list of commands that are often useful for long reports and theses.\n%\n\\begin{itemize}\n\\item \\verb|\\maketitle|: Produces a title page based on the \\verb|\\author|, \\verb|\\title| and \\verb|\\date| (which must be set after the \\verb|\\begin{document}| but before the \\verb|\\maketitle|).\n\\item \\verb|\\appendix|: as just used here, this converts the section or chapter numbering to use letters instead of numbers.\n\\item \\verb|\\tableofcontents|: inserts a table of contents containing the titles of chapters, sections, subsections (there are parameters to control the depth).\n\nNote that if a title is extremely long it may not fit in the table of contents (or in the headers). All sectioning commands provide an option for a short title to be used in headers, table of contents and similar circumstances. An example is the title for this appendix where a short title of ``Additional commands'' can be produced using\n\\begin{verbatim}\n\\section[Additional commands]{Additional commands for long documents}\n\\end{verbatim}\n\\item \\verb|\\listoffigures|, \\verb|\\listoftables|: inserts the appropriate lists based on the captions of figures and tables. Here you will almost certainly want to use the optional short form for the captions.\n\\item \\verb|\\frontmatter|, \\verb|\\mainmatter|, \\verb|\\backmatter|: only avaiable for \\verb|book| class, this explicitly changes the page numbering to Roman letters or Arabic numerals respectively.\n\\end{itemize}\n\n\\section{Citations and bibliographies}\n\\label{sec:Citations}\n\nOne of \\LaTeX's strengths is its cross-referencing. However, the mechanism for including and organizing the bibliography is out-dated, so requires a little work to use in the best fashion.\n\nThe command to reference a bibliography citation is \\verb|\\cite|. Some\nadditional packages (such as \\verb|natbib|) introduce additional\ncitation commands which allow for more control of the appearance of\nthe reference within the text. The \\verb|\\cite| command takes at least\none argument, which is the \\emph{key} to the article in the\nbibliography.\n\nThis section introduces the two most basic ways of building a bibliography in \\LaTeX. Only the \\verb|Bibtex| method of section~\\ref{sec:bibtex} is recommended, and it is best to look at tools mentioned later for ease. Later sections will mainly focus on tools to build, maintain and control bibliographies using the underlying \\verb|Bibtex| technology.\n\nNote that when using \\LaTeX\\ to build a document containing a bibliography it is usually necessary to build the document at least twice, and usually three times. On the first pass it looks in the document and finds which citations are needed. On the second pass it looks in the database and extracts the citations, putting them in the appropriate form. The third pass finalizes the document.\n\n\\subsection{Direct inclusion}\n\\label{sec:Direct}\n\nThe bibliography can be written directly into the \\LaTeX\\ document using the commands (for example)\n%\n\\begin{verbatim}\n\\begin{thebibliography}{99}\n\n\\bibitem{Duncan98} R. C. Duncan, Astrophys. J. {\\bf 498}, L45 (1998).\n\n\\end{thebibliography}\n\\end{verbatim}\n%\nIn this case there is only one item in the bibliography. The \\verb|{99}| at the beginning gives the maximum number of entries in the bibliography -- this could be increased if needed. The article key is here \\verb|Duncan98|, and would be cross-referenced in the text using \\verb|\\cite{Duncan98}|.\n\nThe advantages of this citation method are\n\\begin{enumerate}\n\\item speed; you can directly and rapidly change the document,\n\\item control; you can control exactly how it appears.\n\\end{enumerate}\n\nThe disadvantages are numerous.\n\\begin{enumerate}\n\\item Reuse; for every document you need to copy the reference without error.\n\\item Modification; for every different use you need to manually change the appearance of the reference, and do it consistently.\n\\item Completeness; there is no simple way to store all additional information about the reference that is not explicitly required (e.g.\\ the abstract).\n\\item Errors; if you delete the reference from the text you must consistently remove it from the bibliography. If an unpublished article is published, you must consistently update the reference in all documents.\n\\item Etc...\n\\end{enumerate}\n\n\\subsection{Bibtex}\n\\label{sec:bibtex}\n\n\\verb|Bibtex| was the original solution for the \\LaTeX referencing issues outlined above. An example of using \\verb|Bibtex| is given in the \\verb|BasicLatexBibtex| document, combined with the \\verb|nummeth.bib| database file.\n\nIn brief, the \\verb|Bibtex| file is a database. Written as a plain-text file, each entry is a single reference. An example entry would be\n%\n\\begin{verbatim}\n@article{Pareschi2005,\nauthor = {Pareschi, Lorenzo and Russo, Giovanni},\ndoi = {10.1007/s10915-004-4636-4},\nissn = {0885-7474},\njournal = {Journal of Scientific Computing},\nkeywords = {65c20,82d25,ams subject classification,high order shock capturing,\nhyperbolic systems with relaxation,kutta methods,runge,schemes,stiff,systems},\nmonth = oct,\nnumber = {1},\npages = {129--155},\ntitle = {{Implicit-Explicit Runge-Kutta Schemes and Applications to\nHyperbolic Systems with Relaxation}},\nurl = {http://www.springerlink.com/index/10.1007/s10915-004-4636-4},\nvolume = {25},\nyear = {2005}\n}\n\\end{verbatim}\n%\nThe \\emph{document type} is \\verb|article|, as denoted by the \\verb|@article|. There are many other possible, including books, reports, theses, unpublished, and many more. The \\emph{key} is \\verb|Pareschi2005|, to be cited \\verb|\\cite{Pareschi2005}| in the \\LaTeX\\ file. Some of the information included is required, but precisely what depends on the document type. For articles the minimum is the key, the author, the journal and the year. All other information \\emph{may} be used (if available).\n\nInside the \\LaTeX\\ document only two lines are required. For example, in \\verb|BasicLatexBibtex| the two lines are\n%\n\\begin{verbatim}\n\\bibliographystyle{plain}\n\\bibliography{nummeth}\n\\end{verbatim}\n%\nThe first controls the appearance of the bibliography; what order the references appear (e.g.\\ alphabetical or in citation order), what information is included, and so on. It also controls how the citations appear in the text (e.g.\\ author-date or numerical). The second line says that the references are stored in the \\verb|nummeth.bib| file. Multiple \\verb|bibtex| files can be referenced, separated by commas (e.g. \\verb|\\bibliography{file1,file2,file3}|).\n\nThe advantages of the \\verb|bibtex| database are clear.\n%\n\\begin{enumerate}\n\\item Reuse across multiple documents is easy.\n\\item Additional information is stored with the reference.\n\\item Changing styles is simple.\n\\item Errors can be corrected in a single place.\n\\end{enumerate}\n%\n\nSome disadvantages remain.\n%\n\\begin{enumerate}\n\\item The \\verb|bibtex| database format is difficult to maintain by hand.\n\\item Control over the appearance of the reference is less straightforward.\n\\item Producing a database from scratch is a lengthy and tedious process.\n\\end{enumerate}\n\n\\subsection{Constructing and maintaining a database}\n\\label{sec:maintaining}\n\nWhen starting you will build your own database from everything you read, and also inherit a database from your supervisor, group and office-mates. Merging disparate databases by hand, and typing all the details of references into a plain-text database, is a recipe for mistakes and a huge waste of time. Better tools include the following.\n\n\\subsubsection{Journal websites}\n\\label{sec:journals}\n\nMost published papers have a webpage through the journal, and many of these will export all of the reference information in a standard format. For \\verb|bibtex| this typically means the website sends you a plain text file which you can copy and paste into your database.\n\nIt is often the case that a little tweaking of the entry will be required -- frequently the article key is not memorable, and the appearance of special characters can be problematic. But this approach can save considerable time, as well as giving you information (DOI, URLs) that other \\LaTeX\\ tools can use.\n\n\\subsubsection{Endnote and similar}\n\\label{sec:endnote}\n\nMany people and groups use software such as \\href{http://www.endnote.com/}{Endnote} to maintain their bibliographical database. There are free tools to convert between database formats -- see, for example, the \\href{http://dret.net/bibconvert/}{ShaRef} service at \\verb|http://dret.net/bibconvert/|.\n\nThe advantages of packages like Endnote are their wide use (in certain fields), their tools for maintaining the database, and their tools for use with other word-processing packages such as Word. The conversion process will often require a little tweaking, as above.\n\n\\subsubsection{Cloud and social reference managers}\n\\label{sec:cloud}\n\nOnline reference managers are available and are, for basic services, often free. These services include the basic functions of desktop packages such as Endnote, but have two major additional advantages. Firstly, the database is stored online and so available to you anywhere, on any device. Secondly, the tools are frequently well integrated with journal websites. This means that saving a reference to the database is just a single button click.\n\nExamples include\n%\n\\begin{enumerate}\n\\item \\href{http://www.citeulike.org/}{CiteULike} at \\verb|http://www.citeulike.org/|\n\\item \\href{http://www.mendeley.com/}{Mendeley} at \\verb|http://www.mendeley.com/|\n\\item \\href{http://www.zotero.org/}{Zotero} at \\verb|http://www.zotero.org/|\n\\end{enumerate}\n%\nEach has their own internal database format and will export to other formats, such as \\verb|bibtex|, on demand.\n\nThe advantages of online reference managers for groups of collaborators and for web integration are obvious; it is definitely worth investigating such tools, and finding out which are standard in your field and group.\n\n\\subsection{Controlling the appearance}\n\\label{sec:appearance}\n\nUsually when writing a document there is a template to follow, and often that template will be prescriptive. For example, many journals provide \\LaTeX\\ style files to use, combined with \\verb|bibtex| style files as well. In these cases there is no need to control how the references appear.\n\nHowever, in certain cases (such as your thesis) you may wish for more control. There are three basic methods: using the original \\verb|bibtex| styles, using the \\verb|natbib| package, or using the \\verb|biblatex| package.\n\n\\subsubsection{Bibtex styles}\n\\label{sec:bibtex_styles}\n\nThe original \\verb|bibtex| package came with a small selection of styles, and a number of additional styles have been made publically available. Many can be found online -- \\href{http://www.cs.stir.ac.uk/~kjt/software/latex/showbst.html}{a sample list} can be found at \\verb|http://www.cs.stir.ac.uk/~kjt/software/latex/showbst.html|, and many others exist.\n\nIf you are interested in the style being approximately correct, this is usually sufficient.\n\n\\subsubsection{Natbib}\n\\label{sec:natbib_styles}\n\nThe \\verb|natbib| package contains additional citation commands, and additional software to build a style file that does exactly what you want. I would say it is now out of date, and \\verb|biblatex| is a better package, but it is still widely used.\n\nA few examples of the \\href{http://merkel.zoneo.net/Latex/natbib.php}{citation commands provided} include\n%\n\\begin{enumerate}\n\\item \\verb|\\citet{Jones90}|, producing ``Jones et al.\\ (1990)''\n\\item \\verb|\\citet[chap. 2]{Jones90}|, producing ``Jones et al.\\ (1990, chap.\\ 2)''\n\\item \\verb|\\citep{Jones90}|, producing ``(Jones et al.\\ 1990)''\n\\end{enumerate}\n%\nThe distinction is between \\emph{textual} (\\verb|\\citet|) and \\emph{parenthetical} (\\verb|citep|) citations.\n\nIn addition, \\verb|natbib| has tools for sorting and compressing multiple citations in a single cross-reference, for modifying the appearance of parentheses, for aliasing a citation (i.e.\\ replacing a key reference by ``Paper I'' throughout), and much more.\n\n\\subsubsection{Biblatex}\n\\label{sec:biblatex_styles}\n\nAll of the features mentioned above, and more, have been implemented in the \\verb|biblatex| package. This allows the use of standard \\LaTeX\\ macros and commands for controlling the layout and appearance of citations and the bibliography. The \\href{http://ctan.org/pkg/biblatex}{package description} can be found at \\verb|http://ctan.org/pkg/biblatex|, with \\href{http://mirror.ctan.org/macros/latex/contrib/biblatex/doc/biblatex.pdf}{full documentation} at\n\\verb|http://mirror.ctan.org/macros/latex/contrib/biblatex/doc/biblatex.pdf|.\n\nThere are changes that can be made at the detail level when updating the \\verb|biblatex|; see, for example, the \\href{http://tex.stackexchange.com/questions/5091/what-to-do-to-switch-to-biblatex}{comments at StackExchange} at \\\\ \\verb|http://tex.stackexchange.com/questions/5091/what-to-do-to-switch-to-biblatex|. This allows you to take advantage of the full features of \\verb|biblatex|.\n\n\\end{chapter}\n", "meta": {"hexsha": "1ff1f00d9ae6b3b3c9a5aac200edaae35b8a7e7d", "size": 32764, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "latex_chapter.tex", "max_stars_repo_name": "LaGuer/maths-with-python", "max_stars_repo_head_hexsha": "7bbba1e1e95d3c930a41405ebbb0dcd6735e5009", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 70, "max_stars_repo_stars_event_min_datetime": "2015-06-26T21:14:03.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-20T02:36:02.000Z", "max_issues_repo_path": "latex_chapter.tex", "max_issues_repo_name": "QuantumNovice/maths-with-python", "max_issues_repo_head_hexsha": "9ca8054462e84045353a1a8f7158a87760a93cc8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 19, "max_issues_repo_issues_event_min_datetime": "2015-08-19T06:39:42.000Z", "max_issues_repo_issues_event_max_datetime": "2017-03-04T12:36:13.000Z", "max_forks_repo_path": "latex_chapter.tex", "max_forks_repo_name": "QuantumNovice/maths-with-python", "max_forks_repo_head_hexsha": "9ca8054462e84045353a1a8f7158a87760a93cc8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 49, "max_forks_repo_forks_event_min_datetime": "2015-08-21T02:42:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-03T14:20:08.000Z", "avg_line_length": 68.8319327731, "max_line_length": 1072, "alphanum_fraction": 0.7730435844, "num_tokens": 8066, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.31742626558767584, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.15375496127708685}} {"text": "\\SetPicSubDir{ch-Exp}\n\n\\chapter{Experimenting with Other Random Models}\n\\label{ch:exp}\n\\vspace{2em}\n\nA method similar to the 3-phase method in DHAM has been adopted and used to show existential/constructive results in some other models of random digraphs. Now that we are familiar with the DHAM algorithms, we shall attempt to inpnut graphs from some of these models, and see how DHAM performs on them. We shall try to look for patterns in terms of accuracy, runtime, or number of attempts in the following models.\n\n\\section{$k$-in, $k$-out Graphs}\n\\subsection{Graph Generation}\nThe way $D_{k-in, k-out}$ is defined, it is pretty straightforward to generate instances of this graph. At every vertex $u\\in V_n$, we simply have to generate 2 lists of $k$ vertices each (as in-neighbours and out-neighbours), sampling uniformly at random from the set of all vertices. Now we add an edge from $u$ to each out-neighbour and an edge from each in-neighbour to $u$.\n\\subsection{Observations}\nCooper and Frieze \\cite{cooper:kinout} have shown that $D_{2-in, 2-out}$ is Hamiltonian with High Probability, using a 3-phase analysis. \n\n\\begin{description}\n\\item[Phase 1] Show that $D_{2-in, 2-out}$ contains a permutation digraph, $\\Pi$ of size at most $2\\log n$.\n\\item[Phase 2] Increase the minimum cycle length in $\\Pi$ to $n_0 = \\Big\\lceil \\frac{1000n}{\\log n} \\Big\\rceil$.\n\\item[Phase 3] Convert the Phase 2 permutation digraph to a Hamilton Cycle.\n\\end{description}\nIt is interesting to note that the proof follows a very similar outline to the one for Random Digraphs $D_{n, m}$, showing the existence of a Hamiltonian Cycle but, a similar bound on the runtime has not been obtained. It is still not known if there is a polynomial time algorithm to find the same.\n\n\\begin{figure}[ht]\n\n\\begin{subfigure}{\\textwidth}\n\\centering\n\\includegraphics[width=0.9\\linewidth, height=7cm]{pic/ch-Exp/kin_time.png}\n\\caption{Runtime plot of $D_{k-in, k-out}$}\n\\label{fig:kin:time}\n\\end{subfigure}\n\\begin{subfigure}{\\textwidth}\n\\centering\n\\includegraphics[width=0.9\\linewidth, height=7cm]{pic/ch-Exp/kin_accr.png}\n\\caption{Probability of finding a Hamilton cycle in $D_{k-in, k-out}$}\n\\label{fig:kin:accr}\n\\end{subfigure}\n\n\\caption{DHAM on $D_{k-in, k-out}$}\n\\label{fig:kin:plots}\n\\end{figure}\n\nWe try to test if DHAM might be successful in finding this Hamiltonian cycle in polynomial time.\nFrom \\autoref{fig:kin:time} we can see that (to the extend of n that is feasible for testing)\nthat runtime grows more or less the same as on $D_{n, m}$. This is suggestive of the fact that it might be possible to give a polynomial bound the runtime of 3-phase method on this class of graphs. \n\nWe also see some spikes in the runtime and also a lower probability of finding the Hamiltonian cycle in \\autoref{fig:kin:accr} for $D_{2-in, 2-out}$, even though we know that this graph is Hamiltonian with high probability. This phenomenon is observed again in the next model we take a look at and seems to suggest that the algorithm does not run as well on sparse graphs. \n\n\n\\section{$k$-regular Graphs}\n\\subsection{Graph Generation}\nTo generate a $k$-regular digraph, we need to make sure that the in-degree and the out-degree of each vertex are k. But simply choosing $2k$ neighbours independently like for $D_{k-in, k-out}$ does not work, since we cannot guarantee that exactly $k$ other vertices will also be in-neighbours.\n\nInstead, we notice that in a permutation digraph, each vertex has exactly $1$ in/out neighbour. We use this fact and take the union of k random permutation digraphs (which have no mutual overlap) to obtain a $k$-regular digraph.\n\\subsection{Observations}\nTheoretically, it has been shown that $D_{n, r}$ is Hamiltonian with high probability for $r \\ge 3$ \\cite{cooper:kreg}. The proof for this is again based on a 3-phase method and is very similar to that for $D_{k-in, k-out}$, since large $k$-regular graphs look very similar to $D_{k-in, k-out}$ graphs. Hence it is not very surprising that their runtime plots look similar. The runtime very closely follows the same $n^{1.5}$ curve that $D_{n, m}$ had, suggesting that it might be possible to give a polynomial bound for DHAM on this class of graphs too.\n\nOnce again we notice the spikes in runtime and the lower probabilities of success for $k = 2, 3$ in \\autoref{fig:kreg:accr}, reiterating the idea that DHAM performs poorly on sparse graphs. We can trace this bad performance to the first phase of the algorithm, where we construct a subgraph of average degree 10. The bipartite matching that follows depends on the degree of vertices in this subgraph, and a lower degree limits the success probability of the matching, and hence bottle-necking DHAM. \n\n\\begin{figure}[ht]\n\n\\begin{subfigure}{\\textwidth}\n\\centering\n\\includegraphics[width=0.9\\linewidth, height=7cm]{pic/ch-Exp/kreg_time.png}\n\\caption{Runtime plot of $D_{n, r}$}\n\\label{fig:kreg:time}\n\\end{subfigure}\n\\begin{subfigure}{\\textwidth}\n\\centering\n\\includegraphics[width=0.9\\linewidth, height=7cm]{pic/ch-Exp/kreg_accr.png}\n\\caption{Probability of finding a Hamilton cycle in $D_{n, r}$}\n\\label{fig:kreg:accr}\n\\end{subfigure}\n\n\\caption{DHAM on $D_{n, r}$}\n\\label{fig:kreg:plots}\n\\end{figure}\n\\subsection{Closer look at sparse graphs}\nSince we notice the DHAM performs poorly on sparse graphs, but still works just fine at value below the mentioned degree $10$, in the original paper, we take a closer look to see above what value of $r$, does DHAM find a cycle in $D_{n, r}$, with high probability and low number of attempts.\n\n\\begin{figure}[ht]\n\n\\begin{subfigure}{\\textwidth}\n\\centering\n\\includegraphics[width=0.9\\linewidth, height=7cm]{pic/ch-Exp/sprc_accr.png}\n\\caption{Probability of Finding a cycle in sparse $D_{n, r}$}\n\\label{fig:kreg:spaccr}\n\\end{subfigure}\n\\begin{subfigure}{\\textwidth}\n\\centering\n\\includegraphics[width=0.9\\linewidth, height=7cm]{pic/ch-Exp/sprc_atmp.png}\n\\caption{Average no. of attempts to find the cycle}\n\\label{fig:kreg:spatmp}\n\\end{subfigure}\n\n\\caption{$D_{n, r}$ with low values of $r$}\n\\label{fig:kreg:sparse}\n\\end{figure}\n\nFrom \\autoref{fig:kreg:sparse} we see that for $r \\ge 6$, the probability of finding a cycle is almost at 1, and the number of attempts also stabilises around 5. \n\n\\section{Random Tournaments}\n\\subsection{Graph Generation}\nWe can generate every possible pair of vertices, using a nested loop, and assign a direction to every edge uniformly at random to obtain the desired tournament.\n\\subsection{Observations}\nRandom Tournaments have been shown to have $\\delta = min(\\delta^+, \\delta^-)$ edge disjoint Hamiltonian cycles\\cite{kuhn:tourna}. Though the proof does not rely on the 3-phase method, DHAM using that method, still does find cycles in such graphs (\\autoref{fig:tourna:time}), with high probability (probability 1 in our tests).\n\nTournaments grow in size as a function of $n^2$, limiting the range of $n$ feasible for testing. From the range of sizes that we tested on it is not possible to comment on the runtime on these graphs (since the implementation overhead might be affecting the runtime more than the algorithm itself). But we do notice that every graph generated returned a valid Hamiltonian cycle, which seems to suggest that the probability of success of the 3-phase method is also very high on random tournaments.\nAlso, since tournaments are dense graphs, we do not run into the bottlenecks that we observed in the last 2 models.\n\n\\begin{figure}[ht]\n\n\\centering\n\\includegraphics[width=0.9\\linewidth,height=7cm]{pic/ch-Exp/tourna_time.png}\n\\caption{Runtime plot of Tournaments}\n\\label{fig:tourna:time}\n\n\\end{figure}\n\n\\section{Random $n$-lifts of complete digraph $K_h$}\n\\subsection{Graph Generation}\nWe first create the complete digraph, $K_h$ on $h$ vertices. Now, we start constructing a new digraph $D$, with $h \\times n$ vertices, with the range of vertices $[i \\times n, i \\times (n+1) - 1]$ corresponding to each vertex $i\\in V(K_h)$. \n\nNow, for each edge $(u, v) \\in E(K_h)$, we construct arrays $U$ \\& $V$, of the vertices corresponding to $u, v \\in V(K_h)$. After shuffling the arrays, we obtain a random matching as $\\forall i] (-0.2,0,0) -- (Ex) node[anchor=west]{$x~\\textrm{(east)}$};\n \\draw[thick, ->] (0,-0.2,0) -- (Ey) node[anchor=west]{$y~\\textrm{(north)}$};\n \\draw[thick, ->] (0,0,0) -- (Ez) node[anchor=south]{$z~\\textrm{(up)}$};\n\n \\tdplotsetcoord{P}{1}{45.57}{60};\n \\draw[thick, ->, color=red] (O) -- (P) node[anchor=south west]{sensor};\n \\draw[dashed, color=red] (O) -- (Pxy);\n \\draw[dashed, color=red] (P) -- (Pxy) node[midway,anchor=west]{$\\textrm{umu} = 0.7$};\n\n \\tdplotdrawarc[color=red]{(O)}{0.3}{90}{60}{xshift=0.3cm,anchor=north west}{$\\textrm{phi} = 30\\degree$};\n\\end{tikzpicture}\n\\caption{Sensor coordinate specification (\\codeidx{umu} and \\codeidx{phi}). The red arrow is pointing into the sensor, thus a sensor with positive umu values is looking downwards.}\n\\label{fig_sensor_coordinates}\n\\end{figure}\nGenerally, the sensor orientation is specified using the \\codeidx{umu} and \\codeidx{phi} input options as shown in figure~\\ref{fig_sensor_coordinates}.\nThe location of the sensor is given in the same $x$, $y$, $z$ coordinate system by use of the option \\codeidx{mc\\_sensorposition}.\nThe position of the sun is specified either using \\codeidx{latitude}, \\codeidx{lognitude} and \\codeidx{time} or using \\codeidx{sza} and \\codeidx{phi0}.\nIn the latter case, the angles are (maybe depending on the mindset of the reader), defined slightly different as shown in figure~\\ref{fig_sun_coordinates}.\n\n\\begin{figure}[h!]\n\\centering\n\\tdplotsetmaincoords{70}{20}\n\\begin{tikzpicture}[scale=5,tdplot_main_coords]\n\n \\coordinate (O) at (0,0,0);\n \\coordinate (Ex) at (1,0,0);\n \\coordinate (Ey) at (0,1,0);\n \\coordinate (Ez) at (0,0,1);\n\n\n \\draw[thick, ->] (-0.2,0,0) -- (Ex) node[anchor=west]{$x~\\textrm{(east)}$};\n \\draw[thick, ->] (0,-0.2,0) -- (Ey) node[anchor=west]{$y~\\textrm{(north)}$};\n \\draw[thick, ->] (0,0,0) -- (Ez) node[anchor=south]{$z~\\textrm{(up)}$};\n\n \\tdplotsetcoord{P}{1}{30}{210};\n \\draw[thick, ->, color=orange] (O) -- (P) node[anchor=south east]{sun};\n \\draw[dashed, color=orange] (O) -- (Pxy);\n \\draw[dashed, color=orange] (P) -- (Pxy);\n\n\t\\tdplotsetthetaplanecoords{210};\n \\tdplotdrawarc[tdplot_rotated_coords, color=orange]{(O)}{0.5}{0}{30}{xshift=0.7cm,anchor=west}{$\\textrm{sza} = 30\\degree$}\n\n \\tdplotdrawarc[color=orange]{(O)}{0.15}{270}{210}{yshift=-0.2cm,anchor=north}{$\\textrm{phi0} = 60\\degree$};\n\\end{tikzpicture}\n\\caption{Sun coordinate specification (sza and phi0). The orange arrow is pointing into the sun.}\n\\label{fig_sun_coordinates}\n\\end{figure}\n\n\n\n\\begin{figure}[h!]\n\\centering\n\\tdplotsetmaincoords{70}{20}\n\\pgfmathsetmacro{\\thetavec}{20}\n\\pgfmathsetmacro{\\phivec}{320}\n\\begin{tikzpicture}[scale=5,tdplot_main_coords]\n\n \\coordinate (O) at (0,0,0);\n \\coordinate (Ex) at (1,0,0);\n \\coordinate (Ey) at (0,1,0);\n \\coordinate (Ez) at (0,0,1);\n\n\n \\draw[thick, ->] (-0.2,0,0) -- (Ex) node[anchor=west]{$x~\\textrm{(east)}$};\n \\draw[thick, ->] (0,-0.7,0) -- (Ey) node[anchor=west]{$y~\\textrm{(north)}$};\n \\draw[thick, ->] (0,0,-0.7) node[anchor=north]{nadir} -- (Ez) node[anchor=south]{$z~\\textrm{(up, zenith)}$};\n\n \\tdplotsetcoord{P1}{0.6}{60}{160}\n \\tdplotsetcoord{P2}{0.6}{60}{100}\n \\tdplotsetcoord{P3}{0.6}{100}{100}\n \\tdplotsetcoord{P4}{0.6}{100}{160}\n \\tdplotsetcoord{P3a}{0.6}{90}{100}\n \\tdplotsetcoord{P3b}{0.7}{90}{100}\n\n\t\\draw[dashed,color=orange] (O) -- (P1) node[anchor=east]{$(0,N_y-1)$};\n\t\\draw[dashed,color=orange] (O) -- (P2) node[xshift=0.5cm,anchor=west]{$(N_x-1,N_y-1)$};\n\t\\draw[dashed,color=orange] (O) -- (P3) node[xshift=0.5cm,anchor=west]{$(N_x-1,0)$};\n\t\\draw[dashed,color=orange] (O) -- (P4) node[xshift=-1.2cm,anchor=north east]{$(0,0)$};\n\t\\draw[dashed,color=black] (P3a) -- (P3b);\n\n \\tdplotdrawarc[color=black,dotted]{(0,0,0)}{0.6}{160}{-90}{}{}\n \\tdplotdrawarc[color=orange]{(P1z)}{0.519}{100}{160}{}{}\n \\tdplotdrawarc[dashed,color=blue]{(P1z)}{0.519}{95}{100}{}{}\n \\tdplotdrawarc[color=orange]{(P3z)}{0.59088}{100}{160}{}{}\n\n \\tdplotdrawarc[color=black,dashed]{(0,0,0)}{0.6}{270}{160}{xshift=0.1cm,anchor=west}{$\\phi_1 = 110\\degree$}\n \\tdplotdrawarc[color=black,dashed]{(0,0,0)}{0.7}{270}{100}{anchor=east}{$\\phi_2 = 170\\degree$}\n \\tdplotsetthetaplanecoords{100}\n \\tdplotdrawarc[tdplot_rotated_coords,color=orange]{(0,0,0)}{0.6}{60}{100}{}{}\n %\\tdplotdrawarc[tdplot_rotated_coords,dotted,color=black]{(0,0,0)}{0.6}{0}{360}{}{}\n %\\tdplotdrawarc[tdplot_rotated_coords,dashed,color=black]{(0,0,0)}{0.6}{100}{90}{}{}\n \\tdplotsetthetaplanecoords{155}\n \\tdplotdrawarc[tdplot_rotated_coords,dashed,color=blue]{(0,0,0)}{0.6}{100}{180}{anchor=east}{$\\theta_1 = 80\\degree$}\n \\tdplotsetthetaplanecoords{95}\n \\tdplotdrawarc[tdplot_rotated_coords,dashed,color=blue]{(0,0,0)}{0.6}{60}{180}{anchor=west}{$\\theta_2 = 120\\degree$}\n \\tdplotsetthetaplanecoords{160}\n \\tdplotdrawarc[tdplot_rotated_coords,color=orange]{(0,0,0)}{0.6}{60}{100}{}{}\n %\\tdplotdrawarc[tdplot_rotated_coords,dotted,color=black]{(0,0,0)}{0.6}{0}{360}{}{}\n %\\tdplotdrawarc[tdplot_rotated_coords,dashed,color=black]{(0,0,0)}{0.6}{80}{90}{}{}\n\n\\end{tikzpicture}\n \\caption{Panorama coordinates for the option \\codeidx{mc\\_panorama\\_alignment} \\code{zenith} (default). The camera is located at the coordinate system origin. The image is recorded on a spherical shell inside the orange box, which is behind the origin. The boundaries of this box are given by the parameters $\\phi_1$, $\\phi_2$, $\\theta_1$, $\\theta_2$ to \\codeidx{mc\\_panorama\\_view}. $\\phi_1$ and $\\phi_2$ are measured in the $x-y$-plane, beginning in the south. $\\theta_1$ and $\\theta_2$ measure the \"latitude\" where nadir is 0. The coordinates given in orange show the $(x, y)$ coordinates of the resulting image. The $(x, y)$ coordinates thus correspond to $(\\theta, \\phi)$ coordinates.}\n\\label{fig_panorama_coords_zenith}\n\\end{figure}\n\n\n\\begin{figure}[h!]\n\\centering\n\\tdplotsetmaincoords{70}{20}\n\\pgfmathsetmacro{\\thetavec}{36.87}\n\\pgfmathsetmacro{\\phivec}{-50}\n\\begin{tikzpicture}[scale=5,tdplot_main_coords]\n\n \\coordinate (O) at (0,0,0);\n \\coordinate (Ex) at (1,0,0);\n \\coordinate (Ey) at (0,1,0);\n \\coordinate (Ez) at (0,0,1);\n\n\n \\draw[thick, ->] (-0.1,0,0) -- (Ex) node[anchor=west]{$x~\\textrm{(east)}$};\n \\draw[thick, ->] (0,-0.6,0) -- (Ey) node[anchor=west]{$y~\\textrm{(north)}$};\n \\draw[thick, ->] (0,0,0) -- (Ez) node[anchor=south]{$z~\\textrm{(up)}$};\n\n \\tdplotsetcoord{P}{0.6}{\\thetavec}{\\phivec}\n \\tdplotsetcoord{Q}{0.6}{53.13}{130}\n \\draw[dashed, color=blue] (P) -- (Pxy) node[near start,anchor=west]{$\\textrm{umu} = -0.8$};\n \\draw[dashed, color=blue] (O) -- (Pxy);\n \\tdplotdrawarc[color=red]{(O)}{0.48}{270}{130}{xshift=0.3cm,anchor=south east}{$\\textrm{phi} = 140\\degree$};\n \\draw[dashed, color=red] (Q) -- (Qxy);\n\n \\tdplotsetrotatedcoords{\\phivec}{\\thetavec}{0}\n\n \\draw[tdplot_rotated_coords, thick, ->, color=magenta] (0,-0.1,0) -- (0,0.6,0) node[anchor=south east]{$x'$};\n \\draw[tdplot_rotated_coords, thick, ->, color=red] (0.4,0,0) -- (-0.6,0,0) node[anchor=north west]{$y'$};\n \\draw[tdplot_rotated_coords, thick, -, color=red] (0.6,0,0) -- (0.53,0,0);\n \\draw[tdplot_rotated_coords, thick, ->, color=blue] (0,0,-0.6) -- (0,0,0.6) node[anchor=south east]{$z'$};\n\n \\tdplotdrawarc[tdplot_rotated_coords,color=black,dotted]{(0,0,0)}{0.6}{0}{345}{}{};\n \\tdplotdrawarc[tdplot_rotated_coords,color=black,dashed]{(0,0,0)}{0.6}{0}{-15}{anchor=north west}{$\\phi_1=15\\degree$};\n \\tdplotdrawarc[tdplot_rotated_coords,color=black,dashed]{(0,0,0)}{0.8}{0}{-45}{anchor=north west}{$\\phi_2=45\\degree$};\n\n \\tdplotdrawarc[tdplot_rotated_coords,color=orange]{(0,0,0.1042)}{0.59088}{-15}{-45}{}{}\n \\tdplotdrawarc[tdplot_rotated_coords,color=orange]{(0,0,-0.1042)}{0.59088}{-15}{-45}{}{}\n\n \\tdplotsetrotatedthetaplanecoords{0}\n \\tdplotdrawarc[tdplot_rotated_coords,color=black,dotted]{(0,0,0)}{0.6}{0}{360}{}{}\n \\tdplotsetrotatedthetaplanecoords{-15} %note that this changes the rotated frame already\n \\tdplotdrawarc[tdplot_rotated_coords,color=orange]{(0,0,0)}{0.6}{80}{100}{}{}\n \\tdplotdrawarc[tdplot_rotated_coords,dashed,color=blue]{(0,0,0)}{0.6}{180}{100}{yshift=1cm,anchor=west}{$\\theta_1=80\\degree$}\n \\tdplotsetrotatedthetaplanecoords{-30}\n \\tdplotdrawarc[tdplot_rotated_coords,color=orange]{(0,0,0)}{0.6}{80}{100}{}{}\n \\tdplotsetrotatedthetaplanecoords{-5}\n \\tdplotdrawarc[tdplot_rotated_coords,dashed,color=blue]{(0,0,0)}{0.6}{180}{80}{yshift=0.5cm,anchor=east}{$\\theta_2=100\\degree$}\n\n\\end{tikzpicture}\n \\caption{Panorama corrdinates for \\codeidx{mc\\_panorama\\_alignment} \\code{mu}. In \\emph{mu} aligned mode, the panorama is taken as in \\emph{zenith}-mode, however the whole coordinate system is rotated using the parameters \\codeidx{umu} and \\codeidx{phi} yielding the new coordinates $x'$, $y'$, $z'$. If $\\textrm{umu} = -1$ and $\\textrm{phi} = 180\\degree$, the coordinates are exactly the same as in \\emph{zenith} mode. Be aware that if \\codeidx{umu} is $1$ or $-1$, the value of \\codeidx{phi} is not accepted and the system behaves as if $\\textrm{phi} = 180\\degree$. In this case, the equivalent rotation can be achieved by $\\phi_1$ and $\\phi_2$.}\n\\label{fig_panorama_coords_mu}\n\\end{figure}\n\nIf panoramic images are calculated, the sensor specification is extended by a definition for the field of view of the camera an the option \\codeidx{mc\\_panorama\\_view}.\nThe behavior of this specification can be changed by the \\codeidx{mc\\_panorama\\_alignment}.\nIn the default mode (\\codeidx{mc\\_panorama\\_alignment} \\code{zenith}), \\code{umu} and \\code{phi} are ineffective.\nThe view specificatiion behaves as described in figure~\\ref{fig_panorama_coords_zenith}.\nIf \\codeidx{mc\\_panorama\\_alignment} \\code{mu} is activated, the user can basically rotate the camera.\nThe angles are defined as in figure~\\ref{fig_panorama_coords_mu}.\n\n\\subsubsection{Three-dimensional clouds}\n\nThe options \\codeidx{wc\\_file 3D}\nand \\codeidx{ic\\_file 3D} may be used to define 3D water and ice\ncloud properties respectively. The model atmosphere may contain both 3D \n(defined in a \\code{wc\\_file/ic\\_file 3D}) and 1D clouds (defined in a \n\\code{wc\\_file/ic\\_file 1D}), but for obvious reasons not in the same layer. The format\nof the files is explained in section~\\ref{sec:uvspec_options}. \n\nThe conversion from microphysical to optical properties \nis done identically for 1D and 3D clouds and is defined \nby the options \\codeidx{wc\\_properties} and \\codeidx{ic\\_properties}. All\npossible settings for \\code{wc\\_properties} and \\code{ic\\_properties}\nhave been implemented in MYSTIC (e.g., hu, mie, yang, HEY, baum ...).\nClouds can be defined eiter as ASCII or as netCDF files.\n\n\\paragraph{ASCII}\nThe following example shows the easiest possible 3D \ncloud file which defines a checkerboard grid of clouds:\n\\begin{Verbatim}[fontsize=\\footnotesize, frame=single, samepage=true]\n 2 2 5 3\n 1.0 1.0 0 1 2 3 4 5 \n\n 1 1 2 0.1 10\n 2 2 2 0.1 10\n\\end{Verbatim}\nFor the layer between 1 and 2 km a 3D cloud is defined with liquid water\ncontent 0.1 $g/m^3$ and effective radius 10 $\\mu$m for horizontal \nboxes (1,1) and (2,2). Boxes (1,2) and (2,1) are cloudless. The result are\ncubic clouds with a volume of 1x1x1~km$^3$. The microphysical properties are\nconverted to optical properties according to \\code{wc\\_properties}. \n\n\\paragraph{netCDF}\nIf the provided cloud file is a netCDF instead of an ASCII file, this will be\ndetected automatically. The netCDF file must have the following structure:\n\\begin{Verbatim}[fontsize=\\footnotesize, frame=single, samepage=true]\nnetcdf cloud {\ndimensions:\n\tny = 2 ;\n\tnx = 2 ;\n\tnz = 1 ;\n\tnz_lev = 2 ;\nvariables:\n\tdouble lwc(ny, nx, nz) ;\n\tdouble z(nz_lev) ;\n\tdouble reff(ny, nx, nz) ;\n\n// global attributes:\n\t:cldproperties = 3 ;\n\t:dx = 1. ;\n\t:dy = 1. ;\n}\n\\end{Verbatim}\nThe order of the dimensions is important, and the size of \\code{nz\\_lev} must be\nexactly \\code{nz + 1}. The \\code{cldproperties} attribute is equal to the flag\nin the ASCII format. The variable names change for different \\code{cldproperties}\naccording to the following table:\n\\begin{itemize}\n \\item{1: \\quad \\code{ext g1 ssa}}\n \\item{2: \\quad \\code{ext reff}}\n \\item{3: \\quad \\code{lwc reff}}\n\\end{itemize}\n\n\\subsubsection{Two-dimensional surface albedo}\n\nA 2D surface albedo may be defined using the option\n\\codeidx{mc\\_albedo\\_file}. The format of the file is explained in\nsection~\\ref{sec:uvspec_options}. \n\n\\subsubsection{Topography}\n\nA 2D elevation may be defined using the option \n\\codeidx{mc\\_elevation\\_file}. The ASCII format is explained in\nsection~\\ref{sec:uvspec_options}. For the netcdf format please refer\nto \\file{README.MC}. \n\nCaution:\n\\begin{itemize}\n\\item To avoid confusion, do not specify an \\code{altitude} different\n from 0 in the uvspec input file.\n\\item There may be problems if the 2D surface hits 0 \n (more testing required). Use 0.001 as lowest altitude.\n\\item The elevation file MUST BE PERIODIC\n\\end{itemize}\n\nBetween the grid points, the surface is interpolated \nbilinearely: \n\\begin{equation}\n z(x,y) = a + bx + cy + dxy\n\\end{equation}\nwhere $z$ is the altitude and the coefficients $a$, $b$, $c$, and $d$\nare determined from \nthe altitudes specified at the four corners of each pixel.\nSlant surfaces are treated as they should be; e.g., photons\nmay be reflected downward at snow-covered mountain sides.\n\n\\subsubsection{Bidirectional reflectance distribution function}\nMYSTIC allows different homogenous or 2D-inhomogeneous BRDFs. The \nimplementation of the different BRDFs is rather heterogeneous, \nas were the requirements when each of them was first implemented.\nPlease note that BRDFs currently do not work together with topography. The \nvery simple reason for that is in structured terrain reflection \npolar angles larger than 90 degree are possible for which the \nexisting parameterizations do not provide data. The following \nparameterizations are included:\n\\begin{itemize}\n\\item Water BRDF by \\citet{cox54a,cox54b}; currently only homogeneous; switched \n on with \\codeidx{brdf\\_cam u10}, ... like in the 1D case\n\\item AMBRALS (Algorithm for Modeling[MODIS] Bidirectional Reflectance\n Anisotropies of the Land Surface; \\citet{wanner97}), see also\n \\url{http://i3rc.gsfc.nasa.gov/phase3/brasil/phase3_step1_brasil.htm}.\n AMBRALS is three-parameter BRDF fit for vegetated and non-vegetated surfaces.\n A \\codeidx{mc\\_ambrals\\_file} may be specified which contains the \n 3 parameters for each surface pixel. The format is like \n the format of 2D surface albedo file, except that each data line \n contains (iso, vol, geo) instead of only one albedo value.\n Obviously, wavelength-dependent AMBRALS BRDFs are not \n possible at present.\n\\item RPV \\citep{rahman93a}, a three parameter \n fit for vegetated and non-vegetated surfaces. RPV is currently the \n most flexible surface description in MYSTIC as it is currently \n the only way to define a wavelength-dependent 2D BRDF. \n Two different ways exist to define an RPV BRDF:\n \\begin{itemize}\n \\item 1D, using the options \\codeidx{brdf\\_rpv k} ... like in the 1D case\n \\item using \\codeidx{mc\\_rpv\\_file} and \\codeidx{mc\\_rpv\\_type}.\n The first is a RPV\n type for each surface pixel; type is simply a label like \n \"Grass\" or \"1\" or whatever. For each of these types,\n \\code{mc\\_rpv\\_type} must have an entry which connects the type to\n a file which contains wavelength-dependent RPVs. Sounds\n complicated but is a very efficient way to define a\n wavelength-dependent 2D RPV. Label ``CaM'' is reserved for Cox and Munk \n and invokes the Cox and Munk ocean BRDF for the respective pixel. Thus\n it is possible to combine land and ocean BRDFs.\n \\end{itemize}\n\\item For calculations including polarization the option\n \\codeidx{bpdf\\_tsang\\_u10} is available which calculates polarized\n bidirectional reflection from water surfaces. \n\\end{itemize}\n}\n\n\\subsubsection{MYSTIC output}\n\n{\\sl uvspec} will print its output (horizontally averaged \nirradiance and actinic flux) usually to stdout. MYSTIC provides \nseveral additional output \nfiles. We have to distinguish two classes of output: \nMonochromatic and spectral output where the latter can be recognized \nby the extension ``.spc''. Monochromatic output files\n\n\\begin{itemize}\n\\item mc.flx - irradiance, actinic flux at levels\n\\item mc.rad - radiance \n\\item mc.abs - absorption/emission\n\\item mc.act - actinic flux, averaged over layers\n\\end{itemize} \n\nare generated only for the case of a calculation where MYSTIC is called \nonly once. That is, a monochromatic calculation without subbands introduced \nby \\code{mol\\_abs\\_param}. They contain ``plain'' MYSTIC output, without\nconsideration of extraterrestrial irradiance, sun-earth-distance, spectral\nintegration, etc. As such they are mainly interesting for MYSTIC developers\nor for users interested in artificial cases and photon statistics since \nthey are as close as possible to the photon statistics of MYSTIC: e.g. \nthe ``irradiance'' in these files is basically the number of photons arriving\nat the detector divided by the number of photons traced. In addition to the \naverage, a standard deviation of the result can be calculated online which is \nstored in ``.std''. \n\nFor most real-world applications the user will prefer the ``.spc'' files\n\n\\begin{itemize}\n \\item mc.flx.spc - spectral irradiance, actinic flux at levels\n \\item mc.rad.spc - spectral radiance at levels\n \\item ...\n\\end{itemize}\n\nIn contrast to the monochromatic files which are transmittances (E/E0, L/E0,\n...) the data in \".spc\" is \"fully calibrated\" output, as for all other\nsolvers. \"fully calibrated\" means multiplied with the extraterrestrial \nirradiance, corrected for the Sun-Earth distance, integrated/summed\nover wavelength, etc. Please be aware that such a calculation might require\na lot of memory because output is stored as a function of x, y, z, and\nwavelength (and possibly polarization, if you switched on \\code{mc\\_polarisation}).\nE.g. a comparatively harmless \"mol\\_abs\\_param kato2\" calculation with an sample grid of 100x100 pixels\nat 10 altitudes would imply about 100x100x10x148 = 14,800,000 (Nx$\\cdot$Ny$\\cdot$Nz$\\cdot$Nlambda) grid points. Depending \non the output chosen (irradiance, radiance, ...) up to six floating \npoint numbers need to be stored which amounts to 360 MBytes. Depending \non the post-processing in {\\sl uvspec}, this memory may actually be used \ntwice which then would be 720 MBytes. \n\n\\begin{description}\n\\item[mc.flx / mcNN.flx] \n The output file \\code{mc.flx} contains the irradiance\n at the surface defined by elevation file. Note that\n this output is {\\bf not} for $z=0$, but for the actual 2D surface:\n \\begin{Verbatim}[fontsize=\\footnotesize, frame=single, samepage=true]\n 500 500 0 0.325889 0 0 0.441766 0\n 500 1500 0 0.191699 0 0 0.267122 0\n 500 2500 0 0.210872 0 0 0.420268 0\n \\end{Verbatim}\n The columns are:\n \\begin{enumerate}\n \\item x [m] (pixel center)\n \\item y [m] (pixel center)\n \\item direct transmittance\n \\item diffuse downward transmittance\n \\item diffuse upward transmittance\n \\item direct actinic flux transmittance\n \\item diffuse downward actinic flux transmittance\n \\item diffuse upward actinic flux transmittance\n \\end{enumerate}\n The transmittance is defined as irradiance devided by the extraterrestrial irradiance.\n It is not corrected for Sun-Earth-Distance.\n\n Note that even for an empty atmosphere, the transmittance\n would not be 1 but cos(SZA), due to the slant incidence of the radiation. \n \n The output files \\code{mcNN.flx} contain the irradiances\n at different model levels - one for each \\code{zout}. \\code{NN} is the\n number of the output level counted from the bottom (ATTENTION: Levels are\n counted from 0 here!). The file format is the same as in \\code{mc.flx}.\n\n (If interested in surface quantities, please use the irradiance data at the\n surface from \\code{mc.flx}, not from \\code{mc00.flx}; the data from \n \\code{mc00.flx} or whatever layer coincides with the \n surface may be wrong for technical reasons).\n\n\\item[mc.rad / mcNN.rad] \n The output file \\code{mc.rad} contains the radiance \n at the surface defined by \\code{elevation\\_file}. Note that\n this output is {\\bf not} for $z=0$, but for the actual 2D surface:\n \\begin{Verbatim}[fontsize=\\footnotesize, frame=single, samepage=true]\n 500 500 45 270 0.0239094 0 0.0623305 0.063324\n 500 1500 45 270 0.0239094 0 0.0602891 0.063156\n \\end{Verbatim}\n The columns are:\n \\begin{enumerate}\n \\item x [m] (pixel center)\n \\item y [m] (pixel center)\n \\item viewing zenith angle [deg]\n \\item viewing azimuth angle [deg]\n \\item aperture solid angle [sterad]\n \\item direct radiance component\n \\item diffuse radiance component\n \\item \"escape\" radiance \n \\end{enumerate}\n For almost all applications you may safely ignore the ``direct'' and\n ``diffuse'' radiance components and use only the escape radiance. If the \n latter is 0 then you probably forgot to switch on \\code{mc\\_escape}.\n The \"escape\" radiance is the radiance \"measured\" by an ideal\n instrument with 0$^\\circ$ opening angle. It is only calculated \n when \\codeidx{mc\\_escape} is selected and it usually converges \n much faster than the \"cone sampled\" radiance in column 7. \n It is recommended to always use \\code{mc\\_escape} for radiance\n calculations. For the ``direct'' and ``diffuse'' radiance, photons\n falling into the aperture are counted. This might be an option for \n instruments with a very large aperture only because otherwise the result\n is noisy. \n\n The output files \\code{mcNN.rad} contain the radiances\n at different model levels - one for each \\code{zout}. \\code{NN} is the\n number of the output level counted from the bottom (ATTENTION: Levels are\n counted from 0 here!). The file format is the same as in \\code{mc.rad}.\n \n (If interested in surface quantities, please use the radiance data\n at the surface from \\code{mc.rad}, not from \\code{mc00.rad}; the data from \n \\code{mc00.rad} or whatever layer coincides with the \n surface may be wrong for technical reasons).\n\n\\item[mcNN.abs] \n The file \\code{mcNN.abs} includes the absorption per unit area in the given layer. \n NN is the number of the output layer on the atmospheric \n grid (counted from the bottom, starting from 1). This file is generated if \\code{mc\\_forward\\_ouput absorption} \n or \\code{mc\\_forward\\_output emission} is specified.\n \n The columns are:\n \\begin{enumerate}\n \\item x [m] (pixel center)\n \\item y [m] (pixel center)\n \\item absorption/emission/heating rate (W/m$^2$)\n \\end{enumerate} \n \n If multiplied by the extraterrestrial irradiance, the column \n absorption in W/m$^2$ is obtained. In a 1D atmosphere, with a solar source,\n absorption = e\\_net(top) - e\\_net(bottom) (this is not true for a thermal\n source because then emission needs to be considered; see below). If\n \\code{mc\\_forward\\_output emission} is specified, the file contains the thermal emission of\n the layer per unit area, that is, the Planck function times the optical\n thickness of the layer times 4$\\pi$ (angular integral of the Planck\n radiance). If \\code{mc\\_forward\\_output heating} is specified, the heating rate per unit area is \n provided instead of absorption (in the same units as absorption).\n For a solar source, the heating rate is identical to the absorption. \n In the thermal, however, each emitted photon is counted as cooling \n and hence the heating rate may be negative. In a 1D atmosphere, with a\n solar or thermal source, absorption = e\\_net(top) - e\\_net(bottom). \n\n For computational efficiency reasons \\code{mcNN.abs} is not provided on the\n sample grid but on the atmospheric grid. For the same reason, results are \n only calculated for 3D layers. In order to obtain 3D absorption for 1D\n cloudless layer, you need to specify an optically very thin 3D cloud, e.g.\n LWC/IWC = 10$^{-20}$ g/m$^3$ (yes, this is a dirty trick but a necessary one). \n\n\\item[mcNN.act] \n \\code{mcNN.act} contains the 4$\\pi$ actinic flux in the given layer,\n calculated from the absorbed energy (per unit area) divided by the \n absorption optical thickness of the layer. In contrast to the \n actinic flux in \\code{mcNN.flx}, this is a layer quantity the \n accuracy of which is generally much better than the level quantities \n which are calculated from radiance / cos (theta). As for the absorption\n above, \\code{mcNN.act} is not provided on the sample grid but on the\n atmospheric grid. NN is the number of the output layer (counted from the\n bottom, starting from 1). This file is generated if \\codeidx{mc\\_forward\\_output actinic} is specified. \n \n The columns are:\n \\begin{enumerate}\n \\item x [m]\n \\item y [m]\n \\item actinic flux (W/m$^2$)\n \\end{enumerate}\n\n\\end{description} \n\nThe spectral files are as follows:\n\\begin{description}\n \\item[mc.flx.spc]\n \\ifthreedmystic{This is the most versatile and useful irradiance /\n actinic flux output of MYSTIC}:\n \\begin{Verbatim}[fontsize=\\footnotesize, frame=single, samepage=true]\n 400.0 0 0 0 1.0e+00 0.0e+00 1.5067e-01 1.0e+00 0.0e+00 3.5044e-01\n 401.0 0 0 0 1.0e+00 0.0e+00 1.5044e-01 1.0e+00 0.0e+00 3.5863e-01\n 402.0 0 0 0 1.0e+00 0.0e+00 1.5022e-01 1.0e+00 0.0e+00 3.4755e-01\n \\end{Verbatim}\n\n The columns are:\n \\begin{enumerate}\n \\item wavelength [nm]\n \\item ix (0 ... Nx-1)\n \\item iy (0 ... Ny-1)\n \\item iz (0 ... Nz-1)\n \\item direct irradiance\n \\item diffuse downward irradiance\n \\item diffuse upward irradiance\n \\item direct actinic flux\n \\item diffuse downward actinic flux\n \\item diffuse upward actinic flux\n \\end{enumerate}\n These numbers are created the same way as the standard {\\sl uvspec} output. That\n is, they are multiplied with the extraterrestrial irradiance, corrected for\n Sun-Earth-distance, integrated over wavelength, converted to reflectivity or \n brightness temperature, etc. \n\n \\item[mc.rad.spc]\n \\ifthreedmystic{This is the most versatile and useful radiance output of\n MYSTIC}:\n \\begin{Verbatim}[fontsize=\\footnotesize, frame=single, samepage=true]\n 400.0 0 0 0 0.0398276\n 401.0 0 0 0 0.0396459\n 402.0 0 0 0 0.0398005\n \\end{Verbatim}\n\n The columns are:\n \\begin{enumerate}\n \\item wavelength [nm]\n \\item ix (0 ... Nx-1)\n \\item iy (0 ... Ny-1)\n \\item iz (0 ... Nz-1)\n \\item radiance \n \\end{enumerate}\n These numbers are created the same way as the standard {\\sl uvspec}\n output. That is, they are multiplied with the extraterrestrial irradiance,\n corrected for Sun-Earth-distance, integrated over wavelength, converted to\n reflectivity or brightness temperature, etc. \n\n If the {\\bf polarized} mystic is used (\\code{mc\\_polarisation}) then the four\n components of the Stokes vector (I,Q,U,V) are output for each wavelength and\n grid point, in four separate lines. \n\n\\ifthreedmystic{\n \\item[mc.abs.spc]\n \\code{mc.abs.spc} contains the absorption per unit area for all layers. This\n file is generated if \\code{mc\\_forward\\_output absorption} or \\code{mc\\_forward\\_output emission} is specified.\n \n The columns are:\n \\begin{enumerate}\n \\item wavelength [nm]\n \\item ix (0 ... Nx-1)\n \\item iy (0 ... Ny-1)\n \\item iz (0 ... Nz-1)\n \\item absorption/emission/heating rate\n \\end{enumerate} \n \n These numbers are created the same way as the standard {\\sl uvspec} output. That\n is, they are multiplied with the extraterrestrial irradiance, corrected for\n Sun-Earth-distance, integrated over wavelength, converted to reflectivity or \n brightness temperature, etc. The unit is determined by an extra option to \n \\code{mc\\_forward\\_output absorption} or \\code{mc\\_forward\\_output emission}. \n\n For computational efficiency reasons \\code{mc.abs.spc} is not provided on the\n sample grid but on the atmospheric grid. For the same reason, results are \n only calculated for 3D layers. In order to obtain 3D absorption for 1D\n cloudless layer, you need to specify an optically very thin 3D cloud, e.g.\n LWC/IWC = 10$^{-20}$ g/m$^3$ (yes, this is a dirty trick but a necessary one). \n\n \\item[mc.act.spc]\n \\code{mcNN.act} contains the 4$\\pi$ actinic flux in the given layer,\n calculated from the absorbed energy (per unit area) divided by the \n absorption optical thickness of the layer. In contrast to the \n actinic flux in \\code{mc.act.flx}, this is a layer quantity the \n accuracy of which is generally much better than the level quantities \n which are calculated from radiance / cos (theta). As for the absorption\n above, \\code{mcNN.act} is not provided on the sample grid but on the\n atmospheric grid. NN is the number of the output layer (counted from the\n bottom, starting from 1). This file is generated if \\codeidx{mc\\_forward\\_output actinic} is specified. \n \n The columns are:\n \\begin{enumerate}\n \\item wavelength [nm]\n \\item ix (0 ... Nx-1)\n \\item iy (0 ... Ny-1)\n \\item iz (0 ... Nz-1)\n \\item actinic flux\n \\end{enumerate}\n}\n\\end{description}\n\n\\ifthreedmystic{\n\\subsubsection{Memory requirements and computational speed}\n\\label{sec:mc_memory}\n\n\\begin{enumerate}\n\\item 3D clouds are defined on a 3D grid and the amount of \n memory required by MYSTIC is usually determined by \n the 3D cloud grid. Several variables need to be stored \n for each grid cell, including the optical properties of \n the cell, the grid cell absorption, etc. Umpteen (20-100) \n bytes are typically required for each grid cell. \n Computational time is to a large degree determined by \n the total optical thickness of the cloud because higher \n extinction means more scattering events and a longer \n photon path. To a lesser degree, the computational time \n is influenced by the number of cells but this may become \n important if the radiance is calculated using \n local estimates.\n\n\\item 2D albedo requires some memory but usually less than \n clouds because it is defined on a 2D grid compared to the \n 3D cloud grid. Only one double (8 bytes on a 32 bit machine) \n is stored per pixel. A high resolution has no influence \n on computational time.\n\n\\item 2D elevation requires somewhat more memory than a 2D albedo \n because 5 doubles are stored per pixel. Higher resolution \n will lead to higher computational times. \n\n\\item The sample grid by itself has only little influence on \n computational time because for a given number of photons, \n the computational time does not depend on the number of \n grid cells. The precision of the result, however depends \n strongly on the number of grid cells Nx $\\cdot$ Ny, as it \n decreases with sqrt(Nx$\\cdot$Ny). The number of altitude \n levels has only little influence on the computational \n time but of course a large influence on the memory \n requirements. The calculation of radiances has a large \n impact on computational time if local estimates are used.\n % CE: In current version it is only possible to compute 1 direction at a time\n %In the worst case, the computational time may \n %scale directly with the number of directions for which the \n %radiance is to be calculated.\n\\end{enumerate}\n} \n", "meta": {"hexsha": "869fb1d585a88259570017388b076efbfb8ea77d", "size": 36543, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "ubuntu20/projects/libRadtran-2.0.4/doc/mystic.tex", "max_stars_repo_name": "AmberCrafter/docker-compose_libRadtran", "max_stars_repo_head_hexsha": "0182f991db6a13e0cacb3bf9f43809e6850593e4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ubuntu20/projects/libRadtran-2.0.4/doc/mystic.tex", "max_issues_repo_name": "AmberCrafter/docker-compose_libRadtran", "max_issues_repo_head_hexsha": "0182f991db6a13e0cacb3bf9f43809e6850593e4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ubuntu20/projects/libRadtran-2.0.4/doc/mystic.tex", "max_forks_repo_name": "AmberCrafter/docker-compose_libRadtran", "max_forks_repo_head_hexsha": "0182f991db6a13e0cacb3bf9f43809e6850593e4", "max_forks_repo_licenses": ["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.724, "max_line_length": 694, "alphanum_fraction": 0.7323974496, "num_tokens": 11209, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.29098087236345377, "lm_q1q2_score": 0.15343902198465}} {"text": "\\documentclass[jou]{apa6}\n\n\\usepackage[american]{babel}\n\n\\usepackage{csquotes}\n\\usepackage[style=apa,sortcites=true,sorting=nyt,backend=biber]{biblatex}\n\\DeclareLanguageMapping{american}{american-apa}\n\\addbibresource{bibliography.bib}\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% Discrete Structures\n%% The start of RBS stuff\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% Working internal and external links in PDF\n\\usepackage{hyperref}\n% Extra math symbols in LaTeX\n\\usepackage{amsmath}\n\\usepackage{gensymb}\n\\usepackage{amssymb}\n% Enumerations with (a), (b), etc.\n\\usepackage{enumerate}\n\n\\let\\OLDitemize\\itemize\n\\renewcommand\\itemize{\\OLDitemize\\addtolength{\\itemsep}{-6pt}}\n\n\\usepackage{etoolbox}\n\\makeatletter\n\\preto{\\@verbatim}{\\topsep=3pt \\partopsep=3pt }\n\\makeatother\n\n% These sizes redefine APA for A4 paper size\n\\oddsidemargin 0.0in\n\\evensidemargin 0.0in\n\\textwidth 6.27in\n\\headheight 1.0in\n\\topmargin -24pt\n\\headheight 12pt\n\\headsep 12pt\n\\textheight 9.19in\n\n\\usepackage{xcolor}\n\n\\title{Sample Quiz 3}\n\\author{Discrete Structures, Fall 2020}\n\\affiliation{RBS}\n\n\\leftheader{Discrete Sample Quiz 3}\n\n\\abstract{%\n}\n\n%\\keywords{}\n\n\\begin{document}\n\n\\twocolumn\n\n\\section{Worksheet 3: First Order Logic}\n\n\n\\vspace{6pt}\n{\\bf Question 1.} {\\em Definition.} A Boolean formula is a \n{\\em Conjunctive Normal Form (CNF)}, \nif it is a conjunction of one or more clauses, \nwhere a clause is a disjunction of literals. Each literal \nis either a variable ($u,v,\\ldots$) or its negation ($\\neg u, \\neg v, \\ldots$). \n\nFind the CNF computing the following truth table for Boolean \nexpression $E(a,b,c)$:\\\\\n\\begin{tabular}{ c | c | c | c }\n$a$ & $b$ & $c$ & $E(a,b,c)$ \\\\ \\hline\n{\\tt T} & {\\tt T} & {\\tt T} & {\\tt T} \\\\ \\hline\n{\\tt T} & {\\tt T} & {\\tt F} & {\\tt F} \\\\ \\hline\n{\\tt T} & {\\tt F} & {\\tt T} & {\\tt F} \\\\ \\hline\n{\\tt T} & {\\tt F} & {\\tt F} & {\\tt F} \\\\ \\hline\n{\\tt F} & {\\tt T} & {\\tt T} & {\\tt T} \\\\ \\hline\n{\\tt F} & {\\tt T} & {\\tt F} & {\\tt F} \\\\ \\hline\n{\\tt F} & {\\tt F} & {\\tt T} & {\\tt F} \\\\ \\hline\n{\\tt F} & {\\tt F} & {\\tt F} & {\\tt T} \\\\ \\hline\n\\end{tabular}\n\n\n\n\n\\vspace{6pt}\n{\\bf Question 2.} The following CNF is given:\n$$E = (a \\vee \\neg c) \\wedge (b \\vee \\neg b).$$\nFind $2$ Boolean expressions equivalent to $E$:\\\\[3pt]\n{\\bf (A)} $a \\rightarrow \\neg b$,\\\\[3pt]\n{\\bf (B)} $a \\rightarrow c$,\\\\[3pt]\n{\\bf (C)} $\\neg c \\rightarrow \\neg a$,\\\\[3pt]\n{\\bf (D)} $(a \\wedge c) \\rightarrow b$,\\\\[3pt]\n{\\bf (E)} $c \\rightarrow a$,\\\\[3pt]\n{\\bf (F)} $a \\rightarrow (c \\rightarrow b)$,\\\\[3pt]\n{\\bf (G)} $\\neg a \\rightarrow \\neg c$.\n\n\\vspace{6pt}\n{\\bf Question 3.} We have six statements about Python programs $p \\in \\mathcal{P}$\nthat convert inputs $i \\in \\mathbb{Z}^{+}$ into results $r \\in \\mathbb{Z}^{+}$. \nA Python program may either loop indefinitely or halt (i.e.\\ it eventually stops).\n\n\\begin{enumerate}\n\\item Some programs return the correct result for all possible inputs and \nthey never loop indefinitely.\n\\item For any program one can find another program such that it returns\nthe same result for the same inputs as the first one (or loops indefinitely, \n{\\color{red} \\bf iff} the first program does the same).\n\\item There is a program that only loops indefinitely for at most finitely many inputs (or maybe none at all), \nbut for all other inputs it produces the correct result.\n\\item There is at least one Python program that always halts, and for sufficiently large inputs it produces\nthe correct result, but it may err for some small-size inputs.\n\\item For a program to produce a correct result for some input $i$ it is strictly necessary to halt.\\\\\n\\item A Python program always produces exactly one result for the given input provided that it halts.\n\\end{enumerate}\n\nWe use these $3$ predicates:\\\\\n$A(p_1,i_2,r_3)$ is true iff\nPython program $p_1 \\in \\mathcal{P}$ receives input $i_2 \\in \\mathbb{Z}^{+}$ and outputs \nresult $r_3 \\in \\mathbb{Z}^{+}$.\\\\\n$H(p_1,i_2)$ is true iff program $p_1 \\in \\mathcal{P}$ receives input $i_2$ and halts (i.e.\\ does not\nloop indefinitely).\\\\\n$C(i_1,r_2)$ is true iff for input $i_1$ the correct result is $r_2$. \n\n{\\em Note.} Write your answer as a comma-separated list: For example, \n{\\tt F,E,D,C,B,A} tells that the 1st statement is {\\bf (F)}, the 2nd one\nis {\\bf (E)}, $\\ldots$, the last one is {\\bf (A)}.\n\n\n\\begin{enumerate}[(A)]\n\\item ${\\displaystyle \\forall p \\in \\mathcal{P}\\; \\forall i \\in \\mathbb{Z}^+\\; \\forall r \\in \\mathbb{Z}^+,}$\\\\\n${\\displaystyle \\left( A(p,i,r) \\wedge C(i,r) \\,\\rightarrow\\, H(p,i) \\right) }$.\n\\item ${\\displaystyle \\forall p_1 \\in \\mathcal{P}\\; \\exists p_2 \\in \\mathcal{P}\\;\n\\forall i \\in \\mathbb{Z}^{+}\\; \\textcolor{red}{\\forall r \\in \\mathbb{Z}^{+},}}$\\\\\n${\\displaystyle \\left( (\\neg H(p_1,i) \\wedge \\neg H(p_2,i)) \\vee \n(A(p_1,i,r) \\leftrightarrow A(p_2,i,r)) \\right)}$\n\\item ${\\displaystyle \\exists p \\in \\mathcal{P}\\; \\exists N \\in \\mathbb{Z}^{+}\\; \n\\forall i \\in \\mathbb{Z}^{+}\\; \\textcolor{red}{\\exists r \\in \\mathbb{Z}^{+}},}$\\\\\n${\\displaystyle \\left( ( i \\leq N \\wedge \\neg H(p,i) ) \\vee (A(p,i,r) \\wedge C(i,r)) \\right)}$.\n\\item ${\\displaystyle \\forall p \\in \\mathcal{P}\\; \\forall i \\in \\mathbb{Z}^{+}\\; \\forall r_1 \\in \\mathbb{Z}^{+}\\;\n\\forall r_2 \\in \\mathbb{Z}^{+},}$\\\\ \n${\\displaystyle \\left( H(p,i) \\wedge A(p,i,r_1) \\wedge A(p,i,r_2) \\,\\rightarrow\\, r_1 = r_2 \\right)}$.\n\\item ${\\displaystyle \\exists p \\in \\mathcal{P}\\; \\exists N \\in \\mathbb{Z}^{+}\\; \\forall i \\in \\mathbb{Z}^{+}\\;\n\\textcolor{red}{\\forall r \\in \\mathbb{Z}^{+}},}$\\\\\n${\\displaystyle \\left( H(p,i) \\,\\wedge\\, ( A(p,i,r) \\wedge (i > N) \\,\\rightarrow\\, C(i,r) ) \\right)}$.\n\\item ${\\displaystyle \\exists p \\in \\mathcal{P}\\; \\forall i \\in \\mathbb{Z}^{+}\\; \\forall r \\in \\mathbb{Z}^{+},}$\\\\\n${\\displaystyle \\left( H(p,i) \\,\\wedge\\, (A(p,i,r) \\rightarrow C(i,r) \\right)}$. \n\\end{enumerate}\n\n\n\n\\vspace{10pt}\n{\\bf Question 4.} There is a set of $4$ students $S = \\{ s_1, s_2, s_3, s_4 \\}$ and \na set of $2$ chairs $C = \\{ c_1, c_2 \\}$. \nFind, how many such functions $f\\,:\\,S \\rightarrow C$ exist, \nhow many of them are injective, surjective and bijective.\\\\\n{\\em Note.} Your answer should be a comma-separated list of \n4 numbers (and 3 commas): {\\tt total,injective,surjective,bijective}.\n\n\n\\vspace{10pt}\n{\\bf Question 5.}\nThere is a predicate $S(x, y, z)$ defined for triplets\nof positive integers, \n$S: \\mathbb{Z}^{+} \\times \\mathbb{Z}^{+} \\times \\mathbb{Z}^{+} \\rightarrow \\{ \\mathtt{T}, \\mathtt{F} \\}$. \n$S(x,y,z)$ is true iff $x \\cdot y = z$.\\\\\nExpress these statements about positive integers\nusing only $S(x,y,z)$, Boolean operations and quantifiers.\\\\\n{\\em Note.} Please use only the predicate $S(\\ldots)$ in your answers, \navoid any other predicates or relations (such as equality, divisibility, etc.).\n\n\\begin{enumerate}[(A)] \n\\item $x/y = z$,\n\\item $x = 1$,\n\\item $x = y$, \n\\item $x$ is divisible by $y$ (i.e. $y \\,\\mid\\, x$). \n\\item $x$ has odd number of positive divisors.\n\\item $x$ is not a prime.\n\\item $x$ is a prime.\n\\end{enumerate}\n\n\n\n\n\\subsection{Answers}\n\n\\vspace{6pt}\n{\\bf Question 1.} Answer: \n\\begin{align}\n & \\textcolor{red}{(\\neg a \\vee \\neg b \\vee c)} \\wedge \n\\textcolor{blue}{(\\neg a \\vee b \\vee \\neg c)} \\wedge \n\\textcolor{blue}{(\\neg a \\vee b \\vee c)} \\;\\wedge \\nonumber \\\\\n\\wedge\\; & \\textcolor{red}{(a \\vee \\neg b \\vee c)} \\wedge \n(a \\vee b \\vee \\neg c) \\nonumber\n\\end{align}\nEvery value {\\tt F} in the truth table produces one \nclause in this expression. For example $E(\\mathtt{T},\\mathtt{T},\\mathtt{F}) = \\mathtt{F}$\nis addressed by a disjunction $(\\neg a \\vee \\neg b \\vee c)$. \n\nIf we combine red and blue clauses, we can rewrite this into a more compact expression, \nwhich is also CNF. Note, that this is not the only way to rewrite:\n$$\\textcolor{red}{(\\neg b \\vee c)} \\wedge \n\\textcolor{blue}{(\\neg a \\vee b)} \\wedge\n(a \\vee b \\vee \\neg c).$$\n\n\\vspace{6pt}\n{\\bf Question 2.} Answer: {\\bf (E)}, {\\bf (G)}.\\\\\n$(a \\vee \\neg c) \\wedge (b \\vee \\neg b) = (a \\vee \\neg c) \\wedge \\mathtt{T} = (a \\vee \\neg c)$. \nThis is same as $c \\rightarrow a$ or the contrapositive variant of the same implication:\n$\\neg a \\rightarrow \\neg c$.\n\n\\vspace{6pt}\n{\\bf Question 3.} Answer:\\\\\n\\begin{tabular}{|c|c|c|c|c|c|} \\hline\n1 & 2 & 3 & 4 & 5 & 6 \\\\ \\hline\n{\\bf (F)} & {\\bf (B)} & {\\bf (C)} & {\\bf (E)} & {\\bf (A)} & {\\bf (D)} \\\\ \\hline\n\\end{tabular} \n\n\\vspace{3pt}\nIn {\\bf (B)} we should write: the second program loops indefinitely {\\bf iff} \nthe first program does so. If we write {\\bf if} instead, it \nwould mean only one-way conditional, which does not mean \nequivalence between the programs $p_1$ and $p_2$, but something more complicated.\n\nIn {\\bf (B)} you could write $(H(p_1,i) \\leftrightarrow H(p_2,i))$\ninstead of $(\\neg H(p_1,i) \\wedge \\neg H(p_2,i))$ or \neven omit any reference to $H(\\ldots)$ predicates. \nThe notation $(H(p_1,i) \\leftrightarrow H(p_2,i))$ stresses the fact that $p_1$ and $p_2$ behave in the same way. \nBut in fact the equivalence $(A(p_1,i,r) \\leftrightarrow A(p_2,i,r))$ implicitly \nstates the fact that $p_1$ and $p_2$ are defined on the same inputs.\n\nPlease note that {\\bf (B)} should {\\bf NOT} have quantifier \n $\\textcolor{red}{\\exists r \\in \\mathbb{Z}^{+}}$ \n(instead of $\\textcolor{red}{\\forall r \\in \\mathbb{Z}^{+}}$), because we need\nequivalence for all positive integers $r$. If we only care about the\nactual result of $p$ on input $i$, then it is possible to ``cheat'' the logic formula: \npick result $r$ which is impossible for both $p_1$ and $p_2$; then $A(p_1,i,r)$ \nand $A(p_2,i,r)$ would both be false (and thus equivalent).\n\nIn {\\bf (C)} one cannot replace $\\textcolor{red}{\\exists r \\in \\mathbb{Z}^{+}}$\nwith $\\textcolor{red}{\\forall r \\in \\mathbb{Z}^{+}}$ (as in an earlier draft of this test), \nbecause it does not make sense to ask that a program $p$ on input $i$ produces\n{\\bf each} positive integer result; and all results turn out to be correct. \n(Such a formula may have some useful meaning if predicates $A,H,C$ have different\ninterpretations, but for Python programs this is technically correct, but \nhas an absurd meaning: that a given program produces any result whatsoever.)\n\nIn {\\bf (E)} it is absolutely necessary to write a quantifier \n$\\textcolor{red}{\\forall r \\in \\mathbb{Z}^{+}}$, because \nleaving $r$ as a free variable (without a quantifier) would \nmean that the Python program always produces the same result\n(the value of $r$). It is not \n\n\n\\vspace{6pt}\n{\\bf Question 4.} Answer: {\\tt 16,0,14,0}\\\\\nPlease note that there can be no injections (and therefore also bijections): \nstudents will always collide \\textendash{} run to the same chair, \nsince there are fewer chairs than students.\n\nThe total number of functions is $2^4 = 16$. Each student\ncan choose between $2$ chairs, so it is $2 \\times 2 \\times 2 \\times 2 = 16$. \nMoreover, there are only $2$ ``constant'' functions (where all four\nstudents go to $c_1$ or to $c_2$). They are not surjective, because\nsome chairs stay unoccupied in this case. \nAll the other $16 - 2 = 14$ functions from $S$ (4 elements) to $C$ (2 elements)\nare surjections. \n\n\\vspace{6pt}\n{\\bf Question 5.} Here we write all $7$ statements with predicate $S(x,y,z)$ and quantifiers. \n\n\\begin{enumerate}[(A)]\n\\item $S(z,y,x)$ (or, equivalently, $S(y,z,x)$). \n\\item $\\exists y \\in \\mathbb{Z}^{+},\\; S(x,y,y)$.\\\\\nUse the property: $x = 1$ can multiply with an $y$, and does not increase/decrease. \\\\\nYou could also write simply $S(x,x,x)$. Indeed, $x$ is the only \npositive integer such that $x \\cdot x = x$. (Allowing $x = 0$ would \nspoil this, because $0^2 = 0$.)\n\\item $\\exists z \\in \\mathbb{Z}^{+},\\; S(x,z,y) \\wedge S(z,z,z)$.\\\\\nSo, $x = y$ iff there is a $z = 1$ such that $x \\cdot z = y$.\n\\item $\\exists d \\in \\mathbb{Z}^{+},\\; S(y,d,x)$.\n\\item $\\exists y \\in \\mathbb{Z}^{+},\\; S(y,y,x)$.\\\\ \nThis means that $y^2 = x$ for some $y$; \nhence $x$ is a full square and should have odd number of divisors.\n\\item $\\exists y \\in \\mathbb{Z}^{+}\\;\\exists z \\in \\mathbb{Z}^{+},\\;(S(y,z,x) \\wedge \\neg S(y,y,y) \\wedge \\neg S(z,z,z))$.\\\\\nThis means that a non-prime $x$ can be expressed as a product of two positive integers $y,z$, \nwhere neither of them is $1$.)\n\\item $\\forall y \\in \\mathbb{Z}^{+}\\;\\forall z \\in \\mathbb{Z}^{+},\\;(\\neg S(y,z,x) \\vee S(y,y,y) \\vee S(z,z,z))$.\\\\\nWe apply negation to the previous quantifier formula; all $\\exists$ quantifiers turn into $\\forall$; \nformulas are changed according to De Morgan's laws.\n\\end{enumerate}\n\n\n\n\n\n\n\n\n\n\n\\end{document}\n\n\n", "meta": {"hexsha": "a9737f56930fe44340b8c1cfdcd9d2d826e96af6", "size": 12341, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "src/site/discrete-spring2020/questionbase/quiz-sample-03.tex", "max_stars_repo_name": "kapsitis/math", "max_stars_repo_head_hexsha": "f21b172d4a58ec8ba25003626de02bfdda946cdc", "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": "src/site/discrete-spring2020/questionbase/quiz-sample-03.tex", "max_issues_repo_name": "kapsitis/math", "max_issues_repo_head_hexsha": "f21b172d4a58ec8ba25003626de02bfdda946cdc", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2020-07-20T03:40:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-10T21:50:18.000Z", "max_forks_repo_path": "src/site/discrete-spring2020/questionbase/quiz-sample-03.tex", "max_forks_repo_name": "kapsitis/math", "max_forks_repo_head_hexsha": "f21b172d4a58ec8ba25003626de02bfdda946cdc", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.3300653595, "max_line_length": 124, "alphanum_fraction": 0.6511627907, "num_tokens": 4334, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.3106943959796865, "lm_q1q2_score": 0.15292009553614055}} {"text": "\\chapter{\\wannier\\ as a library}\\label{ch:wann-lib}\n\nThis is a description of the interface between any external program\nand the wannier code. There are two subroutines: \\verb#wannier_setup#\nand \\verb#wannier_run#. Calling \\verb#wannier_setup# will return\ninformation required to construct the $M_{mn}^{(\\mathbf{k,b})}$\noverlaps (Ref.~\\cite{marzari-prb97}, Eq.~(25)) and\n$A_{mn}^{(\\mathbf{k})}=\\left\\langle\n \\psi_{m\\mathbf{k}}|g_{n}\\right\\rangle$ projections\n(Ref.~\\cite{marzari-prb97}, Eq.~(62); Ref.~\\cite{souza-prb01},\nEq.~(22)). Once the overlaps and projection have been computed,\ncalling \\verb#wannier_run# activates the minimisation and plotting\nroutines in \\wannier.\n\n%\\section{Dependencies}\n%\\begin{itemize}\n%\\item Parameters\n%\\item IO\n%\\item Kmesh\n%\\item Overlap\n%\\item Wannierise\n%\\end{itemize}\n\n\\section{Subroutines}\n\n\\subsection{{\\tt wannier\\_setup}}\n\n{\\noindent \\bf \\verb#wannier_setup(seed_name,mp_grid,num_kpts,real_lattice,recip_lattice,#\\\\\n\\verb# kpt_latt,num_bands_tot,num_atoms,atom_symbols,atoms_cart,#\\\\\n\\verb# gamma_only,spinors,nntot,nnlist,nncell,num_bands,num_wann,proj_site,#\\\\\n\\verb# proj_l,proj_m,proj_radial,proj_z,proj_x,proj_zona,#\\\\\n\\verb# exclude_bands,proj_s,proj_s_qaxis)#}\n\n\\begin{itemize}\n\\item \\verb#character(len=*), intent(in) :: seed_name#\\\\ The seedname\n of the current calculation.\n\\item \\verb#integer, dimension(3), intent(in) :: mp_grid#\\\\ The\n dimensions of the {Monkhorst-Pack} k-point grid.\n\\item \\verb#integer, intent(in) :: num_kpts#\\\\ The number of k-points on\n the {Monkhorst-Pack} grid.\n\\item \\verb#real(kind=dp), dimension(3,3), intent(in) :: real_lattice#\\\\\n The lattice vectors in Cartesian co-ordinates in units of Angstrom.\n\\item \\verb#real(kind=dp), dimension(3,3), intent(in) :: recip_lattice#\\\\\n The reciprocal lattice vectors in Cartesian co-ordinates in units of reciprocal Angstrom.\n\\item\n \\verb#real(kind=dp), dimension(3,num_kpts), intent(in) :: kpt_latt#\\\\\n The positions of the k-points in fractional co-ordinates\n relative to the reciprocal lattice vectors.\n\\item \\verb#integer, intent(in) :: num_bands_tot#\\\\ The total number of bands in the\nfirst-principles calculation (note: including semi-core states).\n\\item \\verb#integer, intent(in) :: num_atoms#\\\\ The total number of atoms\n in the system.\n\\item \\verb#character(len=20), dimension(num_atoms),#\n \\verb# intent(in) :: atom_symbols#\\\\ The elemental symbols of\n the atoms.\n\\item \\verb#real(kind=dp), dimension(3,num_atoms),#\n \\verb#intent(in) :: atoms_cart#\\\\ The positions of the atoms in\n Cartesian co-ordinates in Angstrom.\n\\item \\verb#logical, intent(in) :: gamma_only#\\\\ Set to \\texttt{.true.} if the\n underlying electronic structure calculation has been performed with\n only $\\Gamma$-point sampling and, hence, if the Bloch eigenstates\n that are used to construct $A_{mn}^{(\\mathbf{k})}$ and\n $M_{mn}^{\\mathbf{(k,b)}}$ are real.\n\\item \\verb#logical, intent(in) :: spinors#\\\\ Set to \\texttt{.true.} if\n underlying electronic structure calculation has been performed with\n spinor wavefunctions. \n\\item \\verb#integer, intent(out) :: nntot#\\\\ The\n total number of nearest neighbours for each k-point. \n\\item \\verb#integer, dimension(num_kpts,num_nnmax),#\n \\verb# intent(out) :: nnlist#\\\\\n The list of nearest neighbours for each k-point.\n\\item \\verb#integer,dimension(3,num_kpts,num_nnmax),#\n \\verb# intent(out) :: nncell#\\\\ \n The vector, in fractional reciprocal lattice co-ordinates, that\n brings the \\verb#nn#$^{\\mathrm{th}}$ nearest neighbour of\n k-point \\verb#nkp# to its periodic image that\n is needed for computing the overlap \n $M_{mn}^{(\\mathbf{k,b})}$.\n\\item \\verb#integer, intent(out) :: num_bands#\\\\ The number of bands in the\nfirst-principles calculation used to form the overlap matricies (note: excluding eg. semi-core states).\n\\item \\verb#integer, intent(out) :: num_wann#\\\\ The number of MLWF\n to be extracted.\n\\item \\verb#real(kind=dp), dimension(3,num_bands_tot), intent(out) :: proj_site# \\\\\nProjection function centre\nin crystallographic co-ordinates relative to the direct lattice\nvectors.\n\\item \\verb#integer, dimension(num_bands_tot), intent(out) :: proj_l#\\\\\n $l$ specifies the angular part $\\Theta_{lm_{\\mathrm{r}}}(\\theta,\\varphi)$ of the\nprojection function (see Tables~\\ref{tab:angular}, \\ref{tab:hybrids}\nand \\ref{tab:radial}). \n\\item \\verb#integer, dimension(num_bands_tot), intent(out) :: proj_m#\\\\\n $m_\\mathrm{r}$ specifies the angular part $\\Theta_{lm_{\\mathrm{r}}}(\\theta,\\varphi)$, of the\nprojection function\n (see Tables~\\ref{tab:angular}, \\ref{tab:hybrids}\nand \\ref{tab:radial}). \n\\item \\verb#integer, dimension(num_bands_tot), intent(out) :: proj_radial#\\\\\n$\\mathrm{r}$ specifies the radial part $R_{\\mathrm{r}}(r)$ of the\nprojection function \n(see Tables~\\ref{tab:angular}, \\ref{tab:hybrids}\nand \\ref{tab:radial}). \n\\item \\verb#real(kind=dp), dimension(3,num_bands_tot), intent(out) :: proj_z#\\\\\nDefines the axis from which the polar angle\n$\\theta$ in spherical polar coordinates is measured. Default is\n\\verb#0.0 0.0 1.0#.\n\\item \\verb#real(kind=dp), dimension(3,num_bands_tot), intent(out) :: proj_x#\\\\\nMust be orthogonal to\n\\verb#z-axis#; default is \\verb#1.0 0.0 0.0# or a vector\nperpendicular to \\verb#proj_z# if \\verb#proj_z# is given; defines the\naxis from with the azimuthal angle $\\varphi$ in spherical polar\ncoordinates is measured.\n\\item \\verb#real(kind=dp), dimension(num_bands_tot), intent(out) :: proj_zona#\\\\\nThe value of $\\frac{Z}{a}$ associated\nwith the radial part of the atomic orbital. Units are in reciprocal\nAngstrom.\n\\item \\verb#integer, dimension(num_bands_tot), intent(out) :: exclude_bands#\\\\ \n Kpoints independant list of bands to exclude from the\n calculation of the MLWF (e.g., semi-core states). \n\\item \\verb#integer, dimension(num_bands_tot), optional,intent(out) :: proj_s#\\\\\n'1' or '-1' to denote projection onto up or down spin states\n\\item \\verb#real(kind=dp), dimension(3,num_bands_tot), intent(out) :: proj_s_qaxisx#\\\\\nDefines the spin quantisation axis in Cartesian coordinates.\n\n\\end{itemize}\n\nConditions:\n\\begin{itemize}\n\\cond $\\verb#num_kpts# = \\verb#mp_grid(1)# \\times \\verb#mp_grid(2)#\n\\times \\verb#mp_grid(3)#$.\n\\cond $\\verb#num_nnmax# = 12$\n\\end{itemize}\n\nThis subroutine returns the information required to determine the\nrequired overlap elements $M_{mn}^{(\\mathbf{k,b})}$ and\nprojections $A_{mn}^{(\\mathbf{k})}$,\ni.e., \\verb#M_matrix# and \\verb#A_matrix#, described in\nSection~\\ref{wannier_run}. \n\nFor the avoidance of doubt, \\verb#real_lattice(1,2)# is the\n$y-$component of the first lattice vector $\\mathbf{A}_{1}$, etc.\n\nThe list of nearest neighbours of a particular k-point \\verb#nkp# is\ngiven by \\verb#nnlist(nkp,1:nntot)#.\n\nAdditionally, the parameter \\verb#shell_list#\nmay be specified in the \\wannier\\ input file.\n\n\\subsection{{\\tt wannier\\_run}} \\label{wannier_run}\n\n{\\noindent \\bf \\verb#wannier_run(seed_name,mp_grid,num_kpts,real_lattice,recip_lattice,#\\\\\n\\verb# kpt_latt,num_bands,num_wann,nntot,num_atoms,atom_symbols,#\\\\\n\\verb# atoms_cart,gamma_only,M_matrix_orig,A_matrix,eigenvalues,#\\\\\n\\verb# U_matrix,U_matrix_opt,lwindow,wann_centres,wann_spreads,#\\\\\n\\verb# spread#)}\n\n\\begin{itemize}\n\\item \\verb#character(len=*), intent(in) :: seed_name#\\\\ The seedname\n of the current calculation.\n\\item \\verb#integer, dimension(3), intent(in) :: mp_grid#\\\\ The\n dimensions of the {Monkhorst-Pack} k-point grid.\n\\item \\verb#integer, intent(in) :: num_kpts#\\\\ The number of k-points on\n the {Monkhorst-Pack} grid.\n\\item \\verb#real(kind=dp), dimension(3,3),#\n \\verb# intent(in) :: real_lattice#\\\\ The lattice vectors in\n Cartesian co-ordinates in units of Angstrom. \n\\item \\verb#real(kind=dp), dimension(3,3), intent(in) :: recip_lattice#\\\\\n The reciprical lattice vectors in Cartesian co-ordinates in units of inverse Angstrom.\n\\item \\verb#real(kind=dp), dimension(3,num_kpts),#\n \\verb# intent(in) :: kpt_latt#\\\\ The positions of the k-points in\n fractional co-ordinates relative to the reciprocal lattice\n vectors.\n\\item \\verb#integer, intent(in) :: num_bands#\\\\ The total number of\n bands to be processed.\n\\item \\verb#integer, intent(in) :: num_wann#\\\\ The number of MLWF to\n be extracted. \n\\item \\verb#integer, intent(in) :: nntot#\\\\ The number of\n nearest neighbours for each k-point.\n\\item \\verb#integer, intent(in) :: num_atoms#\\\\ The total number of atoms\n in the system.\n\\item \\verb#character(len=20), dimension(num_atoms),#\n \\verb# intent(in) :: atom_symbols#\\\\ The elemental symbols of\n the atoms.\n\\item \\verb#real(kind=dp), dimension(3,num_atoms),#\n \\verb#intent(in) :: atoms_cart#\\\\ The positions of the atoms in\n Cartesian co-ordinates in Angstrom.\n\\item \\verb#logical, intent(in) :: gamma_only#\\\\ Set to \\texttt{.true.} if the\n underlying electronic structure calculation has been performed with\n only $\\Gamma$-point sampling and, hence, if the Bloch eigenstates\n that are used to construct $A_{mn}^{(\\mathbf{k})}$ and\n $M_{mn}^{\\mathbf{(k,b)}}$ are real.\n\\item \\verb#complex(kind=dp),#\n \\verb# dimension(num_bands,num_bands,nntot,num_kpts),#\\\\\n \\verb# intent(in) :: M_matrix#\\\\ \n The matrices of overlaps between neighbouring periodic parts of\n the Bloch eigenstates at each k-point, $M_{mn}^{(\\mathbf{(k,b)})}$\n (Ref.~\\cite{marzari-prb97}, Eq.~(25)).\n\\item \\verb#complex(kind=dp), dimension(num_bands,num_wann,num_kpts),#\\\\\n \\verb# intent(in) :: A_matrix# \\\\The matrices\n describing the projection of \\verb#num_wann# trial orbitals on\n \\verb#num_bands# Bloch states at each k-point,\n $A_{mn}^{(\\mathbf{k})}$ (Ref.~\\cite{marzari-prb97}, Eq.~(62);\n Ref.~\\cite{souza-prb01}, Eq.~(22)).\n\\item \\verb#real(kind=dp), dimension(num_bands,num_kpts),#\n \\verb#intent(in) :: eigenvalues#\\\\ The\n eigenvalues $\\varepsilon_{n\\mathbf{k}}$ corresponding to the\n eigenstates, in eV.\n\\item \\verb#complex(kind=dp), dimension(num_wann,num_wann,num_kpts),#\\\\\n \\verb# intent(out) :: U_matrix#\\\\ The unitary\n matrices at each k-point (Ref.~\\cite{marzari-prb97}, Eq.~(59))\n\\item \\verb#complex(kind=dp), dimension(num_bands,num_wann,num_kpts),#\\\\\n \\verb# optional, intent(out) :: U_matrix_opt#\\\\ The\n unitary matrices that describe the optimal sub-space at each\n k-point (see Ref.~\\cite{souza-prb01}, Section~{\\sc IIIa}). The array is\n packed (see below) \n\\item \\verb#logical, dimension(num_bands,num_kpts), optional, intent(out) :: lwindow#\\\\ \n The element \\verb#lwindow(nband,nkpt)# is {\\tt .true.} if the band\n{\\tt nband} lies within the outer energy window at kpoint {\\tt nkpt}.\n\\item \\verb#real(kind=dp), dimension(3,num_wann), optional, intent(out) :: wann_centres#\\\\ \n The centres of the MLWF in Cartesian co-ordinates in Angstrom. \n\\item \\verb#real(kind=dp), dimension(num_wann), optional, intent(out) :: wann_spreads#\\\\ \n The spread of each MLWF in \\AA$^{2}$.\n\\item \\verb#real(kind=dp), dimension(3), optional, intent(out) ::#\n \\verb#spread#\\\\ \n The values of $\\Omega$, $\\Omega_{\\mathrm{I}}$ and\n $\\tilde{\\Omega}$ (Ref.~\\cite{marzari-prb97}, Eq.~(13)). \n\\end{itemize}\n\nConditions:\n\\begin{itemize}\n\\cond $\\verb#num_wann# \\le \\verb#num_bands#$\n\\cond $\\verb#num_kpts# = \\verb#mp_grid(1)# \\times \\verb#mp_grid(2)#\n\\times \\verb#mp_grid(3)#$.\n\\end{itemize}\n\nIf $\\verb#num_bands# = \\verb#num_wann#$ then \\verb#U_matrix_opt# is the identity matrix and\n\\verb#lwindow=.true.#\n\nFor the avoidance of doubt, \\verb#real_lattice(1,2)# is the\n$y-$component of the first lattice \nvector $\\mathbf{A}_{1}$, etc.\n\n\\begin{eqnarray*}\n\\verb#M_matrix(m,n,nn,nkp)# & = & \\left\\langle u_{m\\mathbf{k}} |\nu_{n\\mathbf{k+b}}\\right\\rangle\\\\\n\\verb#A_matrix(m,n,nkp)# & = &\n\\left\\langle \\psi_{m\\mathbf{k}}|g_{n}\\right\\rangle\\\\\n\\verb#eigenvalues(n,nkp)# &=& \\varepsilon_{n\\mathbf{k}}\n\\end{eqnarray*}\nwhere\n\\begin{eqnarray*}\n\\mathbf{k} &=&\\verb#kpt_latt(1:3,nkp)#\\\\\n\\mathbf{k+b}&=& \\verb#kpt_latt(1:3,nnlist(nkp,nn))# +\n\\verb#nncell(1:3,nkp,nn)# \n\\end{eqnarray*}\nand\n$\\left\\{|g_{n}\\rangle\\right\\}$ are a set of initial trial\norbitals. These are\ntypically atom or bond-centred Gaussians that are modulated by\nappropriate spherical harmonics. \n\nAdditional parameters should be specified in the \\wannier\\ input\nfile.\n\n", "meta": {"hexsha": "7e7d45ab3c4f335e91ec8705e93fba2608a9ed22", "size": 12440, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "wannier90_2.1/doc/user_guide/wannier.tex", "max_stars_repo_name": "comscope/comsuite", "max_stars_repo_head_hexsha": "d51c43cad0d15dc3b4d1f45e7df777cdddaa9d6c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 18, "max_stars_repo_stars_event_min_datetime": "2019-06-15T18:08:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-30T05:01:29.000Z", "max_issues_repo_path": "wannier90_2.1/doc/user_guide/wannier.tex", "max_issues_repo_name": "comscope/Comsuite", "max_issues_repo_head_hexsha": "b80ca9f34c519757d337487c489fb655f7598cc2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "wannier90_2.1/doc/user_guide/wannier.tex", "max_forks_repo_name": "comscope/Comsuite", "max_forks_repo_head_hexsha": "b80ca9f34c519757d337487c489fb655f7598cc2", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2019-06-05T02:57:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-29T02:54:25.000Z", "avg_line_length": 47.3003802281, "max_line_length": 103, "alphanum_fraction": 0.7011254019, "num_tokens": 3827, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.28140561345566495, "lm_q1q2_score": 0.15276477522371518}} {"text": "\n\\chapter{Arches}\n\n\\section{Introduction}\n%\nThe ARCHES component was initially designed for predicting the heat-flux from large buoyant pool fires with potential hazard hazards immersed in or near a pool fire of transportation fuel. Since then, this component has been extended to solve many industrially relevant problems such as industrial flares, oxy-coal combustion processes, and fuel gasification. \n\nThe ARCHES component solves the conservative, finite volume, compressible, low-mach formulation of the Navier-Stokes equation with a pressure projection that includes the effect of variable density, reaction, and heat transfer modes in the gas phase including radiation. Given the wide range of length and time scales that are present in many combustion problems of interest, ARCHES utilizes models for bridging the molecular (micro) scales to the full, large (macro) scales. This bridging occurs through the use of subgrid and resolved scale mixing, reaction, and turbulence models. For example, momentum turbulence closure is accomplished by using various large eddy simulation (LES) type closure models. Fast chemistry scales are modeled by preprocessing the full chemical mechanism, modeled in various idealized configurations (e.g., equilibrium or flamelets), then tracking a set of reduced parameters on the LES mesh that map the full thermochemical state-space. In general, the chemistry is tabulated and stored in a reaction table. Subgrid turbulence species mixing processes and included by using presumed PDF methods and using models for certain moments of the distribution (e.g., scalar variance and mixture fraction). The turbulence-species subgrid interaction model description are termed mixing models. The chemistry and mixing models are usually completely preprocessed together into one tabular format to give a mixing table. \n\nNote that the sister component, MPMARCHES, couples an MPM description of a solid object to include stationary solids with and without conjugate heat transfer. While run as a separate component, MPMARCHES is simply a wrapped version of ARCHES to include the MPM interface. \n\nThe following gives a brief introduction to a few of the key concepts of the Arches formulation of the transport equations and physical models as well as the CFD algorithm. Following this explanation, an overview of the ARCHES input parameters are given. \n\n\\section{Governing Equations}\n%\nThe essential governing equations for the Arches component, written\nin finite volume form, include the mass balance, momentum balance,\nmixture fraction balance, and energy balance equations. Using a bold-face\nsymbol to represent a vector quantity, the equations are: \n\\begin{enumerate}\n\\item The mass balance, \\begin{equation}\n\\int_{V}\\frac{\\partial\\rho}{\\partial t}dV+\\oint_{S}\\rho\\mathbf{u}\\cdot d\\mathbf{S}=0\\;,\\label{eqn:mass_balance}\\end{equation}\n where $\\rho$ is density and $\\mathbf{u}$ is the velocity vector. \n\\item The momentum balance, \\begin{equation}\n\\int_{V}\\frac{\\partial\\rho\\mathbf{u}}{\\partial t}dV+\\oint_{S}\\rho\\mathbf{uu}\\cdot d\\mathbf{S}=\\oint_{S}\\tau\\cdot d\\mathbf{S}-\\int_{V}\\nabla pdV+\\int_{V}\\rho\\mathbf{g}dV\\;,\\label{eqn:mom_balance}\\end{equation}\n where $\\tau$ is the deviatoric stress tensor defined as $\\tau_{ij}=2\\mu S_{ij}-\\frac{2}{3}\\mu\\frac{\\partial u_{k}}{\\partial x_{k}}\\delta_{ij}$,\nthe second isotropic term in $\\tau_{ij}$ is absorbed into the pressure\nprojection for the current low-Mach scheme, and $S_{ij}=\\frac{1}{2}\\left(\\frac{\\partial u_{i}}{\\partial x_{j}}+\\frac{\\partial u_{j}}{\\partial x_{i}}\\right)$.\nAlso in Equation \\ref{eqn:mom_balance}, $\\mathbf{g}$ is the gravitational\nbody force and $p$ is pressure. \n\\item The mixture fraction balance, \\begin{equation}\n\\int_{V}\\frac{\\partial\\rho f}{\\partial t}dV+\\oint_{S}\\rho\\mathbf{u}f\\cdot d\\mathbf{S}=\\oint_{S}D\\nabla f\\cdot d\\mathbf{S}\\;,\\label{eqn:species_balance}\\end{equation}\n where $f$ is the mixture fraction and a Fick's law form of the diffusion\nterm assuming equal diffusivities results in a single diffusion coefficient,\n$D$. \n\\item The thermal energy balance, \\begin{equation}\n\\int_{V}\\frac{\\partial\\rho h}{\\partial t}dV+\\oint_{S}\\rho\\mathbf{u}h\\cdot d\\mathbf{S}=\\oint_{S}k\\nabla h\\cdot d\\mathbf{S}-\\oint_{S}q\\cdot d\\mathbf{S}\\;,\\label{eqn:heat_balance}\\end{equation}\n where $h$ is the sum of the chemical plus sensible enthalpy, $q$\nis the radiative flux, a Fourier's law form of the conduction term\nis used with a diffusion coefficient, $k$, and the pressure term\nis neglected. \n\\end{enumerate}\nThese equations are solved in an LES context, meaning filters are\napplied to the equations. Here, we use Favre filtering, defined as\n\\[\n\\overline{\\phi}=\\frac{\\overline{\\rho\\phi}}{\\overline{\\rho}},\\]\n to isolate the density in the filtered equations. The filtering operations\nresult in the classic turbulence closure problem and thus models are\nrequired. \n\nConsider a control volume, $V$, with surface area $S$. Because the equations will be solved on a computational grid, one can safely assume that the the control volume has $N$ faces, where unique faces are identified with their index, $k$. The discussion is further simplified by only considering cubic volumes with length $h$. \nGiven the cubic control volume, a surface-filtered field for a variable $\\phi$ is defined as $\\overline{\\phi}^{(j)}(\\mathbf{x})$, where the variable is filtered on a plane in the $x_j$ orthogonal direction. Then, for any surface, $k$, the field is sampled at the face centered location. For example, if $j=1$, the surface-filtered quantity is\n%\n\\begin{equation}\n\\overline{\\phi}^{2d, (1)}(\\mathbf x) = \\frac{1}{h^2} \\int_{x_2 - h/2}^{x_2 + h/2} \\int_{x_3 - h/2}^{x_3 + h/2} \\phi(\\mathbf x') dx_2' dx_3' \\; .\n\\end{equation} \n%\nThe volume average follows as\n%\n\\begin{equation}\n\\overline{\\phi}^{3d} (\\mathbf x) = \\frac{1}{h^3} \\int_{x_1 - h/2}^{x_1 + h/2} \\int_{x_2 - h/2}^{x_2 + h/2} \\int_{x_3 - h/2}^{x_3 + h/2} \\phi(\\mathbf x') dx_1' dx_2' dx_3' \\; .\n\\end{equation}\n%\nThe bars over the variable, $\\phi$, are labeled with `2d' and `3d' superscripts to distinguish between the two filters. Pope \\cite{Pope179} identifies the proceeding definitions as using the ``anisotropic box\" filter kernel where the resultant variables are simply averages over the intervals $x_j - \\frac{1}{2}h < x_j' < x_j + \\frac{1}{2}h$. \n\nFor convenience in isolating density in the filtered equations, a Favre-filtered quantity is defined for an arbitrary variable, $\\varphi$, as \n%\n\\begin{equation}\\label{eqn:favre_surf}\n\\widetilde{\\varphi}^{2d} \\equiv \\frac{\\overline{\\rho \\varphi}^{2d}}{\\overline{\\rho}^{2d}} \\; ,\n\\end{equation}\n%\nand\n%\n\\begin{equation}\\label{eqn:favre_vol}\n\\widetilde{\\varphi}^{3d} \\equiv \\frac{\\overline{\\rho \\varphi}^{3d}}{\\overline{\\rho}^{3d}} \\;.\n\\end{equation}\n%\nBecause the 2d and 3d filters are explicitly defined, this convention is slightly different than what is normally observed in the literature. Most literature, however, derives the filtered equations from the finite difference equations rather than the finite volume equations. Thus, using $\\overline{\\rho}^{2d}$ and $\\overline{\\rho}^{3d}$ in Equations \\ref{eqn:favre_surf} and \\ref{eqn:favre_vol} to stress surface and volume filtered densities are appropriate for the present discussion.\n\nThe previous definitions are applied to the integral forms of the governing equations to obtain the Favre-filtered LES equations. Nevertheless, there are terms in the Favre-filtered equations that cannot be solved. These include the surface filtered convection of momentum, $\\widetilde{u_i u}^{2d}_j$, the surface filtered convection of mixture fraction, $\\widetilde{u_j f}^{2d}$, and the surface filtered convection of enthalpy, $\\widetilde{u_j h}^{2d}$. \n\nFor the filtered velocity product, $\\overline{\\rho}^{2d} \\; \\widetilde{ u_i u}^{2d}_j$, a subgrid stress tensor is defined as, \n%\n\\begin{equation}\\label{eqn:tau_sgs}\n\\tau^{sgs}_{ij} = \\widetilde{u_i u}^{2d}_j - \\widetilde{u}^{2d}_i \\widetilde{u}^{2d}_j \\; .\n\\end{equation}\n%\nSimilarly, subgrid diffusion terms are defined for mixture fraction and enthalpy, \n%\n\\begin{eqnarray}\n\\mathcal{J}^{f} = \\widetilde{u_j f}^{2d} - \\widetilde{u}^{2d}_j \\widetilde{f}^{2d} \\;, \\\\\n\\mathcal{J}^{h} = \\widetilde{u_j h}^{2d} - \\widetilde{u}^{2d}_j \\widetilde{h}^{2d} \\; .\\\\\n\\end{eqnarray}\n\nUsing these definitions, the final form of the Favre-filtered equations is\n%\n\\begin{enumerate}\n\\item The filtered mass balance, \n%\n\\begin{equation}\\label{eqn:filtered_mass_balance}\n\\frac{d}{d t} \\left(\\widetilde{\\rho}^{3d} \\right) + \\frac{S_k}{V} n_{kj} \\left( \\overline{\\rho}^{2d} \\; \\widetilde{u}^{2d}_j \\right) = 0 \\; .\n\\end{equation}\n%\n\\item The filtered momentum balance, \n%\n\\begin{equation}\\label{eqn:filtered_mom_balance}\n\\frac{d}{d t} \\left( \\overline{\\rho}^{3d} \\; \\widetilde{u}^{3d}_i \\right) = \\frac{S_{k}}{V} n_{kj}\\left( -\\overline{\\rho}^{2d} \\; \\widetilde{u}^{2d}_i\\widetilde{u}^{2d}_j + \\overline{\\tau}^{2d}_{ij} + \\tau^{sgs}_{ij} - \\overline{p}^{2d} \\delta_{ij} \\right) + \\overline{\\rho}^{3d} \\; g_i \\; .\n\\end{equation}\n%\n\\item The filtered mixture fraction balance,\n%\n\\begin{equation}\\label{eqn:filtered_mixfrac_balance}\n\\frac{d}{d t} \\left( \\overline{\\rho}^{3d} \\; \\widetilde{f}^{3d} \\right) = \\frac{S_k}{V} n_{kj} \\left( -\\overline{\\rho}^{2d} \\; \\widetilde{u}^{2d}_j \\widetilde{f}^{2d} + D \\nabla \\overline{f}^{2d} + \\mathcal{J}^{f} \\right) \\; .\n\\end{equation}\n%\n%\n\\item The filtered thermal energy balance, \n%\n\\begin{equation}\\label{eqn:filtered_heat_balance}\n\\frac{d}{d t} \\left( \\overline{\\rho}^{3d} \\; \\widetilde{h}^{3d} \\right) = \\frac{S_{k}}{V} n_{kj} \\left( -\\overline{\\rho}^{2d} \\; \\widetilde{u_j}^{2d}\\widetilde{h}^{2d} + k \\nabla \\overline{h}^{2d} - \\overline{q}^{2d} + \\mathcal{J}^h \\right) \\; .\n\\end{equation}\n%\n\\end{enumerate}\nThe subgrid momentum stress, $\\tau_{ij}^{sgs}$, the subgrid mixture fraction dissipation, $\\mathcal{J}^{f}$, and the subgrid heat dissipation, $\\mathcal{J}^{h}$, contain the unresolved or subgrid action of the turbulence on the transported quantities. Since these terms arise from definitions, models are introduced to include the subgrid effects that they represent. These models are discussed next.\n\n\\subsection{Subgrid Turbulence Models}\n%\nThe construction of both $\\mathcal{J}^f$ and $\\mathcal{J}^{h}$ is relatively straight forward. Invoking an ``eddy-viscosity\" modeling concept, the subgrid transport due to turbulent advection is treated as an enhanced diffusion term for the unclosed terms listed above. That is, the subgrid mixture fraction dissipation and subgrid enthalpy dissipation are respectively written as, \n%\n\\begin{equation}\n\\mathcal{J}^{f} = D_{t} \\frac{\\partial \\overline{f}^{2d}}{\\partial x_j} \\; , \n\\end{equation}\n%\nand \n%\n\\begin{equation}\n\\mathcal{J}^{h} = k_{t} \\frac{\\partial \\overline{h}^{2d}}{\\partial x_j} \\; .\n\\end{equation}\n%\nTo model $D_{t}$ and $k_{t}$, constant turbulent Schmidt ($Sc_t$),\n%\n\\begin{equation}\\label{eqn:subgrid_mixfrac}\nSc_{t} = \\frac{1}{\\rho} \\frac{\\mu_t}{D_t} \\; ,\n\\end{equation}\n%\nand Prandlt ($Pr_t$), \n%\n\\begin{equation}\\label{eqn:subgrid_enthalpy}\nPr_{t} = \\frac{1}{\\rho} \\frac{\\mu_t}{k_t} \\; ,\n\\end{equation}\n%\nnumbers are assumed with where $\\mu_t$ is a turbulent viscosity. Following Pitsch and Steiner \\cite{pitsch2000}, the values of the turbulent Schmidt and Prandlt number are taken as $Sc_t = Pr_t = 0.4$, which is consistent with a unity Lewis number assumption. \n\nFor the subgrid scale stress tensor, $\\tau^{sgs}_{ij}$, two common LES turbulence closure models are the constant coefficient Smagorinsky model \\cite{Smagorinsky178} and the dynamic coefficient Smagorinsky model \\cite{Moin158}. As with the scalar subgrid modeling terms, the eddy viscosity model is again invoked for $\\tau^{sgs}_{ij}$. Defining the deviatoric subgrid stress tensor as, \n%\n\\begin{equation}\n\\tau^{d, sgs}_{ij} = \\tau^{sgs}_{ij} - \\frac{1}{3}\\tau^{sgs}_{kk} \\delta_{ij}, \n\\end{equation}\n%\nthe subgrid stress is taken as,\n%\n\\begin{equation}\n\\tau_{ij}^{d, sgs} \\approx -2 \\nu_t \\overline{S}_{ij} = -2 (C_s \\Delta)^2 |\\overline{S}|\\overline{S}_{ij} \\; , \n\\end{equation}\n%\nwhere $\\Delta$ is the filter width, $\\nu_t$ is the eddy viscosity and $|\\overline{S}| \\equiv (2\\overline{S}_{ij}\\overline{S}_{ij})^{1/2}$. For the Smagorinsky model, $C_s \\approx 2$ depending on the filter type, numerical method, and flow configuration \\cite{Pope179}. \n\nFor the dynamic Smagorinsky model, $C_s$ is computed by taking a least squares approach to determining the length scale \\cite{Lilly180},\n%\n\\begin{equation} \\label{eqn:cs_eqn}\n(C_s \\Delta)^2 = \\frac{ \\left< \\mathcal{L}_{ij} M_{ij} \\right>}{ \\left< M_{ij}M_{ij} \\right> } \\; ,\n\\end{equation}\n%\nwhere\n%\n%\n\\begin{equation}\n\\mathcal{L}_{ij} = 2( C_s \\Delta)^2 \\widehat{ |\\overline{S} | \\overline{S} }_{ij} - \n 2( C_s \\widehat{\\Delta})^2 \\widehat{ |\\overline{S}} | \\widehat{\\overline{S}}_{ij} \\; ,\n\\end{equation}\n% \nand\n\\begin{equation}\nM_{ij} \\equiv 2 \\left( \\widehat{ | \\overline{S} | \\overline{S} }_{ij} - \\alpha^2 |\\widehat{\\overline{S}}|\\widehat{\\overline{S}}_{ij} \\right) \\; .\n\\end{equation} \n%\nThe hat defines an explicit test filter and the angled brackets in Equation \\ref{eqn:cs_eqn} conceptually represent an averaging over a homogeneous region of space that, experience has shown, is necessary for stability. Experience has also shown that averaging over the test filter width is adequate and the filter width ratio, $\\alpha = \\widehat{\\Delta}/\\Delta$, is usually taken to be 2.\n\n\\subsection{Subgrid Momentum Dissipation}\n%%\nAddressing the momentum closure involves finding a suitable model for the subgrid scale stress tensor, $\\tau^{sgs}_{ij}$. Two common LES turbulence closure models are examined: the constant coefficient Smagorinsky model and the dynamic coefficient Smagorinsky model. \n%%\nIn LES modeling, field variables are decomposed into a spatially filtered field and a residual component, $u = \\overline{u} + u'$. This decomposition is known as a Leonard decomposition. While seemingly similar to a Reynolds decomposition used in Reynolds Averaged Navier-Stokes (RANS) models, the Leonard decomposition has the property that the filtered residual component is generally not equal to zero, $\\overline{u'} \\neq 0$. As a result, the subgrid stress term contains several terms, \n%%%\n\\begin{eqnarray}\n\\tau_{ij}^{sgs} = \\overline{ \\left(\\overline{u}_i + u_i' \\right) \\left(\\overline{u}_i + u_i' \\right)} - \\overline{u}_i \\overline{u}_j \\; , \\; \\; \\; \\; \\; \\; \\; \\; \\; \\; \\; \\; \\; \\; \\; \\; \\nonumber \\\\\n= \\underbrace{\\overline{\\overline{u}_i \\overline{u}_j} - \\overline{u}_i \\overline{u}_j}_{L_{ij}} + \n \\underbrace{\\overline{\\overline{u}_i {u}_j'} + \\overline{{u}_i' \\overline{u}_j}}_{C_{ij}} + \n \\underbrace{ \\overline{u_i' + u_j'} }_{R_{ij}} \\; , \n\\end{eqnarray}\n%\nreferred to as the Leonard stress, the cross stresses, and the Reynolds stress respectively. \n\nIt is useful to consider the physical interpretation of the various components of the stress. The Leonard term is responsible for filtering and projecting the nonlinear interactions of the resolved components back to the finite LES space. This is a correction to the resolved advective term in accordance with the stated explicit filter used to derive the LES equations. It does not account for aliasing errors. The first cross term represents advection of the resolved field by turbulent fluctuations. The second cross term represents the advection of subgrid scales by the resolved field. The Reynolds stress is familiar from RANS and represents the advection of subgrid scales by turbulent fluctuations. \n\nAs with the scalar subgrid modeling terms, the eddy viscosity model is again invoked for $\\tau^{sgs}_{ij}$. The most common eddy viscosity model in LES is the Smagorinsky model \\cite{Smagorinsky178}. Defining the deviatoric subgrid stress tensor as, \n%%\n\\begin{equation}\n\\tau^{d, sgs}_{ij} = \\tau^{sgs}_{ij} - \\frac{1}{3}\\tau^{sgs}_{kk} \\delta_{ij}, \n\\end{equation}\n%%\nthe subgrid stress is approximated by,\n%%\n\\begin{equation}\n\\tau_{ij}^{d, sgs} \\approx -2 \\nu_t \\overline{S}_{ij} = -2 (C_s \\Delta)^2 |\\overline{S}|\\overline{S}_{ij} \\; , \n\\end{equation}\n%%\nwhere, $\\Delta$ is the filter width, $\\nu_t$ is the eddy viscosity, $|\\overline{S}| \\equiv (2\\overline{S}_{ij}\\overline{S}_{ij})^{1/2}$, and typically $C_s \\approx 2$ depending on the filter type, numerical method, and flow configuration \\cite{Pope179}. This model is basically identical to Prandtl's mixing length model with $l = C_s \\Delta$.\n\nThe dynamic procedure \\cite{Germano74, Moin158} eliminates the need to specify the model constant, $C_s$, a priori, with the basic assumption that the constant is the same for two different filter scales. The smaller scale is historically referred to as the ``grid scale\" (though the filter width need not equal the grid spacing, $\\Delta \\geq h$)), and the larger scale is referred to as the ``test scale\". Implicit in this assumption is the requirement that both scales lie within the inertial subrange. \n\nDefining the deviatoric residual stress tensor as, \n\\begin{equation}\nT_{ij}^d = T_{ij} - \\frac{1}{3} T_{kk}\\delta_{ij} \\;,\n\\end{equation}\nthe residual stress at the test scale is given by,\n%%\n\\begin{equation}\\label{eqn:res_stress}\nT_{ij}^{d} \\equiv \\overline{\\widehat {u_i u_j}} - \\overline{\\widehat{u}}_i \\overline{\\widehat{u}}_j \\approx -2(C_s \\widehat{\\Delta})^2 |\\widehat{\\overline{S}}| \\widehat{\\overline{S}}_{ij} \\; .\n\\end{equation}\n%%\nwhere $\\widehat{\\Delta}$ is the test filter width and the hat defines an explicit test filter. By test filtering Equation \\ref{eqn:tau_sgs} and combining this with \\ref{eqn:res_stress}, one can construct the Leonard term, $\\mathcal{L}_{ij}$. This is also known as the ``Germano identity\",\n%%\n\\begin{equation}\n\\mathcal{L}_{ij} = T_{ij} - \\widehat{ \\tau^{sgs}}_{ij} = \\overline{\\widehat {u_i u_j}} - \\overline{\\widehat{u}}_i \\overline{\\widehat{u}}_j \\; .\n\\end{equation}\n%%\nNotice that the Leonard term is directly computable from resolved LES quantities. By restating the Smagorinsky model in terms of the Germano identity, one ends up with an over-determined system of equations for the unknown, $C_s$,\n%%\n\\begin{equation}\n\\mathcal{L}_{ij} = 2( C_s \\Delta)^2 \\widehat{ |\\overline{S} | \\overline{S} }_{ij} - \n 2( C_s \\widehat{\\Delta})^2 \\widehat{ |\\overline{S}} | \\widehat{\\overline{S}}_{ij} \\; .\n\\end{equation}\n%% \nAlthough we have pulled $C_s$ out of the test filtering operation of the subgrid stress, this approximation yields acceptable results. In practice, one takes a least squares approach to determining the length scale \\cite{Lilly180},\n%%\n\\begin{equation} \\label{eqn:cs_eqn}\n(C_s \\Delta)^2 = \\frac{ \\left< \\mathcal{L}_{ij} M_{ij} \\right>}{ \\left< M_{ij}M_{ij} \\right> } \\; ,\n\\end{equation}\n%%\nwhere\n%%\n\\begin{equation}\nM_{ij} \\equiv 2 \\left( \\widehat{ | \\overline{S} | \\overline{S} }_{ij} - \\alpha^2 |\\widehat{\\overline{S}}|\\widehat{\\overline{S}}_{ij} \\right) \\; .\n\\end{equation} \n%%\nThe only model parameter, then, is the filter width ratio, $\\alpha = \\widehat{\\Delta}/\\Delta$, usually taken to be 2.\n\nThe angled brackets in Equation \\ref{eqn:cs_eqn} conceptually represent averaging over a homogeneous region of space which, experience has shown, is necessary for stability. We have found that averaging over the test filter width is adequate.\n%%\nWith these implementation practices, the dynamic model is generally robust. The implementation can be made more efficient by computing the constant roughly every 10 time steps (based on the advective CFL), and only for the first Runge-Kutta step.\n\n\\subsection{LES Algorithm}\\label{Sec:LES_Algorithm}\n%\nThe set of filtered equations (Equations \\ref{eqn:filtered_mass_balance}-\\ref{eqn:filtered_heat_balance}) are discretized in space and time and solved on a staggered, finite volume mesh. The staggering scheme consists of four offset grids. One grid stores the scalar quantities and the remaining three grids store each component of the velocity vector. The velocity components are situated so that the center of their control volume is located on the face centers of the scalar grid in their respective direction. Figure \\ref{fig:staggered_grid} shows an example of a two-dimensional grid and the staggering arrangement.\n%\n%% Staggered Grid\n\\begin{figure}\n \\begin{center}\n \\scalebox{.85}{\\includegraphics{staggered_grid.png}}\n \\caption{Staggered grid arrangement in two dimensions with u and v velocity cell centers located on the face centers of the scalar cells.}\\label{fig:staggered_grid}\n \\end{center}\n\\end{figure}\n%\n\nThe staggering arrangement is advantageous for computing low-Mach LES reacting flows. First, since a pressure projection algorithm is used, the velocities are exactly projected without interpolation error because the location of the pressure gradient coincides directly with the location of the velocity storage location. Second, Morinishi et al. \\cite{morinishi98} showed that kinetic energy is exactly conserved when using a central differencing scheme on the convection and diffusion terms without a subgrid model and in combination with a staggered grid. Having a spatial scheme that conserves kinetic energy is advantageous because it limits artificial dissipation that arises from the differencing scheme. These conservation properties make the staggered grid a prime choice for LES reacting flow simulation.\n\nFor the spatial discretization of the LES scalar equations, flux limiting and upwind schemes for the convection operator are used. These schemes are advantageous for ensuring that scalar values remain bounded. For the momentum equation, a central differencing scheme for the convection operator is used. All diffusion terms are computed with a second order approximation of the gradient. \n\nWhen computing the 2d surface filtered field on the faces of the control volume, one is forced to use an interpolation from the 3d volume filtered field. This approximation is tolerated because computing the 2d surface field is simply not possible with the given grid scheme. % This is a good example of how LES modeling issues and discrete numerics issue intertwine in applied LES modeling. \n\n%Jennifer edited\nAn explicit time stepping scheme is chosen. A general, multistep explicit update for a variable, $\\phi$, may be written as, \n%\n%===== Explicit Update =====\n\\begin{eqnarray}\\label{eqn:forward_euler}\n\\phi^0 = \\phi^n \\; , \\nonumber \\\\\n \\phi^{(i)} = V \\sum_{k=0}^{m-1}\n\\left( \\alpha_{i,k} \\phi^{(k)} +\n\\Delta t \\beta_{i,k} L( \\phi^{(k)}) \\right) \\; , \\; \\; \\; \\; i = 1, ..., m \\\\\n\\phi^{(m)} = \\phi^{n+1} \\; , \\nonumber\n\\end{eqnarray}\n%\nwhere $n$ is the time level, $m$ is the substep between $n$ and $n+1$, $\\alpha$ and $\\beta$ are integration coefficients, and $L$ is a linearization operator on the the convective flux and source terms.\n%\nLetting $m=1$ and $\\alpha = \\beta = 1$ the forward-Euler time\nintegration scheme is determined,\n%%\n%%===== Forward Euler =====\n\\begin{equation}\\label{eqn:forward_euler}\n\\left( \\phi \\right)^{n+1} = \\left(\n\\phi \\right)^{n} + \\Delta t (L( \\phi)^n) \\; .\n\\end{equation}\n%%\nA higher order, multistep method is derived by letting $m > 1$ and\nchoosing appropriate constants for $\\alpha$ and $\\beta$. For this\nstudy, two step and three step, strong stability preserving (SSP)\ncoefficients were chosen from Gottlieb et al.\n\\cite{Gottlieb75}.\n\nUsing the coefficients given by Gottlieb et al., the SSP-RK 2 stepping scheme is\n%%\n%%===== second order time stepping =====\n\\begin{eqnarray}\\label{eqn:rk_second_order}\n( \\phi)^{(1)} = ( \\phi)^{n} + \\Delta\nt (L(\\phi)^n) \\\\ \\nonumber\n( \\phi)^{n+1} = \\frac{1}{2}(\n\\phi)^{n} + \\frac{1}{2}( \\phi)^{1} +\n\\frac{1}{2}\\Delta t (L( \\phi)^{(1)}) \\;.\n\\end{eqnarray}\n%%\nSSP-RK 3 time stepping scheme is,\n%%\n%%===== third order time stepping =====\n\\begin{eqnarray}\\label{eqn:rk_second_order}\n(\\phi)^{(1)} = (\\phi)^{n} + \\Delta t (L(\\phi)^n) \\\\ \\nonumber\n(\\phi)^{(2)} = \\frac{3}{4}(\\phi)^{n} + \\frac{1}{4}( \\phi)^{(1)} +\n\\frac{1}{4}\\Delta t (L( \\phi)^{(1)}) \\\\ \\nonumber ( \\phi)^{(n+1)} =\n\\frac{1}{3}(\\phi)^{n} + \\frac{2}{3}(\n\\phi)^{(2)} + \\frac{1}{4}\\Delta t (L(\n\\phi)^{(2)}) \\; .\n\\end{eqnarray}\n%%\n\nThe time step is limited by\n%\n\\begin{equation}\n\\Delta t \\leq c \\Delta t_{F.E.}\n\\end{equation}\n%\nwhere $\\Delta t_{F.E.}$ is the forward-Euler time step limited by\nthe Courant-Friedrichs-Levy condition and $c$ is a constant less\nthan or equal to one. \n\nA higher order, multistep method is derived by letting $m > 1$ and choosing appropriate constants for $\\alpha$ and $\\beta$. For this study, two step and three step, strong stability preserving (SSP) coefficients were chosen from Gottlieb et al. \\cite{Gottlieb75}. The coefficients for SSP-RK 2 and SSP-RK 3 are optimal in the sense that the scheme is stable when $c=1$ if the forward-Euler time step is stable for hyperbolic problems. In practice, for the Navier-Stokes equations, the value of $c$ is taken less than one.\n\nChoosing an explicit time stepping scheme, rather than an implict one, creates a challenge for solving the set of equations. The density at the $n+1$ timestep, which is required to determine the cardinal variables, requires an estimation. Taking the estimated density for $\\overline{\\rho}^{n+1}$ to be $\\overline{\\rho}^*$, the estimation can be as simple as $\\overline{\\rho}^* = \\overline{\\rho}^n$. Note that the 2d and 3d filter distinction is dropped for the remainder of this discussion for the sake of simplicity. A slightly more complicated procedure involves a forward-Euler step of the continuity equation to obtain $\\overline{\\rho}^*$. This is written as, \n%\n\\begin{equation}\\label{eqn:rho_update}\n\\overline{\\rho}^{ *} = \\overline{\\rho}^{ n} - \\Delta t \\frac{S_k}{V} n_{kj} \\left( \\overline{\\rho} \\widetilde{u_j} \\right) \\; .\n\\end{equation}\n%\n\n% FIXME: section reference is broken\nIdeally, one would like to know $\\overline{\\rho}^{n+1}$ rather than an estimate. While more details will be discussed in Section \\ref{sec:combust_react_models}, one recognizes that $\\rho$ is a function of the same variables that are being updated in time, namely, the mixture fraction, $f$, and enthalpy, $h$. This quandary is a result of the explicit time stepping method will not be resolved for variable density flows without using a fully implicit method. Explicit methods, however, do have advantages, especially for large scale parallel computations. Specifically, explicit methods are easier to load balance because the amount of work required for each processor is readily determined a priori, which makes for an efficient parallel computation. Explicit methods are also easier to code into a computer and to debug. For these reasons, the current algorithm discussion is limited to explicit methods only. \n\nThe explicit algorithm for solving the set of filtered equations is shown in Algorithm \\ref{alg:LES_algorithm}. \n%\n%\\begin{lstlisting}[float, caption = Explicit LES algorithm, label=alg:LES_algorithm]\n%for t:=t_{min} to t_{max} do \n%fill in later..\n%for $RK_{step}$:=1 to $N$\n%end;\n%end; \n%\\end{lstlisting}\n%\n\\begin{algorithm}[t]\n\\caption{Explicit LES algorithm.}\\label{alg:LES_algorithm}\n%\n\\begin{algorithmic}[] %add [1] for #'s\n\\FOR{$t = t_{min}...t_{max}$}\n\\FOR{$RK_{step} = 1$...$N$} \n\\STATE \tSolve for scalars products $(\\overline{\\rho} \\widetilde{f})^{n+1}$ and $(\\overline{\\rho} \\widetilde{h})^{n+1}$.\n\\STATE\tEstimate $\\overline{\\rho}^* = \\overline{\\rho}^{n+1}$ from Equation \\ref{eqn:rho_update}\n\\IF{$\\overline{\\rho}^* < \\overline{\\rho}_{min}$ or $ \\overline{\\rho}^* > \\overline{\\rho}_{max}$}\n\\STATE $\\overline{\\rho}^* = \\overline{\\rho}^{n}$\n\\ENDIF\n\\STATE Compute $\\widetilde{f}^{n+1} = (\\overline{\\rho}\\widetilde{f})^{n+1}/{\\overline{\\rho}^*}$ and $\\widetilde{h}^{n+1} = (\\overline{\\rho}\\widetilde{h})^{n+1}/{\\overline{\\rho}^*}$ \n\\STATE Compute $\\overline{\\rho}^{n+1} = f(\\widetilde{f}^{n+1}, \\widetilde{h}^{n+1})$\n\\STATE Compute $\\widetilde{\\mathbf{u}}^*$, the unprojected velocities\n\\STATE Perform RK averaging if needed\n\\STATE Compute correct pressure from pressure poisson equation\n\\STATE Project velocities with correct pressure to get $\\widetilde{\\mathbf{u}}^{n+1}$ \n\\ENDFOR\n\\ENDFOR\n\\end{algorithmic}\n\\end{algorithm}\n\n\n\\subsection{Direct Quadrature Method of Moments}\\label{sec:DQMOM}\n\nThe direct quadrature method of moments (DQMOM) is a recently-developed moment method for tracking distributions. It has been applied to distributions of evaporating droplets, soot particle distributions, fluidized beds, and subgrid chemistry PDFs. The method is similar to the quadrature method of moments (QMOM), in that it uses quadrature to provide closure for the moment transport equation; however, it differs in that the moment transport equations are not actually solved, unlike the quadrature method of moments (QMOM). Rather, the DQMOM tracks the quadrature weights and weighted abscissas representing the NDF directly, rather than using the product-difference algorithm to transform between a set of moments and quadrature weights and abscissas that would best represent that distribution.\n\nThe basic outline of the method, given below, defines and covers these fundamental steps and concepts:\n\\begin{enumerate}\n\\item Number Density Function (NDF)\n\\item Moments\n\\item Moment Methods for NDF Transport\n\\item Quadrature\n\\item Direct Quadrature Method of Moments\n\\end{enumerate}\n\nThe number density function is the starting point, as it is the function of interest that is being tracked. Moments are defined, and moment methods are explained and applied to the NDF transport equation to yield the moment transport equation. Furthermore, quadrature is defined and applied to approximate the moments, which leads to a quadrature-approximated moment transport equation. This equation leads to the fundamental equations governing DQMOM.\n\n\\subsubsection{Number Density Function}\\label{subsubsec:NDF}\nUsing the direct quadrature method of moments (DQMOM) in Arches, the dispersed phase is represented as a number density function (NDF), which is tracked in a stationary Eulerian reference frame. \nThe NDF is denoted as $f$ and represents the number of particles at a particular point in space and time. \nUsing DQMOM, this NDF is parameterized on several different variables - independent variables for the particles. \nThese are called ``internal coordinates,'' and are denoted by $\\boldsymbol{\\xi}$ (where boldface denotes a vector quantity). \nIn this case the NDF is written as $f\\left(\\boldsymbol{\\xi};\\boldsymbol{x},t\\right)$.\n\nThe starting point for the DQMOM equations is the NDF transport equation; this is derived in several places and will not be derived here. The NDF transport equation is:\n\\begin{eqnarray}\\label{eq:NDF transport equation}\n \\dfrac{\\partial f \\left( \\boldsymbol{\\xi}; \\boldsymbol{x},t \\right)}{\\partial t} % accumulation term\n + \\dfrac{\\partial}{\\partial x_{i}} \\left( \\left< u_{i} \\vert \\boldsymbol{\\xi}; \\boldsymbol{x}, t \\right> f \\left( \\boldsymbol{\\xi}; \\boldsymbol{x},t \\right) \\right) & & \\nonumber \\\\ % spatial convection term\n + \\dfrac{\\partial}{\\partial \\xi_{j}} \\left( \\left< G_{j} \\vert \\boldsymbol{\\xi};\\boldsymbol{x}, t \\right> f \\left( \\boldsymbol{\\xi}; \\boldsymbol{x},t \\right) \\right) % phase-space convection term\n & = & h \\left( \\boldsymbol{\\xi}; \\boldsymbol{x},t \\right),\n\\end{eqnarray}\n\n\\noindent where $G_{j}$ is the velocity of the NDF in phase-space (that is, internal coordinate-space), and is defined by:\n\\begin{equation}\nG_{j} = \\dfrac{ d \\xi_{j} }{d t}\n\\end{equation}\n\n\\noindent (note this is analogous to spatial velocity $v$, defined by:\n\\begin{equation}\nv_{i} = \\dfrac{ d x_{i} }{d t},\n\\end{equation}\n\n\\noindent and that $G_{j}$ takes the same form as Lagrangian particle models); also, $h$ is a birth and death term representing the appearance or disappearance of particles within the domain. Note also that the velocities $v_i$ and $G_j$ are conditioned on the value of the internal coordinates, as well as on space and time. This implies that the spatial and phase-space velocities are full distributions in $\\left( \\boldsymbol{\\xi}, \\boldsymbol{x} \\right)$ space, just as the NDF is.\n\nThe number of internal coordinates is denoted by $N_{\\xi}$. If $N_{\\xi} = 1$, the NDF is called ``univariate''; if $N_{\\xi} > 1$, then the NDF is called ``multivariate''.\n\n\n\n\\subsubsection{Moments}\\label{subsubsec:moments}\nUsing DQMOM, the particles are represented as an Eulerian distribution - that is, the particles are not treated in an individual sense, but in a statistical sense. In order to represent the NDF in the framework of a scalar CFD code, the NDF must be represented using a set of scalars that can be transported. One such set of scalars, the moments of the NDF, provide useful statistical information about the distribution. Additionally, a distribution can be approximately reconstructed from its moments. The first moment of the distribution represents the mean value; the second, the variance of the distribution; and so on. An arbitrary number of moments can be defined. For a univariate NDF, the $k^{th}$ moment of the NDF is defined as:\n\\begin{equation}\\label{eq:univariate moment definition}\nm_{k} = \\dfrac{ \\displaystyle{ \\int_{-\\infty}^{+\\infty}{\\xi^k f \\left( \\xi ; \\boldsymbol{x},t \\right) d\\xi } } }{ \\displaystyle{ \\int_{-\\infty}^{+\\infty}{ f \\left( \\xi ; \\boldsymbol{x},t \\right) d\\xi } } }\n\\end{equation}\n\nAlternatively, if the NDF is a function of several internal coordinates, the $\\boldsymbol{k}^{th}$ moment is defined as:\n\\begin{eqnarray}\\label{eq:multivariate moment definition}\nm_{\\boldsymbol{k}} & = & \\dfrac{ \\displaystyle{ \\dotsintop_{\\infty}^{+\\infty}{ \\xi_{1}^{k_1} \\dots \\xi_{N_{\\xi}}^{k_{N_{\\xi}}} f \\left( \\xi_1, \\dots, \\xi_{N_{\\xi}} \\right) d\\xi_1 \\dots d\\xi_{N_{\\xi}} } }}\n{ \\displaystyle{ \\dotsintop_{\\infty}^{+\\infty}{ f \\left( \\xi_1, \\dots, \\xi_{N_{\\xi}} \\right) d\\xi_1 \\dots d\\xi_{N_{\\xi}} } } }\n%m_{\\boldsymbol{k}} & = & \\dfrac{ \\displaystyle{ \\dotsintop_{-\\infty}^{+\\infty} \\xi_{1}^{k_1} \\dots \\xi_{N_{\\xi}}^{k_{N_{\\xi}}} f \\left( \\xi_1, \\dots \\xi_{N_{\\xi}} \\right) d\\xi_1 \\dots d\\xi_{N_\\xi} }{ \\displaystyle{ } }\n%\t\t\t\t& = & \n\\\\\nm_{\\boldsymbol{k}} & = & \\dfrac{{\\displaystyle \\dotsintop_{-\\infty}^{+\\infty}}\\left[\n\\left({\\displaystyle \\prod_{m=1}^{N_{\\xi}}}\\xi_{m}^{k_{m}}\\right)\n\\, f(\\boldsymbol{\\xi};\\boldsymbol{x},t)\\, d\\boldsymbol{\\xi}\\right]}{{\\displaystyle \\dotsintop_{-\\infty}^{+\\infty}}\\, f(\\boldsymbol{\\xi};\\boldsymbol{x},t)\\, d\\boldsymbol{\\xi}}\n\\end{eqnarray}\n\n\\noindent where $\\boldsymbol{k} = \\left[ k_1, k_2, \\dots k_{N_{\\xi}} \\right] $ is the multivariate moment index.\n\n\n\n\\subsubsection{Moment Methods for NDF Transport}\\label{subsubsec:momentmethods}\n\nThe method of moments is a method of tracking the NDF of a system of particles. Because the NDF is a full, continuous distribution, it is difficult to track without assuming a functional form for it. Rather than assume a functional form, the moments of the NDF, which are simply scalars, are tracked instead. This method requires tracking various scalars, which is computationally feasible in a scalar framework and which greatly simplifies the process of tracking the NDF. However, the approach has a closure problem that prevents it from being used in practice for any but the most simple systems.\n\nThe transport equation for each moment must be written in terms of higher order moments, and the transport equations for these higher order moments must be written in terms of successively higher order moments, etc. Simplifications (models) must be used to express higher order moments only in terms of lower order moments being tracked as a part of the method of moments. Once this is accomplished, the set of moment transport equations becomes a closed set of equations.\n\n\n\n\\subsubsection{Quadrature}\\label{subsubsec:quadrature}\n\nQuadrature approximates the integral of an unknown function with tabulated known values as a summation of a set of $N$ weighted abscissas. It determines a polynomial of degree $2N-1$ whose zeros are the $N$ weighted abscissas, and approximates the unknown function using this polynomial [Press 1992]. There are several common quadrature formulations, including the midpoint rule (the unknown function is assumed to be a constant, or zero-order polynomial), the trapezoid rule (the unknown function is assumed to be a straight line, or first-order polynomial), and Simpson's rule (the unknown function is assumed to be a second-order polynomial). Note that while the unknown function does not have to be a polynomial, the quadrature approximation becomes much better if it is (and exact if the unknown function is a polynomial of degree $2N-1$ or less). The general $N$-point quadrature formula can be written as:\n\n\\begin{equation}\\label{eq:quadrature-definition}\n\\int_{a}^{b}w(r)g(r)\\, dx\\approx{\\displaystyle \\sum_{\\alpha=1}^{N}w_{\\alpha}g(r_{\\alpha})}\n\\end{equation}\n\n\\noindent where $g(r)$ is an arbitrary function of the variable $r$. As $N$ increases, the quadrature approximation usually becomes more accurate. This equation can also be extended to a multivariate function $g(\\mathbf{r)}$, an arbitrary function of the $D$-element vector $\\mathbf{r}=\\left[r_{1},r_{2},\\dots,r_{D}\\right]$ to yield:\n\n\\begin{equation}\\label{eq:multivariate-quadrature-definition}\n{\\displaystyle \\int_{a}^{b}w(\\mathbf{r})g(\\mathbf{r)}d\\mathbf{r}}\n\\end{equation}\n\nThe weights are common to all internal coordinates $\\mathbf{r}$ because the weight function $w(\\mathbf{r})$ is binned into $N$ discrete weights, and this weight function is common to all internal coordinates.\n\n\n\n\\subsubsection{Quadrature-Approximated Moment Transport Equation}\\label{subsubsec:quadapproximated}\n\nWhen the quadrature approximation is applied to a multivariate NDF (where the NDF is the weight function), it yields:\n\n\\begin{eqnarray}\\label{eq:quadrature-approximated-ndf}\nf(\\boldsymbol{\\xi};\\mathbf{x},t) \n& \\approx & {\\displaystyle \\sum_{\\alpha=1}^{N}\\left(w_{\\alpha}(\\boldsymbol{x},t){\\displaystyle \\,\\boldsymbol{\\delta}\\left(\\boldsymbol{\\xi}-\\left\\langle \\boldsymbol{\\xi}(\\boldsymbol{x},t)\\right\\rangle _{\\alpha}\\right)}\\right)} \\nonumber \\\\\n& \\approx & {\\displaystyle \\sum_{\\alpha=1}^{N}\\left(w_{\\alpha}(\\boldsymbol{x},t){\\displaystyle \\prod_{j=1}^{N_{\\xi}}\\delta\\left(\\xi_{j}-\\left\\langle \\xi_{j}(\\boldsymbol{x},t)\\right\\rangle _{\\alpha}\\right)}\\right)}\n\\end{eqnarray}\n\n\\noindent which makes the integral of the NDF:\n\n\\begin{eqnarray}\\label{eq:quadrature-approximated-ndf-integral}\n{\\displaystyle \\int_{-\\infty}^{+\\infty}}\\boldsymbol{\\xi}^{\\boldsymbol{k}}f\\, d\\boldsymbol{\\xi}\n&\\approx&{\\displaystyle \\sum_{\\alpha=1}^{N}\\left\\{ w_{\\alpha}\\left(\\prod_{j=1}^{N_{\\xi}}\\langle\\xi_{j}\\rangle_{\\alpha}^{k_{j}}\\right)\\right\\} }\n\\end{eqnarray}\n\nThis quadrature-approximated NDF can then be substituted into the moment definition to get a quadrature-approximated moment,\n\n\\begin{equation}\\label{eq:quadrature-approximated-moment}\nm_{\\boldsymbol{k}}\\approx\\sum_{\\alpha=1}^{N}\\left\\{ p_{\\alpha}\\left(\\prod_{j=1}^{N_{\\xi}}\\langle\\xi_{j}\\rangle_{\\alpha}^{k_{j}}\\right)\\right\\} \n\\end{equation}\n\n\\noindent where $p_{\\alpha}$ is the probability of environment $\\alpha$ (defined as $w_{\\alpha} / \\sum_{i=1}^{N} w_{i} $), $\\boldsymbol{k}$ is the multivariate moment index vector, and $k_{j}$ is the $j^{th}$ element of vector $\\boldsymbol{k}$ (with a total of $N_{\\xi}$ values).\n\nStarting with the NDF transport equation, the moment transform can be taken, yielding the moment transport equation. Next, the quadrature approximation can be plugged in, which yields the quadrature-approximated moment transport equation. After some algebraic manipulation, this yields:\n\n\\begin{multline}\\label{eq:quadrature-approximated-moment-xport-eqn}\n{\\displaystyle {\\displaystyle \\sum_{\\alpha=1}^{N}\\left[\n{\\displaystyle \\prod_{j=1}^{N_{\\xi}}}\\delta\\left(\\xi_{j}-\\left\\langle \\xi_{j}\\right\\rangle _{\\alpha}\\right)\n+\\sum_{m=1}^{N}\\dfrac{\\partial}{\\partial\\langle\\xi_{m}\\rangle_{\\alpha}}\\left(\\prod_{j=1}^{N_{\\xi}}\n\\delta\\left(\\xi_{j}-\\left\\langle \\xi_{j}\\right\\rangle _{\\alpha}\\right)\n\\right)\\langle\\xi_{m}\\rangle_{\\alpha}\\right]}a_{\\alpha}} \\\\\n-\\sum_{\\alpha=1}^{N}\\sum_{n=1}^{N}\\left[\\dfrac{\\partial}{\\partial\\langle\\xi_{n}\\rangle_{\\alpha}}\\left(\\prod_{j=1}^{N_{\\xi}}\n\\delta\\left(\\xi_{j}-\\left\\langle \\xi_{j}\\right\\rangle _{\\alpha}\\right)\n\\right)\\right]b_{n\\alpha}= \\\\\n{\\displaystyle \\sum_{\\alpha=1}^{N}\\sum_{m=1}^{N_{\\xi}}\\sum_{n=1}^{N_{\\xi}}}\\left[\\dfrac{\\partial^{2}}{\\partial\\langle\\xi_{m}\\rangle_{\\alpha}\\partial\\langle\\xi_{n}\\rangle_{\\alpha}}\\left({\\displaystyle \\prod_{j=1}^{N_{\\xi}}\n\\delta\\left(\\xi_{j}-\\left\\langle \\xi_{j}\\right\\rangle _{\\alpha}\\right)\n}\\right)\\right]C_{mn\\alpha} \\\\\n+S_{\\xi}+D_{\\xi}+h,\n\\end{multline}\n\n\\noindent where $a_{\\alpha}$ and $b_{n,\\alpha}$, defined as:\n\n\\begin{eqnarray}\\label{eq:a-b-transport-eqns}\n\\dfrac{\\partial}{\\partial t}\\left( w_{\\alpha} \\right)\n+\\dfrac{\\partial}{\\partial x_{i}}\\left( \\langle u_{i}\\rangle_{\\alpha}w_{\\alpha} \\right)\n-\\dfrac{\\partial}{\\partial x_{i}} \\left( D_{x,\\alpha} \\dfrac{\\partial}{\\partial x_{i}} \\left( w_{\\alpha} \\right) \\right)\n&=&a_{\\alpha} \\\\\n\\dfrac{\\partial}{\\partial t}\\left( \\varsigma_{n\\alpha} \\right)\n+\\dfrac{\\partial}{\\partial x_{i}}\\left( \\langle u_{i}\\rangle_{\\alpha}\\varsigma_{n\\alpha} \\right) \n-\\dfrac{\\partial}{\\partial x_{i}}\\left( D_{x,\\alpha} \\dfrac{\\partial}{\\partial x_{i}} \\left( \\varsigma_{n,\\alpha} \\right) \\right) \n&=&b_{n\\alpha}, \\\\\n&&\\nonumber \\\\ \n\\text{for }j=1\\dots N_{\\xi} & & \\nonumber\n\\end{eqnarray}\n\n\\noindent are the transport equations implemented to track the evolution of the NDF. The source terms $a_{\\alpha}$ and $b_{n,\\alpha}$ come from the solution to the linear system\n\n\\begin{equation}\\label{eq:Ax=B}\n\\mathbf{Ax} = \\mathbf{B}.\n\\end{equation}\n\n\\subsubsection{Build of Ax=B}\\label{subsubsec:buildAX=B}\nThere are $N_e(N+1)$ unknowns for $a_a$ and $b_{na}$, while there\nare just one linear equations for them. In order to build a complete\nlinear system, $N_e(N+1)-1$ moments are needed. And DQMOM method\nis used to build this linear system. Using properties of delta functions,\nthe $k^{th}$ moment for Eq.(\\ref{eq:a-b-transport-eqns}) is derived\nas\n\n\n\n\\begin{equation}\n\\begin{split}\n\\sum_{a=1}^{N_{e}}\\left[\\left(\\prod_{n=1}^{N}\\left<\\xi_{n}^{k_n}\\right>_{a}\\right)-\\sum_{m=1}^{N}k_m\\left(\\left<\\xi_{m}^{k_m}\\right>_{a}\\right)\\left(\\prod_{n=1,n\\neq m}^{N}\\left<\\xi_{n}^{k_n}\\right>_\\alpha\\right)\\right]a_{a}\n\\\\\n+\\sum_{a=1}^{Ne}\\sum_{n=1}^{N}\\left[k_n\\left<\\xi_{n}^{k_n-1}\\right>_{a}\\left(\\prod_{m=1,m\\neq n}^{N}\\left<\\xi_{m}^{k_m}\\right>_{a}\\right)\\right]b_{a,n}=\n\\\\\n\\sum_{a=1}^{Ne}\\sum_{m=1}^{N}\\left[k_m\\left(k_m-1\\right)\\left<\\xi_m^{k_m-2}\\right>_a\\times\\left(\\prod_{j \\neq m,j=1}^{N_\\xi}\\left<\\xi_j^{k_j}\\right>_a\\right)\\right]{w}_a{C}_{mma}+\n\\\\ \\sum_{a=1}^{Ne}\\sum_{m=1}^{N}\\sum_{n=1}^{N}\\left[k_mk_n\\left<\\xi_{m}^{k_m-1}\\right>_{a}\\left<\\xi_n^{k_n-1}\\right>_a\\times\\left(\\prod_{j=1,j \\neq m}^{N}\\left<\\xi_{j}^{k_j}\\right>_{a}\\right)\\right]w_{a}C_{mna}+\\bar{S}_{k}+\\bar{D}_{k}\n\\end{split}\n\\label{eq:kth_moment}\n\\end{equation}\n\nand\n\n\\begin{equation}\n\\bar{S}_{k}=-\\sum_{a=1}^{N_{e}}\\sum_{n=1}^{n}\\left[\\left(\\prod_{m=1,m\\neq n}^{N}\\left<\\xi_{m}^{k_{m}}\\right>\\right)\\left(k_{n}\\left<\\xi_{n}^{k_{n}-1}\\right>_{a}\\right)\\left(w_{a}\\left_{a}\\right)\\right]\n\\end{equation}\n\n\n\\begin{equation}\n\\bar{D}_{k}=\\sum_{a=1}^{N_{e}}\\sum_{n=1}^{n}\\left(\\prod_{m=1,m\\neq n}^{N}\\left<\\xi_{m}^{k_{m}}\\right>_{a}\\right)\\left(k_{n}\\left(k_{n}-1\\right)\\left<\\xi_{n}^{k_{n}-2}\\right>\\right)\\left(w_{a}\\Gamma_{\\xi_{n},a}\\right)\\label{eq:Dk_bar}\n\\end{equation}\n\n\nwhere $k_m$ represent the $k^{th}$ moment for the $m^{th}$ internal\ncoordinates. With a reasonable selection of the moments for each internal\ncoordinates, a linear system with a rank of $N_e\\left(N+1\\right)$\ncan be constructed by\n\n\\begin{equation} \\label{eq:AXeqB1}\n[A_{1},A2]*[a_{a},b_{an}]^{\\textrm{T}}=[C_{k}+\\bar{S}_{k}+\\bar{D}_{k}]^{\\textrm{T}}\n\\end{equation}\n\n\\subsubsection{solution of DQMOM matrix} \\label{subsubsec:solutionax=b}\nThe detailed solution method can be find in Charles and Julien's Thesis \\cite{Charles_DQMOM, Julien_thesis}. The typical LU solution will offten met singular problems, so Rodney provided a method to rebuild matrix A and B to avoid this problem\\cite{RF_2009}. This method is named as \"Optimize\" in block. However, the \"Optimize\" method is very time consuming.\n\n\\subsubsection{Simplest method in DQMOM} \\label{subsubsec:Simplest}\nIn order to save CPU times for DQMOM method, some simplified method can be adopted to define the source term for \\ref{eq:a-b-transport-eqns}, or $X$. For coal combustion case, when the following assumption was adopted\n\\begin{itemize}\n\\item Assuming that any scalars distribution of the coal particles can be\nperfectly represented by multi-delta functions, especially, the particle\nvelocity distribution can be perfectly represented by $\\left$,\nso that there is no diffusion terms. In other words, the third term\nat the right side and $D_\\xi$ in Eq.(\\ref{eq:AXeqB1}),\nare omited. This is only correct for each single particle, so that\nintegral of Eq.(\\ref{eq:quadrature-approximated-moment-xport-eqn}) with a\nmoment becomes the Langrangian particle equations as:\n\\end{itemize}\n\\begin{equation}\n\\frac{d\\xi^{m}}{dt}=S_{\\xi^{m}}\n\\end{equation}\n\nwhere $\\xi^m$ is the moment that we are interested. As long as we\nconsider a reprentative particles for a group of particles, such diffusion\nterm will exists, which are hard to be modeled. A reasonable way to\neliminate the effect of diffusion term is to increase the phase numbers.\n(but this will meet other chanllenges, for e.g., for the dense phase,\nthe interactions between two phases need to be considered, the computation\ncost would be hudge).\n\\begin{itemize}\n\\item For pulverized coal combustion system, the particles are very dispersed,\nso that any particle-particle interactions is small enough (comparing\npartile-gas interactions) to be omited. With this assumption, the\nsource term, $S_\\xi$ can be easily represented by the single particle\nmodels, so that Langrangian style models can be used.\n\\item There is no particle death or birth, so that the weights do not change\nwith the internal coordinates $\\xi$. In other words, $a_a$ in Eq.(\\ref{eq:a-b-transport-eqns})\nequals to 0 and the rank of the linear system is reduced from $N_e(N+1)$\nto $N_eN$.\n\\end{itemize}\nTaking these three assumptions, the linear system can be reduced further,\nsince there is no diffusion terms, the right side of Eq.(ref\\{eq:kth\\_moment\\})\nis reduced to $\\bar{S}_k$. Then we just consider the first moments\nfor $\\xi_{n,a}$ and $0^{th}$ moments for other $\\xi$(let $k_n=1, and k_(m\\neq n)=0$\nfor the $p^{th}$ phase. This makes the linear system, Eq.(\\ref{AXeqB})\nreduces to\n\n\\begin{equation}\n0+\\ldots+\\text{0+}b_{n,a}+0+\\ldots0=w_{a}\\left_{a}=w_{a}\\frac{d\\xi_{n,a}}{dt}\n\\end{equation}\n\n\nThat means the linear system is already solved without any further\ncalculations (no need of solving linear systems). and the transport\nequations of the weights and weighted abscissas finally are simplified\nto\n\n\\begin{equation}\n\\frac{\\partial}{\\partial t}\\left(w_{a}\\right)+\\frac{\\partial}{\\partial x_{i}}\\left(\\left_{a}w_{a}\\right)=0\\label{eq:ap_transport-simple}\n\\end{equation}\n\n\n\\begin{equation}\n\\frac{\\partial}{\\partial t}\\left(\\zeta_{n,a}\\right)+\\frac{\\partial}{\\partial x_{i}}\\left(\\left_{a}\\zeta_{n,a}\\right)=w_{a}\\frac{d\\xi_{n,a}}{dt}\\label{eq:simplified_transport_equation}\n\\end{equation}\n\n\nIt should be noted these are instantaneous equations, and SGS model\nshould be considered for LES simulation. If we know the diffusion\nmodels, and just with no birth/dirth of particles. There are also\nno need to solve the transport equations, if only the internal coordinates\nare independent, or if we can build the direct correlation among these\ndependent moments. For e.g., if we have to consider the particle surface\nand the particle diameter as well as the particle volume, these internal\ncoordinates are correlated, and linear system is needed to be built\nfor such dependent moments if the particle diameter, surface and volume\nchange can't be decribed by three separate models. For the coal combustion\nsystems we are considering, the internal coordinates are independent,\nso there is no need to solve the linear system. and the final transport\nequations are\n\n\\begin{equation}\n\\frac{\\partial}{\\partial t}\\left(w_{a}\\right)+\\frac{\\partial}{\\partial x_{i}}\\left(\\left_{a}w_{a}\\right)+\\frac{\\partial}{\\partial x_{i}}\\left(D_{x,p}\\frac{\\partial}{\\partial x_{i}}\\left(w_{a}\\right)\\right)=0\\label{eq:ap_transport-simp_diffusion}\n\\end{equation}\n\n\n\\begin{equation}\n\\frac{\\partial}{\\partial t}\\left(\\zeta_{n,a}\\right)+\\frac{\\partial}{\\partial x_{i}}\\left(\\left_{a}\\zeta_{n,a}\\right)+\\frac{\\partial}{\\partial x_{i}}\\left(D_{x,a}\\frac{\\partial}{\\partial x_{i}}\\left(\\zeta_{n,a}\\right)\\right)=w_{a}\\frac{d\\xi_{n,a}}{dt}+D_{\\xi_{n,a}}\\label{eq:simplified_transport_equation_with diffusion}\n\\end{equation}\n\n\nThe chanllenge is that $D_{x,a}$ and $D_{\\xi_{n,a}}$ almost can't\nbe modeled (seems $D_{\\xi_{n,a}}=0$ when multi-delta functions adopted, according to Eq.(\\ref{eq:Dk_bar}).\nand we'd rather to consider more phases to elimate the diffusion terms. \n\n\n\nTaking the assumptions mentioned above, the transport equations of\nPBE in form of PDF acutally degenerate to multi-phase Euler-Euler\nequations without consideration phase-phase interactions (except for\ngas-particle interactions). If the particle phase are enough so that\neach particle is represented by a phase, Eq(\\ref{eq:ap_transport-simple})\nand Eq(\\ref{eq:simplified_transport_equation_with diffusion}) are\nactually Lagrangian method. Or in other words, the simplest case we\nadopted with DQMOM method equvalent that we are using Lagrangian method\nto track infinitely large number of particles falling to only $Ne$\ncategories (each categories of particle has the same values for all\n$N$ internal coordinates). \n\n\n\n\n\\subsubsection{Summary}\\label{subsubsec:summary}\nIn summary, the DQMOM solution procedure requires solving several transport equations, given by \\ref{eq:a-b-transport-eqns}. These transport equations describe the changes in the quadrature weights and weighted abscissas used to approximate the NDF. The source terms for these transport equations, $a_{\\alpha}$ and $b_{n,\\alpha}$, come from the solution to a linear system, $\\mathbf{Ax}=\\mathbf{B}$, in which the vector $\\mathbf{x}$ contains the source terms. This linear system comes from the quadrature-approximated moment trasport equation, equation \\ref{eq:quadrature-approximated-moment-xport-eqn}, of which there are $\\left(N_{\\xi} + 1\\right)N$. It is because this set of equations is linear in the unknowns $a_{\\alpha}$ and $b_{n,\\alpha}$ that it can be re-cast in the form of a linear system.\n\n\\subsection{Wall Heat Transfer Model in Arches} \\label{subsec:WHT}\n\\subsubsection{Basic assumptions and models for wall heat transfer}\n\nThe basic assumptions are as follows:\n\\begin{itemize}\n\\item Wall is regarded as black body, the heat released by the wall is calculated\nby Stefan-Boltzmann law, this assumption is consistant to the assumption\nadopted in DO radiation method in ARCHES.\n\\item There is no time derivation term for wall heat transfer, in other\nwords, wall temperature comes to equilibrium state instantaneously\nat each time step. While a relaxation coefficient, $C_{rex}$, is\nadopted to smooth the wall temperature change, or $T_w=(1-C_{rex})T_{w0}+C_{rex}T_w$.\n\\item When considering convection heat transfer, the gas temperature is\nrepresent by the Cell-Center gas temperature adjecent to the wall,\nPr and Re is calculated based on the velocities and properties of\nthe CC value adjecent to the wall. But up to now, no convection heat\ntransfer is considered in ARCHES.\n\\item thermal resistance from fluid to the tubes is small enough to be neglected,\nso that inside tube wall temperature is set to a constant value. (\nin arches.spec)\n\\end{itemize}\nThe wall heat transfer is calculated by\n\n\\begin{equation}\nq_{net}=(T_{w}-T_{in})/R_{wc}\\label{eq:wallht}\n\\end{equation}\n\n\n\\begin{equation}\nq_{net}=\\epsilon_{w}(q_{in}-q_{rad\\_w})+q_{conv}\\label{eq:net}\n\\end{equation}\n\n\nwhere $q_{net}$ is the heat flux absorbed by the wall. $q_{in}$\nis the incidental radiation heat flux from the ambient gas phase to\nthe wall surface, which is provided by radiation solver in ARCHES,\n$q_{rad\\_w}$ is the heat flux of the black-body wall emission, and\ncan be calculated by\n\n$q_{rad\\_w}=\\sigma T_{w}^{4}$\n\n$q_{conv}$ is the heat flux absorbed by the wall through convection,\n$T_w$ and $T_{in}$ are the wall surface temperature (represented\nby 'temperature' in ARCHES simulation) and fluid temperature inside\nwall tubes (), and $R_{wc}$ is the wall thermal resistance,\n$R_{wc}=l/\\lambda$, $l$ is the in areches.spec,\nand $\\lambda$ is in arches.spec.\n\n\n\\subsubsection{Algorithms of wall heat transfer solution in Arches\\label{sec:Algorithms-of-wall}}\n\nEq.\\ref{eq:wallht} can be recasted by\n\n\\begin{equation}\nT_{w}=T_{in}+q_{net}R_{wc}\\label{eq:3}\n\\end{equation}\n\n\nBased on Eq.\\ref{eq:3}, an iterative algorithm was proposed to solve\n$T_w$:\n\\begin{enumerate}\n\\item Taking an initial $T_w$ and calculate $q_{net}$ by Eq.(\\ref{eq:net}) \n\\item Calculate $T_w$ by Eq.\\ref{eq:3}. And return back to Step.1\n\\end{enumerate}\nSince $q_{net}$ is sensitive to $T_w$ due to Stefan-Boltzmann law,\nthis iteration method is unstable and it's hard to get the final resolutions.\nSo an relaxation coefficient was introduced to help converge. Then\nthe final iteration method would be\n\\begin{enumerate}\n\\item calculate $q_{net}$ based on $T_{w0}$ by Eq.\\ref{eq:wallht}\n\\item Calculate $T_{w1}$ with Eq.\\ref{eq:3}\n\\item Calculate renewed $T_{w1}$ by $T_{w1}=(1-C_{relx})T_{w0}+c_{relx}T_w'$.\nThen go back to step1 with $T_{w1}$\n\\end{enumerate}\nThis Relaxation Iteration Method (RIM) can be used to get the final\n$T_w$ at each timestep. Although with small Relaxation Coefficient,\nRIM method may still be unstable if $R_{wc}$ is very large.\n\n$T_w$ can also be calculated by another iterations method such as\nDichotomy Iteration Method (DIM)as follows:\n\\begin{enumerate}\n\\item To set a maximum wall temperatrue $T_{wmax}$ and a minimum wall temperature\n$T_{wmin}$.\n\\item to calculate initial wall temperature $T_{w0}=(T_{wmax}+T_{wmin})/2$\n\\item To calculate $T_{w1}$ with Eq\\ref{eq:wallht}, Eq\\ref{eq:net} and\nEq\\ref{eq:3}.\n\\item if $T_{w1}>T_{w0}$, then $T_{wmin}=T_{w0}$; if $T_{w1} and in arches.spec), the\nDIM will have very small cost. \n\n\\subsubsection{black body or grey body assumption?}\n\nUp to now, the wall emissivity $\\epsilon_{w}$ in Eq.\\ref{eq:net}\nis set to 1.0 in arches code, since that in DO model, the wall is\nassumed to be the black-body. If the grey body assumption has to be\nconsidered, we must make sure that radiation model (DO or RMCRT) also\nconsider a greybody condition for the wall. Still, there is a trick\nto treat the wall as greybody in wall heat transfer model while keep\nadopting blackbody assumptions in Radiation model. The trick is as\nfollows:\n\\begin{enumerate}\n\\item take an $\\epsilon_{w}$ of less than one in Eq.\\ref{eq:net}, and\ncalculate the grey wall temperature $T_{w1}$ and $Q_{net}$ with\nthe iteration method mentioned in Section\\ref{sec:Algorithms-of-wall}.\n\\item To modify the wall temperature from $T_{w1}$ to $T_w$, so that\nthe following equations are satisfied: $q_{net}=q_{in}-\\sigma T_{w}^{4}$.\nGenerally the difference between $T_w$ and $T_{w1}$ is no more than\n20K if $\\epsilon_{w}=0.8$. So the emissivity won't change the wall\ntemperature a lot. However, it will be better if the wall reflection\ncan be considered in the radiation model.\n\\end{enumerate}\n\n\\subsubsection{numerical steadyness, especially for adiabatic wall BC or small thermal\nconductivities}\n\nIn Section.\\ref{sec:Algorithms-of-wall}, the calculation of $T_w$\nis proposed for each times step. During LES simulation, $q_{in}$\nwill change with $T_w$ as well. The following conditions will cause\nthe numerical simulation of $T_w$ unsteady\n\\begin{itemize}\n\\item A bad initial temperature assumption: a bad initial temperature assumption\nwill casue a bad initial $q_{in}$, and thus a bad $T_w$, although\n$T_w$ is 'accurate' at this timestep, it's a fake wall temperature\nand may have negative effect on $q_{in}$ in next step.\n\\item When simulation case is large and simulation domain is complex, the\nprevious tests show that the simulation is sentitive to wall temperature.\nIf $T_w$ changes frequently and changes in a large range, this may\ncause some numerical problems in Arches simulation. \n\\end{itemize}\nwith these consideration, it's better to change $T_w$ smoothly when\n$q_{in}$ is sensitive to $T_w$. So at the beginning of simulation,\na small relaxation coefficient can be adopted to control the change\nof $T_w$. When simulation comes to a steady state, RIM and DIM moethod\ncan be directly adopted to get the final $T_w$. However, the strategy\nof $T_w$ calculation depends on the real physical problems. \n\nFor adiabatic wall boundary conditions, since the thermal resisitance\n($R_{wc}$) is infinitly large, numerical steady is a challenge when\nwe use iterative method to calculate Eq.\\ref{eq:3}, and DIM is a\ngood way to solve this problem. In ARCHES, the DIM method is adopted\nand the adiabatic wall will be well solved. Still, a small relaxation\ncoefficient, $C_{rex}$, is recommend to be adopted. For e.g., $C_{rex}=0.05$,\nwhich will help to acquire a smooth change of wall temperature with\ntime.\n\n\n\n\n\n\n\\subsection{Digital Filter Generator for Turbulent Inlet Conditions}\\label{sec:DFG}\nThe digital filter method generates a set of both spatially and temporally correlated random data in order to create a synthetic turbulent inlet. In the Arches implementation, the data is generated a priori.\n\n\\subsubsection{Digital Filter}\nLet $r_m$ be a set of random data such that $\\left\\rangle r_m \\right\\rangle = 0$ and $\\left\\lbrace r_m^2 \\right\\lbrace =1$. Then there exists a set of filter coefficients $b_n$ for the convolution such that\n\n\\begin{equation} \\label{eq:DFGconv}\nu_m = \\sum_{-N}^N b_n r_{m+n}\n\\end{equation}\n\nwhere $N$ is the support of the filter. If \\ref{eq:DFGconv} is rearranged in the form of an autocorrelation function then it follows that\n\n\\begin{equation} \\label{eq:DFGauto}\n\\frac{\\bar{u_m u_{m+k} } }{ \\bar{u_m u_m } } = \\sum_{j=-N+k}^N b_j b_{j-k} \\big/ \\sum_{j=-N}^N b_j^2\n\\end{equation}\n\nFor extending filter coefficients to three dimensions a simple convolution of the three one-dimensional filters is used.\n\n\\begin{equation} \\label{eq:DFG3D}\nb_{ijk} = b_i \\cdot b_j \\cdot b_k\n\\end{equation}\n\nNow consider a fully developed flow. A fit line for its autocorrelation function can be expressed as an exponential decay\n\n\\begin{equation}\nR_{uu} (r) = \\exp \\left( - \\frac{ \\pi r^2}{4 L^2} \\right)\n\\end{equation}\n\nwhere L is the integral length scale. If the grid spacing is $\\Delta x$ then the length scale can be set as $L = n \\Delta x$, and the discrete autocorrelation function is then\n\n\\begin{equation}\nR_{uu} ( k \\Delta x) = \\exp \\left( - \\frac{ \\pi (k \\Delta x)^2}{4 (n \\Delta x)^2} \\right) = \\exp \\left( - \\frac{ \\pi k^2}{4 n^2} \\right)\n\\end{equation}\n\nNow apply \\ref{eq:DFGauto} to relate the discrete autocorrelation function to the filter coefficients\n\n\\begin{equation}\nR_{uu} (k \\Delta x) = \\frac{ \\bar{ u_m u_{m+k} } }{ \\bar{u_m u_m} } = \\sum_{j=-N+k}^N b_j b_{j-k} \\big/ \\exp \\left( - \\frac{ \\pi k^2}{4 n^2} \\right)\n\\end{equation}\n\nThere is an approximate solution to the filter coefficients available\n\n\\begin{equation} \\label{eq:DFGfiltercoef}\nb_k \\approx \\tilde{b}_k \\big/ \\left( \\sum_-N^N \\tilde{b}_j^2 \\right)^{1/2} \\; \\; \\text{with} \\; \\; \\tilde{b}_k = \\exp \\left( - \\frac{ \\pi k^2}{2 n^2} \\right)\n\\end{equation}\n\nwhich is a valid approximation as long the the filter support is sufficiently large, $N \\geq 2n$. This maintains the the support of the filter is large enough to capture twice the length scale. This is a brief explanation of the method from Klein's paper \\cite{Klein2003}. Note that as $ N \\rightarrow 0$ this method approaches white noise.\n\n\\subsubsection{Implementation Algorithm}\nThe steps in generating the inlet data are listed here directly from Klein's procedure for isotropic flow \\cite{Klein2003}.\n\n\\begin{enumerate}\n\\item Choose a length scale for each coordinate direction as$ L_{y}=n_{y}\\Delta y , L_{z}=n_{z}\\Delta z $ and a timescale for the flow direction (or length scale by Talyor's hypothesis) $T_{x}=n_{t}\\Delta t$ (or $L_{x} = n_x \\Delta x$ ), set the size of the support $N_{\\alpha}\\geq 2n_{\\alpha} $ for $\\alpha=x,y,z$ . Also prescribe a mean flow profile.\n\\item Initialize three random fields $\\mathcal{R}_{\\alpha}$ of dimensions $[-N_{x}:N_{x},-N_{y}+1:M_{y}+N_{y},-N_{z}+1:M_{z}+N_{z} ]$ , with $M_{y}\\times M_{z}$ denoting the resolution of the grid of the inflow plane. The size is actually $[2N_{x}+1,2N_{y}+M_{y},2N_{z}+M_{z} ]$.\n\\item Calculate the filter coefficients b(i,j,k), using \\ref{eq:DFGfiltercoef}\n\\item Loop over the inlet dimensions j and k and apply the filter operation for each velocity fluctuation\n\\begin{equation} \\label{eq:DFGmain}\n\\mathcal{U}_{\\alpha}(j,k)=\\sum_{i'=-N_{x}}^{N_{x}}\\sum_{j'=-N_{y}}^{N_{y}}\\sum_{k'=-N_{z}}^{N_{z}}b(i',j',k')\\mathcal{R}_{\\alpha}(i',j+j',k+k') \n\\end{equation}\n\\item Using the time-averaged Reynold's stress tensor ($R_{ij}$) solve for the transformation matrix $a_{ij}$\n\\begin{equation}\n a_{ij}=\\left[\\begin{array}{ccc}\n(R_{11})^{1/2} & 0 & 0\\\\\nR_{21}/a_{11} & (R_{22}-a_{21}^{2})^{1/2} & 0\\\\\nR_{31}/a_{11} & (R_{32}-a_{21}a_{31})/a_{22} & (R_{33}-a_{31}^{2}-a_{32}^{2})^{1/2}\n\\end{array}\\right] \n\\end{equation}\n\\item Now solve for each of the velocity components\n\\begin{equation}\nu_{i}=\\bar{u_{i}}+a_{ij}\\mathcal{U}_{j} \n\\end{equation}\n\\item Shift the random data set by the flow direction $\\mathcal{R}_{\\alpha}(i,j,k)=\\mathcal{R}_{\\alpha}(i+1,j,k)$ , and fill the last plane $\\mathcal{R}_{\\alpha}(N_{x},j,k)$ with new random numbers.\n\\item Repeat steps 4 through 7 for each timestep\n\\end{enumerate}\n\nIn Arches two major changes are made to this algorithm. First the data is all pre generated into a table that is loaded when the simulation starts. This happens because the summation in \\ref{eq:DFGmain} can become very expensive at high resolution and occurs at each point in the boundary, and some issues with trying to deal with the random field at patch boundaries. The second is that the option to use Taylor's hypothesis of frozen turbulence is utilized so that the length scale is specified in the flow direction, rather than the time scale. Then the same flow profile is reused for several timesteps, this period is either specified as the number of steps or as a time.\n\n\n% ==========================================================\n% =============== Uintah Specifications =========================\n% ==========================================================\n\\section{Uintah Specification}\n%\n\\subsection{Basic Inputs}\n%\nChoosing the ARCHES component is done through the simulation controller using the {\\it SimulationComponent} tag. In this case (similar to the other Uintah components) the Arches component is specified as\n%\n\\begin{Verbatim}[fontsize=\\footnotesize]\n\n\\end{Verbatim}\n%\nas a child of the \\verb== section. \n\nMost other Arches specifications are located in the {\\it CFD$\\rightarrow$ARCHES} section of the input file. Unless otherwise specified, the system of units for all Arches input parameters are SGI.\n\n\\subsection{Boundary Conditions}\\label{sec:boundaryconditions}\nBoundary conditions for Arches are specified using the Uintah boundary condition mechanism. As such, all boundary conditions for domain faces are specified in the \\verb==$\\rightarrow$\\verb== section of the input file. Generic details of the UCF boundary condition mechanism may be found in \\ref{sec:ucf_bc}. \n\nGenerally, boundary conditions are required for every transport equation except at periodic boundaries. Specifically, every equation specified in the \\verb== section of the input file requires domain boundary specification on every domain face. \n\nThe generic options for the boundary condition type include \\verb=Dirichlet= and \\verb=Neumann= conditions. For the \\verb=Dirichlet= condition, transported variables at domain boundaries satisfy the condition, \n%\n\\begin{equation}\n\\phi_b = \\alpha_D\n\\end{equation}\n%\nwhere $\\phi_b$ is the transported variable at the domain extent and $\\alpha_D$ is the value specified in the \\verb==$\\rightarrow$\\verb== tag. The \\verb=Neumann= condition specifies the gradient of $\\phi$ at the boundary and thus satisfies the condition, \n%\n\\begin{equation}\n\\frac{\\partial \\phi}{\\partial n}|_b = \\alpha_N\n\\end{equation}\n%\nwhere $n$ is the normal direction of the boundary and $\\alpha_N$ is the value specified in the \\verb==$\\rightarrow$\\verb== tag. \n\nMomentum boundary conditions are specified using descriptive tags that in turn choose the appropriate Nuemann, Dirichlet, or some other boundary condition depending on the tag. Note that some momentum boundary conditions have implications for all transported variables despite any previously specified boundary condition for that specific scalar. This is described below. \n\nBoundary conditions for momentum include (with the corresponding \\verb== attribute listed), \n%\n\\begin{itemize}\n\\item Specified velocity inlet (\\verb=VelocityInlet=)\n\\item Specified mass flow rate (\\verb=MassFlowInlet=)\n\\item Specified swirl inlet (\\verb=Swirl=)\n\\item Velocity inlet read from file (\\verb=VelocityFileInput=)\n\\item Digital Filter turbulence inlet from file (\\verb=TurbulentInlet=)\n\\item Pressure boundary condition (\\verb=PressureBC=)\n\\item Outlet boundary condition (\\verb=OutletBC=)\n\\item Wall boundary condition (\\verb=WallBC=)\n\\end{itemize}\n%\nDetails of each boundary condition follow.\n\n\\subsubsection*{Velocity Inlet}\n%\nThe velocity inlet specification requires that \\verb== be specified as a child of \\verb==, where \\verb== represents a three component vector of velocity at the inlet. For example, \n%\n\\begin{Verbatim}[fontsize=\\footnotesize]\n\n\t\n\t\t[0.1, 0.2, 0.2]\n\t\n\n\\end{Verbatim}\n%\nspecifies a non-normal velocity component in a circular region on the x-minus face. Note that the \\verb=label= attribute is generic here, allowing the user to specify any descriptive title to the boundary condition. \n\nVelocity inlet boundary conditions simply set the velocity vector at domain boundary interface. To ensure a constant mass flow rate for the given velocity condition, the actual velocity at the domain interface may vary to compensate for varying density within the domain while maintaining a constant mass flow rate into the domain. This step is necessary because density is a cell centered quantity and interpolation of density to the face may potentially change the mass flow rate if the velocity is not adjusted accordingly. This is accomplished by computing the following for the normal velocity component, \n%\n\\begin{equation}\nu_{n} = 2.0( \\rho u )_{b} / (\\rho_{i} + \\rho_{b}), \n\\end{equation}\n% \nwhere $n$ indicates the normal interfacial velocity, $b$ is the boundary density, and $i$ is the density from the first interior cell in the normal direction of the boundary. Note that a simple linear interpolant has been used to compute the boundary density. \n\n\\subsubsection*{Mass Flow Inlet}\n%\nThe mass flow inlet boundary condition requires that \\verb== be specified as a child of \\verb==, where \\verb== is the mass flow rate in units of \\verb=[kg/s]=. For example, \n%\n\\begin{Verbatim}[fontsize=\\footnotesize]\n\n\t\n\t\t0.4\n\t\n\n\\end{Verbatim}\n%\nspecifies a mass flow rate in a circular region on the x-minus face. Note that the \\verb=label= attribute is generic here, allowing the user to specify any descriptive title to the boundary condition. \n\nA velocity condition is set from the mass flow rate condition using the area and density of the boundary geometry. Note that the area of the geometry is computed from the true area of assembly of the grid cells and not the ideal geometry area. Once velocities are computed, the mass flow rate boundary condition proceeds as the previously described velocity inlet condition. \n\n\\subsubsection*{Swirl Inlet}\n% \nThe swirl condition specifies a mass flow rate condition in addition to adding a swirling component from the non-normal velocity components. This specification requires that the \\verb== (mass flow rate, \\verb=[kg/hr]=), \\verb== (swirl number), and \\verb== be specified as a child of \\verb==. For example, \n%\n\\begin{Verbatim}[fontsize=\\footnotesize]\n\n\t\n\t\t1.0\n\t\t16.0\n\t\t[0, 0.5, 0.5]\n\t\n\n\\end{Verbatim}\n%\nspecifies a mass flow inlet in a circular region on the x-minus face with a swirl number of 16 and a centroid coincident with the circle of the boundary geometry. Note that the swirl condition currently is applied across the entire geometry. \n%\n%add brief description of the swirl condition here.....\n\n\\subsubsection*{Velocity File Input Inlet}\n% \nWork in progress....please check back later. \n\n\\subsubsection*{Turbulent Inlet} \\label{subsubsec:TurbInlet}\n%\nThe turbulent inlet loads a pre-generated table consisting of cell indices for each realization time index provided. It requires a period, which specifies the amount of simulation time to use the same profile, a vector value to set up the iterator, and the input file to load. An example specification is\n%\n\\begin{Verbatim}[fontsize=\\footnotesize]\n\n \n [1.0, 0.0, 0.0] \n 10 \n tubulent_input_file.gz \n \n\n\\end{Verbatim}\n%\nThis loads the table and changes the time index of the realization to use once every 10 simulation timesteps. The period is an optional parameter that defaults to 1. If a timescale is used for generation the period should be one, but if a length scale is used for the flow direction, then the period needs to be such that sufficient time elapses to convect the velocity through one cell. A \\verb== specification can also be used, which is more convenient for a variable \\verb=dt= problem. The input file needs to have the number of total realizations generated and the non axial dimensions of the box around the inlet in the first line. The next line needs to be the minimum (i, j, k) cell index of the bounding box of the inlet, all of the indices of the velocity vectors stored are in relation to the corner being at (0, 0, 0), so this adjusts from the simulation's (i, j, k) to match. Then a list of the (t, j,k) points and (u, v, w) vectors, varying first by k, then j, then t (for a x- or x+ face). For other faces either (t, i, k) or (t, i, j) points are listed instead. It is recommended to use the \\verb=DigitalFilterGenerator= executable for creating a table.\n\n\\subsubsection*{Pressure Boundary Condition}\n%\nA pressure (open) boundary condition is specified using \\verb=PressureBC= attribute. For example, \n%\n\\begin{Verbatim}[fontsize=\\footnotesize]\n\n\t\n\n\\end{Verbatim}\n%\nspecifies a pressure condition on the \\verb=y+= face of the domain. \n%\n% add brief description of the pressure condition here\n\n\\subsubsection*{Flow Outlet Boundary Condition}\n%\nA flow outlet boundary condition is specified using \\verb=OutletBC= attribute. For example, \n%\n\\begin{Verbatim}[fontsize=\\footnotesize]\n\n\t\n\n\\end{Verbatim}\n%\nspecifies an outlet condition on the \\verb=x+= face of the domain. \n%\n% add brief description of the outlet condition here\n\n\\subsubsection*{Wall Boundary Condition}\n%\nA wall boundary condition is specified using \\verb=WallBC= attribute. For example, \n%\n\\begin{Verbatim}[fontsize=\\footnotesize]\n\n\t\n\n\\end{Verbatim}\n%%once moving walls are supported, add documentation%\nspecifies a stationary wall condition on the \\verb=x-= face of the domain. \n%\n% add brief description of the wall condition here\n\n \\subsection{Time Integrator}\n % \n \\subsubsection{Explicit Time Integrator}\n Arches is commonly run in a fully explicit time-stepping mode. That is, the update in time for any variable $\\phi$ is expressed as\n %\n \\begin{equation}\n \\phi^{t+\\Delta t} = \\frac{1}{\\rho^*}\\left( (\\rho\\phi)^t + \\Delta tRHS^t) \\right) \\;,\n \\end{equation}\n %\nwhere $RHS$ represents all forcing terms in the transport equation for $\\phi$ at time level $t$. For the purposes of this discussion, we have dealt with the implicit nature of the density term by simply assuming we have a density approximation, called $\\rho^*$, that suits the current update (for details of the $\\rho$ issue, see Section \\ref{Sec:LES_Algorithm}). \n\nThe explicit time integrator is activated (as a child node of \\verb==$\\rightarrow$\\verb==) by simply inserting the $<$ExplicitIntegrator$>$ node. Within this node, the other solvers for the various transport equations will be defined along with a few parameters. The general structure will look something like this:\n%\n\\begin{Verbatim}[fontsize=\\footnotesize]\n\n\t \n\t \n\t \n\t ....\n\t \n\t\n\t...\n\t\n\t\n\t\n\t...\n\t\n\t\n\t\n\t...\n\t\n\t\n\t\n\t...\n\t\n\n\\end{Verbatim} \n%\nThe options for each transport equation will be described in Section \\ref{Sec:Eqns_options}. \n\nOptions for the $<$ExplicitSolver$>$ section include:\n\\begin{enumerate}\n%\n\\item {\\bf Initial time step}: $<$initial\\_dt$>$ \\\\\n{\\bf Input type}: {\\it Required, double} \\\\\n{\\bf Default}: {\\it NA } \\\\ \n{\\bf Description}: The explicit solver can be stepped forward in time by using a fixed time step or letting the code estimate a time step via a CFL condition (see Section \\ref{Sec:LES_Algorithm}). In either case, an initial time step must be specified. \n%\n\\item {\\bf Variable time step}: $<$variable\\_dt$>$ \\\\\n{\\bf Input type}: {\\it Required, boolean} \\\\\n{\\bf Default}: {\\it NA } \\\\ \n{\\bf Description}: One may either step at a fixed time step with $\\Delta t$ equal to the {\\it intial\\_dt} tag or let the code guess a stable time step according to a CFL condition. It is recommended that one sets the {\\it variable\\_dt} to {\\it true} as it helps maintain stability during the time integration.\n%\n\\item {\\bf Time integration order}: $<$timeIntegratorType$>$ \\\\\n {\\bf Input type}: {\\it Required, string} \\\\\n {\\bf Default}: {\\it FE} \\\\ \n {\\bf Description}: Current options include one of the following: \\\\ \n \\begin{itemize}\n \\item FE, 1st order Forward-Euler \n \\item RK2SSP, Second Order, Strong-Stability Preserving Runge-Kutta \n \\item RK3SSP, Third Order, Strong-Stability Preserving Runge-Kutta \n \\end{itemize}\n See Section \\ref{Sec:LES_Algorithm} for full details.\n % \n\\item {\\bf Stability option for the density guess}: $<$restartOnNegativeDensityGuess$>$ \\\\\n {\\bf Input type}: {\\it Optional, boolean} \\\\\n {\\bf Default}: {\\it false} \\\\\n {\\bf Description}: This parameter restarts a time step, regardless of the time integrator order, if the predicted density guess (see Section \\ref{Sec:LES_Algorithm}) from the continuity equation is negative and therefore unphysical. If this option is true, the time step is reduced by half and the time step is restarted with the new, smaller time step. The process with repeat until a) the density guess is physical or b) the code goes unstable. Instability usually will occur in the implicit pressure projection. If b) occurs, it is advised to set this option to {\\it false}. By default this option is {\\it false} and is not required. Note that in cases where this parameter is {\\it false} and a negative density guess occurs, the density from the previous time step is used. \n %\n\\item {\\bf Message control on density guess}: $<$NoisyDensityGuess$>$ \\\\\n{\\bf Input type}: {\\it Optional, boolean} \\\\\n{\\bf Default}: {\\it true} \\\\\n{\\bf Description }: The negative density guess warning prints for every cell with a negative density guess. One may want to suppress the warning and can do so with this option. When used, a warning is printed for every patch rather than every cell. \n\\item {\\bf Turbulence model calculation frequency}: $<$turbModelCalcFreq$>$ \\\\\n{\\bf Input type}: {\\it Optional, integer} \\\\\n{\\bf Default}: {\\it 1} \\\\ \n{\\bf Description}: This parameter allows one to control the frequency of the execution of the turbulence model. One may want to decrease the frequency for efficiency reasons. \n\\item {\\bf Turbulence model calculation frequency on time integrator sub-steps}: \\newline $<$turbModelCalcForAllRKSteps$>$ \\\\\n{\\bf Input type}: {\\it Optional, boolean} \\\\\n{\\bf Default}: {\\it true } \\\\ \n{\\bf Description}: If {\\it false}, the turbulence closure will only be computed for the first time sub-step and then applied for all subsequent time sub-steps. By default, this parameter is {\\it true}. \n\\item {\\bf Additional time step constraint}: $<$scalarUnderflowCheck$>$ \\\\\n{\\bf Input type}: {\\it Optional, boolean} \\\\\n{\\bf Default}: {\\it false} \\\\ \n{\\bf Description}: Guaranteeing stability for a problem with large length and time scales is difficult. As previously mentioned, a guess at a stable time step is made using a CFL condition. The scalar underflow check option uses additional information about the local flow information to compute an additional time step guess. The minimum of this estimation and the CFL condition is used to step the equations forward in time. Here, a time step is computed from the inverse of the continuity equation by considering outward mass fluxes only. In other words, given the local velocity state, there is a limit to the amount of mass that can leave any given cell. This limit is computed from\n\\[\n\\frac{\\partial \\rho}{\\partial t} = -\\nabla \\cdot (\\rho U)|_{+}\n\\]\nwhen only outward facing fluxes are considered (as indicated by the $|_+$ symbol). Thus one can rearrange this equation to give an estimate for $\\Delta t$ as, \n\\[ \n\\Delta t \\approx \\partial t = \\frac{\\partial \\rho}{ \\nabla \\cdot (\\rho U)|_{+}}\n\\] \nThis option is often helpful in helping with stability if your simulation is experiencing underflow ($<1.0$) or overflow ($>1.0$) errors from the mixture fraction scalar. \n%\n\\item {\\bf Extra pressure projection option}: $<$extraProjection$>$ \\\\\n{\\bf Input type}: {\\it Optional, boolean} \\\\\n{\\bf Default}: {\\it false} \\\\ \n{\\bf Description}: This option performs a second pressure solve and projection step. In general, this option is not needed. By default the value is {\\it false}. \n \\end{enumerate}\n\n\\subsubsection{Implicit Time Integrator}\n%\nCurrently the implicit time integrator is not supported. \n\n\\subsection{Scalar Transport Equations}\\label{Sec:Scalar_transport}\nA set of user defined scalars can be defined through the input file. The scalar can be passive (it doesn't feed back to the CFD) or active (plays a role in the CFD solution). An example of an active scalar would be a mixture fraction variable that is used for the chemistry table look-up. \n\nThe basic form of the scalar transport is\n%\n\\begin{equation}\n\\frac{\\partial \\rho \\phi}{\\partial t} + F_{conv} = F_{diff} + \\sum_{i=1}^{N} S_i, \n\\end{equation}\n% \nwhere $\\phi$ is the scalar, $F_{conv}$ is the total convection term, $F_{diff}$ is the total diffusion term, and $S_i$ is the set of $N$ source terms associated with this scalar. If $N=0$, then the scalar is a conserved scalar.\n\nScalar equations are defined in the $<$TransportEqn$>$ node of the input file. The generic specification looks like\n%\n\\begin{Verbatim}[fontsize=\\footnotesize]\n\n \n \t...equation options...\n \n \n \t...equation options...\n \n\n\\end{Verbatim}\n%\nIn the above example, two scalar equations were defined with a set of solver options. The $label$ specification is used as the equation identifier, and must be unique for every equation. Currently, only one type of scalar is supported ($CCscalar$). Beside the actual definition of the scalar and its respective options, the only other requirement for each scalar is that boundary conditions are defined for all boundary condition specification (see Section \\ref{sec:boundaryconditions}). \n\n\\subsubsection{Options for Scalar Transport Equations} \n%\nOptions for an individual scalar equation ($<$Eqn$>$) includes: \n\\begin{enumerate}\n%\n\\item {\\bf Turbulent Schmidt/Prandtl Number}: $<$turbulentPrandtlNumber$>$ \\\\\n{\\bf Input type}: {\\it Optional, double} \\\\\n{\\bf Default}: 0.4 \\\\\n{\\bf Description}: The total diffusion coefficient is computed as \n\\[\nD_T = \\rho D_{molecular} + \\frac{\\mu_t}{Sc_t}\n\\]\nwhere $D_{molecular}$ is the molecular diffusion coefficient, $mu_t$ is the turbulent viscosity (from the turbulence model) and $Sc_t$ is the turbulent Schmidt number. \n\\item {\\bf Constant Molecular Diffusion Coefficient}: $<$D\\_mol\\_constant value=``DOUBLE''$>$ \\\\\n{\\bf Input type}: {\\it Optional, double} \\\\\n{\\bf Default}: {\\it NA} \\\\\n{\\bf Description}: Sets a constant molecular diffusivity for the scalar. The {\\it value} attribute specifies the constant. Note that if {\\it D\\_mol\\_constant} or {\\it D\\_mol} is not specified, then the molecular diffusion is assumed zero. \n\\item {\\bf Variable Molecular Diffusion Coefficient}: $<$D\\_mol label=``STRING''$>$ \\\\\n{\\bf Input type}: {\\it Optional, string} \\\\\n{\\bf Default}: {\\it NA} \\\\\n{\\bf Description}: Points the equation to the correct label for the molecular diffusion coefficient. The label must be defined elsewhere in a property model, table, etc. If the molecular diffusivity is a table lookup variable, the label must be saved in the uda (as specified in the $<$DataArchiver$>$ section) for the variable to exist (a bit hackish but should suffice for now.) Note that if {\\it D\\_mol\\_constant} or {\\it D\\_mol} is not specified, then the molecular diffusion is assumed zero.\n%\n\\end{enumerate}\n\n\\subsection{Transport Equation Options}\\label{Sec:Eqns_options}\nIn the current configuration of Arches, transport equations are activated by specifying the option for each equation in a equation-specific node under the {\\it ExplicitSolver} node. Currently, all equation nodes are required except for the enthalpy solver node. \n\n\\subsubsection{Momentum Solver}\nThe moment solver refers to solution of $\\rho \\mathbf{U}$, where $\\mathbf{U}$ is the vector quantity of velocity. As mentioned above, the components are solved in a staggered, finite volume configuration. By default, the required $<$MomentumSolver$>$ node must be present in the $<$ExplicitSolver$>$ node. \n\nThe options for the moment solver include:\n\\begin{enumerate}\n%\n\\item {\\bf The order of the convection scheme}: $<$convection\\_scheme$>$ \\\\\n{\\bf Input type}: {\\it Required, string} \\\\\n{\\bf Default}: {\\it NA } \\\\ \n{\\bf Description}: The two options that currently are implemented for the convection term in the moment equation are first-order upwind (set as {\\it upwind}) and second-order central difference (set as {\\it central}). Both types of discretization can be found in any common CFD text. It is recommended that one use the {\\it central} option as it has desirable energy conservation properties (see Moronishi [add reference] ). \n%\n\\item {\\bf Filter the divergence of $\\rho \\mathbf{U}$}: $<$filter\\_divergence\\_constraint$>$ \\\\\n{\\bf Input type}: {\\it Optional, boolean} \\\\\n{\\bf Default}: {\\it false } \\\\ \n{\\bf Description}: This options turns on the filtering of the divergence constraint used in the pressure solver. When false, the divergence is unfiltered. \n%\n\\end{enumerate}\n\n\\subsubsection{Pressure Solver}\nArches is solved in an incompressible manner, in the sense that there is a degree of pressure-velocity decoupling which is resolved through an implicit pressure projection. This results in the classic Poisson equation for pressure than requires solution. By default, the required $<$PressureSolver$>$ node must be present in the $<$ExplicitSolver$>$ node.\n\nThe options for the pressure solver include:\n%\n\\begin{enumerate}\n%\n\\item {\\bf Perform only the last projection}: $<$do\\_only\\_last\\_projection$>$ \\\\\n{\\bf Input type}: {\\it Optional, boolean} \\\\\n{\\bf Default}: {\\it false } \\\\ \n{\\bf Description}: For multi-step time schemes, only perform the projection on the last time sub-step. The result is that intermediate time steps do not conserve mass. \n%\n\\item {\\bf Normalize the pressure with the reference pressure}: $<$normalize\\_pressure$>$ \\\\\n{\\bf Input type}: {\\it Optional, boolean} \\\\\n{\\bf Default}: {\\it false } \\\\ \n{\\bf Description}: When true, this option subtracts the reference pressure, set in $<$PhysicalProperties$>$, from the current value of pressure for each time step. \n%\n\\item {\\bf Solver choice for the pressure Poisson equation}: $<$linear\\_solver$>$ \\\\\n{\\bf Input type}: {\\it Required, string} \\\\\n{\\bf Default}: {\\it NA } \\\\ \n{\\bf Description}: Arches uses external linear solver packages to solve the pressure Poisson equation. Currently, there are two solver that have an interface to the pressure equation; {\\it hypre} or {\\it petsc}. A solver must be specified and specifics of the solver follow in the $<$parameter$>$ section (detailed next). \n%\n\\item {\\bf Solver parameters for the pressure Poisson equation}: $<$parameters$>$ \\\\\n{\\bf Input type}: {\\it Required, NA} \\\\\n{\\bf Default}: {\\it NA } \\\\ \n{\\bf Description}: The solver parameters, as children of the {\\it parameters} node, include the following:\n \\begin{itemize}\n \\item $<$solver$>$, Required solver parameter. Options include: {\\it cg}. \n \\item $<$max\\_iter$>$, Required maximum iterations for the solver.\n \\item $<$preconditioner$>$, Required preconditioner. Options include: {\\it jacobi}, {\\it pfmg}. \n \\item $<$res\\_tol$>$, Required tolerance of the residual ($res = b-Ax$).\n\\end{itemize} \n%\n\\end{enumerate} \n%\n\n\\subsubsection{Mixture Fraction Solver}\nIn Arches current configuration, specific scalar variables that require specification. The mixture fraction equation is one equation that requires definition in order to run any simulation. This is true independent of the relation of the local density with the mixture fraction value. \n\nIn general, the mixture fraction equation is a conserved scalar equation that is used as a parameter to map the thermo-chemical state of the gas. In its most simple form, the mixture fraction and density are related by a linear relationship (such as mixing of two non-reacting gasses with different densities). More complicated state-space relationships are also available, which include subgrid reaction and turbulence mixing. \n\nBy default, the required $<$MixtureFractionSolver$>$ node must be present in the $<$ExplicitSolver$>$ node. Parameters within the mixture fraction node include; \n\n\\begin{enumerate}\n%\n\\item {\\bf Initial value of of the mixture fraction in the domian}: $<$initial\\_value$>$ \\\\\n{\\bf Input type}: {\\it Optional, double} \\\\\n{\\bf Default}: {\\it 0.0 } \\\\ \n{\\bf Description}: One may set the mixture fraction everywhere inside the domain to a constant value. Boundary condition values are set elsewhere. \n%\n\\item {\\bf Convection scheme}: $<$convection\\_scheme$>$ \\\\\n{\\bf Input type}: {\\it Required, string} \\\\\n{\\bf Default}: {\\it central-upwind, flux-limited } \\\\ \n{\\bf Description}: The choice of the convection scheme can affect the stability of the algorithm. The {\\it central-upwind} option is the second upwind differencing scheme defined by Roache (ADD REFERENCE). The {\\it central-upwind} option is kept separate from the {\\it flux\\_limiter} option for historical reasons. One may choose the type of limter for the {\\it flux\\_limited} specification by setting the $<$limeter\\_type$>$ option. The currently available limiters include: \n\\begin{itemize}\n\\item {\\it superbee}\n\\item {\\it vanLeer}\n\\item {\\it upwind} - This option is the standard upwind scheme and is very stable, yet of low-order.\n\\item {\\it none} - This option uses central differencing and will add noise, and possibly cause instabilities, if used. \n\\end{itemize}\nThe super-bee scheme is used if the limiter type is not specified. \n\nOne may also control the limiter type near boundary conditions by setting the $<$boundary\\_limiter\\_type$>$. Options include:\n\\begin{itemize}\n\\item {\\it central-upwind} The second upwind differencing scheme of Roache\n\\item {\\it upwind} First order upwind scheme\n\\end{itemize}\nThese options are necessary due to the wide stencil of some limiter types. \n%\n\\end{enumerate}\n\n\\subsubsection{Enthalpy Solver}\nArches solves a filtered enthalpy transport equation for tracking energy in the system. Modes of heat transfer include convection, diffusion and radiative heat transfer. The energy equation is activated by specifying the $<$EnthalpySolver$>$ section within the $<$ExplicitSolver$>$ node. Note that by neglecting this node, isothermal flow is assumed. \n\nCurrent options for the enthalpy solver include:\n\\begin{enumerate}\n%\n\\item {\\bf Convection scheme}: $<$convection\\_scheme$>$ \\\\\n{\\bf Input type}: {\\it Required, string} \\\\\n{\\bf Default}: {\\it central-upwind, flux-limited } \\\\ \n{\\bf Description}: The choice of the convection scheme can affect the stability of the algorithm. The {\\it central-upwind} option is the second upwind differencing scheme defined by Roache (ADD REFERENCE). The {\\it central-upwind} option is kept separate from the {\\it flux\\_limiter} option for historical reasons. One may choose the type of limter for the {\\it flux\\_limited} specification by setting the $<$limeter\\_type$>$ option. The currently available limiters include: \n\\begin{itemize}\n\\item {\\it superbee}\n\\item {\\it vanLeer}\n\\item {\\it upwind} - This option is the standard upwind scheme and is very stable, yet of low-order.\n\\item {\\it none} - This option uses central differencing and will add noise, and possibly cause instabilities, if used. \n\\end{itemize}\nThe super-bee scheme is used if the limiter type is not specified. \n\nOne may also control the limiter type near boundary conditions by setting the $<$boundary\\_limiter\\_type$>$. Options include:\n\\begin{itemize}\n\\item {\\it central-upwind} The second upwind differencing scheme of Roache\n\\item {\\it upwind} First order upwind scheme\n\\end{itemize}\nThese options are necessary due to the wide stencil of some limiter types. \n%\n\\item Discrete Ordinates Radiation Model: $<$DORadiationModel$>$ \\\\\n{\\bf Input type}: {\\it NA} \\\\\n{\\bf Default}: {\\it NA } \\\\ \n{\\bf Description}: The discrete ordinates method is based on the numerical solution of the radiation transport equation (RTE) along specified directions. The total solid angle about a location is divided into a number of ordinate directions, each assumed to have uniform intensity. Each transport equation that is solved corresponds to an ordinate direction selected from an angular quadrature set that discretizes the unit sphere and describes the variation of directional intensity throughout the domain.\n\nIf the $<$DORadiationModel$>$ section is found, the model is activated and the radiative source is automatically added to the transport equation. If the section is absent, the calculation is assumed to have no radiative energy transport. Options for the discrete radiation model include\n\\begin{itemize}\n\\item Optical path length: $<$opl$>$ \\\\\n{\\bf Input type}: {\\it Required, double} \\\\\n{\\bf Default}: {\\it NA } \\\\ \n{\\bf Description}: The optical path length for the radiation model. \n\\item Number of ordinate directions: $<$ordinates$>$ \\\\\n{\\bf Input type}: {\\it Optional, integer} \\\\\n{\\bf Default}: {\\it 2 } \\\\ \n{\\bf Description}: The discrete ordinates method uses quadrature methods to represent the divergence of the radiative heat flux. The quadrature order is defined by the number of ordinate directions, $n$. The number of equations to be solved depends directly on $n$. The DO scheme is often referred to as an $Sn$ scheme where $n$ is the number of ordinate directions.\n%\n\\item Property Model: $<$property\\_model$>$ \\\\\n{\\bf Input type}: {\\it Optional, double} \\\\\n{\\bf Default}: {\\it radcoef } \\\\ \n{\\bf Description}: This option defines the model for computing the radiation properties. Options include:\n\\begin{itemize}\n\\item {\\it radcoef} %need descriptions of these options\n\\item {\\it patchmean}\n\\item {\\it wsggm}\n\\end{itemize}\n%\n\\item Linear Solver: $<$linear\\_solver$>$ \\\\\n{\\bf Input type}: {\\it Required, string} \\\\\n{\\bf Default}: {\\it NA } \\\\\n{\\bf Description}: This options sets the linear solver for the radiation calculation.\n\n\\end{itemize} \n\n\\end{enumerate}\n\n\\subsection{Initial and Boundary Conditions} \n% \n\\subsubsection{Solid Intrusions (MPMArches only)}\nOne may specify solid intrusions that intersect the physical domain. Intrusions will be treated with a stationary wall boundary condition. \n\nThe options for the \\verb==$\\rightarrow$\\verb==$\\rightarrow$\\verb== section are as follows:\n%\n\\begin{enumerate}\n\\item Geometry object: \\verb== \\\\\n{\\bf Input Type}: {\\it XML node} \\\\\n{\\bf Default}: NA \\\\\n{\\bf Description}: All geometry objects are specified within this single \\verb== tag. \n\\end{enumerate}\n \n%\n\\subsubsection{Species Efficiency Calculations}\n%\nThe scalar efficiency calculator computes an overall balance on an atomic or molecular species. The output is a data file placed within the UDA with the prescribed label. The format of the data file consists of a column of time values and a column of efficiency values. To save the output to the UDA, one must specify the\n\\begin{Verbatim}\n \n\\end{Verbatim}\nin the data archiver section of the input file. Note that the user\\_defined\\_efficiency name is the unique name given to the scalar efficiency (see below). \n\nThe total scalar species is computed as\n%\n\\begin{equation}\n\\eta_{eff} = \\frac{\\dot{m}_{out}-\\dot{m}_{in}}{\\dot{m}_{in}^*}\n\\end{equation} \n%\nwhere the superscript $*$ in the denominator signifies that the inflow is only summed over inlet boundary conditions. The value of $\\dot{m}_{in}$ in the numerator is summed over all boundary condition types. The outflow, $\\dot{m}_{out}$ is only summed over pressure and outlet type boundary conditions.\n\nThe generic setup of the \\verb== node should appear as\n\\begin{Verbatim}[fontsize=\\footnotesize]\n\n \n \n fuel_inlet\n \n\n\\end{Verbatim}\n\nThe \\verb== node is a child of the \\verb== node. Parameters within this node include;\n%\n\\begin{enumerate}\n\\item Scalar: \\verb== \\\\\n{\\bf Input Type}: {\\it XML node} \\\\\n{\\bf Default}: NA \\\\\n{\\bf Description}: All information about a single atomic or molecular efficiency is encapsulated within this node. The following attributes of \\verb== are required\n\\begin{itemize}\n\\item {\\it label}: The user-given name of this species balance. The efficiency output data file will assume this name. \n\\item {\\it fuel\\_ratio}: The mass ratio of species to total species mass in the fuel inlet (kg species/total fuel kg)\n\\item {\\it ox\\_ratio}: The mass ratio of species to total species mass in the air (oxidizer) inlet (kg species/total oxidizer hg)\n\\end{itemize}\n%\n\\item Species: \\verb==$\\rightarrow$\\verb== \\\\\n{\\bf Input Type}: {\\it XML node} \\\\\n{\\bf Default}: NA \\\\\n{\\bf Description}: This node specifies the specific species that will be used to compute the balance. Note that multiple \\verb== may be specified in this section if needed. The following attributes are required for this node: \n\\begin{itemize}\n\\item {\\it label}: The label of the species. \n\\item {\\it mol\\_ratio}: The molecular weight ratio of the species to the molecule. For example, in the case where we are computing a balance on the carbon atom and the output species is $CO_2$, we would enter $0.2727$ because ratio $= 12.0/44.0$. \n\\end{itemize} \n\\item Inlet: \\verb==$\\rightarrow$\\verb== \\\\\n{\\bf Input Type}: {\\it string} \\\\\n{\\bf Default}: {\\it none} \\\\\n{\\bf Description}: This identifies which geometric objects of which inlets (ie, the label attribute of the geometry object) are associated with this scalar balance. One may have multiple \\verb=='s specified. \n\\end{enumerate}\n \n\n%\\subsection{Turbulence Models}\n\n\\subsection{Properties, Reaction and Sub-Grid Mixing}\n% \nTypically, subgrid mixing and reaction processes of the gas phase are described using pre-computed and tabulated mixing and reaction chemistry tables. These tables consists of the thermo-chemical state-space (density, temperature, species) as a function of a few independent parameters (e.g., mixture fraction, heat loss, scalar variance). In the \\verb== child of the \\verb== node, the inputs for the mixing and reaction models are specified, including additional information affecting various gas property models (e.g., empirical soot model). \n\nTo use tabulated chemistry, one must specify\n\\begin{enumerate}\n\\item Transport equations for any independent mixture fraction or other grid resolved species equation that parameterizes the table\n\\item Boundary conditions for every independent variable, including heat loss, scalar variance, and mixture fraction/species equations\n\\item A table specific node in the \\verb== section of the input file defining which table mechanism is being used \n\\end{enumerate}\nInformation on specifying transport equations and boundary conditions is found in Section (ADD SECTION). \n\nARCHES currently has two tabulated property formats that can be interpreted: \n\\begin{enumerate} \n\\item Classic Mixing Table \n\\item New Static Mixing Table \n\\end{enumerate} \n\nTables formatted in the Classic form are activated by using the following \n%\n\\begin{Verbatim}[fontsize=\\footnotesize]\n\n REQUIRED STRING \n OPTIONAL BOOLEAN \n OPTIONAL BOOLEAN \n OPTIONAL DOUBLE \n \n\n\\end{Verbatim} \n%\nThe \\verb== tag is used when the table does not involve a typical combustion process, as in mixing of two non-reacting streams or acid-base chemistry. The \\verb== option provides verbose output during runtime if computed heat losses are exceeding the table bounds. The \\verb== option initializes the domain at the first time step with the specified value for heat loss. \n\nIf one is using a coal table which requires a transformation of mixture fractions, the \\verb== tag with its attributes defines how the third mixture fraction is computed from the following relationship, \n\\begin{equation}\nf = \\frac{ f_p }{(1 - \\eta_c) }.\n\\end{equation} \nThis identifies the mapping for the transformation of the transported $f_p$ (primary mixture fraction) and $eta_c$ (coal gas mixture fraction) equations that must be defined in the \\verb== section of the input file. \n\nTables formatted in the TabProps form are activated by using the following\n%\n\\begin{Verbatim}[fontsize=\\footnotesize]\n\n REQUIRED STRING \n OPTIONAL BOOLEAN\n OPTIONAL DOUBLE \n OPTIONAL NO_DATA \n OPTIONAL DOUBLE\n OPTIONAL DOUBLE\n \n\n\\end{Verbatim}\n%\nwhere the same description of the tags for the Classic Tables applies to the TabProps tables. Note that the TabProps tables do not automatically determine the bounds for the heat loss grid, thus one must explicitly set the lower and upper bounds for heat loss if they differ from $(-1, +1)$ for strict error checking. \n\nFor both the Classic and TabProps tables, any dependent variable in the table is saved by specifying the following in the \\verb== section of the input file: \n%\n\\begin{Verbatim}[fontsize=\\footnotesize]\n\n \n\n\\end{Verbatim} \n%\nwhere the additional \\verb=table_lookup= attribute is specified to signify to ARCHES that the variable is found in the table. Note that the string name must match exactly the name in table. \n\nIn addition to the pre-tabulated chemistry, cold-flow mixing is available for simple two-stream mixing. The cold two-stream mixing is activated by\n%\n\\begin{Verbatim}[fontsize=\\footnotesize]\n\n REQUIRED STRING\n \n REQUIRED DOUBLE POSITIVE\n REQUIRED DOUBLE POSITIVE\n \n \n REQUIRED DOUBLE POSITIVE\n REQUIRED DOUBLE POSITIVE\n \n\n\\end{Verbatim}\n% \nwhere \\verb== is the name given to the mixture fraction equation defined in the \\verb== section. A mixture fraction of, $f=1$ represents a mixture of pure Stream 1 and conversely a mixture fraction of, $f=0$, is pure Stream 2. \n\n\\subsubsection{Classic Table Format}\n\nThe Classic Mixing Tables can function with an arbitrary number of independent variables. The parser for the tables treats \\# as a commented line, so any header information in the table should be precluded by this. The header information can also include various table constants with \\verb+#KEY VARNAME=VALUE+. After the header the sizes of the table and its variables must be specified in a specific order. This is:\n\n\\begin{enumerate}\n\\item{Number of independent variables}\n\\item{Names of independent variables}\n\\item{Grid Sizes of independent variables}\n\\item{Number of dependent variables}\n\\item{Names of dependent variables}\n\\item{Units of dependent variables}\n\\end{enumerate}\n\nThis is followed by a list of grid points for each independent variable, listed \\textit{backwards} from N through independent variable 2. The table format allows for the grid points used for independent variable 1 to vary as a function of the value of last independent variable. The grid point list for independent variable 1 is listed at the start of each block of data where the N$^{th}$ variable varies. The blocks of data for the dependent variable are listed similarly to how Matlab displays a full N-D matrix. Independent variable 1 varies across the row, and independent variable 2 varies down the columns. The next block of data should then change the value of the third independent variable, and vary independent variables 1 and 2 as before. This is repeated up to the (N-1)$^{th}$ independent variable. Then the list of the grid points for the first independent variable for the next value of the N$^{th}$ independent variable is listed , then the other variables are listed as before, and repeated until the last value of the N$^{th}$ independent variable is used. This is repeated for all of the dependent variables.\n\nRefer to \\verb=src/StandAlone/inputs/ARCHES/ClassicMixingTables/= for example tables. A diagram of a 5 dimensional table layout (i.e. for a flamelet model) is also included in figure \\ref{fig:table_ex}.\n\n\\newpage\n\\begin{figure}[H]\n \\begin{center}\n \\scalebox{.75}{\\includegraphics{TableDiagram.pdf}}\n \\caption{Example 5D Table Layout}\\label{fig:table_ex}\n \\end{center}\n\\end{figure}\n\n%\\subsection{Extra Scalar Solvers}\n%This section and all options will soon be replaced with Section \\ref{Sec:AddTransEqn}. \n\n%\\subsection{Additional Transport Equations}\\label{Sec:AddTransEqn}\n\n\n%\\subsubsection{Turbulence}\n\n\n%\\subsubsection{Properties}\n\n\n%\\subsubsection{BoundaryConditions}\n\n\n%\\subsubsection{Physical Constants}\n\n\n%\\subsubsection{Solvers}\n\n\n\\subsection{Direct Quadrature Method of Moments}\n\nThe direct quadrature method of moments (DQMOM) is implemented in Arches, and various parameters, optional and required, are set in the input file. DQMOM involves transporting several transport equations, namely transport equations for the weights $w_{\\alpha}$ and abscissas $ \\left< \\xi_{j} \\right>_{\\alpha}$, or, alternatively, the weights $w_{\\alpha}$ and weighted abscissas $\\varsigma_{j,\\alpha}$. Information about these transport equations must be specified in the DQMOM tags.\n\nThree other things need to be specified, namely: a set of moments with which to generate a set of quadrature-approximated moment transport equations, which make up the linear system $\\mathbf{Ax}=\\mathbf{B}$; parameters related to the solver for the linear system $\\mathbf{Ax} = \\mathbf{B}$; and finally, physical models implemented to describe the evolution of the NDF in state-space. The input file has a DQMOM section denoted by the tag \\verb==.\n\nThe basic structure is as follows:\n\n% Add below, once completed:\n%\t\n%\t\t...\n%\t\n\\begin{Verbatim}[fontsize=\\footnotesize]\n\n\t\n\t\t\n\t\t...\n\t\n\t\n\t\n\t\t\n\t\t...\n\t\n\t\n\t\n\t\t\n\t\t...\n\t\n\t\n\t\n\t\t\n\t\t...\n\t\n\t\n\t\n\t\t\n\t\t...\n\t\n\t\n\t[...]\n\t...\n\t[...]\n\n\\end{Verbatim}\n\nThree additional tags go between the \\verb== tags. These are:\n\n\\begin{enumerate}\n%\n\\item {\\bf Number of quadrature nodes}: \\verb== \\\\\n{\\bf Input type}: {\\it Required, positive integer} \\\\\n%{\\bf Default}: {\\it NA} \\\\\n{\\bf Description}: Denotes the number of quadrature nodes (also called environments) with which to represent the NDF. The NDF is represented by a set of delta function, and each quadrature node represents an additional delta function.\n%\n\\item {\\bf Adiabatic Gas, Non-Adiabatic Particles}: \\verb== \\\\\n{\\bf Input type}: {\\it Optional, boolean} \\\\\n{\\bf Default}: {\\it false} \\\\\n{\\bf Description}: This parameter is used to indicate that the gas is adiabatic (in which case, it is {\\it true}) and therefore heat loss should not be looked up from the table. The default is to assume {\\it false}, so that the heat loss will be used as a variable if it is so determined by the remainder of the input file.\n% FIXME: This description needs some improvement\n%\n\\item {\\bf Save moments}: \\verb== \\\\\n{\\bf Input type}: {\\it Optional, boolean} \\\\\n{\\bf Default}: {\\it false} \\\\\n{\\bf Description}: This boolean determines whether or not the moments specified in the \\verb== tags (see below) should be calculated in order to be saved out as variables. If true, all moments specified in the \\verb== tags will be calculated. In order to actually save them, however, they must also be added to the \\verb== labels.\n%\n\\end{enumerate}\n\n\n\n\\subsubsection{Linear Solver, $<$LinearSolver$>$}\n\\begin{enumerate}\n%\n\\item {\\bf Tolerance}: \\verb== \\\\\n{\\bf Input type}: {\\it Optional, positive double} \\\\\n{\\bf Default}: {\\it } 1.0e-5 \\\\\n{\\bf Description}: Sets the linear solver tolerance for DQMOM. For the linear system\n%\n\\begin{equation}\n\\mathbf{Ax}=\\mathbf{B},\n\\end{equation}\n%\nthe residual vector $\\mathbf{R}$ is defined as \n%\n\\begin{equation}\n\\mathbf{R} = \\mathbf{Ax} - \\mathbf{B}\n\\end{equation}\n%\nand the normalized residual vector $\\mathbf{R^{\\star}}$ is defined as \n%\n\\begin{equation}\n\\mathbf{R^{\\star}} = \\frac{ \\mathbf{Ax} - \\mathbf{B} }{ \\mathbf{x} }.\n\\end{equation}\n%\nThe tolerance set by this tag will enforce the following condition\n%\n\\begin{equation}\n\\begin{cases}\n\\text{if} \\Vert \\mathbf{R^{\\star}} \\Vert \\leq \\text{tol} & \\text{Use solution obtained from } \\mathbf{x} = \\mathbf{A^{-1}B} \\\\\n\\text{if} \\Vert \\mathbf{R^{\\star}} \\Vert > \\text{tol} & \\text{Throw out solution from } \\mathbf{x} = \\mathbf{A^{-1}B} \\text{ and use } \\mathbf{x = 0} \\\\\n\\end{cases}\n\\end{equation}\n%\n\\item {\\bf Type}: \\verb== \\\\\n{\\bf Input type}: {\\it Required, string} \\\\\n{\\bf Default}: {\\it ``LU''} \\\\\n{\\bf Description}: The linear solver type; options are:\n\\begin{itemize}\n\\item ``Lapack-invert'' - uses a Lapack routine to invert $\\mathbf{A}$, which is then multiplied by $\\mathbf{B}$\n\\item ``Lapack-svd'' - uses a Lapack routine to calculate the singular value decomposition (SVD) of $\\mathbf{A}$\n\\item ``LU'' - LU decomposition solver using the Crout's Method algorithm\n\\item ``Optimize'' - uses sets of optimal moments and optimal abscissas to get a well conditioned matrix\n\\end{itemize}\n%\n\\item {\\bf Maximum allowable condition number for $\\mathbf{A}$}: \\verb== \\\\\n{\\bf Input type}: {\\it Optional, positive double} \\\\\n{\\bf Default}: {\\it 1.0e+16} \\\\\n{\\bf Description }: If the condition number of $\\mathbf{A}$ is greater than the maximum allowable condition number, the resulting solution vector is discarded and $\\mathbf{x = 0}$ is used; this prevents large numerical errors from contaminating the solution.\n%\n\\item {\\bf Calculate condition number? (boolean)}: \\verb== \\\\\n{\\bf Input type}: {\\it Optional, boolean} \\\\\n{\\bf Default}: {\\it false} \\\\\n{\\bf Description }: If {\\it true}, the condition number is calculated using singular value decomposition. Note, this calculation is very expensive and should probably only be done when the ``Lapack-svd'' solver option is being used. An error is thrown if this is true and the ``LU'' (Crout's Method) solver option is chosen.\n%\n\\item {\\bf Using the \"Optimize\" solver}: \\verb== \\\\\n{\\bf Description }: This section must be specified to use the \"Optimize\" solver. The section must contain specification of the optimal abscissas: \\\\\n\\verb== \\\\\n{\\bf Input type}: {\\it Required, Vector} \\\\\n{\\bf Default}: {\\it none} \\\\\n{\\bf Description }: The optimal abscissas should be specified as a vector (within brackets) and separated by comas. The set of moments chosen by the user should be consistent with the set of otpimal absissas. The number of optimal abscissas to specify is Nic*Nqn. The user can use the matlab script located in $/src/StandAlone/inputs/ARCHES/matlab/find_optmoments.m$ to determine a set of optimal moments and absissas given a number of internal coordinates and quadrature nodes. After running the script, the set of optimal abscissas is stored in Xgood and the corresponding set of optimal moments is stored in Momentsgood. Note, the order of the abscissas and the moments matters and should not be changed. Also, the following options are irrelevent for the \"Optimize\" solver: tolerance, maxConditionNumber, calcConditionNumber. \\\\\n%\n\\end{enumerate}\n\n\n\n\\subsubsection{Coal Models for DQMOM, $<$Models$>$}\nSee the \\ref{subsec:models} section below for details about the \\verb== tag.\n\n\n\n%\\subsubsection{Iterative Coal Particle Calculation}\n\n\n\n\\subsubsection{Velocity Model}\n%\nThis section sets parameters for the Balachandar velocity model.\n%\n\\begin{enumerate}\n%\n\\item {\\bf Velocity model}: \\verb== \\\\\n{\\bf Attributes}: label, type \\\\\n{\\bf Description}: Attributes determine the label the velocity model is given, and the type of velocity model being used. The label is an arbitrary string. The type takes on these values:\n\\begin{itemize}\n\\item \\verb=Balachandar= - Use the Balachandar particle velocity model\n\\item \\verb=Dragforce= - Use a drag force law, and track particle velocity as an internal coordinate\n\\end{itemize}\n%\n\\item {\\bf Viscosity}: \\verb== \\\\\n{\\bf Input type}: {\\it Required, positive double} \\\\\n{\\bf Default}: {\\it 1.0e-5} \\\\\n{\\bf Description}: The kinematic viscosity.\n%\n\\item {\\bf Length scale}: \\verb== \\\\\n{\\bf Input type}: {\\it Required, positive double} \\\\\n{\\bf Default}: {\\it 1.0} \\\\\n{\\bf Description}: The integral scale of the simulation.\n%\n\\item {\\bf Density ratio}: \\verb== \\\\\n{\\bf Input type}: {\\it Required, positive double} \\\\\n{\\bf Default}: {\\it 1000} \\\\\n{\\bf Description}: The ratio of particle density to fluid density, $\\dfrac{ \\rho_{\\text{particle}} }{ \\rho_{\\text{fluid}} }$.\n%\n\\item {\\bf Regime}: \\verb== \\\\\n{\\bf Input type}: {\\it Required, integer (1 or 3)} \\\\\n{\\bf Default}: {\\it 1} \\\\\n{\\bf Description}: The flow regime for the Balachandar particle velocity model.\n%\n\\item {\\bf Eta}: \\verb== \\\\\n{\\bf Input type}: {\\it Required, positive double} \\\\\n{\\bf Default}: {\\it 1.0e-5} \\\\\n{\\bf Description}: The Kolmogorov scale.\n%\n{\\color[gray]{0.5}\n\\item {\\bf High clip value (via upper limit multiplier)}: \\verb== \\\\\n{\\bf Input type}: {\\it Optional, double} \\\\\n{\\bf Default}: {\\it 2.0} \\\\\n{\\bf Description}: This factor is not actually used. It is used to set a high clip value. The way it stands in the code, this is, for some reason, multiplying the upper limit multiplier and the high clip value for the particle length - which doesn't make sense.\n}\n%\n\\item {\\bf Low clip value}: \\verb== \\\\\n{\\bf Input type}: {\\it Optional, double} \\\\\n{\\bf Default}: {\\it 0.0} \\\\\n{\\bf Description}: Sets the low clip value for the particle velocity.\n%\n{\\color[gray]{0.5}\n\\item {\\bf Particle velocity boundary conditions}: \\verb== \\\\\n{\\bf Input type}: {\\it Optional, double} \\\\\n{\\bf Default}: {\\it false} \\\\\n{\\bf Description}: If this value is true, the particle velocity boundary conditions are the same as the gas velocity boundary conditions. \\\\\nWARNING: This should NOT be turned on! It will cause problems!\n}\n%\n\\item {\\bf Minimum velocity ratio}: \\verb== \\\\\n{\\bf Input type}: {\\it Optional, positive double} \\\\\n{\\bf Default}: {\\it 0.1} \\\\\n{\\bf Description}: This keeps the particle velocity from becoming too different from the gas velocity.\n%\n\\item {\\bf Number of iterations}: \\verb== \\\\\n{\\bf Input type}: {\\it Optional, positive integer} \\\\\n{\\bf Default}: {\\it 15} \\\\\n{\\bf Description}: An iterative procedure is required to determine the particle velocity, since it appears in the Balachandar particle velocity model implicitly. This tag controls the maximum iterations that may be run.\n%\n\\item {\\bf Tolerance}: \\verb== \\\\\n{\\bf Input type}: {\\it Optional, positive double} \\\\\n{\\bf Default}: {\\it 1e-15} \\\\\n{\\bf Description}: This defines a maximum residual for the expression for the particle velocity appearing in the Balachandar particle velocity model; i.e., if $\\left[ (LHS - RHS) \\leq \\text{tol} \\right]$ then the iterative procedure finishes.\n%\n\\end{enumerate}\n\n\n\n\\subsubsection{Weight Transport Equation Options, $<$Weights$>$}\n%\n\\begin{enumerate}\n%\n\\item {\\bf Do Diffusion?}: \\verb== \\\\\n{\\bf Input type}: {\\it Optional, boolean} \\\\\n{\\bf Default}: {\\it false} \\\\\n{\\bf Description}: Boolean to determine whether transport equation's RHS will include a diffusion term. If true, it uses a turbulent Prandtl number to determine the diffusivity. The turbulent Prandtl number can be set, but is 0.4 by default. See \\verb== tag below.\n%\n\\item {\\bf Do Convection?}: \\verb== \\\\\n{\\bf Input type}: {\\it Optional, boolean} \\\\\n{\\bf Default}: {\\it false} \\\\\n{\\bf Description}: Boolean to determine whether transport equation's RHS will include a convection term. Because the weights are DQMOM scalars, and the weight transport equations (originally) come from the NDF transport equation, the velocity used for the convection term is the particle velocity, conditioned on particle size. This velocity comes from the DQMOM particle velocity model (see the \\verb== tag above).\n%\n\\item {\\bf Convection scheme}: \\verb== \\\\\n{\\bf Input type}: {\\it Optional, string} \\\\\n{\\bf Default}: {\\it upwind} \\\\\n{\\bf Description}: Tag to determine the convection scheme used. Valid options are:\n\\begin{itemize}\n\\item \\verb=upwind= - use the upwind convection scheme\n\\item \\verb=super_bee= - use the super-bee convection scheme\n\\end{itemize}\n%\n\\item {\\bf Turbulent Prandtl Number}: \\verb== \\\\\n{\\bf Input type}: {\\it Optional, double} \\\\\n{\\bf Default}: {\\it 0.4} \\\\\n{\\bf Description}: If diffusion is turned on, a turbulent Prandtl number is required to determine the diffusion coefficient. The Prandtl number is defined as:\n\\begin{equation}\nPr = \\dfrac{\\nu}{D}\n\\end{equation}\nwhere $\\nu$ is the fluid viscosity, and $D$ is the scalar diffusivity. This is equivalent to the turbulent Schmidt number.\n%\n\\item {\\bf Initialization function}: \\verb== \\\\\n{\\bf Attributes}: type \\\\\n{\\bf Default}: none \\\\\n{\\bf Description}: There are several options for initialization functions. These are as follows:\n%%\n\\begin{itemize}\n\\item {\\it Constant value initialization}, \\verb=constant= - Initializes the weights to be a constant throughout the domain; the constant value is the same for all weights of all environments. The block looks like:\n\\begin{Verbatim}\n\n\t...\n\n\\end{Verbatim}\nwhere the \\verb== tags encapsulate a double.\n%%\n\\item {\\it Environment-specific constants}, \\verb=env_constant= - Initializes the weights to be a constant throughout the domain; the constant value is different for the weights of each environment. The block looks like:\n\\begin{Verbatim}\n\n\\end{Verbatim}\nwhere ``qn'' is an integer specifying an environment (or quadrature node), and ``value'' is a double, and is the value to which the weight of that environment will be initialized.\n%%\n\\item {\\it Step-function initialization}, \\verb=step= - Initializes the weights to be a step function. Several attributes of the step function must be specified; these include:\n\t\\begin{itemize}\n\t\\item \\verb== - Direction in which the step occurrs (x, y, z) (Required, no default)\n\t\\item \\verb== - The step goes from 0 to \\verb== (double) (Required, no default)\n\t\\item \\verb== - Physical location at which step begins (double) (No default)\n\t\\item \\verb== - Physical location at which step ends (double) (No default)\n\t\\item \\verb== - Cell location at which step begins (integer) (No default)\n\t\\item \\verb== - Cell location at which step ends (integer) (No default)\n\t\\end{itemize}\nThe step function initialization block looks like:\n\\begin{Verbatim}\n\n\t ... \n\t ... \n\t ... \n\t ... \n\n\\end{Verbatim}\nor, alternatively, the start and end of the step could be specified using the cell locations, which would look like:\n\\begin{Verbatim}\n\n\t ... \n\t ... \n\t ... \n\t ... \n\n\\end{Verbatim}\n%%\n\\item {\\it Environmental step-function initialization}, \\verb=env_step= - Initializes the weights to step functions, with the value of the step function different for each environment. The attributes are the same as for the step-function initialization, except that the \\verb== tag becomes a set of \\verb== tags. These tags have the following attributes:\n\t\\begin{itemize}\n\t\\item \\verb=qn= - the environment (or quadrature node) to which the \\verb== tag applies\n\t\\item \\verb=value= - the value to which this environment's step function should be initialized\n\t\\end{itemize}\nso that the tags would look like:\n\\begin{Verbatim}\n\n\t ... \n\t ... \n\t ... \n\t\n\t...\n\t\n\n\\end{Verbatim}\n%%\n\\end{itemize}\n%\n\\item {\\bf Scaling constant}: \\verb== \\\\\n{\\bf Input type}: {\\it Required, double} \\\\\n{\\bf Default}: {\\it 1.0} \\\\\n{\\bf Description}: Value by which to scale the weights. The actual values of the weights are very high, as the weights represent numbers of particles (typically greater than 1e6). Because the values of the weights are going into the $\\mathbf{A}$ matrix, large weight values can cause $\\mathbf{A}$ to become very ill-conditioned. Scaling the values of the weights can help control condition numbers for $\\mathbf{A}$.\n%\n\\item {\\bf Clipping}: \\verb== \\\\\n{\\bf Description}: Values of weights can attain non-physical values (e.g. negative numbers of particles, large and physically unrealistic numbers of particels, etc.). Clipping is implemented to prevent non-physical values. The weights have three types of clipping:\n\t\\begin{itemize}\n\t\\item \\verb== - Low clipping represents the lowest value the weights can attain (in most cases, 0)\n\t\\item \\verb== - As a result of the weight/weighted abscissa formulation of DQMOM, the abscissa values are not calculated by themselves; they are bound to the weights. Many models thus require dividing the weighted abscissas by the weights. When the weights become very small, this leads to physically unrealistic abscissa values. The small clipping sets a minimum value at which weights can divide weighted abscissas; when the weights are lower than this small clipping, the abscissas are set to 0.\n\t\\item \\verb== - High clipping represents an upper limit on values of weights.\n\t\\end{itemize}\n%\n\\end{enumerate}\n\n\n\n\\subsubsection{Weighted Abscissa Transport Equation Options, $<$Ic$>$}\n%\nMany of the options for the weighted abscissa transport equation options are the same as the weight transport equations. Only the differences are highlighted in this section.\n%\n\\begin{enumerate}\n%\n\\item {\\bf Initialization}:\n{\\bf Description}: The initialization function options are more limited for weighted abscissas than for weights. If abscissas coincide, this creates singularities in $\\mathbf{A}$. Thus, the constant and step function initialization functions must be environment-specific\n%\n\\item {\\bf Scaling constant}:\n{\\bf Description}: The scaling constant is for the abscissa, and not for the weighted abscissa. Because the weight is scaled, there are {\\it two} scaling constants for each weighted abscissa: one scaling constant for the weights, the other for the abscissa.\n%\n\\item {\\bf Clipping}:\n{\\bf Description}: The clipping values are set for the abscissas, and not the weighted abscissas. Additionally, there is no ``small'' clipping value, as there is no dividing by the abscissas.\n%\n\\item {\\bf Models}: \\verb==\n{\\bf Attributes}: label \\\\\n{\\bf Description}: Attribute determines which model (identified by the label) should be associated with this internal coordinate. The label is an arbitrary string that must match a label for a model.\n%\n\\end{enumerate}\n\n\n\n\\subsubsection{Moments, $<$Moment$>$}\n%\nAn important part of DQMOM is selecting a set of moments that will be used to provide closure for the NDF. These moments are then used to construct the quadrature-approximated moment transport equations, which are written in the linear form $\\mathbf{Ax} = \\mathbf{B}$. The moments selected have a strong influence on the behavior of the matrix $\\mathbf{A}$.\n%\n\\begin{enumerate}\n%\n\\item {\\bf Moment}: \\verb== \\\\\n{\\bf Input type}: {\\it Required, multiple integers} \\\\\n{\\bf Default}: N/A \\\\\n{\\bf Description}: The moments are specified as sets of integer vectors. The \\verb== block looks like:\n\\begin{Verbatim}\n[ ... , ... , ... ]\n...\n[ ... , ... , ... ]\n\\end{Verbatim}\nNote that the moment index vectors must be of size $N_{\\xi}$, where $N_{\\xi}$ is the number of internal coordinates, and there must be $\\left( N_{\\xi} + 1 \\right) N$ total moments, where $N$ is the number of environments (or quadrature nodes).\n%\n\\end{enumerate}\n\n\n\n\\subsubsection{Verification, $<$Verify\\_Linear\\_Solver$>$, $<$Verify\\_AB\\_Construction$>$}\n%\nOf major importance is the verification procedure for DQMOM. There are two important processes in the DQMOM code that must be verified: the construction of $\\mathbf{Ax}=\\mathbf{B}$, and the linear solver's solution to $\\mathbf{Ax}={B}$. Both have verification mechanisms built in.\n%\nVerification is not something that can be ``turned on'' in the input file - it must be turned on using compiler directives. The file Directives.h in the Arches component directory contains several directives related to verification, two of which are \\verb=VERIFY_LINEAR_SOLVER= and \\verb=VERIFY_AB_CONSTRUCTION=.\n%\nFor verification, some additional information must be put into the input file. This information is specified for each verification procedure. Most of these tags point to files containing information which is used to construct $\\mathbf{Ax}=\\mathbf{B}$. These files are available in the Arches \\verb=inputs/= directory.\n%\n\\begin{enumerate}\n%\n\\item {\\bf Verification of Linear Solver}: \\verb== \\\\\n\t\\begin{itemize}\n\t\\item \\verb== - File containing A matrix\n\t\\item \\verb== - File containing X vector (verification solution)\n\t\\item \\verb== - File containing B vector\n\t\\item \\verb== - File containing norm of the residual vector\n\t\\item \\verb== - File containing several norms of vectors\n\t\\item \\verb== - The dimension of the linear system being solved\n\t\\item \\verb== - Error tolerance\n\t\\end{itemize}\n%\n\\item {\\bf Verification of A, B construction process}: \\verb== \\\\\n\t\\begin{itemize}\n\t\\item \\verb== - File containing A matrix\n\t\\item \\verb== - File containing B vector\n\t\\item \\verb== - File containing various inputs (e.g. model terms)\n\t\\item \\verb== - File containing moments\n\t\\item \\verb== - Number of environments used to represent the NDF\n\t\\item \\verb== - Number of internal coordinates parameterizing the NDF\n\t\\item \\verb== - Error tolerance\n\t\\end{itemize}\n%\n\\end{enumerate}\n\n\n\n\\subsection{Models}\\label{subsec:models}\nThe $<$Models$>$ tags contain several tags that are not specific to models. The outline of a typical $<$Models$>$ section looks like:\n\n\\begin{Verbatim}[fontsize=\\footnotesize]\n\n\t\n\n\t\t\n\n\t\t\t\n\n\t\t\n\n\t\t\n\t\t\n\t\t\t\n\n\t\t\n\n\t\t ... \n\t\t ... \n\n\t\n\t\n\t...\n\t\n\n\\end{Verbatim}\n\nThe sections have the following significance:\n\n\\begin{itemize}\n\\item \\verb== - there is a \\verb== tag block for each coal model\n\\item \\verb== - this tag block contains all of the internal coordinate variables that the model depends on (for example, if a kinetic model depends on temperature, and temperature is being tracked as an internal coordinate variable, the temperature would be included in this \\verb== block)\n\\item \\verb== - this tag block contains all of the scalar variables that the model depends on\n\\item \\verb== - When values of the model are lower than \\verb==, the value is clipped to \\verb==\n\\item \\verb== - When values of the model are higher than \\verb==, the value is clipped to \\verb==\n\\end{itemize}\n\n\\begin{enumerate}\n\n\\item {\\bf Model}: \\verb== \\\\\n{\\bf Attributes}: label, type \\\\\n{\\bf Description}: Attributes determine the label the velocity model is given, and the type of velocity model being used. The label is an arbitrary string. The type takes on these values:\n\\begin{itemize}\n\\item \\verb=KobayashiSarofimDevol= - Use the Kobayashi-Sarofim coal devolatilization model\n\\item \\verb=ConstantModel= - Use a constant model\n\\item \\verb=SimpleHeatTransfer= - Use a simple particle heat transfer model\n\\item \\verb=XDrag, YDrag, ZDrag= - Use a standard drag model for the x-, y-, and z-velocity of the particle\n\\end{itemize}\n\n\\item {\\bf Internal Coordinate Variable}: \\verb= = \\\\\n{\\bf Attributes}: label, role \\\\\n{\\bf Description}: Attributes set the label of the internal coordinate variable, and the role that the internal coordinate variable plays in the model. The label must match a label for one of the internal coordinate variables (see the ``label'' attribute of the \\verb== tag, above). The role must match one of the role names specified by the model, in the model code. These include:\n\\begin{itemize}\n\n\\item KobayashiSarofimDevol\n\t\\begin{itemize}\n\t\\item \\verb=raw_coal_mass=\n\t\\item \\verb=particle_temperature=\n\t\\end{itemize}\n\n\\item SimpleHeatTransfer\n\t\\begin{itemize}\n\t\\item \\verb=particle_length=\n\t\\item \\verb=raw_coal_mass=\n\t\\item \\verb=particle_temperature=\n\t\\end{itemize}\n\n\\item XDrag / YDrag / ZDrag\n\t\\begin{itemize}\n\t\\item \\verb=particle_length=\n\t\\item \\verb=particle_xvel / particle_yvel / particle_zvel=\n\t\\end{itemize}\n\n\\end{itemize}\n\n\\item {\\bf Scalar Variable}: \\verb= = \\\\\n{\\bf Attributes}: label, role \\\\\n{\\bf Description}: As with the above \\verb== tag, this tag specifies information about scalar variables a model may depend on. The label attribute indicates the label of the scalar variable, and the role specifies the role that scalar variable will play in the model. The label attribute must match a label for one of the scalar variables. The role must match one of the role names specified by the model, in the model code. Currently, scalar variables do not play a role in any models currently implemented.\n\n\\end{enumerate}\n\n\n\\subsection{Digital Filter Generator}\nIn order to utilize the digital filter turbulent inlet condition in \\ref{subsubsec:TurbInlet}, the executable \\verb=DigitalFilterGenerator= is the best way to generate the table needed. This executable lies in the \\verb=StandAlone= folder. Its usage is simply \n\n\\begin{verbatim}\n./DigitalFilterGenerator input_file output_table_file\n\\end{verbatim}\n\nIf not output table file is specified this writes out to \\verb=DFGInlet=. The input file is a small text file with the grid size and geometries specified on individual lines. Currently it must be specified in a specific order.\n\n\\begin{enumerate}\n\\item Grid resolution \\verb= =\n\\item Lower grid points \\verb= =\n\\item Upper grid points \\verb= =\n\\item Inlet face \\verb== (x+, x-, y-, y+, z-, z+)\n\\item Inlet geometry shape \\verb== (box/circle/ellipse/annulus)\n\\item Geometry parameters \\verb== (varies on geometry, same order as BCGeom objects )\n\\item Number of realizations in file \\verb==\n\\item Lengthscales \\verb= =\n\\item Accuracy of filter (min 2) \\verb==\n\\item Average velocity vector \\verb= =\n\\item Average Reynold's stress tensor (lower diagonal) \\verb= = \\\\\n\\verb= = $R_{11},\\; R_{21},\\; R_{22},\\; R_{31},\\; R_{32},\\; R_{33} $\n\\item Use spatial variations \\verb== (y, yes, n, no)\n\\item Variation direction \\verb== (x, y, z, none) used if a planar geometric relation is needed\n\\item Velocity variation type \\verb== (tanh, power, laminar, none)\n\\item Stress variation type \\verb== (channel, jet, none)\n\\item Lengthscale variation type \\verb== (channel, jet, none)\n\\end{enumerate}\n\nAn example input file for the digital filter is located in \\\\ \\verb=StandAlone/inputs/ARCHES/DigitalFilter/ChannelInletGenerator.txt=. It is recommended to gzip the file that is created to save space.\n\n\n \n% ====================================================\n% ===================== Examples ======================\n% ====================================================\n\n\n\n\\newpage\n\\section{Examples}\n\nThe following ARCHES examples illustrate the diverse set of problems that can be solved using the ARCHES component of Uintah code. The first two examples exemplify techniques used to verify various ARCHES algorithms that were implemented in the code. The following three [or more] examples illustrate the kinds of problems that ARCHES can solve. The input files used here can be used as templates to build similar input files for similar problems. \nDue to the complexity of ARCHES simulations, exact solutions (with the exception of MMS) do not exist. Hence the emphasis on model validation, or the comparison of simulation with experimental results. Model validation provides a framework that allows the simulation scientist to be confident in his or her results in the absence of analytical solutions. All modeling should be accompanied by some form of validation analysis.\n\n\n\\subsection*{\\center Almgren MMS}\n\\addcontentsline{toc}{subsection}{Almgren MMS}\n\\subsubsection*{\\underline{Problem Description}}\n\nMethods of Manufactured Solutions (MMS) are verification tools that are used with computer codes such as ARCHES that seek to solve the Navier-Stokes Equations. They are extremely useful for finding programming errors and ensuring expected behavior of the computer code. The Almgren MMS is especially easy to implement because of the absence of source terms that must be added to the transport equations.\nARCHES uses a second-order spatial discretization scheme and a first-order scheme in the temporal direction. Therefore, if the Almgren MMS problem is run in Arches at different mesh resolutions and the normalized error plotted on a semilog plot, the slope of the line should be 2. To facilitate this exercise, a shell script has been written to perform this analysis.\n\n\\subsubsection*{\\underline{Simulation Specifics}}\n\\begin{description} \n\\footnotesize\n\\item [Component used:] \\hfill ARCHES\n\\item [Input file name:] \\hfill \\TT{almgrenMMS.ups}\\\\\n\\item [Command used to run input file:]\\hfill \\\\\n\n% Write .sh script to run almgrenMMS.ups 4 times at different resolutions [32,32,8], [24,24,8]. [12,12,8], and [8,8,8] and then extract L2norms to a .dat file that can easily be plotted in Excel or Matlab.\n\\TT{./runAlmgren.sh }\n\nIf you examine the shell script you will see the following line of code:\n\\TT{mpirun -np 1 sus inputs/UintahRelease/ARCHES/almgrenMMS.ups}\nThis is call to run the ARCHES via sus.\n\n\\item [Simulation Domain:]\\hfill 1.0 x 1.0 x 3.0 m\n\\item [Cell Spacing:]\\hfill \\\\ \n0.3125 x 0.3125 x 0.275 m\n\n\\item [Example Runtimes:] \\hfill \\\\\n113.2 seconds (1 processor, 2.4 GHz Intel Core 2)\n\n\\item [Physical time simulated:] \\hfill \\\\\n 1.0 sec.\n\\end{description}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Figure showing plot of error as a function of spatial discretization\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n \n %--------------------------------------------------------------\n \\newpage\n\\subsection*{\\center Periodic Box Problem}\n\\addcontentsline{toc}{subsection}{Periodic Box Problem}\n\\subsubsection*{\\underline{Problem Description}}\n\nThe Periodic Box Problem indicates how well ARCHES is modeling the\nkinetic energy contained in the turbulence modeled on the grid and at\na sub-grid level. The LES algorithm transfers kinetic energy from\ncell to cell in the ARCHES structured grid. Turbulence models such as\n\"compdynamicprocedure,\" \"dynamicprocedure,\" and \"smagorinsky\" are used\nto model kinetic energy at the sub-grid level. Ideally, there would\nbe a seamless transition between the resolved turbulence and sub-grid\nmodels at the Nyquist limit. {\\bf SHOW SAMPLE PLOT} Experience has shown that this is not normally the case. By plotting the kinetic energy as a function of the wave number, it is possible to determine how well the kinetic energy dissipation is being modeled by the code. The Periodic Box problem is initialized with a kinetic energy (turbulence) profile from Direct Numerical Simulation (DNS). As the simulation proceeds that energy is dissipated. \n % COMPLETE ME\n\n\\subsubsection*{\\underline{Simulation Specifics}}\n\\begin{description} \n\\footnotesize\n\\item [Component used:] \\hfill ARCHES\n\\item [Input file name:] \\hfill \\TT{periodic.ups}\\\\\n \n\\item [Command used to run input file:]\\hfill \\\\\nThis simulation, like many ARCHES simulations, requires another file, in addition to the input file called by sus. That file is the initial condition called upon in periodic.ups by %\n\n\\TT{mpirun -np 1 sus inputs/UintahRelease/ARCHES/periodic.ups } % I am using the periodic.ups file found in the tree\n\n\\item [Simulation Domain:]\\hfill 0.565 x 0.565 x 0.565 m\n\\item [Cell Spacing:]\\hfill \\\\ \n0.0177 x 0.0177 x 0.0177 m %[32]^3\n\n\\item [Example Runtimes:] \\hfill \\\\\n2 minutes (1 processor, 2.4 GHz Intel Core 2 )\n\n\\item [Physical time simulated:] \\hfill \\\\\n0.1 sec. % Is this time long enough???\n\\end{description}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Figure showing plot of kinetic energy as a function of the wave number\n%\n% + Discussion\n%\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n %--------------------------------------------------------------\n\\newpage\n\\subsection*{\\center Helium Plume}\n\\addcontentsline{toc}{subsection}{Helium Plume}\n\\subsubsection*{\\underline{Problem Description}}\nHelium plumes are classical experiments that allow for the easy\ncapture of turbulent mixing data that can be used to validate the\nturbulent mixing models used in LES algorithms such as Arches. The\nnon-reacting nature of the plume makes it easy to capture experimental\ndata without damaging expensive equipment. Reacting flows require\nspecial mixing tables that contain temperature, pressure and\ncomposition as a function of the transported scalars in Arches. The\ncoldFlowMixingModel is used to determine the mixing of {\\bf isothermal?} streams. After the mixing model is specific in the .ups file, the temperature and densities of the two mixing streams are specified.\n\n\\subsubsection*{\\underline{Simulation Specifics}}\n\\begin{description} \n\\footnotesize\n\\item [Component used:] \\hfill ARCHES\n\\item [Input file name:] \\hfill \\TT{helium\\_1m.ups}\\\\\n \n\\item [Command used to run input file:]\\hfill \\\\\n\\TT{mpirun -np 8 sus inputs/UintahRelease/ARCHES/helium\\_1m.ups }\n\n\\item [Simulation Domain:]\\hfill 3.0 x 3.0 x 3.0 m\n\\item [Cell Spacing:]\\hfill \\\\ \n0.06 x 0.06 x 0.0.6 m\n\n\\item [Example Runtimes:] \\hfill \\\\\n 54 minutes (8 processors, 2.8 GHz Xeon)\n\n\\item [Physical time simulated:] \\hfill \\\\\n 5.0 sec.\n\\end{description}\n\n\\subsubsection*{\\underline{Results}}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Image from [300]^3 simulation\n%\n% Plot from Diem's work with the Sandia Helium Plume dataset\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n %--------------------------------------------------------------\n\\newpage\n\\subsection*{\\center Methane Plume}\n\\addcontentsline{toc}{subsection}{Methane Plume}\n\\subsubsection*{\\underline{Problem Description}}\nThis methane plume is geometrically identical to the Helium Plume problem. The difference is the addition of chemistry. Instead of unreacting, isothermal fluids mixing, a fuel is reacting to combustion products inside of the computational domain. This chemistry is captured via a mixing table. The input file is pointed to the mixing table which contains state variables and species mass fractions as a function of mixture fraction, heat loss, and mixture fraction variance. \n\n\\subsubsection*{\\underline{Simulation Specifics}}\n\\begin{description} \n\\footnotesize\n\\item [Component used:] \\hfill ARCHES\n\\item [Input file name:] \\hfill \\TT{helium\\_1m.ups}\\\\\nNote that the input file is pointed to the mixing table (inputs/UintahRelease/ARCHES/CH4\\_equil\\_clipped.mxn.gz)\n \n\\item [Command used to run input file:]\\hfill \\\\\n\\TT{mpirun -np 8 sus inputs/UintahRelease/ARCHES/helium\\_1m.ups }\n\n\\item [Simulation Domain:]\\hfill 3.0 x 3.0 x 3.0 m\n\\item [Cell Spacing:]\\hfill \\\\ \n0.06 x 0.06 x 0.0.6 m\n\n\\item [Example Runtimes:] \\hfill \\\\\n 2 hours 10 minutes (8 processors, 2.8 GHz Xeon)\n\n\\item [Physical time simulated:] \\hfill \\\\\n 5.0 sec.\n\\end{description}\n\n\\subsubsection*{\\underline{Results}}\n% Discussion of ...?\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Nifty manta image with realistic looking flame\n% Specify characteristics of simulation\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n %--------------------------------------------------------------\n\\newpage\n\\subsection*{\\center Fast Cookoff}\n\\addcontentsline{toc}{subsection}{Fast Cookoff}\n\\subsubsection*{\\underline{Problem Description}}\nThe Fast Cookoff test is a procedure used for hazard classification of energetic materials. The object is immersed over a jet fuel pool fire and the reaction, if any, is observed. Current protocol requires that the full size article must be subjected to this test, making such procedures prohibitively expensive and unfeasible for articles such as solid rocket motors. An alternative procedure has been proposed, combining sub-scale experiments with computer simulation. Through validation and uncertainty quantification procedures, the computer simulation tool (ARCHES) can be used as a surrogate for full-scale experimental testing. This Fast Cookoff problem includes a reacting flow as well as an MPMARCHES object. After performing the simulation, the incident heat flux to the cylinder can be extracted. \n\n\\subsubsection*{\\underline{Simulation Specifics}}\n\\begin{description} \n\\footnotesize\n\\item [Component used:] \\hfill MPMARCHES\n\n\\item [Input file name:] \\hfill \\TT{fastcookoff.ups}\\\\\n\n\\item [Command used to run input file:]\\hfill \\\\\nNote that the input file is pointed to the mixing table (inputs/UintahRelease/ARCHES/sandia\\_jp8\\_flmlt\\_cg.mxn)\n\n\\TT{mpirun -np 64 sus inputs/UintahRelease/ARCHES/fastcookoff.ups }\nTo extract the incident heat flux to the cylinder, use the faceextract and timeextract utilities. \n\n\\item [Simulation Domain:]\\hfill 24.0 x 24.0 x 24.0 m\n\\item [Cell Spacing:]\\hfill \\\\ \n0.24 x 0.24 x 0.24 m\n\n\\item [Example Runtimes:] \\hfill \\\\\n7 hours 27 minutes (64 processors, 2.8 GHz Xeon) % UDA at /scratch/uintah/hinckley/ARCHES_examples\n\n\\item [Physical time simulated:] \\hfill \\\\\n 10.0 sec.\n\\end{description}\n\n\\subsubsection*{\\underline{Results}}\n\n\n\\section{References}\n\\bibliographystyle{plain}\n\\bibliography{arches}\n", "meta": {"hexsha": "5d5a9dbc31b3ed82cb0a3cfe4b3baaadb712d7cd", "size": 143692, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "doc/UserGuide/arches.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/arches.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/arches.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": 60.8348856901, "max_line_length": 1449, "alphanum_fraction": 0.736742477, "num_tokens": 39215, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665855647395, "lm_q2_score": 0.2568319913875188, "lm_q1q2_score": 0.15221573939943334}} {"text": "% !TEX options=--shell-escape\n\\documentclass [12pt]{article} \n\\usepackage {amsmath}\n\\usepackage {amsthm}\n\\usepackage {amssymb}\n\\usepackage {graphicx} \n\\usepackage {float}\n\\usepackage {multirow}\n\\usepackage {xcolor}\n\\usepackage {algorithmic}\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{listings}\n\\usepackage{xcolor}\n\\usepackage{csquotes}\n\\usepackage[cache=false]{minted}\n\\usepackage{mdframed}\n\\usepackage{tikz}\n\\usetikzlibrary{shapes.symbols}\n\\newtheorem{theorem}{Theorem}\n\n\\DeclareTColorBox {Solution}{}{breakable, title={Solution}}\n\\DeclareTColorBox {Solution*}{}{breakable, title={Solution (provided)}}\n\\DeclareTColorBox {Instruction}{}{boxrule=0pt, boxsep=0pt, left=0.5em, right=0.5em, top=0.5em, bottom=0.5em, arc=0pt, toprule=1pt, bottomrule=1pt}\n\\DeclareDocumentCommand {\\Expecting }{+m}{\\textbf {[We are expecting:} #1\\textbf {]}}\n\\DeclareDocumentCommand {\\Points }{m}{\\textbf {(#1 pt.)}} \n\\newcommand {\\hint }[1]{\\noindent {[\\textbf {HINT:} \\em #1 \\em ]}} \\newcommand {\\pts }[1]{\\textbf {(#1 pt.)}} \n\n\\begin{document} \n\n{\\LARGE \\textbf {COMP 285 (NC A\\&T, Spr `22)}\\hfill \\textbf {Weekly Quiz 6} } \n\n\\begin{Instruction}\n\n\\paragraph{Reporting Issues} If you find any issues with the solutions, reach out to Chi Wang (author) or Luis Perez (reviewer).\n\n\\end{Instruction}\n\n\n\\section{} Snakey the snake is in the bottom left corner of the grid, and is trying to reach O, the ultimate Oreo. \nSnakey can move from her current cell to the adjacent cells (right, left, up, or down) if they exist and are not marked with X (X cells are blocked). However, every time that Snakey moves from one cell to the other, Snakey has to eat a cookie. What is the minimum number of cookies Snakey needs to eat to get to the O? \n\n\\begin{figure}[H]\n \\centering\n \\includegraphics[scale=0.5]{6.png} \n \\label{fig:my_label}\n\\end{figure}\n\n\\begin{Solution}\n10.\n\\paragraph{}\nShortest path problem. Go right, right, right, up, right, right, up, up, left, left.\n\\end{Solution}\n\n\n\\section{} Consider the general case of this problem, where a grid is given as an input with blocked and available cells and the locations of the Snakey and Oreo, and the goal is to find the minimum number of cookies for Snakey to reach the Oreo. Which algorithm would you use to solve this problem?\n\n\\begin{Solution}\nBFS.\n\\end{Solution}\n\n\n\\section{} Assume you want to find the connected components of an undirected graph. Which algorithm would you use?\n\n\\begin{Solution}\nBFS, DFS.\n\\end{Solution}\n\n\n\\section{} Consider the directed graph below. How many strongly connected components does this graph have?\n\n\\begin{figure}[H]\n \\centering\n \\includegraphics[scale=0.5]{2.png} \n \\label{fig:my_label}\n\\end{figure}\n\n\\begin{Solution}\n4\n\\begin{figure}[H]\n \\centering\n \\includegraphics[scale=0.2]{4.jpeg} \n \\label{fig:my_label}\n\\end{figure}\n\\end{Solution}\n\n\n\\section{} Consider the directed graph below. What is the minimum number of directed edges to add to this graph to make all the vertices strongly connected? \n\\begin{figure}[H]\n \\centering\n \\includegraphics[scale=0.5]{2.png} \n \\label{fig:my_label}\n\\end{figure}\n\n\\begin{Solution}\n1\n\\begin{figure}[H]\n \\centering\n \\includegraphics[scale=0.2]{5.jpeg} \n \\label{fig:my_label}\n\\end{figure}\n\\end{Solution}\n\n\n\\section{} Consider the Directed Acyclic Graph (DAG) below. Which of the below is a valid topological sorting of the graph?\n\\begin{figure}[H]\n \\centering\n \\includegraphics[scale=0.5]{3.png} \n \\label{fig:my_label}\n\\end{figure}\n\n\\begin{Solution}\nFDCEBA\n\\end{Solution}\n\n\n\\section{} Consider the DAG below. What is the lexicographically smallest topological ordering of the vertices? There are many valid topological orderings - out of the valid ones, write the one where letters earlier in the alphabet appear first. To receive credit, enter your answer as capital letters with no spaces (eg, ABCDEF).\n\\begin{figure}[H]\n \\centering\n \\includegraphics[scale=0.5]{3.png} \n \\label{fig:my_label}\n\\end{figure}\n\n\\begin{Solution}\nCFBDEA\n\\end{Solution}\n\n\n\\section{} Assume you have two vertices u and v in a directed graph where u and v are in the same strongly connected components (SCC). Which one of the following is incorrect about u and v?\n \n\\begin{Solution}\nThere exists a DFS tree where u is not in v 's subtree and v is not in u's subtree.\n\\paragraph{}\n\nA directed graph G = (V,E) is strongly connected if: \nfor all $v, w$ in V: (1) there is a path from v to w and (2) there is a path from w to v.\nSo there couldn't exist such a DFS tree. \n\\end{Solution}\n\n\n\\section{} Assume you have two vertices u and v in a directed graph where there exists a path from u to v. Which one of the following is incorrect about u and v?\n\n\\begin{Solution}\nu's DFS finish time is always greater than v's DFS finish time.\n\\paragraph{}\nIt depends.\n\\end{Solution}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\\end{document} ", "meta": {"hexsha": "57ab9d44942b2c95aa01c20c2c0b434f1f586b70", "size": 5320, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "assets/quizzes/quiz6.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/quizzes/quiz6.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/quizzes/quiz6.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": 29.3922651934, "max_line_length": 330, "alphanum_fraction": 0.7238721805, "num_tokens": 1551, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4455295350395727, "lm_q2_score": 0.34158251284363395, "lm_q1q2_score": 0.1521850981248731}} {"text": "\\documentclass[a4paper]{article}\n\n%% Language and font encodings\n\\usepackage[english]{babel}\n\\usepackage[utf8x]{inputenc}\n\\usepackage[T1]{fontenc}\n\n%% Sets page size and margins\n\\usepackage[a4paper,top=3cm,bottom=2cm,left=3cm,right=3cm,marginparwidth=1.75cm]{geometry}\n\n%% Useful packages\n\\usepackage{amsmath}\n\\usepackage{graphicx}\n\\usepackage{tikz}\n\\usetikzlibrary{arrows.meta}\n\n\\usepackage[colorinlistoftodos]{todonotes}\n\\usepackage[colorlinks=true, allcolors=blue]{hyperref}\n\n\\usepackage{color}\n\\usepackage{url}\n\n%% display solutions or not\n\\newif\\ifsol\n\\soltrue % comment out to hide solutions\n\n\\title{Section 3: Games and CSPs}\n\\author{CS 182 - Artificial Intelligence}\n\\date{}\n\n\\begin{document}\n\\maketitle\n\n%\\begin{abstract}\n%Your abstract.\n%\\end{abstract}\n\n\\noindent Recall the formalization of a \\textbf{Deterministic Game} from lecture:\n\\begin{itemize}\n\\setlength\\itemsep{0.2em}\n\\item States: $S$ (with start state $S_0$)\n\\item Actions: $A$ (may depend on player/state)\n\\item Transition Function: $R:$ $S \\times A \\rightarrow S$\n\\item Players: $P=\\{1 \\ldots N\\}$ (usually take turns)\n\\item Terminal Test: $T:$ $S \\rightarrow \\{True,False\\}$\n\\item Terminal Utilities: $U:$ $S \\times P \\rightarrow R$\n\\end{itemize}\n\n\\noindent And that a solution for a player is a policy $\\Pi: S \\rightarrow A$.\n\\\\ \\\\\n\\noindent Note that the difference between a game and a search problem is that introduction of multiple players and their policies and a goal test / terminal utility instead of a cost of actions and a goal state set.\n\\\\ \\\\ \n\\textbf{Minimax:} Recall that in games, every state has a value $V$. For terminal states, $V(s)$ is known. In single-player games, you can calculate the value for non-terminal states as \n$$V(s) = \\underset{s' \\in \\textrm{successors}(s)}{\\operatorname{max}} V(s')$$\nNow imagine a two-player, zero-sum, turn-based game like Tic Tac Toe. We still know $V(s)$ for terminal states, but now we have to anticipates the opponents' turn. In the minimax algorithm, we assume that the opponent plays rationally and tries to minimize your reward (thus maximizing theirs). Therefore, for your opponents' turns, we calculate the value of a state as \n$$V(s') = \\underset{s \\in \\textrm{successors}(s')}{\\operatorname{min}} V(s)$$\nTherefore, with two rational agents the optimal strategy is to maximize your moves and assume your opponent will do the same (thus minimizing your utility on their turn), thus minimax. Of course if our opponent isn't optimal, then we can still use this type of procedure if we consider the opponent's move in expectation, thus expectimax!\n\\\\ \\\\\n\\textbf{Alpha-Beta Pruning} is an extension of Minimax which increases efficiency by reducing the number of nodes searched. While we traverse the tree, we keep track of two values, $\\alpha$, and $\\beta$. $\\alpha$ is MAX's best solution on the path to root, $\\beta$ is MIN's best option on the path to root. We then follow the procedure below allowing us to eliminate the need to search over sections of the tree to which we know will not be a part of the optimal solution.\n\\begin{figure}[ht]\n\\centering\n\\includegraphics[width=0.7\\textwidth]{figs/abalg}\n\\end{figure}\n\n\\subsection*{Practice Problems}\n\n\\begin{enumerate}\n\\item Describe Tic Tac Toe as a deterministic game. How many states exist?\n\n\\ifsol\n \\begin{itemize}\n \\color{blue}\n \\item $S$: A state in this problem describes the current board state. Every field can have any of three values: \\textit{empty}, \\textit{X}, and \\textit{O}. If we represent them using the numbers $0, 1, 2$, we can represent a board as an array of length 9, e.g. $[0,0,1,0,0,2,0,0,0]$. Using this representation, there are $3^9 = 19683$ possible states. Side note: This representation allows many illegal states (game is already over, too many $X$ or $O$, etc). This is not a problem for search algorithms because they will never expand those illegal states. However, for an accurate calculation of possible legal states, you can look here: \\url{http://brianshourd.com/posts/2012-11-06-tilt-number-of-tic-tac-toe-boards.html}\n \\item $A$: All legal actions change an empty field to either a $X$ or $O$ depending on the current player. A valid representation would be to encode this as a tuple $(i, p)$, where $i$ is the index of the empty field, and $p$ is the current player.\n \\item Transition Function: $R$: The transition function takes the state and an action and returns the new state by switching the active player and adding an X or O into the appropriate empty space on the board.\n \\item $P$: Tic Tac Toe is a two-player game, so this is $\\{0,1\\}$\n \\item Terminal Test: $T$: The test checks whether there are any three $X$ or $O$ in a diagonal, row, or column. As a simplification, the test only has to check the symbol for the player who most recently played their turn. \n \\item Terminal Utilities: $U$: The winning player gets $+1$, the losing player $-1$, a tie is worth $0$.\n \\end{itemize}\n\\else\n \\vspace{15em}\n\\fi\n\n\\item Draw the search tree including the terminal utilities for the board below. When drawing the tree, you can assume that $X$ plays perfectly and that you know $X$'s response to any play in advance. Therefore, you only need to expand $O$'s options in the tree. \n\n\\begin{figure}[h]\n\\centering\n\\includegraphics[width=0.1\\textwidth]{figs/ttt}\n\\end{figure}\n\n\\ifsol\n \\textcolor{blue}{the terminal utilities are all $-1$. No matter what $O$ does, $X$ will win.\\footnote{Pictures taken from \\url{http://neverstopbuilding.com/minimax}}} \n \n \\begin{figure}[h]\n \\centering\n \\includegraphics[width=0.5\\textwidth]{figs/ttt-sol}\n \\end{figure}\n\\else\n \\vspace{17em}\n\\fi\n\n\\item What move would $O$ play? How would you change the utility function for O to play something different?\n\n\\ifsol\n \\textcolor{blue}{The move that $O$ plays would only depend on your implementation of this algorithm, since all the actions have the same value to $O$. A possible adjustment is to change the utility function to take the depth of the tree into account}\n\\else\n \\vspace{7em}\n\\fi\n\n\n\\item Under what assumptions about player 2 should player 1 use minimax rather than expectimax search to select a move? Under what assumptions about player 2 should player 1 use expectimax rather than minimax search?\n\n\\ifsol\n \\textcolor{blue}{Player 1 should use minimax if they expect player 2 to move optimally. If player 1 expects player 2 to move randomly, they should use expectimax to maximize their expected utility.}\n\\else\n \\vspace{7em}\n \\pagebreak\n\\fi\n\n\\item Imagine that player 1 wishes to act optimally (rationally), and player 1 knows that player 2 also intends to act optimally. However, player 1 also knows that player 2 (mistakenly) believes that player 1 is moving uniformly at random rather than optimally. How should player 1 use this knowledge to select a move?\n\n\\ifsol\n \\textcolor{blue}{This problem can be solved by adding a second game tree. The new game tree is used to anticipate player 2's action. Here, all nodes for player 1 are replaced by chance nodes and player 1 can use expectimax to find player 2's policy. In the original game tree, player 1 can prune all actions by player 2 but the one resulting from expectimax.}\n\\else\n \\vspace{10em}\n\\fi\n\n\\item Conduct alpha-beta pruning for the following minimax tree. \n\n\\begin{figure}[h]\n\\centering\n\\includegraphics[width=0.7\\textwidth]{figs/ab}\n\\end{figure}\n\n\n\\ifsol\n \\textcolor{blue}{The following pictures show the final solution and then the steps to computing the solution. If you want to practice your pruning skills, we recommend the website: \\url{http://inst.eecs.berkeley.edu/~cs61b/fa14/ta-materials/apps/ab_tree_practice/}}\\\\\n \\begin{center}\n \\includegraphics[width=0.7\\textwidth]{figs/ab-sol}\n \n \\includegraphics[width=0.7\\textwidth]{figs/alpha_beta_1} \\includegraphics[width=0.7\\textwidth]{figs/alpha_beta_2} \\includegraphics[width=0.7\\textwidth]{figs/alpha_beta_3} \\includegraphics[width=0.9\\textwidth]{figs/alpha_beta_4} \\includegraphics[width=0.9\\textwidth]{figs/alpha_beta_5}\n \\end{center}\n\\else\n \\vspace{10em}\n\\fi\n\\end{enumerate}\n\\pagebreak\n\n\\section*{CSPs}\nCSPs are formalized as a triple $\\langle X,D,C \\rangle$. \n\\begin{enumerate}\n\\item $X = \\{X_1, \\ldots, X_n\\}$: A set of variables in the problem\n\\item $D = \\{D_1, \\ldots, D_n\\}$: The domains for these variables\n\\item $C = \\{C_1, \\ldots, C_m\\}$: Constraints\n\\end{enumerate}\nConstraints encode the limits on the values/domains for each variable contingent on the values/domains of other variables.\n\\\\ \\\\\n\\noindent One way to solve a CSP is through \\textbf{backtracking search} which is simply DFS with two changes:\n\\begin{enumerate}\n\\item Fix the variable ordering ($X_1 = D_1 \\rightarrow X_2 = D_2 \\equiv X_2 = D_2 \\rightarrow X_1 = D_1$).\n\\item Check constraints as you go and backtrack if you violate any.\n\\end{enumerate}\n\n\\subsection*{Tasks}\n\nAssume there are 5 CS classes that meet on MWF:\n\\begin{enumerate}\n\\item CS50 - Intro to CS: Meets from 8:00-9:00am\n\\item CS124 - Algorithms: Meets from 9:00-10:00am\n\\item CS181 - Machine Learning: Meets from 10:30-11:30am\n\\item CS182 - Artificial Intelligence: Meets from 8:30-9:30am\n\\item CS187 - Natural Language Processing: Meets from 9:00-10:00am\n\\end{enumerate}\nand 3 professors who will be teaching these classes:\n\\begin{enumerate}\n\\item Professor A, who can teach CS50, CS181, and CS182.\n\\item Professor B, who can teach CS124, CS187, and CS181.\n\\item Professor C, who can teach CS50, CS124, and CS187. \n\\end{enumerate}\nYou are in charge of scheduling and are constrained by the fact that each professor can only teach one class at a time (Problem Adapted from Berkeley material).\n\\begin{enumerate}\n\\item Formulate this problem as a CSP problem in which there is one variable per class, stating the domains, and constraints. Constraints should be specified formally and precisely, but may be implicit rather than explicit.\n\n\\ifsol\n\\textcolor{blue}{\n The following list first shows the variable and then the domains:\n \\begin{itemize}\n \\item $CS50$ - $\\{A, C\\}$\n \\item $CS124$ - $\\{B, C\\}$\n \\item $CS181$ - $\\{A, B\\}$\n \\item $CS182$ - $\\{A\\}$\n \\item $CS187$ - $\\{B, C\\}$\n \\end{itemize}\n Implicit constraints: $\\{CS50 \\neq CS182, CS124 \\neq CS182, CS124 \\neq CS187, CS182 \\neq CS187\\}$\n }\n\\else\n \\vspace{12em}\n\\fi\n\n\n\\item Draw the constraint graph associated with your CSP\n\n\\ifsol\n \\vspace{1em}\n \\begin{tikzpicture}[\n shorten >=1pt, auto, thick,\n node distance=2.5cm,\n main node/.style={circle,draw,fill=blue!20,font=\\sffamily\\Large\\bfseries}\n ]\n \\node[main node] (a) at (0,0) {~50};\n \\node[main node] (b) at (3,0) {124};\n \\node[main node] (c) at (6,0) {181};\n \\node[main node] (d) at (0,-3) {182};\n \\node[main node] (e) at (3,-3) {187};\n \n \\path[every node/.style={font=\\sffamily\\small}]\n (a) edge node {} (d)\n (b) edge node {} (d)\n (b) edge node {} (e)\n (d) edge node {} (e);\n \\end{tikzpicture}\n \\vspace{1em}\n\\else\n \\vspace{12em}\n \\pagebreak\n\\fi\n\n\n\\item Describe the standard backtracking search strategy to solve this problem. Write down a possible solution that you found using the strategy. \n\n\\ifsol\n \\textcolor{blue}{We can use backtracking to solve this problem. The domains dictate the possible next assignments, and we consider one assignment per step. We then check whether constraints are violated after each assignment. Once an incomplete end is reached, we backtrack up the search tree. In the following solution, we use the standard backtracking approach and assign the variables numerical order and professors in alphabetical order (You can look at the lecture notes for heuristics for picking the next unassigned variable, or to filter possible solutions which will solve this problem faster!):\n \\begin{enumerate}\n \\item We first pick $CS50: A$. There are no violated constraints.\n \\item We now pick $CS124: B$. There are no violated constraints. The partial solution is $\\{$CS50: A, CS124: B$\\}$. \n \\item We now pick $CS181: A$. There are no violated constraints. The partial solution is $\\{$CS50: A, CS124: B, CS181: A$\\}$. \n \\item We now pick $CS182: A$. This violates the constraint $CS50 \\neq CS182$. Therefore, we backtrack all the way to step (a) before we can address this.\n \\item We now first pick $CS50: C$. There are no violated constraints. \n \\item We now pick $CS124: B$. There are no violated constraints. The partial solution is $\\{$CS50: C, CS124: B$\\}$. \n \\item We now pick $CS181: A$. There are no violated constraints. The partial solution is $\\{$CS50: C, CS124: B, CS181: A$\\}$. \n \\item We now pick $CS182: A$. There are no violated constraints. The partial solution is $\\{$CS50: C, CS124: B, CS181: A, CS182: A$\\}$. \n \\item We pick $CS187: B$. This does violate the constraint $CS124 \\neq CS187$. We backtrack to step (h).\n \\item We pick $CS187: C$. This does not violate a constraint. We are done. The final solution is $\\{$CS50: C, CS124: B, CS181: A, CS182: A, CS187: C$\\}$. \n \\end{enumerate}}\n\\else\n \\vspace{35em}\n\\fi\n\n\\item Explain why it is a good heuristic to choose the variable that is most constrained but the value that is least constraining in a CSP search\n\n\\ifsol\n \\textcolor{blue}{The reason that this heuristic is effective is that the variable with the least options is the hardest to satisfy, while the least constraining value leaves open the most options for other variables. This gives the highest chance of success. If we had done this above we would have finished the problem faster -- try it yourself!}\n\\else\n \\vspace{5em}\n\\fi\n\n\\end{enumerate}\n\n\\end{document}", "meta": {"hexsha": "94651b911c6fd16dc15c591278930ba880369b36", "size": 13787, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Section_03/tex/main.tex", "max_stars_repo_name": "Harvard-CS182-F18/courseware", "max_stars_repo_head_hexsha": "b1c5cc83dd45091c0ab74e0252405bc79ce51718", "max_stars_repo_licenses": ["MIT"], "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_03/tex/main.tex", "max_issues_repo_name": "Harvard-CS182-F18/courseware", "max_issues_repo_head_hexsha": "b1c5cc83dd45091c0ab74e0252405bc79ce51718", "max_issues_repo_licenses": ["MIT"], "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_03/tex/main.tex", "max_forks_repo_name": "Harvard-CS182-F18/courseware", "max_forks_repo_head_hexsha": "b1c5cc83dd45091c0ab74e0252405bc79ce51718", "max_forks_repo_licenses": ["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.2316602317, "max_line_length": 728, "alphanum_fraction": 0.7237977805, "num_tokens": 3881, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4726834914771176, "lm_q2_score": 0.32082129433083023, "lm_q1q2_score": 0.15164692954450482}} {"text": "\\subsection{VIPUR approach}\nVariant interpretation using Rosetta (VIPUR) is a machine learning approach for predicting deleteriousness of proteins (loss of function) and uses sequential and structural information. \nTo train it the VIPUR training set (VTS) was made which contained sequential an structural features from protein structures that were acquired from Modbase \\cite{pieper_modbase_2009} and\n% modbase, a database of annotated comparative protein structure models and associated resources, pieper\nSWISS-MODEL \\cite{guex_automated_2009,bertoni_modeling_2017,benkert_toward_2011,bienert_swiss-model_2017,waterhouse_swiss-model:_2018}.\n% Automated comparative protein structure modeling with SWISS-MODEL and Swiss-PdbViewer: A historical perspective, Guex\n% Modeling protein quaternary structure of homo- and hetero-oligomers beyond binary interactions by homology, Bertoni\n% Toward the estimation of the absolute quality of individual protein structure models, Benkert\n% The SWISS-MODEL Repository—new features and functionality, Bienert\n% SWISS-MODEL: homology modelling of protein structures and complexes, Waterhouse\nProteins that did not have a structure in modbase or SWISS-MODEL were modeled with Modeller (Section \\ref{subsec:MM_Modeller}) from proteins that had the highest amino acid sequence identity to the desired protein.\nbased on protein fragments that had the highest amino acid sequence identity to the protein\nSome structures from the databases had: duplicate chains, ligands, metals and non-standard amino acids which were removed to avoid inconsistencies for the generated features by tools.\nFor all proteins a mutation file was made that described which and how many residues had to be mutated, with this file DDG monomer (Section \\ref{subsubsec:MM_DDG_Monomer}) could determine changes in the protein structure, most results by ddg were used as features.\nStructural mutations of proteins that are in the VTS were introduced by a script using PyMOL (Section \\ref{subsec:MM_PyMOL}) by default or PyRosetta (Section \\ref{subsec:MM_PyRosetta}) when PyMOL was not available.\nAfter a mutation the structure was optimized by the relax application (Section \\ref{subsubsec:MM_Relax}) that produced 50 structures of a single variant, for each of these structures property scores where available of which all quartiles have been used as a machine learning feature.\nof which the quartiles are used as a learning feature. Probe (Section \\ref{subsec:MM_Probe}) calculated the solvent accessible surface area (SASA/ACCP) of a protein in square {\\AA}ngstrom ({\\AA}$^2$) which was used as a structural machine learning feature. \nThe sequence features of VIPUR were produced by PSI-blast (Section \\ref{subsec:MM_PSI_BLAST}) on non mutated sequences and blasted against the NCBI protein database (nr) which resulted in a position specific scoring matrix (PSSM). \nFrom the PSSM scores of the information content, non-mutated, mutated, the difference in scores between non-mutated and mutated and the difference between groups \\cite{baugh_robust_2016, poultney_rational_2011} used as sequential feature for VIPUR.\n% Robust classification of protein variation using structural modelling and large-scale data integration, Baugh et al.\n% Rational Design of Temperature-Sensitive Alleles Using Computational Structure Prediction, Poultney et al.\nWith 106 features generated by the mentioned tools deleteriousness of a protein variant is determined with sparse logistic regression. The term sparse implies that a limited set of features was used because the weights \"shrink\" to 0 with regularization \\cite{baugh_supplementary:_2016}.\n%SUPPLEMENTARY: Robust classification of protein variation using structural modelling and large-scale data integration, Baugh et al.\n\\label{subsec:MM_VIPUR}\n\n\\subsection{VIPUR specific tools}\n\n\\subsubsection{PSI-BLAST}\nPosition specific iterative basic local alignment search tool (PSI-BLAST) focuses on distant relatives of proteins by making a profile of the sequence and querying it at a protein sequence database. With the generated results a new profile is constructed which is queried to the same database as the previous query. These steps are repeated several times to determine which residues are found in distant relatives and results is a position specific scoring matrix (PSSM) that describes the frequency of which residues are substituted by a specific other residue \\cite{ncbi_psiblast_nodate,ncbi_pssm_nodate,wikipedia_blast_2019}.\n%PSIBLAST, NCBI\n%PSSM Viewer, NCBI\n%BLAST, Wikipedia \nFrom the PSSMs sequences features were acquired for the VIPUR machine learning method.\n\\label{subsec:MM_PSI_BLAST}\n\\newline\n\\textit{Position-Specific Iterated BLAST 2.7.1+}\n\n\\subsubsection{Probe}\nProbe is able to evaluate atom packing for a single protein or for interacting proteins. It does this by creating a probe, which is described as a sphere like object, that marks an area with dots when at least two non-covalent atoms are in contact with the probe. \\cite{word_visualizing_1999, richardson_lab_probe_nodate}. VIPUR used this tool to calculate solvent accessible surface area (SASA or ACCP).\n%Visualizing and quantifying molecular goodness-of-fit: small-probe contact dots with explicit hydrogen atoms11Edited by J. Thornton,Word\n%Probe Software : Kinemage Website, Richardson LAB\n\\label{subsec:MM_Probe}\n\\newline\n\\textit{version 2.16.130520}\n\n\\subsection{Rosetta}\nRosetta is a software suite that has a variety of tools that are developed to aid in macro molecular and antibody, analysis, design and prediction \\cite{rosetta_commons_about_nodate}.\n% About | RosettaCommons, Rosetta Commons\nHowever no tools in the suite have been encountered that could introduce missense mutations in the proteins and was done by other software (Sections \\ref{subsec:MM_PyMOL}, \\ref{subsec:MM_PyRosetta}, \\ref{subsec:MM_Modeller}). With the introduced mutations water had to be removed because some tools cannot predict structures well with: water, metals and amino acids that are no part of the standard (20) amino acids \\cite{rosetta_commons_how_nodate}.\n%How to prepare structures for use in Rosetta, Rosetta commons\n\nWithin the tools from Rosetta various scores are assigned to different properties related to bonds, interactions, energies and geometries within structures and are written into a score file. \nFrom all different scoring metrics the Rosetta score, Rosetta energy unit (REU) or total\\_score in the score files, can be used to compare models from the same protein with the same tool. \nNot only is the score based on energy but also it has statistical terms which influence the score based on known favorable folds from existing structures that reside in the curated Rosetta database \\cite{shourya_scoring_nodate}. \nIn summary to asses models, a lower Rosetta score makes a more natural model.\n%Scoring Tutorial, Shourya et al.\n\\label{subsec:MM_Rosetta}\n\\newline\n\\textit{Rosetta software suite Version 3.10}\n\n\\subsubsection{Relax}\nThe Relax application was used by VIPUR and by SPVAA to relax the side chains to minimize energy levels within the local conformational search space \\cite{rosetta_commons_relax_nodate} of the structure. \nIt determines the energy levels with a Monte Carlo method (Section \\ref{section:Chap_Monte_Carlo}) and after a certain set of moves it produces a structure and starts anew \\cite{conway_relaxation_2014,tyka_alternate_2011}. \n%Relax application, Rosetta Commons \n%Relaxation of backbone bond geometry improves protein energy landscape modeling, Conway et al.\n%Alternate States of Proteins Revealed by Detailed Energy Landscape Mapping, Tyka et al.\n\\label{subsubsec:MM_Relax}\n\n\\subsubsection{DDG Monomer}\nDDG monomer is meant to predict energetic stability of a point mutation in monomeric protein. \nThe application was used by VIPUR to collect features related to energies bonds, bridges and constraints differences between the wild type and a mutated protein. \nTo execute the tool a script had to be ran which renumbered the wild type pdb file and it required a \"mutation file\" that described the changes of a residues based on name and position\\cite{leaver-fay_ddg_monomer_nodate}.\n%ddg_monomer application, Andrew Leaver-Fay\n\\label{subsubsec:MM_DDG_Monomer}\n\n\\subsubsection{Rescore}\nWith this tool Rosetta scores can be calculated based on PDB files proteins structures \\cite{jared_score_2016} , the output is identical to that is written within the score files produced by Relax (Section \\ref{subsubsec:MM_Relax}).\n%Score Commands, Jared\n\\label{subsubsec:MM_Rescore}\n\n\\subsubsection{Backrub}\nThe backrub application is based on the Monte Carlo method (Section \\ref{section:Chap_Monte_Carlo}), and alters a protein by moving its backbone residues with a strategy called fix end move (FEM). \nWith this strategy, groups of residues are selected at random from the structure that can contain up to: four dihedral, two bond angles and two end points. \nBoth ends of a group are fixated at their position in which a new angle $\\alpha$ arises, within this angle residues are pivoted in their natural occurring maximum range of $\\pm \\ang{10}$ \\cite{betancourt_efficient_2005, smith_backrub_nodate}.\n%Efficient Monte Carlo trial moves for polypeptide simulations, Betancourt\n%Backrub application, Smith\nWith this application backbones of newly introduced mutations were altered, for each attempt a new file was generated and the scores were written to a score file. The lowest Rosetta scoring model was selected to undergo side chain relaxation with the Relax application (Section \\ref{subsubsec:MM_Relax}).\n\\label{subsubsec:MM_Backrub}\n\n\\subsection{Structure prediction web services}\n\n\\subsubsection{Robetta prediction server}\nThe web tool Robetta integrates several tools to form protein structures with homology modeling (Section \\ref{subsec:GD_Protein_modeling_techniques}).\nIts only requirement is an amino acid sequence, but optionally constrains and fragments can be added to disallow movement of certain structures or add known fragments to avoid calculating pieces that are already known. With this information Robetta searches with the help of sequence aligners for known fragments and tries to incorporate them into a single protein structure \\cite{song_high-resolution_2013,soding_protein_2005,kallberg_template-based_2012,yang_improving_2011,ovchinnikov_protein_2017}.\n%High-Resolution Comparative Modeling with RosettaCM, Song\n%Protein homology detection by HMM-HMM comparison, Soding\n%Template-based protein structure modeling using the RaptorX web server,Källberg\n%Improving protein fold recognition and template-based modeling by employing probabilistic-based matching between predicted one-dimensional structural properties of query and corresponding native properties of templates, Yang\n%Protein structure determination using metagenome sequence data,Ovchinnikov\nThe known fragments of TNFRSF1A (Section \\ref{subsec:GD_Protein_modeling_techniques}) were given as a template to Robetta and modeled into a whole protein to make it possible to introduce mutations and predict pathogenicity of a variants.\\\\\n\\label{subsec:MM_Robetta}\n\\textit{http://new.robetta.org/}\n\n\\subsubsection{I-TASSER prediction server}\nThe I-TASSER web server is a tool that is able to predict protein structures with a FASTA sequence. The first step it takes is finding structural templates which resemble the sequence by local meta-threading server (LOMETS).\nLOMETS starts with multiple sequence alignment of which several sequences will undergo protein threading by different programs to form structural templates. \nThe templates are assessed made from: the highest alignment Z-score, a program within LOMETS specific confidence score and sequence identity \\cite{zhang_lab_lomets_nodate, wu_lomets:_2007}.\n%LOMETS, Zhang LAB\n%LOMETS: A local meta-threading-server for protein structure prediction, Wu\nThe known fragments of TNFRSF1A (Section \\ref{subsec:GD_Protein_modeling_techniques}) were given as a template to I-TASSER and modeled into a whole protein to make it possible to introduce mutations and predict pathogenicity of a variants.\n\\label{subsec:MM_I_TASSER}\n\\newline\n\\textit{Server version, https://zhanglab.ccmb.med.umich.edu/I-TASSER/}\n\n\\subsubsection{HOPE}\nHave yOur Protein Explained (HOPE) is a web service that collects information of about a user specified missense mutation in a protein and comes from various sources. Uniprot (Section \\ref{subsec:MM_Uniprot}) is queried with BLAST to find homologous sequences and structures, other features that are found on Uniprot are active sites, domains and various other sequence features that help to identify the function of a region. From the BLAST results homology models are made with Yasara that are sent of to WHAT IF web services that calculate structural information about the protein. Before the formation of a report all information is put into a decision tree to asses mutational effects in context of: contacts, structural locations, non-structural features, previous variant information and amino acid properties. \\cite{venselaar_protein_2010,cmbi_hope_nodate,cmbi_hope_nodate-1,cmbi_hope_nodate-2}.\n%Protein structure analysis of mutations causing inheritable diseases. An e-Science approach with life scientist friendly interfaces, Venselaar\n%HOPE, CMBI\n%HOPE about, CMBI\n%HOPE methods, CMBI\nWith this method it is not possible to asses ligands and complexes at once but only a single missense mutation within a protein.\n\\label{subsec:MM_HOPE}\n\\textit{Version 1.1.1, https://www3.cmbi.umcn.nl/hope/}\n\n\\subsection{Structural modification and visualization software}\n\n\\subsubsection{Modeller}\nThe Modeller software that is developed for homology modeling but it was used for its utilities. Which allowed to complete protein data bank (PDB) structures with missing atoms, predict disulfide bonds that were missing and mutate protein residues \\cite{modeller_about_nodate,eswar_comparative_2006,sali_comparative_1993,fiser_modeling_2000}. \n%About MODELLER, Modeller\n%Comparative Protein Structure Modeling Using Modeller, Eswar\n%Comparative Protein Modelling by Satisfaction of Spatial Restraints, Sali\n%Modeling of loops in protein structures., Fiser\n\\label{subsec:MM_Modeller}\n\\newline\n\\textit{Version 9.21}\n\n\\subsubsection{PyMOL}\nVisualization of 3D structures, making images of proteins, putting monomeres in the correct position, replacing TNF $\\beta$ structure with a TNF $\\alpha$ in the bound structure and aligning the structures to measure the distance between models and X-ray structures were done with PyMOL \\cite{schrodinger_pymol_nodate}. PyMOL was in VIPUR used in combination with Python (Section \\ref{subsec:MM_Python}) to perform mutagenesis on the protein structures.\n% PyMOL | pymol.org, Schrödinger\n\\label{subsec:MM_PyMOL}\n\\newline\n\\textit{Version 2.2.3}\n\n\\subsubsection{PyRosetta}\nIs an application programming (API) which has Python bindings (Section \\ref{subsec:MM_Python}) for the Rosetta software suite (Section \\ref{subsec:MM_Rosetta}) and founds its use in VIPUR when no PyMOL (Section \\ref{subsec:MM_PyMOL}) was available to mutate residues in a structure \\cite{jeffrey_pyrosetta_nodate}.\n%PyRosetta, Jeffry\n\\label{subsec:MM_PyRosetta}\n\\newline\n\\textit{Version 4}\n\n\\subsection{Amino acid sequence variant tables}\n\n\\subsubsection{GAVIN Machine Learning Data Table}\nIs a collection of nucleotide mutations from rare diseases used by the GAVIN \\cite{van_der_velde_gavin:_2017} machine learning approach. From this set the genes of TNFRSF1A (Section \\ref{section:Chap_Cell_Death}) with a missense mutation were filtered (Section \\ref{subsec:MM_R}) and written into a format which the variant effect predictor could (VEP) \\cite{ensembl_variant_nodate} could read and translate from nucleotide to protein mutations. The classification of the variants was done by experts based on the five tier IARC classification system \\cite{plon_sequence_2008}. \n%GAVIN: Gene-Aware Variant INterpretation for medical sequencing, Van der Velde\n%Variant Effect Predictor - Homo sapiens - GRCh37 Archive browser 96, ensembl\n%Sequence variant classification and reporting: recommendations for improving the interpretation of cancer susceptibility genetic test results, Plon\n\\label{subsec:MM_GAVIN_data_table}\n\n\\subsubsection{gnomAD}\nThe gnomAD database consists of unified data from large scale genome sequencing data projects and is based on genome reference consortium human genome build 37 human genome 19 (GRCh37/hg19). From this database missense mutations were collected for TNFRSF1A (Section \\ref{subsec:CD_TNFRSF1A}), no classification was known from these mutations \\cite{gnomad_gnomad_nodate}.\n%gnomAD,gnomAD\n\\label{subsec:MM_GnomAD}\n\n\\subsubsection{Infevers}\nInfevers is a website about auto hereditary inflammatory diseases for which each are tables that contain information about mutations and their classification. The table for TRAPS (Section \\ref{subsec:CD_TNFRSF1A}) was used to collect missense mutations of TNFRSF1A gene \\cite{sarrauste_de_menthiere_infevers:_2003}.\n%INFEVERS: the Registry for FMF and hereditary inflammatory disorders mutations, Sarrauste de Menthière\n\\label{subsec:MM_Infevers}\n\n\\subsection{Protein functional and structural databases}\n\n\\subsubsection{Research Collaboratory for Structural Bioinformatics}\nResearch Collaboratory for Structural Bioinformatics (RCSB) is a database where whole or fragmented experimentally determined proteins structures, that are published, can be found and downloaded. The Fragments for modeling (Sections \\ref{subsec:MM_Robetta}, \\ref{subsec:MM_I_TASSER}) whole TNFRSF1A (Section \\ref{subsec:CD_TNFRSF1A}) (1EXT \\cite{naismith_structures_1996}) and determining the differences in energy levels (Section \\ref{subsubsec:MM_Relax}) with TNF $\\alpha$ -$\\beta$ (1TNR \\cite{banner_crystal_1993}) with the interaction site were acquired from this database \\cite{burley_rcsb_2018}.\n%Structures of the extracellular domain of the type I tumor necrosis factor receptor,Naismith\n%Crystal structure of the soluble human 55 kd TNF receptor-human TNFβ complex: Implications for TNF receptor activation, Banner\n%RCSB Protein Data Bank: Sustaining a living digital data resource that enables breakthroughs in scientific research and biomedical education, Burley\n\\label{subsec:MM_RCSB}\n\n\\subsubsection{Uniprot}\nKnowledge from various omic domains about proteins have been linked together into single database called Uniprot which makes all information accessible at once. For TNFRSF1A (Section \\ref{section:Chap_Cell_Death}) the FASTA sequences were collected from Uniprot and for structures it redirected to (Section \\ref{subsec:MM_RCSB}) \\cite{the_uniprot_consortium_uniprot:_2015}.\n%UniProt: a hub for protein information,The UniProt Consortium\n\\label{subsec:MM_Uniprot}\n\n\\subsection{Scripting languages}\n\n\\subsubsection{Python}\nBoth VIPUR and the single protein variant analysis approach (SPVAA) were written in Python. SPVAA was written in Python because of its ease of use and the modeller bindings (Section \\ref{subsec:MM_Modeller}) that were available. \nThe mutations that were put together from the different tables (Sections \\ref{subsec:MM_GnomAD}, \\ref{subsec:MM_Infevers}, \\ref{subsec:MM_GAVIN_data_table}) with R (Section \\ref{subsec:MM_R}) were filtered by a Python script. \nFrom the mutations a compact list was made by a different script that described the chains that had to be altered by modeller to introduce the appropriate mutation into a PDB file. From these PDB files several were selected to be optimized by pipeline that used backrub (Section \\ref{subsubsec:MM_Backrub}) and Relax (Section \\ref{subsubsec:MM_Relax} ) to optimize the structure.\n\\label{subsec:MM_Python}\n\\newline\n\\textit{Laptop version 2.7.15}\n\\newline\n\\textit{Server version 2.7.11}\n\n\\subsubsection{R scripting language}\nWith R the tables from gnomAD, GAVIN and Infevers (Sections \\ref{subsec:MM_GnomAD}, \\ref{subsec:MM_GAVIN_data_table}, \\ref{subsec:MM_Infevers}) of TNFRSF1A missense mutations (Section \\ref{subsec:CD_TNFRSF1A}) were merged together in a new comma seperated values file with their known classifications. Ordering and filtering the double mutations and removing double classifcations where done with Python (Section \\ref{subsec:MM_Python}). It has also been used in combination ggplot2 \\cite{wickham_create_nodate} and data.table \\cite{dowle_rs_2019} to make density plots of all scores acquired from Rosetta Backrub and Relax (See the supplementary for R package versions).\n%ggplot Wickham\n% data table, Dowl et al\n\\label{subsec:MM_R}\n\\newline\n\\noindent\n\\textit{R scripting front-end version 3.5.2 (2018-12-20)}\n\n\\subsection{Utility software}\n\n\\subsubsection{Bash}\nUnix like operating systems (OS) have a shell which allows users to interact with programs on a computer or with the computer itself based on commands submitted. The default shell for MacOS and also for several Linux distributions is the Bourne again shell (Bash) which was used to launch Python scripts (Section \\ref{subsec:MM_Python}) and submit jobs to the SLURM workload manager (Section \\ref{subsec:MM_SLURM}). \n\\label{subsec:MM_Bash}\n\\newline\n\\textit{Laptop Version GNU bash, version 3.2.57(1)-release (x86\\_64-apple-darwin18)}\n\\newline\n\\textit{Server Version GNU bash, version 4.1.2(2)-release (x86\\_64-redhat-linux-gnu)}\n\n\\subsubsection{SLURM}\nFor computational jobs where a laptop or desktop does not suffice because due to the lack computational resources a computer cluster could come to aid.\nThese clusters consist out of several computers that execute resource intensive tasks, to manage these systems as optimal and fair as possible a workload manager like simple Linux utility resource management (SLURM), is installed. Jobs are submitted that request resources for execution and are scheduled on the systems queue.\n\\label{subsec:MM_SLURM}\n\n\\subsubsection{MPI}\nSome tools from the Rosetta software suite (Sections \\ref{subsec:MM_Rosetta}) have the ability to use multiple central processing unit (CPU) cores from a single computer or from multiple computers. With a message parsing interface (MPI) it is possible for software to communicate between CPU cores on the same and on different computers to exchange information about processes giving the ability to share work between computers and CPUs.\n\\label{subsec:MM_MPI}\n\\newline\n\\textit{OpenMPI/1.8.8-GNU-4.9.3-2.25}\n\\newline\n\n\n\n", "meta": {"hexsha": "4785f4d15066b5dd4b5ad66b1601b51d93fb486e", "size": 22374, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "Report/Chapters/Materials_And_Methods.tex", "max_stars_repo_name": "Sylt-CSI/variant-protein-prediction", "max_stars_repo_head_hexsha": "2a4451636907e7c54b58c648893b7d92167d1f7e", "max_stars_repo_licenses": ["Python-2.0", "OLDAP-2.7"], "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/Materials_And_Methods.tex", "max_issues_repo_name": "Sylt-CSI/variant-protein-prediction", "max_issues_repo_head_hexsha": "2a4451636907e7c54b58c648893b7d92167d1f7e", "max_issues_repo_licenses": ["Python-2.0", "OLDAP-2.7"], "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/Materials_And_Methods.tex", "max_forks_repo_name": "Sylt-CSI/variant-protein-prediction", "max_forks_repo_head_hexsha": "2a4451636907e7c54b58c648893b7d92167d1f7e", "max_forks_repo_licenses": ["Python-2.0", "OLDAP-2.7"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 97.7030567686, "max_line_length": 903, "alphanum_fraction": 0.8204612497, "num_tokens": 5415, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.26588047309981694, "lm_q1q2_score": 0.15151269255518116}} {"text": "%-*- coding:utf-8 -*-\n\n\\title{ALPS Tutorial \\\\ 03 -- Application Tutorial (1)}\n\n\\begin{document}\n\n\\lstset{language={C++},showspaces=false,rulecolor=\\color[cmyk]{0, 0.29,0.84,0}}\n\n\\begin{frame}\n \\titlepage\n\\end{frame}\n\n\\section*{Outline}\n\\begin{frame}[t,fragile]\n \\tableofcontents\n\\end{frame}\n\n\\section{Before starting simulations}\n\n\\subsection*{\\redb\\whiteb\\greenm}\n\\begin{frame}[t,fragile]{Before starting simulations -- common operations}\n \\begin{itemize}\n % \\setlength{\\itemsep}{1em}\n \\item Open terminal\n \\begin{itemize}\n \\item \\alert{On MateriAps LIVE!: Start Menu $\\Rightarrow$ ``System Tools'' $\\Rightarrow$ ``LXTerminal''}\n \\item On macOS: Open ``Terminal'' application\n \\item If using a remote workstation, open the terminal and SSH to the remote node\n \\end{itemize}\n\n \\item PATH setting\n \\begin{itemize}\n \\item \\alert{On MateriAps LIVE!: PATH has been configured already}\n \\item In other environment, you have to run alpsvars.sh. ex)\n\\begin{lstlisting}\n$ source /usr/local/alps/bin/alpsvars.sh\n\\end{lstlisting}\n \\end{itemize}\n \n \\item Tutorial files\n \\begin{itemize}\n \\item \\alert{On MateriApps LIVE!: Tutorial files can be found in /usr/share/alps/tutorials/}\n \\item In other environment, there should be ``tutorials'' directory in the place where ALPS is installed\n \\end{itemize}\n \\end{itemize}\n\\end{frame}\n\n\\section{Two-dimensional ferromagnetic Ising model}\n\n\\subsection*{\\redb\\whiteb\\greenm}\n\\begin{frame}[t,fragile]{Phase transition in two-dimensional ferromagnetic Ising model (1)}\n \\begin{itemize}\n % \\setlength{\\itemsep}{1em}\n \\item Most simplest model that exhibits a phase transiton\n \\[\n {\\cal H} = - J \\sum_{\\langle i,j \\rangle} \\sigma_i \\sigma_j \\qquad (\\sigma = \\pm 1)\n \\]\n \\item Second-order phase transition happens at critical temperature ($T_{\\rm c} = 2/\\log(1+\\sqrt{2}) = 2.269\\cdots$)\n \\item At high temperatures ($T > T_{\\rm c}$): paramagnetic phase, no long-range order due to entropy effect\n \\item At low temperatures ($T < T_{\\rm c}$): ferromagnetic phase, long-range order due to interaction between spins\n \\item Specific heat and susceptibility diverge at the critical point (critical phenomena)\n    \\item Simulation of equilibrium state by simplemc classical Monte Carlo code (Metropolis method)\n  \\end{itemize}\n\\end{frame}\n\n\\subsection*{\\redb\\whiteb\\greenm}\n\\begin{frame}[t,fragile]{Phase transition in two-dimensional ferromagnetic Ising model (2)}\n \\begin{itemize}\n % \\setlength{\\itemsep}{1em}\n \\item Copy tutorial file\n\\begin{lstlisting}\n$ cp -r /usr/share/alps/tutorials/mc-09-snapshot .\n$ cd mc-09-snapshot\n\\end{lstlisting}\n \\item Convert parameter file into XML files parm9a.*.in.xml\n\\begin{lstlisting}\n$ parameter2xml parm9a\n\\end{lstlisting}\n \\item Execute simulation\n\\begin{lstlisting}\n$ simplemc parm9a.in.xml\n\\end{lstlisting}\n\\item Plot results\n\\begin{lstlisting}\n$ python plot9a.py\n\\end{lstlisting}\n\\item Close three plot windows\n \\end{itemize}\n\\end{frame}\n\n\\subsection*{\\redb\\whiteb\\greenm}\n\\begin{frame}[t,fragile]{Paramter file (parm9a)}\n \\begin{itemize}\n \\setlength{\\itemsep}{1em}\n \\item Look at the contents by ``less parm9a''\n \\begin{itemize}\n \\item \\verb+LATTICE=\"square lattice\"+ : specify square lattice\n \\item \\verb+J=1+ : ferromagnetic interaction ($J>0$)\n \\item \\verb+ALGORITHM=\"ising\"+ : use Ising model simulator\n \\item \\verb+SWEEPS=65536+ : Monte Carlo steps\n \\item \\verb+L=8+ : linear extent of lattice ($L=8, 16, 24$)\n \\item \\verb+{ T = 5.0 }+ : list of temperatures\n \\end{itemize}\n \\item Variables not enclosed in \\{ \\} are common parameters\n \\item Simulation is performed for each \\{ \\} (XML file (*.task*.*) is created for each temperature)\n \\end{itemize}\n\\end{frame}\n\n\\subsection*{\\redb\\whiteb\\greenm}\n\\begin{frame}[t,fragile,shrink]{Python plot script (plot9a.py)}\n \\begin{itemize}\n % \\setlength{\\itemsep}{1em}\n \\item Extraction results from data files\n\\begin{lstlisting}\ndata = pyalps.loadMeasurements(pyalps.getResultFiles(prefix='parm9a'),\n ['Specific Heat','Magnetization Density^2','Binder Ratio of Magnetization'])\n\\end{lstlisting}\n \\item Organize by system sizes\n\\begin{lstlisting}\nfor item in pyalps.flatten(data):\n item.props['L'] = int(item.props['L'])\nmagnetization2 = pyalps.collectXY(data, x='T',y='Magnetization Density^2',\n foreach=['L'])\nmagnetization2.sort(key=lambda item: item.props['L'])\n\\end{lstlisting}\n \\item Plot using matplotlib\n\\begin{lstlisting}\npyplot.figure()\nalpsplot.plot(magnetization2)\n\\end{lstlisting}\n \\end{itemize}\n\\end{frame}\n\n\\subsection*{\\redb\\whiteb\\greenm}\n\\begin{frame}[t,fragile]{Visualization of snapshot of Ising spins (1)}\n \\begin{itemize}\n % \\setlength{\\itemsep}{1em}\n \\item Look at spin state in paramagnetic phase, in critical point, and in ferromagnetic phase\n \\item Parameter SNAPSHOT\\_INTERVAL is added in the parameter file (parm9b)\n \\item Convert parameter file\n\\begin{lstlisting}\n$ parameter2xml parm9b\n\\end{lstlisting}\n \\item Execute simulation\n\\begin{lstlisting}\n$ simplemc parm9b.in.xml\n\\end{lstlisting}\n\\item Convert snapshot\n\\begin{lstlisting}\n$ snap2vtk parm9b.*.snap\n\\end{lstlisting}\n \\end{itemize}\n\\end{frame}\n\n\\subsection*{\\redb\\whiteb\\greenm}\n\\begin{frame}[t,fragile]{Visualization of snapshot of Ising spins (2)}\n \\begin{itemize}\n % \\setlength{\\itemsep}{1em}\n \\item Start ParaView (Start Menu $\\Rightarrow$ ``Education'' $\\Rightarrow$ ``ParaView Viewer''\n \\item file $\\Rightarrow$ open $\\Rightarrow$ choose parm9b.task1.clone1.16384.vtk $\\Rightarrow$ OK $\\Rightarrow$ Apply\n \\begin{itemize}\n \\item filters $\\Rightarrow$ common $\\Rightarrow$ glyph (or click globe-like icon)\n \\item Glyph Type = Box, X Length = 0.08, Y Length = 0.08, Maximum Number of Points = 20000 $\\Rightarrow$ Apply\n \\end{itemize}\n \\item Click horizontal division icon at upper right corner\n \\item file $\\Rightarrow$ open $\\Rightarrow$ choose parm9b.task2.clone1.16384.vtk $\\Rightarrow$ OK $\\Rightarrow$ Apply\n \\begin{itemize}\n \\item filters $\\Rightarrow$ common $\\Rightarrow$ glyph (or click globe-like icon)\n \\item Set Glyph in the same way\n \\end{itemize}\n \\end{itemize}\n\\end{frame}\n\n\\subsection*{\\redb\\whiteb\\greenm}\n\\begin{frame}[t,fragile]{Visualization of snapshot of Ising spins (3)}\n \\begin{itemize}\n % \\setlength{\\itemsep}{1em}\n \\item Click horizontal division icon at upper right corner\n \\item file $\\Rightarrow$ open $\\Rightarrow$ choose parm9b.task3.clone1.16384.vtk $\\Rightarrow$ OK $\\Rightarrow$ Apply\n \\begin{itemize}\n \\item filters $\\Rightarrow$ common $\\Rightarrow$ glyph (or click globe-like icon)\n \\item Set Glyph in the same way\n \\end{itemize}\n \\item Link cameras\n \\begin{itemize}\n \\item Adjust windows to become the same size\n \\item Click middle window $\\Rightarrow$ Tools $\\Rightarrow$ Add Camera Link $\\Rightarrow$ click left window\n \\item Link right window to left one similarly\n \\end{itemize}\n \\end{itemize}\n\\end{frame}\n\n\\section{Visualization of spin vortices}\n\n\\subsection*{\\redb\\whiteb\\greenm}\n\\begin{frame}[t,fragile]{Visualization of spin vortex in two-dimensional classical XY model}\n \\begin{itemize}\n % \\setlength{\\itemsep}{1em}\n \\item Convert parameter file, execute simulation, convert snapshots\n\\begin{lstlisting}\n$ parameter2xml parm9c\n$ simplemc parm9c.in.xml\n$ snap2vtk parm9c.*.snap\n\\end{lstlisting}\nNote that \\verb+ALGORITHM=\"xy\"+ in the parameter file\n \\item Visualization using ParaView\n \\begin{itemize}\n \\item file $\\Rightarrow$ open $\\Rightarrow$ choose parm9c.task1.clone1.16384.vtk $\\Rightarrow$ OK\n \\item properties tab $\\Rightarrow$ Apply\n \\item Add Glyph\n \\item Glyph Type = Arrow, Tip Radius = 0.2, Shaft Radius = 0.06, Translate = -0.1 0 0, Scale = 0.2 0.2 0.2 $\\Rightarrow$ Apply\n \\end{itemize}\n \\end{itemize}\n\\end{frame}\n\n\\section{Antiferromagnetic classical Heisenberg model on triangular lattice}\n\n\\subsection*{\\redb\\whiteb\\greenm}\n\\begin{frame}[t,fragile]{Antiferromagnetic classical Heisenberg model on triangular lattice}\n \\begin{itemize}\n % \\setlength{\\itemsep}{1em}\n \\item Convert parameter file, execute simulation, convert snapshots\n\\begin{lstlisting}\n$ parameter2xml parm9d\n$ simplemc parm9d.in.xml\n$ snap2vtk parm9d.*.snap\n\\end{lstlisting}\nNote that \\verb+LATTICE+, \\verb+J+, \\verb+ALGORITHM+, \\verb+H+ in the parameter file\n \\item Visualization using ParaView\n \\begin{itemize}\n \\item file $\\Rightarrow$ open $\\Rightarrow$ choose parm9d.task1.clone1.16384.vtk $\\Rightarrow$ OK\n \\item properties tag $\\Rightarrow$ Apply\n \\item Add Glyph and set Arrow\n \\item Display tag $\\Rightarrow$ Color by $\\Rightarrow$ Glyph Vector $\\Rightarrow$ Z $\\Rightarrow$ Properties tag\n \\item Display one more snapshot (parm9d.task2.clone1.16384.vtk) and link cameras\n \\end{itemize}\n \\end{itemize}\n\\end{frame}\n\n\\end{document}\n", "meta": {"hexsha": "0dd58c9701e0edf7849a38154cda4cda3a57721f", "size": 8865, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "tutorial/tutorial1-en.tex", "max_stars_repo_name": "cmsi/alps-tutorial", "max_stars_repo_head_hexsha": "3c9949e05b86e26507b483e93deb261f3b6b70a8", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2016-07-04T15:36:56.000Z", "max_stars_repo_stars_event_max_datetime": "2018-10-13T11:05:12.000Z", "max_issues_repo_path": "tutorial/tutorial1-en.tex", "max_issues_repo_name": "cmsi/alps-tutorial", "max_issues_repo_head_hexsha": "3c9949e05b86e26507b483e93deb261f3b6b70a8", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": 21, "max_issues_repo_issues_event_min_datetime": "2015-02-02T09:03:36.000Z", "max_issues_repo_issues_event_max_datetime": "2017-07-21T01:20:27.000Z", "max_forks_repo_path": "tutorial/tutorial1-en.tex", "max_forks_repo_name": "cmsi/alps-tutorial", "max_forks_repo_head_hexsha": "3c9949e05b86e26507b483e93deb261f3b6b70a8", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2017-07-20T08:43:43.000Z", "max_forks_repo_forks_event_max_datetime": "2017-07-20T08:43:43.000Z", "avg_line_length": 36.7842323651, "max_line_length": 132, "alphanum_fraction": 0.7192329385, "num_tokens": 2623, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45713671682749485, "lm_q2_score": 0.33111974622959367, "lm_q1q2_score": 0.1513669936681497}} {"text": "% file: AGAT_dump.tex\n% Algebraic Geometry, Algebraic Topology, in unconventional ``grande'' format; fitting a widescreen format\n% \n% github : ernestyalumni\n% linkedin : ernestyalumni \n% wordpress.com : ernestyalumni\n%\n% This code is open-source, governed by the Creative Common license. Use of this code is governed by the Caltech Honor Code: ``No member of the Caltech community shall take unfair advantage of any other member of the Caltech community.'' \n% \n\n\\documentclass[10pt]{amsart}\n\\pdfoutput=1\n%\\usepackage{mathtools,amssymb,lipsum,caption}\n\\usepackage{mathtools,amssymb,caption}\n\n\n\\usepackage{graphicx}\n\\usepackage{hyperref}\n\\usepackage[utf8]{inputenc}\n\\usepackage{listings}\n\\usepackage[table]{xcolor}\n\\usepackage{pdfpages}\n%\\usepackage[version=3]{mhchem}\n%\\usepackage{mhchem}\n\n\\usepackage{tikz}\n\\usetikzlibrary{matrix,arrows,backgrounds} % background for framed option\n\\usetikzlibrary{arrows.meta}\n\\usetikzlibrary{cd}\n\n\\usepackage{multicol}\n\n% ----------------------------------------------------------------------------------------\n% 20180203\n\n\\usetikzlibrary{calc}\n\n% ----------------------------------------------------------------------------------------\n\n\n\\hypersetup{colorlinks=true,citecolor=[rgb]{0,0.4,0}}\n\n\\oddsidemargin=15pt\n\\evensidemargin=5pt\n\\hoffset-45pt\n\\voffset-55pt\n\\topmargin=-4pt\n\\headsep=5pt\n\\textwidth=1120pt\n\\textheight=595pt\n\\paperwidth=1200pt\n\\paperheight=700pt\n\\footskip=40pt\n\n\n\\newtheorem{theorem}{Theorem}\n\\newtheorem{corollary}{Corollary}\n\\newtheorem{axiom}{Axiom}\n%\\newtheorem*{main}{Main Theorem}\n\\newtheorem{lemma}{Lemma}\n\\newtheorem{proposition}{Proposition}\n\n\\newtheorem{definition}{Definition}\n\\newtheorem{remark}{Remark}\n\n\\newenvironment{claim}[1]{\\par\\noindent\\underline{Claim:}\\space#1}{}\n\\newenvironment{claimproof}[1]{\\par\\noindent\\underline{Proof:}\\space#1}{\\hfill $\\blacksquare$}\n\n%This defines a new command \\questionhead which takes one argument and\n%prints out Question #. with some space.\n\\newcommand{\\questionhead}[1]\n {\\bigskip\\bigskip\n \\noindent{\\small\\bf Question #1.}\n \\bigskip}\n\n\\newcommand{\\problemhead}[1]\n {\n \\noindent{\\small\\bf Problem #1.}\n }\n\n\\newcommand{\\exercisehead}[1]\n { \\smallskip\n \\noindent{\\small\\bf Exercise #1.}\n }\n\n\\newcommand{\\solutionhead}[1]\n {\n \\noindent{\\small\\bf Solution #1.}\n }\n\n\n\\title{The Algebraic Geometry Algebraic Topology Dump}\n\\author{Ernest Yeung \\href{mailto:ernestyalumni@gmail.com}{ernestyalumni@gmail.com}}\n\\date{5 mars 2017}\n\\keywords{Algebraic Geometry, Algebraic Topology}\n\\begin{document}\n\n\\definecolor{darkgreen}{rgb}{0,0.4,0}\n\\lstset{language=Python,\n frame=bottomline,\n basicstyle=\\scriptsize,\n identifierstyle=\\color{blue},\n keywordstyle=\\bfseries,\n commentstyle=\\color{darkgreen},\n stringstyle=\\color{red},\n }\n%\\lstlistoflistings\n\n\\maketitle\n\nFrom the beginning of 2016, I decided to cease all explicit crowdfunding for any of my materials on physics, math. I failed to raise \\emph{any} funds from previous crowdfunding efforts. I decided that if I was going to live in \\emph{abundance}, I must lose a scarcity attitude. I am committed to keeping all of my material \\textbf{open-sourced}. I give all my stuff \\emph{for free}. \n\nIn the beginning of 2017, I received a very generous donation from a reader from Norway who found these notes useful, through \\emph{PayPal}. If you find these notes useful, feel free to donate directly and easily through \\href{https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=ernestsaveschristmas%2bpaypal%40gmail%2ecom&lc=US&item_name=ernestyalumni¤cy_code=USD&bn=PP%2dDonationsBF%3abtn_donateCC_LG%2egif%3aNonHosted}{PayPal}, which won't go through a 3rd. party such as indiegogo, kickstarter, patreon. Otherwise, under the \\emph{open-source MIT license}, feel free to copy, edit, paste, make your own versions, share, use as you wish. \n\n\\noindent gmail : ernestyalumni \\\\\nlinkedin : ernestyalumni \\\\\ntwitter : ernestyalumni \\\\\n\n\\begin{multicols*}{2}\n\n \n\\setcounter{tocdepth}{1}\n\\tableofcontents\n\n\n\n\\begin{abstract}\nEverything about Algebraic Geometry, Algebraic Topology\n\n\\end{abstract}\n\n\\part{Algebra; Groups, Rings, R-Modules, Categories}\n\nWe should know some algebra. I will follow mostly Rotman (2010) \\cite{JRotman2010}. \n\n\\section{Prime numbers, GCD (greatest common denominator), integers, Euler's totient, Chinese Remainder Theorem, integer divison, modulus, remainders; Euclid's Lemma}\n\n\n%--------------------------------------------------------------------------------\n% 20180311 \n%-------------------------------------------------------------------------------\n\n\\begin{definition}[natural numbers $\\mathbb{N}$]\n\tnatural numbers $\\mathbb{N}$ \n\t\n\t\\begin{equation}\n\t\\mathbb{N} = \\lbrace \\text{ integers } n | n \\geq 0 \\rbrace \n\t\\end{equation}\ni.e. $\\mathbb{N}$ is set of all nonnegative integers. \t\n\\end{definition}\n\n\\begin{definition}[prime]\nnatural number $p$ is \\textbf{prime} if $p\\geq 2$, and $\\nexists$ \\emph{ factorization} $p=ab$, where $a0 \\\\ } } i =d$. \n\nSo $r=0$, and $d|c=c/d$. \n\\[\nc \\in (d), \\text{ so } I\\subseteq (d) \\Longrightarrow I =(d)\n\\]\n\\end{proof}\n\n\n\\begin{theorem}[\\textbf{Euclid's Lemma}; 1.10 of Rotman (2010) \\cite{JRotman2010}]\nIf $p$ prime and $p|ab$, then $p|a$ or $p|b$. \n\nMore generally, \\\\\nif prime $p$ divides product $a_1a_2\\dots a_n$, \\\\\nthen it must divide at least 1 of the factors $a_i$. \n\ni.e. (notation), \n\nIf prime $p$, and $ab/p \\in \\mathbb{Z}$, \\\\\nthen $a/p\\in \\mathbb{Z}$ or $b/p \\in \\mathbb{Z}$. \n\nMore generally, \\\\\nif prime $p$, s.t. $a_1a_2 \\dots a_n/p \\in \\mathbb{Z}$, \\\\\nthen $\\exists \\, $ 1 \\, $a_i$ s.t. $a_i/p \\in \\mathbb{Z}$\n\\end{theorem}\n\\begin{proof}\nIf $p\\nmid a$, i.e. $a/p \\notin \\mathbb{Z}$, then $\\text{gcd}(p,a) \\equiv (p,a) =1$. \n\nFrom Thm. \\ref{Thm:lincombgcd}, \n\\[\n1 = sp+ta\n\\]\n\\[\n\\Longrightarrow b = spb + tab = p(sb+td)\n\\]\n$ab/p$ and so $ab=pd$, so $b=spb+tdp$, i.e. $b$ is a multiple of $p$ ($b/p \\in \\mathbb{Z} \\equiv p | b$). \n\n\n\n\n\\end{proof}\n\n\\begin{corollary}[1.11 of Rotman (2010) \\cite{JRotman2010}]\\label{Cor:relprimefactors}\nLet $a,b,c \\in \\mathbb{Z}$. \n\nIf $c,a$ relatively prime, i.e. $\\text{gcd}(c,a)=1$, and if $c|ab \\equiv ab/c\\in \\mathbb{Z}$,\nthen $c|b \\equiv b/c \\in \\mathbb{Z}$\n\\end{corollary}\n\\begin{proof}\n\\[\n\\text{gcd}(c,a)=1 = sc+ta \\Longrightarrow b=sbc + tab = sbc + t(qc) = c(sb+tq) \\Longrightarrow b/c = sb+tq \n\\]\n\\end{proof}\n\n\\begin{theorem}[Euclidean Algorithm]\n\tLet $a,b \\in \\mathbb{Z}^+$. \\\\\n\t$\\exists \\, $ algorithm that finds $d= \\gcd{a,b}$\n\\end{theorem}\n\ncf. pp. 5, Thm. 1.14 (Euclidean Algorithm), Ch. 1 Things Past of Rotman (2010) \\cite{JRotman2010}. \n\n\\begin{proof}\n\t\\end{proof}\n\n\\begin{definition}\n\tLet fixed $m\\geq 0$. Then $a,b \\in \\mathbb{Z}$ are \\textbf{congruent modulo } $m$, denoted by \n\t\\[\n\ta \\equiv b \\bmod{m} \n\t\\]\nif $m|(a-b)$, i.e. $(a-b)/m \\in \\mathbb{Z}$, i.e. if $(a-b)/m\\in\\mathbb{Z}$, i.e. $(a-b)$ integer multiple of $m$\n\\end{definition}\n\n\\begin{proposition}\n\tIf $m\\geq 0$ is fixed, $m\\in \\mathbb{Z}$, then $\\forall \\, a,b,c \\in \\mathbb{Z}$\n\t\\begin{enumerate}\n\t\t\\item $a \\equiv a\\bmod{m}$ \n\t\t\\item if $a \\equiv b\\bmod{m}$, then $b \\equiv a\\bmod{m}$\n\t\t\\item if $a \\equiv b\\bmod{m}$, and $b \\equiv c\\bmod{m}$, then $a \\equiv c\\bmod{m}$\n\t\\end{enumerate}\n\\end{proposition}\n\ncf. Prop. 1.18 of Rotman (2010) \\cite{JRotman2010}\n\n\\begin{proof}\n\t\\begin{enumerate}\n\t\t\\item $(a-a)/m=0/m=0$\n\t\t\\item $(b-a)/m=(-1)(a-b)/m \\in \\mathbb{Z}$\n\t\t\\item $(a-c)/m=(a-b+b-c)/m=(a-b)/m+(b-c)/m\\in\\mathbb{Z}$ \n\t\\end{enumerate}\n\\end{proof}\n\nEY : 20171225 to recap, \n\n\\begin{equation}\n\\boxed{ \n\t\\begin{gathered}\n\ta \\equiv b \\bmod{n} \\\\\n\t\\text{ meaning } \\\\ \n\t\\frac{a-b}{n} \\in \\mathbb{Z} \\text{ or } a- b =kn, \\ k\\in \\mathbb{Z} \\text{ or } a = b+kN \\text{ but rather } \\\\\n\t\\begin{aligned}\n\t& a = pn + r \\\\\n\t& b= qn +r\n\t\\end{aligned}\n\t\\end{gathered}\t\n}\n\\end{equation}\nfor $a= b+ kn$, but $b$ need not be a remainder of division of $a$ by $n$. More precisely, $a= b\\bmod{n}$ asserts that $a,b$ have the same remainder when divided by $n$, i.e. \n\\[\n\\begin{aligned}\n& a = pn + r \\\\ \n& b = qn + r\n\\end{aligned}\n\\]\n\n\nSo $a\\sim b$ or $[a] = [b]$ is an equivalence relation since \\\\\n$a\\sim a$ since $a\\equiv a \\bmod{N}$, since $a=a+0N$, \\\\\nif $a\\sim b$, then $b\\sim a$, since $a-b=kN$, then $b=a-kN$ \\\\\nif $a\\sim b$, $b\\sim c$, then $a\\sim c$, since $\\begin{aligned} & \\quad \\\\ \n\t& a-b = kN \\\\\n\t& b-c = lN \\end{aligned}$, then $a-c = (k+l)N$. \n\t\n\t\n\n\n\ncf. Prop. 1.19 of Rotman (2010) \\cite{JRotman2010} \n\\begin{proposition}\nLet $m\\geq 0$ be fixed \n\\begin{enumerate}\n\t\\item If $a=qm +r$, then $a \\equiv r \\bmod{m}$ \n\t\\item If $0\\leq r' r > r' \\leq 0 \\\\\n\tm > r' + km > r' \\leq 0 \\\\\n\tm-r' > km > 0 \n\t\\end{gathered}\n\t\\]\n\tBut $k>0$ (since $m>0$ and $r-r' = km >0$) and $m-r' > km > 0$ is a contradiction. \n\t\n\t\\item \\emph{Want}: $a \\equiv b \\bmod{m}$ iff $a,b$ leave same remainder after dividing by $m$. By \n\t\n\tBy Division Algorithm, this is true: \n\t\\[\n\t\\begin{aligned}\n\t& a=q_a m + r_a \\\\ \n\t & b= q_b m + r_b \n\t\\end{aligned}\n\t\\] \n\t\\[\n\t\\begin{gathered}\n\t\\frac{a-b}{m} = q_a + \\frac{r_a}{m} - q_b - \\frac{r_b}{m} = k = q_a - q_b + \\frac{r_a - r_b}{m} \\in \\mathbb{Z}\n\t\\end{gathered}\n\t\\]\n\tNow \n\t\\[\n\t\\begin{aligned}\n\t& |m| > r_a \\leq 0 \\\\ \n\t& |m| > r_b \\leq 0 \n\t\\end{aligned}\n\t\t\\]\n\t\t$2|m| > r_a + r_b$. \n\t\t\n\t\tAnd if $r_a > r_b$, $|m| > r_a > r_a -r_b > 0$. \n\t\t\n\t\tIn both cases, $r_a=r_b$ since $q_a - q_b + \\frac{r_a - r_b}{m} \\in \\mathbb{Z}$ needs to be enforced. \n\t\t\n\t\\item \\emph{Want}: If $m\\geq 2$, $\\forall \\, a \\in \\mathbb{Z}$, $a \\equiv b \\bmod{m}$ for some $b\\in 0,1,\\dots m-1$. \n\t\n\tBy Division Algorithm Thm. \\ref{Thm:DivisionAlgorithm}, $a = q_a m + r_a$, \\, $0 \\leq r_a < |m|$. $\\frac{a-r_a}{m} = q_a \\in \\mathbb{Z}$ so let $b= r_a$. \n\t\n\\end{enumerate}\t\n\\end{proof}\n\n\\begin{theorem}[1.26 of Rotman (2010) \\cite{JRotman2010}]\\label{Thm:relprimeinvertible} \nIf $\\text{gcd}(a,m) \\equiv (a,m) = 1$, then $\\forall \\, b \\in \\mathbb{Z}$, $\\exists \\, x $ s.t. \n\\[\nax \\equiv b\\bmod{m}\n\\]\nIn fact, $x=sb$, where $sa\\equiv 1\\bmod{m}$ is 1 solution. Moreover, any 2 solutions are congruent $\\bmod{m}$.\n\ni.e. % \\\\\n\nIf $\\gcd{a,b} = 1$, then $\\forall \\, y \\in \\mathbb{Z}$, $\\exists \\, x$ s.t. $ax \\equiv y \\bmod{b}$, $x=sy$, where $sa\\equiv 1\\bmod{b}$ is 1 solution. \\\\\nMoreover, any 2 solutions are congruent $\\bmod{m}$. This implies that \\\\\n\n$ax\\equiv y \\bmod{b}$ or $\\frac{Ax-y}{b} \\in \\mathbb{Z}$, and $\\frac{(as-1)y }{b} \\in \\mathbb{Z}$. \\\\\n$sa \\equiv 1 \\bmod{b}$ or $\\frac{sa-1}{b} \\in \\mathbb{Z}$, which implies that $sa-1 = b(-t)$ or \n\n\\[\nsa + tb =1\n\\]\nfor some $s,t\\in \\mathbb{Z}$. \n\\end{theorem}\n\\begin{proof}\n$\\gcd(a,m) = 1=sa+tm$, by Thm. \\ref{Thm:lincombgcd} \n\nThen $b=b\\cdot 1= b(sa+tm) = sab+tmb$ or $b=tbm+sab$ or $a(sb) = -tbm + b$. \n\nSo $a(sb)\\bmod{m} \\equiv b$. \n\nLet $x:= sb$ and so $ax \\bmod{m}=b$. \\\\\nNow suppose $x \\neq sb$ s.t. $ax\\bmod{m}=b$. Then $ax=qm +b$. From $a(sb) \\bmod{m}=b$, we also get $a(sb) = q'm + b$. Then $a(x-sb) \\bmod{m}=0$, so $m|a(x-sb) \\equiv a(x-sb)/m\\in \\mathbb{Z}$. \n\nBy Corollary \\ref{Cor:relprimefactors} (which says, if $\\gcd(c,a)=1$ and if $ab/c\\in\\mathbb{Z}$, then $b/c \\in \\mathbb{Z}$), \nsince $\\gcd(m,a) = (m,a)=1$, and since $a(x-sb)/m \\in \\mathbb{Z}$, then $(x-sb)/m\\in\\mathbb{Z}$. So $(x-sb)=qm$ or $(sb)\\bmod{m} = x$. \n\n\n\\end{proof}\n\n\n\n\\begin{proposition}[3.1 of Scheinerman (2006) \\cite{Sche2006}]\\label{Prop:commongcd}\nLet $a,b\\in \\mathbb{Z}$, let $c=a\\bmod{b}$, i.e. $a=qb+c$ s.t. $0\\leq c 1$), then \n\\begin{equation}\n\\boxed{ \n\t\\begin{aligned}\n\t\\varphi(n) & = \\varphi(p_1^{\\alpha_1}) \\varphi(p_2^{\\alpha_2}) \\dots \\varphi(p_s^{\\alpha_s}) \\\\ \n\t& p_1^{\\alpha_1 - 1 } (p_1 - 1) p_2^{\\alpha_2 - 1} (p_2 - 1 ) \\dots p_s^{\\alpha_s -1} (p_s - 1) \n\t\\end{aligned} }\n\\end{equation}\n\n\ncf. pp. 69 Thm. 5.4 (Chinese Remainder) of Scheinerman (2006) \\cite{Sche2006}. \n\\begin{theorem}\n\tLet $n\\in \\mathbb{Z}^+$, \\\\\n\tlet $p_1,p_2, \\dots p_t$ be distinct prime divisors of $n$ (i.e. $\\forall \\, p_i$, $\\frac{n}{p_i^{k_i}} \\in \\mathbb{Z}$ for some $k_i \\geq 1$) \\\\\n\tThen\n\t\\begin{equation}\n\t\\varphi(n) = n\\left( 1 - \\frac{1}{p_1} \\right)\\left( 1- \\frac{1}{p_2} \\right) \\ldots \\left( 1 - \\frac{1}{p_t} \\right) \t\n\t\\end{equation}\n\\end{theorem}\n\n\\begin{proof}\n\tBy Fundamental Thm. of Arithmetic, \n\t\\[\n\tn = p_1^{e_1} p_2^{e_2} \\dots p_t^{e_t} \n\t\\]\n\twhere $p_j$ are distinct primes, and $e_j$ are positive integers. \n\t\n\tFrom Eqns. \\ref{Eq:EulerTotientOfPrimeFactor}, \\ref{Eq:EulerTotientIsMultiplicative}, i.e. where \n\t\\[\n\t\\begin{gathered}\n\t\\varphi(p^a) = p^a - p^{a-1} = p^{a-1} (p-1) \\\\\n\t\\varphi(ab) = \\varphi(a) \\varphi(b) \\text{ if } \\gcd(a,b) = 1\n\t\t\\end{gathered}\n\t\t\\]\n\t\t\\[\n\t\t\\begin{gathered}\n\t\\varphi(n) = \\varphi(p_1^{e_1}p_2^{e_2} \\dots p_t^{e_t}) = \\varphi(p_1^{e_1}) \\varphi(p_2^{e_2}) \\dots \\varphi(p_t^{e_t}) = \\\\\n\t= p_1^{e_1} (1- \\frac{1}{p_1} )p_2^{e_2} (1- \\frac{1}{p_2} ) \\dots p_t^{e_t} (1- \\frac{1}{p_t} ) = n(1- \\frac{1}{p_1}) (1- \\frac{1}{p_2}) \\dots (1- \\frac{1}{p_t})\n\t\t\\end{gathered}\n\t\t\\]\n\t\\end{proof}\n\n\n\\exercisehead{10}\ncf. pp. 7 Exercise 10 Dummit and Foote \\cite{DuFo2003}. \n\nProve: $\\forall \\, $ given $N \\in \\mathbb{Z}^+$ (positive number), \\\\\n$\\exists \\, $ only finite many integers $n$ with $\\varphi(n) = N$, where $\\varphi$ denotes Euler's $\\varphi$-function. \n\nEY, Indeed, by definition, \\\\\n\\[\n\\begin{gathered}\n\\varphi(n) = N \\\\\na_1, a_2 \\dots a_N \\text{ s.t. } a_i \\leq n \\\\\n\\gcd(a_i,n)=1 \\text{ i.e. } 1 = s_i a_i + t_i n \n\\end{gathered}\n\\]\n\n\nGiven $N \\in \\mathbb{Z}^+$, let $n \\in \\mathbb{Z}$, s.t. $\\varphi(n) = N$ (given hypothesis). \n\nLet $p= $ least (i.e. smallest) prime s.t. $p > N+1$. \n\nIf $q\\geq p$ is a prime divisor of $n$, i.e. \n\\[\nn = q^k m \n\\]\nfor some $k\\geq 1$, and $m$ with $q$ not dividing $m$. \n\nThen \n\\[\n\\varphi(n) = \\varphi(q^k) \\varphi(m) = q^{k-1}(q-1) \\varphi(m) \\geq q-1 \\geq p -1 > N\n\\]\nContradiction. \n\nThus, $\\nexists$ prime divisor of $n$ greater than $N+1$. \n\nParticularly, distinct prime divisors of $n$ belong to a finite set, say these primes are $p_1,p_2 \\dots p_m$. \n\n\\begin{definition}\n\tprime divisor $q$ of $n$ if $q$ is prime and \n\t\\begin{equation}\n\t \\frac{n}{q} \\in \\mathbb{Z} \\text{ i.e. } n =q^k m \\text{ for some } k \\geq 1 \\text{ and } \\frac{m}{q} \\notin \\mathbb{Z}^+\n\t\\end{equation}\n\\end{definition}\n\nNow\n\\[\nn=p_1^{a_1}p_2^{a_2} \\dots p_m^{a_m} \n\\]\nfor some $0 N$ for sufficiently large $a_i$. \n\nThus, $\\forall \\, p_i$, $\\exists \\, $ only finitely many permissible choices for exponents $a_i$. \\\\\nSo set of all $n$ with $\\varphi(n) = N$ is subset of finite set, hence finite. \n\n$\\forall \\, N \\in \\mathbb{Z}^+$, $\\exists \\, $ largest integer $n$ with $\\varphi(n) = N$. \\\\\nThus, as $n\\to \\infty$, $\\varphi(n) \\to \\infty$. \n\n\n\n\n%--------------------------------------------------------------------------------\n% END of 20180311 \n%-------------------------------------------------------------------------------\n\n\n\nScheinerman (2006) \\cite{Sche2006}\n\ncf. Ex. 1.19, pp. 13, Sec. 1.1 Some Number Theory of Rotman (2010) \\cite{JRotman2010}\n\\exercisehead{1.19}\nIf $a$ and $b$ are relatively prime and if each divides an integer $n$, then their product $ab$ also divides $n$, i.e. \n\\begin{theorem}\\label{Thm:relprimeproddivisible}\n\tIf $\\gcd{a,b}=1$, and if $n/a \\in \\mathbb{Z} \\equiv a | n$, and $n/b \\in \\mathbb{Z} \\equiv b | n$, then $n/ab \\in \\mathbb{Z} \\equiv ab | n$. \n\\end{theorem}\n\\begin{proof}\n\t$\\gcd{a,b}=1$, so $sa + tb= 1$ for some $s,t \\in \\mathbb{Z}$ (Thm. \\ref{Thm:relprimeinvertible}). \n\t\n\t$\\frac{n}{a}, \\frac{n}{b} \\in \\mathbb{Z}$, so $n=au$, $n=bv$ \n\t\n\t$n = n\\cdot 1 = n(sa+tb) = bvsa + autb = ab(vs + ut)$, so $\\frac{n}{ab} = vs + ut \\in \\mathbb{Z}$. \n\t\\end{proof}\n\n\\subsubsection{Chinese Remainder Theorem}\n\n\\begin{theorem}\n\tIf $m,m'$ relatively prime (i.e. $\\gcd(m,m')=1$), then for \n\\[\n\\begin{aligned}\n\t& x \\equiv b \\bmod{m} \\\\ \n\t& x\\equiv b'\\bmod{m'}\n\\end{aligned}\n\\]\ni.e. given $b,b'm,m'$, and wanting to find $x$, \n$\\exists \\, x$ and $\\forall \\, 2 x$'s, $x=x'\\mod{mm'}$, i.e. \\\\ \n\n Let $m,n$ relatively prime positive integers (i.e. $\\gcd{m,n}=1$), \\\\\n $\\forall \\, a,b\\in \\mathbb{Z}$, \\\\\n then pair of congruences \\\\\n $\\begin{aligned}\n & x \\equiv a\\bmod{m} \\\\\n & x \\equiv b\\bmod{n} \n \\end{aligned}$\n \n has a solution ($x$), and this solution $x$ is uniquely determined, modulo $mn$. \n\\end{theorem}\n\n\n\\begin{proof}\ncf. \\href{http://www.math.uconn.edu/~kconrad/blurbs/ugradnumthy/crt.pdf}{The Chinese Remainder Theorem by Keith Conrad}\n\n\nSuppose \\\\\n$\n\\begin{aligned}\n& (x-a) / m \\in \\mathbb{Z} \\text{ or } x - a = my \\\\ \n& (x-b)/n \\in \\mathbb{Z} \\text{ or } x-b= nz \\text{ or } a + my - b = nz \n\\end{aligned}\n$ \\\\\n$\\gcd{m,n} =1$, so then $\\forall \\, b \\in \\mathbb{Z}$, $\\exists \\, w$ s.t. $mw \\equiv b \\bmod{n}$ i.e. $\\frac{mw-b}{n} \\in \\mathbb{Z}$, in fact, $w=sb$, where $sm \\equiv 1\\bmod{n}$, or $\\frac{sm-1}{n} \\in \\mathbb{Z}$, is 1 solution (Thm. \\ref{Thm:relprimeinvertible}). \n\n\\[\n\\begin{aligned}\nmy & = b-a+nz \\\\\nsmy & = sb - sa + snz = (1+nv) y = s(b-a) + snz \\text{ or } y = s(b-a) + n(sz-vy) \\\\\n\\text{ or } y & \\equiv s(b-a) \\bmod{n} \n\\end{aligned}\\]\n\n\\[\n\\begin{aligned}\nx = a+my & = a+m(s(b-a) + n(sz-vy)) = a+ ms(b-a) + mn(sz-vy) \\equiv a+ms(b-a) + mnu \\\\ \nx-a & = m(s(b-a) + nu) \\Longrightarrow x = a\\bmod{m} \\\\\nx-b & = a+ms(b-a) + mnu -b = a+(1+m)(b-a) + mnu -b = m(b-a) + mnu \\Longrightarrow x \\equiv b\\bmod{n}\n\\end{aligned}\n\\]\n\n%\\textbf{Second way to prove existence of solution}: \n\\textbf{Uniqueness}: \nSuppose $x,y \\in \\mathbb{Z}$ s.t. \n\\[\n\\begin{aligned} \n& x \\equiv a \\bmod{m} \\\\\n& x \\equiv b \\bmod{n} \\end{aligned} \\qquad \\ \n\\begin{aligned} \n& y \\equiv a \\bmod{m} \\\\\n& y \\equiv b \\bmod{n} \\end{aligned}\n\\]\n\nGiven $\\gcd{m,n}=1$, $sm+tn=1$. \n\nSince $\\frac{x-a}{m}, \\frac{y-a}{m} \\in \\mathbb{Z}$, $\\frac{x-y}{m} \\in \\mathbb{Z}$, likewise, $\\frac{x-a}{n}, \\frac{y-a}{n} \\in \\mathbb{Z}$, $\\frac{x-y}{n} \\in \\mathbb{Z}$ \\\\\nSince $\\frac{x-y}{m}, \\frac{x-y}{n} \\in \\mathbb{Z}$, $\\frac{x-y}{mn} \\in \\mathbb{Z}$ by Thm. \\ref{Thm:relprimeproddivisible}. \n\nThus, $x-y = mn k$ for some $k\\in \\mathbb{Z}$. For instance, $k=0$, $x=y$. \n\nThis shows any 2 solutions are the same, modulo $mn$. \n\\end{proof}\n\n\ncf. Ch. 1 Things Past, Thm. 1.28 of Rotman (2010) \\cite{JRotman2010}, pp. 68 Thm. 5.2 (Chinese Remainder) of Scheinerman (2006) \\cite{Sche2006}. \n\n\n\n\n\\section{Groups}\ncf. pp. 16 Chapter 1 Introduction to Groups. Dummit and Foote (2004) \\cite{DuFo2003}\n\\begin{definition}[binary operation]\n\t\\begin{enumerate}\n\t\t\\item binary operation $*$ on set $G$ is a function $*: G \\times G \\to G$. $\\forall \\, a, b \\in G$, $a* b \\equiv *(a,b)$\n\t\t\\item binary operation $*$ on set $G$ is \\emph{associative}: if $\\forall \\, a, b, c \\in G$, $a*(b*c) = (a*b) * c$ \n\t\t\\item If $*$ is binary operation on set $G$, $a,b $ of $G$ commute if $a*b = b*a$. \\\\\n\t\t$*$ (or $G$) is \\textbf{commutative} if $\\forall \\, a, b \\in G$ $a* b = b*a$. \n\t\\end{enumerate}\n\\end{definition}\ncf. pp. 16. Sec. 1.1. Basic Axioms and Examples, Dummit and Foote (2004) \\cite{DuFo2003} \n\n\\begin{definition}[Group]\n\\begin{enumerate}\n\\item Group is an ordered pair $(G, *)$ where $G$ is a set, $*$ is a binary operation on $G$ s.t. \n\\begin{enumerate}\n\\item $(a*b)*c = a*(b*c)$, $\\forall \\, a,b ,c \\in G$, i.e. $*$ \\emph{associative}\n\\item $\\exists \\, e \\in G$, s.t. $\\forall \\, a\\in G$, $a*e = e*a = a$ ($\\exists \\, $ \\emph{identity} $e$)\n\\item $\\forall \\, a\\in G$, $\\exists \\, a^{-1}\\in G$, called an \\emph{inverse} of $a$, s.t. $a*a^{-1} = a^{-1} * a = e$\n\\end{enumerate}\n\\item (optional; abelian or \\emph{commutative}) $(G,*)$ abelian (or commutative) if $a*b = b*a$, $\\forall \\, a,b \\in G$. \n\\end{enumerate}\n\\end{definition}\ne.g.\n\\begin{enumerate}\n\\item $\\mathbb{Z}$, $\\mathbb{Q}$, $\\mathbb{R}$, $\\mathbb{C}$ are groups under $+$ with $e=0$ and $a^{-1} = -a$, $\\forall \\, a$. \n\\item $\\mathbb{Q} - \\lbrace 0 \\rbrace$, $\\mathbb{R} - \\lbrace 0 \\rbrace$, $\\mathbb{C} - \\lbrace 0 \\rbrace, \\mathbb{Q}^+, \\mathbb{R}^+$ groups under $\\times$ with $e=1$, $a^{-1} = \\frac{1}{a}$\n\\item (\\textbf{direct product of groups})If $(A,*), (B,\\circ)$ are groups, we can form new group $A\\times B$ called \\textbf{direct product} s.t.\n\\[\nA \\times B = \\lbrace (a,b) | a\\in A, b\\in B\\rbrace\n\\] and $(a_1,b_1)(a_2,b_2) = (a_1*a_2, b_1 \\circ b_2)$ cf. Example 6, Sec. 1.1 Dummit and Foote (2004) \\cite{DuFo2003}\n\\end{enumerate}\n\n\\begin{proposition}\nIf $G$ group under operation $*$, then \n\\begin{enumerate}\n\\item identity of $G$ is unique\n\\item $\\forall \\, a \\in G$, $a^{-1}$ uniquely determined.\n\\item $(a^{-1})^{-1} = a \\quad \\, \\forall \\, a \\in G$ \n\\item $(a*b)^{-1} = (b^{-1}) * (a^{-1})$ \n\\item $\\forall \\, a_1, a_2, \\dots a_n \\in G$, $a_1 , a_2 \\dots a_n $ independent of how expression is bracketed (generalized associative law)\n\\end{enumerate}\n\\end{proposition}\ncf. Prop. 1, Sec. 1.1 Dummit and Foote (2004)\\cite{DuFo2003}\n\n\\subsection{$\\mathbb{Z} / n \\mathbb{Z}$: The Integers Modulo $n$}\n\ncf. Dummit and Foote (2004) \\cite{DuFo2003}, Sec. 0.3, $\\mathbb{Z}/n\\mathbb{Z}$: The Integers Modulo $n$.\n\nRecall Sec. 0.2 Properties of the Integers, pp. 4, Dummit and Foote (2004) \\cite{DuFo2003}. $\\forall \\, a, b \\in \\mathbb{Z}$, $a | b$ if $\\exists \\, c \\in \\mathbb{Z}$ s.t. $b=ac$. \n\n\\begin{definition}[modulo equivalence relation]\nLet $n\\in \\mathbb{Z}^+$ (positive integer). Define\n\\begin{equation}\na \\sim b \\text{ iff } n | (b-a), \\text{ i.e. } \n\\end{equation}\n$\\exists \\, c \\in \\mathbb{Z}$ s.t. $b-a = nc$ or $a+nc = b$. Rewrite this as $a= b- nc \\equiv b + Nk$ or even $\\begin{aligned} & \\quad \\\\ & a = pn + r \\\\ & b = qn + r \\end{aligned}$. \n\\end{definition} \n\n\\begin{proposition}[modulo is an equivalence relation]\n\tmodulo $n$ is an equivalence relation\n\\end{proposition} \n\n\\begin{proof}\nClearly $a \\sim a$ (choose $k=0$ in $a= b + Nk$), $a\\sim b$ implies $b\\sim a$ (choose $k \\mapsto -k$) $\\forall \\, a, b \\in \\mathbb{Z}$, so $\\sim $ is reflexive and symmetric.\n\nIf $a\\sim b$, and $b\\sim c$, $a= b + Nk$, $b=c +Nl$, so $a= c + N(k+l)$, so $a\\sim c$, and $\\sim$ is transitive.\n\n$\\Longrightarrow \\sim$ is equivalence relation.\n\n\\end{proof} \n\n$a \\equiv b \\bmod{n}$ or $a \\equiv b \\bmod{n}$, i.e. $a$ is congruent to $b \\bmod{n}$ if $a\\sim b$. \n\n$\\forall \\, k \\in \\mathbb{Z}$ denote equivalence class of $a \\equiv \\overline{a}$, called \\emph{congruence class} or \\textbf{residue class} of $a\\bmod{n}$.\n\n\\begin{equation}\n\\overline{a} = \\lbrace a + kn | k \\in \\mathbb{Z} \\rbrace = \\lbrace a , a \\pm n, a \\pm 2n, a \\pm 3n ,\\dots \\rbrace \n\\end{equation}\n\nIf $\\overline{a} = pn +r$, $\\frac{ \\overline{a}}{n} = p + \\frac{r}{n}$ , $0\\leq r < n$, so remainder $r$ determines equivalence class $\\overline{a}$.\n\nThese residue classes partition $\\mathbb{Z}$. \n\\begin{definition}[$\\mathbb{Z} / n \\mathbb{Z}$]\n$\\mathbb{Z} / n\\mathbb{Z} \\equiv$ set of equivalence classes under this equivalence relation $\\equiv$ called integers modulo $n$ (or integers mod $n$)\n\\end{definition} \n\n\\begin{definition}[modular arithmetic]\n\t$\\forall \\, \\overline{a}, \\overline{b} \\in \\mathbb{Z} / n \\mathbb{Z}$, define sum and product by \n\t\\begin{equation}\n\t\\overline{a} + \\overline{b} = \\overline{a+b}, \\, \\overline{a} \\cdot \\overline{b} = \\overline{ab}\n\t\\end{equation}\n\ti.e. $\\forall \\, \\overline{a}, \\overline{b}$ in $\\mathbb{Z}/n\\mathbb{Z}$, take \\emph{any representive} integer $a$ in class $\\overline{a}$ and \\emph{any representative} integer $b$ in class $\\overline{b}$ and add (respectively, multiply), as usual in $\\mathbb{Z}$, and take equivalence class of result.\n\\end{definition}\n\n\\begin{theorem}[Theorem 3 of Dummit and Foote (2004) \\cite{DuFo2003}, Sec. 0.3]\n\t$\\overline{a} + \\overline{b} = \\overline{a+b}$, $\\overline{a} \\cdot \\overline{b} = \\overline{ab}$ on $\\mathbb{Z}/n\\mathbb{Z}$ well-defined, and don't depend on representation choice, i.e. $a_1, a_2 \\in \\mathbb{Z}$, $b_1, b_2 \\in \\mathbb{Z}$, with $\\overline{a}_1 = \\overline{b}_1$, $\\overline{a}_2 = \\overline{b}_2$, then $\\overline{a_1 + a_2} = \\overline{b_1 + b_2}$, and $\\overline{a_1 a_2} = \\overline{b_1 b_2}$\n\\end{theorem} \n\n\\begin{proof}\n\tSuppose $a_1 = b_1 \\bmod{n}$, so $a_1 = b_1 + sn$, likewise $a_2 = b_2 \\bmod{n}$ means $a_2 = b_2 + tn$, so \\\\\n\t$a_1 + a_2 = b_1 + b_2 + (s+t)n$, so $\\overline{a_1 + a_2} = \\overline{b_1 + b_2}$ from $a_1 + a_2 = (b_1 + b_2) \\bmod{n}$\n\nThis shows that sum of residue classes is independent of the representatives chosen.\n\nSimilarly, \n\\[\na_1 a_2 = (b_1 + sn) (b_2 + tn) = b_1 b_2 + (b_1 t + b_2 s + stn) n \\text{ so } a_1 a_2 = b_1b_2(\\bmod{n})\n\\]\n\n\\end{proof}\n\n\\subsubsection{Elementary number theory application: Last 2 digits of $2^{1000}$}\n\nWhat is the last 2 digits of $2^{1000}$?\n\nNow $2^{1000} / 100 =$ last 2 digits of $2^{1000}$. So $2^{1000} \\bmod{100} = $?\n\nObserve $2^{10} = 1024$ \\qquad \\, $2^{10} \\bmod{100} = 24$\n\n\\[\n\\begin{gathered}\n\\begin{aligned}\n& 2^{20} \\bmod{100} = (2^{10})^2 \\bmod{100} = (24)^2 \\bmod{100} = 576 \\bmod{100} = 76 \\bmod{100} \\\\\n& 2^{80} \\bmod{100} = 2^{160} \\bmod{100} = 2^{320} \\bmod{100} = 2^{640} \\bmod{100} = 76 \\bmod{100}\n\\end{aligned}\n\\end{gathered}\n\\]\nwhere $(2^{20})^4 \\bmod{100} = 76^4 \\bmod{100} = 76 \\bmod{100}$, \\\\\n$(76)^{2} \\bmod{100} = 76 \\bmod{100}$ \\\\\n\nSo $2^{1000} \\bmod{100} = 2^{640} 2^{320} 2^{40} \\bmod{100} = 76 \\cdot 76 \\cdot 76 \\bmod{100} = 76 \\bmod{100}$ where $(76)^3 \\bmod{100} = 76 \\bmod{100}$. \n\nNote that we used $\\overline{a_1a_2} = \\overline{a}_1 \\cdot \\overline{a}_2$ definition extensively.\n\n$2^{1000} \\bmod{100} = 76 \\bmod{100}$\n\nCollection of residue classes having multiplicative inverse in $\\mathbb{Z} / n\\mathbb{Z}$ is an important subset of $\\mathbb{Z} / n\\mathbb{Z}$, $\\equiv (\\mathbb{Z} / n\\mathbb{Z})^{\\times}$\n\n\\begin{definition}[cf. pp. 10, Dummit and Foote (2003)\\cite{DuFo2003}]\n\\begin{equation}\n(\\mathbb{Z} / n\\mathbb{Z})^{\\times} = \\lbrace \\overline{a} \\in \\mathbb{Z} / n \\mathbb{Z} | \\exists \\, \\overline{c} \\in \\mathbb{Z} / n \\mathbb{Z} \\text{ with } \\overline{a} \\cdot \\overline{c} = 1 \\rbrace \n\\end{equation}\n\\end{definition}\n\n\\begin{proposition}[Prop. 4, pp. 10, Dummit and Foote (2003) \\cite{DuFo2003}]\n\\[\n(\\mathbb{Z} / n\\mathbb{Z})^{\\times} = \\lbrace \\overline{a} \\in \\mathbb{Z} / n \\mathbb{Z} | (a,n) = 1 \\rbrace\n\\], representatives of residue classes $\\overline{a}$ are relatively prime to $n$.\n\n$(a,n) \\equiv \\gcd{(a,n)}$, greatest common divisor of $a$ and $n$. \n\\end{proposition}\n\n\\begin{proof}\n\tSince $(a,n) = 1$, $1= sa + tn$ so $as = 1 - tn$, so $as = 1 \\bmod{n} \\equiv \\overline{1}$, so $\\overline{s} = s\\bmod{n}$ is a multiplicative inverse of $\\overline{a}$.\n\t\n\t$\\Longrightarrow \\overline{a} \\in (\\mathbb{Z} / n\\mathbb{Z})^{\\times}$. If $\\overline{a} \\cdot \\overline{c} = \\overline{1}$, then $ac= 1 + kn$ or $ac+ k' n=1$\n\t\n\\end{proof}\n\n\\exercisehead{2} cf. Ex. 2, pp. 11, Dummit and Foote (2003) \\cite{DuFo2003}, Sec. 0.3. $\\mathbb{Z} / n \\mathbb{Z} \\ni \\overline{a}$ if $\\overline{a} = a + kn$. \\\\\nBy Division Algorithm, Thm. \\ref{Thm:DivisionAlgorithm}, $\\forall \\, a, N \\in \\mathbb{Z}$, $n\\neq 0$, $a=qn + r$, $0\\leq r < |n| = n$.\n\nComparing expressions $a= r + qn$ and $\\overline{a} = a + kn$, then equivalence classes of $\\mathbb{Z}/n\\mathbb{Z}$ can only be of $r$ s.t. $0\\leq r < |n|$.\n\n\\exercisehead{3} cf. Ex. 3, pp. 11, Dummit and Foote (2003) \\cite{DuFo2003}, Sec. 0.3. If $a= \\sum_{j=0}^{n-1} a_j b^j$, $b=10$, $a\\in \\mathbb{Z}^+$ (positive integer), then prove $a \\equiv a_n + a_{n-1} + \\dots + a_1 + a_0 (\\bmod{9})$. \n\n\\emph{Observe} that $10 \\equiv 1 (\\bmod{9})$. So, \\\\\n\nUse the fact that $b\\equiv 1 \\bmod{(b-1)}$.\n\\[\n\\begin{gathered}\n\ta_j b^j \\bmod{(b-1)} = a_j \\bmod{(b-1)} \\cdot b^j \\bmod{(b-1)} = a^j \\bmod{(b-1)} \\cdot (b \\bmod{(b-1)})^j = a_j \\bmod{(b-1)} 1^j \\bmod{(b-1)} = \\\\\n\ta^j \\bmod{(b-1)} \\\\\n\ta \\bmod{(b-1)} = \\sum_{j=0}^{n-1} a^jb^j \\bmod{(b-1)} = \\sum_{j=0}^{n-1} a^j \\bmod{(b-1)} = \\left( \\sum_{j=0}^{n-1} a_j \\right) \\bmod{(b-1)}\n\\end{gathered}\n\\]\n\nif $b=0$, this says that remainder after division by 9 is same as sum of the decimal digits mod 9 - particularly, an integer is divisible by 9 iff sum of digits is divisible by 9.\n\nIf $b=2$, this says $a$ odd (even) if sum of bits is odd (even).\n\n\\subsubsection{As an abelian group}\n\ncf. Dummit and Foote, pp. 17, Ch. 1, Sec. 1.1, Examples, Example 4.\n\n$\\mathbb{Z}/n\\mathbb{Z}$ is an abelian group under operation $+$ of addition of residue classes, as described in Ch. 0. In Ch. 3 of Dummit and Foote (2003) \\cite{DuFo2003}, prove binary operation $+$ is well-defined and associative.\n\n$(\\overline{a})^{-1} = \\overline{-a}$ \\, $\\forall \\, a \\in \\mathbb{Z}/ n \\mathbb{Z}$, identity of $\\angle \\mathbb{Z}/n\\mathbb{Z}, + \\rangle = \\overline{0}$.\n\n\\exercisehead{3} cf. Exercise 3 in pp. 21, Exercises, of Sec. 1.1, Dummit and Foote (2003) \\cite{DuFo2003}. \n\n\\[\n\\overline{a} + (\\overline{b} + \\overline{c}) = (\\overline{a} + \\overline{b}) + \\overline{c} \n\\]\nis associative, since,\n\\[\n\\begin{gathered}\n\\overline{a} + (\\overline{b} + \\overline{c}) = \\overline{a} + (\\overline{b+c}) = \\overline{a} + (\\overline{b + tn + c + un}) = \\overline{a} + \\overline{b+c} = \\overline{a+b+c} \\\\\n(\\overline{a} + \\overline{b}) + \\overline{c} = (\\overline{a+b}) + \\overline{c} = (\\overline{a + sn + b+ tn}) + \\overline{c} = \\overline{a+b} + \\overline{c} = \\overline{a+b+c}\n\\end{gathered}\n\\]\n\n\\subsection{Cyclic groups and cyclic subgroups}\n\ncf. Sec. 2.3, pp. 54, Dummit and Foote (2003), \\cite{DuFo2003}\n\n\\begin{definition}[Cyclic group]\\label{Def:CyclicGroup}\n\tgroup $H$ is \\textbf{cyclic} if $H$ can be generated by a single element, i.e. $\\exists \\, x \\in H$ s.t. $H= \\lbrace x^n | n\\in \\mathbb{Z} \\rbrace$ (\"multiplication\" operation notation) $\\equiv H = \\lbrace nx | n \\in \\mathbb{Z} \\rbrace$ (\"additive\" operation notation). \\\\\n\t\n\tIn both cases, write $H = \\langle x \\rangle$ and say $H$ \\emph{generated} by $x$ (i.e. $x$ is \\emph{generator} of $H$)\n\\end{definition}\n\tcyclic group may have more than 1 generator; e.g. $H = \\langle x \\rangle$ and $H = \\langle x^{-1} \\rangle$ because $(x^{-1})^n = x^{-n}$ and $-n \\in \\mathbb{Z}$. \n\t\n\\exercisehead{19} cf. Exercise 19, Sec. 1.1, pp. 22, Dummit and Foote (2003) \\cite{DuFo2003}.\n\nLet $x \\in G, a, b\\in \\mathbb{Z}^+$\n\nIn the following steps, I'll use induction a lot.\n\\begin{enumerate}\n\t\\item[(a)] $x^{a+b} = x^a x^b $ and $(x^a)^b = x^{ab}$, prove.\n\t\\[\n\t\\begin{gathered}\n\t\tx^ax^b = x^a \\cdot x \\cdot x^{b-1} = x^{a+1} x^{b-1} = \\dots = x^{a+b - 1} \\cdot x = x^{a+b} \\quad \\, (\\text{used associativity of group operation}) \\\\\n\t\t(x^a)^b = \\underbrace{x^a \\cdot x^a \\cdots x^a }_{b \\text{ times } } = x^{2a} \\cdot \\underbrace{x^a \\dots x^a}_{ b- 2 \\text{ times} } = x^{3a} \\cdot \\underbrace{x^a \\dots x^a }_{b-3 \\text{ times } } = \\dots = x^{(b-1) a} \\cdot x^a = x^{ (b-1) a + a} = x^{ba}\n\t\\end{gathered}\n\t\\]\n\t\\item[(b)] \n\t\\[\n\t\\begin{gathered}\n\t\tx^a \\cdot x^{-a} = x^a \\cdot (x^{-1})^a = x^{a-1} \\cdot 1 \\cdot (x^{-1})^{a-1} = \\dots = x\\cdot x^{-1} = 1 \\Longrightarrow (x^a)^{-1} = x^{-a}\n\t\\end{gathered}\n\t\\]\n\tThe steps previous depended upon defining $x^{-a} = (x^{-1})^a$\n\t\\item[(c)] if $b=0$, $x^{a+0} = x^a = x^a x^b \\Longrightarrow x^0 = 1$. $x^{ab} = x^0 = (x^a)^0 = 1$. \\\\\n\t\n\t$x^{a-b} = x^a \\cdot x^{-b}$ since $x^{-b} = (x^{-1})^b$. \\\\\n\t\n\t$(x^a)^{-b} = ((x^a)^{-1})^b = (x^{-a})^b = x^{-ab}$ \\\\\n\t\n\tSo $x^{a+b} = x^a x^b$, $(x^a)^{-1} = x^{-a}$ $\\, \\forall \\, a,b \\in \\mathbb{Z}$\n\\end{enumerate}\n\n\\begin{theorem}[Cyclic groups are abelian]\\label{Thm:CyclicGroupsAreAbelian}\n\tCyclic groups are abelian since $x^a x^b = x^{a+b} = x^{b+a} = x^b x^a$\n\\end{theorem}\n\n\\begin{proposition}[]\\label{Prop:OrderDividesExponentOfCyclicGroupGeneratorRelation}\ncf. Dummit and Foote (2003) \\cite{DuFo2003}, Prop. 3, pp. 55, Sec. 2.3\n\n\tLet arbitrary group $G$, $x\\in G$, let $m, n \\in \\mathbb{Z}$. \\\\\n\n\tIf $x^n = 1$, $x^m = 1$, then $x^d =1$, where $d= (m,n) \\equiv \\gcd{(m,n)}$ \\\\\n\tIf $x^m = 1$, for some $m \\in \\mathbb{Z}$, then $|x|$ divides $m$ (recall $|x| \\equiv $ order of $x :=$ smallest positive integer $n$ s.t. $x^n = 1$, Def. on pp. 20, Sec. 1.1 of Dummit and Foote (2003) \\cite{DuFo2003}).\n\\end{proposition}\n\n\\begin{proof}\n\tBy Euclidean Algorithm (Sec. 0.2, (6) of Dummit and Foote (2003) \\cite{DuFo2003}), $\\exists \\, r, s \\in \\mathbb{Z}$ s.t. since $d= \\gcd{(m,n)}$, $d|m$ and $d|n$, i.e. $m/d, n/d \\in \\mathbb{Z}$, i.e. $m = pd + r$, $n=qd + s$, with $r=s=0$. \\\\\n\t\n\tConsider $mr+ns = pdr + qds = (pr+qs)d$. Choose $r,s$ s.t. $pr + qs = 1$ (TODO: need to prove Euclidean Algorithm) \\\\\n\n\t$x^d = x^{mr + ns} = (x^m)^r (x^n)^s = 1^r 1^s = 1$. \\\\\n\t\n\tIf $x^m = 1$, let $n=|x|$. If $m=0$, $n |m$, i.e. $m/n = 0/n$, so assume $m \\neq 0$. \\\\\n\t\n\tSince some nonzero power of $x,m$, is identity $n < \\infty$. \\\\\n\t\n\tLet $d= (m,n) = \\gcd{(m,n)}$, so $x^d = 1$ by preceding result for Prop. \\ref{Prop:OrderDividesExponentOfCyclicGroupGeneratorRelation}. \\\\\n\t\n\tSince $0 < d \\leq n$, and $n$ is smallest positive power of $x$ s.t. $x^n= 1$ (def. of order of a group), $d=n$, so $n | m \\equiv m/n = m / |x|$. \n\\end{proof} \n\n\\begin{theorem}[Dummit and Foote, Thm. 4 (2003) \\cite{DuFo2003}]\\label{Thm:CyclicGroupSameOrderIsomorphism}\n\tAny 2 cyclic groups of the same order are isomorphic; more specifically, \n\t\\begin{enumerate}\n\t\t\\item[(1)] if $n\\in \\mathbb{Z}^+$, $\\langle x \\rangle, \\langle y \\rangle$ are cyclic groups of order $n$, then\n\t\t\\begin{equation}\n\t\t\t\\begin{aligned}\n\t\t\t\t\\varphi : & \\langle x \\rangle \\to \\langle y \\rangle \\\\\n\t\t\t\t& x^k \\mapsto y^k \n\t\t\t\\end{aligned}\n\t\t\\end{equation}\n\t\tis well-defined and an isomorphism.\n\t\t\\item[(2)] If $\\langle x \\rangle$ is infinite cyclic group, map $\\varphi$ \n\t\t\\begin{equation}\n\t\t\t\\begin{aligned}\n\t\t\t\t\\varphi & : \\mathbb{Z} \\to \\langle x \\rangle \\\\\n\t\t\t\t& k \\mapsto x^k\n\t\t\t\\end{aligned}\n\t\t\\end{equation}\n\t\tis well-defined and is an isomorphism.\n\t\\end{enumerate}\n\\end{theorem} \n\n\\begin{proof}\n\tSuppose $\\langle x \\rangle, \\langle y \\rangle$ are cyclic groups of order $n$. Let $\\varphi: \\langle x \\rangle \\to \\langle y \\rangle$ s.t. $\\varphi(x^k) = y^k$. \\\\\n\t\n\t$\\varphi$ \\textbf{well-defined}? \\emph{Prove}: \\\\\n\tif $x^r = x^s$, then $\\varphi(x^r) = \\varphi(x^s)$. \\\\\n\t\n\tSince $x^{r-s} = 1$, by Prop. \\ref{Prop:OrderDividesExponentOfCyclicGroupGeneratorRelation}, $|x| | r-s$, i.e. $r-s / |x|$, so $r-s = |x|$ or $r = tn + s$, so \n\t\\[\n\t\\varphi(x^r) = \\varphi(x^{tn + s}) = y^{tn + s} = (y^n)^t y^s = 1^t y^s = y^s = \\varphi(x^s)\n\t\\]\n\t\n\t$\\varphi$ well-defined. \\\\\n\n$\\varphi(x^a x^b) = \\varphi(x^{a+b}) = y^{a+b} = y^a y^b = \\varphi(x^a) \\varphi(x^b)$, so $\\varphi$ homomorphism. \\\\\n\nSince $y^k = \\varphi(x^k)$, $\\varphi$ surjective. \\\\\n\nSince both groups have same finite order, any surjection from 1 to the other is bijection, so $\\varphi$ isomorphism. \\\\\n\nAlternatively, $\\begin{aligned}\n& \\varphi^{-1}:\\langle y \\rangle \\to \\langle x \\rangle\n& \\varphi^{-1}(y^k) = x^k \n\\end{aligned}$ \\quad \\, and \\quad \\, $\\begin{aligned} & \\varphi \\circ \\varphi^{-1}(y^k) = y^k \\\\\n& \\varphi^{-1}\\circ \\varphi(x^k) = x^k \\end{aligned}$.\n\nIf $\\langle x \\rangle$ infinite cyclic group, let $\\varphi : \\mathbb{Z} \\to \\langle x \\rangle$ defined by $\\varphi(k) = x^k$. $\\varphi$ well-defined since if $k = l$ for $x,y \\in \\mathbb{Z}$, \n\\[\nx^k = x^l = \\varphi(k) = \\varphi(l)\n\\]\n\nBy Prop. 2 of Dummit and Foote (2003) \\cite{DuFo2003}, pp. 55, Sec. 2.3, (if $H=\\langle x \\rangle$, $|H| = |x|$), if $x^a \\neq x^b$, $\\forall\\, a, b \\in \\mathbb{Z}$, $a\\neq b$, $\\varphi$ injective. $\\forall \\, x^k \\in \\langle x \\rangle$, $k \\in \\mathbb{Z}$, so $\\varphi(k) = x^k$ is surjective. \\\\\nLaw of exponents ensure $\\varphi$ homomorphism, (as above), hence $\\varphi$ isomorphism. \n\n\\end{proof}\n\n\\begin{theorem}[Cyclic Group and Integer Modulo $N$ are isomorphic]\\label{Thm:CyclicGroupIntegerModuloNIsomorphic}\n\tUp to isomorphism, $Z_n$ is the unique cyclic group of order $n$ and $Z_n \\simeq \\mathbb{Z}/ n\\mathbb{Z}$\n\\end{theorem}\n\n\\subsection{Binary Representation, fixed-width integers as Abelian group}\n\nFor $x\\in \\mathbb{Z}$, $B2U(x) = \\sum_{i=0}^{w-1} x_i \\cdot 2^i \\equiv \\sum_{i=0}^{w-1} x_i b^i$, where $b=2$, $w= $ total number of bits to represent $x$. \\\\\n\nConsider $n=2^w$. \\\\\n\nObserve that if $\\sum_{i=0}^{w-1} 1 \\cdot 2^i = S$, $2S = \\sum_{i=1}^{w-1} 2^i + 2^w = S - 1 + 2^w$. So $S = 2^w-1$, and so consider integers modulo $n=2^w$. \n\n\\[\n\\mathbb{Z} / 2^w \\mathbb{Z} = \\lbrace \\overline{a} = \\lbrace a + kn | k \\in \\mathbb{Z} \\rbrace \\rbrace = \\lbrace \\overline{a} = \\lbrace a + k 2^w | k \\in \\mathbb{Z} \\rbrace \\rbrace\n\\]\nand was shown that $0\\leq a < 2^w$.\n\nObserve that if $x= 2^w + \\sum_{i=0}^{w-1} x_i \\cdot 2^i$, \\\\\n\nsince $x \\leq 2^w - 1$, \\, $\\forall \\, x,y \\in \\mathbb{Z} / 2^w \\mathbb{Z}$, $x+y\\leq 2 \\cdot 2^w - 2 = 2^{w+1} - 2 = \\sum_{i=0}^w 2^i + 1 - 2 = \\sum_{i=0}^w 2^i - 1 \\sim \\left( \\sum_{i=0}^{w-1} 2^i - \\right) \\bmod{2^w}$ \\\\\n\n\nConsider $2^w - 1 = \\sum_{i=0}^{w-1} 1 \\cdot 2^i$. Then $2^w = \\sum_{i=0}^{w-1} 1 \\cdot 2^i + 1 = \\sum_{i=0}^w x_i \\cdot 2^i$ where $x_i = 0$ unless $i=w$, so $x_w = 1$. Define one's complement addition s.t. $2^w \\bmod{2^w} = 0 \\bmod 2^w$ \\\\\n\nThen $B2U(x) \\bmod{2^w}$ is a cyclic group s.t. $(\\overline{1})^{2^w} \\equiv \\sum_{i=1}^{2^w} 1 = \\sum_{i=0}^{2^w -1} 1 = 2^w \\bmod{2^w} = 0 \\bmod{w^2}$, $\\forall \\, w \\in \\mathbb{Z}^+$.\n\n\\section{Groups; normal subgroups} \n\n\\begin{definition}[normal subgroup $K \\lhd G$] \\qquad \\, \\\\\n\\textbf{normal subgroup} $K$ of $G \\equiv K \\lhd G$ - \n\nsubgroup $K\\subset G$, if $\\forall \\, k \\in K$, $\\forall \\, g \\in G$, \n\\[\ngkg^{-1} \\in K\n\\]\n\\end{definition}\n\n\\begin{definition}[quotient group] \\qquad \\, \\\\\n\\textbf{quotient group} $G\\mod{K} \\equiv G/K$ - \n\nif $G/K = $ family of all left cosets of subgroups $K\\subset G = $\n\\[ \n= \\lbrace gK | g\\in G, gK = \\lbrace gk | k \\in K \\rbrace \n\\]\nand \n\n$K = $ normal subgroup of $G$, i.e. $K \\lhd G$, and so \n\\[\naK bK = abK \\qquad \\, \\forall \\, a,b \\in G, \n\\]\nso $G/K $ group. \n\\end{definition}\n\n\n\n\n\n% 20170925 \n\n\\begin{definition}[exact sequence of groups]\n\t\\textbf{exact sequence} if $\\text{im}f_{n+1} = \\text{ker}f_n$ \\qquad \\, $\\forall \\, n $ for sequence of group homomorphisms and groups \n\\begin{equation}\n\\begin{tikzpicture}\n%\\matrix(m)[matrix of math nodes, row sep=3em, column sep=3em, text height=1.5ex, text depth=0.25ex]\n\\matrix(m)[matrix of math nodes, row sep=4em, column sep=4em]\n{\n\tG_{n+1} & G_n & G_{n-1} \\\\\n};\n%\\path[->,font=\\scriptsize]\n\\path[->]\n(m-1-1) edge node[auto]{$f_{n+1}$} (m-1-2)\n(m-1-2) edge node[auto]{$f_n$} (m-1-3);\n\\end{tikzpicture} \n\\end{equation}\n\\end{definition}\n\n\t\n\\begin{theorem}\n\t\\begin{enumerate}\n\t\t\\item \\[\n\t\t\\begin{tikzpicture}\n\t\t%\\matrix(m)[matrix of math nodes, row sep=3em, column sep=3em, text height=1.5ex, text depth=0.25ex]\n\t\t\\matrix(m)[matrix of math nodes, row sep=4em, column sep=4em]\n\t\t{\n\t\t\t1 & A & B \\\\\n\t\t\t%\\path[->,font=\\scriptsize]\n\t\t};\n\t\t\\path[->]\n\t\t(m-1-2) edge node[auto]{$f$} (m-1-3);\n\t\t\\end{tikzpicture} \n\t\t\\]\n\t\t\\item \\[\n\t\t\\begin{tikzpicture}\n\t\t%\\matrix(m)[matrix of math nodes, row sep=3em, column sep=3em, text height=1.5ex, text depth=0.25ex]\n\t\t\\matrix(m)[matrix of math nodes, row sep=4em, column sep=4em]\n\t\t{\n\t\t\tB & C & 1 \\\\\n\t\t};\n\t\t%\\path[->,font=\\scriptsize]\n\t\t\\path[->]\n\t\t(m-1-1) edge node[auto]{$g$} (m-1-2);\n\t\t\\end{tikzpicture} \n\t\t\\]\n\t\t\\item \\[\n\t\t\\begin{tikzpicture}\n\t\t%\\matrix(m)[matrix of math nodes, row sep=3em, column sep=3em, text height=1.5ex, text depth=0.25ex]\n\t\t\\matrix(m)[matrix of math nodes, row sep=4em, column sep=4em]\n\t\t{\n\t\t\t1 & A & B & 1 \\\\\n\t\t};\n\t\t%\\path[->,font=\\scriptsize]\n\t\t\\path[->]\n\t\t(m-1-2) edge node[auto]{$h$} (m-1-3);\n\t\t\\end{tikzpicture} \n\t\t\\]\n\t\t\n\t\\end{enumerate}\n\\end{theorem}\n\n\\begin{proof}\n\t\\begin{enumerate}\n\t\t\\item $\\text{im}(1\\to A)=1$, since $1\\to A$ is a group homomorphism $((1\\to A)(1) = 1_A)$. \\\\\n\t\tif $1\\to A \\xmapsto[]{f} B$ exact, $\\text{ker}f = \\text{im}(1\\to A)=1$, so if $f(x)=1$, $x=1$, $f$ injective. \\\\\n\t\tIf $f$ injective, $\\text{ker}f=1$. $1=\\text{im}(1\\to A)$. $1\\to A \\xmapsto{f}B$, exact. \n\t\t\\item $\\text{ker}(C\\to 1) = C$, by def. of $C\\to 1$ \\\\\n\t\tif $B \\xmapsto{g} C \\to 1$ exact, $\\text{im}g = g(B) = \\text{ker}(C\\to 1)= C$. $g(B) = C$ implies $g$ surjective. \\\\\n\t\tIf $g$ surjective, $g(B) = C =\\text{ker}(C\\to 1)$. $B\\xmapsto{g} C \\to 1$ exact. \n\t\t\\item From (i), $1\\to A \\xmapsto{h}B$ exact iff $h$ injective. \n\t\tFrom (ii), $A\\xmapsto{h}B \\to 1$, exact iff $h$ surjective. \\\\\n\t\t$h$ isomorphism. \n\t\\end{enumerate}\n\\end{proof}\n\n\n\n\n\n\n\n\n% 20170925 END\n\n\n\n\n\n\\subsection{1st, 2nd, 3rd Isomorphism Theorems}\n\n\\begin{theorem}[1st Isomorphism Theorem (Modules) Thm. 7.8 of Rotman (2010) \\cite{JRotman2010}]\nIf $f:M\\to N$ is $R$-map of modules, then $\\exists \\, R$-isomorphism s.t. \n\\begin{equation}\n\t\\begin{aligned}\n\t& \\varphi : M /\\text{ker}f \\to \\text{im}f \\\\ \n\t& \\varphi: m + \\text{ker}f \\mapsto f(m)\n\\end{aligned} \\qquad \\qquad \\, \\begin{tikzpicture}\n%\\matrix(m)[matrix of math nodes, row sep=3em, column sep=3em, text height=1.5ex, text depth=0.25ex]\n\\matrix(m)[matrix of math nodes, row sep=4em, column sep=4em]\n{\nM & N \\\\\nM/\\text{ker}f & \\\\};\n%\\path[->,font=\\scriptsize]\n\\path[->]\n(m-1-1) edge node[auto]{$f$} (m-1-2)\nedge node[auto]{$\\pi$} (m-2-1) \n(m-2-1) edge node[right]{$\\varphi = \\cong$} (m-1-2);\n\\end{tikzpicture} \n\\end{equation}\n%Essentially, \n%\\begin{equation}\n\n%\\end{equation}\n\\end{theorem}\n\n\\begin{proof}\n\tView $M,N$ as abelian groups. \n\nRecall natural map $ \\begin{aligned} & \\quad \\\\ \n\t& \\pi : M \\to M/N \\\\\n& m\\mapsto m + N \\end{aligned}$ \n\nDefine $\\varphi$ s.t. $\\varphi \\pi = f$. \n\n($\\varphi$ well-defined). Let $m+\\text{ker}f = m' + \\text{ker}f$, $m,m' \\in M$, then $\\exists \\, n \\in \\text{ker}f$ s.t. $m=m'+n$. \n\\[\n\\varphi(m+\\text{ker}f) = \\varphi\\pi (m) = f(m) = f(m' +n ) = f(m') + f(n) = \\varphi \\pi(m') + 0 = \\varphi(m' + \\text{ker}f )\n\\]\n$\\Longrightarrow \\varphi $ well-defined. \n\n($\\varphi$ surjective). Clearly, $\\text{im}\\varphi \\subseteq \\text{im} f$. \\\\\nLet $y\\in \\text{im}f$. So $\\exists \\, m \\in M$ s.t. $y=f(m)$. $f(m) = \\varphi \\pi (m) = \\varphi(m+\\text{ker}f) = y$. So $y\\in \\text{im}\\varphi$. $\\text{im}f\\subseteq \\text{im}\\varphi$. \\\\\n$\\Longrightarrow \\varphi $ surjective. \n\n($\\varphi$ injective) If $\\varphi(a+\\text{ker}f) = \\varphi(b+\\text{ker}f)$, then \n\\[\n\\begin{gathered}\n\\varphi\\pi(a) = \\varphi\\pi(b) \\text{ or } f(a) = f(b) \\text{ or } 0 = f(a) -f(b) = f(a-b) \\text{ so } a-b \\in \\text{ker}f\n\t(a-b) + \\text{ker}f = \\text{ker}f \\text{ so } a + \\text{ker}f = b +\\text{ker}f \n\\end{gathered}\n\\]\n$\\varphi$ isomorphism. \n\n$\\varphi$ $R$-map. $\\varphi(r(m+N)) = \\varphi(rm+N) = f(rm)$. \\\\\nSince $f$ $R$-map, $f(rm) = rf(m) = r\\varphi(m+N)$. $\\varphi$ is $R$-map indeed. \n\n\n\\end{proof}\n\n\n\\begin{theorem}[2nd Isomorphism Theorem (Modules) Thm. 7.9 of Rotman (2011) \\cite{JRotman2010}]\nIf $S,T$ are submodules of module $M$, i.e. $S,T \\in M$, then $\\exists \\, $ $R-$isomorphism \n\\begin{equation}\n\\begin{gathered}\n\tS/(S\\cap T) \\to (S+T)/T\n\\end{gathered} \\qquad \\, \n\\qquad \\qquad \\, \\begin{tikzpicture}\n\\matrix(m)[matrix of math nodes, row sep=4em, column sep=4em]\n{\nS & (S+T)/T = \\text{im}h \\\\\nS/(S\\cap T) = S/\\text{ker}h & \\\\};\n\\path[->]\n(m-1-1) edge node[auto]{$h$} (m-1-2)\nedge node[auto]{$\\left. \\pi \\right|_S$} (m-2-1) \n(m-2-1) edge node[right]{$ \\cong$} (m-1-2);\n\\end{tikzpicture} \n\\end{equation}\n\\end{theorem}\n\n\\begin{proof}\nLet natural map $\\pi : M \\to M/T$. \\\\\n\\phantom{Let} So $\\text{ker}\\pi = T$. \n\nDefine $h:= \\left. \\pi \\right|_S$, so $h: S\\to M/T$, so $\\text{ker}h = S\\cap T$, \n\\[\n(S+T)/T = \\lbrace (s+t) + T | a\\in S+T, s\\in S, t\\in T \\rbrace\n\\]\ni.e. $(S+T)/T$ consists of all those cosets in $M/T$ having a representation in $S$. \n\nBy 1st. isomorphism theorem, \n\\[\nS/S\\cap T \\xrightarrow{ \\cong} (S+T)/T\n\\]\n\n\\end{proof} % END of pf. of 2nd Isomorphism Theorem (Modules) Thm. 7.9 of Rotman (2011)\n\n\\begin{theorem}[3rd Isomorphism Theorem (Modules) Thm. 7.10 of Rotman (2011) \\cite{JRotman2010}]\nIf $T\\subseteq S \\subseteq M$ is a tower of submodules, then $\\exists \\, $ $R$-isomorphism\n\\begin{equation}\n\\begin{gathered}\n\t(M/T)/(S/T) \\to M/S\n\\end{gathered} \\qquad \\, \\begin{tikzpicture}\n\\matrix(m)[matrix of math nodes, row sep=4em, column sep=4em]\n{\nM/T & M/S\\\\\n(M/T)/(S/ T) = (M/T)/\\text{ker}g & \\\\};\n\\path[->]\n(m-1-1) edge node[auto]{$g$} (m-1-2)\nedge node[auto]{$ \\pi $} (m-2-1) \n(m-2-1) edge node[right]{$ \\cong$} (m-1-2);\n\\end{tikzpicture} \n\\end{equation}\n\\end{theorem}\n\n\\begin{proof}\n\tDefine $g:M/T \\to M/S$ to be \\textbf{coset enlargement}, i.e. \n\\begin{equation}\n\tg:M +T \\mapsto m+S\n\\end{equation}\n$g$ well-defined: if $m+T = m'+T$, then $m-m' \\in T\\subseteq S$, and $m+S = m'+S \\Longrightarrow g(m+T) = g(m'+T)$\n\n$\\text{ker}g = S/T$ since \n\\[\n\\begin{aligned}\n\t& g(s+T) = s+S = S \\qquad \\, (S/T \\subseteq \\text{ker}g) \\\\\n\t& g(m+T) = m + S = 0 = S = s + S, \\text{ so } m=s \\Longrightarrow \\text{ker}g \\subseteq S/T\n\\end{aligned}\n\\]\n$\\text{im}g = M/S $ since \n\\[\n\\begin{aligned}\n\t& g(m+T) = m+S \\Longrightarrow \\text{ im}g \\subseteq M/S \\\\ \n \t& m+S = g(m+T)\n\\end{aligned}\n\\]\nThen by 1st isomorphism, and commutative diagram, done. \n\\end{proof} % END of pf. of 3rd Isomorphism Theorem (Modules) Thm. 7.10 of Rotman (2011) \n\n\\section{Rings} \n\ncf. Ch. 7 \"Introduction to Rings\" pp. 223, Dummit and Foote (2014)\\cite{DuFo2003}\n\n\\begin{definition}[Ring]\nring $R$ is a set, together with 2 binary operations $+, \\times $ (addition and multiplication, $\\times \\equiv \\cdot $) s.t. \n\\begin{enumerate} \n\\item \\begin{enumerate}\n\t\\item $(R, +)$ abelian group \n\t\\item $\\times $ associative: $a(bc) = (ab)c \\quad \\, \\forall \\, a, b, c \\in R$ \n\t\\item distributivity in $R$: $\\forall \\, a , b, c \\in R$ \n\t\\[\n\t(a+b)c = ac + bc \\text{ and } a(b+c) = ab + ac\n\t\\]\n\\end{enumerate}\t\n\\item $R$ \\emph{commutative} if multiplication commutative\n\\item $R$ has an identity $1$ if $\\exists \\, 1 \\in R$ s.t.\n\\[\n1a = a1 = a \\quad \\, \\forall \\, a \\in R\n\\]\n\\end{enumerate}\n\\end{definition}\n\n\\begin{definition}[division ring]\n\tring $R$ with identity $1$, where $1\\neq 0$ is a \\textbf{division ring} (or skew field) if $\\forall \\, a \\in R$, $a\\neq 0$, $\\exists \\, $ multiplicative inverse $1/a$, i.e. $\\exists \\, b\\in R$ s.t. $ab=ba = 1$\n\\end{definition}\n\ne.g. \n\\begin{enumerate}\n\t\\item rational numbers $\\mathbb{Q}$ \\\\\n\treal numbers $\\mathbb{R}$ \\\\\n\tcomplex numbers $\\mathbb{C}$ \\\\ \n\tare commutative rings with identity (in fact, they're fields) \\\\\n\tRing axioms for each follow ultimately from ring axioms for $\\mathbb{Z}$ \\\\\n\t(verified when $\\mathbb{Z}$ constructed from $\\mathbb{Z}$ (Sec. 7.5)), $\\mathbb{C}$ from $\\mathbb{R}$ (Example 1, Sec. 13.1). \\\\\n\tConstruction of $\\mathbb{R}$ from $\\mathbb{Z}$ carried out in basic analysis texts\n\t\\item \\textbf{quotient group} $\\mathbb{Z}/n\\mathbb{Z}$ is a commutative ring with identity (element 1) under operations of addition and multiplication of residue classes (frequently referred to as \"modular arithmetic\"). \\\\\n\tWe saw additive abelian groups axioms followed from general principles of theory of quotient groups ($\\mathbb{Z}/n\\mathbb{Z}$) was prototypical quotient group. cf. Example 4, pp. 224, Dummit and Foote (2014)\\cite{DuFo2003}\n\t\\item \\textbf{the (real) Hamiltonian Quaternions}. \n\t\\begin{definition}[(real) Hamiltonian Quaternions]\n\t\tLet $\\mathbb{H} = \\lbrace a+ bi + cj + dk | a,b,c,d \\in \\mathbb{R} \\rbrace$ s.t. \n\t\t\"componentwise\" addition is defined as \n\t\t\\begin{equation}\n\t\t(a+bi + cj+dk) + (a' + b'i + c'j + d'k) = (a+a') + (b+b')i + (c+c')j + (d+d')k\n\t\t\\end{equation} and multiplication defined by expanding using distributive laws \n\t\t\\[\n\t\t(a+bi + cj +dk)(a' + b'i + c'j +d' k)\n\t\t\\]\n\t\tusing \n\t\t\\begin{equation}\n\t\t\\begin{aligned}\n\t\t& i^2 = j^2 =k^2 = -1 \\\\\n\t\t& ij = -ji = k \\\\\n\t\t& jk = -kj = i \\\\\n\t\t& ki = -ik = j\n\t\t\\end{aligned}\n\t\t\\end{equation}\n\t\\end{definition}\nWorking out the multiplication\n\\[\n\\begin{gathered}\n(a+bi + cj + dk)(a'+b'i + c'j + d'k) = \\\\\n= \\begin{aligned}\n& aa' + ab' i + ac'j + ad'k + ba' i - bb' + bc' k -bd' j + \\\\\n& ca'j - cb' k - cc' + cd' i + da' k + db' j - dc' i -dd' = \\\\\n\\end{aligned} \\\\\n= aa' - bb' -cc' -dd' + (ab' + ba' + cd' -dc')i + (ac' - bd' + ca' +db')j + (ad' + bc' - cb' + da')k \n\\end{gathered}\n\\]\nHamiltonian Quaternions are noncommutative ring with identity ($1= 1 + 0i + 0j + 0k$). \n\nSimilarly define \\emph{rational} Hamiltonian Quaternions ring by taking $a,b,c,d\\in \\mathbb{Q}$. \n\nreal and rational Hamiltonian Quaternions both are divison rings, where inverse of nonzero element defined as \n\n\n\\begin{equation}\n(a+bi +cj + dk)^{-1} = \\frac{ a-bi -cj -dk}{ a^2 + b^2 + c^2 + d^2 }\n\\end{equation} cf. Example 5, pp. 224, Dummit and Foote (2014)\\cite{DuFo2003}\n\n\\item \\textbf{rings of functions} (important class) \\\\\nLet $X$ be any nonempty set. \\\\\nLet $A$ be any ring. \n\n\\begin{definition}[function ring]\n\tcollection $R= \\lbrace f:X\\to A \\rbrace$ is a ring under pointwise addition and multiplication of functions s.t. \n\t\\begin{equation}\n\t\\begin{aligned}\n\t(f+g)(x) & = f(x) + g(x) \\\\\n\t(fg)(x) & = f(x)g(x)\n\t\\end{aligned}\n\t\\end{equation}\n\\end{definition}\n\t\ncf. Example 6, pp. 225, Dummit and Foote (2014)\\cite{DuFo2003}\n\n\\item cf. Example 7 of p. 225, Dummit and Foote (2014)\\cite{DuFo2003} \\emph{ring which doesn't have an identity}:\n\n\\begin{itemize}\n\t\\item ring $2\\mathbb{Z}$ of even integers (sum and product of even integers is an even integer) \\\\\n\\item function $f: \\mathbb{R} \\to \\mathbb{R}$ has compact support if $\\exists \\, a, b \\in \\mathbb{R}$, (depending on $f$) s.t. $f(x) = 0$, \\quad \\, $\\forall \\, x \\notin [a,b]$ \\\\\n$\\lbrace f: \\mathbb{R}\\to \\mathbb{R} | f \\text{ has compact support } \\rbrace$ is a commutative ring without identity (since an identity couldn't have compact support), \n\nSimilarly, \\\\\n$\\lbrace \\text{ cont. } f : \\mathbb{R} \\to \\mathbb{R} | f \\text{ has compact support } \\rbrace$ is a commutative ring without identity. \n\\end{itemize}\t\n\\end{enumerate}\n\n\\begin{proposition}[Dummit and Foote (2014)\\cite{DuFo2003}, Prop. 1, pp. 226]\nLet $R$ be a ring. \\\\\nThen\n\\begin{enumerate}\n\t\\item $0a = a0 = 0$ \\, $\\forall \\, a \\in R$ \n\t\\item $(-a) 0 = a(-b) = -(ab) \\quad \\, \\forall \\, a,b \\in R$ (recall $-a$ is additive inverse of $a$)\n\t\\item $(-a)(-b) =ab$ \\quad \\, $\\forall \\, a, b \\in R$ \n\t\\item if $R$ has identity $1$, identity unique and $-a = (-1) a$\n\\end{enumerate}\n\\end{proposition}\n\n\\begin{proof}\nUse distributivity and additive existence inverse for abelian group $(R, +)$. \n\n\\begin{enumerate}\n\t\\item \\[\n\t\\begin{gathered}\n\t0a = (0 + 0) a = 0a + 0a \\to 0a = 0 \n\ta0 = a(0 + 0) = a0 + a0 \\text{ so } a0 = 0 \t\n\t\\end{gathered}\n\t\\]\n\t\\item \n\t\\[\n\t\\begin{gathered} \n\tab + (-a)b = (a + (-a)) b = 0b = 0 \\Longrightarrow (-a) b = -(ab) \\\\\n\tab + a(-b) = a(b + (-b)) = a0 = 0 \\Longrightarrow a(-b) = -(ab) \t\n\t\\end{gathered} \n\t\\]\n\t\\item \\[\n\t(-a)(b + (-b)) = (-a)b + (-a)(-b) = -(ab) + (-a)(-b) = 0 \\Longrightarrow (-a)(-b) =ab\n\t\\]\n\t\\item \\[\n\t(-1)a + a = (-1) a + 1a = (-1 + 1) a = 0a = 0 \\text{ so } -a = (-1) a\n\t\\]\n\tSuppose $\\exists \\, 1'$ s.t. $1' a = a1' = a$ and $1' \\neq 1$ \n\t\\[\n\t\\begin{gathered}\n\t-a + a = 0 = (-1) a + 1' a = (-1 + 1') a = 0 a \\Longrightarrow 0 = -1 + 1' \n\t\\end{gathered}\n\t\\]\n\tThen $1' = 1$. Contradiction. \n\\end{enumerate}\n\\end{proof}\n\n\\begin{definition}\nLet $R$ be a ring.\n\\begin{enumerate}\n\t\\item \\textbf{zero divisor} $a$, $a\\neq 0$, $a\\in R$ if $\\exists \\, b\\in R, \\, b\\neq 0$ so either $ab= 0$ or $ba=0$. \n\t\\item Assume $R$ has identity $1\\neq 0$. \\\\\n\t\\textbf{unit} in $R$, $u\\in R$ if $\\exists \\,$ some $v\\in R$ s.t. $uv = vu =1$. \\\\\n\t$R^x \\equiv $ set of units in $R$. \n\t\\[\n\t\\forall \\, u,v \\in R^x, \\, (uv) (v^{-1}u^{-1}) = u(1)u^{-1} = 1\n\t\\]\n\t$1 \\in R^x$ so, $1u = u1 = u$ \\\\\n\tif $u\\in R^x$, $u^{-1} \\in R^x$ since $uu^{-1} = u^{-1} u =1$ \n$R^x$ is a \\textbf{group of units}\n\\end{enumerate}\t\n\\end{definition} \n\nThus a \\emph{field} $= $ commutative ring $F$ with identity $1\\neq 0$ s.t. $\\forall \\, a\\in $ field, $a\\neq 0$ is a unit, i.e. $F^x = F - \\lbrace 0 \\rbrace$. \n\n\\begin{proposition}\n\tzero divisor can never be a unit. \n\\end{proposition}\n\n\\begin{proof}\n\tSuppose a unit in $R$, and $ab=0$ for some $b\\neq 0$, $b\\neq R$. \\\\\n\tThen $va=1$ s.t. some $v\\in R$ and \n\t\\[\n\tb =1b = vab = v(ab) = v(0) = 0\n\t\\]\n\tContradiction.\n\\end{proof} \t\n\n\\section{Commutative Rings}\n\ncf. Ch. 3 \"Commutative Rings I\" of Rotman (2010) \\cite{JRotman2010}\n\n\n\\begin{definition} commutative ring $R$ is a set with 2 binary operations, addition and multiplication, s.t.\n\t\\begin{enumerate}\n\t\t\\item[(i)] $R$ abelian group under addition \n\t\t\\item[(ii)] (commutativity) $ab=ba$ \\quad $\\forall \\, a,b \\in R$ (this isn't there for noncommutativity)\n\t\t\\item[(iii)] (associativity) $a(bc) = (ab)c$ \\quad \\, $\\forall \\, a,b,c\\in R$\n\t\t\\item[(iv)] $\\exists \\, 1 \\in R$ s.t. $1a = a$ \\, $\\forall \\, a \\in R$ \\quad \\, (many names used: one, unit, identity)\n\t\t\\item[(v)] (distributivity) $a(b+c) = ab+ac$ \\quad \\, $a,b,c \\in R$ (this splits up into 2 distributivity laws for noncommutativity)\n\t\\end{enumerate}\n\\end{definition}\n\nTo reiterate, abelian group under addition $R$ (is defined as)\n\\begin{enumerate}\n\t\\item associative $\\forall \\, x , y ,z \\in R$, $x + (y+z) = (x+y)+z$ \n\t\\item $\\exists \\, 0 \\in R$, $0+x = x + 0$, \\, $\\forall \\, x \\in R$ \n\t\\item $\\forall \\, x \\in R$, $\\exists \\, (-x) \\in R$ s.t. $x+(-x) = 0 = (-x) + x$\n\\end{enumerate}\nabelian, if commutativity: $x+y=y+x$. \n\n\\subsection{Linear Algebra; Linear Algebra with commutative rings as fields}\n\n\\subsubsection{Linear Algebra}\n\n\\begin{definition}[subspace]\n\tIf $V$ vector space over field $k$, \\\\\n\tthen \\textbf{subspace} of $V$ is subset $U$ of $V$ s.t. \n\t\\begin{enumerate}\n\t\t\\item $0\\in U$\n\t\t\\item $u,u' \\in U$ imply $u+u' \\in U$ \n\t\t\\item $u\\in U$, and $a\\in k$ imply $au \\in U$\n\t\\end{enumerate}\n\t\\textbf{proper subspace} of $V \\equiv U \\subsetneq V$ is subspace $U \\subseteq V$ with $U \\neq V$.\n\\end{definition}\n$U =V$, $U = \\lbrace 0 \\rbrace$ are always subspaces of a vector space $V$. \n\n\\textbf{Examples} (Example 3.70 Rotman (2010) \\cite{JRotman2010}) \n\\begin{enumerate}\n\t\\item[(ii)] If $V=(a_1, \\dots a_n)$, $v\\neq 0$, $v\\in \\mathbb{R}^n$, \\\\\n\tline through origin $l = \\lbrace av | a \\in \\mathbb{R} \\rbrace$ is a subspace of $\\mathbb{R}^n$. \\\\\n\tplane through origin $=\\lbrace av_1 + bv_2 | v_1 , v_2 \\text{ fixed pair of noncollinear vectors, } a,b \\in \\mathbb{R} \\rbrace$ are subspaces of $\\mathbb{R}^n$\n\t\\item[(iii)] If $m\\leq n$, $\\mathbb{R}^m$ regarded as set of all vectors in $\\mathbb{R}^n$ s.t. last $n-m$ coordinates are $0$, then $\\mathbb{R}^m$ subspace of $\\mathbb{R}^n$.\n\te.g. $\\mathbb{R}^2 = \\lbrace (x,y,0) \\in \\mathbb{R}^3 \\rbrace \\subsetneq \\mathbb{R}^3$\n\t\\item[(iv)] If $k$ field, \\textbf{homogeneous linear system over $k$ } of $m$ equations in $n$ unknowns is a set of equations\n\t\\[\n\t\\begin{aligned}\n\ta_{11} x_1 + \\dots + a_{1n} x_n = 0 & \\\\\n\ta_{21} x_1 + \\dots + a_{2n} x_n = 0 & \\\\\n\t\\vdots \\vdots & \\\\\n\t\ta_{m1} x_1 + \\dots + a_{mn} x_n = 0 & \n\t\\end{aligned}\n\t\\] \n\twhere $a_{ji} \\in k$.\n\t\n\t\\textbf{solution} of this system is vector $(c_1 \\dots c_n) \\in k^n$ s.t. $\\sum_i a_{ji} c_i =0$, $\\forall \\, j$. \\\\\n\tsolution $(c_1 \\dots c_n)$ \\textbf{nontrivial} if $\\exists$ some $c_i \\neq 0$. \\\\\n\t\\textbf{solution space} (or null space) of system $=$ set of all solutions. \\\\\n\tsolution space also a subspace of $k^n$\n\\end{enumerate}\n\ne.g. $k = \\mathbb{I}_p$, \n\\[\n\\begin{aligned}\n& 3x - 2y + z \\equiv 1 \\bmod{7} \\\\\n& x + y -2 z \\equiv 0 \\bmod{7} \\\\\n& -x + 2y + z \\equiv 4 \\bmod{7}\n\\end{aligned}\n\\]\n\\begin{definition}[list]\n\tlist $:=$ vector space $V$ is ordered set $v_1 \\dots v_n$ of vectors in $V$, i.e. \n\t$\\exists \\, $ some $n\\geq 1$, $\\exists \\, $ some function $\\varphi$ \n\t\\[\n\t\\varphi : \\lbrace 1,2\\dots n \\rbrace \\to V\n\t\\]\n\twith $\\varphi(i) = v_i \\quad \\, \\forall \\, i$\n\\end{definition}\n\nThus, $X = \\text{im}\\varphi$.\n\n$X$ ordered, $\\varphi$ need not be injective. \n\n\\begin{definition}[k-linear combination]\n\t$k$-linear combination of list $v_1\\dots v_n$ in $V$, $V\\equiv $ vector space over field $k$, is vector $v$ of form \n\t\\[\n\tv = a_1 v_1 + \\dots + a_n v_n = \\sum_{i=1} a_i v_i \\quad \\, \\forall \\, a_i \\in k, \\, \\quad \\, \\forall \\, i\n\t\\]\n\\end{definition}\n\n\\begin{definition}[list]\n\tIf list $X = v_1 \\dots v_m$ in vector space $V$, then \\\\\n\t\\textbf{subspace spanned by } $X$, $\\langle v_1 \\dots v_m \\rangle := $ set of all $k$-linear combinations of $v_1 \\dots v_m$. Also, say $v_1 \\dots v_m $ spans $\\langle v_1 \\dots v_m\\rangle$. \n\\end{definition}\n\n\\begin{lemma}[$\\langle v_1 \\dots v_m \\rangle$ is smallest subspace of $V$ containing $v_1\\dots v_m$]\\label{Lemma:smallest_subspace}\n\\begin{enumerate}\n\t\\item[(i)] Every intersection of subspaces of $V$ is itself a subspace.\n\t\\item[(ii)] If $X= v_1 \\dots v_m$ list in $V$, then intersection of all subspaces of $V$ containing $X$ is $\\langle v_1 \\dots v_m \\rangle$, subspace spanned by $v_1\\dots v_m$, so $\\langle v_1 \\dots v_m \\rangle$ is smallest subspace of $V$ containing $X$. \n\\end{enumerate}\n\\end{lemma}\ncf. (Lemma 3.71 Rotman (2010) \\cite{JRotman2010}) \n\n\\begin{proof}\n\\begin{enumerate}\n\t\\item[(i)] Consider $\\bigcap_{\\alpha \\in I} V_{\\alpha}$, $\\forall \\, \\alpha \\in I$, $V_{\\alpha} $ subspace of $V$\n\t\\begin{enumerate}\n\t\t\\item[(i)] $0\\in V_{\\alpha}$, $\\forall \\, \\alpha \\in I$, so $0\\in \\bigcap_{\\alpha \\in I} V_{\\alpha}$,\n\t\t\\item[(ii)] Let $u,u' \\in \\bigcap_{\\alpha \\in I} V_{\\alpha}$. Then $u,u' \\in V_{\\alpha}$, $\\forall \\, \\alpha \\in I$. Consider $\\beta \\in I$. $u, u' \\in V_{\\beta}$, so $u+u' \\in V_{\\beta}$. Without loss of generality, $u + u' \\in V_{\\alpha}$, $\\forall \\, \\alpha \\in I$. Then $u+u' \\in \\bigcap_{\\alpha \\in I} V_{\\alpha}$\n\t\t\\item[(iii)] Let $u\\in \\bigcap_{\\alpha \\in I} V_{\\alpha}$. Consider $\\alpha \\in k$. Since $u\\in V_{\\alpha}$, $\\forall \\, \\alpha \\in I$, $au\\in V_{\\alpha}$, $\\forall \\, \\alpha \\in I$. \\\\\n\t\tThen $au \\in \\bigcap_{\\alpha \\in I} V_{\\alpha}$\n\t\\end{enumerate}\n\\item[(ii)] Let $X = \\lbrace v_1 \\dots v_m \\rbrace$, let $\\mathcal{S} \\equiv $ family of all subspaces of $V$ containing $X$. \n\n$\\bigcap_{S \\in \\mathcal{S}} S \\subseteq \\langle v_1 \\dots v_m \\rangle$ because $\\langle v_1 \\dots v_m \\rangle \\in \\mathcal{S}$, since, \\\\\n\\qquad \\, $\\langle v_1 \\dots v_m \\rangle$ is \\emph{a} subspace of $V$ containing $X$. \n\nIf $S\\in \\mathcal{S}$, then $S\\ni v_1 \\dots v_m$. As shown above, $\\forall \\, v\\in \\langle v_1 \\dots v_m \\rangle$, $v\\in S$, and thus $v\\in \\bigcap_{S\\in \\mathcal{S}} S$. $\\langle v_1 \\dots v_m \\rangle \\subseteq \\bigcap_{S\\in \\mathcal{S}} S$. \n\\end{enumerate}\n\t\\end{proof}\n\nWere all terminology in algebra consistent, \\\\\n$\\langle v_1 \\dots v_m \\rangle \\equiv $ subspace \\emph{generated} by $X$. \n\nReason for different terms is that group theory, rings, vector spaces developed independently of each other.\n\n\\textbf{Example 3.72 of Rotman (2010) \\cite{JRotman2010}}\n\\begin{enumerate}\n\t\\item[(i)]\n\t\\item[(ii)]\n\t\\item[(iii)] \\textbf{polynomial vector space; polynomials as a vector space}. \\\\\n\tVector space need not be spanned by finite list. \\\\\n\te.g. $V=k[x]$, \\\\\n\tSuppose $X= f_1(x) \\dots f_m(x)$ finite list in $V$. \\\\\n\tIf $d= $ largest degree of any of $f_i(x)$, \\\\\n\tthen every (nonzero) $k$-linear combination of $f_1(x), \\dots f_m(x)$ has degree at most $d$. \\\\\n\tThus $x^{d+1} \\notin \\langle f_1(x) \\dots f_m(x) \\rangle$, so $X$ doesn't span $k[x]$\n\\end{enumerate}\n\n\\begin{definition}[finite-dimensional vector space; infinite-dimensional vector space]\n\tVector space $V$ is \\textbf{finite-dimensional} if it's spanned by a finite list; otherwise $V$ is \\textbf{infinite-dimensional}.\n\\end{definition}\n\n\\begin{proposition}[linear dependent span properties]\nIf vector space $V$, list $X=v_! \\dots v_m$ spanning $V$, following are equivalent:\n\t\\begin{enumerate}\n\t\t\\item[(i)] $X$ isn't shortest spanning list \n\t\t\\item[(ii)] some $v_i$ is in subspace spanned by others, i.e. $v_i \\in \\langle v_i \\dots \\widehat{v}_i \\dots v_m \\rangle$, \n\t\t\\item[(iii)]\t\t$\\exists \\, a_1 \\dots a_m$ not all $0$ s.t. $\\sum_{l=1}^m a_l v_l = 0$\n\t\\end{enumerate}\n\\end{proposition}\n\n\\begin{proof}\n(i) $\\Longrightarrow$ (ii). If $X$ isn't shortest spanning list, then 1 of vectors in $X$ can be thrown out, and shorter list still spans, i.e. cf. Lemma \\ref{Lemma:smallest_subspace}(Lemma 3.71, Rotman (2010) \\cite{JRotman2010}); let $\\mathcal{S} \\equiv $ family of all subspaces of $V$ containing $X$. \n\nEY: 20180610 \nLet $\\bigcap_{S\\in \\mathcal{S}} S$. $\\bigcap_{S \\in \\mathcal{S}} S \\neq \\langle v_1 \\dots v_m \\rangle$, $\\bigcap_{S \\in \\mathcal{S}} S \\subset \\langle v_1 \\dots v_m \\rangle$ \\\\\n$\\exists \\, v \\in \\langle v_1 \\dots v_m \\rangle$, say$v= \\sum_{i=1}^m a_i v_i$ s.t. $\\exists \\, S \\in \\mathcal{S}$, s.t. $v\\notin S$. \n\n(ii) $\\Longrightarrow$ (iii) If $v_i = \\sum_{j\\neq i} c_j v_j$, define $a_i = -1 \\neq 0$, $a_j = c_j$, $\\forall \\, j \\neq i$. Then $\\sum_{l=1}^m a_l v_l = -v_i + \\sum_{j\\neq i } c_j v_j = 0$\n\n(iii) $\\Longrightarrow$ (i) Suppose for $i \\in 1 \\dots m$, $a_i \\neq 0$. $v_i = -\\sum_{j\\neq i} \\frac{a_j}{a_i} v_j$. $\\langle v_1 \\dots \\widehat{v}_i \\dots v_m\\rangle$ still spans $V$ (i.e. deleting $v_i$ gives a shorter list, which still spans). \n\nFor instance, if $v\\in \\langle v_1 \\dots v_m \\rangle$, $v= \\sum_{l=1}$%m c_l v_l = \\sum_{j\\neq i} c_j v_j + c_i \\left( - \\sum_{j\\neq i} \\frac{a_j}{a_i} v_j \\right) = \\sum_{j\\neq i } \\left( c_j - \\frac{ c_i a_j}{a_i} \\right) v_j$ so $\\langle v_1\\dots v_m \\rangle$ wasn't shortest spanning list.\n\n\n\n\n\n\t\\end{proof}\n\n\\exercisehead{3.67} Suppose $\\text{dim}V >1$. Then $\\exists \\, $ at least 2 elements in a basis of $V$, say $e_1$, $e_2$. (Thm. 3.78 of Rotman (2010) \\cite{JRotman2010}, \"Every finite-dim. vector space $V$ has a basis; Def. of $\\text{dim}$, \"number of elements in a basis of $V$\"). \n\nConsider subspaces $\\langle e_1 \\rangle$, $\\langle e_2 \\rangle$, subspaces spanned by $e_1,e_2$, respectively. Whether $V= \\langle e_1, e_2 \\rangle$ or $V= \\langle e_1, e_2\\rangle$, $\\langle e_1 \\rangle , \\langle e_2 \\rangle \\neq \\lbrace 0 \\rbrace$ nor $V$. Contradiction of hypothesis. \n\nThus, \"If only subspaces of a vector space $V$ are $\\lbrace 0 \\rbrace$ and $V$ itself, $\\text{dim}(V) \\leq 1$.\"\n\n\n\n\\begin{proposition}[Matrix representation of linear transformation; 3.94 of Rotman (2010) \\cite{JRotman2010}]\\label{Prop:MatRepofLinearTransform}\n\tIf linear transformation $T: k^n \\to k^m$, then $\\exists \\, A \\in \\text{Mat}_k(m,n)$ s.t. \n\t\\[\n\tT(y) = Ay, \\qquad \\ \\forall \\, y \\in k^n\n\t\\]\n\\end{proposition}\n\n\\begin{proof}\n\tLet $\\begin{aligned} & (e_1\\dots e_n) & \\text{standard basis of $k^n$ } \\\\\n\t& (e_1' \\dots e_m') & \\text{standard basis of $k^m$ } \\end{aligned}$\n\nDefine $A=[a_{ij}]$, s.t. $T(e_j) = A_{*j} = A_{ij} e_i'$ ($j$th column), \n\nIf $\\begin{aligned} \n& S:k^n \\to k^m \\\\ \n& S(y) = A(y) \\end{aligned}$, then \n\\[\nT(e_j) = a_{ij}e_i' = Ae_j\n\\]\nand so $\\forall \\, y = y_je_j \\in k^n$, \n\\[\nT(y) = T(y_je_j) = y_j T(e_j) = y_j A_{ij}e'_i = Ay\n\\]\n\n\n\t\\end{proof}\n\n\\section{Modules}\n\n\\subsection{R-modules}\n\ncf. Sec. 7.1 Modules of Rotman (2010) \\cite{JRotman2010}\n\n\\begin{definition}[$R$-module]\n\t$R$-module is (additive) abelian group $M$, \\\\\n\tequipped with scalar multiplication $\\begin{aligned} & \\quad \\\\\n\t& R \\times M \\to M \\\\\n\t& (r,m) \\mapsto rm \\end{aligned}$ \n\t\n\ts.t. $\\forall \\, m,m' \\in M$, $\\forall \\, r,r',1 \\in R$\n\t\\begin{enumerate}\n\t\t\\item[(i)] $r(m+m')=rm+rm'$\n\t\t\\item[(ii)] $(r+r')m = rm+r'm$\n\t\t\\item[(iii)] $(rr')m = r(r'm)$\n\t\t\\item[(iv)] $1m = m$\n\t\\end{enumerate}\n\\end{definition}\n\nExample 7.1 \\begin{enumerate}\n\t\\item[(i)] $\\forall \\, $ \\emph{vector space} over field $k$ is a $k$-module. (by inspection of the axioms for a vector space, associativity, distributivity!)\n\t\\item[(ii)] $\\forall \\, $ abelian group is a $\\mathbb{Z}$-module, by laws of exponents (Prop. 2.23)\n\t\n\tIndeed, for\n\t\\[\n\t\\begin{aligned}\n\t\\mathbb{Z} \\times M & \\to M \\\\ \n\t(r,m) & \\mapsto rm \\equiv m^r \n\t\\end{aligned}\n\t\\]\n\tand so\n\t\\[\n\tr(m\\cdot m') \\equiv (m\\cdot m')^r = m^r (m')^r = rm + rm' \n\t\\]\n\t(since $M$ abelian)\n\t\\item[(iii)] For commutative ring, scalar multiplication, defined to be given multiplication of elements of $R$\n\t\\[\n\t\\begin{aligned}\n\tR\\times R & \\to R \\\\\n\t(a,b) & \\mapsto ab \n\t\\end{aligned}\n\t\\]\n\tFor reference, recall some of the properties of a commutative ring:\n\t\\[\n\t\\begin{aligned}\n\t& ab = ba \\\\ \n\t& a(bc) = (ab)c \\\\ \n\t& 1a = a \\\\ \n\t& a(b+c) = ab + ac\n\t\\end{aligned}\n\t\\]\n\t\n\t$\\forall \\, $ ideal $I$ in $R$ is an $R$-module, \\\\\n\tfor if $\\begin{aligned} & \\quad \\\\\n\t& i \\in I \\\\\n\t& r\\in R \\end{aligned}$ , then $ri \\in I$.\n\t\n\t$0\\in I$ \\\\\n\t$\\forall \\, a,b \\in I, \\, a+b \\in I$\n\t\n\t\n\tIf $a\\in I$, $r\\in R$, then $ra \\in I$.\n\t\n\t\n\t\\item[(iv)]\n\t\\item[(v)] Let linear $T:V \\to V$, $V$ finite-dim. vector space over field $k$. \n\t\n\tRecall $k[x] \\equiv $ set of polynomials with coefficients in $k$. \n\t\n\tDefine $\\begin{aligned} & \\quad \\\\\n\t& k[x] \\times V \\to V \\\\\n\t& f(x)v =\\left(\\sum_{i=0}^m c_i x^i\\right)v =\\sum_{i=0}^m c_iT^i(v) \\end{aligned}$ \\quad \\, $\\forall \\, f(x) = \\sum_{i=0}^m c_ix^i \\in k[x]$\n\t\n\t$\\Longrightarrow $ denote $k[x]$-module $V^T$. \n\t\n\tSpecial case: Let $A \\in \\text{Mat}_k(n,n)$, let linear $\\begin{aligned} & \\quad \\\\\n\t& T :k^n \\to k^n \\\\\n\t& T(w) = Aw \\end{aligned}$. \n\t\n\tvector space $k^n$ is $k[x]$-module if we define scalar multiplication \n\t\\[\n\t\\begin{aligned} & \\quad \\\\\n\t& k[x] \\times k^n \\to k^n \\\\\n\t& f(x)w = \\left( \\sum_{i=0}^m c_ix^i \\right)w = \\sum_{i=0}^m c_i A^i w \\end{aligned}\n\t\\] \n\t\\quad \\, $\\forall \\, f(x) = \\sum_{i=0}^m c_ix^i \\in k[x]$\n\t\n\tIn $(k^n)^T$, $xw = T(w)$ \\\\\n\tIn $(k^n)^A$, $xw = Ax $ \\\\\n\t$T(w) = Ax$ and so $(k^n)^T = (k^n)^A$ (EY : 20151015 because of induction?)\n\\end{enumerate}\n\n\n\\begin{definition}[R-homomorphism (or R-map)]\nIf ring $R$, $R$-modules $M,N$, then \\\\\nfunction $f: M\\to N$, \\\\\nif $\\forall \\, m, m' \\in M$, $\\forall \\, r\\in R$, \n\\[\n\\begin{gathered}\n\tf(m+m') = f(m) + f(m') \\\\ \nf(rm) = rf(m)\n\\end{gathered}\n\\]\n\\end{definition}\n\nExample 7.2. of Rotman (2011) on pp. 425 \\cite{JRotman2010}] \n\n\\begin{enumerate}\n\t\\item[(i)] If $R$ field, then $R$-modules are vector spaces and $R$-maps are linear transformations. Isomorphisms are then nonsingular linear transformations. \n\t\\item[(ii)] \n\t\\item[(iii)]\n\t\\item[(iv)]\n\t\\item[(v)] Let linear $T:V \\to V$, let $v_1 \\dots v_n$ be basis of $V$, let $A$ be matrix of $T$ relative to this basis. \n\t\n\tLet $e_1 \\dots e_n$ be standard basis of $k^n$. \\\\\n\tDefine $\\begin{aligned} & \\quad \\\\\n\t& \\varphi : V \\to k^n \\\\\n\t& \\varphi(v_i) = e_i \\end{aligned}$\n\t\n\t\\[\n\t\\begin{aligned}\n\t& \\varphi(xv_i) = \\varphi(T(v_i)) = \\varphi(v_j a_{ji} ) = a_{ji} \\varphi(v_j) = a_{ji}e_j \\\\\n\t& x\\varphi(v_i) = A\\varphi(v_i) = Ae_i\n\t\\end{aligned}\n\t\\]\n\t$\\Longrightarrow \\varphi(xv) = x\\varphi(v) \\quad \\, \\forall \\, v \\in V$\n\t\n\tBy induction on $\\deg{f}$, $\\varphi(f(x)v) = f(x) \\varphi(v)$ \\quad \\, $\\forall \\, f(x) \\in k[x]$ \\quad \\, $\\forall \\, v \\in V$ \n\t\n\t$\\Longrightarrow \\varphi$ is $k[x]$-map \\\\\n\t$\\Longrightarrow \\varphi$ is $k[x]$-isomorphism of $V^T$ and $(k^n)^A$. \n\t\n\\end{enumerate}\n\n\n\\begin{proposition}[7.3 of Rotman (2011) \\cite{JRotman2010}]\\label{Prop:kxmoduleisomorphism}\n\tLet vector space over field $k$, $V$, let linear $T,S : V \\to V$ \\\\\n\tThen $k[x]$-modules $V^T, V^S$ are $k[x]$-isomorphic iff $\\exists \\, $ vector space isomorphism $\\varphi : V \\to V$ s.t. $S = \\varphi T \\varphi^{-1}$. \n\\end{proposition}\n\n\\begin{proof}\n\tIf $\\varphi:V^T \\to V^S$is a $k[x]$-isomorphism, \n\t\\[\n\t\\varphi(f(x)v) = f(x)\\varphi(v) \\quad \\, \\forall \\, v \\in V , \\, \\forall \\, f(x) \\in k[x]\n\t\\]\n\tif $f(x)=x$, then $\\varphi(xv) = x\\varphi(v)$\n\t\\[\n\t\\begin{aligned}\n\t& xv = T(v) \\\\ \n\t& x\\varphi(v) = S(\\varphi(v)) \\\\ \n\t\\Longrightarrow & \\varphi \\circ T(v) = S \\circ \\varphi(v) \\Longrightarrow \\varphi \\circ T = S \\circ \\varphi \n\t\\end{aligned}\n\t\\]\n\t$\\varphi$ isomorphism, so $S = \\varphi \\circ T \\circ \\varphi^{-1}$\n\t\n\tConversely, if given isomorphism $\\varphi: V \\to V$ s.t. $S = \\varphi T \\varphi^{-1}$, then $S\\varphi = \\varphi T$. \n\t\\[\n\tS\\varphi(v) = \\varphi T(v) = \\varphi(xv) = x\\varphi(v)\n\t\\]\n\tThen by induction, $\\varphi(x^nv) = x^n\\varphi(v)$ (for $S^n\\varphi(v) = x^n\\varphi(v) = (\\varphi T \\varphi^{-1})^n \\varphi(v) = \\varphi T^n v = \\varphi(x^nv)$). \\\\\n\tBy induction on $\\deg{(f)}$, $\\varphi(f(x)v) = f(x)\\varphi(v)$. \n\t\n\t\n\\end{proof}\n\n\n\n\\begin{corollary}[7.4 of Rotman (2011) \\cite{JRotman2010}] \n\tLet $k$ be a field, \\\\\n\tLet $A,B \\in \\text{Mat}_k(n,n)$. \\\\\n\tThen $k[x]$-modules $(k^n)^A$, $(k^n)^B$ are $k[x]$-isomorphic. \n\t\n\t(recall, $k[x]\\equiv $ set of polynomials with coefficients in $k = \\lbrace \\sum_{i=0}^m c_ix^i | c_i \\in k \\rbrace$, and define scalar multiplication \n\t\\[\n\t\\begin{aligned}\n\t\t& k[x] \\times k^n \\to k^n \\\\\n\t\t& f(x) w = \\left( \\sum_{i=0}^m c_i x^i \\right) w = \\sum_{i=0}^m c_iA^i w, \\qquad \\ \\forall \\, f(x) = \\sum_{i=0}^m c_i x^i \\in k[x] \n\t\\end{aligned}\n\t\\]\n\t)\n\t\n\tiff $\\exists \\, $ nonsingular $P$ with \n\t\\[\n\tB=PAP^{-1}\n\t\\]\n\t\n\t\\end{corollary}\n\n\\begin{proof}\n\tDefine \n\t\n\t$\\begin{aligned} & T:k^n \\to k^n \\\\\n\t& T(y) = A(y) \\end{aligned}$\nwhere $y\\in k^n $ is a column. \n\nBy Example 7.1 (v) of Rotman (2011) \\cite{JRotman2010}, recall, \n\nand so for $k[x]$-module, $(k^n)^T = (k^n)^A$. \n\nSimilarly, define \n\\[\n\\begin{aligned} \n\t& S: k^n \\to k^n \\\\\n\t& S(y) = B(y) \n\t\\end{aligned}\n\t\\]\n\tDenote corresponding $k[x]$-module by $(k^n)^B$. \n\t\n\tGiven $(k^n)^A \\cong (k^n)^B$ (isomorphic), by Prop. \\ref{Prop:kxmoduleisomorphism}, \\\\\n\t$\\exists \\, $ isomorphism $\\varphi :k^n \\to k^n$ s.t. $B=\\varphi A \\varphi^{-1}$. \n\nBy Prop. \\ref{Prop:MatRepofLinearTransform}, i.e. Prop. 3.94 of Rotman (2011) \\cite{JRotman2010}, in that every linear transformation has a matrix representation (even in the standard \"Euclidean\" basis), $\\exists \\, P \\in \\text{Mat}_{k}(n,n)$, s.t. \n\\[\n\\varphi(y) = Py \\qquad \\ y\\in k^n\n\\]\n($P$ nonsingular because $\\varphi$ isomorphism)\n\nThus, \n\\[\n\\begin{aligned}\n& B\\varphi(y) = \\varphi A(y) \\\\ \n& BPy = P(Ay) \\qquad \\ \\forall \\, y \\in k^n \\\\\n\\Longrightarrow & PA = BP \\text{or } B= PAP^{-1}\n\\end{aligned}\n\\]\n\nConversely, given $B=PAP^{-1}$, $P$ nonsingular matrix, \\\\\ndefine isomorphism \n\\[\n\\begin{aligned}\n& \\varphi :k^n \\to k^n \\\\ \n& \\varphi(y) = Py \\qquad \\ \\forall \\, y \\in k^n\n\\end{aligned}\n\\]\n\nBy Prop. \\ref{Prop:kxmoduleisomorphism}, \\\\\n$(k^n)^B$, $(k^n)^A$ are $k[x]$-isomorphic. \\\\\ni.e. $\\varphi : (k^n)^A \\to (k^n)^B $ is a $k[x]$-module isomorphism. \n\n\n\t\\end{proof}\n\n\\begin{definition}[$\\text{Hom}_R(M,N)$]\n\\begin{equation}\n\\text{Hom}_R(M,N) = \\lbrace \\text{ all $R$-homomorphisms $M\\to N$ } \\rbrace = \\lbrace f | f:M\\to N , \\text{ s.t. } \\forall \\, m,m' \\in M, \\, \\forall \\, r \\in R, \\begin{aligned} & f(m+m') =f(m) + f(m') \\\\ & f(rm) = rf(m) \\end{aligned} \\rbrace\n\\end{equation}\nIf $f,g \\in \\text{Hom}_R(M,N)$, \\\\\ndefine\n\\begin{equation}\n\\begin{aligned}\n& f+g:M \\to N \\\\\n& f+g:m\\mapsto f(m) + g(m)\n\\end{aligned}\n\\end{equation}\n\\end{definition}\n\n\\begin{proposition}[$\\text{Hom}_R(M,N)$ $R$-module, 7.5 of Rotman (2011) \\cite{JRotman2010}]\n\tIf $M,N$ $R$-modules, where $R$ commutative ring, \\\\\n\tthen $\\text{Hom}_R(M,N)$ $R$-module, \\\\\n\twith addition \n\t\\[\n\t\\begin{aligned}\n\t& f+g: M\\to N \\qquad \\ \\forall \\, f,g \\in \\text{Hom}_R(M,N) \\\\\n\t& f+g:m\\mapsto f(m) + g(m)\n\t\\end{aligned}\n\t\\]\nand scalar multiplication \n\\[\nrf:m \\mapsto f(rm)\n\\]\n\tMoreover, distributive laws: \\\\\n\tIf $p:M'\\to M$, $q:N\\to N'$, then \n\t\\[\n\t(f+g)p = fp+gp \\text{ and } q(f+g) = qf + qg\n\t\\]\n$\\forall \\, f,g \\in \\text{Hom}_R(M,N)$\t\n\t\n\t\n\t\n\\end{proposition}\n\n\\begin{proof}\n\t$\\forall \\, f,g \\in \\text{Hom}_R(M,N)$, $\\forall \\, r,r', 1 \\in R$, \n\t\\begin{enumerate}\n\t\t\\item[(i)] \n\t\t\\[\n\t\tr(f+g)(m) = (f+g)(rm) = f(rm) + g(rm) = rf(m) + rg(m) = (rf+rg)(m) \n\t\t\\]\n\t\t\\item[(ii)]\n\t\t\\[\n\t\t(r+r')f(m) = f((r+r')m) = f(rm+r'm) = f(rm) + f(r'm) = (rf+ r'f)(m)\n\t\t\\]\n\t\t\\item[(iii)]\n\t\t\\[\n\t\t(rr')f(m) = f(rr'm) = rf(r'm) = f(r'rm) = f(rr'm) \\Longrightarrow (rr')f = r(r'f)\n\t\t\\]\n\t\t\\item[(iv)]\n\t\t\\[\n\t\t1f(m) = f(1m) = f(m) \\Longrightarrow 1f =f\n\t\t\\]\n\t\\end{enumerate}\n\t\\end{proof}\n\n\n\n\\begin{definition}\n\tif $R$-module $M$, the submodule $N$ of $M$, denoted $N\\subseteq M$, is additive subgroup $N$ of $M$, \\\\\n\tclosed under scalar multiplication $rn \\in N$ whenever $n\\in N$, $r\\in R$\n\\end{definition}\n\n\n\n\n\\begin{definition}[quotient module $M/N$] \\qquad \\, \\\\ \n\\textbf{quotient module} $M/N$ -\n\nFor submodule $N$ of $R$-module $M$, then, \\\\\nremember $M$ abelian group, $N$ subgroup, \\\\\nquotient group $M/N$ equipped with scalar multiplication \n\\[\n\\begin{gathered}\n\tr(m+N) = rm+N \\\\ \nM/N = \\lbrace m +N | m \\in M \\rbrace\n\\end{gathered}\n\\]\n\\textbf{natural map} \n\\begin{equation}\n\\begin{aligned}\n& \\pi : M \\to M /N \\\\ \n& m\\mapsto m + N \n\\end{aligned}\n\\end{equation}\neasily seen to be $R$-map. \n\nScalar multiplication in quotient module well-defined: \\\\\nIf $m+N=m'+N$, $m-m' \\in N$, so $r(m-m') \\in N$ (because $N$ submodule), so \n\\[\nrm - rm' \\in N \\text{ and } rm+ N = rm' +N\n\\]\n\n\n\\end{definition}\n\n\n\\begin{proposition}[7.15 of Rotman (2010) \\cite{JRotman2010}] \n\\begin{enumerate}\n\\item[(i)] $S \\bigsqcup T \\simeq M$ \n\\item[(ii)] $\\exists \\, $ injective $R$-maps $\\begin{aligned} & \\quad \\\\ \n\t& i : S\\to M \\\\ \n& j :T \\to M \\end{aligned}$, s.t. \n\n\\begin{equation}\n\\begin{gathered} \nM = \\text{im}(i) + \\text{im}(j) \\text{ and } \\\\ \n\\text{im}(i) \\bigcap \\text{im}(j) = \\lbrace 0 \\rbrace \n\\end{gathered}\n\\end{equation}\n\\item[(iii)] $\\exists \\, $ R-maps \n\\[\n\\begin{aligned}\n\t& i : S\\to M \\\\ \n\t& j : T\\to M \n\\end{aligned}\n\\]\ns.t. $\\forall \\, m \\in M$, $\\exists \\, !$ \n\\[\n\\begin{aligned}\n\t& s \\in S \\\\ \n\t& t \\in T \n\\end{aligned}\n\\] with $m=is + jt$. \n\\item[(iv)] $\\exists \\, $ R-maps \n\\[\n\\begin{gathered}\n\\begin{aligned} & i: S\\to M \\\\ \n& j:T \\to M \\end{aligned} \\qquad \\, \\begin{aligned}\n& p : M \\to S \\\\ \n& q : M \\to T \\end{aligned}\n\\end{gathered}\n\\]\ns.t. \n\\[\n\\begin{gathered}\n\t\\begin{aligned}\n\t& pi = 1_S \\\\ \n& qj = 1_T \n\\end{aligned} \\qquad \\ , \\begin{aligned}\n\t& pj = 0 \\\\\n\t& qi = 0 \n\\end{aligned} \\qquad \\, ip + jq = 1_M\n\\end{gathered}\n\\]\n\\end{enumerate}\n\\end{proposition}\n\n\\begin{proof}\n\\begin{itemize}\n\\item (i)$\\to$ (ii) Given $S \\bigsqcup T \\simeq M$, \\\\ \n let $\\varphi : S \\bigsqcup T \\to M$ be this isomorphism. \n\nDefine\n\\[\n\\begin{aligned}\n\t& i:= \\varphi \\lambda_S \\qquad \\, & (\\lambda_S : s\\mapsto (s,0)) \\qquad \\, & i :S \\to M \\\\ \n\t& j:= \\varphi \\lambda_T \\qquad \\, & (\\lambda_T : t\\mapsto (0,t)) \\qquad \\, & j :T \\to M \n\\end{aligned}\n\\]\n$i,j$ are injections, being composites of injections. \n\nIf $m\\in M$, $\\exists \\, ! \\, (s,t) \\in S\\bigsqcup T$, s.t. $\\varphi(s,t)=m$. \n\nThen \n\\[\nm = \\varphi(s,t) = \\varphi((s,0) + (0,t)) = \\varphi\\lambda_S(s) \\varphi \\lambda_T(t) = is + jt \\in \\text{im}(i) + \\text{im}(j)\n\\]\n\nLet $c\\in \\text{im}(i) + \\text{im}(j)$. Since $\\begin{aligned} & \\quad \\\\ \n\t& i : S\\to M \\\\\n& j : T \\to M \\end{aligned}$, $c\\in M$. \n\n$\\Longrightarrow M = \\text{im}(i) + \\text{im}(j)$. \n\n\n\nIf $x\\in \\text{im}(i) \\bigcap \\text{im}(j)$, \n\\[\n\\begin{aligned}\n\t& x = i(s) \\text{ for some } s\\in S \\\\ \n\t\t& x = j(t) \\text{ for some } t\\in T \n\\end{aligned}\n\\]\n\n\\[\n\\begin{gathered}\n\tis=jt = \\varphi \\lambda_S(s) = \\varphi \\lambda_T(t) = \\varphi(s,0) = \\varphi(0,t) \n\\end{gathered}\n\\]\n$\\varphi$ isomorphism, so $\\exists \\, \\varphi^{-1}$ $\\Longrightarrow (s,0) = (0,t)$, so $s=t=0$. $x=0$ \n\\item (ii)$\\to $ (iii) Given $\\begin{aligned} & \\quad \\\\ & i:S\\to M \\\\ & j:T\\to M \\end{aligned}$, s.t. $M= \\text{im}(i) + \\text{im}(j)$, so \\\\\n\n$\\forall \\, m \\in M$, $m=i(s) + j(t)$ for some $s\\in S,t\\in T$. \n\nSuppose $\\begin{aligned} & \\quad \\\\ \n\t& s' \\in S \\\\\n& t' \\in T \\end{aligned}$, s.t. $m=i(s'_ + j(t')$. \n\\[\ni(s-s') = j(t-t') \\in \\text{im}(i) \\bigcap \\text{im}(j) = \\lbrace 0 \\rbrace\n\\]\nSo $s=s',t=t'$, since $i,j$ injective. \n\\item (iii)$\\to$ (iv) \n\nGiven $\\forall \\, m \\in M$, $\\exists \\, ! \\, s\\in S,t\\in T$ s.t. \n\\[\nm=i(s) + j(t)\n\\]\nDefine \n\\[\n\\begin{aligned}\n\t& p:M \\to S \\\\ \n\t& p(m) := s\n\\end{aligned} \\qquad \\, \\begin{aligned}\n\t& q: M \\to T \\\\ \n\t& q(m) := t\n\\end{aligned}\n\\]\n\\[\n\\begin{aligned}\n\t& pi(s) = s \\\\ \n\t& qj(t) = t \n\\end{aligned} \\qquad \\, \\begin{aligned}\n& pj(t) =0 \\\\\n& qi(s) = 0 \\end{aligned} \\qquad \\, \n(ip+jq)(m) = ip(m) + jq(m) = i(s) + j(t) = m \n\\]\n\\end{itemize}\n\\end{proof}\n\n\\subsection{Vector Spaces as a Module}\n\nLang made the key insight on vector spaces as a whole in Sec 5. \"Vector Spaces\" in pp. 139-140 of Lang (2005) \\cite{Lang2005}: \n\n\\begin{theorem}[Existence of a basis for vector spaces, Thm. 5.1 Lang (2005) \\cite{Lang2005}]\\label{Thm:ExistenceOfBasisForVectorSpaces}\n\tLet $V$ be a vector space over a field $K$, assume $V \\neq \\lbrace 0 \\rbrace$. \n\t\n\tLet $\\Gamma$ be a set of generators of $V$ over $K$ and let $S$ be a subset of $\\Gamma$ which is linearly independent. \n\t\n\tThen $\\exists \\, $ basis $\\mathcal{B}$ of $V$ s.t. $S \\subset \\mathcal{B} \\subset \\Gamma$.\n\n\\end{theorem}\n\t\nIndeed, while this wikipedia article \\footnote{\\url{https://en.wikipedia.org/wiki/Vector_space}} on Vector space does a good job generalizing the properties defining a vector in a vector space, a vector's properties is separate from what \\emph{characterizes} a vector space. Here, we can \\emph{specify} a vector space by its generators, and furthermore, from Thm. \\ref{Thm:ExistenceOfBasisForVectorSpaces}, it has a basis that characterizes a vector space. This can be useful for implementation in C++.\n\n\\section{Vector Spaces}\n\ncf. Ch. 11, \"Vector Spaces\" pp. 408, Dummit and Foote \\cite{DuFo2003}\n\n\\begin{center}\n\\begin{tabular}{l | l }\n\\textbf{Terminology for $R$ any Ring} & \\textbf{Terminology for $R$ a Field } \\\\\n\\hline\n$M$ is an $R$-module & $M$ is a vector space over $R$ \\\\\n$m$ is an element of $M$ & $m$ is a vector in $M$ \\\\\n$\\alpha$ is a ring element & $\\alpha$ is a scalar \\\\\n$N$ is a submodule of $M$ & $N$ is a subspace of $M$ \\\\\n$M/N$ is a quotient module & $M/N$ is a quotient space \\\\\n$M$ is a free module of rank $n$ & $M$ is a vector space of dimension $n$ \\\\\n$M$ is a finitely generated module & $M$ is a finite dimensional vector space \\\\\n$M$ is a nonzero cyclic module & $M$ is a 1-dimensional vector space \\\\\n$\\varphi : M \\to N$ is a $R$-module homomorphism & $\\varphi : M \\to N$ is a linear transformation \\\\\n$M$ and $N$ are isomorphic as $R$-modules & $M$ and $N$ are isomorphic vector spaces \\\\\nthe subset $A$ of $M$ generates $M$ & the subset $A$ of $M$ spans $M$ \\\\\n$M = RA$ & each element of $M$ is a linear combination of elements of $A$ i.e., $M=\\text{Span}(A)$\n\\end{tabular} \n\\end{center}\ncf. pp. 408, 11.1 \"Definitions and Basic Theory\", Dummit and Foote \\cite{DuFo2003}\n\nVector spaces are free $F$-modules, i.e. vector spaces have bases. \\\\\n\n\\emph{Examples}:\n\n\\begin{enumerate}\n\t\\item Space $V= F[x]$ of polynomials in the variable $x$ with coefficients from field $F$ is a vector space over $F$. elements $1,x,x^2, \\dots $ are linearly independent by def. (i.e. polynomial is $0$ iff all its coefficients are $0$). Since these elements also span $V$, by def., they're a basis for $V$ (basis of vector space $V$ is ordered set of linearly independent vectors which span $V$)\n\t\\item Collection of solutions of a linear, homogeneous, constant coefficient differential equation (e.g. $y'' - 3y' + 2y = 0$) over $\\mathbb{C}$ form a vector space over $\\mathbb{C}$, since differentiation is a linear operator. \\\\\n \te.g. $e^t, e^{2t}$ are linearly independent ($ae^t + be^{2t} =0$, then so $a+b =0 \\, (t=0)$, $ae + be^2 = 0 \\, (t=1) \\Longrightarrow a=b=0$) \\\\\n \tBy Thm. in differential eqns. that these elements span set of solutions of this eqn., hence form a basis.\n\\end{enumerate}\n\n\\begin{proposition}[1, Dummit and Foote \\cite{DuFo2003}]\n\tAssume set $\\mathcal{A} = \\lbrace v_1, v_2 , \\dots v_n \\rbrace$ spans vector space $V$ but no proper subset of $\\mathcal{A}$ spans $V$. Then $\\mathcal{A}$ basis of $V$. In particular, any finitely generated (finitely spanned) vector space over $F$ is a free $F$-module.\n\\end{proposition}\n\n\\begin{proof}\n\\emph{Want}: $v_1, v_2, \\dots v_n$ linearly independent. \\\\\n\nSuppose $\\sum_{i=1}^n \\alpha_i v_i = 0$ s.t. not all $\\alpha_i = 0$. \\\\\n\nBy reordering, assume $\\alpha_1 \\neq 0$ and then $v_1 = \\frac{-1}{\\alpha_1} (\\alpha_2 v_2 + \\dots + \\alpha_n v_n)$. \\\\\nThen $\\lbrace v_2, v_3, \\dots v_n \\rbrace$ also spans $V$ since any linear combination of $v_1, v_2, \\dots v_n$ can be written as a linear combination of $v_2, v_3, \\dots v_n$ using $v_1 = \\frac{-1}{\\alpha_1} (\\alpha_2 v_2 + \\dots + \\alpha_n v_n)$. Contradiction.\t\n\t\n\\end{proof}\n\n\n\\emph{Example}. \n\nLet $F$ be a field, consider $F[x]/(f(x))$ where $f(x) = x^n + \\sum_{j=0}^{n-1} a_j x^j$ \\\\\nideal $(f(x))$ is a subspace of vector space $F[x]$, quotient $F[x]/(f(x))$ is a vector space over $F$. \\\\\n\nBy Euclidean Algorithm, $\\forall \\, $ polynomial $a(x) \\in F[x]$ can be written uniquely in form\n\\[\na(x) = q(x) f(x) + r(x)\n\\]\nwhere $r(x) \\in F[x]$, and $0\\leq \\text{deg}{r(x)} \\leq n -1$ \\\\\nSince $q(x) f(x) \\in (f(x))$, it follows $\\forall\\, $ element of quotient is represented by polynomial $r(x)$ of degree $\\leq n - 1$ \\\\\n2 distinct such polynomials cannot be the same in the quotient since this would say their difference (which is a polynomial of degree at most $n-1$) would be divisible by $f(x)$ (which is of degree $n$), i.e. \n\\[\nf(x) = x^n + \\sum_{j=1}^{n-1} a_j x^j\n\\]\n$\\forall \\, a(x) \\in F[x]$, $a(x) = q(x) f(x) + r(x)$, $q(x) f(x) \\in (f(x))$ (ideal) \\\\\n\nConsider $r_1(x)$, $\\text{deg}(r_1(x)) = n_1 \\leq n -1$, $\\text{deg}(r_2(x)) = n_2 \\leq n -1$. \\\\\nIf $a_1(x), a_2(x) \\in F[x]$, $\\begin{aligned} \n& \\quad \\\\ \na_1(x) & = q_1(x) f(x) + r_1(x) \\\\ \na_2(x) & = q_2(x) f(x) + r_2(x) \\end{aligned}$ $a_1(x) - a_2(x) = (q_1(x) - q_2(x)) f(x) + (r_1(x) - r_2(x))$.\n\nIf $r_1(x) = r_2(x)$, then $a_1(x) - a_2(x) = (q_1(x) - q_2(x)) f(x)$, so $a_1(x) - a_2(x)$ divisible by $f(x)$.\n\n$\\Longrightarrow \\overline{1}, \\overline{x}, \\overline{x^2} , \\dots \\overline{x^{n-1}}$ (bar denotes image of these elements in the quotient) span $F[x]/f(x)$, as vector space over $F$. \\\\\nNo proper subset of these elements also spans, hence elements give basis for $F[x]/(f(x))$.\n\n\n\n\n\n\\section{Categories; Category Theory} \n\n\\subsection{Categories}\n\ncf. 7.2 Categories of Rotman (2010) \\cite{JRotman2010}\n\n\\subsubsection{Russell paradox, Russell set} \n\n\\begin{definition}[Russell set]\nRussell set - set $S$ that's not a member of itself, i.e. $S\\notin R$\n\\end{definition}\n\nIf $R$ is family of all Russell sets, \\\\\nLet $X\\in R$. Then $X\\notin X$. But $X\\in R$. $X\\notin R$. \\\\\nLet $R\\notin R$. Then $R$ in family of Russell Sets. $R\\in R$. Contradiction. \n\nThen consider \\emph{class} as primitive term, instead of set. \n\n\\begin{definition}[Category]\nCategory $\\mathcal{C}$ (Rotman's notation) $\\equiv \\mathbf{C}$ (my notation), consists of class $\\text{obj}(\\mathcal{C})$ (Rotman's notation) $\\equiv \\text{Obj}(\\mathbf{C}) \\equiv \\text{Obj}\\mathbf{C}$ (my notation) of objects, set of morphisms $\\text{Hom}(A,B)$ $\\forall \\, (A,B)$ of ordered tuples of objects, composition \n\\[\n\\begin{gathered} \n\t\\text{Hom}(A,B)\\times \\text{Hom}(B ,C) \\to \\text{Hom}(A,C) \\\\\n(f,g)\\mapsto gf \\end{gathered}\n\\], s.t.\n\\begin{enumerate}\n\\item $\\exists \\, \\mathbf{1}$, $\\forall \\, f:A\\to B$, $\\exists \\, \\begin{aligned} & \\quad \\\\ \n1_A : A \\to A \\\\\n1_B : B \\to B \\end{aligned}$, s.t. $1_B \\cdot f = f= f\\cdot 1_A$, and \n\\item associativity, $\\forall \\, \\begin{aligned} & \\quad \\\\\n& f : A\\to B \\\\\n& g: B\\to C \\\\\n& h: C\\to D \\end{aligned}$, then $h\\circ (g\\circ f) = (h\\circ g) \\circ f$ \n\\end{enumerate}\n\nIn summary, \n\\begin{equation}\n\t\\mathbf{C} := (\\text{Obj}(\\mathbf{C}), \\text{Mor}\\mathbf{C}, \\circ, \\mathbf{1}) \\equiv (\\text{Obj}\\mathbf{C}, \\text{Mor}\\mathbf{C}, \\circ_{\\mathbf{C}}, \\mathbf{1}_{\\mathbf{C}})\n\\end{equation}\ns.t. \n\\[\n\\text{Mor}\\mathbf{C} = \\bigcup_{A,B \\in \\text{Obj}\\mathbf{C}} \\text{Hom}(A,B)\n\\]\n\\end{definition}\n\nExamples (7.25 of Rotman (2010)\\cite{JRotman2010}): \n\\begin{enumerate}\n\\item[(i)] $\\mathbf{C} = \\mathbf{\\text{Sets}}$ \n\\item[(ii)] $\\mathbf{C} = \\mathbf{\\text{Groups}} = \\mathbf{\\text{Grps}}$ \n\\item[(iii)] $\\mathbf{C} = \\mathbf{\\text{CommRings}}$\n\\item[(iv)] $\\mathbf{C} = {}_R\\textbf{Mod}$, if $R=\\mathbb{Z}$, ${}_{\\mathbb{Z}}\\textbf{Mod} = \\textbf{Ab}$, i.e. $\\mathbb{Z}-$modules are just abelian groups. \n\\item[(v)] $\\mathbf{C} =\\textbf{PO}(X)$, If partially ordered set $X$, regard $X$ as category, s.t. $\\textbf{Obj}, \\textbf{PO}(X) = \\lbrace x | x\\in X\\rbrace$, $\\forall \\, \\text{Hom}(x,y) \\in \\textbf{Mor}_{\\textbf{PO}}(X)$, $\\text{Hom}(x,y) = \\begin{cases} \\emptyset & \\text{ if } x \\npreceq y \\\\ \\kappa_y^x & \\text{ if } x \\preceq y \\end{cases}$ where $\\kappa_y^x \\equiv $ unique element in $\\text{Hom}$ set when $x \\preceq y$) s.t. \n\\[\n\\kappa_z^y \\kappa_y^x =\\kappa_z^x\n\\]\nAlso, notice that \n\\[\n1_x = \\kappa_x^x\n\\]\n\\end{enumerate}\n\n\\begin{definition}[isormorphisms or equivalences]\n$f:A\\to B$, $f\\in \\text{Hom}(A,B)$, if $\\exists \\, $ \\textbf{inverse} $g:B\\to A$, $g\\in \\text{Hom}(B,A)$, s.t. \n\\[\n\\begin{aligned}\n& gf = 1_A \\\\ \n& fg = 1_B\n\\end{aligned}\n\\]\nand if $\\mathbf{C} = \\textbf{Top}$, equivalences (isomorphisms) are homeomorphisms. \n\\end{definition}\n\nFeature of category ${}_R\\textbf{Mod}$ not shared by more general categories: \\emph{Homomorphisms can be added.}\n\n\\begin{definition}[pre-additive Category]\ncategory $\\mathbf{C}$\n\\end{definition} \n\n\n\n\n%--------------------------------------------------------------------------------\n% 20180202 \n%-------------------------------------------------------------------------------\n\nWe can force 2 overlapping subsets $A,B$ to be disjoint by ``disjointifying'' them: e.g. consider $(A\\cup B) \\times \\lbrace 1,2 \\rbrace$, consider $\\begin{aligned} & \\quad \\\\\n& A' = A\\times \\lbrace 1 \\rbrace \\\\\n& B' = B\\times \\lbrace 2 \\rbrace \\end{aligned}$.\n\n\\[\n\\Longrightarrow A' \\cap B' = \\emptyset \n\\]\nsince $(a,1) \\neq (b,2)$ \\, $\\forall \\, a \\in A$, $\\forall \\, b \\in B$.\n\nLet bijections $\\begin{aligned} & \\quad \\\\\n& \\alpha : A \\to A' \\\\\n& \\beta : B \\to B' \\end{aligned}$, \\qquad \\, $\\begin{aligned} & \\quad \\\\\n& \\alpha : a \\mapsto (a,1) \\\\\n& \\beta : b\\mapsto (b,2) \\end{aligned}$, denote $A'\\bigcup B' \\equiv A \\coprod B$.\n\nFrom Rotman (2010) \\cite{JRotman2010}, pp. 447,\n\\begin{definition}\n\t\\textbf{coproduct} $A \\coprod B \\equiv C \\in \\text{Obj}(\\mathcal{C})$\n\\end{definition}\n\nIn my notation,\n\n\\textbf{coproduct}\n\\begin{equation}\n\\begin{aligned}\n& (\\mu_1 , A_1 \\coprod A_2 ) \\\\ \n& (\\mu_2 , A_1 \\coprod A_2 ) \n\\end{aligned}\n\\end{equation}\nwhere injection (morphisms)\n\\begin{equation}\n\\begin{aligned}\n& \\mu_1 : A_1 \\to A_1 \\coprod A_2 \\\\ \n& \\mu_2 : A_1 \\to A_1 \\coprod A_2 \n\\end{aligned}\n\\end{equation}\ns.t.\n\\[\n\\forall \\, A \\in \\text{Obj}\\mathbf{A}, \\, \\forall \\, f_1 ,f_2 \\in \\text{Mor}\\mathbf{A} \\text{ s.t. } \\begin{aligned} & \\quad \\\\\n& f_1 : A_1 \\to A \\\\\n& f_2 : A_2 \\to A \\end{aligned}\n\\]\nthen\n\\begin{equation}\n\\begin{gathered}\n\\exists \\, ! [ f_i ] \\equiv [f_1, f_2 ] \\in \\text{Mor} \\mathbf{A}, \\, [f_1, f_2] : A_1 \\coprod A_2 \\to A \\text{ s.t. } \\\\ \n\\begin{aligned}\n& [f_1,f_2] \\mu_1 = f_1 \\\\ \n& [f_1,f_2] \\mu_2 = f_2 \\\\\n\\end{aligned}\n\\end{gathered}\n\\end{equation}\ni.e. \n\\begin{equation}\n\\begin{gathered}\n\\begin{tikzpicture}\n\\matrix (m) [matrix of math nodes, row sep=5em, column sep=4em, minimum width=3em]\n{\n\t& A \\\\ \n\tA_1 & A_1 \\coprod A_2 \\\\\n\tA_2 & \\\\\n};\n\\path[->]\n(m-2-1) edge node [above] {$f_1$} (m-1-2)\nedge node [above] {$\\mu_1$} (m-2-2)\n(m-3-1) edge node [right] {$f_2$} (m-1-2)\nedge node [below] {$\\mu_2$} (m-2-2)\n;\n\\path[dashed,->]\n(m-2-2) edge node [right] {$[f_1,f_2]$} (m-1-2)\n;\n\\end{tikzpicture}\n\\end{gathered}\n\\end{equation}\n\nSo to generalized, for $i\\in I$, (finite set $I$?)\n\n\\textbf{coproduct} $(\\mu_j, \\coprod_{i\\in I} A_i)_{j\\in I}$, where \\\\\n(family of) injection (morphisms) $\\mu_j : A_j \\to \\coprod_{i \\in I } A_i$\n\ns.t.\n\n\\[\n\\forall \\, A \\in \\text{Obj}\\mathbf{A}, \\, \\forall \\, f_i \\in \\text{Mor}\\mathbf{A}, \\, i \\in I, \\, f_i : A_i \\to A\n\\]\nthen\n\\begin{equation}\n\\begin{gathered}\n\\exists \\, ! \\, [f_i ] \\equiv [f_i]_{i\\in I} \\in \\text{Mor}\\mathbf{A} , \\, [f_i] : \\coprod_{i\\in I} A_i \\to A \\text{ s.t. } \\\\ \n[f_i] \\mu_j = f_j \\qquad \\, \\forall \\, j \\in I\n\\end{gathered}\n\\end{equation}\ni.e.\n\n\\begin{equation}\n\\begin{gathered}\n\\begin{tikzpicture}\n\\matrix (m) [matrix of math nodes, row sep=5em, column sep=4em, minimum width=3em]\n{\n\t& A \\\\ \n\tA_j & \\coprod_{i\\in I} A_i \\\\\n};\n\\path[->]\n(m-2-1) edge node [above] {$f_j$} (m-1-2)\nedge node [above] {$\\mu_j$} (m-2-2)\n;\n\\path[dashed,->]\n(m-2-2) edge node [right] {$[f_i]$} (m-1-2)\n;\n\\end{tikzpicture} \n\\end{gathered}\n\\end{equation}\n\n\n\nFor notation purposes only, recall that it's denoted the sets $\\text{Hom}(A,B)$ in ${}_R\\textbf{Mod}$ by\n\\[\n\\text{Hom}_R(A,B)\n\\]\ni.e., in my notation, for $A,B \\in \\text{Obj}{ {}_R \\textbf{Mod}}$, $\\text{Hom}(A,B) \\subset \\text{Mor}( {}_R\\textbf{Mod})$, $\\text{Hom}(A,B) \\equiv \\text{Hom}_R(A,B)$\n\n\\begin{definition}[pre-additive category] \n\tcategory $\\mathbf{C}$ is \\textbf{pre-additive} if $\\forall \\, \\text{Hom}(A,B)$, $\\text{Hom}(A,B)$ equipped with binary operation $+$ s.t. $\\forall \\, f,g \\in \\text{Hom}(A,B)$, \n\t\\begin{enumerate}\n\t\t\\item if $p: B\\to B'$, then \n\t\t\\[\n\t\tp(f+g) = pf + pg \\in \\text{Hom}(A,B')\n\t\t\\]\n\t\t\\item if $q: A'\\to A$, then \n\t\t\\[\n\t\t(f+g)q = fq + gq \\in \\text{Hom}(A',B)\n\t\t\\]\n\t\tand \n\t\t\\[\n\t\tf+g= g+f \\qquad \\, \\text{ (additive abelian) }\n\t\t\\] \n\t\\end{enumerate}\n\\end{definition}\n\n\\subsubsection{Examples of extra assumptions on sets, ${}_R\\textbf{Mod}$ we take for granted}\n\nIn Prop. 7.15(iii) Rotman (2010) \\cite{JRotman2010}, \\\\\ndirect sum $M=A\\oplus B$ if $\\exists \\, $ homomorphisms $\\begin{aligned} & \\quad \\\\\n& p:M\\to A \\\\\n& q:M\\to B \\\\\n& i:A\\to M \\\\\n& j:B\\to M \\end{aligned}$ s.t. $\\begin{aligned} & \\quad \\\\\n& pi = 1_A \\\\\n& qj = 1_B \\\\ \n& pj = 0 \\\\ & qi = 0 \\end{aligned}$, \n\\[\nip + jq = 1_M\n\\]\ndirect sum $M = A\\oplus B$ uses property that morphisms can be added ${}_R\\textbf{Mod}$ has this property. $\\textbf{Sets}$ don't. \n\nIn Corollary 7.17, \\\\\ndirect sum in terms of arrows, \\\\\n$\\exists \\, $ map $\\rho:M \\to S$ s.t. $\\rho(s)=s$. Moreover $\\text{ker}\\rho = \\text{im}j$, $\\text{im}\\rho = \\text{im}i$ and $\\rho(s)=s$, \\, $\\forall \\, s \\in \\text{im}\\rho$. \n\n\\begin{tikzpicture}\n\\matrix (m) [matrix of math nodes, row sep=5em, column sep=4em, minimum width=3em]\n{\n\tS & M & T \\\\ \n};\n\\path[->]\n(m-1-1) edge node [above] {$i$} (m-1-2)\n(m-1-3) edge node [above] {$j$} (m-1-2)\n;\n\\end{tikzpicture} \nand $M\\simeq S \\coprod T$, \\\\\nwhere $\\begin{aligned} & \\quad \\\\\n& i: s \\mapsto s \\\\ \n& j : t \\mapsto t \\end{aligned}$ (i.e. inclusions)\n\nThis makes sense in $\\textbf{Sets}$, but doesn't make sense in arbitrary categories because image of morphism may fail, e.g. $\\text{Mor}(\\mathcal{C}(G))$ are elements in $\\text{Hom}(*,*) =G$, not functions. \n\nCategorically, object $S$ is (equivalent to) retract of object $M$, $S,M \\in \\text{Obj}\\mathbf{C}$, if $\\exists \\, $ morphisms $i,p\\in \\text{Mor}(\\mathbf{C})$, s.t. \n\\[\n\\begin{aligned}\n& i: S\\to M \\\\\n& p:M \\to S \n\\end{aligned}\n\\]\ns.t. $pi=1_S$, $(ip)^2=ip$ (for modules, define $\\rho = ip$)\n\n\\begin{definition}[free products]\n\t\\textbf{free products} are coproducts in groups\n\\end{definition}\n\nProp. 7.26, Rotman (2010) \\cite{JRotman2010}\n\\begin{proposition}[7.26, Rotman]\n\tIf $A,B$ are $R$-modules, \\\\\n\tthen their coproducts in ${}_R\\textbf{Mod}$ exists, and it's the direct sum $C= A\\coprod B$. \n\\end{proposition}\n\n\\begin{proof}\n\tDefine \n\t\\[\n\t\\begin{gathered}\n\t\\begin{aligned}\n\t& \\mu : A \\to C \\\\\n\t& \\mu : a \\mapsto (a,c)\n\t\\end{aligned}\n\t\\qquad \\, \n\t\\begin{aligned}\n\t& \\nu : B \\to C \\\\\n\t& \\nu : b \\mapsto (0,b)\n\t\\end{aligned} \\qquad \\, \\text{ (Rotman's notation) } \\begin{aligned}\n\t& \\alpha : A \\to C \\\\\n\t& \\beta : B\\to C \n\t\\end{aligned}\n\t\\end{gathered}\n\t\\]\n\tLet $X$ be a module, $f:A\\to X$, $g:B\\to X$ homomorphisms\n\\end{proof}\n\nDefine \n\\[\n\\begin{aligned}\n& \\theta : C \\to X \\\\ \n& \\theta: (a,b) \\mapsto f(a) + g(b)\n\\end{aligned}\n\\]\n\\[\n\\begin{aligned}\n& \\theta \\mu (a) = \\theta(a,0) = f(a) \\\\ \n& \\theta\\nu (b) = \\theta(0,b) = g(b)\n\\end{aligned}\n\\]\nso diagram commutes, i.e. \n\n\\[\n\\begin{gathered}\n\\begin{tikzpicture}\n\\matrix (m) [matrix of math nodes, row sep=5em, column sep=4em, minimum width=3em]\n{\n\t& X & \\\\ \n\tA & C & B \\\\\n};\n\\path[->]\n(m-2-1) edge node [above] {$f$} (m-1-2)\nedge node [above] {$\\mu$} (m-2-2)\n(m-2-3) edge node [above] {$g$} (m-1-2)\nedge node [above] {$\\nu$} (m-2-2)\n;\n\\path[dashed,->]\n(m-2-2) edge node [right] {$\\theta$} (m-1-2)\n;\n\\end{tikzpicture} \n\\end{gathered}\n\\]\n\nIf $\\psi: C\\to X$ makes diagram commute, \n\\[\n\\begin{aligned}\n& \\psi((a,0)) = f(a) \\qquad \\, \\forall \\, a\\in A \\\\\n& \\psi((0,b)) = g(b) \\qquad \\, \\forall \\, b\\in B \\\\\n\\end{aligned}\n\\]\nand since $\\psi$ is a homomorphism, $\\psi((a,b)) = \\psi((a,0)) + \\psi((0,b)) = f(a) + g(b) = \\theta((a,b))$. $\\psi = \\theta$. \n\nProp. 7.27, Rotman (2010) \\cite{JRotman2010}\n\\begin{proposition}[7.27, Rotman]\n\tIf category $\\mathcal{C} = \\mathbf{C}$, and if $A,B \\in \\text{Obj}\\mathbf{C}$, then $\\forall \\, $ 2 coproducts of $A,B$, if they $\\exists \\, $, are equivalent. \n\\end{proposition}\n\\begin{proof}\n\tSuppose $C,D$ coproducts of $A,B$. Suppose coproducts $\\begin{aligned} & \\quad \\\\ \n\t& \\mu_A : A \\to C , \\qquad \\, & \\nu_A: A\\to D \\\\\n\t& \\mu_B : B \\to C , \\qquad \\, & \\nu_B : B \\to D \\end{aligned}$ \n\t\\[\n\t\\begin{gathered}\n\t\\begin{tikzpicture}\n\t\\matrix (m) [matrix of math nodes, row sep=5em, column sep=4em, minimum width=3em]\n\t{\n\t\t& D & \\\\ \n\t\tA & C & B \\\\\n\t};\n\t\\path[->]\n\t(m-2-1) edge node [above] {$\\nu_A$} (m-1-2)\n\tedge node [above] {$\\mu_A$} (m-2-2)\n\t(m-2-3) edge node [above] {$\\nu_B$} (m-1-2)\n\tedge node [above] {$\\mu_B$} (m-2-2)\n\t;\n\t\\path[dashed,->]\n\t(m-2-2) edge node [right] {$\\theta$} (m-1-2)\n\t;\n\t\\end{tikzpicture} \n\t\\end{gathered}\n\t\\]\n\tJust substitute $X=D$ in diagram above. \n\t\n\tThen substitute again: \n\t\\[\n\t\\begin{gathered}\n\t\\begin{tikzpicture}\n\t\\matrix (m) [matrix of math nodes, row sep=5em, column sep=4em, minimum width=3em]\n\t{\n\t\t& C & \\\\ \n\t\tA & D & B \\\\\n\t};\n\t\\path[->]\n\t(m-2-1) edge node [above] {$\\mu_A$} (m-1-2)\n\tedge node [above] {$\\nu_A$} (m-2-2)\n\t(m-2-3) edge node [above] {$\\mu_B$} (m-1-2)\n\tedge node [above] {$\\nu_B$} (m-2-2)\n\t;\n\t\\path[dashed,->]\n\t(m-2-2) edge node [right] {$\\psi$} (m-1-2)\n\t;\n\t\\end{tikzpicture} \n\t\\end{gathered}\n\t\\]\n\tThen combine the 2 diagrams: $\\psi \\theta = 1_C$. Likewise by label symmetry of $C,D$, $\\theta \\psi = 1_D$. \n\t\n\tThen $C,D$ are equivalent. \n\\end{proof}\n\n\nExer. 7.29 on pp. 459 of Rotman (2010) \\cite{JRotman2010}\n\n\\begin{definition}\n\tIf $A,B\\in \\text{Obj}\\mathbf{C}$, then their \\textbf{product}; $A\\prod B = P \\in \\text{Obj}\\mathbf{C}$, and morphisms $\\begin{aligned} & \\quad \\\\ \n\t& p : P \\to A \\\\ \n\t& q : P \\to B \\end{aligned}$ s.t. $\\forall \\, X \\in \\text{Obj}\\mathbf{C}$, \\, $\\forall \\, \\begin{aligned} & \\quad \\\\ \n\t& f : X \\to A \\in \\text{Mor}\\mathbf{C} \\\\ \n\t& g : X \\to B \\in \\text{Mor}\\mathbf{C} \\end{aligned}$, \\\\\n\t$\\exists \\, ! \\, \\theta:X \\to P$, s.t. \n\t\n\t\\[\n\t\\begin{gathered}\n\t\\begin{tikzpicture}\n\t\\matrix (m) [matrix of math nodes, row sep=5em, column sep=4em, minimum width=3em]\n\t{\n\t\t& X & \\\\ \n\t\tA & A \\prod B & B \\\\\n\t};\n\t\\path[->]\n\t(m-1-2) edge node [above] {$f$} (m-2-1)\n\tedge node [above] {$g$} (m-2-3)\n\t(m-2-2) edge node [above] {$p$} (m-2-1)\n\tedge node [above] {$q$} (m-2-3)\n\t;\n\t\\path[dashed,->]\n\t(m-1-2) edge node [right] {$\\theta$} (m-2-2)\n\t;\n\t\\end{tikzpicture} \n\t\\end{gathered}\n\t\\]\n\t\n\tIn the notation of Kashiwara and Schapira (2006) \\cite{KaSch2006}, \n\t\\[\n\t\\begin{gathered}\n\t\\begin{tikzpicture}\n\t\\matrix (m) [matrix of math nodes, row sep=5em, column sep=4em, minimum width=3em]\n\t{\n\t\t& Y & \\\\ \n\t\tX_0 & X_0 \\prod X_1 & X_1 \\\\\n\t};\n\t\\path[->]\n\t(m-1-2) edge node [above] {$f_0$} (m-2-1)\n\tedge node [above] {$f_1$} (m-2-3)\n\t(m-2-2) edge node [above] {$p_0$} (m-2-1)\n\tedge node [above] {$p_1$} (m-2-3)\n\t;\n\t\\path[dashed,->]\n\t(m-1-2) edge node [right] {$[f_0f_1]$} (m-2-2)\n\t;\n\t\\end{tikzpicture} \n\t\\end{gathered}\n\t\\]\n\tIn general\n\t\\[\n\t\\begin{gathered}\n\t\\begin{tikzpicture}\n\t\\matrix (m) [matrix of math nodes, row sep=5em, column sep=4em, minimum width=3em]\n\t{\n\t\t& Y \\\\ \n\t\tX_j & \\prod_{i\\in I} X_i \\\\\n\t};\n\t\\path[->]\n\t(m-1-2) edge node [above] {$f_j$} (m-2-1)\n\t(m-2-2) edge node [below] {$p_i$} (m-2-1)\n\t;\n\t\\path[dashed,->]\n\t(m-1-2) edge node [right] {$[f_i]_{i\\in I}$} (m-2-2)\n\t;\n\t\\end{tikzpicture} \n\t\\end{gathered}\n\t\\]\n\t\n\t\\textbf{product} of $X_i$'s, \n\t\\[ \n\t\\prod_i X_i \\equiv \\prod_{i\\in I} X_i\n\t\\]\n\tgiven by \n\t\\begin{equation}\n\t\\prod_i X_i := \\lim_{ \\longleftarrow } \\alpha \n\t\\end{equation}\n\t\n\tWhen $X_i = X$, $\\forall \\, i \\in I$, denote product by $X^{ \\prod I} \\equiv X^I$. \t\n\\end{definition}\n\ne.g. Cartesian product $P= A\\times B$ of 2 sets $A,B$, $A,B \\in \\text{Obj}\\textbf{Sets}$. \n\nDefine \t\n\\[\n\\begin{gathered}\n\\begin{aligned}\n& p:A\\times B \\to A \\\\\n& p(a,b) \\mapsto a \n\\end{aligned} \\qquad \\, \n\\begin{aligned}\n& q:A\\times B \\to B \\\\\n& q(a,b) \\mapsto b \n\\end{aligned}\n\\end{gathered}\n\\]\nIf $X \\in \\text{Obj}\\textbf{Sets}$, \\\\\nif \n$\t\\begin{aligned} & \\quad \\\\ \n& f: X \\to A \\\\\n& g : X \\to B \n\\end{aligned}\n$, then $\\begin{aligned} & \\quad \\\\ \n& \\theta: X \\to A\\times B \\\\\n& \\theta : x \\mapsto (f(x),g(x)) \\in A\\times B\n\\end{aligned}\n$\n\n\\begin{proposition}[7.28 Rotman (2010); equivalence of products, if it exists]\n\tIf $A,B \\in \\text{Obj}\\mathbf{C}$, then $\\forall \\, $ 2 products of $A$ and $B$, should they exist, are equivalent. \n\\end{proposition}\n\n\\begin{proof}\n\tSuppose $C,D$ products of $A,B$. Suppose products $\\begin{aligned} & \\quad \\\\ \n\t& p_A : C \\to A , \\qquad \\, & q_A: D\\to A \\\\\n\t& p_B : C \\to B , \\qquad \\, & q_B : D \\to B \\end{aligned}$ \n\t\\[\n\t\\begin{gathered}\n\t\\begin{tikzpicture}\n\t\\matrix (m) [matrix of math nodes, row sep=5em, column sep=4em, minimum width=3em]\n\t{\n\t\t& D & \\\\ \n\t\tA & C & B \\\\\n\t};\n\t\\path[->]\n\t(m-1-2) edge node [above] {$q_A$} (m-2-1)\n\tedge node [above] {$q_B$} (m-2-3)\n\t(m-2-2) edge node [above] {$p_A$} (m-2-1)\n\tedge node [above] {$p_B$} (m-2-3)\n\t;\n\t\\path[dashed,->]\n\t(m-1-2) edge node [right] {$\\theta$} (m-2-2)\n\t;\n\t\\end{tikzpicture} \n\t\\end{gathered}\n\t\\]\n\tJust substitute $X=D$ in diagram above. \n\t\n\tThen substitute again: \n\t\\[\n\t\\begin{gathered}\n\t\\begin{tikzpicture}\n\t\\matrix (m) [matrix of math nodes, row sep=5em, column sep=4em, minimum width=3em]\n\t{\n\t\t& C & \\\\ \n\t\tA & D & B \\\\\n\t};\n\t\\path[-{>[scale=3.0]}]\n\t(m-1-2) edge node [above] {$p_A$} (m-2-1)\n\tedge node [above] {$p_B$} (m-2-3) \n\t(m-2-2) edge node [above] {$q_A$} (m-2-1)\n\tedge node [above] {$q_B$} (m-2-3)\n\t;\n\t\\path[dashed,->]\n\t(m-1-2) edge node [right] {$\\psi$} (m-2-2)\n\t;\n\t\\end{tikzpicture} \n\t\\end{gathered}\n\t\\]\n\tThen combine the 2 diagrams: $\\psi \\theta = 1_C$. Likewise by label symmetry of $C,D$, $\\theta \\psi = 1_D$. \n\t\n\tThen $C,D$ are equivalent. \n\t\n\t\n\\end{proof}\n\n\\subsubsection{Products of Modules and Sets} \n\n\\begin{proposition}[7.29 Rotman (2010); products of R-modules are equivalent]\n\tIf commutative ring $R$, \\\\\n\tR-modules $A,B$, \\\\\n\tthen $\\exists \\, $ their (categorical) product $A\\sqcup B$, in fact \n\t\\begin{equation}\n\tA \\sqcap B \\cong A\\sqcup B\n\t\\end{equation}\n\t\n\\end{proposition}\n\n\\begin{proof}\n\tIf $A\\sqcup B \\cong M$, then \n\t$\\exists \\, $ R-maps, $\\begin{aligned} & \\quad \\\\\n\t& i : S\\to M \\\\ \n\t& j : T \\to M \\end{aligned}$, \\qquad \\, $\\begin{aligned} & \\quad \\\\\n\t& p : M\\to S \\\\ \n\t& q : M \\to T \\end{aligned}$\n\ts.t. $\\begin{aligned} & \\quad \\\\\n\t& pi = 1_A \\\\ \n\t& qj = 1_B \\end{aligned}$ \\qquad \\, and $\\begin{aligned} & \\quad \\\\\n\t& pj = 0 \\\\ \n\t& qi = 0 \\end{aligned}$, and $ip + jq = 1_M$, i.e. \n\t\n\t\\begin{tikzpicture}\n\t\\matrix (m) [matrix of math nodes, row sep=5em, column sep=4em, minimum width=3em]\n\t{\n\t\tA & M & B \\\\ \n\t};\n\t\\path[->]\n\t($(m-1-2)+(0,-0.1)$) edge node [below] {$p$} ($(m-1-1.east)+(0,-0.1)$)\n\tedge node [below] {$q$} ($(m-1-3.west)+(0,-0.1)$) \n\t($(m-1-1)+(0,0.1)$) edge node [above] {$i$} ($(m-1-2.west)+(0,0.1)$)\n\t($(m-1-3)+(0,0.1)$) edge node [above] {$j$} ($(m-1-2.east)+(0,0.1)$)\n\t;\n\t\\end{tikzpicture} \n\t\n\tIf module $X$, since $\\begin{aligned}\n\t& \\quad \\\\ \n\t& f: X \\to A \\\\\n\t& g:X\\to B\n\t\\end{aligned}\t$ \n\tare homomorphisms, \n\t\n\tdefine \n\t$\\begin{aligned}\n\t& \\theta: X \\to A \\sqcup B \\\\\n\t& \\theta(x) = if(x) + jg(x)\n\t\\end{aligned}\n\t$\n\tso that \n\t\\[\n\t\\begin{tikzpicture}\n\t\\matrix (m) [matrix of math nodes, row sep=5em, column sep=4em, minimum width=3em]\n\t{\n\t\t& X & \\\\ \n\t\tA & A\\sqcup & B \\\\\n\t};\n\t\\path[-{>[scale=4.0]}]\n\t(m-1-2) edge node [above] {$f$} (m-2-1)\n\tedge node [above] {$g$} (m-2-3) \n\t(m-2-2) edge node [above] {$p$} (m-2-1)\n\tedge node [above] {$q$} (m-2-3)\n\t;\n\t\\path[dashed,->]\n\t(m-1-2) edge node [right] {$\\theta$} (m-2-2)\n\t;\n\t\\end{tikzpicture} \n\t\\]\n\tsince, $\\forall \\, x \\in X$, \n\t\\[\n\tp\\theta(x) = pif(x) + pjg(x) = pif(x) + 0 = f(x)\n\t\\]\n\tsince $ip + jq=1_{A\\sqcup B}$ \n\t\n\t\\[\n\t\\psi = ip\\psi + jq \\psi = i f + jf = \\theta\n\t\\]\n\tso product is unique. \n\\end{proof}\n\n\\begin{definition}\n\tLet $R$ be commutative ring, \\\\\n\tlet $\\lbrace A_i : i \\in I \\rbrace$ be indexed family of $R$-modules. \n\t\n\t\\textbf{direct product} $\\prod_{i\\in I} A_i$ is cartesian product (i.e. set of all $I$-tuples $(a_i)$ whose $i$th coordinate $a_i$ lies in $A_i \\quad \\, \\forall \\, i$) with coordinate wise addition and scalar multiplication: \n\t\\[\n\t\\begin{gathered}\n\t(a_i) + (b_i) = (a_i + b_i) \\\\\n\tr(a_i) = (ra_i)\n\t\\end{gathered}\n\t\\]\n\twhere $r\\in R$, $a_i, b_i \\in A_i$, \\, $\\forall \\, i $ \n\\end{definition}\n\n\n\n\ncf. Thm. 7.32 of Rotman (2010) \\cite{JRotman2010}\n\\begin{theorem}[7.32, Rotman]\n\tLet commutative ring $R$. \\\\\n\t$\\forall \\, R$-module $A$, $\\forall \\,$ family $\\lbrace B_i | i \\in I \\rbrace$ of $R$-modules,\n\t\\begin{equation}\n\t\\begin{gathered}\n\t\\text{Hom}_R(A, \\coprod_{i\\in I} B_i ) \\simeq \\coprod_{i \\in I} \\text{Hom}_R(A,B_i)\n\t\\end{gathered}\n\t\\end{equation}\n\tvia $R$-isomorphism\n\t\\[\n\t\\varphi : f\\mapsto (p_if)\n\t\\]\n\twhere $p_i $ are projections of product $\\coprod_{i\\in I }B_i$\n\\end{theorem}\n\n\\begin{proof}\n\tLet $a\\in A$, $f,g \\in \\text{Hom}_R(A,\\coprod_{i\\in I} B_i)$.\n\t\\[\n\t\\varphi(f+g)(a) = (p_i(f+g))(a) = (p_i(f(a) + g(a))) = (p_if + p_ig)(a)\n\t\\]\n\t$\\varphi$ additive.\n\t\n\t$\\forall \\, i, \\, \\forall \\, r \\in R$, $p_i rf = rp_i f$ (since product of $R$-modules, $\\coprod_{i\\in I}B_i$ is also an $R$-module of $\\text{Obj}{}_R\\textbf{Mod}$, by def. of product).\n\t\\[\n\t\\varphi rf \\mapsto (p_i rf) = (r p_i f) = r(p_i f) = r\\varphi(f)\n\t\\]\n\tSo $\\varphi$ is $R$-map.\n\t\n\tIf $(f_i) \\in \\coprod_i \\text{Hom}{}_R(A,B_i)$, then $f_i : A\\to B_i$ \\, $\\forall \\, i$\n\t\n\tBy Rotman's Prop. 7.31 (If family of $R$-modules $\\lbrace A_i | i \\in I \\rbrace$, then direct product $C = \\coprod_{i\\in I} A_i$ is their product in ${}_R \\textbf{Mod}$), \\\\\n\t\\phantom{ \\qquad \\, } By def. or product, $\\exists \\, ! \\, R$-map , \\, $\\theta : A \\to \\coprod_{i\\in I} B_i$ s.t. $p_i \\theta = f_i$ \\, $\\forall \\, i$\n\t\n\t\\[\n\t\\begin{gathered}\n\t\\begin{tikzpicture}\n\t\\matrix (m) [matrix of math nodes, row sep=5em, column sep=4em, minimum width=3em]\n\t{\n\t\t& A \\\\ \n\t\tB_i & \\prod_{i\\in I} B_i \\\\\n\t};\n\t\\path[->]\n\t(m-1-2) edge node [above] {$f_i$} (m-2-1)\n\t(m-2-2) edge node [below] {$p_i$} (m-2-1)\n\t;\n\t\\path[dashed,->]\n\t(m-1-2) edge node [right] {$\\theta$} (m-2-2)\n\t;\n\t\\end{tikzpicture} \n\t\\end{gathered}\n\t\\]\n\t\n\t\n\t\n\t\n\tThen \n\t\\[\n\tf_i = (p_i\\theta) = \\varphi(\\theta)\n\t\\]\n\t, and so $\\varphi$ \\emph{surjective}.\n\t\n\tSuppose $f\\in \\text{ker}\\varphi$, so $\\theta = \\varphi(f) = (p_if)$. Thus $p_i f=0$ \\, $\\forall \\, i$\n\t\n\t\\[\n\t\\begin{gathered}\n\t\\begin{tikzpicture}\n\t\\matrix (m) [matrix of math nodes, row sep=5em, column sep=4em, minimum width=3em]\n\t{\n\t\t& A \\\\ \n\t\tB_i & \\prod_{i\\in I} B_i \\\\\n\t};\n\t\\path[->]\n\t(m-1-2) edge node [above] {$0$} (m-2-1)\n\tedge node [right] {$f$} (m-2-2)\n\t(m-2-2) edge node [below] {$p_i$} (m-2-1)\n\t;\n\t\\end{tikzpicture} \n\t\\end{gathered}\n\t\\]\n\t\n\tBut $0$-homomorphism also makes this diagram commute, so uniqueness of homomorphism $A \\to \\prod B_i$ gives $f=0$. \n\t\n\t\n\t\n\t\n\\end{proof}\n\n\n\n%--------------------------------------------------------------------------------\n% END of 20180202 \n%-------------------------------------------------------------------------------\n\n\\section{Applications of Category Theory: Finite State Machines (FSM)}\n\n\\begin{definition}[Finite State Machines $\\equiv$ Finite State Automaton]\n\tA deterministic finite state machine or acceptor deterministic finite state machine is a quintuple ($\\Sigma, S, s_0, \\delta F$) where \\\\\n\t$\\Sigma \\equiv $ input alphabet (finite, non-empty set of symbols) \\\\\n \t$S \\equiv $ finite, non-empty set of states \\\\\n \t$s_0 \\equiv $ initial state, $s_0 \\in S$ \\\\\n \t$\\delta \\equiv $ state-transition function; $\\delta : S \\times \\Sigma \\to S$ (in a nondeterministic finite automaton, it would be $\\delta : S \\times \\Sigma \\to \\mathcal{P}(S)$), i.e. $\\delta$ would return a set of states; $\\mathcal{P}(S) \\equiv $ set of all subsets of $S$, including $\\emptyset$ and $S \\equiv$ power set. \\\\\n \t$F \\equiv $ set of final states, (possibly empty subset of $S$; $F\\subseteq S$ or $F \\subseteq S \\cup \\lbrace \\emptyset \\rbrace$)\n\n\tFinite State Machine (FSM) is also known as a Finite State Automaton.\n\\end{definition}\ncf. \\href{https://xlinux.nist.gov/dads/HTML/finiteStateMachine.html}{Black, Paul E (12 May 2008). \"Finite State Machine\". \\emph{Dictionary of Algorithms and Data Structres}}. U.S. National Institute of Standards and Technology (NIST).\n\nFor both deterministic and non-deterministic FSMs, it's conventional to allow $\\delta$ to be a partial function, i.e. \n$\\delta(q,x)$ doesn't have to be defined for every combination of $q \\in S$, $x \\in \\Sigma$\n\nIf FSM $M$ is in state $q$; the next symbol (input?) is $x$ and $\\delta(q,x)$ not defined; then $M$ can announce an error (i.e. reject the input (???)). \n\n\n\\begin{definition}[Alphabet]\n\talphabet $:= $ nonempty set of symbols $\\equiv \\Sigma$ \\\\\n\tstring $:=$ finite sequence of members (i.e. symbols) of an underlying base set (i.e. \\textbf{alphabet}) \\\\\n\t$\\Sigma^n \\equiv $ set of all strings of length $n$.\n\\end{definition}\n\nIn Curino and Spivak (2011)\\cite{SpCu2011}, on pp. 6, Sec. 4.2 \"A new concept of state transformations\", they say that \"Legend has it that Eilenberg and MacLane spent the effort to invent category theory because they needed to formalize the concept now known as natural transformation.\" \n\nIt goes and says \"The definition of natural transformations between states naturally captures much of the semantics for what remains unchanged when performing an update.\"\n\n\n\n\\part{Category Theory}\n\n\\section{Note on notation}\n\nFrom the section on ``Terminology'' of the Preface of Barr and Wells (1998) \\cite{BW1998}:\n\n\\begin{quote}\n\t``In most scientific disciplines, notation and terminology are standardized, of- ten by an international nomenclature committee. (Would you recognize Einstein’s equation if it said $p = HU^2$?) We must warn the nonmathematician reader that such is not the case in mathematics. There is no standardization body and terminology and notation are individual and often idiosyncratic.''\n\\end{quote}\n\nTo try to bridge the difference choice of notation and through comparison, suggest the ``best'' notation that's easy to remember and easy to use, I'll present all the different types of notation that I come across as much as I can. My plan of attack is the following:\n\\begin{enumerate}\n\t\\item I'll try to present different types of notation and reference the authors of the text when I can.\n\t\\item I'll try to defer to the notation used in Wikipedia, first.\n\t\\item I'll make a final decision of what notation works best (for me).\n\\end{enumerate}\n\n\\section{Category $\\mathbf{A}$, (definition)}\n\n\\begin{definition}[Category $\\mathbf{A}$]\n\\textbf{category} $\\mathbf{A}$ is quadruple $\\mathbf{A} = (\\text{Obj}(\\mathbf{A}), \\text{Mor}\\mathbf{A}, 1,\\circ)$ \n\\begin{equation}\n\\mathbf{A} = (\\text{Obj}(\\mathbf{A}), \\text{Mor}\\mathbf{A}, 1,\\circ)\n\\end{equation}\ns.t.\n\\begin{enumerate}\n\t\\item $\\text{Obj}{(\\mathbf{A})}$ is a \\emph{class}, whose elements, $A \\in \\text{Obj}(\\mathbf{A})$, are called \\emph{objects}\n\t\\item $\\text{Mor}\\mathbf{A}$ is a \\emph{class}.\n\t\\begin{enumerate}\n\t\t\\item From Ad\\'{a}mek, Herrlich, and Strecker (2004) \\cite{AHS2004}, Kashiwara and Schapira (2006) \\cite{KaSch2006}, \\\\\n\t\t$\\forall \\, A, B \\in \\text{Obj}(\\mathbf{A})$, $\\exists \\, \\text{Hom}(A,B) \\subseteq \\text{Mor}(\\mathbf{A})$. Therefore, \n\t\t\\begin{equation}\n\t\t\\text{Mor}\\mathbf{A} = \\bigcup_{ A,B \\in \\text{Obj}(\\mathbf{A}) } \\text{Hom}(A,B)\n\t\t\\end{equation}\n\t\t\\item $\\forall \\, f \\in \\text{Hom}(A,B)$, $f: A \\to B \\in \\text{Hom}(A,B)$ is a \\emph{morphism}. Leinster (2014) \\cite{Lein2014} also calls them on pp. 10 \\textbf{maps} or \\textbf{arrow} from $A$ to $B$.\n\t\\[\n\\begin{tikzpicture}\n\\matrix (m) [matrix of math nodes, row sep=3em, column sep=4em, minimum width=2em]\n{\n\tA & B \\\\\n};\n\\path[->]\n(m-1-1) edge node [above] {$f$} (m-1-2)\n;\n\\end{tikzpicture}\n\\]\n\t\\end{enumerate}\n\t\\item $\\forall \\, A \\in \\text{Obj}(\\mathbf{A})$, $\\exists \\, 1_A : A \\to A$, i.e. $\\exists \\, \\mathbf{1}_A \\in \\text{Hom}_{\\mathbf{A}}(A,A) \\equiv \\text{Hom}(A,A)$, \n\t\\[\n\t\\begin{tikzpicture}\n\t\\matrix (m) [matrix of math nodes, row sep=3em, column sep=4em, minimum width=2em]\n\t{\n\t\tA & A \\\\\n\t};\n\t\\path[->]\n\t(m-1-1) edge node [above] {$1_A$} (m-1-2)\n\t;\n\t\\end{tikzpicture} \\text{ or } \\begin{tikzpicture}\n\t\\matrix (m) [matrix of math nodes, row sep=3em, column sep=4em, minimum width=2em]\n\t{\n\t\tA \\\\\n\t};\n\t\\path[->]\n\t(m-1-1) edge [loop left] node [above] {$\\mathbf{1}_A$} (m-1-1)\n\t;\n\t\\end{tikzpicture}\n\t\\]\n\t\\item \\textbf{composition:} \n\t$\\forall \\, A,B,C \\in \\text{Obj}\\mathbf{A}$, define \\textbf{composition} to be a map\n\t\\begin{equation}\n\t\\begin{aligned}\n\t\t\\text{Hom}_{\\mathbf{A}}(A, B) \\times \\text{Hom}_{\\mathbf{A}}(B, C) & \\to \\text{Hom}_{\\mathbf{A}}(A, C) \\\\\n\t\t (f, g) & \\mapsto g\\circ f\n \t\\end{aligned}\n\\end{equation}, i.e.\n\t\n\t$\\forall \\, \\begin{aligned} & \\quad \\\\\n\t& f: A \\to B \\in \\text{Hom}(A,B) \\\\\n\t& g:B\\to C \\in \\text{Hom}(B,C) \\end{aligned}$, i.e. $f,g \\in \\text{Mor}\\mathbf{A}$, \\\\\n\tthen $g\\circ f : A \\to C \\in \\text{Hom}(A,C)$, $g\\circ f \\in \\text{Mor}\\mathbf{A}$ i.e. \n\t\\[\n\t\\begin{tikzpicture}\n\t\\matrix (m) [matrix of math nodes, row sep=3em, column sep=4em, minimum width=2em]\n\t{\n\t\tA & B & C \\\\\n\t};\n\t\\path[->]\n\t(m-1-1) edge node [above] {$f$} (m-1-2)\n\t(m-1-2) edge node [above] {$g$} (m-1-3)\n\t(m-1-1) edge [bend right=30] node [below] {$g\\circ f$} (m-1-3) \n\t;\n\t\\end{tikzpicture}\n\t\\]\n\ts.t. \n\t\\begin{enumerate}\n\t\t\\item \\emph{associativity} $\\forall \\, \\begin{aligned} & \\quad \\\\\n\t\t& f: A \\to B \\\\\n\t\t& g: B \\to C \\\\\n\t\t& h: C \\to D \\end{aligned}$, $h\\circ (g\\circ f) = (h\\circ g) \\circ f $ i.e.\n\t\t\n\t\t\\[\n\t\t\\begin{tikzpicture}\n\t\t\\matrix (m) [matrix of math nodes, row sep=3em, column sep=4em, minimum width=2em]\n\t\t{\n\t\t\tA & B & C & D \\\\\n\t\t};\n\t\t\\path[->]\n\t\t(m-1-1) edge node [above] {$f$} (m-1-2)\n\t\t(m-1-2) edge node [above] {$g$} (m-1-3)\n\t\t(m-1-3) edge node [above] {$h$} (m-1-4)\n\t\t(m-1-1) edge [bend right=30] node [below] {$g\\circ f$} (m-1-3) \n\t\t(m-1-2) edge [bend left=30] node [above] {$h\\circ g$} (m-1-4) \n\t\t;\n\t\t\\path[-{>[scale=1.15]}, line width=0.5pt]\n\t\t(m-1-1) edge [bend left=45] node [above] {$(h \\circ g)\\circ f$} (m-1-4)\n\t\tedge [bend right=45] node [below] {$h \\circ (g\\circ f)$} (m-1-4);\n\t\t\\end{tikzpicture}\n\t\t\\]\n\t\t\n\t\t\\item $\\forall \\, f:A \\to B \\in \\text{Hom}(A,B)$, $1_B \\circ f = f $ and $f\\circ 1_A = f$ i.e.\n\t\t\n\t\t$\\forall \\, f \\in \\text{Hom}_{\\mathbf{A}}(A,B)$,\n\t\t\\[\n\t\t\\begin{tikzpicture}\n\t\t\\matrix (m) [matrix of math nodes, row sep=3em, column sep=4em, minimum width=2em]\n\t\t{\n\t\t\tA & B \\\\\n\t\t};\n\t\t\\path[->]\n\t\t(m-1-1) edge node [above] {$f$} (m-1-2)\n\t\tedge [loop left] node [left] {$1_A$} (m-1-1)\n\t\t(m-1-2) edge [loop right] node [right] {$1_B$} (m-1-2)\n\t\t;\n\t\t\\end{tikzpicture}\n\t\t\\]\n\t\t\\item Ad\\'{a}mek, Herrlich, and Strecker (2004) \\cite{AHS2004} posited further that $\\text{Hom}(A,B) \\in \\text{Mor}\\mathbf{A}$ pairwise disjoint (i.e. $\\text{Hom}(A,B) \\bigcap \\text{Hom}(C,D) \\neq \\emptyset$ if $C\\neq A$ or $D\\neq B$)\n\t\\end{enumerate}\n\\end{enumerate}\t\n\\end{definition}\n\n\\subsection{Examples of categories}\n\n\\begin{itemize}\n\t\\item $\\textbf{Set} = (\\text{Obj}{(\\textbf{Set})}, \\text{Hom}{\\textbf{Set}},\\mathbf{1},\\circ)$ where \\\\\n\t$\\text{Obj}{(\\textbf{Set})}$ is the class of all sets \\\\\n\t$\\text{Hom}{\\textbf{Set}}$ is the class of all functions on a set to another set\n\t\\item $\\textbf{Vec}$\n\t\n\t\\[\n\t\\begin{aligned}\n\t& \\text{Obj}\\textbf{Vec} & \\equiv \\text{ all real vector spaces } \\\\ \n\t& \\text{Mor}\\textbf{Vec} & \\equiv \\text{ all linear transformations between them (between real vector spaces) }\n\t\\end{aligned}\n\t\\]\n\t\\item \\emph{preorder} cf. Ch. 1, Example 7, pp. 8, Awodey (2010) \\cite{Awod2010}. \\\\\n\t\\emph{preorder} $P$, set $P$ equipped with binary relation $p\\leq q $, that's both \\\\\n\treflexive: $a\\leq a$, and \\\\\n\ttransitive: if $a \\leq b$ and $b \\leq c$, then $a\\leq c$. \n\t\n\t\\quad \\\\\n\t$\\forall \\, $ preorder $P$ can be regarded as a category: \\\\\n\t$\\text{Obj}(P) = P$ \\\\\n\t$a \\to b$ iff $a\\leq b \\in \\text{Mor}P$. \\\\\n\tidentity: $1 :a \\to a$ since $a\\leq a$ \\\\\n\tcomposition: $f:a\\to b$, $g:b\\to c$, $(g\\circ f)a = g(b) = c$, $a\\leq b$ and $b\\leq c$, so $a\\leq c$. \n\t\n\tGoing in the other direction, a category with at most 1 arrow between 2 objects determines a preorder.\n\t\\item \\textbf{Monoid}. Consider a monoid as a triple $(M, \\cdot, e)$. \\\\\n\tEvery semigroup $(M,\\cdot)$ (recall that a \\emph{semigroup} is a set $S$ with binary operation $\\cdot $, i.e. s.t.\n\t\n\t\\quad \\, $\\begin{aligned} & \\quad \\\\\n\t& S\\times S \\xrightarrow{\\cdot } S \\\\ \n\t& \\forall \\, a,b ,c \\in S, \\, (a\\cdot b)\\cdot c = a\\cdot (b\\cdot c) \\quad \\, \\text{ (associativity) } \\end{aligned}$ \n\t\n\t\\quad \\, (but no inverse, necessarily!)) that also has a unit $e$ can be made into a category $\\mathbf{C}$ \n\t\n\t$\\Longrightarrow \\mathbf{C}(M,\\cdot ,e) = (\\text{Obj}(\\mathbf{C}), \\text{Hom}(\\mathbf{C}), \\mathbf{1}, \\circ)$, a category $\\mathbf{C}$ with only 1 object, i.e. $\\text{Obj}(\\mathbf{C}) = \\lbrace M \\rbrace$, so that \\\\\n\t$\\text{Obj}(\\mathbf{C}) = \\lbrace M \\rbrace$ \\\\\n\t$\\text{Hom}(M,M) = M$ \\\\\n\t$\\mathbf{1}_M = e$ \\\\\n\t$y \\circ x = y \\cdot x$\n\t\n\tcf. pp. 10, Example 12 of Awodey (2010) \\cite{Awod2010}.\n\n\\subsubsection{Monoid as a category}\n\nRecall the definition of a \\emph{category} $\\mathbf{A}$: category $\\mathbf{A} = (\\text{Obj}(\\mathbf{A}), \\text{Mor}{\\mathbf{A}}, 1, \\circ)$ s.t.\\\\\n$A \\in \\text{Obj}\\mathbf{A}$, \\\\\n$\\forall \\, A, B \\in \\text{Obj}\\mathbf{A}$, $\\exists \\, \\text{Hom}(A,B) \\subseteq \\text{Mor}\\mathbf{A}$, \\\\\n$\\forall \\, f \\in \\text{Hom}(A,B)$, $f:A \\to B$ is a morphism.\\\\\n$\\forall \\, A \\in \\text{Obj}\\mathbf{A}$, $\\exists \\, 1_A : A \\to A$, i.e. $\\exists \\, 1_A \\in \\text{Hom}_{\\mathbf{A}}(A,A)$. \\\\\n$\\forall \\, A, B, C \\in \\text{Obj}\\mathbf{A}$, \\\\\n\\[\n\\begin{aligned} \n\t& \\text{Hom}_{\\mathbf{A}}(A, B) \\times \\text{Hom}_{\\mathbf{A}}(B,C) \\to \\text{Hom}_{\\mathbf{A}}(A, C) \\\\ \n\t& (f,g) \\mapsto g\\circ f \\end{aligned} \\] \\\\\n\nRecall the definition of a \\emph{monoid}:\nmonoid $(M, \\cdot, e)$, set $M$, \\\\\n$\\cdot : M\\times M \\to M$, \\\\\n$e \\in M$ s.t. $\\forall \\, x \\in M$, $e\\cdot x = x \\cdot e = x$ \\\\\n\n$\\Longrightarrow \\mathbf{C}(M)$ (monoid as a category) \\\\\n$\\text{Obj}\\mathbf{C}(M) = \\lbrace M \\rbrace$ \\\\\n$\\text{Hom}(M, M) = \\text{Mor}\\mathbf{C}(M)$ and $\\forall \\, f \\in \\text{Hom}(M, M)$, \n\\[\nf = m \\in M\n\\]\ni.e. the morphism \\emph{is} an element in monoid $M$ (there's a 1-to-1 correspondence).\n\n$\\forall \\, n \\in M$, $f:n \\mapsto m\\cdot n \\in M$. \\\\\n$1_M : M \\to M$ \\\\\n$1_M : x \\mapsto e\\cdot x = x$ \\\\\n$m\\cdot n \\cdot x = m\\cdot (n\\cdot x) = (m\\cdot n) \\cdot x$ (composition)\n\n\n\t\n\\subsubsection{Examples of monoids}\n\tExamples of monoids: $\\mathbb{N}, \\mathbb{Q}, \\mathbb{R}$ under either addition and $e=0$, or multiplication and $e=1$. \\\\\n\t$\\forall \\, $ set $X$, set of functions from $X$ to $X$, $\\text{Hom}_{\\mathbf{Sets}}(X, X)$ is a monoid under composition. \n\t\n\tIn general, \\\\\n\t$\\forall \\, $ object $C \\in \\text{Obj}(\\mathbf{C})$, $\\forall \\, $ category $\\mathbf{C}$, $\\text{Hom}_{\\mathbf{C}}(C,C)$ is a monoid under composition of $\\mathbf{C}$. \n\t\n\tSince monoids are structured sets, $\\exists \\, $ category $\\textbf{Mon}$, s.t. $\\text{Obj}\\mathbf{Mon} \\ni $ monoids, $\\text{Mor} \\textbf{Mon} \\ni $ functions that preserve monoid structure.\n\t\n\tIn detail, homomorphism from monoid $M$ to monoid $N$ is function $h:M \\to N$ s.t. $\\forall \\, m,n \\in M$. \n\t\n\t\\[\n\th(m \\cdot_M n) = h(m) \\cdot_N h(n)\n\t\\]\n\tand\n\t\\[\n\th(e_M) = e_N\n\t\\]\n\t\n\t\\quad \\\\ \n\tCheck: Consider functor $F: M \\to N$. \\\\\n\t$F: \\text{Hom}_M(a,b) \\to \\text{Hom}_N(F(a), F(b))$\n\t\\[\n\t\\begin{gathered}\n\tm\\cdot a =b \\qquad \\, n \\cdot_N F(a) = F(b) \\\\\n\tF(m) \\cdot_N F(a) = F(b) = F(m \\cdot_M a) \n\t\\end{gathered}\n\t\\]\n\tso functor $F$ is a monoid homomorphism, and so \\\\\n\t\\emph{a monoid homomorphism from $M$ to $N$ is the same thing as a functor from $M$ regarded as a category to $N$ regarded as a category.}\n\t\\item \\textbf{Poset} cf. Ch. 1, pp. 6, Awodey (2010) \\cite{Awod2010}. partially ordered set or poset is a set $A$, equipped with binary relation $a \\leq_A b$ s.t. $\\forall \\, a, b, c \\in A$, \\\\\n\treflexivity: $a \\leq_A a$ \\\\\n\ttransitivity: if $a\\leq_A b$, $b\\leq_A c$, then $a\\leq_A c$ \\\\\n\tantisymmetry: if $a\\leq_A b$, $b\\leq_A a$, then $a=b$.\n\t\n\tAn arrow from a poset $A$ to a poset $B$ is a function,\n\t\\[\n\tm : A \\to B\n\t\\]\nthat is monotone, i.e. $\\forall \\, a, a' \\in A$, \n\\[\n\\text{ if } a \\leq_A a', \\text{ then } m(a) \\leq_B m(a')\n\\]\t\ncategory $\\textbf{Pos}$ of posets, and monotone functions, \n\\[\n\\forall \\, A \\in \\text{Obj}(\\textbf{Pos}), \\, \\exists \\, 1_A : A \\to A, \\text{ since } \n\\]\nsince if $a \\leq_A a'$, then $a\\leq_A a'$, so $1_A$ monotone.\n\n\\quad \\\\ \n\\emph{composition}: $\\forall \\, f:A \\to B, \\, g:B \\to C$, \\, $\\forall \\, A,B,C \\in \\text{Obj}(\\textbf{Pos})$, $f,g$ monotone, \\\\\n$\\forall \\, a \\leq_A a'$, $f(a) \\leq_B f(a')$, and since \\\\\n$\\forall \\, b \\leq_B b'$, $g(b) \\leq_C g(b')$, then $g(f(a)) \\leq_C g(f(a'))$, or $(g\\circ f)(a) \\leq_C (g\\circ f)(a') \\, \\forall \\, a\\leq_A a'$, so $g\\circ f : A \\to C$ is monotone.\n\n$\\text{Mor}\\textbf{Pos} = \\bigcup_{A, B \\in \\text{Obj}(\\textbf{Pos}) } \\text{ monotone functions $A \\to B$ }$ \n\n\\quad \\\\ \nA \\emph{poset} is a \\emph{preorder}, satisfying additional condition of antisymmetry:\nif $a\\leq b$, and $b\\leq a$, $a=b$. \\\\\ne.g. $\\forall \\, X$, power set $P(X)$ is a poset under inclusion $U\\subseteq V$, $\\forall \\, $ subsets $U,V \\subseteq X$.\n\n\\begin{itemize}\n\t\\item cf. Ch. 1, Example 8, pp. 9, Awodey (2010) \\cite{Awod2010}.\n\t$\\textbf{Pos}$ categories and functors: functor $F: \\mathbf{D} \\to \\mathbf{Q}$ between poset categories $\\mathbf{P}, \\mathbf{Q}$. \\\\\n\tThey are the monotone functions.\n\t\\begin{proof} \n\tConsider \n\t\\[\n\tF : \\text{Hom}_{\\mathbf{P}}(A,B) \\to \\text{Hom}_{\\mathbf{Q}}(F(A), F(B))\n\t\\]\n\t$f\\in \\text{Hom}_{\\mathbf{P}}(A,B)$ so if $a\\leq_A a'$, $f(a) \\leq_B f(a')$\n\t\n\tLet $g\\in \\text{Hom}_{\\mathbf{Q}}(F(A), F(B))$, so if $c\\leq_{F(A)} c'$, $g(c)\\leq_{F(B)} g(c')$. \\\\\n\t\n\t$F(f) \\in \\text{Hom}_{\\mathbf{Q}}(F(A), F(B))$ (by definition of a functor), so if $c\\leq_{F(A)} c'$, $F(f)(c) \\leq_{F(B)} F(f)(c')$ or $F(f(c)) \\leq_{F(B)} F(f(c'))$. \\\\\n\t\n\tSo $F$ itself is monotone.\n\t\\end{proof}\n\\end{itemize}\n\\item cf. \\emph{An example from computer science}, Example 10, pp. 9 of Awodey (2010) \\cite{Awod2010}.\nGiven a functional programming language $L$, $\\exists \\, $ associated category, \\\\\n$\\text{Obj}\\mathbf{L} \\ni $ data types of $L$ \\\\\n$\\text{Mor}\\mathbf{L} \\ni $ computable functions of $L$ (\"processes\", \"procedures\", \"programs\") \\\\\ncomposition (of 2 such programs) $X \\xrightarrow{f} Y \\xrightarrow{g} Z$ given by applying $g$ to output of $f$ \\\\\n(notation note: $g\\circ f = f; g$) \\\\\nidentity is the \"do nothing\" program. \n\n\\quad \\\\\nif $\\mathbf{C}(L)$ is the category just defined, then \\\\\ndenotational semantics of language $L$ in category $\\mathbf{D}$ of say Scott demands is simply functor\n\\[\nS:\\mathbf{C}(L) \\to \\mathbf{D} \n\\]\nsince $S$ assigns domains to the types of $L$, \\\\\ncontinuous functions to programs.\n\nThis example and Example 9, pp. 9, of Awodey (2010) \\cite{Awod2010} are related to the notion of \"Cartesian closed category.\"\n\nFrom Barr and Wells (2012) \\cite{BaWe2012}, a \\emph{functional programming language} $L$ has\n\\begin{enumerate}\n\t\\item primitive data types (built into the language) \n\t\\item constants of each type\n\t\\item operations, which are functions between types\n\t\\item constructors, which are applied to data types and operations, to produce derived data types and operations of the language.\t\n\\end{enumerate}\n\n\tFor a $\\mathbf{C}(L)$ category corresponding to functional programming language $L$, \\\\\n\t\n\t$\\mathbf{C}(L)$ category corresponding to functional programming language $L$, \\\\\n\t$\\text{Obj}\\mathbf{C}(L) = \\lbrace \\text{ types of $L$ } \\rbrace$ \\\\\n\t$\\text{Mor}\\mathbf{C}(L) = \\lbrace \\text{ operations (functions; primitive and derived) of $L$ } \\rbrace$ \\\\\n\nidentity: $\\forall \\, $ type $T \\in \\text{Obj}\\mathbf{C}(L)$, $\\exists \\, 1_T :T \\to T$ i.e. $1_T \\in \\text{Hom}(T,T)$. \\\\\n\ncomposition: $\\forall \\, $ types $T,U,V \\in \\text{Obj}\\mathbf{C}(L)$, defines composition \n\\[\n\\begin{aligned}\n\\text{Hom}(T,U) \\times \\text{Hom}(U,V) & \\to \\text{Hom}(T,V) \\\\ \n(f,g) & \\mapsto g \\circ f\n\\end{aligned}\n\\]\n\nAssume $L$ has a do nothing operation $1_T$, and composition constructor, $\\text{Hom}(T,U) \\times \\text{Hom}(U,V) \\to \\text{Hom}(T, V)$. \\\\\n\nAdd additional type $1$ s.t. $\\forall \\, $ type $T \\in \\text{Obj}\\mathbf{C}(L)$, $\\exists \\, !$ operation (function) to $1, T \\to 1$ \\\\\nInterpret each constant $c$ of type $A$ as arrow (morphism) $c:1\\to A$. \\\\\n\nAs a concrete example (cf. Example 2.2.5 of Barr and Wells (2012) \\cite{BaWe2012}), suppose a simple language with 3 data types, \\texttt{int}, \\texttt{bool}, \\texttt{char}. \\\\\n\nFor \\texttt{int}, $\\exists \\, $ constant $0:1 \\to \\texttt{int}$, consider $\\texttt{succ}:\\texttt{int} \\to \\texttt{int} \\in \\text{Hom}(\\texttt{int}, \\texttt{int})$, \\\\\nFor \\texttt{bool}, $\\exists \\, $ constants $\\texttt{true} : 1 \\to \\texttt{bool}$, $\\texttt{false} : 1 \\to \\texttt{bool}$; consider $\\neg \\in \\text{Hom}(\\texttt{bool}, \\texttt{bool})$, s.t.\n\\[\n\\begin{aligned}\n& \\neg \\circ \\texttt{true} = \\texttt{false} \\\\ \n& \\neg \\circ \\texttt{false} = \\texttt{true} \n\\end{aligned}\n\\]\n\nFor \\texttt{char}, $\\exists \\, $ constants $c:1 \\to \\texttt{char}$, \\, $\\forall \\, \\texttt{char} c$.\n\nSince $\\forall \\, T,U \\in \\text{Obj}(\\mathbf{C}(L))$, $\\exists \\, \\text{Hom}(T,U) \\subseteq \\text{Mor}\\mathbf{C}(L)$. So consider $\\texttt{ord}:\\texttt{char} \\to \\texttt{int}$, $\\texttt{chr}: \\texttt{int} \\to \\texttt{char}$, s.t. \n\\[\n\\texttt{char} \\circ \\texttt{ord} = 1_{\\texttt{char}}\n\\]\n\nSo $\\text{Obj}\\mathbf{C}(L) = \\lbrace \\texttt{int}, \\texttt{bool}, \\texttt{char}, 1 \\rbrace$, \\\\\n\\phantom{So } $\\text{Mor}\\mathbf{C}(L)$ consists of all programs.\n\nSee 5.3.14 Record Types and 5.7.6, 14.2 for flow of control in Barr and Wells (2012) \\cite{BaWe2012} to complete the programming language. For here, see section \\ref{SubSubSect:RecordTypesProduct}\n\n\\item \\textbf{Groups}, cf. pp. 11, Def. 1.4, Sec. 1.5 \\textbf{Isomorphisms}, Awodey (2010) \\cite{Awod2010}.\n\nA \\emph{group} $G$ is a monoid with inverse $g^{-1}$, $\\forall \\, g \\in G$. \\\\\nThus, $G$ is a category with 1 object, $\\forall \\, f \\in \\text{Mor}G$ is an isomorphism.\n\n$\\forall \\, $ set $X$, group $\\text{Aut}(X)$ of automoprhisms (or \"permutations\") of $X$ i.e. $f:X\\to X$ \\\\\n$\\text{Aut}(X)$ is closed under composition $\\circ$ because a permutation of a permutation is another permutation.\n\nHomomorphisms of groups $h: G\\to H$ is just a homomorphism of monoids, preserving inverses.\\\\\nGiven $h$, then $h(gg') = h(g) h(g')$. \\\\\n$G,H$ are monoids. Then $h$ monoid homomorphism.\n\\end{itemize}\n\nConcrete categories: informally, categories which objects are sets, possibly equipped with some structure, and arrows are certain, possibly structure-preserving functions.\n\nFrom pp. 10 of Mac Lane (1978) \\cite{MacL1978}, Leinster (2014) \\cite{Lein2014}, Examples 1.1.8 (Categories as mathematical structures), pp. 13, and Sec. 1.4 Examples of Categories, 5. Finite Categories, pp.7 of Awodey (2010) \\cite{Awod2010}.\n\nCategory $\\mathbf{1}$. $\\text{Obj}{\\mathbf{1}} = \\lbrace A \\rbrace$ \\\\\n$\\text{Mor}{\\mathbf{1}} = \\lbrace 1_A \\rbrace$; $1_A : A \\to A$. \\\\\n\nThe only composition to consider is $1_A \\circ 1_A : A \\to A$, and $1_A \\circ 1_A \\circ 1_A$, so on and so for.\n\nCategory $\\mathbf{2}$. $\\text{Obj}{\\mathbf{2}} = \\lbrace A, B \\rbrace$. \\\\\n$\\text{Hom}(A, B) = \\lbrace f \\rbrace$, $f:A\\to B$. \\\\\n\nThe only \"non-trivial\" composition to consider is $1_B \\circ f \\circ 1_A : A \\to B$. \\\\\n \nCategory $\\mathbf{3}$. pp. 11, Sec. 2 Categories of Mac Lane (1978) \\cite{MacL1978}, Example 5. \"Finite Categories\", Sec. 1.4, pp. 7 of Awodey (2010) \\cite{Awod2010}. \n\n$\\text{Obj}{\\mathbf{3}} = \\lbrace A, B, C \\rbrace$ \\\\\n$\\text{Hom}{(A, B)} = \\lbrace f \\rbrace$ \\\\\n$\\text{Hom}{(A, C)} = \\lbrace g \\rbrace$ \\\\\n$\\text{Hom}{(B, C)} = \\lbrace h \\rbrace$ \\\\\n$\\text{Hom}{(C, \\cdot)} = \\emptyset $ \\\\\n$\\text{Hom}{(B, A)} = \\emptyset$ \\\\\n\nThe only \"non-trivial\" compositions to consider are the following:\n$1_C \\circ h \\circ f : A \\to C$, \\\\\n$1_C \\circ g$, $1_C \\circ h$ (and likewise) \\\\\n\n\n\\subsection{Duality, opposite category}\n\nGiven a category $\\mathbf{A} = ( \\text{Ob}, \\text{hom}_{\\mathbf{A}}, 1, \\circ)$, \n\\begin{definition}[dual opposite category]\n\t\\textbf{dual} or \\textbf{opposite} category of $\\mathbf{A} = (\\text{Obj}(\\mathbf{A}), \\text{Mor}\\mathbf{A}, \\mathbf{1}, \\circ)$, denoted $\\mathbf{A}^{\\text{op}}$, is \n\t\\begin{equation}\n\t\\mathbf{A}^{\\text{op}} = (\\text{Obj}(\\mathbf{A}), \\text{Mor}\\mathbf{A}^{\\text{op}}, \\mathbf{1}, \\circ^{\\text{op}})\n\t\\end{equation}\n\ts.t.\n\\begin{itemize}\n\t\\item \n\t\\begin{equation}\n\t\\text{Obj}(\\mathbf{A}^{\\text{op}}) = \\text{Obj}(\\mathbf{A})\n\t\\end{equation}\n\t\\item $\\forall \\, A, B \\in \\text{Obj}(\\mathbf{A}^{\\text{op}})$, $\\text{Hom}_{\\mathbf{A}^{\\text{op}}}(A,B) \\subseteq \\text{Mor}\\mathbf{A}^{\\text{op}}$, \n\t\t\\begin{equation}\n\\text{Hom}_{\\mathbf{A}^{\\text{op}}}(A,B) = \\text{Hom}_{\\mathbf{A}}(B,A) \\subseteq \\text{Mor}\\mathbf{A}\n\t\t\\end{equation}\n\t\t\\item \\emph{Define} the new composition \n\t\t\\begin{equation}\n\\begin{gathered}\n\t\tf \\circ^{\\text{op}} g \\text{ of } \\begin{aligned} & \\quad \\\\\n\t\t& g \\in \\text{Hom}_{\\mathbf{A}^{\\text{op}}}(C,B) \\\\\n\t\t& f \\in \\text{Hom}_{\\mathbf{A}^{\\text{op}}}(B,A) \n\t\t\\end{aligned}\t\t \\\\\n\t\t\\text{ then } \\\\\n\t\tf \\circ^{\\text{op}} g = g\\circ f\n\\end{gathered}\n\t\t\\end{equation}\n\\[\n\\begin{tikzpicture}\n\\matrix (m) [matrix of math nodes, row sep=3em, column sep=4em, minimum width=2em]\n{\n\tA & B & C \\\\\n};\n\\path[->]\n(m-1-1) edge node [above] {$f$} (m-1-2)\n(m-1-2) edge node [above] {$g$} (m-1-3);\n\t\t\\path[-{>[scale=1.15]}, line width=0.5pt]\n(m-1-1) edge[bend right=45] node [below] {$g\\circ f$} (m-1-3);\n\\end{tikzpicture} \\qquad \\qquad \\, \\, \\text{ dual :} \\begin{tikzpicture}\n\\matrix (m) [matrix of math nodes, row sep=3em, column sep=4em, minimum width=2em]\n{\n\tA & B & C \\\\\n};\n\\path[->]\n(m-1-3) edge node [above] {$g$} (m-1-2)\n(m-1-2) edge node [above] {$f$} (m-1-1);\n\t\t\\path[-{>[scale=1.15]}, line width=0.5pt]\n(m-1-3) edge[bend left=45] node [below] {$f\\circ^{\\text{op}} g$} (m-1-1);\n\\end{tikzpicture}\n\\]\t\t\nor, equivalently (notation-wise)\n\\[\n\\begin{tikzpicture}\n\\matrix (m) [matrix of math nodes, row sep=3em, column sep=4em, minimum width=2em]\n{\n\tA & B & C \\\\\n};\n\\path[->]\n(m-1-3) edge node [above] {$g$} (m-1-2)\n(m-1-2) edge node [above] {$f$} (m-1-1);\n\t\t\\path[-{>[scale=1.15]}, line width=0.5pt]\n(m-1-3) edge[bend left=45] node [below] {$f \\circ g$} (m-1-1);\n\\end{tikzpicture}\n\\qquad \\qquad \\, \\, \\text{ dual :} \n\\begin{tikzpicture}\n\\matrix (m) [matrix of math nodes, row sep=3em, column sep=4em, minimum width=2em]\n{\n\tA & B & C \\\\\n};\n\\path[->]\n(m-1-1) edge node [above] {$f$} (m-1-2)\n(m-1-2) edge node [above] {$g$} (m-1-3);\n\t\t\\path[-{>[scale=1.15]}, line width=0.5pt]\n(m-1-1) edge[bend right=45] node [below] {$g\\circ^{\\text{op}} f$} (m-1-3);\n\\end{tikzpicture} \n\\]\t\t\nin that \n\\[\n\\begin{gathered}\ng \\circ^{\\text{op}} f \\text{ of } \\begin{aligned} & \\quad \\\\\n& f \\in \\text{Hom}_{\\mathbf{A}^{\\text{op}}}(A,B) \\\\\n& g \\in \\text{Hom}_{\\mathbf{A}^{\\text{op}}}(B,C) \n\\end{aligned}\t\t \\\\\n\\text{ then } \\\\\ng \\circ^{\\text{op}} f = f\\circ g\n\\end{gathered}\n\\]\n\\end{itemize}\n\\end{definition}\n\ni.e. (in summary) $\\mathbf{C}^{\\text{op}}$ s.t. $\\text{Obj}\\mathbf{C}^{\\text{op}} = \\text{Obj}\\mathbf{C}$, \\\\\nDenote $\\forall \\, \\overline{C} \\in \\text{Obj}\\mathbf{C}^{\\text{op}}$, $\\overline{C} = C \\in \\text{Obj}\\mathbf{C}$. \\\\\n$\\text{Hom}_{\\mathbf{C}^{\\text{op}}}(\\overline{A}, \\overline{B}) \\ni \\overline{f} : \\overline{C} \\to \\overline{D}$, in $\\mathbf{C}^{\\text{op}}$, for $f:D\\to C$ in $\\mathbf{C}$. \\\\\n\n\\[\n\\begin{gathered}\n1_{\\overline{C}} = 1_C \\\\\n\t\\overline{f} \\circ \\overline{g} \\equiv \\overline{f} \\circ_{\\text{op}} \\overline{g} = g\\circ f \n\\end{gathered}\n\\]\n\nDiagram in $\\mathbf{C}$:\n\n\\[\n\\begin{tikzpicture}\n\\matrix(m)[matrix of math nodes, row sep=4em, column sep=4em]\n{\n\tA & B \\\\\n\t & C \\\\\n};\n\\path[->]\n(m-1-1) edge node[above]{$f$} (m-1-2)\nedge node[left]{$g\\circ f$} (m-2-2) \n(m-1-2) edge node[right]{$g$} (m-2-2);\n\\end{tikzpicture} \n\\]\n\nDiagram in $\\mathbf{C}^{\\text{op}}$:\n\n\\[\n\\begin{tikzpicture}\n\\matrix(m)[matrix of math nodes, row sep=4em, column sep=4em]\n{\n\t\\overline{A} & \\overline{B} \\\\\n\t& \\overline{C} \\\\\n};\n\\path[->]\n(m-1-2) edge node[above]{$\\overline{f}$} (m-1-1)\n(m-2-2) edge node[left]{$\\overline{f}\\circ \\overline{g}$} (m-1-1)\nedge node[right]{$\\overline{g}$} (m-1-2);\n\\end{tikzpicture} \n\\]\n\ne.g. $\\mathbf{Sets}$ is dual to category of complete, atomic Boolean algebras.\n\ne.g. if $\\mathbf{A} = (M,\\cdot, e)$ monoid, then $\\mathbf{A}^{\\text{op}} = (M, \\widehat{\\cdot},e)$ where $a\\widehat{\\cdot} b = b\\cdot a$\n\n\n\\subsubsection{Example}\n\n\\begin{itemize}\n\t\\item $\\text{Vec}^{\\text{op}}$\n\t\\[\n\t\\textbf{Vec}^{\\text{op}} = (\\text{Obj}(\\textbf{Vec}), \\text{Hom}_{\\textbf{Vec}^{\\text{op}}}, 1, \\circ^{\\text{op}})\n\t\\]\n\ts.t.\n\t\\[\n\t\\text{Hom}_{\\textbf{Vec}^{\\text{op}} }(W,V) = \\text{Hom}_{\\textbf{Vec}}(V,W)\n\t\\]\n\\[\t\n\t\\begin{tikzpicture}\n\t\\matrix (m) [matrix of math nodes, row sep=3em, column sep=4em, minimum width=2em]\n\t{\n\t\tU & V & W \\\\\n\t};\n\t\\path[->]\n\t(m-1-1) edge node [above] {$f$} (m-1-2)\n\t(m-1-2) edge node [above] {$g$} (m-1-3);\n\t\t\\path[-{>[scale=1.15]}, line width=0.5pt]\n\t(m-1-1) edge[bend right=45] node [below] {$g\\circ f$} (m-1-3);\n\t\\end{tikzpicture} \\qquad \\, \\begin{tikzpicture}\n\t\\matrix (m) [matrix of math nodes, row sep=3em, column sep=4em, minimum width=2em]\n\t{\n\t\tU & V & W \\\\\n\t};\n\t\\path[->]\n\t(m-1-3) edge node [above] {$g$} (m-1-2)\n\t(m-1-2) edge node [above] {$f$} (m-1-1);\n\t\t\\path[-{>[scale=1.15]}, line width=0.5pt]\n(m-1-3) \tedge[bend left=45] node [below] {$f\\circ^{\\text{op}} g$} (m-1-1);\n\t\\end{tikzpicture}\n\\]\n\\end{itemize}\n\n\\subsection{Kinds of morphisms}\n\ncf. pp. 11, Definition 1.3 of Awodey (2010) \\cite{Awod2010}\n\\begin{definition}[isomorphism]\n\t\\textbf{isomorphism} - $\\forall \\, $ category $\\mathbf{C}$, $\\text{Mor}\\mathbf{C} \\ni $ morphism $f:A \\to B$ is an isomorphism if $\\exists \\, g : B \\to A$ s.t. $f\\circ g = 1_B$, $g\\circ f = 1_A$, $g$ unique. $g$ called inverse of $f,f^{-1}$\n\t\\[\n\t\\begin{gathered}\n\t\\begin{tikzpicture}\n\\matrix (m) [matrix of math nodes, row sep=3em, column sep=4em, minimum width=2em]\n{\n\tA & B \\\\\n};\n\\path[->]\n(m-1-1) edge node [above] {$f$} (m-1-2)\n\t\tedge [loop left] node [left] {$1_A$} (m-1-1);\n\t\t\\path[-{>[scale=1.15]}, line width=0.5pt]\n(m-1-2) edge[bend left=45] node [below] {$g$} (m-1-1);\n\\end{tikzpicture}\t\\qquad \\, \n\t\\begin{tikzpicture}\n\\matrix (m) [matrix of math nodes, row sep=3em, column sep=4em, minimum width=2em]\n{\n\tB & A \\\\\n};\n\\path[->]\n(m-1-1) edge node [above] {$g$} (m-1-2)\n\t\tedge [loop left] node [left] {$1_B$} (m-1-1);\n\\path[-{>[scale=1.15]}, line width=0.5pt]\n(m-1-2) edge[bend left=45] node [below] {$f$} (m-1-1);\n\\end{tikzpicture}\t\n\t\\end{gathered}\t\n\t\\]\n\\end{definition}\n\n\\begin{theorem}[Cayley]\ncf. pp. 11, Sec. 1.5. \\textbf{Isomorphisms}, Awodey (2010) \\cite{Awod2010}\n\n$\\forall \\, $ group $G$, \n\\[\nG \\cong \\text{ group of permutations }\n\\]\n(isomorphic $\\equiv \\cong$)\n\n\\end{theorem} \n\n\\begin{proof}\n\tDefine Cayley representation $\\overline{G}$ of $G$ to be following group of permutations: \\\\\n\tunderlying set of $\\overline{G}$ is just $G$, \\\\\n\t$\\forall \\, g\\in G$, we have permutation $\\overline{g}$, defined $\\forall \\, h \\in G$, \n\t\\[\n\t\\overline{g}(h) = g\\cdot h\n\t\\]\n\tLet $\\overline{g} = \\overline{h}$. \\\\\n\t$\\forall \\, g' \\in G$, \\\\\n\t$\\begin{aligned}\n\t& \\overline{g}(g') = gg' \\\\ \n\t& \\overline{h}(g') = hg'\n\t\\end{aligned}$ \\\\\n\t$g' \\in G$, so $\\exists \\, (g')^{-1}$ s.t. $g'(g')^{-1} =e$, so $gg'(g')^{-1}= g=h$.\n\t\n\t\\quad \\\\\n\tDefine homomorphisms $\\begin{aligned} & \\quad \\\\ \n\t& i : G \\to \\overline{G} \\\\\n\t& i(g) = \\overline{g}\n\t\\end{aligned}$, \\qquad \\, $\\begin{aligned} & \\quad \\\\ \n\t& j : \\overline{G} \\to G \\\\\n\t& j(\\overline{g}) = g\n\t\\end{aligned}$\n\t\n\t\\[\n\t\\begin{gathered} \n\ti(gg') = \\overline{(gg')} \\\\\n\t\\begin{aligned}\n\t& \\overline{(gg')} = h = gg' h = g(g'h) = g(\\overline{g}'(h)) = \\overline{g}(\\overline{g}'(h)) = i(g) = i(g') h \\\\ \n\t& \\Longrightarrow i(gg') = i(g) \\circ i(g') \\\\\n\t& j(\\overline{g}) = j(\\overline{g}') h = j(\\overline{g}) (g'h) = gg'h = j(\\overline{gg'})h = j(\\overline{g} \\cdot \\overline{g}') h \\\\\n\t& j(\\overline{g}) \\cdot j(\\overline{g}') = j(\\overline{g} \\cdot \\overline{g}')\n\t\\end{aligned} \\\\\n\t\\begin{aligned}\n\t& i\\circ j = 1_{\\overline{G}}, \\, j \\circ i = 1_G \\text{ since } \\\\\n\t& i \\circ j (\\overline{g}) = i\\circ g = \\overline{g} \\\\\n\t& j\\circ i (g) = j(\\overline{g}) = g\n\t\\end{aligned}\n\\end{gathered} \t\n\t\\]\n\t$i,j$ are isomorphisms between $G,\\overline{G}$, which is in category $\\textbf{Groups}$ of groups and group homomorphisms. \\\\\n\tpermutations $\\overline{g} \\in \\overline{G}$ are themselves isomorphisms in $\\textbf{Sets}$. \\\\\n\tCayley's Thm. says that any abstract group can be represented as a \"concrete\" one, i.e. group of permutations of a set.\n\\end{proof}\n\nExample 1.1.5 (Leinster (2014) \\cite{Lein2014}) isomorphisms in $\\textbf{Set}$ are exactly bijections. \\\\\n$\\Longrightarrow $ function has 2-sided inverse iff function is injective and surjective (this is not trivial)\n\nExample 1.1.7 Leinster (2014) \\cite{Lein2014} isomorphisms in $\\textbf{Top}$ are exactly homeomorphisms. \\\\\nbijective map in $\\textbf{Top}$ is not necessarily an isomorphism:\n\\[\n\\begin{aligned}\n\t[0, 1) & \\to \\lbrace z \\in \\mathbb{C} | |z| = 1 \\rbrace \\\\\n\tt & \\mapsto e^{2\\pi i t}\n\\end{aligned}\n\\]\nis a continuous bijection but not a homeomorphism (cont. bijection with cont. $f^{-1}$). \n\\[\n\\ln{ \\left( \\frac{w}{2\\pi i} \\right) } = f^{-1}(w)\n\\]\n\nExample 1.1.8 Leinster (2014) \\cite{Lein2014} (Categories as mathematical structures) (b) \\textbf{Discrete} categories contain no maps at all apart from identities. Just a class of objects.\n\n\\exercisehead{1.1.13 pp. 16, Leinster (2014) \\cite{Lein2014}}\n\nSuppose for morphism $f: A \\to B$, $\\exists \\,$ inverse $g$, s.t. $f\\circ g = 1_B$, $g\\circ f = 1_A$ \\\\\nNow $f^{-1} \\circ f = 1_A$, $f\\circ f^{-1} = 1_B$ \\\\\n\\phantom{Now} $f^{-1} \\circ f \\circ g = f^{-1} \\circ 1_B = 1_A \\circ g = f^{-1} \\circ 1_B \\Longrightarrow g= f^{_1}$ \n\n\n\\begin{definition}[endomorphism]\n\t\\textbf{endomorphism} - morphism with same source and target, that is, morphism $f:A \\to A$\n\\end{definition}\n\n\\begin{definition}[automorphism]\n\\textbf{automorphism} - endomorphism which is an isomorphism\n\\end{definition}\n\n\\begin{definition}[parallel]\n\t\\textbf{parallel} - 2 morphisms $f,g$ are parallel if they have same source and same target:\n\t\\[\n\t\\begin{aligned}\n\t& f:A \\to B \\\\\n\t& g:A \\to B\n\t\\end{aligned}\n\t\\]\n\\end{definition}\n\n\\begin{definition}[monomorphism]\n\t\\text{monomorphism} - morphism $f: A \\to B$ is a monomorphism if $\\forall \\, $ pair of parallel $\\begin{aligned}\n\t& \\quad \\\\\n\t& g_1: C \\to A \\\\\n\t& g_2:C \\to A\n\t\\end{aligned}$, \n\t\\begin{equation}\n\tf\\circ g_1 = f\\circ g_2 \\text{ implies } g_1 = g_2\n\t\\end{equation}\n\ti.e.\n\t\\[\n\t\\begin{tikzpicture}\n\t\\matrix (m) [matrix of math nodes, row sep=3em, column sep=4em, minimum width=2em]\n\t{\n\t\tC & B \\\\\n\t};\n\t\\path[->]\n\t(m-1-1) edge node [above] {$f \\circ g_1$} (m-1-2);\n\t\\path[-{>[scale=1.15]}, line width=0.5pt]\n\t(m-1-2) edge[bend left=45] node [below] {$f\\circ g_2$} (m-1-1);\n\t\\end{tikzpicture} \\text{ implies } C \\xrightarrow{ g_1 = g_2 } A\t\n\t\\]\n\\end{definition}\n\n\\begin{definition}[epimorphism]\n\\textbf{epimorphism} - morphism $f:A \\to B$ is an epimorphism if $f^{\\text{op}} : B^{\\text{op}} \\to A^{\\text{op}}$ is a monomorphism in $\\mathbf{A}^{\\text{op}}$. \\\\\nHence $f$ epimorphism iff $\\forall \\, $ parallel morphisms $\\begin{aligned} & \\quad \\\\ \n\t& g_1 : B \\to C \\\\\n\t& g_2 : B\\to C\\end{aligned}$, $g_1 \\circ f = g_2 \\circ f $ \\\\\n\t implies $g_1 = g_2$\n\\end{definition}\n\n\\begin{proposition}[monomorphism, epimorphism iff injective]\n\t$f$ monomorphism iff $f \\circ : \\text{Hom}_{\\mathbf{A}}(C,A) \\to \\text{Hom}_{\\mathbf{A}}(C,B)$ injective \\, $\\forall \\, C \\in \\text{Obj}(\\mathbf{A})$, i.e.\n\t\\begin{equation}\n\t\\begin{gathered}\n\\begin{gathered} \n\t\\text{Hom}_{\\mathbf{A}}(C, A) \\xrightarrow{f \\circ } \\text{Hom}_{\\mathbf{A}}(C,B) \\\\\n g_1 , g_2 \\xmapsto{f \\circ} f\\circ g_1 , f\\circ g_2\n\\end{gathered}, \\\\ \\text{ then } \\\\\nf \\circ \\text{ is injective if } \\\\\n\tf \\circ g_1 = f \\circ g_2 \\Longrightarrow g_1 = g_2\n\\end{gathered} \n\t\\end{equation}\n$f$ epimorphism iff map $\\circ f : \\text{Hom}_{\\mathbf{A}}(B,C) \\to \\text{Hom}_{\\mathbf{A}}(A,C)$ injective $\\forall \\, C \\in \\text{Obj}(\\mathbf{A})$\n\\begin{equation}\n\\begin{gathered}\n\\begin{gathered} \n\\text{Hom}_{\\mathbf{A}}(B, C) \\xrightarrow{\\circ f} \\text{Hom}_{\\mathbf{A}}(A,C) \\\\\ng_1 , g_2 \\xmapsto{ \\circ f} g_1\\circ f , g_2 \\circ f\n\\end{gathered}, \\\\ \\text{ then } \\\\\n\\circ f \\text{ is injective if } \\\\ \ng_1 \\circ f = g_2 \\circ f \\Longrightarrow g_1 = g_2\n\\end{gathered}\n\\end{equation}\n\\end{proposition}\n\n\\begin{definition}[inverses]\n\t$\\forall \\, $ 2 morphisms, $f:X\\to Y$, $g: Y \\to X$ s.t. $f\\circ g= 1_Y$,\\\\\n\t$f$ is called left inverse of $g$, $g$ is called right inverse of $f$.\n\t\n\tWe also say, $g$ is a section of $f$, or $f$ is a cosection of $g$. \\\\\n\t$f$ is an epimorphism, $g$ is a monomorphism.\n\\end{definition}\n\n\\subsection{More definitions with categories}\n\n\\begin{definition}[subcategory]\ncategory $\\mathbf{A}'$, $\\mathbf{A}' \\subset \\mathbf{A}$, if $\\text{Obj}(\\mathbf{A}') \\subset \\text{Obj}(\\mathbf{A})$, $\\text{Hom}_{\\mathbf{A}'}(A,B) \\subset \\text{Hom}_{\\mathbf{A}}(A,B)$, $\\forall \\, A, B \\in \\mathbf{A}'$.\n\nComposition in $\\mathbf{A}'$ is induced by composition in $\\mathbf{A}$.\\\\\nidentity morphisms in $\\mathbf{A}'$ are identity morphisms in $\\mathbf{A}$\n\\end{definition}\n\n\\begin{definition}[full subcategory]\n\tsubcategory $\\mathbf{A}'$ of $\\mathbf{A}$ is full if $\\text{Hom}_{\\mathbf{A}'}(A,B) = \\text{Hom}_{\\mathbf{A}}(A,B)$, $\\forall \\, A, B \\in \\mathbf{A}'$\t\n\\end{definition}\n\n\\begin{definition}[saturated subcategory]\nfull subcategory $\\mathbf{A}'$ of $\\mathbf{A}$ saturated if $A \\in \\mathbf{A}$ belongs to $\\mathbf{A}'$ whenever $A$ is isomorphic to object of $\\mathbf{A}'$\t\n\\end{definition}\n\n\\begin{definition}[discrete category]\n\t\\textbf{discrete} - discrete category if all morphisms are identity morphisms.\n\\end{definition}\n\n\\begin{definition}[nonempty category]\n\t\\textbf{nonempty} - nonempty category if $\\text{Obj}(\\mathbf{A})$ is nonempty\n\\end{definition}\n\n\\begin{definition}[groupoid]\n\\textbf{groupoid} - category $\\mathbf{A}$ is a \\textbf{groupoid} if all morphisms are isomorphisms.\n\\end{definition}\n\n\\begin{definition}[finite category]\n\tfinite - finite category if set of all morphisms in $\\mathbf{A}$ (hence, in particular, set of objects) is a finite set\n\\end{definition}\n\n\\begin{definition}[connected]\n\tconnected category $\\mathbf{A}$ if it's nonempty, and $\\forall \\, A,B \\in \\text{Obj}\\mathbf{A}$, $\\exists \\, $ finite sequence of objects $(A_0 \\dots A_n)$, $A_0 = A$, $A_n = B$, s.t. at least 1 of the sets $\\text{Hom}_{\\mathbf{A}}(A_j, A_{j+1})$ or $\\text{Hom}_{\\mathbf{A}}(A_{j+1}, A_j)$ is nonempty $\\forall \\, j \\in \\mathbb{N}$, with $0\\leq j \\leq n-1$\n\\end{definition}\n\n\\begin{definition}[monoid $M$]\n\t\\textbf{monoid} $M$ (set endowed with internal product with associative and unital law) is nothing but a category with only 1 object (to $M$, associate category $\\mathbf{M}$, with single object $A$, and morphisms $\\text{Hom}_{\\mathbf{M}}(A,A) = M$)\n\\end{definition}\n\ncf. Def. 1.2.5 of Kashiwara and Schapira (2006) \\cite{KaSch2006}.\n\n\\begin{definition}[Morphisms as a category]\n\tLet category $\\mathcal{C} \\equiv \\mathbf{A}$.\n\t\n\t$\\text{Mor}(\\mathbf{A})$ is a category.\n\t\n\t$\\text{Obj}(\\text{Mor}(\\mathbf{A})) = \\text{Mor}\\mathbf{A}$ (objects of category $\\text{Mor}(\\mathbf{A})$ are morphisms in $\\mathbf{A}$).\n\t\n\tLet $\\begin{aligned} & \\quad \\\\ \n\t& f:X \\to Y \\\\\n\t& g: X' \\to Y'\\end{aligned}$, $f,g \\in \\text{Mor}(\\mathbf{A})$ (i.e. $\\begin{aligned} & \\quad \\\\ \n\t& f \\in \\text{Hom}(X,Y) \\\\ \n\t&g \\in \\text{Hom}(X', Y') \\end{aligned}$, for $X, Y, X', Y' \\in \\text{Obj}(\\mathbf{A})$)\n\t\n\tThen\n\t\\[\n\t\\text{Hom}_{\\text{Mor}(\\mathbf{A})}(f,g) = \\lbrace u :X \\to X', v: Y \\to Y'; g \\circ u = v \\circ f \\rbrace\n\t\\]\n\tComposition and identity in $\\text{Mor}(\\mathbf{A})$ are the obvious ones.\n\t\n\tSo \n\t\\[\n\t\\begin{gathered} \n\t\\text{Obj}(\\text{Mor}(\\mathbf{A})) = \\text{Mor}(\\mathbf{A}) \\\\\n\t\\text{Mor}(\\text{Mor}(\\mathbf{A})) = \\bigcup_{f,g \\in \\text{Mor}(\\mathbf{A})} \\text{Hom}(f,g) = \\bigcup_{f,g \\in \\text{Mor}(\\mathbf{A}) } \\lbrace u : X\\to X', v: Y \\to Y' ; g \\circ u = v \\circ f \\rbrace \n\t\\end{gathered} \n\t\\]\n\\[\n\t\\begin{tikzpicture}\n\\matrix (m) [matrix of math nodes, row sep=5em, column sep=5em, minimum width=2em]\n{\n\tX & Y \\\\\n\tX' & Y' \\\\\n};\n\\path[->]\n(m-1-1) edge node [above] {$f$} (m-1-2)\nedge node [auto] {$u$} (m-2-1)\n(m-1-2) edge node [auto] {$v$} (m-2-2)\n(m-2-1) edge node [auto] {$g$} (m-2-2);\n\\end{tikzpicture}\n\\]\n\\end{definition}\n\ncf. Def. 1.2.6 of Kashiwara and Schapira (2006) \\cite{KaSch2006}.\n\n\\begin{definition}\n\t\\begin{enumerate}\n\t\t\\item object $P \\in \\mathcal{C} \\equiv \\mathbf{A}$ is called \\emph{initial} if $\\forall \\, X \\in \\mathbf{A}$, ($\\equiv \\forall \\, x \\in \\text{Obj}(\\mathbf{A})$), $\\text{Hom}_{\\mathbf{A}}(P, X) \\simeq \\lbrace \\text{pt} \\rbrace$. \\\\\n\t\t(Denote by $\\emptyset_{\\mathbf{A}}$ an \\emph{initial object} in $\\mathbf{A}$). \\\\\n\t\t(Note that if $P_1$ and $P_2$ are initial, then $\\exists \\, !$ isomorphism $P_1 \\simeq P_2$)\n\t\t\\item $P$ is terminal in $\\mathbf{A}$ if $P$ is initial in $\\mathbf{A}^{\\text{op}}$, i.e. \n\t\t\n\t\t$\\forall \\, X \\in \\mathbf{A}$, $\\text{Hom}_{\\mathbf{A}}(X, P) \\simeq \\lbrace \\text{pt} \\rbrace$. \n\t\t\n\t\tDenote $\\text{pt}_{\\mathbf{A}}$ a terminal object in $\\mathbf{A}$. \n\t\t\\item $P$ is zero ($0$) object if it's both initial and terminal. \n\t\t\n\t\tSuch a $P$ is denoted by $0$.\n\t\t\n\t\tIf $\\mathbf{A}$ has a zero object, $\\forall \\, $ object $X, Y \\in \\mathbf{A} \\equiv \\text{Obj}\\mathbf{A}$, the morphism obtained as composition $X\\to 0 \\to Y$ is still denoted by $0: X\\to Y$.\n\t\t\n\t\t(Note that composition of $0:X \\to Y$, and any morphism $f:Y \\to Z$ is $0:X \\to Z$)\n\t\\end{enumerate}\n\\end{definition}\n\ncf. Example 1.2.7 of Kashiwara and Schapira (2006) \\cite{KaSch2006}. \nExample \n\\begin{enumerate}\n\t\\item[(i)] In category $\\mathbf{Set}$, $\\emptyset$ initial, $\\lbrace \\text{pt} \\rbrace$ terminal. \n\t\\item[(ii)] Zero module $0$ is zero object in $\\text{Mod}(R)$.\n\\end{enumerate}\n\nNotation 1.2.8 of Kashiwara and Schapira (2006) \\cite{KaSch2006}:\n\\begin{enumerate}\n\t\\item $\\mathbf{Pt} \\equiv $ category with a single object and a single morphism (the identity of this object)\n\t\\item $\\emptyset \\equiv $ empty category with no objects (hence, no morphisms)\n\t\\item $\\bullet \\to \\bullet \\equiv$ category which consists of 2 objects, say $a,b$, and 1 morphism, $a\\to b$, other than $\\text{id}_a, \\text{id}_b \\equiv 1_a, 1_b$. Denote this category by $\\mathbf{Arr}$. \n\\end{enumerate}\n\ncf. Example 1.2.9 of Kashiwara and Schapira (2006) \\cite{KaSch2006}. \n\nLet $R$ be a ring. Let $N\\in \\text{Mod}(R^{\\text{op}})$, $M\\in \\text{Mod}(R)$.\n\nCategory $\\mathbf{C}$: \n\n$\\text{Obj}\\mathbf{C} \\ni (f, L)$, where $L\\in \\text{Mod}(\\mathbb{Z})$, $f$ bilinear map $f: N \\times M \\to L$ (i.e. it's $\\mathbb{Z}$-bilinear and satisfies\n\\[\nf(na, m) = f(n,am), \\quad \\, \\forall \\, a \\in R\n\\])\n\nMorphism from $f:N \\times M \\to L$ to $g: N\\times M$ is a linear map $h:L\\to K$ s.t. $h\\circ f =g$. \n\nSince any bilinear map $f: N\\times M \\to L$ (i.e. any object of $\\mathbf{C}$) factorizes uniquely through\n\\[\nu : N\\times M \\to N \\otimes_R M\n\\]\nobject $(u, N \\otimes_R M)$ is initial in $\\mathbf{C}$\n\n\\section{Functors}\n\ncf. Def. 1.2.10 of Kashiwara and Schapira (2006) \\cite{KaSch2006}, with terminology from pp. 13, Sec. 3. \"Functors\" from Mac Lane (1978) \\cite{MacL1978}\n\n\\begin{definition}[(covariant) Functor]\\label{Def:Functor}\n\\begin{enumerate}\n\t\\item (covariant functor) Let categories $\\mathbf{C}$, $\\mathbf{D}$. \\\\\n(covariant) \\textbf{functor} $F: \\mathbf{C} \\to \\mathbf{D}$ consists of (Mac Lane (1978) \\cite{MacL1978} says 2 suitably related functions)\n\\begin{itemize}\n\t\\item map $F: \\text{Obj}(\\mathbf{C}) \\to \\text{Obj}(\\mathbf{D})$ (i.e. $\\forall \\, C \\in \\text{Obj}(\\mathbf{C})$, $F(C) \\in \\text{Obj}(\\mathbf{D})$), \\\\\n\t(Mac Lane (1978) \\cite{MacL1978} calls this the \\emph{object function} $T$ or $F$ in our notation; we'll call it the \\emph{object map}) and \n\t\\item maps $F: \\text{Hom}_{\\mathbf{C}}(X,Y) \\to \\text{Hom}_{\\mathbf{D}}(F(X), F(Y))$, so that \n\t\t\\[\t\n\t\t\tF(f) : F(X) \\to F(Y) \\text{ or } F(f)(F(X)) = F(f(X)) \n\t\t\\] \\, $\\forall \\, X,Y \\in \\text{Obj}(\\mathbf{C})$ s.t.\n\t\\begin{equation}\n\t\\begin{gathered}\n\tF(1_X) = 1_{F(X)} \\qquad \\, \\forall \\, X \\in \\mathbf{C} \\\\\n\tF(g\\circ f) = F(g) \\circ F(f) \\qquad \\, \\forall \\, \\begin{aligned} & \\quad \\\\ \n\t& f: X \\to Y \\\\\n\t& g: Y \\to Z \\end{aligned}, \\qquad \\, X,Y,Z \\in \\text{Obj}(\\mathbf{C})\n\t\\end{gathered}\n\t\\end{equation}\n\tMac Lane (1978) \\cite{MacL1978} calls this the \\emph{arrow function} (also written as $T$ for Mac Lane's notation; $F$ for our notation); we'll call $F$ to be the \\emph{morphism map}. \n\\end{itemize}\n\\item (composition law for functors) \\\\\nFor categories $\\mathbf{A} , \\mathbf{B}, \\mathbf{C}$, functors $F: \\mathbf{A} \\to \\mathbf{B}$, $G: \\mathbf{B} \\to \\mathbf{C}$, \\\\\nComposition $G\\circ F : \\mathbf{A} \\to \\mathbf{C}$, is a functor defined by \n\\begin{equation}\n\\begin{aligned}\n& (G\\circ F)(X) = G(F(X)) \\qquad \\, \\forall \\, X \\in \\text{Obj}\\mathbf{A}, \\text{ and } \\\\\n& (G\\circ F)(f) = G(F(f)), \\qquad \\, \\forall \\, \\text{ morphism } f \\in \\text{Mor}(\\mathbf{C})\n\\end{aligned}\n\\end{equation}\n\\end{enumerate}\n\\end{definition}\nDiagrammatically,\n\n\\[\n\\begin{gathered}\n\\begin{tikzpicture}\n\\matrix (m) [matrix of math nodes, row sep=1.8em, column sep=1.8em, minimum width=1.2em]\n{\n\tX & Y \\\\\n};\n\\path[->]\n(m-1-1) edge node [above] {$f$} (m-1-2);\n\\end{tikzpicture} \\quad \\xrightarrow{F} \\quad\n\\begin{tikzpicture}\n\\matrix (m) [matrix of math nodes, row sep=1.8em, column sep=1.8em, minimum width=1.2em]\n{\n\tF(X) & F(Y) \\\\\n};\n\\path[->]\n(m-1-1) edge node [above] {$F(f)$} (m-1-2);\n\\end{tikzpicture} \\\\\n\\begin{tikzpicture}\n\\matrix (m) [matrix of math nodes, row sep=1.8em, column sep=1.8em, minimum width=1.2em]\n{\n\tX & Y & Z \\\\\n};\n\\path[->]\n(m-1-1) edge node [above] {$f$} (m-1-2)\nedge[bend right=45] node [below] {$g\\circ f$} (m-1-3)\n(m-1-2) edge node [above] {$g$} (m-1-3)\n;\n\\end{tikzpicture} \n\\quad \\xrightarrow{F} \\quad \\begin{tikzpicture}\n\\matrix (m) [matrix of math nodes, row sep=1.8em, column sep=1.8em, minimum width=1.2em]\n{\n\tF(X) & F(Y) & F(Z) \\\\\n};\n\\path[->]\n(m-1-1) edge node [above] {$F(f)$} (m-1-2)\nedge[bend right=45] node [below] {$F(g\\circ f)$} (m-1-3)\n(m-1-2) edge node [above] {$F(g)$} (m-1-3)\n;\n\\end{tikzpicture} \n\\end{gathered}\n\\]\ni.e.\n\\[\n\\begin{gathered} \n\\begin{tikzpicture}\n\\matrix (m) [matrix of math nodes, row sep=3.8em, column sep=4.8em, minimum width=2.2em]\n{\n\tX & Y \\\\\n\tF(X) & F(Y) \\\\\n};\n\\path[->]\n(m-1-1) edge node [above] {$f$} (m-1-2)\nedge node [auto] {$F$} (m-2-1)\n(m-1-2) edge node [auto] {$F$} (m-2-2)\n(m-2-1) edge node [above] {$F(f)$} (m-2-2) \n;\n\\end{tikzpicture} \\text{ and } \n\\begin{tikzpicture}\n\\matrix (m) [matrix of math nodes, row sep=3.8em, column sep=4.8em, minimum width=2.2em]\n{\n\tX & Y & Z \\\\\n\tF(X) & F(Y) & F(Z) \\\\ \n};\n\\path[->]\n(m-1-1) edge node [above] {$f$} (m-1-2)\nedge[bend left=45] node [above] {$g\\circ f$} (m-1-3)\nedge node [auto] {$F$} (m-2-1)\n(m-1-2) edge node [above] {$g$} (m-1-3)\nedge node [auto] {$F$} (m-2-2)\n(m-1-3) edge node [auto] {$F$} (m-2-3)\n(m-2-1) edge node [above] {$F(f)$} (m-2-2)\nedge[bend right=45] node [below] {$F(g\\circ f) = F(g) \\circ F(f)$} (m-2-3)\n(m-2-2) edge node [above] {$F(g)$} (m-2-3) \n;\n\\end{tikzpicture} \n\\end{gathered}\n\\]\n\n\\subsection{Examples of Functors}\n\ncf. pp. 13, 3. Functors, Maclane (1978) \\cite{MacL1978}\n\n\\emph{Power Set Functor}. \n\\[\n\\begin{gathered}\n\t\\begin{aligned}\n\t\t& P : \\textbf{Set} \\to \\textbf{Set} \\\\\n\t\t& P:\\text{Obj}\\textbf{Set} \\to \\text{Obj}(\\textbf{Set}) \\\\\n\t\t& P: X \\in \\text{Obj}\\textbf{Set} \\mapsto 2^X \\in \\text{Obj}\\textbf{Set}, \\text{ i.e. } \\\\\n\t\t& P:X \\mapsto 2^X = \\lbrace S | S \\subseteq X \\rbrace \n\t\\end{aligned} \\\\\nP : \\text{Hom}_{\\textbf{Set}}(X,Y) \\to \\text{Hom}_{\\textbf{Set}}(P(X), P(Y)) \\\\\n\\begin{aligned} \n& P(f): P(X) \\to P(Y) \\text{ or } P(f)(P(X)) = P(f(X)) \\\\\n& P(f): S \\in 2^X \\mapsto f(S) \\in 2^Y \\text{ or } f(S) \\subseteq Y \n\\end{aligned} \n\\end{gathered}\n\\]\n\\[\n\\begin{gathered}\nP(1_X) = 1_{PX} \\text{ and } P(g\\circ f) = P(g) P(f), \\text{ so $P$ defines a functor }\n\\end{gathered}\n\\]\n\nAlgebraic topology; singular homology in a given dim. $n$ ($n \\in \\mathbb{N}$) Maclane (1978) \\cite{MacL1978}\n\n$\\forall \\, $ topological space $X$, assign $X \\mapsto $ abelian group $H_n(X) \\equiv n$th homology group of $X$, also \\\\\n$\\forall \\, $ cont. $f:X \\to Y$ of spaces corresponding group homomorphism. \n\\[\n\\begin{gathered}\nH_n(f) : H_n(X) \\to H_n(Y) \\\\\n\\begin{aligned}\n& H_n: \\text{Obj}(\\mathbf{Top}) \\to \\text{Obj}(\\textbf{Ab}) \\\\\n& H_n: X \\mapsto H_n(X) \n\\end{aligned} \\\\\nH_n(f)(H_n(X)) = H_n(f(X))\n\\end{gathered}\n\\]\n$\\Longrightarrow H_n: \\textbf{Top} \\to \\textbf{Ab}$.\n\ne.g. if $X=Y = S^1$, $H_1(S^1) = \\mathbb{Z}$\n\nSo group homomorphism $H_1(f): \\mathbb{Z} \\to \\mathbb{Z}$ determined by integer $d\\in \\mathbb{Z}$ (image of 1) \\\\\n$d$ is usual \"degree\" of cont. map $f:S^1 \\to S^1$. \n\nIn this case, and in general, homotopic maps $f,g : X \\to Y$ \\\\\nThen $\\exists \\,$ homotopy $H:X \\times [0,1] \\to Y$ s.t. $H(x,0) = f(x)$; $H(x,1) = g(x) \\, \\forall \\, x \\in X$\n\n\n\n\nExample 1.2.3 (forgetful functors) Leinster (2014) \\cite{Lein2014}, pp. 18\n\n\\begin{enumerate}\n\t\\item[(a)] $U : \\textbf{Grp} \\to \\textbf{Set}$ \\\\\n\tif group $G$ then $U(G)$ is underlying set of $G$. \\\\\n\tIf group homomorphism $f:G \\to H$, \\\\\n\t$U(f)$ is function $f$ itself. \\\\\n\tSo $U$ forgets group structure of groups and forgets group homomorphisms are homomorphisms.\n\t\\item[(c)] $\\textbf{Ab} \\equiv $ category of abelian groups \\\\\n\t$\\textbf{Ring} \\to \\textbf{Ab}$ forgets multiplicative structure. \\\\\n\t$U:\\textbf{Ring} \\to \\textbf{Mon}$ forgets additive structure; $\\textbf{Mon} \\equiv $ category of monoids\n\\end{enumerate}\n\n\n\n\n\\begin{itemize}\n\t\\item (monoid) homomorphism $h: M \\to N$, $\\forall \\, $ monoid $M, N$ s.t. $\\forall \\, m,n \\in M$, \\\\\n\t$h(m\\cdot n) \\equiv h(m\\cdot_M n) = h(m) \\cdot h(n) \\equiv h(m) \\cdot_N h(n)$ and \\\\\n\t$h(e_M) = e_N$. \\\\\n\t\n\t$h:m \\mapsto h(m)$ so $h: \\text{Obj}\\mathbf{C}(M) \\to \\text{Obj}\\mathbf{C}(N)$. \\\\\n\tLet $m\\cdot n \\equiv f_m(n)$, $f_m \\in \\text{Hom}\\mathbf{C}(M)$\n\t\\[\n\t\\begin{aligned}\n\t\t& h(m) \\cdot h(n) \\equiv f_{h(m)}(h(n)), \\, f_{h(m)} \\in \\text{Hom}\\mathbf{C}(N) \\\\\n \t\t& h(f_m) = h(m) \\\\\n\t\t& h(f_m)(h(n)) = h(m)\\cdot h(n) = h(m\\cdot n) = h(f_m\\cdot n)\n\t\\end{aligned}\n\t\\]\n\tCompare the last statement with $F(f)(F(X)) = F(f(X))$.\n\t\\item poset $P, Q$ (set $P$, equipped with $\\leq$), poset as category $\\mathbf{P}, \\mathbf{Q}$, $\\text{Obj}\\mathbf{P} = P$, $\\text{Obj}\\mathbf{Q} = Q$ \\\\\n\t$\\text{Hom}\\mathbf{P} \\ni m$ s.t. $m:x \\mapsto y$ iff $x\\leq y$. \\\\\n\t\n\tLet functor $F: \\mathbf{P} \\to \\mathbf{Q}$ s.t. \n\t\\[\n\t\\begin{aligned} \n\t\t& F: \\text{Obj}\\mathbf{P} \\to \\text{Obj}\\mathbf{Q} \\\\ \n\t\t&\tF: x \\mapsto F(x)\n\t\\end{aligned} \n\t\\]\n\t\\[\n\t\\begin{aligned}\n\t\t& F: \\text{Hom}\\mathbf{P} \\to \\text{Hom}\\mathbf{Q} \\\\ \n\t\t& F: m \\mapsto F(m)\n\t\\end{aligned}\n\t\\]\n\ts.t. for $m(x) =y$ and $x\\leq y$, \\\\\n\t$F(m): F(x) \\mapsto F(y)$ and $F(x) \\leq F(y)$ (so that $F(m)$ is also monotone), i.e.\n\t\\[\n\tF(m)(F(X)) = F(m(X)) = F(y)\n\t\\]\n\\end{itemize}\n\nKleene closure itself is a functor from $\\mathbf{Set}$ to $\\textbf{Set}$, from $A$ to $A^*$, from $f$ to $f^*$. \\\\\nIt's the composition of $U\\circ F$ of underlying functor $U:\\textbf{Mon} \\to \\textbf{Set}$ and free functor $F:\\textbf{Set} \\to \\textbf{Mon}$. \n\n\\begin{itemize}\n\t\\item \\emph{arrow category} $\\mathbf{C}^{\\rightarrow}$ of category $\\mathbf{C}$:\n\\[\n\\text{Obj}\\mathbf{C}^{\\rightarrow} = \\text{Mor}\\mathbf{C}\n\\]\n\nGiven $f:A \\to B$, $f':A' \\to B'$, morphism (arrow) $g: f \\mapsto f'$ is a \"commutative square\", i.e. $g: \\text{Hom}_{\\mathbf{C}}(A\\to B) \\to \\text{Hom}_{\\mathbf{C}}(A' \\to B')$\n\n\\[\n\\begin{gathered} \n\\begin{tikzpicture}\n\\matrix (m) [matrix of math nodes, row sep=3.8em, column sep=4.8em, minimum width=2.2em]\n{\n\tA & A' \\\\\n\tB & B' \\\\\n};\n\\path[->]\n(m-1-1) edge node [above] {$g_1$} (m-1-2)\nedge node [auto] {$f$} (m-2-1)\n(m-1-2) edge node [auto] {$f'$} (m-2-2)\n(m-2-1) edge node [above] {$g_2$} (m-2-2) \n;\n\\end{tikzpicture} \n\\end{gathered}\n\\]\nwhere $g_1, g_2 \\in \\text{Mor}\\mathbf{C}$, \\\\\ni.e. such a morphism (arrow) is a pair of morphisms (arrows) $g=(g_1,g_2)$ in $\\mathbf{C}$ s.t.\n\\[\ng_2 \\circ f = f'\\circ g\n\\]\n\nidentity morphism (arrow) $1_f$ on object $f:A\\to B$ is pair $(1_A, 1_B)$.\n\nComposition of arrows is done componentwise:\n\\[\n(h_1,h_2) \\circ (g_1, g_2) = (h_1 \\circ g_1, h_2\\circ g_2)\n\\]\n\n\\[\n\\begin{tikzpicture}\n\\matrix (m) [matrix of math nodes, row sep=3.8em, column sep=4.8em, minimum width=2.2em]\n{\n\tA & A' & A'' \\\\\n\tB & B' & B'' \\\\ \n};\n\\path[->]\n(m-1-1) edge node [above] {$g_1$} (m-1-2)\nedge[bend left=45] node [above] {$h_1\\circ g_1$} (m-1-3)\nedge node [auto] {$f$} (m-2-1)\n(m-1-2) edge node [above] {$h_1$} (m-1-3)\nedge node [auto] {$f'$} (m-2-2)\n(m-1-3) edge node [auto] {$f''$} (m-2-3)\n(m-2-1) edge node [above] {$g_2$} (m-2-2)\nedge[bend right=45] node [below] {$h_2\\circ g_2$} (m-2-3)\n(m-2-2) edge node [above] {$h_2$} (m-2-3) \n;\n\\end{tikzpicture} \n\\]\n\nObserve that there are 2 functors:\n\n\\[\n\\begin{gathered} \n\\begin{tikzpicture}\n\\matrix (m) [matrix of math nodes, row sep=3.8em, column sep=4.8em, minimum width=2.2em]\n{\n\t\\mathbf{C} & \\mathbf{C}^{\\rightarrow} & \\mathbf{C} \\\\\n};\n\\path[->]\n(m-1-2) edge node [above] {$\\textbf{dom}$} (m-1-1)\nedge node [auto] {$\\textbf{cod}$} (m-1-3)\n;\n\\end{tikzpicture} \n\\end{gathered}\n\\]\n\n\\item \\emph{algebra} cf. pp. 14, Sec. 3, \"Functors\" of Mac Lane (1978) \\cite{MacL1978}.\n\n$\\forall \\, $ commutative ring $K$, set of all non-singular $n\\times n$ matrices with entries in $K = $ general linear group $GL_n(K)$. \\\\\n$\\forall \\, $ homomorphism $f: K \\to K'$ of rings produces \\\\\nhomomorphism $GL_n f : GL_n(K) \\to GL_n(K)$ of groups. \\\\\n\n$\\forall \\, n \\in \\mathbb{N}$ (natural numbers), defined functor $GL_n: \\textbf{CRng} \\to \\textbf{Grp} \\equiv GL_n \\textbf{CommRing} \\to \\textbf{Grp}$. \\\\\n\n\n$\\forall \\, $ group $G$, set of all products of commutators $xyx^{-1} y^{-1}$ ($x,y \\in G$) is a normal subgroup $[G, G]$ of $G$ called commutator subgroup. \\\\\n\nSince $\\forall \\, $ homomorphism $G \\to H$ of groups carries commutators to commutators. \\\\\n$G \\mapsto [G, G]$ defines evident functor $\\textbf{Grp} \\to \\textbf{Grp}$, \\\\\nwhile $G \\mapsto G/[G, G]$ define functor $\\textbf{Grp} \\to \\textbf{Ab}$, factor-commutator functor. \\\\\nTODO - understand the previous commutators.\n\n\\end{itemize} \n\n\\subsubsection{Endofunctor}\n\n\\begin{definition}[Endofunctor]\\label{Def:Endofunctor}\nConsider \\textbf{endofunctor} $T : \\mathbf{C} \\to \\mathbf{C}$. This implies that, for the \\\\\n\nobject map $\\begin{aligned} & \\quad \\\\ \n\t& T : \\text{Obj}{\\mathbf{C}} \\to \\text{Obj}{\\mathbf{C}} \\\\ \n\t& T : X \\to Y \\end{aligned}$, \\\\\n\t\n\tobject map $T$ acts like a morphism, in $\\text{Mor}\\mathbf{C}$ (!!!). In this case $T$ acts like $T\\in \\text{Hom}_{\\mathbf{C}}(X, Y)$. \\\\\n\t\n\tmorphism map $T: \\text{Hom}_{\\mathbf{C}}(X, Y) \\to \\text{Hom}_{\\mathbf{C}}(F(X), F(Y))$ s.t. \n\t\\begin{equation}\n\t\\begin{gathered} \n\t\tT(f) \\equiv Tf:T(X) \\to T(Y) \\text{ so that } Tf \\in \\text{Hom}_{\\mathbf{C}}(T(X), T(Y)) \\\\\n\t\tT(1_X) = 1_{T(X)} \\in \\text{Hom}_{\\mathbf{C}}(T(X), T(Y)) (\\text{implied from Kashiwara and Schapira (2006) \\cite{KaSch2006} in that} \\, 1_X \\in \\text{Hom}(X,X)) \\\\\n\t\tT(g\\circ f) = T(g) \\circ T(f), \\, \\forall \\, f:X \\to Y, \\, g:Y \\to Z, \\, X,Y,Z\\in \\text{Obj}{\\mathbf{C}}\n\t\\end{gathered} \n\t\\end{equation} \n\tSo $T(f) \\equiv Tf$ is indeed a morphism map.\n\n\\end{definition}\n\n\\subsubsection{Hom functors}\n\nLet $\\mathbf{C}$ locally-small category (i.e. category s.t. hom-classes are actually sets and not proper classes).\n\n$\\forall \\, A, B \\in \\text{Obj}\\mathbf{C}$, \n\n\\begin{definition}[covariant Hom functor]\n\t\\textbf{covariant Hom functor} $\\text{Hom}(A, -): \\mathbf{C} \\to \\mathbf{Set}$\n\t\\begin{equation}\n\t\\begin{aligned}\n\t& \\text{Hom}(A, - ) : \\text{Obj}\\mathbf{C} \\to 2^{\\text{Mor}(\\mathbf{C})} \\\\ \n\t& \\text{Hom}(A, - ) : X \\mapsto \\text{Hom}(A,X) \\\\ \n\t& \\text{Hom}(A, - ) : \\text{Mor}\\mathbf{C} \\to (\\text{Mor}(\\mathbf{C}) \\to \\text{Mor}(\\mathbf{C})) \\\\\n\t& \\text{Hom}(A, - ) : \\text{Hom}(X,Y) \\to (\\text{Hom}(A,X) \\to \\text{Hom}(A,Y)) \\\\\n\t& \\text{Hom}(A, - ) : f \\mapsto \\text{Hom}(A,f) \\text{ where } \\\\\n\t& \\begin{aligned} \\text{Hom}(A,f) : & \\text{Hom}(A,X) \\to \\text{Hom}(A,Y) \\\\ \n\t& g\\mapsto f\\circ g \\quad \\, \\forall \\, g \\in \\text{Hom}(A,X) \n\t\\end{aligned} \n\t\\end{aligned}\n\t\\end{equation}\n\\end{definition}\n\n\\begin{claim}\n$\\text{Hom}(A, -)$ is a functor.\n\\end{claim}\n\n\\begin{proof}\n\t\\begin{itemize}\n\t\t\\item \\emph{identity}: $\\text{Hom}(A,-) : 1_X \\mapsto \\text{Hom}(A, 1_X) \\text{ where }$ \n\t\t\\[\n\t\t\\begin{aligned}\n\t\t\t\\text{Hom}(A, 1_X) : & \\text{Hom}(A,X) \\to \\text{Hom}(A,X) \\\\ \n\t\t\t& g\\mapsto 1_X \\cdot g = g , \\quad \\, \\forall \\, g\\in \\text{Hom}(A,X)\n\t\t\\end{aligned}\n\t\t\\]\n\t\tHence\n\t\t\\[\n\t\t\\text{Hom}(A, -)(1_X) = 1_{\\text{Hom}(A,X)} \\in (\\text{Hom}(A,X) \\to \\text{Hom}(A,X))\n\t\t\\]\n\t\t\\item \\text{composition}: Let \n\t\t\\[\n\t\t\\begin{aligned}\n\t\t& f \\in \\text{Hom}(X,Y) \\\\ \n\t\t& g \\in \\text{Hom}(Y,Z) \\\\ \n\t\t& k \\in \\text{Hom}(A,X) \n\t\t\\end{aligned}\n\t\t\\]\n\t\t\\[\n\t\t\\text{Hom}(A, g) \\circ \\text{Hom}(A,f)(k) = \\text{Hom}(A,g)(f\\circ k) = g\\circ f \\circ k = (g\\circ f)(k) = \\text{Hom}(A, g\\circ f)(k)\n\t\t\\]\n\t\\end{itemize}\n\\end{proof}\n\n\\begin{definition}[contravariant Hom functor]\n\t\\textbf{contravariant Hom functor} $\\text{Hom}(-, B): \\mathbf{C} \\to \\mathbf{Set}$\n\t\\begin{equation}\n\t\\begin{aligned}\n\t& \\text{Hom}(-, B ) : \\text{Obj}\\mathbf{C} \\to 2^{\\text{Mor}(\\mathbf{C})} \\\\ \n\t& \\text{Hom}(-, B ) : X \\mapsto \\text{Hom}(X,A) \\\\ \n\t& \\text{Hom}(-, B ) : \\text{Mor}\\mathbf{C} \\to (\\text{Mor}(\\mathbf{C}) \\to \\text{Mor}(\\mathbf{C})) \\\\\n\t& \\text{Hom}(-, B ) : \\text{Hom}(X,Y) \\to (\\text{Hom}(Y,B) \\to \\text{Hom}(X,B)) \\\\\n\t& \\text{Hom}(-, B ) : h \\mapsto \\text{Hom}(h,B) \\text{ where } \\\\\n\t& \\begin{aligned} \\text{Hom}(h,B) : & \\text{Hom}(Y,B) \\to \\text{Hom}(X,B) \\\\ \n\t& g\\mapsto g\\circ h \\quad \\, \\forall \\, g \\in \\text{Hom}(Y,B) \n\t\\end{aligned} \n\t\\end{aligned}\n\t\\end{equation}\n\\end{definition}\n\n$\\text{Hom}(A,-)$, $\\text{Hom}(-,B)$ are related in a natural manner: for\n\\[\n\\begin{gathered}\n\\begin{aligned}\n& f : B\\to B', \\, f\\in \\text{Hom}(B,B') \\\\ \n& g:A \\to A', \\, g\\in \\text{Hom}(A,A')\n\\end{aligned} \\\\\n\\begin{aligned}\n& \\text{Hom}(A,f) : \\text{Hom}(A, B) \\to \\text{Hom}(A,B') \\\\ \n& \\text{Hom}(g, B) : \\text{Hom}(A,B) \\to \\text{Hom}(A', B)\n\\end{aligned}\n\\end{gathered}\n\\]\n\n\\[\n\\begin{gathered}\n\\begin{tikzpicture}\n\\matrix (m) [matrix of math nodes, row sep=4.8em, column sep=4.8em, minimum width=4.2em]\n{\n\t\\text{Hom}(A,B) & \\text{Hom}(A',B) \\\\\n\t\\text{Hom}(A,B') & \\text{Hom}(A',B') \\\\\n};\n\\path[->]\n(m-1-1) edge node [above] {$\\text{Hom}(g,B)$} (m-1-2)\n edge node [left] {$\\text{Hom}(A,f)$} (m-2-1)\n(m-1-2) edge node [right] {$\\text{Hom}(A',f)$} (m-2-2)\n(m-2-1) edge node [above] {$\\text{Hom}(g,B')$} (m-2-2)\n;\n\\end{tikzpicture}\n\\end{gathered}\n\\]\n\n\\begin{definition}[2-variable Hom functor]\n\t2-variable Hom functor $\\text{Hom}(-,-)$ is a bifunctor.\n\t\\[\n\t\\text{Hom}(-,-) : \\mathbf{C}^{\\text{op}} \\times \\mathbf{C} \\to \\textbf{Set} \n\t\\]\n\t\n\\[\n\\begin{gathered}\n\\begin{tikzpicture}\n\\matrix (m) [matrix of math nodes, row sep=4.8em, column sep=4.8em, minimum width=4.2em]\n{\n\t& D \\\\\n\tC & B \\\\\n\tA & \\\\\n};\n\\path[->]\n(m-2-1) edge node [left] {$f\\circ g \\circ h$} (m-1-2)\nedge node [above] {$ g \\circ h$} (m-2-2)\nedge node [left] {$ h$} (m-3-1)\n(m-2-2) edge node [right] {$f$} (m-1-2)\n(m-3-1) edge node [right] {$g$} (m-2-2)\n;\n\\end{tikzpicture}\n\\end{gathered}\n\\]\n\n$\\text{Hom}(-,-)$ is a functor such that:\n\\[\n\\begin{gathered}\n\\begin{aligned} \n& \\text{Hom}(h, f)(g) = f\\circ g \\circ h \\\\\n& \\text{Hom}(h, f) : \\text{Hom}(A, B) \\to \\text{Hom}(C, D) \n\\end{aligned} \\\\\n\\begin{aligned}\n& h : C \\to A, \\, h \\in \\text{Hom}(C,A) \\\\ \n& f: B\\dot D, \\, f \\in \\text{Hom}(B,D)\n\\end{aligned} \\\\\n(h,f) \\in \\text{Hom}(C,A) \\times \\text{Hom}(B,D) \\mapsto \\text{Hom}(h,f) \\in (\\text{Hom}(A,B) \\to \\text{Hom}(C,D)) \\\\\n\\text{Hom}(-,-) : \\text{Hom}(C,A) \\times \\text{Hom}(B,D) \\to (\\text{Hom}(A,B) \\to \\text{Hom}(C,D) )\n\\end{gathered}\n\\]\nand \n\\[\n\\begin{aligned}\n& \\text{Hom}(-,-) : \\text{Obj}\\mathbf{C}^{\\text{op}} \\times \\mathbf{C} \\\\ \n& \\text{Hom}(-,-) : (C,D) \\mapsto \\text{Hom}(C,D)\n\\end{aligned}\n\\]\n\\end{definition}\n\n\n\\section{Construction of Categories}\n\n\\subsection{Slice category}\n\ncf. Construction 4 of Awodey (2010) \\cite{Awod2010}, pp. 15.\n\n\\textbf{Slice category} $\\mathbf{C}/C$, of category $\\mathbf{C}$ over object $C \\in \\text{Obj}\\mathbf{C}$, \\\\\n$\\text{Obj}\\mathbf{C}/C \\ni f \\in \\text{Mor}\\mathbf{C}$ s.t. $\\text{cod}(f) = C$ \\\\\n$\\text{Mor}\\mathbf{C}/C \\ni g$ from $f:X \\to C$ to $f':X' \\to C$ is a morphism (arrow) \\, $g: X\\to X'$ in $\\mathbf{C}$ s.t. $f'\\circ g = f$\n\n\\begin{equation}\n\\begin{gathered}\n\t\\begin{tikzpicture}\n\\matrix (m) [matrix of math nodes, row sep=5em, column sep=5em, minimum width=2em]\n{\n\tX & & X' \\\\\n\t& C & \\\\\n};\n\\path[->]\n(m-1-1) edge node [above] {$g$} (m-1-3)\n(m-1-1) edge node [below] {$f$} (m-2-2)\n(m-1-3) edge node [below] {$f'$} (m-2-2);\n\\end{tikzpicture} \\qquad \\, \n\t\\begin{tikzpicture}\n\\matrix (m) [matrix of math nodes, row sep=5em, column sep=5em, minimum width=2em]\n{\n\tX \\\\\n\tC \\\\\n};\n\\path[->]\n(m-1-1) edge node [left] {$f$} (m-2-2)\nedge [loop right] node [right] {$1_{\\mathbf{C}/C}$} (m-1-1);\n\\end{tikzpicture} \\qquad \\, \n\t\\begin{tikzpicture}\n\\matrix (m) [matrix of math nodes, row sep=5em, column sep=5em, minimum width=2em]\n{\n\tX & X' & X'' \\\\\n\t& C & \\\\\n};\n\\path[->]\n(m-1-1) edge node [above] {$g$} (m-1-2)\n\tedge node [left] {$f$} (m-2-1)\n(m-1-2) edge node [above] {$h$} (m-1-3)\nedge node [left] {$f'$} (m-2-2)\n(m-1-3) edge node [right] {$f''$} (m-2-2);\n\\end{tikzpicture}\n\\end{gathered}\n\\end{equation}\n\nIf $\\mathbf{C} = \\mathbf{P}$ poset category, $p\\in \\mathbf{P}$ (i.e. $p \\in \\text{Obj}(\\mathbf{P})$), then\n\\[\n\\mathbf{P} / p \\simeq \\downarrow (p)\n\\]\nSlice category $\\mathbf{P} / p$ is just the \"principal ideal\" $\\downarrow(p)$ of elements $q\\in \\mathbf{P}$ with $q \\leq p$.\n\n\\subsubsection{$S$-indexed set $X$ and indexed functions as morphisms of slice category $\\mathbf{Set}/S$}\n\n\\begin{definition}[typed set]\n\t$S$-indexed set is set $X$ together with function $\\tau : X \\to S$. \\\\\n\t\n\tIf $x\\in X$, $\\tau(x) = s$, then $x$ is of \\textbf{type} $s$, so $X$ is a \\textbf{typed set}. \\\\\n\t\n\t$\\lbrace \\tau^{-1}(s) | s \\in S \\rbrace$, $\\tau^{-1}(s) \\subset X \\equiv $ family of sets indexed by $S$. \\\\\n\t\n\\end{definition} \ncf. 2.6.11 of Barr and Wells (2012) \\cite{BaWe2012}\n\n\\begin{definition}\n\tset $X$ typed by $S \\to $ set $X'$ typed by $S$ that preserves typing (element of type $s\\mapsto $ element of type $s$), is exactly an arrow (morphism) of slice category $\\mathbf{Set}/S$, called \\textbf{indexed function} or \\textbf{typed function}.\n\\end{definition}\n\ncf. 2.6.13 Indexed functions of Barr and Wells (2012) \\cite{BaWe2012}\n\n\\subsubsection{Underlying functor of the slice $F$}\n\nLet $f: A\\to C$, $f\\in \\text{Hom}(A,C) \\subset \\text{Mor}\\mathbf{C}$ and $f\\in \\text{Obj}\\mathbf{C}/C$. \\\\\n\nLet $f,g \\in \\text{Obj}\\mathbf{C}/C$, s.t. $f\\in \\text{Hom}(A,C)$, $g\\in \\text{Hom}(B,C)$ \\\\\n$h\\in \\text{Hom}(f,g) \\subseteq \\text{Mor}\\mathbf{C}/C$ in that \\\\\n$h : f\\to g$ s.t. $h:A \\to B$, so that $g\\circ h = f$. \\\\\n\n\\textbf{underlying functor of the slice $F$} (notation $U$ in Barr and Wells (2012) \\cite{BaWe2012}):\n\n\\begin{equation}\n\\begin{aligned}\n& F: \\mathbf{C} /C \\to \\mathbf{C} \\\\ \n& F:\\text{Obj}\\mathbf{C}/C \\to \\text{Obj}\\mathbf{C} \\\\ \n& F:f\\mapsto F(f) = A \\\\ \n& F:\\text{Mor}\\mathbf{C}/C \\to \\text{Mor}\\mathbf{C} \\\\ \n& F: h \\mapsto h \n\\end{aligned} \n\\end{equation}\n\nSpecial case: $\\mathbf{C} = \\textbf{Set}$, $C = S \\ni \\text{Obj}\\textbf{Set}$, i.e. $S$ is a set.\n\nFor $f\\in \\text{Obj}\\textbf{Set}/S$, $f: T \\to S$, where $T$ is a set, object $f$ is an $S$-indexed set. (e.g. $x(i) \\in T \\subset \\mathbb{R}$, where for some $y\\in T \\subset \\mathbb{R}$, $\\exists \\, i \\in \\mathbb{Z}$ s.t. $y\\mapsto i$).\n\n\\[\n\\begin{aligned}\n& F:\\textbf{Set}/S \\to \\textbf{Set} \\\\ \n& F:f \\mapsto T\n\\end{aligned}\n\\]\n\nThe underlying functor $F$ forgets the $S$-indexing.\n\n\\subsubsection{Coslice category}\n\n\\[\n\t\\begin{tikzpicture}\n\\matrix (m) [matrix of math nodes, row sep=5em, column sep=5em, minimum width=2em]\n{\n\tX & & X' \\\\\n\t& C & \\\\\n};\n\\path[->]\n(m-1-3) edge node [above] {$\\overline{g}$} (m-1-1)\n(m-2-2) edge node [below] {$\\overline{f}$} (m-1-1)\n edge node [below] {$\\overline{f'}$} (m-1-3);\n\\end{tikzpicture} \n\\]\n\nCoslice category $C/\\mathbf{C}$ of category $\\mathbf{C}$ under object $C \\in \\text{Obj}\\mathbf{C}$: \\\\\n$\\text{Obj}(C/\\mathbf{C}) = \\overline{f} \\in \\text{Mor}\\mathbf{C}$ s.t. $\\text{dom}\\overline{f} = \\overline{C} = C$, \\\\\n$\\text{Mor}(C/\\mathbf{C}) \\ni \\begin{aligned} & \\quad \\\\ & \\overline{g} : \\overline{X}' \\to \\overline{X} \\text{s.t. } \\\\\n& \\overline{g} \\circ \\overline{f'} = \\overline{f} \\end{aligned}$ \n\ncf. Example 1.8 of Awodey (2010) \\cite{Awod2010}, pp. 15. \\emph{pointed sets}\n\n$\\textbf{Sets}_*$ of pointed sets consisting of sets $A$ and distinguished element $a\\in A$, and, i.e. \\\\\n$\\text{Obj}\\textbf{Set}_* \\ni $ set $A$ with distinguished element $a\\in A$, \\\\\n$\\text{Mor}\\textbf{Set}_* \\ni f : (A, a) \\to (B, b)$, function $f:A\\to B$ preserves the \"points\" $f(a) = b$.\n\n\\[\n\\textbf{Sets}_* = \\textbf{Set}_* \\simeq 1 / \\textbf{Sets}\n\\]\ni.e. $\\textbf{Sets}_*$ isomorphic to coslice category of sets \"under\" any singleton $1 = \\lbrace * \\rbrace$\n\n\\quad \\\\ \nfunctions $a: 1 \\to A$ correspond uniquely to elements \\\\\n\\phantom{functions} $a(*) = a \\in A$ \\\\\nmorphisms (arrows) $f:(A, a) \\to (B, b)$ correspond exactly to \n\\[\n\\begin{tikzpicture}\n\\matrix (m) [matrix of math nodes, row sep=5em, column sep=4em, minimum width=3em]\n{\n\t1 & A \\\\ \n\t& B \\\\\n};\n\\path[->]\n(m-1-1) edge node [above] {$a$} (m-1-2)\nedge node [left] {$b$} (m-2-2)\n(m-1-2) edge node [auto] {$f$} (m-2-2)\n;\n\\end{tikzpicture} \n\\]\n\n\\subsection{Free monoid}\n\nGiven set $S$, e.g. $S = $ \"alphabet\" $A$, \\\\\n\\emph{free monoid} $S^*$ is set $S^*$. \\\\\n\n$S^* = $ set of all lists (finite sequences) of elements of $S$, \\\\\ne.g. set of all \\emph{words} (finite sequence of letters) \\emph{over $A$ } $= A^*$. \\\\\n\n\\emph{Concatenation}: $* : \\, \\forall \\, w , w^* \\in A^*$, $w * w' = ww'$ \\\\\nempty list (e.g. empty word \"-\"), $()$, $*$, or $\\epsilon$ is a unit. Or we'll use this notation: \\texttt{\"\"}\n\n\\[\n\\Longrightarrow (S^*, *, \\texttt{\"\"}) \\text{is a monoid. }\n\\]\n\nmonoid $M$ is \\textbf{freely generated} by subset $A$ of $M$, if \n\\begin{enumerate}\n\t\\item \"no junk\": $\\forall \\, m \\in M$, $m$ can be written as product of elements of $A$,\n\t\\[\n\tm = a_1 \\dots a_n, \\, a_i \\in A \n\t\\]\n\t\\item \"no noise\": no \"nontrivial\" relations hold in $M$, i.e. if $a_1 \\dots a_j = a_1' \\dots a_k'$, then this is required by the axioms for monoid.\n\\end{enumerate}\n\n$A^* = $ Kleene closure.\n\n\\subsubsection{Free monoid functor: underlying functor}\n\n\\[\n\\begin{aligned}\n& F: \\textbf{Set} \\to \\textbf{Mon} \\\\\n& F: A \\in \\text{Obj}\\textbf{Set} \\mapsto \\text{ free monoid } F(A) = \\text{ Kleene closure } A^* \n\\end{aligned}\n\\]\nFor $f:A \\to B$, $f\\in \\text{Hom}_{\\textbf{Set}}(A, B)$, \n\\[\n\\begin{aligned}\n& F: f\\mapsto F(f) \\text{ s.t. } \\\\\n& F(f)(w) = F(f)(a_1 \\dots a_m) = (f(a_1), \\dots f(a_m)) = w' \\in B^*, \\text{ i.e. } \\\\\n& F(f) = f^* : F(A) \\to F(B)\n\\end{aligned}\n\\]\n\n\n\\section{Universal mapping property}\n\n\\subsection{Examples of Universal mapping property}\n\ncf. Ch. 0 \"Introduction\" of Leinster (2014) \\cite{Lein2014}.\n\nExample 0.1. Let $\\lbrace 1 \\rbrace$ denote set with 1 element. \\\\\nThen $\\forall \\, $ sets $X \\in \\textbf{Set}$, $\\exists \\, ! $ map $X \\to \\lbrace 1 \\rbrace$\n\\[\nX \\xrightarrow{ f} \\lbrace 1 \\rbrace \n\\]\n\n\\begin{proof}\n$\\exists \\, X \\to \\lbrace 1 \\rbrace$, $\\forall \\, X$ because define $f: X \\to \\lbrace 1 \\rbrace$ s.t. $f(x) = 1$, $\\forall \\, x \\in X$. \\\\\n(!) if for $X \\to \\lbrace 1 \\rbrace$, then $x\\mapsto 1$, so map is equal to $f$.\n\\end{proof} \n\nExample 0.2. $\\forall \\, $ rings $R$ with multiplicative identity $1$, $\\exists \\, !$ homomorphism $\\mathbb{Z} \\to R$. \\label{Example:integerringhomomorphism}\n\nDefine $\\phi : \\mathbb{Z} \\to R$ by \n\\[\n\\phi(n) = \\begin{cases} \\sum_{i=1}^n 1 & \\text{ if } n > 0 \\\\ \n0 & \\text{ if } n = 0 \\\\\n-\\phi(-n) & \\text{if } n < 0 \\end{cases} \n\\]\n\nCheck that $\\phi$ homomorphism. (TODO)\\\\\n\n(!) $\\psi(1)= 1$ (homomorphisms preserve multiplicative identities) \\\\\nhomomorphisms preserve addition:\n\\[\n\\psi(n) = \\psi(\\sum_{i=1}^n 1) = \\sum_{i=1}^n \\psi(1) = \\sum_{i = 1}^n 1 = \\phi(n)\n\\]\n\nhomomorphisms preserve zero: $\\psi(0) = 0 = \\phi(0)$\n\nhomomorphisms preserve negatives: $\\psi(n) = -\\psi(-n) = -\\sum_{i=1}^{-n} 1 = -\\phi(-n) = \\phi(n)$.\n\n\\begin{lemma}[0.3 Leinster (2014) \\cite{Lein2014}]\n\tLet ring $A$ s.t. $\\forall \\,$ rings $R, \\exists \\, !$ homomorphism $A \\to R$ (i.e. $A$ is \"initial\"). Then $A \\cong \\mathbb{Z}$ (isomorphic). \t\n\\end{lemma}\n\n\\begin{proof}\n\t\t$A$ initial, so $\\exists \\, !$ homomorphism $\\phi:A \\to \\mathbb{Z}$. \\\\\n\t\t$\\mathbb{Z}$ initial from Ex. \\ref{Example:integerringhomomorphism}. $\\exists \\, !$ homomorphism $\\phi' : \\mathbb{Z} \\to A$. \\\\\n\t\t\n\t\t$\\phi' \\circ \\phi : A \\to A$, $1_A : A \\to A$ are homomorphisms. \\\\\n\t\tSince $A$ initial, $\\phi' \\circ \\phi = 1_A$. \\\\\n\t\t$\\phi \\circ \\phi' : \\mathbb{Z}\\to \\mathbb{Z}$. Since $\\mathbb{Z}$ initial, $1_{\\mathbb{Z}} : \\mathbb{Z} \\to \\mathbb{Z} \\Longrightarrow \\phi \\circ \\phi' = 1_{\\mathbb{Z}}$. \n\t\t\\[\n\t\t\\Longrightarrow A \\cong \\mathbb{Z} \\text{ (isomorphic) }\n\t\t\\]\n\\end{proof}\n\nExample 0.4. pp. 3 Leinster (2014) \\cite{Lein2014} Let vector space $V$ with basis $(v_s)_{s \\in S}$ (.e.g if $V$ finite-dim., e.g. $S = \\lbrace 1, 2 \\dots , n \\rbrace$). \\\\\nThus $\\forall \\, $ vector space $W$, $\\exists \\, $ natural 1-to-1 correspondence between linear maps $\\lbrace V \\to W \\rbrace$ and functions $S \\to W$. \\\\\ni.e. define $\\begin{aligned} & \\quad \\\\ \n& i : S \\to V \\\\\n& i(s) = v_s \\quad \\, (s \\in S)\\end{aligned}$ \n\nThen universal mapping property (given $i, f, \\exists \\, ! \\overline{f}$)\n\\[\n\\begin{gathered} \n\t\\begin{tikzpicture}\n\\matrix (m) [matrix of math nodes, row sep=5em, column sep=4em, minimum width=3em]\n{\n\tS & V \\\\ \n\t & W \\\\\n};\n\\path[->]\n(m-1-1) edge node [above] {$i$} (m-1-2)\n edge node [below] {$f$} (m-2-2)\n;\n\\path[dashed,->]\n(m-1-2) edge node [right] {$\\overline{f}$} (m-2-2)\n;\n\\end{tikzpicture} \\text{ or } \\begin{tikzpicture}\n\\matrix (m) [matrix of math nodes, row sep=5em, column sep=4em, minimum width=3em]\n{\n\tV & W \\\\ \n\tS & \\\\\n};\n\\path[dashed,->]\n(m-1-1) edge node [above] {$\\overline{f}$} (m-1-2)\n;\n\\path[->]\n(m-2-1) edge node [left] {$i$} (m-1-1)\nedge node [below] {$f$} (m-1-2)\n;\n\\end{tikzpicture}\n\\end{gathered} \n\\]\n\n\\[\n\\begin{gathered}\n\\begin{aligned}\n\\lbrace S \\to W \\rbrace & \\to \\lbrace \\text{ linear } V \\to W \\rbrace \\\\\n\\overline{f} \\circ i & \\mapsto \\overline{f} \n\\end{aligned} \\quad \\, \\text{ bijective }\n\\end{gathered}\n\\]\n\nExample 0.5. pp. 4 Leinster (2014) \\cite{Lein2014}. Given set $S$, topological space $D(S)$; equip $D(S)$ with discrete topology (all subsets open). \\\\\n$\\Longrightarrow \\forall \\, $ map $S \\to $ space $X$ is cont. \n\ni.e. \n\\[\n\\begin{gathered}\n\\begin{tikzpicture}\n\\matrix (m) [matrix of math nodes, row sep=5em, column sep=4em, minimum width=3em]\n{\n\tD(S) & X \\\\ \n\tS & \\\\\n};\n\\path[dashed,->]\n(m-1-1) edge node [above] {$\\overline{f}$} (m-1-2)\n;\n\\path[->]\n(m-2-1) edge node [left] {$i$} (m-1-1)\nedge node [below] {$f$} (m-1-2)\n;\n\\end{tikzpicture}\n\\end{gathered}\n\\]\n\n$\\forall \\, $ topological space $X$, $\\forall \\, f : S \\to X$, $\\exists \\, !$ cont. $\\overline{f} : D(S) \\to X$ s.t. $\\overline{f} \\circ i = f$. \\\\\nIf $D(S)$ equipped with indiscrete topology (open $S = \\lbrace \\phi, S \\rbrace$), then property is false.\n\nExample 0.6. pp. 4 Leinster (2014) \\cite{Lein2014}. Given vector space $U, V, W$, bilinear map $f: U\\times V \\to W$ is linear. \n\\[\n\\begin{gathered}\nf(u, v_1 + \\lambda v_2) = f(u, v_1) + \\lambda f(u, v_2) \\\\\nf(u_1 + \\lambda u_2, v) = f(u_1, v) + \\lambda f(u_2, v)\n\\end{gathered}\n\\]\n$\\forall \\, u, u_1, u_2 \\in U$, $v, v_1,v_2 \\in V$, scalars $\\lambda$. \\\\\ne.g. scalar product (dot product) $\\mathbf{u}\\cdot \\mathbf{v}$ bilniear, cross product bilinear. \\\\\n\n$\\exists \\, $ \"universal bilinear map out of $U\\times V$\", i.e. \\\\\n$\\exists \\, $ vector space $T$, $\\exists \\, $ bilinear map $b:U\\times V \\to T$\n\n\\[\n\\begin{gathered}\n\\begin{tikzpicture}\n\\matrix (m) [matrix of math nodes, row sep=5em, column sep=4em, minimum width=3em]\n{\n\tT & W \\\\ \n\tU \\times V & \\\\\n};\n\\path[dashed,->]\n(m-1-1) edge node [above] {$\\overline{f}$} (m-1-2)\n;\n\\path[->]\n(m-2-1) edge node [left] {$b$} (m-1-1)\nedge node [below] {$f$} (m-1-2)\n;\n\\end{tikzpicture}\n\\end{gathered}\n\\]\ni.e. $\\forall \\, $ bilinear $f$, given $b$, $\\exists \\, !$ linear $\\overline{f}$, s.t. $\\overline{f} \\circ b = f$\n\n\\begin{lemma}[0.7, pp. 5 Leinster (2014) \\cite{Lein2014}]\\label{Lemma:UniveralMappingVectorSpaceProducts}\n\tLet vector spaces $U, V$. Suppose $\\begin{aligned} & \\quad \\\\ \n\t& b : U \\times V \\to T \\\\\n\t& b' : U\\times V \\to T'\\end{aligned}$ \\quad , both universal bilinear maps. \n\t\n\tThen $T \\cong T'$, i.e. $\\exists \\, !$ isomorphism $j: T \\to T'$ s.t. $j\\circ b = b'$\n\\end{lemma}\n\n\\begin{proof}\n\tTake $b': U\\times V \\to T' \\Longrightarrow \\exists \\, b$, $\\exists \\, !$ linear map $j: T \\to T'$ s.t. $j\\circ b = b'$. \n\t\n\tTake $b:U \\times V \\to T$. $\\exists \\, b'$, $\\exists \\, !$ linear map $j':T' \\to T$ s.t. $j'\\circ b' = b$\n\t\n\n\\[\n\\begin{gathered}\n\\begin{tikzpicture}\n\\matrix (m) [matrix of math nodes, row sep=5em, column sep=4em, minimum width=3em]\n{\n\tT & T' \\\\ \n\tU \\times V & T \\\\\n};\n\\path[dashed,->]\n(m-1-1) edge node [above] {$j$} (m-1-2)\n(m-1-2) edge node [above] {$j'$} (m-2-2)\n;\n\\path[->]\n(m-2-1) edge node [left] {$b$} (m-1-1)\nedge node [below] {$b'$} (m-1-2)\nedge node [below] {$b$} (m-2-2)\n;\n\\end{tikzpicture}\n\\end{gathered}\n\\]\nNow linear $j'\\circ j : T\\to T$, s.t. $(j'\\circ j) \\circ b = b$. \n\nBut also $1_T : T\\to T$ linear and $1_T \\circ b = b$\n\n\\[\n\\Longrightarrow j' \\circ j = 1_T\n\\]\ni.e. \n\\[\n\\begin{gathered}\n\\begin{tikzpicture}\n\\matrix (m) [matrix of math nodes, row sep=5em, column sep=4em, minimum width=3em]\n{\n\tT & T \\\\ \n\tU \\times V & \\\\\n};\n\\path[dashed,->]\n(m-1-1) edge node [above] {$j'\\circ j$} (m-1-2)\n;\n\\path[->]\n(m-2-1) edge node [left] {$b$} (m-1-1)\nedge node [below] {$b$} (m-1-2)\n;\n\\end{tikzpicture}\n\\qquad \\, \\text{ but so is } \\begin{tikzpicture}\n\\matrix (m) [matrix of math nodes, row sep=5em, column sep=4em, minimum width=3em]\n{\n\tT & T \\\\ \n\tU \\times V & \\\\\n};\n\\path[dashed,->]\n(m-1-1) edge node [above] {$1_T$} (m-1-2)\n;\n\\path[->]\n(m-2-1) edge node [left] {$b$} (m-1-1)\nedge node [below] {$b$} (m-1-2)\n;\n\\end{tikzpicture}\n\\end{gathered}\n\\]\n\nSimilarly for $j\\circ j' = 1_{T'}$. \n\nSo $j$ is an isomorphism.\n\n\\end{proof} \n\nBy Lemma \\ref{Lemma:UniveralMappingVectorSpaceProducts}, $\\exists \\, !$ tensor product $U\\otimes V$, not \"a\" tensor product.\n\nExample 0.8 of Leinster (2014) \\cite{Lein2014}. Let $\\theta : G \\to H$ be homomorphism of groups.\n\n\\[\n\\begin{tikzcd}\n\\text{ker}{(\\theta)} \\arrow[r, hook, \"i\"] & G \\arrow[r, shift left, \"\\theta\"] \\arrow[r, shift right, \"\\epsilon\"]& H \\\\\n\\end{tikzcd}\n\\]\n\nwhere $i$ inclusion, $\\epsilon$ trivial homomorphism, i.e.$i(x) = x \\, \\forall \\, x \\in \\text{ker}(\\theta)$, $\\epsilon(g) = 1$ \\, $\\forall \\, g \\in G$.\n\nmap $i$ into $G$ s.t. $\\theta \\circ i = \\epsilon \\circ i$ and is universal (Ex. 0.11)\n\nExample 0.9 of Leinster (2014) \\cite{Lein2014}. Let topological space $X = U \\cup V$ be covered by 2 open subsets $U, V$.\n\n\\[\n\\begin{tikzcd}[sep=large] \n\tU \\cap V \\arrow[r, hook, \"i\"] \\arrow[d, hook, \"j\"] & U \\arrow[d, hook, \"j'\"] \\\\\n\tV \\arrow[r, hook, \"i'\"] & X\n\\end{tikzcd}\n\\]\nhas universal property\n\\[\n\\begin{tikzcd}[sep=large] \nU \\cap V \\arrow[r, hook, \"i\"] \\arrow[d, hook, \"j\"] & U \\arrow[d, hook, \"j'\"] \\arrow[ddr, \"f\"] & \\\\\nV \\arrow[r, hook, \"i'\"] \\arrow[drr, \"g\"] & X \\arrow[dr, dotted, \"h\"] & \\\\\n& & Y \n\\end{tikzcd}\n\\]\n$\\forall \\, g, Y, f$ s.t. $f\\circ i = g\\circ j$, $\\exists ! \\, $ cont. $h: X\\to Y$ s.t. $h\\circ j' = f$, $h\\circ i' = g$.\n\nUnder favorable conditions, induced diagram of fundamental groups.\n\n\\[\n\\begin{tikzcd}[sep=large] \n\\pi_1(U \\cup V) \\arrow[r, \"i_*\"] \\arrow[d, \"j_*\"] & \\pi_1(U) \\arrow[d, \"j'_*\"] \\\\\n\\pi_1(V) \\arrow[r, \"i'_*\"] & \\pi_1(X)\n\\end{tikzcd}\n\\]\nhas same universal property: Van Kampen's thm.\n\n\\[\n\\begin{aligned}\n& \\theta : G \\to H \\\\ \n& \\epsilon : G \\to H\n\\end{aligned}\n\\]\n\n$\\theta, \\epsilon$ have common domain and codomain.\n\n$i: \\text{ker}(\\theta) \\to G$ is s.t. $\\theta \\circ i = \\epsilon \\circ i$\n\n\\[\n\\begin{tikzcd}\n\\text{ker}{(\\theta)} \\arrow[r, hook, \"i\"] & G \\arrow[r, shift left, \"\\theta\"] \\arrow[r, shift right, \"\\epsilon\"]& H \\\\\nJ \\arrow[u, dotted, \"u\"] \\arrow[ur, \"a\"] & & \\\\\n\\end{tikzcd}\n\\]\n$\\forall \\, a : J \\to G$ s.t. $\\theta \\circ a = \\epsilon \\circ a$, then $\\exists \\, ! \\, u : J \\to \\text{ker}{\\theta}$ s.t. \n\\[\na = i \\circ u \n\\]\n\n\\subsubsection{Free monoid $A^*$ on set $A$}\n\n$\\exists \\, i : A \\to A^*$, given any monoid $N$, any $f: A \\to |N|$ (where $|N|$ is the underlying set of monoid $N$), \\\\\n$\\exists \\, ! $ monoid homomorphism $\\overline{f}: A^* \\to N$ s.t. $|\\overline{f}| \\circ i = f$.\n\n\n\\[\n\\begin{aligned}\n\\textbf{Mon} : & \n\\begin{tikzpicture}\n\\matrix (m) [matrix of math nodes, row sep=5em, column sep=5em, minimum width=2em]\n{\n\tA^* & N \\\\\n};\n\\path[->]\n(m-1-1) edge [dotted] node [above] {$\\overline{f}$} (m-1-2);\n\\end{tikzpicture} \\\\\n\\quad \\\\ \n\\textbf{Sets} : & \\begin{tikzpicture}\n\\matrix (m) [matrix of math nodes, row sep=5em, column sep=5em, minimum width=2em]\n{\n\t\\lvert A^* \\rvert & \\lvert N \\rvert \\\\\n\tA & \\\\\n};\n\\path[->]\n(m-1-1) edge [dotted] node [above] {$|\\overline{f}|$} (m-1-2)\n(m-2-1) edge node [left] {$i$} (m-1-1)\nedge node [right] {$f$} (m-1-2);\n\\end{tikzpicture} \n\\end{aligned} \n\\]\n\n\\begin{proposition}[Proposition 1.9, Awoday (2010) \\cite{Awod2010}]] $A^*$ has universal mapping property of free monoid on $A$.\n\t\\end{proposition} \n\\begin{proof}\n\tGivne $f: A \\to |N|$, define $\\overline{f} : A^* \\to N$, by \n\t\\[\n\t\\begin{aligned}\n\t& \\overline{f}(\"\") = e_N \\\\ \n\t& \\overline{f}(a_1 \\dots a_n) = f(a_1) \\dots f(a_n) \n\t\\end{aligned}\n\t\\]\t\n\t$\\overline{f}$ is thus a homomorphism with $\\overline{f}(a) = f(a)$ \\quad \\, $\\forall \\, a \\in A$. \\\\\n\t\n\tIf $g: A^* \\to N$ s.t. $g(a) =f(a)$ \\quad \\, $\\forall \\, a \\in A$, then $\\forall \\, (a_1, \\dots a_n) \\in A^*$, \n\t\\[\n\t\\overline{f}(a_1 \\dots a_n) = \\overline{f}(a_1) \\dots \\overline{f}(a_n) = f(a_1) \\dots f(a_n) = g(a_1) \\dots g(a_n) = g(a_1 \\dots a_n)\n\t\\]\n\tsince $\\overline{f} = g$, $\\overline{f}$ unique.\n\\end{proof} \n\nExistence part of UMP is \"no noise.\" \\\\\nUnique part of UMP is \"no junk.\"\n\nTODO Prop. 1.10, Awodey.\n\n\n\n\n\n\n\\exercisehead{1} cf. 3.1.23 Exercises of Barr and Wells (2012) \\cite{BaWe2012}\n\nGiven semigroup $S$, construct monoid $M = S \\cup \\lbrace e \\rbrace$, $e\\notin S$. \\\\\nLet $e=\\lbrace S \\rbrace$. \\\\\nMultiplication in $M$ defined as \n\\begin{enumerate}\n\t\\item $xy \\in S$ if $x,y \\in S$ \n\t\\item $xe=ex = x \\quad \\, \\forall \\, x \\in M$\n\\end{enumerate}\n$M \\equiv S^1$ in semigroup literature.\n\n\\begin{enumerate}\n\t\\item $S^1$ is a monoid (Show). \\\\\n\tIf $a,b,c \\in S \\subset M$, then $(ab)c = a(bc)$ (associative holds by definition of semigroup). \\\\\n\t$\\forall \\, a \\in S$, $ae = ea =a$, by how we defined multiplication. \\\\\n\t$ee = ee =e $ by either definition, or that multiplication in semigroup $S$ is closed.\n\t\\[\n\t\\lbrace S \\rbrace \\lbrace S \\rbrace = \\lbrace S \\rbrace \\lbrace S \\rbrace = \\lbrace S \\rbrace\n\t\\]\n\t\n\tIf for $a,b,c \\in M$, any of $a,b$ or $c=e$, use multiplication to show equality for $(ab)c = a(bc)$; e.g.\n\t\\[\n\t\\begin{aligned}\n\t& (eb) c = (b)\\cdot c = bc = e(bc) = bc \\\\ \n\t& (ae) c = a\\cdot c =a \\cdot (ec) = a(ec)\n\t\\end{aligned}\n\t\\]\n\t$S^1$ is a monoid.\n\t\\item \n\\end{enumerate}\n\n\\section{Actions, Finite State Machines}\n\n\\begin{definition}\nLet monoid $M$ with identity $1$, and a set $S$. \\\\\n\\textbf{action} of $M$ on $S$, $\\alpha$, \\\\\n\\begin{equation}\n\\begin{aligned}\n& \\alpha : M \\times S \\to S \\text{ s.t. } \\\\ \n& \\alpha(1,s) = s \\quad \\, \\forall \\, s \\in S \\\\\n& \\alpha(mn, s) = \\alpha(m, \\alpha(n, s)) \\quad \\, \\forall \\, m,n \\in M, \\, s\\in S\n\\end{aligned}\n\\end{equation}\n\nWrite $ms \\equiv \\alpha(m, s)$ then \n\\[\n\\begin{gathered} \n1s = s \\\\\n(mn) s = m (ns) \\quad \\, \\forall \\, m, n \\in M, \\, s \\in S\n\\end{gathered}\n\\]\n\\end{definition}\n\n\\begin{definition}[equivariant map]\n\tLet monoid $M$ with actions on sets $S,T$. \\\\\n\t\\textbf{equivariant map} $\\phi:S \\to T$ s.t. $m\\phi(s) = \\phi(ms)$\n\\end{definition}\n\nSuppose 2 equivariant maps $\\phi_{TS}$, $\\phi_{UT}$, sets $S,T,U$ s.t. monoid $M$ has actions on $S,T,U$: \n\\[\n\\begin{aligned}\n& \\phi_{TS} : S \\to T \\\\ \n& \\phi_{UT} : T \\to U\n\\end{aligned}\n\\]\n\n\\[\nm\\phi_{UT} \\circ \\phi_{TS}(s) = m \\phi_{UT}(\\phi_{TS}(s)) = \\phi_{UT}(m\\phi_{TS}(s)) = \\phi_{UT} \\phi_{TS} (ms) \n\\]\n\nLet $\\phi_{UT} \\circ \\phi_{TS} \\equiv \\phi_{US}$. $\\phi_{US}$ equivariant.\n\nAssociativity: given equivariant maps \n\\[\n\\begin{aligned}\n& \\phi_{TS} : S \\to T \\\\ \n& \\phi_{UT} : T \\to U \\\\ \n& \\phi_{VU} : U \\to V \n\\end{aligned}\n\\]\n\n\\[\nm \\phi_{VU} \\phi_{UT} \\phi_{TS}(s) = m \\phi_{VU} (\\phi_{UT} \\phi_{TS}(s)) = \\phi_{VU} (m \\phi_{UT} \\phi_{TS}(s)) = (\\phi_{VU} \\phi_{UT}) (\\phi_{TS}(ms))\n\\]\n\nThus, equivariant maps obey associativity on $\\forall \\, S \\in \\text{Obj}(M-\\mathbf{Act})$, (set $S$ that $M$ has action on) \\\\\ncategory $M-\\mathbf{Act}$, $\\text{Obj}(M-\\mathbf{Act}) = \\lbrace \\text{ sets that monoid $M$ has action on }\\rbrace$ \\\\\n\\phantom{category $M-\\mathbf{Act}$,} $\\text{Mor}(M-\\mathbf{Act}) = \\lbrace \\text{ equivariant maps $\\phi$ s.t. } \\forall \\, m \\in M, \\, m\\phi(s) = \\phi(ms) \\rbrace$.\n\n\\subsection{Actions as functors}\n\nLet $\\alpha$ action of monoid $M$ on set $S$. \\\\\n\nConsider $\\mathbf{C}(M)$ (monoid as a category; i.e. $\\text{Obj}\\mathbf{C}(M) = \\lbrace M \\rbrace, \\, \\text{Mor}\\mathbf{C}(M) = M$). \\\\\naction $\\alpha$ determines function $F_{\\alpha} : \\mathbf{C}(M) \\to \\mathbf{Set}$, \n\\begin{enumerate}\n\t\\item $F_{\\alpha}(*) = S \\equiv F_{\\alpha}(\\lbrace M \\rbrace ) = S$\n\t\\item $F_{\\alpha}(m) = s \\mapsto \\alpha(m, s) \\, \\forall \\, m \\in M, s \\in S$\n\\end{enumerate}\ni.e.\n\n\\[\n\\begin{gathered}\n\\begin{aligned}\n& F_{\\alpha} : \\text{Obj}\\mathbf{C}(M) \\to \\text{Obj}\\mathbf{Set} \\\\ \n& F_{\\alpha} : \\lbrace M \\rbrace \\mapsto S \n\\end{aligned} \\\\\n\\begin{aligned}\n& F_{\\alpha} : \\text{Mor}\\mathbf{C}(M) \\to \\text{Mor}\\textbf{Set} \\\\ \n& F_{\\alpha} : m \\mapsto (s\\mapsto \\alpha(m,s)) \\in \\text{Hom}(S,S)\n\\end{aligned}\n\\end{gathered}\n\\]\n\nBarr and Wells (1998) \\cite{BW1998} uses this notation: $\\mathcal{M} = (A, S, s_0, \\phi)$ for a \"machine.\" Compare this to the notation used in these notes:\n\\[\n\\text{FSM} = (\\Sigma, S, s_0, \\delta)\n\\]\n\nTake note that the finite set or input alphabet $A \\equiv \\Sigma$ is \\textbf{not} a monoid. \\\\\n\n$\\forall \\, $ string $\\equiv $ finite sequence $\\equiv $ \"word\" induces sequence of transitions in FSM starting at $s_0$, and ending on some final state; precisely, define\n\\[\n\\begin{aligned}\n& \\delta^* : \\Sigma^* \\times S \\to S \\\\ \n& \\delta^*(\"\", s) = s \\quad \\, \\forall \\in s \\in S \\\\ \n& \\delta^*((a)w, s) = \\delta(a, \\delta^*(w,s)) \\quad \\, \\forall \\, s \\in S, \\, w\\in \\Sigma^*, \\, a\\in A\n\\end{aligned}\n\\]\n\nRecall free monoid $\\Sigma^*$, $(\\Sigma^*, *, \"\")$ where $\\Sigma^* \\in \\text{Obj}\\mathbf{Set}$ is a set. \\\\\n\n\\begin{proposition}\n\t$\\delta^*$ is an action of $\\Sigma^*$ on $S$.\n\\end{proposition}\n\n\\begin{proof}\n\tAssume\n\t\\[\n\t\\delta^*(wv, s) = \\delta^*(w, \\delta^*(v,s))\n\t\\]\t\n\tthen\n\t\\[\n\t\\begin{gathered}\n\t\t\\delta^*((a)wv, s) = \\delta(a, \\delta^*(wv, s)) = \\delta(a, \\delta^*(w, \\delta^*(v,s))) = \\delta^*(aw, \\delta^*(v,s)) \n\t\\end{gathered}\n\t\\]\n1st., 3rd. equalities from $\\delta^*((a)w, s) = \\delta(a, \\delta^*(w,s))$ (definition of $\\delta^*$). \\\\\n2nd. equality is from inductive hypothesis.\n\\end{proof}\n\n\\textbf{recognizer} - subset $L\\subseteq A^*$ of strings which drive FSM from $s_0$ (start state) to acceptor state, is then set of strings, or language, which is \\textbf{recognized} by machine FSM, this is the machine as \\textbf{recognizer}.\n\n\\textbf{transducer} - FSM outputs string of symbols (not necessarily in same alphabet) $\\forall \\, $ state it enters, or each transition it undergoes.\n\n\\subsection{Set-valued functors as actions}\n\ncf. 3.2.6 of Barr and Wells (2012) \\cite{BaWe2012}. \n\n\n\\section{Products, Coproducts}\n\n\\subsection{Sources}\n\nIt appears Ad\\'{a}mek, Herrlich, and Strecker (2004) \\cite{AHS2004} defines \\emph{sources} to simply give a name and formalize a tuple. \n\n\\begin{definition}[source]\n\t\\textbf{source} is a tuple: $(a, (f_i)_{i\\in I})$, $f_i:A\\to A_i$\n\\end{definition}\n\n\\subsection{Products}\n\n\\begin{definition}[Products]\\label{Def:Products}\n\t\n\t(in Turi's notation \\cite{Turi2001})\n\t\n\tGiven objects $C_1,C_2$ of category $\\mathbb{C}$, \\textbf{product} (if exists) consists of object $C_1 \\times C_2$ of $\\mathbb{C}$ and $\\begin{aligned} & \\quad \\\\\n\t& \\pi_1 : C_1 \\times C_2 \\to C_1 \\\\\n\t& \\pi_2: C_1 \\times C_2 \\to C_2 \\end{aligned}$ s.t. \\\\\n\t$\\forall \\, $ object $A$ of $\\mathbb{C}$, \\, $\\forall \\, \\begin{aligned} & \\quad \\\\\n\t& f : A \\to C_1 \\\\\n\t& g : A \\to C_2 \\end{aligned}$ \\quad \\, $\\exists \\, ! \\quad \\, \\langle f,g \\rangle : A \\to C_1 \\times C_2$ s.t. $\\begin{aligned} & \\quad \\\\\n\t& f = \\pi_1 \\circ \\langle f,g \\rangle \\\\\n\t& g = \\pi_2 \\circ \\langle f,g \\rangle \\end{aligned}$, i.e. \n\t\n\t\\begin{tikzpicture}\n\t\\matrix (m) [matrix of math nodes, row sep=5em, column sep=4em, minimum width=3em]\n\t{\n\t\t& A & \\\\ \n\t\tC_1 & C_1 \\times C_2 & C_2 \\\\\n\t};\n\t\\path[->]\n\t(m-1-2) edge node [above] {$f$} (m-2-1)\n\tedge node [above] {$g$} (m-2-3)\n\t(m-2-2) edge node [below] {$\\pi_1$} (m-2-1)\n\tedge node [below] {$\\pi_2$} (m-2-3)\n\t;\n\t\\path[dashed] \n\t(m-1-2) edge node [right] {$\\langle f,g\\rangle$} (m-2-2)\n\t;\n\t\\end{tikzpicture} \n\t\n\t(compare with Leinster (2014) \\cite{Lein2014})\n\t\n\tLet category $\\mathcal{A}$, $X,Y \\in \\mathcal{A}$, \\textbf{product} of $X,Y$ consists of object $P$ and maps\n\t\n\t(compare this definition with Ad\\'{a}mek, Herrlich, and Strecker (2004) \\cite{AHS2004} and their notation)\n\t\n\t\\textbf{product} consisting of \n\t\\[\n\t\\begin{aligned}\n\tC_1 \\times C_2 \\times \\dots \\times C_{\\mathcal{N}} \\in \\text{Obj}\\mathbf{C} \\\\\n\t\\pi_1 : C_1 \\times C_2 \\times \\dots \\times C_{\\mathcal{N}} \\to C_1 \\\\ \n\t\\pi_2 : C_1 \\times C_2 \\times \\dots \\times C_{\\mathcal{N}} \\to C_2 \\\\ \n\t\\vdots \\\\\n\t\\pi_{\\mathcal{N}} : C_1 \\times C_2 \\times \\dots \\times C_{\\mathcal{N}} \\to C_{\\mathcal{N}} \\\\ \n\t\\end{aligned}\n\t\\]\n\t\n\tis s.t. \n\t\n\t$\\forall \\, \\begin{aligned} \\quad \\\\ \n\tA \\in \\text{Obj}\\mathbf{C} \\\\\n\tf_1 : A \\to C_1 \\\\\n\tf_2 : A \\to C_2 \\\\\n\t\\vdots \\\\\n\tf_{\\mathcal{N}} : A \\to C_{\\mathcal{N}} \\end{aligned}$, \n\t\n\t$\\exists \\, ! \\langle f_1 ,f_2 , \\dots , f_{\\mathcal{N}} \\rangle : A \\to C_1 \\times C_2 \\times \\dots \\times C_{\\mathcal{N}}$ s.t.\n\t\\[\n\t\\begin{aligned}\n\tf_1 = \\pi_1 \\circ \\langle f_1 , f_2 , \\dots f_{\\mathcal{N}} \\rangle \\\\ \n\tf_2 = \\pi_2 \\circ \\langle f_1 , f_2 , \\dots f_{\\mathcal{N}} \\rangle \\\\ \n\t\\vdots \\\\ \n\tf_{\\mathcal{N}} = \\pi_{\\mathcal{N}} \\circ \\langle f_1 , f_2 , \\dots f_{\\mathcal{N}} \\rangle \n\t\\end{aligned}\n\t\\]\n\\end{definition}\n\nLet's use the notation of Ad\\'{a}mek, Herrlich, and Strecker (2004) \\cite{AHS2004}. Also note that these references \\emph{assume} the \\emph{universal mapping property} in the definition of a \\textbf{product}.\n\n\\begin{definition}[Product (assuming univeral mapping property)]\n\t\\begin{equation}\n\\begin{gathered}\n\\begin{tikzpicture}\n\\matrix (m) [matrix of math nodes, row sep=4em, column sep=4em, minimum width=3em]\n{\n\t& & A \\\\\n\tP & A_i & \\\\\n\t& A_{i'} & \\\\\n};\n\\path[->]\n(m-2-1) edge node [above] {$p_i$} (m-2-2)\nedge node [above] {$p_{i'}$} (m-3-2)\n(m-1-3) edge node [above] {$f_i$} (m-2-2)\nedge node [above] {$f_{i'}$} (m-3-2)\n;\n\\path[dashed,->]\n(m-1-3) edge node [above] {$f$} (m-2-1)\n;\n\\end{tikzpicture} \n\\end{gathered}\n\\end{equation}\nFor the case of only 2 objects associated with $I$, \n\t\\begin{equation}\n\\begin{gathered}\n\\begin{tikzpicture}\n\\matrix (m) [matrix of math nodes, row sep=5em, column sep=4em, minimum width=3em]\n{\n\t& A & \\\\ \n\tA_1 & P & A_2 \\\\\n};\n\\path[->]\n(m-1-2) edge node [above] {$f_1$} (m-2-1)\nedge node [above] {$f_2$} (m-2-3)\n(m-2-2) edge node [above] {$p_1$} (m-2-1)\nedge node [above] {$p_2$} (m-2-3)\n;\n\\path[dashed,->]\n(m-1-2) edge node [right] {$f$} (m-2-2)\n;\n\\end{tikzpicture} \n\\end{gathered}\n\\end{equation}\n\n\n\\textbf{product} $P, \\lbrace p_i, A_i \\rbrace_{i\\in I}$ s.t. $\\forall \\, A, \\lbrace f_i, A_i \\rbrace_{i \\in I}$, $\\exists \\, !$ morphism $f:A \\to P$ s.t. $f_i = p_i \\circ f$, $i\\in I$.\n\\end{definition}\nThis definition is the same one used in pp. 35, Def. 2.16, of Awodey (2010) \\cite{Awod2010}.\n\nConsider the definition that doesn't use the universal mapping property from Pareigis (2004) \\cite{Pare2004}. \n\n\\begin{definition}[Product without universal property]\n\tGiven objects $A, B \\in \\text{Obj}\\mathbf{C}$, category $\\mathbf{C}$. \n\t\n\tObject $A\\times B$, morphisms $p_A, p_B$, $\\begin{aligned} & \\quad \\\\ \n\t\t& p_A : A \\times B \\to A \\\\ \n\t\t& p_B : A\\times B \\to B\n\t\t\\end{aligned}$ is called a (not the) (categorical) product of $A, B$, projections $p_A, p_B$. \n\t\t\n\t\tIf $\\forall \\, $ object $T\\in \\text{Obj}\\mathbf{C}$, $\\exists \\, $ isomorphism\n\n\t\t\\begin{equation}\n\t\t\t\\text{Mor}_{\\mathbf{C}}(T, A \\times B) \\cong \\text{Mor}_{\\mathbf{C}}(T, A) \\times \\text{Mor}_{\\mathbf{C}}(T,B)\t\t\n\t\t\\end{equation}\n(where $\\text{Mor}_{\\mathbf{C}}$ is the Cartesian product) s.t.\n\n\\begin{equation}\\label{Eq:ProductDefinitionWithoutUniversalPropertyDiagram}\n\\begin{gathered}\n\\begin{tikzpicture}\n\\matrix (m) [matrix of math nodes, row sep=5em, column sep=5em, minimum width=4em]\n{\n\t& \\text{Mor}_{\\mathbf{C}}(T, A\\times B) & \\\\ \n\t\\text{Mor}_{\\mathbf{C}}(T, A) & \\text{Mor}_{\\mathbf{C}}(T, A) \\times \\text{Mor}_{\\mathbf{C}}(T, B) & \\text{Mor}_{\\mathbf{C}}(T, B) \\\\\n};\n\\path[->]\n(m-1-2) edge node [left] {$\\text{Mor}_{\\mathbf{C}}(T,p_A)$} (m-2-1)\nedge node [right] {$\\text{Mor}_{\\mathbf{C}}(T,p_B)$} (m-2-3)\n(m-2-2) edge node [above] {$p_{\\text{Mor}_{\\mathbf{C}}(T, A)}$} (m-2-1)\nedge node [above] {$p_{\\text{Mor}_{\\mathbf{C}}(T, B)}$} (m-2-3)\n;\n\\path[dashed,->]\n(m-1-2) edge node [right] {$h$} (m-2-2)\n;\n\\end{tikzpicture} \\\\\n\\quad \\\\ \n\\begin{tikzpicture}\n\\matrix (m) [matrix of math nodes, row sep=5em, column sep=5em, minimum width=4em]\n{\n\t& u & \\\\ \n\tf & h(u) = (f,g) & g \\\\\n};\n\\path[|->]\n(m-1-2) edge node [left] {$\\text{Mor}_{\\mathbf{C}}(T,p_A)$} (m-2-1)\nedge node [right] {$\\text{Mor}_{\\mathbf{C}}(T,p_B)$} (m-2-3)\n(m-2-2) edge node [above] {$p_{\\text{Mor}_{\\mathbf{C}}(T, A)}$} (m-2-1)\nedge node [above] {$p_{\\text{Mor}_{\\mathbf{C}}(T, B)}$} (m-2-3)\n;\n\\path[dashed,|->]\n(m-1-2) edge node [right] {$h$} (m-2-2)\n;\n\\end{tikzpicture} \n\\end{gathered}\n\\end{equation}\nwhere $\\begin{aligned} & \\quad \\\\ \n& \\text{Mor}_{\\mathbf{C}}(T, p_A)(u) = f = p_{\\text{Mor}_{\\mathbf{C}}(T, A)} h(u) \\\\\n& \\text{Mor}_{\\mathbf{C}}(T, p_B)(u) = g = p_{\\text{Mor}_{\\mathbf{C}}(T, B)} h(u) \\end{aligned}$\n\\end{definition}\n\n\\begin{proposition}[Equivalent definition of product by universal mapping property]\nGiven objects $A, B \\in \\text{Obj}\\mathbf{C}$, category $\\mathbf{C}$, object $A\\times B$, morphisms $\\begin{aligned} & \\quad \\\\ \n\tp_A: A\\times B \\to A \\\\\n\tp_B: A\\times B \\to B \\end{aligned}$ is a (categorical) product, \\\\\n\t\niff $\\forall \\, $ object $T \\in \\text{Obj}\\mathbf{C}$, $\\forall \\, \\begin{aligned} & \\quad \\\\ \n& f: T\\to A \\\\\n& g: T \\to B \\end{aligned}$, $\\exists \\, !$ morphism $(f,g) : T \\to A\\times B$, s.t. \n\n\\begin{equation}\n\\begin{tikzpicture}\n\\matrix (m) [matrix of math nodes, row sep=5em, column sep=4em, minimum width=3em]\n{\n\t& T & \\\\ \n\tA & A\\times B & B \\\\\n};\n\\path[->]\n(m-1-2) edge node [left] {$f$} (m-2-1)\nedge node [right] {$g$} (m-2-3)\n(m-2-2) edge node [above] {$p_A$} (m-2-1)\nedge node [above] {$p_B$} (m-2-3)\n;\n\\path[dashed,->]\n(m-1-2) edge node [left] {$(f,g)$} (m-2-2)\n;\n\\end{tikzpicture} \n\\end{equation}\t\n\\end{proposition}\ncf. Proposition \"Characterization of products by universal mapping property\", 2.7.4 in Pareigis (2004) \\cite{Pare2004}.\n\n\\begin{proof}\n$\\Longleftarrow$ : \\\\\n\n\tLet $(A\\times B, p_A, p_B)$ be a \"product\" of $A\\times B$, obeying the universal (mapping) property. Let $T\\in \\text{Obj}\\mathbf{C}$. Let $u\\in \\text{Mor}_{\\mathbf{C}}(T, A\\times B)$. \\\\\n\t\n\tDefine $\\begin{aligned} & \\quad \\\\\n\t& f:= p_A \\circ u : T \\to A \\\\ \n\t& g:= p_b \\circ u : T \\to B\\end{aligned}$ \\\\\n\tThen $(f,g) \\in \\text{Mor}_{\\mathbf{C}}(T,A) \\times \\text{Mor}_{\\mathbf{C}}(T,B)$. \\\\\n\t\n\tDefine $h(u):= (f,g) \\in \\text{Mor}_{\\mathbf{C}}(T,A) \\times \\text{Mor}_{\\mathbf{C}}(T,B)$. \\\\\n\tThen, \n\t\\[\n\t\\begin{aligned}\n\t\t& \\text{Mor}_{\\mathbf{C}}(T,p_A)(u) = p_A \\circ u = f = p_{\\text{Mor}_{\\mathbf{C}}(T,A)} \\circ h(u) \\\\\t\n\t\t& \\text{Mor}_{\\mathbf{C}}(T,p_B)(u) = p_B \\circ u = g = p_{\\text{Mor}_{\\mathbf{C}}(T,B)} \\circ h(u) \\\\\t\n\t\\end{aligned}\t\n\t\\]\n\t(so Diagram \\ref{Eq:ProductDefinitionWithoutUniversalPropertyDiagram} commutes). \\\\\n\t\n\tShow: $h$ bijective. \\\\\n\tConstruct inverse map $k$:\n\t\\[\n\t\\begin{aligned}\n\t\t& k : \\text{Mor}_{\\mathbf{C}}(T,A) \\times \\text{Mor}_{\\mathbf{C}}(T,B) \\to \\text{Mor}_{\\mathbf{C}}(T,A\\times B) \\\\\n\t\t& k((f,g)) := u\n\t\\end{aligned}\n\t\\]\n\twhere $(f,g) \\in \\text{Mor}_{\\mathbf{C}}(T,A) \\times \\text{Mor}_{\\mathbf{C}}(T,B)$\n\t\n\tBy universal (mapping) property, $\\exists \\, ! \\, u :T\\to A\\times B$ s.t. $\\begin{aligned} & \\quad \\\\ \n\t& p_A \\circ u=f \\\\\n\t& p_B \\circ u = g \\end{aligned}$.\n\t\n\tLet $(f,g) \\in \\text{Mor}_{\\mathbf{C}}(T,A) \\times \\text{Mor}_{\\mathbf{C}}(T,B)$. \\\\\n\tThen $(h\\circ k)((f\\circ g)) = h(u) = (p_A\\circ u, p_B \\circ u) = (f,g)$. Hence $h\\circ k =1$ or i.e. $h\\circ k 1_{\\text{Mor}_{\\mathbf{C}}(T,A) \\times \\text{Mor}_{\\mathbf{C}}(T,B)}$. \\\\\n\t\n\tLet $u\\in \\text{Mor}_{\\mathbf{C}}(T,A\\times B)$. \\\\\n\tThen $(k\\circ h)(u) = k((f, g)) = k((p_A \\circ u, p_B \\circ u))= u'$ where $u':T\\to A\\times B$ and \\\\\n\t\\[\n\t\\begin{aligned} \n\t& p_A \\circ u' = p_A \\circ k((p_A \\circ u, p_B \\circ u)) = p_A \\circ k ((f,g)) = p_A \\circ u \\quad \\, (\\text{since $k((f,g)) := u$}) \\\\\n\t& p_B \\circ u' = p_B \\circ k((p_A \\circ u, p_B \\circ u)) = p_B \\circ k ((f,g)) = p_B \\circ u \\quad \\, (\\text{since $k((f,g)) := u$}) \n\t\\end{aligned} \n\t\\]\n\t2nd. equality is by universal (mapping) property.\n\n$\\Longrightarrow u= u'$ (by component-wise equality), and \\\\\n$k\\circ h = 1_{\\text{Mor}_{\\mathbf{C}}(T,A\\times B)}$. \\\\\n$\\Longrightarrow h$ isomorphic. \\\\\n\n$\\Longrightarrow$ : \\\\\n\nGiven morphisms\n\\[\n\\begin{aligned}\n& f:T \\to A \\\\ \n& g:T \\to B\n\\end{aligned}\n\\]\nthen $(f, g) \\in \\text{Mor}_{\\mathbf{C}}(T, A) \\times \\text{Mor}_{\\mathbf{C}}(T,B)$.\n\n$\\forall \\, $ object $T\\in \\text{Obj}\\mathbf{C}$, $\\exists \\, $ isomorphism $h$ s.t. $\\text{Mor}_{\\mathbf{C}}(T, A\\times B) \\cong \\text{Mor}_{\\mathbf{C}}(T,A) \\times \\text{Mor}_{\\mathbf{C}}(T,B)$, \\\\\nThen $u:=h^{-1}((f, g))$ is a unique morphism, $u\\in \\text{Mor}_{\\mathbf{C}}(T, A\\times B)$. \\\\\nAlso, by Diagram \\ref{Eq:ProductDefinitionWithoutUniversalPropertyDiagram}, \n\\[\n\\begin{aligned}\n& \\text{Mor}_{\\mathbf{C}}(T,p_A)(u) = f = p_{\\text{Mor}_{\\mathbf{C}}(T,A)} \\circ h(u) \\\\ \n& \\text{Mor}_{\\mathbf{C}}(T,p_B)(u) = f = p_{\\text{Mor}_{\\mathbf{C}}(T,B)} \\circ h(u) \n\\end{aligned}\n\\]\n\nNow\n\\[\n\\begin{aligned}\n& \\text{Mor}_{\\mathbf{C}}(T, p_A)(u) = p_A \\circ u \\\\\n& \\text{Mor}_{\\mathbf{C}}(T, p_B)(u) = p_B \\circ u \\\\\n\\end{aligned}\n\\]\n(by definition).\n\nSo\n\\[\n\\begin{aligned} \n& f = p_A \\circ u \\\\ \n& g = p_B \\circ u\n\\end{aligned} \n\\]\nSo universal mapping property is satisfied.\n\\end{proof}\n\nThus,\n\n\\begin{definition}[Product, generalized, assuming universal property]\n\tGive $A_i \\in \\text{Obj}\\mathbf{C}$, $i\\in I$, category $\\mathbf{C}$, \\\\\n\t\\textbf{product} is object $\\prod_{i \\in I} A_i \\in \\text{Obj}\\mathbf{C}$, morphisms $p_j : \\prod_{i\\in I} A_i \\to A_j$, $j\\in I$, \\\\\n\ts.t. $\\forall \\, $ object $A\\in \\in \\text{Obj}\\mathbf{C}$, \\\\\n\t$\\exists \\, !$ morphism $\\langle f_i \\rangle : A \\to \\prod_{i\\in I} A_i$, \\\\\n\ts.t. \n\\begin{equation}\\label{Eq:GeneralizedProductDiagram}\n\t\\begin{tikzpicture}\n\\matrix (m) [matrix of math nodes, row sep=5em, column sep=4em, minimum width=3em]\n{\n\t& A \\\\ \n\tA_j & \\prod_{i\\in I} A_i \\\\\n};\n\\path[->]\n(m-1-2) edge node [left] {$f_j$} (m-2-1)\n(m-2-2) edge node [below] {$p_j$} (m-2-1)\n;\n\\path[dashed,->]\n(m-1-2) edge node [right] {$\\langle f_i \\rangle$} (m-2-2)\n;\n\\end{tikzpicture} \n\\end{equation} \t\ni.e. $\\pi_j \\circ \\langle f_i \\rangle = f_j \\, \\forall \\, i,j \\in I$\n\\end{definition}\n\n\\subsubsection{Example: Set always has products}\n\n$\\forall \\, $ sets $X,Y \\in \\text{Obj}(\\text{Set})$, $\\exists \\, $ product $X\\times Y \\in \\text{Obj}(\\text{Set})$. \n\nLet $A \\in \\text{Obj}(\\text{Set})$, $\\begin{aligned} & \\quad \\\\\n& f_1 : A \\to X \\\\\n& f_2 : A \\to Y \\end{aligned}$ \\qquad \\, Define $\\begin{aligned} & \\langle f_1, f_2 \\rangle : A \\to X \\times Y \\\\\n& \\langle f_1 ,f_2 \\rangle (a) = (f_1(a), f_2(a)) \\end{aligned}$\n\nThen $\\begin{aligned} & \\quad \\\\\n& \\pi_1 \\circ \\langle f_1 , f_2 \\rangle (a) = f_1(a) \\\\\n& \\pi_2 \\circ \\langle f_1, f_2 \\rangle (a) = f_2(a) \\end{aligned}$ \\qquad \\, $\\Longrightarrow \\begin{aligned} & \\quad \\\\\n& \\pi_1 \\circ \\langle f_1 , f_2 \\rangle = f_1 \\\\\n& \\pi_2 \\circ \\langle f_1,f_2 \\rangle = f_2 \\end{aligned}$\n\nSuppose $f': A \\to X\\times Y$ s.t. $\\begin{aligned} & \\quad \\\\\n& \\pi_1 \\circ f' = f_1 \\\\\n& \\pi_2 \\circ f' = f_2 \\end{aligned}$\n\nWrite $f'(a) = (x,y)$\n\\[\n\\begin{aligned}\n& f_1(a) = \\pi_1 \\circ f'(a) = \\pi_1(x,y) =x \\\\ \n& f_2(a) = \\pi_2 \\circ f'(a) = \\pi_2(x,y) =y \\\\ \n\\end{aligned} \\qquad \\, \\Longrightarrow f'(a) = (f_1(a), f_2(a)) = \\langle f_1, f_2 \\rangle (a)\n\\]\n$\\langle f_1, f_2 \\rangle $ unique. \n\n\\subsubsection{Example: \"Record Types\", classes (in computer science, C++, Python)}\\label{SubSubSec:RecordTypesProduct}\n\ncf. pp. 174, 5.3.14 \"Record Types\" Barr and Wells (1998) \\cite{BW1998}.\n\nLook at Diagram \\ref{Eq:GeneralizedProductDiagram} again.\n\nTo allow operations depending on several variables in a functional programming language $L$, \\\\\ne.g. assume $\\forall \\,$ types $A_j$, $\\forall \\, j \\in I$, language $L$ has record type $\\prod_{i\\in I} A_i$, and field selectors $p_j$\n\\[\np_j : \\prod_{i\\in I} A_i \\to A_j\n\\]\nInsist that any data in $\\prod_{i\\in I} A_i$ be determined completely by those fields $A_j$, $j\\in I$, \\\\\nthen $\\forall \\, $ operations $f_j$, $f_j : A \\to A_j$, \\, $\\forall \\, j \\in I$, \\\\\nthere ought to be an unique operation $\\lbrace f_i \\rangle : A \\to \\coprod_{i\\in I} A_i$ s.t. \n\\[\np_j\\langle f_i \\rangle = f_j, \\quad \\, \\forall \\, i, j \\in I\n\\]\nThis would make $\\prod_{i\\in I} A_i$ the product of $A_i$'s, with selectors as product projections.\n\nThus, to say that one can always construct record types in a functional programming language $L$ to say that the corresponding category $C(L)$ has finite products. \n\n\n\\begin{proposition}\n\tIf product $(A_1 \\times \\dots \\times A_{\\mathcal{N}} \\xrightarrow{ \\pi_i } A_i )_{i\\in I}$, if $\\exists \\, i_0 \\in I$ s.t. $\\text{Hom}(A_{i_0}, A_i) \\neq \\emptyset$, \\, $\\forall \\, i \\in I$, \\\\\n\tthen $\\pi_{i_0}$ \\emph{retraction }\n\\end{proposition}\n\n\\begin{proof}\n\t$\\forall \\, i \\in I$, choose $f_i \\in \\text{Hom}(A_{i_0}, A_i)$ with $f_{i_0} = 1_{A_{i_0}}$. \n\t\n\tThen $\\langle f_i \\rangle : A_{i_0} \\to A_1 \\times \\dots \\times A_{\\mathcal{N}}$ is a morphism s.t. \n\t\\[\n\t\\pi_{i_0} \\circ \\langle f_i \\rangle = f_{i_0} = 1_{A_{i_0}}\n\t\\]\n\\end{proof}\n\n\nAd\\'{a}mek, Herrlich, and Strecker (2004) \\cite{AHS2004} and their notation) calls a \\textbf{sink} what Leinster (2014) \\cite{Lein2014} calls a \\textbf{cocone}. \n\\begin{definition}\n\t\\textbf{sink} $((f_i)_{i\\in I}, A) \\equiv (f_i , A)_I \\equiv (A_i \\xrightarrow{ f_i } A)_I$, object $A$, family of morphisms $f_i : A_i \\to A$\n\\end{definition}\n\nFor the \\emph{coproduct}, consider this enlightening comparision:\n\\[\n\\begin{aligned}\n\\begin{gathered}\n\\text{ product } ( \\prod_{i\\in I } A_i, \\pi_j )_{j \\in I} \\\\ \n\\text{ projection } \\pi_j : \\prod_{i\\in I} A_i \\to A_j \\\\\n\\begin{tikzpicture}\n\\matrix (m) [matrix of math nodes, row sep=5em, column sep=4em, minimum width=3em]\n{\n\t& A \\\\ \n\tA_j & \\prod_{i\\in I} A_i \\\\\n};\n\\path[->]\n(m-1-2) edge node [above] {$f_j$} (m-2-1)\nedge node [right] {$\\langle f_i \\rangle$} (m-2-2)\n(m-2-2) edge node [below] {$\\pi_j$} (m-2-1)\n;\n\\end{tikzpicture} \\\\\nC\\xrightarrow{ \\langle f, g \\rangle } A\\times B \\\\\n\\prod_{i \\in I } f_i \\, , \\text{ or if } i = \\lbrace 1,2 \\rbrace, \\, f\\times g\n\\end{gathered} & \\qquad \\, \n\\begin{gathered}\n\\text{ coproduct } ( \\mu_j, \\coprod_{i\\in I } A_i )_{j \\in I} \\\\ \n\\text{ injection } \\mu_j : A_j \\to \\coprod_{i\\in I} A_i \\\\\n\\begin{tikzpicture}\n\\matrix (m) [matrix of math nodes, row sep=5em, column sep=4em, minimum width=3em]\n{\n\t& A \\\\ \n\tA_j & \\coprod_{i\\in I} A_i \\\\\n};\n\\path[->]\n(m-2-1) edge node [above] {$f_j$} (m-1-2)\nedge node [above] {$\\mu_j$} (m-2-2)\n(m-2-2) edge node [right] {$[f_i]$} (m-1-2)\n;\n\\end{tikzpicture} \\\\\nC\\xleftarrow{ [ f, g ] } A + B \\\\\n\\coprod_{i \\in I } f_i \\, , \\text{ or if } i = \\lbrace 1,2 \\rbrace, \\, f + g\n\\end{gathered}\n\\end{aligned}\n\\]\n\n\\subsubsection{Examples (of coproducts)} \n\n\\begin{itemize}\n\t\\item if $(A_i)_I$ pairwise-disjoint family of sets, then $(\\mu_j, \\bigcup_{i\\in I} A_i)_{j\\in I}$ is coproduct in $\\text{Set}$. \\\\\n\tIf $(A_i)_I$ arbitrary set-indexed family of sets, then it can be ``made disjoint'' by pairing each $A_i$ with index $i$, i.e. by working with $A_i \\times \\lbrace i \\rbrace$ rather than $A_i$. \n\t\n\tSo $\\bigcup_{i\\in I } (A_i \\times \\lbrace i \\rbrace)$ disjoint. Consider \n\t\\[\n\t\\begin{aligned}\n\t& \\mu_j : A_j \\to \\bigcup_{i \\in I} A_i \\times \\lbrace i \\rbrace \\\\ \n\t& \\mu_i(a) = (a,j)\n\t\\end{aligned}\n\t\\]\n\t$(\\mu_j, \\bigcup_{i\\in I} A_i \\times \\lbrace i \\rbrace )_{j\\in I}$ is a coproduct in $\\text{Set}$. \n\t\n\tIndeed, given $\\begin{aligned} & \\quad \\\\\n\t& f_j:A_j \\to A \\\\\n\t& f_j(a) \\in A \\end{aligned}$, \n\t\\[\n\t\\begin{aligned}\n\t& [f_i] : \\coprod_{i\\in I} A_i \\times \\lbrace i \\rbrace \\to A \\\\ \n\t& [f_i]\\circ \\mu_j = f_j \n\t\\end{aligned}\n\t\\]\n\twhere\n\t\\[\n\tf_j(a) = [f_i]\\circ \\mu_j(a) = [f_i](a,j) = f_j(a)\n\t\\]\n\t\\item $\\text{Top}$ coproducts are ``topological sums''; they're ``concrete'' coproducts (Ad\\'{a}mek, Herrlich, and Strecker (2004) \\cite{AHS2004})\n\t\\item $\\text{Vec}$ (nonconcrete) coproducts called \\emph{direct sums}\n\t\n\tdirect sum $\\bigoplus_{i\\in I} A_i$ of vector spaces $A_i$ is subspace of direct product $\\prod_{i\\in I} A_i$ \\\\\n\tconsisting of all elements $(a_i)_{i\\in I}$ with finite carrier (i.e. $\\lbrace i \\in I | a_i \\neq 0 \\rbrace$ is finite), \\\\\n\t\\qquad injections \\[\n\t\\begin{aligned} & \\quad \\\\\n\t& \\mu_j : A_j \\to \\bigoplus_{i\\in I } A_i \\\\\n\t& \\mu_j(a) = (a_i)_{i\\in I} \\text { with } a_i = \\begin{cases} a & \\text{ if } i = j \\\\ 0 & \\text{ if } i \\neq j \\end{cases}\n\t\\end{aligned}\n\t\\]\n\t\n\t\\item $\\text{Grp}$ has nonconcrete coproducts, ``free products''\n\\end{itemize}\n\n\\section{Naturality; Natural transformations}\n\n\\begin{definition}[Natural Transformation]\\label{Def:NaturalTransformation}\n\tIf functors $F,G$, categories $\\mathbf{C}, \\mathbf{D}$, \n\t\\[\n\t\\begin{aligned}\n\t& F:\\mathbf{C} \\to \\mathbf{D} \\\\ \n\t& G:\\mathbf{C} \\to \\mathbf{D} \n\t\\end{aligned}\n\t\\]\n\tthe \\textbf{natural transformation} $\\eta$ from $F$ to $G$ is a family of morphisms s.t. \\\\\n\t\n\t\\begin{enumerate} \n\t\t\\item $\\forall \\, X \\in \\text{Obj}\\mathbf{C}$, $\\eta_X : F(X) \\to G(X)$ s.t. $F(X), G(X) \\in \\text{Obj}\\mathbf{D}$. morphisms $\\eta_X \\in \\text{Hom}_{\\mathbf{D}}(F(X), G(X)) \\subset \\text{Mor}\\mathbf{D}$ is called \\textbf{component} of $\\eta$ at $X$.\n\t\t\\item components must be s.t. $\\forall \\, $ morphism $f: X \\to Y$ in $\\mathbf{C}$, i.e. $f\\in \\text{Hom}_{\\mathbf{C}}(X, Y) \\in \\text{Mor}\\mathbf{C}$, \n\t\t\\begin{equation}\n\t\t\\eta_Y \\circ F(f) = G(f) \\circ \\eta_X\n\t\t\\end{equation} \n\t\ti.e. \n\t\t\\[\n\t\t \\begin{tikzpicture}\n\t\t\\matrix (m) [matrix of math nodes, row sep=5em, column sep=5em, minimum width=2em]\n\t\t{\n\t\t\t F(X) & F(Y) \\\\\n\t\t\t G(X) & G(Y) \\\\\n\t\t\t};\n\t\t\\path[->]\n\t\t(m-1-1) edge node [above] {$F(f)$} (m-1-2)\n\t\tedge node [auto] {$\\eta_X$} (m-2-1)\n\t\t(m-1-2) edge node [auto] {$\\eta_Y$} (m-2-2)\n\t\t(m-2-1) edge node [auto] {$G(f)$} (m-2-2);\n\t\t\\end{tikzpicture}\n\t\t\\]\n\t\t\n\t\tIf both $F,G$ contravariant, \n\t\t\\[\n\t\t\\begin{tikzpicture}\n\t\t\\matrix (m) [matrix of math nodes, row sep=5em, column sep=5em, minimum width=2em]\n\t\t{\n\t\t\t F(X) & F(Y) \\\\\n\t\t\t G(X) & G(Y) \\\\\n\t\t\t};\n\t\t\\path[->]\n\t\t(m-1-2) edge node [above] {$F(f)$} (m-1-1)\n\t\t(m-1-1) edge node [auto] {$\\eta_X$} (m-2-1)\n\t\t(m-1-2) edge node [auto] {$\\eta_Y$} (m-2-2)\n\t\t(m-2-2) edge node [auto] {$G(f)$} (m-2-1);\n\t\t\\end{tikzpicture}\n\t\t\\]\n\t\t\\end{enumerate} \n\t\\end{definition}\ncf. \\href{https://en.wikipedia.org/wiki/Natural_transformation}{Wikipedia, \"Natural transformation\"}\n\nNotation: natural transformation from $F$ to $G$, $\\eta:F \\to G$, i.e. family of morphisms $\\eta_X : F(X) \\to G(X)$ is natural in $X$.\n\ncf. Ad\\'{a}mek, Herrlich, and Strecker (2004) \\cite{AHS2004}. \\\\\n\nFrom pp. 16, Sec. 14 \"Natural Transformations\", Mac Lane (1978) \\cite{MacL1978}, \\\\\n\n$\\forall \\,$ arrow $f: C \\to C'$ in $C$, i.e. notation: $\\forall \\, $ morphism $f:X \\to Y$ in $\\mathbf{C}$, \n\nMac Lane's notation:\n\\[\n\\begin{gathered}\n\\begin{tikzcd} \nc \\arrow{d}{f} \\\\\nc'\n\\end{tikzcd} \\qquad \\, \n\\begin{tikzcd}\nSc \\arrow{d}{Sf} \\arrow{r}{\\tau c} & Tc \\arrow{d}{Tf} \\\\\nSc' \\arrow{r}{\\tau c'} & Tc'\n\\end{tikzcd}\n\\end{gathered}\n\\]\n\nMy notation:\n\\[\n\\begin{gathered}\n\\begin{tikzcd} \nX \\arrow{d}{f} \\\\\nY\n\\end{tikzcd} \\qquad \\,\n\\begin{tikzcd}\nFX \\arrow{d}{Ff} \\arrow{r}{\\eta_X} & GX \\arrow{d}{Gf} \\\\\nFY \\arrow{r}{\\eta_Y} & GY\n\\end{tikzcd}\n\\end{gathered}\n\\]\n\nWe say that $\\tau_c : Sc \\to Tc$ is natural in $C$; $\\eta_X : FX \\to GX$ is natural in $X$. \\\\\n\nIf we think of functor $S$ as giving a picture in $B$ of (all the objects, arrows of) $C$, then \\\\\nnatural transformation $\\tau$ is set of arrow $s$ mapping (or, translating) the picture $S$ to picture $T$, with all squares (and parallelograms!) like that above commutative:\n\nMac Lane's notation:\n\\[\n\\begin{gathered}\n\\begin{tikzcd}\na \\arrow{dr}{f} \\arrow{dd}{h} & \\\\\n& b \\arrow{dl}{g} \\\\ \nc & \n\\end{tikzcd} \\qquad \\, \n\\begin{tikzcd}\nSa \\arrow{dr}{Sf} \\arrow{dd}{Sh} \\arrow{rr}{\\tau a} & & Ta \\arrow[dd, crossing over]{} \\arrow{dr}{Tf} & \\\\\n& Sb \\arrow{dl}{Sg} \\arrow{rr}[swap, pos=0.2]{\\tau b} & & Tb \\arrow{dl}{Tg} \\\\ \nSc \\arrow{rr}{\\tau c} & & Tc & \n\\end{tikzcd} \n\\end{gathered}\n\\]\n\nMy notation:\n\\[\n\\begin{gathered}\n\\begin{tikzcd}\nX \\arrow{dr}{f} \\arrow{dd}{g} & \\\\\n& Y \\arrow{dl}{h} \\\\ \nZ & \n\\end{tikzcd} \\qquad \\,\n\\begin{tikzcd}\nFX \\arrow{dr}{Ff} \\arrow{dd}{Fg} \\arrow{rr}{\\eta_X} & & GX \\arrow[dd, crossing over]{} \\arrow{dr}{Gf} & \\\\\n& FY \\arrow{dl}{Fh} \\arrow{rr}[swap, pos=0.2]{\\eta_Y} & & GY \\arrow{dl}{Gh} \\\\ \nFZ \\arrow{rr}{\\eta_Z} & & GZ & \n\\end{tikzcd} \n\\end{gathered}\n\\]\n\n\\emph{natural equivalence} or i.e. natural isomorphism - natural transformation $\\tau$ with $\\forall \\, $ component $\\tau c$ invertible in $B$, $\\tau : S \\cong T$. \\\\\nnotation: $\\eta$ with $\\forall \\, $ component $\\eta_X$ invertible in $\\mathbf{D}$; $\\eta : F \\cong G$. \\\\\n$\\Longrightarrow $ inverses $(\\tau c)^{-1}$ in $B$ are components of natural isomorphism $\\tau^{-1} :T \\to S$. \\\\\nnotation: inverses $(\\eta_X)^{-1}$ in $\\mathbf{D}$ are components of natural isomorphism $\\eta^{-1}: G\\to F$. \n\n\n\\subsection{Examples of Natural transformations}\n\ne.g. Hurewicz homomorphism $\\pi_n(X) \\to H_n(X)$ $\\forall \\, $ topological space $X$ is a natural transformation from $n$th homology functor. \\\\\n$\\pi_n : \\textbf{Top} \\to \\mathbf{Grp}$ to $n$th homology functor $H_n : \\textbf{Top} \\to \\textbf{Grp}$.\n\ne.g. \\textbf{determinant} $\\det$ is a natural transformation (cf. Mac Lane (1978) \\cite{MacL1978}). \\\\\nLet $\\det_KM = $ determinant of $n\\times n$ matrix $M$, with entries in commutative ring $K$, while \\\\\n$K^* \\equiv $ group of units (invertible elements) of $K$ \\\\\n\nThus $M$ non-singular when $\\det_KM$ is a unit, and $\\det_K$ is a morphism $GL_nK \\to K^*$ of groups. \\\\\nBecause $\\det$ is defined by same formula $\\forall \\,$ ring $K$, each morphism $f: K \\to K'$ of commutative rings leads to \n\\[\n\\begin{tikzcd}\nGL_nK \\arrow{d}{GL_nf} \\arrow{r}{\\det_K} & K^* \\arrow{d}{f^*} \\\\\nGL_nK' \\arrow{r}{\\det_{K'}} & (K')^*\n\\end{tikzcd}\n\\]\n\n$\\Longrightarrow \\det : GL_n \\to ()^*$ is natural between 2 functors $\\textbf{CRng} \\to \\textbf{Grp}$\n\nTODO: Work out examples of natural transformations involving group commutators on pp. 17 of Mac Lane (1978) \\cite{MacL1978}.\n\ne.g. category $\\textbf{Finord} = $ all finite ordinal numbers $n$ \\\\\ncategory $\\textbf{Set}_f = $ all finite sets (in some universe $U$) \\\\ \n$\\forall \\, $ ordinal $n = \\lbrace 0 , 1 , \\dots n-1 \\rbrace$ is a finite set, so inclusion $S$ is a functor $S: \\textbf{FinOrd} \\to \\textbf{Set}_f$ \\\\\n$\\forall \\, $ finite set $X$ determines ordinal number $n = \\# X$, number of elements in $X$ \\\\\n$\\forall \\, X$, choose bijection $\\theta_X:X \\to \\# X$ \\\\\n$\\forall \\, $ function $f:X \\to Y$, $X,Y$ finite sets, \\\\\nChoose corresponding function $\\# f : \\# X \\to \\# Y$ between ordinals by $\\# f = \\theta_Y f \\theta_X^{-1}$, so that \n\\begin{equation}\\label{Eq:NaturalIsomorphismOrdinalNumbersFiniteSets}\n\\begin{tikzcd}\nX \\arrow{d}{f} \\arrow{r}{\\theta_X} & \\# X \\arrow{d}{\\# f} \\\\\nY \\arrow{r}{\\theta_Y} & \\# Y\n\\end{tikzcd}\n\\end{equation}\n\n$\\Longrightarrow \\# $ a functor $\\# : \\textbf{Set}_f \\to \\textbf{FinOrd}$ \\\\\nIf $X$ itself an ordinal number, take $\\theta_X$ to be an identity. \\\\\n$\\Longrightarrow \\# \\circ S$ is identity functor $I'$ of $\\textbf{FinOrd}$ \\\\\n$S \\circ \\#$ is not identity functor $I : \\textbf{Set}_f \\to \\textbf{Set}_f$ because \\\\\n$S \\circ \\#$ sends each finite set $X$ to a special finite set - ordinal number $n$ with same number of elements as $X$. \\\\\nHowever $\\theta: I \\to S \\#$ is a natural isomorphism by square diagram above (Eq. \\ref{Eq:NaturalIsomorphismOrdinalNumbersFiniteSets}). \n\\[\nI \\cong S\\circ \\# , \\quad \\, I' = \\# \\circ S \n\\]\n\nequivalence between categories $\\mathbf{C}, \\mathbf{D} =$ \\\\\npair of functors $\\begin{aligned} & \\quad \\\\ \n& S : \\mathbf{C} \\to \\mathbf{D} \\\\ \n& T : \\mathbf{C} \\to \\mathbf{D} \\end{aligned}$ and \\\\\nnatural isomorphisms $I_C \\cong T \\circ S$, $I_D \\cong S \\circ T$. \n\n\n\n\n\n\\section{Limits}\n\n\\subsection{Pullback}\n\n\\begin{definition}\n\tFor some category $\\mathbf{A}$, and for \n\t\n\t\\begin{tikzpicture}\n\t\\matrix (m) [matrix of math nodes, row sep=5em, column sep=5em, minimum width=2em]\n\t{\n\t\t& Y \\\\\n\t\tX & Z \\\\\n\t};\n\t\\path[->]\n\t(m-1-2) edge node [right] {$t$} (m-2-2)\n\t(m-2-1) edge node [below] {$s$} (m-2-2);\n\t\\end{tikzpicture}\n\t\n\t$X,Y,Z \\in \\text{Obj}\\mathbf{A}$. \n\t\n\t$\\begin{aligned} & \\quad \\\\\n\t& s : X \\to Z \\\\\n\t& t: Y \\to Z \\end{aligned}$ ; \\qquad \\, $s,t \\in \\text{Mor}\\mathbf{A}$\n\t\n\tThen the \\textbf{pullback} or ``pullback square'' consists of $P \\in \\text{Obj}\\mathbf{A}$, $\\begin{aligned} & \\quad \\\\\n\t& \\pi_1 : P \\to X \\\\\n\t& \\pi_2: P \\to Y \\end{aligned}$ s.t. \n\t\n\t\\begin{tikzpicture}\n\t\\matrix (m) [matrix of math nodes, row sep=5em, column sep=5em, minimum width=2em]\n\t{\n\t\tP & Y \\\\\n\t\tX & Z \\\\\n\t};\n\t\\path[->]\n\t(m-1-1) edge node [above] {$\\pi_2$} (m-1-2)\n\tedge node [auto] {$\\pi_1$} (m-2-1)\n\t(m-1-2) edge node [auto] {$t$} (m-2-2)\n\t(m-2-1) edge node [auto] {$s$} (m-2-2);\n\t\\end{tikzpicture}\n\t\n\tcommutes and s.t. $\\forall \\, $ commutative square in $\\mathbf{A}$ \n\t\n\t\\begin{tikzpicture}\n\t\\matrix (m) [matrix of math nodes, row sep=5em, column sep=5em, minimum width=2em]\n\t{\n\t\tA & Y \\\\\n\t\tX & Z \\\\\n\t};\n\t\\path[->]\n\t(m-1-1) edge node [above] {$f_2$} (m-1-2)\n\tedge node [auto] {$f_1$} (m-2-1)\n\t(m-1-2) edge node [auto] {$t$} (m-2-2)\n\t(m-2-1) edge node [auto] {$s$} (m-2-2);\n\t\\end{tikzpicture}\n\t\n\tthen $\\exists \\, ! \\, f: A \\to P$ s.t. \n\t\n\t\\begin{tikzpicture}\n\t\\matrix (m) [matrix of math nodes, row sep=5em, column sep=5em, minimum width=2em]\n\t{\n\t\tA & & \\\\ \n\t\t& P & Y \\\\\n\t\t& X & Z \\\\\n\t};\n\t\\path[->]\n\t(m-2-2) edge node [above] {$\\pi_2$} (m-2-3)\n\tedge node [auto] {$\\pi_1$} (m-3-2)\n\t(m-2-3) edge node [auto] {$t$} (m-3-3)\n\t(m-3-2) edge node [auto] {$s$} (m-3-3)\n\t(m-1-1) edge node [above] {$f_2$} (m-2-3)\n\tedge node [above] {$f$} (m-2-2)\n\tedge node [below] {$f_1$} (m-3-2);\n\t\\end{tikzpicture}\n\t\n\t\n\\end{definition}\n\nSimmons (2011) \\cite{Simm2011}\n\ncf. 3.3 \\emph{Some less simple functors}, pp. 79, of Simmons (2011) \\cite{Simm2011}\n\n\\section{Monads}\n\ncf. Ch. 6, Monads and Algebras, starting on pp. 137 of Mac Lane (1971) \\cite{MacL1978}.\n\n\\subsection{Monads in a Category}\n\n\\subsubsection{Development of a Monad}\n\nLet's follow the development of a Monad according to Mac Lane (1971) \\cite{MacL1978} starting on pp. 137 in Sec. 1. \"Monads in a Category.\"\n\n$\\forall \\, $ endofunctor $T: X \\to X$, $T$ has composites $T^2 = T\\circ T : X \\to X$, $T^3 = T^2 \\circ T:X \\to X$ in Mac Lane's notation, $X$ is a category. In our notation, $\\mathbf{C}$ denotes the category. And so for endofunctor $T: \\mathbf{C} \\to \\mathbf{C}$, $T^2 = T\\circ T: \\mathbf{C} \\to \\mathbf{C}$, $T^3 = T^2 \\circ T: \\mathbf{C} \\to \\mathbf{C}$. \n\nRecall from Def. \\ref{Def:Endofunctor}, that for endofunctor $T:\\mathbf{C} \\to \\mathbf{C}$, the \\emph{object map} $T: \\text{Obj}{\\mathbf{C}} \\to \\text{Obj}{\\mathbf{C}}$ acts just like a morphism in $\\text{Mor}{\\mathbf{C}}$! So $T: X \\to T(X)$ for $X, T(X) \\in \\text{Obj}{\\mathbf{C}}$. Also, recall that the \\emph{morphism map} $T: \\text{Mor}_{\\mathbf{C}} \\to \\text{Mor}_{\\mathbf{C}}$ acts like the usual morphism map, such that $Tf : T(X) \\to T(Y)$ if $f:X\\to Y$, for $X,Y \\in \\text{Obj}{\\mathbf{C}}$. \\\\\n\nIf $\\mu:T^2 \\to T$ is a \\emph{natural transformation}, then recall the definition of the natural transformation, Def. \\ref{Def:NaturalTransformation}, and apply that onto $\\mu$. \\\\\n\n$\\forall \\, X \\in \\text{Obj}{\\mathbf{C}}$, $\\mu_X: T^2(X) \\to T(X)$ with $T^2(X), T(X) \\in \\text{Obj}{\\mathbf{C}}$. $\\mu_X$ is a morphism $\\in \\text{Hom}_{\\mathbf{C}}(T^2(X), T(X))$ (!!), as well as being a component of $\\mu$ at $X$. \\\\\n\n$\\forall \\,$ morphism $f: X\\to Z$ in $\\mathbf{C}$, $X, Z \\in \\text{Obj}{\\mathbf{C}}$ (the notation of using $Z$ to emphasize that $f$ can map $X$ to \\emph{any} arbitrary object in $\\text{Obj}{\\mathbf{C}}$), \n\\[\n\\mu_Z \\circ T^2f = Tf \\circ \\mu_X \n\\]\ni.e. \n\\[\n\\begin{tikzcd}\n\tT^2(X) \\arrow{d}{T^2f} \\arrow{r}{\\mu_X} & T(X) \\arrow{d}{Tf} \\\\\n\tT^2(Z) \\arrow{r}{\\mu_Z} & T(Z)\n\\end{tikzcd}\n\\]\n\nLet $T\\mu : T^3 \\to T^2$ \\emph{denote} a natural transformation with components $(T\\mu)_X = T(\\mu_X) : T^3(X) \\to T^2(X)$, \\\\\nwhile $\\mu T: T^3\\to T^2$ denotes another natural transformation with components $(\\mu T)_X = \\mu_{T(X)}$. \n\n$T\\mu$, $\\mu T$ are \"horizontal\" composites in the sense of Sec. II. 5, \"The Category of All Categories\". (TODO: Understand what Mac Lane (1971) \\cite{MacL1978} means when he says this on pp. 137). \\\\\n\nLet's jump the gun and consider what natural transformation $\\eta : 1_{\\mathbf{C}} \\to T$ means with respect to the definition of a natural transformation, Def. \\ref{Def:NaturalTransformation}. $1_{\\mathbf{C}}$ is the identity functor, mapping everything to itself. \\\\\n\n$\\forall \\, X \\in \\text{Obj}{\\mathbf{C}}$, $\\eta_X: 1_{\\mathbf{C}}(X) \\to T(X)$ with $1_{\\mathbf{C}}(X) = X, T(X) \\in \\text{Obj}{\\mathbf{C}}$. $\\eta_X$ is a morphism $\\in \\text{Hom}_{\\mathbf{C}}(1_{\\mathbf{C}}(X), T(X)) = \\text{Hom}_{\\mathbf{C}}(X, T(X))$ (!!!), as well as being a component of $\\eta$ at $X$. Not only that, it applies $T$ onto $X$! \\\\\n\n$\\forall \\,$ morphism $f: X\\to Z$ in $\\mathbf{C}$, $X, Z \\in \\text{Obj}{\\mathbf{C}}$, \n\\[\n\\eta_Z \\circ 1_{\\mathbf{C}}f = \\eta_Z \\circ f = Tf \\circ \\eta_X \n\\]\ni.e. \n\\[\n\\begin{tikzcd}\n1_{\\mathbf{C}}(X) \\arrow{d}{1_{\\mathbf{C}}f} \\arrow{r}{\\eta_X} & T(X) \\arrow{d}{Tf} \\\\\n1_{\\mathbf{C}}(Z) \\arrow{r}{\\eta_Z} & T(Z)\n\\end{tikzcd} \\Longrightarrow \n\\begin{tikzcd}\nX \\arrow{d}{f} \\arrow{r}{\\eta_X} & T(X) \\arrow{d}{Tf} \\\\\nZ \\arrow{r}{\\eta_Z} & T(Z)\n\\end{tikzcd}\n\\]\n\n\\subsubsection{Definitions and Properties of a Monad}\n\n\\begin{definition}[Monad]\\label{Def:Monad}\n\\textbf{monad} $T = \\langle T, \\eta, \\mu \\rangle$ in category $\\mathbf{C}$ consists of functor $T: \\mathbf{C} \\to \\mathbf{C}$ and 2 natural transformations\n\\begin{equation}\n\\begin{aligned}\n& \\eta : 1_{\\mathbf{C}} \\to T \\\\ \n& \\mu : T^2 \\to T\n\\end{aligned}\n\\end{equation}\t\ns.t. \n\\begin{equation}\\label{Eq:MonadAssociativeDiagram}\n\\begin{tikzcd}\nT^3 \\arrow{d}{\\mu T} \\arrow{r}{T\\mu} & T^2 \\arrow{d}{\\mu} \\\\\nT^2 \\arrow{r}{\\mu} & T\n\\end{tikzcd}\n\\end{equation}\nbeing like an \"associative\" diagram, and \n\\begin{equation}\\label{Eq:MonadLeftRightUnitLawsDiagram}\n\\begin{tikzcd}\n\t1T \\arrow[equal]{d} \\arrow{r}{\\eta T} & T^2 \\arrow{d}{\\mu} & T1 \\arrow{l}[swap]{T \\eta} \\arrow[equal]{d} \\\\\n\tT \\arrow[equal]{r} & T & T \\arrow[equal]{l}\n\\end{tikzcd}\n\\end{equation}\nbeing a diagram that could be said to express the left and right unit laws.\n\\end{definition} \n\nFormally, the monad definition is like that of a monoid $M$ in $\\mathbf{Sets}$: \\\\\nset $M$ of elements of monad \\quad $\\to $ \\, replaced by endofunctor $T : X \\to X$ \\\\\nCartesian product $\\times$ of 2 sets \\quad $\\to $ \\, composite of 2 functors \\\\\nbinary operation $\\mu : M \\times M \\to M$ of multiplication \\quad $\\to $ \\, transformation $\\mu : T^2 \\to T$ and \\\\\nunit (identity) element $\\eta:1 \\to M$ \\quad $\\to $ \\, $\\eta : 1_{\\mathbf{C}} \\to T$. \\\\\n\nThus, call \\\\\n$\\eta$ the \\textbf{unit} of monad $T$. The first commutative diagram, Eq. \\ref{Eq:MonadAssociativeDiagram}, is the associative law for a monad, and \\\\\n$\\mu$ the \\textbf{multiplication} of monad $T$. The 2nd. and 3rd. diagrams, Eq. \\ref{Eq:MonadLeftRightUnitLawsDiagram} expresses the left and right \\emph{unit laws}.\n\n\\begin{proposition}[Coherence conditions]\\label{Prop:MonadCoherenceConditions}\n\t\\begin{equation}\n\t\\begin{aligned}\n\t& \\mu \\circ T \\mu = \\mu \\circ \\mu T \\quad (\\text{as natural transformations $T^3 \\to T$, $\\mu \\circ T\\mu$ and $\\mu \\circ \\mu T$, that is}) \\\\ \n\t& \\mu \\circ T \\eta = \\mu \\circ \\eta T = 1_T \\quad (\\text{as natural transformations $T \\to T$, $1_T \\equiv$ identity functor}) \n\t\\end{aligned}\n\t\\end{equation}\n\t\n\tFor the last statement, it is equal to commutative diagram Eq. \\ref{Eq:MonadLeftRightUnitLawsDiagram}, since it can be redrawn as follows:\n\\[\n\\begin{tikzcd}\n\tT \\arrow{d}{ T \\eta} \\arrow{r}{\\eta T} \\arrow[equal]{dr} & T^2 \\arrow{d}{\\mu} \\\\\n\tT^2 \\arrow{r}{\\mu} & T\n\\end{tikzcd}\t\n\\]\n\t\n\\end{proposition}\n\n\\subsection{Monads and Adjoints}\n\ncf. Ch. 6, Monads and Algebras, pp. 138 of Mac Lane (1971) \\cite{MacL1978}.\n\\begin{proposition}\n\tadjunction $\\langle F, G, \\eta, \\epsilon \\rangle : X \\to A$, $\\exists \\, $ monad in category $X$ (notation $\\langle F,G, \\eta, \\epsilon \\rangle : \\mathbf{C} \\to \\mathbf{D}$, $\\exists \\, $ monad in category $\\mathbf{C}$). \n\t\n\tSpecifically, 2 functors $F:\\mathbf{C} \\to \\mathbf{D}$, $G:\\mathbf{D} \\to \\mathbf{C}$ have composite $T = GF$, an endofunctor, \\\\\n\tunit $\\eta$ of adjunction is natural transformation $\\eta : 1 \\to T$, \\\\\n\tcounit $\\epsilon :FG \\to 1_A$ of adjunction yields by horizontal composition; a natural transformation\n\t\\[\n\t\\mu = G\\epsilon F: GFGF \\to GF = T\n\t\\] \n\\end{proposition}\n\nTODO: adjunction.\n\n\\subsection{Applications of Monads: Correspondence between Monads in Computer Science and Monads in Category Theory}\n\ncf. \\href{https://ncatlab.org/nlab/show/monad+%28in+computer+science%29}{monad (in computer science), nLab}\n\nFor monads in computer science, \\\\\nmaps type $X$ to new type $T(X)$, \\\\\nequipped with rule for composing 2 functions of form $f:X \\to T(Y)$ (called Kleisli functions), $g:Y \\to T(Z)$ to function \n\\[\ng\\circ f : X \\to T(Z) \\quad \\text{(their Kleisi composition)}\n\\]\nassociative in evident sense, unital with respect to given unit function called $\\text{pure}_X: X \\to T(X)$ to be thought of as taking a value to the pure computation that simply returns that value. \\\\\n\ne.g. when monad $T(-)$ forms product types $T(X) = X \\times Q$, some fixed type $Q$ that carries structure of monoid. \\\\\nThen Kleisi function $f:X \\to Y \\times Q$ is a function $X\\to Y$ that produces as a side effect output of type $Q$. \\\\\nKleisi composition of $\\begin{aligned} & \\quad \\\\\n\t& f:X\\to Y\\times Q \\\\\n\t& g: Y \\to Z\\times Q\\end{aligned}$ \\, not only evaluates the 2 programs in sequence, but also combines their $Q$-output using monoid operation of $Q$, e.g.\n\t\n\tif $\\begin{aligned} & \\quad \\\\ \n\t& fx = (y, q) \\\\ \n\t& gy = (z,q')\\end{aligned}$ \\, then $(g\\circ f)(x) = (z, qq')$ \\\\\n\t\nLet syntactic category be denoted $\\mathbf{C}$. \\\\\n\n$\\text{Obj}{\\mathbf{C}} \\ni X$ \\quad \\, $\\to $ \\, types of the (programming) language \\\\\n$\\text{Hom}_{\\mathbf{C}}(X,Y)$ \\quad \\, $\\to $ \\, \"programs\" that takes value of type $X$ as input and returns value of type $Y$ \\\\\n\nendofunctor $T: \\mathbf{C} \\to \\mathbf{C}$ \\\\\nobject map $T:X \\to T(X)$ sends each type $X\\in \\text{Obj}{\\mathbf{C}}$ to another type $T(X) \\in \\text{Obj}{\\mathbf{C}}$. \\\\\n\nunit natural transformation $\\epsilon:1_{\\mathbf{C}} \\to T$ provides $\\forall \\,$ type $X$ a component morphism $\\text{pure}_X :X \\to T(X)$ (notation, \\href{https://ncatlab.org/nlab/show/monad+%28in+computer+science%29}{ncat} uses the notation $\\epsilon$; we will use $\\eta$ for the \"unit\" natural transformation of a monad):\n\t\\[\n\t\t\\begin{aligned}\n\t\t& \\eta : 1_{\\mathbf{C}} \\to T \\\\ \n\t\t& \\eta_X : X\\to T(X) \\equiv \\text{pure}_X : X \\to T(X)\n\t\t\\end{aligned}\t\n\t\\]\n\nmultiplication natural transformation $\\mu :T^2 \\to T$ provides $\\mu_X : T^2(X) \\to T(X)$ which induces Klesli composition by formula\n\\begin{equation}\n\\begin{aligned} \n\t(g\\circ f) & := (Y \\xrightarrow{g} T(Z)) \\circ_{\\text{Klesli}} (X\\xrightarrow{f} T(Y)) \\\\\n\t& := X \\xrightarrow{f} T(Y) \\xrightarrow{T(g)} T(T(Z)) \\xrightarrow{ \\mu(Z) } TZ\n\\end{aligned} \n\\end{equation}\n$T(g)$ uses fact that $T(-)$ is functor morphism $\\mu(Z)$ is 1 that implements \"$T$-computation\".\n\nNow \\href{https://ncatlab.org/nlab/show/monad+%28in+computer+science%29}{nLab} says this about the \"bind\" operation: \\\\\n\t\"bind\" \\quad $\\leftrightarrow$ \\, multiplication on monad $M$, \\\\\n\t\\begin{equation}\\label{Eq:BindAsStrongMonad}\n\t\\begin{gathered} \n\tMA \\to (MB)^A \\to MB \\text{ equivalent to map } MA \\times MB^A \\to MB \\\\ \n\t MA \\times MB^A \\xrightarrow{ \\text{ strength } } M(A\\times MB^A) \\xrightarrow{ M_{\\text{eval}_{A, MB} } } MMB \\xrightarrow{ mB } MB\n\t\\end{gathered} \n\t\\end{equation}\nTo try to make sense of Eq. \\ref{Eq:BindAsStrongMonad}, consider the following: \n\\[\n\\begin{gathered}\n\\text{Recall for natural transformation $\\eta$, the component $\\eta_X$: } \\mu_X : T^2(X) \\to T(X) \\text{ and for some morphism $f \\in \\text{Mor}{\\mathbf{C}}$}, \\\\\n\tf:X\\to Z \\\\\n\tTf:T(X) \\to T(Z)\n\\end{gathered} \n\\]\nSo if $f:X\\to T(Y)$ instead, \n\\[\n\\begin{gathered}\nTf:T(X) \\to T^2(Y) \\\\ \n(\\mu_Y \\circ Tf) : T(X) \\to T(Y)\n\\end{gathered} \n\\]\nForm a Cartesian product of $T(X)$ and $\\text{Hom}_{\\mathbf{C}}(X,T(Y)) \\ni f$ as inputs: $T(X) \\times \\text{Hom}_{\\mathbf{C}}(X, T(Y))$. \\\\\n\nThen I suggest that Eq. \\ref{Eq:BindAsStrongMonad} is translated as follows:\n\\begin{equation}\nT(X) \\times \\text{Hom}_{\\mathbf{C}}(X, T(Y)) \\xrightarrow{ \\text{ apply } T } T( T(X) \\times \\text{Hom}_{\\mathbf{C}}(X, T(Y))) \\xrightarrow{ Tf} T^2(Y) \\xrightarrow{ \\mu_Y } T(Y) \n\\end{equation}\nwhere apply $T$ is on $f\\in \\text{Hom}_{\\mathbf{C}}(X,T(Y))$ in order to form $Tf$.\n\n\\subsubsection{More on Klesli composition}\n\ncf. \\href{https://ncatlab.org/nlab/show/Kleisli+category}{Kleisli category, nLab}.\n\n\\begin{proposition}\\label{Prop:KlesliCompositionForm}\n\tKlesli composition of $g\\circ f$ of $\\begin{aligned} & \\quad \\\\ \n\t& f: X\\to T(Y) \\\\ \n\t& g: Y \\to T(Z) \\end{aligned}$ \\, is given by \n\t\\[\n\tX \\xrightarrow{f} TY \\xrightarrow{ Tg} T^2Z \\xrightarrow{\\mu_Z} TZ \n\t\\]\n\ti.e. \n\t\\begin{equation}\n\t\t\\boxed{ g \\circ_{\\text{Klesli}} f = \\mu_Z \\circ Tg \\circ f }\n\t\\end{equation}\n\twith $ \\mu_Z \\circ Tg \\circ f : X \\to T(Z)$\n\\end{proposition}\n\n\\begin{proof}\n\tFullness of functor $T$: \\\\\n\t\n\t$\\forall \\, $ morphism $g: T(X) \\to T(Y)$ has antecedent the composition\n\t\\[\n\tX\\xrightarrow{ \\eta_X} T(X) \\xrightarrow{g} T(Y) \n\t\\]\n\ti.e. $g\\circ \\eta_X : X \\to T(Y)$. \\\\\n\t\nConsider $T(g \\circ \\eta_X) = Tg \\circ T \\eta_X : T(X) \\to T^2(Y)$ for \n\\[\n\\begin{aligned} \n\t& T\\eta_X : T(X) \\to T^2(X) \\\\ \n\t& Tg : T^2(X) \\to T^2(Y) \\\\ \n\t& \\mu_Y : T^2(Y) \\to T(Y) \n\\end{aligned} \n\\]\nSo \n\\[\n\\mu_Y \\circ Tg \\circ T\\eta_X = \\mu_Y \\circ T(g\\circ \\eta_X) : T(X) \\to T(Y)\n\\]\nBecause $g$ is a morphism of algebras (TODO: understand what this means, from \\href{https://ncatlab.org/nlab/show/Kleisli+category}{Kleisli category, nLab}), \n\\[\n\\mu_Y \\circ Tg \\circ T\\eta_X = g\\circ \\mu_X \\circ T\\eta_X = g\n\\]\nwhere $\\mu_Y \\circ Tg = g\\circ \\mu_X$ uses natural transformation definition \\ref{Def:NaturalTransformation} for the property $\\mu_Z \\circ T^2 f = Tf \\circ \\mu_X$ (TODO: Show $g=Tf$ is of this form), \\\\\nand $\\mu \\circ T\\eta = \\mu \\circ \\eta T = 1_T$ (coherence condition from Prop. \\ref{Prop:MonadCoherenceConditions}). \\\\\n\nFaithfulness: \\\\\n\nIf $\\mu_Y \\circ Tf = \\mu_Y \\circ Tg$, then precompose by $\\eta_X$ yields \n\\[\n\\mu_Y \\circ Tf \\circ \\eta_X = \\mu_Y \\circ \\eta_{f(X)} \\circ f = \\mu_Y \\circ \\eta_{T(Y)} \\circ f = f\n\\]\nwhere \\\\\n$Tf\\circ \\eta_X = \\eta_{T(Y)} \\circ f$ from natural transformation def. \\ref{Def:NaturalTransformation} was used, and $\\mu \\circ \\eta T = 1_T$ (coherence condition) was also used, for $f:X \\to T(Y)$. \\\\\n\nSimilarly for $g$. $\\mu_Y \\circ Tf = \\mu_Y \\circ Tg \\Longrightarrow f=g$.\n\\end{proof} \n\nNotice that the multiplication natural transformation $\\mu:T^2 \\to T$ was needed to induce the Klesli composition.\n\n\\subsubsection{Dictionary between Monads in Computer Science and Monads in Category Theory}\n\n\\[\n\\boxed{ \\texttt{join} \\quad \\text{ is } \\, \\mu_X : T^2(X) \\to T(X)}\n\\]\n\n\\[\n\\boxed{ \\texttt{return} \\quad \\text{ is } \\, \\eta_X: X \\to T(X) }\n\\]\n\n\\[\n\\boxed{ \\texttt{fmap} \\quad \\text{ is the morphism map (arrow map) for functor } F}\n\\]\n\n\\[\n\\boxed{ \\texttt{bind} \\quad \\text{ is } \\, \\mu_Y \\circ Tf : T(X) \\to T(Y) \\text{ but ... }}\n\\]\n\\texttt{bind} is more nuanced in that, from the Haskell and functional programming perspective, it takes in \\emph{two} inputs. \\\\\n\nOne of them is an element $x$ in the object $X$, $x \\in X$. The other is a \"transformation of type $X \\to T(Y)$.\" I believe that would mean a morphism $f: X \\to T(Y)$. \\\\\n\nWhat \\v{C}uki\\'{c} in \\v{C}uki\\'{c} (2018) \\cite{Cuki2018} calls \\texttt{transform} is the \\emph{morphism map} (arrow map) for a functor $F$. However, note that when it comes to concrete implementation, the concrete implementation applies to \\emph{instances} of a type $X \\in \\text{Obj}{\\mathbf{C}}$. For a given type $X$, e.g. \\verb|int| (the integer type in C or C++), there are many values that will have that type. It would be good that we work out how the definitions, theorems, and commutative diagrams apply in this case.\n\n% TODO: work out the case when an object in $\\text{Obj}{\\mathbf{C}}$ for category $\\mathbf{C}$, when the object itself has associated elements.\n\nI don't think there's a great way to reconcile what Haskell and functional programming programmers mean by \\texttt{bind} with the corresponding concept in category theory. \n\n\\subsection{Examples of Monads in Computer Science}\n\n\n\\subsubsection{Reader Monad; Function Monad; Environment Monad} $[W, -] : \\mathbf{C}\\to \\mathbf{C}$.\n\nGiven $W \\in \\text{Obj}{\\mathbf{C}}$, ($W$ is a type), \n\\[\n[W, - ] = (W \\to (-))\n\\]\nwhere $[-, -] : \\mathbf{C}^{\\text{op}} \\times \\mathbf{C} \\to \\mathbf{C}$.\n\n$W \\mapsto $ internal hom out of $W$.\n\n\\[\n\\begin{aligned} \n& \\eta_X : X \\to [W, -](X) \\\\ \n& \\eta_W: W \\to [W, -](W) \\\\ \n& \\eta_W : w \\mapsto [W,-](W)(w) \\text{ \\, value to constant functions with that value } \\\\ \n& \\Delta : X \\in \\text{Obj}{\\mathbf{C}} \\xrightarrow{ (1,1) } X \\times X \\\\ \n& \\Delta : x \\mapsto (w,w)\n\\end{aligned} \n\\]\n\n\"read in \" state of type $W$ (an environment)\n\n\\href{https://en.wikipedia.org/wiki/Monad_(functional_programming)#State_monads}{wikipedia} calls this the Environment Nomad. \\\\\n\n\\texttt{reader}: $T \\to E \\to T = t\\mapsto e \\mapsto t$ corresponds to $\\eta_X : X \\to T(X)$ where $T(X) = \\text{Hom}_{\\mathbf{C}}(E,X)$ s.t. $\\eta_X$ sends values $x\\in X $ to constant functions (on $E$) to value $x$. \\\\\n\nTherefore, rewrite the unit component at $X$, i.e. \\texttt{reader}, as \\\\\n\\begin{equation}\n\\begin{gathered}\n\\begin{aligned}\n& X \\to E \\to X \\\\\n& x \\mapsto e \\mapsto x\n\\end{aligned} \\qquad \\, \n\\begin{aligned}\n\t& \\eta_X : X \\to \\text{Hom}_{\\mathbf{C}}(E,X) \\\\ \n\t& \\eta_X : x \\mapsto (e\\mapsto x)\n\\end{aligned}\n\\end{gathered}\n\\end{equation}\nThus, the \\emph{unit} component at $X$, called \\texttt{unit} or \\texttt{return} by programmers, truly maps a value $x \\in X$ to a \\emph{constant function}:\n\\begin{equation}\n\\eta_X : x \\mapsto (e \\mapsto x) \\in \\text{Hom}_{\\mathbf{C}}(E, X)\n\\end{equation}\n\n\n\\texttt{bind}: $(E\\to T) \\to (T\\to E \\to T') \\to E \\to T' = r\\mapsto f \\mapsto e \\mapsto f(re)e$ corresponds to $\\mu_Y \\circ Tf:T(X) \\to T(Y)$ where $T(X) = \\text{Hom}_{\\mathbf{C}}(E,X)$, $T(Y) = \\text{Hom}_{\\mathbf{C}}(E,Y)$, and \\\\\n$f:X\\to T(Y)$ or $f:X\\to \\text{Hom}_{\\mathbf{C}}(E,Y)$ \\\\\n$Tf : T(X) \\to T^2(Y)$ or $Tf : \\text{Hom}_{\\mathbf{C}}(E,X) \\to \\text{Hom}_{\\mathbf{C}}(E,T(Y)) = \\text{Hom}_{\\mathbf{C}}(E, \\text{Hom}_{\\mathbf{C}}(E,Y))$. \\\\\n\nSo let's rewrite \\texttt{bind} in our notation:\n\\[\n\\begin{aligned}\n\t& (E\\to X) \\to & (X \\to E \\to Y) \\to & E \\to & Y \\\\\n\t& r \\mapsto & f \\mapsto & e \\mapsto (f(r))(e)(e)\n\\end{aligned}\n\\]\n\nTo clarify these definitions, rewrite the reader monad: the endomorphism $T$ is defined as\n\\begin{equation}\n\\boxed{ \\begin{aligned} & T := [E, -] \\\\ & T(X) = [E, X] \\end{aligned} }\n\\end{equation}\n\nFor any morphism $f : X \\to T(Y) = [E, Y]$, then \\\\\nrecall the Klesli composition: $g \\circ_{\\text{Klesli}} f = \\mu_Z \\circ Tg \\circ f$ with $g: Y \\to T(Z) = [E,Z]$. \n\nBut if you take a look at how wikipedia defines \"bind\" for the reader monad, then bind \\emph{is not} the Klesli composition, but rather it's $\\mu_Y \\circ Tf$ (!!!):\n\\begin{equation}\n\\begin{gathered}\n\\mu_Y \\circ Tf: T(X) \\to T(Y) \\text{ or } \\mu_Y \\circ Tf : [E, X] \\to [E, Y] \\\\ \nr \\in [E,X] \\qquad \\, r(e) \\in X \\text{ for } e \\in E \\qquad \\, f(r(e)) \\in T(Y) = [E,Y] \\qquad \\, f(r(e))(e) \\in Y\n\\end{gathered}\n\\end{equation}\nbind, as defined by wikipedia for the reader monad \\emph{is not} the Klesli composition.\n\nAs an example, consider the following example: \\\\\n$T(Y) \\ni (E\\to Y) \\in \\text{Hom}_{\\mathbf{C}}(E,Y)$ \\\\\n$e = $ \"dag\" $\\mapsto y = $ \"Hello Dag!\" \\\\\n\n$T(X) \\ni (E\\to X) \\in \\text{Hom}_{\\mathbf{C}}(E,X)$ \\\\\n$e \\equiv $ \\texttt{name} $\\mapsto x = $ \"Hi \\texttt{name}!\" \\\\\n\n$f:X\\to T(Y) \\to f:X\\to \\text{Hom}{(E,Y)}$ \\\\\n$f(x) = $ replace \"Hi\" with \"Hello\" in $X$. \\\\\n\n\\texttt{ask}: $E\\to E = 1_E$. \\\\\n\\texttt{ask} operation used to retrieve current context. \\\\\n\n\\texttt{local}: $(E\\to E) \\to (E\\to T) \\to E \\to T = f \\mapsto c \\mapsto e \\mapsto c(fe)$ \\\\\nlocal executes a computation in a modified subcontext. $(E\\to E)$ modifies the environment, $(E\\to T)$ uses the modified environment. \\\\\nRewrite \\texttt{local} in our notation: \\\\\n\\[\n\\begin{aligned} \n\t& (E\\to E) \\to & (E\\to X) \\to & E \\to & X \\\\\n\t& f \\mapsto & c \\mapsto & e \\mapsto & c(f(e))\n\\end{aligned}\n\\]\nTo make sense of this, let $f \\in [E, E]$, $c\\in [E,X] = T(X)$, $c\\circ f \\in [E, X]$ so $(c\\circ f)(e) \\in X$. \\\\\n\n\n\\subsubsection{Writer Monad} $W \\times (-) : \\mathbf{C} \\to \\mathbf{C}$ where $W \\in \\text{Obj}{\\mathbf{C}}$. If $W$ equipped with the structure of monoid, $W \\times (-)$ canonically inherits the structure of a \\emph{monad}. Hence, the Writer \\emph{Monad}. \n\nRecall $W$ monoid if $W$ is a set equipped with binary operation $\\mu : M \\times M \\to M$ s.t. $(xy)z = x(yz)$ and $1 \\in M$ s.t. $1\\cdot x = x = x \\cdot 1$. \\\\\n\n\\subsubsection{State Monad}\n\ncf. \\href{https://ncatlab.org/nlab/show/state+monad}{state monad, nLab}\n\nInput of type $X$, output of type $Y$, mutable state type $W$.\n\nConsider morphism \n\\[\nX\\times W \\to Y\\times W\n\\]\n\nUnder (Cartesian product $\\vdash$ internal hom) adjunction, this is equivalently given by its adjunt, which is a function of type\n\\[\nX \\to [W, W\\times Y]\n\\]\n$[W, W\\times (-)]$ is the monad, induced by the above adjunction. \\\\\n\n$X \\to [W, W\\times Y]$ regarded as a morphism.\n\n$[W, W\\times Y]:\\mathbf{H} \\to \\mathbf{H}$ is called \\emph{state monad} for mutable states of type $W$.\n\nTODO: Understand the above.\n\nWriter comonad $W \\times (-):\\mathbf{C} \\to \\mathbf{C}$, \\\\\n\nGiven by forming Cartesian product with $W$. \\\\\n\nReader Monad $\\circ$ Writer Comonad is state monad.\n\ncf. \\href{https://en.wikipedia.org/wiki/Monad_(functional_programming)#State_monads}{wikipedia}\n\nunit or \"return\":\n\\begin{equation}\\label{Eq:ReturnStateMonadWikipedia}\n\\begin{aligned}\n& X \\to & S \\to X \\times S \\\\\n& x \\mapsto & (s \\mapsto (x, s))\n\\end{aligned}\n\\end{equation} \nCompare this to \n\\[\n\\begin{aligned} \n\t& \\eta_X : X \\to T(X) = [S, S \\times X] \\\\ \n\t& \\eta_X : x \\mapsto (S \\to S \\times X)\n\\end{aligned} \n\\]\n\n\"bind\" was given by \\href{https://en.wikipedia.org/wiki/Monad_(functional_programming)#State_monads}{wikipedia} as \n\\begin{equation}\\label{Eq:BindStateMonadWikipedia}\n\\begin{aligned} \n\t& (S \\to X \\times S) \\to & (X \\to S \\to Y \\times S) \\to & S \\to & Y \\times S \\\\ \n\t& m \\mapsto & k \\mapsto & s \\mapsto & k(x)(s) \n\\end{aligned} \n\\end{equation}\nwhere $(x, t) = m(s)$\n\n\\subsubsection{Properties of the State Monad}\n\nFor the unit or \"return\", $\\eta_X : X \\to T(X) = [S, S \\times X]$, \\\\\n%Choose $\\eta_X$ s.t. it sets state $s\\in S$ to be the initial state $s_0$\n\\begin{equation}\n\\begin{gathered} \n\\eta_X : x \\mapsto (S \\to S \\times X) \\text{ s.t. } \\\\\n(S \\to S \\times X) : s \\mapsto (s, x)\n\\end{gathered} \n\\end{equation}\nTherefore, for the unit component at $X$ of a state monad,\n\\begin{equation}\n\\boxed{ \\eta_X(x)(s) = (s, x) \\text{ for } s \\in S }\n\\end{equation}\nCompare this to what wikipedia says how it defines the \"\\texttt{return}\" operation in Eq. \\ref{Eq:ReturnStateMonadWikipedia}.\n\nConsider any morphism $f : X \\to T(Y) = [S, S\\times Y]$,\n\\begin{equation}\n\\begin{aligned}\n& f : X \\to T(Y) = [S, S\\times Y] \\\\\n& f:x \\mapsto (S \\to S\\times Y) \\text{ s.t. } (S \\to S \\times Y) : s \\mapsto (t = f_s(s, x), y = f_x(s, x))\n\\end{aligned}\n\\end{equation}\n\nAllow morphism $f$ to have \"freedom\" to set state to arbitrary $t$.\n\n\\begin{equation}\n\\begin{aligned}\n& Tf:T(X) \\to T^2(Y) \\to Tf : [S, S\\times X] \\to T([S, S\\times Y]) = [S, S \\times [S, S\\times Y]] \\\\\n& Tf:(S \\to S \\times X) \\mapsto (S \\to S \\times (S \\to S \\times Y))\n\\end{aligned}\n\\end{equation}\n\nThen\n\\begin{equation}\n\\begin{aligned}\n& \\mu_Y \\circ Tf : T(X) \\to T(Y) \\text{ or } \\mu_Y \\circ Tf : [S, S \\times X] \\to [S, S \\times Y] \\\\ \n& \\mu_Y \\circ Tf: (S \\to S \\times X) \\mapsto (S \\to S \\times Y)\n\\end{aligned}\n\\end{equation}\n\nNote that \n\\begin{equation}\n\t\\begin{aligned}\n\t& \\mu_X : T^2(X) \\to T(X) \\\\ \n\t& \\mu_X : (S \\to S \\times (S \\to S \\times X)) \\mapsto (S \\to S \\times X)\n\t\\end{aligned}\n\\end{equation} \n\n\\begin{equation}\n\\begin{aligned}\n& T^2 f : T^2(X) \\to T^3(Y) \\\\ \n& T^2 f: (S \\to S \\times (S \\to S\\times X)) \\mapsto (S \\to S \\times (S \\to S \\times (S \\to S \\times Y)))\n\\end{aligned}\n\\end{equation}\n\nNow\n\\[\n\\begin{gathered} \n \\mu_X \\circ T^2 f : (S \\to (S \\times (S \\to S \\times X))) \\mapsto (S \\to S \\times (S \\to S \\times Y)) \\\\ \n Tf \\circ \\mu_X : (S \\to S \\times (S \\to S \\times X)) \\mapsto (S \\to S \\times (S \\to S \\times Y))\n\\end{gathered} \n\\]\nand so \n\\[\n\\Longrightarrow \\mu_X T^2 = Tf \\mu_X \n\\]\nThus, $\\mu$, as defined above, \\emph{is} a natural transformation.\n\nShow $\\eta_{T(Y)} \\circ f = Tf\\circ \\eta_X$. \n\\[\n\\begin{gathered} \n\tTf \\circ \\eta_X (x) = (S \\to S \\times (S \\to S \\times Y)) \\\\ \n \\eta_{T(Y)} \\circ f(x) = \\eta_{T(Y)} (S \\to S \\times Y) = (S \\to S \\times (S \\to S \\times Y))\n\\end{gathered} \n\\]\n%Thus, we have to backtrack and make $s= s_0$ for $f:X \\to T(Y)$, and $T$ needs to induce $\\eta_{T(Y)}$ to apply a non-trivial morphism.\n\nProve now the coherence conditions, Prop. \\ref{Prop:MonadCoherenceConditions}. For the first one,\n\\[\n\\mu \\circ T \\mu = \\mu \\circ \\mu T\n\\]\n\n\\[\n\\begin{gathered} \n\t\\mu \\circ T \\mu (S \\to (S \\to S \\times (S\\to S \\times X))) = \\mu \\circ T (S \\times (S \\to S \\times X)) = \\mu (S \\to S \\times (S \\times (S \\to S \\times Y))) = \\\\\n\t= (S \\times (S \\to S \\times Y)) \\\\ \n \\mu\\circ \\mu T (S \\to (S \\to S \\times (S\\to S \\times X))) = \\mu^2 (S \\to S \\times (S \\to (S \\to S \\times (S \\to S \\times Y)))) = \\\\\n \t= S \\times (S \\to S \\times Y)\n\\end{gathered} \n\\]\n\\[\n\\Longrightarrow \\mu \\circ T \\mu = \\mu \\circ \\mu T\n\\]\nSo the first coherence condition is proven.\n\nFor the second, \n\\[\n%\\begin{aligned} \n%&\t\\mu \\circ T \\eta (x) = (y, t) \\\\ \n%& \\mu \\eta T (x) = \\mu \\circ \\eta(x, s) = (y, t)\n%\\end{aligned} \\Longrightarrow \\begin{aligned} \n%& T:X\\to T(X) \\\\ \n%& T: x\\mapsto (x, s_0)\n%\\end{aligned} \n\\begin{gathered}\n\\mu \\circ T \\eta (S\\to S \\times X) = \\mu \\circ T (S \\to S \\times (S \\to S \\times X)) = (S \\to S \\times (S \\to S \\times X)) \\\\\n\\mu \\eta T (S\\to S \\times X) = \\mu \\circ (S \\to S \\times T(S \\to S \\times X)) = T(S \\to S \\times X) = (S \\to S \\times (S \\to S \\times X))\n\\end{gathered}\n\\]\n\n\\[\n%\\begin{aligned} \n%\t& \\mu \\circ T \\eta(x,s) = \\mu \\circ T ((y, t), s) = ((z,u) , t) \\\\ \n%\t& \\mu \\circ \\eta T(x,s) = \\mu\\circ \\eta ((y,t) , s) = ((z,u), t) \n%\\end{aligned} \\Longrightarrow \\begin{aligned}\n%& T:T(X) \\to T^2(X) \\\\ \n%& T(x,s) = ((y,t), s)\n%\\end{aligned}\n\\]\nThus, it's been shown that the choice of endomorphism for the state monad, $X \\to [S, S \\times X]$, fulfills the monad coherence conditions being of this form.\n\n%However, $1_T(x,s) = ((y,t), s)$. Therefore, we must give up on making both $\\mu \\circ \\eta T$ and $\\mu \\circ T \\eta$ be ever equal to $1_T$. Thus, diagram \\ref{Eq:MonadLeftRightUnitLawsDiagram} is modified as such: \n\n%\\begin{equation}\\label{Eq:StateMonadLeftRightUnitLawsDiagram}\n%\\begin{tikzcd}\n%T \\arrow{d}{ T \\eta} \\arrow{r}{\\eta T} & T^2 \\arrow{d}{\\mu} \\\\\n%T^2 \\arrow{r}{\\mu} & T\n%\\end{tikzcd}\t\n%\\end{equation}\n\n%I would argue that this is ok because there are examples of mathematical structures without an \"identity\" or \"unit\" such as a semi-group.\n\nConsider what \"bind\" means in category theory. Given\n\\begin{equation}\n\\begin{aligned}\n& f:X \\to T(Y) = [S, S \\times Y] \\\\ \n& g: Y \\to T(Z) = [S, S\\times Z] \\\\ \n& f(x) = (S \\to S\\times Y) \\\\\n& f(x)(s) = (t, y) \\text{ where } s, t \\in W \\\\ \n& g(y) = (S \\to S \\times Z) \\\\ \n& g(y)(t) = (u, z)\n\\end{aligned}\n\\end{equation}\nTherefore, if we define the usual projection operations on a Cartesian product,\n\\begin{equation}\n\\begin{aligned}\n& \\Pi_W : W \\times X \\to W \\\\\n& \\Pi_W(w,x) = w\n\\end{aligned} \\qquad \\, \n\\begin{aligned}\n& \\Pi_X : W \\times X \\to X \\\\\n& \\Pi_X(w,x) = x\n\\end{aligned}\n\\end{equation}\n\\begin{equation}\n\\begin{aligned}\n& \\mu_Z \\circ Tg \\circ f : X \\to T(Z) = [S, S\\times Z] \\ni (W \\to W \\times Z) \\\\ \n& \\mu_Z \\circ Tg \\circ f : x \\mapsto (S \\to S \\times Z) \\equiv \\mu_Z \\circ Tg \\circ f(x)\n\\end{aligned}\n\\end{equation}\nsuch that \n\\begin{equation}\n\\boxed{ g(y)(t) = (u,z) \\text{ where } y = \\Pi_Y(f(x)(s)), \\, t = \\Pi_W(f(x)(s)) }\n\\end{equation}\nCompare this to what wikipedia says in Eq. \\ref{Eq:BindStateMonadWikipedia}.\n\n\\subsubsection{Continuation Monad}\n\nFrom \\href{https://ncatlab.org/nlab/show/continuation+monad}{nLab}, \\\\\nIn a category $\\mathbf{C}$ with internal homs $[-, -]$, so internal homs $[-,-]$ belong to $\\text{Obj}{\\mathbf{C}}$ (they're objects as well), given object $Y \\in \\text{Obj}{\\mathbf{C}}$, the \\emph{continuation monad} is endofunctor\n\\begin{equation}\n\\boxed{ X \\mapsto [[X, Y], Y] } \\text{ i.e. } T(X) = [[X, Y], Y] \\text{ for object $Y \\in \\text{Obj}{\\mathbf{C}}$ } \n\\end{equation}\nso that $T = X\\mapsto [[X, Y] , Y]$\n\nFrom \\href{https://en.wikipedia.org/wiki/Monad\\_(functional\\_programming)\\#Continuation\\_monad}{wikipedia},\n\nunit or return: \\\\\n\nreturn type $Y$, maps type $X$ into functions of type $(X \\to Y) \\to Y$\n\\begin{equation} \n\\begin{aligned}\n\t& X \\to & (X\\to Y) \\to & Y \\\\\n\t& x\\mapsto & f \\mapsto & f(x) = y\n\\end{aligned}\n\\end{equation}\n\nCompare this to\n\\begin{equation}\n\\begin{aligned}\n& T : X \\to [[X, Y], Y] \\\\ \n& \\eta_X : X \\to T(X) = [[X,Y], Y]\n\\end{aligned}\n\\end{equation}\n\nAnd so for the \\emph{unit} of the Continuation monad,\n\\begin{equation}\n\\boxed{\n\\begin{aligned}\n& \\eta_X : X \\to T(X) = [[X, Y], Y] \\\\\n& \\eta_X : x\\mapsto (f \\to y) \\\\ \n& \\eta_X(x)(f) = y = f(x)\n\\end{aligned}\n}\n\\end{equation}\n\nbind: \\\\\n\n\\begin{equation}\\label{Eq:ContinuationMonadBindWiki}\n\\begin{aligned}\n& ((X\\to Y) \\to Y) \\to & (X \\to (X' \\to Y) \\to Y) \\to & (X' \\to Y) \\to & Y \\\\\n& c \\mapsto & f \\mapsto & k \\mapsto & c(t\\mapsto ftk)\n\\end{aligned}\n\\end{equation}\n\nFrom \\href{https://ncatlab.org/nlab/show/continuation+monad}{nLab}, if morphism $f:X\\to Y$ is in Klesi category of the continuation monad, then it's a morphism in $\\mathbf{C}$ of form $X\\to T(Y)$ in $\\mathbf{C}$. Hence morphism in original category \\emph{of the form} $X\\to [[Y,S], S]$ is much like a map from $X \\to Y$, only instead of \"returning\" output $Y$ directly, it instead feeds it into given function $Y\\to S$, which hence \\textbf{continues} the computation. \n\nSo for $X \\to [[Y, S], S]$, \\href{https://ncatlab.org/nlab/show/internal+hom}{nLab} gives the corresponding \\emph{computation rule} for function types of the internal hom $[X, S]$:\n\\[\n(y \\mapsto a(y))(x) = a(x)\n\\]\n\nHence for $X \\to [[X, Y], Y]$, we have $x\\mapsto f \\mapsto f(x)$ because $f \\in [X, Y]$ because $f$ is treated as an object in $\\mathbf{C}$. \\\\\n\nSo do the following \"rewrite\" or change of notation on Eq. \\ref{Eq:ContinuationMonadBindWiki}:\n\n\\begin{equation}\\label{Eq:ContinuationMonadBindWiki2}\n\\begin{aligned}\n& ((X \\to Z) \\to Z) \\to (X \\to (Y\\to Z) \\to Z) \\to (Y \\to Z) \\to Z \\\\ \n& T(X) \\to (X \\to T(Y)) \\equiv \\text{Hom}(X, T(Y)) \\to \\text{Hom}(Y,Z) \\to Z\n\\end{aligned}\n\\end{equation}\nLet $c\\in T(X) = [[X,Z], Z]$. \\\\\nLet $k \\in [Y,Z]$ \\\\\nLet $f(x) \\in [[Y,Z], Z]$ and so \\\\\n$f(x)(k) \\in Z$ \\\\\n\nForm $x \\mapsto f(x)(k) \\in [X,Z]$, so $c(x\\mapsto f(x)(k)) \\in Z$. \\\\\n\nSo \"bind\" as defined in wikipedia, Haskell/Functional Programming isn't the Klesli composition, but it's\n\\[\n\\mu_Y \\circ Tf : T(X) \\to T(Y) = [[Y,Z], Z]\n\\]\n\nWrite this as \n\\begin{equation}\n\\boxed{\n\\begin{aligned}\n& (\\mu_Y \\circ T)(f)(c) \\in T(Y) = [[Y,Z], Z] \\\\\n& (\\mu_Y \\circ T)(f)(c)(k) \\in Z\n\\end{aligned}}\n\\end{equation}\n\n\n\\emph{call with current continuation} function defined as follows: \\\\\ncall/cc\n\\begin{equation}\\label{Eq:CallCurrentContinuationContinuationMonad}\n\\begin{aligned}\n((X \\to (X' \\to Y) \\to Y) \\to (X\\to Y) \\to Y) & \\to (X\\to Y) & \\to Y \\\\ \nf & \\mapsto k & \\mapsto (f(t\\mapsto x \\mapsto kt) k) \n\\end{aligned}\n\\end{equation}\n\nLet's look at Eq. \\ref{Eq:CallCurrentContinuationContinuationMonad}, step-by-step.\n\\[\n\\begin{gathered}\n\\begin{aligned} \n& (X\\to (X' \\to Y) \\to Y) \\\\\n& f\n\\end{aligned} \\text{ corresponds to } \\\\\n\\begin{gathered}\nX \\to [[X' , Y], Y] = T(X') \\\\\nf \\equiv f_{XX'} : X \\to T(X')\n\\end{gathered}\n\\end{gathered}\n\\]\n\n\\subsubsection{\\texttt{future} as Continuation Monad}\n\n \\v{C}uki\\'{c} (2018) \\cite{Cuki2018} asks first if \\verb|std::future| in C++ is a functor. Recall the definition of a functor, Def. \\ref{Def:Functor}:\n\n\\[\n\\begin{aligned}\n& F: \\mathbf{C} \\to \\mathbf{D} \\text{ with \"object\" map } \\\\ \n& F: \\text{Obj}{\\mathbf{C}} \\to \\text{Obj}{\\mathbf{D}} \\\\ \n& F: X \\to F(X)\n\\end{aligned}\n\\] \nand the functor's \"morphism map\":\n\\[\n\\begin{aligned}\n& Ff :F(X) \\to F(Y) \\\\ \n& f:X \\to Y, \\, f \\in \\text{Hom}_{\\mathbf{C}}(X, Y)\n\\end{aligned}\n\\]\n\nSuppose $X = $ \\texttt{T1}, $Y = $ \\texttt{T2}. Then in the example on pp. 220, Sec. 10.7.1 Futures as monads\" example of \\v{C}uki\\'{c} (2018) \\cite{Cuki2018}, \n\\[\n\\begin{aligned}\n& F(X) = \\verb|future| \\\\ \n& F(Y) = \\verb|future|\n\\end{aligned}\n\\]\n\nInstead, the morphisms to consider is of this form:\n\\[\nf:X \\to T(Y)\n\\]\nwhere $T$ is a functor but a special one: the endomorphism. And $T$ is \\verb|std::future|.\n\nHere are examples of morphisms $f, g$:\n\\[\n\\begin{aligned}\n& \\verb|future user_full_name(const std::string& login);| \\\\\n& \\verb|future to_html(const std::string& text);|\n\\end{aligned}\n\\]\n\nNow $Tf:T(X) \\to T^2(Y)$, how the morphism map for $T$ applies to morphism $f$, now. Recall that we can compose this with the multiplication natural transformation component at $X$, $\\mu_X$:\n\\[\n\\begin{aligned}\n& \\mu_X \\circ Tf : T(X) \\to T(Y) \\\\ \n& \\mu_X : T^2(X) \\to T(X)\n\\end{aligned}\n\\]\n\nIn order to compose morphisms, say $f,g$, recall the \"Klesli composition\", Prop. \\ref{Prop:KlesliCompositionForm}\n\\begin{equation}\ng\\circ_{\\text{Klesili}} f = \\mu_Z \\circ Tg \\circ f\n\\end{equation}\nIf we call $\\mu_Z \\circ T$ \"bind\", $\\mu_Z \\circ T: \\text{Hom}(Y, T(Z)) \\to \\text{Hom}(T(Y), T(Z))$. The correspondence is such:\n\\begin{equation}\n(\\texttt{bind}(\\verb|to_html|))(\\verb|user_full_name|) \\Longleftrightarrow \\mu_Z \\circ Tg \\circ f: X \\to T(Z)\n\\end{equation}\n\n\n\\subsubsection{Resources for implementations of Monads} Python and C++ code. \\\\\n\n\\url{https://github.com/Iasi-C-CPP-Developers-Meetup/presentations-code-samples}, namely \\\\\n\\url{https://github.com/Iasi-C-CPP-Developers-Meetup/presentations-code-samples/tree/master/radugeorge} \\\\\n\n\\url{https://github.com/dbrattli/OSlash}, namely \\\\\n\\url{https://github.com/dbrattli/OSlash/tree/master/tests} \\\\\n\n\\href{https://gist.github.com/pfultz2/f538423ebc9bbbe3df92}{State Monad implementation in C++}\n\n\n\\section{Applications of Category Theory on Hybrid Systems}\n\ncf. Ames (2006) \\cite{Ames2006}.\n\t\n\\subsection{D-Categories}\n\n$D$ stands for discrete.\n\nRecall that a small category $\\mathbf{C}$ is called \\emph{small} if both $\\text{Obj}(\\mathbf{C})$ and $\\text{hom}(\\mathbf{C})$ are sets, not proper classes. \n\n\\begin{definition}[Axiomatic D-categories]\nLet D-category be a \\emph{small} category $\\mathbf{D}$ s.t.\n\\begin{enumerate}\n\t\\item $\\forall \\, D \\in \\text{Obj}(\\mathbf{D})$, \\\\\n\t$\\exists \\,$ morphism $f \\in \\text{Mor}(\\mathbf{D})$ s.t. $f \\neq 1$ s.t. \\\\\n\t$f \\in \\text{Hom}(D, *)$ or $f\\in \\text{Hom}(*, D)$, but never both, \\\\\n\ti.e. $\\forall \\, $ diagram $a_0 \\xrightarrow{ \\alpha_1} a_1 \\xrightarrow{ \\alpha_2} \\dots \\xrightarrow{ \\alpha_n} a_n$ in $\\mathbf{D}$, all but 1 morphism must be identity (i.e. longest chain of composite non-identity morphisms is of length 1). \n\t\\item If for $D\\in \\text{Obj}(\\mathbf{D})$, $D$ is the domain of a non-identity morphism, i.e. $\\exists \\, f_1 \\in \\text{Mor}(\\mathbf{D})$ s.t. \n\t\\[\n\tf_1 \\in \\text{Hom}(D, *), \\, f_1 \\neq 1\n\t\\]\n\tthen $\\exists \\, f_2 \\in \\text{Hom}(D, *)$, $f_2 \\neq f_1$, $f_2 \\neq 1$ and $\\forall \\, f \\in \\text{Hom}(D, *)$ s.t. $f\\neq f_1,f_2$, \\, $f=1$\n\\end{enumerate}\n\\end{definition}\n\t\ncf. 1.2.1 Important objects in D-categories, Ames (2006) \\cite{Ames2006}.\n\nLet \n\\[\n\\begin{gathered}\n\t\\text{Mor}{\\mathbf{A}} = \\bigcup_{A, B \\in \\text{Obj}(\\mathbf{A})} \\text{Hom}(A,B) \\qquad \\, \\text{(my notation)} \\\\\n\t\\text{Mor}(\\mathcal{D}) = \\bigcup_{(a,b) \\in \\text{Obj}(\\mathcal{D}) \\times \\text{Obj}(\\mathcal{D}) } \\text{Hom}_{\\mathcal{D}}(a,b) \\qquad \\, \\text{ (Ames' notation) }\n\\end{gathered}\n\\]\t\n\t\nLet \n\\begin{equation}\n\\text{Mor}_{1}{\\mathbf{A}} := \\lbrace A \\in \\text{Mor}(\\mathbf{A}) | A \\neq 1 \\rbrace \n\\end{equation}\n\nFor a D-category, consider these subset of $\\text{Obj}(\\mathbf{D})$, \n\n\\begin{definition}[Edge set]\n\t\\textbf{edge set} of $\\mathbf{D}$, $E(\\mathbf{D})$, \n\\begin{equation}\n\\begin{gathered}\nE(\\mathbf{D}) := \\lbrace A \\in \\text{Obj}(\\mathbf{D}) | \\alpha \\in \\text{Hom}(A, *), \\beta \\in \\text{Hom}(A, *), \\alpha, \\beta \\in \\text{Mor}_{1}(\\mathbf{D}), \\, \\alpha \\neq \\beta \\rbrace \\text{ i.e. } \\\\\nE(\\mathbf{D}) := \\lbrace A \\in \\text{Obj}(\\mathbf{D}) | \\alpha, \\beta \\in \\text{Hom}(A, *), \\, \\alpha, \\beta \\neq 1, \\, \\alpha \\neq \\beta \\rbrace\n\\end{gathered}\n\\end{equation}\t\n\\end{definition}\ni.e. $\\forall \\, A \\in E(\\mathbf{D})$, $\\exists \\, \\alpha, \\beta \\in \\text{Mor}(\\mathbf{D})$, \\, $\\alpha, \\beta \\neq 1$, s.t. $\\alpha, \\beta \\in \\text{Hom}(D, *)$; denote these morphisms by $s_a,t_a$ (this specific choice will define an \\textbf{orientation}).\n\nConversely, given morphism $\\gamma \\in \\text{Mor}(\\mathbf{D})$, $\\gamma \\neq 1$, $\\exists \\, ! \\, A \\in E(\\mathbf{D})$ s.t. $\\gamma = s_a$ or $\\gamma = t_a$, i.e. $\\gamma \\in \\text{Hom}(A, *)$. \n\n\\begin{definition}[Vertex set]\n\\textbf{vertex set} of $\\mathbf{D}$:\n\\begin{equation}\n V(\\mathbf{D}) = (E(\\mathbf{D}))^c\n\\end{equation} \n\\end{definition}\n\n\\begin{definition}[Orientation]\n\tOrientation of D-category $\\mathbf{D}$ is a pair of functions $(s,t)$ between sets.\n\t\n\\end{definition}\n\n\n\t\n%\\subsection{Blog (Running log)}\n\n\\part{Category Theory and Databases} \n\t\n\\section{Types}\n\n\\subsection{Data models for nested arrays, dictionaries, and tabular data}\n\n\\begin{definition}[Container types]\n\t\\textbf{Container types} - arrays, key/value pair dictionaries (or: hashes, association lists)\n\\end{definition}\n\n\\begin{definition}[atomic types]\n\tbasic atomic types (e.g. numbers, strings, Booleans)\n\\end{definition}\n\n\\begin{definition}[nesting]\n\t\\textbf{nesting}: containers may contain atomic values as well as other containers.\n\\end{definition}\n\n\\begin{definition}[flat]\n\tTabular data model (i.e. tables) is \\textbf{flat}: field contains \\textbf{atomic} values.\n\\end{definition}\ncf. Number 2, Data Models and Languages, Grust and Duta (2017) \\cite{GrDu2017}\n\n\n\\subsection{Typed Data, Untyped data, in the relational data model}\n\n\\begin{definition}\n\tUntyped data models - text, JSON, and tabular data models (e.g. CSV) do \\textbf{not} enforce values (container or atomic) to be of specific types. \n\t\n\tThese data models are thus referred to as being \\textbf{untyped}.\n\\end{definition}\ncf. Grust and Duta (2017) \\cite{GrDu2017}\n\n\ncf. Number 4, \"The Relational Data Model\", Grust and Duta (2017) \\cite{GrDu2017}\n\n\\begin{definition}[Types]\nLet $\\mathbb{T} \\equiv $ set of all data types (built-in and user-defined). \\\\\n$\\forall \\, $ value $v\\in \\mathbb{V}$ stored in a relation cell must be of type $t\\in \\mathbb{T}$. \\\\\ne.g. When PostgreSQL starts, $\\mathbb{T}$ initialized as \n\\begin{equation}\n \\mathbb{T} = \\lbrace \\texttt{boolean}, \\texttt{integer}, \\texttt{text}, \\texttt{bytea}, \\dots \\rbrace \n\\end{equation}\nConsider category \\textbf{Text} s.t. $\\text{Obj}(\\mathbf{Types}) \\equiv DT \\in \\text{Obj}(\\textbf{Set})$. Then $\\mathbb{T} \\equiv DT$, denoting \\emph{data type}.\n\\end{definition}\n\n\\begin{definition}[Values]\n$\\forall \\, v \\in \\mathbb{V}$ stored in a relation cell, $v$ is an element of the set of all values $\\mathbb{V}$. \n\nin the relational data model, all values $v\\in \\mathbb{V}$ are \"atomic.\"\n\n\\[\n\\mathbb{V} = \\lbrace \\texttt{true}, \\texttt{false}, 0, -1, 1, -2, 2 , \\dots \\rbrace\n\\]\t\n\nHere, I'll use the notation $V$ to denote $\\mathbb{V}$, the set of all values.\n\\end{definition}\n\n\\begin{definition}[Domains]\n\t$\\forall \\, t \\in DT$, its domain $\\text{dom}(t) := $ set of all values of type $t$ (i.e. $\\text{dom}(\\cdot)$ is a function with signature \n\t\\[\n\tDT \\to 2^V\n\t\\])\n\te.g. $\\text{dom}(\\texttt{integer}) = \\lbrace 0 , -1, 1, -2, 2, \\dots \\rbrace $ \\\\\n\t$\\text{dom}(\\texttt{boolean}) = \\lbrace \\texttt{true}, \\texttt{false} \\rbrace$ \n\\end{definition} \n\n\\begin{definition}[type specification]\n\ttype specification $:= $ function $\\pi : U \\to \\mathbf{DT}$ (Spivak's notation) $ \\equiv \\pi : U \\to DT$, $U, DT \\in \\textbf{Set}$.\n\t\n\tset $DT \\equiv $ set of data types for $\\pi$, set $U \\equiv $ domain bundle for $\\pi$.\n\t\n\t$\\forall \\, t \\in DT$, preimage $\\pi^{-1}(t) \\subset U$, \\, $\\pi^{-1}(t) \\equiv $ domain of $t$, $x \\in \\pi^{-1}(t) \\equiv $ object of type $T$.\n\n\tTo reconcile Grust and Duta (2017) \\cite{GrDu2017}'s definition of types above, use this notation:\n\t\\begin{equation}\n\t\\boxed{\n\t\\begin{gathered}\n\t\\textbf{ type specification } \\begin{aligned} & \\quad \\\\ \n\t& \\pi : V \\to DT \\\\ \n\t& \\pi(v) \\in DT \\end{aligned} \\\\\n\t\\text{dom} \\equiv \\pi^{-1}: DT \\to V, \\text{ i.e. } \\\\\n\t\\pi^{-1}(t) \\subset t \\qquad \\, \\forall \\, t \\in DT \n\t\\end{gathered}}\n\t\\end{equation}\n\\end{definition}\n\tcf. Spivak (2009) \\cite{Spiv2009}\n\n\\begin{corollary}[type specification]\n\tIf $v$ has type $T$, $\\pi(v) = T$, $\\Longrightarrow v \\in \\pi^{-1}(T)$\n\\end{corollary}\n\n\\begin{proposition}[\\texttt{CREATE DOMAIN}]\n\tConsider new type $t'$ (SQL command \\texttt{CREATE DOMAIN}) so \n\t\\begin{equation}\n\t\\begin{gathered}\n\tt' \\in DT \\\\\n\t\\pi^{-1}(t') \\subseteq \\pi^{-1}(t)\n\t\\end{gathered}\n\t\\end{equation}\n\\end{proposition}\n\n\n\\section{Relational Data Model}\n\n\t\\textbf{relational data model} maybe understood as a typed variant of the tabular data model. \n\t\\begin{enumerate}\n\t\t\\item $\\exists \\, $ only 1 container type: \\textbf{table} (or: multisets) \\textbf{ of rows}\n\t\t\\item all rows are of same \\textbf{row type} which is declared when table is created.\n\t\t\\item row type \\textbf{consists} of sequence of \\textbf{atomic types}.\n\t\\end{enumerate}\n\nIn the relational data mode, data is exclusively organized in \\textbf{relations}, i.e. sets of tuples of data. Data in each \\textbf{attribute} (tuple component) is \\textbf{atomic}, and of declared \\textbf{type}.\n\n\\subsection{Schemata and Relations}\n\nIn the relational data model, each \\textbf{attribute} of a table has a \\textbf{declared type}.\n\nIf attribute has declared type $t$, the RDBMS will exclusively store values $v$ in that attribute s.t. \n\\begin{enumerate}\n\t\\item $v \\in \\text{dom}(t)$ i.e. $v \\in \\pi^{-1}(t)$\n\t\\item $v$ can successfully be casted to type $t$\n\\end{enumerate}\n\n\\subsection{Attributes (Columns)}\n\nLet $\\mathbb{A}$ denote set of attribute names of all relations.\n\n\\subsection{Attribute types}\n$\\forall \\, $ attribute $a\\in \\mathbb{A}$ has declared (attribute) type $\\text{type}(a) = t\\in DT$ (i.e. $\\text{type}(\\cdot)$ is a function with signature $\\mathbb{A} \\to \\mathbb{T}$).\n\nConsider Definition 2.2.3 of Spivak (2009) \\cite{Spiv2009}, \n\n\\begin{definition}[simple schema of type $\\pi$, $(C,\\sigma)$]\n\tLet type specification $\\pi :V \\to DT$. \n\t\n\t\\textbf{simple schema} of type $\\pi$ consists of pair $(C, \\sigma)$ where $C$ is a finite (totally) ordered set and function $\\sigma : C \\to DT$. $C \\equiv $ \\textbf{column set} or \\textbf{set of attributes} for $\\sigma$ and $\\pi$ as \\emph{type specification for} $\\sigma$.\n\\end{definition}\n\nCompare the notation above. Conclude that\n\\[\n\\begin{gathered}\nC \\equiv \\mathbb{A}, \\quad \\, c \\equiv a \\\\\n\\sigma(c) \\equiv \\text{type}(a)\n\\end{gathered}\n\\]\n\nHere, choose the following notation:\n\\[\n\\boxed{\\begin{gathered}\n\\sigma : C \\to DT \\\\\n\\pi^{-1}: DT \\to V \\\\\n\\pi^{-1} \\circ \\sigma \\equiv \\text{val} \\equiv \\text{set of (admissable) attribute values for attribute (column) $a$ ($c$)}\n\\end{gathered} }\n\\]\nAlso, summarize our definitions with these commutative diagrams:\n\\begin{equation}\n\\begin{gathered}\n\\begin{tikzpicture}\n\\matrix (m) [matrix of math nodes, row sep=3em, column sep=4em, minimum width=2em]\n{\n\tV \\\\\n\tDT \\\\\n};\n\\path[->]\n(m-1-1) edge node [left] {$\\pi$} (m-2-1)\n;\n\\end{tikzpicture} \\qquad \\, \n\\begin{tikzpicture}\n\\matrix (m) [matrix of math nodes, row sep=3em, column sep=4em, minimum width=2em]\n{\n\tv \\\\\n\tt \\\\\n};\n\\path[|->]\n(m-1-1) edge node [left] {$\\pi$} (m-2-1)\n;\n\\end{tikzpicture} \\qquad \\, \n\\begin{tikzpicture}\n\\matrix (m) [matrix of math nodes, row sep=3em, column sep=4em, minimum width=2em]\n{\n\tV & \\pi^{-1}(DT) \\\\\n\tDT & \\\\\n};\n\\path[left hook->]\n(m-1-2) edge node [above] {$i$} (m-1-1)\n;\n\\path[->] \n(m-2-1) edge node [left] {$i \\circ \\pi^{-1}$} (m-1-1)\nedge node [left] {$\\pi^{-1}$} (m-1-2)\n;\n\\end{tikzpicture} \\qquad \\, \n\\begin{tikzpicture}\n\\matrix (m) [matrix of math nodes, row sep=3em, column sep=4em, minimum width=2em]\n{\n\tV & V_t \\subseteq V \\\\\n\tt & \\\\\n};\n\\path[left hook->]\n(m-1-2) edge node [above] {$i$} (m-1-1)\n;\n\\path[|->] \n(m-2-1) edge node [left] {$\\pi^{-1}$} (m-1-2)\n;\n\\end{tikzpicture} \\\\\n\\begin{tikzpicture}\n\\matrix (m) [matrix of math nodes, row sep=3em, column sep=4em, minimum width=2em]\n{\n\tV & \\pi^{-1}(DT) \\\\\n\tDT & C \\\\\n};\n\\path[left hook->]\n(m-1-2) edge node [above] {$i$} (m-1-1)\n;\n\\path[->] \n(m-2-1) edge node [left] {$i \\circ \\pi^{-1}$} (m-1-1)\nedge node [left] {$\\pi^{-1}$} (m-1-2)\n(m-2-2) edge node [right] {$\\pi^{-1} \\circ \\sigma \\equiv \\text{dom} \\circ \\text{type} $} (m-1-2)\nedge node [above] {$\\sigma$} (m-2-1)\n;\n\\end{tikzpicture} \\qquad \\, \n\\begin{tikzpicture}\n\\matrix (m) [matrix of math nodes, row sep=3em, column sep=4em, minimum width=2em]\n{\n\tV & \\pi^{-1}(\\sigma(c_i)) = V_{c_i} \\\\\n\t\\sigma(c_i) \\equiv t_i & c_i \\\\\n};\n\\path[left hook->]\n(m-1-2) edge node [above] {$i$} (m-1-1)\n;\n\\path[|->] \n(m-2-1) edge node [left] {$\\pi^{-1}$} (m-1-2)\n(m-2-2) edge node [above] {$\\sigma$} (m-2-1)\nedge node [right] {$\\pi^{-1} \\circ \\sigma$} (m-1-2)\n;\n\\end{tikzpicture} \n\\end{gathered}\n\\end{equation}\n\n\n\\begin{definition}[Relation Schema]\n\tA relation schema associates a relation (table?) name $R$ with its set of declared attributes (a subset of $\\mathbb{A}$)\n\t\\begin{equation}\n\t(R, \\lbrace a_1, \\dots a_n \\rbrace)\n\t\\end{equation}\nCommon notation: $R(a_1, \\dots a_n)$, so that $R$ is called a $n$-ary relation.\n\nMore notation: $\\text{sch}(R) = \\lbrace a_1, \\dots a_n \\rbrace$, and $\\text{deg}(R) = n$ (degree).\n\t\t\n\\textbf{Relational database schema}: a non-empty finite set of relation schemata makes a \\textbf{relational database schema}\n\\begin{equation}\n\\lbrace (R_1, \\alpha_1), (R_2, \\alpha_2) , \\dots \\rbrace \n\\end{equation}\nwhere $\\alpha_i \\subseteq \\mathbb{A}_i$. In a relational database schema, the relation names $R_i$ are unique.\t\t\n\\end{definition}\n\n\\begin{definition}[Tuple]\n\tGiven relation (i.e. table) $R(a_1, \\dots , a_n)$, a \\textbf{tuple} $t$ of $R$ maps attributes to values, i.e. $t$ is a function with signature $\\lbrace a_1, \\dots a_n \\rbrace \\to V$ with \n\t\\[\n\t\\forall \\, a \\in \\lbrace a_1 , \\dots , a_n \\rbrace : t(a) \\in \\text{val}(a)\n\t\\]\n\tCommon notation for $t(a)$ is $t.a$.\n\\end{definition}\n\nRecall that $\\text{val}(a) := \\text{dom}(\\text{type}(a))$.\n\nTake note that \\textbf{tuple}, defined by Grust and Duta (2017) \\cite{GrDu2017}, is the \\emph{same} as \\textbf{record} or \\textbf{row} $r$, defined by Spivak (2009) \\cite{Spiv2009}.\n\n\\begin{definition}[record or row]\n\t\\textbf{record} or \\textbf{row} on $(C, \\sigma)$\n\t\\begin{equation}\n\t\\begin{aligned}\n\t& r: C \\to V_{\\sigma} \\equiv V_c \\\\ \n\t& r(c) \\equiv v_{rc} \\in \\pi^{-1}\\circ \\sigma(c)\n\t\\end{aligned}\n\t\\end{equation}\n\\end{definition} \n\nSQL \\texttt{CREATE TABLE} command prescribes an order of the attributes of a relation. This deviates from relational data model's tuple model (name-to-value mapping).\n\n\\begin{definition}[Row]\n\tGiven SQL table $R(a_1, \\dots, a_n) \\equiv R(\\alpha) \\equiv \\tau$, a row $r$ of $\\tau$ is an ordered sequence ($a_i$ is called the $i$th column)\n\t\\begin{equation}\n\tr = (v_1, \\dots, v_n) \\in \\text{val}(a_1) \\times \\dots \\times \\text{val}(a_n) \\equiv \\pi^{-1} \\circ \\sigma(a_1) \\times \\dots \\times \\pi^{-1} \\circ \\sigma(a_n)\n\t\\end{equation}\n\tThus, $r$ is a function $\\lbrace 1, \\dots , n \\rbrace \\to V$ with $\\forall \\, i \\in \\lbrace 1 , \\dots , n \\rbrace$, $r(i) \\in \\pi^{-1} \\circ \\sigma(a_i)$\n\\end{definition}\n\nThe set of tuples (rows) stored in a relation (table) is expected to change frequently.\n\n\\begin{definition}[Relation instance (state)]\n\tThe current finite set of tuples $t_i \\equiv r_i$ of relation (table) $R(a_1, \\dots a_n) \\equiv (A, \\sigma)$ is called the relation's \\textbf{instance} (or \\textbf{state}).\n\n\\[\n\\text{inst}(R) = \\lbrace t_1 , t_2 , \\dots t_m \\rbrace \\Longrightarrow \\equiv \\Gamma^{\\pi}(\\sigma) \\equiv \\Gamma(A, \\sigma)\n\\]\n\nDatabase (instance) state - The database instance comprises instances of all its relations.\n\\[\n= \\lbrace \\Gamma(A^i, \\sigma^i) \\rbrace_i\n\\]\n\\end{definition} \n\n\\subsection{Constraints}\n\ncf. Number 5, \"Constraints\" of Grust and Duta (2017) \\cite{GrDu2017}.\n\n\\begin{definition}[Constraints]\n\tAn \\textbf{integrity constraints} specifies conditions which table states have to satisfy at all times. \n\t\n\tCurrent set of constraints, $\\mathbb{C}$, is integral part of database schema:\n\t\\[\n\t(\\lbrace (R_1, \\alpha_1), (R_2, \\alpha_2), \\dots \\rbrace, \\mathbb{C})\n\t\\]\n\tSet of constraints $\\mathbb{C} \\equiv$ set of morphisms of table $\\tau \\equiv \\lbrace (R_1,\\alpha_1), (R_2, \\alpha_2), \\dots \\rbrace $, $C \\subset \\text{Mor}{\\tau}$. \n\\end{definition} \n\nRDBMS will refuse table state changes that violate any constraint $c\\in C$.\n\n\\subsection{Key constraints}\n\n\\begin{definition}[Key]\nKey of a table $R(a_1, \\dots, a_n) \\equiv (\\alpha, \\sigma) \\equiv (\\alpha, \\text{type}) :=$ set of columns $K \\subseteq \\lbrace a_1, \\dots, a_n \\rbrace$ that unique identifies rows of $R$:\n\\[\n\\forall \\, t, u \\in \\text{inst}(R), \\, t.K = u.K \\Longrightarrow t = u\n\\]\nRead: \"If 2 rows agree on the columns in $K$, they are indeed the same row.\"\n\nI will give the following change of notation a try:\n\\begin{equation}\n\\forall \\, r_i , r_j \\in \\lbrace r_i \\rbrace_i^{\\tau}, \\, \\text{ if } r_i(K) = r_j(K), \\text{ then } r_i = r_j\n\\end{equation}\n\\end{definition} \n\n\\begin{equation}\n\\begin{gathered}\n\\begin{tikzpicture}\n\\matrix (m) [matrix of math nodes, row sep=3em, column sep=4em, minimum width=2em]\n{\n\tA & DT \\\\\n\tV_A & \\\\\n};\n\\path[->] \n(m-1-1) edge node [above] {$\\sigma$} (m-1-2)\nedge node [left] {$r$} (m-2-1)\n(m-2-1) edge node [right] {$\\pi^{-1}$} (m-1-2)\n;\n\\end{tikzpicture} \\qquad \\, \n\\begin{tikzpicture}\n\\matrix (m) [matrix of math nodes, row sep=3em, column sep=4em, minimum width=2em]\n{\n\ta & t \\\\\n\tV_A & \\\\\n};\n\\path[|->] \n(m-1-1) edge node [above] {$\\sigma$} (m-1-2)\nedge node [left] {$r$} (m-2-1)\n(m-2-1) edge node [right] {$\\pi^{-1}$} (m-1-2)\n;\n\\end{tikzpicture}\n\\end{gathered}\n\\end{equation}\n\n\nHere's a \"dictionary\" between the definitions so far for relational databases and familiar terms for tables filled with data: cf. 08-30, Week 1 slides of Yang (2012) \\cite{Yang2012}.\n\ndatabase - collection of relations (or tables) \\\\\nrelation - table \\\\\nattributes - columns \\\\\ntuple - row - record \\\\\nrelation schema - heading (heading for a table?, Grust and Duta (2017) \\cite{GrDu2017}) \\\\\nrelation contents - body (body of a table?, Grust and Duta (2017) \\cite{GrDu2017})\n\n\\begin{tabular}{l c r}\n\tCSV & Relational Model & SQL \\\\\n\t& Domain & Domain \\\\ \n\t& Type & Type \\\\\n\t& Schema & Schema \\\\\n\tFile & Relation & Table \\\\\n\tLine & Tuple & Row \\\\\n\tField & Attribute & Column\n\\end{tabular}\n\nIndeed, even Grust and Duta (2017) \\cite{GrDu2017} remarks: \"You will find that textbooks, papers, practitioners, academics, these slides, and even PostgreSQL use a mixture of terminology. Deal with it.\"\n\n\ncf. Slides Number 7, \"Referential Integrity\" of Grust and Duta (2017) \\cite{GrDu2017}.\n\n\\begin{definition}[Foreign Keys]\n\tLet $(S, \\alpha)$ and $(T, \\beta)$ denote 2 relational schemata (not necessarily distinct), \\\\\n\twhere $K = \\lbrace b_{j_1}, \\dots , b_{j_k} \\rbrace \\subseteq \\beta$ is the primary key of $T$. \\\\\n\tLet $F = \\lbrace a_{i_1}, \\dots , a_{i_k} \\rbrace \\subseteq \\alpha $ with $\\text{type}(a_{i_h}) = \\text{type}(b_{j_h})$, $h \\in 1, \\dots, k$. \n\t\n\t$F$ is a \\textbf{foreign key} in $S$ \\textbf{referencing} $T$, if \n\t\\[\n\t\\forall \\, s \\in \\text{inst}(S) : \\exists \\, t \\in \\text{inst}(T) : s.F = t.K\n\t\\]\n\\end{definition} \nThe $\\forall$ and $\\exists $ condition validates the assumption of $K$ being a key in target $T$, i.e. that there \\textbf{exists a row} in table $T$ whose $K$ identifier matches that of table $S$\n\n$K$ being a key in target $T$ validates the assumption that there is \\textbf{no more than one row} of in a table $T$ with a matching key $K$.\n\nIn general, \\textbf{ a foreign key $F$ is not a key} in source table $S$. 2 rows $s_1, s_2 \\in \\text{inst}(S)$ with $s_1.F = s_2.F$ can refer to the same row in target $T$.\n\nHere is a great example of a foreign key: \\url{https://www.w3schools.com/sql/sql_foreignkey.asp}\n\nSo from w3schools, \n\n\"A FOREIGN KEY is a key used to link 2 tables together.\n\nA FOREIGN KEY is a field (or collection of fields) in 1 table that refers to the PRIMARY KEY in another table.\n\nThe table containing the foreign key is called the child table, and the table containing the candidate key is called the referenced or parent table.\n\n\"Persons\" table:\n\n\\begin{tabular}{|l |c |c |r|}\n\\textbf{PersonID} & \\textbf{LastName} & \\textbf{FirstName} & \\textbf{Age} \\\\\n1 & Hansen & Ola & 30 \\\\\n2 & Svendson & Tove & 23 \\\\\n3 & Pettersen & Kari & 20 \n\\end{tabular}\n\n\"Orders\" table:\n\n\\begin{tabular}{ | l | c | r | }\n\t\\textbf{OrderID} & \\textbf{OrderNumber} & \\textbf{PersonID} \\\\ \n\t1 & 77895 & 3 \\\\\n\t2 & 44678 & 3 \\\\\n\t3 & 22456 & 2 \\\\\n\t4 & 24562 & 1 \n\\end{tabular}\n\nNotice that the \"PersonID\" column in the \"Orders\" table points to the \"PersonID\" column in the \"Persons\" table.\n\nThe \"PersonID\" column in the \"Persons\" table is the PRIMARY KEY in the \"Persons\" table.\n\nThe \"PersonId\" column in the \"Orders\" table is a FOREIGN KEY in the \"Orders\" table.\n\n\\quad \\\\\nThus, in other words, \\\\\ngiven 2 tables (i.e. 2 relational schemata, not necessarily distinct), $(S, \\alpha)$, $(T,\\beta)$, \\\\\ngiven primary key $PK = \\lbrace b_{j_1}, \\dots, b_{j_k} \\rbrace \\subseteq \\beta$, primary key of of $T$, and \\\\\ngiven foreign key $FK = \\lbrace a_{i_1} , \\dots , a_{i_k} \\rbrace \\subseteq \\alpha$ s.t.\n\\[\n\\begin{gathered}\n\\text{type}(a_{i_h}) = \\text{type}(b_{j_h}), \\quad \\, h \\in 1, 2 , \\dots k \\\\\n\\text{(alternate notation)} \\sigma(a_{i_h}) = \\sigma(b_{j_h})\n\\end{gathered}\n\\]\nthen \\\\\n$\\forall \\, s \\in \\text{inst}(S), \\, \\exists \\, t \\in \\text{inst}(T)$ ((alternate notation) $s\\in \\Gamma(S), \\, t\\in \\Gamma(T)$), s.t.\n\\[\ns(FK) = t(PK)\n\\]\n\nDescribe this categorically as\n\\[\n\\begin{tikzpicture}\n%\\matrix(m)[matrix of math nodes, row sep=3em, column sep=3em, text height=1.5ex, text depth=0.25ex]\n\\matrix(m)[matrix of math nodes, row sep=4em, column sep=4em]\n{\n\tS & T \\\\\n};\n%\\path[->,font=\\scriptsize]\n\\path[->]\n(m-1-1) edge node[auto]{$FK$} (m-1-2)\n;\n\\end{tikzpicture} \n\\]\nwhich is from the introductory talk by Spivak (2012)\\cite{Spiv2012}, \"What does equivalence of paths mean?\", where it states, \"arrows represent foreign keys\", \"from table $a$ to table $b$,\" and where \"we can take any record in table $a$ and return a record in table $b$.\n\n\\subsection{Functional Dependency}\n\n\\begin{definition}[Functional Dependency (FD)]\n\tcf. Slides Number 10, \"Functional Dependencies\" of Grust and Duta (2017) \\cite{GrDu2017}.\n\t\n\tLet $(R, \\alpha) \\equiv $ relational schema. Given $\\beta \\subseteq \\alpha$, $c\\in \\alpha$, \\\\\n\t\\textbf{functional dependency} $\\beta \\to c$ holds in $R$ if \n\t\\[\n\t\\forall \\, t, u \\in \\text{inst}(R), \\, t.\\beta = u.\\beta \\Longrightarrow t.c = u.c\n\t\\]\n\tNotation: the functional dependency $\\beta \\to \\lbrace c_1, \\dots , c_n \\rbrace $ abbreviates set of FDs $\\beta \\to c_1, \\dots , \\beta \\to c_n$.\n\t\n\tcf. \\href{https://en.wikipedia.org/wiki/Functional_dependency}{\"Functional dependency\", wikipedia}\n\t\n\tA set of attributes $X \\subseteq R$ ($\\equiv X \\subseteq \\alpha$ for $R = (R,\\alpha)$) is said to functionally determine another set of attributes $Y \\subseteq R$ ($\\equiv Y \\subseteq \\alpha$), written $X\\to Y$. ($\\equiv \\beta \\to c$) \\\\\n\tiff $\\forall \\, X$ value in $R$ is associated with precisely 1 $Y$ value in $R$; $R$ is then said to satisfy the functional dependency $X\\to Y$\n\\end{definition}\n\ne.g. Cars: $\\beta = $ vehicle identification number (VIN), $c=$ Engine capacity (because assume a car cannot have 2 engines).\n\ne.g Employee department: \\\\\n$\\beta = $ employee ID, \\qquad \\, $c = $ employee name. \\\\\n$\\beta = $ employee ID, \\qquad \\, $c = $ department ID. \\\\\n$\\beta = $ department ID, \\qquad \\, $c = $ department name.\n\nRecall definition of injective function, $f:X \\to Y$,\n\\[\n\\forall \\, a,b \\in X, \\, f(a) = f(b) \\Longrightarrow a =b\n\\]\n\nInstead of writing the functional dependency (FD) with this notation: given $\\beta, c \\subseteq \\alpha$, \n\\[\n\\begin{gathered} \n\\forall \\, r_1, r_2 \\in \\text{inst}(R) \\equiv \\Gamma(\\alpha), \\, r_1(\\beta) = r_2(\\beta), \\Longrightarrow r_1(c) = r_2(c) \\\\\n\\end{gathered} \n\\]\n\\emph{rewrite} this as follows:\n\n\\begin{equation}\n\\begin{gathered} \n\t\\text{ Given } \\\\\n\t\\begin{aligned} \n\t& \\beta : \\Gamma(\\alpha) \\to \\text{val}(\\beta) \\equiv \\text{dom}(\\text{type}(\\beta)) \\equiv \\pi^{-1} \\circ \\sigma(\\beta), \\, \\\\\n\t& c : \\Gamma(\\alpha) \\to \\text{val}(c) \\equiv \\text{dom}(\\text{type}(c)) \\equiv \\pi^{-1} \\circ \\sigma(c), \\end{aligned} \\\\\n\\forall \\, r_1, r_2 \\in \\text{inst}(R) \\equiv \\Gamma(\\alpha), \\, \\beta(r_1), \\beta(r_2) \\in \\text{val}(\\beta) \\\\\n\\text{ Then } \\beta \\in \\text{Hom}(\\text{inst}(R), \\text{val}(\\beta)) \\equiv \\text{Hom}(\\Gamma(\\alpha), \\pi^{-1}\\circ \\sigma(\\alpha))\n\\end{gathered} \n\\end{equation}\n\nSo define a \\textbf{functional dependency} $FD$ as \n\\begin{equation}\n\\begin{gathered}\n\t\\begin{aligned} \n&\t\\text{FD} : 2^{\\alpha} \\to 2^{\\alpha} \\\\\n& \\text{FD} : \\beta \\mapsto c \\text{ i.e. } \\boxed{ FD(\\beta) = c }\n\\end{aligned} \n\\end{gathered}\n\\end{equation}\nwhere $\\beta, c \\in 2^{\\alpha} \\equiv $ power set of $\\alpha$, i.e. set of all subsets of $\\alpha$, so that $\\beta, c \\subseteq \\alpha$. \n\nLet $FD^{-1}:2^{\\alpha} \\to 2^{\\alpha}$, s.t. $FD^{-1}(c) = \\beta$.\n\nSo if $\\forall \\, r_1, r_2 \\in \\text{inst}(R) \\equiv \\Gamma(\\alpha)$, for $\\beta \\subseteq \\alpha$, $\\beta(r_1), \\beta(r_2) \\in \\text{val}(\\beta)$. Then $\\beta \\in \\text{Hom}(\\text{inst}(R), \\text{val}(\\beta)) \\equiv \\text{Hom}(\\Gamma(\\alpha), \\pi^{-1}\\circ \\sigma(\\alpha))$.\n\nSuppose $\\beta(r_1) = \\beta(r_2)$. The \\emph{key insight} is the following:\n\n\\begin{equation}\n\\beta(r_1) = \\beta(r_2) = \\text{FD}^{-1}(c)(r_1) = \\text{FD}^{-1}(c)(r_2) = (\\text{FD}^{-1}\\circ c)(r_1) = (\\text{FD}^{-1}\\circ c)(r_2)\n\\end{equation}\n\nThen $c(r_1) = c(r_2)$ implies that $\\text{FD}^{-1}$ is \\emph{injective}.\n\nThen $\\text{FD}^{-1}$ is a \\emph{monomorphism}, and $\\text{FD}^{-1}$ is injective, since $\\forall \\, r_1, r_2 \\in \\text{inst}(R) \\equiv \\Gamma(\\alpha)$,\n\\begin{equation}\n\\beta(r_1) = \\beta(r_2) = (\\text{FD}^{-1}\\circ c)(r_1) = (\\text{FD}^{-1}\\circ c)(r_2) \\Longrightarrow c(r_1) = c(r_2)\n\\end{equation} \n\n\\[\n\\begin{tikzpicture}\n\\matrix (m) [matrix of math nodes, row sep=1.8em, column sep=1.8em, minimum width=1.2em]\n{\n\t\\text{inst}(R) & \\text{val}(C) & \\text{val}(\\beta) \\\\\n};\n\\path[->]\n(m-1-1) edge node [above] {$c$} (m-1-2)\n(m-1-2) edge node [above] {$\\text{FD}^{-1}$} (m-1-3)\n;\n\\end{tikzpicture} \n\\]\n\nThen conclude that \n\\begin{theorem}\n\tGiven a relational schema $(R, \\alpha)$, a set of attributes $\\alpha$, instance of the relation (i.e. a table), $\\text{inst}(R) \\equiv \\Gamma(\\alpha)$, and $\\beta, c \\subseteq \\alpha$, \\\\ for morphisms $\\beta, c$, \n\\[\t\\begin{aligned}\n\t\t& \\beta \\in \\text{Hom}(\\Gamma(\\alpha), \\text{val}(\\beta)) \\\\\n\t\t& c \\in \\text{Hom}(\\Gamma(\\alpha), \\text{val}(c))\n\t\\end{aligned}\n\t\\]\nThen for $\\text{FD}:2^{\\alpha} \\to 2^{\\alpha}$, $\\text{FD}(\\beta) =c$, $\\text{FD}^{-1}$ is a \\textbf{monomorphism}, i.e. $\\forall \\, r_1, r_2 \\in \\Gamma(\\alpha)$,\n\\[\n\\beta(r_1) = \\beta(r_2) = (\\text{FD}^{-1}\\circ c)(r_1) = (\\text{FD}^{-1}\\circ c)(r_2) \\text{ i.e. } (\\text{FD}^{-1}\\circ c) = (\\text{FD}^{-1} \\circ c)\n\\]\nthen $c(r_1) = c'(r_2) $ i.e. $c=c'$.\n\\end{theorem}\n\nDatabase Queries and Constraints via Lifting Problems. David I. Spivak.\n\\url{https://arxiv.org/pdf/1202.2591.pdf}\n\n\\section{Databases and Categories}\n\ncf. Spivak (2012) \\cite{Spiv2012}.\n\n$A \\xrightarrow{\\text{FK}} B$, \\, $A, B \\in \\text{Obj}(\\mathbf{DB})$\n\n\n\\part{Reading notes on Cox, Little, O'Shea's \\emph{Ideals, Varieties, and Algorithms: An Introduction to Computational Algebraic Geometry and Commutative Algebra}}\n\n\\section{Geometry, Algebra, and Algorithms}\n\n\\subsection{Polynomials and Affine Space}\n\nfields are important is that linear algebra works over \\emph{any} field\n\n\\begin{definition}[2] set of all polynomials in $x_1 , \\dots , x_n$ with coefficients in $k$, denoted $k[x_1, \\dots , x_n]$\n\n\\end{definition}\n\npolynomial $f$ \\emph{divides} polynomial $g$ provided $g= fh$ for some $h \\in k[x_1, \\dots , x_n ]$\n\n$k[x_1, \\dots, x_n]$ satisfies all field axioms except for existence of multiplicative inverses; commutative ring, $k[x_1, \\dots , x_n]$ \\emph{polynomial ring}\n\n\n\\subsubsection*{Exercises for 1}\n\n\\exercisehead{1}\n$\\mathbb{F}_2$ commutative ring since it's an abelian group under addition, commutative in multiplication, and multiplicative identity exists, namely $1$. It is a field since for $1\\neq 0$, the multiplicative identity is $1$. \n\n\\exercisehead{2}\n\\begin{enumerate}\n\\item[(a)]\n\\item[(b)]\n\\item[(c)]\n\\end{enumerate}\n\n\n\n\n\\subsection{Affine Varieties }\n\n\n\\subsection{Parametrizations of Affine Varieties}\n\n\n\\subsection{Ideals}\n\n\n\n\\subsection{Polynomials of One Variable}\n\n\n\n\n\\section{Groebner Bases}\n\n\\subsection{Introduction}\n\n\n\n\n\\subsection{Orderings on the Monomials in $k[x_1, \\dots , x_n]$ }\n\n\n\n\n\\subsection{A Division Algorithm in $k[x_1, \\dots , x_n ]$ }\n\n\n\n\\subsection{Monomial Ideals and Dickson's Lemma }\n\n\n\\subsection{The Hilbert Basis Theorem and Groebner Bases}\n\n\n\\subsection{Properties of Groebner Bases}\n\n\n\n\\subsection{Buchberger's Algorithm}\n\n\n\n\n\n\n\\section{Elimination Theory}\n\n\n\n\\subsection{The Elimination and Extension Theorems}\n\n\n\\subsection{The Geometry of Elimination}\n\n\n\n\\section{The Algebra-Geometry Dictionary}\n\n\n\\subsection{Hilbert's Nullstellensatz}\n\n\n\\subsection{Radical Ideals and the Ideal-Variety Correspondence}\n\n\n\n\\section{Polynomial and Rational Functions on a Variety}\n\n\n\\subsection{Polynomial Mappings }\n\n\n\\section{Robotics and Automatic Geometric Theorem Proving}\n\n\n\n\\subsection{Geometric Description of Robots}\n\n\n\n\n\n\n\\part{Reading notes on Cox, Little, O'Shea's \\emph{Using Algebraic Geometry}}\n\n\\textbf{Using Algebraic Geometry}. David A. Cox. John Little. Donal O'Shea. Second Edition. Springer. 2005. ISBN 0-387-20706-6 QA564.C6883 2004\n\n\\section{ Introduction }\n\n\\subsection{ Polynomials and Ideals }\n\n\\emph{monomial } \n\n\\begin{equation}\n (1.1) \\quad \\quad \\, x_1^{\\alpha_1} \\dots x_n^{\\alpha_n}\n\\end{equation}\n\ntotal degree of $x^{\\alpha}$ is $\\alpha_1 + \\dots + \\alpha_n \\equiv |\\alpha|$ \\\\\n\n\n\nfield $k$, $k[x_1 \\dots x_n]$ collection of all polynomials in $x_1 \\dots x_n$ with coefficients $k$. \\\\\n\npolynomials in $k[x_1 \\dots x_n]$ can be added and multiplied as usual, so $k[x_1 \\dots x_n]$ has structure of commutative ring (with identity) \\\\\nhowever, only nonzero constant polynomials have multiplicative inverses in $k[x_1 \\dots x_n]$, so $k[x_1 \\dots x_n]$ not a field \\\\\n\\quad however set of rational functions $\\lbrace f/g | f,g \\in k[x_1 \\dots x_n], \\, g\\neq 0\\rbrace$ is a field, denoted $k(x_1 \\dots x_n)$ \\\\\n\nso\n\\[\nf = \\sum_{\\alpha} c_{\\alpha}x^{\\alpha}\n\\]\nwhere $c_{\\alpha} \\in k$\n\nso\n\n\\[\nf \\in k [x_1 \\dots x_n ] = \\lbrace f | f = \\sum_{\\alpha} c_{\\alpha} x^{\\alpha} , x^{\\alpha} = x_1^{\\alpha_1} \\dots x_n^{\\alpha_n}, c_{\\alpha} \\in k \\rbrace\n\\]\n\n$f$ homogeneous if all monomials have same total degrees\n\npolynomial $f$ is homogeneous if all monomials have the \\emph{same total degree} \\\\\n\nGiven a collection of polynomials $f_1 \\dots f_s \\in k[x_1 \\dots x_n]$, we can consider all polynomials which can be built up from these by multiplication by arbitrary polynomials and by taking sums\n\n\\begin{definition}[1.3] Let $f_1 \\dots f_s \\in k[x_1 \\dots x_n]$ \\\\\nLet $\\langle f_1 \\dots f_s \\rangle = \\lbrace p_1 f_1 + \\dots + p_s f_s | p_i \\in k[x_1 \\dots x_n] \\text{ for } i = 1 \\dots s \\rbrace$\n\\end{definition}\n\n\n\\exercisehead{1} \n\\begin{enumerate}\n\\item[(a)] $x^2 = x \\cdot ( x -y^2 ) + y \\cdot ( xy )$ \n\\item[(b)] \n\\[\n p \\cdot ( x - y^2 ) = p x - p y^2\n\\]\nand for $p xy = (py)x$\n\\item[(c)] \n\\[\np(y) ( x - y^2) = p(y)x - p(y) y^2 \\notin \\langle x^2, xy \\rangle\n\\]\n\\end{enumerate}\n\n\\exercisehead{2} \n\\[\n\\begin{gathered}\n \\sum_{i=1}^s p_i f_i + \\sum_{j=1}^s q_j f_j = \\sum_{i=1}^s (p_i + q_i )f_i, \\quad \\, p_i + q_i \\in k[x_1 \\dots x_n] \\end{gathered}\n\\]\n$\\langle f_1 \\dots f_s \\rangle$ closed under sums in $k[x_1 \\dots x_n]$ \\\\\n\nIf $f\\in \\langle f_1 \\dots f_s \\rangle$, \\\\\n\\phantom{If }$ p \\in k [x_1 \\dots x_n]$\n\n\\[\n\\begin{gathered}\np\\cdot f = p \\sum_{i=1}^s q_j f_j = \\sum_{i=1}^s pq_j f_j, \\quad \\, pq_j \\in k[x_1 \\dots x_n] \\text{ so } \\\\\np\\cdot f \\in \\langle f_1 \\dots f_s \\rangle\n\\end{gathered}\n\\]\n\nDone. \\\\\n\nThe 2 properties in Ex. 2 are defining properties of ideals in the ring $k[x_1 \\dots x_n]$\n\n\\begin{definition}[1.5]\nLet $I \\subset k[x_1 \\dots x_n]$, \\, $I \\neq \\emptyset$ \\\\\n$I$ ideal if \n\\begin{enumerate}\n\\item[(a)] $f+ g \\in I$, \\, $\\forall \\, f,g \\in I$ \n\\item[(b)] $pf \\in I$, \\, $\\forall \\, f \\in I$, arbitrary $p \\in k[x_1 \\dots x_n]$\n\\end{enumerate}\n\\end{definition}\n\nThus $\\langle f_1 \\dots f_s\\rangle$ is an ideal by Ex. 2. \\\\\n\nwe call it the ideal generated by $f_1 \\dots f_s$. \n\n\\exercisehead{3} Suppose $\\exists \\, $ ideal $J$, $f_1 \\dots f_s \\in J$ s.t. $J \\subset \\langle f_1 \\dots f_s \\rangle$ \\\\\nif $f\\in \\langle f_1 \\dots f_s \\rangle$, $f = \\sum_{i=1}^s p_i f_i$, \\, $p_i \\in k[x_1 \\dots x_n]$ \\\\\n\n$\\forall \\, i = 1 \\dots s$, $p_i f_i \\in J$ and so $\\sum_{i=1}^s p_i f_i \\in J$, by def. of $J$ as an ideal.\n\n\\[\n\\langle f_1 \\dots f_s \\rangle \\subseteq J \\quad \\quad \\, \\Longrightarrow J = \\langle f_1 \\dots f_s \\rangle\n\\]\n\n$\\Longrightarrow \\langle f_1 \\dots f_s \\rangle$ is smallest ideal in $k[x_1 \\dots x_n]$ containing $f_1 \\dots f_s$\n\n\n\\exercisehead{4} For $\\begin{aligned} & \\quad \\\\\n & I = \\langle f_1 \\dots f_s \\rangle \\\\\n & J = \\langle g_1 \\dots g_t \\rangle \\end{aligned}$ \\\\\n\n $I = J$ iff $s=t$ and $\\forall \\, f \\in I$, $f = \\sum_{i=1}^t q_i g_i$ and if $ 0 = \\sum_{i=1}^t q_i g_i$, $q_i =0$, \\, $\\forall \\, i = 1 \\dots t$, and if $0 = \\sum_{i=1}^s p_i f_i$, \\, $p_i = 0$, \\, $\\forall \\, i = 1 \\dots s$\n\n\n\\begin{definition}[1.6]\n\\[\n\\sqrt{I} = \\lbrace g \\in k[x_1\\dots x_n] | g^m \\in I \\text{ for some } m \\geq 1 \\rbrace\n\\]\n\\end{definition}\n\ne.g. $x+y \\in \\sqrt{ \\langle x^2 + 3 xy , 3xy + y^2 \\rangle }$\n\nin $\\mathbb{Q}[x,y]$ since \n\n\\[\n(x+y)^3 =x(x^2 + 3xy) + y(3xy + y^2) \\in \\langle x^2 + 3xy, 3xy + y^2\\rangle\n\\]\n\n\n%\\begin{definition}[1.6]\n%\\[\n%\\sqrt{I } = \\lbrace g \\in k[x_1 \\dots x_n ] | g^m \\in I \\text{ for some m } \\geq 1 \\rbrace\n%\\]\n%\\end{definition}\n\n%e.g. $x+y \\in \\sqrt{ \\langle x^2 + 3xy, 3xy + y^2 \\rangle }$\n\n%in $\\mathbb{Q}[x,y]$ since\n\n%\\[\n%(x+y)^3 = x(x^2 + 3xy) + y(3xy + y^2) \\in \\langle x^2 + 3xy, 3xy + y^2 \\rangle\n%\\]\n\n\\begin{itemize}\n\\item (Radical Ideal Property) $\\forall \\, $ ideal $I\\subset k[x_1 \\dots x_n]$, $\\sqrt{I}$ ideal, $\\sqrt{I} \\supset I$\n\\item \\textbf{(Hilbert basis Thm.)} $\\forall \\, $ ideal $I\\subset k[x_1\\dots x_n]$ \\\\\n$\\exists \\, $ finite generating set, \\\\\ni.e. $\\exists \\, \\lbrace f_1 \\dots f_2 \\rbrace \\subset k [x_1 \\dots x_n]$ s.t. $I=\\langle f_1 \\dots f_s \\rangle$\n\\item (Division Algorithm in $k[x]$) $\\forall \\, f,g \\in k[x]$ (EY : in 1 variable) \\\\\n$\\forall \\, f, g \\in k[x]$ (in 1 variable )\\\\\n$f= qg + r$, $\\exists \\, !$ quotient $q$, $\\exists \\, $ remainder $r$\n\\end{itemize}\n\n\\subsection{}\n\n\\subsection{Gr\\\"obner Bases}\n\n\\begin{definition}[3.1]\n Gr\\\"obner basis for $I$ $\\equiv G = \\lbrace g_1 \\dots g_k \\rbrace \\subset I$ s.t. $\\forall \\, f \\in I$, $\\text{LT}(f)$ divisible by $\\text{LT}(g_i)$ for some $i$\n\\end{definition}\n\n\\begin{itemize}\n\\item (Uniqueness of Remainders) let ideal $I\\subset k[x_1 \\dots x_n]$ \\\\\ndivision of $f\\in k[x_1 \\dots x_n]$ by Gr\\\"o bner basis for $I$, produces $f=g+r$, $g\\in I$, and no term in $r$ divisible by any element of $\\text{LT}(I)$\n\\end{itemize}\n\n\n\n\n\n\\subsection{Affine Varieties}\n\naffine $n$-dim. space over $k$ \\quad \\, $k^n = \\lbrace (a_1 \\dots a_n ) | a_1 \\dots a_n \\in k \\rbrace$\n\n$\\forall \\, $ polynomial $f\\in k[x_1 \\dots x_n ]$, $(a_1 \\dots a_n) \\in k^n$ \\\\\n\\phantom{ \\quad } $f: k^n \\to k$ \\\\\n\\phantom{ \\quad } $f(a_1 \\dots a_n)$ s.t. $x_i = a_i$ i.e. \\\\\n\nif $f= \\sum_{\\alpha} c_{\\alpha} x^{\\alpha}$ for $c_{\\alpha} \\in k$, then \\\\\n\\phantom{ \\quad } $f(a_1 \\dots a_n) =\\sum_{\\alpha} c_{\\alpha}a^{\\alpha} \\in k$, where $a^{\\alpha} = a_1^{\\alpha_1} \\dots a_n^{\\alpha_n}$\n\n\\begin{definition}[4.1]\naffine variety $\\mathbf{V}(f_1 \\dots f_s) = \\lbrace ( a_1 \\dots a_n) | (a_1 \\dots a_n) \\in k^n, \\, f_1(x_1 \\dots x_n) = \\dots = f_s(x_1 \\dots x_n) = 0 \\rbrace$ \\\\\nsubset $V\\subset k^n$ is affine variety if $V = V(f_1 \\dots f_s)$ for some $\\lbrace f_i \\rbrace$, polynomial $f_i \\in k[x_1 \\dots x_n]$\n\\end{definition}\n\n\\begin{itemize}\n \\item (Equal Ideals Have Equal Varieties) If $\\langle f_1 \\dots f_s \\rangle = \\langle g_1 \\dots g_t \\rangle$ in $k[x_1 \\dots x_n]$, then $\\mathbf{V}(f_1 \\dots f_s) = \\mathbf{V}(g_1 \\dots g_t)$\n\\end{itemize}\n\nso, recap \\\\\nif $\\langle f_1 \\dots f_s \\rangle = \\langle g_1 \\dots g_t \\rangle $ in $k[x_1 \\dots x_n]$, \\\\\nthen $V(f_1 \\dots f_s) = V(g_1 \\dots g_t)$ \\\\\n\nRecall Hilbert basis Thm. $\\forall \\, $ ideal $I \\subset k[x_1 \\dots x_n]$ \n\\[\nI= \\langle f_1 \\dots f_s \\rangle\n\\]\n$\\Longrightarrow $ if $I=J$, then $V(I) = V(J)$\n\nthink of $V$ defined by $I$, rather than $f_1 = \\dots = f_s =0$\n\n\\exercisehead{3}\n\nRecall Def. 1.5 Let $I\\subset k[x_1 \\dots x_n]$ \\\\\n$I$ ideal if $\\begin{aligned} & \\quad \\\\\n & f + g \\in I \\quad \\, \\forall \\, f,g \\in I \\\\\n & pf \\in I, \\quad \\, \\forall \\, f \\in I \\text{ arbitrary } p \\in k[x_1 \\dots x_n]\n\\end{aligned}$\n\nLet $f,g \\in I(V)$ \n\\[\n\\begin{gathered}\n (f+g)(a_1 \\dots a_n) = f(a_1 \\dots a_n) + g(a_1 \\dots a_n) = 0 + 0 = 0 \\quad \\quad \\, f+g \\in I(V) \\\\ \n pf(a_1 \\dots a_n) = p(a_1 \\dots a_n) f(a_1 \\dots a_n) = 0 \\quad \\quad \\, pf \\in I(V)\n\\end{gathered}\n\\]\nThen $I(V)$ an ideal.\n\n%\\exercisehead{3} Recall Def. 1.5. Let $I \\subset k[x_1 \\dots x_n]$, $I$ ideal if $\\begin{aligned} & \\quad \\\\\n% & f+g \\in I \\quad \\, \\forall \\, f,g\\in I \\\\\n% & pf \\in I , \\quad \\, \\forall \\, f \\in I, \\text{ arbitrary } p \\in k[x_1 \\dots x_n ] \\end{aligned}$\n\n%Let $f,g \\in I(V)$ \n%\\[\n\n$V = V(x^2)$ in $\\mathbb{R}^2$ \\\\\n$I=\\langle x^2 \\rangle$ in $\\mathbb{R}[x,y]$, \\, $I= \\lbrace px^2 | p \\in k[x,y]\\rbrace$ \\\\\n\\phantom{ \\quad } $I \\subset I(V)$, since $px^2 = 0$ for $x^2=0$, $(0,b)$, \\, $b\\in \\mathbb{R}$ \\\\\nBut $p(x,y) = x\\in I(V)$, as \n\\[\nI(V) = \\lbrace f \\in k[x_1 \\dots x_n] | f(a_1 \\dots a_n)=0, \\, \\forall \\, (a_1\\dots a_n) \\in V\\rbrace\n\\]\n\\phantom{ \\quad \\quad } $p(0,b) = x = 0$\n\nBut $x\\notin I$\n\n\\exercisehead{4} $I\\subset \\sqrt{I}$\n\nRecall Def. 1.6 $\\sqrt{I} = \\lbrace g \\in k[x_1 \\dots x_n] |g^m \\in I \\text{ for some } m\\geq 1\\rbrace$ \\\\\n$\\forall \\, f \\in I$, $f=f^1$, $m=1$, so $f\\in \\sqrt{I}$, \\quad \\, $I\\subset \\sqrt{I}$ \\\\\n\\phantom{\\quad \\quad } Hilbert basis thm., $\\forall \\, $ ideal $I\\subset k[x_1 \\dots x_n]$ s.t. $I=\\langle f_1 \\dots f_s \\rangle$ \\\\\n\\phantom{\\quad } $V(I) = \\lbrace (a_1 \\dots a_n) |(a_1 \\dots a_n) \\in k^n, \\, f_1(a_1\\dots a_n) = \\dots = f_s(a_1\\dots a_n)=0\\brace$ \\\\\n$\\mathbf{I}(\\mathbf{V}(I)) = \\lbrace f \\in k[x_1 \\dots x_n] | f(a_1 \\dots a_n) =0 \\quad \\, \\forall \\, (a_1 \\dots a_n) \\in V(I) \\rbrace$ \\\\\nLet $g\\in \\sqrt{I}$, \\, $g^m \\in I$, \\, $g^m=g^{m-1}g$ \\\\\n\\phantom{\\quad \\quad \\,} $g^m(a_1 \\dots a_n) =0 = g^{m-1}(a_1 \\dots a_n)g(a_1 \\dots a_n) =0$. Then $g(a_1 \\dots a_n)=0$ or $g^{m-1}(a_1\\dots a_m)=0$ \\\\\n\\phantom{\\quad }as $g^m\\in I$, and $V(I)$ is s.t. $f_1(a_1 \\dots a_n) = \\dots = f_s(a_1 \\dots a_n)=0$ for $I=\\langle f_1 \\dots f_s \\rangle$\n\n\\begin{itemize}\n \\item (Strong Nullstellensatz) if $k$ algebraically closed (e.g. $\\mathbb{C}$), $I$ ideal in $k[x_1 \\dots x_n]$, then \n\\[\n\\mathbf{I}(\\mathbf{V}(I) = \\sqrt{I}\n\\]\n\\item (Ideal-variety correspondence) Let $k$ arbitrary field\n\\[\n\\begin{aligned}\n & I \\subset I(V(I)) \\\\ \n & V(I(V)) = V \\quad \\, \\forall \\, V\n\\end{aligned}\n\\]\n\\end{itemize}\n\n\\subsection*{Additional Exercises for Sec.4}\n\n\\exercisehead{6}\n\n\n\n\\section{ Solving Polynomial Equations}\n\n\\subsection{}\n\n\\subsection{Finite-Dimensional Algebras}\n\nGr\\\"obner basis $G = \\lbrace g_1 \\dots g_t \\rbrace$ of ideal $I\\subset k[x_1\\dots x_n]$, \\\\\nrecall def.: Gr\\\"obner basis $G = \\lbrace g_1 \\dots g_t\\rbrace \\subset I$ of ideal $I$, \\, $\\forall \\, f \\in I$, $\\text{LT}(f)$ divisible by $\\text{LT}(g_i)$ for some $i$ \\\\\n\\phantom{\\quad \\, } $f \\in k[x_1\\dots x_n]$ divide by $G$ produces $f=g+r$, $g\\in I$, $r$ not divisible by any $\\text{LT}(I)$ uniqueness of $r$ \\\\\n$f\\in k[x_1 \\dots x_n]$ divide by $G$, \n\nRecall from Ch. 1, divide $f\\in k[x_1 \\dots x_n]$ by $G$, the division algorithm yields\n\n\\begin{equation}\n (2.1) \\quad \\quad \\quad \\, f = h_1 g_1 + \\dots + h_t g_t + \\overline{f}^G\n\\end{equation}\nwhere remainder $\\overline{f}^G$ is a linear combination of monomials $x^{\\alpha} \\notin \\langle \\text{LT}(I) \\rangle $ \\\\\n\\phantom{\\quad } since Gr\\\"obner basis, $f\\in I$ iff $\\overline{f}^G=0$\n\n$\\forall \\, f \\in k[x_1\\dots x_n]$, we have coset $[f] = f+I = \\lbrace f +h|h\\in I\\rbrace$ s.t. $[f]=[g]$ iff $f- g \\in I$\n\nWe have a 1-to-1 correspondence \n\\[\n\\begin{gathered}\n\\text{remainders } \\leftrightarrow \\text{ cosets } \\\\\n\\overline{f}^G \\leftrightarrow [f]\n\\end{gathered}\n\\]\nalgebraic\n\\[\n\\begin{aligned}\n & \\overline{f}^G + \\overline{g}^G \\leftrightarrow [f] + [g] \\\\ \n & \\overline{ \\overline{f}^G \\cdot \\overline{g}^G } \\leftrightarrow [f]\\cdot [g]\n\\end{aligned}\n\\]\n$B = \\lbrace x^{\\alpha} | x^{\\alpha} \\notin \\langle \\text{LT}(I) \\rangle \\rbrace$ is a basis of $A$, basis monomials, standard monomials\n\n20141023 EY's take\n\n$\\forall \\, [f] \\in A = k[x_1 \\dots x_n]/I$, \\, $[f] = p_ib_i$; \\, $b_i \\in B = \\lbrace x^{\\alpha} | x^{\\alpha} \\notin \\langle \\text{LT}(I) \\rangle \\rbrace$ \\\\\nFor $I = \\langle G \\rangle$ \\\\\n\\phantom{\\quad } e.g. $G=\\lbrace x^2 + \\frac{3}{2} xy + \\frac{1}{2} y^2 - \\frac{3}{2} x - \\frac{3}{2} y, xy^2-x, y^3-y \\rbrace$ \\\\\n$\\langle \\text{LT}(I) \\rangle = \\langle x^2, xy^2,y^3 \\rangle$ \\\\\ne.g. $B=\\lbrace 1,x,y,xy,y^2\\rbrace$ \\\\\n\\phantom{\\quad } $[f]\\cdot[g] = [fg]$ \\\\\ne.g. $f=x, \\, g=xy, \\, [fg] = [x^2y]$ \\\\\nnow $f=h_1g_1 + \\dots +h_tg_t+ \\overline{f}^G$\n\n\\subsection{}\n\n\\subsection{Solving Equations via Eigenvalues and Eigenvectors}\n\n\n\\section{ Resultants }\n\n\\section{Computation in Local Rings}\n\n\\subsection{Local Rings}\n\n\n\\begin{definition}[1.1]\n \\[\nk[x_1 \\dots x_n]_{\\langle x_1 \\dots x_n \\rangle} \\equiv \\lbrace \\frac{f}{g} | \\text{ rational functions } \\frac{f}{g} \\text{ of } x_1 \\dots x_n \\text{ with } g(p) \\neq 0 \\text{ at } p \\rbrace\n\\]\n\\end{definition}\n\nmain properties of $k[x_1 \\dots x_n]_{\\langle x_1 \\dots x_n \\rangle }$\n\n\\begin{proposition}[1.2]\n Let $R= k[x_1 \\dots x_n]_{\\langle x_1 \\dots x_n \\rangle }$. Then\n\\begin{enumerate}\n\\item[(a)] $R$ subring of field of rational functions $k(x_1 \\dots x_n) \\supset k[x_1 \\dots x_n]$\n\\item[(b)] Let $M=\\langle x_1 \\dots x_n \\rangle \\subset R$ (ideal generated by $x_1 \\dots X_n$ in $R$) \\\\\nThen $\\forall \\, \\frac{f}{g} \\in R \\backslash M$, $\\frac{f}{g}$ unit in $R$ (i.e. multiplicative inverse in $R$)\n\\item[(c)] $M$ maximal ideal in $R$\n\\end{enumerate}\n\\end{proposition}\n\n\n\\exercisehead{1} if $p=(a_1 \\dots a_n) \\in k^n$, $R = \\lbrace \\frac{f}{g} | f,g\\in k[x_1 \\dots x_n] , \\, g(p) \\neq 0 \\rbrace$ \n\\begin{enumerate}\n\\item[(a)] $R$ subring of field of rational functions $k(x_1 \\dots x_n)$ \n\\item[(b)] Let $M$ ideal generated by $x_1 - a_1 \\dots x_n -a_n$ in $R$ \\\\\nThen $\\forall \\, \\frac{f}{g} \\in R\\backslash M$, $\\frac{f}{g}$ unit in $R$ (i.e. multiplicative inverse in $R$)\n\\item[(c)] $M$ maximal ideal in $R$\n\\end{enumerate}\n\n\n\\begin{proof}\nlet $p = (a_1 \\dots a_n) \\in k^n$ \\\\\nlet $g_1(p) \\neq 0$, $g_2(p) \\neq 0$ \n\\[\n\\begin{gathered}\n \\frac{f_1}{g_1 } + \\frac{f_2}{g_2} = \\frac{f_1 g_2 + f_2 g_1}{ g_1 g_2 } \\quad \\quad \\, g_1(p)g_2(p) \\neq 0 \\text{ so } \\frac{f_1}{g_1} + \\frac{f_2}{g_2} \\in R \\\\\n \\frac{f_1}{g_1} \\cdot \\frac{f_2}{g_2} = \\frac{f_1 f_2}{g_1 g_2} \\quad \\quad \\, g_1(p) g_2(p) \\neq 0 \\text{ so } \\frac{f_1}{g_1}\\frac{f_2}{g_2} \\in R\n\\end{gathered}\n\\]\n$f= \\frac{f}{I} \\in R$, \\quad \\, $\\forall \\, f\\in k[x_1 \\dots x_n]$, so $k[x_1 \\dots x_n]\\subset R$\n\n\\end{proof}\n\nEY : 20141027, to recap, \n\nLet $V = k^n$ \\\\\nLet $p = (a_1 \\dots a_n)$ \\\\\nsingle pt. $\\lbrace p \\rbrace$ is (an example of) a variety \\\\\n$I(\\lbrace p \\rbrace) = \\lbrace x_1 -a_1 \\dots x_n -a_n \\rangle \\subset k[x_1 \\dots x_n]$ \\\\\n\n$R \\equiv k[x_1 \\dots x_n]_{\\langle x_1 - a_1 \\dots x_n-a_n \\rangle }$ \n\\[\nR = \\lbrace \\frac{f}{g} | \\text{ rational function $\\frac{f}{g}$ of $x_1 \\dots x_n$, $g(p) \\neq 0$, $p=(a_1 \\dots a_n) $ } \\rbrace\n\\]\n\nProp. 1.2. properties \n\n\\begin{enumerate}\n\\item[(a)] $R$ subring of field of rational functions $k(x_1 \\dots x_n)$ \\quad \\, $k(x_1 \\dots x_n) \\subset R$ \n\\item[(b)] $M = \\langle x_1 \\dots a_1 \\dots x_n -a_n \\rangle \\subset R$. ideal generated by $x_1 - a_1 \\dots x_n-a_n$ \\\\\nThen $\\forall \\, \\frac{f}{g} \\in R\\backslash M$, $\\frac{f}{g}$ unit in $R$ ( $\\exists \\, $ multiplicative inverse in $R$ )\n\\item[(c)] $M$ maximal ideal in $R$. \\\\\nin $R$ we allow denominators that are not elements of this ideal $I(\\lbrace p \\rbrace)$ \n\\end{enumerate}\n\n\\begin{definition}[1.3] local ring is a ring that has exactly 1 maximal ideal \\end{definition}\n\n\\begin{proposition}[1.4] ring $R$ with proper ideal $M\\subset R$ is local ring if $\\forall \\, \\frac{f}{g} \\in R\\backslash M$ is unit in $R$\n\\end{proposition}\n\nlocalization Ex. 8, Ex. 9 \\\\\nparametrization\n\n\\exercisehead{2} \\[\n\\begin{aligned}\n & x = x(t) = \\frac{-2t^2 }{1+t^2} \\\\ \n & y = y(t) = \\frac{2t}{1+t^2}\n\\end{aligned}\n\\]\n$k[t]_{\\langle t \\rangle}$ \\quad \\, $\\frac{-2t^2}{1+t^2}$ rational function of $t$. $1+t^2 \\neq 0$\n\nif $k = \\mathbb{C}$ or $\\mathbb{R}$ \\\\\n\nConsider set of convergent power series in $n$ variables \\\\\n\n\\begin{equation}\n(1.5) \\quad \\quad \\, k\\lbrace x_1 \\dots x_n \\rbrace = \\lbrace \\sum_{\\alpha \\in \\mathbb{Z}^n_{\\geq 0}} c_{\\alpha} x^{\\alpha} | c_{\\alpha} \\in k, \\text{ series converges in some open $U\\ni 0 \\in k^n $ } \\rbrace\n\\end{equation}\n\nConsider set $k[[x_1 \\dots x_n]]$ of formal power series\n\n\\begin{equation}\n (1.6) \\quad \\quad \\, k[[x_1 \\dots x_n]] = \\lbrace \\sum_{\\alpha \\in \\mathbb{Z}^n_{\\geq 0}} c_{\\alpha} x^{\\alpha} | c_{\\alpha} \\in k \\rbrace \\text{ series need not converge }\n\\end{equation} \n\n\nvariety $V$ \\\\\n\n$k[x_1\\dots x_n]/\\mathbf{I}(V)$ \\phantom{ \\quad \\quad \\quad } variety $V$\n\n\n\\subsection{Multiplicities and Milnor Numbers}\n\n\nif $I$ ideal in $k[x_1\\dots x_n]$, then denote $Ik[x_1\\dots x_n]_{\\langle x_1 \\dots x_n \\rangle}$ ideal generated by $I$ in larger ring $k[x_1\\dots x_n]_{\\langle x_1 \\dots x_n \\rangle}$\n\n\\begin{definition}[2.1] Let $I$ $0$-dim. ideal in $k[x_1 \\dots x_n]$, so $V(I)$ consists of finitely many pts. in $k^n$. \\\\\nAssume $(0 \\dots 0) \\in V(I)$ \\\\\nmultiplicity of $(0\\dots 0)\\in V(I)$ is \n\\[\n\\text{dim}_k{ k[x_1\\dots x_n]_{\\langle x_1\\dots x_n \\rangle}} / Ik[x_!\\dots x_n]_{\\langle x_1 \\dots x_n \\rangle}\n\\]\n\\end{definition}\n\n\ngenerally, if $p=(a_1 \\dots a_n) \\in V(I)$ \\\\\nmultiplicity of $p$, $m(p) = \\text{dim}{ k[x_1 \\dots x_n]_M } / Ik[x_1 \\dots x_n]_M$\n\n\\[\n\\text{dim}{ k[x_1 \\dots x_n]_M } / Ik[x_1 \\dots x_n]_M\n\\]\n\nlocalizing $k[x_1 \\dots x_n]$ at maximal ideal $M = I(\\lbrace p \\rbrace) = \\langle x_1 - a_1 \\dots x_n-a_n \\rangle$\n\n\n\\section{}\n\n\\section{}\n\n\\section{ Polytopes, Resultants, and Equations }\n\n\\section{ Polyhedral Regions and Polynomials }\n\n\\subsection{ Integer Programming }\n\nProp. 1.12. \\\\\n\nSuppose 2 customers $A, B$ ship to same location \\\\\n\\quad A: ship 400 kg pallet taking up $2 \\, m^3$ volume \\\\\n\\quad B: ship 500 kg pallet taking up $3 \\, m^3$ volume \\\\\n\nshipping firm trucks carry up to 3700 \\, kg, up to $20 \\, m^3$ \\\\\n\nB's product more perishable, paying \\$ 15 per pallet \\\\\n\nA pays \\$ 11 per pallet\n\nHow many pallets from A, B each in truck to maximize revenues?\n\n\\begin{equation}\n(1.1) \\quad \\quad \\, \\begin{gathered}\n 4A + 5B \\leq 37 \\\\\n 2A + 3B \\leq 20 \\\\\n A, B \\in \\mathbb{Z}^*_{ \\geq 0 } \\end{gathered}\n\\end{equation}\n\nmaximize $11 A + 15 B$ \\\\\n\ninteger programming. \\\\\nmax. or min. value of some linear function \n\n\\[\nl(A_1 \\dots A_n) = \\sum_{i=1}^n c_i A_i \n\\]\n\non set $(A_1 \\dots A_n) \\in \\mathbb{Z}^n_{ \\geq 0}$ s.t. \n\n\n3. Finally, by introducing additional variables; rewrite linear constraint inequalities as equalities. The new variables are called ``slack variables''\n\n\\begin{equation}\n(1.4) \\quad \\quad \\, a_{ij} A_j = b_i, \\quad \\, A_j \\in \\mathbb{Z}_{\\geq 0}\n\\end{equation}\n\nintroduce indeterminate $z_i$, \\, $\\forall \\, $ equation in (1.4)\n\n\\[\nz_i^{a_{ij} A_j} = z_i^{b_i}\n\\]\n\n$m$ constraints\n\n\\[\n\\prod_{i=1}^m z_i^{a_{ij}A_j} = \\prod_{i=1}^m z_i^{b_i} = \\left( \\prod_{i=1}^m z_i^{a_{ij}} \\right)^{ A_j}\n\\]\n\n\\begin{proposition}[1.6]\n Let $k$ field, define $\\varphi: k[w_1 \\dots w_n] \\to k[z_1 \\dots z_m]$ by \n\\[\n\\varphi(w_j) = \\prod_{i=1}^m z_i^{a_{ij}} \\quad \\quad \\quad \\, \\forall \\, j = 1 \\dots n \n\\]\n\nand \n\n\\[\n\\varphi(g(w_1 \\dots w_n) ) = g(\\varphi(w_1) \\dots \\varphi(w_n))\n\\]\n$\\forall \\, $ general polynomial $g\\in k[w_1 \\dots w_n]$\n\nThen $(A_1 \\dots A_n)$ integer pt. in feasible region iff $\\varphi: w_1^{A_1} \\dots w_n^{A_n} \\mapsto z_1^{b_1} \\dots z_m^{b_m}$\n\n\n\n\\end{proposition}\n\n\\exercisehead{3}\n\nNow \n\n\\[\n\\begin{gathered}\n\\varphi(w_j) = \\prod_{i=1}^m z_i^{a_{ij}} \\\\\nz_i^{a_{ij} A_j} = z_i^{b_i}\n\\end{gathered}\n\\]\n\nIf $(A_1 \\dots A_n)$ an integer pt. in feasible region, $a_{ij} A_j = b_i$\n\n\\[\n\\begin{gathered}\nz_i^{a_{ij}A_j } = z_i^{b_i} = \\prod_{j=1}^n z_i^{a_{ij} A_j} \\Longrightarrow \\prod_{j=1}^n \\prod_{i=1}^m (z_i^{a_{ij} })^{A_j} = \\prod_{i=1}^m z_i^{b_i} = \\prod_{j=1}^n \\varphi(w_j)^{ A_j} = \\prod_{j=1}^n \\varphi(w_j)^{A_j} = \\varphi\\left( \\prod_{j=1}^n w_j^{ A_j } \\right) = \\prod_{i=1}^m z_i^{b_i}\n\\end{gathered}\n\\]\nsince $\\varphi(g(w_1 \\dots w_n)) = g(\\varphi(w_1) \\dots \\varphi(w_n))$ \\\\\n\nIf $\\varphi: \\prod_{j=1}^n w_j^{A_j} \\mapsto \\prod_{i=1}^m z_i^{b_i}$\n\n\\[\n\\varphi\\left( \\prod_{j=1}^n w_j^{A_j} \\right) = \\prod_{j=1}^n (\\varphi(w_j))^{A_j} = \\prod_{i=1}^m z_i^{b_i} = \\prod_{j=1}^n \\left( \\prod_{i=1}^m z_i^{a_{ij}} \\right)^{ A_j} \\Longrightarrow \\prod_{j=1}^n z_i^{a_{ij} A_j} = z_i^{b_i}\n\\]\nor $a_{ij}A_j = b_i$. So $(A_1\\dots A_n)$ integer pt. \n\n\n\n\n\\exercisehead{4} \n\\[\n\\prod_{i=1}^m z_i^{b_i} = \\prod_{i=1}^m \\prod_{j=1}^n z_i^{ a_{ij} A_j } = \\prod_{j=1}^n \\left( \\prod_{i=1}^m z_i^{a_{ij}} \\right)^{A_j} = \\prod_{j=1}^n \\varphi(w_j)^{A_j} = \\varphi\\left( \\prod_{j=1}^n w_j^{A_j} \\right)\n\\]\nSo if given $(b_1 \\dots b_m) \\in \\mathbb{Z}^m$, and for a given $a_{ij}$, $a_{ij}A_j = b_i$ \\\\\n\nFor $m\\leq n$, then $a_{ij}$ is surjective, so $\\exists \\, A_j$ s.t. $\\prod_{i=1}^m z_i^{b_i} = \\varphi\\left( \\prod_{j=1}^n w_j^{A_j} \\right)$\n\n\n\n\\begin{proposition}[1.8]\nSuppose $f_1 \\dots f_n \\in k[z_1 \\dots z_m]$ given \\\\\nFix monomial order in $k[z_1 \\dots z_n, w_1 \\dots w_n ]$ with elimination property: \\\\\n$\\forall \\, $ monomial containing 1 of $z_i$ greater than any monomial containing only $w_j$ \\\\\n\nLet $\\mathcal{G}$ Gr\\\"{o}bner basis for ideal\n\\[\nI = \\langle f_1 - w_1 \\dots f_n - w_n \\rangle \\subset k[z_1 \\dots z_m, w_1 \\dots w_n]\n\\]\n$\\forall \\, f \\in k[z_1 \\dots z_m]$, let $\\overline{f}^{ \\mathcal{G}}$ be remainder on division of $f$ by $\\mathcal{G}$ \\\\\nThen\n\\begin{enumerate}\n\\item[(a)] polynomial $f$ s.t. $f\\in k[f_1 \\dots f_n]$ iff $g= \\overline{f}^{ \\mathcal{G}} \\in k[w_1 \\dots w_n]$\n\\item[(b)] if $\\begin{aligned} & \\quad \\\\\n & f \\in k [f_1 \\dots f_n ] \\\\\n & g = \\overline{f}^{\\mathcal{G}}\\in k[ w_1 \\dots w_n] \\end{aligned}$ \\quad as in part (a), \\\\\n\nthen $f = g(f_1 \\dots f_n)$ , giving an expression for $f$ as polynomial in $f_j$\n\\item[(c)] if $\\forall \\, f_i, f$ monomials, $f\\in k[f_1 \\dots f_n]$, \\\\\nthen $g$ also a monomial. \n\\end{enumerate}\n\\end{proposition}\n\n\n\n\\subsection{Integer Programming and Combinatorics}\n\n\n\n\\section{Algebraic Coding Theory}\n\n\n\\section{The Berlekamp-Massey-Sakata Decoding Algorithm}\n\n\n\n\n\n\\href{https://martinralbrecht.files.wordpress.com/2010/07/20131022_buchberger_dtu.pdf}{Gr\\\"{o}bner Bases, Martin R. Albrecht of the DTU Crypto Group}\n\n\\part{Statistical Mechanics: Ising Model} \n\n\\section{Ising Model} \n\n\\subsection{Definition of Ising Model} \n\ncf. \\href{https://en.wikipedia.org/wiki/Ising_model}{Wikipedia, \"Ising model\"}\n\nConsider set of lattice sites $\\Lambda$, each with set of adjacent sites (e.g. \\textbf{graph}) forming $d$-dim. lattice. \\\\\n$\\forall \\, $ lattice site $k\\in \\Lambda$, $\\exists \\, $ discrete variable $\\sigma_k$, s.t. $\\sigma_k \\in \\lbrace -1, 1\\rbrace$. \\\\\nspin configuration $\\equiv \\sigma = (\\sigma_k)_{k\\in \\Lambda}$ is an assignment of spin value to each lattice site. \n\ni.e. \n\n$d=1$, consider \"line\" configuration: $i \\in \\mathbb{Z}$, $i=0,1,\\dots L-1$. Lattice site $k \\in \\Lambda = \\Lambda_{d=1}$. $\\forall \\, k \\in \\Lambda$, \\\\ \n$\\exists \\, $ bijection to its index $i$, $k\\mapsto i$, and $\\exists \\, \\sigma_k$ i.e. \n\\[\n\\begin{aligned}\n\t& \\sigma : \\Lambda \\leftrightarrow \\sigma: \\mathbb{Z} \\to \\mathbb{Z}_2 \\\\ \n\t& \\sigma(k) \\equiv \\sigma_k \\leftrightarrow \\sigma(i) \\equiv \\sigma_i \\mapsto \\lbrace -1, 1 \\rbrace\n\\end{aligned}\n\\]\nspin configuration $\\sigma : \\Lambda \\mapsto (\\sigma_k)_{k\\in \\Lambda} \\in \\lbrace -1,1 \\rbrace^{| \\Lambda |}$, where $|\\Lambda | =L$. \\\\\n$\\forall \\, k \\in \\Lambda$, $\\exists \\, ! $ only at most 2 edges, given, for $k\\mapsto i$, $i+1,i-1$, $\\forall \\, i = 1 \\dots L-2$. \n\n$d=2$, \"rectangle\" configuration. $(i,j) \\in \\mathbb{Z}^2$. $\\begin{aligned} & \\quad \\\\ \n&\t i \\in 0,1,\\dots L_x-1 \\\\ \n&\t j \\in 0,1,\\dots L_y-1 \\end{aligned}$. Lattice site $\\mathbf{k} \\in \\Lambda = \\Lambda_{d=2}$. \\\\ $\\forall \\, \\mathbf{k} \\in \\Lambda$, $\\exists \\, $ bijection to its \"grid coordinates\" $(i,j)$, $\\mathbf{k} \\mapsto (i,j)$, and $\\exists \\, \\sigma_{\\mathbf{k}} $ i.e. $\\sigma_{\\mathbf{k}} = \\sigma_{ij} \\in \\lbrace -1,1\\rbrace$. \\\\\nspin configuration $\\sigma: \\Lambda \\mapsto (\\sigma_{\\mathbf{k}})_{\\mathbf{k} \\in \\Lambda} \\in \\lbrace -1,1\\rbrace^{|\\Lambda|}$, where $|\\Lambda | \\equiv |\\Lambda_{d=2} | = L_xL_y$. \\\\\n$\\forall \\, \\mathbf{k} \\in \\Lambda$, $\\exists \\, !$ only at most 4 edges, given by $\\mathbf{k} \\mapsto (i,j)$, $(i \\pm 1, j ), (i,j\\pm 1)$, \\ $\\begin{aligned} & \\quad \\\\ & i = 1\\dots L_x -2 \\\\ & j = 1\\dots L_y-2 \\end{aligned}$. \n\nNote that in both cases, I haven't yet defined the boundary conditions, and leave that to be discussed thoroughly in the future (i.e. following sections). \n\nThere are $2^{|\\Lambda|}$ number of configurations in any dim. $d$. \n\ncf. \\href{https://en.wikipedia.org/wiki/Ising_model}{Wikipedia, \"Ising model\"}\n\n\\subsubsection{Interaction $J_{ij} \\equiv J_{\\mathbf{k} \\mathbf{l}}$, Hamiltonian (energy functional)for a configuration $H(\\sigma)$} \n\n$\\forall \\, $ 2 adjacent (lattice) sites, $i,j \\equiv \\mathbf{k}, \\mathbf{l} \\in \\Lambda$, let there be an interaction $J_{ij} \\equiv J_{\\mathbf{k} \\mathbf{l}}$ i.e. $\\begin{aligned} & \\quad \\\\ \n& J : \\Lambda^2 \\to \\mathbb{R} \\\\ \n& J: (\\mathbf{k}, \\mathbf{l}) \\mapsto J_{\\mathbf{k} \\mathbf{l}} \\end{aligned}$. \\\\\nAdjacent means $\\exists \\, $ edge $\\mathbf{k} \\mapsto \\mathbf{l}$ (the mapping is the edge) \n\nSuppose $\\forall \\, $ site $j \\equiv \\mathbf{l} \\in \\Lambda$ , $\\exists \\, $ external magnetic field $h_j \\equiv h_{\\mathbf{l}}$ interacting with it. \\\\\nGiven (site) configuration $\\sigma : \\Lambda \\mapsto (\\sigma_{\\mathbf{k}})_{\\mathbf{k} \\in \\Lambda} \\in \\lbrace -1 ,1 \\rbrace^{ | \\Lambda | }$. \n\\begin{equation}\nH(\\sigma) = -\\sum_{ \\langle i j \\rangle } J_{ij} \\sigma_i \\sigma_j - \\mu \\sum_j h_j \\sigma_j \\equiv H(\\sigma(\\Lambda)) = -\\sum_{\\langle \\mathbf{k} \\mathbf{l} \\rangle } J_{\\mathbf{k} \\mathbf{l} }\\sigma_{\\mathbf{k}} \\sigma_{\\mathbf{l}} - \\mu \\sum_{ \\mathbf{k} \\in \\Lambda } h_{\\mathbf{k}} \\sigma_{ \\mathbf{k}}\n\\end{equation}\nwhere $\\sum_{ \\langle \\mathbf{k} \\mathbf{l} \\rangle }$ is overall pairs of adjacent spins (every pair is counted once), \\\\\n\\phantom{where } $\\langle \\mathbf{k}, \\mathbf{l} \\rangle \\equiv $ sites $\\mathbf{k}, \\mathbf{l}$ are nearest neighbors. \n\nNote sign in 2nd. term, $-\\mu \\sum_{\\mathbf{k}} h_{\\mathbf{k}} \\sigma_{\\mathbf{k}}$ should be positive because of electron's magnetic moment is antiparallel to its spin, but negative term used conventionally. \n\nNothing was said about boundary conditions, I propose that it can be either fixed in the summation or by setting $J_{\\mathbf{k} \\mathbf{l}}=0$. \n\n$\\forall \\, \\mathbf{k} \\in \\Lambda$, let $\\begin{aligned} & \\quad \\\\\n\t& \\mathbf{y} : \\Lambda \\to E \\\\ \n\t\t& \\mathbf{y}: \\mathbf{k} \\mapsto \\lbrace \\langle \\mathbf{k}, \\mathbf{l} \\rangle_{\\mathbf{l}} \\end{aligned}$, with $\\lbrace \\langle \\mathbf{k}, \\mathbf{l} \\rangle \\rbrace_{\\mathbf{l}}$ be set of all edges from $\\mathbf{k}$\n\t\t\n\t\tThen clearly $\\sum_{\\langle \\mathbf{k} \\mathbf{l} \\rangle } = \\frac{1}{2} \\sum_{\\mathbf{k} \\in \\Lambda} \\sum_{ \\lbrace \\langle \\mathbf{k} \\mathbf{l} \\rangle \\rbrace_{\\mathbf{l}}}$. \n\t\t\n\t\t\nTaking into account only interaction between adjoining dipoles, on a square lattice: \n\\[\nE(\\sigma) = -J \\sum_{k,l=0}^{L-1} ( \\sigma_{kl}\\sigma_{k,l+1} + \\sigma_{kl} \\sigma_{k+1, l} )\n\\]\ncf. Landau and Lifshitz \\cite{LaLi1980}\n\n\nEY : 20171223 Things to check from Hjorth-Jensen (2015) \\cite{Hjor2015}: \n\n2-dim. Ising model, with $\\mathcal{B} \\equiv h_j =0$, undergoes phase transition of 2nd. order: meaning below given critical temperature $T_C$, there's spontaneous magnetization with $\\langle \\mathcal{M} \\rangle \\equiv \\langle \\mathbf{M} \\rangle \\neq 0$. $\\langle \\mathbf{B} \\rangle \\to 0$ at $T_C$ with \\emph{infinite} slope, a behavior called \\emph{critical phenomena}. Critical phenomenon normally marked by 1 or more thermodynamical variables which is 0 above a critical point. In this case, $\\langle \\mathbf{B} \\rangle \\neq 0$, such a parameter normally called \\emph{order parameter}. \n\nCritical phenomena; we still don't have a satisfactory understanding of system's properties close to the critical point, even for simplest 3-dim. systems. Even mean-field models can predict wrong physics; mean-field theory results in a 2nd.-order phase transition for 1-dim. Ising model, wherea 1-dim. Ising model doesn't predict any spontaneous magnetization at any finite temperature $T$. \n\ne.g. Consider 1-dim. $N$-spin system. Assume periodic boundary conditions. Consider state of all spins up, with total energy $-NJ$ and magnetization $N$. Flip half of spins (e.g. all spins of index $i>N/2$) so 1st half of spins point upwards and last half points downwards. Energy is $-NJ + 4J$, net magnetization $0$. This is an example of a possible disordered state with net magnetization $0$. Change in energy is too small to stabilize disordered state (to $-NJ$). \n\n\\begin{definition}[configuration probability]\n\\textbf{configuration probability} $P_{\\beta}(\\sigma)$ given by Boltzmann distribution: \n\\begin{equation}\\label{Eq:Isingconfigprob}\n P_{\\beta}(\\sigma) = \\frac{ \\exp{ (-\\beta H(\\sigma))} }{ Z_{\\beta} } = \\text{ prob. of configuration } \\sigma \\equiv \\sigma(\\Lambda) \\equiv (\\sigma_{\\mathbf{k}})_{\\mathbf{k} \\in \\Lambda}\n\\end{equation} with the partition function as normalization constant $Z_{\\beta}$: \n\\begin{equation}\\label{Eq:IsingPartitionFuncZ}\nZ_{\\beta} = \\sum_{\\sigma} \\exp{ -\\beta H(\\sigma)}\n\\end{equation}\n\\end{definition} \n\n\n\ncf. pp. 504 Sec. 151 Phase transitions of the second kind in a 2-dim. lattice, Landau and Lifshitz \\cite{LaLi1980}\n\n\n\\begin{equation}\\label{Eq:2dIsingZexact}\nZ = 2^N(1-x^2)^{-N} \\coprod_{p,q=0}^{L-1} \\left[ (1+x^2)^2 - 2x(1-x^2) \\left( \\cos{ \\frac{2\\pi p}{L} } + \\cos{ \\frac{2\\pi q }{L} } \\right) \\right]^{1/2} \n\\end{equation}\ncf. (151.11) of Landau and Lifshitz \\cite{LaLi1980}, where $x= \\tanh{\\theta}$, $\\theta = J/T \\equiv J/\\tau = \\beta J$. \n\n\\begin{equation}\n\\begin{gathered}\n\\Phi \\equiv F = -\\tau \\ln{Z} = \\\\\n= -\\tau N \\ln{2} + \\tau N \\ln{ (1-x^2)} - \\frac{\\tau}{2} \\sum_{p,q=0}^L \\ln{ \\left[ (1+x^2)^2 - 2x(1-x^2) \\left( \\cos{ \\frac{2\\pi p}{L} } + \\cos{ \\frac{2\\pi q }{L} } \\right) \\right] }\n\\end{gathered}\n\\end{equation}\n\nLet $\\begin{aligned}& \\quad \\\\ \n& \\omega_1 = \\frac{2\\pi p }{ L } \\text{ with } p\\to 0 \\text{ as } L \\to \\infty \\\\ \n& \\omega_2 = \\frac{2\\pi q }{ L } \\text{ with } q\\to 0 \\text{ as } L \\to \\infty \\end{aligned}$ so $\\begin{aligned} & \\quad \\\\ \n& \\frac{ L d\\omega_1 }{2\\pi } = dp \\\\ \n& \\frac{ L d\\omega_2}{ 2\\pi } = dq \\end{aligned}$ and using $L^2 = N$. \n\n\n\\[\n\\Phi = -\\tau N \\ln{2} + \\tau N \\ln{ (1-x^2)} - \\frac{N\\tau }{ 2(2\\pi)^2 } \\int_0^{2\\pi } \\int_0^{2\\pi } d\\omega_1 d\\omega_2 \\ln{ \\left[ (1-x^2) - 2x(1-x^2) \\left( \\cos{ \\omega_1 } + \\cos{ \\omega_2 } \\right) \\right] }\n\\] \n\n$F \\equiv \\Phi$ has singularity when $ (1-x^2) - 2x(1-x^2) \\left( \\cos{ \\omega_1 } + \\cos{ \\omega_2 } \\right) $ in $\\ln{ \\left[ (1-x^2) - 2x(1-x^2) \\left( \\cos{ \\omega_1 } + \\cos{ \\omega_2 } \\right) \\right] }$. \\\\\n$ (1-x^2) - 2x(1-x^2) \\left( \\cos{ \\omega_1 } + \\cos{ \\omega_2 } \\right) $ minimized when $\\cos{\\omega_1} = \\cos{\\omega_2}=1$ (since $-1 < x < 1$) \n\\[\n\\begin{gathered}\n\\Longrightarrow (1+x^2)^2 - 4x(1-x^2 ) = 1+2x^2 + x^4 - 4x + 4x^3 = (x^2+2x-1)^2 =0 \\Longrightarrow x = \\frac{-2 \\pm \\sqrt{ 4-4(-1) } }{2} = -1 + \\sqrt{2} \\\\\nx = \\tanh{\\theta} = \\frac{e^{\\theta} - e^{-\\theta} }{ e^{\\theta} + e^{-\\theta} } = \\sqrt{2} -1 \\text{ or } \\begin{gathered}\n\\qquad \\\\ e^{\\theta} - e^{-\\theta} = \\sqrt{2} e^{\\theta} + \\sqrt{2} e^{-\\theta} - e^{\\theta} - e^{-\\theta} \\text{ so } \\\\ \n(2-\\sqrt{2}) e^{\\theta} = \\sqrt{2} e^{-\\theta} \\\\\ne^{2\\theta} = \\frac{\\sqrt{2}}{ 2-\\sqrt{2}} \\left( \\frac{2+\\sqrt{2} }{ 2 + \\sqrt{2}} \\right) \\text{ or } \\\\ \n2\\theta = \\ln{ (1+ \\sqrt{2})}\n\\end{gathered}\n\\end{gathered}\n\\]\n\n\\[\n\\begin{gathered}\n\\frac{J}{T_c} = \\frac{1}{2} \\ln{ (1+\\sqrt{2})} \\text{ or } \n\\end{gathered}\n\\]\n\\begin{equation}\n\\boxed{ \\tau_c = \\frac{2J}{ \\ln{ (1+\\sqrt{2}) }} }\n\\end{equation}\nso that $\\tau_C \\equiv T_C$ is where phase transition occurs. \n\nLet $t:= \\tau - \\tau_c$. $\\theta = \\frac{J}{\\tau} = \\frac{J}{t+\\tau_C}$ \n\nExpand about minimum \n\nEY:20171230 do this explicitly \n\n\\[\n\\begin{gathered}\n\\int_0^{2\\pi } \\int_0^{2\\pi} d\\omega_1 d\\omega_2 \\ln{ [ c_1 t^2 + c_2(\\omega_1^2 + \\omega_2^2 )]} \\\\ \nF \\equiv \\Phi \\simeq a + \\frac{1}{2} b (\\tau-\\tau_c)^2 \\ln{ |\\tau-\\tau_c|} \\\\ \nC = \\frac{ \\partial^2 F}{ \\partial \\tau } \\simeq - b\\tau_c \\ln{ |\\tau-\\tau_c| }\n\\end{gathered}\n\\]\nwith $C$ being heat capacity. \n\nOrder parameter $\\langle M \\rangle \\equiv \\eta = \\text{constant}(\\tau_c - \\tau)^{1/8} = \\begin{cases} 0 & \\text{ if } \\tau > \\tau_c \\\\ \n\\text{ constant } (\\tau_c-\\tau)^{1/8} & \\text{ if } \\tau < \\tau_c \\end{cases}$ \n\ncf. pp. 505 Sec. 151 Phase transitions of the second kind in a 2-dim. lattice, Landau and Lifshitz \\cite{LaLi1980}, L.Onsager 1947. \n\n\\subsection{An actual calculation of a small number of spins with Ising model} \n\nSec. 3.7 \"An actual calculation\" on pp. 76 of Newman and Barkema (1999) \\cite{NeBa1999}\ngoes through a simple actual Monte Carlo calculation as a test case check so to compare this exact calculation/solution to the simulation, as a test of whether the simulation/program is correct. This is done in Sec. 1.3 of Newman and Barkema (1999) \\cite{NeBa1999}. \n\nHowever, none of these promised simple calculations were shown explicitly in Newman and Barkema (1999) \\cite{NeBa1999}. I will forego this simple case. \n\n\\subsection{Explicit calculation showing stencil operation on each spin on a periodic lattice grid} \n\nConsider \n\\[\n\\begin{gathered}\nH(\\sigma) = -\\sum_{ \\langle \\mathbf{k} \\mathbf{l} \\rangle } J \\sigma_{\\mathbf{k}} \\sigma_{\\mathbf{l}} = -J \\sum_{i=0}^{L_x-1} \\sum_{j=0}^{L_y-1} \\sigma_{ij}( \\sigma_{i+1j} + \\sigma_{ij+1} ) = \\\\\t\n= \\frac{-J}{2} \\left( \\sum_{i=0}^{L_x-1} \\sum_{j=0}^{L_y-1} \\sigma_{ij} (\\sigma_{i+1 j} + \\sigma_{ij+1} ) + \\sum_{i=1}^{L_x} \\sum_{j=0}^{L_y-1} \\sigma_{i-1j} (\\sigma_{ij} + \\sigma_{i-1 j+1} ) \\right) = \\\\\n\t= \\frac{-J}{2} \\left( \\sum_{i=0}^{L_x-1} \\sum_{j=0}^{L_y-1} \\sigma_{ij} (\\sigma_{i+1 j} + \\sigma_{ij+1} ) + \\sum_{i=1}^{L_x} \\sum_{j=0}^{L_y-1} \\sigma_{i-1j} \\sigma_{ij} + \\sum_{i=0}^{L_x-1} \\sum_{j=1}^{L_y} \\sigma_{i j-1} \\sigma_{ij} \\right) \n\\end{gathered}\n\\]\nNow for each of these terms, \n\\[\n\\begin{gathered}\n\t\\sum_{i=1}^{L_x} \\sum_{j=0}^{L_y-1} \\sigma_{i-1 j} \\sigma_{ij} = \\sum_{i=1}^{L_x} \\left( \\sum_{j=1}^{ L_y-1 } \\sigma_{i-1 j} \\sigma_{ij} + \\sigma_{i-1 0 }\\sigma_{i0} \\right) = \\sum_{i=1}^{L_x-1} \\left( \\sum_{j=1}^{L_y-1} \\sigma_{i-1 j} \\sigma_{ij} + \\sigma_{i-10} \\sigma_{i0} \\right) + \\left( \\sum_{j=1}^{L_y-1} \\sigma_{L_x-1 j } \\sigma_{L_xj} \\right) + \\sigma_{L_x-1 0 } \\sigma_{L_x0} \\\\ \n\\sum_{i=0}^{L_x-1} \\sum_{j=1}^{L_y} \\sigma_{ij-1} \\sigma_{ij} = \\sum_{j=1}^{L_y-1} \\left( \\sum_{i=1}^{L_x-1} \\sigma_{ij-1} \\sigma_{ij}+ \\sigma_{0j-1} \\sigma_{0j} \\right) + \\sum_{i=1}^{L_x-1} \\sigma_{i L_y-1} \\sigma_{iL_y} + \\sigma_{0L_y-1} \\sigma_{0L_y} \n\\end{gathered}\n\\]\n\\[\n\\begin{gathered}\n\t\\sum_{i=0}^{L_x-1} \\sum_{j=0}^{L_y-1} \\sigma_{ij} (\\sigma_{i+1j } + \\sigma_{ij+1} ) = \\sum_{i=0}^{L_x-1} \\left( \\sum_{j=1}^{L_y} \\sigma_{ij} ( \\sigma_{i+1j } + \\sigma_{ij+1} ) + \\sigma_{i0} (\\sigma_{i+1 0 } + \\sigma_{i1} ) \\right) = \\\\\n\t\\sum_{i=1}^{L_x-1} \\left( \\sum_{j=1}^{L_y-1} \\sigma_{ij} (\\sigma_{i+1j} + \\sigma_{ij+1}) + \\sigma_{i0} (\\sigma_{i+1 0 } + \\sigma_{i1}) \\right) + \\sum_{j=1}^{L_y-1} \\sigma_{0j} (\\sigma_{1j} + \\sigma_{0j+1} ) + \\sigma_{00} (\\sigma_{10} + \\sigma_{01} )\n\\end{gathered}\n\\]\n\nApply periodic boundary conditions. Adding up all the terms above, clearly we obtain 1 term which shows the stencil operation for spins on the \"interior\" of the grid: \n\\[\n\\sum_{i=1}^{L_x-1} \\sum_{j=1}^{L_y-1} \\sigma_{ij} ( \\sigma_{i+1j} + \\sigma_{ij+1} + \\sigma_{i-1j} + \\sigma_{ij-1} )\n\\]\nand if we apply \\emph{periodic} boundary conditions, neatly, we'll see all the lattice sites at the boundary also will have this stencil operation: \n\\[\n\\begin{gathered}\n\t\\sum_{i=1}^{L_x - 1} \\sigma_{i0} (\\sigma_{i+10} + \\sigma_{i1} ) + \\sum_{j=1}^{L_y-1} \\sigma_{0j} (\\sigma_{1j} + \\sigma_{0j+1} ) + \\sigma_{00} (\\sigma_{10} + \\sigma_{01} ) + \\left( \\sum_{i=1}^{L_x-1} \\sigma_{iL_y-1} \\sigma_{i0} \\right) + \\sigma_{0L_y-1} \\sigma_{00} + \\sum_{j=1}^{L_y-1} \\sigma_{0j-1} \\sigma_{0j} + \\\\\n\t+ \\sum_{j=1}^{L_y - 1} \\sigma_{L_x- 1 j} \\sigma_{0j} + \\sigma_{L_x-1 0} \\sigma_{00} + \\sum_{i=1}^{L_x-1} \\sigma_{i-10} \\sigma_{i0} \n\\end{gathered}\n\\]\n\nNow, we can obtain the following for Hamiltonian, given spin configuration $\\sigma$ with a lattice grid obeying periodic conditions: \n\n\\begin{equation}\n\\begin{gathered}\nH(\\sigma) = -\\frac{J}{2} \\sum_{i=0}^{L_x-1} \\sum_{j=0}^{L_y-1} \\sigma_{ij} (\\sigma_{i+1j } + \\sigma{i-1j} + \\sigma_{ij+1} + \\sigma_{ij-1} ) = \\\\\n= \\frac{-J}{2} \\left[ \\sum_{i=0}^{L_x-1} \\left( \\sum_{ \\substack{ j=0 \\\\ j \\neq j' \\\\ } }^{L_y -1} \\sigma_{ij} ( \\sigma_{i+1j} + \\sigma_{i-1j} + \\sigma_{ij+1} + \\sigma_{ij-1} ) + \\sigma_{ij'} ( \\sigma_{i+1j'} + \\sigma_{i-1j'} + \\sigma_{ij'+1} + \\sigma_{ij'-1} ) \\right) + \\right. \\\\ \n\\left. \\sum_{ \\substack{j=0 \\\\ j\\neq j' \\\\ } }^{L_y-1} \\sigma_{i'j} ( \\sigma_{i'+1j} + \\sigma_{i'-1j} + \\sigma_{i'j+1} + \\sigma_{i'j-1} ) + \\sigma_{i'j'} ( \\sigma_{i'+1j'} + \\sigma_{i'-1j'} + \\sigma_{i'j'+1} + \\sigma_{i'j'-1}) \\right] \n \\end{gathered}\n\\end{equation}\n\nConsider a psin flip of $\\sigma_{i'j'}$. Contribution to $\\Delta H$ at stencil operation on $\\sigma_{i'j'}$, at $(i'j') \\in \\Lambda$, is \n\\[\n\\frac{-J}{2} ( - \\sigma_{i'j'} - \\sigma_{i'j'} ) (\\sigma_{i'+1j'} + \\sigma_{i'-1j'} + \\sigma_{i'j'+1} + \\sigma_{i'j'-1}) = J\\sigma_{i'j'} ( \\sigma_{i'+1j'} + \\sigma_{i'-1j'} + \\sigma_{i'j'+1} + \\sigma_{i'j'-1})\n\\]\nConsider $\\sigma_{i'j'} \\sigma_{i'+1j'}$. Clearly, term $\\sigma_{i-1j'} \\sigma_{ij'}$ with $i=i'+1$ only occurs once more in the summation. Thus, we can definitely conclude that for $\\Delta H \\equiv \\Delta H(\\Delta \\sigma_{i'j'})$ due to a single spin-flip is \n\\begin{equation}\n\\Delta H(\\Delta \\sigma_{i'j'}) = 2J\\sigma_{i'j'} ( \\sigma_{i'+1j'} + \\sigma_{i'-1j'} + \\sigma_{i'j'+1} + \\sigma_{i'j'-1} )\n\\end{equation}\n\n\n\\url{https://www.colorado.edu/physics/phys7240/phys7240_fa12/notes/Week3.pdf}\n\\href{https://www.colorado.edu/physics/phys7240/phys7240_fa12/notes/Week3.pdf}{Victor Gurarie, Advanced Statistical Mechanics, Fall 2012}\nExact solution by transfer matrices for 2-dim. Ising model. \n\n\n\\part{Conformal Field Theory; Virasoro Algebra} \n\ncf. Schottenloher (2008) \\cite{Scho2008}\n\n\\section{Conformal Transformations}\n\n\\subsection{Semi-Riemannian manifolds (review and (key) examples)}\n\ncf. pp. 7, Ch. 1 \"Conformal Transformations and Conformal Killing Fields.\" Schottenloher (2008) \\cite{Scho2008}\n\nSemi-Riemannian manifold is a pair $(M, g)$ s.t. \\\\\nsmooth manifold $M$, $\\text{dim}{M} = n$, \\\\\nsmooth tensor field $g$ s.t. $g: a\\in M \\mapsto \\Omega^2(T_aM)$, i.e. \n$\\forall \\, a \\in M$, $g$ assigns $a$ a nonnegative and symmetric bilinear form on tangent space $T_aM$. \n\nIn local coordinates, $x^1 \\dots x^n $ of manifold $M$, \\\\\ngiven chart $\\phi : U \\to V$, open subset $U \\subseteq M$, open subset $V \\subseteq \\mathbb{R}^n$, \n\\[\n\\phi(a) = (x^1(a) \\dots x^n(a)), \\, a\\in M\n\\]\nBilinear form $g_a$ on $T_aM$, written\n\\[\ng_a(X,Y) = g_{\\mu \\nu}(a) X^{\\mu} Y^{\\nu}\n\\]\n\nTangent vectors $X = X^{\\mu} \\partial_{\\mu}$, $Y = Y^{\\nu} \\partial_{\\nu} \\in T_aM$ basis $\\partial_{\\mu} := \\frac{ \\partial }{ \\partial x^{\\mu}}$, $\\mu = 1 \\dots n$ of tangent space $T_aM$, induced by chart $\\phi$. \n\nBy assumption, matrix\n\\[\ng_{\\mu \\nu}(a)\n\\]\nNondegenerate and symmetric, $\\forall \\, a \\in U$, i.e. \n\\[\n\\text{det}(g_{\\mu \\nu }(a)) \\neq 0 , \\qquad \\, (g_{\\mu \\nu}(a))^T = (g_{\\mu \\nu}(a))\n\\]\n\nDifferentiating of $g_a$ implies matrix $g_{\\mu \\nu}(a)$ depends differentiably on $a$.\n\nThat means that in its dependence on local coordinates $x^j$, coefficient $g_{\\mu \\nu} = g_{\\mu \\nu}(x)$ are smooth functions.\n\nIn general, $g_{\\mu \\nu}X^{\\mu} X^{\\nu} >0 $ doesn't hold $\\forall \\, X \\neq 0$, i.e. $g_{\\mu \\nu}(a)$ not required to be positive-definite.\n\n2 important subcases: \\footnote{\\url{https://doc.sagemath.org/html/en/reference/manifolds/sage/manifolds/differentiable/pseudo_riemannian.html}}\n\nRiemannian manifold: metric $g$ positive definite, signature $n= \\text{dim}M$. \n\nLorentz manifold specified as semi-Riemannian manifold with $(p,q)= (n-1,1)$ or $(p,q) = (1, n-1)$. \n\nMetric $g$ has signature $n-2$ (positive convention) or $2-n$ (negative convention).\n\n\\subsubsection{Examples (of Riemannian manifolds for Conformal Field Theory)}\n\n$\\mathbb{R}^{p,q} = (\\mathbb{R}^{p,q}, g^{p,q})$, $p,q \\in \\mathbb{N}$, where\n\\[\ng^{p,q}(X,Y) := \\sum_{i=1}^p X^i Y^i - \\sum_{i = p+1}^{p+q} X^i Y^i\n\\]\n\nHence\n\\[\n(g_{\\mu \\nu}) = \\left( \\begin{matrix} 1_p & \\\\ & -1_q \\end{matrix} \\right) = \\text{diag}(1\\dots 1, -1, \\dots -1)\n\\]\n\n$\\mathbb{R}^{1,3} = \\mathbb{R}^{3,1}$, usual Minkowski space. \\\\\n$\\mathbb{R}^{1,1}$, 2 -dim. Minkowski space (Minkowski plane). \\\\\n$\\mathbb{R}^{2,0}$, Euclidean plane. \\\\\n$\\mathbb{S}^2 \\subset \\mathbb{R}^{3,0}$, compactification of $\\mathbb{R}^{2,0}$, structure of Riemannian manifold on 2-sphere $\\mathbb{S}^2$ induced by inclusion in $\\mathbb{R}^{2,0}$ \\\\\n$\\mathbb{S} \\times \\mathbb{S} \\subset \\mathbb{R}^{2,2}$, compactification of $\\mathbb{R}^{1,1}$. More precisely, \\\\\n$\\mathbb{S} \\times \\mathbb{S} \\subset \\mathbb{R}^{2,0} \\times \\mathbb{R}^{0,2} \\simeq \\mathbb{R}^{2,2}$ where structure of semi-Riemannian manifold on $\\mathbb{S} \\times \\mathbb{S}$ induced by inclusion into $\\mathbb{R}^{2,2}$. \n\n$\\mathbb{S}^p \\times \\mathbb{S}^q \\subset \\mathbb{R}^{p+1, 0} \\times \\mathbb{R}^{0, q+1} \\simeq \\mathbb{R}^{p+1,q+1}$ with $p$-sphere $\\mathbb{S}^p = \\lbrace X \\in \\mathbb{R}^{p+1} : g^{p+1, 0}(X,X) = 1\\rbrace \\subset \\mathbb{R}^{p+1,0}$, $q$-sphere $\\mathbb{S}^q \\subset \\mathbb{R}^{0, q+1}$ \\\\\nyields a compactification of $\\mathbb{R}^{p,q}$ for $p,q \\geq 1$\n\nCompact semi-Riemannian manifold denoted by $\\mathbb{S}^{p,q}$, for $p, q\\geq 0$.\n\nQuadrics $N^{p,q}$ (of Sec. 2.1) are locally isomorphic to $\\mathbb{S}^{p,q}$ from point of view of conformal geometry.\n\nFor the \"\\emph{negative convention}\": \n\n\\[\ng^{p,q}(X,Y) = - \\sum_{i=0}^{p-1} X^i Y^i + \\sum_{i=p}^{p+q} X^i Y^i\n\\]\n\\[\n(g_{\\mu \\nu}) = \\left( \\begin{matrix} -1_p & \\\\ & 1_q \\end{matrix} \\right) = \\text{diag}(-1 , \\dots - 1, 1 \\dots 1)\n\\]\n\n$\\mathbb{R}^{1,3} $, Minkowski space. \\\\\n$\\mathbb{R}^{1,1}$, 2 -dim. Minkowski space. \\\\\n$\\mathbb{R}^{0,2}$, Euclidean plane. \\\\\n$\\mathbb{S}^2 \\subset \\mathbb{R}^{0,3}$, compactification of $\\mathbb{R}^{0,2}$ \\\\\n$\\mathbb{S} \\times \\mathbb{S} \\subset \\mathbb{R}^{0,2} \\times \\mathbb{R}^{2,0} \\simeq \\mathbb{R}^{2,2}$ \n\n$\\mathbb{S}^p \\times \\mathbb{S}^q \\subset \\mathbb{R}^{0, p+1} \\times \\mathbb{R}^{q+1, 0} \\simeq \\mathbb{R}^{p+1,q+1}$ with $p$-sphere $\\mathbb{S}^p = \\lbrace X \\in \\mathbb{R}^{p+1} : g^{ 0, p+1}(X,X) = 1\\rbrace \\subset \\mathbb{R}^{0, p+1}$, $q$-sphere $\\mathbb{S}^q \\subset \\mathbb{R}^{q+1, 0}$ \\\\\nyields a compactification of $\\mathbb{R}^{p,q}$ \n\n\n\n\n\\begin{definition}[Conformal transformation or conformal map]\nLet 2 semi-Riemannian manifolds$(M,g)$, $(M',g')$, $\\text{dim}M = \\text{dim}M'$, let open $U\\subset M$, open $V\\subset M'$. \n\n\\textbf{conformal transformation} or \\textbf{conformal map} is a smooth $\\varphi : U\\to V$ of maximal rank, if $\\exists \\, $ smooth $\\Omega : U\\to \\mathbb{R}^+$ s.t. \n\\begin{equation}\n\t\\varphi^* g' = \\Omega^2 g\n\\end{equation}\nwhere $\\varphi* g'(X,Y) :=g'(T\\varphi(X), T\\varphi(Y))$ and $T\\varphi: TU \\to TV$ denote tangent map (derivative) of $\\varphi$. \n\n$\\Omega \\equiv $ \\emph{conformal factor} of $\\varphi$. \n\\end{definition}\n\nLocally, $y^i = \\varphi^i(x)$, \\[\n\\begin{gathered}\n\t\\frac{ \\partial \\varphi^i }{ \\partial x^j} = \\frac{ \\partial y^i }{ \\partial x^j}\n\\end{gathered}\t\n\\]\nThen\n\\[\nX = X^k \\frac{ \\partial }{ \\partial x^k} = X^k \\frac{ \\partial y^i }{ \\partial x^k} \\frac{ \\partial }{ \\partial y^i } = X^k \\frac{ \\partial \\varphi^i }{ \\partial x^k} \\frac{ \\partial }{ \\partial y^k} \\in TM\n\\]\nand so \n\\[\n\\begin{gathered}\n\t\\varphi^* g'(X,Y) = g'(T\\varphi(X), T\\varphi(Y)) = (g')_{ij} X^k \\frac{ \\partial y^i }{ \\partial x^k} Y^l \\frac{ \\partial y^j }{ \\partial x^l} = (g')_{ij} X^k \\frac{ \\partial \\varphi^i }{ \\partial x^k } Y^l \\frac{ \\partial y^j}{ \\partial x^l} \\\\ \n\\Longrightarrow (\\varphi^* g')_{kl} = (g')_{ij} \\frac{ \\partial y^i }{ \\partial x^k } \\frac{ \\partial y^j}{ \\partial x^l } \\\\ \n\\Longrightarrow (\\varphi^* g')_{kl} = (g')_{ij} \\frac{ \\partial \\varphi^i }{ \\partial x^k} \\frac{ \\partial \\varphi^j}{ \\partial x^l} = \\Omega^2 g_{kl}\n\\end{gathered}\n\\]\n\n\n% 20170926 \n\n\\begin{definition}\n\t\\textbf{extension} of $G$ by group $A$ is (given by) an \\emph{exact sequence} of group homomorphisms. \n\t\\begin{tikzpicture}\n\t%\\matrix(m)[matrix of math nodes, row sep=3em, column sep=3em, text height=1.5ex, text depth=0.25ex]\n\t\\matrix(m)[matrix of math nodes, row sep=4em, column sep=4em]\n\t{\n\t\t1 & A & E & G & 1 \\\\\n\t};\n\t%\\path[->,font=\\scriptsize]\n\t\\path[->]\n\t(m-1-1) edge node[auto]{$$} (m-1-2)\n\t(m-1-2) edge node[auto]{$i$} (m-1-3)\n\t(m-1-3) edge node[auto]{$\\pi$} (m-1-4)\n\t(m-1-4) edge node[auto]{$$} (m-1-5)\t\n\t;\n\t\\end{tikzpicture} \n\\end{definition}\ncf. Def. 3.1 of Schottenloher (2008) \\cite{Scho2008}. \n\nRecall that an exact sequence, if $\\begin{aligned} & \\quad \\\\\n\t& \\text{im}(1\\to A) = \\text{ker}(i) \\\\\n\t& \\text{im}(i) = \\text{ker}(\\pi) \\\\\n\t& \\text{im}(\\pi) = \\text{ker}(G\\to 1)\n\\end{aligned}$\n\nBy Thm., \n$1\\to A \\xrightarrow{i} E$ exact so $i$ injective. \\\\\n$E\\xrightarrow{\\pi} G \\to 1$ exact so $\\pi$ surjective. \n\nExtension is called \\textbf{central} if $A$ abelian and image $\\text{im}i$ is in center of $E$, i.e. \n$a\\in A, b\\in E \\Longrightarrow i(a) b = bi(a)$. \n\n\\subsubsection{Examples of extensions of $G$, and central extensions of $G$ (which has a particular $E$)}\n\\begin{itemize}\n\\item e.g. central extension has form \n\\[\n\\begin{tikzpicture}\n%\\matrix(m)[matrix of math nodes, row sep=3em, column sep=3em, text height=1.5ex, text depth=0.25ex]\n\\matrix(m)[matrix of math nodes, row sep=4em, column sep=4em]\n{\n\t1 & A & A\\times G & G & 1 \\\\\n};\n%\\path[->,font=\\scriptsize]\n\\path[->]\n(m-1-1) edge node[auto]{$$} (m-1-2)\n(m-1-2) edge node[auto]{$i$} (m-1-3)\n(m-1-3) edge node[auto]{$\\text{pr}_2$} (m-1-4)\n(m-1-4) edge node[auto]{$$} (m-1-5)\t\n;\n\\end{tikzpicture} \n\\]\nwhere \\\\\n$\\begin{aligned}\n i:A & \\to A\\times G \\\\\na & \\mapsto (a,1) \\end{aligned}$ \n\n\\[\n\\begin{gathered}\ni(a)(a',g) = (a,1)(a',g) = (aa',g) = \\\\\n= (a'a,g\\cdot 1) = (a',g)(a,1) = (a',g)i(a)\n\\end{gathered}\n\\]\n\nNotice that what the \\emph{exactness} property of an exact sequence does:\n\\[\n\\text{pr}_2i(a) = \\text{pr}_2(a,1) = 1\n\\]\n\n\\item e.g. of a \\text{nontrivial central extension} is exact sequence \n\\begin{equation}\n\\begin{tikzpicture}\n%\\matrix(m)[matrix of math nodes, row sep=3em, column sep=3em, text height=1.5ex, text depth=0.25ex]\n\\matrix(m)[matrix of math nodes, row sep=4em, column sep=4em]\n{\n\t1 & \\mathbb{Z}/k\\mathbb{Z} & E\\times U(1) & U(1) & 1 \\\\\n};\n%\\path[->,font=\\scriptsize]\n\\path[->]\n(m-1-1) edge node[auto]{$$} (m-1-2)\n(m-1-2) edge node[auto]{$$} (m-1-3)\n(m-1-3) edge node[auto]{$\\pi$} (m-1-4)\n(m-1-4) edge node[auto]{$$} (m-1-5)\t\n;\n\\end{tikzpicture} \n\\end{equation}\nwith $\\pi(z) = z^k$ \\, $\\forall \\, k \\in \\mathbb{N}$, $k\\geq 2$, since $E=U(1)$ and $\\mathbb{Z}/k\\mathbb{Z}$ are not isomorphic. \n\nAlso, homomorphism $\\tau:U(1) \\to E$ with $\\pi \\circ \\tau = 1_{U(1)}$, doesn't exist, since there's no global $k$th root. \n\nEY : 20170926 It's that in integer division of the argument in a complex number $z\\in U(1)$, and exponent multiplication by $k$, you go from 1 to many and many to 1, depending upon the \"branch\" you're mapping to for complex numbers. \n\nFor $[n] \\in \\mathbb{Z}/k\\mathbb{Z}$, \n\\[\n[n]\\xmapsto[]{ i } \\exp{ \\left( \\frac{ [n] }{ k} 2\\pi i \\right) }\n\\]\nand so \n\\[\n\\text{ker}\\pi = \\lbrace z | \\pi(z) = 1 \\rbrace \\text{ so that } \\text{ker}\\pi = \\lbrace z = \\exp{ \\left( \\frac{i 2\\pi n}{k} \\right) } \\rbrace\n\\]\n\n\\item e.g. \\emph{Semidirect products}. \n\ngroup $G$ acting on another group $H$, by homomorphism \n\\[\n\\tau : G \\to \\text{Aut}(H)\n\\]\n\n\n\n\n% 20170926 of END \n\n\\begin{definition}[semi-direct product]\\label{Def:Semidirectprod}\n\\textbf{semidirect product} group $G \\ltimes H$ is set $H\\times G$, with multiplication \n\\[\n(x,g) \\cdot (x',g') := (x\\tau(g)(x'), gg') \\qquad \\, \\forall \\, (x,g), (x',g') \\in H\\times G\n\\]\n\\end{definition}\n\\begin{equation}\n\\begin{tikzpicture}\n%\\matrix(m)[matrix of math nodes, row sep=3em, column sep=3em, text height=1.5ex, text depth=0.25ex]\n\\matrix(m)[matrix of math nodes, row sep=4em, column sep=4em]\n{\n\t1 & H & G \\ltimes H & G & 1 \\\\\n};\n%\\path[->,font=\\scriptsize]\n\\path[->]\n(m-1-1) edge node[auto]{$$} (m-1-2)\n(m-1-2) edge node[auto]{$i$} (m-1-3)\n(m-1-3) edge node[auto]{$\\pi$} (m-1-4)\n(m-1-4) edge node[auto]{$$} (m-1-5)\t\n;\n\\end{tikzpicture} \n\\end{equation}\nwith \n\\begin{equation}\n\t\\begin{aligned}\n\t& i : H\\to G \\ltimes H \\\\ \n\t& i(x) = (x,1)\n\\end{aligned}\n\\end{equation}\n$i$ group homomorphism, since \n\\[\ni(x_1x_2) = (x_1x_2 ,1) = (x_1 \\tau(1)x_2 , 1) = (x_1,1)\\cdot (x_2,1) = i(x_1)i(x_2)\n\\]\n\\begin{equation}\n\t\\begin{aligned}\n\t& \\pi : G \\ltimes H \\to G\\\\ \n\t& \\pi(x,g) = g \n\\end{aligned}\n\\end{equation}\ncf. \\url{http://sierra.nmsu.edu/morandi/oldwebpages/math683fall2002/GroupExtensions.pdf}\n\nObserve that \n\\[\n\\pi i(x) = \\pi(x,1)=1 \\text{ so } \\text{ker}\\pi = \\text{im}i\n\\]\n\n\\begin{definition}[Semi-direct product (2); with direct product]\\label{Def:Semidirectprod2}\n\t\\textbf{direct product} $G=HK$ if \\\\\n$H,K$ subgroups of group $G$, s.t. \\\\\n\\begin{itemize}\n\\item $H$ and $K$ are normal in $G$ ($gkg^{-1} \\in K$ \\, $\\forall \\, g\\in G$, $\\forall \\, k \\in K$) \n\\item $H\\cap K = \\lbrace 1 \\rbrace$ \n\\item $HK=G$. \n\\end{itemize} \n\n\\textbf{semi-direct product}. Relax the 1st condition (of direct products) so $H$ still normal in $G$, but $K$ need not be. \\\\\n\\begin{itemize}\n\\item $H$ normal in $G$ ($ghg^{-1} \\in H, \\, \\forall \\, g , \\, \\forall \\, h \\in H$) \n\\item $H\\cap K = \\lbrace 1 \\rbrace$ \n\\item $HK = G$\n\\end{itemize}\n\\end{definition}\n\n\\emph{Connection between} Def. \\ref{Def:Semidirectprod} and Def. \\ref{Def:Semidirectprod2} for the \\emph{semidirect product}: Consider $\\tau : G \\to \\text{Aut}(H)$. \n\nConsider $G \\ltimes H$ - what is the identity $1_{G\\ltimes H} \\equiv (1_H,1_G)$ of this group? \n\\[\n(x,g)\\cdot (1_H,1_G) = (x\\tau(g) 1_H, g1_G) = (x\\tau(g)1_H, g) \\Longrightarrow 1_H = \\tau(g^{-1})1, \\, 1_G=1\n\\]\nand so the inverse, $\\forall (x,g) \\in G\\ltimes H$, $(x,g)^{-1} \\equiv ((x^{-1}), (g^{-1}))$, \n\\[\n\\begin{gathered}\n\t(x,g) (x,g)^{-1} = (x\\tau(g) (x^{-1}),g(g^{-1}) ) = (x\\tau(g)(x^{-1}), 1) \\text{ (if $(g^{-1}) = g^{-1}$) }\n\\end{gathered}\n\\]\nMoving along, \n\\[\n\\begin{gathered}\n\tx\\tau(g) (x^{-1}) = \\tau(g^{-1})1 \\\\\n\\Longrightarrow (x^{-1}) = \\tau(g^{-1}) x^{-1}\\tau(g^{-1})1\n\\end{gathered}\n\\]\n\nChecking out the $H$ being a normal subgroup of $G\\ltimes H$ condition, i.e. $H \\lhd G$, \n\\[\n\\begin{gathered}\n\t(x,g)(h,1)(\\tau(g^{-1})x^{-1} \\tau(g^{-1}) , g^{-1}) = (x\\tau(g)h, g)(\\tau(g^{-1})x^{-1}\\tau(g^{-1}) , g^{-1}) = \\\\\n= (x\\tau(g)h \\tau(g)\\tau(g^{-1}) x^{-1}\\tau(g^{-1}), 1) = (x\\tau(g) hx^{-1}\\tau(g^{-1}), 1) \n\\end{gathered}\n\\]\n$\\Longrightarrow$ $H$ normal subgroup of $G\\ltimes H \\equiv H \\lhd (G\\ltimes H)$. \n\n\\href{http://www.math.columbia.edu/~bayer/S09/ModernAlgebra/semidirect.pdf}{Notes on Semidirect products}\n\\item extension \n\\begin{equation}\n\\begin{tikzpicture}\n%\\matrix(m)[matrix of math nodes, row sep=3em, column sep=3em, text height=1.5ex, text depth=0.25ex]\n\\matrix(m)[matrix of math nodes, row sep=4em, column sep=4em]\n{\n\t1 & SL(n,\\mathbb{R}) & GL(n,\\mathbb{R}) & \\mathbb{R}^* & 1 \\\\\n};\n%\\path[->,font=\\scriptsize]\n\\path[->]\n(m-1-1) edge node[auto]{$$} (m-1-2)\n(m-1-2) edge node[auto]{$i$} (m-1-3)\n(m-1-3) edge node[auto]{$\\text{det}$} (m-1-4)\n(m-1-4) edge node[auto]{$$} (m-1-5)\t\n;\n\\end{tikzpicture} \n\\end{equation}\n\nwith \\\\\n$GL(n,\\mathbb{R}) \\equiv Gl_n(\\mathbb{R}) = \\lbrace A | A \\in \\text{Mat}_{\\mathbb{R}}(n,n); \\text{det}A \\neq 0\\rbrace$ \\\\\n$\\text{det}:GL(n,\\mathbb{R}) \\to \\mathbb{R}^* \\equiv \\mathbb{R} \\backslash \\lbrace 0 \\rbrace $, $\\text{det}$ surjective homomorphism \\\\\n$SL(n,\\mathbb{R}) \\equiv Sl_n(\\mathbb{R}) = \\lbrace A | A \\in \\text{Mat}_{\\mathbb{R}}(n,n); \\, \\text{det}A=1\\rbrace$ \\\\\n\nNote that $\\text{ker}(\\text{det}) = SL(n,\\mathbb{R})$. \n\nNow \n\\[\n\\mathbb{R}^* \\simeq \\lbrace a 1_n | a \\in \\mathbb{R}^* \\rbrace\n\\]\nand $\\text{det}(a1_n) = a^n$. \n\nIf $n$ odd, and $\\text{det}(a1_n)=a^n =1$, then $a=1$. If $n$ even, $a=\\lbrace -1, 1 \\rbrace$. \n\nBy the second definition of a semi-direct product, Def. \\ref{Def:Semidirectprod2}, it's required that $SL(n,\\mathbb{R}) \\cap \\mathbb{R}^* = 1$ (i.e. the intersection is only the identity). This will only be the case if $n$ odd. \n\ncf. \\url{http://sierra.nmsu.edu/morandi/oldwebpages/math683fall2002/GroupExtensions.pdf}\n\n\\end{itemize}\n\n\\part{Quantum Mechanics}\n\n\\section{The Wave function and the Schr\\\"{o}dinger Equation, its probability interpretation, some postulates}\n\ncf. Ch. 2 \"The Wave Function and the Schr\\\"{o}dinger Equation\" in \\textbf{Quantum Mechanics} by Franz Schwabl (2007) \\cite{FrSc2007}.\n\nFrom experimental considerations (Sec. 1.2.2, Schwabl (2007) \\cite{FrSc2007}), with electron diffraction, electrons, $e^-$, have wavelike properties; let this wave be $\\psi(\\mathbf{x}, t)$. \n\nFor free $e^-$ of momentum $\\mathbf{p}$, energy $E = \\frac{ \\mathbf{p}^2}{2m}$, in accordance with diffraction experiments, consider as free plane waves \n\\[\n\\psi(\\mathbf{x}, t) = C \\exp{ \\left( i ( \\mathbf{k} \\cdot \\mathbf{x} - \\omega t)\\right)}, \\qquad \\, \\omega = E / \\hbar = E, \\, \\mathbf{k} = \\mathbf{p}/ hbar = \\mathbf{p}\n\\]\nwith $\\hbar = 1$\n\nHypothesis: wave function $\\psi(\\mathbf{x},t)$ gives probability distribution \n\\[\n\\rho(\\mathbf{x}, t) = | \\psi(\\mathbf{x}, t)|^2\n\\]\n$\\rho(\\mathbf{x}, t) d^3 x = $ probability of finding $e^-$ at location $\\mathbf{x}$ in volume element $d^3x$.\n\ne.g. $e^-$ waves $\\psi_1(\\mathbf{x}, t)$ , $\\psi_2(\\mathbf{x},t)$\n\nIf both slits open, superposition of wave functions $\\psi_1(\\mathbf{x}, t) + \\psi_2(\\mathbf{x},t)$\n\nNote $| \\psi_1(\\mathbf{x},t) + \\psi_2(\\mathbf{x},t) |^2 \\neq | \\psi_1(\\mathbf{x},t) |^2 + |\\psi_2(\\mathbf{x},t) |^2$ if there are no interference terms.\n\nImportant remarks: \n\n\\begin{enumerate}\n\t\\item[(i)] Single $e^-$ not smeared out. $\\rho(\\mathbf{x},t)$ is \\textbf{not} the charge distribution of $e^-$, but is the probability density for measuring particle at position $\\mathbf{x}$ at time $t$.\n\t\\item[(ii)] Prob. distribution doesn't occur by interference of many simultaneously incoming $e^-$, but one obtains same interference pattern if each $e^-$ enters separately, i.e. even for very low intensity source. Thus, wave function applies to every electron and describes state of single $e^-$.\n\\end{enumerate}\n\ncf. 2.2 \"The Schr\\\"{o}dinger Equation for Free Particles\" in \\textbf{Quantum Mechanics} by Franz Schwabl (2007) \\cite{FrSc2007}.\n\n(i) 1st. order DE (differential equation); (ii) linear in $\\psi$ for linear superposition (iii) \"homogeneous\" $\\int d^3x | \\psi(\\mathbf{x}, t) |^2 = 1$, (iv) plane waves\n\\[\n\\psi(\\mathbf{x},t) = C \\exp{ \\left[ i (\\mathbf{p} \\cdot \\mathbf{x} - \\frac{p^2}{2m} t)/ \\hbar\\right]} \\qquad \\, \\text{ plane waves }\n\\]\nShould be solutions of the equations.\n\nFrom postulates (i-iv),\n\\[\ni \\hbar \\frac{\\partial}{ \\partial t} \\psi(\\mathbf{x}, t) = \\frac{ -\\hbar^2}{2m } \\nabla^2 \\psi(\\mathbf{x},t)\n\\]\nTime-dependent Schr\\\"{o}dinger equation for free particles.\n\n\\[\n\\int_{-\\infty}^{\\infty} d^3k e^{i\\mathbf{k} \\cdot \\mathbf{x}} e^{-k^2 \\alpha^2} = \\prod_{j=x}^z \\int_{-\\infty}^{\\infty} dk_j e^{ik_j x_j} e^{-k_j^2 \\alpha^2} = \\prod_{j=x}^z \\left( \\sqrt{ \\frac{\\pi}{\\alpha^2} } \\exp{ \\left( \\frac{-x_j^2}{4\\alpha^2} \\right)} \\right) = \\left( \\frac{\\sqrt{\\pi}}{\\alpha} \\right)^3 \\exp{ \\left( \\frac{-x^2}{4\\alpha^2} \\right)}\n\\]\n\n\n\\part{Algebraic Topology} \n\ncf. Bredon (1997) \\cite{Bred1997}\n\n\n\\section{Simplicial Complexes} \n\ncf. pp. 245, from Sec. 21 Simplicial Complexes of Ch. 4 Homology Theory in Bredon (1997) \\cite{Bred1997}\n\n$\\mathbf{v}_0, \\dots \\mathbf{v}_n \\in \\mathbb{R}^{\\infty}$, \"affinely independent\" if they span an affine $n$-plane, i.e. \n\\[\n\\text{ if } \\left( \\sum_{i=0}^n \\lambda_i \\mathbf{v}_i =0 , \\, \\sum_{i=0}^n \\lambda_i = 0 \\right), \\text{ then } \\Longrightarrow \\forall \\, \\lambda_i = 0\n\\]\nIf not, then, e.g. $\\lambda_0 \\neq 0$, assume $\\lambda_0 =-1$, and solve the equations to get \n\n\\[\n\\begin{gathered}\n\\mathbf{v}_0 = \\sum_{i=1}^n \\lambda_i \\mathbf{v}_i \\\\\n\\sum_{i=1}^n \\lambda_i = 1\n\\end{gathered}\n\\]\ni.e. $\\mathbf{v}_0$ is in affine space spanned by $\\mathbf{v}_1\\dots \\mathbf{v}_n$. \n\nIf $\\mathbf{v}_0, \\dots \\mathbf{v}_n$ affinely independent, then \n\\begin{equation}\n\\sigma = ( \\mathbf{v}_0, \\dots \\mathbf{v}_n) = \\lbrace \\sum_{i=0}^n \\lambda_i \\mathbf{v}_i | \\sum_{i=0}^n \\lambda_i = 1, \\, \\lambda_i \\geq 0 \\rbrace\n\\end{equation}\nis \"affine simplex\" spanned by $\\mathbf{v}_i$; also convex hull of $\\mathbf{v}_i$. \n\n$\\forall \\, k \\leq n$, $k$-face of $\\sigma$ is any affine simplex of form $(\\mathbf{v}_{i_1}, \\dots \\mathbf{v}_{i_k})$, where vertices all distinct, so are affinely independent. \n\n\\begin{definition}\n\t(geometric) simplicial complex $K:= $ collection of affine simplices s.t. \\begin{enumerate}\n\t\t\\item $\\sigma \\in K \\Longrightarrow $ any face of $\\sigma \\in K$; and \n\t\t\\item $\\sigma, \\tau \\in K \\Longrightarrow \\sigma \\bigcap \\tau $ is a face of both $\\sigma$ and $\\tau$, or $\\sigma \\bigcap \\tau =\\emptyset$\n\t\\end{enumerate}\n\nIf $K$ simplicial complex, $|K| = \\bigcup \\lbrace \\sigma | \\sigma \\in K \\rbrace \\equiv $ \"polyhedron\" of $K$\n\\end{definition}\n\n\\begin{definition}[Def. 21.2 of Bredon (1997) \\cite{Bred1997}]\n\tpolyhedron $:= $ space $X$ if $\\exists \\, $ homeomorphism $h: |K| \\xrightarrow{ \\approx } X$ for some simplicial complex $K$. \n\t$h,K$ is triangulation of $X$; (map $h$, complex $K$)\n\\end{definition}\n\nLet $K$ finite simplicial complex. \\\\\nChoose ordering of vertices $\\mathbf{v}_0,\\mathbf{v}_1\\dots $ of $K$. \\\\\nIf $\\sigma = (\\mathbf{v}_{\\sigma_0}, \\dots \\mathbf{v}_{\\sigma_n})$ is simplex of $K$, where $\\sigma_0 < \\dots < \\sigma_n$, then \\\\\n\\phantom{If } let $f_{\\sigma} : \\Delta_n \\to |K|$ be \n\\[\nf_{\\sigma} = [\\mathbf{v}_{\\sigma_b}, \\dots \\mathbf{v}_{\\sigma_n}]\n\\]\nin notation of Def. 1.2. Bredon (1997) \\cite{Bred1997}. \n\nThen this gives CW-complex structure on $|K|$ with $f_{\\sigma}$ as characteristic maps. \n\n\n\n\n\\part{Graphs, Finite Graphs}\n\n\\section{Graphs, Finite Graphs, Trees }\n\nSerre (1980) \\cite{Serr1980} \n\ncf. Chapter I. Trees and Amalgams, Section 1 Amalgams, Subsection 1.1 Direct limits of Serre (1980) \\cite{Serr1980} \n\n\nLet $(G_i)_{i\\in I}$, family of groups. \n\n$\\forall \\, $ pair $(i,j)$, let $F_{ij} = $ set of homomorphisms of $G_i$ into $G_j$\n\nWant: group $G= \\varinjlim G_i$ and \n\\[\n\\lbrace f_i | f_i : G_i \\to G \\rbrace \\text{s.t. } f_j \\circ f = f_i \\quad \\, \\forall \\, f \\in F_{ij}\n\\]\ngroup $G$ and family $\\lbrace f_i\\rbrace$ universal in that \n\n(*) if $H$ group, if $\\lbrace h_i | h_i :G_i \\to H ; h_j \\circ f = h_i \\qquad \\, \\forall \\, f \\in F_{ij} \\rbrace$, \\\\\nthen $\\exists \\, ! h: G\\to H$ s.t. $h_i = h\\circ f_i$ \\\\\ni.e. $\\text{Hom}(G,H) \\simeq \\varprojlim \\text{Hom}(G_i,H)$, the inverse limit being taken relative to $F_{ij}$. \\\\\ni.e. $G$ direct limit of $G_i$ relative to the $F_{ij}$. \n\nEY : 20170918 this is my rewrite/reinterpretation:\n\nLet $(G_i)_{i\\in I}$, $\\forall \\, (i,j) \\in I^2$, let $F_{ij} = \\lbrace f \\equiv f_{ij} | f:G_i \\to G_j , f \\text{ homomorphism of $G_i$ into $G_j$ } \\rbrace$. \n\nGiven group $G = \\varinjlim G_i$ (for fixed $i$), $\\lbrace f_i | f_i : G_i \\to G | f_j \\circ f = f_i \\quad \\, \\forall \\, f \\in F_{ij} \\rbrace$, i.e. \n\n\\begin{tikzpicture}\n\\matrix(m)[matrix of math nodes, row sep=4em, column sep=8em]\n{\nG_i & G \\\\\nG_j & \\\\};\n\\path[->]\n(m-1-1) edge node[auto]{$f_i$} (m-1-2)\nedge node[auto]{$f_{ij} \\equiv f$} (m-2-1) \n(m-2-1) edge node[right]{$ f_j$ } (m-1-2);\n\\end{tikzpicture} \n\nThen $G$, $\\lbrace f_i | f_i : G_i \\to G | f_j \\circ f = f_i \\quad \\, \\forall \\, f \\in F_{ij} \\rbrace$ \\textbf{universal} \\\\\n\\phantom{Then } if $\\forall \\, $ group $H$, $\\forall \\, \\lbrace h_i | h_i : G_i \\to H | h_j \\circ f = h_i \\quad \\, \\forall \\, f \\in F_{ij} \\rbrace$, \\\\\n\\phantom{Then if } then $\\exists \\, ! \\ h : G\\to H$, s.t. $h_i = h \\circ f_i$ i.e. \n\\begin{tikzpicture}\n\\matrix(m)[matrix of math nodes, row sep=4em, column sep=8em]\n{\nH & G_i & G \\\\\n& G_j & \\\\};\n\\path[->]\n(m-1-2) edge node[auto]{$f_i$} (m-1-3)\nedge node[auto]{$f_{ij} \\equiv f$} (m-2-2) \nedge node [auto]{$h_i$} (m-1-1)\n(m-2-2) edge node[right]{$ f_j$ } (m-1-3)\nedge node [auto]{$h_j$} (m-1-1) \n(m-1-3) edge[bend right = 30] node [auto]{ $\\exists \\, ! h$ } (m-1-1) \n;\n\\end{tikzpicture} \n\n\n\n\n\n\n\\begin{proposition}\n\t$\\exists \\, !$ pair $G$, family $(f_i)_{i\\in I}$, i.e. (pair consisting of $G, (f_i)_{i\\in I}$, unique up to unique isomorphism. \n\\end{proposition}\n\\begin{proof}\nDefine $G$ by generators and relations. \\\\\nTake generating family to be disjoint union of those for $G_i$. \\\\\nrelations - $xyz^{-1}$ where $x,y,z \\in G_i$, $z=xy \\in G_i$ \\\\\n\\phantom{relations - } $xy^{-1}$ where $x\\in G_i$, $y \\in G_j$, $y=f(x)$ for at least $f\\in F_{ij}$. \n\nThus, existence of $G,\\lbrace f_i\\rbrace$. \n\n$G$ represents functor $H\\mapsto \\varprojlim \\text{Hom}{(G_i,H)}$. \n\nThus, uniqueness (also from universal property). \n\\end{proof}\n\ne.g. groups $A,G_1,G_2$, homomorphisms $\\begin{aligned} & \\quad \\\\ \n& f_1 : A \\to G_1 \\\\\n& f_2 : A \\to G_2 \n\\end{aligned}$. \n\n$G$ obtained by amalgamating $A$ in $G_1,G_2$ by $f_1,f_2 \\equiv G_1 *_A G_2$. \\\\\n1 can have $G=\\lbrace 1 \\rbrace$, even though $f_1,f_2$ non-trivial. \n\n\\emph{Application}: (Van Kampen Thm.)\n\nLet topological space $X$ be covered by open $U_1,U_2$. \\\\\nSuppose $U_1,U_2, U_{12}=U_1\\bigcap U_2$ arcwise connected. \n\nLet basept. $x\\in U_{12}$. \n\nThen $\\pi_1(X;x)$ obtained by taking 3 groups \n\\[\n\\pi_1(U_1;x), \\pi_1(U_2;x), \\pi_1(U_{12};x)\n\\]\nand amalagamating them according to homomorphism\n\\[\n\\begin{aligned}\n& \\pi_1(U_{12};x) \\to \\pi_1(U_1;x) \\\\\n& \\pi_1(U_{12};x) \\to \\pi_1(U_2;x)\n\\end{aligned}\n\\]\n\n\\exercisehead{1} \nLet homomorphisms $\\begin{aligned} & \\quad \\\\\n\t& f_1 : A \\to G_1 \\\\ \n\t& f_2: A \\to G_2 \\end{aligned}\n$\namalgam $G=G_1 *_A G_2$. \n\nDefine subgroups $A^n,G_1^n, G_2^n$, of $A,G_1,G_2$ recursively by \n\\[\n\\begin{aligned}\n& A^1 = \\lbrace 1 \\rbrace \\\\\n& G_1^1 = \\lbrace 1 \\rbrace \\\\ \n& G_2^1 = \\lbrace 1 \\rbrace \\\\ \n\\end{aligned}\n\\]\n\n$A^n = $ subgroup of $A$ generated by $f_1^{-1}(G_1^{n-1})$ and $f_2^{-1}(G_2^{n-1})$ \n\\[\nG_1^n = \\text{subgroup of $G_i$ generated by $f_i(A^n)$ }\n\\]\n\nLet $A^{\\infty}, G_i^{\\infty}$ be unions of $A^n, G_i^n$ resp. \n\nShow that $f_i$ defines injection $A/A^{\\infty} \\to G_i/G_i^{\\infty}$. \n\nSo the amalgamation is $G \\simeq G_1/G_1^{\\infty} *_{A/A^{\\infty}} G_2/G_2^{\\infty}$. \n\nTake the first induction case (for intuition about the solution). \n\n\\[\n\\begin{aligned}\n\t& A^2 = \\langle f_1^{-1}( G_1^1), f_2^{-1}(G_2^1) \\rangle = \\langle f_1^{-1}(\\lbrace 1 \\rbrace), f_2^{-1}(\\lbrace 1 \\rbrace ) \\rangle \\\\\n\t& G_i^2 = f_i(A^2)\n\\end{aligned}\n\\]\nLet $f_i(a) = f_i(b) \\in G_i/G_i^{\\infty}$; $a,b\\in A/A^{\\infty}$. \n\nThen since $f_i(a),f_i(b) \\in G_i/G_i^{\\infty}$, $f_i(a),f_i(b) \\in \\lbrace gG_i^{\\infty} | g\\in G_i \\rbrace$ (quotient is defined to be the set of all left cosets of $G_i^{\\infty}$, which has to be a normal subgroup for $G_i/G_i^{\\infty}$ to be a quotient group). \n\nSince $a,b \\in A/A^{\\infty}$, suppose we take $a,b\\in A$. \n\nAnd suppose we take \n\\[\n\\begin{aligned}\n& \tf_i(a) = f_i(a)G_i^{\\infty} = f_i(a) f_i(A^{n_a} ) = f_i(aA^{n_a}) \\\\ \n& \tf_i(b) = f_i(b)G_i^{\\infty} = f_i(b) f_i(A^{n_b} ) = f_i(bA^{n_b}) \n\\end{aligned}\n\\]\nTaking $f_i^{-1}$ (recall for group homomorphisms, they map inverse of element of 1st. group to inverse of image of this element). \n\n$aA^{n_a}=bA^{n_b}\\in A/A^{\\infty}$ (This is okay as we've \"quotiented out $A^{\\infty}$; so indeed, they're equal)\n\n\ncf. Subsection 1.2 Structure of amalgams of Serre (1980) \\cite{Serr1980} \n\nSuppose given group $A$, family of groups $(G_i)_{i\\in I}$, and, $\\forall \\, i\\in I$, injective homomorphism $A\\to G_i$. \n\n$*_A G_i \\equiv $ direct limit (cf. no. 1.1) of family $(A,G_i)$ with respect to these homomorphisms, call it \\emph{sum} (in category theory sense, i.e. product) of $G_i$ with $A$ amalgamated. \n\ne.g. $A=\\lbrace 1 \\rbrace$, \\\\\n$*G_i \\equiv $ free product of $G_i$. \n\n\\subsubsection{reduced word} \n\n$\\forall \\, i \\in I$, choose set $S_i$ of right coset representations of $G_i$ modulo $A$, \n\nassume $1 \\in S_i$, \n\n$(a,s)\\mapsto as$ is bijection of $A\\times S_i$ onto $G_i$, \\\\\n$A\\times (S_i-\\lbrace 1 \\rbrace) \\to G_i-A$ (onto)\n\nLet $\\mathbf{i} = (i_1\\dots i_n)$, $n\\geq 0$, $i_j \\in I$, s.t. \n\\begin{equation}\ni_m \\neq i_{m+1} \\text{ for } 1 \\leq m \\leq n-1\n\\end{equation}\ncf. (T) of Serre (1980) \\cite{Serr1980}. \n\nSo \\emph{reduced word} $m$ is defined as \n\\[\nm = (a;s_1\\dots s_n)\n\\]\nwhere $a\\in A, s_1\\in S_{i_1} \\dots s_n \\in S_{i_n}$, and $s-j \\neq 1\\, \\forall \\, j$. \n\n$f\\equiv $ canonical homomorphism of $A$ into group $G= *_A G_i$ \\\\ \n$f_i \\equiv $ canonical homomorphism of $G_i$ into group $G= *_A G_i$\n\nEY : 20170611 (Further explanations, basic examples, from me): \n\nGiven $A, \\lbrace G_i\\rbrace_{i\\in I}$, injective (group) homomorphisms $\\lbrace f_i: A \\to G_i\\rbrace_i$. \n\n$G_i \\backslash f_i(A) = \\lbrace f_i(A)g | g\\in G_i\\rbrace$. \n\nRight coset representation of $f_i(A)g\\mapsto g$. \n\ne.g. $A,G_1,G_2$, $\\begin{aligned} & \\quad \\\\\n\t& f_1:A \\to G_1 \\\\\n\t\t& f_2 : A\\to G_2 \\end{aligned}$. \n\t\t\n\t\\[\n\t\\begin{aligned}\n\t& G_1\\backslash f_1(A) = \\lbrace f_1(A)g| g\\in G_1\\rbrace \\\\\n\t& G_2\\backslash f_2(A) = \\lbrace f_2(A)g | g\\in G_2 \\rbrace\n\t\\end{aligned}\n\t\\]\n\n$\\mathbf{i} = (i_1\\dots i_n)$, $i_j\\in I$, $i_m\\neq i_{m+1}$ for $1\\leq m \\leq n-1$. \n\nConsider $(1212\\dots 12)$ \n\n$m=(a;f_1 g_2 f_3 g_4 \\dots f_{2n-1}, g_{2n})$ where $f$'s $\\in S_1 \\subset G_1$, $g$'s $\\in S_2 \\subset G_2$. \n\nand so \n\\begin{definition}[reduced word]\n\t\\textbf{reduced word} of type $\\mathbf{i}$, $m$, \\begin{equation}\n\tm=(a;s_1\\dots s_n)\n\t\\end{equation}\n\twhere $a\\in A, s_1 \\in S_{i_1}, \\dots s_n \\in S_{i_n}$, $s_j\\neq 1$ \\, $\\forall \\, j$, \\\\\n\t\\phantom{where } $\\mathbf{i} = (i_1\\dots i_n)$, $i_j \\in I$, s.t. $i_m \\neq i_{m+1}$ for $1\\leq m \\leq n-1$, \\\\\n\twith $S_i = \\lbrace g | g\\in f_i(A)g \\in f_i(A) G_i\\rbrace$ \n\\end{definition}\n\n\n\n\n\\begin{theorem}[1 of Serre (1980) \\cite{Serr1980} ]\n\t$\\forall \\, g \\in G$, $\\exists \\, $ sequence $\\mathbf{i}$ s.t. $i_m \\neq i_{m+1}$ for $1\\leq m \\leq n-1$ and \n\t\n\treduced word \n\t\\[\n\tm = (a;s_1\\dots s_n) \n\t\\]\n\tof type $\\mathbf{i}$ s.t. \n\t\\[\n\tg = f(a)f_{i_1}(s_1) \\dots f_{i_n}(s_n)\n\t\\]\n\\end{theorem}\n\nFurthermore, $\\mathbf{i}$ and $m$ unique. \n\n\\emph{Remark}. Thm. 1 implies $f;f_i$ injective. \n\nThen identify $A$ and $G_i$ with images $f(A), f_i(G_i)$ in $G$, and reduced decomposition (*) of $g\\in G$ \n\\[\ng = as_1\\dots s_n, \\quad \\, a\\in A, \\, s_1 \\in S_{i_1} - \\lbrace 1 \\rbrace \\dots s_n \\in S_{i_n} - \\lbrace 1 \\rbrace\n\\]\nLikewise, $G_i \\bigcap G_j = A$ if $i\\neq j$. \n\nIn particular, $S_i - \\lbrace 1 \\rbrace$ pairwise disjoint in $G$. \n\n\\begin{proof}\nLet $X_i \\equiv $set of reduced words of type $\\mathbf{i}$, $X = \\coprod X_i$. \n\nMake $G$ act on $X$. \n\nIn view of universal property of $G$, sufficient to make $\\forall \\, i, G_i$ act, \n\ncheck action induced on $A$ doesn't depend on $i$ \n\nSuppose then that $i\\in I$, and let $Y_i = $ set of reduced words of form $(1;s_1 \\dots s_n)$, with $i_1\\neq i$. \n\nEY : 20170611\n\nRecall that \n\\[\nS_i = \\lbrace g| g\\in f_i(A) g \\in f_i(A) G_i \\rbrace\n\\]\n\\[\n\\begin{aligned}\n\t& A \\times S_i \\to G_i \\text{ onto } \\\\ \n\t& A\\times (S_i - \\lbrace 1 \\rbrace) \\to G_i - A \\text{ onto } \\\\ \n\t& (a,s) \\mapsto as \\text{ bijection }\n\\end{aligned}\n\\]\n\nLet $Y_i = $ set of reduced words of form $(1; s_1 \\dots s_n) = \\lbrace (1;s_1 \\dots s_n) | 1\\in A; s_1 \\in S_{i_1}\\dots s_n \\in S_{i_n} ; \\mathbf{i} = (i_1\\dots i_n), \\, i_j \\in I \\text{ s.t. } i_m \\neq i_{m+1} \\text{ for } 1\\leq m \\leq n -1 \\rbrace$. \n\n\\[\n\\begin{gathered}\n\\begin{gathered}\nA \\times Y_i \\to X = \\coprod_i X_i \\\\\n(a,(1; s_1 \\dots s_n)) \\mapsto (a; s_1 \\dots s_n)\n\\end{gathered} \\\\\n\\begin{gathered}\nA\\times \\lbrace S_i - \\lbrace 1 \\rbrace ) \\times Y_i \\to X \\\\\n((a,s), (1;s_1 \\dots s_n)) \\mapsto (a;s,s_1\\dots s_n)\n\\end{gathered}\n\\end{gathered}\n\\]\nand remember that $X_i = $ set of reduced words of type $\\mathbf{i}$. \n\nIt's clear that this yields a bijection $A\\times Y_i \\bigcup A\\times (S_i - \\lbrace 1 \\rbrace) \\times Y_i \\to X$. \n\nLet $x\\in X$. Then $x\\in X_{\\mathbf{i}}$ for some $\\mathbf{i}$. So $x$ is a reduced word of type $\\mathbf{i}$: $x = (a;s_1\\dots s_n)$. Then clearly $x = (a;s_1\\dots s_n) \\mapsto (a,(1;s_1\\dots s_n)) \\in A\\times Y_i$. So $\\forall \\, x \\in X$, $\\exists (a, (1; s_1 \\dots s_n) \\in A \\times Y_i)$. So we've proven, for part of bijection, the mapping going one way. \\\\\n\nIdentify $A \\bigcup A \\times (S_i - \\lbrace 1 \\rbrace )$ with $G_i$, with \\\\\n\\phantom{Identify} $a \\in A$, \\, $A \\times (S_i - \\lbrace 1 \\rbrace) \\ni (a, s_i)$. \\\\\n\n$G_i$ act on $G_i \\times Y_i$ : \\\\\n\\[\n\\begin{aligned}\nG_i \\times (G_i \\times Y_i) & \\mapsto G_i \\times Y_i \\\\\ng' \\cdot (g, y) & = (g' g , y)\n\\end{aligned}\n\\]\n\n(group $G_i, Y_i \\equiv $ set of reduced words) \\\\\n\nTransfer this to an action of $G_i$ on $X$ by means of $\\theta_i$: \\\\\n\\[\n\\begin{aligned}\nG_i \\times X & \\mapsto X \\\\\ng' \\cdot (a, s_1, \\dots , s_n) & = (g'a, s_1 , \\dots s_n) \n\\end{aligned}\n\\]\n$X \\equiv $ set of reduced words of type $\\mathbf{i}$. \\\\\n\nrestriction to $A \\Longrightarrow a' \\cdot (a; s_1 , \\dots s_n ) = (a'a ; s_1, \\dots s_n)$, which doesn't depend on $i$.\n\nWe've now defined action of $G$ on $X$.\n\n\\end{proof}\n\n\ncf. pp. 13, Sec. 2. Trees, 2.1 Graphs of Serre (1980) \\cite{Serr1980}\n\n\\begin{definition}[1. of Serre (1980) \\cite{Serr1980}]\n\t\\textbf{graph} $\\Gamma = (X,Y, Y\\to X\\times X, Y\\to Y)$, where $\\begin{aligned} & \\quad \\\\\n\t\t& \\text{ set } X = \\text{ vert } \\Gamma \\\\ \n\t\t& \\text{ set } Y = \\text{ edge } \\Gamma \\end{aligned}$ \n\n\\[\n\\begin{aligned}\n& Y \\to X\\times X \\\\ \n& y\\mapsto (o(y), t(y)) \\\\\n& Y\\to Y \\\\\n& y\\mapsto \\overline{y}\n\\end{aligned}\n\\]\ns.t. $\\forall \\, y \\in Y$, $\\overline{ \\overline{y}} = y$, $\\overline{y} \\neq y$, $o(y) = t(\\overline{y})$. \n\nvertex $P \\in X$ of $\\Gamma$. \n\n(oriented) edge $y\\in Y$, $\\overline{y} \\equiv $ inverse edge. \n\norigin of $y := $ vertex $o(y) = t(\\overline{y})$. \n\nterminus of $y:= $ vertex $t(y) = o(\\overline{y})$ \n\nextremities of $y:= \\lbrace o(y),t(y)\\rbrace$ \n\nIf 2 vertices \\textbf{adjacent}, they're extremities of some edge. \n\norientation of graph $\\Gamma = Y_+ \\subset Y = \\text{ edge } \\Gamma$ s.t. $Y = Y_+ \\coprod \\overline{Y}_+$. It always exists. \n\noriented graph defined, up to isomorphism, by giving 2 sets $X,Y_+$ and $Y+ \\to X\\times X$. \n\t\n\tcorresponding set of edges is $Y = Y_+\\coprod \\overline{Y}_+$ where $\\overline{Y}_+ \\equiv $ copy of $Y_+$ \n\\end{definition}\n\n\\subsubsection{Realization of a Graph}\n\ncf. Realization of a Graph in Serre (1980) \\cite{Serr1980}. \n\nLet graph $\\Gamma$, $X = \\text{vert}\\Gamma$, $Y = \\text{edge}\\Gamma$.\n\ntopological space $T = X \\coprod Y \\times [0,1]$, where $X,Y$ provided with discrete topology. \n\nLet $R$ be finest equivalence relation on $T$ for which \n\\begin{equation}\n\\begin{gathered} \\begin{aligned}\n\t& (y,t) \\equiv (\\overline{y}, 1-t) \\\\ \n\t& (y,0) \\equiv o(y) \\\\\n\t& (y,1) \\equiv t(y)\n\\end{aligned} \\qquad \\, \\forall \\, y \\in Y, \\, \\forall \\, t \\in [0,1]\n\\end{gathered}\n\\end{equation}\n\nquotient space $\\text{real}(\\Gamma) = T/R $ is \\emph{realization} of graph $\\Gamma$. (realization is a functor which commutes with direct limits). \n\nLet $n\\in \\mathbb{Z}^+$. Consider oriented graph of $n+1$ vertices $0,1,\\dots n$, \\\\\n\n\\begin{definition}\n\tpath (of length $n$) in graph $\\Gamma$ is morphism $c$ of $\\mathbf{\\text{Path}}_n$ into $\\Gamma$ \n\\end{definition}\n\norientation given by $n$ edges $[i,i+1]$, $0\\leq i 2$) by $(y_1\\dots y_{i-1}, y_{i+2}\\dots y_n)$ \n\nIf $\\exists \\, $ path from $P$ to $Q$ in $\\Gamma$, $\\exists \\, $ one without backtracking (by induction) \n\ndirect limit $\\mathbf{\\text{Path}}_{\\infty} = \\varinjlim \\mathbf{\\text{Path}}_n$ provides notion of infinite path. \\\\\n$\\mathbf{\\text{Path}}_{\\infty} \\ni $ infinite sequence $(y_1,y_2 , \\dots)$ of edges s.t. $t(y_i) = o(y_{i+1})$ \\, $\\forall \\, i \\geq 1$. \n\n\n\\begin{definition}[connected graph; Def. 3 of Serre (1980) \\cite{Serr1980}]\n\tgraph connected if $\\forall \\, $ 2 vertices, 2 vertices are extremities of at least 1 path. \n\t\n\tmaximal connected subgraphs (under relation of inclusion) are \\emph{connected components} of graph. \n\\end{definition}\n\n\\subsubsection{Circuits} \n\nLet $n\\in \\mathbb{Z}^+$, $n\\geq 1$. \n\nConsider \\\\\nset of vertices $\\mathbb{Z}/n\\mathbb{Z}$, orientation given by $n$ edges $[i,i+1]$, $(i\\in \\mathbb{Z}/n\\mathbb{Z})$ with $\\begin{aligned} & \\quad \\\\\n & o([i,i+1]) = i \\\\\n & t([i,i+1]) = i+1 \\end{aligned}$\n\n\\begin{definition}[circuit; Def. 4 of Serre (1980) \\cite{Serr1980}]\n\tcircuit (length $n$) in graph is subgraph isormorphic to $\\mathbf{\\text{Circ}}_n$. \n\\end{definition}\ni.e. subgraph = path $(y_1\\dots y_n)$, without backtracking, s.t. $P_i = t(y_i)$, \\, $(1\\leq i \\leq n)$ distinct, s.t. $P_n = o(y_1)$\n\n$n=1$ case: $\\mathbf{\\text{Circ}}_1$, $\\mathbb{Z}/\\mathbb{Z} = \\lbrace 0 \\rbrace$, $1$ edge, $[0,1]$, $0 \\in \\mathbb{Z}/1\\mathbb{Z}$, $\\begin{aligned} & \\quad \\\\\n\t& o([0,1]) = 0 \\\\\n\t& t([0,1]) = 1 \\end{aligned}$ \n\t\n\tNote $\\mathbf{\\text{Circ}}_1$ has automorphism of order 2, which changes its orientation, i.e. \\\\\n\t$\\exists \\, $ automorphism $\\sigma \\in \\text{Aut}( \\mathbf{\\text{Circ}}_1) $ s.t. $|\\sigma | = 2$, i.e. $\\sigma^2=1$. \\\\\n\tloop $:= $ circuit of length $1$; so loop $\\in \\overline{ \\mathbf{\\text{Circ}} }_1$. \n\t\n\tpath $(y_1)$, $P_1 = t(y_1) = o(y_1)$. \n\t\n\t$n=2$ case: $\\mathbf{\\text{Circ}}_2$, $\\mathbb{Z}/2\\mathbb{Z} = \\lbrace 0 ,1\\rbrace$, 2 edges $[0,1], [1,2]$, \\\\\n\tpath $(y_1,y_2)$, $(1\\leq i \\leq 2)$, $\\begin{aligned} & \\quad \\\\\n\t\t& P_1 = t(y_1) \\\\\n\t\t& P_2 = t(y_2) = o(y_1) \\end{aligned}$ \n\t\t\n\t\t\n\t\n\n\\subsection{Combinatorial graphs}\n\nLet $(X,S)\\equiv $ simplicial complex of dim. $\\leq 1$, with \\\\\n$X \\equiv $ set \\\\\n$S \\equiv $ set of subsets of $X$ with $1$ or $2$ elements, containing all the 1-element subsets. \n\nassociates with it a graph $\\Gamma = (X, \\lbrace (P,Q) \\rbrace)$. \n\n$X$ is its set of vertices. \n\nedges $=\\lbrace (P,Q)\\in X\\times X\\rbrace$ s.t. $P\\neq Q$, $\\lbrace P ,Q \\rbrace \\in S$, with $\\overline{(P,Q)} = (Q,P)$\n\\[\n\\begin{aligned}\n& o(P,Q) = P \\\\\n& t(P,Q) = Q\n\\end{aligned}\n\\]\n\nIn this graph, 2 edges with same origin and same terminus are equal. This is equivalent to (see following Def.)\n\n\\begin{definition}[combinatorial; Def. 5 of Serre (1980) \\cite{Serr1980}]\n\tgraph is combinatorial if it has no circuit of length $\\leq 2$\n\\end{definition}\nConversely, it's easy to see that \n\nevery combinatorial graph $\\Gamma$ derived (up to isomorphism) by construction above from simplicial complex $(X,S)$, where \\\\\n$X = \\text{vert} \\Gamma$ \\\\\n$S=$ set of subset $\\lbrace P,Q \\rbrace$ of $X$ s.t. $P$ and $Q$ either adjacent or equal. \n\n\\part{Tensors, Tensor networks; Singular Value Decomposition, QR decomposition, Density Matrix Renormalization Group (DMRG), Matrix Product states (MPS)}\n\n\\section{Introductions to Tensor Networks}\n\nJos\\'{e} Barbon (IFT-CSIC, Univ. Autonoma de Madrid) gave the \\href{Workshop introductory overview}{https://youtu.be/nsxgAOAEgbg} for the workshop \"Black Holes, Quantum Information, Entanglement, and all that,\" (29 May-1 June, 2017, with the organizing committee of Thibault Damour (IHES), Vasily Pestun (IHES), Eliezer Rabinovici (IHES \\& Hebrew Univ. of Jerusalem). \n\nIn the talk, \n\n\ncf. \\href{https://youtu.be/nsxgAOAEgbg?t=43m13s}{43:13} \n\n\\subsection*{The church of the doubled Hilbert space}\n \nAny thermal box can be obtained by tracing over a second identical copy, if appropriately entangled into a global pure state. \n\n\\[\n\\rho_R = \\text{Tr}_L \\sum_n C_n \\Psi_n^L \\otimes \\Psi_n^R\n\\]\n\\[\n(C_n)_{\\text{thermal}} = \\left[ \\frac{ e^{-\\beta E_n} }{ \\sum_m e^{-\\beta E_M} } \\right]^{1/2}\n\\]\n\nBut!!\n\nIf the entanglement basis is taken to be the high-energy band of two \"entangled\" CFTs ... \n\\[\n|TFD \\rangle \\sim \\sum_{E_n} e^{-\\beta E_n/2} | E_n \\rangle_L \\otimes | E_n \\rangle_R\n\\]\nneglecting the tiny $e^{-S}$ spacings. we can approximate by continuous spectrum of fields in the background of an AdS black hole, to get ... \n \n\\[\n\\int_E e^{-\\beta E/2} |E\\rangle_L \\otimes | E\\rangle_R \n\\]\nThe HH state of the bulk fields! \n\ncf. \\href{https://youtu.be/nsxgAOAEgbg?t=46m16s}{46:16}\n\nSLOGAN: EPR $=$ ER\nMaldacena-Susskind \n\nAccumulating a density of entanglement of $S \\gg 1$ well-separated Bell pairs within a transversal size of order $(GS)^{1/2}$ seems to generate a geometrical bridge of area $GS$. \n\n\n\ncf. \\href{https://youtu.be/nsxgAOAEgbg?t=49m26s}{49:26} \n\n\\subsection*{Parametrizing complexity of entanglement}\n\nPick a tensor decomposition of Hilbert space of dimension $\\exp{(S)}$ into $S$ factors of $O(1)$ dimension. \n\\[\n\\mathcal{H} = \\mathcal{H}_1 \\otimes \\mathcal{H}_2 \\otimes \\dots \\otimes \\mathcal{H}_S\n\\]\nA tensor of S indices gives a generic state. \n\ncf. \\href{https://youtu.be/nsxgAOAEgbg?t=50m27s}{50:27} \n\nThe decomposition of the big tensor in small building blocks gives a notion of \"complexity of entanglement\" \n\nrather simple entanglement pattern \n\nsomewhat more complex entanglement pattern\n\npicture from M von Raamsdonk \n\ncf. \\href{https://youtu.be/nsxgAOAEgbg?t=55m10s}{55:10}\n\n\\subsection*{A list of open questions \\& problems}\n\n\\begin{itemize}\n\\item Need exactly calculable toy models of AdS/CFT along the lines of SYK model \n\\item Give a \"renormalized\" definition of quantum complexity for continuum CFTs \n\\item Can tensor networks describe bulk gravitons? \n\\item What is the space-time meaning of quantum complexity saturation? \n\\item Can we define approximate local observables for black hole inferiors? \n\\item Are there obstructions related to firewalls and/or fuzzballs? \n\\end{itemize}\n\n\\href{https://youtu.be/nsxgAOAEgbg}{Workshop introductory overview } by Jos\\'{e} Barbon for the \\href{https://www.youtube.com/channel/UC4R1IsRVKs_qlWKTm9pT82Q}{Institut des Hautes Études Scientifiques (IHÉS)} gave me the first impetus to understand tensor networks as I sought to also understand the condensates of entanglement pairs within the black hole. \n\nA Google search for introductions to tensor networks that are on arxiv (\"Introduction Tensor Network arxiv\") yielded Bridgeman and Chubb's course notes (bf. Bridgeman and Chubb (2017) \\cite{BrCh2017}). \n\n\\subsection{List of stuff I want to look at/do/study} \nI would like to compare/contrast the following: \n\\begin{itemize}\n\\item Rotman (2010) \\cite{JRotman2010}, Ch. 8, but starting from 8.4 Tensor Products, pp. 574 \n\\item Jeffrey Lee (2009) \\cite{JLee2009}, Ch. 7 Tensors \n\\item \\url{http://www.irisa.fr/sage/bernard/publis/SVD-Chapter06.pdf}, \\url{https://math.stackexchange.com/questions/694339/parallel-algorithms-for-svd}\n\\end{itemize}\n\n\n\nMaldacena and Susskind (2013) \\cite{MaSu2013} \n\nLectures on Gravity and Entanglement. Mark Van Raamsdonk \\cite{Raam2016}\n\n\\begin{itemize}\n\\item Consider as physical system AdS-Schwarzchild black hole \n\\item CFT \n\\begin{itemize}\n\\item \\href{https://arxiv.org/pdf/1601.05000.pdf}{PFL Lectures on Conformal Field Theory in $D\\geq 3$ Dimensions}, Rychkov (2016) \\cite{Rych2016}. \n\\end{itemize}\n\\end{itemize}\n\nEvenbly and Vidal (2011) \\cite{EvVi2011}, Tensor network states and geometry\n\nLoose ends (might not be useful links)\n\\begin{itemize}\n\\item \\url{https://arxiv.org/pdf/1506.06958.pdf}\n\\item \\url{https://arxiv.org/pdf/1512.02532.pdf} One-point Functions in AdS/dCFT from Matrix Product States\n\\end{itemize}\n\nNumerical implementation strategy: 1st, CUDA cuSolver, 2nd, Numerical Recepes version, 3rd, parallel algorithm review.\n\n\n\\subsection{Tensor operations; Tensor properties}\n\n\\subsubsection{rank}\n\n$r=$ rank tensor of dim. $d_1\\times \\dots \\times d_r$ is element of $\\mathbb{C}^{d_1\\times \\dots \\times d_r}$ \n\nTensor product\n\\begin{equation}\n\t[A \\otimes B]_{i_1 \\dots i_r, j_1 \\dots j_s } := A_{i_1 \\dots i_r} \\cdot B_{j_1 \\dots j_s }\n\\end{equation}\n\n\\subsubsection{Trace}\nGiven tensor $A$, $x$th, $y$th indices have identical dims. ($d_x = d_y$), \\\\\npartial trace over these 2 dims. is simply joint summation over that index\n\\begin{equation}\n\t[\\text{Tr}_{x,y} A]_{i_1\\dots i_{x-1}i_{x+1} \\dots i_{y-1}i_{y+1} \\dots i_r} = \\sum_{\\alpha=1}^{d_x} A_{i_1 \\dots i_{x-1} \\alpha i_{x+1} \\dots i_{y-1} \\alpha i_{y+1} \\dots i_r}\n\\end{equation}\n\n\\subsubsection{Contraction}\n\n\\subsubsection{Group and splitting, Bridgeman and Chubb (2017) \\cite{BrCh2017} }\n\n\"Rank is a rather fluid concept in the study of tensor networks.\" Bridgeman and Chubb (2017) \\cite{BrCh2017}. \n\n$\\mathbb{C}^{a_1 \\times \\dots \\times a_n} \\simeq \\mathbb{C}^{b_1 \\times \\dots \\times b_m}$ isomorphic as vector spaces if $\\prod_i a_i = \\prod_i b_i$. \n\nWe can \"group\" or \"split\" indices to lower or raise rank of given tensor, resp. \n\nConsider contracting 2 arbitrary tensors. \n\nIf we group together indices which are and are not involved in contraction, \\\\\n\"It should be noted that not only is this reduction to matrix multiplication pedagogically handy, but this is precisely the manner in which numerical tensor packages perform contraction, allowing them to leverage highly optimised matrix multiplication code.\" (cf. Bridgeman and Chubb (2017) \\cite{BrCh2017}; check this)\n\n\"Owing to freedom in choice of basis, precise details of grouping and splitting aren't unique.\" (cf. Bridgeman and Chubb (2017) \\cite{BrCh2017}). \n\n1 specific choice of convention: \\\\\ntensor product basis, defining basis on product space by product of respective bases. \n\n\"The canonical use of tensor product bases in quantum information allows for grouping and splitting described above to be - dealt with implicitly.\" \n\n\n\\begin{equation}\n | 0 \\rangle \\otimes | 1 \\rangle \\equiv | 0 \\rangle \n\\end{equation} and precisely this grouping, \n\\begin{equation}\n\\begin{gathered}\n\t| 0 \\rangle \\otimes | 1 \\rangle \\in \\text{Mat}_{\\mathbb{C}}(2,2), \\text{ whilst } \\\\ \n | 0 1 \\rangle \\in \\mathbb{C}^4 \n\\end{gathered}\n\\end{equation}\n\nSuppose rank $n+m$ tensor $T$, group its first $n$ indices, last $m$ indices together.\n\\[\nT_{I,J} := T_{i_1\\dots i_n,j_1\\dots j_m}\n\\]\nwhere \n\\[\n\\begin{aligned}\n\t& I := i_1 + d_1^{(i)} i_2 + d_1^{(i)} d_2^{(i)} i_3 + \\dots + d_1^{(i)} \\dots d_{n-1}^{(i)} i_n \\\\ \n\t& J := j_1 + d_1^{(j)} j_2 + d_1^{(j)} d_2^{(j)} j_3 + \\dots + d_1^{(j)} \\dots d_{m-1}^{j)} j_m \n\\end{aligned}\n\\]\n\nEY : 20170627 to elaborate, consider a functor \\verb|flatten| that does what's described above, in the context of category theory (and so this is the generalization):\n\n\\begin{equation}\n\\begin{gathered}\n\t\\mathbb{K}^{d_1^{(i)} } \\times \\mathbb{K}^{d_2^{(i)} } \\times \\dots \\times \\mathbb{K}^{d_n^{(i)} } \\times \\mathbb{K}^{d_1^{(j)} } \\times \\mathbb{K}^{d_2^{(j)} } \\times \\dots \\times \\mathbb{K}^{d_m^{(j)} } \\xrightarrow{ \\text{ flatten } } \\mathbb{K}^{ \\prod_{p=1}^n d_p^{(i)} } \\times \\mathbb{K}^{ \\prod_{q=1}^m d_q^{(j)} } \\\\\nT_{i_1 \\dots i_n, j_1 \\dots j_m } \\xmapsto{ \\text{ flatten } } T_{I,J} \\\\\n\\lbrace 0 ,1, \\dots d_1^{(i)} \\rbrace \\times \\lbrace 0 ,1, \\dots d_2^{(i)} \\rbrace \\times \\dots \\times \\lbrace 0 ,1, \\dots d_n^{(i)} \\rbrace \\times \\lbrace 0 ,1, \\dots d_1^{(j)} \\rbrace \\times \\lbrace 0 ,1, \\dots d_2^{(j)} \\rbrace \\times \\dots \\times \\lbrace 0 ,1, \\dots d_m^{(j)} \\rbrace \\xrightarrow{ \\text{ flatten } } \\\\\n\\xrightarrow{ \\text{ flatten } } \\lbrace 0 ,1, \\dots \\prod_{p=1}^n d_p^{(i)} -1 \\rbrace \\times \\lbrace 0 ,1, \\dots \\prod_{q=1}^m d_q^{(j)} - 1 \\rbrace \\\\\n(i_1,i_2, \\dots i_n, j_1,j_2 \\dots j_m ) \\xmapsto{ \\text{ flatten } } (I,J) := (i_1 + d_1^{(i)} i_2 + \\dots + d_1^{(i)} \\dots d_{n-1}^{(i)} i_n ,j_1 + d_1^{(j)} j_2 + \\dots + d_1^{(j)} \\dots d_{m-1}^{(j)} j_m ) \\\\ \n\\end{gathered}\n\\end{equation}\nIt doesn't make sense to call this \"row-major\" or \"column-major\" ordering generalization, because we are not dealing with only 2 indices where we can definitely say the first index indexes the \"row\" and the second index indexes the \"column.\" At most, possibly, you can alternatively have this:\n\\[\n(i_1 \\dots i_n,j_1\\dots j_m) \\xmapsto{ \\text{ flatten } } (I,J) := (d_2^{(i)} \\dots d_n^{(i)}i_1 + d_3^{(i)} \\dots d_n^{(i)} i_2 + \\dots + i_n , d_2^{(j)} \\dots d_m^{(j)} j_1 + \\dots + j_m )\n\\]\nNote that this is all \\emph{$0$-based counting} (i.e. we start counting from $0$ just like in C,C++,Python, etc.). If you really wanted $1$-based counting, you'd have to complicate the above formulas as such:\n\\[\n\\begin{gathered}\n(I,J) := (i_1 + d_1^{(i)} (i_2-1) + \\dots + d_1^{(i)} \\dots d_{n-1}^{(i)} (i_n-1) ,j_1 + d_1^{(j)} (j_2-1) + \\dots + d_1^{(j)} \\dots d_{m-1}^{(j)} (j_m-1) ) \\\\ \n\\end{gathered}\n\\]\nNote that formulas are easily checked by pluggin in the minimum and maximum values for the indices and seeing if they make sense (e.g. plug in $(0,0,\\dots ,0)$ for all indices for $0$-based counting and make sure you get back $I=0$ or $J=0$). \n\n\\subsection{Singular Value Decomposition} \n\n\\begin{equation}\n\\begin{gathered}\n\tT_{I,J} = \\sum_{\\alpha} U_{I,\\alpha} S_{\\alpha,\\alpha} \\overline{V}_{J,\\alpha} \\\\ \n \\text{Mat}_{\\mathbb{K}}(N,M) \\xrightarrow{ \\text{ SVD } } \\text{Mat}_{\\mathbb{K}}(N,P) \\times \\text{Mat}_{\\mathbb{K}}(P,P) \\times \\text{Mat}_{\\mathbb{K}}(M,P) \\\\\n\tT_{I,J} \\xmapsto{ \\text{ SVD } } U_{I,\\alpha}, S_{\\alpha,\\alpha} , \\overline{V}_{I,\\alpha} \\text{ s.t. } \\\\\nT_{I,J} = \\sum_{\\alpha} U_{I,\\alpha} S_{\\alpha, \\alpha} \\overline{V}_{J,\\alpha} \\\\\nT=USV^{\\dag}\n\\end{gathered}\n\\end{equation}\nFor the higher-dimensional version of SVD, \n\\begin{equation}\n\\begin{gathered}\n\t\\mathbb{K}^{d_1^{(i)} } \\otimes \\dots \\otimes \\mathbb{K}^{d^{(i)}_N} \\otimes \\mathbb{K}^{d_1^{(j)} }\\otimes \\dots \\otimes \\mathbb{K}^{d_M^{(j)} } \\xrightarrow{ \\text{ flatten } } \\text{Mat}_{\\mathbb{K}}(N,M) \\xrightarrow{ \\text{ SVD } } \\text{Mat}_{\\mathbb{K}}(N,P) \\times \\text{Mat}_{\\mathbb{K}}(P,P) \\times \\text{Mat}_{\\mathbb{K}}(M,P) \\xrightarrow{ \\text{ splitting } } \\\\ \n\\xrightarrow{ \\text{ splitting } } \\mathbb{K}^{d_1^{(i)} } \\otimes \\dots \\otimes \\mathbb{K}^{d^{(i)}_N} \\otimes \\mathbb{K}^P \\times \\text{Mat}_{\\mathbb{K}}(P,P) \\times \\mathbb{K}^{d_1^{(j)} }\\otimes \\dots \\otimes \\mathbb{K}^{d_M^{(j)} } \\otimes \\mathbb{K}^P \\\\\nT_{i_1\\dots i_N,j_1 \\dots j_M} = \\sum_{\\alpha} U_{i_1\\dots i_N,\\alpha} S_{\\alpha,\\alpha} \\overline{V}_{j_1 \\dots j_M, \\alpha}\n\\end{gathered}\n\\end{equation}\n\n\\section{Density Matrix Renormalization Group; Matrix Product States (MPS)}\n\n\\subsection{Introduction; physical system (physical setup)}\n\ncf. \"Density Matrix Renormalization Group/Matrix Product States\" lectures by Schollw\\\"{o}ck (2017) \\cite{ArSo2017}.\n\nRecall the fundamental Hamiltonian (frequently in solid state physics), for \\emph{electrons moving in a Hamiltonian potential}. \n\\begin{equation}\nH = \\sum_{j=1}^{ e^-} \\frac{\\mathbf{p}_j^2}{ 2m_e} + \\frac{1}{2} \\frac{1}{ 4\\pi \\epsilon_0} \\frac{q_e^2}{ |\\mathbf{r}_i - \\mathbf{r}_j|^2 } + \\sum_{j=1}^{e^-} V_{\\text{eff}}(\\mathbf{r}_j)\n\\end{equation}\nwhere $\\frac{\\mathbf{p}_j^2}{ 2m_e}$ is the kinetic energy term, $\\sum_{j=1}^{e^-} V_{\\text{eff}}(\\mathbf{r}_j)$ is the lattice potential.\nThe problem is in the 2nd. term, electron-electron interaction, $\\frac{1}{2} \\frac{1}{ 4\\pi \\epsilon_0} \\frac{q_e^2}{ |\\mathbf{r}_i - \\mathbf{r}_j|^2 }$\n\nTypical models include the following:\n\n\\begin{itemize}\n\t\\item Hubbard model (tight, binding-like model; basis states are not energy states but \\emph{Wannier basis} states):\n\t\\begin{equation}\n\tH = -t \\sum_{ \\langle i, j \\rangle, \\sigma } c^{\\dag}_{i \\sigma} c_{j \\sigma} + h.c. + U \\sum_i n_{i \\uparrow} n_{i \\downarrow }\n\t\\end{equation}\n\twhere $\\langle i, j \\rangle$ denotes nearest neighbors, $\\sigma$ index is for all possible states, $h.c.$ stands for hermitian conjugate, and \\\\\n\t$d \\equiv$ number of states of single spin site. \\\\\n\t$-t \\sum_{ \\langle i, j \\rangle, \\sigma } c^{\\dag}_{i \\sigma} c_{j \\sigma} + h.c.$ is the kinetic energy term, \\\\\n\t$U \\sum_i n_{i \\uparrow} n_{i \\downarrow }$ is the Coulomb energy.\n\t\n\tHilbert space for the Hubbard model is \n\t\\begin{equation}\n\t\\lbrace | \\emptyset \\rangle , | \\uparrow \\rangle , | \\downarrow \\rangle , | \\uparrow \\downarrow \\rangle \\rbrace^{ \\otimes L}, \\qquad \\, d = 4\n\t\\end{equation}\n\t\\item Heisenberg model (large -$U$ Hubbard at half-filling)\n\t\\begin{equation}\n\tH = J \\sum_{ \\langle i , j \\rangle } \\mathbf{S}_i \\cdot \\mathbf{S}_j = J \\sum_{ \\langle i, j \\rangle } \\frac{1}{2} (S_i^{+} S_j^- + S_j^{+} S_i^-) + S_i^z S_j^z )\n\t\\end{equation}\n\tHilbert space $\\lbrace | \\uparrow \\rangle, | \\downarrow \\rangle \\rbrace^{\\otimes L}$, $d=2$ \n\\end{itemize}\n\n\\subsubsection{Compression of information viewpoint for solid-state Hamiltonians, quantum many-body systems}.\n\n\"emergent\" macroscopic quantities, $\\tau, p$ (temperature, pressure). For \n\\[\n\tH = J \\sum_{ \\langle i , j \\rangle } \\mathbf{S}_i \\cdot \\mathbf{S}_j = J \\sum_{ \\langle i, j \\rangle } \\frac{1}{2} (S_i^{+} S_j^- + S_j^{+} S_i^-) + S_i^z S_j^z )\n\\]\n\n$H$ as classical spins: thermodynamic limit $N \\to \\infty$. 2 angles required to describe unit vector on unit sphere ($S^3$) $\\Longrightarrow 2N $ degrees of freedom (linear)\n\nquantum spins: superposition of states, thermodynamic limit: $N \\to \\infty$, $2^N$ degrees of freedom (exponential).\n\n\\subsubsection{Definitions; notation and conventions}\n\nQuantum system living on $L$ lattice sites; cf. Schollw\\\"{o}ck (2017) \\cite{ArSo2017}, lattice can be in any dim., effectively most useful in 1-dim., think of the example of a 1-dim. chain of $L$ sites. \\\\\n\n$d$ local states per site $\\lbrace \\sigma_i \\rangle$, $i \\in \\lbrace 1,2, \\dots L\\rbrace$\n\ne.g. spin $\\frac{1}{2}$, $d=2$, $| \\uparrow \\rangle, | \\downarrow \\rangle$.\n\nHilbert space: $\\mathcal{H} = \\otimes_{i=1}^L \\mathcal{H}_i$, $\\mathcal{H}_i = \\lbrace | 1_i \\rangle , \\dots | d_i \\rangle \\rbrace$. \n\nNotice, there are \\emph{exponentially many coefficients}, $c$'s. Most general state (not necessarily 1-dim.) is \n\\begin{equation}\n|\\psi \\rangle = \\sum_{\\sigma_1 \\dots \\sigma_L} c^{\\sigma_1 \\dots \\sigma_L} | \\sigma_1 \\dots \\sigma_L \\rangle\n\\end{equation}\n\nabbreviations: $\\lbrace \\sigma \\rbrace = \\sigma_1 \\dots \\sigma_L$. And so we can write $c^{\\lbrace \\sigma \\rbrace}$. \n\n\\subsection{MPS, matrix product states}\n\n\\begin{equation}\n| \\psi \\rangle = \\sum_{\\sigma_1 \\dots \\sigma_L} M^{\\sigma_1} M^{\\sigma_2} \\dots M^{\\sigma_L} | \\sigma_1 \\sigma_2 \\dots \\sigma_L \\rangle\n\\end{equation}\n\nThe $\\sum_{\\sigma_1 \\dots \\sigma_L}$ means that all basis states participate; Schollw\\\"{o}ck is not kicking out any states arbitrarily. \n\\[\nc^{\\lbrace \\sigma \\rbrace} = M^{\\sigma_1} M^{\\sigma_2} \\dots M^{\\sigma_L} \\in \\mathbb{C}\n\\] so\n\n$M^{\\sigma_1} \\in \\text{Mat}_{\\mathbb{C}}(1, n_1)$ so to get a scalar in the product of matrices. Likewise, $M^{\\sigma_L} \\in \\text{Mat}_{\\mathbb{C}}(m_L, 1)$\n\n(variational) constraint is in expansion coefficients. \n\n$\\forall \\, $ $d$ local basis states, $|\\sigma_i \\rangle \\in V_i \\equiv V$,$\\text{dim}V = d$, let there be 1 matrix $M$, i.e. $M^{\\sigma_i}$. \\\\\nThus, $dL$ matrices altogether (in total).\n\nAssume matrix size has upper limit $D$ (a computer limitation).\n\nUp to $dLD^2$ coefficients, instead of exponentially many ($c^{\\lbrace \\sigma \\rbrace}$, and sum over $\\lbrace \\sigma \\rbrace$). \n\n\\subsubsection{Product States and MPS}\n\nMean-filed approximation/product state misses essential quantum feature: \\textbf{entanglement}. \n\nConsider 2 spin $\\frac{1}{2}$ systems: $\\mathcal{H} = \\mathcal{H}_1 \\otimes \\mathcal{H}_2$, $\\mathcal{H}_i = \\lbrace | \\uparrow \\rangle, | \\downarrow \\rangle \\rbrace$\n\nGeneral state is \n\\[\n| \\psi \\rangle = c^{ \\uparrow \\uparrow} | \\uparrow \\uparrow \\rangle + c^{ \\uparrow \\downarrow} | \\uparrow \\downarrow \\rangle + c^{ \\downarrow \\uparrow} | \\downarrow \\uparrow \\rangle + c^{ \\downarrow \\downarrow} | \\downarrow \\downarrow \\rangle \n\\]\n\ne.g. singlet state: $|\\psi \\rangle = \\frac{1}{ \\sqrt{2} } | \\uparrow \\downarrow \\rangle - \\frac{1}{ \\sqrt{2} } | \\downarrow \\uparrow \\rangle $. \n\nAs an exercise, show that the singlet state cannot be written as product of local coefficients, i.e. \n\\[\nc_{\\uparrow \\downarrow } \\neq c^{\\uparrow} c^{ \\downarrow }\n\\]\n\nInstead of writing products of scalars, write product of matrices, i.e. $e^{\\sigma_1} \\cdot e^{\\sigma_2} \\to M^{\\sigma_1} M^{\\sigma_2}$\n\n\\[\n\\begin{gathered}\n\\begin{aligned}\n\t& M^{\\uparrow 1} = \\left[ \\begin{matrix} 1 & 0 \\end{matrix} \\right]\n\t& M^{\\downarrow 1} = \\left[ \\begin{matrix} 0 & 1 \\end{matrix} \\right] \n\t\\end{aligned} \\quad \\quad \\, \\begin{aligned}\n\t& M^{\\uparrow 2 } = \\left[ \\begin{matrix} 0 \\\\ \\frac{-1}{\\sqrt{2}} \\end{matrix} \\right] \\\\\n\t& M^{\\downarrow 2} = \\left[ \\begin{matrix} \\frac{1}{\\sqrt{2}} \\\\ 0 \\end{matrix} \\right] \n\t\\end{aligned}\n\\end{gathered}\n\\]\n\n\\[\n\\begin{gathered}\nM^{\\uparrow 1} M^{\\downarrow 2} = \\frac{1}{\\sqrt{2}} \\\\ \nM^{\\downarrow 1} M^{\\uparrow 2} = \\frac{-1}{\\sqrt{2}} \n\\end{gathered}\n\\]\n\n\\subsubsection{AKLT model (Affleck-Kennedy-Lieb-Tasaki)}\n\nMPS is useful even for matrices of dim. 2.\n\n\n\\subsection{General matrix product state (MPS) and SVD (Singular Value Decomposition)}\n\ncf. Schollw\\\"{o}ck (2017) \\cite{ArSo2017}\n\nThe general matrix product state (MPS) is the following:\n\\begin{equation}\n|\\psi \\rangle = \\sum_{ \\sigma_1 \\dots \\sigma_L } M^{\\sigma_1} M^{\\sigma_2} \\dots M^{\\sigma_L} | \\sigma_1 \\sigma_2 \\dots \\sigma_L \\rangle\n\\end{equation}\nwhere $\\sigma_i \\in V_i$, $\\text{dim}V_i = d_i$ and \\\\\n$M^{\\sigma_1} \\in \\text{Mat}_{\\mathbb{C}}(1, D_1)$ \\\\ \n$M^{\\sigma_2} \\in \\text{Mat}_{\\mathbb{C}}(D_1, D_2)$ \\\\ \n$\\vdots$ \\\\ \n$M^{\\sigma_{L-1}} \\in \\text{Mat}_{\\mathbb{C}}(D_{L-2}, D_{L-1})$ \\\\ \n$M^{\\sigma_L} \\in \\text{Mat}_{\\mathbb{C}}(D_{L-1}, 1)$ \\\\ \n\nNotice the non-unique \\textbf{gauge degree of freedom}:\n\n$\\forall \\, A \\in \\text{Mat}_{\\mathbb{C}}(m,n)$, then for $k = \\min{(m,n)}$, \n\\begin{equation}\n\\begin{gathered}\nA = U SV^{\\dagger} \\equiv U \\Sigma V^{\\dagger} \\text{ where }\n\\end{gathered}\n\\end{equation}\n\n$U \\in \\text{Mat}_{\\mathbb{C}}(m,k)$, $U^{\\dagger} U =1$ (i.e. $U$ consists of orthonormal columns, or $k$ number of $u$'s $\\in \\mathbb{C}^m$); if $m=k$, $UU^{\\dagger} = 1$, \\\\\n$S \\in \\text{Mat}_{\\mathbb{C}}(k,k)$ s.t. $S \\in \\text{diag}_{\\mathbb{C}}(k)$, $s_1 \\geq s_2 \\geq s_3 \\geq \\dots s_i \\geq 0$, $s_j$'s non-negative \"singular values\" (adjacent \"singular\" in name doesn't imply anything), non-vanishing = $\\text{rank} r \\leq k$. \\\\\n$V^{\\dagger} \\in \\text{Mat}_{\\mathbb{C}}(k,n)$, $V^{\\dagger} V = 1$, (orthonormal rows, or $k$ number of $v\\in \\mathbb{C}^n$); if $k=n $, $VV^{\\dagger} = 1$\n\nRecall eigenvalue equation and thus so-called eigenvalue decomposition.\n\nFor $A \\in \\text{Mat}_{\\mathbb{C}}(m,m)$, \n\\[\n\\begin{gathered}\n\tAu_j = \\lambda_j u_j ; \\qquad \\, j =1 \\dots r ; \\, r \\equiv \\text{ rank }, \\quad \\, u_j \\in \\text{Mat}_{\\mathbb{C}}(m, 1) \\\\\n\tA_{ik} u_{kj} = \\lambda_j u_{ij} = u_{ik} \\delta_{kj} \\lambda_j \\Longrightarrow AU = U \\Lambda\n\\end{gathered}\n\\]\nwith $U \\in \\text{Mat}_{\\mathbb{C}}(m, r)$, $\\Lambda \\in \\text{Mat}_{\\mathbb{C}}(r, r)$.\n\nAnd so\n\\[\n\\begin{gathered}\n\\begin{aligned}\n& AA^{\\dagger} = USV^{\\dagger} VSU^{\\dagger} = US^2 U^{\\dagger} \\Longrightarrow (AA^{\\dagger})U = US^2 \\\\ \n& A^{\\dagger} A = VSU^{\\dagger} U SV^{\\dagger} = VS^2 V^{\\dagger} \\Longrightarrow (A^{\\dagger}A)V = VS^2\n\\end{aligned}\n\\end{gathered}\n\\]\nso if we treat $U$ and $V$, matrices of left, right singular vectors, then $S^2$ singular value squared are eigenvalues.\n\nStart with \n\n\\begin{equation}\n| \\psi \\rangle = \\sum_{\\sigma_1 \\dots \\sigma_L} c^{\\sigma_1 \\dots \\sigma_L} | \\sigma_1 \\dots \\sigma_L \\rangle \\in V \\text{ s.t. } \\text{dim} V = d^L\n\\end{equation}\n\nNote the \\emph{abuse of notation}: while $c^{\\sigma_1 \\dots \\sigma_L} \\in \\mathbb{C}$ itself, also denote $c^{\\sigma_1 \\dots \\sigma_L} \\in \\mathbb{C}^{d^L}$ as a shorthand for $\\sum_{\\sigma_1 \\dots \\sigma_L} c^{\\sigma_1 \\dots \\sigma_L} | \\sigma_1 \\dots \\sigma_L \\rangle$\n\nReshape coefficient vector into matrix of (size) dimension ($d\\times d^{L-1}$). \n\\[\n\\begin{gathered}\n\\mathbb{C}^{d^L} \\xrightarrow{\\text{reshape}} \\text{Mat}_{\\mathbb{C}}(d, d^{L-1}) \\\\\nc^{\\sigma_1 \\dots \\sigma_L} \\xmapsto{\\text{reshape}} \\Psi_{\\sigma_1, (\\sigma_2 \\dots \\sigma_L)} \n\\end{gathered}\n\\]\n\nThen do SVD:\n\\[\n\\Psi_{\\sigma_1, (\\sigma_2 \\dots \\sigma_L)} \\stackrel{ \\text{SVD} }{=} \\sum_{a_1} U_{\\sigma_1 a_1} S_{a_1 a_1} V^{\\dagger}_{a_1, \\sigma_2 \\dots L} = U_{\\sigma_1 a_1} S_{a_1 a_1 } V^{\\dagger}_{a_1, \\sigma_2 \\dots \\sigma_L}\n\\]\n\n\nLet's utilize commutative diagrams to summarize the reshaping and SVD operations that we've done.\n\n\\[\n\\begin{tikzpicture}\n\\matrix (m) [matrix of math nodes, row sep=1.55em, column sep=4.7em, minimum width=3.2em]\n{\n\t\\mathbb{C}^{d^L} = \\text{Mat}_{\\mathbb{C}}(1, d^L) & \\text{Mat}_{\\mathbb{C}}(d, d^{L-1}) & \\text{Mat}_{\\mathbb{C}}(d, r_1) \\times \\text{Mat}_{\\mathbb{C}}(r_1, r_1) \\times \\text{Mat}_{\\mathbb{C}}(r_1 , d^{L-1}) \\\\\n\t\\left| \\Psi \\right. \\rangle \\equiv c^{\\sigma_1 \\dots \\sigma_L} & \\Psi_{\\sigma_1, (\\sigma_2 \\dots \\sigma_L) } & \\Psi_{\\sigma_1, (\\sigma_2 \\dots \\sigma_L) } \\stackrel{\\text{SVD}}{=} U_{\\sigma_1 a_1 } S_{a_1 a_1} V^{\\dagger}_{a_1, \\sigma_2 \\dots \\sigma_L} \\\\\n};\n\\path[->]\n(m-1-1) edge node [above] { \\text{reshape} } (m-1-2)\n(m-1-2) edge node [above] { \\text{SVD} } (m-1-3)\n;\n\\path[|->]\n(m-2-1) edge node [above] { \\text{reshape} } (m-2-2)\n(m-2-2) edge node [above] { \\text{SVD} } (m-2-3)\n;\n\\end{tikzpicture} \n\\]\nwhere I abuse notation for the SVD operation in that, SVD maps a matrix (in this case, $\\Psi$) into 3 matrices, that obey the equality relationship when they're multiplied together (i.e. $\\Psi = USV^{\\dagger}$). \n\n\nSlice $U$ into $d$ row vectors, i.e. for $U \\in \\text{Mat}_{\\mathbb{C}}(d,r_1)$.\n\\[\n\\begin{gathered}\n\\begin{aligned}\n\\text{Mat}_{\\mathbb{C}}(d, r_1) & \\xrightarrow{\\text{slice}} \\text{Mat}_{\\mathbb{C}}(1, r_1)^d \\\\\nU_{\\sigma_1 a_1} & \\mapsto \\lbrace A^{\\sigma_1} \\rbrace \\equiv \\lbrace A^{\\sigma_1}_{1, a_1} \\rbrace_{\\sigma_1} \\text{ s.t. } A^{\\sigma_1}_{1,a_1} = U_{\\sigma_1 a_1} \\text{ and } | \\lbrace A^{\\sigma_1}_{1, a_1} \\rbrace | = d\n\\end{aligned}\n\\end{gathered}\n\\]\n\nCollecting all the operations, and doing the following notation rewrite,\n\\[\n\\begin{gathered}\nc^{\\sigma_1 \\sigma_2 \\dots \\sigma_L} \\mapsto \\Psi_{\\sigma_1 \\sigma_2 \\dots \\sigma_L} = \\sum_{a_1} A^{\\sigma_1}_{1 a_1} S_{a_1 a_1} V^{\\dagger}_{a_1, \\sigma_2 \\dots \\sigma_L} = \\sum_{a_1} A^{\\sigma_1}_{1a_1} c^{a_1 \\sigma_2 \\sigma_3 \\dots \\sigma_L}\n\\end{gathered}\n\\]\nwhere\n\\[\nc^{a_1 \\sigma_2 \\sigma_3 \\dots \\sigma_L} = S_{a_1 a_1} V^{\\dagger}_{a_1 \\sigma_2 \\dots \\sigma_L}\n\\]\n\nDo the same procedure again. \n\n\\[\n\\begin{tikzpicture}\n\\matrix (m) [matrix of math nodes, row sep=1.55em, column sep=4.7em, minimum width=3.2em]\n{\n\t\\text{Mat}_{\\mathbb{C}}(r_1, d^{L-1}) & \\text{Mat}_{\\mathbb{C}}(r_1d, d^{L-2}) & \\text{Mat}_{\\mathbb{C}}(r_1d, r_2) \\times \\text{Mat}_{\\mathbb{C}}(r_2, r_2) \\times \\text{Mat}_{\\mathbb{C}}(r_2 , d^{L-2}) \\\\\n\tc^{a_1, \\sigma_2 \\sigma_3 \\dots \\sigma_L} & \\Psi_{a_1\\sigma_2, (\\sigma_3 \\dots \\sigma_L) } & \\Psi_{a_1 \\sigma_2, (\\sigma_3 \\dots \\sigma_L) } \\stackrel{\\text{SVD}}{=} U_{a_1 \\sigma_2, a_2 } S_{a_2 a_2} V^{\\dagger}_{a_2, \\sigma_3 \\dots \\sigma_L} \\\\\n};\n\\path[->]\n(m-1-1) edge node [above] { \\text{reshape} } (m-1-2)\n(m-1-2) edge node [above] { \\text{SVD} } (m-1-3)\n;\n\\path[|->]\n(m-2-1) edge node [above] { \\text{reshape} } (m-2-2)\n(m-2-2) edge node [above] { = } (m-2-3)\n;\n\\end{tikzpicture} \n\\]\n\nThen slice $U$ into $d$ matrices, and then matrix multiply the $S$ and $V^{\\dagger}$ matrices together:\n\\[\n\\begin{tikzpicture}\n\\matrix (m) [matrix of math nodes, row sep=1.55em, column sep=4.7em, minimum width=3.2em]\n{\n\t\\text{Mat}_{\\mathbb{C}}(r_1d, r_2) \\times \\text{Mat}_{\\mathbb{C}}(r_2, r_2) \\times \\text{Mat}_{\\mathbb{C}}(r_2 , d^{L-2}) & \\text{Mat}_{\\mathbb{C}}(r_1, r_2)^d \\times \\text{Mat}_{\\mathbb{C}}(r_2, d^{L-2}) \\\\\n\t\\sum_{a_2} U_{a_1 \\sigma_2, a_2 } S_{a_2 a_2} V^{\\dagger}_{a_2, \\sigma_3 \\dots \\sigma_L} & = \\sum_{a_2} A^{\\sigma_2}_{a_1 a_2} c^{a_2, a_3 \\dots \\sigma_L} \\text{ where } A^{\\sigma_2}_{a_1 a_2} = U_{a_1\\sigma_2, \\sigma_3 \\dots \\sigma_L } \\\\\n};\n\\path[->]\n(m-1-1) edge node [above] { \\text{slice and multiply} } (m-1-2)\n;\n\\path[|->]\n(m-2-1) edge node [above] { = } (m-2-2)\n;\n\\end{tikzpicture} \n\\]\n\n\\end{multicols*}\n%\\begin{multicols*}{1}\n\n\nThus, generalize the \\emph{$i$th procedure}: for $i = 1 \\dots L$, \n\nLet $r_0 = 1$.\n\n\\begin{equation}\\label{Eq:LeftMPSoperation}\n\\begin{tikzpicture}[framed]\n\\matrix (m) [matrix of math nodes, row sep=2.55em, column sep=7.7em, minimum width=6.2em]\n{\n\t\\text{Mat}_{\\mathbb{C}}(r_{i-1}, d^{L-(i-1)}) & \\text{Mat}_{\\mathbb{C}}(r_{i-1}d, d^{L-i}) & \\text{Mat}_{\\mathbb{C}}(r_{i-1}d, r_i) \\times \\text{Mat}_{\\mathbb{C}}(r_i, r_i) \\times \\text{Mat}_{\\mathbb{C}}(r_i , d^{L-i}) & \\text{Mat}_{\\mathbb{C}}(r_{i-1}, r_i)^d \\times \\text{Mat}_{\\mathbb{C}}(r_i, d^{L-i}) \\\\\n\tc^{a_{i-1}, \\sigma_i \\sigma_{i+1} \\dots \\sigma_L} & \\Psi_{a_{i-1}\\sigma_i, (\\sigma_{i+1} \\sigma_{i+2} \\dots \\sigma_L) } & U_{a_{i-1} \\sigma_i, a_i } S_{a_i a_i} V^{\\dagger}_{a_i, \\sigma_{i+1} \\dots \\sigma_L} & A^{\\sigma_i}_{a_{i-1}, a_i} c^{a_i, \\sigma_{i+1} \\dots \\sigma_L} \\\\\n};\n\\path[->]\n(m-1-1) edge node [above] { \\text{reshape} } (m-1-2)\n(m-1-2) edge node [above] { \\text{SVD} } (m-1-3)\n(m-1-3) edge node [above] { \\text{slice and multiply} } (m-1-4)\n;\n\\path[|->]\n(m-2-1) edge node [above] { \\text{reshape} } (m-2-2)\n(m-2-2) edge node [above] { = } (m-2-3)\n(m-2-3) edge node [above] { = } (m-2-4)\n;\n\\end{tikzpicture} \n\\end{equation}\n\nRemember that $r_i \\leq \\min{(r_{i-1} d, d^{L-i})} $ and for $i=L$, there is no need to do a SVD, but only a reshape, and slice and multiply.\n\nCollecting all the $A$ matrices:\n\n\\begin{equation}\n\\boxed{\n\t\\begin{gathered}\n\\begin{aligned}\n& A^{\\sigma_1}_{1, a_1} \\in \\text{Mat}_{\\mathbb{C}}(1,r_1); \\qquad \\, r_1 \\leq d \\\\\n& A^{\\sigma_2}_{a_1, a_2} \\in \\text{Mat}_{\\mathbb{C}}(r_1,r_2); \\qquad \\, r_2 \\leq r_1 d \\\\\n& \\vdots \\\\\n& A^{\\sigma_i}_{a_{i-1}, a_i} \\in \\text{Mat}_{\\mathbb{C}}(r_{i-1},r_i); \\qquad \\, r_i \\leq \\min{(r_{i-1}d, d^{L-i})} \\\\\n& \\vdots \\\\\n& A^{\\sigma_L}_{a_{L-1}, a_L} \\in \\text{Mat}_{\\mathbb{C}}(r_{L-1}, 1); \\qquad \\, r_{L-1} \\leq d\n\\end{aligned}\n\t\\end{gathered}}\n\\end{equation}\n\n\\begin{multicols*}{2}\n\n\\subsubsection{Left and Right Normalization, $A$ and $B$ matrices, \"special gauge\" from normalization}\n\nChoose orthonormal basis states $\\forall \\, a_l, \\, \\forall \\, l = 1, 2, \\dots L$\nFor\n\\[\n\\begin{aligned}\n& | a_l \\rangle = \\sum_{ a_{l-1} \\sigma_l } M^{\\sigma_l}_{a_{l-1}a_l } | a_{l-1} \\sigma_l \\rangle \\\\\n& \\langle a_l' | = \\sum_{a'_{l-1} \\sigma_l'} \\langle a'_{l-1} \\sigma'_l | (M^{\\sigma_l'}_{a'_{l-1} a'_l})^*\n\\end{aligned}\n\\]\nthen,\n\\begin{equation}\n\\begin{gathered}\n\\delta_{a'_l a_l} = \\langle a'_l | a_l \\rangle = \\sum_{a'_{l-1}\\sigma_l', a_{l-1}\\sigma_l } M^{\\sigma_l' *}_{a'_{l-1} a'_l} M^{\\sigma_l}_{a_{l-1} a_l} \\langle a'_{l-1} \\sigma'_l | a_{l-1} \\sigma_l \\rangle = \\sum_{a_{l-1} \\sigma_l } M^{\\sigma_l *}_{a_{l-1} a'_l} M^{\\sigma_l}_{a_{l-1} a_l} = \\\\\n= \\sum_{\\sigma_l} ( (M^{\\sigma_l})^{\\dag} M^{\\sigma_l})_{a_l' a_l}\n\\end{gathered}\n\\end{equation}\n\n\\textbf{Left normalization} comes from a property of SVD in that $\\forall \\, U$ matrices, $U^{\\dagger} U =1$, and so \n\\begin{equation}\n\\begin{gathered}\n(U^{\\dagger})_{a'_i k_i} U_{k_i a_i} = \\delta_{a'_i a_i} = U^*_{ k_i a_i'} U_{k_i a_i} = U^*_{a'_{i-1} \\sigma_i, a_i'} U_{a''_{i-1}\\sigma_i, a_i} = \\\\ \n= A^{\\sigma_i *}_{a''_{i-1}, a_i'} A^{\\sigma_i}_{a''_{i-1}, a_i} = (A^{\\sigma_i})^{\\dagger} A^{\\sigma_i} = \\boxed{ \\sum_{\\sigma_i} (A^{\\sigma_i})^{\\dagger} A^{\\sigma_i} = 1 }\n\\end{gathered}\n\\end{equation}\n\nFor right normalization, consider doing the operations of Eq. \\ref{Eq:LeftMPSoperation} \"on the right\":\n\n\n\\end{multicols*}\n%\\begin{multicols*}{1}\n\n\n\\[\n\\begin{tikzpicture}\n\\matrix (m) [matrix of math nodes, row sep=2.55em, column sep=7.7em, minimum width=6.2em]\n{\n\t\\text{Mat}_{\\mathbb{C}}( d^{L}, 1 ) & \\text{Mat}_{\\mathbb{C}}(d^{L-1}, d ) & \\text{Mat}_{\\mathbb{C}}(d^{L-1},r_1 ) \\times \\text{Mat}_{\\mathbb{C}}(r_1, r_1) \\times \\text{Mat}_{\\mathbb{C}}(r_1 , d) & \\text{Mat}_{\\mathbb{C}}(d^{L-1}, r_1) \\times \\text{Mat}_{\\mathbb{C}}(r_1, 1)^d \\\\\n\tc^{\\sigma_1 \\sigma_{2} \\dots \\sigma_L} & \\Psi_{\\sigma_1 \\dots \\sigma_{L-1}, \\sigma_L } & U_{ \\sigma_1 \\dots \\sigma_{L-1} a_1 } S_{a_1 a_1} V^{\\dagger}_{a_1, \\sigma_{L} } & \\sum_{\\sigma_L} c^{\\sigma_{1} \\dots \\sigma_{L-1}, a_1 } B^{\\sigma_L}_{a_{1}, 1}\\\\\n};\n\\path[->]\n(m-1-1) edge node [above] { \\text{reshape} } (m-1-2)\n(m-1-2) edge node [above] { \\text{SVD} } (m-1-3)\n(m-1-3) edge node [above] { \\text{slice and multiply} } (m-1-4)\n;\n\\path[|->]\n(m-2-1) edge node [above] { \\text{reshape} } (m-2-2)\n(m-2-2) edge node [above] { = } (m-2-3)\n(m-2-3) edge node [above] { = } (m-2-4)\n;\n\\end{tikzpicture} \n\\]\n\n\n\\[\n\\begin{gathered}\n\\begin{tikzpicture}\n\\matrix (m) [matrix of math nodes, row sep=2.55em, column sep=7.7em, minimum width=6.2em]\n{\n\t\\text{Mat}_{\\mathbb{C}}( d^{L-1}, r_1 ) & \\text{Mat}_{\\mathbb{C}}(d^{L-2}, r_1d ) & \\text{Mat}_{\\mathbb{C}}(d^{L-2},r_2 ) \\times \\text{Mat}_{\\mathbb{C}}(r_2, r_2) \\times \\text{Mat}_{\\mathbb{C}}(r_2 , r_1d) & \\text{Mat}_{\\mathbb{C}}(d^{L-2}, r_2) \\times \\text{Mat}_{\\mathbb{C}}(r_2, r_1)^d \\\\\n\tc^{\\sigma_1 \\dots \\sigma_{L-1} a_1} & \\Psi_{\\sigma_1 \\dots \\sigma_{L-2}, \\sigma_{L-1} a_1 } & U_{ \\sigma_1 \\dots \\sigma_{L-2}, a_2 } S_{a_2 a_2} V^{\\dagger}_{a_2, \\sigma_{L-1} a_1 } & \\sum_{\\sigma_{L-1}} c^{\\sigma_{1} \\dots \\sigma_{L-2}, a_2 } B^{\\sigma_{L-1}}_{a_{2}, a_1} \\\\\n};\n\\path[->]\n(m-1-1) edge node [above] { \\text{reshape} } (m-1-2)\n(m-1-2) edge node [above] { \\text{SVD} } (m-1-3)\n(m-1-3) edge node [above] { \\text{slice and multiply} } (m-1-4)\n;\n\\path[|->]\n(m-2-1) edge node [above] { \\text{reshape} } (m-2-2)\n(m-2-2) edge node [above] { = } (m-2-3)\n(m-2-3) edge node [above] { = } (m-2-4)\n;\n\\end{tikzpicture} \\\\\n\\vdots\n\\end{gathered}\n\\]\n\n\\begin{equation}\\label{Eq:RightMPSoperation}\n\\begin{gathered}\n\\begin{tikzpicture}[framed]\n\\matrix (m) [matrix of math nodes, row sep=2.55em, column sep=7.7em, minimum width=6.2em]\n{\n\t\\text{Mat}_{\\mathbb{C}}( d^{L-(i-1)}, r_{i-1} ) & \\text{Mat}_{\\mathbb{C}}(d^{L-i}, r_{i-1}d ) & \\text{Mat}_{\\mathbb{C}}(d^{L-i},r_i ) \\times \\text{Mat}_{\\mathbb{C}}(r_i, r_i) \\times \\text{Mat}_{\\mathbb{C}}(r_i , r_{i-1}d) & \\text{Mat}_{\\mathbb{C}}(d^{L-i}, r_i) \\times \\text{Mat}_{\\mathbb{C}}(r_i, r_{i-1})^d \\\\\n\tc^{\\sigma_1 \\dots \\sigma_{L-(i-1)} a_{i-1}} & \\Psi_{\\sigma_1 \\dots \\sigma_{L-i}, \\sigma_{L-(i-1)} a_{i-1 } } & U_{ \\sigma_1 \\dots \\sigma_{L-i}, a_i } S_{a_i a_i} V^{\\dagger}_{a_i, \\sigma_{L-(i-1)} a_{i-1} } & \\sum_{\\sigma_{L-(i-1)}} c^{\\sigma_{1} \\dots \\sigma_{L-i}, a_i } B^{\\sigma_{L-(i-1)}}_{a_{i}, a_{i-1}} \\\\\n};\n\\path[->]\n(m-1-1) edge node [above] { \\text{reshape} } (m-1-2)\n(m-1-2) edge node [above] { \\text{SVD} } (m-1-3)\n(m-1-3) edge node [above] { \\text{slice and multiply} } (m-1-4)\n;\n\\path[|->]\n(m-2-1) edge node [above] { \\text{reshape} } (m-2-2)\n(m-2-2) edge node [above] { = } (m-2-3)\n(m-2-3) edge node [above] { = } (m-2-4)\n;\n\\end{tikzpicture} \n\\end{gathered}\n\\end{equation}\n\nRemember that $r_i \\leq \\min{(d^{L-i}, r_{i-1} d)} $ and for $i=L$, just do reshape and slice and multiply operations.\n\nThen, finally, the \\textbf{right normalization} is derived and is such:\n\\[\n\t\\begin{gathered}\n\tV^{\\dagger}V = 1 \\Longrightarrow \\\\\n\t(V^{\\dagger}V)_{a_i a'_i} = \\delta_{a_i a'_i} = V^{\\dagger}_{a_i, \\sigma_{L-(i-1)}a_{i-1}} V_{\\sigma_{L-(i-1)}a_{i-1}, a_i'} = B^{\\sigma_{L - (i-1)}}_{a_i, a_{i-1}} (V^{\\dagger})^{\\dagger}_{ \\sigma_{L - (i-1)}a_{i-1}, a_i' } = \\\\\n\t= B^{\\sigma_{L- (i-1)}}_{ a_i a_{i-1}} (V^{\\dagger})^*_{a_i', \\sigma_{L- (i-1)}, a_{i-1}} = B^{\\sigma_{L-(i-1)}}_{ a_i, a_{i-1}} B^{\\sigma_{L - (i-1)}}_{a_i' , a_{i-1}} = B^{\\sigma_{L-(i-1)}}_{a_i a_{i-1}} (B^{\\dagger})^{\\sigma_{L-(i-1)}}_{ a_{i-1} a_i'} \\qquad \\, \\forall i = 1 \\dots L\n\t\\end{gathered}\n\\]\n\n\\begin{equation}\n\\Longrightarrow \\sum_{ \\sigma_{L-(i-1)}} B^{\\sigma_{L-(i-1)}} (B^{\\dagger})^{\\sigma_{L-(i-1)}} = 1\n\\end{equation}\n\n\n\n\\begin{multicols*}{2}\n\n\n\n\n\ncf. Sec. 4, Matrix Product States (MPS) of Schollw\\\"{o}ck \\cite{Scho2010}. \n\nNecessarily, given matrix $M\\in \\text{Mat}_{\\mathbb{K}}(M,N)$ (notation in Bridgeman and Chubb (2017) \\cite{BrCh2017} and \\href{http://docs.nvidia.com/cuda/cusolver/index.html}{CUDA Toolkit Documentation}; I will follow the notation in Schollw\\\"{o}ck \\cite{Scho2010} since his $A$,$B$ denote specific physical meaning). \n\nFor \n\\[\nU\\in \\text{Mat}_{\\mathbb{K}}(N_A, \\min{(N_A,N_B)}) \\text{ s.t. } UU^{\\dag}=1\n\\]\n\\[\nS \\in \\text{Mat}_{\\mathbb{K}}(\\min{(N_A,N_B)}, \\min{(N_A,N_B)} )\n\\]\ns.t. $S$ diagonal with nonnegative $S_{aa} = s_a$, i.e. $S_{ij} = \\delta_{ij}s_i$ s.t. $s_i\\geq 0$ \\, $\\forall \\, i = 1,2, \\dots \\min{(N_A,N_B)}$. \n\n$r\\equiv $ (Schmidt) rank of $M :=$ number of nonzero singular values. \n\nAssume $s_1\\geq s_2 \\geq \\dots \\geq s_r \\geq 0$. \n\n$V^{\\dag} \\in \\text{Mat}_{\\mathbb{K}}(\\min{(N_A,N_B)},N_B)$ s.t. $V^{\\dag}V=1$. \n\n\\begin{tikzpicture}\n \\matrix (m) [matrix of math nodes, row sep=1.75em, column sep=4.8em, minimum width=1.2em]\n {\n\t\\text{Mat}_{\\mathbb{K}}(N_A,N_B) & U_{\\mathbb{K}}(N_A,\\min{(N_A,N_B)}) \\times \\text{diag}_{\\mathbb{K}}(\\min{(N_A,N_B)}) \\times U_{\\mathbb{K}}(\\min{(N_A,N_B)},N_B) \\\\ \n M & USV^{\\dag} \\\\\n};\n \\path[->]\n (m-1-1) edge node [above] { SVD } (m-1-2)\n ;\n \\path[|->]\n (m-2-1) edge node [above] { SVD } (m-2-2)\n ;\n\\end{tikzpicture} \n\nOptimal approximation of $M$ (rank $r$ by matrix $M'$ (rank $r' 0$ \\, $\\forall \\, a \\leq r$, and so \n\\[\n|\\psi \\rangle =\\sum_{a=1}^r s_a |a\\rangle_A |a\\rangle_B\n\\]\n$r=1$ (classical) product states. $|\\psi \\rangle = s_1 |1\\rangle_A |1\\rangle_B$. \\\\\n$r>1$ entangled (quantum) states. \n\nSchmidt decomposition on reduced density operators for $A$ and $B$: \n\n\\[\n\\begin{aligned}\n\t& \\widehat{\\rho}_A =\\sum_{a=1}^r s_a^2 |a\\rangle_A \\langle a |_A \\\\ \n\t& \\widehat{\\rho}_B = \\sum_{a=1}^r s_a^2 |a\\rangle_B \\langle a |_B\n\\end{aligned}\n\\]\nRespective eigenvectors are left and right singular vectors. \n\nVon Neumann entropy can be read off: \n\\[\nS_{A|B}(|\\psi \\rangle) = -\\text{tr}\\widehat{\\rho}_A \\log_2{\\widehat{\\rho}_A} = -\\sum_{a=1}^r s_a^2 \\log_2{s_a^2}\n\\]\n\nIn view of large size of Hilbert spaces, approximate $| \\psi \\rangle$ by some $| \\widetilde{\\psi} \\rangle$ spanned over state spaces $A,B$ that have dims. $r'$ only. \n\nSince 2-norm of $| \\psi \\rangle$, \n\\[\n\\| | \\psi\\rangle \\|_2^2 = \\sum_{ij} |\\Psi_{ij} |^2 = \\| \\Psi \\|^2_F\n\\]\nsince\n\\[\n\\| | \\psi\\rangle \\|_2^2 = \\sum_{a=1}^r s_a^2 = \\sum_{ij} |\\Psi_{ij} |^2\n\\] \niff $\\lbrace |i \\rangle \\rbrace , \\lbrace | j \\rangle \\rbrace$ orthonormal. Optimal approx. of 2-norm given by optimal approx. of $\\Psi$ by $\\overline{\\Psi}$ in Frobenius norm, where $\\overline{\\Psi}$ is matrix of rank $r'$. \n\n$\\overline{\\Psi} = US'V^{\\dag}$, $S' =\\text{diag}(s_1 , \\dots s_{r'} , 0\\dots )$ from above. \n\n$\\Longrightarrow $ Schmidt decomposition of approximate state \n\\begin{equation}\n| \\overline{\\Psi}\\rangle = \\sum_{a=1}^{r'} s_a|a\\rangle_A | a \\rangle_B\n\\end{equation}\ncf. Eq. (27) of Schollw\\\"{o}ck \\cite{Scho2010}, where $s_a$ must be rescaled if normalization desired. \n\n\\subsection{QR decomposition}\ncf. 4.1.2. of Schollw\\\"{o}ck \\cite{Scho2010}. \n\nIf actual value of singular values not used explicitly, then use \\emph{QR decomposition}. \n\nQR decomposition: $\\forall \\, M \\in \\text{Mat}_{\\mathbb{K}}(N_A,N_B)$, \n\\begin{equation}\nM=QR, \\, Q\\in U_{\\mathbb{K}}(N_A), \\text{ i.e. } Q^{\\dag}Q = 1=QQ^{\\dag} , \\, R \\in \\text{Mat}_{\\mathbb{K}}(N_A,N_B) \\text{ s.t. } \\text{ upper triangular, i.e. } R_{ij}= 0 \\text{ if } i >j \n\\end{equation}\n\\textbf{thin} QR decomposition: assume $N_A>N_B$. Then bottom $N_A-N_B$ rows of $R$ are $0$, so \n\\[\n\\begin{gathered}\nM=Q \\left[ \\begin{matrix} R_1 \\\\ 0 \\end{matrix} \\right] = \\left[ \\begin{matrix} Q_1 & Q_2 \\end{matrix} \\right] \\left[ \\begin{matrix} R_1 \\\\ 0 \\end{matrix} \\right] = Q_1R_1 \\\\\n\\begin{aligned}\n& Q_1 \\in \\text{Mat}_{\\mathbb{K}}(N_A,N_B) \\\\ \n& R_1 \\in \\text{Mat}_{\\mathbb{K}}(N_B,N_B) \n\\end{aligned}\n\\end{gathered}\n\\]\nWhile $Q_1^{\\dag}Q_1=1$ in general $Q_1 Q_1^{\\dag} \\neq 1$\n\n\\section{Matrix Product States (MPS)}\n\ncf. Section 4.13 Decomposition of arbitrary quantum states into MPS of Schollw\\\"{o}ck \\cite{Scho2010}. \n\nConsider lattice of $L$ sites, $d$-dim. local state spaces $\\lbrace \\sigma_i \\rbrace_{i=1,\\dots L}$. \n\nMost general pure quantum state on lattice (assume normalized) \n\\begin{equation}\n|\\psi \\rangle = \\sum_{\\sigma_1 \\dots \\sigma_L} c_{\\sigma_1 \\dots \\sigma_L }|\\sigma_1 \\dots \\sigma_L \\rangle\n\\end{equation}\ncf. Eq. (30) of Schollw\\\"{o}ck \\cite{Scho2010},\n\n\\subsection{Left-canonical matrix product state} \ncf. Schollw\\\"{o}ck \\cite{Scho2010},\n\nConsider the process of refactoring or \"flattening\", which I claim to be a functor \\emph{flatten}: \n\\[\n| \\psi \\rangle \\in \\mathcal{H} \\text{ s.t. } \\text{dim}\\mathcal{H} = d^L \\mapsto \\Psi \\in \\text{Mat}_{\\mathbb{K}}(d,d^{L-1})\n\\]\n\\[\n\\Psi_{\\sigma_1, (\\sigma_2 \\dots \\sigma_L) } = c_{\\sigma_1 \\dots \\sigma_L}\n\\]\n\\begin{equation}\n\\begin{gathered}\n\\xrightarrow{ \\text{ SVD } } c_{\\sigma_1 \\dots \\sigma_L} = \\Psi_{\\sigma_1, (\\sigma_2 \\dots \\sigma_L)} = \\sum_a^{r_1} U_{\\sigma_1, a_1} S_{a_1,a_1} (V^{\\dag})_{a_1, (\\sigma_2 \\dots \\sigma_L)} \\equiv \\sum_{a_1}^{r_1} U_{\\sigma_1 , a_1} c_{a_1 , \\sigma_2 \\dots \\sigma_L}\n\\end{gathered}\n\\end{equation}\ni.e.\n\\[\n\\begin{aligned}\n\t& (\\mathbb{K}^d)^L \\to \\text{Mat}_{\\mathbb{K}}(1,r) \\times \\text{Mat}_{\\mathbb{K}}(r_1 d, d^{L-2}) \\\\ \n\t& c_{\\sigma_1 \\dots \\sigma_L} \\mapsto A_{a_1}^{\\sigma_1} , \\Psi_{(a_1\\sigma_2), (\\sigma_3\\dots \\sigma_L)} \n\\end{aligned}\n\\]\ns.t. \n\\[\nc_{\\sigma_1\\dots \\sigma_L} = \\sum_{a_1}^{r_1} A_{a_1}^{\\sigma_1} \\Psi_{(a_1\\sigma_2), (\\sigma_3 \\dots \\sigma_L)}\n\\]\nwhere rank $r_1 \\leq d$. \n\\[\nU \\in \\text{Mat}_{\\mathbb{K}}(d,\\min{(d,r)}) = \\text{Mat}_{\\mathbb{K}}(d,r)\n\\]\nConsider $d$ row vectors $A^{\\sigma_1}$, $A^{\\sigma_1}_{a_1} = U_{\\sigma_1,a_1}$. \n\n\\[\n\\begin{gathered}\nc_{a_1\\sigma_2 \\dots \\sigma_L } = \\sum_{a_1}^{r_1} A_{a_1}^{\\sigma_1} \\Psi_{(a_1,\\sigma_2),(\\sigma_3\\dots \\sigma_L)} \\text{ with } \\\\\n\\Psi_{(a_1\\sigma_2),(\\sigma_3\\dots \\sigma_L)}\\in \\text{Mat}_{\\mathbb{K}}(r_1d,d^{L-2})\n\\end{gathered}\n\\]\nSo from Eq. (34) of Schollw\\\"{o}ck \\cite{Scho2010},\n\\begin{equation}\n\\begin{gathered}\n\tc_{\\sigma_1 \\dots \\sigma_L} = \\sum_{a_1}^{r_1} \\sum_{a_2}^{r_2} A_{a_1}^{\\sigma_1} U_{ (a_1\\sigma_2) , a_2} S_{a_2,a_2} (V^{\\dag})_{a_2, (\\sigma_3\\dots \\sigma_L)} = \\sum_{a_1}^{r_1} \\sum_{a_2}^{r_2} A_{a_1}^{\\sigma_1} A_{a_1,a_2}^{\\sigma_2} \\Psi_{(a_2\\sigma_3), (\\sigma_4\\dots \\sigma_L)}\n\\end{gathered}\n\\end{equation}\nSo for \n\\[\nU\\in \\text{Mat}_{\\mathbb{K}}(d,r_1\\times r_2) \\mapsto \\lbrace A^{\\sigma_2} \\rbrace_{\\sigma_2}, \\qquad \\, | \\lbrace A^{\\sigma_2} \\rbrace_{\\sigma_2} | = d , \\qquad \\, A^{\\sigma_2} \\in \\text{Mat}_{\\mathbb{K}}(r_1,r_2)\n\\]\n$A^{\\sigma_2}_{a_1,a_2} = U_{(a_1,\\sigma_2),a_2}$ and multiplied $S$ and $V^{\\dag}$, \n\\[\nSV^{\\dag} \\mapsto \\Psi \\in \\text{Mat}_{\\mathbb{K}}(r_2d, d^{L-3}); \\qquad \\, r_2 \\leq r_1 d \\leq d^2\n\\]\nand so continuing the application of SVD and refactoring (what I call applying the \\emph{flatten} functor)\n\\[\n\\begin{gathered}\n\\xrightarrow{ \\text{ SVD } } c_{\\sigma_1 \\dots \\sigma_L} = \\sum_{a_1 \\dots a_{L-1}} A^{\\sigma_1}_{a_1} A^{\\sigma_2}_{a_1 a_2} \\dots A^{\\sigma_{L-1}}_{a_{L-2}, a_{L-1} } A^{\\sigma_L }_{a_L-1 } \\equiv A^{\\sigma_1} A^{\\sigma_2} \\dots A^{\\sigma_{L-1}} A^{\\sigma_L}\n\\end{gathered}\n\\]\n\n\\subsubsection{Matrix Product State (definition)}\n\n\\begin{definition}[Matrix Product State]\n\\begin{equation}\n|\\psi \\rangle = \\sum_{\\sigma_1 \\dots \\sigma_L} A^{\\sigma_1}A^{\\sigma_2} \\dots A^{\\sigma_{L-1}} A^{\\sigma_L} | \\sigma_1 \\dots \\sigma_L \\rangle\n\\end{equation}\n\\end{definition}\n\nMaximally, the dims. are \n\\[\n(1\\times d), (d\\times d^2) \\dots (d^{L/2-1} \\times d^{L/2} ), (d^{L/2} \\times d^{L/2-1} ) \\dots (d^2 \\times d), (d\\times 1)\n\\]\nSince $\\forall \\, $ SVD, $U^{\\dag} U=1$, \n\\[\n\\delta_{a_l , a_l'} = \\sum_{a_{l-1} a_l} (U^{\\dag})_{a_l,(a_{l-1} \\sigma_l)} U_{(a_{l-1} \\sigma_l),a'_l } = \\sum_{a_{l-1} \\sigma_l} (A^{\\sigma_l})^{\\dag}_{a_l,a_{l-1}} A^{\\sigma_l}_{a_{l-1},a_l'} = \\sum_{\\sigma_l} ( (A^{\\sigma_2})^{\\dag} A^{\\sigma_l} )_{a_l,a_l'}\n\\]\nor \n\\begin{equation}\n\t\\sum_{\\sigma_l} (A^{\\sigma_l})^{\\dag} A^{\\sigma_l} = 1\n\\end{equation}\ncf. Eq. (38) of Schollw\\\"{o}ck \\cite{Scho2010},\n\nIf for $\\lbrace A^{\\sigma_l} \\rbrace_{\\sigma_l} $, $\\sum_{\\sigma_l} (A^{\\sigma_l})^{\\dag} A = 1$, $\\lbrace A^{\\sigma_l} \\rbrace_{\\sigma_l}$ are \\textbf{left-normalized}; matrix product states that consist of only left-normalized matrices are \\textbf{left-canonical}. \n\nView Density Matrix Renormalization Group (DMRG) decomposition of universe into blocks $A$ and $B$, split lattice into parts $A$,$B$, where $A$ compries sites $1$ through $l$ and $B$ sites $l+1$ through $L$. \n\n\\[\n\\begin{aligned}\n\t& | a_l \\rangle_A = \\sum_{\\sigma_1 \\dots \\sigma_l} (A^{\\sigma_1} A^{\\sigma_2} \\dots A^{\\sigma_l} )_{a_l,1} | \\sigma_1 \\dots \\sigma_l \\rangle \\\\ \n\t\t& | a_l \\rangle_B = \\sum_{\\sigma_{l+1} \\dots \\sigma_L} (A^{\\sigma_{l+1}} A^{\\sigma_{l+2}} \\dots A^{\\sigma_L} )_{a_l,1} | \\sigma_{l+1} \\dots \\sigma_L \\rangle \n\\end{aligned}\n\\]\ns.t. matrix product state (MPS) is \n\\[\n|\\psi \\rangle =\\sum_{a_l} | a_l \\rangle_A | a_l \\rangle_B\n\\]\n\n\\subsubsection{Summarize this procedure of constructing, from a pure state, the matrix product state (version) by successive application Singular Value Decomposition (SVD) from the Category Theory point of view}\n\nConsider all applications of SVD to get to a matrix product state (MPS): \n\\begin{tikzpicture}\n \\matrix (m) [matrix of math nodes, row sep=1.75em, column sep=4.8em, minimum width=1.2em]\n {\n\t(\\mathbb{K}^d)^L & (\\text{Mat}_{\\mathbb{K}}(1,r_1))^d \\times (\\text{Mat}_{\\mathbb{K}}(r_1,r_2))^d \\times \\dots \\times (\\text{Mat}_{\\mathbb{K}}(r_{L-2},r_{L-1}))^d \\times (\\text{Mat}_{\\mathbb{K}}(r_{L-1},1))^d \\\\\n c_{\\sigma_1 \\dots \\sigma_L} & c_{\\sigma_1\\dots \\sigma_L} = \\sum_{a_1 \\dots a_{L-1}} A^{\\sigma_1}_{a_1} A_{a_1a_2}^{\\sigma_2} \\dots A^{\\sigma_{L-1}}_{a_{L-2}, a_{L-1}} A_{a_{L-1}}^{\\sigma_L} \\\\\n};\n \\path[->]\n (m-1-1) edge node [above] { SVD } (m-1-2)\n ;\n \\path[|->]\n (m-2-1) edge node [above] { SVD } (m-2-2)\n ;\n\\end{tikzpicture} \nand remember the maximal values that the $r_i$'s can take:\n\\[\n\\begin{gathered}\n\t\\begin{aligned}\n& r_1 \\leq d \\\\ \n\t& r_2 \\leq d^2 \n\\end{aligned}\t \\qquad \\, \t\\begin{aligned}\n& r_{L/2} \\leq d^{L/2} \\\\ \n\t& r_{L/2+1} \\leq d^{L/2-1} \n\\end{aligned} \\qquad \\, \t\\begin{aligned}\n& r_{L-2} \\leq d^2 \\\\ \n\t& r_{L-1} \\leq d \n\\end{aligned}\n\\end{gathered}\n\\]\n\nLet us explicitly note the functors (that were applied) flatten (and its inverse), and the application of SVD, explicitly:\n\n\\end{multicols*}\n%\\begin{multicols*}{1}\n\n\\[\n\\begin{tikzpicture}\n \\matrix (m) [matrix of math nodes, row sep=1.75em, column sep=2.8em, minimum width=1.2em]\n {\n\t(\\mathbb{K}^d)^L & \\text{Mat}_{\\mathbb{K}}(d,d^{L-1}) & U_{\\mathbb{K}}(d,r_1) \\times \\text{diag}_{\\mathbb{K}}(r_1) \\times U_{\\mathbb{K}}(r_1,d^{L-1}) & (\\text{Mat}_{\\mathbb{K}}(1,r_1))^d \\times \\text{Mat}_{\\mathbb{K}}(r_1d, d^{L-2}) & (\\text{Mat}_{\\mathbb{K}}(1,r_1))^d \\times (\\mathbb{K}^{r_1}) \\times (\\mathbb{K}^d)^{L-1} \n \\\\\n\t c_{\\sigma_1 \\dots \\sigma_L} & c_{\\sigma_1 \\dots \\sigma_L} = \\Psi_{\\sigma_1,(\\sigma_2\\dots \\sigma_L)} & \\Psi_{\\sigma_1,(\\sigma_2\\dots \\sigma_L)} = \\sum_{a_1}^{r_1}U_{\\sigma_1a_1} S_{a_1,a_1} (V^{\\dag})_{a_1,(\\sigma_2 \\dots \\sigma_L)} & c_{a_1\\sigma_2\\dots \\sigma_L} = \\sum_{a_1}^{r_1} A_{a_1}^{\\sigma_1} \\Psi_{(a_1,a_2),(\\sigma_3 \\dots \\sigma_L)} & c_{a_1\\sigma_2\\dots \\sigma_L} = \\sum_{a_1}^{r_1} A^{\\sigma_1}_{a_1} c_{a_1 \\sigma_2 \\dots \\sigma_L} \\\\\n};\n \\path[->]\n (m-1-1) edge node [above] { $\\text{flatten}^{-1}$ } (m-1-2)\n (m-1-2) edge node [above] { SVD } (m-1-3)\n (m-1-3) edge node [above] { $\\cong$ } (m-1-4)\n (m-1-4) edge node [above] { flatten } (m-1-5)\n ;\n \\path[|->]\n (m-2-1) edge node [above] { $\\text{flatten}^{-1}$ } (m-2-2)\n (m-2-2) edge node [above] { SVD } (m-2-3)\n (m-2-3) edge node [above] { $\\cong$ } (m-2-4)\n (m-2-4) edge node [above] { flatten } (m-2-5)\n ;\n\\end{tikzpicture} \n\\]\nwith $\\cong$ in this case denoting an isomorphism (clearly). \n\n\nIn considering some kind of recursive algorithm, so to repeat some series of steps until a matrix product state is obtained, consider this:\n\\[\n\\begin{tikzpicture}\n \\matrix (m) [matrix of math nodes, row sep=1.75em, column sep=4.8em, minimum width=1.2em]\n {\n\t(\\mathbb{K}^d)^L & (\\text{Mat}_{\\mathbb{K}}(1,r_1))^d \\times \\mathbb{K}^{r_1} \\times (\\mathbb{K}^d)^{L-1} \\\\\n c_{\\sigma_1 \\dots \\sigma_L} & c_{\\sigma_1\\dots \\sigma_L} = \\sum_{a_1}^{r_1} A^{\\sigma_1}_{a_1} c_{a_1 \\sigma_2\\dots \\sigma_L} \\\\ \n};\n \\path[->]\n (m-1-1) edge node [above] { } (m-1-2)\n ;\n \\path[|->]\n (m-2-1) edge node [above] { } (m-2-2)\n ;\n\\end{tikzpicture} \n\\]\n\nSo in summary, to obtain matrix product states, starting from a matrix, \n\\begin{equation}\n\\begin{tikzpicture}[framed]\n \\matrix (m) [matrix of math nodes, row sep=1.55em, column sep=1.7em, minimum width=1.2em]\n {\n\t\\text{Mat}_{\\mathbb{K}}(d,d^{L-1}) & (\\text{Mat}_{\\mathbb{K}}(1,r_1))^d \\times \\text{Mat}_{\\mathbb{K}}(r_1d, d^{L-2}) & \\dots & (\\text{Mat}_{\\mathbb{K}}(1,r_1))^d \\times (\\text{Mat}_{\\mathbb{K}}(r_1,r_2))^d \\times \\dots \\times (\\text{Mat}_{\\mathbb{K}}(r_{n-1},r_{n}))^d \\times (\\text{Mat}_{\\mathbb{K}}(r_{n}d,d^{L-(n+1)}))^d \\\\\n \\Psi_{\\sigma_1,(\\sigma_2\\dots \\sigma_L)} & \\sum_{a_1}^{r_1} A_{a_1}^{\\sigma_1} \\Psi_{(a_1,\\sigma_2),(\\sigma_3 \\dots \\sigma_L)} & \\dots & \\sum_{a_1,a_2,\\dots a_n}^{r_1,r_2,\\dots r_n} A^{\\sigma_1}_{a_1} A^{\\sigma_2}_{a_1a_2}\\dots A^{\\sigma_n}_{a_{n-1}a_n} \\Psi_{ (a_n \\sigma_{n+1}), (\\sigma_{n+2}\\dots \\sigma_L) } \\\\ \n};\n \\path[->]\n (m-1-1) edge node [above] { } (m-1-2)\n (m-1-2) edge node [above] { } (m-1-3)\n (m-1-3) edge node [above] { } (m-1-4)\n ;\n \\path[|->]\n (m-2-1) edge node [above] { } (m-2-2)\n (m-2-2) edge node [above] { } (m-2-3)\n (m-2-3) edge node [above] { } (m-2-4)\n;\n\\end{tikzpicture} \n\\end{equation}\n\n\n\n%\\end{multicols*}\n%\\begin{multicols*}{2}\n\n\\subsection{Right-canonical matrix product state} \ncf. Schollw\\\"{o}ck \\cite{Scho2010},\n\nWe can start from right in order to obtain \n\\[\n\\begin{gathered}\n\tc_{\\sigma_1\\dots \\sigma_L} = \\Psi_{(\\sigma_1 \\dots \\sigma_{L-1}), \\sigma_L } = \\sum_{a_{L-1}} U_{(\\sigma_1 \\dots \\sigma_{L-1} ), a_{L-1} } S_{a_{L-1}, a_{L-1} } (V^{\\dag})_{a_{L-1}, \\sigma_L } = \\sum_{a_{L-1}} \\Psi_{(\\sigma_1\\dots \\sigma_{L-2}), (\\sigma_{L-1} a_{L-1} ) } B^{\\sigma_L}_{a_{L-1}} = \\\\ \n = \\sum_{a_{L-1},a_{L-2}} U_{(\\sigma_1 \\dots \\sigma_{L-2} ), a_{L-2} } S_{a_{L-2}, a_{L-2} } (V^{\\dag})_{a_{L-2}, (\\sigma_{L-1}a_{L-1}) } B^{\\sigma_L}_{a_{L-1}} = \\sum_{a_{L-2},a_{L-1}} \\Psi_{(\\sigma_1\\dots \\sigma_{L-3}), (\\sigma_{L-2} a_{L-2} ) } B^{\\sigma_{L-1}}_{a_{L-2},a_{L-1}} B^{\\sigma_L}_{a_{L-1}} = \\dots \\\\ \n\\end{gathered}\n\\]\nor consider \n\\[\n\\begin{tikzpicture}\n \\matrix (m) [matrix of math nodes, row sep=1.95em, column sep=3.8em, minimum width=1.8em]\n {\n\t(\\mathbb{K}^d)^L & \\text{Mat}_{\\mathbb{K}}(d^{L-1},d) & U_{\\mathbb{K}}(d^{L-1},r_{L-1}) \\times \\text{diag}_{\\mathbb{K}}(r_{L-1}) \\times U_{\\mathbb{K}}(r_{L-1},d ) & \\text{Mat}_{\\mathbb{K}}(d^{L-2},d r_{L-1}) \\times ( \\text{Mat}_{\\mathbb{K}}(r_{L-1}, 1))^d & \\qquad \\, \n \\\\\n\t c_{\\sigma_1 \\dots \\sigma_L} & c_{\\sigma_1 \\dots \\sigma_L} = \\Psi_{(\\sigma_1\\dots \\sigma_{L-1}),\\sigma_L} & c_{\\sigma_1 \\dots \\sigma_L} = \\sum_{a_{L-1}}^{r_{L-1}}U_{(\\sigma_1 \\dots \\sigma_{L-1}), a_{L-1}} S_{a_{L-1},a_{L-1}} (V^{\\dag})_{a_{L-1}, \\sigma_L} & \\begin{gathered}\n\tU_{(\\sigma_1 \\dots \\sigma_{L-1}), a_{L-1} } S_{a_{L-1}, a_{L-1}} = \\Psi_{(\\sigma_1\\dots \\sigma_{L-2}), (\\sigma_{L-1} a_{L-1}) } \\\\ \n(V^{\\dag})_{a_{L-1},\\sigma_L} = B^{\\sigma_L}_{a_{L-1}} \\\\\nc_{\\sigma_1\\dots \\sigma_L} = \\sum_{a_{L-1}} \\Psi_{(\\sigma_1 \\dots \\sigma_{L-2} ) , (\\sigma_{L-1}, a_{L-1})} B_{a_{L-1}}^{\\sigma_L} \n\\end{gathered} & \\qquad \\, \\\\\n\\qquad \\, & U_{\\mathbb{K}}(d^{L-2},r_{L-2}) \\times \\text{diag}_{\\mathbb{K}}(r_{L-2}) \\times U_{\\mathbb{K}}(r_{L-2},dr_{L-1} ) \\times ( \\text{Mat}_{\\mathbb{K}}(r_{L-1}, 1))^d & \\text{Mat}_{\\mathbb{K}}(d^{L-3},d r_{L-2}) \\times ( \\text{Mat}_{\\mathbb{K}}(r_{L-2}, r_{L-1}))^d \\times ( \\text{Mat}_{\\mathbb{K}}(r_{L-1}, 1))^d & & \\\\\n\\qquad \\, & c_{\\sigma_1\\dots \\sigma_L} = \\sum_{a_{L-1},a_{L-2}} U_{(\\sigma_1 \\dots \\sigma_{L-2} ), a_{L-2} } S_{a_{L-2}, a_{L-2} } (V^{\\dag})_{a_{L-2}, (\\sigma_{L-1}a_{L-1}) } B^{\\sigma_L}_{a_{L-1}} & \\begin{gathered}\n\tU_{(\\sigma_1 \\dots \\sigma_{L-2}), a_{L-2} } S_{a_{L-2}, a_{L-2}} = \\Psi_{(\\sigma_1\\dots \\sigma_{L-3}), (\\sigma_{L-2} a_{L-2}) } \\\\ \n(V^{\\dag})_{a_{L-2},(\\sigma_{L-1}a_{L-1})} = B^{\\sigma_{L-1}}_{a_{L-2}a_{L-1}} \\\\\nc_{\\sigma_1\\dots \\sigma_L} = \\sum_{a_{L-1}, a_{L-2}} \\Psi_{(\\sigma_1 \\dots \\sigma_{L-3} ) , (\\sigma_{L-2}, a_{L-2})} B_{a_{L-2},a_{L-1}}^{\\sigma_{L-1}} B^{\\sigma_L}_{a_{L-1}} \n\\end{gathered} & & \\\\\n};\n \\path[->]\n (m-1-1) edge node [above] { $\\text{flatten}^{-1}$ } (m-1-2)\n (m-1-2) edge node [above] { SVD } (m-1-3)\n (m-1-3) edge node [above] { $\\cong$ } (m-1-4)\n (m-1-4) edge node [above] { SVD } (m-1-5)\n (m-3-1) edge node [above] { SVD } (m-3-2)\n (m-3-2) edge node [above] { $\\cong$ } (m-3-3)\n ;\n \\path[|->]\n (m-2-1) edge node [above] { $\\text{flatten}^{-1}$ } (m-2-2)\n (m-2-2) edge node [above] { SVD } (m-2-3)\n (m-2-3) edge node [above] { $\\cong$ } (m-2-4)\n (m-2-4) edge node [above] { SVD } (m-2-5)\n (m-4-1) edge node [above] { SVD } (m-4-2)\n (m-4-2) edge node [above] { $\\cong$ } (m-4-3)\n ;\n\\end{tikzpicture} \n\\]\nwith $\\cong$ in this case denoting an isomorphism (clearly). \n\nAnd so we can explicitly state the recursion step, for the purpose of writing numerical implementations/algorithms: $\\forall \\, l = 1,2\\dots L$,\n\n\\begin{tikzpicture}\n \\matrix (m) [matrix of math nodes, row sep=1.75em, column sep=4.8em, minimum width=1.2em]\n {\n\\text{Mat}_{\\mathbb{K}}(d^{L-l},d r_{L-(l-1)}) \t & \\text{Mat}_{\\mathbb{K}}(d^{L-(l+1)},d r_{L-l}) \\times (\\text{Mat}_{\\mathbb{K}}(r_{L-l},r_{L-(l-1)}))^d \\\\\n \\Psi_{(\\sigma_1\\dots \\sigma_{L-l}), (\\sigma_{L-(l-1)} a_{L-(l-1)}) } & \\Psi_{(\\sigma_1\\dots \\sigma_{L-l}), (\\sigma_{L-(l-1)} a_{L-(l-1)}) } = \\sum_{a_{L-l}} \\Psi_{(\\sigma_1\\dots \\sigma_{L-(l+1)}), (\\sigma_{L-l} a_{L-l}) } B_{a_{L-l},a_{L-(l-1)}}^{\\sigma_{L-(l-1)}} \\\\ \n};\n \\path[->]\n (m-1-1) edge node [above] { } (m-1-2)\n ;\n \\path[|->]\n (m-2-1) edge node [above] { } (m-2-2)\n ;\n\\end{tikzpicture} \n\nand we finally obtained, after successive applications SVD, the matrix product state:\n\n\\begin{tikzpicture}\n \\matrix (m) [matrix of math nodes, row sep=1.75em, column sep=4.8em, minimum width=1.2em]\n {\n(\\mathbb{K}^d)^L & \\text{Mat}_{\\mathbb{K}}(d^{L-1},d ) & (\\text{Mat}_{\\mathbb{K}}( 1, r_1))^d \\times (\\text{Mat}_{\\mathbb{K}}(r_1,r_2))^d \\times \\dots \\times (\\text{Mat}_{\\mathbb{K}}(r_{L-2},r_{L-1}))^d \\times (\\text{Mat}_{\\mathbb{K}}(r_{L-1}, 1 ))^d \\\\\n c_{\\sigma_1\\dots \\sigma_L} & \\Psi_{(\\sigma_1\\dots \\sigma_{L-l}), \\sigma_L } & c_{\\sigma_1\\dots \\sigma_L} = \\sum_{ a_1 \\dots a_{L-1} } B_{a_1}^{\\sigma_1} B_{a_1a_2}^{\\sigma_2 } \\dots B_{a_{L-2}a_{L-1}}^{\\sigma_{L-1} } B_{a_{L-1}}^{\\sigma_L} \\\\ \n};\n \\path[->]\n (m-1-1) edge node [above] { } (m-1-2)\n (m-1-2) edge node [above] { } (m-1-3)\n ;\n \\path[|->]\n (m-2-1) edge node [above] { } (m-2-2)\n (m-2-2) edge node [above] { } (m-2-3)\n ;\n\\end{tikzpicture} \n\n\\begin{multicols*}{2}\n\nSince \n\\begin{equation}\nV^{\\dag} V =1\n\\end{equation},\nthen\n\\begin{equation}\n\t\\delta_{a_l a_l'} = \\sum_{\\sigma_m a_m } (V^{\\dag})_{a_l (\\sigma_ma_m) } V_{(\\sigma_m a_m) a_l'} = \\sum_{\\sigma_m a_m } B_{a_l a_m}^{\\sigma_m} \\overline{B}^{\\sigma_m}_{a_l' a_m} \\Longrightarrow \\sum_{\\sigma_m} \\boxed{ B^{\\sigma_m} (B^{\\sigma_m})^{\\dag} = 1 }\n\\end{equation}\nThe $B$-matrices that obey this condition are referred to as \\textbf{right-normalized} matrices. A matrix product state (MPS) entirely consisting of a product of these right-normalized matrices is called \\textbf{right-canonical}. \n\n\\subsection{Matrix Product Operators (MPO)}\n\nThe form of a general operator, $\\widehat{O}$ is the following:\n\\begin{equation}\n\\begin{gathered}\n\\widehat{O} = \\sum_{ \\lbrace \\sigma \\rbrace } \\sum_{ \\lbrace \\sigma' \\rbrace } c^{\\sigma_1 \\dots \\sigma_L, \\sigma_1' \\dots \\sigma_L'} | \\sigma_1 \\dots \\sigma_L \\rangle \\langle \\sigma_1' \\dots \\sigma_L' | \\in \\mathcal{H} \\otimes \\mathcal{H}^* \n\\end{gathered}\n\\end{equation}\nwith $\\text{dim}\\mathcal{H} = \\text{dim}\\mathcal{H}^* = d^L$. \n\nFor MPO, do the same decomposition as done in Eq. \\ref{Eq:LeftMPSoperation} or in \\ref{Eq::RightMPSoperation}, but with the double index $\\sigma_i \\sigma_i'$ taking the role of index $\\sigma_i$ in MPS (i.e. do this substitution and the decomposition will proceed \\emph{exactly} as before).\n\n\\end{multicols*}\n%\\begin{multicols*}{1}\n\n\n\\[\n\\begin{tikzpicture}\n\\matrix (m) [matrix of math nodes, row sep=2.55em, column sep=7.7em, minimum width=6.2em]\n{\n\t\\text{Mat}_{\\mathbb{C}}(d^L, d^L) \\\\\n\t\\text{Mat}_{\\mathbb{C}}(1, (d^2)^{L}) & \\text{Mat}_{\\mathbb{C}}(d^2, (d^2)^{L-1}) & \\text{Mat}_{\\mathbb{C}}(d^2, r_i) \\times \\text{Mat}_{\\mathbb{C}}(r_i, r_i) \\times \\text{Mat}_{\\mathbb{C}}(r_i , (d^2)^{L-1}) & \\text{Mat}_{\\mathbb{C}}(1, r_i)^d \\times \\text{Mat}_{\\mathbb{C}}(r_i, (d^2)^{L-1}) \\\\\n\tc^{\\sigma_1 \\dots \\sigma_L, \\sigma_1' \\dots \\sigma_L'} \\\\\n\tc^{\\sigma_1 \\sigma_1' \\sigma_2 \\sigma_2' \\dots \\sigma_L \\sigma_L'} & \\Psi_{\\sigma_1 \\sigma_1', (\\sigma_{2} \\sigma_2', \\sigma_{3} \\sigma_3' \\dots \\sigma_L \\sigma_L') } & U_{ \\sigma_1\\sigma_1', a_1 } S_{a_1 a_1} V^{\\dagger}_{a_1, (\\sigma_{2} \\sigma_2' \\dots \\sigma_L \\sigma_L'} & \\sum_{\\sigma_1 \\sigma_1'} A^{\\sigma_1 \\sigma_1'}_{1, a_1} c^{a_1, \\sigma_{2}\\sigma_2' \\dots \\sigma_L\\sigma_L'} \\\\\n};\n\\path[->]\n(m-1-1) edge node [right] { \\text{reorder} } (m-2-1)\n(m-2-1) edge node [above] { \\text{reshape} } (m-2-2)\n(m-2-2) edge node [above] { \\text{SVD} } (m-2-3)\n(m-2-3) edge node [above] { \\text{slice and multiply} } (m-2-4)\n;\n\\path[|->]\n(m-3-1) edge node [right] { \\text{reorder} } (m-4-1)\n(m-4-1) edge node [above] { \\text{reshape} } (m-4-2)\n(m-4-2) edge node [above] { = } (m-4-3)\n(m-4-3) edge node [above] { = } (m-4-4)\n;\n\\end{tikzpicture} \n\\]\n\n\\begin{equation}\\label{Eq:LeftMPOoperation}\n\\begin{tikzpicture}[framed]\n\\matrix (m) [matrix of math nodes, row sep=2.55em, column sep=7.7em, minimum width=6.2em]\n{\n\t\\text{Mat}_{\\mathbb{C}}(r_{i-1}, (d^2)^{L-(i-1)}) & \\text{Mat}_{\\mathbb{C}}(r_{i-1}d^2, (d^2)^{L-i}) & \\text{Mat}_{\\mathbb{C}}(r_{i-1}d^2, r_i) \\times \\text{Mat}_{\\mathbb{C}}(r_i, r_i) \\times \\text{Mat}_{\\mathbb{C}}(r_i , (d^2)^{L-i}) & \\text{Mat}_{\\mathbb{C}}(r_{i-1}, r_i)^{d^2} \\times \\text{Mat}_{\\mathbb{C}}(r_i, (d^2)^{L-i}) \\\\\n\tc^{a_{i-1}, \\sigma_i \\sigma_i' \\sigma_{i+1} \\sigma_{i+1}' \\dots \\sigma_L \\sigma_L'} & \\Psi_{a_{i-1}\\sigma_i \\sigma_i', (\\sigma_{i+1}\\sigma_{i+1}' \\sigma_{i+2}\\sigma_{i+2}' \\dots \\sigma_L\\sigma_L') } & U_{a_{i-1} \\sigma_i \\sigma_i', a_i } S_{a_i a_i} V^{\\dagger}_{a_i, \\sigma_{i+1} \\sigma_{i+1}' \\dots \\sigma_L\\sigma_L'} & \\sum_{\\sigma_i \\sigma_i'}^{max}A^{\\sigma_i \\sigma_i'}_{a_{i-1}, a_i} c^{a_i, \\sigma_{i+1} \\sigma_{i+1}' \\dots \\sigma_L \\sigma_L'} \\\\\n};\n\\path[->]\n(m-1-1) edge node [above] { \\text{reshape} } (m-1-2)\n(m-1-2) edge node [above] { \\text{SVD} } (m-1-3)\n(m-1-3) edge node [above] { \\text{slice and multiply} } (m-1-4)\n;\n\\path[|->]\n(m-2-1) edge node [above] { \\text{reshape} } (m-2-2)\n(m-2-2) edge node [above] { = } (m-2-3)\n(m-2-3) edge node [above] { = } (m-2-4)\n;\n\\end{tikzpicture} \n\\end{equation}\n\n\n\\begin{multicols*}{2}\n\n\n\\subsubsection{Numerical implementation; both in BLAS and cuBLAS}\n\nAs stated in the \\href{http://docs.nvidia.com/cuda/cusolver/index.html#cuds-lt-t-gt-gesvd}{CUDA Toolkit Documentation v8.0} for cuSOLVER, under section 5.3.6. \\verb|cusolverDngesvd()| and Remark 1, \\verb|gesvd| \"only supports\" \\verb|m>=n|, for matrix you want to decompose $A\\in \\text{Mat}_{\\mathbb{K}}(m,n)$. So number of rows must be greater than or equal to number of columns. And so we can only consider right-normalized matrices in a practical implementation. \n\nI suspect it's the same in BLAS. \n\nConsider the very first step, $l=1$, in a procedure to calculate the matrix product state. \n\n\\begin{tikzpicture}\n \\matrix (m) [matrix of math nodes, row sep=1.95em, column sep=3.8em, minimum width=1.8em]\n {\n\t \\text{Mat}_{\\mathbb{K}}(d^{L-1},d) & U_{\\mathbb{K}}(d^{L-1},r_{L-1}) \\times \\text{diag}_{\\mathbb{K}}(r_{L-1}) \\times U_{\\mathbb{K}}(r_{L-1},d ) & \\text{Mat}_{\\mathbb{K}}(d^{L-2},d r_{L-1}) \\times ( \\text{Mat}_{\\mathbb{K}}(r_{L-1}, 1))^d & \\qquad \\, \\\\\t \n \\Psi_{(\\sigma_1\\dots \\sigma_{L-1}),\\sigma_L} & = \\sum_{a_{L-1}}^{r_{L-1}}U_{(\\sigma_1 \\dots \\sigma_{L-1}), a_{L-1}} S_{a_{L-1},a_{L-1}} (V^{\\dag})_{a_{L-1}, \\sigma_L} & \\begin{gathered}\n\tU_{(\\sigma_1 \\dots \\sigma_{L-1}), a_{L-1} } S_{a_{L-1}, a_{L-1}} = \\Psi_{(\\sigma_1\\dots \\sigma_{L-2}), (\\sigma_{L-1} a_{L-1}) } \\\\ \n(V^{\\dag})_{a_{L-1},\\sigma_L} = B^{\\sigma_L}_{a_{L-1}} \n\\end{gathered} \\\\\n};\n \\path[->]\n (m-1-1) edge node [above] { SVD } (m-1-2)\n (m-1-2) edge node [above] { $\\cong$ } (m-1-3)\n ;\n \\path[|->]\n (m-2-1) edge node [above] { SVD } (m-2-2)\n (m-2-2) edge node [above] { $\\cong$ } (m-2-3)\n ;\n\\end{tikzpicture} \nwith $\\cong$ in this case denoting an isomorphism, the \\emph{reshaping} of a matrix into different matrix size dimensions, which should be the inverse of a \"flatten\" functor, which I'll denote as $\\text{flatten}^{-1}$ as well (and this is this same isomorphism we're talking about). \n\nLet's deal with the specific procedure of $\\text{flatten}^{-1}$, how it reshapes indices in accordance with different matrix size dimensions, and with the so-called \"stride\" when going from, say, 2-dimensional indices to a \"flattened\" 1-dimensional index. \n\nNote also as a practical numerical implementation design point, LAPACK's linear algebra BLAS library package and CUBLAS assumes \\emph{column}-major ordering. \n\nConsider $i= 1,2,\\dots L-1$ (for site $i$) (or for $0$-based counting, starting to count from $0$, $i=0,1,\\dots L-2$; be aware of this difference as in practical numerical implementation, in C, C++, Python, it assumes $0$-based counting). \n\nFor a state space of dimension $d$, we can consider the specific example of $d=2$, representing say a spin-$1/2$ system. Then index $\\sigma_i$ can be $0$ or $1$: $\\sigma_i \\in \\lbrace 0 ,1\\rbrace$. In general, $\\sigma_i \\in \\lbrace 0 ,1, \\dots d-1\\rbrace$. I may use $d$ or $2$ in the context of the number of states (basis vectors) of the spin system (state vector space). \n\nConsider site $i$. Suppose the spin system there interacts most with sites $i-1$, $i+1$, and then next sites $i-2$, $i+2$, etc. So the values at $\\sigma_{i-1}, \\sigma_{i+1}$, etc. are most important in calculating interactions with spin system at site $i$. \n\nThen we seek this reshaping of the matrix index - assuming $0$-based counting/ordering, for $l=1$:\n\\begin{tikzpicture}\n \\matrix (m) [matrix of math nodes, row sep=1.95em, column sep=3.8em, minimum width=1.8em]\n {\n\t\\lbrace 0 ,1 \\rbrace^{L-1} & \\lbrace 0 ,1, \\dots 2^{L-1} -1 \\rbrace \\\\\n\t(\\sigma_0,\\sigma_1, \\dots \\sigma_{L-2}) & I_{L-1} := \\sigma_0 + 2\\sigma_1 + \\dots + 2^i \\sigma_i + \\dots + 2^{L-2}\\sigma_{L-2} = \\sum_{i=0}^{L-2} 2^i \\sigma_i \\\\\n};\n \\path[->]\n (m-1-1) edge node [above] { $(\\text{flatten})^{-1}$ } (m-1-2)\n ;\n \\path[|->]\n (m-2-1) edge node [above] { $(\\text{flatten})^{-1}$ } (m-2-2)\n ;\n\\end{tikzpicture} \n\nIn this way, states of a site $i$ are closest in memory addresses in the allocation of a 1-dim. array, on CPU or GPU memory, so that memory access operations should be efficient. \n\nAssuming SVD doesn't change the striding, and defining the result of matrix multiplication:\n\\[\nU_{(\\sigma_0, \\sigma_1 \\dots \\sigma_{L-2}), a_{L-1} } S_{a_{L-1}, a_{L-1}} =: (US)_{(\\sigma_0 \\dots \\sigma_{L-2} ), a_{L-1} } \\in \\text{Mat}_{\\mathbb{K}}(d^{L-1},r_{L-1} )\n\\]\n\nWe can reshape (i.e. $(\\text{flatten})^{-1}$) in such a manner: \n\\[\n\\begin{tikzpicture}\n \\matrix (m) [matrix of math nodes, row sep=1.95em, column sep=3.8em, minimum width=1.8em]\n {\n\t\\text{Mat}_{\\mathbb{K}}(d^{L-1},r_{L-1}) & \\text{Mat}_{\\mathbb{K}}(d^{L-2},dr_{L-1}) \\\\ \n\t(US)_{(\\sigma_0 \\dots \\sigma_{L-2} ), a_{L-1} } & \\Psi_{(\\sigma_0,\\sigma_1 ,\\dots \\sigma_{L-3}), (\\sigma_{L-2} a_{L-1}) } \\\\\n\t\\lbrace 0 ,1,\\dots 2^{L-1}-1 \\rbrace \\times \\lbrace 0 ,1,\\dots r_{L-1} -1 \\rbrace & \\lbrace 0 ,1,\\dots 2^{L-2}-1 \\rbrace \\times \\lbrace 0 ,1,\\dots dr_{L-1} -1 \\rbrace \\\\\nI_{L-1}, a_{L-1} & I_{L-1} \\mod{ 2^{L-2}} , \\frac{ I_{L-1} }{ 2^{L-2} } + da_{L-1} \\\\\n};\n \\path[->]\n (m-1-1) edge node [above] { $(\\text{flatten})^{-1}$ } (m-1-2)\n (m-3-1) edge node [above] { $(\\text{flatten})^{-1}$ } (m-3-2)\n ;\n \\path[|->]\n (m-2-1) edge node [above] { $(\\text{flatten})^{-1}$ } (m-2-2)\n (m-4-1) edge node [above] { $(\\text{flatten})^{-1}$ } (m-4-2)\n ;\n\\end{tikzpicture} \n\\]\nReshaping $V^{\\dag}$ at iteration $l=1$ can be done as follows: \n\\[\n\\begin{tikzpicture}\n \\matrix (m) [matrix of math nodes, row sep=1.95em, column sep=3.8em, minimum width=1.8em]\n {\n\tU_{\\mathbb{K}}(r_{L-1},d) & ( \\text{Mat}_{\\mathbb{K}}( r_{L-1} , 1) )^d \\\\ \n\t(V^{\\dag})_{a_{L-1},\\sigma_{L-1 } } & (V^{\\dag})_{a_{L-1},\\sigma_{L-1} } = B_{a_{L-1}}^{\\sigma_{L-1}} \\\\\n\t\\lbrace 0 ,1,\\dots r_{L-1} -1 \\rbrace \\times \\lbrace 0 ,1,\\dots d -1 \\rbrace & ( \\lbrace 0 ,1,\\dots r_{L-1}-1 \\rbrace )^d \\\\\na_{L-1}, \\sigma_{L-1} & a_{L-1} \\\\\n};\n \\path[->]\n (m-1-1) edge node [above] { $(\\text{flatten})^{-1}$ } (m-1-2)\n (m-3-1) edge node [above] { $(\\text{flatten})^{-1}$ } (m-3-2)\n ;\n \\path[|->]\n (m-2-1) edge node [above] { $(\\text{flatten})^{-1}$ } (m-2-2)\n (m-4-1) edge node [above] { $(\\text{flatten})^{-1}$ } (m-4-2)\n ;\n\\end{tikzpicture} \n\\]\n\nLet's do this same procedure, reshaping or $(\\text{flatten})^{-1}$, for a general $l$ iteration. \n\n\\[\n\\begin{tikzpicture}\n \\matrix (m) [matrix of math nodes, row sep=1.95em, column sep=3.8em, minimum width=1.8em]\n {\n\t\\text{Mat}_{\\mathbb{K}}(d^{L-l},r_{L-l}) & \\text{Mat}_{\\mathbb{K}}(d^{L-(l+1)},dr_{L-l}) \\\\ \n\t(US)_{(\\sigma_0 \\dots \\sigma_{L-(l+1)} ), a_{L-l } } & \\Psi_{(\\sigma_0,\\sigma_1 ,\\dots \\sigma_{L-(l+2)}), (\\sigma_{L-(l+1)} a_{L-l}) } \\\\\n\t\\lbrace 0 ,1,\\dots d^{L-l}-1 \\rbrace \\times \\lbrace 0 ,1,\\dots r_{L-l} -1 \\rbrace & \\lbrace 0 ,1,\\dots d^{L-(l+1)}-1 \\rbrace \\times \\lbrace 0 ,1,\\dots dr_{L-l} -1 \\rbrace \\\\\nI_{L-l}, a_{L-l} & I_{L-l} \\mod{ d^{L-(l+1)}} , \\frac{ I_{L-l} }{ d^{L-(l+1)} } + da_{L-l} \\\\\n};\n \\path[->]\n (m-1-1) edge node [above] { $(\\text{flatten})^{-1}$ } (m-1-2)\n (m-3-1) edge node [above] { $(\\text{flatten})^{-1}$ } (m-3-2)\n ;\n \\path[|->]\n (m-2-1) edge node [above] { $(\\text{flatten})^{-1}$ } (m-2-2)\n (m-4-1) edge node [above] { $(\\text{flatten})^{-1}$ } (m-4-2)\n ;\n\\end{tikzpicture} \n\\]\n\n\\[\n\\begin{tikzpicture}\n \\matrix (m) [matrix of math nodes, row sep=1.95em, column sep=3.8em, minimum width=1.8em]\n {\n\tU_{\\mathbb{K}}(r_{L-l},dr_{L-(l-1)}) & ( \\text{Mat}_{\\mathbb{K}}( r_{L-l} , r_{L-(l-1)}) )^d \\\\ \n\t(V^{\\dag})_{a_{L-l}, (\\sigma_{L-l } a_{L-(l-1)}) } & (V^{\\dag})_{a_{L-l}, ( \\sigma_{L-l} a_{L-(l-1)} ) } = B^{\\sigma_{L-l}}_{a_{L-l}, a_{L-(l-1)}} \\\\\n\t\\lbrace 0 ,1,\\dots r_{L-l} -1 \\rbrace \\times \\lbrace 0 ,1,\\dots d r_{L-(l-1)} -1 \\rbrace & ( \\lbrace 0 ,1,\\dots r_{L}-1 \\rbrace \\times \\lbrace 0 ,1,\\dots r_{L-(l-1)}-1 \\rbrace )^d \\\\\na_{L-l}, ( \\sigma_{L-l} a_{L-(l-1)} ) := a_{L-l}, \\sigma_{L-1} + da_{L-(l-1)} & a_{L-l} , \\frac{ (\\sigma_{L-1} a_{L-(l-1)} ) }{d} \\, ; \\, \\sigma_{L-l} = (\\sigma_{L-l} a_{L-(l-1)} ) \\mod{d} \\\\\n};\n \\path[->]\n (m-1-1) edge node [above] { $(\\text{flatten})^{-1}$ } (m-1-2)\n (m-3-1) edge node [above] { $(\\text{flatten})^{-1}$ } (m-3-2)\n ;\n \\path[|->]\n (m-2-1) edge node [above] { $(\\text{flatten})^{-1}$ } (m-2-2)\n (m-4-1) edge node [above] { $(\\text{flatten})^{-1}$ } (m-4-2)\n ;\n\\end{tikzpicture} \n\\]\n\n\\subsubsection{Numerical implementations of initial states}\n\nSomething else that shouldn't be overlooked is the numerical implementation of \\emph{initial states}, the $c$'s of a state $| \\psi \\rangle = \\sum_{ \\lbrace \\sigma \\rbrace } c^{\\sigma} | \\lbrace \\sigma \\rbrace \\rangle$ for a many-body quantum system. Remember what the postulates of quantum mechanics say and interpret accordingly (and correctly). While we call them \"probability amplitudes\", one should be careful about what physical interpretation we may (or may not!) assign them. One thing's for certain: $c \\in \\mathbb{C}$ and normalization of the quantum state: $ | \\langle \\psi | \\psi \\rangle |^2 = 1$\n\nHere are some setups to try:\n\n$d= 2, L=2$, $d^L = 2^2=4$.\n\\[\n\\left[ \\begin{matrix} c_{\\uparrow \\uparrow} & c_{\\uparrow \\downarrow} & c_{\\downarrow \\uparrow} & c_{\\downarrow \\downarrow} \\end{matrix} \\right] \\mapsto \\left[ \\begin{matrix} c_{\\uparrow \\uparrow} & c_{\\uparrow \\downarrow} \\\\\nc_{\\downarrow \\uparrow} & c_{\\downarrow \\downarrow} \\end{matrix} \\right]\n\\]\n\nSinglet state: $|\\psi \\rangle = \\frac{1}{ \\sqrt{2}} | \\uparrow \\downarrow \\rangle - \\frac{1}{\\sqrt{2}} | \\downarrow \\uparrow \\rangle $, $\\left[ \\begin{matrix} 0 & \\frac{1}{\\sqrt{2}} \\\\ \\frac{-1}{\\sqrt{2}} & 0 \\end{matrix} \\right]$ \n\n$d=2, L=3, d^L = 2^8 = 8$\n\nFor notational convenience, let $\\uparrow \\equiv 1$, $\\downarrow \\equiv 0$\n\n\\[\n\\left[ \\begin{matrix} c_{000} & c_{001} & c_{010} & c_{011} & c_{100} & \\dots & c_{111} \\end{matrix} \\right] \\mapsto \\left[ \\begin{matrix} c_{000} & c_{001} & \\dots & c_{011} \\\\\nc_{100} & c_{001} & \\dots & c_{111} \\end{matrix} \\right]\n\\]\n\n$d=3, L=2$, $d^L = 3^2 = 9$\n\n\\[\n\\left[ \\begin{matrix} c_{-1-1} & c_{-10 } & c_{-11} & \\dots & c_{11} \\end{matrix} \\right] \\mapsto \\left[ \\begin{matrix} c_{-1-1} & c_{-10} & c_{-11} \\\\\nc_{0-1} & c_{00} & c_{01} \\\\ \nc_{1-1} & c_{10} & c_{11} \\end{matrix} \\right]\n\\]\n\n\n%\\end{multicols*}\n%\\begin{multicols*}{2}\n\n\n\n\n\n\n\n%\\end{multicols*}\n\n\\part{Algebraic Geometry}\n\n\\section{Affine and Projective Varieties}\n\ncf. Harris (1992)\\cite{Har1992}\n\nFor (algebraically closed) field $K$, \\\\\nvector space $K^n$, \\\\\naffine space $\\mathbb{A}^n_K \\equiv \\mathbb{A}^n = K^n$, but origin plays no special role in affine space. \\\\\nAffine variety $X \\subset \\mathbb{A}^n := $ common zero locus of collection of polynomials $f_{\\alpha} \\in K [z_1 \\dots z_n] :=$ \n\\[\nX = \\lbrace Z | f_{\\alpha}(Z) = 0 \\quad \\, \\forall \\, \\alpha , \\quad \\, f_{\\alpha} \\in K(z_1 \\dots z_n), Z = (z_1 \\dots z_n) \\rbrace \n\\]\n\n\\subsection{Projective Space and Projective Varieties} \n\nProjective space over field $K = $ set of 1-dim. subspaces of vector space $K^{n+1} \\equiv \\mathbb{P}^n_K \\equiv \\mathbb{P}^n = (K^{n+1} - \\lbrace 0 \\rbrace ) / K^*$, \\\\\nwhere $(K^{n+1} - \\lbrace 0 \\rbrace ) / K^*$ is the quotient of $K^{n+1} - \\lbrace 0 \\rbrace$ by the action of the group $K^n$ acting by scalar multiplication. \n\n$\\mathbb{P}(V) \\equiv \\mathbb{P}V \\equiv $ projective space of 1-dim. subspaces of a vector space $V$ over field $K$. \\\\\n$P \\in \\mathbb{P}^n$ usually written as homogeneous vector $[Z_0 \\dots Z_n]$, by which be mean line spaced by $(Z_0 \\dots Z_n) \\in K^{n+1}$. \n\nFor $U_n$ s.t. $\\forall \\, P \\in U_n \\subset \\mathbb{P}^n \\subset V^{n+1}$, $Z_n \\neq 0$. Then $[Z_0 \\dots Z_n] \\sim \\left[ \\frac{ Z_0}{ Z_n} , \\dots , \\frac{Z_{n-1}}{Z_n} , 1 \\right] \\cong \\left[ \\frac{Z_0}{Z_n} , \\dots \\frac{Z_{n-1}}{ Z_n } \\right] \\in K^n$. \n\n$\\forall \\, v \\neq 0$ , $v\\in V$, $[v] = $ corresponding pt. in $\\mathbb{P}V \\cong \\mathbb{P}^n$\n\nPolynomial $F \\in K[Z_0 \\dots Z_n]$ on vector space $K^{n+1}$ doesn't define a function on $\\mathbb{P}^n$, but \\\\\nif $F$ is homogeneous of degree $d$, \\\\\n\\phantom{if }then since \n\\[\n\tF(\\lambda Z_0 , \\dots , \\lambda Z_n) = \\lambda^d F(Z_0 \\dots Z_n)\n\\]\nit does make sense to talk about $0$ locus of polynomial $F$.\n\n\\begin{definition}[Projective variety]\n\tprojective variety $X \\subset \\mathbb{P}^n = \\lbrace P | F_{\\alpha}(P) = 0 \\, \\, \\forall \\, \\alpha, \\, \\, F_{\\alpha}(\\lambda P) = \\lambda^d F_{\\alpha}(P) \\rbrace = $ zero locus of a collection of homogeneous polynomials $F_{\\alpha}$. \n\\end{definition}\n\nGroup $PGL_{n+1}K$ acts on space $\\mathbb{P}^n$ (in Lecture 18, $PGL_{n+1}K$ are automorphisms of $\\mathbb{P}^n$).\n\nVarieties $X, Y \\subset \\mathbb{P}^n$ are projectively equivalent, if they're congruent, modulo this group.\n\nNote that if $\\mathbb{P}^n = \\mathbb{P}V$ is projective space associated with vector space $V$, \\\\\n\\begin{itemize}\n\t\\item homogeneous coordinates on $\\mathbb{P}V$ correspond to elements of dual space $V^*$ \n\t\\item similarly, space of homogeneous polynomials of degree $d$ on $\\mathbb{P}V$ naturally identified with vector space $\\text{Sym}^d(V^*)$\n\\end{itemize}\nMeaning, set of linear coordinates on vector space $V$, $\\text{dim}V = n$, over field $K$ (so $V= K^n$), $\\alpha_i \\equiv z_i$, $i=1 \\dots n$, is a \\emph{basis} $(\\alpha_i)$ of $V^*$, since \n\\[\n\\begin{gathered}\n\t\\begin{gathered}\n\t\\alpha : V \\to K^n \\\\\n\tv \\mapsto (\\alpha_1(v) , \\dots \\alpha_n(v)) \n\t\\end{gathered} \\text{ i.e. } \\equiv \\begin{gathered}\n\tz : V \\to K^n \\\\\n\tv \\mapsto (z_1(v) \\dots z_n(v))\n\t\\end{gathered}\n\\end{gathered}\n\\]\n\nNow $\\mathbb{P}(V) = (V \\backslash \\lbrace 0 \\rbrace ) / K^*$ and homogeneous coordinates on $\\mathbb{P}(V)$ are just linear coordinates on $V$ up to action $K^*$\n\ncf. \\href{https://math.stackexchange.com/questions/62588/correspondence-between-the-projective-space-associated-to-a-vector-space-and-the}{\"Correspondence between the projective space associated to a vector space and the dual space of the vector space?\", stackexchange}, \\href{https://math.stackexchange.com/questions/2093271/can-dual-vector-spaces-be-thought-of-as-linear-coordinate-functions}{Can dual vector spaces be thought of as linear coordinate functions? stackexchange}\n\nFrom $Z_i \\in V^*$, $i = 0, 1 \\dots n$, $Z_i : V \\to K$, $Z_i : v \\mapsto Z_i(v) = Z_i \\in K$, \\\\\nlet $f$ be a homogeneous polynomial of degree $d$ on $\\mathbb{P}V$:\n\\[\nf = \\sum a_{i_0 i_1 \\dots i_n} z_0^{i_0} z_1^{i_1} \\dots z_n^{i_n} \n\\]\nwhere summation $\\sum$ is over $0 \\leq i_0, i_1, \\dots i_n \\leq d$ s.t. $\\sum_{j=0}^n i_j = d$.\n\n$\\text{dim}{\\text{Sym}^d(V^*)} = \\binom{d+n}{n}$\n\n$\\lbrace z_0^{i_0} z_1^{i_1} \\dots z_n^{i_n} \\rbrace_{ \\substack{ 0 \\leq i_0 , i_1 \\dots i_n \\leq d \\\\ \\sum_{j=0}^n i_j = d } }$ form a basis for $\\text{Sym}^d(V^*)$\n \nLet $U_i \\subset \\mathbb{P}^n$, $U_i = \\lbrace [Z_0 \\dots Z_n ] | Z_i \\neq 0 \\rbrace$. Then $[Z_0 \\dots Z_n ] \\sim \\left[ \\frac{Z_0}{Z_i} \\dots \\frac{Z_{i-1}}{ Z_i }, 1 \\dots \\frac{Z_n}{Z_i} \\right] \\equiv [ z_0, \\dots z_{i-1} , 1 , z_i \\dots z_{n-1} ] \\cong (z_0 , z_1 \\dots z_{n-1}) \\in K^n$. \n\nSo there's a bijection $U_i \\to K^n$.\n\nGeometrically, this map is associating line $L \\subset K^{n+1}$ not contained in hyperplane ($Z_i = 0$), its pt. $p$ of intersection with affine plane $(Z_i = 1) \\subset K^{n+1}$. \n\nCoordinates $z_j$ on $U_i$ are called affine or Euclidean coordinates on projective space or open set $U_i$ \\\\\n- open sets $U_i$ comprise standard cover of $\\mathbb{P}^n$ by affine open sets.\n\nIf $X \\subset \\mathbb{P}^n$ is a variety, $X_i = X \\cup U_i$ is affine variety: \\\\\nif $X$ given by polynomials $F_{\\alpha} \\in K[Z_0 , \\dots Z_n]$, then e.g. $X_0$ will be zero locus of polynomials\n\\[\n\\begin{gathered}\nf_{\\alpha}(z_0 \\dots z_n) = F_{\\alpha}(Z_0 \\dots Z_n) / Z_0^d = F_{\\alpha}(1, z_1 \\dots z_n)\n\\end{gathered}\n\\]\nwhere $d = \\deg{F_{\\alpha}}$. \n\nFor (projective) variety $X \\subset \\mathbb{P}^n$, $X = \\lbrace P | F_{\\alpha}(P) = 0, \\forall \\, \\alpha, F_{\\alpha} \\text{ homogeneous, } P = [ Z_0 , Z_1 \\dots Z_n] \\in \\mathbb{P}^n \\rbrace$, \\\\\nobtain affine variety $X_i = X \\cup U_i$ as follows: for \n\\[\nz_j = \\begin{cases} \\frac{ Z_{j-1}}{ Z_i } & j \\leq i \\\\ \\frac{Z_j}{ Z_i} , & j > i \\end{cases}\n\\]\n\n\\[\n\\begin{gathered}\nf_{\\alpha}(z_1 \\dots z_n) = f_{\\alpha}\\left( \\frac{Z_0}{Z_i} , \\dots \\frac{Z_{i-1}}{Z_i} , \\frac{Z_{i+1}}{Z_i} \\dots \\frac{Z_n}{Z_i} \\right) = \\frac{1}{Z_i}^{d_{\\alpha}} F_{\\alpha}(Z_0 \\dots Z_n) = F_{\\alpha}(z_1 \\dots z_i, 1, z_{i+1}, \\dots z_n)\n\\end{gathered}\n\\]\n\nIf $F_{\\alpha}(Z_0 \\dots Z_n) = 0$, then $f_{\\alpha}(z_1 \\dots z_n) =0$\n\n$\\forall \\, $ projective variety $X$, $X$ is union of affine varieties. \n\nIf affine variety $X_i \\subset K^n \\cong U_i \\subset \\mathbb{P}^n$, by def. $X_i$ given by polynomials $\\lbrace f_{\\alpha} \\rbrace_{\\alpha}$\n\n\\[\nf_{\\alpha} (z_1 \\dots z_n) = \\sum a_{i_1 \\dots i_n} z_1^{i_1} \\dots z_n^{i_n} = 0\n\\]\nof degree $d_{\\alpha}$ (i.e. $i_1+ \\dots i_n = d_{\\alpha}$)\n\nThen\n\\[\n\\begin{gathered}\nF_{\\alpha}(Z_0 \\dots Z_n) = Z_i^{D_{\\alpha}} F_{\\alpha}\\left( \\frac{ Z_0}{Z_i} \\dots \\frac{Z_n}{Z_i} \\right) = Z_i^{D_{\\alpha}}f_{\\alpha}(z_1 \\dots z_n) = \\sum a_{i_1 \\dots i_n} Z_i^{D_{\\alpha} - \\sum i_l} Z_0^{i_0} \\dots Z_n^{i_n} = \\\\\n= \\sum a_{i_1 \\dots i_n} Z_i^{ D_{\\alpha} - d_{\\alpha}} Z_0^{i_0} \\dots \\widehat{Z}_i^{i_i} \\dots Z_n^{i_n}\n\\end{gathered}\\]\n\n\\subsubsection{Example: ellipse}\n\n\\begin{equation}\n\\begin{gathered}\n\\mathbb{P}^n \\to U_Z \\cong K^n \\\\\n[X,Y,Z] \\mapsto (x,y) = \\left( \\frac{X}{Z}, \\frac{Y}{Z} \\right) \n\\end{gathered}\n\\end{equation}\n\nConsider \n\\begin{equation}\n\\frac{x^2}{a^2} + \\frac{y^2}{b^2} = 1 \\text{ or } f(x,y) = \\frac{x^2}{a^2} + \\frac{y^2}{b^2} -1\n\\end{equation}\n\nFor affine variety $X_Z \\subset K^2$, \n\\begin{equation}\nF(X,Y,Z) = \\left( \\frac{X^2}{Z^2 a^2} + \\frac{Y^2}{Z^2 b^2} - 1 \\right) Z^2 = \\frac{X^2}{a^2} + \\frac{Y^2}{b^2} - Z^2\n\\end{equation}\n\n\n\n\\section{Algebraic Curves; Conic sections}\n\ncf. Reid (2013) \\cite{Reid2013}.\n\ncf. Ch. 0 \"Woffle\" of Reid (2013) \\cite{Reid2013}.\n\nGiven field $k$, $k[x_1 \\dots x_n]$ colelction of all polynomials in $x_1 \\dots x_n$, with coefficients in $k$, \n\\[\nf \\in k[x_1 \\dots x_n] = \\lbrace f | f = \\sum_{\\alpha} c_{\\alpha} x^{\\alpha}, x^{\\alpha} = x_1^{\\alpha_1} \\dots x_n^{\\alpha_n}, \\, c_{\\alpha} \\in k \\rbrace \n\\]\nVariety is (roughly) locus defined by polynomial equations\n\\[\nV = \\lbrace P \\in k^n | f_i(P) = 0 \\rbrace \\subset k^n, \\, f_i \\in k[x_1 \\dots x_n]\n\\]\ne.g. plane curves $C$: $(f(x,y) = 0) \\subset \\mathbb{R}^2$ or $\\mathbb{C}^2$\n\n\nGroups of transformations (i.e. transformation groups) are of central importance throughout geometry; properties of geometric figures must be invariant under appropriate kind of transformations before they're significant.\n\n\\emph{affine change of coordinates in} $\\mathbb{R}^2$ is of form\n\\begin{equation}\nT(\\mathbf{x}) = A \\mathbf{x} + B \\quad \\, (\\text{affine change of coordinates})\n\\end{equation}\nwhere $\\mathbf{x} = (x,y) \\in \\mathbb{R}^2$, $A$ $2\\times 2$ invertible matrix (i.e. $A \\in GL(2, \\mathbb{R})$), $B\\in \\mathbb{R}^2$. \n\nIf $A$ orthogonal, transformation $T$ is \\emph{Euclidean}.\n\n$\\forall \\, $ nondegenerate conic can be reduced to \"standard form\" by Euclidean transformation.\n\n\\textbf{projectivity} or projective transformation $\\mathbb{P}^2_{\\mathbb{R}}$ is map $T(\\mathbf{X}) = M \\mathbf{X}$, $M \\in GL(3, \\mathbb{R})$. \n\nUnderstand $T$ on affine piece $\\mathbb{R}^2 \\subset \\mathbb{P}^2_{\\mathbb{R}}$ is partially defined map $\\mathbb{R}^2 \\to \\mathbb{R}^2$; it's a fractional linear transformation.\n\n\\[\n\\begin{gathered}\n\t\\begin{aligned}\n\t& (x,y) \\xmapsto{\\cong} [x,y, 1] \\\\\n\t& (x,y) \\mapsto \\left( \\begin{matrix} A \\left( \\begin{matrix} x \\\\ y \\end{matrix} \\right) + B \\\\ cx + dy + e \\end{matrix} \\right) \n\t\\end{aligned}\n\\end{gathered}\n\\]\nwhere \n\\[\nM = \\left( \\begin{array}{c|c} A & B \\\\ \\begin{matrix} c & d \\end{matrix} & e \\end{array} \\right) \n\\]\ne.g. 2 different photographs of same (plane) object are obviously related by a projectivity.\n\nFor inhomogeneous quadratic polynomial $q$, homogeneous quadratic polynomial $Q$, then there exists bijection\n\\[\n\\begin{gathered}\n\tq \\in K[x,y] \\xmapsto{\\cong} Q \\in K[X,Y,Z] \\\\\n\tq(x,y) = ax^2 + bxy + cy^2 + dx + ey + f \\mapsto Q(X,Y,Z) = aX^2 + bXY + cY^2 + dXZ + eYZ + fZ^2 \n\\end{gathered}\n\\]\nso\n\\[\nq(x,y) = Q\\left( \\frac{X}{Z} , \\frac{Y}{Z} , 1 \\right) \\text{ with } x= X/Z, \\, y = Y/Z\n\\]\ninverse:\n\\[\nQ = Z^2 q(X/Z, Y/Z)\n\\]\n\n\n\\subsubsection{\"Line at infinity\" and asymptotic directions}\n\ncf. Ch. 1 of Reid (2013)\n\nPoints of $\\mathbb{P}^2$ with $Z=0$, $[X,Y,0]$, form \\emph{line at infinity}, a copy of $\\mathbb{P}^1_{\\mathbb{R}} = \\mathbb{R} \\cup \\lbrace \\infty \\rbrace$ (since $[X,Y] \\mapsto X/Y$) define bijection $\\mathbb{P}^1_{\\mathbb{R}} \\to \\mathbb{R} \\cup \\lbrace \\infty \\rbrace$. \n\nLine in $\\mathbb{P}^2$, $L$, $L: = \\lbrace [ X, Y,Z] | aX + bY + cZ = 0 \\rbrace$. \n\n$L$ passes through $(X,Y,0) \\Longleftrightarrow a X + bY = 0$. \n\n\n\n\\begin{enumerate}\n\t\\item[(a)] hyperbola $\\left( \\frac{x^2}{a^2} - \\frac{y^2}{b^2} = 1 \\right)$. Recall that the lines of asymptotes (asymptotic lines). They are found in the following manner: \n\t\\[\n\t\\begin{gathered}\n\t\\frac{(bx-ay)(bx + ay)}{a^2 b^2} = 1 \\text{ or } \\frac{bx-ay}{a^2 b^2} = \\frac{1}{ bx + ay} \\xrightarrow{ x,y \\to \\infty} \\frac{bx- ay}{a^2 b^2 } =0 \\text{ or } y = \\frac{b}{a} x\n\t\\end{gathered}\\]\n\t\n\tNow, $\\left( \\frac{x^2}{a^2} - \\frac{y^2}{b^2} = 1 \\right)$ in $\\mathbb{R}^2$ \n\tcorresponds in $\\mathbb{P}^2_{\\mathbb{R}}$ to $C: \\left( \\frac{X^2}{a^2} - \\frac{Y^2}{b^2} = Z^2 \\right)$.\n\t\n\tThis meets ($Z=0$) in 2 pts. $(a, \\pm b, 0) \\in \\mathbb{P}^2_{\\mathbb{R}}$, corresponding to asymptotic lines of hyperbola, $y = \\frac{b}{a}x$, $y = \\frac{-b}{a} x$\n\t\n\tFor affine piece $U_x \\subset \\mathbb{P}^2_{\\mathbb{R}}$, $U_x = \\lbrace p \\in \\mathbb{P}^2_{\\mathbb{R}} | p = [X,Y,Z] \\text{ s.t. } X \\neq 0 \\rbrace$, then \\\\\n\tbijection $U_x \\to \\mathbb{R}^2$, \n\t\\[\n\t\\begin{gathered}\n\t[X,Y,Z \\sim [1, \\frac{Y}{X}, \\frac{Z}{X} ] \\mapsto (u,v) = \\left( \\frac{Y}{X}, \\frac{Z}{X} \\right), \\text{ so } \\\\\n\tC : X^2/a^2 - Y^2/b^2 = Z^2 \\mapsto u^2 + \\frac{v^2}{b^2} = \\frac{1}{a^2} \\text{ or } \\frac{u^2}{1/a^2} + \\frac{v^2}{ (b/a)^2 } = 1 \\qquad \\, (\\text{an ellipse!})\n\t\\end{gathered}\n\t\\]\n\t\\item[(b)] $y = mx^2$ (parabola) in $\\mathbb{R}^2 \\mapsto C: YZ = mX^2$ in $\\mathbb{P}^2_{\\mathbb{R}}$.\n\t\n\tFor $Z = 0$, $C$ meets $Z=0$ at single pt. $[0, 1, 0] \\sim [0, Y, 0]$. So in $\\mathbb{P}^2$, \"2 branches of parabola meet at infinity.\"\n\\end{enumerate} \n\n\\subsubsection{Classification of conics in $\\mathbb{P}^2$}\n\ncf. 1.6. Classification of conics in $\\mathbb{P}^2$, Reid (2013) \\cite{Reid2013}\n\nLet $K$ be any field of characteristic $\\neq 2$.\n\nRecall 2 linear algebra results for quadratic forms:\n\n\\begin{proposition}\n\t$\\exists \\, $ bijections\n\t\n\t$\\lbrace \\text{ homogeneous quadratic polynomials } \\rbrace = \\lbrace \\text{ quadratic forms $K^3 \\to K$ } \\rbrace \\cong \\lbrace \\text{ symmetric bilinear forms on $K^3$ } \\rbrace $\ngiven by\n\\[\n\\begin{gathered} \n\taX^2 + 2bXY + cY^2 + 2dXZ + 2eYZ + fZ^2 \\cong \\left( \\begin{matrix} a & b & d \\\\ b & c & e \\\\ d & e & f \\end{matrix} \\right) \\text{ since } \\\\\n\t[ \\begin{matrix} X & Y & Z \\end{matrix} ] \\left( \\begin{matrix} a & b & d \\\\ b & c & e \\\\ d & e & f \\end{matrix} \\right) \\left[ \\begin{matrix} X \\\\ Y \\\\ Z \\end{matrix} \\right] = aX^2 + 2bXY + cY^2 + 2d XZ +2eYZ + fZ^2 \n\\end{gathered} \n\\]\n\\end{proposition}\nQuadratic form nondegenerate if corresponding bilinear form nondegenerate, i.e. matrix is nonsingular.\n\n\\begin{theorem}\\label{Thm:DiagonalizedQuadraticForm}\nLet $V$ be vector space over $K$, quadratic form $Q:V \\to K$, then $\\exists \\, $ basis of $V$ s.t.\n\\begin{equation}\nQ = \\epsilon_1 x_1^2 + \\epsilon_2 x_2^2 + \\dots + \\epsilon_n x_n^2 \\text{ with } \\epsilon_i \\in K\n\\end{equation}\n\\end{theorem}\nThis theorem is proved by Gram-Schmidt orthogonalization.\n\nFor $\\lambda \\in K \\backslash \\lbrace 0 \\rbrace$, $x_i \\mapsto \\lambda x_i$ takes $\\epsilon_i \\mapsto \\lambda^{-2} \\epsilon_i$. \n\n\\begin{corollary}\\label{Cor:ConicsClassification}\nIn a suitable coordinate system, any conic in $\\mathbb{P}^2$ is one of \n\\begin{enumerate}\n\\item[(a)] nondegenerate conic $C: (X^2 + Y^2- Z^2 =0)$\n\\end{enumerate}\n\\end{corollary}\n\n\\subsubsection{Parametrization of a conic}\n\nLet $C$ be a nondegenerate, nonempty conic of $\\mathbb{P}^2_{\\mathbb{R}}$.\n\nThen by Corollary \\ref{Cor:ConicsClassification} (cf. Corollary 1.6 (cf. Reid (2013) \\cite{Reid2013}), and taking new coordinates $[X+Z, Y, Z-X]$, \n\\[\nX^2 + Y^2-Z^2 = 0 \\mapsto (X+Z)^2 + Y^2 - (Z-X)^2 = X^2 + 2XZ + Z^2 + Y^2 - (Z^2 - 2ZX + X^2) = Y^2 + 4XZ = 0\n\\]\n$\\Longrightarrow C$ is projectively equivalent to curve $(Y^2 =XZ)$.\n\nThis is a curve parametrized by \n\\[\n\\begin{aligned} \n& \\Phi : \\mathbb{P}^1_{\\mathbb{R}} \\to C \\subset \\mathbb{P}^2_{\\mathbb{R}} \\\\\n& [U,V] \\mapsto [ U^2, UV, V^2]\n\\end{aligned} \n\\]\n\nThis is because \n\\[\n\\begin{gathered}\n\t[X, Y, Z ] \\sim [X^2 , XY , XZ ] = [X^2 , XY, Y^2]\n\\end{gathered}\n\\]\nand so let $U=X, V=Y$. Note that if $X \\mapsto X+Z$, then $U=X+Z$. \n\nInverse map $\\Psi = \\Phi^{-1}$, $\\Psi : C \\to \\mathbb{P}^1_{\\mathbb{R}}$ given by \n\\[\n[X,Y,Z] \\mapsto [X,Y] = [Y,Z]\n\\]\n$[X,Y]$ defined if $X \\neq 0$, $[Y,Z]$ defined if $Z\\neq 0$.\n\n$\\Phi, \\Psi$ are inverse isomorphisms of varieties. \n\n\n\n\n\ncf. Ch. 2 \"Cubics and the group law\" of Reid (2013) \\cite{Reid2013}.\n\ncf. Sec. 2.1 \"Examples of parametrized cubics\" in Ch. 2 of Reid (2013) \\cite{Reid2013}.\n\nNodal cubic: $C: (y^2 = x^3 + x^2) \\subset \\mathbb{R}^2$, is image of map $\\varphi : \\mathbb{R}^1 \\to \\mathbb{R}^2$, $t \\mapsto (t^2 - 1, t^3 - t)$, since \n\\[\n\\begin{gathered}\n\t(t^2 - 1)^3 + (t^2 - 1)^2 = t^6- 3t^4 + 3t^2 - 1 + t^4 - 2t^3 + 1 = t^6 - 2t^4 + t^2 = t^2 (t^4 - 2t^2 + 1) = t^2 (t^2 -1)^2 = y^2\n\\end{gathered}\n\\]\n\nCuspidal cubic \n$C : (y^2 = x^3) \\subset \\mathbb{R}^2$ is image of $\\varphi: \\mathbb{R}^1 \\to \\mathbb{R}^2$, $t\\mapsto (t^2 , t^3)$\n\n\\subsubsection{Curve $y^2 = x(x-1)(x-\\lambda )$ has no rational parametrization}\n\ncf. Sec. 2.2 \"Curve $y^2 = x(x-1)(x-\\lambda)$\" in Ch. 2 of Reid (2013) \\cite{Reid2013}.\n\n$f = f(t)$ \\emph{rational function} if it's a quotient of 2 polynomials. \n\n\\begin{lemma}\\label{Lem:SquaresOfCoprimesAreConstant}\n\tLet $\\overline{K}$ algebraically closed field, $p, q \\in \\overline{K}[t]$ coprime elements (i.e. if $\\exists \\, x $ s.t. $p/x$, $q/x \\in \\overline{K}$ (i.e. $x | p$, $x | q$), then $x=1$), \\\\\n\tassume 4 distinct linear combinations (i.e. $\\lambda p + \\mu q$ for 4 distinct ratios $(\\lambda : \\mu) \\in \\mathbb{P}^1K$) are squares in $\\overline{K}[t]$, \\\\ \n\tthen $p,q \\in \\overline{K}$\n\\end{lemma}\n\ncf. Lemma 2.3 of Reid (2013) \\cite{Reid2013}\n\n\\begin{proof}\n\t(Fermat's method of \"infinite descent\")\n\t\n\tWithout loss of generality, \n\t\\[\n\t\\begin{aligned}\n\t\t& p' = ap + bq \\\\ \n\t\t& q' = cp + dq\n\t\\end{aligned}\n\t\\]\n\t$a,b,c, d \\in K$, $ad-bc \\neq 0$. \n\t\n\tHence, assume 4 given squares are \n\t\\[\n\tp, p-q, p-\\lambda q , q\n\t\\]\n\ti.e. $\\lambda p + \\mu q$, for $\\lambda = 1, \\mu = 0$; $\\lambda = 1, \\mu = -1$; $\\lambda = 1, \\mu = -\\lambda$; $\\lambda = 0, \\mu = 1$\n\t\n\tSince $a,b,c,d$ arbitrary linear transformation.\n\t\n\tThen $p = u^2, q = v^2$, $u,v \\in \\overline{K}[t]$ are coprime, with \n\t\\[\n\t\\max{ (\\deg{u} , \\deg{v} )} < \\max{ (\\deg{p}, \\deg{q})}\n\t\\]\n\tSuppose $\\max{(\\deg{p}, \\deg{q})} >0$ and is minimal among all $p,q$ satisfying lemma condition.\n\t\n\tThen \n\t\\[\n\t\\begin{aligned}\n\t& p - q = u^2 - v^2 = (u-v)(u+v) \\\\\n\t& p - \\lambda q = u^2 - \\lambda v^2 = (u-\\mu v) (u + \\mu v)\n\t\\end{aligned}\n\t\\]\n\twhere $\\mu = \\sqrt{\\lambda}$, are squares in $\\overline{K}[t]$. \n\t\n\tSo by $u,v $ being coprime, \\\\\n\t\\phantom{ \\qquad \\, } Then $u-v, u+v, u- \\mu v, u + \\mu v$ are squares.\n\t\n\tThis contradicts minimality of $\\max{(\\deg{p}, \\deg{q})}$\n\n\n\\end{proof}\t\n\n\n\n\n\n\\begin{theorem}[$y^2 = x(x-1)(x-\\lambda)$ has no rational parametrization]\\label{Thm:SomeEqnHasNoRationalParametrization}\n\tLet $K$ be field of characteristic $\\neq 2$, let $\\lambda \\in K$, $\\lambda \\neq 0, 1$; let $f,g \\in K(t)$ be rational functions s.t.\\[\n\tf^2 = g(g-1)(g-\\lambda)\n\t\\]\n\tThen $f, g\\in K$. \t\n\\end{theorem}\n\tEY (20181229). Recall, \\emph{characteristic of ring} $R$ (e.g. field), $\\text{char}(K)$, smallest number of times $1$ must using ring's multiplicative identity $1$ in a sum to get additive identity ($0$). \n\t\n\t$\\text{char}(K) = 0$ for case that $\\underbrace{n}{1 + \\dots + 1} = \\sum_{i=1}^n 1 \\neq 0 \\quad \\, \\forall \\, n \\in \\mathbb{Z}^+$. \n\n\tTheorem \\ref{Thm:SomeEqnHasNoRationalParametrization} is equivalent to $\\nexists $ nonconstant map $\\mathbb{R}^1 \\to C : (y^2 = x(x-1)(x-\\lambda))$ given by rational functions.\n\t\n\t\\begin{proof}\n$K[t]$ UFD; unique factorization domain (given).\n\nEY: 20181229, recall the definitions:\nintegral domain - nonzero commutative ring in which product of any 2 nonzero elements is nonzero. \\\\\nunique factorization domain is an integral domain $R$ s.t. $\\forall \\, x \\in R$, $x\\neq 0$, $x$ can be written as \n\\[\nx = u p_1 p_2 \\dots p_n , \\quad \\, n \\geq 0\n\\]\t\t\nwith irreducible elements $p_i$ of $R$, unit $u$.\n\n\\[\n\\begin{gathered}\n\\Longrightarrow \\begin{aligned} & f = r/s \\\\ & g = p /q \\end{aligned} \\qquad \\quad \\, \n\\begin{aligned}\n& r,s \\in K[t] \\text{ and coprime } \\\\\n& p,q \\in K[t] \\text{ and coprime } \n\\end{aligned}\n\\end{gathered}\n\\]\n\n\\[\n\\begin{gathered}\n\\Longrightarrow f^2 = g(g-1)(g-\\lambda) = \\frac{r^2 }{s^2} = \\frac{p}{q} \\left( \\frac{ p-q}{q} \\right)\\left( \\frac{ p - \\lambda q}{q} \\right) \\Longrightarrow r^2 q^3 = s^2 p(p-q)(p-\\lambda q)\n\\end{gathered}\n\\]\n$r,s$ are coprime, so RHS $s^2$ must divide $q^3$. \\\\\n$p,q$ are coprime, LHS $q^3$ must divide $s^2$\n\nEY (20181229): observe that LHS and RHS are different and equal. How to get them into the same form? Try to divide both sides!\n\n\\[\n\\Longrightarrow s^2 | q^3 \\text{and } q^3 | s^2, \\text{ so } s^2 = aq^3 \\text{ with } a \\in K\n\\]\n\nThen $aq = (s/q)^2$ is square in $K[t]$\n\nThen $r^2 = ap(p-q)(p-\\lambda q)$\n\nConsider factorization into primes $\\Longrightarrow$ nonzero constants $b,c,d \\in K$, s.t. $bp, c(p-q), d(p-\\lambda q)$ are all squares in $K[t]$. \\\\\nLet algebraic closure $\\overline{K}$ (algebraic extension of $K$ s.t. $\\overline{K}$ algebraically closed, i.e. $\\forall \\, $ nonconstant $f(x) \\in K[x]$ has a root in $K$).\n\nThen $\\forall \\, p, q \\in \\overline{K}(t)$, by lemma, $p,q \\in \\overline{K}$. Then $r,s \\in \\overline{K}$. Then $\\boxed{ f, g \\in \\overline{K}}$.\n\n\t\t\\end{proof}\n\t\n\ncf. Sec. 2.4 \"Linear systems\" in Ch. 2 of Reid (2013) \\cite{Reid2013}.\n\nLet $S_d \\equiv \\lbrace \\text{ forms of degree $d$ in $(X, Y, Z)$ } \\rbrace$; recall form is just a homogeneous polynomial.\n\n$\\forall \\, F \\in S_d$, $\\exists \\, $ unique form for $F$: $F = \\sum a_{ijk} X^i Y^j Z^k$, $a_{ijk} \\in K$, and $\\sum \\equiv \\sum_{ \\substack{ i,j,k \\geq 0 \\\\ i + j + k = d } }$.\n\n$\\Longrightarrow S_d $ is $K$-vector space with basis $\\lbrace Z^d, XZ^{d-1}, YZ^{d-1}, \\dots X^{d-2} Y^2 \\dots Y^d \\rbrace$, where\n\\[\n\\boxed{ \\text{dim}S_d = \\binom{d+2}{2} }\n\\]\n(to see this, imagine $d$ stars, 2 bars, and the 2 bars distinguish which are $X$'s, $Y$'s, or $Z$'s). \n\nFor $P_1 \\dots P_n \\in \\mathbb{P}^2$, let \n\\[\nS_d(P_1 \\dots P_n) = \\lbrace F \\in S_d | F(P_i) =0 \\quad \\, \\forall \\, i = 1 \\dots n \\rbrace \\subset S_d\n\\]\n\n$\\forall \\, $ condition $F(P_i) = 0$ (e.g. $F(X_i, Y_i, Z_i) =0$, where $P_i = (X_i, Y_i, Z_i)$) is 1 linear condition on $F$, so $S_d(P_1 \\dots P_n)$ is a vector space of $\\text{dim} \\geq \\binom{ d+2}{2} - n$\n\n\\begin{lemma}[Special case of Nullstellensatz]\\label{Lem:SpecialCaseOfNullstellensatz}\n\t\\begin{enumerate}\n\t\t\\item[(i)] Let $L \\subset \\mathbb{P}_K^2$ be a line; if $F \\equiv 0$ on $L$, then $F$ divisible in $K[X, Y, Z]$ by equation of $L$, i.e. $F = H \\cdot F'$, where $H$ is equation of $L$, and $F' \\in S_{d-1}$. \n\t\t\\item[(ii)] Let $C \\subset \\mathbb{P}^2_K$ be nonempty nondegenerate conic; if $F =0$ on $C$, then $F$ divisible in $K[X,Y,Z]$, by equation of $C$, i.e. $F = QF'$, where $Q$ is equation of $C$, and $F' \\in S_{d-2}$. \n\t\\end{enumerate}\n\\end{lemma}\n\ncf. Lemma 2.5 of Reid (2013). \n\n\\begin{proof}\n\\begin{enumerate}\n\t\\item[(i)] By change of coordinates, assume $H = X$, \n\tThen, $\\forall \\, F \\in S_d$, $\\exists \\, ! \\, F = X \\cdot F'_{d-1} + G(Y,Z)$, since, just gather together all monomials involving $X$ into 1st. summand, and what's left must be a polynomial $Y,Z$.\n\t\n\tSince \\\\\n\t$F = 0$ on $L$, $F(0) = 0 = 0 \\cdot F'_{d-1} + G(Y,Z) $ $\\Longrightarrow G(Y,Z) = 0\\quad \\, \\forall \\, Y,Z$. \n\t\n\tOtherwise, if $G(Y,Z) \\neq 0$, then it has at most $d$ zeros on $\\mathbb{P}_K^1$, whereas if $K$ is infinite, then so is $\\mathbb{P}_K^1$. \n\t\\item[(ii)] By change of coordinates $Q = XZ - Y^2$, \\\\ \n\tConsider why \n\t\\[\n\tF = QF_{d-2}' + A(X,Z) + YB(X,Z)\n\t\\]\n\twhere $d-2$ in $F_{d-2}'$ denotes the \\emph{degree} of the polynomial (to be $d-2$).\n\t\n\tThis is because if $Y^2 = XZ - Q$, then $F(Y^2 = XZ - Q)$ has degree $\\leq 1$ in $Y$, and so would have the form \n\t\\[\n\tF(Y^2 = XZ - Q) = A(X,Z) + YB(X,Z)\n\t\\]\n\t$C$ is a parametrized conic given by \n\t\\[\n\tX = U^2 , Y = UV, \\, Z = V^2\n\t\\]\n\tso that, \\\\\n\t$F = 0$ on $C$ $\\Longleftrightarrow A(U^2, V^2) + UVB(U^2 , V^2) = 0$ on $C$ \\\\\n\t$\\Longrightarrow A(U^2, V^2) + UVB(U^2 , V^2) =0 \\in K[U,V]$. \\\\\n\t$\\Longrightarrow A(X,Z) = B(X,Z) =0 $\n\t\n\tSince here the last equality comes by considering separately terms of even and odd degrees in form \n\t\\[\n\tA(U^2, V^2) + UVB(U^2, V^2)\n\t\\]\n\t\n\\end{enumerate}\t\n\\end{proof}\n\ncf. Exercises to Ch. 2, Reid (2013)\n\n\\exercisehead{2.2}\nLet $\\begin{aligned} & \\quad \\\\ \n& \\varphi : \\mathbb{R}^1 \\to \\mathbb{R}^2\t\\\\\n& t \\mapsto (t^2, t^3) \\end{aligned}$. \n\n$\\forall \\, $ polynomial $f \\in \\mathbb{R}[X, Y]$, s.t. $f= 0$ on image $C = \\varphi(\\mathbb{R}^1)$, $f$ divisible by $Y^2 - X^3$. \n\n\\begin{proof}\n\tGiven $\\varphi(t) = (t^2, t^3) = (x,y)$, then $y^2 = x^3$ \\, $\\forall \\, t \\in \\mathbb{R}$, or $y^2 - x^3 = 0$.\n\t\n\tLet $q= q(x,y) = y^2 - x^3 \\in K[x,y]$.\n\t\n\tSuppose $f$ of degree $d$.\n\t\n\tThen \n\t\\[\n\tf = q f'_{d-2} + a(x) + y b(x)\n\t\\]\n\t\n\tThis is because, if $y^2 = q- x^3$, $f(y^2 = q- x^3)$ has degree $\\leq 1$ in $y$, so would have the previous form.\n\t\n\tNow \n\t\\[\n\t\\begin{gathered}\n\tf(y^2 = q- x^3) = 0 = 0 + a(x) + yb(x)\n\t\\end{gathered}\n\t\\]\n\t$f = 0$ on $C = \\varphi(\\mathbb{R}^1) \\Longrightarrow $ $a(x) + yb(x) =0 = a(t^2) + t^3 b(t^2) = 0$.\n\t\n\tSuppose for $t_1 > 0$, $t_1^3 b(t_1^2) = -a(t_1^2)$. \n\t\n\tConsider $-t_1 < 0$: \n\t\\[\n\t\\begin{gathered}\n\t\\Longrightarrow -t_1^3 b(t_1^3) = -a(t_1^2) \\Longrightarrow a(t_1^2) = 0 \\quad \\, \\forall \\, t_1 >0\n\t\\end{gathered}\n\t\\]\n\tThen $b(t_1^2) = 0$ $\\forall \\, t_1 > 0$.\n\t\n\t$\\Longrightarrow f = qf_{d-2}'$ where $q = y^2-x^3$.\n\t\n\t$K$ needs to have \"negative numbers\" (i.e. additive inverses) to exist, for this proof to work.\n\t\\end{proof}\t\n\n\\part{Algebraic Geometry applications}\n\n\\section{References for Algebraic Geometry applications}\n\n A tutorial on geometric programming\n\tStephen Boyd, Seung-Jean Kim, Lieven Vandenberghe, Arash Hassibi\n\n\\url{https://math.berkeley.edu/~bernd/math275old.html}\n\n\\url{https://arxiv.org/pdf/math/0103170.pdf}\n\n\\url{https://www.researchgate.net/publication/257426699_Lossless_Convexification_of_Nonconvex_Control_Bound_and_Pointing_Constraints_in_the_Soft_Landing_Optimal_Control_Problem}\n\n\\end{multicols*}\n\n\n\\begin{thebibliography}{9}\n\n%--------------------------------------------------------------------------------\n% 20180203 \n%-------------------------------------------------------------------------------\n\\bibitem{KaSch2006}\nMasaki Kashiwara and Pierre Schapira. \\textbf{Categories and Sheaves}. \\emph{Grundlehren der mathematischen Wissenschaften}. Volume 332. 2006. Springer-Verlag Berlin Heidelberg. eBook ISBN 978-3-540-27950-1\n\n%--------------------------------------------------------------------------------\n% END of 20180203 \n%-------------------------------------------------------------------------------\n\n%--------------------------------------------------------------------------------\n% 20180311 \n%-------------------------------------------------------------------------------\n\\bibitem{DuFo2003}\nDavid S. Dummit, Richard M. Foote. \\textbf{Abstract Algebra}. 3rd. Ed. Wiley; (July 14, 2003). ISBN-13: 978-0471433347 \n%--------------------------------------------------------------------------------\n% END of 20180311 \n%-------------------------------------------------------------------------------\n\n\\bibitem{BW1998}\nMichael Barr, Charles Wells. \\textbf{Category Theory for Computing Science}. \\url{http://www.tac.mta.ca/tac/reprints/articles/22/tr22.pdf}, \\url{http://www.math.mcgill.ca/triples/Barr-Wells-ctcs.pdf}\n \n\\bibitem{AHS2004}\nJi\\v{r}\\'{i} Ad\\'{a}mek, Horst Herrlich, George E. Strecker. \\textbf{Abstract and Concrete Categories The Joy of Cats}. 2004. \\url{http://katmat.math.uni-bremen.de/acc/acc.pdf}\n\n\\bibitem{MacL1978}\nSaunders Mac Lane. \\textbf{Categories for the Working Mathematician}. Graduate Texts in Mathematics. Volume 5. 1978. Springer-Verlag New York. eBook ISBN\n978-1-4757-4721-8\n\n\\bibitem{Simm2011}\nHarold Simmons. \\textbf{An Introduction to Category Theory}. 1st Edition. Cambridge University Press; 1 edition (November 21, 2011). ISBN-13: 978-0521283045\n\n\\bibitem{Turi2001}\nDaniele Turi. \\textbf{Category Theory Lecture Notes}. September 1996 – December 2001. \\url{http://www.dcs.ed.ac.uk/home/dt/CT/categories.pdf}\n\n\\bibitem{Lein2014}\nTom Leinster. \\textbf{Basic Category Theory} (Cambridge Studies in Advanced Mathematics) 1st Edition. 2014. ISBN-13: 978-1107044241\n\n\\bibitem{Pare2004}\nProf. Dr. B. Pareigis. \\textbf{Category Theory}. Summer Semester 2004. June 14, 2004. \\url{http://www.mathematik.uni-muenchen.de/~pareigis/Vorlesungen/04SS/Cats1.pdf}\n\n\\bibitem{Cuki2018}\nIvan \\v{C}uki\\'{c}. \\textbf{Functional Programming in C++: How to improve your C++ programs using functional techniques}. Manning Publications; 1st edition (November 19, 2018). ISBN-13: 978-1617293818\n\n\n%%--------------------------------------------------------------------------------------------------\n%%% Applications of Category Theory\n%%--------------------------------------------------------------------------------------------------\n\\bibitem{Ames2006}\nAaron David Ames. \"A Categorical Theory of Hybrid Systems.\" PhD dissertation. Dec. 11, 2006. Technical Report No. UCB/EECS-2006-165. \\url{http://www.eecs.berkeley.edu/Pubs/TechRpts/2006/EECS-2006-165.html}\n\n\n\\bibitem{CLS2005}\nDavid A. Cox. John Little. Donal O'Shea. \\textbf{Using Algebraic Geometry}. Second Edition. Springer. 2005. ISBN 0-387-20706-6 QA564.C6883 2004\n\n\\bibitem{CLS2015}\nDavid Cox, John Little, Donal O'Shea. \\textbf{Ideals, Varieties, and Algorithms: An Introduction to Computational Algebraic Geometry and Commutative Algebra}, Fourth Edition, Springer\n\n\\bibitem{GrDu2017}\nTorsten Grust, Christian Duta. \\emph{Datenbanksysteme I}. Winter 2017-2018. Eberhard Karls Universit\\\"{a}t T\\\"{u}bingen. \\url{https://www-db.informatik.uni-tuebingen.de/teaching/DatenbanksystemeIWS2017-2018.html}\n\n\n\\bibitem{Spiv2009}\nDavid I. Spivak. \\emph{Simplicial Databases}. \\href{https://arxiv.org/abs/0904.2012}{arXiv: 0904.2012v1} [cs.DB] 13 Apr 2009.\n\n\\bibitem{Spiv2012}\nDavid I. Spivak. \\emph{Categorical Databases}. Presented on 2012/01/13. \\url{http://math.mit.edu/~dspivak/informatics/talks/CTDBIntroductoryTalk}\n\n\\bibitem{Yang2012}\nJun Yang. \\emph{CompSci 316}: \\emph{Introduction to Database Systems}. Fall 2012. Duke University. \\url{https://www2.cs.duke.edu/courses/fall12/compsci316/index.html}\n\n\\bibitem{SpCu2011}\nCarlo Curino. David Spivak. \\emph{Category Theory as a Unifying Database Formalism}. 2011. \\url{http://math.mit.edu/~dspivak/informatics/notes/unorganized/PODS.pdf}\n\n\\bibitem{Awod2010}\nSteve Awodey. \\textbf{Category Theory} (Oxford Logic Guides) 2nd Edition. Oxford Logic Guides (Book 52). Oxford University Press; 2 edition (August 13, 2010). ISBN-13: 978-0199237180\n\n\\bibitem{BaWe2012}\nMichael Barr, Charles Wells. \\textbf{Category Theory for Computing Science}. 2012\n\n\\bibitem{FrSc2007} \nFranz Schwabl. \\textbf{Quantum Mechanics}. Springer-Verlag Berlin Heidelberg. 2007. 4th Edition. ISBN 978-3-540-71933-5\n\n\\bibitem{Scho2008} \nSchottenloher, Martin. \\textbf{A Mathematical Introduction to Conformal Field Theory}. Springer, 2008. \n\n\\bibitem{LaLi1980}\nL.D. Landau and E.M. Lifshitz. \\textbf{Statistical Physics}, Third Edition, Part 1: Volume 5 (Course of Theoretical Physics, Volume 5) 3rd Edition. Butterworth-Heinemann; 3 edition (January 15, 1980). ISBN-13: 978-0750633727\n\n\\bibitem{Hjor2015}\nM. Hjorth-Jensen, \\textbf{Computational Physics}, University of Oslo (2015) \\url{http://www.mn.uio.no/fysikk/english/people/aca/mhjensen/}\n\n\n\n\\bibitem{NeBa1999} \nM.E.J. Newman and G.T. Barkema. \\textbf{Monte Carlo Methods in Statistical Physics}. Oxford University Press. 1999. \n\n\n\\bibitem{Bred1997}\nGlen E. Bredon. \\textbf{Topology and Geometry}. Graduate Texts in Mathematics (Book 139). Springer; Corrected edition (October 17, 1997). ISBN-13: 978-0387979267\n\n\\bibitem{Rotm1988}\nJoseph Rotman. \\textbf{An Introduction to Algebraic Topology}. \\emph{Graduate Texts in Mathematics}. Volume 119. 1988. Springer-Verlag New York. eBook ISBN\n978-1-4612-4576-6\n\n\\bibitem{Serr1980} \nJean-Pierre Serre (Author), J. Stilwell (Translator). \\textbf{Trees} (Springer Monographs in Mathematics) 1st ed. 1980. Corr. 2nd printing 2002 Edition. ISBN-13: 978-3540442370\n\n\\bibitem{JRotman2010}\nJoseph J. Rotman, \\textbf{Advanced Modern Algebra} (Graduate Studies in Mathematics) 2nd Edition, American Mathematical Society; 2 edition (August 10, 2010), ISBN-13: 978-0821847411\n\n\\bibitem{Lang2005}\nSerge Lang. \\textbf{Algebra} (Graduate Texts in Mathematics) 3rd Edition. \\emph{Graduate Texts in Mathematics} (Book 211). Springer; 3rd edition (June 21, 2005). ISBN-13: 978-0387953854\n\n\\bibitem{Sche2006}\nEdward Scheinerman. \\textbf{C++ for Mathematicians: An Introduction for Students and Professionals}. 1st Edition. CRC Press; 1 edition (June 8, 2006). ISBN-13: 978-1584885849 \n\n\n\\bibitem{JLee2009}\nJeffrey M. Lee. \\textbf{Manifolds and Differential Geometry}, \\emph{Graduate Studies in Mathematics} Volume: 107, American Mathematical Society, 2009. ISBN-13: 978-0-8218-4815-9\n\n\\bibitem{BrCh2017}\nJacob C. Bridgeman and Christopher T. Chubb. \\emph{Hand-waving and Interpretive Dance: An Introductory Course on Tensor Networks: \\textbf{Lecture Notes}}. \\href{https://arxiv.org/abs/1603.03039}{arXiv:1603.03039 \\textbf{[quant-ph]}}\n\n\\bibitem{Scho2004}\nUlrich Schollwoeck. \\emph{The density-matrix renormalization group}. \\emph{Rev. Mod. Phys.} \\textbf{77}, 259 (2005)\t\\href{https://arxiv.org/abs/cond-mat/0409292}{arXiv:cond-mat/0409292 \\textbf{[cond-mat.str-el]}}\n\n\\bibitem{Scho2010}\nUlrich Schollwoeck. \\emph{The density-matrix renormalization group in the age of matrix product states}. \\emph{Annals of Physics} \\textbf{326}, 96 (2011). \\href{https://arxiv.org/abs/1008.3477}{arXiv:1008.3477 \\textbf{[cond-mat.str-el]}}\n\n\\bibitem{ArSo2017}\nUlrich Schollw\\\"{o}ck, et. al. \\emph{Numerical methods for correlated many-body systems}. \\href{https://www.asc.physik.lmu.de/activities/schools/archiv/asc_school_17/index.html}{\\textbf{2017 Arnold Sommerfeld School}}. \n\n\\href{https://cast.itunes.uni-muenchen.de/clips/WE0Gf4L6f3/vod/high_quality.mp4}{Matrix product states (MPS), Density matrix renormalization group (DMRG) Lecture 1} \n\n\\href{https://cast.itunes.uni-muenchen.de/clips/1PTFIT1n42/vod/high_quality.mp4}{Matrix product states (MPS), Density matrix renormalization group (DMRG) Lecture 2} \n\n\\href{https://cast.itunes.uni-muenchen.de/clips/uN8yxWC8m9/vod/high_quality.mp4}{Matrix product states (MPS), Density matrix renormalization group (DMRG) Hands on Session 1} \n\n\\href{https://cast.itunes.uni-muenchen.de/clips/xJRe4DD7Fo/vod/high_quality.mp4}{Matrix product states (MPS), Density matrix renormalization group (DMRG) Hands on Session 2} \n\n\\href{https://www.asc.physik.lmu.de/activities/schools/archiv/asc_school_17/extramaterial/schollwoeck_asc_1.pdf}{Ulrich Schollw\\\"{o}ck (LMU): \\emph{Matrix product states (MPS), Density matrix renormalization group (DMRG)}}\n\n\\href{https://www.asc.physik.lmu.de/activities/schools/archiv/asc_school_17/extramaterial/schollwoeck_asc_2.pdf}{Ulrich Schollw\\\"{o}ck (LMU): \\emph{Matrix product states (MPS), Density matrix renormalization group (DMRG)}}\n\n\n\\bibitem{BaRa2015}\nJos\\'{e} L.F. Barb\\'{o}n and Eliezer Rabinovici. \"Holographic Complexity And Spacetime Singularities.\" \\href{https://arxiv.org/abs/1509.09291v3}{arXiv:1509.09291 \\textbf{[hep-th]}}\n\n\\bibitem{MaSu2013} \nJuan Maldacena, Leonard Susskind. \"Cool horizons for entangled black holes.\" \\href{https://arxiv.org/abs/1306.0533}{ \tarXiv:1306.0533 \\textbf{[hep-th]}}\n\n\\bibitem{Rych2016}\nSlava Rychkov. \"EPFL Lectures on Conformal Field Theory in $D \\geq 3$ Dimensions.\" \\href{https://arxiv.org/abs/1601.05000}{arXiv:1601.05000 \\textbf{[hep-th]}}\n\n\\bibitem{EvVi2011}\nG. Evenbly, G. Vidal. \"Tensor network states and geometry.\" \\href{https://arxiv.org/abs/1106.1082}{arXiv:1106.1082 \\textbf{[quant-ph]}}\n\n\\bibitem{Raam2016} \nMark Van Raamsdonk. \"Lectures on Gravity and Entanglement.\" \\href{https://arxiv.org/abs/1609.00026}{arXiv:1609.00026 \\textbf{[hep-th]}}\n\n\n\\bibitem{Reid2013}\nMiles Reid. \\textbf{Undergraduate Algebraic Geometry}. October 20, 2013. \\url{https://homepages.warwick.ac.uk/staff/Miles.Reid/MA4A5/UAG.pdf}\n\n\\bibitem{Har1992} \nJoe Harris. \\textbf{Algebraic Geometry: A First Course}. Graduate Texts in Mathematics. 1992. Springer-Verlag New York. eBook ISBN 978-1-4757-2189-8\n \n\n\n\n\n\\end{thebibliography}\n\n\n\\end{document}\n", "meta": {"hexsha": "4ae95790587a751558e331cd1fea859cb3bc0d66", "size": 460059, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "LaTeX_and_pdfs/AGAT_dump.tex", "max_stars_repo_name": "ernestyalumni/mathphysics", "max_stars_repo_head_hexsha": "24ad9436bcb4860462cd10fe592e93ebd0ade0e3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 50, "max_stars_repo_stars_event_min_datetime": "2017-01-10T14:24:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T11:19:23.000Z", "max_issues_repo_path": "LaTeX_and_pdfs/AGAT_dump.tex", "max_issues_repo_name": "ernestyalumni/mathphysics", "max_issues_repo_head_hexsha": "24ad9436bcb4860462cd10fe592e93ebd0ade0e3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2017-09-29T09:29:53.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-12T03:12:29.000Z", "max_forks_repo_path": "LaTeX_and_pdfs/AGAT_dump.tex", "max_forks_repo_name": "ernestyalumni/mathphysics", "max_forks_repo_head_hexsha": "24ad9436bcb4860462cd10fe592e93ebd0ade0e3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 25, "max_forks_repo_forks_event_min_datetime": "2018-01-21T05:33:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T20:15:13.000Z", "avg_line_length": 39.5443527592, "max_line_length": 662, "alphanum_fraction": 0.6149776442, "num_tokens": 185572, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4493926344647596, "lm_q2_score": 0.334589441253186, "lm_q1q2_score": 0.15036203046886118}} {"text": "%\\section{Design}\n\\section{ Just-In-Time Compilation and Optimizing Code}\n\\label{JM:sec:JITOpt}\n\nA common complain of users new to \\textit{Julia} is that is does not hold up to its promise of speed, often feels even slower than e.g. using \\textit{Python} for the same \ntask. This chapter gives a brief explanation on why this is the case, how performance should and can be measured and how to optimize code for performance. Consider the following code\n\n\\lstinputlisting[language=Julia,firstline=1, lastline=15]{../scripts/optimizing_code.jl}\n\nHere the @time macro\\footnote{A macro transforms the abstract syntax tree of the program. Interested readers might also refer to \\cite{JMKwong2020}.}\nreturns basic performance metrics about the function call like overall execution time, memory allocations, and compilation time.\n\n\\begin{lstlisting}[language=Julia]\n 0.016432 seconds (6.08 k allocations: 342.705 KiB, 99.78% compilation time)\n\\end{lstlisting}\n\nAnother execution of the same command holds a different result.\n\n\\begin{lstlisting}[language=Julia]\n 0.000008 seconds (1 allocation: 160 bytes)\n\\end{lstlisting}\n\nThe reason is \\textit{Julia}'s underlying just-in-time (JIT) compilation. On the first call of the method $g$, \nthe code is lowered to machine instructions and stored in memory for the specific types of arguments. This means that the first \ncall of a method has an additional overhead due to the effort of the LLVM \\cite{JMLattnerAdve2004} compiler\\footnote{Which is also the reason for the infamous time to first plot benchmark in \\textit{Julia}}.\nThe second call of a method leverages the already compiled function and can be executed and benchmarked faster. \nA slight change of arguments shows that this process is indeed type-specific.\n\n\\lstinputlisting[language=Julia,firstline=19, lastline=22]{../scripts/optimizing_code.jl}\n\nAgain, the compilation time is present and takes up most of the execution time\n\n\\begin{lstlisting}[language=Julia]\n 0.100689 seconds (269.78 k allocations: 15.753 MiB, 10.07% gc time, 99.92% compilation time)\n\\end{lstlisting}\n\nJIT compilation also exists for different languages, such as \\textit{Python}, \\textit{lua} or \\textit{Matlab}\\cite{JMMATLAB2010}, as an optional extension. However, most of the performance comes\nfrom compiler optimization where \\textit{Julia} exceeds performance-wise due to JIT being the standard. \nA slightly outdated benchmark comparing different algorithms and languages can be found \\href{https://julialang.org/benchmarks/}{on the micro-benchmark page.}\\\\\n\n\\textit{Julia} is storing array-like data in a column major memory layout, which highly impacts the speed. The execution of the following\ncode shows that a column major iteration can result in a high speedup, using the same array. \n\n\\lstinputlisting[language=Julia,firstline=24, lastline=46]{../scripts/optimizing_code.jl}\n\nInstead of using @time the performance metrics are derived via @btime \\footnote{\\href{https://github.com/JuliaCI/BenchmarkTools.jl}{BenchmarkTools.jl}}, which evaluates the method over multiple trials, limited by the memory and time consumption of the function.\\\\\n\nTo investiage the use of parallel processing, consider the example given in \\cite[p. 178 ff.]{JMSengupta2019}\n\n\\lstinputlisting[language=Julia,firstline=49, lastline=68]{../scripts/optimizing_code.jl}\n\nBoth methods defined above are mutating, indicated by the exclamation mark at the end of the function. They modify the values of their first argument, the array $x$, overwriting it inplace with no further allocations.\nWe see that the use of the second function, which leverages single-instruction-multiple-data (SIMD) - via {@simd} - and disableing the checking of bounds- via {@inbounds} - holds a relative speedup of $4.18$ in comparision to the first implementation. \nA similar syntax enables multithreading\n\n\\lstinputlisting[language=Julia,firstline=74, lastline=83]{../scripts/optimizing_code.jl}\n\nWhich shows the ease of use, but the communication time dominates the execution time and no speedup is achieved. Likwise, computations can be moved from the CPU to the GPU using different pacakges \\cite[p.204 ff.]{JMSengupta2019}.\n\n\\newpage\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "71155ed293aaab31f70c00b318aa05c8dc8f17e3", "size": 4194, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "report/contents/03_multiple_dispatch.tex", "max_stars_repo_name": "AlCap23/ScientificComputingSeminar2021", "max_stars_repo_head_hexsha": "1adf9984f2948d3b990036ffb616fd1b2ffc2ae6", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "report/contents/03_multiple_dispatch.tex", "max_issues_repo_name": "AlCap23/ScientificComputingSeminar2021", "max_issues_repo_head_hexsha": "1adf9984f2948d3b990036ffb616fd1b2ffc2ae6", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "report/contents/03_multiple_dispatch.tex", "max_forks_repo_name": "AlCap23/ScientificComputingSeminar2021", "max_forks_repo_head_hexsha": "1adf9984f2948d3b990036ffb616fd1b2ffc2ae6", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 55.92, "max_line_length": 263, "alphanum_fraction": 0.7892226991, "num_tokens": 1046, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.42250463481418826, "lm_q2_score": 0.35577489351363034, "lm_q1q2_score": 0.1503165414600331}}