show_ts_distribution.py
8.54 KB
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
#! /usr/bin/env python
# ==========================================================================
# Display TS distribution generated by cstsdist
#
# Copyright (C) 2011-2016 Jurgen Knodlseder
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# ==========================================================================
import sys
import csv
import math
import cscripts
try:
import matplotlib.pyplot as plt
plt.figure()
plt.close()
except (ImportError, RuntimeError):
print('This script needs the "matplotlib" module')
sys.exit()
try:
import numpy as np
except ImportError:
print('This script needs the "numpy" module')
sys.exit()
# ==================== #
# Read TS distribution #
# ==================== #
def read_ts(filename, tsname='TS'):
"""
Read TS distribution values from CSV file
Parameters
----------
filename : str
Name of CSV file
tsname : str, optional
Column name of TS
Returns
-------
a : `numpy.array`
Array of TS values
"""
# Initialise list
values = []
# Open reader
reader = csv.reader(open(filename, 'r'), delimiter=',')
# Read rows
first = True
index = -1
for row in reader:
# Get column index if first row
if first:
try:
index = row.index(tsname)
except:
print('ERROR: Column "'+tsname+'" not found in file')
print(row)
raise NameError(tsname)
# Handle data rows
else:
values.append(float(row[index]))
# Flag that first row has been passed
first = False
# Create numpy array
a = np.array(values)
# Return array
return a
# =========== #
# Compute erf #
# =========== #
def erf(x):
"""
Compute error function
Parameters
----------
x : float
Value
Returns
-------
erf(-x) : float
Error function
"""
# save the sign of x
sign = 1
if x < 0:
sign = -1
x = abs(x)
# constants
a1 = 0.254829592
a2 = -0.284496736
a3 = 1.421413741
a4 = -1.453152027
a5 = 1.061405429
p = 0.3275911
# A&S formula 7.1.26
t = 1.0/(1.0 + p*x)
y = 1.0 - (((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t*math.exp(-x*x)
# Return result
return sign*y # erf(-x) = -erf(x)
# =============================== #
# Display cumulative distribution #
# =============================== #
def dist_cdf(values, nbins, title, plotfile, expect=''):
"""
Display cumulative TS distribution and overplots expectation
Parameters
----------
values : float
TS values
nbins : int
Number of bins
title : str
Plot title
plotfile : str
Plot file name
expect : str, optional
If 'show', show expectation
"""
# Set range and adapt number of bins. We make sure that we have a
# histogram bin centred on 0 that will capture the TS=0 part.
max_value = max(values)
binsize = max_value/nbins
min_value = 0.5*binsize
while min_value > min(values):
min_value -= binsize
nbins += 1
# Create histogram
hist_x = []
hist_y = []
hist_expect = []
norm = 0.5*len(values)
for i in range(nbins):
x_min = min_value+i*binsize
x_max = min_value+(i+1)*binsize
x_val = 0.5*(x_min+x_max)
y_val = 0.0
for ts in values:
if ts > x_min:
y_val += 1.0
hist_x.append(x_min)
hist_y.append(y_val)
hist_x.append(x_max)
hist_y.append(y_val)
if x_min > 0.0:
value = norm*erf(math.sqrt(0.5*x_min)) + norm
hist_expect.append(len(values)-value)
hist_expect.append(len(values)-value)
else:
hist_expect.append(norm)
hist_expect.append(norm)
# Show expected distribution (half)
plt.semilogy(hist_x, hist_y, 'r-', linewidth=2, label='simulations')
if expect == 'show':
plt.semilogy(hist_x, hist_expect, 'k-', linewidth=2, label='expectation')
plt.semilogy(hist_x, hist_y, 'r-', linewidth=2)
# Set plot
plt.xlabel('TS')
plt.ylabel('Number of trials > TS')
plt.title(title)
plt.grid(True)
plt.legend(loc='upper right')
# Show figure
if len(plotfile) > 0:
plt.savefig(plotfile)
else:
plt.show()
# Return
return
# ======================================== #
# Display probability density distribution #
# ======================================== #
def dist_pdf(values, nbins, title, plotfile, expect=''):
"""
Display probability density TS distribution and overplots expectation
Parameters
----------
values : float
TS values
nbins : int
Number of bins
title : str
Plot title
plotfile : str
Plot file name
expect : str, optional
If 'show', show expectation
"""
# Set range and adapt number of bins. We make sure that we have a
# histogram bin centred on 0 that will capture the TS=0 part.
max_value = max(values)
binsize = max_value/nbins
min_value = 0.5*binsize
while min_value > min(values):
min_value -= binsize
nbins += 1
# Create histogram
n, bins, patches = plt.hist(values, nbins, range=[min_value, max_value],
align='mid', facecolor='green',
log=True, label='simulations')
# Create expected distribution (only for positive TS). We compute the
# full and half of the distribution, as for positively constrained
# quantities half of the values have TS=0
x = []
y_full = []
y_half = []
width = bins[1]-bins[0]
norm = len(values)/(math.sqrt(2.0)*math.sqrt(math.pi))*width
x.append(0.0)
y_full.append(len(values))
y_half.append(0.5*len(values))
for bin in bins:
ts = bin + 0.5*width
if ts > 0:
y = norm*math.pow(ts,-0.5)*math.exp(-0.5*ts)
x.append(ts)
y_full.append(y)
y_half.append(0.5*y)
# Show expected distribution (half)
if expect == 'show':
plt.semilogy(x, y_half, 'ro', linewidth=2, label='expectation')
# Set plot
plt.xlabel('TS')
plt.ylabel('Number of trials')
plt.title(title)
plt.grid(True)
plt.legend(loc='upper right')
# Show figure
if len(plotfile) > 0:
plt.savefig(plotfile)
else:
plt.show()
# Return
return
# ==================== #
# Show TS distribution #
# ==================== #
def show_ts_distribution():
"""
Show TS distribution
"""
# Set usage string
usage = ('show_ts_distribution.py [-n bins] [-c column] [-title title] '
'[-e expect] [-t type] [-p plotfile] file')
# Set default options
options = [{'option': '-n', 'value': 30},
{'option': '-c', 'value': 'TS'},
{'option': '-title', 'value': 'TS distribution'},
{'option': '-e', 'value': ''},
{'option': '-t', 'value': 'pdf'},
{'option': '-p', 'value': ''}]
# Get arguments and options from command line arguments
args, options = cscripts.ioutils.get_args_options(options, usage)
# Extract script parameters from options
nbins = int(options[0]['value'])
tsname = options[1]['value']
title = options[2]['value']
expect = options[3]['value']
disttype = options[4]['value']
plotfile = options[5]['value']
# Read values from CSV file
values = read_ts(args[0], tsname=tsname)
print('%d values read.' % len(values))
# Show histogram
if disttype == 'pdf':
dist_pdf(values, nbins, title, plotfile, expect=expect)
else:
dist_cdf(values, nbins, title, plotfile, expect=expect)
# Return
return
# ======================== #
# Main routine entry point #
# ======================== #
if __name__ == '__main__':
# Show TS distribution
show_ts_distribution()