-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathuvbeam.py
More file actions
1960 lines (1672 loc) · 95.9 KB
/
uvbeam.py
File metadata and controls
1960 lines (1672 loc) · 95.9 KB
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
# -*- mode: python; coding: utf-8 -*
# Copyright (c) 2018 Radio Astronomy Software Group
# Licensed under the 2-clause BSD License
"""Primary container for radio telescope antenna beams.
"""
from __future__ import absolute_import, division, print_function
import numpy as np
import warnings
import copy
from scipy import interpolate
from .uvbase import UVBase
from . import parameter as uvp
from . import utils as uvutils
class UVBeam(UVBase):
"""
A class for defining a radio telescope antenna beam.
Attributes:
UVParameter objects: For full list see UVBeam Parameters
(http://pyuvdata.readthedocs.io/en/latest/uvbeam_parameters.html).
Some are always required, some are required for certain beam_types,
antenna_types and pixel_coordinate_systems and others are always optional.
"""
coordinate_system_dict = {
'az_za': {'axes': ['azimuth', 'zen_angle'],
'description': 'uniformly gridded azimuth, zenith angle coordinate system, '
'where az runs from East to North in radians'},
'orthoslant_zenith': {'axes': ['zenorth_x', 'zenorth_y'],
'description': 'orthoslant projection at zenith where y points North, '
'x point East'},
'healpix': {'axes': ['hpx_inds'],
'description': 'HEALPix map with zenith at the north pole and '
'az, za coordinate axes (for the basis_vector_array) '
'where az runs from East to North'}}
interpolation_function_dict = {'az_za_simple': '_interp_az_za_rect_spline'}
def __init__(self):
"""Create a new UVBeam object."""
# add the UVParameters to the class
self._Nfreqs = uvp.UVParameter('Nfreqs', description='Number of frequency channels',
expected_type=int)
self._Nspws = uvp.UVParameter('Nspws', description='Number of spectral windows '
'(ie non-contiguous spectral chunks). '
'More than one spectral window is not '
'currently supported.', expected_type=int)
desc = ('Number of basis vectors specified at each pixel, options '
'are 2 or 3 (or 1 if beam_type is "power")')
self._Naxes_vec = uvp.UVParameter('Naxes_vec', description=desc,
expected_type=int, acceptable_vals=[2, 3])
desc = ('Number of basis vectors components specified at each pixel, options '
'are 2 or 3. Only required for E-field beams.')
self._Ncomponents_vec = uvp.UVParameter('Ncomponents_vec', description=desc,
expected_type=int, acceptable_vals=[2, 3], required=False)
desc = ('Pixel coordinate system, options are: "'
+ '", "'.join(list(self.coordinate_system_dict.keys())) + '".')
for key in self.coordinate_system_dict:
desc = desc + (' "' + key + '" is a ' + self.coordinate_system_dict[key]['description']
+ '. It has axes [' + ', '.join(self.coordinate_system_dict[key]['axes']) + '].')
self._pixel_coordinate_system = uvp.UVParameter('pixel_coordinate_system',
description=desc, form='str',
expected_type=str,
acceptable_vals=list(self.coordinate_system_dict.keys()))
desc = ('Number of elements along the first pixel axis. '
'Not required if pixel_coordinate_system is "healpix".')
self._Naxes1 = uvp.UVParameter('Naxes1', description=desc, expected_type=int,
required=False)
desc = ('Coordinates along first pixel axis. '
'Not required if pixel_coordinate_system is "healpix".')
self._axis1_array = uvp.UVParameter('axis1_array', description=desc,
expected_type=np.float,
required=False, form=('Naxes1',))
desc = ('Number of elements along the second pixel axis. '
'Not required if pixel_coordinate_system is "healpix".')
self._Naxes2 = uvp.UVParameter('Naxes2', description=desc, expected_type=int,
required=False)
desc = ('Coordinates along second pixel axis. '
'Not required if pixel_coordinate_system is "healpix".')
self._axis2_array = uvp.UVParameter('axis2_array', description=desc,
expected_type=np.float,
required=False, form=('Naxes2',))
desc = ('Healpix nside parameter. Only required if pixel_coordinate_system is "healpix".')
self._nside = uvp.UVParameter('nside', description=desc, expected_type=int,
required=False)
desc = ('Healpix ordering parameter, allowed values are "ring" and "nested". '
'Only required if pixel_coordinate_system is "healpix".')
self._ordering = uvp.UVParameter('ordering', description=desc, expected_type=str,
required=False, acceptable_vals=['ring', 'nested'])
desc = ('Number of healpix pixels. Only required if pixel_coordinate_system is "healpix".')
self._Npixels = uvp.UVParameter('Npixels', description=desc, expected_type=int,
required=False)
desc = ('Healpix pixel numbers. Only required if pixel_coordinate_system is "healpix".')
self._pixel_array = uvp.UVParameter('pixel_array', description=desc, expected_type=int,
required=False, form=('Npixels',))
desc = 'String indicating beam type. Allowed values are "efield", and "power".'
self._beam_type = uvp.UVParameter('beam_type', description=desc, form='str',
expected_type=str,
acceptable_vals=['efield', 'power'])
desc = ('Beam basis vector components -- directions for which the '
'electric field values are recorded in the pixel coordinate system. '
'Not required if beam_type is "power". The shape depends on the '
'pixel_coordinate_system, if it is "healpix", the shape is: '
'(Naxes_vec, Ncomponents_vec, Npixels), otherwise it is '
'(Naxes_vec, Ncomponents_vec, Naxes2, Naxes1)')
self._basis_vector_array = uvp.UVParameter('basis_vector_array',
description=desc, required=False,
expected_type=np.float,
form=('Naxes_vec', 'Ncomponents_vec', 'Naxes2', 'Naxes1'),
acceptable_range=(0, 1),
tols=1e-3)
self._Nfeeds = uvp.UVParameter('Nfeeds', description='Number of feeds. '
'Not required if beam_type is "power".',
expected_type=int, acceptable_vals=[1, 2],
required=False)
desc = ('Array of feed orientations. shape (Nfeeds). '
'options are: N/E or x/y or R/L. Not required if beam_type is "power".')
self._feed_array = uvp.UVParameter('feed_array', description=desc, required=False,
expected_type=str, form=('Nfeeds',),
acceptable_vals=['N', 'E', 'x', 'y',
'R', 'L'])
self._Npols = uvp.UVParameter('Npols', description='Number of polarizations. '
'Only required if beam_type is "power".',
expected_type=int, required=False)
desc = ('Array of polarization integers, shape (Npols). '
'Uses the same convention as UVData: pseudo-stokes 1:4 (pI, pQ, pU, pV); '
'circular -1:-4 (RR, LL, RL, LR); linear -5:-8 (XX, YY, XY, YX). '
'Only required if beam_type is "power".')
self._polarization_array = uvp.UVParameter('polarization_array',
description=desc, required=False,
expected_type=int, form=('Npols',),
acceptable_vals=list(np.arange(-8, 0)) + list(np.arange(1, 5)))
desc = 'Array of frequencies, shape (Nspws, Nfreqs), units Hz'
self._freq_array = uvp.UVParameter('freq_array', description=desc,
form=('Nspws', 'Nfreqs'),
expected_type=np.float,
tols=1e-3) # mHz
self._spw_array = uvp.UVParameter('spw_array',
description='Array of spectral window '
'Numbers, shape (Nspws)', form=('Nspws',),
expected_type=int)
desc = ('Normalization standard of data_array, options are: '
'"physical", "peak" or "solid_angle". Physical normalization '
'means that the frequency dependence of the antenna sensitivity '
'is included in the data_array while the frequency dependence '
'of the receiving chain is included in the bandpass_array. '
'Peak normalized means that for each frequency the data_array'
'is separately normalized such that the peak is 1 (so the beam '
'is dimensionless) and all direction-independent frequency '
'dependence is moved to the bandpass_array (if the beam_type is "efield", '
'then peak normalized means that the absolute value of the peak is 1). '
'Solid angle normalized means the peak normalized '
'beam is divided by the integral of the beam over the sphere, '
'so the beam has dimensions of 1/stradian.')
self._data_normalization = uvp.UVParameter('data_normalization', description=desc,
form='str', expected_type=str,
acceptable_vals=["physical", "peak", "solid_angle"])
desc = ('Depending on beam type, either complex E-field values ("efield" beam type) '
'or power values ("power" beam type) for beam model. units are linear '
'normalized to either peak or solid angle as given by data_normalization. '
'The shape depends on the beam_type and pixel_coordinate_system, if it is '
'"healpix", the shape is: (Naxes_vec, Nspws, Nfeeds or Npols, Nfreqs, Npixels), '
'otherwise it is (Naxes_vec, Nspws, Nfeeds or Npols, Nfreqs, Naxes2, Naxes1)')
self._data_array = uvp.UVParameter('data_array', description=desc,
expected_type=np.complex,
form=('Naxes_vec', 'Nspws', 'Nfeeds',
'Nfreqs', 'Naxes2', 'Naxes1'),
tols=1e-3)
desc = ('Frequency dependence of the beam. Depending on the data_normalization, '
'this may contain only the frequency dependence of the receiving '
'chain ("physical" normalization) or all the frequency dependence '
'("peak" normalization).')
self._bandpass_array = uvp.UVParameter('bandpass_array', description=desc,
expected_type=np.float,
form=('Nspws', 'Nfreqs'),
tols=1e-3)
# --------- metadata -------------
self._telescope_name = uvp.UVParameter('telescope_name',
description='Name of telescope '
'(string)', form='str',
expected_type=str)
self._feed_name = uvp.UVParameter('feed_name',
description='Name of physical feed '
'(string)', form='str',
expected_type=str)
self._feed_version = uvp.UVParameter('feed_version',
description='Version of physical feed '
'(string)', form='str',
expected_type=str)
self._model_name = uvp.UVParameter('model_name',
description='Name of beam model '
'(string)', form='str',
expected_type=str)
self._model_version = uvp.UVParameter('model_version',
description='Version of beam model '
'(string)', form='str',
expected_type=str)
self._history = uvp.UVParameter('history', description='String of history, units English',
form='str', expected_type=str)
# ---------- phased_array stuff -------------
desc = ('String indicating antenna type. Allowed values are "simple", and '
'"phased_array"')
self._antenna_type = uvp.UVParameter('antenna_type', form='str', expected_type=str,
description=desc,
acceptable_vals=['simple', 'phased_array'])
desc = ('Required if antenna_type = "phased_array". Number of elements '
'in phased array')
self._Nelements = uvp.UVParameter('Nelements', required=False,
description=desc, expected_type=int)
desc = ('Required if antenna_type = "phased_array". Element coordinate '
'system, options are: N-E or x-y')
self._element_coordinate_system = \
uvp.UVParameter('element_coordinate_system', required=False,
description=desc, expected_type=str,
acceptable_vals=['N-E', 'x-y'])
desc = ('Required if antenna_type = "phased_array". Array of element '
'locations in element coordinate system, shape: (2, Nelements)')
self._element_location_array = uvp.UVParameter('element_location_array',
required=False,
description=desc,
form=('2', 'Nelements'),
expected_type=np.float)
desc = ('Required if antenna_type = "phased_array". Array of element '
'delays, units: seconds, shape: (Nelements)')
self._delay_array = uvp.UVParameter('delay_array', required=False,
description=desc,
form=('Nelements',),
expected_type=np.float)
desc = ('Required if antenna_type = "phased_array". Array of element '
'gains, units: dB, shape: (Nelements)')
self._gain_array = uvp.UVParameter('gain_array', required=False,
description=desc,
form=('Nelements',),
expected_type=np.float)
desc = ('Required if antenna_type = "phased_array". Matrix of complex '
'element couplings, units: dB, '
'shape: (Nelements, Nelements, Nfeed, Nfeed, Nspws, Nfreqs)')
self._coupling_matrix = uvp.UVParameter('coupling_matrix', required=False,
description=desc,
form=('Nelements', 'Nelements',
'Nfeed', 'Nfeed', 'Nspws', 'Nfreqs'),
expected_type=np.complex)
# -------- extra, non-required parameters ----------
desc = ('String indicating interpolation function. Must be set to use '
'the interp_* methods. Allowed values are : "'
+ '", "'.join(list(self.interpolation_function_dict.keys())) + '".')
self._interpolation_function = uvp.UVParameter('interpolation_function',
required=False,
form='str', expected_type=str,
description=desc,
acceptable_vals=list(self.interpolation_function_dict.keys()))
desc = ('Any user supplied extra keywords, type=dict. Keys should be '
'8 character or less strings if writing to beam fits files. '
'Use the special key "comment" for long multi-line string comments.')
self._extra_keywords = uvp.UVParameter('extra_keywords', required=False,
description=desc, value={},
spoof_val={}, expected_type=dict)
desc = ('Reference input impedance of the receiving chain (sets the reference '
'for the S parameters), units: Ohms')
self._reference_input_impedance = uvp.UVParameter('reference_input_impedance', required=False,
description=desc,
expected_type=np.float, tols=1e-3)
desc = ('Reference output impedance of the receiving chain (sets the reference '
'for the S parameters), units: Ohms')
self._reference_output_impedance = uvp.UVParameter('reference_output_impedance', required=False,
description=desc,
expected_type=np.float, tols=1e-3)
desc = 'Array of receiver temperatures, shape (Nspws, Nfreqs), units K'
self._receiver_temperature_array = \
uvp.UVParameter('receiver_temperature_array', required=False,
description=desc, form=('Nspws', 'Nfreqs'),
expected_type=np.float, tols=1e-3)
desc = 'Array of antenna losses, shape (Nspws, Nfreqs), units dB?'
self._loss_array = uvp.UVParameter('loss_array', required=False,
description=desc, form=('Nspws', 'Nfreqs'),
expected_type=np.float,
tols=1e-3)
desc = 'Array of antenna-amplifier mismatches, shape (Nspws, Nfreqs), units ?'
self._mismatch_array = uvp.UVParameter('mismatch_array', required=False,
description=desc,
form=('Nspws', 'Nfreqs'),
expected_type=np.float,
tols=1e-3)
desc = ('S parameters of receiving chain, shape (4, Nspws, Nfreqs), '
'ordering: s11, s12, s21, s22. see '
'https://en.wikipedia.org/wiki/Scattering_parameters#Two-Port_S-Parameters')
self._s_parameters = uvp.UVParameter('s_parameters', required=False,
description=desc,
form=(4, 'Nspws', 'Nfreqs'),
expected_type=np.float,
tols=1e-3)
super(UVBeam, self).__init__()
def check(self, check_extra=True, run_check_acceptability=True):
"""
Check that all required parameters are set reasonably.
Check that required parameters exist and have appropriate shapes.
Optionally check if the values are acceptable.
Args:
check_extra: Option to check optional parameters as well as
required ones. Default is True.
run_check_acceptability: Option to check if values in required parameters
are acceptable. Default is True.
"""
# first make sure the required parameters and forms are set properly
# for the pixel_coordinate_system
self.set_cs_params()
# first run the basic check from UVBase
super(UVBeam, self).check(check_extra=check_extra,
run_check_acceptability=run_check_acceptability)
# check that basis_vector_array are basis vectors
if self.basis_vector_array is not None:
if np.max(np.linalg.norm(self.basis_vector_array, axis=1)) > (1 + 1e-15):
raise ValueError('basis vectors must have lengths of 1 or less.')
# issue warning if extra_keywords keys are longer than 8 characters
for key in list(self.extra_keywords.keys()):
if len(key) > 8:
warnings.warn('key {key} in extra_keywords is longer than 8 '
'characters. It will be truncated to 8 if written '
'to a fits file format.'.format(key=key))
# issue warning if extra_keywords values are lists, arrays or dicts
for key, value in self.extra_keywords.items():
if isinstance(value, (list, dict, np.ndarray)):
warnings.warn('{key} in extra_keywords is a list, array or dict, '
'which will raise an error when writing fits '
'files'.format(key=key))
return True
def set_cs_params(self):
"""
Set various forms and required parameters depending on pixel_coordinate_system.
"""
if self.pixel_coordinate_system == 'healpix':
self._Naxes1.required = False
self._axis1_array.required = False
self._Naxes2.required = False
self._axis2_array.required = False
self._nside.required = True
self._ordering.required = True
self._Npixels.required = True
self._pixel_array.required = True
self._basis_vector_array.form = ('Naxes_vec', 'Ncomponents_vec', 'Npixels')
if self.beam_type == "power":
self._data_array.form = ('Naxes_vec', 'Nspws', 'Npols', 'Nfreqs',
'Npixels')
else:
self._data_array.form = ('Naxes_vec', 'Nspws', 'Nfeeds', 'Nfreqs',
'Npixels')
else:
self._Naxes1.required = True
self._axis1_array.required = True
self._Naxes2.required = True
self._axis2_array.required = True
if self.pixel_coordinate_system == 'az_za':
self._axis1_array.acceptable_range = [0, 2. * np.pi]
self._axis2_array.acceptable_range = [0, np.pi]
self._nside.required = False
self._ordering.required = False
self._Npixels.required = False
self._pixel_array.required = False
self._basis_vector_array.form = ('Naxes_vec', 'Ncomponents_vec', 'Naxes2', 'Naxes1')
if self.beam_type == "power":
self._data_array.form = ('Naxes_vec', 'Nspws', 'Npols', 'Nfreqs',
'Naxes2', 'Naxes1')
else:
self._data_array.form = ('Naxes_vec', 'Nspws', 'Nfeeds', 'Nfreqs',
'Naxes2', 'Naxes1')
def set_efield(self):
"""Set beam_type to 'efield' and adjust required parameters."""
self.beam_type = 'efield'
self._Naxes_vec.acceptable_vals = [2, 3]
self._Ncomponents_vec.required = True
self._basis_vector_array.required = True
self._Nfeeds.required = True
self._feed_array.required = True
self._Npols.required = False
self._polarization_array.required = False
self._data_array.expected_type = np.complex
# call set_cs_params to fix data_array form
self.set_cs_params()
def set_power(self):
"""Set beam_type to 'power' and adjust required parameters."""
self.beam_type = 'power'
self._Naxes_vec.acceptable_vals = [1, 2, 3]
self._basis_vector_array.required = False
self._Ncomponents_vec.required = False
self._Nfeeds.required = False
self._feed_array.required = False
self._Npols.required = True
self._polarization_array.required = True
# If cross pols are included, the power beam is complex. Otherwise it's real
self._data_array.expected_type = np.float
for pol in self.polarization_array:
if pol in [3, 4, -3, -4, -7, -8]:
self._data_array.expected_type = np.complex
# call set_cs_params to fix data_array form
self.set_cs_params()
def set_simple(self):
"""Set antenna_type to 'simple' and adjust required parameters."""
self.antenna_type = 'simple'
self._Nelements.required = False
self._element_coordinate_system.required = False
self._element_location_array.required = False
self._delay_array.required = False
self._gain_array.required = False
self._coupling_matrix.required = False
def set_phased_array(self):
"""Set antenna_type to 'phased_array' and adjust required parameters."""
self.antenna_type = 'phased_array'
self._Nelements.required = True
self._element_coordinate_system.required = True
self._element_location_array.required = True
self._delay_array.required = True
self._gain_array.required = True
self._coupling_matrix.required = True
def peak_normalize(self):
"""
Convert to peak normalization.
"""
if self.data_normalization == 'solid_angle':
raise NotImplementedError('Conversion from solid_angle to peak '
'normalization is not yet implemented')
for i in range(self.Nfreqs):
max_val = abs(self.data_array[:, :, :, i, :]).max()
self.data_array[:, :, :, i, :] /= max_val
self.bandpass_array[:, i] *= max_val
self.data_normalization = 'peak'
def _stokes_matrix(self, pol_index):
"""
Calculate Pauli matrices (where indices are reordered from the quantum mechanical
convention to an order which gives the ordering of the pseudo-Stokes vector
['pI', 'pQ', 'pU, 'pV']) according to https://arxiv.org/pdf/1401.2095.pdf.
Args:
pol_index : Polarization index for which the Pauli matrix is generated, the index
must lie between 0 and 3 ('pI': 0, 'pQ': 1, 'pU': 2, 'pV':3).
"""
if pol_index < 0:
raise ValueError('n must be positive integer.')
if pol_index > 4:
raise ValueError('n should lie between 0 and 3.')
if pol_index == 0:
pauli_mat = np.array([[1., 0.], [0., 1.]])
if pol_index == 1:
pauli_mat = np.array([[1., 0.], [0., -1.]])
if pol_index == 2:
pauli_mat = np.array([[0., 1.], [1., 0.]])
if pol_index == 3:
pauli_mat = np.array([[0., -1.j], [1.j, 0.]])
return pauli_mat
def _construct_mueller(self, jones, pol_index1, pol_index2):
"""
Generate Mueller component as done in https://arxiv.org/pdf/1802.04151.pdf
Mij = Tr(J sigma_i J^* sigma_j)
where sigma_i and sigma_j are Pauli matrices
Args:
jones : Jones matrices containing the electric field for the dipole arms
or linear polarizations.
pol_index1 : Polarization index referring to the first index of Mij (i).
pol_index2 : Polarization index referring to the second index of Mij (j).
Returns:
npix numpy array containing the Mij values.
"""
pauli_mat1 = self._stokes_matrix(pol_index1)
pauli_mat2 = self._stokes_matrix(pol_index2)
Mij = 0.5 * np.einsum('...ab,...bc,...cd,...ad', pauli_mat1, jones, pauli_mat2, np.conj(jones))
Mij = np.abs(Mij)
return Mij
def efield_to_pstokes(self, run_check=True, check_extra=True, run_check_acceptability=True, inplace=True):
"""
Convert E-field to pseudo-stokes power as done in https://arxiv.org/pdf/1802.04151.pdf.
M_ij = Tr(sigma_i J sigma_j J^*)
where sigma_i and sigma_j are Pauli matrices.
Args:
run_check : Option to check for the existence and proper shapes of the required parameters
after converting to power. Default is True.
run_check_acceptability: Option to check acceptable range of the values of required parameters
after combining objects. Default is True.
check_extra : Option to check optional parameters as well as required ones. Default is True.
inplace : Option to perform the select directly on self (True, default) or return a new UVBeam
object, which is a subselection of self (False).
"""
if inplace:
beam_object = self
else:
beam_object = copy.deepcopy(self)
if beam_object.beam_type != 'efield':
raise ValueError('beam_type must be efield.')
if self.pixel_coordinate_system != 'healpix':
raise ValueError('Currently only healpix format is supported')
# construct jones matrix containing the electric field
_sh = beam_object.data_array.shape
efield_data = beam_object.data_array
Nfreqs = beam_object.Nfreqs
pol_strings = ['pI', 'pQ', 'pU', 'pV']
power_data = np.zeros((1, 1, len(pol_strings), _sh[-2], _sh[-1]), dtype=np.complex)
beam_object.polarization_array = np.array([uvutils.polstr2num(ps.upper()) for ps in pol_strings])
for fq_i in range(Nfreqs):
jones = np.zeros((_sh[-1], 2, 2), dtype=np.complex)
pol_strings = ['pI', 'pQ', 'pU', 'pV']
jones[:, 0, 0] = efield_data[0, 0, 0, fq_i, :]
jones[:, 0, 1] = efield_data[0, 0, 1, fq_i, :]
jones[:, 1, 0] = efield_data[1, 0, 0, fq_i, :]
jones[:, 1, 1] = efield_data[1, 0, 1, fq_i, :]
for pol_i in range(len(pol_strings)):
power_data[:, :, pol_i, fq_i, :] = self._construct_mueller(jones, pol_i, pol_i)
beam_object.data_array = power_data
beam_object.polarization_array = np.array([uvutils.polstr2num(ps.upper()) for ps in pol_strings])
beam_object.Naxes_vec = 1
beam_object.set_power()
history_update_string = (' Converted from efield to pseudo-stokes power using pyuvdata.')
beam_object.Npols = beam_object.Nfeeds ** 2
beam_object.history = beam_object.history + history_update_string
beam_object.Nfeeds = None
beam_object.feed_array = None
beam_object.basis_vector_array = None
beam_object.Ncomponents_vec = None
if run_check:
beam_object.check(check_extra=check_extra,
run_check_acceptability=run_check_acceptability)
if not inplace:
return beam_object
def efield_to_power(self, calc_cross_pols=True, keep_basis_vector=False,
run_check=True, check_extra=True, run_check_acceptability=True,
inplace=True):
"""
Convert E-field beam to power beam.
Args:
calc_cross_pols: If True, calculate the crossed polarization beams
(e.g. 'xy' and 'yx'), otherwise only calculate the same
polarization beams (e.g. 'xx' and 'yy'). Default is True.
keep_basis_vector: If True, keep the directionality information and
just multiply the efields for each basis vector separately
(caution: this is not what is standardly meant by the power beam).
Default is False.
run_check: Option to check for the existence and proper shapes of
required parameters after converting to power. Default is True.
check_extra: Option to check optional parameters as well as
required ones. Default is True.
run_check_acceptability: Option to check acceptable range of the values of
required parameters after combining objects. Default is True.
inplace: Option to perform the select directly on self (True, default) or return
a new UVBeam object, which is a subselection of self (False)
"""
if inplace:
beam_object = self
else:
beam_object = copy.deepcopy(self)
if beam_object.beam_type != 'efield':
raise ValueError('beam_type must be efield')
efield_data = beam_object.data_array
efield_naxes_vec = beam_object.Naxes_vec
feed_pol_order = [(0, 0)]
if beam_object.Nfeeds > 1:
feed_pol_order.append((1, 1))
if calc_cross_pols:
beam_object.Npols = beam_object.Nfeeds ** 2
if beam_object.Nfeeds > 1:
feed_pol_order.extend([(0, 1), (1, 0)])
else:
beam_object.Npols = beam_object.Nfeeds
pol_strings = []
for pair in feed_pol_order:
pol_strings.append(beam_object.feed_array[pair[0]] + beam_object.feed_array[pair[1]])
beam_object.polarization_array = np.array([uvutils.polstr2num(ps.upper()) for ps in pol_strings])
if not keep_basis_vector:
beam_object.Naxes_vec = 1
# adjust requirements, fix data_array form
beam_object.set_power()
power_data = np.zeros(beam_object._data_array.expected_shape(beam_object), dtype=np.complex)
if keep_basis_vector:
for pol_i, pair in enumerate(feed_pol_order):
power_data[:, :, pol_i] = (efield_data[:, :, pair[0]]
* np.conj(efield_data[:, :, pair[1]]))
else:
for pol_i, pair in enumerate(feed_pol_order):
if efield_naxes_vec == 2:
for comp_i in range(2):
power_data[0, :, pol_i] += \
((efield_data[0, :, pair[0]]
* np.conj(efield_data[0, :, pair[1]]))
* beam_object.basis_vector_array[0, comp_i]**2
+ (efield_data[1, :, pair[0]]
* np.conj(efield_data[1, :, pair[1]]))
* beam_object.basis_vector_array[1, comp_i]**2
+ (efield_data[0, :, pair[0]]
* np.conj(efield_data[1, :, pair[1]])
+ efield_data[1, :, pair[0]]
* np.conj(efield_data[0, :, pair[1]]))
* (beam_object.basis_vector_array[0, comp_i]
* beam_object.basis_vector_array[1, comp_i]))
else:
raise ValueError('Conversion to power with 3-vector efields '
'is not currently supported because we have '
'no examples to work with.')
power_data = np.real_if_close(power_data, tol=10)
beam_object.data_array = power_data
beam_object.Nfeeds = None
beam_object.feed_array = None
if not keep_basis_vector:
beam_object.basis_vector_array = None
beam_object.Ncomponents_vec = None
history_update_string = (' Converted from efield to power using pyuvdata.')
beam_object.history = beam_object.history + history_update_string
if run_check:
beam_object.check(check_extra=check_extra,
run_check_acceptability=run_check_acceptability)
if not inplace:
return beam_object
def _interp_freq(self, freq_array):
"""
Simple interpolation function for frequency axis.
Args:
freq_array: frequency values to interpolate to
Returns:
an array of interpolated values, shape: (Naxes_vec, Nspws, Nfeeds or Npols, freq_array.size, Npixels or (Naxis2, Naxis1))
an array of distances from nearest frequency, shape: (freq_array.size)
"""
assert(isinstance(freq_array, np.ndarray))
assert(freq_array.ndim == 1)
nfreqs = freq_array.size
for f_i in range(nfreqs):
freq_dists = self.freq_array[0, :] - freq_array[f_i]
if self.Nfreqs == 1:
raise ValueError('Only one frequency in UVBeam so cannot interpolate.')
if np.iscomplexobj(self.data_array):
data_type = np.complex
else:
data_type = np.float
interp_data_shape = np.array(self.data_array.shape)
interp_data_shape[3] = nfreqs
interp_data = np.zeros(interp_data_shape, dtype=data_type)
if (np.min(freq_array) < np.min(self.freq_array) or np.max(freq_array) > np.max(self.freq_array)):
raise ValueError('at least one interpolation frequency is outside of '
'the UVBeam freq_array range.')
def get_lambda(real_lut, imag_lut=None):
# Returns function objects for interpolation reuse
if imag_lut is None:
return lambda freqs: real_lut(freqs)
else:
return lambda freqs: (real_lut(freqs) + 1j * imag_lut(freqs))
if np.iscomplexobj(self.data_array):
# interpolate real and imaginary parts separately
real_lut = interpolate.interp1d(self.freq_array[0, :], self.data_array.real, axis=3)
imag_lut = interpolate.interp1d(self.freq_array[0, :], self.data_array.imag, axis=3)
lut = get_lambda(real_lut, imag_lut)
else:
lut = interpolate.interp1d(self.freq_array[0, :], self.data_array, axis=3)
lut = get_lambda(lut)
interp_data = lut(freq_array)
return interp_data
def _interp_az_za_rect_spline(self, az_array, za_array, freq_array, reuse_spline=False):
"""
Simple interpolation function for az_za coordinate system.
Args:
az_array: az values to interpolate to (same length as za_array)
za_array: za values to interpolate to (same length as az_array)
freq_array: frequency values to interpolate to
reuse_spline: Save the interpolation functions for reuse.
Returns:
an array of interpolated values, shape: (Naxes_vec, Nspws, Nfeeds or Npols, Nfreqs, az_array.size)
an array of interpolated basis vectors, shape: (Naxes_vec, Ncomponents_vec, az_array.size)
"""
if self.pixel_coordinate_system != 'az_za':
raise ValueError('pixel_coordinate_system must be "az_za"')
if reuse_spline and not hasattr(self, 'saved_interp_functions'):
self.saved_interp_functions = {}
if freq_array is not None:
assert(isinstance(freq_array, np.ndarray))
input_data_array = self._interp_freq(freq_array)
input_nfreqs = freq_array.size
else:
input_data_array = self.data_array
input_nfreqs = self.Nfreqs
freq_array = self.freq_array[0]
if az_array is None:
return input_data_array, self.basis_vector_array
assert(isinstance(az_array, np.ndarray))
assert(isinstance(za_array, np.ndarray))
assert(az_array.ndim == 1)
assert(az_array.shape == za_array.shape)
npoints = az_array.size
axis1_diff = np.diff(self.axis1_array)[0]
axis2_diff = np.diff(self.axis2_array)[0]
max_axis_diff = np.max([axis1_diff, axis2_diff])
phi_vals, theta_vals = np.meshgrid(self.axis1_array, self.axis2_array)
assert(input_data_array.shape[3] == input_nfreqs)
if np.iscomplexobj(input_data_array):
data_type = np.complex
else:
data_type = np.float
if self.beam_type == 'efield':
data_shape = (self.Naxes_vec, self.Nspws, self.Nfeeds, input_nfreqs, npoints)
else:
data_shape = (self.Naxes_vec, self.Nspws, self.Npols, input_nfreqs, npoints)
interp_data = np.zeros(data_shape, dtype=data_type)
if self.basis_vector_array is not None:
if (np.any(self.basis_vector_array[0, 1, :] > 0)
or np.any(self.basis_vector_array[1, 0, :] > 0)):
""" Input basis vectors are not aligned to the native theta/phi
coordinate system """
raise NotImplementedError('interpolation for input basis '
'vectors that are not aligned to the '
'native theta/phi coordinate system '
'is not yet supported')
else:
""" The basis vector array comes in defined at the rectangular grid.
Redefine it for the interpolation points """
interp_basis_vector = np.zeros([self.Naxes_vec,
self.Ncomponents_vec,
npoints])
interp_basis_vector[0, 0, :] = np.ones(npoints) # theta hat
interp_basis_vector[1, 1, :] = np.ones(npoints) # phi hat
else:
interp_basis_vector = None
def get_lambda(real_lut, imag_lut=None):
# Returns function objects for interpolation reuse
if imag_lut is None:
return lambda za, az: real_lut(za, az, grid=False)
else:
return lambda za, az: (real_lut(za, az, grid=False) + 1j * imag_lut(za, az, grid=False))
# Npols is only defined for power beams. For E-field beams need Nfeeds.
if self.beam_type == 'power':
Npol_feeds = self.Npols
else:
Npol_feeds = self.Nfeeds
for index1 in range(self.Nspws):
for index3 in range(input_nfreqs):
freq = freq_array[index3]
if reuse_spline:
luts = np.empty((self.Naxes_vec, self.Nspws, Npol_feeds), dtype=object)
for index0 in range(self.Naxes_vec):
for index2 in range(Npol_feeds):
if reuse_spline and freq in self.saved_interp_functions.keys():
lut = self.saved_interp_functions[freq][index0, index1, index2]
else:
if np.iscomplexobj(input_data_array):
# interpolate real and imaginary parts separately
real_lut = interpolate.RectBivariateSpline(self.axis2_array,
self.axis1_array,
input_data_array[index0, index1, index2, index3, :].real)
imag_lut = interpolate.RectBivariateSpline(self.axis2_array,
self.axis1_array,
input_data_array[index0, index1, index2, index3, :].imag)
lut = get_lambda(real_lut, imag_lut)
else:
lut = interpolate.RectBivariateSpline(self.axis2_array,
self.axis1_array,
input_data_array[index0, index1, index2, index3, :])
lut = get_lambda(lut)
if reuse_spline:
luts[index0, index1, index2] = lut
if index0 == 0 and index1 == 0 and index2 == 0 and index3 == 0:
for point_i in range(npoints):
pix_dists = np.sqrt((theta_vals - za_array[point_i])**2.
+ (phi_vals - az_array[point_i])**2.)
if np.min(pix_dists) > (max_axis_diff * 2.0):
raise ValueError('at least one interpolation location is outside of '
'the UVBeam pixel coverage.')
interp_data[index0, index1, index2, index3, :] = lut(za_array, az_array)
if reuse_spline:
self.saved_interp_functions[freq] = luts
return interp_data, interp_basis_vector
def interp(self, az_array=None, za_array=None, freq_array=None, reuse_spline=False):
"""
Interpolate beam to given az, za locations (in radians).
Args:
az_array: az values to interpolate to (same length as za_array)
za_array: za values to interpolate to (same length as az_array)
freq_array: frequency values to interpolate to
Returns:
an array of interpolated values, shape: (Naxes_vec, Nspws, Nfeeds or Npols,
Nfreqs or freq_array.size if freq_array is passed,
Npixels/(Naxis1, Naxis2) or az_array.size if az/za_arrays are passed)
an array of interpolated basis vectors (or self.basis_vector_array
if az/za_arrays are not passed), shape: (Naxes_vec, Ncomponents_vec,
Npixels/(Naxis1, Naxis2) or az_array.size if az/za_arrays are passed)
"""
if self.interpolation_function is None:
raise ValueError('interpolation_function must be set on object first')
interp_func = self.interpolation_function_dict[self.interpolation_function]
return getattr(self, interp_func)(az_array, za_array, freq_array, reuse_spline)
def to_healpix(self, nside=None, run_check=True, check_extra=True,
run_check_acceptability=True,
inplace=True):
"""
Convert beam in to healpix coordinates.
The interpolation is done using the interpolation method specified in
self.interpolation_function.
Note that this interpolation isn't perfect. Interpolating an Efield beam
and then converting to power gives a different result than converting
to power and then interpolating at about a 5% level.
Args:
nside: The nside to use for the Healpix map. If not specified, use
the nside that gives the closest resolution that is higher than the
input resolution.
run_check: Option to check for the existence and proper shapes of
required parameters after converting to healpix. Default is True.
check_extra: Option to check optional parameters as well as
required ones. Default is True.
run_check_acceptability: Option to check acceptable range of the values of
required parameters after combining objects. Default is True.
inplace: Option to perform the select directly on self (True, default) or return
a new UVBeam object, which is a subselection of self (False)
"""
try:
import healpy as hp
except ImportError: # pragma: no cover
uvutils._reraise_context('healpy is not installed but is required for '
'healpix functionality')
if inplace:
beam_object = self
else:
beam_object = copy.deepcopy(self)
if nside is None:
min_res = np.min(np.array([np.diff(beam_object.axis1_array)[0], np.diff(beam_object.axis2_array)[0]]))
nside_min_res = np.sqrt(3 / np.pi) * np.radians(60.) / min_res
nside = int(2**np.ceil(np.log2(nside_min_res)))
assert(hp.pixelfunc.nside2resol(nside) < min_res)
npix = hp.nside2npix(nside)
hpx_res = hp.pixelfunc.nside2resol(nside)
if np.iscomplexobj(beam_object.data_array):
data_type = np.complex
else:
data_type = np.float
pixels = np.arange(hp.nside2npix(nside))
hpx_theta, hpx_phi = hp.pix2ang(nside, pixels)
phi_vals, theta_vals = np.meshgrid(self.axis1_array, self.axis2_array)
# Don't ask for interpolation to pixels that aren't inside the beam area
inds_to_use = []
for index in range(pixels.size):
pix_dists = np.sqrt((theta_vals - hpx_theta[index])**2.
+ (phi_vals - hpx_phi[index])**2.)
if np.min(pix_dists) < hpx_res * 2:
inds_to_use.append(index)
inds_to_use = np.array(inds_to_use)
if inds_to_use.size < npix:
pixels = pixels[inds_to_use]
hpx_theta = hpx_theta[inds_to_use]
hpx_phi = hpx_phi[inds_to_use]
interp_data, interp_basis_vector = \
self.interp(az_array=hpx_phi, za_array=hpx_theta)
beam_object.pixel_coordinate_system = 'healpix'
beam_object.nside = nside
beam_object.Npixels = npix
beam_object.ordering = 'ring'
beam_object.set_cs_params()
if beam_object.basis_vector_array is not None: