-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmakelcfromruncat.py
More file actions
217 lines (187 loc) · 8.57 KB
/
makelcfromruncat.py
File metadata and controls
217 lines (187 loc) · 8.57 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
import psycopg2
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
import datetime
import argparse
from astropy.coordinates import SkyCoord
parser = argparse.ArgumentParser()
parser.add_argument('csvfile',type=str,help='csvfile from slidingetaint.py')
parser.add_argument('--usefpeak',action='store_true',help='Use peak flux instead of integrated flux')
args = parser.parse_args()
def initdb():
import psycopg2
import os
from psycopg2.extensions import register_adapter, AsIs
# psycopg2 complains about numpy datatypes, this avoids that error. Got this from stackoverflow but don't recall where
def addapt_numpy_float64(numpy_float64):
return AsIs(numpy_float64)
def addapt_numpy_int64(numpy_int64):
return AsIs(numpy_int64)
register_adapter(np.float64, addapt_numpy_float64)
register_adapter(np.int64, addapt_numpy_int64)
host = os.getenv('TKP_DBHOST')
port = os.getenv('TKP_DBPORT')
user = os.getenv('TKP_DBUSER')
password = os.getenv('TKP_DBPASSWORD')
database = os.getenv('TKP_DBNAME')
if password is None:
conn = psycopg2.connect("dbname="+database+" user="+user+" host="+host)
else:
conn = psycopg2.connect("dbname="+database+" user="+user+" password="+password+" host="+host)
################################################################################
# Typical psycopg2 setup
conn = psycopg2.connect("dbname="+database+" user="+user+" password="+password+" host="+host)
return conn.cursor()
def makelc(dates,flux,fluxerr,runcat):
from matplotlib import rcParams, rcParamsDefault
rcParams.update(rcParamsDefault)
fig = plt.figure()
plt.scatter(dates,flux)
plt.errorbar(dates,flux,yerr=np.sqrt(fluxerr**2+(0.1*flux)**2),fmt='none')
ax=plt.gca()
# ax.set_xscale('log')
ax.set_xlabel('Days post trigger')
ax.set_ylabel('$F_{int}$ (Jy)')
ax.set_title(f'src {runcat}')
plt.savefig(f'src{runcat}lc.png')
plt.close()
def make2lc(obsnums,myruncat):
font = {'family' : 'normal',
'weight' : 'bold',
'size' : 22}
matplotlib.rc('font', **font)
fig,axs = plt.subplots(1,2,figsize=(30,15),sharey=True)
fig.suptitle(f'src {myruncat}')
dummyindex = 0
for a in axs:
obs = f'%{obsnums[dummyindex]}%'
query = """SELECT image.taustart_ts, extractedsource.f_int, extractedsource.f_int_err FROM extractedsource JOIN
image ON image.id=extractedsource.image JOIN assocxtrsource ON
assocxtrsource.xtrsrc=extractedsource.id WHERE assocxtrsource.runcat=%s AND image.url LIKE %s ;""",
if args.usefpeak:
query = query.replace('f_int','f_peak')
cur.execute(query,
(myruncat,obs,))
fetchedfluxerr = cur.fetchall()
datlist = [ ((d-triggerdate).total_seconds()/3600./24.,f,fe) for d,f,fe in fetchedfluxerr]
dat = np.array(datlist)
# print(dat)
a.scatter(dat[:,0],dat[:,1])
a.errorbar(dat[:,0],dat[:,1],yerr=np.sqrt(dat[:,2]**2+(dat[:,1]*0.1)**2),fmt='none')
# a.set_xscale('log')
a.grid()
if dummyindex==1:
a.set_xlabel('Days post trigger')
a.set_ylabel('$F_{int}$ (Jy)')
dummyindex +=1
plt.tight_layout()
plt.savefig(f'src{myruncat}lc_twopanel.png')
plt.close()
def make3lc(obsnums,myruncat):
font = {'family' : 'normal',
'weight' : 'bold',
'size' : 22}
matplotlib.rc('font', **font)
fig,axs = plt.subplots(1,3,figsize=(40,15),sharey=True)
fig.suptitle(f'src {myruncat}')
dummyindex = 0
for a in axs:
obs = f'%{obsnums[dummyindex]}%'
query = """SELECT image.taustart_ts, extractedsource.f_int, extractedsource.f_int_err FROM extractedsource JOIN
image ON image.id=extractedsource.image JOIN assocxtrsource ON
assocxtrsource.xtrsrc=extractedsource.id WHERE assocxtrsource.runcat=%s AND image.url LIKE %s ;""",
if args.usefpeak:
query = query.replace('f_int','f_peak')
cur.execute(query,
(myruncat,obs,))
fetchedfluxerr = cur.fetchall()
datlist = [ ((d-triggerdate).total_seconds()/3600./24.,f,fe) for d,f,fe in fetchedfluxerr]
dat = np.array(datlist)
# print(dat)
a.scatter(dat[:,0],dat[:,1])
a.errorbar(dat[:,0],dat[:,1],yerr=np.sqrt(dat[:,2]**2+(dat[:,1]*0.1)**2),fmt='none')
# a.set_xscale('log')
a.grid()
if dummyindex==2:
a.set_xlabel('Days post trigger')
a.set_ylabel('$F_{int}$ (Jy)')
dummyindex +=1
plt.tight_layout()
plt.savefig(f'src{myruncat}lc_threepanel.png')
plt.close()
def make4lc(obsnums,myruncat):
font = {'family' : 'normal',
'weight' : 'bold',
'size' : 22}
matplotlib.rc('font', **font)
title= f'src{myruncat}lc_threepanel.png'
fig,axs = plt.subplots(2,2,figsize=(30,20),sharey=True)
fig.suptitle(f'src {title}')
dummyindex = 0
for ax in axs:
for a in ax:
obs = f'%{obsnums[dummyindex]}%'
# print(obs)
# print(myruncat)
query = """SELECT image.taustart_ts, extractedsource.f_int, extractedsource.f_int_err FROM extractedsource JOIN
image ON image.id=extractedsource.image JOIN assocxtrsource ON
assocxtrsource.xtrsrc=extractedsource.id WHERE assocxtrsource.runcat=%s AND image.url LIKE %s ;""",
if args.usefpeak:
query = query.replace('f_int','f_peak')
cur.execute(query,
(myruncat,obs,))
fetchedfluxerr = cur.fetchall()
# print(fetchedfluxerr)
datlist = [ ((d-triggerdate).total_seconds()/3600./24.,f,fe) for d,f,fe in fetchedfluxerr]
dat = np.array(datlist)
# print(dat)
a.scatter(dat[:,0],dat[:,1])
a.errorbar(dat[:,0],dat[:,1],yerr=np.sqrt(dat[:,2]**2+(dat[:,1]*0.1)**2),fmt='none')
# a.set_xscale('log')
a.grid()
if dummyindex in [2,3]:
a.set_xlabel('Days post trigger')
if dummyindex in [0,2]:
a.set_ylabel('$F_{int}$ (Jy)')
dummyindex +=1
plt.tight_layout()
plt.show()
plt.close()
if __name__=='__main__':
infile = np.loadtxt(args.csvfile,delimiter=',',usecols=(0,1), dtype=[('id','i8'),('eta','f8')])
srcstoplot = infile['id'][infile['eta'].round(decimals=2) >=2]
cur = initdb()
query = """SELECT runningcatalog.wm_ra, runningcatalog.wm_decl, runningcatalog.id FROM runningcatalog WHERE runningcatalog.id in %s;"""
cur.execute(query,(tuple(srcstoplot),))
srcinfo = np.array(cur.fetchall(),dtype=[('ra','f8'),('dec','f8'),('id','i8')])
triggers = np.loadtxt('commensal2triggerdates.csv',skiprows=1,delimiter=',', dtype=[('name','<U32'),('target','<U32'),('trigger','<U128'),('ra','f8'),('dec','f8')])
triggerarr = np.array([(n,tar,datetime.datetime.strptime(trig,"%Y-%m-%dT%H:%M:%S.%f"),tra,tdec) for n,tar,trig,tra,tdec in triggers],dtype=[('name','<U32'),('target','<U32'),('trigger','O'),('ra','f8'),('dec','f8')])
for src in srcinfo:
sc1 = SkyCoord(src['ra'],src['dec'],unit='deg')
sc2 = SkyCoord(triggerarr['ra'],triggerarr['dec'],unit='deg')
seps = sc1.separation(sc2).arcsecond
nobs = len(triggerarr[seps==seps.min()])
triggerdate = np.unique(triggerarr['trigger'][seps==seps.min()])[0]
query = """SELECT image.taustart_ts, extractedsource.f_int, extractedsource.f_int_err FROM extractedsource JOIN
image ON image.id=extractedsource.image JOIN assocxtrsource ON
assocxtrsource.xtrsrc=extractedsource.id WHERE assocxtrsource.runcat=%s ;"""
if args.usefpeak:
query = query.replace('f_int','f_peak')
cur.execute(query, (src['id'],))
fetchedfluxerr = cur.fetchall()
datlist = [ ((d-triggerdate).total_seconds()/3600./24.,f,fe) for d,f,fe in fetchedfluxerr]
dat = np.array(datlist)
if nobs==1:
makelc(dat[:,0],dat[:,1],dat[:,2],src['id'])
else:
try:
if nobs==2:
make2lc(list(triggerarr['name'][seps==seps.min()]),src)
elif nobs==3:
make3lc(list(triggerarr['name'][seps==seps.min()]),src)
elif nobs==4:
make4lc(list(triggerarr['name'][seps==seps.min()]),src)
except Exception as e:
print(e)
makelc(dat[:,0],dat[:,1],dat[:,2],src['id'])