-
Notifications
You must be signed in to change notification settings - Fork 0
/
dilltools.py
226 lines (198 loc) · 6.97 KB
/
dilltools.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
import numpy as np
#import pyfits as pf
import os
import scipy.signal
import scipy.ndimage as nd
#hello from fermilab2
# Returns xvals, medians, mads
def bindata(x, y, bins, returnn=False):
medians = np.zeros(len(bins) - 1)
mads = np.zeros(len(bins) - 1)
nums = np.zeros(len(bins) - 1)
for i in np.arange(len(bins) - 1):
bs = bins[i]
bf = bins[i + 1]
ww = [(x > bs) & (x < bf)]
yhere = y[ww]
yhere = yhere[np.isfinite(yhere) & ~np.isnan(yhere)]
ss = [abs(yhere) < 3. * np.std(yhere)]
try:
nums[i] = len(yhere[ss])
medians[i] = np.median(yhere[ss])
mads[i] = 1.48 * np.median(abs(yhere[ss] - medians[i])) * 1 / np.sqrt(len(yhere[ss]))
except IndexError:
print('excepted')
nums[i] = 0.
medians[i] = np.nan
mads[i] = np.nan
xvals = (bins[1:] + bins[:-1]) / 2.
if returnn:
return xvals, medians, mads, nums
return xvals, medians, mads
# Takes in Filename, reads file columnwise, and returns dictionary such that:
# import rdcol
# a = rdcol.read('filename',headline,datastartline)
# a["Column_Name"] -> returns the list for that column
#
# headline and datastartline are always > 0
#
# By Dillon Brout
# dbrout@physics.upenn.edu
def read(filename, headline, startline, delim=None):
linenum = 0
go = 0
column_list = []
return_cols = {}
inf = open(filename)
for line in inf:
line = line.replace('#', '')
line = line.strip()
cols = line.split(delim)
cols[:] = (value for value in cols if value != '')
if linenum == headline - 1:
for col in cols:
return_cols[col.strip()] = []
column_list.append(col.strip())
go += 1
if linenum >= startline - 1:
index = 0
for col in cols:
try:
return_cols[column_list[index]].append(float(col.strip()))
except:
return_cols[column_list[index]].append(col.strip())
index += 1
linenum += 1
inf.close()
return return_cols
def save_fits_image(image,filename):
hdu = pf.PrimaryHDU(image)
if os.path.exists(filename):
os.remove(filename)
hdu.writeto(filename)
return
def psfphotometry(im, psf, sky, weight, gal, guess_scale):
chisqvec = []
fluxvec = []
galconv = scipy.signal.fftconvolve(gal, psf, mode='same')
radius = 12
substamp = galconv.shape[0]
# Make a mask with radius
fitrad = np.zeros([substamp, substamp])
for x in np.arange(substamp):
for y in np.arange(substamp):
if np.sqrt((substamp / 2. - x) ** 2 + (substamp / 2. - y) ** 2) < radius:
fitrad[int(x), int(y)] = 1.
if guess_scale is None:
for i in np.arange(-10000, 200000, 5):
sim = galconv + sky + i * psf
chisqvec.append(np.sum((im - sim) ** 2 * weight * fitrad))
fluxvec.append(i)
else:
for i in np.arange(guess_scale - 2000, guess_scale + 2000, 1):
sim = galconv + sky + i * psf
chisqvec.append(np.sum((im - sim) ** 2 * weight * fitrad))
fluxvec.append(i)
ii = fitrad.ravel()
i = ii[ii != 0]
ndof = len(i) + 1
fluxvec = np.array(fluxvec)
chisqvec = np.array(chisqvec)
hh = chisqvec * 0 + min(chisqvec)
mchisq = min(chisqvec)
idx = np.isclose(chisqvec, hh, atol=1.)
sim = galconv + sky + fluxvec[chisqvec == min(chisqvec)] * psf
sum_data_minus_sim = np.sum(im - sim)
return fluxvec[chisqvec == min(chisqvec)], fluxvec[chisqvec == min(chisqvec)] - fluxvec[idx][
0], mchisq / ndof, sum_data_minus_sim
# Takes in Filename, reads file columnwise, and returns dictionary such that:
# import rdcol
# a = rdcol.read('filename',headline,datastartline)
# a["Column_Name"] -> returns the list for that column
#
# headline and datastartline are always > 0
#
# By Dillon Brout
# dbrout@physics.upenn.edu
def readcol(filename,headline=1,startline=2,delim=' '):
linenum = 0
go = 0
column_list = []
return_cols = {}
inf = open(filename)
for line in inf:
line = line.replace('#', '')
line = line.strip()
cols = line.split(delim)
cols[:] = (value for value in cols if value != '')
if linenum == headline - 1:
for col in cols:
return_cols[col.strip()] = []
column_list.append(col.strip())
go += 1
if linenum >= startline - 1:
index = 0
for col in cols:
try:
return_cols[column_list[index]].append(float(col.strip()))
except:
return_cols[column_list[index]].append(col.strip())
index += 1
linenum += 1
inf.close()
for k in return_cols.keys():
return_cols[k] = np.array(return_cols[k])
return return_cols
def pixelate(matrix, pixelation_factor):
zmatrix = nd.interpolation.zoom(matrix, 1. / float(pixelation_factor))
return zmatrix
class tmpwriter():
# tempdir = location to write files
# tmp_index = index for parallel computation to avoid over-writing files
def __init__(self, tempdir='./tmp/',tmp_subscript=0,usedccp=False):
self.tmpdir = tempdir
self.tmp_index = str(tmp_subscript)
self.usedccp = usedccp
def writefile(self,text,filename):
tempfile = os.path.join(self.tmpdir, 'tmp_' + self.tmp_index + '.txt')
if os.path.isfile(tempfile):
os.remove(tempfile)
if os.path.isfile(filename):
os.remove(filename)
a = open(tempfile,'w')
a.write(text)
a.close()
if self.usedccp:
os.system('dccp ' + tempfile + ' ' + filename)
else:
os.system('mv ' + tempfile + ' ' + filename)
print('saved', filename)
def appendfile(self,text,filename):
tempfile = os.path.join(self.tmpdir, 'tmp_' + self.tmp_index + '.txt')
if os.path.isfile(tempfile):
os.remove(tempfile)
if self.usedccp:
os.system('dccp ' + filename + ' ' + tempfile)
else:
os.system('mv ' + filename + ' ' + tempfile)
a = open(tempfile,'a')
a.write(text)
a.close()
if os.path.isfile(filename):
os.remove(filename)
if self.usedccp:
os.system('dccp ' + tempfile + ' ' + filename)
else:
os.system('mv ' + tempfile + ' ' + filename)
def savez(self,filename,**kwargs):
tempfile = os.path.join(self.tmpdir, 'tmp_' + self.tmp_index + '.npz')
if os.path.isfile(tempfile):
os.remove(tempfile)
if os.path.isfile(filename):
os.remove(filename)
np.savez(tempfile,**kwargs)
if self.usedccp:
os.system('dccp ' + tempfile + ' ' + filename)
else:
os.system('mv ' + tempfile + ' ' + filename)
print('saved',filename)