heapyx 0.1.3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
heapy/auto/polybase.py ADDED
@@ -0,0 +1,437 @@
1
+ import os
2
+ import warnings
3
+ import numpy as np
4
+ import matplotlib.pyplot as plt
5
+ from matplotlib import rcParams
6
+ from astropy.stats import bayesian_blocks
7
+ from .baseline import Baseline
8
+ from .polynomial import Polynomial
9
+ from ..util.significance import pgsig, ppsig
10
+ from ..util.data import union, msg_format, json_dump
11
+
12
+
13
+
14
+ class PolyBase(object):
15
+
16
+ """
17
+ NOTE: only apply to possion data with gaussian background
18
+ """
19
+
20
+ def __init__(self, ts, bins, exp=None, ignore=None):
21
+ self.ts = np.array(ts).astype(float)
22
+ self.bins = np.array(bins).astype(float)
23
+
24
+ cts, _ = np.histogram(self.ts, bins=self.bins)
25
+ self.cts = np.array(cts).astype(int)
26
+
27
+ self.lbins = self.bins[:-1]
28
+ self.rbins = self.bins[1:]
29
+ self.binsize = self.bins[1:] - self.bins[:-1]
30
+ if exp is None:
31
+ self.exp = self.binsize
32
+ else:
33
+ self.exp = np.array(exp).astype(float)
34
+
35
+ if (self.exp.size + 1) != self.bins.size:
36
+ raise TypeError("expected size(exp) + 1 = size(bins)")
37
+ if not (self.exp <= self.binsize).all():
38
+ raise TypeError("expected exp <= binsize")
39
+
40
+ self.ignore = ignore
41
+
42
+ self.time = (self.lbins + self.rbins) / 2
43
+ self.rate = self.cts / self.exp
44
+
45
+ self.ini_res = {'time': self.time, 'cts': self.cts,
46
+ 'rate': self.rate, 'exp': self.exp,
47
+ 'bins': self.bins, 'ignore': self.ignore}
48
+
49
+ # basefit method
50
+ self.base_res = None
51
+
52
+ # bblock method
53
+ self.block_res = None
54
+
55
+ # calsnr method
56
+ self.snr_res = None
57
+
58
+ # fetsig method
59
+ self.sort_res = None
60
+
61
+ # polyfit method
62
+ self.poly_res = None
63
+
64
+
65
+ @classmethod
66
+ def frombin(cls, cts, bins, exp=None, ignore=None):
67
+ cts = np.array(cts)
68
+ bins = np.array(bins)
69
+
70
+ if bins.size != (cts.size + 1):
71
+ raise TypeError("expected size(bins) = size(cts)+1")
72
+
73
+ msg = 'rebuilt the time list, but may not accurate'
74
+ warnings.warn(msg_format(msg), UserWarning, stacklevel=2)
75
+ ts = np.array([])
76
+ for t1, t2, n in zip(bins[:-1], bins[1:], cts):
77
+ ts = np.append(ts, np.random.random(size=int(n)) * (t2 - t1) + t1)
78
+
79
+ sbs_ = cls(ts, bins, exp, ignore)
80
+ return sbs_
81
+
82
+
83
+ def bblock(self):
84
+ if len(self.ts) > 1e4:
85
+ pos = np.where(self.cts > 0)[0]
86
+ edges_ = bayesian_blocks(self.time[pos], self.cts[pos], fitness='events', p0=0.05)
87
+ else:
88
+ edges_ = bayesian_blocks(self.ts, fitness='events', p0=0.05)
89
+
90
+ edges = [self.time[0], edges_[0], edges_[-1], self.time[-1]]
91
+ for i in range(1, len(edges_) - 1, 1):
92
+ flag1 = (edges_[i] - edges_[i-1]) > np.min(self.binsize) / 1.8
93
+ flag2 = (edges_[i+1] - edges_[i]) > np.min(self.binsize) / 1.8
94
+ if flag1 and flag2:
95
+ edges.append(edges_[i])
96
+ self.edges = np.unique(edges)
97
+ self.nblock = len(self.edges) - 1
98
+ self.re_binsize = self.edges[1:] - self.edges[:-1]
99
+
100
+ self.re_cts, _ = np.histogram(self.ts, bins=self.edges)
101
+
102
+ self.block_res = {'edges': self.edges, 'nblock': self.nblock, 're_binsize': self.re_binsize}
103
+
104
+
105
+ def basefit(self, weight=None):
106
+ if self.block_res is None: self.bblock()
107
+
108
+ if weight is None:
109
+ weight = np.ones_like(self.time)
110
+
111
+ if self.ignore is not None:
112
+ ignore_idx = []
113
+ for i, (l, u) in enumerate(zip(self.lbins, self.rbins)):
114
+ for low, upp in self.ignore:
115
+ if not (u <= low or l >= upp):
116
+ ignore_idx.append(i)
117
+ ignore_idx = np.unique(ignore_idx).astype(int)
118
+ weight[ignore_idx] = 0
119
+
120
+ pos = np.where(self.cts > 0)[0]
121
+ self.bl = Baseline.set_method('drpls')
122
+ self.bl.fit(self.time[pos], self.rate[pos], w=weight[pos], lam=None, nk=None)
123
+ self.bak = self.bl.val(self.time)
124
+ self.bcts = self.bak * self.exp
125
+
126
+ # plus zero for copy
127
+ self.base_res = {'bcts': self.bcts + 0, 'bak': self.bak + 0}
128
+
129
+
130
+ def calsnr(self):
131
+ if self.base_res is None: self.basefit()
132
+
133
+ if self.poly_res is not None:
134
+ self.re_bcts = np.zeros(self.nblock, dtype=float)
135
+ self.re_bcts_se = np.zeros(self.nblock, dtype=float)
136
+ for i, (l, r) in enumerate(zip(self.edges[:-1], self.edges[1:])):
137
+ x = np.linspace(l, r, 100)
138
+ y, y_se = self.poly.val(x)
139
+ self.re_bcts[i] = np.trapz(y, x)
140
+ self.re_bcts_se[i] = np.sqrt(np.trapz(y_se ** 2, x))
141
+ else:
142
+ self.re_bcts = np.zeros(self.nblock, dtype=float)
143
+ for i, (l, r) in enumerate(zip(self.edges[:-1], self.edges[1:])):
144
+ x = np.linspace(l, r, 100)
145
+ y = self.bl.val(x)
146
+ self.re_bcts[i] = np.trapz(y, x)
147
+
148
+ self.snr = np.zeros_like(self.binsize)
149
+ for i in range(len(self.binsize)):
150
+ cts_i = self.cts[i]
151
+ bcts_i = self.bcts[i]
152
+ try:
153
+ bcts_se_i = self.bcts_se[i]
154
+ except:
155
+ if bcts_i <= 0 or cts_i <= 0:
156
+ snr_i = -5 # bad events
157
+ else:
158
+ snr_i = ppsig(cts_i, bcts_i, 1)
159
+ else:
160
+ if bcts_i <= 0 or cts_i <= 0 or bcts_se_i == 0:
161
+ snr_i = -5 # bad events
162
+ else:
163
+ snr_i = pgsig(cts_i, bcts_i, bcts_se_i)
164
+ self.snr[i] = snr_i
165
+
166
+ self.re_snr = np.zeros_like(self.re_binsize)
167
+ for i in range(len(self.re_binsize)):
168
+ cts_i = self.re_cts[i]
169
+ bcts_i = self.re_bcts[i]
170
+ size_i = self.re_binsize[i]
171
+ alpha = size_i / (20 * self.binsize.mean())
172
+
173
+ if alpha > 1:
174
+ cts_i = cts_i / alpha
175
+ bcts_i = bcts_i / alpha
176
+
177
+ try:
178
+ bcts_se_i = self.re_bcts_se[i]
179
+ except:
180
+ if bcts_i <= 0 or cts_i <= 0:
181
+ snr_i = -5 # bad events
182
+ else:
183
+ snr_i = ppsig(cts_i, bcts_i, 1)
184
+ else:
185
+ if bcts_i <= 0 or cts_i <= 0 or bcts_se_i == 0:
186
+ snr_i = -5 # bad events
187
+ else:
188
+ snr_i = pgsig(cts_i, bcts_i, bcts_se_i)
189
+ self.re_snr[i] = snr_i
190
+
191
+ self.snr_res = {'snr': self.snr, 're_snr': self.re_snr,
192
+ 'cts': self.cts, 'bcts': self.bcts,
193
+ 're_cts': self.re_cts, 're_bcts': self.re_bcts}
194
+
195
+
196
+ def sorting(self, sigma=3):
197
+ if self.snr_res is None: self.calsnr()
198
+
199
+ self.sigma = sigma
200
+ self.re_bkg_idx, self.re_sig_idx, self.re_bad_idx = [], [], []
201
+ self.re_sig_int, self.re_bkg_int, self.re_bad_int = [], [], []
202
+ self.bkg_idx, self.sig_idx, self.bad_idx = [], [], []
203
+ self.sig_int, self.bkg_int, self.bad_int = [], [], []
204
+
205
+ for i, snr_i in enumerate(self.re_snr):
206
+ if snr_i > sigma:
207
+ self.re_sig_idx.append(i)
208
+ self.re_sig_int.append([self.edges[i], self.edges[i+1]])
209
+ elif -5 < snr_i <= sigma:
210
+ self.re_bkg_idx.append(i)
211
+ self.re_bkg_int.append([self.edges[i], self.edges[i+1]])
212
+ else:
213
+ self.re_bad_idx.append(i)
214
+ self.re_bad_int.append([self.edges[i], self.edges[i+1]])
215
+
216
+ for i, snr_i in enumerate(self.snr):
217
+ if snr_i > sigma:
218
+ self.sig_idx.append(i)
219
+ self.sig_int.append([self.lbins[i], self.rbins[i]])
220
+ elif -5 < snr_i <= sigma:
221
+ self.bkg_idx.append(i)
222
+ self.bkg_int.append([self.lbins[i], self.rbins[i]])
223
+ else:
224
+ self.bad_idx.append(i)
225
+ self.bad_int.append([self.lbins[i], self.rbins[i]])
226
+
227
+ self.re_bkg_idx = np.array(self.re_bkg_idx, dtype=int)
228
+ self.re_sig_idx = np.array(self.re_sig_idx, dtype=int)
229
+ self.re_bad_idx = np.array(self.re_bad_idx, dtype=int)
230
+
231
+ self.bkg_idx = np.array(self.bkg_idx, dtype=int)
232
+ self.sig_idx = np.array(self.sig_idx, dtype=int)
233
+ self.bad_idx = np.array(self.bad_idx, dtype=int)
234
+
235
+ self.re_bad_index = []
236
+ for i, (l, u) in enumerate(zip(self.lbins, self.rbins)):
237
+ for low, upp in self.re_bad_int:
238
+ if not (u <= low or l >= upp):
239
+ self.re_bad_index.append(i)
240
+ self.re_bad_index = np.unique(self.re_bad_index).astype(int)
241
+
242
+ self.re_sig_index = []
243
+ for i, (l, u) in enumerate(zip(self.lbins, self.rbins)):
244
+ for low, upp in self.re_sig_int:
245
+ if not (u <= low or l >= upp):
246
+ self.re_sig_index.append(i)
247
+ self.re_sig_index = np.unique(self.re_sig_index).astype(int)
248
+
249
+ self.ignore_int = union(self.re_bad_int + self.re_sig_int)
250
+
251
+ self.sort_res = {'sigma': self.sigma, 'ignore': self.ignore_int,
252
+ 're_bkg': (self.re_bkg_int, self.re_bkg_idx),
253
+ 're_sig': (self.re_sig_int, self.re_sig_idx, self.re_sig_index),
254
+ 're_bad': (self.re_bad_int, self.re_bad_idx, self.re_bad_index)}
255
+
256
+
257
+ def polyfit(self, deg=None):
258
+ if self.ignore is None:
259
+ if self.sort_res is None: self.sorting()
260
+ self.ignore = self.sort_res['ignore']
261
+
262
+ ignore_idx = []
263
+ for i, (l, u) in enumerate(zip(self.lbins, self.rbins)):
264
+ for low, upp in self.ignore:
265
+ if not (u <= low or l >= upp):
266
+ ignore_idx.append(i)
267
+ ignore_idx = np.unique(ignore_idx).astype(int)
268
+
269
+ notice_time = np.delete(self.time, ignore_idx)
270
+ notice_rate = np.delete(self.rate, ignore_idx)
271
+ notice_exp = np.delete(self.exp, ignore_idx)
272
+ # notice_lbins = np.delete(self.lbins, ignore_idx)
273
+ # notice_rbins = np.delete(self.rbins, ignore_idx)
274
+ # notice_binsize = notice_rbins - notice_lbins
275
+
276
+ self.poly = Polynomial.set_method('2pass')
277
+ self.poly.fit(notice_time, notice_rate, deg=deg, dx=notice_exp)
278
+ self.bak, self.bak_se = self.poly.val(self.time)
279
+ # self.bak[self.re_bad_index] = 0
280
+ # self.bak_se[self.re_bad_index] = 0
281
+
282
+ self.bcts = self.bak * self.exp
283
+ self.bcts_se = self.bak_se * self.exp
284
+
285
+ self.poly_res = {'deg': self.poly.deg,
286
+ 'fit': self.poly.ls_res,
287
+ 'bcts': self.bcts,
288
+ 'bcts_se': self.bcts_se,
289
+ 'bak': self.bak,
290
+ 'bak_se': self.bak_se}
291
+
292
+
293
+ def loop(self, sigma=3, deg=None):
294
+ self.calsnr()
295
+ self.sorting(sigma)
296
+ self.polyfit(deg)
297
+
298
+
299
+ def save(self, savepath, suffix=''):
300
+ if not os.path.exists(savepath):
301
+ os.makedirs(savepath)
302
+
303
+ json_dump(self.ini_res, savepath + '/ini_res%s.json'%suffix)
304
+ json_dump(self.base_res, savepath + '/base_res%s.json'%suffix)
305
+ json_dump(self.block_res, savepath + '/block_res%s.json'%suffix)
306
+ json_dump(self.snr_res, savepath + '/snr_res%s.json'%suffix)
307
+ json_dump(self.sort_res, savepath + '/sort_res%s.json'%suffix)
308
+ json_dump(self.poly_res, savepath + '/poly_res%s.json'%suffix)
309
+
310
+ rcParams['font.family'] = 'serif'
311
+ rcParams['font.sans-serif'] = 'Georgia'
312
+ rcParams['font.size'] = 12
313
+ rcParams['pdf.fonttype'] = 42
314
+
315
+ fig, ax = plt.subplots(1, 1, figsize=(8, 5))
316
+ ax.plot(self.time, self.rate, lw=1.0, c='b', label='Light curve')
317
+ ax.plot(self.edges, np.append(self.re_cts/self.re_binsize, [(self.re_cts/self.re_binsize)[-1]]),
318
+ lw=1.0, c='c', drawstyle='steps-post', label='Bayesian block')
319
+ ax.plot(self.time, self.bak, lw=1.0, c='r', label='Background')
320
+ ax.fill_between(self.time, self.bak-self.bak_se, self.bak+self.bak_se, facecolor='red', alpha=0.5)
321
+ ax.set_xlim([min(self.time), max(self.time)])
322
+ ax.set_xlabel('Time')
323
+ ax.set_ylabel('Rate')
324
+ ax.minorticks_on()
325
+ ax.tick_params(axis='x', which='both', direction='in', labelcolor='k', colors='k')
326
+ ax.tick_params(axis='y', which='both', direction='in', labelcolor='k', colors='k')
327
+ ax.tick_params(which='major', width=1.0, length=5)
328
+ ax.tick_params(which='minor', width=1.0, length=3)
329
+ ax.xaxis.set_ticks_position('both')
330
+ ax.yaxis.set_ticks_position('both')
331
+ ax.legend(frameon=False)
332
+ fig.savefig(savepath + '/bs%s.pdf'%suffix, bbox_inches='tight', pad_inches=0.1, dpi=300)
333
+ plt.close(fig)
334
+
335
+ fig, ax = plt.subplots(1, 1, figsize=(8, 5))
336
+ p1, = ax.plot(self.time, self.rate - self.bak, lw=1.0, c='k', label='Net light curve')
337
+ ax.set_xlim([min(self.time), max(self.time)])
338
+ ax.set_xlabel('Time')
339
+ ax.set_ylabel('Rate')
340
+ ax.minorticks_on()
341
+ ax.tick_params(axis='x', which='both', direction='in', labelcolor='k', colors='k')
342
+ ax.tick_params(axis='y', which='both', direction='in', labelcolor='k', colors='k')
343
+ ax.tick_params(which='major', width=1.0, length=5)
344
+ ax.tick_params(which='minor', width=1.0, length=3)
345
+ ax.xaxis.set_ticks_position('both')
346
+ ax.yaxis.set_ticks_position('both')
347
+
348
+ ax1 = ax.twinx()
349
+ p2, = ax1.plot(self.time, self.snr, lw=1.0, c='b', label='SNR', drawstyle='steps-mid')
350
+ p3, = ax1.plot(self.edges, np.append(self.re_snr, [self.re_snr[-1]]), lw=1.0, c='c',
351
+ label='Bayesian block SNR', drawstyle='steps-post')
352
+ p4 = ax1.axhline(self.sigma, lw=1.0, c='grey', ls='--', label='%.1f$\\sigma$' % self.sigma)
353
+ ax1.set_xlim([min(self.time), max(self.time)])
354
+ ax1.set_ylabel('SNR')
355
+
356
+ plt.legend(handles=[p1, p2, p3, p4], frameon=False)
357
+ fig.savefig(savepath + '/snr%s.pdf'%suffix, bbox_inches='tight', pad_inches=0.1, dpi=300)
358
+ plt.close(fig)
359
+
360
+ fig, ax = plt.subplots(1, 1, figsize=(8, 5))
361
+ colors = []
362
+ for i in range(len(self.re_binsize)):
363
+ if i in self.re_sig_idx: colors.append('m')
364
+ if i in self.re_bkg_idx: colors.append('b')
365
+ if i in self.re_bad_idx: colors.append('k')
366
+ ax.bar((self.edges[:-1]+self.edges[1:])/2, self.re_cts/self.re_binsize, bottom=0, width=self.re_binsize, color=colors)
367
+ ax.plot(self.time, self.bak, lw=1.0, c='r')
368
+ ax.fill_between(self.time, self.bak-self.bak_se, self.bak+self.bak_se, facecolor='red', alpha=0.5)
369
+ ax.set_xlim([min(self.time), max(self.time)])
370
+ ax.set_xlabel('Time')
371
+ ax.set_ylabel('Rate')
372
+ ax.minorticks_on()
373
+ ax.tick_params(axis='x', which='both', direction='in', labelcolor='k', colors='k')
374
+ ax.tick_params(axis='y', which='both', direction='in', labelcolor='k', colors='k')
375
+ ax.tick_params(which='major', width=1.0, length=5)
376
+ ax.tick_params(which='minor', width=1.0, length=3)
377
+ ax.xaxis.set_ticks_position('both')
378
+ ax.yaxis.set_ticks_position('both')
379
+ fig.savefig(savepath + '/sort%s.pdf'%suffix, bbox_inches='tight', pad_inches=0.1, dpi=300)
380
+ plt.close(fig)
381
+
382
+
383
+ # def save(self, savepath, suffix=''):
384
+ # if not os.path.exists(savepath):
385
+ # os.makedirs(savepath)
386
+
387
+ # json_dump(self.ini_res, savepath + '/ini_res%s.json'%suffix)
388
+ # json_dump(self.base_res, savepath + '/base_res%s.json'%suffix)
389
+ # json_dump(self.block_res, savepath + '/block_res%s.json'%suffix)
390
+ # json_dump(self.snr_res, savepath + '/snr_res%s.json'%suffix)
391
+ # json_dump(self.sort_res, savepath + '/sort_res%s.json'%suffix)
392
+ # json_dump(self.poly_res, savepath + '/poly_res%s.json'%suffix)
393
+
394
+ # rcParams['font.family'] = 'serif'
395
+ # rcParams['font.sans-serif'] = 'Georgia'
396
+ # rcParams['font.size'] = 12
397
+ # rcParams['pdf.fonttype'] = 42
398
+
399
+ # fig, ax = plt.subplots(1, 2, figsize=(12, 5))
400
+ # ax[0].plot(self.time, self.rate, lw=1.0, c='b', label='Light curve')
401
+ # ax[0].plot(self.time, self.base_res['bak'], lw=1.0, c='g', label='Baseline')
402
+ # ax[0].plot(self.time, self.bak, lw=1.0, c='r', label='Polynomial')
403
+ # ax[0].set_xlim([min(self.time), max(self.time)])
404
+ # ax[0].set_xlabel('Time')
405
+ # ax[0].set_ylabel('Rate')
406
+ # ax[0].minorticks_on()
407
+ # ax[0].tick_params(axis='x', which='both', direction='in', labelcolor='k', colors='k')
408
+ # ax[0].tick_params(axis='y', which='both', direction='in', labelcolor='k', colors='k')
409
+ # ax[0].tick_params(which='major', width=1.0, length=5)
410
+ # ax[0].tick_params(which='minor', width=1.0, length=3)
411
+ # ax[0].xaxis.set_ticks_position('both')
412
+ # ax[0].yaxis.set_ticks_position('both')
413
+ # ax[0].legend(frameon=False)
414
+
415
+ # p1, = ax[1].plot(self.time, self.rate - self.bak, lw=1.0, c='b', label='Net light curve')
416
+ # ax[1].set_xlim([min(self.time), max(self.time)])
417
+ # ax[1].set_xlabel('Time')
418
+ # ax[1].set_ylabel('Rate')
419
+ # ax[1].minorticks_on()
420
+ # ax[1].tick_params(axis='x', which='both', direction='in', labelcolor='k', colors='k')
421
+ # ax[1].tick_params(axis='y', which='both', direction='in', labelcolor='k', colors='k')
422
+ # ax[1].tick_params(which='major', width=1.0, length=5)
423
+ # ax[1].tick_params(which='minor', width=1.0, length=3)
424
+ # ax[1].xaxis.set_ticks_position('both')
425
+ # ax[1].yaxis.set_ticks_position('both')
426
+
427
+ # ax1 = ax[1].twinx()
428
+ # p3, = ax1.plot(self.edges, np.append(self.re_snr, [self.re_snr[-1]]), lw=1.0, c='r',
429
+ # label='Bayesian block SNR', drawstyle='steps-post')
430
+ # p4 = ax1.axhline(self.sigma, lw=1.0, c='g', ls='--', label='%.1f$\\sigma$' % self.sigma)
431
+ # ax1.set_xlim([min(self.time), max(self.time)])
432
+ # ax1.set_ylabel('SNR')
433
+ # ax1.set_ylim([-6, 26])
434
+
435
+ # ax[1].legend(handles=[p1, p3, p4], frameon=False)
436
+ # fig.savefig(savepath + '/bs%s.pdf'%suffix, bbox_inches='tight', pad_inches=0.1, dpi=300)
437
+ # plt.close(fig)
@@ -0,0 +1,266 @@
1
+ import warnings
2
+ import numpy as np
3
+
4
+
5
+
6
+ class Polynomial(object):
7
+
8
+ def __init__(self):
9
+ pass
10
+
11
+
12
+ @classmethod
13
+ def set_method(cls, method='2pass'):
14
+ if method == '2pass':
15
+ pass
16
+ # print(
17
+ # '''
18
+ # +-----------------+-----------+
19
+ # | polyfit method | 2pass |
20
+ # +-----------------+-----------+
21
+ # ''')
22
+ else:
23
+ raise ValueError('invalid method')
24
+
25
+ cls_ = cls()
26
+ cls_.method = method
27
+ return cls_
28
+
29
+
30
+ def fit(self, x, y, deg=None, dx=None):
31
+ self.x = np.array(x).astype(float)
32
+ self.y = np.array(y).astype(float)
33
+ self.deg = deg
34
+ self.dx = dx
35
+
36
+ self.ls_res = None
37
+ self.mo = None
38
+ self.se = None
39
+
40
+ if self.method == '2pass':
41
+ self.two_pass()
42
+ else:
43
+ raise ValueError('invalid method')
44
+
45
+
46
+ def val(self, x):
47
+ x = np.array(x)
48
+
49
+ if min(x) < min(self.x) or max(x) > max(self.x):
50
+ msg = "External interpolation may be imprecise"
51
+ warnings.warn(msg, InterpWarning, stacklevel=2)
52
+
53
+ assert self.ls_res is not None, 'you should first perform fitting'
54
+
55
+ mo, se = self.ls_polyval(x, coeff=self.ls_res['coeff'], covar=self.ls_res['covar'])
56
+ return mo, se
57
+
58
+
59
+ def two_pass(self):
60
+ # Two-pass fitting
61
+ # First pass donot use the variances (i.e. uniform weight)
62
+ # GBM and GECAM: First pass uses the data variances calculated from data rates
63
+ # Second pass uses the data variances calculated from model rates
64
+ # 1) rate * livetime = counts
65
+ # 2) variance of counts = counts
66
+ # 3) variance of rate = variance of counts/livetime^2 = rate/livetime
67
+ time = self.x
68
+ rate = self.y
69
+
70
+ if self.deg is None:
71
+ if len(time) <= 15:
72
+ self.deg = 0
73
+ elif 15 < len(time) <= 30:
74
+ self.deg = 1
75
+ elif 30 < len(time) <= 60:
76
+ self.deg = 2
77
+ else:
78
+ self.deg = 3
79
+
80
+ if self.dx is None:
81
+ dt = time[1] - time[0]
82
+ else:
83
+ dt = np.array(self.dx)
84
+ if dt.ndim != 0 and dt.shape != time.shape:
85
+ raise TypeError("if dt is array, expected dt and time to have same length")
86
+
87
+ variance = rate / dt
88
+ zero = (variance <= 0)
89
+ weight = np.piecewise(variance,
90
+ condlist=[zero, ~zero],
91
+ funclist=[lambda var: 1.0, lambda var: 1.0]) # uniform weight
92
+
93
+ for ipass in range(2):
94
+ self.ls_res = self.ls_polyfit(time, rate, self.deg, w=weight, cov=True)
95
+ self.mo, self.se = self.ls_polyval(time, coeff=self.ls_res['coeff'], covar=self.ls_res['covar'])
96
+
97
+ if ipass == 0:
98
+ variance = self.mo / dt
99
+ zero = (variance <= 0)
100
+ weight = np.piecewise(variance,
101
+ condlist=[zero, ~zero],
102
+ funclist=[lambda var: 0.0, lambda var: np.sqrt(1 / var)])
103
+
104
+
105
+ @staticmethod
106
+ def ls_polyval(x, coeff, covar=None):
107
+ if x.ndim != 1:
108
+ raise TypeError("expected 1D vector for x")
109
+ if x.size == 0:
110
+ raise TypeError("expected non-empty vector for x")
111
+ if coeff.ndim != 1:
112
+ raise TypeError("expected 1D vector for coeff")
113
+ if coeff.size < 1:
114
+ raise TypeError("expected coeff.size >= 1")
115
+
116
+ order = coeff.shape[0]
117
+
118
+ # set up least squares equation for powers of x
119
+ lhs = np.vander(x, order)
120
+
121
+ # evaluate the model values at given x
122
+ mo = coeff @ lhs.T
123
+ # or
124
+ # mo = np.zeros_like(x)
125
+ # for ci in coeff:
126
+ # mo = mo * x + ci
127
+
128
+ # mo[mo < 0] = 0
129
+
130
+ if covar is not None:
131
+ if covar.ndim != 2:
132
+ raise TypeError("expected 2D vector for covar")
133
+ if covar.shape[0] != covar.shape[1]:
134
+ raise TypeError("expected m*m matrix for covar")
135
+ if covar.shape[0] != order:
136
+ raise TypeError("expected each dim of covar and coeff have same length")
137
+
138
+ # evaluate the model uncertainty at given x
139
+ # M (i.e. var) = X M_\beta (i.e. covar) X^T
140
+ var = lhs @ covar @ lhs.T
141
+ se = np.sqrt(np.diag(var))
142
+
143
+ return mo, se
144
+
145
+ else:
146
+ return mo
147
+
148
+
149
+ @staticmethod
150
+ def ls_polyfit(x, y, deg, rcond=None, w=None, cov=True) -> dict:
151
+ """
152
+ Parameters
153
+ ----------
154
+ x: array_like, shape (M,)
155
+ y: array_like, shape (M,)
156
+ deg: int, degree of the fitting polynomial
157
+ rcond: float, optional
158
+ w: array_like, shape (M,), optional, w[i] = 1/sigma(y[i])
159
+ cov: bool or str, optional
160
+ #-------------------------#
161
+ #see np.polyfit for details#
162
+ #-------------------------#
163
+ Returns
164
+ -------
165
+ coeff: polynomial coefficients
166
+ resids: sum of squared residuals of the least squares fit
167
+ rank: the effective rank of the scaled Vandermonde coefficient matrix
168
+ svs: singular values of the scaled Vandermonde coefficient matrix
169
+ covar: the covariance matrix of the polynomial coefficient estimates
170
+ """
171
+ if x.ndim != 1 or y.ndim != 1:
172
+ raise TypeError("expected 1D vector for x and y")
173
+ if x.size == 0 or y.size == 0:
174
+ raise TypeError("expected non-empty vector for x and y")
175
+ if x.shape != y.shape:
176
+ raise TypeError("expected x and y to have same length")
177
+ if deg < 0:
178
+ raise ValueError("expected deg >= 0")
179
+
180
+ order = int(deg) + 1
181
+
182
+ if (y == 0).all():
183
+ coeff = np.full(order, 0.0)
184
+ res = {'coeff': coeff}
185
+ if cov:
186
+ covar = np.full((order, order), 0.0)
187
+ res['covar'] = covar
188
+ return res
189
+
190
+ if rcond is None:
191
+ rcond = len(x) * np.finfo(x.dtype).eps
192
+
193
+ # set up least squares equation for powers of x
194
+ lhs = np.vander(x, order)
195
+ rhs = y + 0.0 # to avoid to change y
196
+
197
+ # apply weighting
198
+ if w is not None:
199
+ if w.ndim != 1:
200
+ raise TypeError("expected a 1-d array for weights")
201
+ if w.shape != y.shape:
202
+ raise TypeError("expected w and y to have the same length")
203
+ else:
204
+ w = np.ones_like(y)
205
+
206
+ dof = np.sum(w != 0) - order
207
+ if dof <= 0:
208
+ msg = 'The degree of freedom should be great than zero'
209
+ warnings.warn(msg, DofWarning, stacklevel=2)
210
+
211
+ # X' = diag(w)X, see "Weighted least squares" in Wikipedia for details
212
+ lhs *= w[:, np.newaxis]
213
+ # y' = diag(w)y, see "Weighted least squares" in Wikipedia for details
214
+ rhs *= w
215
+
216
+ # scale lhs to improve condition number and solve
217
+ scale = np.sqrt((lhs * lhs).sum(axis=0))
218
+ lhs /= scale
219
+ # solve WX@\beta = Wy, minimize sum((w*yi - w*f(xi, \beta))^2)
220
+ # ==> X^TWy = (X^TWX)\beta ==> X'^Ty' = (X'^TX')\beta (uncorrelated w=sqrt(W))
221
+ # see "Weighted least squares" in Wikipedia for details
222
+ coeff, resids, rank, svs = np.linalg.lstsq(lhs, rhs, rcond)
223
+ # broadcast scale coefficients
224
+ coeff = coeff / scale
225
+
226
+ # warn on rank reduction, which indicates an ill conditioned matrix
227
+ if rank != order:
228
+ msg = "Polyfit may be poorly conditioned"
229
+ warnings.warn(msg, RankWarning, stacklevel=2)
230
+
231
+ res = {'coeff': coeff, 'chi2': resids, 'rank': rank, 'svs': svs, 'rcond': rcond, 'dof': dof}
232
+
233
+ if cov:
234
+ # M^\beta (i.e. covar) = (X^TWX)^{-1} = (X'^TX)^{-1}
235
+ # see "Weighted least squares" in Wikipedia for details
236
+ covar = np.linalg.inv(np.dot(lhs.T, lhs))
237
+ covar /= np.outer(scale, scale)
238
+ if cov == "unscaled":
239
+ fac = 1
240
+ else:
241
+ fac = resids / dof
242
+ covar *= fac
243
+ res['covar'] = covar
244
+
245
+ return res
246
+
247
+
248
+ class RankWarning(UserWarning):
249
+ """
250
+ Issued by self.ls_polyfit when the Vandermonde matrix is rank deficient.
251
+ """
252
+ pass
253
+
254
+
255
+ class InterpWarning(UserWarning):
256
+ """
257
+ Issued by self.val for External interpolation.
258
+ """
259
+ pass
260
+
261
+
262
+ class DofWarning(UserWarning):
263
+ """
264
+ Issued by self.ls_polyfit for dof < 0.
265
+ """
266
+ pass