-
Notifications
You must be signed in to change notification settings - Fork 1
/
pyirc.py
1665 lines (1500 loc) · 66.8 KB
/
pyirc.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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import sys
import numpy
import scipy
import astropy
from astropy.io import fits
import scipy.stats
import scipy.ndimage
import fitsio
import copy
import warnings
from fitsio import FITS,FITSHDR
from ftsolve import center,decenter,solve_corr,solve_corr_many,solve_corr_vis,solve_corr_vis_many,pad_to_N
from scipy.signal import correlate2d,fftconvolve
# <== TESTING PARAMETERS ONLY ==>
#
# [these are false and should only be set to true for debugging purposes]
Test_SubBeta = False
# <== THESE FUNCTIONS DEPEND ON THE FORMAT OF THE INPUT FILES ==>
# Version number of script
def get_version():
return 36
# Function to get array size from format codes in load_segment
# (Note: for WFIRST this will be 4096, but we want the capability to
# run this script on H1/H2RG data.)
#
def get_nside(formatpars):
if formatpars==1: return 4096
if formatpars==2: return 2048
if formatpars==3: return 4096
if formatpars==4: return 4096
if formatpars==5: return 4096
if formatpars==6: return 4096
if formatpars==7: return 2048
# Get number of time slices
def get_num_slices(formatpars, filename):
# Switch based on input format
if formatpars==1 or formatpars==2 or formatpars==5:
hdus = fits.open(filename)
ntslice = int(hdus[0].header['NAXIS3'])
hdus.close()
elif formatpars==3 or formatpars==7:
hdus = fits.open(filename)
ntslice = len(hdus)-1
hdus.close()
elif formatpars==4 or formatpars==6:
hdus = fits.open(filename)
ntslice = int(hdus[1].header['NAXIS3'])
hdus.close()
else:
print ('Error! Invalid formatpars =', formatpars)
exit()
return ntslice
# Function to load an image segment
#
# filename = name of the source FITS file
# formatpars = integer describing which type of format to use
# format 1: H4RG, all data in a single HDU, ramp slope positive (ex. DCL H4RG-18237 data)
# xyrange = list [xmin,xmax,ymin,ymax] (first row/col are zero) -- EXcluding xmax and ymax!
# tslices = list of time slices to use (first is *1*)
# verbose = True or False (use True only for de-bugging)
#
# Returns a 3D array of dimension number tslices, ymax-ymin, xmax-xmin
#
def load_segment(filename, formatpars, xyrange, tslices, verbose):
if verbose: print ('Reading:', filename)
# Recommended True (False defaults to astropy tools, which work but are slow because of the way this script works)
use_fitsio = True
# Get dimensions of output cube
nxuse = xyrange[1]-xyrange[0]
nyuse = xyrange[3]-xyrange[2]
ntslice_use = len(tslices)
output_cube = numpy.zeros((ntslice_use, nyuse, nxuse))
# Switch based on input format
if formatpars==1 or formatpars==2 or formatpars==5:
if use_fitsio:
fileh = fitsio.FITS(filename)
N = get_nside(formatpars)
for ts in range(ntslice_use):
t = tslices[ts]
if ts>0 and tslices[ts]==tslices[ts-1]:
output_cube[ts,:,:] = output_cube[ts-1,:,:] # don't read this slice again
else:
output_cube[ts,:,:] = 65535 - numpy.array(fileh[0][t-1, xyrange[2]:xyrange[3], xyrange[0]:xyrange[1]])
fileh.close()
else:
hdus = fits.open(filename)
in_hdu = hdus[0]
ntslice = in_hdu.data.shape[0]
if verbose:
print ('input shape -> ', in_hdu.data.shape)
print ('number of slices =', ntslice, ', used =', ntslice_use)
for ts in range(ntslice_use):
t = tslices[ts]
output_cube[ts,:,:] = 65535 - in_hdu.data[t-1, xyrange[2]:xyrange[3], xyrange[0]:xyrange[1]]
hdus.close()
elif formatpars==3 or formatpars==7:
if use_fitsio:
fileh = fitsio.FITS(filename)
N = get_nside(formatpars)
for ts in range(ntslice_use):
t = tslices[ts]
output_cube[ts,:,:] = numpy.array(fileh[t][xyrange[2]:xyrange[3], xyrange[0]:xyrange[1]])
fileh.close()
else:
print ('Error: non-fitsio methods not yet supported for formatpars=3 or 7')
exit()
elif formatpars==4:
if use_fitsio:
fileh = fitsio.FITS(filename)
N = get_nside(formatpars)
for ts in range(ntslice_use):
t = tslices[ts]
if ts>=1 and t==tslices[ts-1]:
output_cube[ts,:,:] = output_cube[ts-1,:,:] # asked for same slice again
else:
output_cube[ts,:,:] = numpy.array(fileh[1][0, t-1, xyrange[2]:xyrange[3], xyrange[0]:xyrange[1]])
fileh.close()
else:
print ('Error: non-fitsio methods not yet supported for formatpars=4')
exit()
elif formatpars==5:
if use_fitsio:
fileh = fitsio.FITS(filename)
N = get_nside(formatpars)
for ts in range(ntslice_use):
t = tslices[ts]
if ts>=1 and t==tslices[ts-1]:
output_cube[ts,:,:] = output_cube[ts-1,:,:] # asked for same slice again
else:
output_cube[ts,:,:] = numpy.array(fileh[0][t-1, xyrange[2]:xyrange[3], xyrange[0]:xyrange[1]])
fileh.close()
else:
print ('Error: non-fitsio methods not yet supported for formatpars=5')
exit()
elif formatpars==6:
if use_fitsio:
fileh = fitsio.FITS(filename)
N = get_nside(formatpars)
for ts in range(ntslice_use):
t = tslices[ts]
if ts>=1 and t==tslices[ts-1]:
output_cube[ts,:,:] = output_cube[ts-1,:,:] # asked for same slice again
else:
output_cube[ts,:,:] = 65535 - numpy.array(fileh[1][0, t-1, xyrange[2]:xyrange[3], xyrange[0]:xyrange[1]])
fileh.close()
else:
print ('Error: non-fitsio methods not yet supported for formatpars=6')
exit()
else:
print ('Error! Invalid formatpars =', formatpars)
exit()
return output_cube
# <== FUNCTIONS BELOW HERE ARE INDEPENDENT OF THE INPUT FORMAT ==>
# Dictionary of indices
# These are designed for consistency with the outputs lists of certain functions
class IndexDictionary:
def __init__(self, itype):
# basic characterization parameter index list -- outputs for "basic" function
if itype==0:
self.Nb = 11 # number of basic parameters
#
self.ngood = 0
self.graw = 1
self.gacorr = 2
self.g = 3
self.alphaH = 4
self.alphaV = 5
self.beta = 6
self.I = 7
self.alphaD = 8
self.tCH = 9
self.tCV = 10
#
# polychar indices: output is list [1, ***, residual]
# intermediate terms are basic output [ind1:ind2]
self.ind1 = 3
self.ind2 = 9
self.indp1 = 1
self.indp2 = self.indp1 + self.ind2-self.ind1
#
self.N = self.Nbb = self.Nb
# adds BFE kernel, (2s+1) x (2s+1)
def addbfe(self, s):
self.s = s
self.ker0 = self.Nb + 2*s*(s+1) # BFE (0,0) kernel index
self.Nbb += (2*s+1)*(2*s+1)
self.N += (2*s+1)*(2*s+1)
# adds higher-order non-linearity coefficients (p coefs, for total degree 1+p)
def addhnl(self, p):
self.p = p
self.N += p
swi = IndexDictionary(0)
# Routine to get percentile cuts with a mask removed
# disc flag if True (default) tells the code to interpolate based on the assumption
# that the input data are integers
#
# mask consists of 0's and 1's and is the same size as this_array
def pyIRC_percentile(this_array, mask, perc, disc=True):
val = this_array.flatten()
ma = mask.flatten()
w = numpy.array([val[x] for x in numpy.where(ma>.5)])
n = numpy.size(w)
if disc:
ctr = numpy.percentile(w,perc)
n1 = numpy.count_nonzero(w<ctr-.499999)
n2 = numpy.count_nonzero(w<=ctr+.499999)
assert n1<=n2
if n1==n2: return(ctr)
dctr = (perc/100.*n-(n1+n2)/2.)/float(n2-n1)
return(ctr + dctr)
#w -= numpy.modf(numpy.linspace(0,(1.+numpy.sqrt(5.))/2*(n-1), num=n))[0] - .5
return numpy.percentile(w,perc)
# Routine to get mean with a mask removed
def pyIRC_mean(this_array, mask):
val = this_array.flatten()
ma = mask.flatten()
w = numpy.array([val[x] for x in numpy.where(ma>.5)])
return numpy.mean(w)
# Get reference corrections from left & right pixel sets
# yrange = [ymin,ymax] (inclusive)
#
# Output depends on the length of tslices:
# elements 0 .. ntslice_use-1 -> median of that time slice
# elements ntslice_use .. 2*ntslice_use-1 -> median of (first) - (this slice)
# (if ntslice_use>=2) then
# element 2*ntslice_use -> median of [(-2) - (-1)] - [(0) - (1)] (otherwise this is 0)
# [this is really used to measure curvature of the reference pixel ramp]
#
# output always has length 2*ntslice_use+1
#
def ref_corr(filename, formatpars, yrange, tslices, verbose):
# Side length of the array (needed to find reference pixel indexing)
N = get_nside(formatpars)
# Number of time slices
ntslice_use = len(tslices)
# Clear list
output_ref = []
# Build arrays of reference pixels
my_array_band = load_segment(filename, formatpars, [0,N]+yrange, tslices, False)
my_array_L = my_array_band[:,:,:4]
my_array_R = my_array_band[:,:,-4:]
#my_array_L = load_segment(filename, formatpars, [0,4]+yrange, tslices, False)
#my_array_R = load_segment(filename, formatpars, [N-4,N]+yrange, tslices, False)
my_array_LR = numpy.concatenate((my_array_L, my_array_R), axis=2)
if verbose: print (N, my_array_LR.shape)
for ts in range(ntslice_use):
output_ref.append(numpy.median(my_array_LR[ts,:,:]))
for ts in range(ntslice_use):
diff_array = my_array_LR[0,:,:] - my_array_LR[ts,:,:]
output_ref.append(numpy.median(diff_array))
if ntslice_use>1:
diff_array = my_array_LR[ntslice_use-2,:,:] - my_array_LR[ntslice_use-1,:,:]\
-(my_array_LR[0,:,:]-my_array_LR[1,:,:])*(tslices[-1]-tslices[-2])/float(tslices[1]-tslices[0])
output_ref.append(numpy.median(diff_array))
else:
output_ref.append(0)
return output_ref
#
# Get reference corrections from left & right pixel sets
# for a full list of files.
# ny = number of y-bins (e.g. 32 for an H4RG and regions of 128 pixel size in y-direction)
#
# Output depends on the length of tslices:
# elements 0 .. ntslice_use-1 -> median of that time slice
# elements ntslice_use .. 2*ntslice_use-1 -> median of (first) - (this slice)
# (if ntslice_use>=2) then
# element 2*ntslice_use -> median of [(-2) - (-1)] - [(0) - (1)] (otherwise this is 0)
# [this is really used to measure curvature of the reference pixel ramp]
#
# output is stored in a numpy array of size num_files, ny, 2*ntslice_use+1
#
def ref_array(filelist, formatpars, ny, tslices, verbose):
num_files = len(filelist)
ntslice_use = len(tslices)
output_array = numpy.zeros((num_files, ny, 2*ntslice_use+1))
dy = get_nside(formatpars)//ny
for ifile in range(num_files):
for iy in range(ny):
ymin = dy*iy
ymax = ymin+dy
output_array[ifile, iy, :] = numpy.asarray(ref_corr(filelist[ifile], formatpars, [ymin,ymax], tslices, False))
if verbose:
print (ifile, iy)
print (output_array[ifile, iy, :])
return(output_array)
#
# Similar but if we only need one row (iy) to be good
# *** Only use this function if you are absolutely sure of what you need!
def ref_array_onerow(filelist, formatpars, iy, ny, tslices, verbose):
num_files = len(filelist)
ntslice_use = len(tslices)
output_array = numpy.zeros((num_files, ny, 2*ntslice_use+1))
dy = get_nside(formatpars)//ny
for ifile in range(num_files):
ymin = dy*iy
ymax = ymin+dy
output_array[ifile, iy, :] = numpy.asarray(ref_corr(filelist[ifile], formatpars, [ymin,ymax], tslices, False))
if verbose:
print (ifile, iy)
print (output_array[ifile, iy, :])
return(output_array)
#
# similar but uses a user-specified range of y-values, and output lacks the 'iy' index
# (i.e. is 2D array)
def ref_array_block(filelist, formatpars, yrange, tslices, verbose):
num_files = len(filelist)
ntslice_use = len(tslices)
output_array = numpy.zeros((num_files, 2*ntslice_use+1))
if len(yrange)<2:
print ('Error in ref_array_block: yrange =', yrange)
exit()
for ifile in range(num_files):
ymin = yrange[0]
ymax = yrange[1]
output_array[ifile, :] = numpy.asarray(ref_corr(filelist[ifile], formatpars, [ymin,ymax], tslices, False))
if verbose:
print (ifile)
print (output_array[ifile, :])
return(output_array)
# Generate a 4D date cube containing information on a region of the detector
#
# filename = name of the source FITS file
# formatpars = integer describing which type of format to use
# format 1: H4RG, all data in a single HDU, ramp slope positive (ex. DCL H4RG-18237 data)
# xyrange = list [xmin,xmax,ymin,ymax] (first row/col are zero) -- EXcluding xmax and ymax!
# tslices = list of time slices to use (first is *1*)
# maskinfo = information on how the masking works (list format, if not enough elements goes to default)
# maskinfo[0] = range around median to accept (default: 0.1, must be within 10% of median)
# maskinfo[1] = boolean, mask assuming light exposure (default: True)
#
# verbose = True or False (use True only for de-bugging)
#
# Returns a 4D array of dimension number of files +1, number tslices, ymax-ymin, xmax-xmin
# the *last* "file" is the mask (0 or 1)
#
def pixel_data(filelist, formatpars, xyrange, tslices, maskinfo, verbose):
# Masking parameters
cut_offset = 0.1
if len(maskinfo)>=1: cut_offset = maskinfo[0]
do_mask = True
if len(maskinfo)>=2: do_mask = maskinfo[1]
num_files = len(filelist)
ntslice_use = len(tslices)
output_array = numpy.zeros((num_files+1, ntslice_use, xyrange[3]-xyrange[2], xyrange[1]-xyrange[0]))
for ifile in range(num_files):
output_array[ifile,:,:,:] = load_segment(filelist[ifile], formatpars, xyrange, tslices, verbose)
# Generate mean CDS image and consider the median
mCDS = numpy.mean(output_array[0:num_files,0,:,:], axis=0) - numpy.mean(output_array[0:num_files,-1,:,:], axis=0)
mCDS_med = numpy.median(mCDS)
if do_mask:
a = (1./mCDS_med)*mCDS
goodmap = numpy.where(numpy.logical_and(a>1-cut_offset,a<1+cut_offset),1,0)
else:
goodmap = numpy.ones_like(mCDS)
for f in range(num_files):
for t in range(ntslice_use):
goodmap *= numpy.where(output_array[f,t,:,:]>0,1,0)
if verbose:
print ('Median =', mCDS_med, 'cut_offset =', cut_offset)
print (goodmap)
print (goodmap.shape)
# Copy map of good pixels into the output
for t in range(ntslice_use):
output_array[num_files,t,:,:] = goodmap
return output_array
# Routine to get nonlinearity curve
# Inputs:
# filelist <- list of 'light' files
# formatpars <- format type for file
# timeslice <- integer (does frames 1 .. tmax) or list [tref,t1,t2], uses t1 ... t2 with reset at tref
# ngrid <- number of cells, list [ny,nx]
# Ib <- shouldn't need this except for de-bugging (forces a specific quadratic fit)
# usemode <- 'dev' (deviation from beta fit) or 'abs' (absolute -- zero of time is absolute)
# verbose <- Boolean
#
# Output:
# signal, fit, derivative [, coefs]
# array of dimensions [tmax, ny, nx] containing reference corrected signal (in DN)
# This is median within a file, followed by the mean.
# The second and third outputs have the same shape as the first:
# 2nd is a polynomial fit
# 3rd is a corrected derivative (in DN/frame)
# The polynomial coefficients are reported as coefs (ascending order: t^0, then t^1 ...) in 'abs' mode,
# and as a data cube [order+1, ny, nx]
def gen_nl_cube(filelist, formatpars, timeslice, ngrid, Ib, usemode, verbose):
# Extract basic information
nfiles = len(filelist)
nx = ngrid[1]; ny = ngrid[0]
N = get_nside(formatpars)
dx = N//nx; dy = N//ny
# Check whether we have a list or single slice
if isinstance(timeslice, list):
tref = timeslice[0]
tmin = timeslice[1]
tmax = timeslice[2]
nt = tmax-tmin+1
else:
tref = 0
tmin = 1
nt = tmax = timeslice
output_array = numpy.zeros((nt, ny, nx))
temp_array = numpy.zeros((nfiles, ny, nx))
# order of polynomial fit per pixel
my_order = 5
if usemode=='abs': my_order = swi.p
if verbose:
print ('Nonlinear cube:')
sys.stdout.write(' reference pixel extraction ...'); sys.stdout.flush()
# Extract reference information
# Now ref_signal[ifile, iy, it] contains it_th time slice of group iy of ref pixels in file ifile
ref_signal = ref_array(filelist, formatpars, ny, range(tmin,tmax+1), False)
if verbose:
print (' done.')
sys.stdout.write('Time slices:'); sys.stdout.flush()
# Now loop over times
for t in range(tmin,tmax+1):
temp_array[:,:,:] = 0.
if verbose:
sys.stdout.write(' {:2d}'.format(t)); sys.stdout.flush()
for ifile in range(nfiles):
val = load_segment(filelist[ifile], formatpars, [0,N,0,N], [1,t], False) # make 2D array
valc = val[1,:,:] - val[0,:,:]
for iy in range(ny):
for ix in range(nx):
temp_array[ifile,iy,ix] = numpy.median(valc[dy*iy:dy*(iy+1), dx*ix:dx*(ix+1)])\
- (ref_signal[ifile, iy, t-tmin] - ref_signal[ifile, iy, 0])
output_array[t-tmin,:,:] = -numpy.mean(temp_array,axis=0)
# <-- note: we flipped the sign so that the signal is positive
if verbose: print ('')
# Make fit and derivatives
coefs_array = numpy.zeros((my_order+1, ny, nx))
fit_array = numpy.zeros_like(output_array)
deriv_array = numpy.zeros_like(output_array)
for iy in range(ny):
for ix in range(nx):
p = numpy.poly1d(numpy.polyfit(numpy.asarray(range(tmin-tref,tmax+1-tref)), output_array[:,iy,ix], my_order))
# p = numpy.poly1d([-Ib[iy,ix],1,0]) # <-- force proportional to beta-model (if not commented; for debugging only)
q=numpy.poly1d.deriv(p)
fit_array[:,iy,ix] = p(range(tmin-tref,tmax+1-tref))
deriv_array[:,iy,ix] = q(range(tmin-tref,tmax+1-tref))
coefs_array[:p.order+1,iy,ix] = p.c[::-1]
if usemode=='dev':
return output_array, fit_array, deriv_array
else:
return output_array, fit_array, deriv_array, coefs_array
# Routine to estimate the fractional gain error,
# log( gain[full NL] / gain[est. quad.])
# caused by using a beta-model for the nonlinearity curve instead of the full curve.
#
# Inputs are:
# fit_array = signal in DN for true curve (length tmax array, starting with frame #1)
# deriv_array = signal rate in DN/frame
# Ib = charge per frame times beta (unitless)
# tslices = time slices used for the gain (select 3 here)
# reset_frame = which frame was reset? (0 if 1st frame is 1 after reset)
#
def compute_gain_corr(fit_array, deriv_array, Ib, tslices, reset_frame):
# unpack time information
ta = tslices[0] - reset_frame
tb = tslices[1] - reset_frame
td = tslices[2] - reset_frame
# indices
ina = tslices[0]-1
inb = tslices[1]-1
ind = tslices[2]-1
# We want the nonlinearity corrections (mean[td]-mean[tb])/(var[tad]-var[tab])
# which, for a non-linearity curve f(t) with f(0)=0, f'(0)=1, is
# [f(td)-f(tb)] / { [ta*(f'(td)-f'(ta))^2 + tad*f'(td)^2] - [ta*(f'(tb)-f'(ta))^2 + tab*f'(tb)^2] }
# = [f(td)-f(tb)] / [ ta*(f'(td)^2-f'(tb)^2 - 2f'(ta)*(f'(td)-f'(tb)) ) + td*f'(td)^2 - ta*f'(td)^2 - tb*f'(tb)^2 + ta*f'(tb)^2 ]
# = [f(td)-f(tb)] / [ -2 ta f'(ta) (f'(td)-f'(tb)) + td f'(td)^2 - tb f'(tb)^2 ]
#
# Let us call that factor e^{epsilon}
# Now for the beta-model, f(t) = t - Ib * t^2
# so e^{epsilon} = tbd [1 - Ib (tb+td) ] / [ 4 Ib ta tbd (1 - 2 Ib ta) + td (1 - 2 Ib td)^2 - tb (1 - 2 Ib tb)^2 ]
# = [1 - Ib (tb+td) ] / [ 4 Ib ta (1 - 2 Ib ta) + 1 - 4 Ib (tb+td) + Ib^2 (td^2 + tb td + tb^2) ]
# to lowest order in Ib (what is in the notes):
# epsilon ~ Ib (-4ta+3tb+3td)
true_expepsilon = (fit_array[ind]-fit_array[inb]) / (-2*ta*deriv_array[ina]*(deriv_array[ind]-deriv_array[inb])
+ td*deriv_array[ind]**2 - tb*deriv_array[inb]**2)
return numpy.log(true_expepsilon*deriv_array[0]) - Ib*(-4.*ta+3.*tb+3.*td)
#
# Same but for a whole grid of points (i.e. all nx x ny cells at a time).
# also includes a mask to avoid error messages.
def compute_gain_corr_many(fit_array, deriv_array, Ib, tslices, reset_frame, is_good):
out_array = numpy.zeros_like(fit_array[0,:,:])
ny = numpy.shape(fit_array)[1]; nx = numpy.shape(fit_array)[2]
for iy in range(ny):
for ix in range(nx):
if is_good[iy,ix]>.5:
out_array[iy,ix] = compute_gain_corr(fit_array[:,iy,ix], deriv_array[:,iy,ix], Ib[iy,ix], tslices, reset_frame)
return out_array
# Routine to estimate the correction to the correlation
# g^2 C_{abab}(+/-1,0)/(It_{ab}) / (2 alpha (1-4 alpha) )
# caused by using a beta-model for the nonlinearity curve instead of the full curve.
#
# Inputs are:
# fit_array = signal in DN for true curve (length tmax array, starting with frame #1)
# deriv_array = signal rate in DN/frame
# Ib = charge per frame times beta (unitless)
# tslices = time slices used for the x-corr (select 2 here)
# reset_frame = which frame was reset? (0 if 1st frame is 1 after reset)
#
def compute_xc_corr(fit_array, deriv_array, Ib, tslices, reset_frame):
# unpack time information
ta = tslices[0] - reset_frame
tb = tslices[1] - reset_frame
# indices
ina = tslices[0]-1
inb = tslices[1]-1
# We want the correction
# f'(tb)^2 + ta/tab * (f'(tb)-f'(ta)) - (1 - 4 Ib tb)
return( (deriv_array[inb]**2 - ta/(tb-ta)*(deriv_array[inb]-deriv_array[ina])**2) / deriv_array[0]**2
- (1. - 4*Ib*tb) )
#
# Same but for a whole grid of points (i.e. all nx x ny cells at a time).
# also includes a mask to avoid error messages.
def compute_xc_corr_many(fit_array, deriv_array, Ib, tslices, reset_frame, is_good):
out_array = numpy.zeros_like(fit_array[0,:,:])
ny = numpy.shape(fit_array)[1]; nx = numpy.shape(fit_array)[2]
for iy in range(ny):
for ix in range(nx):
if is_good[iy,ix]>.5:
out_array[iy,ix] = compute_xc_corr(fit_array[:,iy,ix], deriv_array[:,iy,ix], Ib[iy,ix], tslices, reset_frame)
return out_array
# Routine to get IPC-corrected gain
#
# Inputs:
# graw = uncorrected gain (e/DN)
# CH = horizontal correlation (DN^2)
# CV = vertical correlation (DN^2)
# signal = signal in this ramp (DN)
#
# Output list:
# gain (alpha corr), e/DN
# alphaH
# alphaV
#
# returns [] if failed.
def gain_alphacorr(graw, CH, CV, signal):
g = graw
for i in range(100):
alphaH = CH*g/(2*signal)
alphaV = CV*g/(2*signal)
if (alphaH+alphaV>0.25): return [] # FAIL!
g = graw*( (1-2*(alphaH+alphaV))**2 + 2*(alphaH**2+alphaV**2) )
return [g, alphaH, alphaV]
# Routine to get IPC+NL-corrected gain
#
# Inputs:
# graw = uncorrected gain (e/DN)
# CH = horizontal correlation (DN^2)
# CV = vertical correlation (DN^2)
# signal = signal in this ramp (DN)
# frac_dslope = mean signal rate in (cd) / mean signal rate in (ab) - 1
# times = list of times [a,b,c,d] used, normalized to reference slice
#
# Output list:
# gain g (alpha corr), e/DN
# alphaH
# alphaV
# beta
# current I (electrons per time slice)
#
# returns [] if failed
def gain_alphabetacorr(graw, CH, CV, signal, frac_dslope, times):
# This is solving the following set of equations
# (see Hirata's brighter-fatter effect paper)
#
# graw = g * [ 1 + beta I (3tb+3td-4ta) ] / [ (1-4alpha)^2 + 2alphaH^2 + 2alphaV^2 ]
# CH = (2 I tad alphaH / g^2) [ 1 - 4alpha - 4 beta I td ]
# CV = (2 I tad alphaV / g^2) [ 1 - 4alpha - 4 beta I td ]
# signal = I tad [ 1 - beta I (ta+td) ] / g
# frac_dslope = - beta I (tc+td-ta-tb)
# Initial guess
g = graw
alpha = alphaH = alphaV = beta = 0
I = signal*g/(times[3]-times[0])
# Iterate
# (100 iterations is overkill for this problem if alpha and beta are small)
for numIter in range(100):
g = graw * ((1-4*alpha)**2+2*(alphaH**2+alphaV**2)) / (1+beta*I*(3*(times[1]+times[3])-4*times[0]))
if g<1e-3:
print ('Gain did not converge')
print ('IN:', graw, CH, CV, signal, frac_dslope, times)
print ('STATUS:', g, alphaH, alphaV, alpha, I, beta)
exit()
temp = (1-4*alpha-4*beta*I*times[3])*2*I*(times[3]-times[0])/g**2
alphaH = CH/temp
alphaV = CV/temp
if (alphaH+alphaV>0.25): return [] # FAIL!
alpha = (alphaH+alphaV)/2.
I = signal*g/(times[3]-times[0])/(1-beta*I*(times[3]+times[0]))
beta = -frac_dslope/I/(times[2]+times[3]-times[0]-times[1])
if numpy.fabs(beta)*I*(times[3]+times[0])>0.5: return [] # FAIL!
return [g, alphaH, alphaV, beta, I]
# Basic characterization of a data cube
#
# region_cube = 4D array of the region of interest (order of indices: file, timeslice, y-ymin, x-xmin)
# dark_cube = same, but for a suite of darks
# tslices = list of time slices
# lightref = reference pixel table for correcting light exposures (2D)
# size is num_files, 2*ntslice_use+1 (assumes we are taking the correct y-slice)
# darkref = same as for lightref
# ctrl_pars = control parameter list
# ctrl_pars.epsilon = cut fraction (default to 0.01)
# ctrl_pars.subtr_corr = mean subtraction for the IPC correlation? (default to True)
# ctrl_pars.noise_corr = noise subtraction for the IPC correlation? (default to True)
# ctrl_pars.reset_frame = reset frame (default to 0)
# ctrl_pars.subtr_href = reference pixel subtraction? (default to True)
# ctrl_pars.full_corr = which parameters to report (default to True = standard basic pars; False = correlation data instead)
# ctrl_pars.leadtrailSub = lead-trail subtraction? (default to False)
# ctrl_pars.g_ptile = percentile for inter-quantile range (default to 75)
# verbose = True or False (recommend True only for de-bugging)
#
# Returns a list of basic calibration parameters.
# if ctrl_pars.full_corr is True
# [number of good pixels, gain_raw, gain_acorr, gain_abcorr, aH, aV, beta, I, 0., tCH, tCV]
# if False:
# [number of good pixels, median, variance, tCH, tCV, tCD]
# Returns the null list [] if failed.
#
# Includes a test so this won't crash if tslices[1]>=tslices[-1] but returns meaningful x-correlation C_{abab}
# (everything else is nonsense in this case)
#
def basic(region_cube, dark_cube, tslices, lightref, darkref, ctrl_pars, verbose):
# Settings:
newMeanSubMethod = True # use False only for test/debug
leadtrailSub = True # subtract leading & trailing (by +/-4 pix) from horiz & vert correlations
g_ptile = 75. # percentile use for inter-quantile range for variance (default: 75, giving standard IQR)
# Extract basic parameters
num_files = region_cube.shape[0]-1
nt = region_cube.shape[1]
dy = region_cube.shape[2]
dx = region_cube.shape[3]
npix = dx*dy
if nt!=len(tslices):
print ('Error in pyirc.basic: incompatible number of time slices')
exit()
if verbose: print ('nfiles = ',num_files,', ntimes = ',nt,', dx,dy=',dx,dy)
treset = 0
if hasattr(ctrl_pars,'reset_frame'): treset = ctrl_pars.reset_frame
# First get correlation parameters
epsilon = .01
if hasattr(ctrl_pars,'epsilon'): epsilon = ctrl_pars.epsilon
subtr_corr = True
if hasattr(ctrl_pars,'subtr_corr'): subtr_corr = ctrl_pars.subtr_corr
noise_corr = True
if hasattr(ctrl_pars,'noise_corr'): noise_corr = ctrl_pars.noise_corr
if verbose: print ('corr pars =', epsilon, subtr_corr, noise_corr)
#
# Reference pixel subtraction?
subtr_href = True
if hasattr(ctrl_pars,'subtr_href'): subtr_href = ctrl_pars.subtr_href
# return full correlation information?
full_corr = True
if hasattr(ctrl_pars,'full_corr'): full_corr = ctrl_pars.full_corr
# lead-trail subtraction for IPC correlations?
if hasattr(ctrl_pars,'leadtrailSub'): leadtrailSub = ctrl_pars.leadtrailSub
# quantile for variance?
if hasattr(ctrl_pars,'g_ptile'): g_ptile = ctrl_pars.g_ptile
# Get means and variances at the early and last slices
# (i.e. 1-point information)
gauss_iqr_in_sigmas = scipy.stats.norm.ppf(g_ptile/100.)*2 # about 1.349 for g_ptile=75.
box1 = region_cube[0:num_files,0,:,:] - region_cube[0:num_files,1,:,:]
box2 = region_cube[0:num_files,0,:,:] - region_cube[0:num_files,-1,:,:]
box2Noise = dark_cube[0:num_files,0,:,:] - dark_cube[0:num_files,-1,:,:]
#
if subtr_href:
for f in range(num_files):
if verbose: print ('lightref.shape=',lightref.shape, 'subtr ->', lightref[f,nt+1], lightref[f,2*nt-1], darkref[f,2*nt-1])
box1[f,:,:] -= lightref[f,nt+1]
box2[f,:,:] -= lightref[f,2*nt-1]
box2Noise[f,:,:] -= darkref[f,2*nt-1]
mean1 = numpy.mean(box1, axis=0)
mean2 = numpy.mean(box2, axis=0)
med1 = numpy.median(mean1)
med2 = numpy.median(mean2)
var1 = 0
var2 = 0
corr_mask = region_cube[-1,0,:,:]
for if1 in range(1,num_files):
for if2 in range(if1):
temp_box = box1[if1,:,:] - box1[if2,:,:]
iqr1 = pyIRC_percentile(temp_box,corr_mask,g_ptile) - pyIRC_percentile(temp_box,corr_mask,100-g_ptile)
temp_box = box2[if1,:,:] - box2[if2,:,:]
iqr2 = pyIRC_percentile(temp_box,corr_mask,g_ptile) - pyIRC_percentile(temp_box,corr_mask,100-g_ptile)
var1 += (iqr1/gauss_iqr_in_sigmas)**2/2.
var2 += (iqr2/gauss_iqr_in_sigmas)**2/2.
if verbose: print ('Inner loop,', if1, if2, temp_box.shape)
var1 /= num_files*(num_files-1)/2.
var2 /= num_files*(num_files-1)/2.
if var2<=var1 and tslices[1]<tslices[-1]: return [] # FAIL!
gain_raw = (med2-med1)/(var2-var1+1e-100) # in e/DN
# 1e-100 does nothing except to prevent an error when var1 and var2 are exactly the same
# Correlations of neighboring pixels, in DN^2
#
tCH = tCV = tCD = 0
for if1 in range(1,num_files):
for if2 in range(if1):
temp_box = box2[if1,:,:] - box2[if2,:,:]
# Run through twice if we have noise, otherwise once
nrun = 2 if noise_corr else 1
for icorr in range (nrun):
# clipping
cmin = pyIRC_percentile(temp_box,corr_mask,100*epsilon)
cmax = pyIRC_percentile(temp_box,corr_mask,100*(1-epsilon))
this_mask = numpy.where(numpy.logical_and(temp_box>cmin,temp_box<cmax),1,0) * corr_mask
if numpy.sum(this_mask)<1: return [] # FAIL!
# mean subtraction
mean_of_temp_box = numpy.sum(temp_box*this_mask)/numpy.sum(this_mask)
if subtr_corr and newMeanSubMethod: temp_box -= mean_of_temp_box
# Correlations in horizontal and vertical directions
maskCV = numpy.sum(this_mask[:-1,:]*this_mask[1:,:])
maskCH = numpy.sum(this_mask[:,:-1]*this_mask[:,1:])
CV = numpy.sum(this_mask[:-1,:]*this_mask[1:,:]*temp_box[:-1,:]*temp_box[1:,:])
CH = numpy.sum(this_mask[:,:-1]*this_mask[:,1:]*temp_box[:,:-1]*temp_box[:,1:])
if maskCH<1 or maskCV<1: return []
CH /= maskCH
CV /= maskCV
# diagonal directions
if not full_corr:
maskCD1 = numpy.sum(this_mask[:-1,:-1]*this_mask[1:,1:])
maskCD2 = numpy.sum(this_mask[:-1,1:]*this_mask[1:,:-1])
CD1 = numpy.sum(this_mask[:-1,:-1]*this_mask[1:,1:]*temp_box[:-1,:-1]*temp_box[1:,1:])
CD2 = numpy.sum(this_mask[:-1,1:]*this_mask[1:,:-1]*temp_box[:-1,1:]*temp_box[1:,:-1])
if maskCD1<1 or maskCD2<1: return []
CD1 /= maskCD1
CD2 /= maskCD2
CD = (CD1+CD2)/2.
if leadtrailSub:
maskCVx1 = numpy.sum(this_mask[:-1,:-4]*this_mask[1:,4:])
maskCHx1 = numpy.sum(this_mask[:,:-5]*this_mask[:,5:])
CVx1 = numpy.sum(this_mask[:-1,:-4]*this_mask[1:,4:]*temp_box[:-1,:-4]*temp_box[1:,4:])
CHx1 = numpy.sum(this_mask[:,:-5]*this_mask[:,5:]*temp_box[:,:-5]*temp_box[:,5:])
if maskCHx1<1 or maskCVx1<1: return []
CHx1 /= maskCHx1
CVx1 /= maskCVx1
maskCVx2 = numpy.sum(this_mask[:-1,4:]*this_mask[1:,:-4])
maskCHx2 = numpy.sum(this_mask[:,:-3]*this_mask[:,3:])
CVx2 = numpy.sum(this_mask[:-1,4:]*this_mask[1:,:-4]*temp_box[:-1,4:]*temp_box[1:,:-4])
CHx2 = numpy.sum(this_mask[:,:-3]*this_mask[:,3:]*temp_box[:,:-3]*temp_box[:,3:])
if maskCHx2<1 or maskCVx2<1: return []
CHx2 /= maskCHx2
CVx2 /= maskCVx2
CH -= (CHx1+CHx2)/2.
CV -= (CVx1+CVx2)/2.
#
# correction of the diagonal directions
if not full_corr:
maskCDx1 = numpy.sum(this_mask[:-1,:-5]*this_mask[1:,5:])
maskCDx2 = numpy.sum(this_mask[:-1,:-3]*this_mask[1:,3:])
maskCDx3 = numpy.sum(this_mask[1:,:-5]*this_mask[:-1,5:])
maskCDx4 = numpy.sum(this_mask[1:,:-3]*this_mask[:-1,3:])
CDx1 = numpy.sum(this_mask[:-1,:-5]*this_mask[1:,5:]*temp_box[:-1,:-5]*temp_box[1:,5:])
CDx2 = numpy.sum(this_mask[:-1,:-3]*this_mask[1:,3:]*temp_box[:-1,:-3]*temp_box[1:,3:])
CDx3 = numpy.sum(this_mask[1:,:-5]*this_mask[:-1,5:]*temp_box[1:,:-5]*temp_box[1:,5:])
CDx4 = numpy.sum(this_mask[1:,:-3]*this_mask[:-1,3:]*temp_box[1:,:-3]*temp_box[1:,3:])
if maskCDx1<1 or maskCDx2<1 or maskCDx3<1 or maskCDx4<1: return []
CDx1 /= maskCDx1
CDx2 /= maskCDx2
CDx3 /= maskCDx3
CDx4 /= maskCDx4
CD -= (CDx1+CDx2+CDx3+CDx4)/4.
if subtr_corr and not newMeanSubMethod and not leadtrailSub:
CH -= mean_of_temp_box**2
CV -= mean_of_temp_box**2
tCH += CH * (1 if icorr==0 else -1)
tCV += CV * (1 if icorr==0 else -1)
if not full_corr:
if subtr_corr and not newMeanSubMethod and not leadtrailSub: CD -= mean_of_temp_box**2
tCD += CD * (1 if icorr==0 else -1)
if verbose:
print ('pos =', if1, if2, 'iteration', icorr, 'cmin,cmax =', cmin, cmax)
print ('Mask size', numpy.sum(this_mask), 'correlations =', maskCH, maskCV, 'data:', CH, CV)
temp_box = box2Noise[if1,:,:] - box2Noise[if2,:,:]
# end nested for loop
#
# Normalize covariances. Note that taking the difference of 2 frames doubled the covariance
# matrix, so we have introduced cov_clip_corr
xi = scipy.stats.norm.ppf(1-epsilon)
cov_clip_corr = (1. - numpy.sqrt(2./numpy.pi)*xi*numpy.exp(-xi*xi/2.)/(1.-2.*epsilon) )**2
tCH /= num_files*(num_files-1)*cov_clip_corr
tCV /= num_files*(num_files-1)*cov_clip_corr
if not full_corr: tCD /= num_files*(num_files-1)*cov_clip_corr
# if we don't need full correlations, exit now
if not full_corr:
return [numpy.sum(this_mask), med2, var2, tCH, tCV, tCD]
# Curvature information (for 2nd order NL coefficient)
if (tslices[-1]!=tslices[-2]):
if subtr_href:
for f in range(num_files):
box1[f,:,:] += lightref[f,nt+1]
boxD = region_cube[0:num_files,-2,:,:] - region_cube[0:num_files,-1,:,:]\
- (tslices[-1]-tslices[-2])/float(tslices[1]-tslices[0])*box1
# difference map
if subtr_href:
for f in range(num_files):
box1[f,:,:] -= lightref[f,nt+1]
boxD[f,:,:] -= (tslices[-1]-tslices[-2])/float(tslices[1]-tslices[0]) * lightref[f,2*nt]
fac0 = fac1 = 0
for if1 in range(num_files):
box1R = box1[if1,:,:]
boxDR = boxD[if1,:,:]
c1min = pyIRC_percentile(box1R, corr_mask, 100*epsilon)
if c1min<=.5: c1min = .5 # should have no effect if successful, but prevents division by 0 if failure
c1max = pyIRC_percentile(box1R, corr_mask, 100*(1-epsilon))
cDmin = pyIRC_percentile(boxDR, corr_mask, 100*epsilon)
cDmax = pyIRC_percentile(boxDR, corr_mask, 100*(1-epsilon))
this_file_mask = numpy.where(numpy.logical_and(box1R>c1min, numpy.logical_and(box1R<c1max,
numpy.logical_and(boxDR>cDmin, boxDR<cDmax))), corr_mask, 0)
fac0 += numpy.sum(this_file_mask*boxDR)
fac1 += numpy.sum(this_file_mask*box1R)
if fac1<.5: return [] # FAIL!
frac_dslope = fac0/fac1/((tslices[-1]-tslices[-2])/float(tslices[1]-tslices[0]))
else:
frac_dslope = 0.
if verbose: print ('frac_dslope =', frac_dslope)
if verbose:
print ('Group 1 ->', med1, var1)
print ('Group 2 ->', med2, var2)
print ('correlations in Group 2:', tCH, tCV)
print ('factors used: xi =', xi, ', cov_clip_corr =', cov_clip_corr)
# Get alpha-corrected gains
out = gain_alphacorr(gain_raw, tCH, tCV, med2)
if tslices[1]>=tslices[-1] and len(out)<1:
return [numpy.sum(this_mask), gain_raw, gain_raw, gain_raw, 0., 0., 0., med2/gain_raw/(tslices[1]-tslices[0]), 0., tCH, tCV]
if len(out)<1: return [] # FAIL!
gain_acorr = out[0]
aH = out[1]
aV = out[2]
if tslices[1]>=tslices[-1]:
return [numpy.sum(this_mask), gain_raw, gain_acorr, gain_acorr, aH, aV, 0., med2/gain_acorr/(tslices[1]-tslices[0]), 0., tCH, tCV]
out = gain_alphabetacorr(gain_raw, tCH, tCV, med2, frac_dslope, [t-treset for t in tslices])
if len(out)<1: return [] # FAIL!
gain_abcorr = out[0]
aH = out[1]
aV = out[2]
beta = out[3]
I = out[4]
return [numpy.sum(this_mask), gain_raw, gain_acorr, gain_abcorr, aH, aV, beta, I, 0., tCH, tCV]
# Under construction correlation functions for charge diffusion measurements
# many parts drawn from basic, might want option to do the usual 3x3 vs 5x5 but
# this could be done in principle just with the usual basic function?
# There's probably a better way of writing this...?!
def corr_5x5(region_cube, dark_cube, tslices, lightref, darkref, ctrl_pars, verbose):
# Settings:
newMeanSubMethod = True # use False only for test/debug
leadtrailSub = True # subtract leading & trailing (by +/-4 pix) from horiz & vert correlations
g_ptile = 75. # percentile use for inter-quantile range for variance (default: 75, giving standard IQR)
# Extract basic parameters
num_files = region_cube.shape[0]-1
nt = region_cube.shape[1]
dy = region_cube.shape[2]
dx = region_cube.shape[3]
npix = dx*dy
if nt!=len(tslices):
print ('Error in pyirc.corr_5x5: incompatible number of time slices')
exit()
if verbose: print ('nfiles = ',num_files,', ntimes = ',nt,', dx,dy=',dx,dy)
treset = 0
if hasattr(ctrl_pars,'reset_frame'): treset = ctrl_pars.reset_frame
# First get correlation parameters
epsilon = .01
if hasattr(ctrl_pars,'epsilon'): epsilon = ctrl_pars.epsilon
subtr_corr = True
if hasattr(ctrl_pars,'subtr_corr'): subtr_corr = ctrl_pars.subtr_corr
noise_corr = True
if hasattr(ctrl_pars,'noise_corr'): noise_corr = ctrl_pars.noise_corr
if verbose: print ('corr pars =', epsilon, subtr_corr, noise_corr)
#
# Reference pixel subtraction?
subtr_href = True
if hasattr(ctrl_pars,'subtr_href'): subtr_href = ctrl_pars.subtr_href
# lead-trail subtraction for IPC correlations?
if hasattr(ctrl_pars,'leadtrailSub'): leadtrailSub = ctrl_pars.leadtrailSub
# quantile for variance?
if hasattr(ctrl_pars,'g_ptile'): g_ptile = ctrl_pars.g_ptile
# Get means and variances at the early and last slices
# (i.e. 1-point information)
gauss_iqr_in_sigmas = scipy.stats.norm.ppf(g_ptile/100.)*2 # about 1.349 for g_ptile=75.
box1 = region_cube[0:num_files,0,:,:] - region_cube[0:num_files,1,:,:]
box2 = region_cube[0:num_files,0,:,:] - region_cube[0:num_files,-1,:,:]
box2Noise = dark_cube[0:num_files,0,:,:] - dark_cube[0:num_files,-1,:,:]
#
if subtr_href:
for f in range(num_files):
if verbose: print ('lightref.shape=',lightref.shape, 'subtr ->', lightref[f,nt+1], lightref[f,2*nt-1], darkref[f,2*nt-1])
box1[f,:,:] -= lightref[f,nt+1]
box2[f,:,:] -= lightref[f,2*nt-1]
box2Noise[f,:,:] -= darkref[f,2*nt-1]
mean1 = numpy.mean(box1, axis=0)
mean2 = numpy.mean(box2, axis=0)
med1 = numpy.median(mean1)
med2 = numpy.median(mean2)
med21 = numpy.median(mean2-mean1)
var1 = 0
var2 = 0
corr_mask = region_cube[-1,0,:,:]
C_shift_mean = numpy.zeros((dy,dx))
tC_all = numpy.zeros((dy,dx))
for if1 in range(1,num_files):
for if2 in range(if1):
temp_box = box1[if1,:,:] - box1[if2,:,:]
iqr1 = pyIRC_percentile(temp_box,corr_mask,g_ptile) - pyIRC_percentile(temp_box,corr_mask,100-g_ptile)
temp_box = box2[if1,:,:] - box2[if2,:,:]
iqr2 = pyIRC_percentile(temp_box,corr_mask,g_ptile) - pyIRC_percentile(temp_box,corr_mask,100-g_ptile)
var1 += (iqr1/gauss_iqr_in_sigmas)**2/2.
var2 += (iqr2/gauss_iqr_in_sigmas)**2/2.