From 46a4fc25683453e54b6e737027f0b5a933731b7c Mon Sep 17 00:00:00 2001 From: Morten Hjorth-Jensen Date: Tue, 23 Aug 2022 21:33:37 +0200 Subject: [PATCH] updating --- doc/BookChapters/statistics.do.txt | 704 +---------- doc/LectureNotes/statistics.ipynb | 1772 +++++++++++++--------------- 2 files changed, 828 insertions(+), 1648 deletions(-) diff --git a/doc/BookChapters/statistics.do.txt b/doc/BookChapters/statistics.do.txt index 51ca22e65..631c7657d 100644 --- a/doc/BookChapters/statistics.do.txt +++ b/doc/BookChapters/statistics.do.txt @@ -2,7 +2,7 @@ ===== Domains and probabilities ===== -!bblock + Consider the following simple example, namely the tossing of two dice, resulting in the following possible values !bt \begin{equation*} @@ -16,11 +16,7 @@ To this domain we have the corresponding *probabilities* \{1/36,2/36/,3/36,4/36,5/36,6/36,5/36,4/36,3/36,2/36,1/36\}. \end{equation*} !et -!eblock - -===== Tossing the dice ===== -!bblock The numbers in the domain are the outcomes of the physical process of tossing say two dice. We cannot tell beforehand whether the outcome is 3 or 5 or any other number in this domain. This defines the randomness of the outcome, or unexpectedness or any other synonimous word which @@ -42,18 +38,14 @@ appear in a random order. After 11 throws the results may look like \{10,8,6,3,6,9,11,8,12,4,5\}. \end{equation*} !et -!eblock -===== Stochastic variables ===== -!bblock - _Random variables are characterized by a domain which contains all possible values that the random value may take. This domain has a corresponding probability distribution function(PDF)_. -!eblock -===== Stochastic variables and the main concepts, the discrete case ===== -!bblock + +=== Stochastic variables and the main concepts, the discrete case === + There are two main concepts associated with a stochastic variable. The *domain* is the set $\mathbb D = \{x\}$ of all accessible values the variable can assume, so that $X \in \mathbb D$. An example of a @@ -69,12 +61,7 @@ occur p(x) = \mathrm{Prob}(X=x). \end{equation*} !et -!eblock - - -===== Stochastic variables and the main concepts, the continuous case ===== -!bblock In the continuous case, the PDF does not directly depict the actual probability. Instead we define the probability for the stochastic variable to assume any value on an infinitesimal interval @@ -91,11 +78,7 @@ on a non-infinitesimal interval $[a,\,b]$ is then just the integral Qualitatively speaking, a stochastic variable represents the values of numbers chosen as if by chance from some specified PDF so that the selection of a large set of these numbers reproduces this PDF. -!eblock - -===== The cumulative probability ===== -!bblock Of interest to us is the *cumulative probability distribution function* (_CDF_), $P(x)$, which is just the probability for a stochastic variable $X$ to assume any value less than $x$ @@ -112,11 +95,8 @@ The relation between a CDF and its corresponding PDF is then p(x) = \frac{d}{dx}P(x). \end{equation*} !et -!eblock - -===== Properties of PDFs ===== -!bblock +=== Properties of PDFs === There are two properties that all PDFs must satisfy. The first one is positivity (assuming that the PDF is normalized) @@ -137,11 +117,7 @@ both discrete and continuous PDFs, this condition is \int_{x\in\mathbb D} p(x)\,dx & = 1. \end{align*} !et -!eblock - -===== Important distributions, the uniform distribution ===== -!bblock The first one is the most basic PDF; namely the uniform distribution !bt @@ -159,11 +135,7 @@ p(x)dx = dx & \in [0,1]. \] !et The latter distribution is used to generate random numbers. For other PDFs, one needs normally a mapping from this distribution to say for example the exponential distribution. -!eblock - -===== Gaussian distribution ===== -!bblock The second one is the Gaussian Distribution !bt \begin{equation*} @@ -217,23 +189,17 @@ plt.subplots_adjust(left=0.15) plt.savefig('gaussian.pdf', format='pdf') plt.show() !ec -!eblock - - -===== Exponential distribution ===== -!bblock Another important distribution in science is the exponential distribution !bt \begin{equation*} p(x) = \alpha\exp{-(\alpha x)}. \end{equation*} !et -!eblock -===== Expectation values ===== -!bblock +=== Expectation values === + Let $h(x)$ be an arbitrary continuous function on the domain of the stochastic variable $X$ whose PDF is $p(x)$. We define the *expectation value* of $h$ with respect to $p$ as follows @@ -254,11 +220,7 @@ follows \langle x^n \rangle \equiv \int\! x^n p(x)\,dx \end{equation*} !et -!eblock - -===== Stochastic variables and the main concepts, mean values ===== -!bblock The zero-th moment $\langle 1\rangle$ is just the normalization condition of $p$. The first moment, $\langle x\rangle$, is called the *mean* of $p$ and often denoted by the letter $\mu$ @@ -276,12 +238,8 @@ for a continuous distribution and for a discrete distribution. Qualitatively it represents the centroid or the average value of the PDF and is therefore simply called the expectation value of $p(x)$. -!eblock -===== Stochastic variables and the main concepts, central moments, the variance ===== -!bblock - A special version of the moments is the set of *central moments*, the n-th central moment defined as !bt \begin{equation*} @@ -305,14 +263,10 @@ The square root of the variance, $\sigma =\sqrt{\langle (x-\langle x\rangle)^2\r _standard deviation_ of $p$. It is the RMS (root-mean-square) value of the deviation of the PDF from its mean value, interpreted qualitatively as the ``spread'' of $p$ around its mean. -!eblock +=== Probability Distribution Functions === - -===== Probability Distribution Functions ===== -!bblock - The following table collects properties of probability distribution functions. In our notation we reserve the label $p(x)$ for the probability of a certain event, while $P(x)$ is the cumulative probability. @@ -330,12 +284,7 @@ while $P(x)$ is the cumulative probability. | Normalization | $P_N=1$ | $P(b)=1$ | |--------------------------------------------------------------------------------------------------------------------------------------| -!eblock - - -===== Probability Distribution Functions ===== -!bblock With a PDF we can compute expectation values of selected quantities such as !bt @@ -352,12 +301,8 @@ if we have a discrete PDF or !et in the case of a continuous PDF. We have already defined the mean value $\mu$ and the variance $\sigma^2$. -!eblock -===== The three famous Probability Distribution Functions ===== -!bblock - There are at least three PDFs which one may encounter. These are the _Uniform distribution_ @@ -380,7 +325,7 @@ yielding probabilities different from zero in the interval $[0,\infty)$ and with \mu = \int_0^{\infty}xp(x)dx=\int_0^{\infty}x\alpha \exp{(-\alpha x)}dx=\frac{1}{\alpha}, \end{equation*} !et -!eblock + with variance !bt \begin{equation*} @@ -389,8 +334,7 @@ with variance !et -===== Probability Distribution Functions, the normal distribution ===== -!bblock + Finally, we have the so-called univariate normal distribution, or just the _normal distribution_ !bt \begin{equation*} @@ -412,11 +356,7 @@ which becomes with a suitable change of variables \mu =\frac{1}{b\sqrt{2\pi}}\int_{-\infty}^{\infty}b\sqrt{2}(a+b\sqrt{2}y)\exp{-y^2}dy=a. \end{equation*} !et -!eblock - -===== Probability Distribution Functions, the normal distribution ===== -!bblock Similarly, the variance becomes !bt \begin{equation*} @@ -440,11 +380,6 @@ centered around zero and with a variance $\sigma^2=1$, leading to p(x)=\frac{1}{\sqrt{2\pi}}\exp{\left(-\frac{x^2}{2}\right)}. \end{equation} !et -!eblock - - -===== Probability Distribution Functions, the cumulative distribution ===== -!bblock The exponential and uniform distributions have simple cumulative functions, whereas the normal distribution does not, being proportional to the so-called @@ -456,13 +391,8 @@ P(x) = \frac{1}{\sqrt{2\pi}}\int_{-\infty}^x\exp{\left(-\frac{t^2}{2}\right)}dt, \end{equation*} !et which is difficult to evaluate in a quick way. -!eblock - -===== Probability Distribution Functions, other important distribution ===== -!bblock - Some other PDFs which one encounters often in the natural sciences are the binomial distribution !bt \begin{equation*} @@ -479,12 +409,8 @@ The sequence of binomial trials is characterized by the following definitions * In every independent trial one registers if a specific situation happens or not, such as the jump to the left or right of a random walker. * The probability for every outcome in a single trial has the same value, for example the outcome of tossing (either heads or tails) a coin is always $1/2$. -!eblock -===== Probability Distribution Functions, the binomial distribution ===== -!bblock - In order to compute the mean and variance we need to recall Newton's binomial formula !bt @@ -521,13 +447,10 @@ which we rewrite as \mu=ny\sum_{\nu=0}^n\left(\begin{array}{c} n-1 \\ \nu\end{array}\right)y^{\nu}(1-y)^{n-1-\nu} =ny(y+1-y)^{n-1}=ny. \end{equation*} !et -!eblock + The variance is slightly trickier to get. It reads $\sigma^2=ny(1-y)$. -===== Probability Distribution Functions, Poisson's distribution ===== -!bblock - Another important distribution with discrete stochastic variables $x$ is the Poisson model, which resembles the exponential distribution and reads !bt @@ -544,13 +467,7 @@ In this case both the mean value and the variance are easier to calculate, \end{equation*} !et and the variance is $\sigma^2=\lambda$. -!eblock - - - -===== Probability Distribution Functions, Poisson's distribution ===== -!bblock An example of applications of the Poisson distribution could be the counting of the number of $\alpha$-particles emitted from a radioactive source in a given time interval. In the limit of $n\rightarrow \infty$ and for small probabilities $y$, the binomial distribution @@ -562,12 +479,10 @@ the binomial distribution we can show that \lim_{n\rightarrow \infty}\left(\begin{array}{c} n \\ x\end{array}\right)y^x(1-y)^{n-x} e^{-\lambda}=\sum_{x=1}^{\infty}\frac{\lambda^x}{x!} e^{-\lambda}. \end{equation*} !et -!eblock +=== Meet the covariance! === -===== Meet the covariance! ===== -!bblock An important quantity in a statistical analysis is the so-called covariance. Consider the set $\{X_i\}$ of $n$ @@ -589,13 +504,7 @@ with \int\cdots\int x_i P(x_1,\dots,x_n)\,dx_1\dots dx_n. \end{equation*} !et -!eblock - - - -===== Meet the covariance in matrix disguise ===== -!bblock If we consider the above covariance as a matrix !bt \[ @@ -606,10 +515,7 @@ then the diagonal elements are just the familiar variances, $C_{ii} = \mathrm{Cov}(X_i,\,X_i) = \mathrm{Var}(X_i)$. It turns out that all the off-diagonal elements are zero if the stochastic variables are uncorrelated. -!eblock - -===== Covariance ===== !bc pycod # Importing various packages from math import exp, sqrt @@ -641,8 +547,6 @@ print(c) -===== Meet the covariance, uncorrelated events ===== -!bblock Consider the stochastic variables $X_i$ and $X_j$, ($i\neq j$). We have !bt @@ -668,14 +572,8 @@ leading to Cov(X_i, X_j) = 0 \hspace{0.1cm} (i\neq j). \] !et -!eblock - - -===== Numerical experiments and the covariance ===== -!bblock - Now that we have constructed an idealized mathematical framework, let us try to apply it to empirical observations. Examples of relevant physical phenomena may be spontaneous decays of nuclei, or a purely @@ -690,12 +588,7 @@ chain of values \{x_1, x_2,\dots\,x_k,\dots\}. \end{equation*} !et -!eblock - - -===== Numerical experiments and the covariance ===== -!bblock We will call these values our *measurements* and the entire set as our measured *sample*. The action of measuring all the elements of a sample @@ -708,12 +601,7 @@ stochastic variable whose PDF is $p_X^{\phantom X}(x)$. Instead of trying to determine the full distribution $p$ we are often only interested in finding the few lowest moments, like the mean $\mu_X^{\phantom X}$ and the variance $\sigma_X^{\phantom X}$. -!eblock - - -===== Numerical experiments and the covariance, actual situations ===== -!bblock In practical situations however, a sample is always of finite size. Let that size be $n$. The expectation value of a sample $\alpha$, the _sample mean_, is then defined as follows !bt @@ -728,12 +616,7 @@ The *sample variance* is: \end{equation*} !et with its square root being the *standard deviation of the sample*. -!eblock - - -===== Numerical experiments and the covariance, our observables ===== -!bblock You can think of the above observables as a set of quantities which define a given experiment. This experiment is then repeated several times, say $m$ times. The total average is then @@ -757,11 +640,6 @@ which we rewrite as label{eq:exptvariance} \end{equation} !et -!eblock - - -===== Numerical experiments and the covariance, the sample variance ===== -!bblock We define also the sample variance $\sigma^2$ of all $mn$ individual experiments as !bt @@ -778,11 +656,9 @@ may differ, in some cases significantly, from the similarly named exact values for the mean value $\mu_X$, the variance $\mathrm{Var}(X)$ and the covariance $\mathrm{Cov}(X,Y)$. -!eblock +=== Numerical experiments and the covariance, central limit theorem === -===== Numerical experiments and the covariance, central limit theorem ===== -!bblock The central limit theorem states that the PDF $\tilde{p}(z)$ of the average of $m$ random values corresponding to a PDF $p(x)$ @@ -800,11 +676,7 @@ standard deviation, given by !et In many cases the above estimate for the standard deviation, in particular if correlations are strong, may be too simplistic. We need therefore a more precise defintion of the error and the variance in our results. -!eblock - -===== Definition of Correlation Functions and Standard Deviation ===== -!bblock Our estimate of the true average $\mu_{X}$ is the sample mean $\langle X_m \rangle$ !bt @@ -828,15 +700,7 @@ and rewrite it as !et where the first term is the sample variance of all $mn$ experiments divided by $n$ and the last term is nothing but the covariance which arises when $k\ne l$. -!eblock - - - - - -===== Definition of Correlation Functions and Standard Deviation ===== -!bblock Our estimate of the true average $\mu_{X}$ is the sample mean $\langle X_m \rangle$ If the @@ -850,12 +714,8 @@ measurement $x$ we receive. The correlation term, though, has to be calculated at the end of the experiment since we need all the measurements to calculate the cross terms. Therefore, all measurements have to be stored throughout the experiment. -!eblock -===== Definition of Correlation Functions and Standard Deviation ===== -!bblock - Let us analyze the problem by splitting up the correlation term into partial sums of the form @@ -873,12 +733,7 @@ $f_d$ \frac{2}{n}\sum_{d=1}^{n-1} f_d \end{equation*} !et -!eblock - - -===== Definition of Correlation Functions and Standard Deviation ===== -!bblock The value of $f_d$ reflects the correlation between measurements separated by the distance $d$ in the samples. Notice that for $d=0$, $f$ is just the sample variance, $\sigma^2$. If we divide $f_d$ @@ -892,12 +747,8 @@ label{eq:autocorrelformal} !et which gives us a useful measure of the correlation pair correlation starting always at $1$ for $d=0$. -!eblock -===== Definition of Correlation Functions and Standard Deviation, sample variance ===== -!bblock - The sample variance of the $mn$ experiments can now be written in terms of the autocorrelation function @@ -923,13 +774,7 @@ label{eq:autocorrelation_time} # autocorrelation function. For a correlation free experiment, $\tau$ equals 1. -!eblock - - - -===== Definition of Correlation Functions and Standard Deviation ===== -!bblock From the point of view of Eq. (ref{eq:error_estimate_corr_time}) we can interpret a sequential correlation as an effective reduction of the number of measurements by @@ -947,11 +792,7 @@ autocorrelation time poses an efficiency problem if the set of measurements is very large. The solution to this problem is given by more practically oriented methods like the blocking technique. #add ref here to flybjerg -!eblock - - -===== Code to compute the Covariance matrix and the Covariance ===== !bc pycod # Importing various packages from math import exp, sqrt @@ -993,8 +834,7 @@ print(Eigvals) !ec -===== Random Numbers ===== -!bblock +=== Random Numbers === Uniform deviates are just random numbers that lie within a specified range (typically 0 to 1), with any one number in the range just as likely as any other. They @@ -1006,12 +846,6 @@ performing appropriate operations on one or more uniform deviates, as we will se in subsequent sections. So, a reliable source of random uniform deviates, the subject of this section, is an essential building block for any sort of stochastic modeling or Monte Carlo computer work. -!eblock - - - -===== Random Numbers, better name: pseudo random numbers ===== -!bblock A disclaimer is however appropriate. It should be fairly obvious that something as deterministic as a computer cannot generate purely random numbers. @@ -1026,12 +860,7 @@ numbers, hopefully abiding to the following criteria: * the period before the same sequence of random numbers is repeated is as large as possible and finally * the algorithm should be fast. -!eblock - - -===== Random number generator RNG ===== -!bblock The most common random number generators are based on so-called Linear congruential relations of the type @@ -1054,12 +883,8 @@ $M$ is called the period and it should be as large as possible $N_0$ is the starting value, or seed. The function $\mathrm{MOD}$ means the remainder, that is if we were to evaluate $(13)\mathrm{MOD}(9)$, the outcome is the remainder of the division $13/9$, namely $4$. -!eblock -===== Random number generator RNG and periodic outputs ===== -!bblock - The problem with such generators is that their outputs are periodic; they will start to repeat themselves with a period that is at most $M$. If however @@ -1084,11 +909,7 @@ example shows !et which still, with $N_0=2$, results in $11,38,11,38,11,38,\dots$, a period of just $2$. -!eblock - -===== Random number generator RNG and its period ===== -!bblock Typical periods for the random generators provided in the program library are of the order of $\sim 10^9$ or larger. Other random number generators which have become increasingly popular are so-called shift-register generators. @@ -1102,11 +923,7 @@ number is the sum of the $l-i$th and $l-j$th values with modulo $M$, N_l=(aN_{l-i}+cN_{l-j})\mathrm{MOD}(M). \end{equation*} !et -!eblock - -===== Random number generator RNG, other examples ===== -!bblock Such a generator again produces a sequence of pseudorandom numbers but this time with a period much larger than $M$. It is also possible to construct more elaborate algorithms by including @@ -1128,11 +945,7 @@ followed by \end{equation} !et which according to the authors has a period larger than $2^{94}$. -!eblock - -===== Random number generator RNG, other examples ===== -!bblock Instead of using modular addition, we could use the bitwise exclusive-OR ($\oplus$) operation so that @@ -1151,13 +964,8 @@ $1101$, or $2^3+2^2+2^0=13$. In Fortran90, the bitwise $\oplus$ operation is coded through the intrinsic function $\mathrm{IEOR}(m,n)$ where $m$ and $n$ are the input numbers, while in $C$ it is given by $m\wedge n$. -!eblock - -===== Random number generator RNG, RAN0 ===== -!bblock - We show here how the linear congruential algorithm can be implemented, namely !bt \begin{equation*} @@ -1188,13 +996,6 @@ and !et where the brackets denote integer division. In the code below the numbers $q$ and $r$ are chosen so that $r < q$. -!eblock - - - - -===== Random number generator RNG, RAN0 ===== -!bblock To see how this works we note first that !bt @@ -1206,12 +1007,7 @@ label{eq:rntrick1} since we can add or subtract any integer multiple of $M$ from $aN_{i-1}$. The last term $[N_{i-1}/q]M\mathrm{MOD}(M)$ is zero since the integer division $[N_{i-1}/q]$ just yields a constant which is multiplied with $M$. -!eblock - - -===== Random number generator RNG, RAN0 ===== -!bblock We can now rewrite Eq. (ref{eq:rntrick1}) as !bt @@ -1236,12 +1032,7 @@ yielding label{eq:rntrick4} \end{equation} !et -!eblock - - -===== Random number generator RNG, RAN0 ===== -!bblock The term $[N_{i-1}/q]r$ is always smaller or equal $N_{i-1}(r/q)$ and with $r < q$ we obtain always a number smaller than $N_{i-1}$, which is smaller than $M$. And since the number $N_{i-1}\mathrm{MOD} (q)$ is between zero and $q-1$ then @@ -1254,46 +1045,6 @@ the starting point for each generation of a random number. The period of $ran0$ is $\sim 2.1\times 10^{9}$. A special feature of this algorithm is that is should never be called with the initial seed set to $0$. -!eblock - - - -===== Random number generator RNG, RAN0 code ===== -!bblock - -!bc cppcod - /* - ** The function - ** ran0() - ** is an "Minimal" random number generator of Park and Miller - ** Set or reset the input value - ** idum to any integer value (except the unlikely value MASK) - ** to initialize the sequence; idum must not be altered between - ** calls for sucessive deviates in a sequence. - ** The function returns a uniform deviate between 0.0 and 1.0. - */ -double ran0(long &idum) -{ - const int a = 16807, m = 2147483647, q = 127773; - const int r = 2836, MASK = 123459876; - const double am = 1./m; - long k; - double ans; - idum ^= MASK; - k = (*idum)/q; - idum = a*(idum - k*q) - r*k; - // add m if negative difference - if(idum < 0) idum += m; - ans=am*(idum); - idum ^= MASK; - return ans; -} // End: function ran0() -!ec -!eblock - - -===== Properties of Selected Random Number Generators ===== -!bblock As mentioned previously, the underlying PDF for the generation of random numbers is the uniform distribution, meaning that the @@ -1308,11 +1059,7 @@ deviations. Two additional measures are the standard deviation $\sigma$ and the mean $\mu=\langle x\rangle$. -!eblock - -===== Properties of Selected Random Number Generators ===== -!bblock For the uniform distribution, the mean value $\mu$ is then !bt @@ -1327,11 +1074,7 @@ while the standard deviation is \sigma=\sqrt{\langle x^2\rangle-\mu^2}=\frac{1}{\sqrt{12}}=0.2886. \end{equation*} !et -!eblock - -===== Properties of Selected Random Number Generators ===== -!bblock The various random number generators produce results which agree rather well with these limiting values. @@ -1352,11 +1095,7 @@ these limiting values. | $\sigma$ | 0.2882 | 0.2892 | 0.2861 | 0.2915 | |------------------------------------------------------| -!eblock - -===== Simple demonstration of RNGs using python ===== -!bblock The following simple Python code plots the distribution of the produced random numbers using the linear congruential RNG employed by Python. The trend displayed in the previous table is seen rather clearly. !bc pyscpro #!/usr/bin/env python @@ -1382,12 +1121,7 @@ plt.axis([0, 1, 0, 1100]) plt.grid(True) plt.show() !ec -!eblock - - -===== Properties of Selected Random Number Generators ===== -!bblock Since our random numbers, which are typically generated via a linear congruential algorithm, are never fully independent, we can then define an important test which measures the degree of correlation, namely the so-called @@ -1413,11 +1147,8 @@ numbers are not independent. The independence of the random numbers is crucial in the evaluation of other expectation values. If they are not independent, our assumption for approximating $\sigma_N$ is no longer valid. -!eblock - - -===== Autocorrelation function ===== +=== Autocorrelation function === This program computes the autocorrelation function as discussed in the equation on the previous slide for random numbers generated with the normal distribution $N(0,1)$. !bc pycod # Importing various packages @@ -1457,408 +1188,3 @@ For the remaining values we notice that there are still non-zero values for the - - - - - - - - - - - - -===== Correlation function and which random number generators should I use ===== -!bblock -The program here computes the correlation function for one of the standard functions included with the c++ compiler. -!bc cppcod -// This function computes the autocorrelation function for -// the standard c++ random number generator - -#include -#include -#include -#include -using namespace std; -// output file as global variable -ofstream ofile; - -// Main function begins here -int main(int argc, char* argv[]) -{ - int n; - char *outfilename; - - cin >> n; - double MCint = 0.; double MCintsqr2=0.; - double invers_period = 1./RAND_MAX; // initialise the random number generator - srand(time(NULL)); // This produces the so-called seed in MC jargon - // Compute the variance and the mean value of the uniform distribution - // Compute also the specific values x for each cycle in order to be able to - // the covariance and the correlation function - // Read in output file, abort if there are too few command-line arguments - if( argc <= 2 ){ - cout << "Bad Usage: " << argv[0] << - " read also output file and number of cycles on same line" << endl; - exit(1); - } - else{ - outfilename=argv[1]; - } - ofile.open(outfilename); - // Get the number of Monte-Carlo samples - n = atoi(argv[2]); - double *X; - X = new double[n]; - for (int i = 0; i < n; i++){ - double x = double(rand())*invers_period; - X[i] = x; - MCint += x; - MCintsqr2 += x*x; - } - double Mean = MCint/((double) n ); - MCintsqr2 = MCintsqr2/((double) n ); - double STDev = sqrt(MCintsqr2-Mean*Mean); - double Variance = MCintsqr2-Mean*Mean; -// Write mean value and standard deviation - cout << " Standard deviation= " << STDev << " Integral = " << Mean << endl; - - // Now we compute the autocorrelation function - double *autocor; autocor = new double[n]; - for (int j = 0; j < n; j++){ - double sum = 0.0; - for (int k = 0; k < (n-j); k++){ - sum += (X[k]-Mean)*(X[k+j]-Mean); - } - autocor[j] = sum/Variance/((double) n ); - ofile << setiosflags(ios::showpoint | ios::uppercase); - ofile << setw(15) << setprecision(8) << j; - ofile << setw(15) << setprecision(8) << autocor[j] << endl; - } - ofile.close(); // close output file - return 0; -} // end of main program -!ec -!eblock - - - - -===== Which RNG should I use? ===== -!bblock -* C++ has a class called _random_. The "random class":"http://www.cplusplus.com/reference/random/" contains a large selection of RNGs and is highly recommended. Some of these RNGs have very large periods making it thereby very safe to use these RNGs in case one is performing large calculations. In particular, the "Mersenne twister random number engine":"http://www.cplusplus.com/reference/random/mersenne_twister_engine/" has a period of $2^{19937}$. -* Add RNGs in Python - -!eblock - - - -===== How to use the Mersenne generator ===== -!bblock -The following part of a c++ code (from project 4) sets up the uniform distribution for $x\in [0,1]$. -!bc cppcod -/* - -// You need this -#include - -// Initialize the seed and call the Mersienne algo -std::random_device rd; -std::mt19937_64 gen(rd()); -// Set up the uniform distribution for x \in [[0, 1] -std::uniform_real_distribution RandomNumberGenerator(0.0,1.0); - -// Now use the RNG -int ix = (int) (RandomNumberGenerator(gen)*NSpins); -!ec -!eblock - - - - - -===== Why blocking? ===== -!bblock Statistical analysis - * Monte Carlo simulations can be treated as *computer experiments* - * The results can be analysed with the same statistical tools as we would use analysing experimental data. - * As in all experiments, we are looking for expectation values and an estimate of how accurate they are, i.e., possible sources for errors. - -A very good article which explains blocking is H. Flyvbjerg and H. G. Petersen, *Error estimates on averages of correlated data*, "Journal of Chemical Physics 91, 461-466 (1989)":"http://scitation.aip.org/content/aip/journal/jcp/91/1/10.1063/1.457480". - -!eblock - - - - -===== Why blocking? ===== -!bblock Statistical analysis - * As in other experiments, Monte Carlo experiments have two classes of errors: - * Statistical errors - * Systematical errors - * Statistical errors can be estimated using standard tools from statistics - * Systematical errors are method specific and must be treated differently from case to case. (In VMC a common source is the step length or time step in importance sampling) -!eblock - - - -===== Code to demonstrate the calculation of the autocorrelation function ===== -The following code computes the autocorrelation function, the covariance and the standard deviation -for standard RNG. -The "following file":"https://github.com/CompPhysics/ComputationalPhysics2/tree/gh-pages/doc/Programs/LecturePrograms/programs/Blocking/autocorrelation.cpp" gives the code. -!bc cppcod -// This function computes the autocorrelation function for -// the Mersenne random number generator with a uniform distribution -#include -#include -#include -#include -#include -#include -#include -#include -using namespace std; -using namespace arma; -// output file -ofstream ofile; - -// Main function begins here -int main(int argc, char* argv[]) -{ - int MonteCarloCycles; - string filename; - if (argc > 1) { - filename=argv[1]; - MonteCarloCycles = atoi(argv[2]); - string fileout = filename; - string argument = to_string(MonteCarloCycles); - fileout.append(argument); - ofile.open(fileout); - } - - // Compute the variance and the mean value of the uniform distribution - // Compute also the specific values x for each cycle in order to be able to - // compute the covariance and the correlation function - - vec X = zeros(MonteCarloCycles); - double MCint = 0.; double MCintsqr2=0.; - std::random_device rd; - std::mt19937_64 gen(rd()); - // Set up the uniform distribution for x \in [[0, 1] - std::uniform_real_distribution RandomNumberGenerator(0.0,1.0); - for (int i = 0; i < MonteCarloCycles; i++){ - double x = RandomNumberGenerator(gen); - X(i) = x; - MCint += x; - MCintsqr2 += x*x; - } - double Mean = MCint/((double) MonteCarloCycles ); - MCintsqr2 = MCintsqr2/((double) MonteCarloCycles ); - double STDev = sqrt(MCintsqr2-Mean*Mean); - double Variance = MCintsqr2-Mean*Mean; - // Write mean value and variance - cout << " Sample variance= " << Variance << " Mean value = " << Mean << endl; - // Now we compute the autocorrelation function - vec autocorrelation = zeros(MonteCarloCycles); - for (int j = 0; j < MonteCarloCycles; j++){ - double sum = 0.0; - for (int k = 0; k < (MonteCarloCycles-j); k++){ - sum += (X(k)-Mean)*(X(k+j)-Mean); - } - autocorrelation(j) = sum/Variance/((double) MonteCarloCycles ); - ofile << setiosflags(ios::showpoint | ios::uppercase); - ofile << setw(15) << setprecision(8) << j; - ofile << setw(15) << setprecision(8) << autocorrelation(j) << endl; - } - // Now compute the exact covariance using the autocorrelation function - double Covariance = 0.0; - for (int j = 0; j < MonteCarloCycles; j++){ - Covariance += autocorrelation(j); - } - Covariance *= 2.0/((double) MonteCarloCycles); - // Compute now the total variance, including the covariance, and obtain the standard deviation - double TotalVariance = (Variance/((double) MonteCarloCycles ))+Covariance; - cout << "Covariance =" << Covariance << "Totalvariance= " << TotalVariance << "Sample Variance/n= " << (Variance/((double) MonteCarloCycles )) << endl; - cout << " STD from sample variance= " << sqrt(Variance/((double) MonteCarloCycles )) << " STD with covariance = " << sqrt(TotalVariance) << endl; - - ofile.close(); // close output file - return 0; -} // end of main program - - -!ec - - - -===== What is blocking? ===== -!bblock Blocking - * Say that we have a set of samples from a Monte Carlo experiment - * Assuming (wrongly) that our samples are uncorrelated our best estimate of the standard deviation of the mean $\langle \mathbf{M}\rangle$ is given by -!bt -\[ -\sigma=\sqrt{\frac{1}{n}\left(\langle \mathbf{M}^2\rangle-\langle \mathbf{M}\rangle^2\right)} -\] -!et - * If the samples are correlated we can rewrite our results to show that -!bt -\[ -\sigma=\sqrt{\frac{1+2\tau/\Delta t}{n}\left(\langle \mathbf{M}^2\rangle-\langle \mathbf{M}\rangle^2\right)} -\] -!et - where $\tau$ is the correlation time (the time between a sample and the next uncorrelated sample) and $\Delta t$ is time between each sample -!eblock - - -===== What is blocking? ===== -!bblock Blocking - * If $\Delta t\gg\tau$ our first estimate of $\sigma$ still holds - * Much more common that $\Delta t<\tau$ - * In the method of data blocking we divide the sequence of samples into blocks - * We then take the mean $\langle \mathbf{M}_i\rangle$ of block $i=1\ldots n_{blocks}$ to calculate the total mean and variance - * The size of each block must be so large that sample $j$ of block $i$ is not correlated with sample $j$ of block $i+1$ - * The correlation time $\tau$ would be a good choice -!eblock - - -===== What is blocking? ===== -!bblock Blocking - * Problem: We don't know $\tau$ or it is too expensive to compute - * Solution: Make a plot of std. dev. as a function of blocksize - * The estimate of std. dev. of correlated data is too low $\to$ the error will increase with increasing block size until the blocks are uncorrelated, where we reach a plateau - * When the std. dev. stops increasing the blocks are uncorrelated -!eblock - - -===== Implementation ===== -!bblock - * Do a Monte Carlo simulation, storing all samples to file - * Do the statistical analysis on this file, independently of your Monte Carlo program - * Read the file into an array - * Loop over various block sizes - * For each block size $n_b$, loop over the array in steps of $n_b$ taking the mean of elements $i n_b,\ldots,(i+1) n_b$ - * Take the mean and variance of the resulting array - * Write the results for each block size to file for later - analysis -!eblock - - - - - - -===== Actual implementation with code, main function ===== -When the file gets large, it can be useful to write your data in binary mode instead of ascii characters. -The "following python file":"https://github.com/CompPhysics/MachineLearning/blob/master/doc/Programs/Sampling/analysis.py" reads data from file with the output from every Monte Carlo cycle. -!bc pycod -# Blocking - @timeFunction - def blocking(self, blockSizeMax = 500): - blockSizeMin = 1 - - self.blockSizes = [] - self.meanVec = [] - self.varVec = [] - - for i in range(blockSizeMin, blockSizeMax): - if(len(self.data) % i != 0): - pass#continue - blockSize = i - meanTempVec = [] - varTempVec = [] - startPoint = 0 - endPoint = blockSize - - while endPoint <= len(self.data): - meanTempVec.append(np.average(self.data[startPoint:endPoint])) - startPoint = endPoint - endPoint += blockSize - mean, var = np.average(meanTempVec), np.var(meanTempVec)/len(meanTempVec) - self.meanVec.append(mean) - self.varVec.append(var) - self.blockSizes.append(blockSize) - - self.blockingAvg = np.average(self.meanVec[-200:]) - self.blockingVar = (np.average(self.varVec[-200:])) - self.blockingStd = np.sqrt(self.blockingVar) - -!ec - - - - - -===== The Bootstrap method ===== - -The Bootstrap resampling method is also very popular. It is very simple: - -o Start with your sample of measurements and compute the sample variance and the mean values -o Then start again but pick in a random way the numbers in the sample and recalculate the mean and the sample variance. -o Repeat this $K$ times. - -It can be shown, see the article by "Efron":"https://projecteuclid.org/download/pdf_1/euclid.aos/1176344552" -that it produces the correct standard deviation. - -This method is very useful for small ensembles of data points. - - -===== Bootstrapping ===== -Given a set of $N$ data, assume that we are interested in some -observable $\theta$ which may be estimated from that set. This observable can also be for example the result of a fit based on all $N$ raw data. -Let us call the value of the observable obtained from the original -data set $\hat{\theta}$. One recreates from the sample repeatedly -other samples by choosing randomly $N$ data out of the original set. -This costs essentially nothing, since we just recycle the original data set for the building of new sets. - - -===== Bootstrapping, recipe ===== -Let us assume we have done this $K$ times and thus have $K$ sets of $N$ -data values each. -Of course some values will enter more than once in the new sets. For each of these sets one computes the observable $\theta$ resulting in values $\theta_k$ with $k = 1,...,K$. Then one determines -!bt -\[ -\tilde{\theta} = \frac{1}{K} \sum_{k=1}^K \theta_k, -\] -!et -and -!bt -\[ -sigma^2_{\tilde{\theta}} = \frac{1}{K} \sum_{k=1}^K \left(\theta_k-\tilde{\theta}\right)^2. -\] -!et - -These are estimators for $\angle\theta\rangle$ and its variance. They are not unbiased and therefore -$\tilde{\theta}\neq\hat{\theta}$ for finite K. - -The difference is called bias and gives an idea on how far away the result may be from -the true $\angle\theta\rangle$. As final result for the observable one quotes $\angle\theta\rangle = \tilde{\theta} \pm \sigma_{\tilde{\theta}}$ . - - - -===== Bootstrapping, "code":"https://github.com/CompPhysics/MachineLearning/blob/master/doc/Programs/Sampling/analysis.py" ===== -!bc -# Bootstrap - @timeFunction - def bootstrap(self, nBoots = 1000): - bootVec = np.zeros(nBoots) - for k in range(0,nBoots): - bootVec[k] = np.average(np.random.choice(self.data, len(self.data))) - self.bootAvg = np.average(bootVec) - self.bootVar = np.var(bootVec) - self.bootStd = np.std(bootVec) -!ec - - -===== Jackknife, "code":"https://github.com/CompPhysics/MachineLearning/blob/master/doc/Programs/Sampling/analysis.py" ===== -!bc -# Jackknife - @timeFunction - def jackknife(self): - jackknVec = np.zeros(len(self.data)) - for k in range(0,len(self.data)): - jackknVec[k] = np.average(np.delete(self.data, k)) - self.jackknAvg = self.avg - (len(self.data) - 1) * (np.average(jackknVec) - self.avg) - self.jackknVar = float(len(self.data) - 1) * np.var(jackknVec) - self.jackknStd = np.sqrt(self.jackknVar) -!ec - - diff --git a/doc/LectureNotes/statistics.ipynb b/doc/LectureNotes/statistics.ipynb index 8690ffe7a..4ea8e3730 100644 --- a/doc/LectureNotes/statistics.ipynb +++ b/doc/LectureNotes/statistics.ipynb @@ -2,18 +2,43 @@ "cells": [ { "cell_type": "markdown", - "metadata": {}, + "id": "1de4abfb", + "metadata": { + "editable": true + }, + "source": [ + "" + ] + }, + { + "cell_type": "markdown", + "id": "9268be0a", + "metadata": { + "editable": true + }, + "source": [ + "# Elements of Probability Theory and Statistical Data Analysis" + ] + }, + { + "cell_type": "markdown", + "id": "b24d433f", + "metadata": { + "editable": true + }, "source": [ - "# Elements of Probability Theory and Statistical Data Analysis\n", - "\n", - "\n", "## Domains and probabilities\n", + "\n", "Consider the following simple example, namely the tossing of two dice, resulting in the following possible values" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "9fa7c59b", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\{2,3,4,5,6,7,8,9,10,11,12\\}.\n", @@ -22,7 +47,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "d1c9912c", + "metadata": { + "editable": true + }, "source": [ "These values are called the *domain*. \n", "To this domain we have the corresponding *probabilities*" @@ -30,7 +58,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "6626ea89", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\{1/36,2/36/,3/36,4/36,5/36,6/36,5/36,4/36,3/36,2/36,1/36\\}.\n", @@ -39,9 +70,11 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "65c54c5b", + "metadata": { + "editable": true + }, "source": [ - "## Tossing the dice\n", "The numbers in the domain are the outcomes of the physical process of tossing say two dice.\n", "We cannot tell beforehand whether the outcome is 3 or 5 or any other number in this domain.\n", "This defines the randomness of the outcome, or unexpectedness or any other synonimous word which\n", @@ -55,7 +88,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "84e29b68", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\{2,3,4,5,6,7,8,9,10,11,12\\},\n", @@ -64,14 +100,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "8ae71934", + "metadata": { + "editable": true + }, "source": [ "appear in a random order. After 11 throws the results may look like" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "c3901951", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\{10,8,6,3,6,9,11,8,12,4,5\\}.\n", @@ -80,16 +122,23 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "9c659ce0", + "metadata": { + "editable": true + }, "source": [ - "## Stochastic variables\n", + "**Random variables are characterized by a domain which contains all possible values that the random value may take. This domain has a corresponding probability distribution function(PDF)**." + ] + }, + { + "cell_type": "markdown", + "id": "eb18a204", + "metadata": { + "editable": true + }, + "source": [ + "### Stochastic variables and the main concepts, the discrete case\n", "\n", - "**Random variables are characterized by a domain which contains all possible values that the random value may take. This domain has a corresponding probability distribution function(PDF)**.\n", - "\n", - "\n", - "\n", - "\n", - "## Stochastic variables and the main concepts, the discrete case\n", "There are two main concepts associated with a stochastic variable. The\n", "*domain* is the set $\\mathbb D = \\{x\\}$ of all accessible values\n", "the variable can assume, so that $X \\in \\mathbb D$. An example of a\n", @@ -104,7 +153,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "2589c0ee", + "metadata": { + "editable": true + }, "source": [ "$$\n", "p(x) = \\mathrm{Prob}(X=x).\n", @@ -113,9 +165,11 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "ef71f105", + "metadata": { + "editable": true + }, "source": [ - "## Stochastic variables and the main concepts, the continuous case\n", "In the continuous case, the PDF does not directly depict the\n", "actual probability. Instead we define the probability for the\n", "stochastic variable to assume any value on an infinitesimal interval\n", @@ -127,7 +181,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "9c5efaee", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\mathrm{Prob}(a\\leq X\\leq b) = \\int_a^b p(x)dx.\n", @@ -136,16 +193,15 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "cbf1d43c", + "metadata": { + "editable": true + }, "source": [ "Qualitatively speaking, a stochastic variable represents the values of\n", "numbers chosen as if by chance from some specified PDF so that the\n", "selection of a large set of these numbers reproduces this PDF.\n", "\n", - "\n", - "\n", - "\n", - "## The cumulative probability\n", "Of interest to us is the *cumulative probability\n", "distribution function* (**CDF**), $P(x)$, which is just the probability\n", "for a stochastic variable $X$ to assume any value less than $x$" @@ -153,7 +209,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "be829d81", + "metadata": { + "editable": true + }, "source": [ "$$\n", "P(x)=\\mathrm{Prob(}X\\leq x\\mathrm{)} =\n", @@ -163,14 +222,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "1f193798", + "metadata": { + "editable": true + }, "source": [ "The relation between a CDF and its corresponding PDF is then" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "3d29d961", + "metadata": { + "editable": true + }, "source": [ "$$\n", "p(x) = \\frac{d}{dx}P(x).\n", @@ -179,9 +244,12 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "fc5b2c18", + "metadata": { + "editable": true + }, "source": [ - "## Properties of PDFs\n", + "### Properties of PDFs\n", "\n", "There are two properties that all PDFs must satisfy. The first one is\n", "positivity (assuming that the PDF is normalized)" @@ -189,7 +257,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "2a465c1b", + "metadata": { + "editable": true + }, "source": [ "$$\n", "0 \\leq p(x) \\leq 1.\n", @@ -198,7 +269,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "d69e520a", + "metadata": { + "editable": true + }, "source": [ "Naturally, it would be nonsensical for any of the values of the domain\n", "to occur with a probability greater than $1$ or less than $0$. Also,\n", @@ -209,7 +283,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "2208b590", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\begin{align*}\n", @@ -221,16 +298,21 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "f3d91dca", + "metadata": { + "editable": true + }, "source": [ - "## Important distributions, the uniform distribution\n", "The first one\n", "is the most basic PDF; namely the uniform distribution" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "0f431dd2", + "metadata": { + "editable": true + }, "source": [ "\n", "
\n", @@ -245,14 +327,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "155c6cf7", + "metadata": { + "editable": true + }, "source": [ "For $a=0$ and $b=1$ we have" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "42993dcc", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\begin{array}{ll}\n", @@ -263,20 +351,22 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "749d5c23", + "metadata": { + "editable": true + }, "source": [ - "The latter distribution is used to generate random numbers. For other PDFs, one needs normally a mapping from this distribution to say for example the exponential distribution.\n", + "The latter distribution is used to generate random numbers. For other PDFs, one needs normally a mapping from this distribution to say for example the exponential distribution. \n", "\n", - "\n", - "\n", - "\n", - "## Gaussian distribution\n", "The second one is the Gaussian Distribution" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "6e2110dc", + "metadata": { + "editable": true + }, "source": [ "$$\n", "p(x) = \\frac{1}{\\sigma\\sqrt{2\\pi}} \\exp{(-\\frac{(x-\\mu)^2}{2\\sigma^2})},\n", @@ -285,14 +375,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "d00fdbe1", + "metadata": { + "editable": true + }, "source": [ "with mean value $\\mu$ and standard deviation $\\sigma$. If $\\mu=0$ and $\\sigma=1$, it is normally called the **standard normal distribution**" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "23c37b45", + "metadata": { + "editable": true + }, "source": [ "$$\n", "p(x) = \\frac{1}{\\sqrt{2\\pi}} \\exp{(-\\frac{x^2}{2})},\n", @@ -301,14 +397,18 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "07558d2c", + "metadata": { + "editable": true + }, "source": [ "The following simple Python code plots the above distribution for different values of $\\mu$ and $\\sigma$." ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 1, + "id": "b99f544d", "metadata": { "collapsed": false, "editable": true @@ -358,15 +458,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "617597ef", + "metadata": { + "editable": true + }, "source": [ - "## Exponential distribution\n", "Another important distribution in science is the exponential distribution" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "18be0515", + "metadata": { + "editable": true + }, "source": [ "$$\n", "p(x) = \\alpha\\exp{-(\\alpha x)}.\n", @@ -375,9 +480,13 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "cafcff78", + "metadata": { + "editable": true + }, "source": [ - "## Expectation values\n", + "### Expectation values\n", + "\n", "Let $h(x)$ be an arbitrary continuous function on the domain of the stochastic\n", "variable $X$ whose PDF is $p(x)$. We define the *expectation value*\n", "of $h$ with respect to $p$ as follows" @@ -385,7 +494,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "f5c68a26", + "metadata": { + "editable": true + }, "source": [ "\n", "
\n", @@ -400,7 +512,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "291e3ff7", + "metadata": { + "editable": true + }, "source": [ "Whenever the PDF is known implicitly, like in this case, we will drop\n", "the index $X$ for clarity. \n", @@ -411,7 +526,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "294080d7", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\langle x^n \\rangle \\equiv \\int\\! x^n p(x)\\,dx\n", @@ -420,9 +538,11 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "9d493962", + "metadata": { + "editable": true + }, "source": [ - "## Stochastic variables and the main concepts, mean values\n", "The zero-th moment $\\langle 1\\rangle$ is just the normalization condition of\n", "$p$. The first moment, $\\langle x\\rangle$, is called the *mean* of $p$\n", "and often denoted by the letter $\\mu$" @@ -430,7 +550,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "6ca38798", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\langle x\\rangle = \\mu \\equiv \\int x p(x)dx,\n", @@ -439,14 +562,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "9a779b37", + "metadata": { + "editable": true + }, "source": [ "for a continuous distribution and" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "9fc21016", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\langle x\\rangle = \\mu \\equiv \\sum_{i=1}^N x_i p(x_i),\n", @@ -455,23 +584,24 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "a146b327", + "metadata": { + "editable": true + }, "source": [ "for a discrete distribution. \n", "Qualitatively it represents the centroid or the average value of the\n", "PDF and is therefore simply called the expectation value of $p(x)$.\n", "\n", - "\n", - "\n", - "\n", - "## Stochastic variables and the main concepts, central moments, the variance\n", - "\n", "A special version of the moments is the set of *central moments*, the n-th central moment defined as" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "0b282f14", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\langle (x-\\langle x\\rangle )^n\\rangle \\equiv \\int\\! (x-\\langle x\\rangle)^n p(x)\\,dx\n", @@ -480,7 +610,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "512e6e16", + "metadata": { + "editable": true + }, "source": [ "The zero-th and first central moments are both trivial, equal $1$ and\n", "$0$, respectively. But the second central moment, known as the\n", @@ -490,7 +623,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "e244a343", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\begin{align*}\n", @@ -505,26 +641,31 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "c0d8e272", + "metadata": { + "editable": true + }, "source": [ "The square root of the variance, $\\sigma =\\sqrt{\\langle (x-\\langle x\\rangle)^2\\rangle}$ is called the \n", "**standard deviation** of $p$. It is the RMS (root-mean-square)\n", "value of the deviation of the PDF from its mean value, interpreted\n", - "qualitatively as the \"spread\" of $p$ around its mean.\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "## Probability Distribution Functions\n", + "qualitatively as the \"spread\" of $p$ around its mean." + ] + }, + { + "cell_type": "markdown", + "id": "12fb667e", + "metadata": { + "editable": true + }, + "source": [ + "### Probability Distribution Functions\n", "\n", "The following table collects properties of probability distribution functions.\n", "In our notation we reserve the label $p(x)$ for the probability of a certain event,\n", "while $P(x)$ is the cumulative probability. \n", "\n", - "\n", - "\n", + "
\n", "\n", "\n", "\n", @@ -539,17 +680,15 @@ "\n", "
Discrete PDF Continuous PDF
\n", "\n", - "\n", - "\n", - "\n", - "\n", - "## Probability Distribution Functions\n", "With a PDF we can compute expectation values of selected quantities such as" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "7d318e93", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\langle x^k\\rangle=\\sum_{i=1}^{N}x_i^kp(x_i),\n", @@ -558,14 +697,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "6ef87b82", + "metadata": { + "editable": true + }, "source": [ "if we have a discrete PDF or" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "d11f1bdb", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\langle x^k\\rangle=\\int_a^b x^kp(x)dx,\n", @@ -574,15 +719,13 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "2a8abb3d", + "metadata": { + "editable": true + }, "source": [ "in the case of a continuous PDF. We have already defined the mean value $\\mu$\n", - "and the variance $\\sigma^2$.\n", - "\n", - "\n", - "\n", - "\n", - "## The three famous Probability Distribution Functions\n", + "and the variance $\\sigma^2$. \n", "\n", "There are at least three PDFs which one may encounter. These are the\n", "\n", @@ -591,7 +734,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "6c14f838", + "metadata": { + "editable": true + }, "source": [ "$$\n", "p(x)=\\frac{1}{b-a}\\Theta(x-a)\\Theta(b-x),\n", @@ -600,7 +746,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "62149f95", + "metadata": { + "editable": true + }, "source": [ "yielding probabilities different from zero in the interval $[a,b]$.\n", "\n", @@ -609,7 +758,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "f8f51c0a", + "metadata": { + "editable": true + }, "source": [ "$$\n", "p(x)=\\alpha \\exp{(-\\alpha x)},\n", @@ -618,14 +770,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "9a038bf3", + "metadata": { + "editable": true + }, "source": [ "yielding probabilities different from zero in the interval $[0,\\infty)$ and with mean value" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "bdaf914a", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\mu = \\int_0^{\\infty}xp(x)dx=\\int_0^{\\infty}x\\alpha \\exp{(-\\alpha x)}dx=\\frac{1}{\\alpha},\n", @@ -634,14 +792,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "74226a02", + "metadata": { + "editable": true + }, "source": [ "with variance" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "32215b82", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\sigma^2=\\int_0^{\\infty}x^2p(x)dx-\\mu^2 = \\frac{1}{\\alpha^2}.\n", @@ -650,15 +814,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "688f69a2", + "metadata": { + "editable": true + }, "source": [ - "## Probability Distribution Functions, the normal distribution\n", "Finally, we have the so-called univariate normal distribution, or just the **normal distribution**" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "082e6778", + "metadata": { + "editable": true + }, "source": [ "$$\n", "p(x)=\\frac{1}{b\\sqrt{2\\pi}}\\exp{\\left(-\\frac{(x-a)^2}{2b^2}\\right)}\n", @@ -667,7 +836,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "ba9c8bd4", + "metadata": { + "editable": true + }, "source": [ "with probabilities different from zero in the interval $(-\\infty,\\infty)$.\n", "The integral $\\int_{-\\infty}^{\\infty}\\exp{\\left(-(x^2\\right)}dx$ appears in many calculations, its value\n", @@ -677,7 +849,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "f9540188", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\mu = \\int_0^{\\infty}xp(x)dx=\\frac{1}{b\\sqrt{2\\pi}}\\int_{-\\infty}^{\\infty}x \\exp{\\left(-\\frac{(x-a)^2}{2b^2}\\right)}dx,\n", @@ -686,14 +861,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "0507fa0a", + "metadata": { + "editable": true + }, "source": [ "which becomes with a suitable change of variables" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "74ee9f1a", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\mu =\\frac{1}{b\\sqrt{2\\pi}}\\int_{-\\infty}^{\\infty}b\\sqrt{2}(a+b\\sqrt{2}y)\\exp{-y^2}dy=a.\n", @@ -702,15 +883,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "0cf42992", + "metadata": { + "editable": true + }, "source": [ - "## Probability Distribution Functions, the normal distribution\n", "Similarly, the variance becomes" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "e3554ca3", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\sigma^2 = \\frac{1}{b\\sqrt{2\\pi}}\\int_{-\\infty}^{\\infty}(x-\\mu)^2 \\exp{\\left(-\\frac{(x-a)^2}{2b^2}\\right)}dx,\n", @@ -719,14 +905,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "728ba052", + "metadata": { + "editable": true + }, "source": [ "and inserting the mean value and performing a variable change we obtain" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "60276744", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\sigma^2 = \\frac{1}{b\\sqrt{2\\pi}}\\int_{-\\infty}^{\\infty}b\\sqrt{2}(b\\sqrt{2}y)^2\\exp{\\left(-y^2\\right)}dy=\n", @@ -736,7 +928,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "c5b45c52", + "metadata": { + "editable": true + }, "source": [ "and performing a final integration by parts we obtain the well-known result $\\sigma^2=b^2$.\n", "It is useful to introduce the standard normal distribution as well, defined by $\\mu=a=0$, viz. a distribution\n", @@ -745,7 +940,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "a005fdfe", + "metadata": { + "editable": true + }, "source": [ "\n", "
\n", @@ -760,10 +958,11 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "12c13ae4", + "metadata": { + "editable": true + }, "source": [ - "## Probability Distribution Functions, the cumulative distribution\n", - "\n", "The exponential and uniform distributions have simple cumulative functions,\n", "whereas the normal distribution does not, being proportional to the so-called\n", "error function $erf(x)$, given by" @@ -771,7 +970,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "68e56af7", + "metadata": { + "editable": true + }, "source": [ "$$\n", "P(x) = \\frac{1}{\\sqrt{2\\pi}}\\int_{-\\infty}^x\\exp{\\left(-\\frac{t^2}{2}\\right)}dt,\n", @@ -780,22 +982,22 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "99071464", + "metadata": { + "editable": true + }, "source": [ - "which is difficult to evaluate in a quick way.\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "## Probability Distribution Functions, other important distribution\n", + "which is difficult to evaluate in a quick way. \n", "\n", "Some other PDFs which one encounters often in the natural sciences are the binomial distribution" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "08b3b2e3", + "metadata": { + "editable": true + }, "source": [ "$$\n", "p(x) = \\left(\\begin{array}{c} n \\\\ x\\end{array}\\right)y^x(1-y)^{n-x} \\hspace{0.5cm}x=0,1,\\dots,n,\n", @@ -804,7 +1006,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "57d2b4a7", + "metadata": { + "editable": true + }, "source": [ "where $y$ is the probability for a specific event, such as the tossing of a coin or moving left or right\n", "in case of a random walker. Note that $x$ is a discrete stochastic variable. \n", @@ -817,18 +1022,16 @@ "\n", " * The probability for every outcome in a single trial has the same value, for example the outcome of tossing (either heads or tails) a coin is always $1/2$.\n", "\n", - "\n", - "\n", - "\n", - "## Probability Distribution Functions, the binomial distribution\n", - "\n", "In order to compute the mean and variance we need to recall Newton's binomial\n", "formula" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "4ce5e39f", + "metadata": { + "editable": true + }, "source": [ "$$\n", "(a+b)^m=\\sum_{n=0}^m \\left(\\begin{array}{c} m \\\\ n\\end{array}\\right)a^nb^{m-n},\n", @@ -837,14 +1040,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "4b87bcf7", + "metadata": { + "editable": true + }, "source": [ "which can be used to show that" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "29e93603", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\sum_{x=0}^n\\left(\\begin{array}{c} n \\\\ x\\end{array}\\right)y^x(1-y)^{n-x} = (y+1-y)^n = 1,\n", @@ -853,7 +1062,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "524d4e2f", + "metadata": { + "editable": true + }, "source": [ "the PDF is normalized to one. \n", "The mean value is" @@ -861,7 +1073,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "d129841d", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\mu = \\sum_{x=0}^n x\\left(\\begin{array}{c} n \\\\ x\\end{array}\\right)y^x(1-y)^{n-x} =\n", @@ -871,14 +1086,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "f68c25df", + "metadata": { + "editable": true + }, "source": [ "resulting in" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "f19452aa", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\mu = \n", @@ -888,14 +1109,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "c75f2dc5", + "metadata": { + "editable": true + }, "source": [ "which we rewrite as" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "c7b760bf", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\mu=ny\\sum_{\\nu=0}^n\\left(\\begin{array}{c} n-1 \\\\ \\nu\\end{array}\\right)y^{\\nu}(1-y)^{n-1-\\nu} =ny(y+1-y)^{n-1}=ny.\n", @@ -904,20 +1131,23 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "6fc3e294", + "metadata": { + "editable": true + }, "source": [ "The variance is slightly trickier to get. It reads $\\sigma^2=ny(1-y)$. \n", "\n", - "\n", - "## Probability Distribution Functions, Poisson's distribution\n", - "\n", "Another important distribution with discrete stochastic variables $x$ is \n", "the Poisson model, which resembles the exponential distribution and reads" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "c67cc7c9", + "metadata": { + "editable": true + }, "source": [ "$$\n", "p(x) = \\frac{\\lambda^x}{x!} e^{-\\lambda} \\hspace{0.5cm}x=0,1,\\dots,;\\lambda > 0.\n", @@ -926,14 +1156,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "3988d52a", + "metadata": { + "editable": true + }, "source": [ "In this case both the mean value and the variance are easier to calculate," ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "9b3e4562", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\mu = \\sum_{x=0}^{\\infty} x \\frac{\\lambda^x}{x!} e^{-\\lambda} = \\lambda e^{-\\lambda}\\sum_{x=1}^{\\infty}\n", @@ -943,16 +1179,13 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "88138c21", + "metadata": { + "editable": true + }, "source": [ - "and the variance is $\\sigma^2=\\lambda$.\n", + "and the variance is $\\sigma^2=\\lambda$. \n", "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "## Probability Distribution Functions, Poisson's distribution\n", "An example of applications of the Poisson distribution could be the counting\n", "of the number of $\\alpha$-particles emitted from a radioactive source in a given time interval.\n", "In the limit of $n\\rightarrow \\infty$ and for small probabilities $y$, the binomial distribution\n", @@ -962,7 +1195,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "36ecffde", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\lim_{n\\rightarrow \\infty}\\left(\\begin{array}{c} n \\\\ x\\end{array}\\right)y^x(1-y)^{n-x} e^{-\\lambda}=\\sum_{x=1}^{\\infty}\\frac{\\lambda^x}{x!} e^{-\\lambda}.\n", @@ -971,9 +1207,13 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "be4e015c", + "metadata": { + "editable": true + }, "source": [ - "## Meet the covariance!\n", + "### Meet the covariance!\n", + "\n", "An important quantity in a statistical analysis is the so-called covariance. \n", "\n", "Consider the set $\\{X_i\\}$ of $n$\n", @@ -984,7 +1224,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "93522854", + "metadata": { + "editable": true + }, "source": [ "\n", "
\n", @@ -999,7 +1242,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "e667c0aa", + "metadata": { + "editable": true + }, "source": [ "\n", "
\n", @@ -1014,14 +1260,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "44f76dd9", + "metadata": { + "editable": true + }, "source": [ "with" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "1041b2af", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\langle x_i\\rangle =\n", @@ -1031,15 +1283,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "e42984a2", + "metadata": { + "editable": true + }, "source": [ - "## Meet the covariance in matrix disguise\n", "If we consider the above covariance as a matrix" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "a46f958e", + "metadata": { + "editable": true + }, "source": [ "$$\n", "C_{ij} =\\mathrm{Cov}(X_i,\\,X_j),\n", @@ -1048,22 +1305,21 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "37763243", + "metadata": { + "editable": true + }, "source": [ "then the diagonal elements are just the familiar\n", "variances, $C_{ii} = \\mathrm{Cov}(X_i,\\,X_i) = \\mathrm{Var}(X_i)$. It turns out that\n", "all the off-diagonal elements are zero if the stochastic variables are\n", - "uncorrelated.\n", - "\n", - "\n", - "\n", - "\n", - "## Covariance" + "uncorrelated." ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 2, + "id": "aedc8b8c", "metadata": { "collapsed": false, "editable": true @@ -1098,16 +1354,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "4ad05ea1", + "metadata": { + "editable": true + }, "source": [ - "## Meet the covariance, uncorrelated events\n", - "\n", "Consider the stochastic variables $X_i$ and $X_j$, ($i\\neq j$). We have" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "3f643cb0", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\begin{align*}\n", @@ -1124,14 +1384,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "bedb81e0", + "metadata": { + "editable": true + }, "source": [ "If $X_i$ and $X_j$ are independent (assuming $i \\neq j$), we have that" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "8a8f5bdd", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\langle x_i x_j\\rangle = \\langle x_i\\rangle\\langle x_j\\rangle,\n", @@ -1140,14 +1406,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "cc3e8c15", + "metadata": { + "editable": true + }, "source": [ "leading to" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "cf107fa4", + "metadata": { + "editable": true + }, "source": [ "$$\n", "Cov(X_i, X_j) = 0 \\hspace{0.1cm} (i\\neq j).\n", @@ -1156,10 +1428,11 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "c3d6eefd", + "metadata": { + "editable": true + }, "source": [ - "## Numerical experiments and the covariance\n", - "\n", "Now that we have constructed an idealized mathematical framework, let\n", "us try to apply it to empirical observations. Examples of relevant\n", "physical phenomena may be spontaneous decays of nuclei, or a purely\n", @@ -1173,7 +1446,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "11084473", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\{x_1, x_2,\\dots\\,x_k,\\dots\\}.\n", @@ -1182,9 +1458,11 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "ec3bb41f", + "metadata": { + "editable": true + }, "source": [ - "## Numerical experiments and the covariance\n", "We will call these\n", "values our *measurements* and the entire set as our measured\n", "*sample*. The action of measuring all the elements of a sample\n", @@ -1198,18 +1476,16 @@ "interested in finding the few lowest moments, like the mean\n", "$\\mu_X^{\\phantom X}$ and the variance $\\sigma_X^{\\phantom X}$.\n", "\n", - "\n", - "\n", - "\n", - "\n", - "## Numerical experiments and the covariance, actual situations\n", "In practical situations however, a sample is always of finite size. Let that\n", "size be $n$. The expectation value of a sample $\\alpha$, the **sample mean**, is then defined as follows" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "9654f276", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\langle x_{\\alpha} \\rangle \\equiv \\frac{1}{n}\\sum_{k=1}^n x_{\\alpha,k}.\n", @@ -1218,14 +1494,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "9c339ccc", + "metadata": { + "editable": true + }, "source": [ "The *sample variance* is:" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "9d523f50", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\mathrm{Var}(x) \\equiv \\frac{1}{n}\\sum_{k=1}^n (x_{\\alpha,k} - \\langle x_{\\alpha} \\rangle)^2,\n", @@ -1234,15 +1516,13 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "2793f264", + "metadata": { + "editable": true + }, "source": [ - "with its square root being the *standard deviation of the sample*.\n", + "with its square root being the *standard deviation of the sample*. \n", "\n", - "\n", - "\n", - "\n", - "\n", - "## Numerical experiments and the covariance, our observables\n", "You can think of the above observables as a set of quantities which define\n", "a given experiment. This experiment is then repeated several times, say $m$ times.\n", "The total average is then" @@ -1250,7 +1530,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "b0432b14", + "metadata": { + "editable": true + }, "source": [ "\n", "
\n", @@ -1265,7 +1548,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "c1981b2d", + "metadata": { + "editable": true + }, "source": [ "where the last sums end at $m$ and $n$.\n", "The total variance is" @@ -1273,7 +1559,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "679d42bc", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\sigma^2_m= \\frac{1}{mn^2}\\sum_{\\alpha=1}^m(\\langle x_{\\alpha} \\rangle-\\langle X_m \\rangle)^2,\n", @@ -1282,14 +1571,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "2bb94e0d", + "metadata": { + "editable": true + }, "source": [ "which we rewrite as" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "0611f240", + "metadata": { + "editable": true + }, "source": [ "\n", "
\n", @@ -1304,16 +1599,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "624f9965", + "metadata": { + "editable": true + }, "source": [ - "## Numerical experiments and the covariance, the sample variance\n", - "\n", "We define also the sample variance $\\sigma^2$ of all $mn$ individual experiments as" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "c0d8ff9e", + "metadata": { + "editable": true + }, "source": [ "\n", "
\n", @@ -1328,18 +1627,26 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "d058f856", + "metadata": { + "editable": true + }, "source": [ "These quantities, being known experimental values or the results from our calculations, \n", "may differ, in some cases\n", "significantly, from the similarly named\n", "exact values for the mean value $\\mu_X$, the variance $\\mathrm{Var}(X)$\n", - "and the covariance $\\mathrm{Cov}(X,Y)$.\n", - "\n", - "\n", - "\n", - "\n", - "## Numerical experiments and the covariance, central limit theorem\n", + "and the covariance $\\mathrm{Cov}(X,Y)$." + ] + }, + { + "cell_type": "markdown", + "id": "76e956db", + "metadata": { + "editable": true + }, + "source": [ + "### Numerical experiments and the covariance, central limit theorem\n", "\n", "The central limit theorem states that the PDF $\\tilde{p}(z)$ of\n", "the average of $m$ random values corresponding to a PDF $p(x)$ \n", @@ -1353,7 +1660,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "bd4e286e", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\sigma_m=\n", @@ -1363,20 +1673,22 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "877355c7", + "metadata": { + "editable": true + }, "source": [ "In many cases the above estimate for the standard deviation, in particular if correlations are strong, may be too simplistic. We need therefore a more precise defintion of the error and the variance in our results.\n", "\n", - "\n", - "\n", - "\n", - "## Definition of Correlation Functions and Standard Deviation\n", "Our estimate of the true average $\\mu_{X}$ is the sample mean $\\langle X_m \\rangle$" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "abc25d1f", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\mu_{X}^{\\phantom X} \\approx X_m=\\frac{1}{mn}\\sum_{\\alpha=1}^m\\sum_{k=1}^n x_{\\alpha,k}.\n", @@ -1385,14 +1697,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "29a4c67d", + "metadata": { + "editable": true + }, "source": [ "We can then use Eq. ([7](#eq:exptvariance))" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "46b6a9e4", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\sigma^2_m=\\frac{1}{mn^2}\\sum_{\\alpha=1}^m\\sum_{kl=1}^n (x_{\\alpha,k}-\\langle X_m \\rangle)(x_{\\alpha,l}-\\langle X_m \\rangle),\n", @@ -1401,14 +1719,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "350ee280", + "metadata": { + "editable": true + }, "source": [ "and rewrite it as" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "321d0a3d", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\sigma^2_m=\\frac{\\sigma^2}{n}+\\frac{2}{mn^2}\\sum_{\\alpha=1}^m\\sum_{k\n", "
\n", @@ -1508,23 +1836,24 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "03919ae2", + "metadata": { + "editable": true + }, "source": [ "which gives us a useful measure of the correlation pair correlation\n", "starting always at $1$ for $d=0$.\n", "\n", - "\n", - "\n", - "\n", - "## Definition of Correlation Functions and Standard Deviation, sample variance\n", - "\n", "The sample variance of the $mn$ experiments can now be\n", "written in terms of the autocorrelation function" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "f4edb79b", + "metadata": { + "editable": true + }, "source": [ "\n", "
\n", @@ -1540,7 +1869,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "209c3c0a", + "metadata": { + "editable": true + }, "source": [ "and we see that $\\sigma_m$ can be expressed in terms of the\n", "uncorrelated sample variance times a correction factor $\\tau$ which\n", @@ -1550,7 +1882,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "d0c7027f", + "metadata": { + "editable": true + }, "source": [ "\n", "
\n", @@ -1565,19 +1900,16 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "8183355a", + "metadata": { + "editable": true + }, "source": [ "\n", "\n", "For a correlation free experiment, $\\tau$\n", - "equals 1.\n", + "equals 1. \n", "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "## Definition of Correlation Functions and Standard Deviation\n", "From the point of view of\n", "Eq. ([10](#eq:error_estimate_corr_time)) we can interpret a sequential\n", "correlation as an effective reduction of the number of measurements by\n", @@ -1586,7 +1918,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "04f300ab", + "metadata": { + "editable": true + }, "source": [ "$$\n", "n_\\mathrm{eff} = \\frac{n}{\\tau}\n", @@ -1595,7 +1930,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "d9bdb1eb", + "metadata": { + "editable": true + }, "source": [ "To neglect the autocorrelation time $\\tau$ will always cause our\n", "simple uncorrelated estimate of $\\sigma_m^2\\approx \\sigma^2/n$ to\n", @@ -1604,18 +1942,13 @@ "autocorrelation time poses an efficiency problem if the set of\n", "measurements is very large. The solution to this problem is given by \n", "more practically oriented methods like the blocking technique.\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "## Code to compute the Covariance matrix and the Covariance" + "" ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 3, + "id": "93013c0b", "metadata": { "collapsed": false, "editable": true @@ -1663,9 +1996,12 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "65e8cd76", + "metadata": { + "editable": true + }, "source": [ - "## Random Numbers\n", + "### Random Numbers\n", "\n", "Uniform deviates are just random numbers that lie within a specified range\n", "(typically 0 to 1), with any one number in the range just as likely as any other. They\n", @@ -1678,12 +2014,6 @@ "of this section, is an essential building block for any sort of stochastic modeling\n", "or Monte Carlo computer work.\n", "\n", - "\n", - "\n", - "\n", - "\n", - "## Random Numbers, better name: pseudo random numbers\n", - "\n", "A disclaimer is however appropriate. It should be fairly obvious that \n", "something as deterministic as a computer cannot generate purely random numbers.\n", "\n", @@ -1698,18 +2028,16 @@ "\n", " * the algorithm should be fast.\n", "\n", - "\n", - "\n", - "\n", - "\n", - "## Random number generator RNG\n", " The most common random number generators are based on so-called\n", "Linear congruential relations of the type" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "4daecdd3", + "metadata": { + "editable": true + }, "source": [ "$$\n", "N_i=(aN_{i-1}+c) \\mathrm{MOD} (M),\n", @@ -1718,14 +2046,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "fd1c5e47", + "metadata": { + "editable": true + }, "source": [ "which yield a number in the interval [0,1] through" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "d8c06853", + "metadata": { + "editable": true + }, "source": [ "$$\n", "x_i=N_i/M\n", @@ -1734,7 +2068,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "0d971106", + "metadata": { + "editable": true + }, "source": [ "The number \n", "$M$ is called the period and it should be as large as possible \n", @@ -1743,11 +2080,6 @@ "that is if we were to evaluate $(13)\\mathrm{MOD}(9)$, the outcome is the remainder\n", "of the division $13/9$, namely $4$.\n", "\n", - "\n", - "\n", - "\n", - "## Random number generator RNG and periodic outputs\n", - "\n", "The problem with such generators is that their outputs are periodic;\n", "they \n", "will start to repeat themselves with a period that is at most $M$. If however\n", @@ -1758,7 +2090,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "d12a26d7", + "metadata": { + "editable": true + }, "source": [ "$$\n", "N_i=(6N_{i-1}+7) \\mathrm{MOD} (5),\n", @@ -1767,7 +2102,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "2ee32cc9", + "metadata": { + "editable": true + }, "source": [ "with a seed $N_0=2$. This generator produces the sequence\n", "$4,1,3,0,2,4,1,3,0,2,...\\dots$, i.e., a sequence with period $5$.\n", @@ -1777,7 +2115,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "441be869", + "metadata": { + "editable": true + }, "source": [ "$$\n", "N_i=(27N_{i-1}+11) \\mathrm{MOD} (54),\n", @@ -1786,15 +2127,14 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "c0803129", + "metadata": { + "editable": true + }, "source": [ "which still, with $N_0=2$, results in $11,38,11,38,11,38,\\dots$, a period of\n", "just $2$.\n", "\n", - "\n", - "\n", - "\n", - "## Random number generator RNG and its period\n", "Typical periods for the random generators provided in the program library \n", "are of the order of $\\sim 10^9$ or larger. Other random number generators which have\n", "become increasingly popular are so-called shift-register generators.\n", @@ -1807,7 +2147,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "43aef6df", + "metadata": { + "editable": true + }, "source": [ "$$\n", "N_l=(aN_{l-i}+cN_{l-j})\\mathrm{MOD}(M).\n", @@ -1816,9 +2159,11 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "1c7bddf4", + "metadata": { + "editable": true + }, "source": [ - "## Random number generator RNG, other examples\n", "Such a generator again produces a sequence of pseudorandom numbers\n", "but this time with a period much larger than $M$.\n", "It is also possible to construct more elaborate algorithms by including\n", @@ -1829,7 +2174,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "fed2dc23", + "metadata": { + "editable": true + }, "source": [ "\n", "
\n", @@ -1844,14 +2192,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "dc9d8537", + "metadata": { + "editable": true + }, "source": [ "followed by" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "aa9465e9", + "metadata": { + "editable": true + }, "source": [ "\n", "
\n", @@ -1866,21 +2220,23 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "def99a7e", + "metadata": { + "editable": true + }, "source": [ "which according to the authors has a period larger than $2^{94}$.\n", "\n", - "\n", - "\n", - "\n", - "## Random number generator RNG, other examples\n", "Instead of using modular addition, we could use the bitwise\n", "exclusive-OR ($\\oplus$) operation so that" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "61c8f9ef", + "metadata": { + "editable": true + }, "source": [ "$$\n", "N_l=(N_{l-i})\\oplus (N_{l-j})\n", @@ -1889,7 +2245,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "c59c90b8", + "metadata": { + "editable": true + }, "source": [ "where the bitwise action of $\\oplus$ means that if $N_{l-i}=N_{l-j}$ the result is\n", "$0$ whereas if $N_{l-i}\\ne N_{l-j}$ the result is\n", @@ -1900,20 +2259,17 @@ "\n", "In Fortran90, the bitwise $\\oplus$ operation is coded through the intrinsic\n", "function $\\mathrm{IEOR}(m,n)$ where $m$ and $n$ are the input numbers, while in $C$\n", - "it is given by $m\\wedge n$.\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "## Random number generator RNG, RAN0\n", + "it is given by $m\\wedge n$. \n", "\n", "We show here how the linear congruential algorithm can be implemented, namely" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "06587f00", + "metadata": { + "editable": true + }, "source": [ "$$\n", "N_i=(aN_{i-1}) \\mathrm{MOD} (M).\n", @@ -1922,7 +2278,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "c3255e8e", + "metadata": { + "editable": true + }, "source": [ "However, since $a$ and $N_{i-1}$ are integers and their multiplication \n", "could become greater than the standard 32 bit integer, there is a trick via \n", @@ -1932,7 +2291,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "8e3ec364", + "metadata": { + "editable": true + }, "source": [ "$$\n", "M=aq+r,\n", @@ -1941,14 +2303,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "4b7c18d5", + "metadata": { + "editable": true + }, "source": [ "where we have defined" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "4e58c88d", + "metadata": { + "editable": true + }, "source": [ "$$\n", "q=[M/a],\n", @@ -1957,14 +2325,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "1fecdb9a", + "metadata": { + "editable": true + }, "source": [ "and" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "aa126ce7", + "metadata": { + "editable": true + }, "source": [ "$$\n", "r = M\\hspace{0.1cm}\\mathrm{MOD} \\hspace{0.1cm}a.\n", @@ -1973,24 +2347,23 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "20cab2fa", + "metadata": { + "editable": true + }, "source": [ "where the brackets denote integer division. In the code below the numbers \n", "$q$ and $r$ are chosen so that $r < q$.\n", "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "## Random number generator RNG, RAN0\n", - "\n", "To see how this works we note first that" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "904a6320", + "metadata": { + "editable": true + }, "source": [ "\n", "
\n", @@ -2005,23 +2378,24 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "36c6f816", + "metadata": { + "editable": true + }, "source": [ "since we can add or subtract any integer multiple of $M$ from $aN_{i-1}$.\n", "The last term $[N_{i-1}/q]M\\mathrm{MOD}(M)$ is zero since the integer division \n", - "$[N_{i-1}/q]$ just yields a constant which is multiplied with $M$.\n", + "$[N_{i-1}/q]$ just yields a constant which is multiplied with $M$. \n", "\n", - "\n", - "\n", - "\n", - "\n", - "## Random number generator RNG, RAN0\n", "We can now rewrite Eq. ([14](#eq:rntrick1)) as" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "319af13b", + "metadata": { + "editable": true + }, "source": [ "\n", "
\n", @@ -2036,15 +2410,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "0c426357", + "metadata": { + "editable": true + }, "source": [ - "which results\n", - "in" + "which results" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "52547452", + "metadata": { + "editable": true + }, "source": [ "\n", "
\n", @@ -2059,14 +2438,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "86bf958f", + "metadata": { + "editable": true + }, "source": [ "yielding" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "d2015392", + "metadata": { + "editable": true + }, "source": [ "\n", "
\n", @@ -2081,9 +2466,11 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "83495015", + "metadata": { + "editable": true + }, "source": [ - "## Random number generator RNG, RAN0\n", "The term $[N_{i-1}/q]r$ is always smaller or equal $N_{i-1}(r/q)$ and with $r < q$ we obtain always a \n", "number smaller than $N_{i-1}$, which is smaller than $M$. \n", "And since the number $N_{i-1}\\mathrm{MOD} (q)$ is between zero and $q-1$ then\n", @@ -2095,52 +2482,7 @@ "the starting point for each generation of a random number. The period\n", "of $ran0$ is $\\sim 2.1\\times 10^{9}$. A special feature of this\n", "algorithm is that is should never be called with the initial seed \n", - "set to $0$.\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "## Random number generator RNG, RAN0 code" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - " /*\n", - " ** The function\n", - " ** ran0()\n", - " ** is an \"Minimal\" random number generator of Park and Miller\n", - " ** Set or reset the input value\n", - " ** idum to any integer value (except the unlikely value MASK)\n", - " ** to initialize the sequence; idum must not be altered between\n", - " ** calls for sucessive deviates in a sequence.\n", - " ** The function returns a uniform deviate between 0.0 and 1.0.\n", - " */\n", - " double ran0(long &idum)\n", - " {\n", - " const int a = 16807, m = 2147483647, q = 127773;\n", - " const int r = 2836, MASK = 123459876;\n", - " const double am = 1./m;\n", - " long k;\n", - " double ans;\n", - " idum ^= MASK;\n", - " k = (*idum)/q;\n", - " idum = a*(idum - k*q) - r*k;\n", - " // add m if negative difference\n", - " if(idum < 0) idum += m;\n", - " ans=am*(idum);\n", - " idum ^= MASK;\n", - " return ans;\n", - " } // End: function ran0() \n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Properties of Selected Random Number Generators\n", + "set to $0$. \n", "\n", "As mentioned previously, the underlying PDF for the generation of\n", "random numbers is the uniform distribution, meaning that the \n", @@ -2156,16 +2498,15 @@ "Two additional measures are the standard deviation $\\sigma$ and the mean\n", "$\\mu=\\langle x\\rangle$.\n", "\n", - "\n", - "\n", - "\n", - "## Properties of Selected Random Number Generators\n", "For the uniform distribution, the mean value $\\mu$ is then" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "268aac30", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\mu=\\langle x\\rangle=\\frac{1}{2}\n", @@ -2174,14 +2515,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "25bd4ea3", + "metadata": { + "editable": true + }, "source": [ "while the standard deviation is" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "29e8d709", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\sigma=\\sqrt{\\langle x^2\\rangle-\\mu^2}=\\frac{1}{\\sqrt{12}}=0.2886.\n", @@ -2190,13 +2537,15 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "90a07c88", + "metadata": { + "editable": true + }, "source": [ - "## Properties of Selected Random Number Generators\n", "The various random number generators produce results which agree rather well with\n", "these limiting values. \n", "\n", - "\n", + "
\n", "\n", "\n", "\n", @@ -2216,16 +2565,13 @@ "\n", "
$x$-bin ran0 ran1 ran2 ran3
\n", "\n", - "\n", - "\n", - "\n", - "## Simple demonstration of RNGs using python\n", "The following simple Python code plots the distribution of the produced random numbers using the linear congruential RNG employed by Python. The trend displayed in the previous table is seen rather clearly." ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 4, + "id": "3c296708", "metadata": { "collapsed": false, "editable": true @@ -2258,9 +2604,11 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "7a028dda", + "metadata": { + "editable": true + }, "source": [ - "## Properties of Selected Random Number Generators\n", "Since our random numbers, which are typically generated via a linear congruential algorithm,\n", "are never fully independent, we can then define \n", "an important test which measures the degree of correlation, namely the so-called \n", @@ -2270,7 +2618,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "bc325e1a", + "metadata": { + "editable": true + }, "source": [ "$$\n", "C_k=\\frac{f_d}\n", @@ -2280,7 +2631,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "a7738ea8", + "metadata": { + "editable": true + }, "source": [ "with $C_0=1$. Recall that \n", "$\\sigma^2=\\langle x_i^2\\rangle-\\langle x_i\\rangle^2$ and that" @@ -2288,7 +2642,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "b647158e", + "metadata": { + "editable": true + }, "source": [ "$$\n", "f_d = \\frac{1}{nm}\\sum_{\\alpha=1}^m\\sum_{k=1}^{n-d}(x_{\\alpha,k}-\\langle X_m \\rangle)(x_{\\alpha,k+d}-\\langle X_m \\rangle),\n", @@ -2297,24 +2654,33 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "273afa83", + "metadata": { + "editable": true + }, "source": [ "The non-vanishing of $C_k$ for $k\\ne 0$ means that the random\n", "numbers are not independent. The independence of the random numbers is crucial \n", "in the evaluation of other expectation values. If they are not independent, our\n", - "assumption for approximating $\\sigma_N$ is no longer valid.\n", + "assumption for approximating $\\sigma_N$ is no longer valid." + ] + }, + { + "cell_type": "markdown", + "id": "70391792", + "metadata": { + "editable": true + }, + "source": [ + "### Autocorrelation function\n", "\n", - "\n", - "\n", - "\n", - "\n", - "## Autocorrelation function\n", "This program computes the autocorrelation function as discussed in the equation on the previous slide for random numbers generated with the normal distribution $N(0,1)$." ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 5, + "id": "2b08e1a4", "metadata": { "collapsed": false, "editable": true @@ -2354,529 +2720,17 @@ }, { "cell_type": "markdown", - "metadata": {}, - "source": [ - "As can be seen from the plot, the first point gives back the variance and a value of one. \n", - "For the remaining values we notice that there are still non-zero values for the auto-correlation function.\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "## Correlation function and which random number generators should I use\n", - "The program here computes the correlation function for one of the standard functions included with the c++ compiler." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - " // This function computes the autocorrelation function for \n", - " // the standard c++ random number generator\n", - " \n", - " #include \n", - " #include \n", - " #include \n", - " #include \n", - " using namespace std;\n", - " // output file as global variable\n", - " ofstream ofile; \n", - " \n", - " // Main function begins here \n", - " int main(int argc, char* argv[])\n", - " {\n", - " int n;\n", - " char *outfilename;\n", - " \n", - " cin >> n;\n", - " double MCint = 0.; double MCintsqr2=0.;\n", - " double invers_period = 1./RAND_MAX; // initialise the random number generator\n", - " srand(time(NULL)); // This produces the so-called seed in MC jargon\n", - " // Compute the variance and the mean value of the uniform distribution\n", - " // Compute also the specific values x for each cycle in order to be able to\n", - " // the covariance and the correlation function \n", - " // Read in output file, abort if there are too few command-line arguments\n", - " if( argc <= 2 ){\n", - " cout << \"Bad Usage: \" << argv[0] << \n", - " \t \" read also output file and number of cycles on same line\" << endl;\n", - " exit(1);\n", - " }\n", - " else{\n", - " outfilename=argv[1];\n", - " }\n", - " ofile.open(outfilename); \n", - " // Get the number of Monte-Carlo samples\n", - " n = atoi(argv[2]);\n", - " double *X; \n", - " X = new double[n];\n", - " for (int i = 0; i < n; i++){\n", - " double x = double(rand())*invers_period; \n", - " X[i] = x;\n", - " MCint += x;\n", - " MCintsqr2 += x*x;\n", - " }\n", - " double Mean = MCint/((double) n );\n", - " MCintsqr2 = MCintsqr2/((double) n );\n", - " double STDev = sqrt(MCintsqr2-Mean*Mean);\n", - " double Variance = MCintsqr2-Mean*Mean;\n", - " // Write mean value and standard deviation \n", - " cout << \" Standard deviation= \" << STDev << \" Integral = \" << Mean << endl;\n", - " \n", - " // Now we compute the autocorrelation function\n", - " double *autocor; autocor = new double[n];\n", - " for (int j = 0; j < n; j++){\n", - " double sum = 0.0;\n", - " for (int k = 0; k < (n-j); k++){\n", - " \t sum += (X[k]-Mean)*(X[k+j]-Mean); \n", - " }\n", - " autocor[j] = sum/Variance/((double) n );\n", - " ofile << setiosflags(ios::showpoint | ios::uppercase);\n", - " ofile << setw(15) << setprecision(8) << j;\n", - " ofile << setw(15) << setprecision(8) << autocor[j] << endl;\n", - " }\n", - " ofile.close(); // close output file\n", - " return 0;\n", - " } // end of main program \n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Which RNG should I use?\n", - "* C++ has a class called **random**. The [random class](http://www.cplusplus.com/reference/random/) contains a large selection of RNGs and is highly recommended. Some of these RNGs have very large periods making it thereby very safe to use these RNGs in case one is performing large calculations. In particular, the [Mersenne twister random number engine](http://www.cplusplus.com/reference/random/mersenne_twister_engine/) has a period of $2^{19937}$. \n", - "\n", - "* Add RNGs in Python\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "## How to use the Mersenne generator\n", - "The following part of a c++ code (from project 4) sets up the uniform distribution for $x\\in [0,1]$." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - " /*\n", - " \n", - " // You need this \n", - " #include \n", - " \n", - " // Initialize the seed and call the Mersienne algo\n", - " std::random_device rd;\n", - " std::mt19937_64 gen(rd());\n", - " // Set up the uniform distribution for x \\in [[0, 1]\n", - " std::uniform_real_distribution RandomNumberGenerator(0.0,1.0);\n", - " \n", - " // Now use the RNG\n", - " int ix = (int) (RandomNumberGenerator(gen)*NSpins);\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Why blocking?\n", - "**Statistical analysis.**\n", - "\n", - " * Monte Carlo simulations can be treated as *computer experiments*\n", - "\n", - " * The results can be analysed with the same statistical tools as we would use analysing experimental data.\n", - "\n", - " * As in all experiments, we are looking for expectation values and an estimate of how accurate they are, i.e., possible sources for errors.\n", - "\n", - "A very good article which explains blocking is H. Flyvbjerg and H. G. Petersen, *Error estimates on averages of correlated data*, [Journal of Chemical Physics 91, 461-466 (1989)](http://scitation.aip.org/content/aip/journal/jcp/91/1/10.1063/1.457480).\n", - "\n", - " \n", - "\n", - "\n", - "\n", - "\n", - "## Why blocking?\n", - "**Statistical analysis.**\n", - "\n", - " * As in other experiments, Monte Carlo experiments have two classes of errors:\n", - "\n", - " * Statistical errors\n", - "\n", - " * Systematical errors\n", - "\n", - "\n", - " * Statistical errors can be estimated using standard tools from statistics\n", - "\n", - " * Systematical errors are method specific and must be treated differently from case to case. (In VMC a common source is the step length or time step in importance sampling)\n", - "\n", - " \n", - "\n", - "\n", - "\n", - "## Code to demonstrate the calculation of the autocorrelation function\n", - "The following code computes the autocorrelation function, the covariance and the standard deviation\n", - "for standard RNG. \n", - "The [following file](https://github.com/CompPhysics/ComputationalPhysics2/tree/gh-pages/doc/Programs/LecturePrograms/programs/Blocking/autocorrelation.cpp) gives the code." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - " // This function computes the autocorrelation function for \n", - " // the Mersenne random number generator with a uniform distribution\n", - " #include \n", - " #include \n", - " #include \n", - " #include \n", - " #include \n", - " #include \n", - " #include \n", - " #include \n", - " using namespace std;\n", - " using namespace arma;\n", - " // output file\n", - " ofstream ofile;\n", - " \n", - " // Main function begins here \n", - " int main(int argc, char* argv[])\n", - " {\n", - " int MonteCarloCycles;\n", - " string filename;\n", - " if (argc > 1) {\n", - " filename=argv[1];\n", - " MonteCarloCycles = atoi(argv[2]);\n", - " string fileout = filename;\n", - " string argument = to_string(MonteCarloCycles);\n", - " fileout.append(argument);\n", - " ofile.open(fileout);\n", - " }\n", - " \n", - " // Compute the variance and the mean value of the uniform distribution\n", - " // Compute also the specific values x for each cycle in order to be able to\n", - " // compute the covariance and the correlation function \n", - " \n", - " vec X = zeros(MonteCarloCycles);\n", - " double MCint = 0.; double MCintsqr2=0.;\n", - " std::random_device rd;\n", - " std::mt19937_64 gen(rd());\n", - " // Set up the uniform distribution for x \\in [[0, 1]\n", - " std::uniform_real_distribution RandomNumberGenerator(0.0,1.0);\n", - " for (int i = 0; i < MonteCarloCycles; i++){\n", - " double x = RandomNumberGenerator(gen); \n", - " X(i) = x;\n", - " MCint += x;\n", - " MCintsqr2 += x*x;\n", - " }\n", - " double Mean = MCint/((double) MonteCarloCycles );\n", - " MCintsqr2 = MCintsqr2/((double) MonteCarloCycles );\n", - " double STDev = sqrt(MCintsqr2-Mean*Mean);\n", - " double Variance = MCintsqr2-Mean*Mean;\n", - " // Write mean value and variance\n", - " cout << \" Sample variance= \" << Variance << \" Mean value = \" << Mean << endl;\n", - " // Now we compute the autocorrelation function\n", - " vec autocorrelation = zeros(MonteCarloCycles);\n", - " for (int j = 0; j < MonteCarloCycles; j++){\n", - " double sum = 0.0;\n", - " for (int k = 0; k < (MonteCarloCycles-j); k++){\n", - " sum += (X(k)-Mean)*(X(k+j)-Mean); \n", - " }\n", - " autocorrelation(j) = sum/Variance/((double) MonteCarloCycles );\n", - " ofile << setiosflags(ios::showpoint | ios::uppercase);\n", - " ofile << setw(15) << setprecision(8) << j;\n", - " ofile << setw(15) << setprecision(8) << autocorrelation(j) << endl;\n", - " }\n", - " // Now compute the exact covariance using the autocorrelation function\n", - " double Covariance = 0.0;\n", - " for (int j = 0; j < MonteCarloCycles; j++){\n", - " Covariance += autocorrelation(j);\n", - " }\n", - " Covariance *= 2.0/((double) MonteCarloCycles);\n", - " // Compute now the total variance, including the covariance, and obtain the standard deviation\n", - " double TotalVariance = (Variance/((double) MonteCarloCycles ))+Covariance;\n", - " cout << \"Covariance =\" << Covariance << \"Totalvariance= \" << TotalVariance << \"Sample Variance/n= \" << (Variance/((double) MonteCarloCycles )) << endl;\n", - " cout << \" STD from sample variance= \" << sqrt(Variance/((double) MonteCarloCycles )) << \" STD with covariance = \" << sqrt(TotalVariance) << endl;\n", - " \n", - " ofile.close(); // close output file\n", - " return 0;\n", - " } // end of main program \n", - " \n", - " \n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## What is blocking?\n", - "**Blocking.**\n", - "\n", - " * Say that we have a set of samples from a Monte Carlo experiment\n", - "\n", - " * Assuming (wrongly) that our samples are uncorrelated our best estimate of the standard deviation of the mean $\\langle \\mathbf{M}\\rangle$ is given by" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\sigma=\\sqrt{\\frac{1}{n}\\left(\\langle \\mathbf{M}^2\\rangle-\\langle \\mathbf{M}\\rangle^2\\right)}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "* If the samples are correlated we can rewrite our results to show that" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\sigma=\\sqrt{\\frac{1+2\\tau/\\Delta t}{n}\\left(\\langle \\mathbf{M}^2\\rangle-\\langle \\mathbf{M}\\rangle^2\\right)}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "where $\\tau$ is the correlation time (the time between a sample and the next uncorrelated sample) and $\\Delta t$ is time between each sample\n", - "\n", - " \n", - "\n", - "\n", - "## What is blocking?\n", - "**Blocking.**\n", - "\n", - " * If $\\Delta t\\gg\\tau$ our first estimate of $\\sigma$ still holds\n", - "\n", - " * Much more common that $\\Delta t<\\tau$\n", - "\n", - " * In the method of data blocking we divide the sequence of samples into blocks\n", - "\n", - " * We then take the mean $\\langle \\mathbf{M}_i\\rangle$ of block $i=1\\ldots n_{blocks}$ to calculate the total mean and variance\n", - "\n", - " * The size of each block must be so large that sample $j$ of block $i$ is not correlated with sample $j$ of block $i+1$\n", - "\n", - " * The correlation time $\\tau$ would be a good choice\n", - "\n", - "\n", - "\n", - "\n", - "## What is blocking?\n", - "**Blocking.**\n", - "\n", - " * Problem: We don't know $\\tau$ or it is too expensive to compute\n", - "\n", - " * Solution: Make a plot of std. dev. as a function of blocksize\n", - "\n", - " * The estimate of std. dev. of correlated data is too low $\\to$ the error will increase with increasing block size until the blocks are uncorrelated, where we reach a plateau\n", - "\n", - " * When the std. dev. stops increasing the blocks are uncorrelated\n", - "\n", - "\n", - "\n", - "\n", - "## Implementation\n", - " * Do a Monte Carlo simulation, storing all samples to file\n", - "\n", - " * Do the statistical analysis on this file, independently of your Monte Carlo program\n", - "\n", - " * Read the file into an array\n", - "\n", - " * Loop over various block sizes\n", - "\n", - " * For each block size $n_b$, loop over the array in steps of $n_b$ taking the mean of elements $i n_b,\\ldots,(i+1) n_b$\n", - "\n", - " * Take the mean and variance of the resulting array\n", - "\n", - " * Write the results for each block size to file for later\n", - " analysis\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "## Actual implementation with code, main function\n", - "When the file gets large, it can be useful to write your data in binary mode instead of ascii characters.\n", - "The [following python file](https://github.com/CompPhysics/MachineLearning/blob/master/doc/Programs/Sampling/analysis.py) reads data from file with the output from every Monte Carlo cycle." - ] - }, - { - "cell_type": "code", - "execution_count": null, + "id": "5848dd32", "metadata": { - "collapsed": false, "editable": true }, - "outputs": [], "source": [ - "# Blocking\n", - " @timeFunction\n", - " def blocking(self, blockSizeMax = 500):\n", - " blockSizeMin = 1\n", - "\n", - " self.blockSizes = []\n", - " self.meanVec = []\n", - " self.varVec = []\n", - "\n", - " for i in range(blockSizeMin, blockSizeMax):\n", - " if(len(self.data) % i != 0):\n", - " pass#continue\n", - " blockSize = i\n", - " meanTempVec = []\n", - " varTempVec = []\n", - " startPoint = 0\n", - " endPoint = blockSize\n", - "\n", - " while endPoint <= len(self.data):\n", - " meanTempVec.append(np.average(self.data[startPoint:endPoint]))\n", - " startPoint = endPoint\n", - " endPoint += blockSize\n", - " mean, var = np.average(meanTempVec), np.var(meanTempVec)/len(meanTempVec)\n", - " self.meanVec.append(mean)\n", - " self.varVec.append(var)\n", - " self.blockSizes.append(blockSize)\n", - "\n", - " self.blockingAvg = np.average(self.meanVec[-200:])\n", - " self.blockingVar = (np.average(self.varVec[-200:]))\n", - " self.blockingStd = np.sqrt(self.blockingVar)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## The Bootstrap method\n", - "\n", - "The Bootstrap resampling method is also very popular. It is very simple:\n", - "\n", - "1. Start with your sample of measurements and compute the sample variance and the mean values\n", - "\n", - "2. Then start again but pick in a random way the numbers in the sample and recalculate the mean and the sample variance.\n", - "\n", - "3. Repeat this $K$ times.\n", - "\n", - "It can be shown, see the article by [Efron](https://projecteuclid.org/download/pdf_1/euclid.aos/1176344552)\n", - "that it produces the correct standard deviation.\n", - "\n", - "This method is very useful for small ensembles of data points. \n", - "\n", - "\n", - "## Bootstrapping\n", - "Given a set of $N$ data, assume that we are interested in some \n", - "observable $\\theta$ which may be estimated from that set. This observable can also be for example the result of a fit based on all $N$ raw data. \n", - "Let us call the value of the observable obtained from the original \n", - "data set $\\hat{\\theta}$. One recreates from the sample repeatedly \n", - "other samples by choosing randomly $N$ data out of the original set. \n", - "This costs essentially nothing, since we just recycle the original data set for the building of new sets. \n", - "\n", - "\n", - "## Bootstrapping, recipe\n", - "Let us assume we have done this $K$ times and thus have $K$ sets of $N$ \n", - "data values each. \n", - "Of course some values will enter more than once in the new sets. For each of these sets one computes the observable $\\theta$ resulting in values $\\theta_k$ with $k = 1,...,K$. Then one determines" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\tilde{\\theta} = \\frac{1}{K} \\sum_{k=1}^K \\theta_k,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "and" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "sigma^2_{\\tilde{\\theta}} = \\frac{1}{K} \\sum_{k=1}^K \\left(\\theta_k-\\tilde{\\theta}\\right)^2.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "These are estimators for $\\angle\\theta\\rangle$ and its variance. They are not unbiased and therefore \n", - "$\\tilde{\\theta}\\neq\\hat{\\theta}$ for finite K. \n", - "\n", - "The difference is called bias and gives an idea on how far away the result may be from \n", - "the true $\\angle\\theta\\rangle$. As final result for the observable one quotes $\\angle\\theta\\rangle = \\tilde{\\theta} \\pm \\sigma_{\\tilde{\\theta}}$ .\n", - "\n", - "\n", - "\n", - "## Bootstrapping, [code](https://github.com/CompPhysics/MachineLearning/blob/master/doc/Programs/Sampling/analysis.py)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - " # Bootstrap\n", - " @timeFunction\n", - " def bootstrap(self, nBoots = 1000):\n", - " bootVec = np.zeros(nBoots)\n", - " for k in range(0,nBoots):\n", - " bootVec[k] = np.average(np.random.choice(self.data, len(self.data)))\n", - " self.bootAvg = np.average(bootVec)\n", - " self.bootVar = np.var(bootVec)\n", - " self.bootStd = np.std(bootVec)\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Jackknife, [code](https://github.com/CompPhysics/MachineLearning/blob/master/doc/Programs/Sampling/analysis.py)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - " # Jackknife\n", - " @timeFunction\n", - " def jackknife(self):\n", - " jackknVec = np.zeros(len(self.data))\n", - " for k in range(0,len(self.data)):\n", - " jackknVec[k] = np.average(np.delete(self.data, k))\n", - " self.jackknAvg = self.avg - (len(self.data) - 1) * (np.average(jackknVec) - self.avg)\n", - " self.jackknVar = float(len(self.data) - 1) * np.var(jackknVec)\n", - " self.jackknStd = np.sqrt(self.jackknVar)\n" + "As can be seen from the plot, the first point gives back the variance and a value of one. \n", + "For the remaining values we notice that there are still non-zero values for the auto-correlation function." ] } ], "metadata": {}, "nbformat": 4, - "nbformat_minor": 4 + "nbformat_minor": 5 }