blob: cda39ce6016f72e10177a5973ff71bb4c4274502 [file] [log] [blame]
Cody Heiner52db4742023-06-29 13:19:01 -07001/*
2 * Copyright 2023 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 "MotionPredictorMetricsManager"
18
19#include <input/MotionPredictorMetricsManager.h>
20
21#include <algorithm>
22
23#include <android-base/logging.h>
24
25#include "Eigen/Core"
26#include "Eigen/Geometry"
27
Cody Heiner52db4742023-06-29 13:19:01 -070028namespace android {
29namespace {
30
31inline constexpr int NANOS_PER_SECOND = 1'000'000'000; // nanoseconds per second
32inline constexpr int NANOS_PER_MILLIS = 1'000'000; // nanoseconds per millisecond
33
34// Velocity threshold at which we report "high-velocity" metrics, in pixels per second.
35// This value was selected from manual experimentation, as a threshold that separates "fast"
36// (semi-sloppy) handwriting from more careful medium to slow handwriting.
37inline constexpr float HIGH_VELOCITY_THRESHOLD = 1100.0;
38
39// Small value to add to the path length when computing scale-invariant error to avoid division by
40// zero.
41inline constexpr float PATH_LENGTH_EPSILON = 0.001;
42
43} // namespace
44
Cody Heiner7b26dbe2023-11-14 14:47:10 -080045void MotionPredictorMetricsManager::defaultReportAtomFunction(
46 const MotionPredictorMetricsManager::AtomFields& atomFields) {
Cody Heiner80dadc62024-05-01 01:10:35 +000047 // TODO(b/338106546): Fix bootanimation build dependency issue, then re-add
48 // the stats_write function call here.
49 (void)atomFields;
Cody Heiner7b26dbe2023-11-14 14:47:10 -080050}
51
52MotionPredictorMetricsManager::MotionPredictorMetricsManager(
53 nsecs_t predictionInterval,
54 size_t maxNumPredictions,
55 ReportAtomFunction reportAtomFunction)
Cody Heiner52db4742023-06-29 13:19:01 -070056 : mPredictionInterval(predictionInterval),
57 mMaxNumPredictions(maxNumPredictions),
58 mRecentGroundTruthPoints(maxNumPredictions + 1),
59 mAggregatedMetrics(maxNumPredictions),
Cody Heiner7b26dbe2023-11-14 14:47:10 -080060 mAtomFields(maxNumPredictions),
61 mReportAtomFunction(reportAtomFunction ? reportAtomFunction : defaultReportAtomFunction) {}
Cody Heiner52db4742023-06-29 13:19:01 -070062
63void MotionPredictorMetricsManager::onRecord(const MotionEvent& inputEvent) {
64 // Convert MotionEvent to GroundTruthPoint.
65 const PointerCoords* coords = inputEvent.getRawPointerCoords(/*pointerIndex=*/0);
66 LOG_ALWAYS_FATAL_IF(coords == nullptr);
67 const GroundTruthPoint groundTruthPoint{{.position = Eigen::Vector2f{coords->getY(),
68 coords->getX()},
69 .pressure =
70 inputEvent.getPressure(/*pointerIndex=*/0)},
71 .timestamp = inputEvent.getEventTime()};
72
73 // Handle event based on action type.
74 switch (inputEvent.getActionMasked()) {
75 case AMOTION_EVENT_ACTION_DOWN: {
76 clearStrokeData();
77 incorporateNewGroundTruth(groundTruthPoint);
78 break;
79 }
80 case AMOTION_EVENT_ACTION_MOVE: {
81 incorporateNewGroundTruth(groundTruthPoint);
82 break;
83 }
84 case AMOTION_EVENT_ACTION_UP:
85 case AMOTION_EVENT_ACTION_CANCEL: {
86 // Only expect meaningful predictions when given at least two input points.
87 if (mRecentGroundTruthPoints.size() >= 2) {
88 computeAtomFields();
89 reportMetrics();
Cody Heiner52db4742023-06-29 13:19:01 -070090 }
Cody Heiner7b26dbe2023-11-14 14:47:10 -080091 break;
Cody Heiner52db4742023-06-29 13:19:01 -070092 }
93 }
94}
95
96// Adds new predictions to mRecentPredictions and maintains the invariant that elements are
97// sorted in ascending order of targetTimestamp.
98void MotionPredictorMetricsManager::onPredict(const MotionEvent& predictionEvent) {
Cody Heiner50582ba2024-02-20 17:47:37 -080099 const size_t numPredictions = predictionEvent.getHistorySize() + 1;
100 if (numPredictions > mMaxNumPredictions) {
101 LOG(WARNING) << "numPredictions (" << numPredictions << ") > mMaxNumPredictions ("
102 << mMaxNumPredictions << "). Ignoring extra predictions in metrics.";
103 }
104 for (size_t i = 0; (i < numPredictions) && (i < mMaxNumPredictions); ++i) {
Cody Heiner52db4742023-06-29 13:19:01 -0700105 // Convert MotionEvent to PredictionPoint.
106 const PointerCoords* coords =
107 predictionEvent.getHistoricalRawPointerCoords(/*pointerIndex=*/0, i);
108 LOG_ALWAYS_FATAL_IF(coords == nullptr);
109 const nsecs_t targetTimestamp = predictionEvent.getHistoricalEventTime(i);
110 mRecentPredictions.push_back(
111 PredictionPoint{{.position = Eigen::Vector2f{coords->getY(), coords->getX()},
112 .pressure =
113 predictionEvent.getHistoricalPressure(/*pointerIndex=*/0,
114 i)},
115 .originTimestamp = mRecentGroundTruthPoints.back().timestamp,
116 .targetTimestamp = targetTimestamp});
117 }
118
119 std::sort(mRecentPredictions.begin(), mRecentPredictions.end());
120}
121
122void MotionPredictorMetricsManager::clearStrokeData() {
123 mRecentGroundTruthPoints.clear();
124 mRecentPredictions.clear();
125 std::fill(mAggregatedMetrics.begin(), mAggregatedMetrics.end(), AggregatedStrokeMetrics{});
126 std::fill(mAtomFields.begin(), mAtomFields.end(), AtomFields{});
127}
128
129void MotionPredictorMetricsManager::incorporateNewGroundTruth(
130 const GroundTruthPoint& groundTruthPoint) {
131 // Note: this removes the oldest point if `mRecentGroundTruthPoints` is already at capacity.
132 mRecentGroundTruthPoints.pushBack(groundTruthPoint);
133
134 // Remove outdated predictions – those that can never be matched with the current or any future
135 // ground truth points. We use fuzzy association for the timestamps here, because ground truth
136 // and prediction timestamps may not be perfectly synchronized.
137 const nsecs_t fuzzy_association_time_delta = mPredictionInterval / 4;
138 const auto firstCurrentIt =
139 std::find_if(mRecentPredictions.begin(), mRecentPredictions.end(),
140 [&groundTruthPoint,
141 fuzzy_association_time_delta](const PredictionPoint& prediction) {
142 return prediction.targetTimestamp >
143 groundTruthPoint.timestamp - fuzzy_association_time_delta;
144 });
145 mRecentPredictions.erase(mRecentPredictions.begin(), firstCurrentIt);
146
147 // Fuzzily match the new ground truth's timestamp to recent predictions' targetTimestamp and
148 // update the corresponding metrics.
149 for (const PredictionPoint& prediction : mRecentPredictions) {
150 if ((prediction.targetTimestamp >
151 groundTruthPoint.timestamp - fuzzy_association_time_delta) &&
152 (prediction.targetTimestamp <
153 groundTruthPoint.timestamp + fuzzy_association_time_delta)) {
154 updateAggregatedMetrics(prediction);
155 }
156 }
157}
158
159void MotionPredictorMetricsManager::updateAggregatedMetrics(
160 const PredictionPoint& predictionPoint) {
161 if (mRecentGroundTruthPoints.size() < 2) {
162 return;
163 }
164
165 const GroundTruthPoint& latestGroundTruthPoint = mRecentGroundTruthPoints.back();
166 const GroundTruthPoint& previousGroundTruthPoint =
167 mRecentGroundTruthPoints[mRecentGroundTruthPoints.size() - 2];
168 // Calculate prediction error vector.
169 const Eigen::Vector2f groundTruthTrajectory =
170 latestGroundTruthPoint.position - previousGroundTruthPoint.position;
171 const Eigen::Vector2f predictionTrajectory =
172 predictionPoint.position - previousGroundTruthPoint.position;
173 const Eigen::Vector2f predictionError = predictionTrajectory - groundTruthTrajectory;
174
175 // By default, prediction error counts fully as both off-trajectory and along-trajectory error.
176 // This serves as the fallback when the two most recent ground truth points are equal.
177 const float predictionErrorNorm = predictionError.norm();
178 float alongTrajectoryError = predictionErrorNorm;
179 float offTrajectoryError = predictionErrorNorm;
180 if (groundTruthTrajectory.squaredNorm() > 0) {
181 // Rotate the prediction error vector by the angle of the ground truth trajectory vector.
182 // This yields a vector whose first component is the along-trajectory error and whose
183 // second component is the off-trajectory error.
184 const float theta = std::atan2(groundTruthTrajectory[1], groundTruthTrajectory[0]);
185 const Eigen::Vector2f rotatedPredictionError = Eigen::Rotation2Df(-theta) * predictionError;
186 alongTrajectoryError = rotatedPredictionError[0];
187 offTrajectoryError = rotatedPredictionError[1];
188 }
189
190 // Compute the multiple of mPredictionInterval nearest to the amount of time into the
191 // future being predicted. This serves as the time bucket index into mAggregatedMetrics.
192 const float timestampDeltaFloat =
193 static_cast<float>(predictionPoint.targetTimestamp - predictionPoint.originTimestamp);
194 const size_t tIndex =
195 static_cast<size_t>(std::round(timestampDeltaFloat / mPredictionInterval - 1));
196
197 // Aggregate values into "general errors".
198 mAggregatedMetrics[tIndex].alongTrajectoryErrorSum += alongTrajectoryError;
199 mAggregatedMetrics[tIndex].alongTrajectorySumSquaredErrors +=
200 alongTrajectoryError * alongTrajectoryError;
201 mAggregatedMetrics[tIndex].offTrajectorySumSquaredErrors +=
202 offTrajectoryError * offTrajectoryError;
203 const float pressureError = predictionPoint.pressure - latestGroundTruthPoint.pressure;
204 mAggregatedMetrics[tIndex].pressureSumSquaredErrors += pressureError * pressureError;
205 ++mAggregatedMetrics[tIndex].generalErrorsCount;
206
207 // Aggregate values into high-velocity metrics, if we are in one of the last two time buckets
208 // and the velocity is above the threshold. Velocity here is measured in pixels per second.
209 const float velocity = groundTruthTrajectory.norm() /
210 (static_cast<float>(latestGroundTruthPoint.timestamp -
211 previousGroundTruthPoint.timestamp) /
212 NANOS_PER_SECOND);
213 if ((tIndex + 2 >= mMaxNumPredictions) && (velocity > HIGH_VELOCITY_THRESHOLD)) {
214 mAggregatedMetrics[tIndex].highVelocityAlongTrajectorySse +=
215 alongTrajectoryError * alongTrajectoryError;
216 mAggregatedMetrics[tIndex].highVelocityOffTrajectorySse +=
217 offTrajectoryError * offTrajectoryError;
218 ++mAggregatedMetrics[tIndex].highVelocityErrorsCount;
219 }
220
221 // Compute path length for scale-invariant errors.
222 float pathLength = 0;
223 for (size_t i = 1; i < mRecentGroundTruthPoints.size(); ++i) {
224 pathLength +=
225 (mRecentGroundTruthPoints[i].position - mRecentGroundTruthPoints[i - 1].position)
226 .norm();
227 }
228 // Avoid overweighting errors at the beginning of a stroke: compute the path length as if there
229 // were a full ground truth history by filling in missing segments with the average length.
230 // Note: the "- 1" is needed to translate from number of endpoints to number of segments.
231 pathLength *= static_cast<float>(mRecentGroundTruthPoints.capacity() - 1) /
232 (mRecentGroundTruthPoints.size() - 1);
233 pathLength += PATH_LENGTH_EPSILON; // Ensure path length is nonzero (>= PATH_LENGTH_EPSILON).
234
235 // Compute and aggregate scale-invariant errors.
236 const float scaleInvariantAlongTrajectoryError = alongTrajectoryError / pathLength;
237 const float scaleInvariantOffTrajectoryError = offTrajectoryError / pathLength;
238 mAggregatedMetrics[tIndex].scaleInvariantAlongTrajectorySse +=
239 scaleInvariantAlongTrajectoryError * scaleInvariantAlongTrajectoryError;
240 mAggregatedMetrics[tIndex].scaleInvariantOffTrajectorySse +=
241 scaleInvariantOffTrajectoryError * scaleInvariantOffTrajectoryError;
242 ++mAggregatedMetrics[tIndex].scaleInvariantErrorsCount;
243}
244
245void MotionPredictorMetricsManager::computeAtomFields() {
246 for (size_t i = 0; i < mAggregatedMetrics.size(); ++i) {
247 if (mAggregatedMetrics[i].generalErrorsCount == 0) {
248 // We have not received data corresponding to metrics for this time bucket.
249 continue;
250 }
251
252 mAtomFields[i].deltaTimeBucketMilliseconds =
253 static_cast<int>(mPredictionInterval / NANOS_PER_MILLIS * (i + 1));
254
255 // Note: we need the "* 1000"s below because we report values in integral milli-units.
256
257 { // General errors: reported for every time bucket.
258 const float alongTrajectoryErrorMean = mAggregatedMetrics[i].alongTrajectoryErrorSum /
259 mAggregatedMetrics[i].generalErrorsCount;
260 mAtomFields[i].alongTrajectoryErrorMeanMillipixels =
261 static_cast<int>(alongTrajectoryErrorMean * 1000);
262
263 const float alongTrajectoryMse = mAggregatedMetrics[i].alongTrajectorySumSquaredErrors /
264 mAggregatedMetrics[i].generalErrorsCount;
265 // Take the max with 0 to avoid negative values caused by numerical instability.
266 const float alongTrajectoryErrorVariance =
267 std::max(0.0f,
268 alongTrajectoryMse -
269 alongTrajectoryErrorMean * alongTrajectoryErrorMean);
270 const float alongTrajectoryErrorStd = std::sqrt(alongTrajectoryErrorVariance);
271 mAtomFields[i].alongTrajectoryErrorStdMillipixels =
272 static_cast<int>(alongTrajectoryErrorStd * 1000);
273
274 LOG_ALWAYS_FATAL_IF(mAggregatedMetrics[i].offTrajectorySumSquaredErrors < 0,
275 "mAggregatedMetrics[%zu].offTrajectorySumSquaredErrors = %f should "
276 "not be negative",
277 i, mAggregatedMetrics[i].offTrajectorySumSquaredErrors);
278 const float offTrajectoryRmse =
279 std::sqrt(mAggregatedMetrics[i].offTrajectorySumSquaredErrors /
280 mAggregatedMetrics[i].generalErrorsCount);
281 mAtomFields[i].offTrajectoryRmseMillipixels =
282 static_cast<int>(offTrajectoryRmse * 1000);
283
284 LOG_ALWAYS_FATAL_IF(mAggregatedMetrics[i].pressureSumSquaredErrors < 0,
285 "mAggregatedMetrics[%zu].pressureSumSquaredErrors = %f should not "
286 "be negative",
287 i, mAggregatedMetrics[i].pressureSumSquaredErrors);
288 const float pressureRmse = std::sqrt(mAggregatedMetrics[i].pressureSumSquaredErrors /
289 mAggregatedMetrics[i].generalErrorsCount);
290 mAtomFields[i].pressureRmseMilliunits = static_cast<int>(pressureRmse * 1000);
291 }
292
293 // High-velocity errors: reported only for last two time buckets.
294 // Check if we are in one of the last two time buckets, and there is high-velocity data.
295 if ((i + 2 >= mMaxNumPredictions) && (mAggregatedMetrics[i].highVelocityErrorsCount > 0)) {
296 LOG_ALWAYS_FATAL_IF(mAggregatedMetrics[i].highVelocityAlongTrajectorySse < 0,
297 "mAggregatedMetrics[%zu].highVelocityAlongTrajectorySse = %f "
298 "should not be negative",
299 i, mAggregatedMetrics[i].highVelocityAlongTrajectorySse);
300 const float alongTrajectoryRmse =
301 std::sqrt(mAggregatedMetrics[i].highVelocityAlongTrajectorySse /
302 mAggregatedMetrics[i].highVelocityErrorsCount);
303 mAtomFields[i].highVelocityAlongTrajectoryRmse =
304 static_cast<int>(alongTrajectoryRmse * 1000);
305
306 LOG_ALWAYS_FATAL_IF(mAggregatedMetrics[i].highVelocityOffTrajectorySse < 0,
307 "mAggregatedMetrics[%zu].highVelocityOffTrajectorySse = %f should "
308 "not be negative",
309 i, mAggregatedMetrics[i].highVelocityOffTrajectorySse);
310 const float offTrajectoryRmse =
311 std::sqrt(mAggregatedMetrics[i].highVelocityOffTrajectorySse /
312 mAggregatedMetrics[i].highVelocityErrorsCount);
313 mAtomFields[i].highVelocityOffTrajectoryRmse =
314 static_cast<int>(offTrajectoryRmse * 1000);
315 }
Cody Heiner50582ba2024-02-20 17:47:37 -0800316 }
Cody Heiner52db4742023-06-29 13:19:01 -0700317
Cody Heiner50582ba2024-02-20 17:47:37 -0800318 // Scale-invariant errors: the average scale-invariant error across all time buckets
319 // is reported in the last time bucket.
320 {
321 // Compute error averages.
322 float alongTrajectoryRmseSum = 0;
323 float offTrajectoryRmseSum = 0;
324 int bucket_count = 0;
325 for (size_t j = 0; j < mAggregatedMetrics.size(); ++j) {
326 if (mAggregatedMetrics[j].scaleInvariantErrorsCount == 0) {
327 continue;
Cody Heiner52db4742023-06-29 13:19:01 -0700328 }
329
Cody Heiner50582ba2024-02-20 17:47:37 -0800330 LOG_ALWAYS_FATAL_IF(mAggregatedMetrics[j].scaleInvariantAlongTrajectorySse < 0,
331 "mAggregatedMetrics[%zu].scaleInvariantAlongTrajectorySse = %f "
332 "should not be negative",
333 j, mAggregatedMetrics[j].scaleInvariantAlongTrajectorySse);
334 alongTrajectoryRmseSum +=
335 std::sqrt(mAggregatedMetrics[j].scaleInvariantAlongTrajectorySse /
336 mAggregatedMetrics[j].scaleInvariantErrorsCount);
337
338 LOG_ALWAYS_FATAL_IF(mAggregatedMetrics[j].scaleInvariantOffTrajectorySse < 0,
339 "mAggregatedMetrics[%zu].scaleInvariantOffTrajectorySse = %f "
340 "should not be negative",
341 j, mAggregatedMetrics[j].scaleInvariantOffTrajectorySse);
342 offTrajectoryRmseSum += std::sqrt(mAggregatedMetrics[j].scaleInvariantOffTrajectorySse /
343 mAggregatedMetrics[j].scaleInvariantErrorsCount);
344
345 ++bucket_count;
346 }
347
348 if (bucket_count > 0) {
349 const float averageAlongTrajectoryRmse = alongTrajectoryRmseSum / bucket_count;
Cody Heiner52db4742023-06-29 13:19:01 -0700350 mAtomFields.back().scaleInvariantAlongTrajectoryRmse =
351 static_cast<int>(averageAlongTrajectoryRmse * 1000);
352
Cody Heiner50582ba2024-02-20 17:47:37 -0800353 const float averageOffTrajectoryRmse = offTrajectoryRmseSum / bucket_count;
Cody Heiner52db4742023-06-29 13:19:01 -0700354 mAtomFields.back().scaleInvariantOffTrajectoryRmse =
355 static_cast<int>(averageOffTrajectoryRmse * 1000);
356 }
357 }
358}
359
360void MotionPredictorMetricsManager::reportMetrics() {
Cody Heiner7b26dbe2023-11-14 14:47:10 -0800361 LOG_ALWAYS_FATAL_IF(!mReportAtomFunction);
362 // Report one atom for each prediction time bucket.
Cody Heiner52db4742023-06-29 13:19:01 -0700363 for (size_t i = 0; i < mAtomFields.size(); ++i) {
Cody Heiner7b26dbe2023-11-14 14:47:10 -0800364 mReportAtomFunction(mAtomFields[i]);
Cody Heiner52db4742023-06-29 13:19:01 -0700365 }
366}
367
368} // namespace android