-
Notifications
You must be signed in to change notification settings - Fork 10
/
concat_timehack.py
executable file
·153 lines (141 loc) · 6.56 KB
/
concat_timehack.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2019 - Francesco de Gasperin
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
import pyrap.tables as pt
import glob, optparse, sys, subprocess, os
import numpy as np
from pyrap.quanta import quantity
from datetime import datetime
usage = "usage: python %prog [options] MStoConcat1 MS2 .."
description="Temporary script to concat data in such a way to eliminate time gaps between the data to enable imaging with AWimager."
vers="1.0"
parser = optparse.OptionParser(usage=usage, version="%prog v{0}".format(vers), description=description)
parser.add_option("-f", "--force", action="store_true", dest="force", default=False ,help="Force concat despite different time intervals [default: %default]")
parser.add_option("-g", "--gap", action="store", type='float', dest="gap", default=120. ,help="Define time gap, in seconds, to include between observations [default: %default]")
parser.add_option("-o", "--output", action="store", type="string", dest="output", default='TIME_HACK.MS',help="Define the name of the output measurement set [default: %default]")
parser.add_option("-w", "--overwrite", action="store_true", dest="ow", default=False,help="Overwrite output MS if it already exists [default: %default]")
(options, args) = parser.parse_args()
def checkintervals(mss):
"""Checks the intervals of each measurement set"""
intervals=[]
print("Measurement Set\t\t\tTime Interval\t\tStart\t\tEnd")
print("-----------------------------------------------------------------------------------------------")
for i in mss:
temp=pt.table(i, ack=False)
t=temp.getcol('INTERVAL')[0]
intervals.append(t)
temp.close()
#Open table again to get start and end tomes
temp=pt.table(i, ack=False)
tempst,tempend=temp.getcol("TIME")[[0,-1]]
print("{0}\t{1}s\t{2}\t{3}".format(i, t, datetime.utcfromtimestamp(quantity('{0}s'.format(tempst)).to_unix_time()),
datetime.utcfromtimestamp(quantity('{0}s'.format(tempend)).to_unix_time())))
intervals=np.array(intervals)
uniq=np.unique(intervals)
if len(uniq) > 1:
return False, uniq
else:
return True, uniq
def concat(sets, outname):
"""Just the function from concat.py"""
sys.stdout.write("Concatenating Measurement Sets...")
sys.stdout.flush()
try:
newtable = pt.table(sets, ack=False)
newtable.sort('TIME').copy(outname, deep = True)
print("Done!")
return True
except:
print("Error!")
print("Concat failed most likely channel number differences?")
return False
def newtimearray(times, cen_times, interval, g):
newtimes={} #to hold the new times for each unique old time
newtimes_cen={}
diff_times=np.unique(times)
diff_cen_times=np.unique(times)
newtimes[diff_times[0]]=diff_times[0]
newtimes_cen[diff_cen_times[0]]=diff_cen_times[0]
boost=False
for i in range(1,len(diff_times)):
if diff_times[i] not in list(newtimes.keys()):
if diff_times[i]-diff_times[i-1]>interval*1.01:
boost=True
newtimes[diff_times[i]]=newtimes[diff_times[i-1]]+interval+g
else:
newtimes[diff_times[i]]=newtimes[diff_times[i-1]]+interval
if diff_cen_times[i] not in list(newtimes_cen.keys()):
if boost:
newtimes_cen[diff_cen_times[i]]=newtimes_cen[diff_cen_times[i-1]]+interval+g
else:
newtimes_cen[diff_cen_times[i]]=newtimes_cen[diff_cen_times[i-1]]+interval
boost=False
# for j in diff_times:
# print "{0} --> {1}".format(datetime.utcfromtimestamp(quantity('{0}s'.format(j)).to_unix_time()), datetime.utcfromtimestamp(quantity('{0}s'.format(newtimes[j])).to_unix_time()))
newtimes_list=[newtimes[k] for k in times]
newcentimes_list=[newtimes_cen[l] for l in cen_times]
return np.array(newtimes_list), np.array(newcentimes_list), newtimes_list[0], newtimes_list[-1]
oname=options.output
gap=options.gap
#check for measurement sets arguments
if len(args)<1:
print("You must enter some datasets! - 'python hack.py MS1 MS2 ... MSX'")
sys.exit()
#check if output already exists
if os.path.isdir(oname):
if not options.ow:
print("{0} already exists! Delete or run with '-w' option".format(oname))
sys.exit()
else:
subprocess.call(["rm", "-r", oname])
#check intervals
print("\nChecking intervals of sets {0}...\n".format(", ".join(args)))
check, interv=checkintervals(args)
if check:
inter=interv[0]
else:
if options.force:
print("\nForcing concat with different time intervals. Will take first interval as interval to use")
inter=interv[0]
else:
print("\nMeasurement sets intervals are not the same!")
print("Intervals detected: {0}".format(interv))
sys.exit()
print("\nInterval = {0}s".format(inter))
if concat(args, oname):
# if True:
print("Changing Times on Set...")
mstochange=pt.table(oname, ack=False, readonly=False)
amps_time = mstochange.getcol('TIME')
amps_time_cen = mstochange.getcol('TIME_CENTROID')
new_time, newtime_cen, start, end=newtimearray(amps_time, amps_time_cen, inter, gap)
mstochange.putcol('TIME',new_time)
mstochange.putcol('TIME_CENTROID',newtime_cen)
mstochange.close()
mstochange=pt.table(oname+'/OBSERVATION', ack=False, readonly=False)
mstochange.putcell("LOFAR_OBSERVATION_START", 0, start)
mstochange.putcell("LOFAR_OBSERVATION_END", 0, start)
newrange=np.array([start, end])
mstochange.putcell("TIME_RANGE", 0, newrange)
mstochange.close()
inttime=end-start
print("Start Time: {0}".format(datetime.utcfromtimestamp(quantity('{0}s'.format(start)).to_unix_time())))
print("NEW End Time: {0}".format(datetime.utcfromtimestamp(quantity('{0}s'.format(end)).to_unix_time())))
print("Integration Time = {0:.2f}s ({1:.2f} hours)".format(inttime, (inttime)/3600.))
else:
sys.exit()