{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# AS5001 (SUPAAAA) Advanced (Astronomical) Data Analysis\n",
"\n",
"## Problem Set 1, due 9 am Monday 4 October 2021"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Problem 1 - get set up [5]\n",
"\n",
"Find out how to compile and execute programs (e.g. Python, FORTRAN, Mathematica), and how to make plots on the\n",
"screen and laser printer (e.g. PGPLOT for FORTRAN, matplotlib for Python). (This is a Jupyter notebook written in Anaconda3 Python 3.8, which we recommend. We also recommend using Firefox as the default browser.)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Enable inline plotting in notebook\n",
"%matplotlib inline\n",
"# Populate namespace with numerical python function library and matplotlib plotting library.\n",
"import numpy as np\n",
"import matplotlib.pyplot as plt"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Problem 2. Histogram and Cumulative Distributions of Random Variables [20]\n",
"\n",
"(a) Be encouraged to build up a toolkit of function definitions (subroutines) that you can then use again and again in different contexts. Write a function to generate a random number distributed uniformly between specified limits A and B. Document the inputs and outputs of each subroutine. For example, in Python your function RANU might start with comments as follows:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def ranu(a,b,iseed):\n",
" # Return on each call a new random number sampling\n",
" # a uniform distribution between limits A and B,\n",
" # and a new value of the seed integer ISEED.\n",
" # Input:\n",
" # a (float) lower limit of boxcar\n",
" # b (float) upper limit of boxcar\n",
" # iseed (int) seed integer used for the random number generator\n",
" # Output:\n",
" # ranu (float) uniform random number\n",
" .\n",
" .\n",
" .\n",
" return ranu"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Note: This should be very easy because you can use the numpy random number generator, e.g.\n",
"np.random.uniform, or equivalent, to obtain random numbers distributed uniformly between 0 and 1, and \n",
"np.random.seed to set the random number generator seed."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"(b) Plot the binned histogram and cumulative (staircase) distribution function for $N$ samples drawn from your uniform random number generator RANU. The staircase should step up at each of the $N$ values, not just at the histgram bin boundaries, so that the finite bin size of your histogram does not degrade the resolution of your cumulative distribution. Make plots for $N = 10; 100; 1000; 10^4$."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"(c) Write similar functions rang(avg,sig,iseed) for Gaussian and rane(tau,iseed)\n",
"for Exponential random numbers. These should transform values from ranu into samples\n",
"from the Gaussian and Exponential distributions. Make plots as in (b) for $N = 10^4$."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Problem 3. Mean and Variance, Median and MAD [25]\n",
"\n",
"(a) Write a function that computes the the sample mean and sample variance of an input array of data values. Take care to ensure that the sample variance is an unbiased estimator. As always, describe the input and output arguments of the surbroutine in comments at the top."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def meanvar(x):\n",
" # compute sample mean and sample variance of data array x\n",
" # Input:\n",
" # x (float) array of data values\n",
" # Output:\n",
" # xmean (float) mean of data\n",
" # xvar (float) variance of the data\n",
" n = len(x)\n",
" .\n",
" .\n",
" .\n",
" return xmean, xvar"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"(b) Write a function to compute the median, and the mean-absolute-deviation (MAD) of an array of\n",
"data. Note: To compute the median, sort the data values, find the value half-way through the sorted\n",
"list, and interpolate if needed."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def medmad(x):\n",
" # compute median and mean-absolute-deviation of data array x\n",
" # Input:\n",
" # x (float) array of data values\n",
" # Output:\n",
" # avg (float) mean of data\n",
" # var (float) variance of the data\n",
" n = len(x)\n",
" .\n",
" .\n",
" .\n",
" return avg, var"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"(c) I'll supply a dataset from part of a zero-exposure CCD frame. Use your routines meanvar(x)\n",
"and medmad(x) to compute statistics that estimate the CCD bias level (mean and median) and the readout noise (standard deviation and mean-absolute-deviation). Summarise your results in a table, giving also a 1-$\\sigma$ error bar for your estimates of the mean and standard deviation."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import numpy as np\n",
"datadir = '/Users/acc4/Downloads/'\n",
"file = datadir+ 'bias.dat'\n",
"data = np.loadtxt(file,skiprows=6)\n",
"x,y,value = data[:,0],data[:,1],data[:,2]\n",
".\n",
".\n",
"."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Problem 4. Central Moments of a Distribution [25]\n",
"\n",
"(a) Write a subroutine that computes statistics that estimate the mean, variance, and higher-order central moments of a dataset."
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"ename": "SyntaxError",
"evalue": "invalid syntax (, line 12)",
"output_type": "error",
"traceback": [
"\u001b[0;36m File \u001b[0;32m\"\"\u001b[0;36m, line \u001b[0;32m12\u001b[0m\n\u001b[0;31m .\u001b[0m\n\u001b[0m ^\u001b[0m\n\u001b[0;31mSyntaxError\u001b[0m\u001b[0;31m:\u001b[0m invalid syntax\n"
]
}
],
"source": [
"def moments(x, m):\n",
" # compute first M central moments of the data array x\n",
" # Input:\n",
" # x (float) array of data values\n",
" # m (int) number of moments\n",
" # Output:\n",
" # xmom[0] (float) mean of data\n",
" # xmom[1] (float) variance of the data\n",
" # \n",
" # xmom[m] (float) m-th central moment \n",
" n = len(x)\n",
" .\n",
" .\n",
" .\n",
" return xmom"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"(b) Use ranu(a,b), rang($\\mu,\\sigma$) and rane($\\tau$) (Problem 2) to generate $N=10^6$ random samples of Uniform, Gaussian, and Exponential distributions. Use moments(x,m) to compute the first 4 central moments in each case. Derive analytic formulae for the first 4 central moments in terms of the parameters of each distribution. (The required integrals are not too difficult. If you get stuck, for partal credit, try http://integrals.wolfram.com.) \n",
"Prepare a table comparing your numerical and analytic results (test at least 2 sets of input parameters) to demonstrate the accuracy of your subroutines, and comment on reasons for any discrepancies."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Problem 5. Monte-Carlo Simulation to compare Sample Means and Medians [25]\n",
"\n",
"(a) The median $X_{\\rm med}$ is a \"robust\" statistic, less sensitive\n",
"to large outliers than the sample mean $\\overline{X}$.\n",
"For this reason, a \"running median filter\" is often used to \"smooth\" \n",
"or remove \"spikes\" from a light curve or spectrum.\n",
"Medians are also often used to combine a series of CCD frames\n",
"so that the result is not badly affected by cosmic ray hits.\n",
"However, $X_{\\rm med}$ is a noisier statistic than $\\overline{X}$, as you will\n",
"discover in the following Monte-Carlo calculation.\n",
"\n",
"Use your subroutine rang($\\mu$,$\\sigma$) to draw $N$ samples from a Gaussian distribution\n",
"with $(\\mu,\\sigma)=(0,1)$.\n",
"Calculate the sample mean $\\overline{X}$ and median $X_{\\rm med}$ for the set of $N$ samples.\n",
"Repeat the above calculation $M$ times,\n",
"and characterise the distributions of $X_{\\rm med}$ and $\\overline{X}$\n",
"by calculating their mean values and standard deviations over the $M$ \n",
"samples. Choose $M$ large enough to keep uncertainties below\n",
"1% of the standard deviations.\n",
"Make a log-log plot showing from your Monte-Carlo simulation\n",
"how the standard deviations of $X_{\\rm med}$ and $\\overline{X}$\n",
"vary with $N$ for $N=1,2,3,...,100$.\n",
"(If this calculation takes a very long time, try to improve the efficiency of your code.)\n",
"Which statistic has the larger variance, $X_{\\rm med}$ or $\\overline{X}$?\n",
"Based on your results, decide whether it is better to take medians\n",
"with an odd or even number of data points. Explain your reasoning.\n",
"\n",
"(b) For a sample of $N$ Gaussian random variables \n",
"(each with mean 0 and standard deviation $\\sigma$),\n",
"derive an analytic formula in terms of $N$ and $\\sigma$\n",
"for $\\sigma^2(\\overline{X})$, the variance of the sample mean.\n",
"Derive a similar formula for $\\sigma^2(X_{\\rm med})$, in the limit of large $N$.\n",
"Which is larger, $\\sigma^2(\\overline{X})$ or $\\sigma^2(X_{\\rm med})$?\n",
"Compare your formulae with the large-$N$ results \n",
"from your Monte-Carlo simulation."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"anaconda-cloud": {},
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.8.8"
}
},
"nbformat": 4,
"nbformat_minor": 1
}