-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathplot_distribution.py
348 lines (305 loc) · 12.5 KB
/
plot_distribution.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
import re
import sys
import math
import numpy as np
from matplotlib import pyplot as plt
from scipy import integrate
'''
Script for visualising data generated by the test_distribution.cc
main program.
This script processes text files in the format given below. It plots
a binned distribution and compares the evaluated distribution to the
analytical expression. The file header depends on the considered
distribution and is parsed to extract the relevant parameters.
-------------------------------------------------
BesselProductDistribution
beta = 4
x_p = 2.82743
x_m = 0
n_samples = 1000
n_points = 129
==== samples ====
2.05174
1.82559
0.806089
[...]
1.50355
==== points ====
-3.14159 0.0371872
-3.09251 0.0364034
[...]
3.09251 0.0385538
3.14159 0.0371872
-------------------------------------------------
'''
class Distribution(object):
'''Class for wrapping a distribution
:arg samples: Samples drawn for distribution
:arg X: x-coordinates of points to be plotted
:arg Y: y-coordinates of points to be plotted
'''
def __init__(self,samples,X,Y):
self.samples = samples
self.X = X
self.Y = Y
self.label = 'UNKNOWN'
'''Plot a histogram of the samples and the distribution
and save to file
:arg filename: Name of file to write to
:arg bins: Number of bins in sample histogram
'''
def plot(self,filename,bins=64):
plt.clf()
plt.hist(self.samples,
histtype='stepfilled',
alpha=0.5,
density=True,
bins=bins,
label='samples')
plt.plot(self.X,self.Y,
linewidth=2,
linestyle='-',
color='black',
label='distribution')
self._plot_analytical()
ax = plt.gca()
self._set_xaxis(ax)
plt.legend(loc='upper right')
plt.title(self.label)
plt.savefig(filename,bbox_inches='tight')
def _plot_analytical(self):
'''Plot analytical expression for distribution'''
X_analytical = np.arange(np.min(self.X),np.max(self.X),1.E-3)
Y_analytical = np.vectorize(self.f_analytical)(X_analytical)
plt.plot(X_analytical,Y_analytical,
linewidth=2,
linestyle='--',
color='red',
label='analytical')
'''Set range and ticks on horizontal set_xaxis
overwrite this to use an interval which is not [-pi,+pi]
:arg ax: axis instance
'''
def _set_xaxis(self,ax):
ax.set_xlim(-1.05*np.pi,1.05*np.pi)
ax.set_xticks((-np.pi,-0.5*np.pi,0,0.5*np.pi,np.pi))
ax.set_xticklabels((r'$-\pi$',r'$-\frac{\pi}{2}$','$0$',r'$\frac{\pi}{2}$',r'$\pi$'))
class ExpSin2Distribution(Distribution):
'''Wrapper for ExpSin2Distribution
:arg samples: Samples drawn for distribution
:arg X: x-coordinates of points to be plotted
:arg Y: y-coordinates of points to be plotted
:arg sigma: parameter sigma
'''
def __init__(self,samples,X,Y,sigma):
super().__init__(samples,X,Y)
self.label = 'ExpSin2Distribution'
self.sigma = sigma
self.Znorm_inv = np.exp(0.5*self.sigma)/(2.*np.pi*np.i0(0.5*self.sigma))
'''Analytical value of distribution at a given point
:arg x: Point at which the distribution is evaluated
'''
def f_analytical(self,x):
return self.Znorm_inv*np.exp(-self.sigma*np.sin(0.5*x)**2)
class CompactExpDistribution(Distribution):
'''Wrapper for CompactExpDistribution
:arg samples: Samples drawn for distribution
:arg X: x-coordinates of points to be plotted
:arg Y: y-coordinates of points to be plotted
:arg sigma: parameter sigma
'''
def __init__(self,samples,X,Y,sigma):
super().__init__(samples,X,Y)
self.label = 'CompactExpDistribution'
self.sigma = sigma
self.Znorm_inv = 0.5*self.sigma/np.sinh(self.sigma)
'''Analytical value of distribution at a given point
:arg x: Point at which the distribution is evaluated
'''
def f_analytical(self,x):
return self.Znorm_inv*np.exp(self.sigma*x)
'''Set range and ticks on horizontal set_xaxis
:arg ax: axis instance
'''
def _set_xaxis(self,ax):
ax.set_xlim(-1.05,1.05)
ax.set_xticks((-1.0,-0.5,0.0,0.5,1.0))
ax.set_xticklabels((r'$-1$',r'$-\frac{1}{2}$','$0$',r'$\frac{1}{2}$',r'$1$'))
class ExpCosDistribution(Distribution):
def __init__(self,samples,X,Y,beta,x_p,x_m):
super().__init__(samples,X,Y)
self.label = 'ExpCosDistribution'
self.beta = beta
self.x_p = x_p
self.x_m = x_m
self.Znorm = 2.*np.pi*np.i0(2.*beta*np.cos(0.5*(self.x_p-self.x_m)))
'''Analytical value of distribution at a given point
:arg x: Point at which the distribution is evaluated
'''
def f_analytical(self,x):
return 1./self.Znorm*np.exp(self.beta*(np.cos(x-self.x_p)+np.cos(x-self.x_m)))
class BesselProductDistribution(Distribution):
def __init__(self,samples,X,Y,beta,x_p,x_m):
super().__init__(samples,X,Y)
self.label = 'BesselProductDistribution'
self.beta = beta
self.x_p = x_p
self.x_m = x_m
f = lambda x: self._i0_scaled(np.cos(0.5*(x-self.x_p)))*self._i0_scaled(np.cos(0.5*(x-self.x_m)))
self.Znorm = integrate.quad(f,-np.pi,+np.pi)[0]
'''Compute e^{-2\beta} I_0(2\beta x)
:arg x: argument at which the function is evaluated
'''
def _i0_scaled(self,x):
f = lambda phi: np.exp(2.0*self.beta*(x*np.cos(phi)-1))
return 1./(2.*np.pi)*integrate.quad(f,-np.pi,+np.pi)[0]
'''Analytical value of distribution at a given point
:arg x: Point at which the distribution is evaluated
'''
def f_analytical(self,x):
return 1./self.Znorm*self._i0_scaled(np.cos(0.5*(x-self.x_p)))*self._i0_scaled(np.cos(0.5*(x-self.x_m)))
class ApproximateBesselProductDistribution(Distribution):
def __init__(self,samples,X,Y,beta,x_p,x_m):
super().__init__(samples,X,Y)
self.label = 'ApproximateBesselProductDistribution'
self.beta = beta
self.x_p = x_p
self.x_m = x_m
# Number of terms included in the sum
self.kmax = 16
self.x0 = self.x_p-self.x_m
self.sign_flip = -1 if (self.x0<0) else +1
self.x0 *= self.sign_flip
if (self.x0 > np.pi):
self.x0 = 2.*np.pi - self.x0
self.sign_flip *= -1
self.sigma2_inv_p = abs(self.beta*np.cos(0.25*self.x0))
self.sigma2_inv_m = abs(self.beta*np.sin(0.25*self.x0))
rho = (self.sigma2_inv_m/self.sigma2_inv_p)**1.5*np.exp(-4.*(self.sigma2_inv_p-self.sigma2_inv_m))
self.N_p = 1./(1.+rho)
self.N_m = 1.-self.N_p
def _plot_analytical(self):
'''Plot analytical expression for distribution together
with original Bessel distribution'''
X_analytical = np.arange(-np.pi,np.pi,1.E-3)
Y_analytical = np.vectorize(self.f_analytical)(X_analytical)
plt.plot(X_analytical,Y_analytical,
linewidth=2,
linestyle='--',
color='red',
label='analytical')
bessel_prod_dist = BesselProductDistribution(self.samples,
self.X,
self.Y,
self.beta,
self.x_p,
self.x_m)
Y_analytical_bessel = np.vectorize(bessel_prod_dist.f_analytical)(X_analytical)
plt.plot(X_analytical,Y_analytical_bessel,
linewidth=2,
linestyle='--',
color='green',
label='BesselProductDistribution')
'''Analytical value of distribution at a given point
:arg x: Point at which the distribution is evaluated
'''
def f_analytical(self,x):
z = (x-self.x_m)*self.sign_flip
s_p = 0.0
s_m = 0.0
for k in range(-self.kmax,self.kmax+1):
z_shifted = z-0.5*self.x0+2*k*np.pi
s_p += np.exp(-0.5*self.sigma2_inv_p*z_shifted**2)
z_shifted += np.pi
s_m += np.exp(-0.5*self.sigma2_inv_m*z_shifted**2)
value = (np.sqrt(1./(2.*np.pi))
* ( np.sqrt(self.sigma2_inv_p)*self.N_p*s_p
+ np.sqrt(self.sigma2_inv_m)*self.N_m*s_m ))
return value
'''Read data in the format given above from a text file
Returns a distribution wrapper of the type saved in the file
:arg: filename Name of file to read
'''
def read_data(filename):
mode = None
j = 0 # Counter for points
k = 0 # Counter for samples
param = {} # Dictionary for saving distribution parameters
with open(filename) as f:
for line in f.readlines():
# Read in samples
if (mode == 'ParseSamples'):
if (j<n_samples) and (line.strip() != ''):
samples[j] = float(line)
j += 1
elif (mode == 'ParsePoints'):
if (k<n_points) and (line.strip() != ''):
x,y = line.split()
X[k] = float(x)
Y[k] = float(y)
k += 1
else:
# Work out which name of distribution
m = re.match(' *(.*Distribution)',line)
if m:
distribution = m.group(1)
# Work out number of samples contained in file
m = re.match(' *n_samples *= *([0-9]+)',line)
if m:
n_samples = int(m.group(1))
# Work out number of points contained in file
m = re.match(' *n_points *= *([0-9]+)',line)
if m:
n_points = int(m.group(1))
# Parse any other parameters
m = re.match(' *([a-zA-Z0-9_]+) *= *([0-9\.\-\+Ee]+)',line)
if m:
param[m.group(1)] = m.group(2)
# Check for line marking start of samples
m = re.match('.*==== samples ====.*',line)
if m:
mode = 'ParseSamples'
samples = np.zeros(n_samples)
m = re.match('.*==== points ====.*',line)
if m:
mode = 'ParsePoints'
X = np.zeros(n_points)
Y = np.zeros(n_points)
print ('distribution = ',distribution)
print ('n_samples = ',n_samples)
print ('n_points = ',n_points)
print ('distribution parameters:')
for (key,value) in param.items():
if not ((key == 'n_samples') or (key == 'n_points')):
print (' ',key,' = ',value)
if (distribution == 'ExpSin2Distribution'):
return ExpSin2Distribution(samples,X,Y,float(param['sigma']))
elif (distribution == 'CompactExpDistribution'):
return CompactExpDistribution(samples,X,Y,float(param['sigma']))
elif (distribution == 'ExpCosDistribution'):
return ExpCosDistribution(samples,X,Y,
float(param['beta']),
float(param['x_p']),
float(param['x_m']))
elif (distribution == 'BesselProductDistribution'):
return BesselProductDistribution(samples,X,Y,
float(param['beta']),
float(param['x_p']),
float(param['x_m']))
elif (distribution == 'ApproximateBesselProductDistribution'):
return ApproximateBesselProductDistribution(samples,X,Y,
float(param['beta']),
float(param['x_p']), float(param['x_m']))
else:
print ('ERROR: Unknown distribution: ',distribution)
#################################################################
### M A I N ###
#################################################################
if (__name__ == '__main__'):
nbins = 64 # Number of bins used for sample histogram
if (len(sys.argv) != 2):
print ('Usage: python3 '+sys.argv[0]+' FILENAME')
sys.exit(-1)
filename = sys.argv[1]
distribution = read_data(filename)
distribution.plot('distribution.pdf')