-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfunctions_polarization.py
1347 lines (1077 loc) · 44.1 KB
/
functions_polarization.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 aplpy
import numpy as np
from tqdm import tqdm
import astropy.wcs as wcs
from astropy.io import fits
from scipy import interpolate
import matplotlib.pyplot as plt
from astropy import constants as const
from matplotlib.collections import LineCollection
from functions_misc import fmask_signal, fwavel
from functions_fits import fheader_3Dto2D
def fPI(Q,U):
'''
Coomputes the polarized intensity.
Input
Q : Stokes Q map
U : Stokes U map
Output
PI : polarized intensity
'''
# compute polarized intensity
PI = np.sqrt(Q**2.+U**2.)
return PI
def fPI_err(Q,U,Q_err,U_err):
'''
Computes the uncertainty in the polarized intensity.
Input
Q : Stokes Q
U : Stokes U
Q_err : uncertainty in Stokes Q
U_err : uncertainty in Stokes U
'''
P = np.sqrt(Q**2.+U**2.)
Q_term = (Q/P)**2. * Q_err**2.
U_term = (U/P)**2. * U_err**2.
P_err = np.sqrt(Q_term + U_term)
return P_err
def fPI_error(Q,U,QQ,QU,UU):
'''
Computes the uncertainty of the the polarized intensity.
See Equation B.4 in Planck XIX (2015).
Input
Q : Stokes Q
U : Stokes U
QQ : QQ covariance
QU : QU covariance
UU : UU covariance
Output
PI_error : uncertainty in polarized intensity
'''
# compute polarized intensity
PI = fPI(Q,U)
PI_error = (Q**2.*QQ + U**2.*UU + 2.*Q*U*QU)/(PI**2.)
return PI_error
def fpolangle(Q,U,toIAU=False,deg=True):
'''
Computes the polarization angle.
Input
Q : Stokes Q
U : Stokes U
toIAU : if True, converts from COSMO to IAU convention (default=False)
deg : if True, convert angles to degrees for output (default=True)
Output
polangle : polarization angle
'''
if toIAU==True:
# if converting from COSMOS to IAU convention
# flip sign of Stokes U
# compute polarization angle
pol_angle = np.mod(0.5*np.arctan2(U*-1.,Q), np.pi)
elif toIAU==False:
# don't flip sign of Stokes U
# compute polarization angle
pol_angle = np.mod(0.5*np.arctan2(U,Q), np.pi)
if deg==True:
# convert from radians to degrees
pol_angle = np.degrees(pol_angle)
return pol_angle
def fpolangle_error(Q,U,QQ,QU,UU,deg=True):
'''
Computed the uncertainty in the polarization angle.
See Equation B.3 in Planck XIX (2015).
Input
Q : Stokes Q
U : Stokes U
QQ : QQ covariance
QU : QU covariance
UU : UU covariance
deg : if True, convert angles to degrees for output (default=True)
Output
polangle_error : uncertainty in polarization angle
'''
num = Q**2.*UU + U**2.*QQ - 2.*Q*U*QU
den = Q**2.*QQ + U**2.*UU + 2.*Q*U*QU
# compute uncertainty in polarized intensity
PI_error = fPI_error(Q,U,QQ,QU,UU)
if deg==True:
fac = 28.65
else:
fac = np.radians(28.65)
# compute uncertainty in polarization angle
polangle_error = fac * np.sqrt(num/den) * PI_error
return polangle_error
def fBangle(Q,U,toIAU=False,deg=True):
'''
Computes the plane-of-sky magnetic field angle.
COSMO polarization angle convention to IAU B-field convention = flip sign of Stokes U
Input
Q : Stokes Q
U : Stokes U
toIAU : if True, converts from COSMO to IAU convention (default=False)
deg : if True, convert angles to degrees for output (default=True)
Output
polangle : magnetic field angle
'''
if toIAU==True:
# if converting from COSMOS to IAU convention flip sign of Stokes U
# and flip both Q and U to convert from E to B
# (i.e., just flip sign of Q)
# compute B angle
B_angle = np.mod(0.5*np.arctan2(U,Q*-1.), np.pi)
elif toIAU==False:
# don't flip sign of Stokes U
# but do flip both Q and U to convert from E to B
# (i.e., flip sign of both Q and U)
# compute polarization angle
B_angle = np.mod(0.5*np.arctan2(U*-1.,Q*-1.), np.pi)
if deg==True:
# convert from radians to degrees
B_angle = np.degrees(B_angle)
return B_angle
def fQU(P,chi,deg=True):
'''
Compute Stokes Q and U.
Input
P : polarized intensity
chi : polarization angle
deg : if True, polarization angle is in degrees (otherwise radians) [default=True]
Output
Q : Stokes Q
U : Stokes U
'''
# make sure polarization angles are in radians
if deg==True:
chi_rad = np.radians(chi)
elif deg==False:
chi_rad = chi
# compute Stokes QU
Q = P*np.cos(2.*chi_rad)
U = P*np.sin(2.*chi_rad)
return Q,U
def fpolanglediff_Stokes(Q_1,U_1,Q_2,U_2,toIAU=False,deg=True):
'''
Computes the difference between two polarization angles.
See Equation 7 in Planck XIX (2015).
Input
Q_1 : Stokes Q corresponding to reference polarization angle
U_1 : Stokes U corresponding to reference polarization angle
Q_2 : Stokes Q corresponding to displaced polarization angle
U_2 : Stokes U corresponding to displaced polarization angle
toIAU : if True, converts from COSMO to IAU convention (default=False)
deg : if True, convert angles to degrees for output (default=True)
Output
pol_angle_diff : difference between polarization angles
'''
Q_1 = np.copy(Q_1)
U_1 = np.copy(U_1)
Q_2 = np.copy(Q_2)
U_2 = np.copy(U_2)
if toIAU==True:
# if converting from COSMOS to IAU convention
# flip sign of Stokes U
U_1 *= -1.
U_2 *= -1.
# difference between polarization angles
pol_angle_diff = 0.5*np.arctan2(Q_2*U_1-Q_1*U_2,Q_2*Q_1-U_2*U_1)
if deg==True:
# convert from radians to degrees
pol_angle_diff = np.degrees(pol_angle)
return pol_angle_diff
def fpolanglediff(polangle_1,polangle_2,inunits="deg",outunits="deg"):
'''
Computes the difference between two polarization angles.
See Equation 15 in Clark (2019a).
Input
polangle_1 :
polangle_2 :
Output
pol_angle_diff : difference between polarization angles
'''
degree_units = ["deg","degree","degrees"]
rad_units = ["rad","radian","radians"]
if inunits in degree_units:
polangle_1_deg = polangle_1.copy()
polangle_2_deg = polangle_2.copy()
polangle_1_rad = np.radians(polangle_1)
polangle_2_rad = np.radians(polangle_2)
elif inunits in rad_units:
polangle_1_rad = polangle_1.copy()
polangle_2_rad = polangle_2.copy()
polangle_1_deg = np.degrees(polangle_1)
polangle_2_deg = np.degrees(polangle_2)
# difference between polarization angles
num = np.sin(2.*polangle_1_rad)*np.cos(2.*polangle_2_rad) - np.cos(2.*polangle_1_rad)*np.sin(2.*polangle_2_rad)
den = np.cos(2.*polangle_1_rad)*np.cos(2.*polangle_2_rad) + np.sin(2.*polangle_1_rad)*np.sin(2.*polangle_2_rad)
pol_angle_diff = 0.5*np.arctan2(num,den)
if outunits in degree_units:
pol_angle_diff = np.degrees(pol_angle_diff)
return pol_angle_diff
def fAM(theta1,theta2,inunits="deg"):
'''
Computes the alignment measure (AM) between two angles on the range [0,180).
See Equation 16 in Clark et al. (2019a).
Input
theta1 : angles in units of inunits
theta2 : angles in units of inunits
inunits : defines units of input angles
Output
AM_full : full array of "AM" measurements
AM : alignment measure on the range [-1,1]
Note: An AM of +1, -1, and 0 implies that the angles are perfectly aligned, perfeclty anti-aligned, and not at all aligned, respectively.
'''
# compute angular diference in radians
deltatheta_rad = fpolanglediff(theta1,theta2,inunits=inunits,outunits="rad")
# compute AM
AM_full = np.cos(2.*deltatheta_rad)
AM = np.nanmean(AM_full)
return AM_full,AM
def fpolfrac(I,Q,U):
'''
Coomputes the polarization fraction.
Input
I : Stokes I map
Q : Stokes Q map
U : Stokes U map
Output
polfrac : polarization fraction
'''
# compute polarized intensity
PI = np.sqrt(Q**2.+U**2.)
# compute the polarization fraction
polfrac = PI/I
return polfrac
def fpolfrac_error(I,Q,U,II,IQ,IU,QQ,QU,UU):
'''
Computes the uncertainty in the polarization fraction.
Input
I : Stokes I
Q : Stokes Q
U : Stokes U
II : II covariance
IQ : IQ covariance
IU : IU covariance
QQ : QQ covariance
QU : QU covariance
UU : UU covariance
Output
polfrac_error : uncertainty in polarization fraction
'''
# compute polarization fraction
polfrac = fpolfrac(I,Q,U)
# compute uncertainty in polarization fraction
a_den = (polfrac**2.) * (I**4.)
a = 1./fac_den
b = Q**2.*QQ + U**2.*UU + (II/(I**2.))*(Q**2.+U**2.)**2. + 2.*Q*U*QU - (2.*U*(Q**2.+U**2.)*IQ)/I - (2.*U*(Q**2.+U**2.)*IU)/I
polfrac_error = np.sqrt(a*b)
return polfrac_error
def fPI_debiased(Q,U,Q_std,U_std):
'''
Compute the de-biased polarized intensity.
Input
Q : Stokes Q map
U : Stokes U map
Q_std : standard deviation of Stokes Q noise
U_std : standard deviation of Stokes U noise
Output
PI_debiased : debiased polarized intensity
'''
# compute effective Q/U noise standard deviation
std_QU = np.sqrt(Q_std**2. + U_std**2.)
# compute polarized intensity
PI = np.sqrt(Q**2.+U**2.)
# compute de-biased polarized intensity
PI_debiased = PI * np.sqrt( 1. - (std_QU/PI)**2. )
return PI_debiased
def fpolgrad(Q,U):
'''
Computes the polarization gradient.
See Equation 1 in Gaensler et al. (2011).
Input
Q : Stokes Q map
U : Stokes U map
Output
polgrad : polarization gradient
'''
# compute Stokes spatial gradients
Q_grad_y,Q_grad_x = np.gradient(Q)
U_grad_y,U_grad_x = np.gradient(U)
# compute spatial polarization gradient
polgrad = np.sqrt(Q_grad_x**2.+Q_grad_y**2.+U_grad_x**2.+U_grad_y**2.)
return polgrad
def fpolgradnorm(Q,U):
'''
Computes the normalized polarization gradient.
See Iacobelli et al. (2014).
Input
Q : Stokes Q map
U : Stokes U map
Output
polgrad_norm : normalized polarization gradient
'''
# compute Stokes spatial gradients
Q_grad_y,Q_grad_x = np.gradient(Q)
U_grad_y,U_grad_x = np.gradient(U)
# compute spatial polarization gradient
polgrad = np.sqrt(Q_grad_x**2.+Q_grad_y**2.+U_grad_x**2.+U_grad_y**2.)
# compute the polarized intensity
P = np.sqrt(Q**2.+U**2.)
# compute normalized polarization gradient
polgrad_norm = polgrad/P
return polgrad_norm
def fpolgrad_crossterms(Q,U):
'''
Computes the polarization gradient with cross-terms.
See Equation 15 in Herron et al. (2018).
Input
Q : Stokes Q data
U : Stokes U data
Output
polgrad : polarization gradient with cross-terms
'''
# compute Stokes spatial gradients
Q_grad_y,Q_grad_x = np.gradient(Q)
U_grad_y,U_grad_x = np.gradient(U)
# compute spatial polarization gradient
a = Q_grad_x**2.+Q_grad_y**2.+U_grad_x**2.+U_grad_y**2.
b = a**2. - 4.*(Q_grad_x*U_grad_y - Q_grad_y*U_grad_x)**2.
# compute polarization gradient
polgrad = np.sqrt(0.5*a + 0.5*np.sqrt(b))
return polgrad
def fpolgradnorm_crossterms(Q,U):
'''
Computes the polarization gradient with cross-terms.
See Equation 15 in Herron et al. (2018).
Input
Q : Stokes Q data
U : Stokes U data
Output
polgrad : polarization gradient with cross-terms
'''
# compute Stokes spatial gradients
Q_grad_y,Q_grad_x = np.gradient(Q)
U_grad_y,U_grad_x = np.gradient(U)
# compute spatial polarization gradient
a = Q_grad_x**2.+Q_grad_y**2.+U_grad_x**2.+U_grad_y**2.
b = a**2. - 4.*(Q_grad_x*U_grad_y - Q_grad_y*U_grad_x)**2.
# compute polarization gradient
polgrad = np.sqrt(0.5*a + 0.5*np.sqrt(b))
# compute the polarized intensity
P = np.sqrt(Q**2.+U**2.)
# compute normalized polarization gradient
polgrad_norm = polgrad/P
return polgrad_norm
def fpolgradarg(Q,U,parallel=False,deg=True):
'''
Computes the argument of the polarization gradient.
See the equation in the caption of Figure 2 in Gaensler et al. (2011).
Input
Q : Stokes Q data
U : Stokes U data
parallel : if True, compute angle parallel (rather then perpendicular) to polarization gradient structures (default=False)
deg : if True, converts the argument to degrees for output
Output
polgrad_arg : argument of polarization gradient
'''
# compute Stokes spatial gradients
Q_grad_y,Q_grad_x = np.gradient(Q)
U_grad_y,U_grad_x = np.gradient(U)
# compute argument of polarization gradient
a = np.sign(Q_grad_x*Q_grad_y + U_grad_x*U_grad_y)
b = np.sqrt(Q_grad_y**2.+U_grad_y**2.)
c = np.sqrt(Q_grad_x**2.+U_grad_x**2.)
polgrad_arg = np.arctan(a*b/c) # angle measured from the x-axis on [-pi/2,+pi/2] in radians
if parallel==True:
# compute argument angle parallel to filaments from North (like the RHT)
polgrad_arg += np.pi/2. # angle measured from the y-axis on [0,pi] in radians
if deg==True:
# convert to degrees
polgrad_arg = np.degrees(polgrad_arg)
return polgrad_arg
def fpolgradarg_crossterms(Q,U,parallel=False,deg=True):
'''
Computes the argument of the polarization gradint with cross-terms.
See Equations 13 and 14 in Herron et al. (2018) paper I.
Input
Q : Stokes Q map
U : Stokes U map
parallel : if True, compute angle parallel (rather then perpendicular) to polarization gradient structures
deg : if True, converts to degrees at the end
Output
polgrad_arg : argument of polarization gradient
'''
# compute Stokes spatial gradients
Q_grad_y,Q_grad_x = np.gradient(Q)
U_grad_y,U_grad_x = np.gradient(U)
# compute the cos(2*theta) term
cos2theta_num = -(Q_grad_y**2. - Q_grad_x**2. + U_grad_y**2. - U_grad_x**2.)
cos2theta_den = np.sqrt((Q_grad_x**2. + Q_grad_y**2. + U_grad_x**2. + U_grad_y**2.)**2. - 4.*(Q_grad_x*U_grad_y - Q_grad_y*U_grad_x)**2.)
cos2theta = cos2theta_num/cos2theta_den
# compute the sin(2*theta) term
sin2theta_num = 2.*(Q_grad_x*Q_grad_y + U_grad_x*U_grad_y)
sin2theta_den = np.sqrt((Q_grad_x**2. + Q_grad_y**2. + U_grad_x**2. + U_grad_y**2.)**2. - 4.*(Q_grad_x*U_grad_y - Q_grad_y*U_grad_x)**2.)
sin2theta = sin2theta_num/sin2theta_den
# compute tan(theta)
tantheta_num = sin2theta
tantheta_den = 1.+cos2theta
# take inverse tan to compute argument
polgrad_arg = np.arctan2(tantheta_num,tantheta_den) # angle measured from the x-axis on [-pi,+pi] in radians
# transform angles from [-pi,pi] to [-pi/2,pi/2]
polgrad_arg[polgrad_arg<-np.pi/2.] += np.pi
polgrad_arg[polgrad_arg>np.pi/2.] += np.pi
if parallel==True:
# compute argument angle parallel to filaments from North (like the RHT)
polgrad_arg += np.pi/2. # angle measures from the y-axis on [0,pi] in radians
if deg==True:
# convert to degrees
polgrad_arg = np.degrees(polgrad_arg)
return polgrad_arg
def fargmask(angles,min,max):
'''
Creates a mask for the argument of polarization gradient based on an input of angle range(s).
Inputs
angles : angle map
min : minimum of the range of angles to be masked (can be single-valued or a list/array)
max : maximum of the range of angles to be masked (can be single-valued or a list/array)
Output
mask : a mask the same size as the angle map
'''
# initialize mask
mask = np.ones(shape=angles.shape)
# fill in mask using input angles
for i in range(len(min)):
mask_i = np.copy(mask)
min_i = min[i]
max_i = max[i]
mask_angles = np.where((angles>=min_i) & (angles<=max_i))
mask_i[mask_angles] = np.nan
mask *=mask_i
return mask
def fpolgrad_rad(Q,U):
'''
Computes the radial component of the polarization gradient.
See Equation 22 in Herron et al. (2018).
Input
Q : Stokes Q map
U : Stokes U map
Output
polgrad_rad : radial component of the polarization gradient
'''
# compute Stokes spatial gradients
Q_grad_y,Q_grad_x = np.gradient(Q)
U_grad_y,U_grad_x = np.gradient(U)
polgrad_rad_num = (Q*Q_grad_x+U*U_grad_x)**2. + (Q*Q_grad_y+U*U_grad_y)**2.
polgrad_rad_den = Q**2.+U**2.
# compute radial component of polarization gradient
polgrad_rad = np.sqrt(polgrad_rad_num/polgrad_rad_den)
return polgrad_rad
def fpolgrad_tan(Q,U):
'''
Computes the tangential component of the polarization gradient.
See Equation 25 in Herron et al. (2018).
Input
Q : Stokes Q map
U : Stokes U map
Output
polgrad_tan : tangential component of the polarization gradient
'''
# compute Stokes spatial gradients
Q_grad_y,Q_grad_x = np.gradient(Q)
U_grad_y,U_grad_x = np.gradient(U)
polgrad_tan_num = (Q*U_grad_x+U*Q_grad_x)**2. + (Q*U_grad_y-U*Q_grad_y)**2.
polgrad_tan_den = Q**2.+U**2.
# compute tangential component of polarization gradient
polgrad_tan = np.sqrt(polgrad_tan_num/polgrad_tan_den)
return polgrad_tan
def fgradchi(Q,U):
'''
Computes the angular version of the polarization gradient.
See Equation 6 in Planck XII (2018).
Input
Q : Stokes Q
U : Stokes U
Output
gradchi :
'''
# compute polarized intensity
P = fPI(Q,U)
# compute main terms in gradphi
QP = Q/P
UP = U/P
# compute Stokes spatial gradients
QP_grad_y,QP_grad_x = np.gradient(QP)
UP_grad_y,UP_grad_x = np.gradient(UP)
# compute gradient of angular component
gradchi = np.sqrt((QP_grad_x)**2. + (QP_grad_y)**2. + (UP_grad_x)**2. + (UP_grad_y)**2.)
return gradchi
def fSest(Q,U,delta):
'''
Computes an estimate of the polarization angle dispersion function.
See Equation 7 in Planck XII (2018).
Input
Q : Stokes Q
U : Stokes U
delta : lag in pixels
'''
# compute gradient of polarization angle
gradchi = fgradchi(Q,U)
# compute Sest
Sest = delta*gradchi/(2.*np.sqrt(2.))
return Sest
def fderotate(pangle,RM,freq,inunit,outunit):
'''
Computes the de-rotated polarization angles.
Input
pangle : polarization angle [degrees or radians]
RM : rotation measure [rad/m^2]
freq : frequency channels [Hz]
inunit : units of input polarization angle [degrees or radians]
outunit : units of output polarization angle [degrees or radians]
'''
# compute weighted average of wavelength squared
wavel_sq = fwavel(freq)**2.
weights = np.ones(shape=wavel_sq.shape)
K = 1.0/np.sum(weights)
wavel_0_sq = K*np.sum(weights*wavel_sq)
degree_units = ["deg","degree","degrees"]
rad_units = ["rad","radian","radians"]
if inunit in degree_units:
# if input polarization angle is in degrees
pangle_deg = pangle
pangle_rad = np.radians(pangle)
elif inunit in rad_units:
# if input polarization angle is in radians
pangle_rad = pangle
pangle_deg = np.degrees(pangle)
pangle_0_rad = np.mod(pangle_rad-RM*wavel_0_sq,np.pi)
pangle_0_deg = np.degrees(pangle_0_rad)
if outunit in degree_units:
# if output polarization angle is in degrees
pangle_0 = pangle_0_deg
elif outunit in rad_units:
# if output polarization angle is in radians
pangle_0 = pangle_0_rad
return pangle_0
def fderotate_err(RMSF_FWHM,SNR,lambda_sq,deg=True):
'''
Commputes the uncertainty in de-rotated polarization angles.
Input
RMSF_FWHM : the FWHM of the RMSF [rad/m^2]
SNR : signal-to-noise [dimensionless]
lambda_sq : wavelength^2 [m^2]
deg : if true, converts uncertainty to degrees [default=True]
Output
derotate_err : unceertainty in de-rotated angles [deg]
'''
derotate_err = (RMSF_FWHM/(2.*SNR))*lambda_sq
if deg==True:
derotate_err = np.degrees(derotate_err)
return derotate_err
def fRM_err(RMSF_FWHM,SNR):
'''
Commputes the uncertainty in the rotation measure (RM).
Input
RMSF_FWHM : the FWHM of the RMSF [rad/m^2]
SNR : signal-to-noise [dimensionless]
Output
derotate_err : unceertainty in de-rotated angles [deg]
'''
RM_err = (RMSF_FWHM/(2.*SNR))
return RM_err
def fpolgradargdict(polgrad_arg):
'''
Creates a dictionary of polarization gradient arguments for each pixel in the image plane.
Input
polgrad_arg : two-dimensional image of polarization gradient argument
Output
polgrad_arg_dict : dictionary of polarization gradient argument with pixel coordinate keys
ijpoints : tuple of pixel coordinates
'''
polgrad_arg_dict = {}
ijpoints = []
NAXIS2,NAXIS1 = polgrad_arg.shape
for j in range(NAXIS2):
for i in range(NAXIS1):
arg = polgrad_arg[j,i]
polgrad_arg_dict[i,j]=arg
ijpoints.append((i,j))
return polgrad_arg_dict,ijpoints
def fplotvectors(imagefile,anglefile,deltapix=5,scale=1.,angleunit="deg",coords="wcs",figsize=(20,10)):
'''
Plots an image with pseudovectors.
Input
imagefile : image directory
anglefile : angle map directory
deltapix : the spacing of image pixels to draw pseudovectors
scale : a scalefactor for the length of the pseudovectors
angleunit : the unit of the input angle map (can be deg/degree/degrees or rad/radian/radians)
Output
Saves the image in the same directory as imagefile with "_angles.pdf" as the filename extension
'''
degree_units = ["deg","degree","degrees"]
radian_units = ["rad","radian","radians"]
wcs_units = ["wcs","WCS","world"]
pixel_units = ["pix","pixel","pixels"]
if coords in wcs_units:
# extract image data and WCS header
image,header = fits.getdata(imagefile,header=True)
NAXIS1,NAXIS2 = header["NAXIS1"],header["NAXIS2"]
w = wcs.WCS(header)
elif coords in pixel_units:
# extract image data
image = fits.getdata(imagefile)
NAXIS2,NAXIS1 = image.shape
# extract angle data
angles = fits.getdata(anglefile)
linelist_pix = []
linelist_wcs = []
for y in range(0,NAXIS2,deltapix):
# iterate through y pixels
for x in range(0,NAXIS1,deltapix):
# iterate through x pixels
image_xy = image[y,x]
if np.isnan(image_xy)==False:
# do not plot angle if image data is NaN
if angleunit in degree_units:
# convert angles to radians
angles_deg = np.copy(angles)
angles_rad = np.radians(angles)
elif angleunit in radian_units:
# convert angles to degrees
angles_deg = np.degrees(angles)
angles_rad = np.copy(angles)
else:
# raise error
print("Input angleunit is not defined.")
sys.exit() # pol_angle = np.mod(0.5*np.arctan2(U,Q), np.pi)
angle_rad = angles_rad[y,x]
angle_deg = angles_deg[y,x]
amp = image[y,x]*100.*scale
# create line segment in pixel coordinates
(x1_pix,y1_pix) = (x-amp*np.sin(angle_rad),y+amp*np.cos(angle_rad))
(x2_pix,y2_pix) = (x+amp*np.sin(angle_rad),y-amp*np.cos(angle_rad))
line_pix = np.array([(x1_pix,y1_pix),(x2_pix,y2_pix)])
if coords in pixel_units:
linelist_pix.append(line_pix)
elif coords in wcs_units:
# create line segment in WCS coordinates (units of degrees)
x1_wcs,y1_wcs = w.wcs_pix2world(x1_pix,y1_pix,0)
x2_wcs,y2_wcs = w.wcs_pix2world(x2_pix,y2_pix,0)
line_wcs = np.array([(x1_wcs,x2_wcs),(y1_wcs,y2_wcs)])
linelist_wcs.append(line_wcs)
# plot figure
if coords in pixel_units:
# replace NaNs with zeros just for plotting visuals
image[np.isnan(image)==True] = 0.0
fig = plt.figure(figsize=figsize)
ax = fig.add_subplot(111)
im = ax.imshow(image,vmax=0.05,cmap="Greys_r",origin="lower")
plt.xlabel("pixels")
plt.ylabel("pixels")
lc = LineCollection(linelist_pix,color="red")
plt.gca().add_collection(lc)
plt.colorbar(im, ax=ax, orientation="vertical")
plt.show()
plt.savefig(imagefile.split(".fits")[0]+"_angles.pdf")
elif coords in wcs_units:
fig = plt.figure(figsize=figsize)
# colorscale
f = aplpy.FITSFigure(imagefile,figure=fig)
#f.show_grayscale()
f.show_colorscale(cmap="hot",vmin=0.0,vmax=0.03)
f.set_nan_color("black")
# pseudovectors
f.show_lines(linelist_wcs,layer="vectors",color="white",linewidth=0.5)
# tick coordinates
f.tick_labels.set_xformat("hh:mm")
f.tick_labels.set_yformat("dd")
# axis labels
f.axis_labels.set_font(size=20)
# tick labels
f.tick_labels.show()
f.tick_labels.set_font(size=20)
# colour bar
f.add_colorbar()
f.colorbar.set_axis_label_text(r"$|\vec{\nabla}\vec{P}|_\mathrm{max}\,\mathrm{(K/arcmin)}$")
#f.colorbar.set_axis_label_text(r"$I_{857}\,\mathrm{(MJy/sr)}$")
f.colorbar.set_axis_label_font(size=20)
# scale bar
f.add_scalebar(5.,color="white",corner="top left")
f.scalebar.set_label("5 degrees")
f.scalebar.set_font(size=20)
# remove whitespace
plt.subplots_adjust(top=1,bottom=0,right=1,left=0,hspace=0,wspace=0)
fig.canvas.draw()
f.save(imagefile.split(".fits")[0]+"_angles.pdf")
def frun_RM1d_iterate(do_RMsynth_1D_dir,Q_filedir,U_filedir,Q_err,U_err,freq_Hz_filedir,rmsynth_inputfiledir,options):
'''
Iteratively runs 1D RM synthesis on a cube of data.
Input
do_RMsynth_1D_dir :
Q_filedir :
U_filedir :
Q_err :
U_err :
freq_Hz_filedir :
rmsynth_inputfiledir :
options :
Output
'''
rmsynth_outputfiledir = rmsynth_inputfiledir.split(".")[0]+"_RMsynth."+rmsynth_inputfiledir.split(".")[-1]
# extract data
Q_data = fits.getdata(Q_filedir)
U_data = fits.getdata(U_filedir)
freq_Hz_data = np.loadtxt(freq_Hz_filedir)
Q_header_2D = fheader_3Dto2D(Q_filedir,Q_filedir,write=False)
# turn uncertainties into arrays
sigma_Q = np.ones(shape=Q_data.shape[0])*Q_err
sigma_U = np.ones(shape=U_data.shape[0])*U_err
# create nan arrays to later replace with RM synthesis results
dFDFcorMAD = np.ones(shape=(Q_data.shape[1],Q_data.shape[2]))*np.nan
dFDFrms = np.ones(shape=(Q_data.shape[1],Q_data.shape[2]))*np.nan
phiPeakPIchan_rm2 = np.ones(shape=(Q_data.shape[1],Q_data.shape[2]))*np.nan
dPhiPeakPIchan_rm2 = np.ones(shape=(Q_data.shape[1],Q_data.shape[2]))*np.nan
ampPeakPIchan = np.ones(shape=(Q_data.shape[1],Q_data.shape[2]))*np.nan
ampPeakPIchanEff = np.ones(shape=(Q_data.shape[1],Q_data.shape[2]))*np.nan
dAmpPeakPIchan = np.ones(shape=(Q_data.shape[1],Q_data.shape[2]))*np.nan
snrPIchan = np.ones(shape=(Q_data.shape[1],Q_data.shape[2]))*np.nan
indxPeakPIchan = np.ones(shape=(Q_data.shape[1],Q_data.shape[2]))*np.nan
peakFDFimagChan = np.ones(shape=(Q_data.shape[1],Q_data.shape[2]))*np.nan
peakFDFrealChan = np.ones(shape=(Q_data.shape[1],Q_data.shape[2]))*np.nan
polAngleChan_deg = np.ones(shape=(Q_data.shape[1],Q_data.shape[2]))*np.nan
dPolAngleChan_deg = np.ones(shape=(Q_data.shape[1],Q_data.shape[2]))*np.nan
polAngle0Chan_deg = np.ones(shape=(Q_data.shape[1],Q_data.shape[2]))*np.nan
dPolAngle0Chan_deg = np.ones(shape=(Q_data.shape[1],Q_data.shape[2]))*np.nan
phiPeakPIfit_rm2 = np.ones(shape=(Q_data.shape[1],Q_data.shape[2]))*np.nan
dPhiPeakPIfit_rm2 = np.ones(shape=(Q_data.shape[1],Q_data.shape[2]))*np.nan
ampPeakPIfit = np.ones(shape=(Q_data.shape[1],Q_data.shape[2]))*np.nan
ampPeakPIfitEff = np.ones(shape=(Q_data.shape[1],Q_data.shape[2]))*np.nan
dAmpPeakPIfit = np.ones(shape=(Q_data.shape[1],Q_data.shape[2]))*np.nan
snrPIfit = np.ones(shape=(Q_data.shape[1],Q_data.shape[2]))*np.nan
indxPeakPIfit = np.ones(shape=(Q_data.shape[1],Q_data.shape[2]))*np.nan
peakFDFimagFit = np.ones(shape=(Q_data.shape[1],Q_data.shape[2]))*np.nan
peakFDFrealFit = np.ones(shape=(Q_data.shape[1],Q_data.shape[2]))*np.nan
polAngleFit_deg = np.ones(shape=(Q_data.shape[1],Q_data.shape[2]))*np.nan
dPolAngleFit_deg = np.ones(shape=(Q_data.shape[1],Q_data.shape[2]))*np.nan
polAngle0Fit_deg = np.ones(shape=(Q_data.shape[1],Q_data.shape[2]))*np.nan
dPolAngle0Fit_deg = np.ones(shape=(Q_data.shape[1],Q_data.shape[2]))*np.nan
Ifreq0 = np.ones(shape=(Q_data.shape[1],Q_data.shape[2]))*np.nan
#polyCoeffs = np.ones(shape=(Q_data.shape[1],Q_data.shape[2]))*np.nan
IfitStat = np.ones(shape=(Q_data.shape[1],Q_data.shape[2]))*np.nan
IfitChiSqRed = np.ones(shape=(Q_data.shape[1],Q_data.shape[2]))*np.nan
lam0Sq_m2 = np.ones(shape=(Q_data.shape[1],Q_data.shape[2]))*np.nan
freq0_Hz = np.ones(shape=(Q_data.shape[1],Q_data.shape[2]))*np.nan
fwhmRMSF = np.ones(shape=(Q_data.shape[1],Q_data.shape[2]))*np.nan
dQU = np.ones(shape=(Q_data.shape[1],Q_data.shape[2]))*np.nan
dFDFth = np.ones(shape=(Q_data.shape[1],Q_data.shape[2]))*np.nan
#units = np.ones(shape=(Q_data.shape[1],Q_data.shape[2]))*np.nan
min_freq = np.ones(shape=(Q_data.shape[1],Q_data.shape[2]))*np.nan
max_freq = np.ones(shape=(Q_data.shape[1],Q_data.shape[2]))*np.nan
N_channels = np.ones(shape=(Q_data.shape[1],Q_data.shape[2]))*np.nan
median_channel_width = np.ones(shape=(Q_data.shape[1],Q_data.shape[2]))*np.nan
fracPol = np.ones(shape=(Q_data.shape[1],Q_data.shape[2]))*np.nan
sigmaAddQ = np.ones(shape=(Q_data.shape[1],Q_data.shape[2]))*np.nan
dSigmaAddMinusQ = np.ones(shape=(Q_data.shape[1],Q_data.shape[2]))*np.nan
dSigmaAddPlusQ = np.ones(shape=(Q_data.shape[1],Q_data.shape[2]))*np.nan
sigmaAddU = np.ones(shape=(Q_data.shape[1],Q_data.shape[2]))*np.nan