-
Notifications
You must be signed in to change notification settings - Fork 0
/
spirouPolar.py
2846 lines (2339 loc) · 114 KB
/
spirouPolar.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Spirou polarimetry module
Created on 2018-06-12 at 9:31
@author: E. Martioli
"""
import numpy as np
import os
import astropy.io.fits as fits
import matplotlib.pyplot as plt
plt.rcParams.update({'font.size': 16})
from scipy.interpolate import interp1d
from scipy import interpolate
from scipy.interpolate import UnivariateSpline
from scipy import stats
from scipy import constants
from copy import copy, deepcopy
import pylab as pl
import scipy as sp
import scipy.interpolate as sint
import scipy.signal as sig
# =============================================================================
# Define variables
# =============================================================================
# Name of program
__NAME__ = 'spirouPolar.py'
# -----------------------------------------------------------------------------
# =============================================================================
# Define user functions
# =============================================================================
def sort_polar_files(p):
"""
Function to sort input data for polarimetry.
:param p: parameter dictionary, ParamDict containing constants
Must contain at least:
LOG_OPT: string, option for logging
REDUCED_DIR: string, directory path where reduced data are stored
ARG_FILE_NAMES: list, list of input filenames
KW_CMMTSEQ: string, FITS keyword where to find polarimetry
information
:return polardict: dictionary, ParamDict containing information on the
input data
adds an entry for each filename, each entry is a
dictionary containing:
- basename, hdr, cdr, exposure, stokes, fiber, data
for each file
"""
func_name = __NAME__ + '.sort_polar_files()'
polardict = {}
# set default properties
stokes, exposure, expstatus = 'UNDEF', 0, False
# loop over all input files
for filename in p['INPUT_FILES']:
# initialize dictionary to store data for this file
polardict[filename] = {}
# Get t.fits and v.fits files if they exist
tfits = filename.replace("e.fits","t.fits")
polardict[filename]["TELLURIC_REDUC_FILENAME"] = ""
if os.path.exists(tfits):
polardict[filename]["TELLURIC_REDUC_FILENAME"] = tfits
wmsg = 'Telluric file {0} loaded successfully'
wargs = [tfits]
print('info', wmsg.format(*wargs))
vfits = filename.replace("e.fits","v.fits")
polardict[filename]["RV_FILENAME"] = ""
if os.path.exists(vfits) and p['IC_POLAR_SOURCERV_CORRECT'] :
vhdr = fits.getheader(vfits)
polardict[filename]["RV_FILENAME"] = vfits
polardict[filename]["SOURCE_RV"] = float(vhdr['CCFRV'])
wmsg = 'CCF RV={0:.5f} km/s from file {1} loaded successfully'
wargs = [polardict[filename]["SOURCE_RV"], vfits]
print('info', wmsg.format(*wargs))
else :
polardict[filename]["SOURCE_RV"] = 0.0
# load SPIRou spectrum
hdu = fits.open(filename)
hdr = hdu[0].header
hdr1 = hdu[1].header
polardict[filename]["BERV"] = hdr1['BERV']
# ------------------------------------------------------------------
# add filepath
polardict[filename]["filepath"] = os.path.abspath(filename)
# add filename
polardict[filename]["basename"] = os.path.basename(filename)
# try to get polarisation header key
if 'CMMTSEQ' in hdr and hdr['CMMTSEQ'] != "":
cmmtseq = hdr['CMMTSEQ'].split(" ")
stokes, exposure = cmmtseq[0], int(cmmtseq[2][0])
expstatus = True
if exposure == 1 :
p["BASE_EXPOSURE"] = filename
else:
exposure += 1
wmsg = 'File {0} has empty key="CMMTSEQ", setting Stokes={1} Exposure={2}'
wargs = [filename, stokes, exposure]
print('warning', wmsg.format(*wargs))
expstatus = False
# store exposure number
polardict[filename]["exposure"] = exposure
# store stokes parameter
polardict[filename]["stokes"] = stokes
# ------------------------------------------------------------------
# log file addition
wmsg = 'File {0}: Stokes={1} exposure={2}'
wargs = [filename, stokes, str(exposure)]
print('info', wmsg.format(*wargs))
# return polarDict
return polardict
# Alternative method to compute the telluric template.
def compute_spirou_AB_recon(input, nan_pos_filter=True) :
"""
Function to compute the telluric absorption "recon" spectrum.
:param input: string
input file name, could be either *e.fits or *t.fits
:param nan_pos_filter: bool
to filter out NaNs and negative numbers
:return Reconout: list
list of numpy float arrays, where each array contains the telluric
recon spectrum for a given spectral order
"""
# open fits file
if input.endswith("e.fits") :
# Read spectra with tellurics
hdu_efits = fits.open(input)
WaveAB = hdu_efits["WaveAB"].data
FluxAB = hdu_efits["FluxAB"].data
BlazeAB = hdu_efits["BlazeAB"].data / np.nanmean(hdu_efits["BlazeAB"].data)
# Read spectra corrected from tellurics
new_input = input.replace("e.fits", "t.fits")
hdu_tfits = fits.open(new_input)
WaveAB_corr = hdu_tfits["WaveAB"].data
FluxAB_corr = hdu_tfits["FluxAB"].data
Recon = FluxAB/FluxAB_corr
elif input.endswith("t.fits") :
# Read spectra corrected from tellurics
hdu_tfits = fits.open(input)
WaveAB_corr = hdu_tfits["WaveAB"].data
FluxAB_corr = hdu_tfits["FluxAB"].data
# Read spectra with tellurics
new_input = input.replace("t.fits", "e.fits")
hdu_efits = fits.open(new_input)
WaveAB = hdu_efits["WaveAB"].data
FluxAB = hdu_efits["FluxAB"].data
BlazeAB = hdu_efits["BlazeAB"].data / np.nanmean(hdu_efits["BlazeAB"].data)
Recon = FluxAB/FluxAB_corr
Reconout = []
for i in range(len(WaveAB)) :
if nan_pos_filter :
# mask NaN values from FluxAB & FluxAB_corr
nanmask = np.where(~( (np.isnan(FluxAB[i])) & (np.isnan(FluxAB_corr[i])) ))
# mask negative and zero values
negmask = np.where((FluxAB[i][nanmask] > 0) & (FluxAB_corr[i][nanmask] > 0))
Reconout.append(Recon[i][nanmask][negmask])
else :
Reconout.append(Recon[i])
return Reconout
def load_data(p, polardict, loc, silent=True):
"""
Function to load input SPIRou data for polarimetry.
:param p: parameter dictionary, ParamDict containing constants
Must contain at least:
LOG_OPT: string, option for logging
IC_POLAR_STOKES_PARAMS: list, list of stokes parameters
IC_POLAR_FIBERS: list, list of fiber types used in polarimetry
:param polardict: dictionary, ParamDict containing information on the
input data
:param loc: parameter dictionary, ParamDict to store data
:return p, loc: parameter dictionaries,
The updated parameter dictionary adds/updates the following:
FIBER: saves reference fiber used for base file in polar sequence
The updated data dictionary adds/updates the following:
DATA: array of numpy arrays (2D), E2DS data from all fibers in
all input exposures.
BASENAME, string, basename for base FITS file
HDR: dictionary, header from base FITS file
CDR: dictionary, header comments from base FITS file
STOKES: string, stokes parameter detected in sequence
NEXPOSURES: int, number of exposures in polar sequence
"""
func_name = __NAME__ + '.load_data()'
# get constants from p
stokesparams = p['IC_POLAR_STOKES_PARAMS']
polarfibers = p['IC_POLAR_FIBERS']
if silent:
import warnings
warnings.simplefilter(action='ignore', category=RuntimeWarning)
speed_of_light_in_kps = constants.c / 1000.
# First identify which stokes parameter is used in the input data
stokes_detected = []
# loop around filenames in polardict
for filename in polardict.keys():
# get this entry
entry = polardict[filename]
# condition 1: stokes parameter undefined
cond1 = entry['stokes'].upper() == 'UNDEF'
# condition 2: stokes parameter in defined parameters
cond2 = entry['stokes'].upper() in stokesparams
# condition 3: stokes parameter not already detected
cond3 = entry['stokes'].upper() not in stokes_detected
# if (cond1 or cond2) and cond3 append to detected list
if (cond1 or cond2) and cond3:
stokes_detected.append(entry['stokes'].upper())
# if more than one stokes parameter is identified then exit program
if len(stokes_detected) == 0:
stokes_detected.append('UNDEF')
elif len(stokes_detected) > 1:
wmsg = ('Identified more than one stokes parameter in the input '
'data... exiting')
print('error', wmsg)
# set all possible combinations of fiber type and exposure number
four_exposure_set = []
for fiber in polarfibers:
for exposure in range(1, 5):
keystr = '{0}_{1}'.format(fiber, exposure)
four_exposure_set.append(keystr)
# detect all input combinations of fiber type and exposure number
four_exposures_detected = []
loc['RAWFLUXDATA'], loc['RAWFLUXERRDATA'], loc['RAWBLAZEDATA'] = {}, {}, {}
loc['RAWTELCORFLUXDATA'], loc['RAWTELCORFLUXERRDATA'] = {}, {}
loc['FLUXDATA'], loc['FLUXERRDATA'] = {}, {}
loc['WAVEDATA'], loc['BLAZEDATA'] = {}, {}
loc['TELLURICDATA'] = {}
exp_count = 0
# loop around the filenames in polardict
for filename in polardict.keys():
# load SPIRou spectrum
hdu = fits.open(filename)
hdr = hdu[0].header
# get this entry
entry = polardict[filename]
# get exposure value
exposure = entry['exposure']
# save basename, wavelength, and object name for 1st exposure:
if (exp_count == 0) :
loc['BASENAME'] = p['BASE_EXPOSURE']
# load SPIRou spectrum
hdu_base = fits.open(loc['BASENAME'])
hdr_base = hdu_base[0].header
# get this entry
entry_base = polardict[loc['BASENAME']]
waveAB = deepcopy(hdu_base["WaveAB"].data)
if p['IC_POLAR_BERV_CORRECT'] :
rv_corr = 1.0 + (entry_base['BERV'] - entry_base['SOURCE_RV']) / speed_of_light_in_kps
waveAB *= rv_corr
#vel_shift = entry_base['SOURCE_RV'] - entry_base['BERV']
#rv_rel_corr = np.sqrt((1-vel_shift/speed_of_light_in_kps)/(1+vel_shift/speed_of_light_in_kps))
#waveAB *= rv_rel_corr
loc['WAVE'] = waveAB
loc['OBJECT'] = hdr_base['OBJECT']
loc['HEADER0'] = hdu_base[0].header
loc['HEADER1'] = hdu_base[1].header
if 'OBJTEMP' in loc['HEADER0'].keys() :
loc['OBJTEMP'] = loc['HEADER0']['OBJTEMP']
elif 'OBJTEMP' in loc['HEADER1'].keys() :
loc['OBJTEMP'] = loc['HEADER1']['OBJTEMP']
for fiber in polarfibers:
# set fiber+exposure key string
keystr = '{0}_{1}'.format(fiber, exposure)
# set flux key for given fiber
flux_key = "Flux{0}".format(fiber)
# set wave key for given fiber
wave_key = "Wave{0}".format(fiber)
# set blaze key for given fiber
blaze_key = "Blaze{0}".format(fiber)
# get flux data
flux_data = hdu[flux_key].data
# get normalized blaze data
blaze_data = hdu[blaze_key].data / np.nanmax(hdu[blaze_key].data)
# get wavelength data
wave_data = hdu[wave_key].data
# apply BERV correction if requested
if p['IC_POLAR_BERV_CORRECT'] :
rv_corr = 1.0 + (entry['BERV'] - entry['SOURCE_RV']) / speed_of_light_in_kps
wave_data *= rv_corr
#vel_shift = entry['SOURCE_RV'] - entry['BERV']
#rv_rel_corr = np.sqrt((1-vel_shift/speed_of_light_in_kps)/(1+vel_shift/speed_of_light_in_kps))
#waveAB *= rv_rel_corr
# store wavelength and blaze vectors
loc['WAVEDATA'][keystr], loc['RAWBLAZEDATA'][keystr] = wave_data, blaze_data
# calculate flux errors assuming Poisson noise only
fluxerr_data = np.zeros_like(flux_data)
for o in range(len(fluxerr_data)) :
fluxerr_data[o] = np.sqrt(flux_data[o])
# save raw flux data and errors
loc['RAWFLUXDATA'][keystr] = deepcopy(flux_data / blaze_data)
loc['RAWFLUXERRDATA'][keystr] = deepcopy(fluxerr_data / blaze_data)
# get shape of flux data
data_shape = flux_data.shape
# initialize output arrays to nan
loc['FLUXDATA'][keystr] = np.empty(data_shape) * np.nan
loc['FLUXERRDATA'][keystr] = np.empty(data_shape) * np.nan
loc['BLAZEDATA'][keystr] = np.empty(data_shape) * np.nan
loc['TELLURICDATA'][keystr] = np.empty(data_shape) * np.nan
# remove tellurics if possible and if 'IC_POLAR_USE_TELLURIC_CORRECTED_FLUX' parameter is set to "True"
if entry["TELLURIC_REDUC_FILENAME"] != "" and p['IC_POLAR_USE_TELLURIC_CORRECTED_FLUX'] :
telluric_spectrum = compute_spirou_AB_recon(entry["TELLURIC_REDUC_FILENAME"], nan_pos_filter=False)
loc['RAWTELCORFLUXDATA'][keystr] = loc['RAWFLUXDATA'][keystr]/telluric_spectrum
loc['RAWTELCORFLUXERRDATA'][keystr] = loc['RAWFLUXERRDATA'][keystr]/telluric_spectrum
for order_num in range(len(wave_data)) :
clean = np.isfinite(flux_data[order_num])
if len(wave_data[order_num][clean]) :
# interpolate flux data to match wavelength grid of first exposure
tck = interpolate.splrep(wave_data[order_num][clean], flux_data[order_num][clean], s=0)
# interpolate blaze data to match wavelength grid of first exposure
btck = interpolate.splrep(wave_data[order_num][clean], blaze_data[order_num][clean], s=0)
wlmask = loc['WAVE'][order_num] > wave_data[order_num][clean][0]
wlmask &= loc['WAVE'][order_num] < wave_data[order_num][clean][-1]
loc['BLAZEDATA'][keystr][order_num][wlmask] = interpolate.splev(loc['WAVE'][order_num][wlmask], btck, der=0)
loc['FLUXDATA'][keystr][order_num][wlmask] = interpolate.splev(loc['WAVE'][order_num][wlmask], tck, der=0) / loc['BLAZEDATA'][keystr][order_num][wlmask]
loc['FLUXERRDATA'][keystr][order_num][wlmask] = np.sqrt(loc['FLUXDATA'][keystr][order_num][wlmask] / loc['BLAZEDATA'][keystr][order_num][wlmask] )
# remove tellurics if possible and if 'IC_POLAR_USE_TELLURIC_CORRECTED_FLUX' parameter is set to "True"
if entry["TELLURIC_REDUC_FILENAME"] != "" and p['IC_POLAR_USE_TELLURIC_CORRECTED_FLUX'] :
# clean telluric nans
clean &= np.isfinite(telluric_spectrum[order_num])
if len(wave_data[order_num][clean]) :
# interpolate telluric data
ttck = interpolate.splrep(wave_data[order_num][clean], telluric_spectrum[order_num][clean], s=0)
loc['TELLURICDATA'][keystr][order_num][clean] = interpolate.splev(loc['WAVE'][order_num][clean], ttck, der=0)
#plt.plot(loc['WAVE'][order_num],loc['FLUXDATA'][keystr][order_num],color='k', lw=0.4, label="Raw flux")
# divide spectrum by telluric transmission spectrum
loc['FLUXDATA'][keystr][order_num] /= loc['TELLURICDATA'][keystr][order_num]
loc['FLUXERRDATA'][keystr][order_num] /= loc['TELLURICDATA'][keystr][order_num]
#plt.plot(loc['WAVE'][order_num],loc['FLUXDATA'][keystr][order_num]/np.nanmedian(loc['FLUXDATA'][keystr][order_num]),color='r',label="Corrected flux")
#plt.plot(loc['WAVE'][order_num],loc['TELLURICDATA'][keystr][order_num],color='g',label="Telluric")
#plt.show()
# add to four exposure set if correct type
cond1 = keystr in four_exposure_set
cond2 = keystr not in four_exposures_detected
if cond1 and cond2:
four_exposures_detected.append(keystr)
exp_count += 1
# initialize number of exposures to zero
n_exposures = 0
# now find out whether there is enough exposures
# first test the 4-exposure set
if len(four_exposures_detected) == 8:
n_exposures = 4
else:
wmsg = ('Number of exposures in input data is not sufficient'
' for polarimetry calculations... exiting')
print('error', wmsg)
# set stokes parameters defined
loc['STOKES'] = stokes_detected[0]
# set the number of exposures detected
loc['NEXPOSURES'] = n_exposures
# add polardict to loc
loc['POLARDICT'] = polardict
# calculate time related quantities
loc = calculate_polar_times(polardict, loc)
# return loc
return p, loc
def calculate_polar_times(polardict, loc) :
"""
Function to calculate time related quantities of polar product
:param p: parameter dictionary, ParamDict containing constants
:param polardict: dictionary, ParamDict containing information on the
input data
:param loc: parameter dictionary, ParamDict containing data
"""
mjd_first, mjd_last = 0.0, 0.0
meanbjd, tot_exptime = 0.0, 0.0
meanberv = 0.
bjd_first, bjd_last, exptime_last = 0.0, 0.0, 0.0
berv_first, berv_last = 0.0, 0.0
bervmaxs = []
mid_mjds, mid_bjds, mean_fluxes = [],[],[]
# loop over files in polar sequence
for filename in polardict.keys():
# get expnum
expnum = polardict[filename]['exposure']
# get header
hdr0 = fits.getheader(filename)
hdr1 = fits.getheader(filename,1)
# calcualte total exposure time
tot_exptime += float(hdr0['EXPTIME'])
# get values for BJDCEN calculation
if expnum == 1:
mjd_first = float(hdr0['MJDATE'])
bjd_first = float(hdr1['BJD'])
berv_first = float(hdr1['BERV'])
elif expnum == loc['NEXPOSURES']:
mjd_last = float(hdr0['MJDATE'])
bjd_last = float(hdr1['BJD'])
berv_last = float(hdr1['BERV'])
exptime_last = float(hdr0['EXPTIME'])
meanbjd += float(hdr1['BJD'])
# append BERVMAX value of each exposure
bervmaxs.append(float(hdr1['BERVMAX']))
# sum all BERV values
meanberv += hdr1['BERV']
# calculate mjd at middle of exposure
mid_mjds.append(float(hdr0['MJDATE']) + float(hdr0['EXPTIME'])/(2.*86400.))
# calculate bjd at middle of exposure
mid_bjds.append(float(hdr1['BJD']) + float(hdr0['EXPTIME'])/(2.*86400.))
# calculate mean A+B flux
meanflux = np.nanmean(loc['RAWFLUXDATA']['A_{0}'.format(expnum)] + loc['RAWFLUXDATA']['B_{0}'.format(expnum)])
# append mean A+B flux to the array
mean_fluxes.append(meanflux)
# add elapsed time parameter keyword to header
elapsed_time = (bjd_last - bjd_first) * 86400. + exptime_last
loc['ELAPSED_TIME'] = elapsed_time
# save total exposure time
loc['TOTEXPTIME'] = tot_exptime
# cast arrays to numpy arrays
mid_mjds, mid_bjds = np.array(mid_mjds), np.array(mid_bjds)
mean_fluxes = np.array(mean_fluxes)
# calculate flux-weighted mjd of polarimetric sequence
mjdfwcen = np.sum(mean_fluxes * mid_mjds) / np.sum(mean_fluxes)
loc['MJDFWCEN'] = mjdfwcen
# calculate flux-weighted bjd of polarimetric sequence
bjdfwcen = np.sum(mean_fluxes * mid_bjds) / np.sum(mean_fluxes)
loc['BJDFWCEN'] = bjdfwcen
# calculate MJD at center of polarimetric sequence
mjdcen = mjd_first + (mjd_last - mjd_first + exptime_last/86400.)/2.0
loc['MJDCEN'] = mjdcen
# calculate BJD at center of polarimetric sequence
bjdcen = bjd_first + (bjd_last - bjd_first + exptime_last/86400.)/2.0
loc['BJDCEN'] = bjdcen
# calculate BERV at center by linear interpolation
berv_slope = (berv_last - berv_first) / (bjd_last - bjd_first)
berv_intercept = berv_first - berv_slope * bjd_first
loc['BERVCEN'] = berv_intercept + berv_slope * bjdcen
loc['MEANBERV'] = meanberv / loc['NEXPOSURES']
# calculate maximum bervmax
bervmax = np.max(bervmaxs)
loc['BERVMAX'] = bervmax
# add mean BJD
meanbjd = meanbjd / loc['NEXPOSURES']
loc['MEANBJD'] = meanbjd
return loc
def calculate_polarimetry(p, loc):
"""
Function to call functions to calculate polarimetry either using
the Ratio or Difference methods.
:param p: parameter dictionary, ParamDict containing constants
Must contain at least:
LOG_OPT: string, option for logging
IC_POLAR_METHOD: string, to define polar method "Ratio" or
"Difference"
:param loc: parameter dictionary, ParamDict containing data
:return polarfunc: function, either polarimetry_diff_method(p, loc)
or polarimetry_ratio_method(p, loc)
"""
if p['IC_POLAR_APERO'] :
from apero import core
# Get Logging function
WLOG = core.wlog
# get parameters from p
method = p['IC_POLAR_METHOD']
# decide which method to use
if method == 'Difference':
return polarimetry_diff_method(p, loc)
elif method == 'Ratio':
return polarimetry_ratio_method(p, loc)
else:
emsg = 'Method="{0}" not valid for polarimetry calculation'
if p['IC_POLAR_APERO'] :
WLOG(p, 'error', emsg.format(method))
else :
print('error', emsg.format(method))
return 1
def calculate_stokes_i(p, loc):
"""
Function to calculate the Stokes I polarization
:param p: parameter dictionary, ParamDict containing constants
Must contain at least:
LOG_OPT: string, option for logging
:param loc: parameter dictionary, ParamDict containing data
Must contain at least:
DATA: array of numpy arrays (2D), E2DS data from all fibers in
all input exposures.
NEXPOSURES: int, number of exposures in polar sequence
:return loc: parameter dictionary, the updated parameter dictionary
Adds/updates the following:
STOKESI: numpy array (2D), the Stokes I parameters, same shape as
DATA
STOKESIERR: numpy array (2D), the Stokes I error parameters, same
shape as DATA
"""
func_name = __NAME__ + '.calculate_stokes_I()'
name = 'CalculateStokesI'
# log start of Stokes I calculations
wmsg = 'Running function {0} to calculate Stokes I total flux'
if p['IC_POLAR_APERO'] :
from apero import core
# Get Logging function
WLOG = core.wlog
WLOG(p, 'info', wmsg.format(name))
else :
print('info', wmsg.format(name))
# get parameters from loc
if p['IC_POLAR_INTERPOLATE_FLUX'] :
data, errdata = loc['FLUXDATA'], loc['FLUXERRDATA']
else :
if p['IC_POLAR_USE_TELLURIC_CORRECTED_FLUX'] :
data, errdata = loc['RAWTELCORFLUXDATA'], loc['RAWTELCORFLUXERRDATA']
else :
data, errdata = loc['RAWFLUXDATA'], loc['RAWFLUXERRDATA']
nexp = float(loc['NEXPOSURES'])
# ---------------------------------------------------------------------
# set up storage
# ---------------------------------------------------------------------
# store Stokes I variables in loc
data_shape = loc['FLUXDATA']['A_1'].shape
# initialize arrays to zeroes
loc['STOKESI'] = np.zeros(data_shape)
loc['STOKESIERR'] = np.zeros(data_shape)
flux, var = [], []
for i in range(1, int(nexp) + 1):
# Calculate sum of fluxes from fibers A and B
flux_ab = data['A_{0}'.format(i)] + data['B_{0}'.format(i)]
# Save A+B flux for each exposure
flux.append(flux_ab)
# Calculate the variances for fiber A+B -> varA+B = sigA * sigA + sigB * sigB
var_ab = errdata['A_{0}'.format(i)] * errdata['A_{0}'.format(i)] + errdata['B_{0}'.format(i)] * errdata['B_{0}'.format(i)]
# Save varAB = sigA^2 + sigB^2, ignoring cross-correlated terms
var.append(var_ab)
# Sum fluxes and variances from different exposures
for i in range(len(flux)):
loc['STOKESI'] += flux[i]
loc['STOKESIERR'] += var[i]
# Calcualte errors -> sigma = sqrt(variance)
loc['STOKESIERR'] = np.sqrt(loc['STOKESIERR'])
# log end of Stokes I intensity calculations
wmsg = 'Routine {0} run successfully'
if p['IC_POLAR_APERO'] :
WLOG(p, 'info', wmsg.format(name))
else :
print('info', wmsg.format(name))
# return loc
return loc
def polarimetry_diff_method(p, loc):
"""
Function to calculate polarimetry using the difference method as described
in the paper:
Bagnulo et al., PASP, Volume 121, Issue 883, pp. 993 (2009)
:param p: parameter dictionary, ParamDict containing constants
Must contain at least:
p['LOG_OPT']: string, option for logging
:param loc: parameter dictionary, ParamDict containing data
Must contain at least:
loc['RAWFLUXDATA']: numpy array (2D) containing the e2ds flux data for all
exposures {1,..,NEXPOSURES}, and for all fibers {A,B}
loc['RAWFLUXERRDATA']: numpy array (2D) containing the e2ds flux error data for all
exposures {1,..,NEXPOSURES}, and for all fibers {A,B}
loc['NEXPOSURES']: number of polarimetry exposures
:return loc: parameter dictionary, the updated parameter dictionary
Adds/updates the following:
loc['POL']: numpy array (2D), degree of polarization data, which
should be the same shape as E2DS files, i.e,
loc[DATA][FIBER_EXP]
loc['POLERR']: numpy array (2D), errors of degree of polarization,
same shape as loc['POL']
loc['NULL1']: numpy array (2D), 1st null polarization, same
shape as loc['POL']
loc['NULL2']: numpy array (2D), 2nd null polarization, same
shape as loc['POL']
"""
func_name = __NAME__ + '.polarimetry_diff_method()'
name = 'polarimetryDiffMethod'
# log start of polarimetry calculations
wmsg = 'Running function {0} to calculate polarization'
if p['IC_POLAR_APERO'] :
from apero import core
# Get Logging function
WLOG = core.wlog
WLOG(p, 'info', wmsg.format(name))
else :
print('info', wmsg.format(name))
# get parameters from loc
if p['IC_POLAR_INTERPOLATE_FLUX'] :
data, errdata = loc['FLUXDATA'], loc['FLUXERRDATA']
else :
data, errdata = loc['RAWFLUXDATA'], loc['RAWFLUXERRDATA']
nexp = float(loc['NEXPOSURES'])
# ---------------------------------------------------------------------
# set up storage
# ---------------------------------------------------------------------
# store polarimetry variables in loc
data_shape = loc['RAWFLUXDATA']['A_1'].shape
# initialize arrays to zeroes
loc['POL'] = np.zeros(data_shape)
loc['POLERR'] = np.zeros(data_shape)
loc['NULL1'] = np.zeros(data_shape)
loc['NULL2'] = np.zeros(data_shape)
gg, gvar = [], []
for i in range(1, int(nexp) + 1):
# ---------------------------------------------------------------------
# STEP 1 - calculate the quantity Gn (Eq #12-14 on page 997 of
# Bagnulo et al. 2009), n being the pair of exposures
# ---------------------------------------------------------------------
part1 = data['A_{0}'.format(i)] - data['B_{0}'.format(i)]
part2 = data['A_{0}'.format(i)] + data['B_{0}'.format(i)]
gg.append(part1 / part2)
# Calculate the variances for fiber A and B:
a_var = errdata['A_{0}'.format(i)] * errdata['A_{0}'.format(i)]
b_var = errdata['B_{0}'.format(i)] * errdata['B_{0}'.format(i)]
# ---------------------------------------------------------------------
# STEP 2 - calculate the quantity g_n^2 (Eq #A4 on page 1013 of
# Bagnulo et al. 2009), n being the pair of exposures
# ---------------------------------------------------------------------
nomin = 2.0 * data['A_{0}'.format(i)] * data['B_{0}'.format(i)]
denom = (data['A_{0}'.format(i)] + data['B_{0}'.format(i)]) ** 2.0
factor1 = (nomin / denom) ** 2.0
a_var_part = a_var / (data['A_{0}'.format(i)] * data['A_{0}'.format(i)])
b_var_part = b_var / (data['B_{0}'.format(i)] * data['B_{0}'.format(i)])
gvar.append(factor1 * (a_var_part + b_var_part))
# if we have 4 exposures
if nexp == 4:
# -----------------------------------------------------------------
# STEP 3 - calculate the quantity Dm (Eq #18 on page 997 of
# Bagnulo et al. 2009 paper) and the quantity Dms with
# exposures 2 and 4 swapped, m being the pair of exposures
# Ps. Notice that SPIRou design is such that the angles of
# the exposures that correspond to different angles of the
# retarder are obtained in the order (1)->(2)->(4)->(3),
# which explains the swap between G[3] and G[2].
# -----------------------------------------------------------------
d1, d2 = gg[0] - gg[1], gg[3] - gg[2]
d1s, d2s = gg[0] - gg[2], gg[3] - gg[1]
# -----------------------------------------------------------------
# STEP 4 - calculate the degree of polarization for Stokes
# parameter (Eq #19 on page 997 of Bagnulo et al. 2009)
# -----------------------------------------------------------------
loc['POL'] = (d1 + d2) / nexp
# -----------------------------------------------------------------
# STEP 5 - calculate the first NULL spectrum
# (Eq #20 on page 997 of Bagnulo et al. 2009)
# -----------------------------------------------------------------
loc['NULL1'] = (d1 - d2) / nexp
# -----------------------------------------------------------------
# STEP 6 - calculate the second NULL spectrum
# (Eq #20 on page 997 of Bagnulo et al. 2009)
# with exposure 2 and 4 swapped
# -----------------------------------------------------------------
loc['NULL2'] = (d1s - d2s) / nexp
# -----------------------------------------------------------------
# STEP 7 - calculate the polarimetry error
# (Eq #A3 on page 1013 of Bagnulo et al. 2009)
# -----------------------------------------------------------------
sum_of_gvar = gvar[0] + gvar[1] + gvar[2] + gvar[3]
loc['POLERR'] = np.sqrt(sum_of_gvar / (nexp ** 2.0))
# else if we have 2 exposures
elif nexp == 2:
# -----------------------------------------------------------------
# STEP 3 - calculate the quantity Dm
# (Eq #18 on page 997 of Bagnulo et al. 2009) and
# the quantity Dms with exposure 2 and 4 swapped,
# m being the pair of exposures
# -----------------------------------------------------------------
d1 = gg[0] - gg[1]
# -----------------------------------------------------------------
# STEP 4 - calculate the degree of polarization
# (Eq #19 on page 997 of Bagnulo et al. 2009)
# -----------------------------------------------------------------
loc['POL'] = d1 / nexp
# -----------------------------------------------------------------
# STEP 5 - calculate the polarimetry error
# (Eq #A3 on page 1013 of Bagnulo et al. 2009)
# -----------------------------------------------------------------
sum_of_gvar = gvar[0] + gvar[1]
loc['POLERR'] = np.sqrt(sum_of_gvar / (nexp ** 2.0))
# else we have insufficient data (should not get here)
else:
wmsg = ('Number of exposures in input data is not sufficient'
' for polarimetry calculations... exiting')
if p['IC_POLAR_APERO'] :
WLOG(p, 'error', wmsg)
else :
print('error', wmsg)
# set the method
loc['METHOD'] = 'Difference'
# log end of polarimetry calculations
wmsg = 'Routine {0} run successfully'
if p['IC_POLAR_APERO'] :
WLOG(p,'info', wmsg.format(name))
else :
print('info', wmsg.format(name))
# return loc
return loc
def polarimetry_ratio_method(p, loc):
"""
Function to calculate polarimetry using the ratio method as described
in the paper:
Bagnulo et al., PASP, Volume 121, Issue 883, pp. 993 (2009)
:param p: parameter dictionary, ParamDict containing constants
Must contain at least:
p['LOG_OPT']: string, option for logging
:param loc: parameter dictionary, ParamDict containing data
Must contain at least:
loc['RAWFLUXDATA']: numpy array (2D) containing the e2ds flux data for all
exposures {1,..,NEXPOSURES}, and for all fibers {A,B}
loc['RAWFLUXERRDATA']: numpy array (2D) containing the e2ds flux error data for all
exposures {1,..,NEXPOSURES}, and for all fibers {A,B}
loc['NEXPOSURES']: number of polarimetry exposures
:return loc: parameter dictionary, the updated parameter dictionary
Adds/updates the following:
loc['POL']: numpy array (2D), degree of polarization data, which
should be the same shape as E2DS files, i.e,
loc[DATA][FIBER_EXP]
loc['POLERR']: numpy array (2D), errors of degree of polarization,
same shape as loc['POL']
loc['NULL1']: numpy array (2D), 1st null polarization, same
shape as loc['POL']
loc['NULL2']: numpy array (2D), 2nd null polarization, same
shape as loc['POL']
"""
func_name = __NAME__ + '.polarimetry_ratio_method()'
name = 'polarimetryRatioMethod'
# log start of polarimetry calculations
wmsg = 'Running function {0} to calculate polarization'
if p['IC_POLAR_APERO'] :
from apero import core
# Get Logging function
WLOG = core.wlog
WLOG(p, 'info', wmsg.format(name))
else :
print('info', wmsg.format(name))
# get parameters from loc
if p['IC_POLAR_INTERPOLATE_FLUX'] :
data, errdata = loc['FLUXDATA'], loc['FLUXERRDATA']
else :
data, errdata = loc['RAWFLUXDATA'], loc['RAWFLUXERRDATA']
nexp = float(loc['NEXPOSURES'])
# ---------------------------------------------------------------------
# set up storage
# ---------------------------------------------------------------------
# store polarimetry variables in loc
data_shape = loc['RAWFLUXDATA']['A_1'].shape
# initialize arrays to zeroes
loc['POL'] = np.zeros(data_shape)
loc['POLERR'] = np.zeros(data_shape)
loc['NULL1'] = np.zeros(data_shape)
loc['NULL2'] = np.zeros(data_shape)
flux_ratio, var_term = [], []
# Ignore numpy warnings to avoid warning message: "RuntimeWarning: invalid
# value encountered in power ..."
#np.warnings.filterwarnings('ignore')
for i in range(1, int(nexp) + 1):
# ---------------------------------------------------------------------
# STEP 1 - calculate ratio of beams for each exposure
# (Eq #12 on page 997 of Bagnulo et al. 2009 )
# ---------------------------------------------------------------------
part1 = data['A_{0}'.format(i)]
part2 = data['B_{0}'.format(i)]
flux_ratio.append(part1 / part2)
# Calculate the variances for fiber A and B:
a_var = errdata['A_{0}'.format(i)] * errdata['A_{0}'.format(i)]
b_var = errdata['B_{0}'.format(i)] * errdata['B_{0}'.format(i)]
# ---------------------------------------------------------------------
# STEP 2 - calculate the error quantities for Eq #A10 on page 1014 of
# Bagnulo et al. 2009
# ---------------------------------------------------------------------
var_term_part1 = a_var / (data['A_{0}'.format(i)] * data['A_{0}'.format(i)])
var_term_part2 = b_var / (data['B_{0}'.format(i)] * data['B_{0}'.format(i)])
var_term.append(var_term_part1 + var_term_part2)
# if we have 4 exposures
if nexp == 4:
# -----------------------------------------------------------------
# STEP 3 - calculate the quantity Rm
# (Eq #23 on page 998 of Bagnulo et al. 2009) and
# the quantity Rms with exposure 2 and 4 swapped,
# m being the pair of exposures
# Ps. Notice that SPIRou design is such that the angles of
# the exposures that correspond to different angles of the
# retarder are obtained in the order (1)->(2)->(4)->(3),which
# explains the swap between flux_ratio[3] and flux_ratio[2].
# -----------------------------------------------------------------
r1, r2 = flux_ratio[0] / flux_ratio[1], flux_ratio[3] / flux_ratio[2]
r1s, r2s = flux_ratio[0] / flux_ratio[2], flux_ratio[3] / flux_ratio[1]
# -----------------------------------------------------------------
# STEP 4 - calculate the quantity R
# (Part of Eq #24 on page 998 of Bagnulo et al. 2009)
# -----------------------------------------------------------------
rr = (r1 * r2) ** (1.0 / nexp)
# -----------------------------------------------------------------
# STEP 5 - calculate the degree of polarization
# (Eq #24 on page 998 of Bagnulo et al. 2009)
# -----------------------------------------------------------------
loc['POL'] = (rr - 1.0) / (rr + 1.0)
# -----------------------------------------------------------------
# STEP 6 - calculate the quantity RN1
# (Part of Eq #25-26 on page 998 of Bagnulo et al. 2009)
# -----------------------------------------------------------------
rn1 = (r1 / r2) ** (1.0 / nexp)
# -----------------------------------------------------------------
# STEP 7 - calculate the first NULL spectrum
# (Eq #25-26 on page 998 of Bagnulo et al. 2009)
# -----------------------------------------------------------------
loc['NULL1'] = (rn1 - 1.0) / (rn1 + 1.0)
# -----------------------------------------------------------------
# STEP 8 - calculate the quantity RN2
# (Part of Eq #25-26 on page 998 of Bagnulo et al. 2009),
# with exposure 2 and 4 swapped
# -----------------------------------------------------------------
rn2 = (r1s / r2s) ** (1.0 / nexp)
# -----------------------------------------------------------------
# STEP 9 - calculate the second NULL spectrum
# (Eq #25-26 on page 998 of Bagnulo et al. 2009),
# with exposure 2 and 4 swapped
# -----------------------------------------------------------------
loc['NULL2'] = (rn2 - 1.0) / (rn2 + 1.0)
# -----------------------------------------------------------------
# STEP 10 - calculate the polarimetry error (Eq #A10 on page 1014
# of Bagnulo et al. 2009)
# -----------------------------------------------------------------
numer_part1 = (r1 * r2) ** (1.0 / 2.0)
denom_part1 = ((r1 * r2) ** (1.0 / 4.0) + 1.0) ** 4.0
part1 = numer_part1 / (denom_part1 * 4.0)
sumvar = var_term[0] + var_term[1] + var_term[2] + var_term[3]
loc['POLERR'] = np.sqrt(part1 * sumvar)
# else if we have 2 exposures
elif nexp == 2:
# -----------------------------------------------------------------
# STEP 3 - calculate the quantity Rm
# (Eq #23 on page 998 of Bagnulo et al. 2009) and
# the quantity Rms with exposure 2 and 4 swapped,
# m being the pair of exposures
# -----------------------------------------------------------------
r1 = flux_ratio[0] / flux_ratio[1]
# -----------------------------------------------------------------
# STEP 4 - calculate the quantity R
# (Part of Eq #24 on page 998 of Bagnulo et al. 2009)
# -----------------------------------------------------------------
rr = r1 ** (1.0 / nexp)
# -----------------------------------------------------------------
# STEP 5 - calculate the degree of polarization
# (Eq #24 on page 998 of Bagnulo et al. 2009)
# -----------------------------------------------------------------
loc['POL'] = (rr - 1.0) / (rr + 1.0)
# -----------------------------------------------------------------
# STEP 6 - calculate the polarimetry error (Eq #A10 on page 1014
# of Bagnulo et al. 2009)
# -----------------------------------------------------------------
# numer_part1 = R1
denom_part1 = ((r1 ** 0.5) + 1.0) ** 4.0
part1 = r1 / denom_part1
sumvar = var_term[0] + var_term[1]
loc['POLERR'] = np.sqrt(part1 * sumvar)