-
Notifications
You must be signed in to change notification settings - Fork 0
/
Lib_b4r.py
2129 lines (1620 loc) · 60.7 KB
/
Lib_b4r.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
### common modules ###
import numpy as np
import os
### functions ###
################################################################################
# date2mjs
def date2mjs(t):
# t = '2018-10-05T05:37:50.994900'
y = int(str(t)[0:4])
m = int(str(t)[5:7])
d = int(str(t)[8:10])
hh = int(str(t)[11:13])
mm = int(str(t)[14:16])
ss = float(str(t)[17:])
return (int(365.25*y)+y//400-y//100.+int(30.59*(m-2))+d-678912)*24.*3600.+hh*3600+mm*60+ss
# end date2mjs
################################################################################
# xffts2netcdf
def xffts2netcdf(infile,outfile):
#os.system('python xffts2netcdf.py '+infile+' '+outfile)
"""Convert XFFTS binary file to netCDF.
Usage: $ python xffts2netcdf.py <xffts binary file> <netcdf>
"""
# standard library
import os
import re
import sys
from collections import deque, OrderedDict
from pathlib import Path
from struct import Struct
# dependent packages
import numpy as np
from netCDF4 import Dataset
from tqdm import tqdm
# module constants
CONFIG = (
('date', '28s'),
('junk1', '4s'),
('obsnum', 'q'),
('bufpos', '8s'),
('scanmode', '8s'),
('chopperpos', '8s'),
('scancount', 'q'),
('speccount', 'q'),
('integtime', 'l'),
('junk2', '172s'),
('array', 'f', 32768)
)
''' Old config
CONFIG = [
('date', '28s'),
('junk1', '4s'),
('obsnum', 'l'),
('bufpos', '8s'),
('scanmode', '8s'),
('chopperpos', '8s'),
('scancount', 'l'),
('speccount', 'l'),
('integtime', 'l'),
('junk2', '184s'),
('array', 'f', 32768)
]
'''
# functions and classes
class Struct2NetCDF:
def __init__(self, path, config, overwrite=False,
byteorder='<', unlimited_dim='t'):
"""Initialize structure-to-netCDF converter.
Args:
path (str or path object): Path of netCDF to be created.
config (tuple of items): Tuple that contains tuple items
(name, format character, shape) for member in a structure.
overwrite (bool, optional): If True, the converter overwrites
an existing netCDF of the same name. Default is False.
byteorder (str, optional): Format character that indicates
the byte order of a binary file. Default is for little
endian ('<'). Use '>' for big endian instead.
"""
# instance variables
self.path = Path(path).expanduser()
self.byteorder = byteorder
self.unlimited_dim = unlimited_dim
# check netCDF existance
if self.path.exists() and not overwrite:
raise FileExistsError(f'{self.path} already exists')
# initialization
self.config = self.parse_config(config)
self.struct = self.create_struct()
self.dataset = self.create_empty_dataset()
# initialize writing counter
self.n_write = 0
# aliases
self.close = self.dataset.close
self.readsize = self.struct.size
def write(self, binary):
"""Convert binary data compatible to netCDF format and write it."""
if len(binary) == 0:
raise EOFError('Reached the end of file')
assert len(binary) == self.readsize
data = deque(self.struct.unpack(binary))
for name, (fmt, shape) in self.config.items():
variable = self.dataset[name]
# in the case of no additional dimensions
if shape == (1,):
variable[self.n_write] = data.popleft()
continue
# otherwise
flat = [data.popleft() for i in range(np.prod(shape))]
variable[self.n_write] = np.reshape(flat, shape)
self.n_write += 1
def create_struct(self):
"""Create structure object for unpacking binary string."""
joined = ''.join(c*np.prod(s) for c, s in self.config.values())
return Struct(self.byteorder + joined)
def create_empty_dataset(self):
"""Create empty netCDF dataset according to structure config."""
# add unlimited dimension
empty = Dataset(self.path, 'w')
empty.createDimension(self.unlimited_dim)
# add variables and additional dimensions
for name, (fmt, shape) in self.config.items():
dtype = self.convert_fmt_to_dtype(fmt)
# in the case of no additional dimensions
if shape == (1,):
dims = (self.unlimited_dim,)
empty.createVariable(name, dtype, dims)
continue
# otherwise
n_dims = len(shape)
dims = [f'{name}_dim{i}' for i in range(n_dims)]
for i in range(n_dims):
dim, size = dims[i], shape[i]
empty.createDimension(dim, size)
dims = (self.unlimited_dim,) + tuple(dims)
empty.createVariable(name, dtype, dims)
return empty
@staticmethod
def parse_config(config):
"""Parse structure config to ordered dictionary."""
parsed = OrderedDict()
for item in config:
if not 2 <= len(item) <= 3:
raise ValueError(item)
name, fmt = item[:2]
shape = (item[2:] or (1,))[0]
if isinstance(shape, int):
shape = (shape,)
assert isinstance(name, str)
assert isinstance(fmt, str)
assert isinstance(shape, tuple)
parsed[name] = fmt, shape
return parsed
@staticmethod
def convert_fmt_to_dtype(fmt):
"""Convert format character to NumPy dtype object."""
if re.search('[bhil]', fmt, re.I):
return np.int32
elif re.search('[q]', fmt, re.I):
return np.int64
elif re.search('[ef]', fmt):
return np.float32
elif re.search('[d]', fmt):
return np.float64
elif re.search('[csp]', fmt):
return np.str
elif re.search('[?]', fmt):
return np.bool
else:
raise ValueError(fmt)
def __enter__(self):
"""Special method for with statement."""
return self
def __exit__(self, exc_type, exc_value, traceback):
"""Special method for with statement."""
self.close()
def main(infile,outfile):
"""Main function for command line tool."""
#args = sys.argv[1:]
args = [infile,outfile]
xffts = Path(args[0]).expanduser()
if len(args) == 1:
netcdf = Path(f"{xffts}.nc")
elif len(args) == 2:
netcdf = Path(args[1]).expanduser()
else:
print(__doc__)
sys.exit(0)
with xffts.open('rb') as f, Struct2NetCDF(netcdf, CONFIG) as g:
filesize = xffts.stat().st_size
readsize = g.readsize
assert not filesize % readsize
n_struct = int(filesize / readsize)
for i in tqdm(range(n_struct)):
binary = f.read(readsize)
g.write(binary)
main(infile,outfile)
# end xffts2netcdf
################################################################################
# pathOFnc
def pathOFnc(path_cal_raw,path_sci_raw):
if path_cal_raw[-3:] == '.nc':
path_cal = path_cal_raw
else:
path_cal = path_cal_raw+'.nc'
#os.system('rm -rf '+path_cal)
xffts2netcdf(path_cal_raw,path_cal)
if path_sci_raw[-3:] == '.nc':
path_sci = path_sci_raw
else:
path_sci = path_sci_raw+'.nc'
#os.system('rm -rf '+path_sci)
xffts2netcdf(path_sci_raw,path_sci)
return path_cal,path_sci
# end pathOFnc
################################################################################
# create_freq
def create_freq(path_ant,sideband,tBW=2.5,nchan=2**15):
# modules
import xarray as xr
# get frequency array
ant = xr.open_dataset(path_ant)
LO1 = ant['Header.B4r.LineFreq'].values[0]
LO2 = ant['Header.B4r.If2Freq'].values[0]
if (sideband=='USB'):
return np.linspace(LO1+LO2, LO1+LO2-tBW,nchan)
elif (sideband=='LSB'):
return np.linspace(LO1-LO2, LO1-LO2+tBW,nchan)
# end create_freq
################################################################################
# read_rawdata_science
def read_rawdata_science(path_sci,freq,timestampFlag=True,cal=True,Tsys=None,threshold_despiking=100.):
# modules
import xarray as xr
import fmflow as fm
with xr.open_dataset(path_sci) as ds:
array = ds['array'].copy().values
integtime = ds['integtime'].copy().values
scantype = ds['bufpos'].copy().values
scanno = ds['scancount'].copy().values
date = ds['date'].copy().values
# flagging invalid datetime
if timestampFlag:
t_sci = np.array([s[:-4] for s in date], 'datetime64[us]')
flag = t_sci < t_sci[-1]
array = array[flag]
integtime = integtime[flag]
scantype = scantype[flag]
scanno = scanno[flag]
state_id = (scantype == 'ON').astype('int32')
tcoords = {'scanno': scanno, 'scantype': scantype, 'state_id': state_id}
chcoords = {'fsig': freq}
state_id = {'state_id': state_id}
P = fm.array(array/integtime[:,None],
tcoords=tcoords, chcoords=chcoords)
#print(P)
if cal:
Pon = P[scantype=='ON']
Poff = P[scantype=='REF']
Tcal = fm.zeros_like(Pon)
for no in np.unique(Pon.scanno):
# ON array of single scan
Pon_ = Pon[Pon.scanno==no]
# OFF array for single scan
Poff_l = Poff[Poff.scanno==no-1].mean('t')
Poff_r = Poff[Poff.scanno==no+1].mean('t')
if np.all(np.isnan(Poff_r)):
Poff_ = Poff_l
else:
Poff_ = (Poff_l+Poff_r) / 2
#print(Tsys)
#print(Pon_)
#print(Poff_)
# calibrated array
Tcal_ = Tsys * (Pon_-Poff_) / (Poff_)
Tcal[Tcal.scanno==no] = Tcal_.T
Tcal.values[np.abs(Tcal)>threshold_despiking] = 0
return Tcal
else:
return P
# end read_rawdata_science
################################################################################
# cal_Tsys_from_rawdata_R
def cal_Tsys_from_rawdata_R(path_cal,path_ant,freq,CASAoffset=3506716797.):
# modules
import xarray as xr
import fmflow as fm
with xr.open_dataset(path_cal) as ds:
array = ds['array'].copy().values
integtime = ds['integtime'].copy().values
chopperpos = ds['chopperpos'].copy().values
date = ds['date'].copy().values
ant = xr.open_dataset(path_ant)
Tamb = 273.0 + ant['Header.Weather.Temperature'].copy().values
#Tamb = 273.0 + ant['Header.B4r.LoadAmbientTemp'].copy().values
t_tsys = np.array([s[:-4] for s in date], 'datetime64[us]')[0]
Tsys_time = CASAoffset + (t_tsys - np.array('1970-01-01T00:00:00.000000',dtype='datetime64[us]'))/np.timedelta64(1,'s')
Pr = fm.array((array/np.array([integtime]).T)[chopperpos=='R']).mean('t')
Psky = fm.array((array/np.array([integtime]).T)[chopperpos=='S']).mean('t')
chcoords = {'fsig': freq}
Tsys = Tamb*Psky/(Pr-Psky)
return Tsys, Tsys_time
# end cal_Tsys_from_rawdata_R
################################################################################
# getOBSinfo
def getOBSinfo(path_ant):
# modules
import xarray as xr
ant = xr.open_dataset(path_ant)
try:
sourcename_ = ant['Header.Source.SourceName'].copy().values.astype('|U')
sourcename = np.array([sourcename_,sourcename_])[0].replace(' ','')
except:
sourcename_ = ''
sourcename = ''
ra = ant['Header.Source.Ra'].copy().values[0]/np.pi*180.
dec = ant['Header.Source.Dec'].copy().values[0]/np.pi*180.
sysvel = ant['Header.Source.Velocity'].copy().values + 0.
project_ = ant['Header.Dcs.ProjectId'].copy().values.astype('|U')
project = np.array([project_,project_])[0].replace(' ','')
observer_ = ant['Header.Telescope.Operator'].copy().values.astype('|U')
observer = np.array([observer_,observer_])[0].replace(' ','')
return ra,dec,sysvel,sourcename,project,observer
# end getOBSinfo
################################################################################
# data2coord
def data2coord(path_sci,path_ant,nrows=False,cal=True):
# modules
import xarray as xr
from scipy.interpolate import interp1d
from datetime import datetime as dt
from datetime import timezone as tz
with xr.open_dataset(path_sci) as ds:
array = ds['array'].copy().values
integtime = ds['integtime'].copy().values
scantype = ds['bufpos'].copy().values
scanno = ds['scancount'].copy().values
date = ds['date'].copy().values
# flagging invalid datetime
t_sci = np.array([s[:-4] for s in date], 'datetime64[us]')
flag = t_sci < t_sci[-1]
array = array[flag]
integtime = integtime[flag]
scantype = scantype[flag]
scanno = scanno[flag]
date = date[flag]
t_sci = t_sci[flag]
#ON
#t_sci = t_sci[scantype == 'ON']
with xr.open_dataset(path_ant) as ds:
x_ant = np.rad2deg(ds['Data.TelescopeBackend.TelAzSky'].values)
y_ant = np.rad2deg(ds['Data.TelescopeBackend.TelElSky'].values)
unix = ds['Data.TelescopeBackend.TelTime'].values # unix time
SourceName = bytes(ds['Header.Source.SourceName'].values).decode()
t_ant = np.array([dt.fromtimestamp(t,tz.utc) for t in unix], 'datetime64[us]')
dt_sci = (t_sci - t_ant[0]).astype(np.float64)
dt_ant = (t_ant - t_ant[0]).astype(np.float64)
x_sci = interp1d(dt_ant, x_ant, fill_value='extrapolate')(dt_sci)
y_sci = interp1d(dt_ant, y_ant, fill_value='extrapolate')(dt_sci)
if cal:
x_sci = x_sci[scantype=='ON']
y_sci = y_sci[scantype=='ON']
t_sci = t_sci[scantype=='ON']
if nrows:
return x_sci, y_sci, t_sci, x_sci.shape[0]
else:
return x_sci, y_sci, t_sci
# end data2coord
################################################################################
# AZEL2RADEC
def AZEL2RADEC(az,
el,
utc,
lon = -97.31461167440136,
lat = 18.98607157170612,
height = 4640.):
# modules
from astropy import coordinates
from astropy.time import Time
import astropy.units as u
site = coordinates.EarthLocation.from_geodetic(lon=lon,lat=lat,height=height)
c = str(az) + ' ' + str(el)
radec = coordinates.SkyCoord(c, unit=(u.deg,u.deg),frame='altaz',obstime=Time(utc.astype('|U')),location=site).transform_to('icrs')
return radec.ra.value, radec.dec.value
################################################################################
# PointingINFO
def PointingINFO(path_sci,path_ant,CASAoffset=3506716797.,cal=True):
# modules
x,y,t,nrows = data2coord(path_sci,path_ant,nrows=True,cal=cal)
direction = np.zeros((nrows,2),dtype='float64')
time = np.full(nrows,5.04545e+09,dtype='float64')
for i in range(nrows):
ra,dec = AZEL2RADEC(x[i],y[i],t[i])
direction[i][0] = ra
direction[i][1] = dec
#time[i] = CASAoffset + (t[i] - np.array('1970-01-01T00:00:00.000000',dtype='datetime64[us]'))/np.timedelta64(1,'s')
time[i] = date2mjs(t[i])
return direction, time
# end PointingINFO
################################################################################
# loadB4Rdata
def loadB4Rdata(path_cal_raw,path_sci_raw,path_ant,sideband,cal=True,blsub=False,qlook=False,Tsys_qlook=200.):
# modules
import xarray as xr
import fmflow as fm
# load
freq = create_freq(path_ant,sideband)
if qlook:
path_cal_dammy, path_sci = pathOFnc(path_sci_raw+'.nc',path_sci_raw)
Tsys = fm.array(np.full([1,32768],Tsys_qlook))[0]
Tsys_time = 5.0e9
P = read_rawdata_science(path_sci,freq,timestampFlag=True,Tsys=Tsys,cal=cal)
else:
path_cal, path_sci = pathOFnc(path_cal_raw,path_sci_raw)
Tsys, Tsys_time = cal_Tsys_from_rawdata_R(path_cal,path_ant,freq)
P = read_rawdata_science(path_sci,freq,timestampFlag=True,Tsys=Tsys,cal=cal)
if blsub:
for no in np.unique(P.scanno):
P_ = P[P.scanno==no]
N = P_.shape[0]
t = xr.DataArray(np.arange(N), dims='t')
Pbl_ = ((N-1-t)/(N-1)*P_[0]).values + (t/(N-1)*P_[-1]).values
P[P.scanno==no] -= Pbl_
return P, Tsys, Tsys_time
# end loadB4Rdata
################################################################################
# np.array(['Hz'],dtype='|S3'data
def loadB4Rfulldata(path_cal_raw_head,path_sci_raw_head,path_antlog,chbin,cal=True,blsub=False):
# modules
import fmflow as fm
# Params
num = ['.01','.03','.02','.04']
sideband = ['LSB','LSB','USB','USB']
for i in [0,1]:
if os.path.exists(path_cal_raw_head+num[i]+'.nc'):
path_cal_raw = path_cal_raw_head+num[i]+'.nc'
else:
path_cal_raw = path_cal_raw_head+num[i]
if os.path.exists(path_sci_raw_head+num[i]+'.nc'):
path_sci_raw = path_sci_raw_head+num[i]+'.nc'
else:
path_sci_raw = path_sci_raw_head+num[i]
P_, Tsys_, Tsys_time = loadB4Rdata(path_cal_raw,path_sci_raw,path_antlog,sideband[i],cal=cal,blsub=blsub)
if i==0:
P_LSB_X = fm.chbinning(P_, chbin).copy().values
Tsys_LSB_X = fm.chbinning(Tsys_, chbin).copy().values
state_id = P_['state_id'].copy().values
freq_LSB = fm.chbinning(P_, chbin)['fsig'].copy().values
nrows = P_LSB_X.shape[0]
nchan = P_LSB_X.shape[1]
else:
P_LSB_Y = fm.chbinning(P_, chbin).copy().values
Tsys_LSB_Y = fm.chbinning(Tsys_, chbin).copy().values
for i in [2,3]:
if os.path.exists(path_cal_raw_head+num[i]+'.nc'):
path_cal_raw = path_cal_raw_head+num[i]+'.nc'
else:
path_cal_raw = path_cal_raw_head+num[i]
if os.path.exists(path_sci_raw_head+num[i]+'.nc'):
path_sci_raw = path_sci_raw_head+num[i]+'.nc'
else:
path_sci_raw = path_sci_raw_head+num[i]
P_, Tsys_, Tsys_time = loadB4Rdata(path_cal_raw,path_sci_raw,path_antlog,sideband[i],cal=cal,blsub=blsub)
if i==2:
P_USB_X = fm.chbinning(P_, chbin).copy().values
Tsys_USB_X = fm.chbinning(Tsys_, chbin).copy().values
freq_USB = fm.chbinning(P_, chbin)['fsig'].copy().values
else:
P_USB_Y = fm.chbinning(P_, chbin).copy().values
Tsys_USB_Y = fm.chbinning(Tsys_, chbin).copy().values
P = np.zeros((nrows,2,2,nchan),dtype='float64')
P[:,0,0] = P_LSB_X
P[:,0,1] = P_LSB_Y
P[:,1,0] = P_USB_X
P[:,1,1] = P_USB_Y
Tsys = np.zeros((2,2,nchan),dtype='float64')
Tsys[0,0] = Tsys_LSB_X
Tsys[0,1] = Tsys_LSB_Y
Tsys[1,0] = Tsys_USB_X
Tsys[1,1] = Tsys_USB_Y
freq = np.zeros((2,nchan),dtype='float64')
freq[0] = freq_LSB
freq[1] = freq_USB
return P, Tsys, freq, state_id, Tsys_time
# end loadB4Rfulldata
################################################################################
# addKeywords
def addKeywords(colname,keyword_list,type_list,value_list,f):
if not isinstance(keyword_list, list):
keyword_list = [keyword_list]
if not isinstance(type_list, list):
type_list = [type_list]
if not isinstance(value_list, list):
value_list = [value_list]
f.write('.keywords '+colname+'\n')
for keyword,type,value in zip(keyword_list,type_list,value_list):
f.write(keyword+' '+type+' '+value+'\n')
f.write('.endkeywords'+'\n')
# end addKeywords
################################################################################
# makeMAIN
def makeMAIN(tablename,outputfilename,specdata,time,state_id,texp=0.2,tBW=2.5e9):
'''
specdata: (nrow,nspw,npol,nchan) array
time: (nrow,)
'''
# modules
import casacore.tables as tb
# params
nrow = specdata.shape[0]
nspw = specdata.shape[1]
npol = specdata.shape[2]
nchan = specdata.shape[3]
weight = tBW/float(nchan) * texp
sigma = (tBW/float(nchan) * texp)**-0.5
ind_spw = (np.linspace(0,2*nrow-1,2*nrow,dtype='int32') % 2)
#header
f = open(outputfilename+'.header','w')
header1 = 'UVW;WEIGHT;SIGMA;ANTENNA1;ANTENNA2;ARRAY_ID;DATA_DESC_ID;EXPOSURE;FEED1;FEED2;FIELD_ID;FLAG_ROW;INTERVAL;OBSERVATION_ID;PROCESSOR_ID;SCAN_NUMBER;STATE_ID;TIME;TIME_CENTROID;FLAG_CATEGORY;FLAG;FLOAT_DATA'
header2 = 'D3;R2;R2;I;I;I;I;D;I;I;I;B;D;I;I;I;I;D;D;B3;B2,'+str(nchan)+';R2,'+str(nchan)
f.write(header1+'\n')
f.write(header2+'\n')
f.close()
f = open(outputfilename+'.dat','w')
# table
for i in range(nrow):
for i_spw in range(nspw):
UVW = '0;0;0'
WEIGHT = str(weight)+';'+str(weight)
SIGMA = str(sigma)+';'+str(sigma)
ANTENNA1 = '0'
ANTENNA2 = '0'
ARRAY_ID = '0'
DATA_DESC_ID = str(i_spw)
EXPOSURE = str(texp)
FEED1 = '0'
FEED2 = '0'
FIELD_ID = '0'
FLAG_ROW = '0'
INTERVAL = str(texp)
OBSERVATION_ID = '0'
PROCESSOR_ID = '0'
SCAN_NUMBER = str(i)
STATE_ID = str(state_id[i])
TIME = str(time[i])
TIME_CENTROID = str(time[i])
FLAG_CATEGORY = ''
FLAG = ''
FLOAT_DATA = ''
f.write(UVW+';')
f.write(WEIGHT+';')
f.write(SIGMA+';')
f.write(ANTENNA1+';')
f.write(ANTENNA2+';')
f.write(ARRAY_ID+';')
f.write(DATA_DESC_ID+';')
f.write(EXPOSURE+';')
f.write(FEED1+';')
f.write(FEED2+';')
f.write(FIELD_ID+';')
f.write(FLAG_ROW+';')
f.write(INTERVAL+';')
f.write(OBSERVATION_ID+';')
f.write(PROCESSOR_ID+';')
f.write(SCAN_NUMBER+';')
f.write(STATE_ID+';')
f.write(TIME+';')
f.write(TIME_CENTROID+';')
f.write(FLAG_CATEGORY)
f.write(FLAG)
f.write(FLOAT_DATA+'\n')
f.close()
# make table
returned_table = tb.tablefromascii(tablename,outputfilename+'.dat',headerfile=outputfilename+'.header',sep=';',readonly=False)
value = np.zeros_like(np.concatenate([specdata[:,0],specdata[:,1]],axis=0),dtype='bool').transpose(0,2,1)
returned_table.putcol('FLAG',value)
value = np.zeros_like(np.concatenate([specdata[:,0],specdata[:,1]],axis=0),dtype='float64')
for i in range(2):
value[ind_spw==i] = specdata[:,i].copy()
value = value.transpose(0,2,1)
returned_table.putcol('FLOAT_DATA',value)
#value = np.zeros([2*nrow,3],dtype='bool')
#returned_table.putcol('FLAG_CATEGORY',value)
value = {'QuantumUnits': np.array(['m', 'm', 'm'],dtype='|S2'),
'MEASINFO': {'type': 'uvw', 'Ref': 'ITRF'},
}
returned_table.putcolkeywords('UVW',value)
value = {'CATEGORY': np.array([],dtype='|S1')}
returned_table.putcolkeywords('FLAG_CATEGORY',value)
value = {'QuantumUnits': np.array(['s'],dtype='|S2')}
returned_table.putcolkeywords('EXPOSURE',value)
value = {'QuantumUnits': np.array(['s'],dtype='|S2')}
returned_table.putcolkeywords('INTERVAL',value)
value = {'QuantumUnits': np.array(['s'],dtype='|S2'),
'MEASINFO': {'type': 'epoch', 'Ref': 'UTC'}
}
returned_table.putcolkeywords('TIME',value)
value = {'QuantumUnits': np.array(['s'],dtype='|S2'),
'MEASINFO': {'type': 'epoch', 'Ref': 'UTC'},
}
returned_table.putcolkeywords('TIME_CENTROID',value)
value = {'UNIT': 'K'}
returned_table.putcolkeywords('FLOAT_DATA',value)
returned_table.flush()
returned_table.close()
# end makeMAIN
################################################################################
# makeMAIN2
def makeMAIN2(tablename,specdata,time,state_id,texp=0.2,tBW=2.5e9):
# modules
import casacore.tables as tb
# params
nrow = specdata.shape[0]
nspw = specdata.shape[1]
npol = specdata.shape[2]
nchan = specdata.shape[3]
weight = tBW/float(nchan) * texp
sigma = (tBW/float(nchan) * texp)**-0.5
ind_spw = (np.linspace(0,2*nrow-1,2*nrow,dtype='int32') % 2)
# tables
colnames = ['UVW',
'FLAG',
'FLAG_CATEGORY',
'WEIGHT',
'SIGMA',
'ANTENNA1',
'ANTENNA2',
'ARRAY_ID',
'DATA_DESC_ID',
'EXPOSURE',
'FEED1',
'FEED2',
'FIELD_ID',
'FLAG_ROW',
'INTERVAL',
'OBSERVATION_ID',
'PROCESSOR_ID',
'SCAN_NUMBER',
'STATE_ID',
'TIME',
'TIME_CENTROID',
'FLOAT_DATA'
]
colkeywords = [
{'MEASINFO': {'Ref': 'ITRF', 'type': 'uvw'},'QuantumUnits': np.array(['m', 'm', 'm'],dtype='|S2')},
{},
{'CATEGORY': np.array([],dtype='|S1')},
{},{},{},{},{},{},
{'QuantumUnits': np.array(['s'],dtype='|S2')},
{},{},{},{},
{'QuantumUnits': np.array(['s'],dtype='|S2')},
{},{},{},{},
{'MEASINFO': {'Ref': 'UTC', 'type': 'epoch'}, 'QuantumUnits': np.array(['s'],dtype='|S2')},
{'MEASINFO': {'Ref': 'UTC', 'type': 'epoch'}, 'QuantumUnits': np.array(['s'],dtype='|S2')},
{'UNIT': 'K'}
]
ndims = [1,2,3,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2]
isarrays = [True,True,True,True,True,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,True]
valuetypes = ['double','bool','bool','float','float','int','int','int','int','double','int','int','int','bool','double','int','int','int','int','double','double','float']
descs = []
for colname,colkeyword,ndim,valuetype,isarray in zip(colnames,colkeywords,ndims,valuetypes,isarrays):
if colname=='UVW':
descs.append(tb.makearrcoldesc(colname,0.0,datamanagertype='StandardStMan',datamanagergroup='StandardStMan',ndim=ndim,keywords=colkeyword,valuetype=valuetype,options=5,shape=np.array([3], dtype='int32')))
elif isarray:
descs.append(tb.makearrcoldesc(colname,0.0,datamanagertype='StandardStMan',datamanagergroup='StandardStMan',ndim=ndim,keywords=colkeyword,valuetype=valuetype))
else:
descs.append(tb.makescacoldesc(colname,0.0,datamanagertype='StandardStMan',datamanagergroup='StandardStMan',keywords=colkeyword,valuetype=valuetype))
td = tb.maketabdesc(descs=descs)
returned_table = tb.table(tablename,tabledesc=td,nrow=2*nrow,readonly=False)
# put values
value = np.zeros([2*nrow,3],dtype='float64')
returned_table.putcol('UVW',value)
value = np.full([2*nrow,2],sigma)
returned_table.putcol('SIGMA',value)
value = np.full([2*nrow,2],weight)
returned_table.putcol('WEIGHT',value)
value = np.zeros([2*nrow],dtype='int32')
returned_table.putcol('ANTENNA1',value)
returned_table.putcol('ANTENNA2',value)
returned_table.putcol('ARRAY_ID',value)
returned_table.putcol('FEED1',value)
returned_table.putcol('FEED2',value)
returned_table.putcol('FIELD_ID',value)
returned_table.putcol('OBSERVATION_ID',value)
returned_table.putcol('PROCESSOR_ID',value)
value = np.zeros([2*nrow],dtype='bool')
returned_table.putcol('FLAG_ROW',value)
value = np.full([2*nrow],texp,dtype='float64')
returned_table.putcol('EXPOSURE',value)
returned_table.putcol('INTERVAL',value)
value = np.zeros_like(np.concatenate([specdata[:,0],specdata[:,1]],axis=0),dtype='bool')
value = value.transpose(0,2,1)
returned_table.putcol('FLAG',value)
value = np.zeros_like(np.concatenate([specdata[:,0],specdata[:,1]],axis=0),dtype='float64')
for i in range(2):
value[ind_spw==i] = specdata[:,i].copy()
value = value.transpose(0,2,1)
returned_table.putcol('FLOAT_DATA',value)
value = np.zeros(2*nrow,dtype='int32')
for i in range(2):
value[ind_spw==i] = state_id
value = np.zeros(2*nrow,dtype='int32')
for i in range(2):
value[ind_spw==i] = i
returned_table.putcol('DATA_DESC_ID',value)
value = np.zeros(2*nrow,dtype='int32')
for i in range(2):
value[ind_spw==i] = state_id
returned_table.putcol('STATE_ID',value)
value = np.zeros(2*nrow,dtype='int32')
for i in range(2):
value[ind_spw==i] = np.linspace(0,nrow-1,nrow,dtype='int32')
returned_table.putcol('SCAN_NUMBER',value)
value = np.zeros(2*nrow,dtype='float64')
for i in range(2):
value[ind_spw==i] = time.copy()
returned_table.putcol('TIME',value)
returned_table.putcol('TIME_CENTROID',value)
returned_table.flush()
returned_table.close()
# end makeMAIN2
################################################################################
# makeANTENNA
def makeANTENNA(tablename,
outputfilename,
dish_diameter = 50.,
nbeam = 1,
beamname = 'LMT-b4r-beam',
lon = -97. + 18./60. + 53./3600.,
lat = 18. + 59./60. + 6./3600.,
height = 4600.,
type = 'GROUND-BASED',
mounit='ALT-AZ'):
# modules
from astropy import coordinates
import casacore.tables as tb
# params
c = coordinates.EarthLocation.from_geodetic(lon=lon,lat=lat,height=height)
x = c.value[0]
y = c.value[1]
z = c.value[2]
beamname_list = []
for i in range(nbeam):
beamname_list.append(beamname+str(i))
# header
header1 = 'OFFSET;POSITION;TYPE;DISH_DIAMETER;FLAG_ROW;MOUNT;NAME;STATION'
header2 = 'D3;D3;A;D;B;A;A;A'
f = open(outputfilename+'.header','w')
f.write(header1+'\n')
f.write(header2+'\n')
f.close()
# table
f = open(outputfilename+'.dat','w')
for i in range(nbeam):
OFFSET = '0;0;0'
POSITION = str(x)+';'+str(y)+';'+str(z)
TYPE = '"'+type+'"'
DISH_DIAMETER = str(dish_diameter)
FLAG_ROW = '0'
MOUNT = '"'+mounit+'"'
NAME = '"'+';'.join(beamname_list)+'"'
STATION = '""'
f.write(OFFSET+';')
f.write(POSITION+';')
f.write(TYPE+';')
f.write(DISH_DIAMETER+';')
f.write(FLAG_ROW+';')
f.write(MOUNT+';')
f.write(NAME+';')
f.write(STATION+'\n')
f.close()
# make table
returned_table = tb.tablefromascii(tablename,outputfilename+'.dat',headerfile=outputfilename+'.header',sep=';',readonly=False)
value = {'QuantumUnits': np.array(['m', 'm', 'm'],dtype='|S2'),
'MEASINFO': {'type': 'position','Ref': 'ITRF'},
}
returned_table.putcolkeywords('OFFSET',value)
value = {'QuantumUnits': np.array(['m', 'm', 'm'],dtype='|S2'),
'MEASINFO': {'type': 'position','Ref': 'ITRF'},
}
returned_table.putcolkeywords('POSITION',value)
value = {'QuantumUnits': np.array(['m'],dtype='|S2')}