blob: 2fb094ee6687e375cd80feba7b31d4beafc21347 [file] [log] [blame]
Jeff Brown8a90e6e2012-05-11 12:24:35 -07001/*
2 * Copyright (C) 2012 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "VelocityTracker"
18//#define LOG_NDEBUG 0
19
20// Log debug messages about velocity tracking.
21#define DEBUG_VELOCITY 0
22
23// Log debug messages about least squares fitting.
24#define DEBUG_LEAST_SQUARES 0
25
26#include <math.h>
27#include <limits.h>
28
29#include <androidfw/VelocityTracker.h>
30#include <utils/BitSet.h>
31#include <utils/String8.h>
32#include <utils/Timers.h>
33
34namespace android {
35
36// --- VelocityTracker ---
37
38const uint32_t VelocityTracker::DEFAULT_DEGREE;
39const nsecs_t VelocityTracker::DEFAULT_HORIZON;
40const uint32_t VelocityTracker::HISTORY_SIZE;
41
42static inline float vectorDot(const float* a, const float* b, uint32_t m) {
43 float r = 0;
44 while (m--) {
45 r += *(a++) * *(b++);
46 }
47 return r;
48}
49
50static inline float vectorNorm(const float* a, uint32_t m) {
51 float r = 0;
52 while (m--) {
53 float t = *(a++);
54 r += t * t;
55 }
56 return sqrtf(r);
57}
58
59#if DEBUG_LEAST_SQUARES || DEBUG_VELOCITY
60static String8 vectorToString(const float* a, uint32_t m) {
61 String8 str;
62 str.append("[");
63 while (m--) {
64 str.appendFormat(" %f", *(a++));
65 if (m) {
66 str.append(",");
67 }
68 }
69 str.append(" ]");
70 return str;
71}
72
73static String8 matrixToString(const float* a, uint32_t m, uint32_t n, bool rowMajor) {
74 String8 str;
75 str.append("[");
76 for (size_t i = 0; i < m; i++) {
77 if (i) {
78 str.append(",");
79 }
80 str.append(" [");
81 for (size_t j = 0; j < n; j++) {
82 if (j) {
83 str.append(",");
84 }
85 str.appendFormat(" %f", a[rowMajor ? i * n + j : j * m + i]);
86 }
87 str.append(" ]");
88 }
89 str.append(" ]");
90 return str;
91}
92#endif
93
94VelocityTracker::VelocityTracker() {
95 clear();
96}
97
98void VelocityTracker::clear() {
99 mIndex = 0;
100 mMovements[0].idBits.clear();
101 mActivePointerId = -1;
102}
103
104void VelocityTracker::clearPointers(BitSet32 idBits) {
105 BitSet32 remainingIdBits(mMovements[mIndex].idBits.value & ~idBits.value);
106 mMovements[mIndex].idBits = remainingIdBits;
107
108 if (mActivePointerId >= 0 && idBits.hasBit(mActivePointerId)) {
109 mActivePointerId = !remainingIdBits.isEmpty() ? remainingIdBits.firstMarkedBit() : -1;
110 }
111}
112
113void VelocityTracker::addMovement(nsecs_t eventTime, BitSet32 idBits, const Position* positions) {
114 if (++mIndex == HISTORY_SIZE) {
115 mIndex = 0;
116 }
117
118 while (idBits.count() > MAX_POINTERS) {
119 idBits.clearLastMarkedBit();
120 }
121
122 Movement& movement = mMovements[mIndex];
123 movement.eventTime = eventTime;
124 movement.idBits = idBits;
125 uint32_t count = idBits.count();
126 for (uint32_t i = 0; i < count; i++) {
127 movement.positions[i] = positions[i];
128 }
129
130 if (mActivePointerId < 0 || !idBits.hasBit(mActivePointerId)) {
131 mActivePointerId = count != 0 ? idBits.firstMarkedBit() : -1;
132 }
133
134#if DEBUG_VELOCITY
135 ALOGD("VelocityTracker: addMovement eventTime=%lld, idBits=0x%08x, activePointerId=%d",
136 eventTime, idBits.value, mActivePointerId);
137 for (BitSet32 iterBits(idBits); !iterBits.isEmpty(); ) {
138 uint32_t id = iterBits.firstMarkedBit();
139 uint32_t index = idBits.getIndexOfBit(id);
140 iterBits.clearBit(id);
141 Estimator estimator;
142 getEstimator(id, DEFAULT_DEGREE, DEFAULT_HORIZON, &estimator);
143 ALOGD(" %d: position (%0.3f, %0.3f), "
144 "estimator (degree=%d, xCoeff=%s, yCoeff=%s, confidence=%f)",
145 id, positions[index].x, positions[index].y,
146 int(estimator.degree),
147 vectorToString(estimator.xCoeff, estimator.degree).string(),
148 vectorToString(estimator.yCoeff, estimator.degree).string(),
149 estimator.confidence);
150 }
151#endif
152}
153
154void VelocityTracker::addMovement(const MotionEvent* event) {
155 int32_t actionMasked = event->getActionMasked();
156
157 switch (actionMasked) {
158 case AMOTION_EVENT_ACTION_DOWN:
159 case AMOTION_EVENT_ACTION_HOVER_ENTER:
160 // Clear all pointers on down before adding the new movement.
161 clear();
162 break;
163 case AMOTION_EVENT_ACTION_POINTER_DOWN: {
164 // Start a new movement trace for a pointer that just went down.
165 // We do this on down instead of on up because the client may want to query the
166 // final velocity for a pointer that just went up.
167 BitSet32 downIdBits;
168 downIdBits.markBit(event->getPointerId(event->getActionIndex()));
169 clearPointers(downIdBits);
170 break;
171 }
172 case AMOTION_EVENT_ACTION_MOVE:
173 case AMOTION_EVENT_ACTION_HOVER_MOVE:
174 break;
175 default:
176 // Ignore all other actions because they do not convey any new information about
177 // pointer movement. We also want to preserve the last known velocity of the pointers.
178 // Note that ACTION_UP and ACTION_POINTER_UP always report the last known position
179 // of the pointers that went up. ACTION_POINTER_UP does include the new position of
180 // pointers that remained down but we will also receive an ACTION_MOVE with this
181 // information if any of them actually moved. Since we don't know how many pointers
182 // will be going up at once it makes sense to just wait for the following ACTION_MOVE
183 // before adding the movement.
184 return;
185 }
186
187 size_t pointerCount = event->getPointerCount();
188 if (pointerCount > MAX_POINTERS) {
189 pointerCount = MAX_POINTERS;
190 }
191
192 BitSet32 idBits;
193 for (size_t i = 0; i < pointerCount; i++) {
194 idBits.markBit(event->getPointerId(i));
195 }
196
197 nsecs_t eventTime;
198 Position positions[pointerCount];
199
200 size_t historySize = event->getHistorySize();
201 for (size_t h = 0; h < historySize; h++) {
202 eventTime = event->getHistoricalEventTime(h);
203 for (size_t i = 0; i < pointerCount; i++) {
204 positions[i].x = event->getHistoricalX(i, h);
205 positions[i].y = event->getHistoricalY(i, h);
206 }
207 addMovement(eventTime, idBits, positions);
208 }
209
210 eventTime = event->getEventTime();
211 for (size_t i = 0; i < pointerCount; i++) {
212 positions[i].x = event->getX(i);
213 positions[i].y = event->getY(i);
214 }
215 addMovement(eventTime, idBits, positions);
216}
217
218/**
219 * Solves a linear least squares problem to obtain a N degree polynomial that fits
220 * the specified input data as nearly as possible.
221 *
222 * Returns true if a solution is found, false otherwise.
223 *
224 * The input consists of two vectors of data points X and Y with indices 0..m-1.
225 * The output is a vector B with indices 0..n-1 that describes a polynomial
226 * that fits the data, such the sum of abs(Y[i] - (B[0] + B[1] X[i] + B[2] X[i]^2 ... B[n] X[i]^n))
227 * for all i between 0 and m-1 is minimized.
228 *
229 * That is to say, the function that generated the input data can be approximated
230 * by y(x) ~= B[0] + B[1] x + B[2] x^2 + ... + B[n] x^n.
231 *
232 * The coefficient of determination (R^2) is also returned to describe the goodness
233 * of fit of the model for the given data. It is a value between 0 and 1, where 1
234 * indicates perfect correspondence.
235 *
236 * This function first expands the X vector to a m by n matrix A such that
237 * A[i][0] = 1, A[i][1] = X[i], A[i][2] = X[i]^2, ..., A[i][n] = X[i]^n.
238 *
239 * Then it calculates the QR decomposition of A yielding an m by m orthonormal matrix Q
240 * and an m by n upper triangular matrix R. Because R is upper triangular (lower
241 * part is all zeroes), we can simplify the decomposition into an m by n matrix
242 * Q1 and a n by n matrix R1 such that A = Q1 R1.
243 *
244 * Finally we solve the system of linear equations given by R1 B = (Qtranspose Y)
245 * to find B.
246 *
247 * For efficiency, we lay out A and Q column-wise in memory because we frequently
248 * operate on the column vectors. Conversely, we lay out R row-wise.
249 *
250 * http://en.wikipedia.org/wiki/Numerical_methods_for_linear_least_squares
251 * http://en.wikipedia.org/wiki/Gram-Schmidt
252 */
253static bool solveLeastSquares(const float* x, const float* y, uint32_t m, uint32_t n,
254 float* outB, float* outDet) {
255#if DEBUG_LEAST_SQUARES
256 ALOGD("solveLeastSquares: m=%d, n=%d, x=%s, y=%s", int(m), int(n),
257 vectorToString(x, m).string(), vectorToString(y, m).string());
258#endif
259
260 // Expand the X vector to a matrix A.
261 float a[n][m]; // column-major order
262 for (uint32_t h = 0; h < m; h++) {
263 a[0][h] = 1;
264 for (uint32_t i = 1; i < n; i++) {
265 a[i][h] = a[i - 1][h] * x[h];
266 }
267 }
268#if DEBUG_LEAST_SQUARES
269 ALOGD(" - a=%s", matrixToString(&a[0][0], m, n, false /*rowMajor*/).string());
270#endif
271
272 // Apply the Gram-Schmidt process to A to obtain its QR decomposition.
273 float q[n][m]; // orthonormal basis, column-major order
274 float r[n][n]; // upper triangular matrix, row-major order
275 for (uint32_t j = 0; j < n; j++) {
276 for (uint32_t h = 0; h < m; h++) {
277 q[j][h] = a[j][h];
278 }
279 for (uint32_t i = 0; i < j; i++) {
280 float dot = vectorDot(&q[j][0], &q[i][0], m);
281 for (uint32_t h = 0; h < m; h++) {
282 q[j][h] -= dot * q[i][h];
283 }
284 }
285
286 float norm = vectorNorm(&q[j][0], m);
287 if (norm < 0.000001f) {
288 // vectors are linearly dependent or zero so no solution
289#if DEBUG_LEAST_SQUARES
290 ALOGD(" - no solution, norm=%f", norm);
291#endif
292 return false;
293 }
294
295 float invNorm = 1.0f / norm;
296 for (uint32_t h = 0; h < m; h++) {
297 q[j][h] *= invNorm;
298 }
299 for (uint32_t i = 0; i < n; i++) {
300 r[j][i] = i < j ? 0 : vectorDot(&q[j][0], &a[i][0], m);
301 }
302 }
303#if DEBUG_LEAST_SQUARES
304 ALOGD(" - q=%s", matrixToString(&q[0][0], m, n, false /*rowMajor*/).string());
305 ALOGD(" - r=%s", matrixToString(&r[0][0], n, n, true /*rowMajor*/).string());
306
307 // calculate QR, if we factored A correctly then QR should equal A
308 float qr[n][m];
309 for (uint32_t h = 0; h < m; h++) {
310 for (uint32_t i = 0; i < n; i++) {
311 qr[i][h] = 0;
312 for (uint32_t j = 0; j < n; j++) {
313 qr[i][h] += q[j][h] * r[j][i];
314 }
315 }
316 }
317 ALOGD(" - qr=%s", matrixToString(&qr[0][0], m, n, false /*rowMajor*/).string());
318#endif
319
320 // Solve R B = Qt Y to find B. This is easy because R is upper triangular.
321 // We just work from bottom-right to top-left calculating B's coefficients.
322 for (uint32_t i = n; i-- != 0; ) {
323 outB[i] = vectorDot(&q[i][0], y, m);
324 for (uint32_t j = n - 1; j > i; j--) {
325 outB[i] -= r[i][j] * outB[j];
326 }
327 outB[i] /= r[i][i];
328 }
329#if DEBUG_LEAST_SQUARES
330 ALOGD(" - b=%s", vectorToString(outB, n).string());
331#endif
332
333 // Calculate the coefficient of determination as 1 - (SSerr / SStot) where
334 // SSerr is the residual sum of squares (squared variance of the error),
335 // and SStot is the total sum of squares (squared variance of the data).
336 float ymean = 0;
337 for (uint32_t h = 0; h < m; h++) {
338 ymean += y[h];
339 }
340 ymean /= m;
341
342 float sserr = 0;
343 float sstot = 0;
344 for (uint32_t h = 0; h < m; h++) {
345 float err = y[h] - outB[0];
346 float term = 1;
347 for (uint32_t i = 1; i < n; i++) {
348 term *= x[h];
349 err -= term * outB[i];
350 }
351 sserr += err * err;
352 float var = y[h] - ymean;
353 sstot += var * var;
354 }
355 *outDet = sstot > 0.000001f ? 1.0f - (sserr / sstot) : 1;
356#if DEBUG_LEAST_SQUARES
357 ALOGD(" - sserr=%f", sserr);
358 ALOGD(" - sstot=%f", sstot);
359 ALOGD(" - det=%f", *outDet);
360#endif
361 return true;
362}
363
364bool VelocityTracker::getVelocity(uint32_t id, float* outVx, float* outVy) const {
365 Estimator estimator;
366 if (getEstimator(id, DEFAULT_DEGREE, DEFAULT_HORIZON, &estimator)) {
367 if (estimator.degree >= 1) {
368 *outVx = estimator.xCoeff[1];
369 *outVy = estimator.yCoeff[1];
370 return true;
371 }
372 }
373 *outVx = 0;
374 *outVy = 0;
375 return false;
376}
377
378bool VelocityTracker::getEstimator(uint32_t id, uint32_t degree, nsecs_t horizon,
379 Estimator* outEstimator) const {
380 outEstimator->clear();
381
382 // Iterate over movement samples in reverse time order and collect samples.
383 float x[HISTORY_SIZE];
384 float y[HISTORY_SIZE];
385 float time[HISTORY_SIZE];
386 uint32_t m = 0;
387 uint32_t index = mIndex;
388 const Movement& newestMovement = mMovements[mIndex];
389 do {
390 const Movement& movement = mMovements[index];
391 if (!movement.idBits.hasBit(id)) {
392 break;
393 }
394
395 nsecs_t age = newestMovement.eventTime - movement.eventTime;
396 if (age > horizon) {
397 break;
398 }
399
400 const Position& position = movement.getPosition(id);
401 x[m] = position.x;
402 y[m] = position.y;
403 time[m] = -age * 0.000000001f;
404 index = (index == 0 ? HISTORY_SIZE : index) - 1;
405 } while (++m < HISTORY_SIZE);
406
407 if (m == 0) {
408 return false; // no data
409 }
410
411 // Calculate a least squares polynomial fit.
412 if (degree > Estimator::MAX_DEGREE) {
413 degree = Estimator::MAX_DEGREE;
414 }
415 if (degree > m - 1) {
416 degree = m - 1;
417 }
418 if (degree >= 1) {
419 float xdet, ydet;
420 uint32_t n = degree + 1;
421 if (solveLeastSquares(time, x, m, n, outEstimator->xCoeff, &xdet)
422 && solveLeastSquares(time, y, m, n, outEstimator->yCoeff, &ydet)) {
423 outEstimator->degree = degree;
424 outEstimator->confidence = xdet * ydet;
425#if DEBUG_LEAST_SQUARES
426 ALOGD("estimate: degree=%d, xCoeff=%s, yCoeff=%s, confidence=%f",
427 int(outEstimator->degree),
428 vectorToString(outEstimator->xCoeff, n).string(),
429 vectorToString(outEstimator->yCoeff, n).string(),
430 outEstimator->confidence);
431#endif
432 return true;
433 }
434 }
435
436 // No velocity data available for this pointer, but we do have its current position.
437 outEstimator->xCoeff[0] = x[0];
438 outEstimator->yCoeff[0] = y[0];
439 outEstimator->degree = 0;
440 outEstimator->confidence = 1;
441 return true;
442}
443
444} // namespace android