\documentclass[fancy,11pt,twocol]{elegantbook}
\usepackage{booktabs}
\title{A Statistical Analysis of Age Prediction}
\subtitle{First Homework of Modern Biological Technology}

\author{Yufeng Xie}
\institute{School of Life Sciences, Tsinghua University}
\date{\today}
\version{1.0}

\extrainfo{}

\logo{i.png}
\cover{cov.pdf}

\begin{document}

\maketitle
\tableofcontents
\clearpage
\thispagestyle{empty}
\mainmatter
\hypersetup{pageanchor=true}

\chapter{Survey}
Prof.Wang taught Modern Biological Technology to graduate students. He made a survey about his age estimation.
Of the 239 people, everyone submitted his own age, gender and age estimation.
Here are parts of the results:
% Table generated by Excel2LaTeX from sheet 'Sheet1'
\begin{table}[htbp]
	\centering
	\caption{Age Estimation}
	  \begin{tabular}{ccc}
	  \toprule
	  sex   & age   & pred\_age \\
	  \midrule
	  F     & 21    & 43 \\
	  F     & 22    & 45 \\
	  M     & 23    & 40 \\
	  F     & 21    & 45 \\
	  F     & 22    & 45 \\
	  F     & 22    & 45 \\
	  F     & 26    & 46 \\
	  F     & 22    & 46 \\
	  M     & 22    & 50 \\
	  \bottomrule
	  \end{tabular}%
	\label{tab:addlabel}%
  \end{table}%

Contact Infos:
\begin{itemize}
	\item Email: \email{xyf19@mails.tsinghua.edu.cn}
\end{itemize}

\section{Students Age}
To have a better understanding the distribution of data, we have a quick look on age using Waffle Chart.
\begin{figure}[htbp]
	\centering
	\includegraphics[width=0.7\textwidth]{waffe.pdf}
	\caption{Distribution of students' ages}
\end{figure}

\begin{note}
	Waffle chart, please refer to \href{https://en.wikipedia.org/wiki/Pie_chart#Square_chart_/_Waffle_chart}{this}.
\end{note}
Every cell represents one student. Most students are 22 and 23 years old.

\section{Students Age}
We have a quick look on gender using Waffle Chart.
\begin{figure}[htbp]
	\centering
	\includegraphics[width=0.7\textwidth]{waffle_sex.pdf}
	\caption{Distribution of students' genders}
\end{figure}

\chapter{The Normal Distribution}
To know whether age estimation obey normal distribution, we can have a graphic judgment or use nonparametric test method.

\section{Normal Distribution Fit}
We plot the age estimation using histogram, and fit it with normal distribution.
The data set is denoted as $A$, where $A_i$ represents an element and $i$ is a natural number from 1 to a total of 239.
We use $$
\frac{1}{n} \sum_{i=1}^{n} A_{i}
, n= 239$$ to estimate the average age, and adopt unbiased estimation of standard errors.
$$
\frac{1}{n-1} \sum_{i=1}^{n}\left(A_{i}-\overline{A}\right)^{2}
$$
\begin{figure}[htbp]
	\centering
	\includegraphics[width=0.7\textwidth]{norm_fit.pdf}
	\caption{The Fit of Age estimation distribution.
	The x-axis represents the estimated age,
	and the y-axis represents the proportion of people of the estimated age to the total number of people.
	The purple histogram represents real data, and the red dotted line indicates the fit of the data.
	The line is a normally distributed shape with $\mu$ and $\sigma$ being 45.2 and 4.2, respectively.  }
\end{figure}

We can see that most of the actual data is concentrated at an intermediate level, making it higher than the peak of the normal distribution. To
There are two outliers. Two girls had the estimation to be 18.
\section{The quantitle-quantile plot}
\begin{introduction}
	\item The quantitle-quantile(q-q) plot is a graphical technique for determining if two data sets come from populations with a common distribution. If so, each data point has the same quantile in the two different data set, and the points should fall along the 45-degree reference line.
\end{introduction}

\begin{figure}[htbp]
	\centering
	\includegraphics[width=0.7\textwidth]{qqplot.pdf}
	\caption{The quantitle-quantile plot of age estimation distribution. The points didn't fall along the $y=x$ reference line. }
\end{figure}

\begin{lstlisting}
	def qqplot(sample=raw['pred_age']):
		import numpy as np
		x = sample
		mu =np.mean(x)
		sigma =np.std(x,ddof=1)
		from scipy.stats import norm,percentileofscore
		samp_pct = [percentileofscore(x, i) for i in x]
		fit_pct = [norm.cdf(i,mu,sigma)*100 for i in x]
		import matplotlib.pyplot as plt
		plt.scatter(x=samp_pct, y=fit_pct)
		linex = np.arange(0, 100, 1)
		liney = np.arange(0, 100, 1)
		plt.plot(linex, liney, 'r--')
		plt.xlabel('Sample Percentage%') #绘制x轴
		plt.ylabel('Fit Percentage%') #绘制y轴
		plt.title(r'Q-Q plot')
		plt.savefig('qqplot.pdf')
	qqplot()
\end{lstlisting}

We compared the quantitles between age estimation dataset and standard normal distribution. The result may indicate that the data does not obey the normal distribution. We apply nonparametric test method to judge whether the data obey the normal distribution.

\section{Kolmogorov-Smirnov test}
Kolmogorov-Smirnov test is a nonparametric method to judge whether the data obey the normal distribution.
We are concerned about whether the data obey the normal distribution. Null hypothesis is that the data obey the normal distribution with $\mu$ and $\sigma$ being 45.2 and 4.2. Alternative hypothesis is that the data does't obey the normal distribution with $\mu$ and $\sigma$ being 45.2 and 4.2.
We test it with Python.

\begin{lstlisting}
import scipy.stats as stats
x = raw['pred_age']
mu =np.mean(x)
sigma =np.std(x,ddof=1)
normed_data=(x-mu)/sigma
print(stats.kstest(normed_data,'norm'))
\end{lstlisting}

The result is:
\begin{lstlisting}
KstestResult(statistic=0.2138458125325069, pvalue=4.5205350061342694e-10)
\end{lstlisting}
P-value is less than 0.05 and we can reject the null hypothesis, so the data doesn't obey the normal distribution.

To know whether the two girls affect the results, we delete their data, and have a test repeatly.
Null hypothesis is that after removing the two girls' data, the data obey the normal distribution.
Alternative hypothesis is that after removing the two girls' data, the data doesn't obey the normal distribution.
\begin{lstlisting}
	import scipy.stats as stats
	x = raw['pred_age']
	sp_x=x.tolist()
	sp_x.sort()
	sp_x = sp_x[2:]
	mu =np.mean(sp_x)
	sigma =np.std(sp_x,ddof=1)
	normed_data=(sp_x-mu)/sigma
	print(stats.kstest(normed_data,'norm'))
\end{lstlisting}

The result is:
\begin{lstlisting}
	KstestResult(statistic=0.19918782897725168, pvalue=1.0219734444990697e-08)
\end{lstlisting}
P-value is less than 0.05 and we can reject the null hypothesis, so the data doesn't obey the normal distribution.

\chapter{Gender}
We care about the influence of genders. For example, for the student of some gender, estimation of age is deeply affected by experience, so the data has a strong heterogeneity.
To know whether genders bring heterogeneity, we have Kolmogorov-Smirnov test on data of each gender.
\section{Male}
We individually had a test on mens' data to judge whether obeying the normal distribution.
Null hypothesis is that the mens' data obey the normal distribution.
Alternative hypothesis is that the mens' data doesn't obey the normal distribution.
\begin{lstlisting}
import scipy.stats as stats
	x = raw[raw['sex']=='M']['pred_age']
	mu =np.mean(x)
	sigma =np.std(x,ddof=1)
	normed_data=(x-mu)/sigma
	print(stats.kstest(normed_data,'norm'))
\end{lstlisting}
The result is:
\begin{lstlisting}
	KstestResult(statistic=0.2257722756474092, pvalue=5.831570657013506e-05)
\end{lstlisting}
P-value is less than 0.05 and we can reject the null hypothesis, so the men's data doesn't obey the normal distribution.

\section{Female}
We individually had a test on women‘s data to judge whether obeying the normal distribution.
Null hypothesis is that the women's data obey the normal distribution.
Alternative hypothesis is that the women's data doesn't obey the normal distribution.
\begin{lstlisting}
import scipy.stats as stats
	x = raw[raw['sex']=='M']['pred_age']
	mu =np.mean(x)
	sigma =np.std(x,ddof=1)
	normed_data=(x-mu)/sigma
	print(stats.kstest(normed_data,'norm'))
\end{lstlisting}
The result is:
\begin{lstlisting}
	KstestResult(statistic=0.20340064135351327, pvalue=1.613067403598425e-05)
\end{lstlisting}
P-value is less than 0.05 and we can reject the null hypothesis, so the women's data doesn't obey the normal distribution.

The data of both gender doesn't obey the normal distribution.

\chapter{One-way ANOVA—fixed-effects}
Data has labels such as genders and students' ages, so it can be divided into several groups.

\begin{lstlisting}
import scipy.stats as stats
raw.groupby('sex').describe(),raw.groupby('age').describe()
\end{lstlisting}

% Table generated by Excel2LaTeX from sheet 'des_sex'
\begin{table}[htbp]
	\centering
	\caption{Age estimation data for different groups\label{group}}
	  \begin{tabular}{rrrrr}
	  \toprule
			&       & \multicolumn{1}{l}{count} & \multicolumn{1}{l}{mean} & \multicolumn{1}{l}{std} \\
	  \midrule
	  \multicolumn{1}{l}{sex} & \multicolumn{1}{l}{F} & 139   & 22.4316547 & 1.70272739 \\
			& \multicolumn{1}{l}{M} & 100   & 22.37 & 1.0411241 \\
	  \midrule
	  \multicolumn{1}{l}{age} & 19    & 1     & 48    &  \\
			& 20    & 7     & 45.2857143 & 5.18698004 \\
			& 21    & 30    & 45.4666667 & 2.95638798 \\
			& 22    & 125   & 45.5  & 3.52067625 \\
			& 23    & 47    & 43.6595745 & 6.16891434 \\
			& 24    & 15    & 45.7333333 & 3.03471973 \\
			& 25    & 5     & 46.6  & 5.6833089 \\
			& 26    & 3     & 48    & 2 \\
			& 27    & 2     & 48.5  & 4.94974747 \\
			& 28    & 1     & 38    &  \\
			& 29    & 1     & 43    &  \\
			& 30    & 1     & 47    &  \\
			& 31    & 1     & 45    &  \\
	  \bottomrule
	  \end{tabular}%
	\label{tab:addlabel}%
\end{table}%
Table \ref{group} summaries the properties of data.
Suppose there are $k$ groups with $n_i$ observations in the $i$th group. The $j$th observation in the $i$th group will be denoted by $y_{ij}$. Let’s assume the following model.
$$
y_{i j}=\mu+\alpha_{i}+e_{i j}
$$
where $\mu$ is a constant, $\alpha_i$ is a constant specific to the ith group, and $e_{ij}$ is an error term.

\begin{note}
	\begin{itemize}
		\item  $\mu$ represents the underlying mean of all groups taken together.
		\item $\alpha_i$ represents the difference between the mean of the $i$th group and the overall mean.
		\item $e_{ij}$ represents random error about the mean $\mu + \alpha_{i}$ for an individual observation from the ith group.
	\end{itemize}
\end{note}
Whether the underlying mean age estimation of each of the several groups is the same? For gender groups and age groups, we have a ANOVA test.
\section{Gender}

The null hypothesis is that the underlying mean age estimation of each of the several groups(Female and male) is the same.
The alternative hypothesis is that the underlying mean age estimation of each of the several groups(Female and male) is different.

To test the hypothesis $H_0 : α_i = 0 $for all $i$ vs. $H_1$: at least one $α_i ≠ 0$, use the following procedure:
Compute the test statistic F = Between MS/Within MS.
If $F > F_{k−1,n−k,1−α}$ then reject $H_0$.

$$\text { Between SS }=\sum_{i=1}^{k} n_{i} \overline{y}_{i}^{2}-\frac{\left(\sum_{i=1}^{k} n_{i} \overline{y}_{i}\right)^{2}}{n}=\sum_{i=1}^{k} n_{i} \overline{y}_{i}^{2}-\frac{y_{*}^{2}}{n} $$
$$
\text { Within } \mathrm{SS}=\sum_{i=1}^{k}\left(n_{i}-1\right) s_{i}^{2}
$$
$$\text { Between MS } = \text { Between SS }/(k-1)$$
$$\text { Within MS } = \text { Within SS }/(n-k)$$

We only need to write down three-lines code:
\begin{lstlisting}
	import scipy
	archive = {i:j['pred_age'].tolist() for i,j in raw.groupby('sex')}
	scipy.stats.f_oneway(*archive.values())
\end{lstlisting}

The result is:
\begin{lstlisting}
	F_onewayResult(statistic=1.8527456025602052e-06, pvalue=0.9989151000012089)
\end{lstlisting}

P-value is more than 0.05, so we can't reject the null hypothesis. The underlying mean age estimation of each of the several groups(Female and male) is the same. It can be seen in figure \ref{sex}
\begin{figure}[htbp]
	\centering
	\includegraphics[width=0.7\textwidth]{sex.pdf}
	\caption{Age estimation distribution of genders.
	The x-axis represents the estimated age,
	and the y-axis represents genders. The difference does't exist among dots of different colors.\label{sex}}
\end{figure}

\section{Age}
Same as above, we have ANOVA test.
\begin{lstlisting}
	import scipy
	archive = {i:j['pred_age'].tolist() for i,j in raw.groupby('age')}
	scipy.stats.f_oneway(*archive.values())
\end{lstlisting}

The result is:
\begin{lstlisting}
	F_onewayResult(statistic=1.189127155588131, pvalue=0.291846925534072)
\end{lstlisting}

P-value is more than 0.05, so we can't reject the null hypothesis. The underlying mean age estimation of each of the several groups(ages) is the same. It can be seen in figure \ref{age}
\begin{figure}[htbp]
	\centering
	\includegraphics[width=0.7\textwidth]{age.pdf}
	\caption{Age estimation distribution of ages.
	The x-axis represents the students' ages,
	and the y-axis represents estimated age. The difference does't exist among dots of different colors.\label{age}}
\end{figure}

\chapter{Code}
My code is upload to \href{https://en.wikipedia.org/wiki/Pie_chart#Square_chart_/_Waffle_chart}{this repo}.

Statistical code:
\begin{lstlisting}
	'''
	@Description:
	@Version:
	@School: Tsinghua Univ
	@Date: 2019-09-19 09:59:30
	@LastEditors: Xie Yufeng
	@LastEditTime: 2019-09-22 23:52:45
	'''
	#!/usr/bin/env python
	# -*- encoding: utf-8 -*-
	'''
	@File    :   sta.py
	@Time    :   2019/09/19 09:59:37
	@Author  :   Xie Yufeng
	@Version :   1.0
	@Contact :   xyfzkd@outlook.com
	@Desc    :   None
	'''

	# -*- coding: utf-8 -*-
	#%%
	import pandas as pd
	raw = pd.read_excel('raw.xlsx')

	#%%
	import seaborn as sns
	sns.set_style("darkgrid")
	#sns.set(style="ticks")
	g = sns.pairplot(raw,hue="sex",diag_kind='hist')

	#%%
	g.savefig('cov.pdf',facecolor='white')

	#%%
	from pywaffle import Waffle
	import pandas as pd
	import matplotlib.pyplot as plt
	#%%
	df_age = raw.groupby('age').size().reset_index(name='counts_age')
	n_categories = df_agef.shape[0]
	colors_age = [plt.cm.Set3(i/float(n_categories)) for i in range(n_categories)]
	fig = plt.figure(
		FigureClass=Waffle,
		plots={
			'111': {
				'values': df_age['counts_age'],
				'labels': ["{1}".format(n[0], n[1]) for n in df_age[['age', 'counts_age']].itertuples()],
				'legend': {'loc': 'upper left', 'bbox_to_anchor': (1.05, 1), 'fontsize': 12, 'title':'Age'},
				'title': {'label': '# Vehicles by Age', 'loc': 'center', 'fontsize':18},
				'colors': colors_age
			}
		},
		rows=12,
		figsize=(16, 10)
	)
	fig.savefig("waffe.pdf",transparent=True)
	#%%
	df_age = raw.groupby('sex').size().reset_index(name='counts_age')
	n_categories = df_age.shape[0]
	colors_age = [plt.cm.Set3(i/float(n_categories)) for i in range(n_categories)]
	fig = plt.figure(
		FigureClass=Waffle,
		plots={
			'111': {
				'values': df_age['counts_age'],
				'labels': ["{1}".format(n[0], n[1]) for n in df_age[['sex', 'counts_age']].itertuples()],
				'legend': {'loc': 'upper left', 'bbox_to_anchor': (1.05, 1), 'fontsize': 12, 'title':'Gender'},
				'title': {'label': '# Vehicles by Age', 'loc': 'center', 'fontsize':18},
				'colors': colors_age
			}
		},
		rows=12,
		figsize=(16, 10)
	)
	fig.savefig("waffle_sex.pdf",transparent=True)
	#%%
	df_agef = raw[raw['sex']=='F'].groupby('age').size().reset_index(name='counts_age')
	df_agem = raw[raw['sex']=='M'].groupby('age').size().reset_index(name='counts_age')
	n_categoriesf = df_agef.shape[0]
	n_categoriesm = df_agem.shape[0]
	colors_agef = [plt.cm.Set3(i/float(n_categoriesf)) for i in range(n_categoriesf)]
	colors_agem = [plt.cm.Set3(i/float(n_categoriesm)) for i in range(n_categoriesm)]
	fig = plt.figure(
		FigureClass=Waffle,
		plots={
			'211': {
				'values': df_agef['counts_age'],
				'labels': ["{1}".format(n[0], n[1]) for n in df_agef[['age', 'counts_age']].itertuples()],
				'legend': {'loc': 'upper left', 'bbox_to_anchor': (1.05, 1), 'fontsize': 12, 'title':'Age'},
				'title': {'label': '# Vehicles by Age', 'loc': 'center', 'fontsize':18},
				'colors': colors_agef
			},
			'212': {
				'values': df_agem['counts_age'],
				'labels': ["{1}".format(n[0], n[1]) for n in df_agem[['age', 'counts_age']].itertuples()],
				'legend': {'loc': 'upper left', 'bbox_to_anchor': (1.05, 1), 'fontsize': 12, 'title':'Age'},
				'title': {'label': '# Vehicles by Age', 'loc': 'center', 'fontsize':18},
				'colors': colors_agem
			}
		},
		columns=6,
		figsize=(16, 10)
	)
	#g.savefig('1.pdf',facecolor='white')
	#%%
	raw
	#%%
	from scipy import stats
	fig,ax = plt.subplots()
	scipy.stats.probplot(raw['pred_age'],dist='norm',plot=ax,fit=True)
	#%%
	import probscale
	def equality_line(ax, label=None):
		limits = [
			np.min([ax.get_xlim(), ax.get_ylim()]),
			np.max([ax.get_xlim(), ax.get_ylim()]),
		]
		ax.set_xlim(limits)
		ax.set_ylim(limits)
		ax.plot(limits, limits, 'k-', alpha=0.75, zorder=0, label=label)

	norm = stats.norm(loc=21, scale=8)
	fig, ax = plt.subplots(figsize=(5, 5))
	ax.set_aspect('equal')

	common_opts = dict(
		plottype='qq',
		probax='x',
		problabel='Theoretical Quantiles',
		datalabel='Emperical Quantiles',
		scatter_kws=dict(label='Bill amounts')
	)

	fig = probscale.probplot(raw['pred_age'], ax=ax, dist=norm, **common_opts)

	equality_line(ax, label='Guessed Normal Distribution')
	ax.legend(loc='lower right')
	sns.despine()
	#%%
	fig.savefig('norm.pdf',edgecolor='black',transparent=False)

	#%%
	import seaborn as sns
	import numpy as np
	x = np.linspace(min(raw['pred_age']), max(raw['pred_age']), 50)
	y = 239*1/(3.82 * np.sqrt(2 * np.pi))*np.exp( - (x - 45.12)**2 / (2 * 3.82**2))
	plt.plot(x,y)
	plt.hist(raw['pred_age'],bins=int(max(raw['pred_age'])-min(raw['pred_age'])))
	plt.savefig('normbin.pdf')
	#%%
	max(raw['pred_age'])-min(raw['pred_age'])

	#%%
	import seaborn as sns
	import numpy as np
	import matplotlib.mlab as mlab
	import matplotlib.pyplot as plt
	x = raw['pred_age']
	mu =np.mean(x)
	sigma =np.std(x,ddof=1)

	num_bins = int(max(raw['pred_age'])-min(raw['pred_age']))
	n, bins, patches = plt.hist(x, num_bins,normed=1, facecolor='blue', alpha=0.5)
	y = mlab.normpdf(bins, mu, sigma)
	plt.plot(bins, y, 'r--')
	plt.xlabel('Age Estimation') #绘制x轴
	plt.ylabel('Probability') #绘制y轴
	plt.title(r'Normal Distribution Fit: $\mu=%.1f$,$\sigma=%.1f$'%(mu,sigma))
	plt.savefig('norm_fit.pdf')
	#%%
	def qqplot(sample=raw['pred_age']):
		import numpy as np
		x = sample
		mu =np.mean(x)
		sigma =np.std(x,ddof=1)
		from scipy.stats import norm,percentileofscore
		samp_pct = [percentileofscore(x, i) for i in x]
		fit_pct = [norm.cdf(i,mu,sigma)*100 for i in x]
		import matplotlib.pyplot as plt
		plt.scatter(x=samp_pct, y=fit_pct)
		linex = np.arange(0, 100, 1)
		liney = np.arange(0, 100, 1)
		plt.plot(linex, liney, 'r--')
		plt.xlabel('Sample Percentage%') #绘制x轴
		plt.ylabel('Fit Percentage%') #绘制y轴
		plt.title(r'Q-Q plot')
		plt.savefig('qqplot.pdf')
	qqplot()

	#%%
	import scipy.stats as stats
	x = raw['pred_age']
	mu =np.mean(x)
	sigma =np.std(x,ddof=1)
	normed_data=(x-mu)/sigma
	print(stats.kstest(normed_data,'norm'))
	#%%
	import scipy.stats as stats
	x = raw['pred_age']
	sp_x=x.tolist()
	sp_x.sort()
	sp_x = sp_x[2:]
	mu =np.mean(sp_x)
	sigma =np.std(sp_x,ddof=1)
	normed_data=(sp_x-mu)/sigma
	print(stats.kstest(normed_data,'norm'))

	#%%

	import scipy.stats as stats
	x = raw[raw['sex']=='M']['pred_age']
	mu =np.mean(x)
	sigma =np.std(x,ddof=1)
	normed_data=(x-mu)/sigma
	print(stats.kstest(normed_data,'norm'))
	#%%
	import scipy.stats as stats
	x = raw[raw['sex']=='F']['pred_age']
	sp_x=x.tolist()
	sp_x.sort()
	sp_x = sp_x[2:]
	mu =np.mean(sp_x)
	sigma =np.std(sp_x,ddof=1)
	normed_data=(sp_x-mu)/sigma
	print(stats.kstest(normed_data,'norm'))

	#%%
	import scipy.stats as stats
	import pandas as pd
	pd.DataFrame(raw.groupby('sex').describe()).to_csv('des_sex.csv',sep=',')
	pd.DataFrame(raw.groupby('age').describe()).to_csv('des.csv',sep=',')

	#%%
	from scipy import stats

	F, p = stats.f_oneway(d_data['ctrl'], d_data['trt1'], d_data['trt2'])
	#%%
	for i,j in raw.groupby('sex'):
		print(i)

	#%%
	[j for i,j in raw.groupby('sex')].values()

	#%%
	archive = {'group1': np.array([ 1, 2, 3 ]),
			'group2': np.array([ 9, 8, 7])}

	#%%

	#%%
	import scipy
	archive = {i:j['pred_age'].tolist() for i,j in raw.groupby('sex')}
	scipy.stats.f_oneway(*archive.values())

	#%%
	import seaborn as sns
	import matplotlib.pyplot as plt
	fig,ax = plt.subplots()
	ax = sns.stripplot(y='sex',x='pred_age',data=raw)
	fig.savefig('sex.pdf')
	#%%
	import scipy
	archive = {i:j['pred_age'].tolist() for i,j in raw.groupby('age')}
	scipy.stats.f_oneway(*archive.values())

	#%%
	import seaborn as sns
	import matplotlib.pyplot as plt
	fig,ax = plt.subplots()
	ax = sns.stripplot(x='age',y='pred_age',data=raw)
	fig.savefig('age.pdf')

	#%%

\end{lstlisting}

\end{document}


\chapter{Built-in Quantum Applications}\label{ch:apps}

This section describes the apps provided with this software, in the `Algorithms/' directory.

\begin{enumerate}

\item Cat-State Preparation: Prepares an $n$-bit quantum register in the maximally entangled Cat-State.
  The app is parameterized by $n$.

\item Quantum Fourier Transform (QFT): Performs quantum Fourier transform on an $n$-bit
  number. The app is parameterized by $n$.

\item Square Root: Uses a quantum concept
  called \emph{amplitude amplification} to find the square root of an $n$-bit number
  with the Grover's search technique\cite{Grover}. The app is parameterized by $n$.

\item Binary Welded Tree: Uses quantum random walk algorithm to
  find a path between an entry and exit node of a binary welded tree
  \cite{ref:bwt}. The app is parameterized by the height of the tree ($n$) and
  a time parameter ($s$) within which to find the solution.

\item Ground State Estimation: Uses quantum phase estimation algorithm to
  estimate the ground state energy of a molecule \cite{ref:gse}. The app
  is parameterized by the size of the molecule in terms of its molecular
  weight (M).

\item Triangle Finding Problem: Finds a triangle within a dense,
  undirected graph \cite{ref:tfp}. The app is parameterized by the
  number of nodes $n$ in the graph.

\item Boolean Formula: Uses the quantum algorithm described
  in~\cite{ref:boolean_formula}, to compute a winning strategy for the game of
  Hex. The app is parameterized by size of the Hex board $(x,y)$.

\item Class Number: A problem from computational algebraic number theory,
  to compute the class group of a real quadratic number field
  \cite{DBLP:conf/stoc/Hallgren05}. The app is parameterized by $p$, the
  number of digits after the radix point for floating point numbers used in
  computation.

\item Secure Hash Algorithm 1: An implementation of the reverse cryptographic hash function \cite{ref:sha1}. The message is decrypted by using the SHA-1 function as the oracle in a Grovers search algorithm. The app is parameterized by the size of the message in bits ($n$).

\item Shor's Factoring Algorithm: Performs factorization using the Quantum
  Fourier Transform \cite{Shor}. The app is parameterized by $n$, the
  size in bits of the number to factor.

\end{enumerate}


\section{Building blocks of grids: simplices}

%\subsection{outline}

\begin{myDef}[Simplex]
A simplex \coderm{BoSSS.Foundation.Grid.Simplex} (of dimension $D$) contains
\begin{packed_itemize}
  \item A subset $K_\textrm{REF} \subset \real^D$, that is the convex hull of the
        simplex vertices\coderm{BoSSS.Foundation.Grid.Simplex.Vertices}
         $\left( \vec{w}_0,\ldots,\vec{w}_{L-1} \right) \in \real^{D \times L}$,
         which is called the reference domain, or domain of the simplex.
         The center of gravity of $K_\textrm{ref}$ is $0$. It is further required that
         for $D > 0$
         $\left(\vec{w}_1 - \vec{w}_0,\ldots,\vec{w}_D - \vec{w}_0\right)$
         is a Basis of $\real^D$.
  \item A list of polynomials
        \coderm{BoSSS.Foundation.Basis.Polynomials},
        $\left( \phi_0(\vec{x}),\phi_1(\vec{x}),\vdots \right)$,
        which are pair-wise orthonormal
        (i.e. $\langle \phi_n, \phi_m \rangle_{K_\textrm{ref}} = \delta_{n,m}$).
        For some $p \in \nat$ there should be some $N$ so that
        $(\phi_0,\cdots,\phi_{N-1})$ form a complete (orthonormal) basis of the space of all
        polynomials of degree smaller or equal to $p$.
        Furthermore, this list is
        sorted according with respect to the polynomial degree, i.e.
        $\deg (\phi_0) = 0$ and for $m>n$ the relation $\deg(\phi_m) \geq \deg(\phi_n)$ holds.
  \item A set of quadrature rules\coderm{BoSSS.Foundation.Grid.Simplex.GetQuadratureRule(...)}
  \item An $(D-1)$ dimensional edge simplex\coderm{BoSSS.Foundation.Grid.Simplex.EdgeSimplex}
\end{packed_itemize}
The edges-spaces $ \left( F_e \right)_{e=0,\ldots,E-1}$ of $K_\textrm{REF}$ are a sorted list of all
different $(D-1)$  dimensional affine-linear spaces that can be found on $\partial K_\textrm{ref}$;
the edge $\epsilon_e := F_e \cap \partial K_\textrm{ref}$ is itself a $(D-1)$ dimensional convex hull.
Furthermore, a simplex contains
\begin{packed_itemize}
  \item an (ordered) list of edge transformations\coderm{BoSSS.Foundation.Grid.Simplex.TransformEdgeCoordinates(...)},
        $Te_e : \real^{D-1} \rightarrow \real^D$ for $e \in \{0,\ldots,E-1\}$ which are affine-linear,
        for which $Te_e(K_{\textrm{ref,edg}}) = \epsilon_e$ holds.
        $K_{\textrm{ref,edg}}$ is the domain of the edge simplex.
\end{packed_itemize}
\label{simplex}
\end{myDef}

\begin{myNot}[Reference coordinates] Coordinates within the domain of a simplex
are called reference coordinates and will be denoted by $\grvec{\upxi}:=(\xi,\eta) \in \real^2$
or $\grvec{\upxi}:=(\xi,\eta,\nu) \in \real^3$ in below.
\end{myNot}

%\begin{myRem}[on quadrature rules]
%The usage of product quadrature rules has shown to be inexact for the tetrahedron simplex.
%\end{myRem}

%\subsection{Simplices available in BoSSS}

\begin{myRem}
BoSSS offers the following simplices:
Point\coderm{BoSSS.Foundation.Grid.Point},
Line\coderm{BoSSS.Foundation.Grid.Line},
Square\coderm{BoSSS.Foundation.Grid.Square},
Triangle\coderm{BoSSS.Foundation.Grid.Triangle},
Cube\coderm{BoSSS.Foundation.Grid.Cube},
and
Tetrahedron\coderm{BoSSS.Foundation.Grid.Tetra};
The individual properties of these simplices can be found in the source code or read out from the
binaries.
\end{myRem}

%\subsubsection{Point}
%\subsubsection{Line}
%\subsubsection{Square}
%\subsubsection{Triangle}
%\subsubsection{Cube}
%\begin{myDef}[Cube simplex\coderm{BoSSS.Foundation.Grids.Cube}]
%Refer to figure \ref{figcube}; The vertices are: \\
%\begin{tabular}{cc}
%  $\vec{w}_0 = (-1,-1,-1)$ & $\vec{w}_4 = (-1,-1,1)$  \\
%  $\vec{w}_1 = (1,-1,-1)$  & $\vec{w}_5 = (1,-1,1)$  \\
%  $\vec{w}_2 = (-1,1,-1)$  & $\vec{w}_6 = (-1,1,1)$  \\
%  $\vec{w}_3 = (1,1,-1)$   & $\vec{w}_7 = (1,1,1)$  \\
%\end{tabular}
%\\
%The Edges are: \\
%\begin{tabular}{cc}
%  $\epsilon_0 = CH(\vec{w}_0,\vec{w}_2,\vec{w}_3,\vec{w}_7)$  & $\epsilon_3 = CH(\vec{w}_0,\vec{w}_1,\vec{w}_3,\vec{w}_6)$  \\
%  $\epsilon_1 = CH(\vec{w}_1,\vec{w}_4,\vec{w}_5,\vec{w}_6)$  & $\epsilon_4 = CH(\vec{w}_3,\vec{w}_5,\vec{w}_6,\vec{w}_7)$  \\
%  $\epsilon_2 = CH(\vec{w}_0,\vec{w}_1,\vec{w}_3,\vec{w}_6)$  & $\epsilon_5 = CH(\vec{w}_0,\vec{w}_1,\vec{w}_2,\vec{w}_4)$  \\
%\end{tabular}
%\end{myDef}
%
%\begin{figure}
%  % Requires \usepackage{graphicx}
%  \begin{center}
%      \includegraphics[width=0.6\textwidth]{figures/cube.eps} \\
%  \end{center}
%  \caption{The cube simplex}\label{figcube}
%\end{figure}
%\subsubsection{Tetra}


\section{Model Calibration}
\label{calibration}
We calibrated the Sri Lanka national model to two targets: case notifications and infection-related deaths. Further details on the calibration procedure are described below and the prior distributions of epidemiological calibration parameters are described in (Table \ref{tab:calibration_params}).

\subsection{General approach}
The model was calibrated using an adaptive Metropolis (AM) algorithm. In particular, we used the algorithm
based on adaptive Gaussian proposal functions proposed by Haario et al. to sample parameters from
their posterior distributions. We ran seven independent AM chains and combined the samples of the
seven chains to project epidemic trajectories over time. The definitions of the prior distributions and the
likelihood are detailed as follows.

\subsection{Likelihood function}
Likelihood functions are derived from comparing model outputs to target data at each time point nominated
for calibration. The dispersion parameters of these distribution are included as calibration parameters and
varied during the calibration approach to improve calibration efficiency.

\subsection{Calibration parameters}
Epidemiological calibration parameters are described in (Table \ref{tab:calibration_params}).
\vspace{-24mm}
\begin{table}[t]

    \begin{tabular}{| p{4.4cm} | p{4.4cm} | p{5cm} |}
        \hline
        \textbf{Parameter name} & \textbf{Distribution type} & \textbf{Distribution Parameters} \\
        \hline
        Incubation period & Truncated normal & Mean 5.5 days, standard 			        deviation 0.97 days, truncation \textless 1 day \\
      \hline
      Infectious period (for clinical strata 1 to 3) & Truncated normal &         	  Mean 6.5 days, standard deviation 0.77 days, truncation \textless 4 		      days \\
      \hline
      Risk of infection per contact & Uniform & 0.018 to 0.028\\
      \hline
      Infectious seed & Uniform & Range 150 to 400 \\
      \hline
   	  Case detection rate at testing rate of 1 test per 10, 000 per day 		      (proportion) & Uniform 	      & Range 0.04 to 0.18 \\
   	  \hline
   	  Increased transmissibility of VoC strains  & Uniform & 1.5 to 3.0\\
      \hline
      Start time of VoC emergence  & Uniform & Jan 14, 2021 to Mar 15, 2021 \\
      \hline
    \end{tabular}
    \caption{Epidemiological calibration parameters}
    \label{tab:calibration_params}
\end{table}
\clearpage


\documentclass[conference]{IEEEtran}
\IEEEoverridecommandlockouts
% The preceding line is only needed to identify funding in the first footnote. If that is unneeded, please comment it out.
\usepackage{cite}
\usepackage{amsmath,amssymb,amsfonts}
\usepackage{algorithmic}
\usepackage{graphicx}
\usepackage{textcomp}
\usepackage{xcolor}
\usepackage{tikz}

\usetikzlibrary{matrix}
\def\BibTeX{{\rm B\kern-.05em{\sc i\kern-.025em b}\kern-.08em
    T\kern-.1667em\lower.7ex\hbox{E}\kern-.125emX}}

\begin{document}

\title{CPS843 Assignment 1}

\author{\IEEEauthorblockN{Udbhav Prasad}
\IEEEauthorblockA{\textit{500909034}}
}

\maketitle

\begin{abstract}

First Assignment for Intro to Computer Vision (CPS843).

\end{abstract}

\section*{Part 1 - Problem 1}

Figure 1 contains the original gray scale image used in the various transformations.

\begin{figure}[htbp]
    \centering
    \includegraphics[width=8cm, height=4.5cm]{images/eldenring_grayscale.jpg}
    \caption{Original Gray scale Image}
\end{figure}

\subsection{Log Transformation}

Figure 2 contains the gray scale image after its been log transformed.

r is the input pixel, s is the output pixel, and c is a constant.

\begin{equation}
s=c\log{(1+r)}
\end{equation}

\begin{figure}[htbp]
    \centering
    \includegraphics[width=8cm, height=4.5cm]{images/eldenring_log_transform.jpg}
    \caption{Log Transformation Image}
\end{figure}

The log transformation brightens the dark areas of the image. It stretch's the low intensity areas and compresses the high intensity areas. Here we can see the dark areas under the tables are more visible.

\subsection{Inverse Log Transformation}

Figure 3 contains the gray scale image after its been inverse log transformed.

r is the input pixel, s is the output pixel, and c is a constant.

\begin{equation}
s=c\log^{-1} (r)
\end{equation}

\begin{figure}[htbp]
    \centering
    \includegraphics[width=8cm, height=4.5cm]{images/eldenring_inverse_log_transform.jpg}
    \caption{Inverse Log Transformation Image}
\end{figure}

The inverse log transformation darkens the dark areas of the image. It stretch's the high intensity areas and compresses the low intensity areas. Here we can see the dark areas under the tables are even less visible.

\subsection{Power Law Transformation}

Figure 4 contains the gray scale image after its been power law transformed with gamma as 3.

Figure 5 contains the gray scale image after its been power law transformed with gamma as 0.3.

\hfill

r is the input pixel, s is the output pixel, c and gamma is a constant.

\begin{equation}
s=cr^\gamma
\end{equation}

\begin{figure}[htbp]
    \centering
    \includegraphics[width=8cm, height=4.5cm]{images/eldenring_power_law_blacken.jpg}
    \caption{Power law Transformation Image (gamma is 3)}
    \centering
    \includegraphics[width=8cm, height=4.5cm]{images/eldenring_power_law_whiten.jpg}
    \caption{Power law Transformation Image (gamma is 0.3)}
\end{figure}

With gamma as 3 we see the transformation work similar to inverse log transformation. With gamma as 0.3 we see the transformation work similar to the log transformation.

\section*{Part 1 - Problem 2}

In figure 6, the 8-bit place slicing is shown for the image.

The highest 4-bit and 2-bit planes reconstruction images are show in figure 7 and 8 respectively.

The 4-bit reconstruction shows more detail than the 2-bit reconstruction. Also, the 4-bit reconstruction is more discernible than the 2-bit reconstruction image.

\begin{figure}
    \begin{tabular}{cc}
        \includegraphics[width=4cm]{images/eldenring_1.jpg} & \includegraphics[width=4cm]{images/eldenring_2.jpg} \\
        (a) Bit 1 & (b) Bit 2 \\[6pt]
        \includegraphics[width=4cm]{images/eldenring_3.jpg} & \includegraphics[width=4cm]{images/eldenring_4.jpg} \\
        (c) Bit 3 & (d) Bit 4 \\[6pt]
        \includegraphics[width=4cm]{images/eldenring_5.jpg} & \includegraphics[width=4cm]{images/eldenring_6.jpg} \\
        (a) Bit 5 & (b) Bit 6 \\[6pt]
        \includegraphics[width=4cm]{images/eldenring_7.jpg} & \includegraphics[width=4cm]{images/eldenring_8.jpg} \\
        (a) Bit 7 & (b) Bit 8 \\[6pt]
        %\multicolumn{2}{c}{\includegraphics[width=65mm]{it} }\\
        %\multicolumn{2}{c}{(e) Bit 5}
    \end{tabular}
    \caption{8-Bit Place Slicing}
\end{figure}

\begin{figure}[htbp]
    \centering
    \includegraphics[width=8cm, height=4.5cm]{images/eldenring_5678.jpg}
    \caption{Highest 4-bit Reconstruction Image}
    \centering
    \includegraphics[width=8cm, height=4.5cm]{images/eldenring_78.jpg}
    \caption{Highest 2-bit Reconstruction Image}
\end{figure}

\section*{Part 1 - Problem 3}

Figure 9 shows the histograms of the original image and the power-law images, before and after they are histogram equalized.
\bigbreak
Figure 9a is the image histogram before equalization and Figure 9b is the image histogram after equalization. Before the image is clustered to lower intensities and after equalization it is more spread out.
\bigbreak
Figure 9c is the power law transformed(gamma=0.3) image histogram before equalization and Figure 9d is the power law transformed(gamma=0.3) image histogram after equalization. Before equalization the image has the intensities clustered in the middle and after it is is spread out just like 9b.
\bigbreak
Figure 9e is the power law transformed(gamma=3) image histogram before equalization and Figure 9f is the power law transformed(gamma=3) image histogram after equalization. Before equalization the image is very dark hence the it has very low intensity. After equalization, the image has higher intensity and is more spread out.
\bigbreak

\begin{figure}
    \begin{tabular}{cc}
        \includegraphics[width=3cm]{images/original_pre_hist.png} \\
        (a) Before-Original Image \\ [2pt]
        \includegraphics[width=3cm]{images/original_post_hist.png} \\
        (b) After-Original Image \\[2pt]
        \includegraphics[width=3cm]{images/power_1_pre_hist.png} \\
        (c) Before-Power Law (gamma=0.3) \\[2pt]
        \includegraphics[width=3cm]{images/power_1_post_hist.png} \\
        (d) After-Power Law (gamma=0.3) \\[2pt]
        \includegraphics[width=3cm]{images/power_2_pre_hist.png} \\
        (e) Before-Power Law (gamma=3) \\[2pt]
        \includegraphics[width=3cm]{images/power_2_post_hist.png} \\
        (f) After-Power Law (gamma=3) \\[2pt]
    \end{tabular}
    \caption{Before and After Histogram Equalization}
\end{figure}

\section*{Part 1 - Problem 4}

Histogram matching is a transformation of an image to make its histogram match another histogram.

The procedure for histogram matching is as follows:
\begin{itemize}
  \item First we get the probability distribution of the input data p\textsubscript{r}(r\textsubscript{k})
  \item Second, do Histogram Equalization on input $s=T(r)$, where T is the histogram equalization.
  \item Thirdly, we compute $s=G(z)$.
  \item After, we get the inverse mapping $z=G^{-1}(s)$.
  \item The output image with values z is the histogram matched image.
\end{itemize}

You will not obtain the same histogram as the desired one after histogram matching because of rounding to discrete values that happens during histogram equalization.

\section*{Part 1 - Problem 5}

The histogram before equalization is shown in Figure 10, while the histogram after equalization is shown in Figure 11.

The calculation of histogram equalization is as follows:
\hfill

\begin{center}
\begin{tabular}{ |c|c|c|c|c| }
\hline
r\textsubscript{k} & n\textsubscript{k} & p\textsubscript{r}(r\textsubscript{k}) = n\textsubscript{k}/MN & s\textsubscript{k} & Rounded s\textsubscript{k}\\
\hline
r\textsubscript{0} = 0 & 0 & 0 & s\textsubscript{0} = 0 & s\textsubscript{0} = 0\\
r\textsubscript{1} = 1 & 7 & 0.35 & s\textsubscript{1} = 2.45 & s\textsubscript{1} = 2\\
r\textsubscript{2} = 2 & 3 & 0.15 & s\textsubscript{2} = 3.50 & s\textsubscript{2} = 4\\
r\textsubscript{3} = 3 & 2 & 0.10 & s\textsubscript{3} = 4.20 & s\textsubscript{3} = 4\\
r\textsubscript{4} = 4 & 3 & 0.15 & s\textsubscript{4} = 5.25 & s\textsubscript{4} = 5\\
r\textsubscript{5} = 5 & 1 & 0.05 & s\textsubscript{5} = 5.60 & s\textsubscript{5} = 6\\
r\textsubscript{6} = 6 & 1 & 0.05 & s\textsubscript{6} = 5.95 & s\textsubscript{6} = 6\\
r\textsubscript{7} = 7 & 3 & 0.15 & s\textsubscript{7} = 7.00 & s\textsubscript{7} = 7\\
\hline
\end{tabular}
\end{center}

\begin{figure}[htbp]
    \centering
    \includegraphics[width=8cm, height=4.5cm]{images/manual_pre_hist.png}
    \caption{Before Histogram Equalization}
    \centering
    \includegraphics[width=8cm, height=4.5cm]{images/manual_post_hist.png}
    \caption{After Histogram Equalization}
\end{figure}

Before Histogram Equalization:

\begin{center}
\begin{tabular}{ |l|l|l|l|l| }
\hline
1 & 2 & 4 & 7 & 3\\ \hline
2 & 4 & 7 & 3 & 1\\ \hline
5 & 6 & 2 & 1 & 1\\ \hline
4 & 7 & 1 & 1 & 1\\ \hline
\end{tabular}
\end{center}

After Histogram Equalization:

\begin{center}
\begin{tabular}{ |l|l|l|l|l| }
\hline
2 & 4 & 5 & 7 & 4\\ \hline
4 & 5 & 7 & 4 & 2\\ \hline
6 & 6 & 4 & 2 & 2 \\ \hline
5 & 7 & 2 & 2 & 2\\ \hline
\end{tabular}
\end{center}

\section*{Part 2}

Explanation of each step for padding and shearing an image:
\begin{itemize}
  \item \textbf{Step 1:} We use simple shear to transform the image. Simple shear is an affine transformation, we make an affine with maketform with the simple shear matrix values. What shear does is it moves a point further away from an axis, the more further away it is from another axis, which creates a bent rotated like shape.
  \includegraphics[width=8cm, height=4.5cm]{images/original.png}

  \item \textbf{Step 2:} Here we draw lines and circles to examine how the simple shear transformation affected these shapes. We can see the circles and lines have been bent according to the shear.
  \includegraphics[width=8cm, height=4.5cm]{images/sheared.png}

  \item \textbf{Step 3:} We compare different padding options, for "fill" we simply feel with a orange static color. Replicate padding makes a copy of the input, reverses it and applies that as the padding. Bound padding applies a strict distinction between the padding and the input. Bound has clear boundaries compared to fill method.
  \includegraphics[width=8cm, height=4.5cm]{images/transformation_fill.png}
  \includegraphics[width=8cm, height=4.5cm]{images/transformation_replicate.png}
  \includegraphics[width=8cm, height=4.5cm]{images/transformation_bound.png}

  \item \textbf{Step 4:} Here we try two padding methods, circular and symmetric. The circular method takes copies of the image and replicates it. The symmetric method takes the mirror of the image and fills padding with it.
  \includegraphics[width=8cm, height=4.5cm]{images/transform_symmetric.png}
  \includegraphics[width=8cm, height=4.5cm]{images/transformation_circular.png}

\end{itemize}

\begin{thebibliography}{00}
\bibitem{b1} Code for this assignment at ./a1.m
\bibitem{b2} Assignment source code: \url{https://github.com/UdbhavPrasad072300/CPS843-Assignments}
\end{thebibliography}

\end{document}

Assignment 1/LaTeX report/CPS843 Assignment 1.tex