Repository navigation
Expand file tree
/
Copy pathtesting_support.py
More file actions
1091 lines (853 loc) · 46.5 KB
/
Copy pathtesting_support.py
File metadata and controls
1091 lines (853 loc) · 46.5 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
"""
Functions that aid testing in various ways. A typical use would be::
lowcore = create_named_configuration('LOWBD2-CORE')
times = numpy.linspace(-3, +3, 13) * (numpy.pi / 12.0)
frequency = numpy.array([1e8])
channel_bandwidth = numpy.array([1e7])
# Define the component and give it some polarisation and spectral behaviour
f = numpy.array([100.0])
flux = numpy.array([f])
phasecentre = SkyCoord(ra=+15.0 * u.deg, dec=-35.0 * u.deg, frame='icrs', equinox='J2000')
compabsdirection = SkyCoord(ra=17.0 * u.deg, dec=-36.5 * u.deg, frame='icrs', equinox='J2000')
comp = create_skycomponent(flux=flux, frequency=frequency, direction=compabsdirection,
polarisation_frame=PolarisationFrame('stokesI'))
image = create_test_image(frequency=frequency, phasecentre=phasecentre,
cellsize=0.001,
polarisation_frame=PolarisationFrame('stokesI')
vis = create_visibility(lowcore, times=times, frequency=frequency,
channel_bandwidth=channel_bandwidth,
phasecentre=phasecentre, weight=1,
polarisation_frame=PolarisationFrame('stokesI'),
integration_time=1.0)
"""
import csv
import logging
from typing import List
import astropy.units as u
import numpy
from astropy.coordinates import SkyCoord
from astropy.io import fits
from astropy.wcs import WCS
from astropy.wcs.utils import pixel_to_skycoord
from scipy import interpolate
from data_models.memory_data_models import Configuration, Image, GainTable, Skycomponent, SkyModel, PointingTable
from data_models.parameters import arl_path
from data_models.polarisation import PolarisationFrame
from processing_components.calibration.calibration_control import create_calibration_controls
from processing_components.calibration.operations import create_gaintable_from_blockvisibility, apply_gaintable
from processing_components.image.operations import import_image_from_fits
from processing_components.imaging.base import predict_2d, predict_skycomponent_visibility, \
create_image_from_visibility, advise_wide_field
from processing_components.imaging.primary_beams import create_pb
from processing_components.skycomponent.operations import create_skycomponent, insert_skycomponent, \
apply_beam_to_skycomponent, filter_skycomponents_by_flux
from processing_components.visibility.base import create_blockvisibility, create_visibility
from processing_components.visibility.coalesce import convert_blockvisibility_to_visibility, \
convert_visibility_to_blockvisibility
from processing_library.image.operations import create_image_from_array
log = logging.getLogger(__name__)
def create_test_image(canonical=True, cellsize=None, frequency=None, channel_bandwidth=None,
phasecentre=None, polarisation_frame=PolarisationFrame("stokesI")) -> Image:
"""Create a useful test image
This is the test image M31 widely used in ALMA and other simulations. It is actually part of an Halpha region in
M31.
:param canonical: Make the image into a 4 dimensional image
:param cellsize:
:param frequency: Frequency (array) in Hz
:param channel_bandwidth: Channel bandwidth (array) in Hz
:param phasecentre: Phase centre of image (SkyCoord)
:param polarisation_frame: Polarisation frame
:return: Image
"""
if frequency is None:
frequency = [1e8]
im = import_image_from_fits(arl_path("data/models/M31.MOD"))
if canonical:
if polarisation_frame is None:
im.polarisation_frame = PolarisationFrame("stokesI")
elif isinstance(polarisation_frame, PolarisationFrame):
im.polarisation_frame = polarisation_frame
else:
raise ValueError("polarisation_frame is not valid")
im = replicate_image(im, frequency=frequency, polarisation_frame=im.polarisation_frame)
if cellsize is not None:
im.wcs.wcs.cdelt[0] = -180.0 * cellsize / numpy.pi
im.wcs.wcs.cdelt[1] = +180.0 * cellsize / numpy.pi
if frequency is not None:
im.wcs.wcs.crval[3] = frequency[0]
if channel_bandwidth is not None:
im.wcs.wcs.cdelt[3] = channel_bandwidth[0]
else:
if len(frequency) > 1:
im.wcs.wcs.cdelt[3] = frequency[1] - frequency[0]
else:
im.wcs.wcs.cdelt[3] = 0.001 * frequency[0]
im.wcs.wcs.radesys = 'ICRS'
im.wcs.wcs.equinox = 2000.00
if phasecentre is not None:
im.wcs.wcs.crval[0] = phasecentre.ra.deg
im.wcs.wcs.crval[1] = phasecentre.dec.deg
# WCS is 1 relative
im.wcs.wcs.crpix[0] = im.data.shape[3] // 2 + 1
im.wcs.wcs.crpix[1] = im.data.shape[2] // 2 + 1
return im
def create_test_image_from_s3(npixel=16384, polarisation_frame=PolarisationFrame("stokesI"), cellsize=0.000015,
frequency=numpy.array([1e8]), channel_bandwidth=numpy.array([1e6]),
phasecentre=None, fov=20, flux_limit=1e-3) -> Image:
"""Create MID test image from S3
The input catalog was generated at http://s-cubed.physics.ox.ac.uk/s3_sex using the following query::
Database: s3_sex
SQL: select * from Galaxies where (pow(10,itot_151)*1000 > 1.0) and (right_ascension between -5 and 5) and (declination between -5 and 5);;
Number of rows returned: 29966
For frequencies < 610MHz, there are three tables to use::
data/models/S3_151MHz_10deg.csv, use fov=10
data/models/S3_151MHz_20deg.csv, use fov=20
data/models/S3_151MHz_40deg.csv, use fov=40
For frequencies > 610MHz, there are three tables:
data/models/S3_1400MHz_1mJy_10deg.csv, use flux_limit>= 1e-3
data/models/S3_1400MHz_100uJy_10deg.csv, use flux_limit < 1e-3
data/models/S3_1400MHz_1mJy_18deg.csv, use flux_limit>= 1e-3
data/models/S3_1400MHz_100uJy_18deg.csv, use flux_limit < 1e-3
The component spectral index is calculated from the 610MHz and 151MHz or 1400MHz and 610MHz, and then calculated
for the specified frequencies.
If polarisation_frame is not stokesI then the image will a polarised axis but the values will be zero.
:param npixel: Number of pixels
:param polarisation_frame: Polarisation frame (default PolarisationFrame("stokesI"))
:param cellsize: cellsize in radians
:param frequency:
:param channel_bandwidth: Channel width (Hz)
:param phasecentre: phasecentre (SkyCoord)
:param fov: fov 10 | 20 | 40
:param flux_limit: Minimum flux (Jy)
:return: Image
"""
ras = []
decs = []
fluxes = []
if phasecentre is None:
phasecentre = SkyCoord(ra=+180.0 * u.deg, dec=-60.0 * u.deg, frame='icrs', equinox='J2000')
if polarisation_frame is None:
polarisation_frame = PolarisationFrame("stokesI")
npol = polarisation_frame.npol
nchan = len(frequency)
shape = [nchan, npol, npixel, npixel]
w = WCS(naxis=4)
# The negation in the longitude is needed by definition of RA, DEC
w.wcs.cdelt = [-cellsize * 180.0 / numpy.pi, cellsize * 180.0 / numpy.pi, 1.0, channel_bandwidth[0]]
w.wcs.crpix = [npixel // 2 + 1, npixel // 2 + 1, 1.0, 1.0]
w.wcs.ctype = ["RA---SIN", "DEC--SIN", 'STOKES', 'FREQ']
w.wcs.crval = [phasecentre.ra.deg, phasecentre.dec.deg, 1.0, frequency[0]]
w.naxis = 4
w.wcs.radesys = 'ICRS'
w.wcs.equinox = 2000.0
model = create_image_from_array(numpy.zeros(shape), w, polarisation_frame=polarisation_frame)
if numpy.max(frequency) > 6.1E8:
if fov > 10:
fovstr = '18'
else:
fovstr = '10'
if flux_limit >= 1e-3:
csvfilename = arl_path('data/models/S3_1400MHz_1mJy_%sdeg.csv' % fovstr)
else:
csvfilename = arl_path('data/models/S3_1400MHz_100uJy_%sdeg.csv' % fovstr)
log.info('create_test_image_from_s3: Reading S3 sources from %s ' % csvfilename)
else:
assert fov in [10, 20, 40], "Field of view invalid: use one of %s" % ([10, 20, 40])
csvfilename = arl_path('data/models/S3_151MHz_%ddeg.csv' % (fov))
log.info('create_test_image_from_s3: Reading S3 sources from %s ' % csvfilename)
with open(csvfilename) as csvfile:
readCSV = csv.reader(csvfile, delimiter=',')
r = 0
for row in readCSV:
# Skip first row
if r > 0:
ra = float(row[4]) + phasecentre.ra.deg
dec = float(row[5]) + phasecentre.dec.deg
if numpy.max(frequency) > 6.1E8:
alpha = (float(row[11]) - float(row[10])) / numpy.log10(1400.0 / 610.0)
flux = numpy.power(10, float(row[10])) * numpy.power(frequency / 1.4e9, alpha)
else:
alpha = (float(row[10]) - float(row[9])) / numpy.log10(610.0 / 151.0)
flux = numpy.power(10, float(row[9])) * numpy.power(frequency / 1.51e8, alpha)
if numpy.max(flux) > flux_limit:
ras.append(ra)
decs.append(dec)
fluxes.append(flux)
r += 1
csvfile.close()
assert len(fluxes) > 0, "No sources found above flux limit %s" % flux_limit
log.info('create_test_image_from_s3: %d sources read' % (len(fluxes)))
p = w.sub(2).wcs_world2pix(numpy.array(ras), numpy.array(decs), 1)
total_flux = numpy.sum(fluxes)
fluxes = numpy.array(fluxes)
ip = numpy.round(p).astype('int')
ok = numpy.where((0 <= ip[0, :]) & (npixel > ip[0, :]) & (0 <= ip[1, :]) & (npixel > ip[1, :]))[0]
ps = ip[:, ok]
fluxes = fluxes[ok]
actual_flux = numpy.sum(fluxes)
log.info('create_test_image_from_s3: %d sources inside the image' % (ps.shape[1]))
log.info('create_test_image_from_s3: average channel flux in S3 model = %.3f, actual average channel flux in '
'image = %.3f' % (total_flux / float(nchan), actual_flux / float(nchan)))
for chan in range(nchan):
for iflux, flux in enumerate(fluxes):
model.data[chan, 0, ps[1, iflux], ps[0, iflux]] = flux[chan]
return model
def create_test_skycomponents_from_s3(polarisation_frame=PolarisationFrame("stokesI"),
frequency=numpy.array([1e8]), channel_bandwidth=numpy.array([1e6]),
phasecentre=None, fov=20, flux_limit=1e-3,
radius=None):
"""Create test image from S3
The input catalog was generated at http://s-cubed.physics.ox.ac.uk/s3_sex using the following query::
Database: s3_sex
SQL: select * from Galaxies where (pow(10,itot_151)*1000 > 1.0) and (right_ascension between -5 and 5) and (declination between -5 and 5);;
Number of rows returned: 29966
For frequencies < 610MHz, there are three tables to use::
data/models/S3_151MHz_10deg.csv, use fov=10
data/models/S3_151MHz_20deg.csv, use fov=20
data/models/S3_151MHz_40deg.csv, use fov=40
For frequencies > 610MHz, there are three tables:
data/models/S3_1400MHz_1mJy_10deg.csv, use flux_limit>= 1e-3
data/models/S3_1400MHz_100uJy_10deg.csv, use flux_limit < 1e-3
data/models/S3_1400MHz_1mJy_18deg.csv, use flux_limit>= 1e-3
data/models/S3_1400MHz_100uJy_18deg.csv, use flux_limit < 1e-3
The component spectral index is calculated from the 610MHz and 151MHz or 1400MHz and 610MHz, and then calculated
for the specified frequencies.
If polarisation_frame is not stokesI then the image will a polarised axis but the values will be zero.
:param npixel: Number of pixels
:param polarisation_frame: Polarisation frame (default PolarisationFrame("stokesI"))
:param cellsize: cellsize in radians
:param frequency:
:param channel_bandwidth: Channel width (Hz)
:param phasecentre: phasecentre (SkyCoord)
:param fov: fov 10 | 20 | 40
:param flux_limit: Minimum flux (Jy)
:return: Image
"""
ras = []
decs = []
fluxes = []
names = []
if phasecentre is None:
phasecentre = SkyCoord(ra=+180.0 * u.deg, dec=-60.0 * u.deg, frame='icrs', equinox='J2000')
if polarisation_frame is None:
polarisation_frame = PolarisationFrame("stokesI")
if numpy.max(frequency) > 6.1E8:
if fov > 10:
fovstr = '18'
else:
fovstr = '10'
if flux_limit >= 1e-3:
csvfilename = arl_path('data/models/S3_1400MHz_1mJy_%sdeg.csv' % fovstr)
else:
csvfilename = arl_path('data/models/S3_1400MHz_100uJy_%sdeg.csv' % fovstr)
log.info('create_test_skycomponents_from_s3: Reading S3-SEX sources from %s ' % csvfilename)
else:
assert fov in [10, 20, 40], "Field of view invalid: use one of %s" % ([10, 20, 40])
csvfilename = arl_path('data/models/S3_151MHz_%ddeg.csv' % (fov))
log.info('create_test_skycomponents_from_s3: Reading S3-SEX sources from %s ' % csvfilename)
skycomps = list()
with open(csvfilename) as csvfile:
readCSV = csv.reader(csvfile, delimiter=',')
r = 0
for row in readCSV:
# Skip first row
if r > 0:
ra = float(row[4])/numpy.cos(phasecentre.dec.rad) + phasecentre.ra.deg
dec = float(row[5]) + phasecentre.dec.deg
if numpy.max(frequency) > 6.1E8:
alpha = (float(row[11]) - float(row[10])) / numpy.log10(1400.0 / 610.0)
flux = numpy.power(10, float(row[10])) * numpy.power(frequency / 1.4e9, alpha)
else:
alpha = (float(row[10]) - float(row[9])) / numpy.log10(610.0 / 151.0)
flux = numpy.power(10, float(row[9])) * numpy.power(frequency / 1.51e8, alpha)
if numpy.max(flux) > flux_limit:
ras.append(ra)
decs.append(dec)
fluxes.append([[f] for f in flux])
names.append("S3_%s" % row[0])
r += 1
csvfile.close()
assert len(fluxes) > 0, "No sources found above flux limit %s" % flux_limit
directions = SkyCoord(ra=ras * u.deg, dec=decs * u.deg)
if phasecentre is not None:
separations = directions.separation(phasecentre).to('rad').value
else:
separations = numpy.zeros(len(names))
for isource, name in enumerate(names):
direction = directions[isource]
if separations[isource] < radius:
if not numpy.isnan(flux).any():
skycomps.append(Skycomponent(direction=direction, flux=fluxes[isource], frequency=frequency,
name=names[isource], shape='Point',
polarisation_frame=polarisation_frame))
log.info('create_test_skycomponents_from_s3: %d sources found above fluxlimit inside search radius' %
len(skycomps))
return skycomps
def create_low_test_image_from_gleam(npixel=512, polarisation_frame=PolarisationFrame("stokesI"), cellsize=0.000015,
frequency=numpy.array([1e8]), channel_bandwidth=numpy.array([1e6]),
phasecentre=None, kind='cubic', applybeam=False, flux_limit=0.1,
flux_max=numpy.inf, flux_min=-numpy.inf,
radius=None, insert_method='Nearest') -> Image:
"""Create LOW test image from the GLEAM survey
Stokes I is estimated from a cubic spline fit to the measured fluxes. The polarised flux is always zero.
See http://www.mwatelescope.org/science/gleam-survey The catalog is available from Vizier.
VIII/100 GaLactic and Extragalactic All-sky MWA survey (Hurley-Walker+, 2016)
GaLactic and Extragalactic All-sky Murchison Wide Field Array (GLEAM) survey. I: A low-frequency extragalactic
catalogue. Hurley-Walker N., et al., Mon. Not. R. Astron. Soc., 464, 1146-1167 (2017), 2017MNRAS.464.1146H
:param npixel: Number of pixels
:param polarisation_frame: Polarisation frame (default PolarisationFrame("stokesI"))
:param cellsize: cellsize in radians
:param frequency:
:param channel_bandwidth: Channel width (Hz)
:param phasecentre: phasecentre (SkyCoord)
:param kind: Kind of interpolation (see scipy.interpolate.interp1d) Default: linear
:return: Image
"""
if phasecentre is None:
phasecentre = SkyCoord(ra=+15.0 * u.deg, dec=-35.0 * u.deg, frame='icrs', equinox='J2000')
if radius is None:
radius = npixel * cellsize / numpy.sqrt(2.0)
sc = create_low_test_skycomponents_from_gleam(flux_limit=flux_limit, polarisation_frame=polarisation_frame,
frequency=frequency, phasecentre=phasecentre,
kind=kind, radius=radius)
sc = filter_skycomponents_by_flux(sc, flux_min=flux_min, flux_max=flux_max)
if polarisation_frame is None:
polarisation_frame = PolarisationFrame("stokesI")
npol = polarisation_frame.npol
nchan = len(frequency)
shape = [nchan, npol, npixel, npixel]
w = WCS(naxis=4)
# The negation in the longitude is needed by definition of RA, DEC
w.wcs.cdelt = [-cellsize * 180.0 / numpy.pi, cellsize * 180.0 / numpy.pi, 1.0, channel_bandwidth[0]]
w.wcs.crpix = [npixel // 2 + 1, npixel // 2 + 1, 1.0, 1.0]
w.wcs.ctype = ["RA---SIN", "DEC--SIN", 'STOKES', 'FREQ']
w.wcs.crval = [phasecentre.ra.deg, phasecentre.dec.deg, 1.0, frequency[0]]
w.naxis = 4
w.wcs.radesys = 'ICRS'
w.wcs.equinox = 2000.0
model = create_image_from_array(numpy.zeros(shape), w, polarisation_frame=polarisation_frame)
model = insert_skycomponent(model, sc, insert_method=insert_method)
if applybeam:
beam = create_pb(model, telescope='LOW', use_local=False)
model.data[...] *= beam.data[...]
return model
def create_low_test_skymodel_from_gleam(npixel=512, polarisation_frame=PolarisationFrame("stokesI"), cellsize=0.000015,
frequency=numpy.array([1e8]), channel_bandwidth=numpy.array([1e6]),
phasecentre=None, kind='cubic', applybeam=True, flux_limit=0.1,
flux_max=numpy.inf, flux_threshold=1.0, insert_method='Nearest',
telescope='LOW') -> SkyModel:
"""Create LOW test skymodel from the GLEAM survey
Stokes I is estimated from a cubic spline fit to the measured fluxes. The polarised flux is always zero.
See http://www.mwatelescope.org/science/gleam-survey The catalog is available from Vizier.
VIII/100 GaLactic and Extragalactic All-sky MWA survey (Hurley-Walker+, 2016)
GaLactic and Extragalactic All-sky Murchison Wide Field Array (GLEAM) survey. I: A low-frequency extragalactic
catalogue. Hurley-Walker N., et al., Mon. Not. R. Astron. Soc., 464, 1146-1167 (2017), 2017MNRAS.464.1146H
:param telescope:
:param npixel: Number of pixels
:param polarisation_frame: Polarisation frame (default PolarisationFrame("stokesI"))
:param cellsize: cellsize in radians
:param frequency:
:param channel_bandwidth: Channel width (Hz)
:param phasecentre: phasecentre (SkyCoord)
:param kind: Kind of interpolation (see scipy.interpolate.interp1d) Default: cubic
:param applybeam: Apply the primary beam?
:param flux_limit: Weakest component
:param flux_max: Maximum strength component to be included in components
:param flux_threshold: Split between components (brighter) and image (weaker)
:param insert_method: Nearest | PSWF | Lanczos
:return:
:return: SkyModel
"""
if phasecentre is None:
phasecentre = SkyCoord(ra=+15.0 * u.deg, dec=-35.0 * u.deg, frame='icrs', equinox='J2000')
radius = npixel * cellsize
sc = create_low_test_skycomponents_from_gleam(flux_limit=flux_limit, polarisation_frame=polarisation_frame,
frequency=frequency, phasecentre=phasecentre,
kind=kind, radius=radius)
sc = filter_skycomponents_by_flux(sc, flux_max=flux_max)
if polarisation_frame is None:
polarisation_frame = PolarisationFrame("stokesI")
npol = polarisation_frame.npol
nchan = len(frequency)
shape = [nchan, npol, npixel, npixel]
w = WCS(naxis=4)
# The negation in the longitude is needed by definition of RA, DEC
w.wcs.cdelt = [-cellsize * 180.0 / numpy.pi, cellsize * 180.0 / numpy.pi, 1.0, channel_bandwidth[0]]
w.wcs.crpix = [npixel // 2 + 1, npixel // 2 + 1, 1.0, 1.0]
w.wcs.ctype = ["RA---SIN", "DEC--SIN", 'STOKES', 'FREQ']
w.wcs.crval = [phasecentre.ra.deg, phasecentre.dec.deg, 1.0, frequency[0]]
w.naxis = 4
w.wcs.radesys = 'ICRS'
w.wcs.equinox = 2000.0
model = create_image_from_array(numpy.zeros(shape), w, polarisation_frame=polarisation_frame)
if applybeam:
beam = create_pb(model, telescope=telescope, use_local=False)
sc = apply_beam_to_skycomponent(sc, beam)
weaksc = filter_skycomponents_by_flux(sc, flux_max=flux_threshold)
brightsc = filter_skycomponents_by_flux(sc, flux_min=flux_threshold)
model = insert_skycomponent(model, weaksc, insert_method=insert_method)
log.info(
'create_low_test_skymodel_from_gleam: %d bright sources above flux threshold %.3f, %d weak sources below ' %
(len(brightsc), flux_threshold, len(weaksc)))
return SkyModel(components=brightsc, image=model, mask=None, gaintable=None)
def create_low_test_skycomponents_from_gleam(flux_limit=0.1, polarisation_frame=PolarisationFrame("stokesI"),
frequency=numpy.array([1e8]), kind='cubic', phasecentre=None,
radius=1.0) \
-> List[Skycomponent]:
"""Create sky components from the GLEAM survey
Stokes I is estimated from a cubic spline fit to the measured fluxes. The polarised flux is always zero.
See http://www.mwatelescope.org/science/gleam-survey The catalog is available from Vizier.
VIII/100 GaLactic and Extragalactic All-sky MWA survey (Hurley-Walker+, 2016)
GaLactic and Extragalactic All-sky Murchison Wide Field Array (GLEAM) survey. I: A low-frequency extragalactic
catalogue. Hurley-Walker N., et al., Mon. Not. R. Astron. Soc., 464, 1146-1167 (2017), 2017MNRAS.464.1146H
:param flux_limit: Only write components brighter than this (Jy)
:param polarisation_frame: Polarisation frame (default PolarisationFrame("stokesI"))
:param frequency: Frequencies at which the flux will be estimated
:param kind: Kind of interpolation (see scipy.interpolate.interp1d) Default: linear
:param phasecentre: Desired phase centre (SkyCoord) default None implies all sources
:param radius: Radius of sources selected around phasecentre (default 1.0 rad)
:return: List of Skycomponents
"""
fitsfile = arl_path("data/models/GLEAM_EGC.fits")
rad2deg = 180.0 / numpy.pi
decmin = phasecentre.dec.to('deg').value - rad2deg * radius / 2.0
decmax = phasecentre.dec.to('deg').value + rad2deg * radius / 2.0
hdulist = fits.open(fitsfile, lazy_load_hdus=False)
recs = hdulist[1].data[0].array
fluxes = recs['peak_flux_wide']
mask = fluxes > flux_limit
filtered_recs = recs[mask]
decs = filtered_recs['DEJ2000']
mask = decs > decmin
filtered_recs = filtered_recs[mask]
decs = filtered_recs['DEJ2000']
mask = decs < decmax
filtered_recs = filtered_recs[mask]
ras = filtered_recs['RAJ2000']
decs = filtered_recs['DEJ2000']
names = filtered_recs['Name']
if polarisation_frame is None:
polarisation_frame = PolarisationFrame("stokesI")
npol = polarisation_frame.npol
nchan = len(frequency)
# For every source, we read all measured fluxes and interpolate to the
# required frequencies
gleam_freqs = numpy.array([76, 84, 92, 99, 107, 115, 122, 130, 143, 151, 158, 166, 174, 181, 189, 197, 204,
212, 220, 227])
gleam_flux_freq = numpy.zeros([len(names), len(gleam_freqs)])
for i, f in enumerate(gleam_freqs):
gleam_flux_freq[:, i] = filtered_recs['int_flux_%03d' % (f)][:]
skycomps = []
directions = SkyCoord(ra=ras * u.deg, dec=decs * u.deg)
if phasecentre is not None:
separations = directions.separation(phasecentre).to('rad').value
else:
separations = numpy.zeros(len(names))
for isource, name in enumerate(names):
direction = directions[isource]
if separations[isource] < radius:
fint = interpolate.interp1d(gleam_freqs * 1.0e6, gleam_flux_freq[isource, :], kind=kind)
flux = numpy.zeros([nchan, npol])
flux[:, 0] = fint(frequency)
if not numpy.isnan(flux).any():
skycomps.append(Skycomponent(direction=direction, flux=flux, frequency=frequency,
name=name, shape='Point',
polarisation_frame=polarisation_frame))
log.info('create_low_test_skycomponents_from_gleam: %d sources above flux limit %.3f' % (len(skycomps), flux_limit))
hdulist.close()
return skycomps
def replicate_image(im: Image, polarisation_frame=PolarisationFrame('stokesI'), frequency=numpy.array([1e8])) \
-> Image:
""" Make a new canonical shape Image, extended along third and fourth axes by replication.
The order of the data is [chan, pol, dec, ra]
:param frequency:
:param im:
:param polarisation_frame: Polarisation_frame
:return: Image
"""
if len(im.data.shape) == 2:
fim = Image()
newwcs = WCS(naxis=4)
newwcs.wcs.crpix = [im.wcs.wcs.crpix[0] + 1.0, im.wcs.wcs.crpix[1] + 1.0, 1.0, 1.0]
newwcs.wcs.cdelt = [im.wcs.wcs.cdelt[0], im.wcs.wcs.cdelt[1], 1.0, 1.0]
newwcs.wcs.crval = [im.wcs.wcs.crval[0], im.wcs.wcs.crval[1], 1.0, frequency[0]]
newwcs.wcs.ctype = [im.wcs.wcs.ctype[0], im.wcs.wcs.ctype[1], 'STOKES', 'FREQ']
nchan = len(frequency)
npol = polarisation_frame.npol
fim.polarisation_frame = polarisation_frame
fim.wcs = newwcs
fshape = [nchan, npol, im.data.shape[1], im.data.shape[0]]
fim.data = numpy.zeros(fshape)
log.info("replicate_image: replicating shape %s to %s" % (im.data.shape, fim.data.shape))
for i3 in range(nchan):
fim.data[i3, 0, :, :] = im.data[:, :]
return fim
else:
return im
def create_blockvisibility_iterator(config: Configuration, times: numpy.array, frequency: numpy.array,
channel_bandwidth, phasecentre: SkyCoord, weight: float = 1,
polarisation_frame=PolarisationFrame('stokesI'), integration_time=1.0,
number_integrations=1, predict=predict_2d, model=None, components=None,
phase_error=0.0, amplitude_error=0.0, sleep=0.0, **kwargs):
""" Create a sequence of Visibilities and optionally predicting and coalescing
This is useful mainly for performing large simulations. Do something like::
vis_iter = create_blockvisibility_iterator(config, times, frequency, channel_bandwidth, phasecentre=phasecentre,
weight=1.0, integration_time=30.0, number_integrations=3)
for i, vis in enumerate(vis_iter):
if i == 0:
fullvis = vis
else:
fullvis = append_visibility(fullvis, vis)
:param config: Configuration of antennas
:param times: hour angles in radians
:param frequency: frequencies (Hz] Shape [nchan]
:param weight: weight of a single sample
:param phasecentre: phasecentre of observation
:param npol: Number of polarizations
:param integration_time: Integration time ('auto' or value in s)
:param number_integrations: Number of integrations to be created at each time.
:param model: Model image to be inserted
:param components: Components to be inserted
:param sleep_time: Time to sleep between yields
:return: Visibility
"""
for time in times:
actualtimes = time + numpy.arange(0, number_integrations) * integration_time * numpy.pi / 43200.0
bvis = create_blockvisibility(config, actualtimes, frequency=frequency, phasecentre=phasecentre, weight=weight,
polarisation_frame=polarisation_frame, integration_time=integration_time,
channel_bandwidth=channel_bandwidth)
if model is not None:
vis = convert_blockvisibility_to_visibility(bvis)
vis = predict(vis, model, **kwargs)
bvis = convert_visibility_to_blockvisibility(vis)
if components is not None:
vis = predict_skycomponent_visibility(bvis, components)
# Add phase errors
if phase_error > 0.0 or amplitude_error > 0.0:
gt = create_gaintable_from_blockvisibility(bvis)
gt = simulate_gaintable(gt=gt, phase_error=phase_error, amplitude_error=amplitude_error)
bvis = apply_gaintable(bvis, gt)
import time
time.sleep(sleep)
yield bvis
def simulate_gaintable(gt: GainTable, phase_error=0.1, amplitude_error=0.0, smooth_channels=1, leakage=0.0,
**kwargs) -> GainTable:
""" Simulate a gain table
:type gt: GainTable
:param phase_error: std of normal distribution, zero mean
:param amplitude_error: std of log normal distribution
:param leakage: std of cross hand leakage
:param smooth_channels: Use bspline over smooth_channels
:param kwargs:
:return: Gaintable
"""
def moving_average(a, n=3):
return numpy.convolve(a, numpy.ones((n,)) / n, mode='valid')
log.debug("simulate_gaintable: Simulating amplitude error = %.4f, phase error = %.4f"
% (amplitude_error, phase_error))
amps = 1.0
phases = 1.0
ntimes, nant, nchan, nrec, _ = gt.data['gain'].shape
if phase_error > 0.0:
phases = numpy.zeros(gt.data['gain'].shape)
for time in range(ntimes):
for ant in range(nant):
phase = numpy.random.normal(0, phase_error, nchan + int(smooth_channels) - 1)
if smooth_channels > 1:
phase = moving_average(phase, smooth_channels)
phases[time, ant, ...] = phase[..., numpy.newaxis, numpy.newaxis]
if amplitude_error > 0.0:
amps = numpy.ones(gt.data['gain'].shape, dtype='complex')
for time in range(ntimes):
for ant in range(nant):
amp = numpy.random.lognormal(mean=0.0, sigma=amplitude_error, size=nchan + int(smooth_channels) - 1)
if smooth_channels > 1:
amp = moving_average(amp, smooth_channels)
amp = amp / numpy.average(amp)
amps[time, ant, ...] = amp[..., numpy.newaxis, numpy.newaxis]
gt.data['gain'] = amps * numpy.exp(0 + 1j * phases)
nrec = gt.data['gain'].shape[-1]
if nrec > 1:
if leakage > 0.0:
leak = numpy.random.normal(0, leakage, gt.data['gain'][..., 0, 0].shape) + 1j * \
numpy.random.normal(0, leakage, gt.data['gain'][..., 0, 0].shape)
gt.data['gain'][..., 0, 1] = gt.data['gain'][..., 0, 0] * leak
leak = numpy.random.normal(0, leakage, gt.data['gain'][..., 1, 1].shape) + 1j * \
numpy.random.normal(0, leakage, gt.data['gain'][..., 1, 1].shape)
gt.data['gain'][..., 1, 0] = gt.data['gain'][..., 1, 1] * leak
else:
gt.data['gain'][..., 0, 1] = 0.0
gt.data['gain'][..., 1, 0] = 0.0
return gt
def simulate_pointingtable(pt: PointingTable, pointing_error, static_pointing_error=None, global_pointing_error=None,
seed=None, **kwargs) -> PointingTable:
""" Simulate a gain table
:type pt: PointingTable
:param pointing_error: std of normal distribution (radians)
:param static_pointing_error: std of normal distribution (radians)
:param global_pointing_error: 2-vector of global pointing error (rad)
:param kwargs:
:return: PointingTable
"""
if seed is not None:
numpy.random.seed(seed)
if static_pointing_error is None:
static_pointing_error = [0.0, 0.0]
r2s = 180.0 * 3600.0 / numpy.pi
pt.data['pointing'] = numpy.zeros(pt.data['pointing'].shape)
ntimes, nant, nchan, nrec, _ = pt.data['pointing'].shape
if pointing_error > 0.0:
log.debug("simulate_pointingtable: Simulating dynamic pointing error = %g (rad) %g (arcsec)"
% (pointing_error, r2s * pointing_error))
pt.data['pointing'] += numpy.random.normal(0.0, pointing_error, pt.data['pointing'].shape)
if (abs(static_pointing_error[0]) > 0.0) or (abs(static_pointing_error[1]) > 0.0):
numpy.random.seed(18051955)
log.debug("simulate_pointingtable: Simulating static pointing error = (%g, %g) (rad) (%g, %g)(arcsec)"
% (static_pointing_error[0], static_pointing_error[1],
r2s * static_pointing_error[0], r2s * static_pointing_error[1]))
static_pe = numpy.zeros(pt.data['pointing'].shape[1:])
static_pe[...,0] = numpy.random.normal(0.0, static_pointing_error[0],
static_pe[...,0].shape)[numpy.newaxis, ...]
static_pe[...,1] = numpy.random.normal(0.0, static_pointing_error[1],
static_pe[...,1].shape)[numpy.newaxis, ...]
pt.data['pointing'] += static_pe
if global_pointing_error is not None:
if seed is not None:
numpy.random.seed(seed)
log.debug("simulate_pointingtable: Simulating global pointing error = [%g, %g] (rad) [%g,s %g] (arcsec)"
% (global_pointing_error[0], global_pointing_error[1],
r2s * global_pointing_error[0], r2s * global_pointing_error[1]))
pt.data['pointing'][..., :] += global_pointing_error
return pt
def simulate_pointingtable_from_timeseries(pt, type='wind', time_series_type='precision',
pointing_directory=None, reference_pointing=False,
seed=None):
"""Create a pointing table with time series created from PSD.
:param pt: Pointing table to be filled
:param type: Type of pointing: 'tracking' or 'wind'
:param pointing_file: Name of pointing file
:param reference_pointing: Use reference pointing?
:return:
"""
if seed is not None:
numpy.random.seed(seed)
if pointing_directory is None:
pointing_directory = arl_path("data/models/%s" % time_series_type)
pt.data['pointing'] = numpy.zeros(pt.data['pointing'].shape)
ntimes, nant, nchan, nrec, _ = pt.data['pointing'].shape
# Use az and el at the beginning of this pointingtable
axis_values = pt.nominal[0,0,0,0,0]
el = pt.nominal[0,0,0,0,1]
el_deg = el * 180.0 / numpy.pi
az_deg = axis_values * 180.0 / numpy.pi
if el_deg < 30.0:
el_deg = 15.0
elif el_deg < (90.0+45.0)/2.0:
el_deg = 45.0
else:
el_deg = 90.0
if abs(az_deg) < 45.0 / 2.0:
az_deg = 0.0
elif abs(az_deg) < (45.0 + 90.0)/2.0:
az_deg = 45.0
elif abs(az_deg) < (90.0 + 135.0)/2.0:
az_deg = 90.0
elif abs(az_deg) < (135.0 + 180.0)/2.0:
az_deg = 135.0
else:
az_deg = 180.0
pointing_file = '%s/El%dAz%d.dat' % (pointing_directory, int(el_deg), int(az_deg))
log.info("simulate_pointingtable_from_timeseries: Reading wind PSD from %s" % pointing_file)
psd = numpy.loadtxt(pointing_file)
# define some arrays
freq = psd[:, 0]
axesdict = {
"az": psd[:, 1],
"el": psd[:, 2],
"pxel": psd[:, 3],
"pel": psd[:, 4]
}
if type == 'tracking':
axes = ["az", "el"]
elif type == 'wind':
axes = ["pxel", "pel"]
else:
raise ValueError("Pointing type %s not known" % type)
freq_interval = 0.0001
for axis in axes:
axis_values = axesdict[axis]
if (axis == "az") or (axis == "el"):
# determine index of maximum PSD value; add 50 for better fit
axis_values_max_index = numpy.argwhere(axis_values == numpy.max(axis_values))[0][0] + 50
axis_values_max_index = min(axis_values_max_index, len(axis_values))
# max_freq = 2.0 / pt.interval[0]
max_freq = 0.4
freq_max_index = numpy.argwhere(freq > max_freq)[0][0]
else:
break_freq = 0.01 # not max; just a break
axis_values_max_index = numpy.argwhere(freq>break_freq)[0][0]
# max_freq = 2.0 / pt.interval[0]
max_freq = 0.1
freq_max_index = numpy.argwhere(freq > max_freq)[0][0]
# construct regularly-spaced frequencies
regular_freq = numpy.arange(freq[0], freq[freq_max_index], freq_interval)
regular_axis_values_max_index = numpy.argwhere(numpy.abs(regular_freq-freq[axis_values_max_index])==numpy.min(numpy.abs(regular_freq-freq[axis_values_max_index])))[0][0]
# print ('Frequency break: ', freq[az_max_index])
# print ('Max frequency: ', max_freq)
#
# print ('New frequency break: ', regular_freq[regular_az_max_index])
# print ('New max frequency: ', regular_freq[-1])
if axis_values_max_index>=freq_max_index:
raise ValueError('Frequency break is higher than highest frequency; select a lower break')
# use original frequency break and max frequency to fit function
# fit polynomial to psd up to max value
p_axis_values1 = numpy.polyfit(freq[:axis_values_max_index],
numpy.log(axis_values[:axis_values_max_index]), 5)
f_axis_values1 = numpy.poly1d(p_axis_values1)
# fit polynomial to psd beyond max value
p_axis_values2 = numpy.polyfit(freq[axis_values_max_index:freq_max_index],
numpy.log(axis_values[axis_values_max_index:freq_max_index]), 5)
f_axis_values2 = numpy.poly1d(p_axis_values2)
# use new frequency break and max frequency to apply function (ensures equal spacing of frequency intervals)
# resampled to construct regularly-spaced frequencies
regular_axis_values1 = numpy.exp(f_axis_values1(regular_freq[:regular_axis_values_max_index]))
regular_axis_values2 = numpy.exp(f_axis_values2(regular_freq[regular_axis_values_max_index:]))
# join
regular_axis_values = numpy.append(regular_axis_values1, regular_axis_values2)
M0 = len(regular_axis_values)
# check rms of resampled PSD
# df = regular_freq[1:]-regular_freq[:-1]
# psd2rms_pxel = numpy.sqrt(numpy.sum(regular_az[:-1]*df))
# print ('Calculate rms of resampled PSD: ', psd2rms_pxel)
original_regular_freq = regular_freq
original_regular_axis_values = regular_axis_values
# get amplitudes from psd values
if (regular_axis_values<0).any():
raise ValueError('Resampling returns negative power values; change fit range')
amp_axis_values = numpy.sqrt(regular_axis_values*2*freq_interval)
# need to scale PSD by 2* frequency interval before square rooting, then by number of modes in resampled PSD
# Now we generate some random phases
for ant in range(nant):
regular_freq = original_regular_freq
regular_axis_values = original_regular_axis_values
phi_axis_values = numpy.random.rand(len(regular_axis_values)) * 2 * numpy.pi
# create complex array
z_axis_values = amp_axis_values * numpy.exp(1j * phi_axis_values) # polar
# make symmetrical frequencies
mirror_z_axis_values = numpy.copy(z_axis_values)
# make complex conjugates
mirror_z_axis_values.imag -= 2 * z_axis_values.imag
# make negative frequencies
mirror_regular_freq = -regular_freq
# join
z_axis_values = numpy.append(z_axis_values, mirror_z_axis_values[::-1])
regular_freq = numpy.append(regular_freq, mirror_regular_freq[::-1])
# add a 0 Fourier term
z_axis_values = numpy.append(0 + 0 * 1j, z_axis_values)
regular_freq = numpy.append(0, regular_freq)
# perform inverse fft
ts = numpy.fft.ifft(z_axis_values)
# set up and check scalings
N = len(ts)
Dt = pt.interval[0]
ts = numpy.real(ts)
ts *= M0 # the result is scaled by number of points in the signal, so multiply - real part - by this
# The output of the iFFT will be a random time series on the finite
# (bounded, limited) time interval t = 0 to tmax = (N-1) X Dt, #
# where Dt = 1 / (2 X Fmax)
# scale to time interval
times = numpy.arange(ntimes) * Dt
# Convert from arcsec to radians
ts *= numpy.pi / (180.0 * 3600.0)
# We take reference pointing to mean that the pointing errors are zero at the beginning
# of the set of integrations
if reference_pointing:
ts[:] -= ts[0]
# pt.data['time'] = times[:ntimes]
if axis == 'az':
pt.data['pointing'][:, ant, :, :, 0] = ts[:ntimes, numpy.newaxis, numpy.newaxis, ...]
elif axis == 'el':
pt.data['pointing'][:, ant, :, :, 1] = ts[:ntimes, numpy.newaxis, numpy.newaxis, ...]
elif axis == 'pxel':
pt.data['pointing'][:, ant, :, :, 0] = ts[:ntimes, numpy.newaxis, numpy.newaxis, ...]
elif axis == 'pel':
pt.data['pointing'][:, ant, :, :, 1] = ts[:ntimes, numpy.newaxis, numpy.newaxis, ...]
else:
raise ValueError("Unknown axis %s" % axis)
return pt
def ingest_unittest_visibility(config, frequency, channel_bandwidth, times, vis_pol, phasecentre, block=False,
zerow=False):
if block:
vt = create_blockvisibility(config, times, frequency, channel_bandwidth=channel_bandwidth,