\documentclass{beamer}
\usetheme{Madrid}
\usepackage[utf8]{inputenc}
\DeclareMathOperator*{\argmax}{arg\,max}
\DeclareMathOperator*{\argmin}{arg\,min}
\DeclareMathOperator{\sign}{sign}

\title[Multi-agent Dynamics in the SFBP]{Multi-agent Dynamics in the Santa Fe Bar Problem}
\subtitle{Fairness and efficiency}
\author{Angelo Ortiz}
\institute{SMA @ LIP6}
\date{\today}

\begin{document}

\begin{frame}
\titlepage
\end{frame}

\begin{frame}
\frametitle{Outline}
\tableofcontents
\end{frame}

\section{Presentation}
\subsection{Definitions}
\begin{frame}
\frametitle{The SFBP}
\begin{block}<1->{Brian Arthur:}
\begin{quote}
 $N$ people decide independently each week whether to go to a bar that offers entertainment on a certain night... Space is limited, and the evening is enjoyable if things are not too crowded -- especially, if fewer than $c$ percent of the possible $N$ are present... a person or agent goes if she expects fewer than $c$ percent to show up and stays home if she expects more than $c$ percent to go.
\end{quote}
\end{block}

\begin{block}<2->{Only datum}
 Previous attendance numbers.
\end{block}

\begin{alertblock}<3->{Restrictions}
 \begin{itemize}
  \item Choices are unaffected by previous visits.
  \item No collusion among the agents.
 \end{itemize}
\end{alertblock}

\end{frame}

\begin{frame}
\begin{definition}[Fairness]
An outcome is said to be fair if agents with identical utilities are equally likely to attend the bar.
\end{definition}

\begin{definition}[Efficiency]
Efficiency is a measure of collective, or total agent, utility achieved relative to its maximum value.
\end{definition}

\end{frame}

\subsection{Formalisation}
\begin{frame}
 \frametitle{Formalisation}
 \begin{block}{Notations}
 \begin{itemize}
  \item Agents: $\mathcal{N}=\{1,...,N\}$, with $n \in \mathcal{N}$.
  \item The strategy set $S_n = \{0, 1\}$ for agent $n$, where 0 denotes \textit{stay home} while 1, \textit{go to the bar}.
  \item $Q_n$ denotes the set of probability distributions over $S_n$, with mixed strategy $q_n \in Q_n$.
  \item $s_n$ denotes the realisation of agent $n$'s mixed strategy $q_n$; thus, the bar attendance is $s=\sum_{n \in \mathcal{N}} s_n$.
  \item Externality : if $s \leq c$, then $E(s) = 0$; otherwise, $E(s) = 1$.
  \item $\alpha_n \in ]0,1[$ denotes the value to player $n$ of attending the bar.
  \item Payoff function: $\pi(s_n, s) = s_n (\alpha_n - E(s))$.
 \end{itemize}

 The agents population is denoted by $\mathcal{N}=\{1,...,N\}$, with $n \in \mathcal{N}$.
 \end{block}
\end{frame}

\section{Efficient outcome}
\begin{frame}
 \frametitle{Fictitious play}
 \begin{block}{Notations}
 \begin{itemize}
  \item Uncrowdedness time: $a^0 = 0$, $a^{t+1}=a^t + E(s^t)$.
  \item Probability that the bar is uncrowded: $p^t = \frac{a^t}{t}$ \textcolor{red}{(Convergence)}.
  \item Conditioned on its own action: $b^0_n = c^0_n = 0$, $c^{t+1}_n = c^t_n + s^t_n$,
  $\left .b^{t+1}_n = b^t_n + \begin{cases}
      1 & \text{if } s^t \leq c \text{ and } s^t_n = 1 \\
      0 & \text{if } s^t > c \text{ and } s^t_n = 1
   \end{cases} \right.$, $p^t_n = \frac{b^t_n}{c^t_n}$.
   \item Expected utility at time $t+1$: $\mathbb{E}^{t+1}[\pi_n(s_n, s^t)] = \begin{cases}
      p^t_n\alpha_n - (1-p^t_n)(1-\alpha_n) & \text{if } s_n = 1 \\
      0 & \text{otherwise}
   \end{cases}$
   \item Chosen action at time $t+1$: $s^{t+1}_n \in \argmax_{s_n \in S_n} \mathbb{E}^{t+1}[\pi_n(s_n, s^t)]$
 \end{itemize}
 \end{block}
\end{frame}

\begin{frame}
 \begin{block}{Features}
 \begin{itemize}
  \item Rationality.
  \item Utility-maximising: bar attendance $\sim \frac{c}{N}$.
  \item Unfair: personal attendance likelihood converges to either 0 or 1.
  \item Pure strategy Nash equilibrium.
 \end{itemize}
 \end{block}
\end{frame}

\section{Fair outcome}
\begin{frame}
 \frametitle{No-regret learning}
 \begin{block}<1->{Notations}
 \begin{itemize}
  \item Cumulative utility through time $t$ with strategy $s_n$: $P^t_n(s_n) = \sum_{x=1}^t \pi_n(s_n, s^x)$.
  \item Weight assigned to strategy $s_n$ at time $t+1$, for $\beta > 0$: $q^{t+1}_n(s_n) = \frac{(1+\beta)^{P^t_n(s_n)}}{\sum_{s'_n \in S_n} (1+\beta)^{P^t_n(s'_n)}}$.
 \end{itemize}
 \end{block}

 \begin{block}<2->{Features}
 \begin{itemize}
  \item Bounded rationality.
  \item Fair: personal attendance $\sim \frac{c}{N}$.
  \item Inefficient: collective utility near 0.
  \item Mixed strategy Nash equilibrium.
 \end{itemize}
 \end{block}
\end{frame}

\section{Fair \& efficient mechanism}
\begin{frame}
 \frametitle{Q-learning}
 \begin{block}<1->{Notations}
 \begin{itemize}
  \item Utility function, for the bar attendance $\lambda \in \mathbb{N}$ and $\sigma_i \geq 0$: $u_i(\lambda) = \max\{1-\frac{(\lambda - \mu_i)^2}{\sigma_i^2}, 0\}$, where $\mu_i$ is agent $i$'s utility-peak bar attendance.
  \item Taxation scheme: charge people attending the bar an entrance fee, and distribute this sum among those that stayed home.
  \item \textit{Derivative-following} approach: $f_{t+1} = f_t+\gamma[\sign(f_t-f_{t-1})\sign(u_t-u_{t-1})]$, where $u_t$ is the agents' average utility at time $t$.
 \end{itemize}
 \end{block}

 \begin{block}<2->{Features}
 \begin{itemize}
  \item Bounded rationality.
  \item Fee and average utility per agent converge to about 0.5.
  \item Fair and approximately efficient.
 \end{itemize}
 \end{block}
\end{frame}

\section{Some results \& foreseeable work}
\begin{frame}
\frametitle{Some results \& foreseeable work}
\begin{definition}[Predictivity]
 Given $\epsilon > 0$, a belief-based learning algorithm is said to be $\epsilon$-predictive for player $n$ iff it generates a sequence of probabilistic beliefs $\{p^t_n\}$ s.t.:
 \[
 \lim_{t \to \infty} |p^t_n - p^t_0| < \epsilon.
 \]
\end{definition}

\begin{block}{Rationality vs Learning}
 Rationality precludes learning.
\end{block}
\end{frame}

\begin{frame}
\begin{block}{Envisioned tasks}
 \begin{itemize}
  \item Implement the aforementioned algorithms and replicate the results.
  \item Analyse a variable-utility setup.
  \item Work with other fairness and/or efficiency definitions.
  \item (Optimise the setup with heterogeneous agents.)
  \item (Transpose to the two-bar problem setup.)
 \end{itemize}

\end{block}
\end{frame}

\section*{References}
\begin{frame}
\frametitle{References}
\begin{enumerate}
 \item W.B. Arthur. Inductive reasoning and bounded rationality. Complexity in Economic Theory, 84(2):406–411,
1994.
\item A. Greenwald, A. Jafari, G. Ercal, and D. Gondek. On no-regret learning, Nash equilibrium, and fictitious play.
In Proceedings of Eighteenth International Conference on Machine Learning, pages 226–233, June 2001.
\item A. Greenwald, B. Mishra, and R. Parikh. The Santa Fe bar problem revisited: Theoretical and practical implica-
tions. Presented at Stonybrook Festival on Game Theory: Interactive Dynamics and Learning, July 1998.
\item Farago, Julie \& Greenwald, Amy \& Hall, Keith. (2003). Fair and Efficient Solutions to the Santa Fe Bar Problem.
\end{enumerate}
\end{frame}

\end{document}


\documentclass[simplex.tex]{subfiles}
% NO NEED TO INPUT PREAMBLES HERE
% packages are inherited; you can compile this on its own

\onlyinsubfile{
\title{NeuroData SIMPLEX Report: Subfile}
}

\begin{document}
\onlyinsubfile{
\maketitle
\thispagestyle{empty}

The following report documents the progress made by the labs of Randal~Burns and Joshua~T.~Vogelstein at Johns Hopkins University towards goals set by the DARPA SIMPLEX grant.

%%%% Table of Contents
\tableofcontents

%%%% Publications
\bibliographystyle{IEEEtran}
\begin{spacing}{0.5}
\section*{Publications, Presentations, and Talks}
%\vspace{-20pt}
\nocite{*}
{\footnotesize	\bibliography{simplex}}
\end{spacing}
%%%% End Publications
}

\subsection{Nonparametric Network Dependence Test}

Deciphering the association between network structures and corresponding nodal attributes of interest is a core problem in network science. We propose a new nonparametric procedure for testing dependence between network topology and nodal attributes, via diffusion maps and \texttt{MGC}. Specifically, under an exchangeable graph, we verify that the diffusion maps provide a set of conditionally independent multivariate coordinates for the nodes, which can be combined with \texttt{MGC} (or in general, any distance-based correlation measures) to yield consistent statistic for network dependence testing. In simulation, the new approach achieves superior testing performance under a variety of common network models than existing benchmarks. The diffusion maps provides a robust metric compared to adjacency matrix or geodesic distance, while \texttt{MGC} can better capture nonlinear dependencies, with their combined advantages shown in Figure~\ref{fig:threeSBM}.

\begin{figure}[h!]
\begin{cframed}
		\centering
		\includegraphics[width=0.6\textwidth]{../../figs/ThreeSBM.png}
		\caption{Power comparison for all possible combinations of metrics and correlation measure, under the stochastic block model with three blocks. \texttt{MGC} with the diffusion maps (DM) yields the best power, comparing to using other metrics like adjacency matrix (AM), latent factors (LF), and other test statistics like distance correlation (mcorr), Heller-Heller-Gorfine (HHG) test, or Fosdick and Hoff (FH) method.}
		\label{fig:threeSBM}
		\end{cframed}
\end{figure}

%In order to show that \texttt{MGC} combined with diffusion maps as a network metrics perform better even in the case arbitrary noisy is added to edges or the attributes in real data, we are doing an experiment on brain network with physical locations as nodal attributes. Our proposed method not only detects the dependence between network topology and nodal attributes but also helps us to reveal possibly diverse dependence patterns through multiscale correlation maps or multiscale statistics as a function of diffusion time.

This month we made significant progress in writing the manuscript and improving the exposition. The current draft was submitted to ASA Nonparametric Statistics Section Student Paper Awards, and we are notified as finalists for awards and special presentation section in the Joint Statistical Meeting this year.

\end{document}


\section{Parameters Summary}\label{app:parameters}

All the parameters used in this manuscript alongside their explanation are
given by Table~\ref{table:parameters_summary}.

\begin{table}[!htbp]
    \begin{center}
    \resizebox{.7\textwidth}{!}{
    \begin{tabular}{ll}
    \toprule
Feature & Explanation \\
 \midrule
SSE                       & A measure of how far a strategy is from extortionate behaviour defined in~\cite{Knight2019}. \\
$C_{\text{max}}$          & The biggest cooperating rate in the tournament. \\
$C_{\text{min}}$          & The smallest cooperating rate in the tournament. \\
$C_{\text{median}}$       & The median cooperating rate in the tournament. \\
$C_{\text{mean}}$         & The mean cooperating rate in the tournament. \\
$C_r$ / $C_{\text{max}}$    & A strategy's cooperating rate divided by the maximum cooperating rate in the tournament. \\
$C_{\text{min}}$ / $C_r$    & The minimum in the tournament divided by a strategy's cooperating rate. \\
$C_r$ / $C_{\text{median}}$ & A strategy's cooperating rate divided by the median cooperating rate in the tournament. \\
$C_r$ / $C_{\text{mean}}$   & A strategy's cooperating rate divided by the mean cooperating rate in the tournament. \\
$C_r$                       & The cooperating rate of a strategy. \\
$CC$ to $C$ rate            & The probability a strategy will cooperate after a mutual cooperation. \\
$CD$ to $C$ rate            & The probability a strategy will cooperate after being betrayed by the opponent. \\
$DC$ to $C$ rate            & The probability a strategy will cooperate after betraying the opponent. \\
$DD$ to $C$ rate            & The probability a strategy will cooperate after a mutual defection. \\
$p_n$                       & The probability of a player's action being flipped at each interaction. \\
$n$                         & The number of turns in a match. \\
$p_e$                       & The probability of a match ending in the next turn. \\
$N$                         & The number of strategies in the tournament. \\
$k$                         & The number that a given tournament is repeated. \\
    \bottomrule
        \end{tabular}}
    \end{center}
    \caption{The features which are included in the performance evaluation analysis.}\label{table:parameters_summary}
\end{table}


% This LaTeX was auto-generated from an M-file by MATLAB.
% To make changes, update the M-file and republish this document.

      \subsection{getPlotDistr\_cp.m}

\begin{par}
\textbf{Summary:} Compute means and covariances of the Cartesian coordinates of the tips both the inner and outer pendulum assuming that the joint state $x$ of the cart-double-pendulum system is Gaussian, i.e., $x\sim N(m, s)$
\end{par} \vspace{1em}

\begin{verbatim}   function [M, S] = getPlotDistr_cp(m, s, ell)\end{verbatim}
    \begin{par}
\textbf{Input arguments:}
\end{par} \vspace{1em}
\begin{verbatim}m       mean of full state                                    [4 x 1]
s       covariance of full state                              [4 x 4]
ell     length of pendulum\end{verbatim}
\begin{verbatim}Note: this code assumes that the following order of the state:
       1: cart pos.,
       2: cart vel.,
       3: pendulum angular velocity,
       4: pendulum angle\end{verbatim}
\begin{par}
\textbf{Output arguments:}
\end{par} \vspace{1em}
\begin{verbatim}M      mean of tip of pendulum                               [2 x 1]
S      covariance of tip of pendulum                         [2 x 2]\end{verbatim}
\begin{par}
Copyright (C) 2008-2013 by Marc Deisenroth, Andrew McHutchon, Joe Hall, and Carl Edward Rasmussen.
\end{par} \vspace{1em}
\begin{par}
Last modification: 2013-03-27
\end{par} \vspace{1em}

\subsection*{High-Level Steps}

\begin{enumerate}
\setlength{\itemsep}{-1ex}
   \item Augment input distribution to complex angle representation
   \item Compute means of tips of pendulums (in Cartesian coordinates)
   \item Compute covariances of tips of pendulums (in Cartesian coordinates)
\end{enumerate}

\begin{lstlisting}
function [M, S] = getPlotDistr_cp(m, s, ell)
\end{lstlisting}

\subsection*{Code}

\begin{lstlisting}
% 1. Augment input distribution to complex angle representation
[m1 s1 c1] = gTrig(m,s,4,ell); % map input distribution through sin/cos
m1 = [m; m1];        % mean of joint
c1 = s*c1;           % cross-covariance between input and prediction
s1 = [s c1; c1' s1]; % covariance of joint

% 2. Compute means of tips of pendulums (in Cartesian coordinates)
M = [m1(1)+m1(5); -m1(6)];

% 3. Compute covariances of tips of pendulums (in Cartesian coordinates)
s11 = s1(1,1) + s1(5,5) + s1(1,5) + s1(5,1); % x+l sin(theta)
s22 = s1(6,6); % -l*cos(theta)
s12 = -(s1(1,6)+s1(5,6)); % cov(x+l*sin(th), -l*cos(th)

S = [s11 s12; s12' s22];
try
  chol(S);
catch
  warning('matrix S not pos.def. (getPlotDistr)');
  S = S + (1e-6 - min(eig(S)))*eye(2);
end
\end{lstlisting}


\documentclass[11pt,answers]{exam}

% Preamble % (fold)

\usepackage[paper=letterpaper,margin=.75in,twoside=false,includehead]{geometry}

\usepackage{amsfonts,amsmath,amsthm,amssymb}
\usepackage{enumerate}
\usepackage{graphicx}

\usepackage{paralist}
\usepackage{multicol}
\usepackage{bm}

\let\svthefootnote\thefootnote

\newtheorem*{thm}{Theorem}

\newcommand{\Z}{\mathbb{Z}}
\newcommand{\E}{\mathbb{E}}
\newcommand{\N}{\mathbb{N}}
\newcommand{\cP}{\mathcal{P}}
\newcommand{\Q}{\mathbb{Q}}
\newcommand{\R}{\mathbb{R}}
\newcommand{\e}{\varepsilon}

%\printsolutions

\title{Communicating in Mathematics (MTH 210) Exam 2}
\date{April 8, 2020}

\begin{document}

\maketitle

\section*{Instructions}

\noindent The following are very important, please read carefully!
\begin{itemize}
\item This exam must be uploaded to Blackboard by \textbf{April 9 at 5PM}. Please plan to try to upload before then so you can get help if there are issues.
\item Your exam should be scanned as a single PDF (with the app of your choosing) in black and white. Other file formats or color scans are sometimes too large for Blackboard to accept, and having to flip through multiple files makes grading difficult for Dr. Keough. You do not want to make grading difficult for your professors :)
\item You can write your answers on whatever paper you have, or print the exam if you've got a printer.
\item You do not need to write down the whole question, but you should do the following:
	\begin{itemize}
	\item Start each section on a new page.
	\item Clearly label at the top of \emph{every} page the section from which the problems are from.
	\item Number each problem as it is numbered on the exam.
	\end{itemize}
\item You may use your notes and your textbook for this exam. However, you may NOT use any other resources, including, but not limited to, your classmates, friends you know in other sections, Blackboard, the internet, your mom, your dog, etc. Violation of this policy will be penalized and could result in failure of the course.
\item There is no time limit on the exam, and you do not have to take it in one sitting. I do not expect this to take you more than 2 hours though!
\end{itemize}

\begin{center}
\textbf{If you aren't sure what to do, take a deep breath and just show me what you know. You'll be able to revise!}
\end{center}

\begin{center}

\begin{tabular}{|c|c|c|}
\hline
Section &Score\\
\hline
Sets &\\
&\\
\hline
Functions &\\
&\\
\hline
Which Proof Technique &\\
&\\
\hline
Proof Section &\\
&\\
\hline
\end{tabular}
\end{center}

\pagebreak

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Sets}

\begin{questions}

\question This question is about definitions (and their negations) related to sets.  Describe precisely what you need to prove if you were trying to prove the following.

Let $A$ and $B$ be subsets of some universal set $U$.

\begin{parts}
\part   If I needed to prove that $A\subset B$ I would need to...
\vspace{.5in}
\part  If I needed to prove that $A= B$ I would need to...
\vspace{.5in}
\part If I needed to prove that $x\notin A \cap B$ I would need to...
\vspace{.5in}
\part  If I needed to prove that $x\in A - B$ I would need to...
\vspace{.5in}
\end{parts}

\question Let $U = \{x\in\Z : 1\leq x \leq 20\}$. Define $A = \{1,3,5,7,9,11,13,15,17,19\}$, $B = \{7,10,13\}$, and $C = \{x,y\}$. Make sure to use proper notation in each of the following!

\begin{parts}
\part Show $B\not\subseteq A$.
\vfill
\part Find $\mathcal{P}(C)$.
\vfill
\part Find $B\times C$.
\vfill
\part Find $|A\cup B|$, that is, the cardinality of $A\cup B$.
\vfill
\end{parts}

\end{questions}
\newpage

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Functions}

\begin{questions}

\question

Let $f: \R\to\R$ be defined by $f(x) = \sin(x)$. (You may use graphing software to graph this.)

\begin{parts}
\part Explain why $f$ is a function. You should state the definition of function in your answer.
\vfill
\vfill
\part What is the codomain of $f$?
\vspace{.2in}
\part Use the word preimage in a sentence about the function $f$.
\vfill
\part Is $f$ an injection? Justify your answer using the definition of injection.
\vfill
\part Is $f$ a surjection? Justify your answer using the definition of surjection.
\vfill

%\part Is $f$ a bijection? Justify your answer using the definition of bijection.
%\vfill
\end{parts}

\question Let $A = \{1,2,3\}$ and $B = \{x,w\}$.
 Give an example of a function $f:A\to B$ that is a bijection or explain why no such example exists.
\vfill

\end{questions}

\newpage

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\section{Which Proof Technique When?}

Over the next 2 pages are 4 theorem statements with which you will need to do 3 things:
	\begin{itemize}
	\item State which proof technique you would use. Your options are: direct, contrapositive, contradiction, cases, and induction.
	\item Explain your choice of proof technique.\footnote{As a reminder - for the second bullet you should be specific - what was the key? Something about the hypothesis or conclusion?
}
	\item Outline the steps in a proof using the proof technique (but you should not actually attempt to prove the statement). You should say what you would assume and what you would try to prove. \footnote{In the third bullet you need to be detailed - for a proof by cases, what cases would you use? For a proof by induction, what steps would you use (and what's $P(k)$?)? In each case you need to be as specific as possible - do not say ``I would assume the negation", say what the negation actually is. }

	\end{itemize}
\emph{You should NOT actually prove any of the following theorems.}

\begin{questions}
\question Let $f_n$ be the $n^{th}$ Fibonacci number. For all natural numbers $n$, $3\mid f_{4n}$.

\vfill

\question For each integer $a$, $a^3 \equiv a \pmod{3}$.
\vfill
\newpage

%\question If $A = \{x\in\Z : x\equiv 0 \pmod{2}\}$ and $B = \{y\in \Z: y \equiv 0\pmod{4}\}$ then $A\subseteq B$.
%\vfill
\question For all integers $a$, if $a^2\not\equiv  0\pmod{3}$ then $a\not\equiv 0\pmod{3}$.
\vfill

\question For all $x,y\in \mathbb{R}$, and for all integers $a$ and $b$ with $b\neq 0$, if $x$ is rational and $y$ is irrational, then $ax+by$ is irrational.
\vfill

\end{questions}

\newpage

\section{Proofs}

IMPORTANT DIRECTIONS: You need to do both of the following proofs. Each proof needs to be written according to our writing guidelines.  Don't forget to include a theorem statement (which should always be declarative sentences)! The next page is for the first proof and the page after is for the second proof. Please include any scratch work you have in the PDF, but label it ``scratch work".

\begin{enumerate}
\item Prove the following theorem. The proof needs to be written according to our writing guidelines.

\begin{center}
For each $n\in\N$, $5\mid n^5+4n$.
\end{center}
It will probably be helpful for you to know that
\[(k+1)^5 = k^5+5k^4+10k^3+10k^2+5k+1.\]
You can use this without showing work for it.

\item Determine the relationship between the sets $A$ and $B$ and prove it. You should write your proof according to our writing guidelines.

\begin{center}
Let $A = \{x\in\Z : x\equiv 3 \pmod{6} \}$ and $B = \{ x\in \Z : 4\mid x\}$ . Determine a relationship between the sets $A$ and $B$, state the relationship as a theorem, and prove it.
\end{center}

\end{enumerate}

\newpage

\emph{If you printed the exam you can write your proof for  on this page. }

\newpage

\emph{If you printed the exam you can write your proof for 2 on this page. }

\end{document}


The main interest of interactive simulation is that the user can modify the course of the computations in real-time.
This is essential for surgical simulation : during a training procedure, when a virtual medical instrument comes into contact with some models of a soft-tissue, \emph{instantaneous} deformations must be computed.
This visual feedback of the contact can be enhanced by haptic rendering so that the surgeon can really "feel" the contact.

There are two main issues for a platform like SOFA for providing haptic: The first is that haptic forces need to be computed at $1kHz$ whereas real-time visual feedback (without haptic) is obtained at $30Hz$. The second is that haptic feedback can add artificially some energy inside the simulation and can create instabilities, if the control is not \emph{passive}.

Thus two different approaches are currently implemented into SOFA. The first one is the \emph{Virtual Coupling} technique and the other, more advanced, allows for rendering the constraints presented in section \ref{lm}.

\section{Virtual Coupling} Plugging of a haptic device is bidirectional: the user applies some motions or some forces on the device and this device, in return, applies forces and/or motions to the user.
The majority of the haptic devices propose a \emph{Impedance} coupling: the position of the device is provided by the API and this API asks for force values from the application.
A very simple scheme of coupling, presented in Fig\ref{fig:haptic1}, could have been used.
In this \emph{Direct coupling} case, the simulation would play the role of a controller in an open loop.

\begin{figure}
\centering
 \includegraphics[width=0.7\linewidth]{haptic1.png}
 \caption{Direct coupling}
 \label{fig:haptic1}
\end{figure}

Such design is not suitable when stable and robust haptic feedback on a virtual environment is desired. Indeed some combination of the environment impedance and human user reactions can destabilize the system \cite{Adams99}.
To avoid this, a virtual mechanical coupling is set. It corresponds to the use of a damped-stiffness between the position measured on the device and the simulated position in the virtual environment (see Fig\ref{fig:haptic2}). If very stiff constraints are being simulated then, the stiffness perceived by the user will not be infinite but will correspond to the stiffness of this virtual coupling.
Hence, a compromise between stability and performance must be found by tuning the stiffness value of the coupling.

\begin{figure}
\centering
 \includegraphics[width=\linewidth]{haptic2.png}
 \caption{Virtual coupling technique. A 6 DoFs Damped spring is placed between the haptic loop and the simulation.}
 \label{fig:haptic2}
\end{figure}

The damped spring is simulated two times. One time in the haptic loop and one time in the simulation loop.
If the two loops are synchronized, then the result is the same. But it can also be used in asynchronous mode: fast update of the haptic loop and low rates in the simulation.
In such case, the haptic feedback remains stable but the delay between the two loop is creating an artificial damping.
There is an option to cancel this artificial damping if no contact is detected in the simulation. However, this option can create a sensation of sticking contacts.
The main advantage of the virtual coupling technique is that it can be easily employed with every simulation of SOFA. The main drawback is that the haptic rendering is not transparent.

\section{Constraint-based rendering} An innovative way of dealing with haptic rendering for medical simulation has been proposed in the context of SOFA (see\footnote{The implementation of  \cite{Saupin08} is available in open-source, for the implementation of \cite{Peterlik11}, please contact: christian.duriez@inria.fr }  \cite{Saupin08} and \cite{Peterlik11}).
The approach deals with the mechanical interactions using appropriate force and/or motion transmission models named \emph{compliant mechanisms} (see Fig\ref{fig:haptic3}).
These mechanisms are formulated as a constraint-based problem (like presented in section \ref{lm}) that is solved in two separate threads running at different frequencies.
The first thread processes the whole simulation including the soft-tissue deformations, whereas the second one only deals with computer haptics.
With this approach, it is possible to describe the specific behavior of various medical devices while relying on a unified method for solving the mechanical interactions between deformable objects and haptic rendering.
\begin{figure}
\centering
 \includegraphics[width=\linewidth]{haptic3.png}
 \caption{Compliant mechanisms technique. The simulation shares the mechanical compliance of the objects and the constraints between them. The constraint response is being computed at low rate within the simulation and at high rates within a separate haptic thread. A 6 DoFs Damped spring is still used to coupled the position of the device to its position in the simulation}
 \label{fig:haptic3}
\end{figure}

\section{How to use it in SOFA ?}
Please see the web page: http://wiki.sofa-framework.org/wiki/Haptic  and use the tutorial "dentistry".


\section{Conclusions and Future Work}
The goal of this research is to find out what the best move is in the casino game Blackjack with each hand value and to confirm the thought that the dealer always wins more games than the player. \\
First the total number of wins: The simulation of Blackjack gives an accurate representation of the game. After playing one million games in this simulation, it shows that the dealer indeed wins more games than the player. 22 percent more games to be exact in the case of this simulation. So this proves the hypothesis, in Blackjack, the dealer wins more games than the player. \\
\\
The best move for the player is the move with the highest probability to win. For the values bellow 12 and over 17 this is clear, draw if under 12 and pass if over 17. Between these values these choice gets more difficult. The results shows for 12 and 13 a clear advantage to draw a card and for 16 and 17 a clear advantage by passing. But for 14 and 15 things get very close. On the long run, one should draw a card with a value of 14 and pass at a value of 15. So in short:
\begin{itemize}
    \item < 12: Draw
    \item 12: Draw
    \item 13: Draw
    \item 14: Draw
    \item 15: Pass
    \item 16: Pass
    \item 17: Pass
    \item > 17: Pass
\end{itemize}
This paper is based on generation one time, one million games of Blackjack. To further proof the working of this experiment in more depth, one could generate multiple sets of one million games of Blackjack and compare the differences between these sets. Expected is that the differences between these sets should be minimal. The only differences in the data will be coincidences, which should be canceled out by the large size of the dataset.


\documentclass[12pt]{cdblatex}
\usepackage{fancyhdr}
\usepackage{footer}

\lstset{gobble=2}

\begin{document}

% =================================================================================================
% create checkpoint file

\bgroup
\CdbSetup{action=hide}
\begin{cadabra}
   import cdblib
   checkpoint_file = 'tests/semantic/output/geodesic-ivp.json'
   cdblib.create (checkpoint_file)
   checkpoint = []
\end{cadabra}
\egroup

% =================================================================================================
\section*{Geodesic IVP}

Our game here is to find the solution of
\begin{align*}
   0 = \frac{d^2 x^{a}}{ds^2} + \Gamma^{a}_{bc}(x) \frac{dx^b}{ds} \frac{dx^c}{ds}
\end{align*}
subject to the initial conditions $x^{a}(s) = x^a$ and $dx^a(s)/ds={\Dot x}^{a}$ at $s=0$.

% =================================================================================================
\section*{Algorithm}

By successive differentiation of the above equation we can compute
\begin{align*}
   \frac{d^n x^{a}}{ds^n} = -\Gamma^{a}_{\udn}\frac{dx^{\udn}}{ds}
\end{align*}
at $s=0$ for $n=2,3,4,\dotsc$. The $\Gamma^{a}_{\udn}$ are the \emph{generalised connections}.

We can then construct the Taylor series solution for $x^{a}(s)$
\begin{align*}
   x^a(s) = x^a + s {\Dot x}^a - \sum_{k=2}^\infty\>\frac{s^{k}}{k!} \Gamma^{a}_{\udk}{\Dot x}^{\udk}
\end{align*}

\clearpage

\begin{cadabra}
   {a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w#}::Indices(position=independent).

   \nabla{#}::Derivative.

   import cdblib

   # change signs to account for - sign in front of the sum for x^a(s), see above preamble

   def flip_sign (obj):
       return Ex(0) - obj

   sterm21 = flip_sign (cdblib.get ('genGamma01','genGamma.json'))
   sterm22 = flip_sign (cdblib.get ('genGamma02','genGamma.json'))
   sterm23 = flip_sign (cdblib.get ('genGamma03','genGamma.json'))
   sterm24 = flip_sign (cdblib.get ('genGamma04','genGamma.json'))

   sterm31 = flip_sign (cdblib.get ('genGamma11','genGamma.json'))
   sterm32 = flip_sign (cdblib.get ('genGamma12','genGamma.json'))
   sterm33 = flip_sign (cdblib.get ('genGamma13','genGamma.json'))

   sterm41 = flip_sign (cdblib.get ('genGamma21','genGamma.json'))
   sterm42 = flip_sign (cdblib.get ('genGamma22','genGamma.json'))

   sterm51 = flip_sign (cdblib.get ('genGamma31','genGamma.json'))

   sterm2 := @(sterm21) + @(sterm22) + @(sterm23) + @(sterm24).  # cdb (sterm2.000,sterm2)
   sterm3 := @(sterm31) + @(sterm32) + @(sterm33).               # cdb (sterm3.000,sterm3)
   sterm4 := @(sterm41) + @(sterm42).                            # cdb (sterm4.000,sterm4)
   sterm5 := @(sterm51).                                         # cdb (sterm5.000,sterm5)

   factor_out (sterm2,$A^{a?}$)                                  # cdb (sterm2.001,sterm2)
   factor_out (sterm3,$A^{a?}$)                                  # cdb (sterm3.001,sterm3)
   factor_out (sterm4,$A^{a?}$)                                  # cdb (sterm4.001,sterm4)
   factor_out (sterm5,$A^{a?}$)                                  # cdb (sterm5.001,sterm5)

   sterm2 := 360 @(sterm2).
   sterm3 := 360 @(sterm3).
   sterm4 :=  90 @(sterm4).
   sterm5 :=   3 @(sterm5).

   substitute (sterm2,$A^{a}->1$)                                # cdb (sterm2.002,sterm2)
   substitute (sterm3,$A^{a}->1$)                                # cdb (sterm3.002,sterm3)
   substitute (sterm4,$A^{a}->1$)                                # cdb (sterm4.002,sterm4)
   substitute (sterm5,$A^{a}->1$)                                # cdb (sterm5.002,sterm5)

\end{cadabra}

% =================================================================================================
% the remaining code is just for pretty printing

\clearpage

% =================================================================================================
\section*{The geodesic ivp}

\begin{align*}
   x^{a}(s) = x^{a}
            + s {\dot{x}^a}
            + \frac{s^2}{2!} {\dot{x}^b} {\dot{x}^c} A^{a}_{bc}
            + \frac{s^3}{3!} {\dot{x}^b} {\dot{x}^c} {\dot{x}^d} A^{a}_{bcd}
            + \frac{s^4}{4!} {\dot{x}^b} {\dot{x}^c} {\dot{x}^d} {\dot{x}^e} A^{a}_{bcde}
            + \frac{s^5}{5!} {\dot{x}^b} {\dot{x}^c} {\dot{x}^d} {\dot{x}^e} {\dot{x}^f} A^{a}_{bcdef}
            + \dotsb
\end{align*}
\begin{dgroup*}
   \begin{dmath*} 360 A^{a}_{bc} = \cdb{sterm2.002} \end{dmath*}
   \begin{dmath*} 360 A^{a}_{bcd} = \cdb{sterm3.002} \end{dmath*}
   \begin{dmath*}  90 A^{a}_{bcde} = \cdb{sterm4.002} \end{dmath*}
   \begin{dmath*}   3 A^{a}_{bcdef} = \cdb{sterm5.002} \end{dmath*}
\end{dgroup*}

\clearpage

% =================================================================================================
% export selected objects, these will later be imported into a library
% these are the objects that will appear in the paper

\begin{cadabra}
   sterm2short := @(sterm21) + @(sterm22).             # cdb (sterm2.short.001,sterm2short)
   sterm3short := @(sterm31).                          # cdb (sterm3.short.001,sterm3short)
   sterm2shortscaled := 12 @(sterm2short).             # cdb (sterm2.short.scaled.002,sterm2shortscaled)
   sterm3shortscaled :=  2 @(sterm3short).             # cdb (sterm3.short.scaled.002,sterm3shortscaled)

   substitute (sterm2shortscaled,$A^{a}->1$)           # cdb (sterm2.short.scaled.003,sterm2shortscaled)
   substitute (sterm3shortscaled,$A^{a}->1$)           # cdb (sterm3.short.scaled.003,sterm3shortscaled)

   cdblib.create ('geodesic-ivp.export')

   # 4th order ivp terms scaled
   cdblib.put ('ivp42',sterm2shortscaled,'geodesic-ivp.export')
   cdblib.put ('ivp43',sterm3shortscaled,'geodesic-ivp.export')

   # 6th order ivp terms scaled
   cdblib.put ('ivp62',sterm2,'geodesic-ivp.export')
   cdblib.put ('ivp63',sterm3,'geodesic-ivp.export')
   cdblib.put ('ivp64',sterm4,'geodesic-ivp.export')
   cdblib.put ('ivp65',sterm5,'geodesic-ivp.export')

   checkpoint.append (sterm2shortscaled)
   checkpoint.append (sterm3shortscaled)

   checkpoint.append (sterm2)
   checkpoint.append (sterm3)
   checkpoint.append (sterm4)
   checkpoint.append (sterm5)
\end{cadabra}

% just to check that we are exporting the correct 4th order terms

\begin{dgroup*}
   \begin{dmath*} \cdb*{sterm2.short.001} \end{dmath*}
   \begin{dmath*} \cdb*{sterm3.short.001} \end{dmath*}
   \begin{dmath*} \cdb*{sterm2.short.scaled.002} \end{dmath*}
   \begin{dmath*} \cdb*{sterm3.short.scaled.002} \end{dmath*}
   \begin{dmath*} \cdb*{sterm2.short.scaled.003} \end{dmath*}
   \begin{dmath*} \cdb*{sterm3.short.scaled.003} \end{dmath*}
\end{dgroup*}

% =================================================================================================
% export checkpoints in json format

\bgroup
\CdbSetup{action=hide}
\begin{cadabra}
   for i in range( len(checkpoint) ):
      cdblib.put ('check{:03d}'.format(i),checkpoint[i],checkpoint_file)
\end{cadabra}
\egroup

\end{document}


% !TEX root = altosaar-2020-thesis.tex
\chapter{Discussion}
\label{ch:discussion}
\lettrine[image=true,lines=3]{design/P}{robabilistic} modeling is useful across scientific domains. However, probabilistic modeling methods that do not take into account the structure of a problem, the form of individual datapoints, or information about probability distributions during optimization leave performance gains on the table.

As a motivating example, we built the structure of a statistical physics model into a probabilistic modeling method with \acrlongpl{hvm}. Efficient use of the connectivity patterns in physics models enabled scaling variational approximations to models with millions of random variables.

There is also utility in constructing probabilistic models with knowledge about individual datapoints. \acrlong{rfs} outperforms competitive recommendation models that either fail to take into account the goals of recommendation or the structure of items with sets of attributes.

We also improved variational inference, by making use of information about probability distributions within the \acrlong{PVI} algorithm. This enabled accurate inferences about probability distributions.

To further unify the thesis of problem structure as utile in probabilistic modeling, we test \acrlong{PVI} to measure whether the benefits of leveraging knowledge about a probability distributions are additive to performance gains from developing applied methods.

\input{table/tab_pvi_hvm}
Consider an Ising model studied in \Cref{ch:hvm}, where the goal is accurate inference of the free energy. \Cref{tab:pvi-hvm} shows a comparison between \gls{vi} and \gls{PVI} in an \gls{hvm}. This is a result of testing the best-performing settings from \Cref{ch:pvi} with the entropy constraint on both the variational prior and recursive variational approximation in an \gls{hvm}. The additional information \gls{PVI} makes available to the variational approximation during optimization leads to more accurate inference of the free energy.

Further, \gls{PVI} can be applied to probability models fit with maximum likelihood estimation. \Cref{tab:pvi-rfs} reports the performance of a \gls{rfs} model from \Cref{sec:rfs-experiments} fit to arXiv user behavior data. Fitting the recommendation model using the \gls{PVI} entropy proximity constraint improves top-10 recommendation recall. Metrics other than out-matrix recall (e.g. in-matrix recall) were comparable between these methods. With the \gls{PVI} entropy constraint, the recommendation performance of \gls{rfs} also improved in the meal recommendation task. \Cref{tab:pvi-rfs-meals} reports these results. The best-performing settings from \Cref{ch:pvi} generalize to maximum likelihood estimation in recommender systems, here giving a $6.9\%$ boost in top-$1$ recommender recall.

That \gls{PVI} yielded improvements when applied to both \glspl{hvm} applied to statistical physics problems and the \gls{rfs} recommendation model highlights several directions for further research. First, might \gls{PVI} yield further gains in accuracy when applied to statistical physics models with millions of random variables? Practitioners are willing to trade off diminished accuracy for scale in some cases, and \gls{PVI} is straightforward to test in new probability models and might help reduce the need for such trade-offs.
\input{table/tab_pvi_rfs}

Studying where \gls{PVI} yields marginal gains is also worth considering. For example, the entropy proximity constraint yielded less-significant improvements when applied to \gls{rfs} fit to the meal recommendation data in \Cref{sec:rfs-experiments}. This may be because the large size of data helped prevent overfitting, leading to reduced benefits of constraining parameter updates. In contrast, \glspl{hvm} fit to statistical physics models in \Cref{sec:hvm-experiments} converged to a solution very quickly, so monitoring convergence rates may be an additional source of information for proximity statistics.
\input{table/tab_pvi_rfs_meals}

While \Cref{ch:hvm} studied classical statistical physics models, future work in computational materials science and computational drug discovery will need to incorporate or approximate quantum effects. Density functional theory calculations based on quantum mechanics are expensive~\citep{schmidt2019recent} and limit the length of time that a material or drug binding to a protein can be simulated. Future work in this area should include study of the trade-off between the size of a system and the accuracy needed to study the behavior of a system to achieve a materials design or drug design goal. For example, suppose the behavior of a drug binding to a protein over the course of several seconds is of clinical interest. Then a practitioner might tolerate more inaccuracy in an \gls{hvm} approximation than they would if the short-run behavior could be accurately captured in a density functional theory calculation. One way of improving the trade-off may be to reduce the cost of fitting \glspl{hvm} by derive objective functions with better gradient signal-to-noise ratio~\citep{tucker2018doubly,rainforth2018tighter}. A similar trade-off occurs for system size, and it is unclear where \glspl{hvm} may provide the only way to model a large-scale physical system.

\Cref{ch:rfs} developed \gls{rfs}, and there remain several directions for future work on recommendation models for items with sets of attributes. Probabilistic generative models for use in recommendation may enable better recommendations under uncertainty, or easier incorporation of prior knowledge. However, probability distributions of sets of attributes are difficult to parameterize. One example of a distribution defined on sets is the Wallenius distribution~\citep{wallenius1963biased,junqu2000wallenius}. It is interesting to consider how a distribution on sets might be parameterized using a permutation-invariant model such as \gls{rfs}~\citep{bloem-reddy2019probabilistic,lee2018set-transformer}. Further, generalization bounds are necessary follow-up work to universal approximation properties. A model may be able to represent a distribution, but for practical purposes a key desideratum is finding functions, nonlinearities, and architectures that make optimization easy and generalization feasible~\citep{dziugaite2017computing}.

Another line of work is in developing robust negative sampling-based objective functions. The numeric value of the negative log-likelihood objective function used in \gls{rfs} or other models that use negative samples and embeddings cannot reliably assess convergence. This is due to embeddings that are used in both positive and negative examples, leading stochastic gradient updates to increase and decrease Monte Carlo estimates of the objective during optimization. Reliable methods to estimate the value of objective functions may help reduce the need for expensive recommender systems evaluation metrics where a model may need to be evaluated on every item in an evaluation set. While \gls{rfs} was designed for the recall evaluation metric, connecting binary classification objective functions with negative examples to ranking-based metrics such as normalized discounted cumulative gain would make these models useful broadly.

In \Cref{ch:rfs}, we found that \gls{rfs} outperforms \gls{lstm} recurrent neural networks in the task of recommending arXiv documents to users. This is counterintuitive, as the order of item attributes (words in abstracts) should carry significant information.  However, the computational budget was fixed for both models, and it is unclear which recommendation model to use with a large computational budget. Models such as transformers~\citep{vaswani2017attention,devlin2019bert:,lee2018set-transformer} might lead to improved recommendation performance, but at a greater computational cost than models such as \gls{rfs} with inner product parameterizations. Analyzing these trade-offs will help make informed choices of computational budget given performance requirements in practice. Under computational constraints due to monetary budget or privacy regulation, such as in clinical settings~\citep{huang2019clinicalbert:}, models such as \gls{rfs} that make fast, accurate, predictions may be preferable to more accurate, slower models.

Through careful consideration of how to build problem structure into probabilistic models, we were able to scale variational methods to statistical physics models with millions of random variables, fit recommender systems to tens of millions of datapoints, and improve the accuracy of variational inference. This highlights the need to ensure that progress in probabilistic modeling continues to be translated into progress in applied domains such as statistical physics and recommender systems.


\documentclass[12pt]{article}

% packages
\usepackage{setspace}
\usepackage{array}
\usepackage[margin=0.75in]{geometry}
\usepackage{amsmath,bm}
\usepackage{amssymb}
\usepackage{bbold}
\usepackage{physics}
\usepackage{xcolor}
\usepackage{indentfirst}
\usepackage{enumerate}
\usepackage{mathtools}
\usepackage{fancyhdr}

\pagestyle{fancy}
\fancyhf{}
\rhead{Creative Destruction Lab}
\lhead{Introductions to Projects}
\rfoot{Page \thepage}

\allowdisplaybreaks

\title{Project 3: Calculating Franck-Condon Factors}

\begin{document}

\maketitle

\thispagestyle{empty}

\subsection*{Motivation}

Spectroscopy is the study of how light and matter (atoms and molecules) interact.
Light can be absorbed by matter (\textit{absorption}) or matter can emit light (\textit{emission}).
It turns out that spectroscopy is scientists' main tool for discovering properties of molecules (e.g. their molecular structure, bond strengths, etc.) and for chemical identification. Picture for instance an astronomer taking spectroscopic measurements from a gas cloud located millions of light years away from the Earth. To determine what chemicals this gas cloud comprises of, they certainly cannot travel there and take a physical sample of the gas cloud. The astronomer is tasked with utilizing spectroscopic theory (i.e. models wherein numerical studies can be carried out efficiently) to explain what they see.

Countless other applications like drug discovery, magnetic-resonance imaging (MRI) and climate science rely heavily on spectroscopic methods and theory. This week, you'll familiarize yourself with calculating Franck Condon Factors (FCFs), which are useful in studying {\it vibronic} transitions in molecules. You'll also get to compare your calculations to real experiments.

\subsection*{Your Tasks}

\subsubsection*{Task \#1}

In this task, you will calculate Franck-Condon Factors for H$_2-$H$_2^+$ using the harmonic oscillator approximation and compare to a real experiment! In a real experiment, we can excite many different vibronic transitions. We would therefore be able to calculate many FCFs that describe different vibronic transitions. For example, it could be that we see excitations corresponding to an H$_2$ molecule in its $n = 0$ vibrational state to H$_2^+$ in its $n = 2$ vibrational state (green line in Fig.~\ref{fig:visualize_vibronic}) and its $n = 4$ vibrational state. In this task, we will look at only transitions that have a high FCF (i.e. the corresponding transition is very intense).

\begin{figure}
    \begin{center}
        \includegraphics[width=0.5\linewidth]{../figures/potential_energy_curve.pdf}
    \end{center}
    \caption{A visualization of vibronic transitions. The blue and red curves represent H$_2$ and H$_2^+$, respectively.}
        \label{fig:visualize_vibronic}
\end{figure}

You are provided with a \texttt{python} notebook called \texttt{Task1.ipynb} which calculates all of the information you require. The \texttt{FCF\_helper.py} file contains all of the calculations done under the hood. \footnote{Calculating FCFs comes down to calculating the overlap between the wavefunctions before and after the vibronic transition. The overlap calculation is an integral which we chose to evaluate numerically. We emphasize that molecular parameters like the reduced mass of H$_2$ and fundamental frequencies of H$_2$ and H$_2^+$ are hard-coded in \texttt{FCF\_helper.py}} Currently, the \texttt{spectrum\_analysis} function in \texttt{FCF\_helper.py} only outputs the following.
\begin{itemize}
    \item \texttt{n\_0} and \texttt{n\_p}: The vibrational state numbers of H$_2$ and H$_2^+$, respectively, involved in the vibronic transition
    \item \texttt{FCF}: The corresponding FCF associated to the vibronic transition
\end{itemize}
Here's what we'd like you to do:
\begin{enumerate}
    \item Open up \texttt{FCF\_helper.py} and navigate to the \texttt{spectrum\_analysis} function. Modify the \texttt{data} variable so that it also includes the spectral intensity (\texttt{Ep - E0}).
    \item Plot the corresponding FCF versus spectral intensity (i.e. plot \texttt{FCF} versus \texttt{Ep - E0}) and show the results for \texttt{n\_0}=0 and \texttt{n\_p}=10. \footnote{You may need to adjust the input bounds on the maximum vibrational state numbers. For now, start with both being 2.}
\end{enumerate}

Congratulations, you have now successfully predicted the Franck-Condon Factors of H$_2-$H$_2^+$! Figure \ref{fig:h2_spectrum} shows the photoionization spectrum for H$_2$. Does it look like the real data in Fig.~\ref{fig:h2_spectrum}?

\begin{figure}
    \begin{center}
        \includegraphics[width=\linewidth]{../figures/H2-expspectrum.pdf}
    \end{center}
    \caption{
    Experimental photoionization spectrum of H$_2$-H$_2^+$ from Ref.~\cite{berkowitz1973comparison} with the vibrational level of H$_2$=0.
    }
    \label{fig:h2_spectrum}
\end{figure}

\subsubsection*{Task \#2}

You are provided with a \texttt{C++} code \texttt{FC.cxx} created by P.-N. Roy \cite{yang1995structure}, which calculates the photoionization spectrum for any molecule up to triple excitations and goes beyond the harmonic oscillator approximation. The theory is based on the paper by Ref~\cite{doktorov1977dynamical}. The molecule you will be investigating is $V_3$.
This code takes as input a file which requires the results of diagonalizing the mass-weighted hessian/force-constant matrix (2nd derivative of the Hamiltonian with respect to position). This input file is provided for you (V3).

Browse the following references to understand how the code works, as you will need a basic understanding of this for the next task, but it's not necessary to fully understand it. Compile and run the code \texttt{./FC\_quick V3}. This code outputs the spectrum \texttt{V3.spec.out}. Plot it in your favourite plotting program.

\subsubsection*{Task \#3}

You are provided with a \texttt{python} notebook code Sample\_Vibronic.py which calculates all of the information you require.
\noindent This code takes as input a file which requires the following information:
\begin{enumerate}
    \item Number of atoms in the molecule
    \item Vibrational frequencies of the molecule in the ground electronic state
    \item Vibrational frequencies of the molecule in the excited electronic state
    \item Duschinsky Matrix (encodes information on transformation between ground and excited electronic states)
    \item Displacement vector
\end{enumerate}

\noindent This code outputs the spectrum in HTML format.

However, to be able to use this code, you require an input file. To create this input file, you will need to generate results from another code, \texttt{FC.cxx}. This code calculates the Franck-Condon Factors using matrix elements and recursive Hermite polynomial relations. Feel free to look around this code, but it is not necessary to completely understand it to achieve this task (the reference(s) noted in this code are Refs~\cite{yang1995structure,doktorov1977dynamical,quesadaFranckCondonFactorsCounting2019}. Each piece of information that you need to output has been clearly marked in the code and your task is to write that information to a file, which will then be used as your input file to \texttt{Sample\_Vibronic.py}. Once you have that input file, you should be able to produce the spectrum for $V_3$. Compare this spectrum to the previous method. What happens if you decrease the number of samples to 10? 100? 1000? At what number of samples do you feel the spectrum is converged?

\section*{Challenges}

\begin{enumerate}
    \item An alternative and analogous method to calculating these Franck-Condon Factors using matrix elements is to use a loop hafnian approach. This loop hafnian approach uses Gauss Boson Sampling which would allow these Factors to be calculated using a quantum circuit. Use the result of Task 3 to provide data to a skeleton code provided that uses loop hafnians to calculate the Franck-Condon Factors.
    \item Explain briefly the similarities and differences between these three methods.
\end{enumerate}

\section*{Possible Business Outcomes}

\begin{enumerate}
    \item Explain to a layperson what theoretical chemistry/physics is, in the general context of Franck-Condon Factors
    \item What is the importance of theoretical chemistry/physics from an economic point of view
    \item Explain to a layperson what a quantum circuit is and it's relationship to theoretical chemistry/physics
    \item What are advantages and disadvantages of codes licensed for the public domain and those that are licensed for private use
\end{enumerate}

\newpage

\bibliography{refs}
\bibliographystyle{unsrt}

\end{document}


% Copyright 2019 by Mark Wibrow
%
% This file may be distributed and/or modified
%
% 1. under the LaTeX Project Public License and/or
% 2. under the GNU Free Documentation License.
%
% See the file doc/generic/pgf/licenses/LICENSE for more details.

\section{Math Library}
\label{section-library-math}

\begin{tikzlibrary}{math}
    This library defines a simple mathematical language to define simple
    functions and perform sequences of basic mathematical operations.
\end{tikzlibrary}

\subsection{Overview}

\pgfname\ and \tikzname\ both use the \pgfname\ mathematical engine which
provides many commands for parsing expressions. Unfortunately the \pgfname\
math engine is somewhat cumbersome for long sequences of mathematical
operations, particularly when assigning values to multiple variables. The
\tikzname\ |calc| library provides some additional ``convenience'' operations
for doing calculations (particularly with coordinates), but this can only be
used inside \tikzname\ path commands.

This |math| library provides a means to perform sequences of mathematical
operations in a more `user friendly' manner than the \pgfname\ math engine. In
addition, the coordinate calculations of the |calc| library can be accessed
(provided it is loaded).
%
However as the |math| library uses the \pgfname\ math engine -- which uses pure
\TeX\ to perform all its calculations -- it is subject to the same speed and
accuracy limitations. It is worth bearing this in mind, before trying to
implement algorithms requiring intensive and highly accurate computation. You
can, of course use the |fp| or the |fpu| libraries to increase the accuracy
(but not necessarily the speed) of computations.

For most purposes, the features provided by this library are accessed using the
following command:

\begin{command}{\tikzmath\texttt{\{}\meta{statements}\texttt{\}}}
    This command process  a series of \meta{statements} which can represent
    assignments, function definitions, conditional evaluation, and iterations.
    It provides, in effect, a miniature mathematical language to perform basic
    mathematical operations. Perhaps the most important thing to remember is
    that \emph{every statement should end with a semi-colon}. This is likely to
    be the most common reason why the |\tikzmath| command fails.
    %
\begin{codeexample}[preamble={\usetikzlibrary{math}}]
\tikzmath{
  % Adapted from http://www.cs.northwestern.edu/academics/courses/110/html/fib_rec.html
  function fibonacci(\n) {
    if \n == 0 then {
      return 0;
    } else {
       return fibonacci2(\n, 0, 1);
     };
  };
  function fibonacci2(\n, \p, \q) {
    if \n == 1 then {
      return \q;
    } else {
      return fibonacci2(\n-1, \q, \p+\q);
    };
  };
  int \f, \i;
  for \i in {0,1,...,20}{
    \f = fibonacci(\i);
    print {\f, };
  };
}
\end{codeexample}
    %
\end{command}

In addition to this command the following key is provided:

\begin{key}{/tikz/evaluate={\meta{statements}}}
    This key simply executes |\tikzmath{|\meta{statements}|}|.
    %
\begin{codeexample}[preamble={\usetikzlibrary{math}}]
\tikz[x=0.25cm,y=0.25cm,
  evaluate={
    int \i, \j;
    for \i in {0,...,10}{
      for \j in {0,...,10}{
        \a{\i,\j} = (\i+\j)*5;
      };
    };
  }
]
\foreach \i in {0,...,10}
  \foreach \j in {0,...,10}
    \fill [red!\a{\i,\j}!yellow]  (\i,\j) rectangle ++(1, 1);
\end{codeexample}
    %
\end{key}

The following sections describe the miniature language that this library
provides and can be used in the |\tikzmath| command and the |evaluate| key.
The language consists only of simple keywords and expressions but the
mini-parser allows you to format code in a reasonably versatile way (much like
the |tikz| parser) except that \emph{all the keywords must be followed by at
least one space}. This is the second most important thing to remember (after
remembering to insert semi-colons at the end of every statement).

\subsection{Assignment}

In the simplest case, you will want to evaluate an expression and assign it to
a macro, or a \TeX\ count or dimension register. In this case, use of the
|math| library is straightforward:
%
\begin{codeexample}[preamble={\usetikzlibrary{math}}]
\newcount\mycount
\newdimen\mydimen
\tikzmath{
  \a = 4*5+6;
  \b = sin(30)*4;
  \mycount = log10(2048) / log10(2);
  \mydimen = 15^2;
}
\a, \b, \the\mycount, \the\mydimen
\end{codeexample}

In addition, \TeX-macros (\emph{not} \TeX\ registers) can be suffixed with an
index, similar to indices in mathematical notation, for example, $x_1$, $x_2$,
$x_3$:
%
\begin{codeexample}[preamble={\usetikzlibrary{math}}]
\tikzmath{
  \x1 = 3+4; \x2 = 30+40; \x3 = 300+400;
}
\x1, \x2, \x3
\end{codeexample}

The index does not have to be a number. By using braces |{}|, more
sophisticated indices can be created:
%
\begin{codeexample}[preamble={\usetikzlibrary{math}}]
\tikzmath{
  \c{air} = 340; \c{water} = 1435; \c{steel} = 6100;
}
\foreach \medium in {air,steel}{The speed of sound in \medium\ is \c{\medium} m/s. }
\end{codeexample}

You should not, however, try to mix indexed and non-indexed variables. Once an
assignment is made using an index, the |math| library expects all instances of
the variable on the right hand side of an assignment to be followed by an
index. This effect is reversed if you subsequently make an assignment to the
variable without an index: the |math| library (or to be precise the \pgfname\
math-engine) will then ignore any index following the variable on the right
hand side of an assignment.

In some cases, you may wish to assign a value or expression to a variable
without evaluating it with the \pgfname\ math-engine. In this case, you can use
the following keyword:

\begin{math-keyword}{{let} \meta{variable} \texttt{=} \meta{expression}\texttt{;}}
    This keyword assigns \meta{expression} to \meta{variable} without
    evaluation. The \meta{expression} is however fully expanded using |\edef|.
    Any spaces preceding \meta{expression} are removed, but any trailing spaces
    (before the semi-colon) are included.
    %
\begin{codeexample}[preamble={\usetikzlibrary{math}}]
\tikzmath{
  let \x = (5*4)+1;
  let \c1 = blue;
}
\x, ``\c1''
\end{codeexample}
    %
\end{math-keyword}

\subsection{Integers, ``Real'' Numbers, and Coordinates}

By default, assignments are made by evaluating expressions using the \pgfname\
math-engine and results  are usually returned as number with a decimal point
(unless you are assigning to a count register or use the |int| function).
%
As this is not always desirable, the |math| library allows variables -- which
\emph{must} be \TeX\ macros -- to be `declared' as being a particular `type'.
The library recognizes three types: integers (numbers without a decimal point),
real numbers (numbers with a decimal point\footnote{Strictly speaking, due to
the finite range and precision of \TeX\ numerical capabilities, the term
``real'' is not correct.}), and coordinates.

To declare a variable as being one of the three types, you  can use the
keywords shown below. It is important to remember that by telling the |math|
library you want it to do a particular assignment for a variable, it will also
do the same assignment when the variable is indexed.
%
\begin{codeexample}[preamble={\usetikzlibrary{math}}]
\tikzmath{
  integer \x;
  \x1 = 3+4; \x2 = 30+40; \x3 = 300+400;
}
\x1, \x2, \x3
\end{codeexample}

%But, if you want integer results without using a count register or the
%|int| function, you can use a keyword to indicate this:

\begin{math-keyword}{{integer} \meta{variable}\opt{\texttt{,} \meta{additional variables}}\texttt{;}}
    The |integer| keyword indicates that assignments to the \meta{variable} or
    the comma separated list of \meta{additional variables} should be truncated
    (not rounded) to integers. The variables should be ordinary macros --
    \emph{not} \TeX\ registers. In addition the variables should \emph{not} be
    indexed.
    %
\begin{codeexample}[preamble={\usetikzlibrary{math}}]
\tikzmath{
   integer \x, \y, \z;
   \x = 4*5+6;
   \y = sin(30)*4;
   \z = log10(512) / log10(2);
   print {$x=\x$, $y=\y$, $z=\z$};
}
\end{codeexample}
    %
\end{math-keyword}

\begin{math-keyword}{{int} \meta{variable}\opt{\texttt{,} \meta{additional variables}}\texttt{;}}
    Short version of the |integer| keyword.
\end{math-keyword}

Having declared a variable as an integer, the |math| library will continue to
assign only integers to that variable within the current \TeX\ scope. If you
wish to assign non-integer (i.e., \emph{real}) numbers to the same variable,
the following keyword can be used.

\begin{math-keyword}{{real} \meta{variable}\opt{\texttt{,} \meta{additional variables}}\texttt{;}}
    The |real| keyword ensures that assignments \meta{variable} (and
    \meta{additional variables}) will not be truncated to integers.
\end{math-keyword}

In order to take advantage of |math| library interface to the |calc| library
you must indicate that a variable is to be assigned coordinates, using the
following keyword.

\begin{math-keyword}{{coordinate} \meta{variable}\opt{\texttt{,} \meta{additional variables}}\texttt{;}}
    This keyword enables \tikzname-style coordinates such as |(2cm,3pt)| or
    |(my node.east)| to be parsed and assigned to \meta{variable} in the form
    $x,y$, which can then be used in a |tikzpicture|:
    %
\begin{codeexample}[preamble={\usetikzlibrary{math}}]
\tikzmath{
   coordinate \c;
   \c = (45:10pt);
}
\tikz\draw (0,0) -- (\c);
\end{codeexample}

    If the \tikzname\ |calc| library is loaded, coordinate calculations can be
    performed; the coordinate expression does not have to be surrounded by
    |($|\ldots|$)|.
    %
\begin{codeexample}[preamble={\usetikzlibrary{math}}]
\tikzmath{
   coordinate \c, \d;
   \c = (-1,2)+(1,-1);
   \d = (4,1)-(2,-1);
}
\tikz\draw (\c) -- (\d);
\end{codeexample}

    In addition to assigning the $x$ and $y$ coordinates to \meta{variable}
    (possibly with an optional index), two further variables are defined. The
    first takes the name of \meta{variable} (e.g., |\c|) suffixed with |x|
    (i.e., |\cx|) and is assigned the $x$ coordinate of |\c|. The second takes
    the name of \meta{variable} suffixed with |y| (i.e., |\cy|) and is assigned
    the $y$ coordinate of |\c|.
    %
\begin{codeexample}[preamble={\usetikzlibrary{math}}]
\tikzmath{
   coordinate \c;
   \c1 = (30:20pt);
   \c2 = (210:20pt);
}
\tikz\draw (\cx1,\cy1) -- (\cx2,\cy1) -- (\cx2,\cy2) -- (\cx1,\cy2);
\end{codeexample}
    %
\end{math-keyword}

%\begin{math-keyword}{{point} \meta{variable}\opt{\texttt{,} \meta{additional variables}}\texttt{;}}
%    The |point| keyword is a synonym for the |coordinate| keyword and performs
%    the same function.
%\end{math-keyword}

\subsection{Repeating Things}

\begin{math-keyword}{{for} \meta{variable} \texttt{in \{}\meta{list}\texttt{\}\{}\meta{expressions}\texttt{\};}}
    This is a ``trimmed down'' version of the |\foreach| command available as
    part of \pgfname\ and \tikzname, but cannot currently be used outside of
    the |\tikzmath| command. It is important to note the following:
    %
    \begin{itemize}
        \item Every value in \meta{list} is evaluated using the \pgfname\
            mathematical engine. However, if an item in \meta{list} contains a
            comma, it \emph{must} be surrounded by braces, for example,
            |{mod(5, 2)}|.
            %
\begin{codeexample}[pre={\pgfmathsetseed{1}},preamble={\usetikzlibrary{math}}]
\tikzmath{
  int \x, \v;
  \v=1;
  for \x in {1,...,{random(3,10)}}{
     \v=\v*2;
  };
  print {$x=\x, v=\v$};
}
\end{codeexample}
            %
        \item Because each item is evaluated, you cannot use \tikzname\
            coordinates in \meta{list}.
        \item Only single variable assignment is supported.
        \item The ``dots notation'' (e.g., |1,2,...,9|) can be used in
            \meta{list}, but is not as sophisticated as the \pgfname\
            |\foreach| command. In particular, contextual replacement is not
            possible.
        \item Assignments that occur in the loop body \emph{are not scoped}.
            They last beyond the body of each iteration and the end of the
            |for| statement. This includes the values assigned to the
            \meta{variable}.
            %
\begin{codeexample}[preamble={\usetikzlibrary{math}}]
\tikzmath{
  int \x, \y;
  \y = 0;
  for \x1 in {1,...,5}{
    for \x2 in {10,20,...,50}{
      \y = \y+\x1*\x2;
    };
  };
}
$x_1=\x1, x_2=\x2, y=\y$
\end{codeexample}
    \end{itemize}
\end{math-keyword}

\subsection{Branching Statements}

Sometimes you may wish to execute different statements depending on the value
of an expression. In this case the following keyword can be used:

\begin{math-keyword}{{if} \meta{condition} \texttt{then \{}\meta{if-non-zero-statements}\texttt{\};}}
    This keyword executes \meta{if-non-zero-statements} if the expression in
    \meta{condition} evaluates to any value other than zero.
\end{math-keyword}

\begin{math-keyword}{{if} \meta{condition} \texttt{then \{}\meta{if-non-zero-statements}\texttt{\}} \texttt{else} \texttt{\{}\meta{if-zero-statements}\texttt{\}}\texttt{;}}
    This keyword executes \meta{if-non-zero-statements} if the expression in
    \meta{condition} evaluates to any value other than zero and the
    \meta{if-zero-statements} are executed if the expression in
    \meta{condition} evaluates to zero.
    %
\begin{codeexample}[preamble={\usetikzlibrary{math}}]
  \begin{tikzpicture}
  \tikzmath{
    int \x;
    for \k in {0,10,...,350}{
      if \k>260 then { let \c = orange; } else {
        if \k>170 then { let \c = blue; } else {
          if \k>80 then { let \c = red; } else {
            let \c = green; }; }; };
      {
        \path [fill=\c!50, draw=\c] (\k:0.5cm) -- (\k:1cm) --
          (\k+5:1cm) -- (\k+5:0.5cm) -- cycle;
      };
    };
  }
  \end{tikzpicture}
\end{codeexample}
    %
\end{math-keyword}

\subsection{Declaring Functions}

You can add functions by using the following keywords:

\begin{math-keyword}{{function} \meta{name}\texttt{(}\meta{arguments}\texttt{) \{} \meta{definition} \texttt{\};}}
    This keyword works much like the |declare function| provided by the
    \pgfname\ math-engine. The function \meta{name} can be any name that is not
    already a function name in the current scope. The list of \meta{arguments}
    are comma separated \TeX\ macros such as |\x|, or |\y| (it is not possible
    to declare functions that take variable numbers of arguments). If the
    function takes no arguments then the parentheses need not be used. It is
    very important to note that the arrays that the \pgfname\ math engine
    supports \emph{cannot currently be passed as arguments to functions}.

    The function \meta{definition} should be a sequence of statements that can
    be parsed by the |\tikzmath| command and should use the commands specified
    in the \meta{arguments}. The |return| keyword (described below) should be
    used to indicate the value returned by the function.
    %
    Although \meta{definition} can take any statements accepted by |\tikzmath|,
    it is not advisable try to define functions inside other functions.
    %
\begin{codeexample}[pre={\pgfmathsetseed{1}},preamble={\usetikzlibrary{math}}]
\tikzmath{
  function product(\x,\y) {
    return \x*\y;
  };
  int \i, \i, \k;
  \i = random(1,10);
  \j = random(20, 40);
  \k = product(\i, \j);
  print { $\i\times \j = \k$ };
}
\end{codeexample}
    %
\end{math-keyword}

\begin{math-keyword}{{return} \meta{expression}\texttt{;}}
    This keyword should be used as the last executed statement in a function
    definition to indicate the value that should be returned.
\end{math-keyword}

\subsection{Executing Code Outside the Parser}

Sometimes you may wish to do ``something'' outside the parser, perhaps display
some intermediate result or execute some code. In this case you have two
options. Firstly, the following keyword can be used:

\begin{math-keyword}{{print} \texttt{\{}\meta{code}\texttt{\};}}
    Execute \meta{code} immediately. This is intended as convenience keyword
    for displaying information in a document (analogous to the |print| command
    in real programming languages). The \meta{code} is executed inside a \TeX\
    group.
    %
\begin{codeexample}[pre={\pgfmathsetseed{1}},preamble={\usetikzlibrary{math}}]
\tikzmath{
  int \x, \y, \z;
  \x = random(2, 5);
  for \y in {0,...,6}{
    \z = \x^\y;
    print {$\x^\y=\z$, };
  };
}
\end{codeexample}
    %
\end{math-keyword}

Secondly, if a statement begins with  a brace |{|, then everything up to the
closing brace |}| is collected and executed (the closing brace \emph{must} be
followed by a semi-colon). Like the |print| keyword, the contents of the braces
is executed inside a \TeX\ group. Unlike the |print| keyword, the brace
notation can be used in functions so that |tikz| path commands can be safely
executed inside a |tikzpicture|.
%
\begin{codeexample}[preamble={\usetikzlibrary{math}}]
\begin{tikzpicture}
\draw [help lines] grid (3,2);
\tikzmath{
  coordinate \c;
  for \x in {0,10,...,360}{
    \c = (1.5cm, 1cm) + (\x:1cm and 0.5cm);
    { \fill (\c) circle [radius=1pt]; };
  };
}
\end{tikzpicture}
\end{codeexample}