-
Notifications
You must be signed in to change notification settings - Fork 0
/
fit_ellipse_stack_conic.py
360 lines (251 loc) · 7.85 KB
/
fit_ellipse_stack_conic.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
#!/usr/bin/env python2.5
#
# Written (W) 2011-2013 Christian Widmer
# Copyright (C) 2011-2013 Max-Planck-Society, TU-Berlin, MSKCC
"""
@author: Christian Widmer
@summary: Procedures for fitting stacks of ellipses using
conic parameterization
"""
#solvers.options['feastol'] = 1e-1
from collections import defaultdict
import numpy
import cvxmod
import fit_ellipse_conic
from util import Ellipse, conic_to_ellipse
def fit_ellipse_stack_decoupled(dx, dy, dz, di):
"""
fit ellipse stack by independently fitting
each layer
"""
# sanity check
assert len(dx) == len(dy) == len(dz) == len(di)
# unique zs
dat = defaultdict(list)
# resort data by layer
for idx in range(len(dx)):
dat[dz[idx]].append( [dx[idx], dy[idx]] )
# init ret
ellipse_stack = {}
# iterate over layers
for z in dat.keys():
x_layer = numpy.array(dat[z])[:, 0]
y_layer = numpy.array(dat[z])[:, 1]
# fit ellipse
try:
[c, a, b, alpha] = fit_ellipse_conic.fit_ellipse_squared(x_layer, y_layer)
#[c, a, b, alpha] = fit_ellipse_conic.fit_ellipse_linear(x_layer, y_layer)
#[c, a, b, alpha] = fit_ellipse_conic.fit_ellipse_eps_insensitive(x_layer, y_layer)
# reconstruct ellipse stack
ellipse_stack[z] = Ellipse(c[0], c[1], z, a, b, alpha)
except Exception, detail:
print detail
return ellipse_stack
def fit_ellipse_stack_squared(dx, dy, dz, di):
"""
fit ellipoid using squared loss
idea to learn all stacks together including smoothness
"""
# sanity check
assert len(dx) == len(dy)
assert len(dx) == len(dz)
assert len(dx) == len(di)
# unique zs
dat = defaultdict(list)
# resort data
for idx in range(len(dx)):
dat[dz[idx]].append( [dx[idx], dy[idx], di[idx]] )
# init ret
ellipse_stack = []
for idx in range(max(dz)):
ellipse_stack.append(Ellipse(0, 0, idx, 1, 1, 0))
total_N = len(dx)
M = len(dat.keys())
D = 5
X_matrix = []
thetas = []
for z in dat.keys():
x = numpy.array(dat[z])[:,0]
y = numpy.array(dat[z])[:,1]
# intensities
i = numpy.array(dat[z])[:,2]
# log intensities
i = numpy.log(i)
# create matrix
ity = numpy.diag(i)
# dimensionality
N = len(x)
d = numpy.zeros((N, D))
d[:,0] = x*x
d[:,1] = y*y
#d[:,2] = x*y
d[:,2] = x
d[:,3] = y
d[:,4] = numpy.ones(N)
#d[:,0] = x*x
#d[:,1] = y*y
#d[:,2] = x*y
#d[:,3] = x
#d[:,4] = y
#d[:,5] = numpy.ones(N)
# consider intensities
old_shape = d.shape
d = numpy.dot(ity, d)
assert d.shape == old_shape
print d.shape
d = cvxmod.matrix(d)
#### parameters
# da
X = cvxmod.param("X" + str(z), N, D)
X.value = d
X_matrix.append(X)
#### varibales
# parameter vector
theta = cvxmod.optvar("theta" + str(z), D)
thetas.append(theta)
# contruct objective
objective = 0
for (i,X) in enumerate(X_matrix):
#TODO try abs loss here!
objective += cvxmod.sum(cvxmod.atoms.square(X*thetas[i]))
#objective += cvxmod.sum(cvxmod.atoms.abs(X*thetas[i]))
# add smoothness regularization
reg_const = float(total_N) / float(M-1)
for i in xrange(M-1):
objective += reg_const * cvxmod.sum(cvxmod.atoms.square(thetas[i] - thetas[i+1]))
print objective
# create problem
p = cvxmod.problem(cvxmod.minimize(objective))
# add constraints
for i in xrange(M):
p.constr.append(thetas[i][0] + thetas[i][1] == 1)
###### set values
p.solve()
# wrap up result
ellipse_stack = {}
active_layers = dat.keys()
assert len(active_layers) == M
for i in xrange(M):
theta_ = numpy.array(cvxmod.value(thetas[i]))
z_layer = active_layers[i]
ellipse_stack[z_layer] = conic_to_ellipse(theta_)
ellipse_stack[z_layer].cz = z_layer
return ellipse_stack
def fit_ellipse_stack_abs(dx, dy, dz, di):
"""
fit ellipoid using squared loss
idea to learn all stacks together including smoothness
"""
# sanity check
assert len(dx) == len(dy)
assert len(dx) == len(dz)
assert len(dx) == len(di)
# unique zs
dat = defaultdict(list)
# resort data
for idx in range(len(dx)):
dat[dz[idx]].append( [dx[idx], dy[idx], di[idx]] )
# init ret
ellipse_stack = []
for idx in range(max(dz)):
ellipse_stack.append(Ellipse(0, 0, idx, 1, 1, 0))
total_N = len(dx)
M = len(dat.keys())
D = 5
X_matrix = []
thetas = []
slacks = []
eps_slacks = []
mean_di = float(numpy.mean(di))
for z in dat.keys():
x = numpy.array(dat[z])[:,0]
y = numpy.array(dat[z])[:,1]
# intensities
i = numpy.array(dat[z])[:,2]
# log intensities
i = numpy.log(i)
# create matrix
ity = numpy.diag(i)# / mean_di
# dimensionality
N = len(x)
d = numpy.zeros((N, D))
d[:,0] = x*x
d[:,1] = y*y
#d[:,2] = x*y
d[:,2] = x
d[:,3] = y
d[:,4] = numpy.ones(N)
#d[:,0] = x*x
#d[:,1] = y*y
#d[:,2] = x*y
#d[:,3] = x
#d[:,4] = y
#d[:,5] = numpy.ones(N)
print "old", d
# consider intensities
old_shape = d.shape
d = numpy.dot(ity, d)
print "new", d
assert d.shape == old_shape
print d.shape
d = cvxmod.matrix(d)
#### parameters
# da
X = cvxmod.param("X" + str(z), N, D)
X.value = d
X_matrix.append(X)
#### varibales
# parameter vector
theta = cvxmod.optvar("theta" + str(z), D)
thetas.append(theta)
# construct obj
objective = 0
# loss term
for i in xrange(M):
objective += cvxmod.atoms.norm1(X_matrix[i] * thetas[i])
# add smoothness regularization
reg_const = 5 * float(total_N) / float(M-1)
for i in xrange(M-1):
objective += reg_const * cvxmod.norm1(thetas[i] - thetas[i+1])
# create problem
prob = cvxmod.problem(cvxmod.minimize(objective))
# add constraints
"""
for (i,X) in enumerate(X_matrix):
p.constr.append(X*thetas[i] <= slacks[i])
p.constr.append(-X*thetas[i] <= slacks[i])
#eps = 0.5
#p.constr.append(slacks[i] - eps <= eps_slacks[i])
#p.constr.append(0 <= eps_slacks[i])
"""
# add non-degeneracy constraints
for i in xrange(1, M-1):
prob.constr.append(thetas[i][0] + thetas[i][1] == 1.0) # A + C = 1
# pinch ends
prob.constr.append(cvxmod.sum(thetas[0]) >= -0.01)
prob.constr.append(cvxmod.sum(thetas[-1]) >= -0.01)
print prob
###### set values
from cvxopt import solvers
solvers.options['reltol'] = 1e-1
solvers.options['abstol'] = 1e-1
print solvers.options
prob.solve()
# wrap up result
ellipse_stack = {}
active_layers = dat.keys()
assert len(active_layers) == M
# reconstruct original parameterization
for i in xrange(M):
theta_ = numpy.array(cvxmod.value(thetas[i]))
z_layer = active_layers[i]
ellipse_stack[z_layer] = conic_to_ellipse(theta_)
ellipse_stack[z_layer].cz = z_layer
return ellipse_stack
if __name__ == "__main__":
import data_processing
dx, dy, dz, di, v = data_processing.artificial_data()
#fit = fit_ellipse_stack_scipy(dx, dy, dz, di)
#fit1 = fit_ellipse_stack(dx, dy, dz, di)
#fit1 = fit_ellipse_stack_abs(dx, dy, dz, di)
fit1 = fit_ellipse_stack_squared(dx, dy, dz, di)