-
Notifications
You must be signed in to change notification settings - Fork 24
/
mog.py
272 lines (228 loc) · 9.27 KB
/
mog.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
from __future__ import print_function
from tractor.galaxy import HoggGalaxy
from tractor.utils import MogParams, ParamList
from tractor.mixture_profiles import MixtureOfGaussians
import numpy as np
#################### First way -- expose the mixture-of-Gaussians directly,
#################### allowing them to be fit in general.
class MogGalaxy(HoggGalaxy):
'''
A galaxy model that directly exposes the Mixture of Gaussians components.
'''
@staticmethod
def getNamedParams():
return dict(pos=0, brightness=1, mog=2,
# Alias '.shape' to '.mog' to use Galaxy derivatives code
shape=2)
def getProfile(self):
return self.mog.mog
def getRadius(self):
return 5. * np.sqrt(np.max(self.mog.mog.var))*3600.
def _getAffineProfile(self, img, px, py):
''' Returns a MixtureOfGaussians profile that has been
affine-transformed into the pixel space of the image.
'''
cd = img.getWcs().cdAtPixel(px, py)
Tinv = np.linalg.inv(cd)
galmix = self.getProfile()
amix = galmix.apply_affine(np.array([px,py]), Tinv.T)
amix.symmetrize()
return amix
class MyMogParams(MogParams):
def getStepSizes(self):
'''Set step sizes when taking derivatives of the parameters of the mixture of Gaussians.'''
K = self.mog.K
vv = (self.mog.var[:,0,0] + self.mog.var[:,1,1]) / 2.
ss = [0.01]*K + [0.01]*K*2 + list((0.01 * vv).repeat(3))
return list(self._getLiquidArray(ss))
#################### (end of first way)
#################### Second way -- fit the radial profile as MoG, but keep
#################### the elliptical 2-d shape
class EllipticalMogGalaxy(HoggGalaxy):
'''
A galaxy model that is still based on an elliptical radial profile
but allows the radial profile to be fit as a Mixture of Gaussians.
'''
@staticmethod
def getNamedParams():
return dict(pos=0, brightness=1, shape=2, profile=3)
nre = 5.
def getName(self):
return 'EllipticalMogGalaxy'
def getProfile(self):
return self.profile.getMog()
def getParamDerivatives(self, img, modelMask=None):
derivs = super(EllipticalMogGalaxy, self).getParamDerivatives(img, modelMask=modelMask)
pos0 = self.getPosition()
(px0,py0) = img.getWcs().positionToPixel(pos0, self)
counts = img.getPhotoCal().brightnessToCounts(self.brightness)
patch0 = self.getUnitFluxModelPatch(img, px0, py0,
modelMask=modelMask)
if patch0 is None:
return [None] * self.numberOfParams()
# derivatives wrt MoG componets... this is boilerplate-ish
psteps = self.profile.getStepSizes()
if not self.isParamFrozen('profile'):
pnames = self.profile.getParamNames()
oldvals = self.profile.getParams()
if counts == 0:
derivs.extend([None] * len(oldvals))
psteps = []
for i,pstep in enumerate(psteps):
oldval = self.profile.setParam(i, oldvals[i]+pstep)
patchx = self.getUnitFluxModelPatch(
img, px0, py0, modelMask=modelMask)
self.profile.setParam(i, oldval)
if patchx is None:
continue
dx = (patchx - patch0) * (counts / pstep)
dx.setName('d(%s)/d(%s)' % (self.dname, pnames[i]))
derivs.append(dx)
return derivs
class MogProfile(ParamList):
def __init__(self, *args):
K = len(args) / 2
## HACK -- internally, keep stddevs rather than variances (to avoid negatives?)
# OR work in log-variances?
args = np.array(args)
#args[K:] = np.sqrt(args[K:])
args[K:] = np.log10(args[K:])
super(MogProfile, self).__init__(*args)
self.K = self.numberOfParams() / 2
self._set_param_names(self.K)
def getMog(self):
p = self.getAllParams()
K = len(p) / 2
assert(K == self.K)
amps = np.array(p[:K])
# ??
amps /= np.sum(amps)
# log-variance
var = 10.**np.array(p[K:])
if hasattr(self, 'mog'):
assert(self.mog.K == K)
self.mog.amp[:] = amps
self.mog.var[:,0,0] = self.mog.var[:,1,1] = var
else:
vv = np.zeros((K,2,2))
vv[:,0,0] = vv[:,1,1] = var
self.mog = MixtureOfGaussians(amps, np.zeros((K,2)), vv)
return self.mog
def _set_param_names(self, K):
names = {}
for k in range(K):
names['amp%i' % k] = k
#names['var%i' % k] = k+K
names['logvar%i' % k] = k+K
self.addNamedParams(**names)
def getStepSizes(self):
'''Set step sizes when taking derivatives of the parameters of the mixture of Gaussians.'''
return [0.01]*self.K*2
#################### (end of second way)
if __name__ == '__main__':
h,w = 100,100
from tractor.galaxy import ExpGalaxy
from tractor import Image, GaussianMixturePSF, LinearPhotoCal
from tractor import PixPos, Flux, EllipseE, Tractor, ModelMask
import pylab as plt
# Create a Tractor Image that works in pixel space (WCS not specified).
tim = Image(data=np.zeros((h,w)), inverr=np.ones((h,w)),
psf=GaussianMixturePSF(1., 0., 0., 3., 3., 0.),
photocal=LinearPhotoCal(1.))
# Create a plain Exp galaxy to generate a postage stamp that we'll try to fit with
# the MogGalaxy model.
gal = ExpGalaxy(PixPos(w//2, h//2), Flux(1000.),
EllipseE(10., 0.5, 0.3))
# Get the model
tractor = Tractor([tim], [gal])
mod = tractor.getModelImage(0)
#mog = gal._getAffineProfile(tim, w//2, h//2)
#print('Exp galaxy profile:', str(mog))
# Plot the model
plt.clf()
plt.imshow(mod, interpolation='nearest', origin='lower')
plt.savefig('mod.png')
# Set the tractor Image to the Exp model postage stamp -- this is what we'll try to fit.
tim.data = mod
# Initialize the MoG components
amp = np.array([0.4, 0.3, 0.3])
mean = np.zeros((3,2))
var = np.array([
[0.01,0., 0., 0.01],
[0.1, 0., 0., 0.1 ],
[1., 0., 0., 1.0 ],
])
var *= 64.
var = var.reshape((-1,2,2))
# ~ arcsec -> degrees
var /= 3600.**2
if False:
# Create the MoG galaxy object
moggal = MogGalaxy(gal.pos.copy(), gal.brightness.copy(),
MyMogParams(amp, mean, var))
# Freeze the MoG means -- The overall mean is degenerate with
# galaxy position.
K = moggal.mog.mog.K
for i in range(K):
moggal.mog.freezeParam('meanx%i' % i)
moggal.mog.freezeParam('meany%i' % i)
# Freeze the galaxy brightness -- otherwise it's degenerate with MoG amplitudes.
moggal.freezeParam('brightness')
else:
# The "MogProfile" call here takes a list of amplitudes (they
# get normalized), followed by a list of variances.
moggal = EllipticalMogGalaxy(gal.pos.copy(), gal.brightness.copy(),
EllipseE(1., 0., 0.),
MogProfile(1.0, 1.0, 1.0,
1.0, 4.0, 9.0))
# Create a Tractor object that will fit the "moggal" given its appearance in "tim".
tractor = Tractor([tim], [moggal])
# Initial model:
mod = tractor.getModelImage(0)
#mog = moggal._getAffineProfile(tim, w//2, h//2)
#print('MoG galaxy profile:', str(mog))
# Plot initial model.
plt.clf()
plt.imshow(mod, interpolation='nearest', origin='lower')
plt.savefig('mod2.png')
# Don't fit any of the image calibration params
tractor.freezeParam('images')
# Plot the parameter derivatives
derivs = moggal.getParamDerivatives(tim, modelMask=ModelMask(0,0,w,h))
for i,p in enumerate(moggal.getParamNames()):
print('Param', p, 'derivative:', derivs[i])
if derivs[i] is None:
continue
plt.clf()
plt.imshow(derivs[i].patch, interpolation='nearest', origin='lower')
plt.title('MoG galaxy derivative for parameter %s' % p)
plt.savefig('deriv-%02i.png' % i)
# import sys
# import logging
# lvl = logging.DEBUG
# logging.basicConfig(level=lvl, format='%(message)s', stream=sys.stdout)
# Optimize the model.
for step in range(50):
print('Tractor params:')
tractor.printThawedParams()
dlnp,X,alpha = tractor.optimize(damp=1.)
print('dlnp', dlnp)
print('galaxy:', moggal)
#print('Mog', moggal.mog.getParams())
if dlnp == 0:
break
# Plot the model as we're optimizing...
mod = tractor.getModelImage(0)
chi = (tim.getImage() - mod) * tim.getInvError()
plt.clf()
plt.subplot(1,2,1)
plt.imshow(mod, interpolation='nearest', origin='lower')
plt.title('Model')
plt.subplot(1,2,2)
mx = np.abs(chi).max()
plt.imshow(chi, interpolation='nearest', origin='lower',
vmin=-mx, vmax=mx)
plt.colorbar()
plt.title('Chi residuals')
plt.suptitle('MoG model after optimization step %i' % step)
plt.savefig('mod-o%02i.png' % step)