-
Notifications
You must be signed in to change notification settings - Fork 68
/
ellipses.py
executable file
·173 lines (134 loc) · 5.51 KB
/
ellipses.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
import numpy
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse
"""Demonstration of least-squares fitting of ellipses
__author__ = "Ben Hammel, Nick Sullivan-Molina"
__credits__ = ["Ben Hammel", "Nick Sullivan-Molina"]
__maintainer__ = "Ben Hammel"
__email__ = "bdhammel@gmail.com"
__status__ = "Development"
Requirements
------------
Python 2.X or 3.X
numpy
matplotlib
References
----------
(*) Halir, R., Flusser, J.: 'Numerically Stable Direct Least Squares
Fitting of Ellipses'
(**) http://mathworld.wolfram.com/Ellipse.html
(***) White, A. McHale, B. 'Faraday rotation data analysis with least-squares
elliptical fitting'
"""
class LSqEllipse:
def fit(self, data):
"""Lest Squares fitting algorithm
Theory taken from (*)
Solving equation Sa=lCa. with a = |a b c d f g> and a1 = |a b c>
a2 = |d f g>
Args
----
data (list:list:float): list of two lists containing the x and y data of the
ellipse. of the form [[x1, x2, ..., xi],[y1, y2, ..., yi]]
Returns
------
coef (list): list of the coefficients describing an ellipse
[a,b,c,d,f,g] corresponding to ax**2+2bxy+cy**2+2dx+2fy+g
"""
x, y = numpy.asarray(data, dtype=float)
#Quadratic part of design matrix [eqn. 15] from (*)
D1 = numpy.mat(numpy.vstack([x**2, x*y, y**2])).T
#Linear part of design matrix [eqn. 16] from (*)
D2 = numpy.mat(numpy.vstack([x, y, numpy.ones(len(x))])).T
#forming scatter matrix [eqn. 17] from (*)
S1 = D1.T*D1
S2 = D1.T*D2
S3 = D2.T*D2
#Constraint matrix [eqn. 18]
C1 = numpy.mat('0. 0. 2.; 0. -1. 0.; 2. 0. 0.')
#Reduced scatter matrix [eqn. 29]
M=C1.I*(S1-S2*S3.I*S2.T)
#M*|a b c >=l|a b c >. Find eigenvalues and eigenvectors from this equation [eqn. 28]
eval, evec = numpy.linalg.eig(M)
# eigenvector must meet constraint 4ac - b^2 to be valid.
cond = 4*numpy.multiply(evec[0, :], evec[2, :]) - numpy.power(evec[1, :], 2)
a1 = evec[:, numpy.nonzero(cond.A > 0)[1]]
#|d f g> = -S3^(-1)*S2^(T)*|a b c> [eqn. 24]
a2 = -S3.I*S2.T*a1
# eigenvectors |a b c d f g>
self.coef = numpy.vstack([a1, a2])
self._save_parameters()
def _save_parameters(self):
"""finds the important parameters of the fitted ellipse
Theory taken form http://mathworld.wolfram
Args
-----
coef (list): list of the coefficients describing an ellipse
[a,b,c,d,f,g] corresponding to ax**2+2bxy+cy**2+2dx+2fy+g
Returns
_______
center (List): of the form [x0, y0]
width (float): major axis
height (float): minor axis
phi (float): rotation of major axis form the x-axis in radians
"""
#eigenvectors are the coefficients of an ellipse in general form
#a*x^2 + 2*b*x*y + c*y^2 + 2*d*x + 2*f*y + g = 0 [eqn. 15) from (**) or (***)
a = self.coef[0,0]
b = self.coef[1,0]/2.
c = self.coef[2,0]
d = self.coef[3,0]/2.
f = self.coef[4,0]/2.
g = self.coef[5,0]
#finding center of ellipse [eqn.19 and 20] from (**)
x0 = (c*d-b*f)/(b**2.-a*c)
y0 = (a*f-b*d)/(b**2.-a*c)
#Find the semi-axes lengths [eqn. 21 and 22] from (**)
numerator = 2*(a*f*f+c*d*d+g*b*b-2*b*d*f-a*c*g)
denominator1 = (b*b-a*c)*( (c-a)*numpy.sqrt(1+4*b*b/((a-c)*(a-c)))-(c+a))
denominator2 = (b*b-a*c)*( (a-c)*numpy.sqrt(1+4*b*b/((a-c)*(a-c)))-(c+a))
width = numpy.sqrt(numerator/denominator1)
height = numpy.sqrt(numerator/denominator2)
# angle of counterclockwise rotation of major-axis of ellipse to x-axis [eqn. 23] from (**)
# or [eqn. 26] from (***).
phi = .5*numpy.arctan((2.*b)/(a-c))
self._center = [x0, y0]
self._width = width
self._height = height
self._phi = phi
@property
def center(self):
return self._center
@property
def width(self):
return self._width
@property
def height(self):
return self._height
@property
def phi(self):
"""angle of counterclockwise rotation of major-axis of ellipse to x-axis
[eqn. 23] from (**)
"""
return self._phi
def parameters(self):
return self._center, self._width, self._height, self._phi
def make_test_ellipse(center=[1,1], width=1, height=.6, phi=3.14/5):
"""Generate Elliptical data with noise
Args
----
center (list:float): (<x_location>, <y_location>)
width (float): semimajor axis. Horizontal dimension of the ellipse (**)
height (float): semiminor axis. Vertical dimension of the ellipse (**)
phi (float:radians): tilt of the ellipse, the angle the semimajor axis
makes with the x-axis
Returns
-------
data (list:list:float): list of two lists containing the x and y data of the
ellipse. of the form [[x1, x2, ..., xi],[y1, y2, ..., yi]]
"""
t = numpy.linspace(0, 2*numpy.pi, 1000)
x_noise, y_noise = numpy.random.rand(2, len(t))
ellipse_x = center[0] + width*numpy.cos(t)*numpy.cos(phi)-height*numpy.sin(t)*numpy.sin(phi) + x_noise/2.
ellipse_y = center[1] + width*numpy.cos(t)*numpy.sin(phi)+height*numpy.sin(t)*numpy.cos(phi) + y_noise/2.
return [ellipse_x, ellipse_y]