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