-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbf_ppl.py
3217 lines (2572 loc) · 114 KB
/
bf_ppl.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
# coding=utf-8
import moments
import matplotlib as mpl
import pdb
import configparser
import gc
import sigma_clip
import glob
import badger
import matplotlib.cm as cm
import matplotlib.patches as patches
from scipy import stats
import matplotlib.font_manager as fm
from matplotlib.backends.backend_pdf import PdfPages
import matplotlib.pyplot as plt
from scipy import ndimage
from scipy import optimize
import collections
import astropy.io.fits as pf
import os
import sys
import subprocess as S
import numpy as np
import matplotlib
matplotlib.use('Pdf')
#from hope import jit
################################## 1. PLOTTING PARAMETERS ##################################
plt.minorticks_on()
mpl.rc('lines', linewidth=1, color='black', linestyle='-')
mpl.rc('font', family='serif', weight='normal', size=10.0)
mpl.rc('text', color='black', usetex=False)
mpl.rc('axes', edgecolor='black', linewidth=1, grid=False, titlesize='x-large',
labelsize='x-large', labelweight='normal', labelcolor='black')
mpl.rc('axes.formatter', limits=[-4, 4])
mpl.rcParams['xtick.major.size'] = 7
mpl.rcParams['xtick.minor.size'] = 4
mpl.rcParams['xtick.major.pad'] = 5
mpl.rcParams['xtick.minor.pad'] = 5
mpl.rcParams['xtick.labelsize'] = 10 # 'x-large'
mpl.rcParams['xtick.minor.width'] = 1.0
mpl.rcParams['xtick.major.width'] = 1.0
mpl.rcParams['ytick.major.size'] = 7
mpl.rcParams['ytick.minor.size'] = 4
mpl.rcParams['ytick.major.pad'] = 5
mpl.rcParams['ytick.minor.pad'] = 5
mpl.rcParams['ytick.labelsize'] = 10 # 'x-large'
mpl.rcParams['ytick.minor.width'] = 1.0
mpl.rcParams['ytick.major.width'] = 1.0
mpl.rc('legend', numpoints=1, fontsize='x-large', shadow=False, frameon=False)
prop = fm.FontProperties(size=5)
loc_label = 'upper right'
################################## 2. FUNCTION DEFINITIONS ################################
def plot_array(image):
"""
Plot 2D np.array
Parameters
----------
image : `numpy.array`
input 2D array
"""
return
# @jit
def fitfunc_m(x, m):
# x=np.array(x)
return m*x
# pinit=[0.1]
# @jit
def linear_fit_m(x, y, y_err):
pinit = [-0.001]
pfinal, covar = optimize.curve_fit(
fitfunc_m, x, y, p0=pinit, sigma=y_err, maxfev=100000)
return pfinal[0], np.sqrt(covar[0])
# QUADRATIC POLYNOMIAL
fit_order = 2
# @jit
def fitfunc_quad(x, p0, p1, p2):
# x=np.array(x)
return p0 + p1*x + p2*(p1*x)**2
#pinit=np.repeat([1.0], fit_order + 1)
pinit_quad = [10000, 1000, -7.76e-7]
pinit2_quad = [10000, 1000, -7e-10]
# Cubic polynomial
# @jit
def fitfunc_cubic(x, p0, p1, p2, p3):
# x=np.array(x)
return p0 + p1*x + p2*(p1*x)**2 + p3*(p1*x)**3
pinit_cubic = [10000, 1000, -7.76e-7, -1e-12]
pinit2_cubic = [10000, 1000, -7e-10, 1e-11]
# 0 0 1 1
# 0 1 2 2
# 0 2 3 3
# 1 0 4 4
# 1 1 5 5
# 1 2 6 6
# 2 0 7 7
# 2 1 8 8
# 2 2 9 9
dict_3x3 = {(0, 0): (-1, 1), (0, 1): (0, 1), (0, 2): (1, 1),
(1, 0): (-1, 0), (1, 1): (0, 0), (1, 2): (1, 0),
(2, 0): (-1, -1), (2, 1): (0, -1), (2, 2): (1, -1)}
# @jit
def get_centroid_3x3(stamp):
s1, s2 = stamp.shape
if not s1 == 3 and s2 == 3:
print("Error: stamp must be 3X3")
sys.exit()
xcent, ycent = 0, 0
sum_stamp = np.sum(stamp)
for (j, i), val in np.ndenumerate(stamp):
xcent += dict_3x3[(j, i)][0]*val
ycent += dict_3x3[(j, i)][1]*val
return xcent/sum_stamp, ycent/sum_stamp
# (0, 0) 1
# (0, 1) 2
# (0, 2) 3
# (0, 3) 4
# (0, 4) 5
# (1, 0) 6
# (1, 1) 7
# (1, 2) 8
# (1, 3) 9
# (1, 4) 10
# (2, 0) 11
# (2, 1) 12
# (2, 2) 13
# (2, 3) 14
# (2, 4) 15
# (3, 0) 16
# (3, 1) 17
# (3, 2) 18
# (3, 3) 19
# (3, 4) 20
# (4, 0) 21
# (4, 1) 22
# (4, 2) 23
# (4, 3) 24
# (4, 4) 25
dict_5x5 = {(0, 0): (-2, 2), (0, 1): (-1, 2), (0, 2): (0, 2), (0, 3): (1, 2), (0, 4): (2, 2),
(1, 0): (-2, 1), (1, 1): (-1, 1), (1, 2): (0, 1), (1, 3): (1, 1), (1, 4): (2, 1),
(2, 0): (-2, 0), (2, 1): (-1, 0), (2, 2): (0, 0), (2, 3): (1, 0), (2, 4): (2, 0),
(3, 0): (-2, -1), (3, 1): (-1, -1), (3, 2): (0, -1), (3, 3): (1, -1), (3, 4): (2, -1),
(4, 0): (-2, -2), (4, 1): (-1, -2), (4, 2): (0, -2), (4, 3): (1, -2), (4, 4): (2, -2)}
def get_centroid_5x5(stamp):
s1, s2 = stamp.shape
if not s1 == 5 and s2 == 5:
print("Error: stamp must be 5X5")
sys.exit()
xcent, ycent = 0, 0
sum_stamp = np.sum(stamp)
for (j, i), val in np.ndenumerate(stamp):
xcent += dict_5x5[(j, i)][0]*val
ycent += dict_5x5[(j, i)][1]*val
return xcent/sum_stamp, ycent/sum_stamp
# @jit
def fit_pixel_ramp(ramp='', time='', i=0, j=0, order=2):
if not len(ramp) == len(time):
print("inside function ;fit_pixel_ramp': len(ramp) not equal to len (time).")
print("len (ramp) == len (time): ", len(ramp), len(time))
print("ramp: ", ramp, ramp.shape)
sys.exit()
print("time: ", time)
sys.exit()
flag = False
if order == 2:
pinit = pinit_quad
elif order == 3:
pinit = pinit_cubic
else:
print("Wrong order within fit_pixel_ramp function ")
sys.exit()
time_vec, signal_vec, signal_vec_err = [], [], []
# a=[]
# b=[]
# counter=0
for t, sample_array in zip(time, ramp):
# np.unravel_index (counter, sample_array.shape)
index_x, index_y = j, i
s = sample_array[index_x, index_y]
time_vec.append(t)
#signal_vec.append( 2**16-1-s )
signal_vec.append(s) # s=ADU_dark - ADU_data
# print "np.sqrt(s): ", np.sqrt(s)
signal_vec_err.append(np.sqrt(1)) # TOMATO
# if not counter == 0:
# a.append(time_vec[counter]-time_vec[counter-1])
# b.append(signal_vec[counter]-signal_vec[counter-1])
# counter+=1
time_vec = np.array(time_vec)
signal_vec = np.array(signal_vec)
signal_vec_err = np.array(signal_vec_err)
# a=np.array(a)
# b=np.array(b)
print("time_vec, signal_vec: ", time_vec, signal_vec)
# print "diff time, diff signal, ratio: ", a, b, b/a
if signal_vec[0] < 0:
print("Inside fit_pixel_ramp, negative signal: ", signal_vec)
signal_vec = np.fabs(signal_vec)
if np.isnan(signal_vec).any() or np.isinf(signal_vec_err).any():
flag = True
print("FLAG TRUE 1")
return np.zeros(order+1), np.zeros((order+1, order+1)), 0., flag, signal_vec
else:
pfinal, covar, chi2_red = get_final_parameters_first_fit(
x=time_vec, y=signal_vec, y_err=signal_vec_err, order=order)
if np.isinf(pfinal).any(): # or np.isinf(covar).any():
flag = True
print("FLAG TRUE 2")
print("pfinal, covar: ", pfinal, covar)
print("time_vec, y=signal_vec, y_err=signal_vec_err",
time_vec, signal_vec, signal_vec_err)
sys.exit()
return np.zeros(order+1), np.zeros((order+1, order+1)), 0., flag, signal_vec
else:
#p0, p1, p2 = pfinal[0], pfinal[1], pfinal[2]
# p0_err=np.sqrt(np.diag(covar))[0]
# p1_err=np.sqrt(np.diag(covar))[1]
# p2_err=np.sqrt(np.diag(covar))[2]
print("Todo bien in fit pixel ramp: pfinal, covar, chi2_red, flag: ",
pfinal, covar, chi2_red, flag)
return pfinal, covar, chi2_red, flag, signal_vec
# @jit
def correct_and_fit_pixel_ramp(ramp='', dark_ramp='', time='', i=0, j=0, pinit=pinit_quad, c0_spot=0, c0_dark=0, c1_spot=0, c1_dark=0, c2=1):
# c2=-7.76e-7
c3 = -1e-12
if not len(ramp) == len(time):
print("inside function 'correct_and_fit_pixel_ramp': len(ramp) not equal to len (time).")
print("len (ramp), len (time): ", len(ramp), len(time))
sys.exit()
flag = False
time_vec, signal_vec, signal_vec_err, sum_stamp = [], [], [], []
if not len(time) == len(ramp):
print("len(time)==len(ramp) not satisfied")
sys.exit(1)
a, b, delta_sum_stamp, counter = [], [], [], 0
for t, sample_array, sample_dark in zip(time, ramp, dark_ramp):
# np.unravel_index (counter, sample_array.shape)
index_x, index_y = j, i
# SPOT
s_temp = sample_array[index_x, index_y]
# print "s before NL correction: ", s_temp
# print "c0_spot, c0_dark, c2: ", c0_spot, c2_dark, c2
#s=c0_spot + c1_spot*t
# Apply the correction here!
s = (1/(2*c2))*(-1+np.sqrt(1-4*c2*(c0_spot-s_temp)))
print("DISCRIMINANTE: ")
print(18*c3*c2*(c0_spot-s_temp) - 4*c3**3*(c0_spot-s_temp) +
c2**2-4*c3-27*c3**2*(c0_spot-s_temp)**2)
# sys.exit()
# print "signal: %g, corrected signal: %g" %(s_temp, s)
# print "s/s2: ", s/s2, s, s2
# sys.exit(1)
# Same pixels, in dark fields
d_temp = sample_dark[index_x, index_y]
d = (1/(2*c2))*(-1+np.sqrt(1-4*c2*(c0_dark-d_temp)))
#d=c0_dark + c1_dark*t
# TEMP, turn off NL corection
if correct_NL == False:
s = s_temp
d = d_temp
print(" ")
print("c0_spot, c0_dark, c1_spot, c1_dark, c2 (from flat) ",
c0_spot, c0_dark, c1_spot, c1_dark, c2)
print("signal: %g, corrected_signal: %g " % (s_temp, s))
print("dark: %g, corrected_dark: %g " % (d_temp, d))
# Subtract dark from data
if subtract_dark == True:
s -= d
print("dark subtracted signal (corrected and not corrected): %g, %g" %
(s, s_temp-d_temp))
# print bias_frame[j,i]
# sys.exit(1)
#if i == 1 and j == 1: sys.exit()
time_vec.append(t)
#signal_vec.append( 2**16-1-s )
signal_vec.append(s) # s=ADU_dark - ADU_data
signal_vec_err.append(np.sqrt(1)) # TOMATO2
sum_stamp.append(np.sum(sample_array))
if not counter == 0:
a.append(time_vec[counter]-time_vec[counter-1])
b.append(signal_vec[counter]-signal_vec[counter-1])
delta_sum_stamp.append(sum_stamp[counter]-sum_stamp[counter-1])
delta_sum_stamp.append(sum_stamp)
counter += 1
print(" ")
print("j, i: ", j, i)
print(" ")
# if j == 2 and i == 2:
# sys.exit()
time_vec = np.array(time_vec)
signal_vec = np.array(signal_vec)
signal_vec_err = np.array(signal_vec_err)
delta_sum_stamp = np.array(delta_sum_stamp)
a = np.array(a)
b = np.array(b)
r = b/a
# r=signal_vec
# print "time_vec, corrected signal_vec, signal/time: ", time_vec, signal_vec, signal_vec/time_vec
print("diff time, diff signal, ratio of diffs ", a, b, b/a)
if np.isnan(signal_vec).any() or np.isinf(signal_vec_err).any():
flag = True
print("inside corract_and fit function, NAN ",
signal_vec, signal_vec_err)
# sys.exit()
return [0., 0., 0.], np.array([[0., 0., 0.], [0., 0., 0.], [0., 0., 0.]]), 0., flag, r, b, delta_sum_stamp, signal_vec
else:
pfinal, covar, chi2_red = get_final_parameters_first_fit(
x=time_vec, y=signal_vec, y_err=signal_vec_err, order=2)
if np.isinf(pfinal).any() or np.isinf(covar).any():
c = np.polyfit(time_vec, signal_vec, 2)
pfinal = c
pfinal[0] = c[2]
pfinal[1] = c[1]
pfinal[2] = c[0]/c[1]**2
return pfinal, np.array([[1., 1., 1.], [1., 1., 1.], [1., 1., 1.]]), 1, flag, r, b, delta_sum_stamp, signal_vec
# flag=True
# print "inside corract_and fit function, INF ", pfinal, covar
# sys.exit()
# return [0.,0.,0.], np.array([[0.,0.,0.],[0.,0.,0.],[0.,0.,0.]]), 0., flag, r, b, delta_sum_stamp, signal_vec
else:
p0, p1, p2 = pfinal[0], pfinal[1], pfinal[2]
p0_err = np.sqrt(np.diag(covar))[0]
p1_err = np.sqrt(np.diag(covar))[1]
p2_err = np.sqrt(np.diag(covar))[2]
return pfinal, covar, chi2_red, flag, r, b, delta_sum_stamp, signal_vec
def get_final_parameters_first_fit(x=[], y=[], y_err=[], order=2):
if order == 2:
pinit = pinit_quad
elif order == 3:
pinit = pinit_cubic
else:
print("wrong order in get_final_parameters_first_fit ")
sys.exit()
# this function gets all the parameters according to the polynomial order: alpha, beta, gamma, delta, etc
#x,y,y_err = np.array(x), np.array(y), np.array(y_err)
print("Inside get_final_parameters_first_fit (x, y, y_err): ", x, y, y_err)
for i in range(len(y)):
if y[i] < 0:
y[i] = 0
y_err[i] = 1
if order == 2:
fitfunc = fitfunc_quad
p0 = np.ones(order+1)
elif order == 3:
fitfunc = fitfunc_cubic
p0 = np.ones(order+1)
else:
print()
pfinal, covar = optimize.curve_fit(
fitfunc, x, y, p0=p0, sigma=y_err, maxfev=1000000000)
chi2 = np.power((fitfunc(x, *pfinal) - y)/y_err, 2).sum()
n, d = len(x), len(pinit)
nu = n-d
chi2_red = chi2*1./nu
#c=np.polyfit (x, y, 2)
# pfinal=c
# pfinal[0]=c[2]
# pfinal[1]=c[1]
# pfinal[2]=c[0]/c[1]**2
# chi2_red=1
# covar=np.array([[1,1,1],[1,1,1],[1,1,1]])
return pfinal, covar, chi2_red
# @jit
def aux_quadratic_fit(t_vec, s_vec, s_e_vec, label="_", order=2):
# if order == 2:
# pinit = pinit_quad
# elif order == 3:
# pinit=pinit_cubic
# else:
# print "Wrong order in aux_quadratic_fit"
# sys.exit()
p, c, chi2 = get_final_parameters_first_fit(
x=t_vec, y=s_vec, y_err=s_e_vec, order=order)
pe = np.sqrt(np.diag(c))
print("p, pe, chi2: ", p, pe, chi2)
p_all = np.array([p, pe])
#np.savetxt (outdir+"parameters_quadratic_%s.txt"%label, p_all)
return p, pe, chi2, c
def get_residual_error(l='', s='', varc0='', varc1='', covc0c1='', t=''):
# t=t/1000
# return 100*np.sqrt((s/l**2)+ s**2*(varc0+t**2*varc1 + 2*t*covc0c1)/l**2)
return 100*np.sqrt(s)/l
def run_shell_cmd(cmd):
print(cmd, file=sys.stderr)
S.Popen([cmd], shell=True, stdout=S.PIPE).communicate()[0].split()
def twoD_Gaussian(xxx_todo_changeme, amplitude, xo, yo, sigma_x, sigma_y, theta, offset):
(x, y) = xxx_todo_changeme
xo = float(xo)
yo = float(yo)
a = (np.cos(theta)**2)/(2*sigma_x**2) + (np.sin(theta)**2)/(2*sigma_y**2)
b = -(np.sin(2*theta))/(4*sigma_x**2) + (np.sin(2*theta))/(4*sigma_y**2)
c = (np.sin(theta)**2)/(2*sigma_x**2) + (np.cos(theta)**2)/(2*sigma_y**2)
g = offset + amplitude*np.exp(- (a*((x-xo)**2) + 2*b*(x-xo)*(y-yo)
+ c*((y-yo)**2)))
return g.ravel()
def plot_ratio_ramps(all, pp=None, title='', discard=[], threshold=5e-4):
new_all = []
for i, ramp in enumerate((all)):
if not len(discard) == 0:
# discard=len(all)-np.array(discard)
if i in discard:
continue
new_all.append(ramp)
new_all = np.array(new_all)
num_plots = len(new_all)
colormap = plt.cm.gist_ncar
# plt.gca().set_prop_cycle([colormap(i)
# for i in np.linspace(0, 0.9, num_plots)])
fig = plt.figure()
ax = fig.add_subplot(211)
# first_vec=[]
labels = []
new_ramp_list = []
nsamples = len(new_all[0])
# new_all_copy=(2**16-1-new_all)*gain
ramp_mean = np.mean(new_all, axis=0)
print(len(ramp_mean))
print(len(new_all))
last_frame_diff_vec = []
for i, ramp in enumerate((new_all)):
temp_vec = []
ratio_vec = []
# for (sample, sample_mean) in zip(ramp, mean_ramp):
for j in range(len(ramp)-1):
sample2 = (2**16 - 1 - ramp[j+1])*gain
sample1 = (2**16 - 1 - ramp[j])*gain
diff = sample2-sample1
sample2_mean = (2**16 - 1 - ramp_mean[j+1])*gain
sample1_mean = (2**16 - 1 - ramp_mean[j])*gain
diff_mean = sample2_mean - sample1_mean
mean_region = np.mean(diff[200:1900, 200:1900])
mean_region_of_mean_ramp = np.mean(diff_mean[200:1900, 200:1900])
#sample= 2**16 - 1 - sample
#sample_mean= 2**16 - 1 - sample_mean
#mean_region= np.mean (sample[200:1900, 200:1900])
#mean_region_of_mean_ramp= np.mean (sample_mean[200:1900, 200:1900])
ratio_vec.append(mean_region/mean_region_of_mean_ramp - 1)
ratio_vec = np.array(ratio_vec)
last_frame_diff_vec.append(ratio_vec[-1])
# if np.abs(ratio_vec[-1]) > threshold: continue # discard ramp
new_ramp_list.append(ramp)
plt.plot(ratio_vec, '.-')
ax.annotate('%g' % i, xy=(nsamples-1-1, ratio_vec[nsamples-1-1]), xytext=(
nsamples-1-1, ratio_vec[nsamples-1-1]), size=4)
labels.append("%g" % (i))
ax.set_title(title)
ax.set_xlabel('frame number')
ax.set_ylabel('(ramp kth[region]/ <ramp>[region]) - 1')
print(last_frame_diff_vec)
print(len(last_frame_diff_vec))
ax = fig.add_subplot(212)
plt.plot(last_frame_diff_vec, '.-')
ax.set_xlabel('ramp number')
ax.set_ylabel('last frame (e)')
if pp is not None:
pp.savefig()
else:
print("Enter valid PdfPages context manager in: 'plot_ratio_ramps'")
sys.exit()
print("Exiting plot_ratio_ramps function")
return new_ramp_list
# @jit
def plot_near_nl_corr(fig, frame, p_spot_corr, signal_corrected_spots, p_flat_corr, signal_corrected_flats, pos_x, pos_y):
linear_s = p_spot_corr[1]*time_darks
#linear_s=[12889.7802830, 25779.5605659, 38669.3408489, 51559.1211319, 64448.9014149]
#linear_s=[ 6444.8901415, 12889.7802830, 19334.6704245, 25779.5605659, 32224.4507074]
#linear_s=[ 19334.6704245, 38669.3408489, 58004.0112734, 77338.6816978, 96673.3521223 ]
res_s = 100*(signal_corrected_spots-linear_s)/linear_s
print("linear_s: ", linear_s)
print("signal_corrected_spots ", signal_corrected_spots)
linear_f = p_flat_corr[1]*time_flats
#linear_f=[18000.0000000, 36000.0000000, 54000.0000000, 72000.0000000, 90000.0000000]
#linear_f=[9000.0000000, 18000.0000000, 27000.0000000, 36000.0000000, 45000.0000000]
#linear_f=[27000.0000000, 54000.0000000, 81000.0000000, 108000.0000000, 135000.0000000]
res_f = 100*(signal_corrected_flats-linear_f)/linear_f
print("linear_f: ", linear_f)
print("signal_corrected_flats ", signal_corrected_flats)
flag = False
if (np.max(np.abs(res_f))) > nl_threshold_f or (np.max(np.abs(res_s))) > nl_threshold_s:
flag = True
return flag
ax = fig.add_subplot(3, 3, frame)
plt.plot(time_darks, res_s, 'r.-', label='spots')
plt.plot(time_flats, res_f, 'b.-', label='flats')
ax.legend(loc=loc_label, fancybox=True, ncol=1, numpoints=1, prop=prop)
ax.set_ylabel('Fractional NL\n(after NL correction)', size=8)
ax.set_xlabel('Time (mili seconds)', size=8)
ax.set_title("%g electrons.\n Position: (%g,%g)" %
(signal_corrected_spots[-1], pos_x, pos_y), size=8)
plt.tight_layout()
print("plot_near_nl_corr residuals spots in %: ", res_s)
print("plot_near_nl_corr residuals flats in %: ", res_f)
print("plot_near_nl_corr: ", frame, p_spot_corr, signal_corrected_spots,
p_flat_corr, signal_corrected_flats, pos_x, pos_y)
# PRINT
if frame == 5:
string = "center"
if frame == 2:
string = "n1"
if frame == 4:
string = "n2"
if frame == 6:
string = "n3"
if frame == 8:
string = "n4"
f = open(out_dir+"flat_calibration_"+string+".dat", 'a+')
#line_array=np.hstack ((linear_s, res_s, linear_f, res_f))
# line=""
# for x in line_array:
# line+="%g "%x
# line+="\n"
if flag == False:
for (a, b, c, d) in zip(linear_s, res_s, linear_f, res_f):
line = "%g %g %g %g \n" % (a, b, c, d)
f.write(line)
f.close()
return flag
def plot_pixel_ramp(ramp='', time='', fig='', i=0, j=0, counter='', fmt='k-o', plot_flag=False):
if not len(ramp) == len(time):
print("inside function 'plot_pixel_ramp': len(ramp) not equal to len (time).")
print("len(ramp), len(time): ", len(ramp), len(time))
sys.exit()
time_vec, signal_vec, signal_vec_err = [], [], []
a, b = [], []
counter2 = 0
for t, sample_array in zip(time[:], ramp[:]):
# np.unravel_index (counter, sample_array.shape)
index_x, index_y = j, i
s = sample_array[index_x, index_y]
time_vec.append(t)
#signal_vec.append( 2**16-1-s )
signal_vec.append(s) # s=ADU_dark - ADU_data
signal_vec_err.append(np.sqrt(s))
if not counter2 == 0:
a.append(time_vec[counter2]-time_vec[counter2-1])
b.append(signal_vec[counter2]-signal_vec[counter2-1])
counter2 += 1
time_vec = np.array(time_vec)
signal_vec = np.array(signal_vec)
signal_vec_err = np.array(signal_vec_err)
if plot_flag:
ax = fig.add_subplot(3, 3, counter)
ax.errorbar(time_vec, signal_vec, yerr=None, fmt=fmt, alpha=1.0,
label="(%g, %g, %g)" % (i, j, counter), markersize=5)
#ax.errorbar(time_vec[1:],b, yerr=None, fmt=fmt, alpha=1.0, label="(%g, %g, %g)" %(i,j,counter), markersize=5)
ax.legend(loc='upper left', fancybox=True,
ncol=1, numpoints=1, prop=prop)
#ax.set_xlabel ('Time (seconds)')
#ax.set_ylabel ('Signal (e-)')
ax.tick_params(axis='both', which='major', labelsize=5)
ax.tick_params(axis='both', which='minor', labelsize=5)
return np.array(b)/np.array(a)
# Helper function to stack ramps in each pixel ad plot them. To be used in the nested loop immediatly below.
# @jit
def stack_ramps_and_plot(ax, ramps_dict_mean_signal, ramps_dict, fmt_string, counter_pixel, label=" ", title=" "):
# print "HOLA "
(j, i) = get_pair_index[counter_pixel]
signal_vector = ramps_dict_mean_signal[(j, i)]
ramps_vector = ramps_dict[(j, i)]
signal_vector = np.array(signal_vector)
ramps_vector = np.array(ramps_vector)
if not len(ramps_vector) == len(signal_vector):
print("ERROR")
sys.exit()
# print "HOLA 2"
# print "counter_pixel: ", counter_pixel
# Stack vectors doing sigma clipping in each component
# print "len(ramps_vector): ", len(ramps_vector)
# print "len(ramps_vector[:,1]): ", len(ramps_vector[:,1])
# print "ramps_vector[:,k]: ", ramps_vector[:,1]
# print ramps_vector.shape
# sys.exit()
stacked_signal, stacked, stacked_err, stacked_numbers = [], [], [], []
# for k in range(len(ramps_vector[:,1])):
# for k in [0,1,2,3]:
# print range(shapes_darks[0] -start_sample_spots -1)
# sys.exit()
for k in range(ramps_vector.shape[1]):
# if len(ramps_vector) == 0:
# stacked_signal.append(0)
# stacked.append(0)
# stacked_err.append(0)
# stacked_numbers.append(1)
# continue
print("Bin: %g, number of objects: %g" % (k, len(ramps_vector[:, k])))
# if len(ramps_vector) == 0: continue
print("ramps_vector[:,k]:", ramps_vector[:, k])
print("signal_vector[:,k]:", signal_vector[:, k])
if k == -1:
print("hola")
# stacked_signal.append(0)
# stacked.append(0)
# stacked_err.append(0)
# stacked_numbers.append(1)
else:
temp_mean, temp_sigma, indices = sigma_clip.sigma_clip(
ramps_vector[:, k], niter=6, nsig=sigma_cut, get_indices=True, verbose=True)
temp_mean_signal, temp_sigma_signal, indices_signal = sigma_clip.sigma_clip(
signal_vector[:, k], niter=6, nsig=sigma_cut, get_indices=True, verbose=True)
if (indices is None) and (indices_signal is not None):
n = 1
stacked_signal.append(temp_mean_signal)
stacked.append(0.0)
stacked_err.append(0.0)
else:
stacked_signal.append(temp_mean_signal)
stacked.append(temp_mean)
stacked_err.append(temp_sigma)
n = len(indices)
print("Number of points in bin %g: %g " % (k, n))
stacked_numbers.append(n)
stacked_signal = np.array(stacked_signal)
stacked = np.array(stacked)
stacked_err = np.array(stacked_err)
stacked_numbers = np.array(stacked_numbers)
# stacked=np.mean(ramps_vector, axis=0) #Old way: just mean, no sigma clipping
#stacked_err=np.std(ramps_vector, axis=0)
samples = (list(range(1, len(stacked)+1)))
# print "Samples, STACKED: ", samples, stacked
print(stacked_signal, stacked_err, stacked_numbers)
plt.errorbar(stacked_signal, stacked, yerr=stacked_err /
np.sqrt(stacked_numbers), fmt=fmt_string, markersize=4, label=label)
#plt.errorbar (samples,stacked, yerr=stacked_err/np.sqrt(len(ramps_vector[:,1])), fmt=fmt_string, markersize=4, label=label)
# return (stacked, stacked_err/np.sqrt(stacked_numbers))
if STAMP_SIZE == 5 and counter_pixel == 13: # 5
plt.legend(loc='upper right', fancybox=True,
ncol=1, numpoints=1, prop=prop)
ax.set_yticklabels(ax.get_yticks(), size=5, visible=True)
# plt.ylim([-3e-2,3e-2])
elif STAMP_SIZE == 3 and counter_pixel == 5:
plt.legend(loc='upper right', fancybox=True,
ncol=1, numpoints=1, prop=prop)
ax.set_yticklabels(ax.get_yticks(), size=5, visible=True)
#plt.ylim([-0.03, 0.005])
else:
print("hola nada!!")
# plt.ylim([-2e-3,5e-3])
print("range(shapes_darks[0]): ", list(range(shapes_darks[0])))
# plt.xlim([0, np.max(range(shapes_darks[0]))]) # number of samples
#plt.ylim([0, -1e-2])
#ax.fill_between(range(-100,nsamples+100), -2e-3, 2e-3, facecolor='gray', alpha=0.3)
# in [1,6,11,16,21]: #in [1,4,7]:
if STAMP_SIZE == 5 and counter_pixel in [1, 6, 11, 16, 21]:
ax.set_ylabel(r"$f_{N}$", size=9)
# [21,22,23,24,25]: #[7,8,9]:
if STAMP_SIZE == 5 and counter_pixel in [21, 22, 23, 24, 25]:
ax.set_xlabel("Frame number (time)", size=7)
if STAMP_SIZE == 5 and counter_pixel in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]:
ax.set_xticklabels(ax.get_xticks(), size=9, visible=False)
# if counter_pixel in [2,3,4,5,7,8,9,10,12,14,15,17,18,19,20,22,23,24,25]:
# ax.set_yticklabels(ax.get_yticks(), size=9, visible=True)
# in [1,6,11,16,21]: #in [1,4,7]:
if STAMP_SIZE == 3 and counter_pixel in [1, 4, 7]:
ax.set_ylabel(r"$f_{N}$", size=16)
# [21,22,23,24,25]: #[7,8,9]:
if STAMP_SIZE == 3 and counter_pixel in [7, 8, 9]:
ax.set_xlabel("Frame number (time)", size=11)
if STAMP_SIZE == 3 and counter_pixel in [1, 2, 3, 4, 5, 6]:
ax.set_xticklabels(ax.get_xticks(), size=9, visible=False)
ax.tick_params(labelsize=7)
# ax.set_title (title + " \n pixel#: %g"%(counter_pixel), size=6)
print("HELLO ")
return (stacked_signal, stacked, stacked_err/np.sqrt(stacked_numbers))
# @jit
def stack_ramps_and_plot2(ax, ramps_dict, fmt_string, counter_pixel, label=" ", title=" "):
# print "HOLA "
(j, i) = get_pair_index[counter_pixel]
ramps_vector = ramps_dict[(j, i)]
ramps_vector = np.array(ramps_vector)
# print "HOLA 2"
# print "counter_pixel: ", counter_pixel
# Stack vectors doing sigma clipping in each component
# print "len(ramps_vector): ", len(ramps_vector)
# print "ramps_vector[:,k]: ", ramps_vector[:,1]
print(ramps_vector.shape)
for r in ramps_vector:
if len(ramps_vector) == 0:
r = np.zeros(len(GLOBAL_SPOTS))
plt.errorbar(list(range(len(r))), r, yerr=None,
fmt=fmt_string, markersize=2)
#plt.errorbar (samples,stacked, yerr=stacked_err/np.sqrt(len(ramps_vector[:,1])), fmt=fmt_string, markersize=4, label=label)
if STAMP_SIZE == 5 and counter_pixel == 13: # 5
plt.legend(loc='upper right', fancybox=True,
ncol=1, numpoints=1, prop=prop)
elif STAMP_SIZE == 3 and counter_pixel == 5: # 5
plt.legend(loc='upper right', fancybox=True,
ncol=1, numpoints=1, prop=prop)
else:
print("Incorrect STAMP_SIZE")
sys.exit(1)
# plt.xlim([0,nsamples+1])
plt.xlim([0, list(range(shapes_darks[0]))])
#plt.ylim([0, -1e-2])
#ax.fill_between(range(-100,nsamples+100), -2e-3, 2e-3, facecolor='gray', alpha=0.3)
# in [1,6,11,16,21]: #in [1,4,7]:
if STAMP_SIZE == 5 and counter_pixel in [1, 6, 11, 16, 21]:
ax.set_ylabel(r"$f_{N}$", size=8)
# in [1,6,11,16,21]: #in [1,4,7]:
elif STAMP_SIZE == 3 and counter_pixel in [1, 4, 7]:
ax.set_ylabel(r"$f_{N}$", size=8)
else:
print("Incorrect STAMP_SIZE")
sys.exit(1)
# [21,22,23,24,25]: #[7,8,9]:
if STAMP_SIZE == 5 and counter_pixel in [21, 22, 23, 24, 25]:
ax.set_xlabel("Frame number (time)", size=7)
# [21,22,23,24,25]: #[7,8,9]:
elif STAMP_SIZE == 3 and counter_pixel in [7, 8, 9]:
ax.set_xlabel("Frame number (time)", size=11)
else:
print("Incorrect STAMP_SIZE")
sys.exit(1)
# if counter_pixel == 5:
# plt.ylim([-3e-2,3e-2])
# else:
# plt.ylim([-6e-3,6e-3])
# plt.ylim([-7e-6,7e-6])
ax.tick_params(labelsize=7)
ax.set_title(title + " \n pixel#: %g" % (counter_pixel), size=7)
# Sum the 8 neighboring pixels
def plot_surrounding_pixels(fig, ramps_dict, fmt, label):
surrounding_pixels = []
surrounding_pixels_err = []
if stamp_string == 'five':
final = 26
elif stamp_string == 'three':
final = 10
else:
print("ERROR!!!!!")
sys.exit()
for i in range(1, final):
if STAMP_SIZE == 5 and i == 13:
continue # 5
if STAMP_SIZE == 3 and i == 5:
continue
(j, i) = get_pair_index[i]
ramps_vector = ramps_dict[(j, i)]
ramps_vector = np.array(ramps_vector)
#stacked=np.mean(ramps_vector, axis=0)
stacked, stacked_err, stacked_numbers = [], [], []
# for k in range(len(ramps_vector[0])):
for k in range(ramps_vector.shape[1]):
if len(ramps_vector) == 0:
stacked.append(0)
stacked_err.append(0)
stacked_numbers.append(1)
continue
if k == -1:
stacked.append(0)
stacked_err.append(0)
stacked_numbers.append(1)
else:
temp_mean, temp_sigma, indices = sigma_clip.sigma_clip(
ramps_vector[:, k], niter=6, nsig=sigma_cut, get_indices=True, verbose=True)
stacked.append(temp_mean)
stacked_err.append(temp_sigma)
if indices is None:
n = 0
else:
n = len(indices)
stacked_numbers.append(n)
stacked = np.array(stacked)
stacked_err = np.array(stacked_err)
stacked_numbers = np.array(stacked_numbers)
surrounding_pixels.append(stacked)
surrounding_pixels_err.append(stacked_err/np.sqrt(stacked_numbers))
surrounding_pixels = np.array(surrounding_pixels)
surrounding_pixels_err = np.array(surrounding_pixels_err)
# sum of the means in the 8 pixels
stacked_surrounding_pixels = np.sum(surrounding_pixels, axis=0)
stacked_surrounding_pixels_err = np.sqrt(
np.sum(surrounding_pixels_err**2, axis=0)) # add in cuadrature
# Stack vectors doing sigma clipping in each component
if STAMP_SIZE == 5:
# Number five or (1,1) is central pixel / 13 or 2,2
ramps_vector = ramps_dict[(2, 2)]
elif STAMP_SIZE == 3:
ramps_vector = ramps_dict[(1, 1)]
else:
print("error!!!!!")
sys.exit()
ramps_vector = np.array(ramps_vector)
stacked_central_pixel, stacked_central_pixel_err, stacked_central_pixel_numbers = [], [], []
# for k in range(len(ramps_vector[0])):
for k in range(ramps_vector.shape[1]):
if len(ramps_vector) == 0:
stacked_central_pixel.append(0)
stacked_central_pixel_err.append(0)
stacked_central_pixel_numbers.append(1)
continue
if k == -1:
stacked_central_pixel.append(0)
stacked_central_pixel_err.append(0)
stacked_central_pixel_numbers.append(1)
else:
temp_mean, temp_sigma, indices = sigma_clip.sigma_clip(
ramps_vector[:, k], niter=6, nsig=sigma_cut, get_indices=True, verbose=True)
if indices is None:
n = 1
stacked_central_pixel.append(0.0)
stacked_central_pixel_err.append(0.0)
else:
stacked_central_pixel.append(temp_mean)
stacked_central_pixel_err.append(temp_sigma)
n = len(indices)
stacked_central_pixel_numbers.append(n) # number of objects
stacked_central_pixel = np.array(stacked_central_pixel)
stacked_central_pixel_err = np.array(stacked_central_pixel_err)
stacked_central_pixel_numbers = np.array(stacked_central_pixel_numbers)
#stacked_central_pixel=np.mean(ramps_vector, axis=0)
print("stacked_central_pixel_numbers", stacked_central_pixel_numbers)
print("stacked_central_pixel_numbers", stacked_central_pixel_numbers)
samples = (list(range(1, len(stacked_central_pixel)+1)))
print(len(samples), len(stacked_surrounding_pixels), len(
stacked_central_pixel), list(range(ramps_vector.shape[1])))
dict = {'1': [], '2': []}
# fig=plt.figure()
ax = fig.add_subplot(211)
#ax.fill_between(range(-100,nsamples+100), -2e-3, 2e-3, facecolor='gray', alpha=0.3)
plt.errorbar(samples, stacked_surrounding_pixels,
yerr=stacked_surrounding_pixels_err, fmt=fmt, markersize=9, label=label)
ax.set_ylabel(r"$f_{N}$", size=14)
#ax.set_xlabel("Sample number (time)", size =8)
ax.set_title("Sum of %g surrounding pixels" % (final-2), size=11)
plt.legend(loc='upper left', fancybox=True, ncol=1, numpoints=1, prop=prop)
plt.xlim([0, np.max(list(range(shapes_darks[0]))) + 1])
# plt.ylim([0.24,0.31])