blob: 0412d08181dac014b5daf43ec8f569f1eda2537f [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) {
116 for (size_t i = 0; i < predictionEvent.getHistorySize() + 1; ++i) {
117 // Convert MotionEvent to PredictionPoint.
118 const PointerCoords* coords =
119 predictionEvent.getHistoricalRawPointerCoords(/*pointerIndex=*/0, i);
120 LOG_ALWAYS_FATAL_IF(coords == nullptr);
121 const nsecs_t targetTimestamp = predictionEvent.getHistoricalEventTime(i);
122 mRecentPredictions.push_back(
123 PredictionPoint{{.position = Eigen::Vector2f{coords->getY(), coords->getX()},
124 .pressure =
125 predictionEvent.getHistoricalPressure(/*pointerIndex=*/0,
126 i)},
127 .originTimestamp = mRecentGroundTruthPoints.back().timestamp,
128 .targetTimestamp = targetTimestamp});
129 }
130
131 std::sort(mRecentPredictions.begin(), mRecentPredictions.end());
132}
133
134void MotionPredictorMetricsManager::clearStrokeData() {
135 mRecentGroundTruthPoints.clear();
136 mRecentPredictions.clear();
137 std::fill(mAggregatedMetrics.begin(), mAggregatedMetrics.end(), AggregatedStrokeMetrics{});
138 std::fill(mAtomFields.begin(), mAtomFields.end(), AtomFields{});
139}
140
141void MotionPredictorMetricsManager::incorporateNewGroundTruth(
142 const GroundTruthPoint& groundTruthPoint) {
143 // Note: this removes the oldest point if `mRecentGroundTruthPoints` is already at capacity.
144 mRecentGroundTruthPoints.pushBack(groundTruthPoint);
145
146 // Remove outdated predictions – those that can never be matched with the current or any future
147 // ground truth points. We use fuzzy association for the timestamps here, because ground truth
148 // and prediction timestamps may not be perfectly synchronized.
149 const nsecs_t fuzzy_association_time_delta = mPredictionInterval / 4;
150 const auto firstCurrentIt =
151 std::find_if(mRecentPredictions.begin(), mRecentPredictions.end(),
152 [&groundTruthPoint,
153 fuzzy_association_time_delta](const PredictionPoint& prediction) {
154 return prediction.targetTimestamp >
155 groundTruthPoint.timestamp - fuzzy_association_time_delta;
156 });
157 mRecentPredictions.erase(mRecentPredictions.begin(), firstCurrentIt);
158
159 // Fuzzily match the new ground truth's timestamp to recent predictions' targetTimestamp and
160 // update the corresponding metrics.
161 for (const PredictionPoint& prediction : mRecentPredictions) {
162 if ((prediction.targetTimestamp >
163 groundTruthPoint.timestamp - fuzzy_association_time_delta) &&
164 (prediction.targetTimestamp <
165 groundTruthPoint.timestamp + fuzzy_association_time_delta)) {
166 updateAggregatedMetrics(prediction);
167 }
168 }
169}
170
171void MotionPredictorMetricsManager::updateAggregatedMetrics(
172 const PredictionPoint& predictionPoint) {
173 if (mRecentGroundTruthPoints.size() < 2) {
174 return;
175 }
176
177 const GroundTruthPoint& latestGroundTruthPoint = mRecentGroundTruthPoints.back();
178 const GroundTruthPoint& previousGroundTruthPoint =
179 mRecentGroundTruthPoints[mRecentGroundTruthPoints.size() - 2];
180 // Calculate prediction error vector.
181 const Eigen::Vector2f groundTruthTrajectory =
182 latestGroundTruthPoint.position - previousGroundTruthPoint.position;
183 const Eigen::Vector2f predictionTrajectory =
184 predictionPoint.position - previousGroundTruthPoint.position;
185 const Eigen::Vector2f predictionError = predictionTrajectory - groundTruthTrajectory;
186
187 // By default, prediction error counts fully as both off-trajectory and along-trajectory error.
188 // This serves as the fallback when the two most recent ground truth points are equal.
189 const float predictionErrorNorm = predictionError.norm();
190 float alongTrajectoryError = predictionErrorNorm;
191 float offTrajectoryError = predictionErrorNorm;
192 if (groundTruthTrajectory.squaredNorm() > 0) {
193 // Rotate the prediction error vector by the angle of the ground truth trajectory vector.
194 // This yields a vector whose first component is the along-trajectory error and whose
195 // second component is the off-trajectory error.
196 const float theta = std::atan2(groundTruthTrajectory[1], groundTruthTrajectory[0]);
197 const Eigen::Vector2f rotatedPredictionError = Eigen::Rotation2Df(-theta) * predictionError;
198 alongTrajectoryError = rotatedPredictionError[0];
199 offTrajectoryError = rotatedPredictionError[1];
200 }
201
202 // Compute the multiple of mPredictionInterval nearest to the amount of time into the
203 // future being predicted. This serves as the time bucket index into mAggregatedMetrics.
204 const float timestampDeltaFloat =
205 static_cast<float>(predictionPoint.targetTimestamp - predictionPoint.originTimestamp);
206 const size_t tIndex =
207 static_cast<size_t>(std::round(timestampDeltaFloat / mPredictionInterval - 1));
208
209 // Aggregate values into "general errors".
210 mAggregatedMetrics[tIndex].alongTrajectoryErrorSum += alongTrajectoryError;
211 mAggregatedMetrics[tIndex].alongTrajectorySumSquaredErrors +=
212 alongTrajectoryError * alongTrajectoryError;
213 mAggregatedMetrics[tIndex].offTrajectorySumSquaredErrors +=
214 offTrajectoryError * offTrajectoryError;
215 const float pressureError = predictionPoint.pressure - latestGroundTruthPoint.pressure;
216 mAggregatedMetrics[tIndex].pressureSumSquaredErrors += pressureError * pressureError;
217 ++mAggregatedMetrics[tIndex].generalErrorsCount;
218
219 // Aggregate values into high-velocity metrics, if we are in one of the last two time buckets
220 // and the velocity is above the threshold. Velocity here is measured in pixels per second.
221 const float velocity = groundTruthTrajectory.norm() /
222 (static_cast<float>(latestGroundTruthPoint.timestamp -
223 previousGroundTruthPoint.timestamp) /
224 NANOS_PER_SECOND);
225 if ((tIndex + 2 >= mMaxNumPredictions) && (velocity > HIGH_VELOCITY_THRESHOLD)) {
226 mAggregatedMetrics[tIndex].highVelocityAlongTrajectorySse +=
227 alongTrajectoryError * alongTrajectoryError;
228 mAggregatedMetrics[tIndex].highVelocityOffTrajectorySse +=
229 offTrajectoryError * offTrajectoryError;
230 ++mAggregatedMetrics[tIndex].highVelocityErrorsCount;
231 }
232
233 // Compute path length for scale-invariant errors.
234 float pathLength = 0;
235 for (size_t i = 1; i < mRecentGroundTruthPoints.size(); ++i) {
236 pathLength +=
237 (mRecentGroundTruthPoints[i].position - mRecentGroundTruthPoints[i - 1].position)
238 .norm();
239 }
240 // Avoid overweighting errors at the beginning of a stroke: compute the path length as if there
241 // were a full ground truth history by filling in missing segments with the average length.
242 // Note: the "- 1" is needed to translate from number of endpoints to number of segments.
243 pathLength *= static_cast<float>(mRecentGroundTruthPoints.capacity() - 1) /
244 (mRecentGroundTruthPoints.size() - 1);
245 pathLength += PATH_LENGTH_EPSILON; // Ensure path length is nonzero (>= PATH_LENGTH_EPSILON).
246
247 // Compute and aggregate scale-invariant errors.
248 const float scaleInvariantAlongTrajectoryError = alongTrajectoryError / pathLength;
249 const float scaleInvariantOffTrajectoryError = offTrajectoryError / pathLength;
250 mAggregatedMetrics[tIndex].scaleInvariantAlongTrajectorySse +=
251 scaleInvariantAlongTrajectoryError * scaleInvariantAlongTrajectoryError;
252 mAggregatedMetrics[tIndex].scaleInvariantOffTrajectorySse +=
253 scaleInvariantOffTrajectoryError * scaleInvariantOffTrajectoryError;
254 ++mAggregatedMetrics[tIndex].scaleInvariantErrorsCount;
255}
256
257void MotionPredictorMetricsManager::computeAtomFields() {
258 for (size_t i = 0; i < mAggregatedMetrics.size(); ++i) {
259 if (mAggregatedMetrics[i].generalErrorsCount == 0) {
260 // We have not received data corresponding to metrics for this time bucket.
261 continue;
262 }
263
264 mAtomFields[i].deltaTimeBucketMilliseconds =
265 static_cast<int>(mPredictionInterval / NANOS_PER_MILLIS * (i + 1));
266
267 // Note: we need the "* 1000"s below because we report values in integral milli-units.
268
269 { // General errors: reported for every time bucket.
270 const float alongTrajectoryErrorMean = mAggregatedMetrics[i].alongTrajectoryErrorSum /
271 mAggregatedMetrics[i].generalErrorsCount;
272 mAtomFields[i].alongTrajectoryErrorMeanMillipixels =
273 static_cast<int>(alongTrajectoryErrorMean * 1000);
274
275 const float alongTrajectoryMse = mAggregatedMetrics[i].alongTrajectorySumSquaredErrors /
276 mAggregatedMetrics[i].generalErrorsCount;
277 // Take the max with 0 to avoid negative values caused by numerical instability.
278 const float alongTrajectoryErrorVariance =
279 std::max(0.0f,
280 alongTrajectoryMse -
281 alongTrajectoryErrorMean * alongTrajectoryErrorMean);
282 const float alongTrajectoryErrorStd = std::sqrt(alongTrajectoryErrorVariance);
283 mAtomFields[i].alongTrajectoryErrorStdMillipixels =
284 static_cast<int>(alongTrajectoryErrorStd * 1000);
285
286 LOG_ALWAYS_FATAL_IF(mAggregatedMetrics[i].offTrajectorySumSquaredErrors < 0,
287 "mAggregatedMetrics[%zu].offTrajectorySumSquaredErrors = %f should "
288 "not be negative",
289 i, mAggregatedMetrics[i].offTrajectorySumSquaredErrors);
290 const float offTrajectoryRmse =
291 std::sqrt(mAggregatedMetrics[i].offTrajectorySumSquaredErrors /
292 mAggregatedMetrics[i].generalErrorsCount);
293 mAtomFields[i].offTrajectoryRmseMillipixels =
294 static_cast<int>(offTrajectoryRmse * 1000);
295
296 LOG_ALWAYS_FATAL_IF(mAggregatedMetrics[i].pressureSumSquaredErrors < 0,
297 "mAggregatedMetrics[%zu].pressureSumSquaredErrors = %f should not "
298 "be negative",
299 i, mAggregatedMetrics[i].pressureSumSquaredErrors);
300 const float pressureRmse = std::sqrt(mAggregatedMetrics[i].pressureSumSquaredErrors /
301 mAggregatedMetrics[i].generalErrorsCount);
302 mAtomFields[i].pressureRmseMilliunits = static_cast<int>(pressureRmse * 1000);
303 }
304
305 // High-velocity errors: reported only for last two time buckets.
306 // Check if we are in one of the last two time buckets, and there is high-velocity data.
307 if ((i + 2 >= mMaxNumPredictions) && (mAggregatedMetrics[i].highVelocityErrorsCount > 0)) {
308 LOG_ALWAYS_FATAL_IF(mAggregatedMetrics[i].highVelocityAlongTrajectorySse < 0,
309 "mAggregatedMetrics[%zu].highVelocityAlongTrajectorySse = %f "
310 "should not be negative",
311 i, mAggregatedMetrics[i].highVelocityAlongTrajectorySse);
312 const float alongTrajectoryRmse =
313 std::sqrt(mAggregatedMetrics[i].highVelocityAlongTrajectorySse /
314 mAggregatedMetrics[i].highVelocityErrorsCount);
315 mAtomFields[i].highVelocityAlongTrajectoryRmse =
316 static_cast<int>(alongTrajectoryRmse * 1000);
317
318 LOG_ALWAYS_FATAL_IF(mAggregatedMetrics[i].highVelocityOffTrajectorySse < 0,
319 "mAggregatedMetrics[%zu].highVelocityOffTrajectorySse = %f should "
320 "not be negative",
321 i, mAggregatedMetrics[i].highVelocityOffTrajectorySse);
322 const float offTrajectoryRmse =
323 std::sqrt(mAggregatedMetrics[i].highVelocityOffTrajectorySse /
324 mAggregatedMetrics[i].highVelocityErrorsCount);
325 mAtomFields[i].highVelocityOffTrajectoryRmse =
326 static_cast<int>(offTrajectoryRmse * 1000);
327 }
328
329 // Scale-invariant errors: reported only for the last time bucket, where the values
330 // represent an average across all time buckets.
331 if (i + 1 == mMaxNumPredictions) {
332 // Compute error averages.
333 float alongTrajectoryRmseSum = 0;
334 float offTrajectoryRmseSum = 0;
335 for (size_t j = 0; j < mAggregatedMetrics.size(); ++j) {
336 // If we have general errors (checked above), we should always also have
337 // scale-invariant errors.
338 LOG_ALWAYS_FATAL_IF(mAggregatedMetrics[j].scaleInvariantErrorsCount == 0,
339 "mAggregatedMetrics[%zu].scaleInvariantErrorsCount is 0", j);
340
341 LOG_ALWAYS_FATAL_IF(mAggregatedMetrics[j].scaleInvariantAlongTrajectorySse < 0,
342 "mAggregatedMetrics[%zu].scaleInvariantAlongTrajectorySse = %f "
343 "should not be negative",
344 j, mAggregatedMetrics[j].scaleInvariantAlongTrajectorySse);
345 alongTrajectoryRmseSum +=
346 std::sqrt(mAggregatedMetrics[j].scaleInvariantAlongTrajectorySse /
347 mAggregatedMetrics[j].scaleInvariantErrorsCount);
348
349 LOG_ALWAYS_FATAL_IF(mAggregatedMetrics[j].scaleInvariantOffTrajectorySse < 0,
350 "mAggregatedMetrics[%zu].scaleInvariantOffTrajectorySse = %f "
351 "should not be negative",
352 j, mAggregatedMetrics[j].scaleInvariantOffTrajectorySse);
353 offTrajectoryRmseSum +=
354 std::sqrt(mAggregatedMetrics[j].scaleInvariantOffTrajectorySse /
355 mAggregatedMetrics[j].scaleInvariantErrorsCount);
356 }
357
358 const float averageAlongTrajectoryRmse =
359 alongTrajectoryRmseSum / mAggregatedMetrics.size();
360 mAtomFields.back().scaleInvariantAlongTrajectoryRmse =
361 static_cast<int>(averageAlongTrajectoryRmse * 1000);
362
363 const float averageOffTrajectoryRmse = offTrajectoryRmseSum / mAggregatedMetrics.size();
364 mAtomFields.back().scaleInvariantOffTrajectoryRmse =
365 static_cast<int>(averageOffTrajectoryRmse * 1000);
366 }
367 }
368}
369
370void MotionPredictorMetricsManager::reportMetrics() {
Cody Heiner7b26dbe2023-11-14 14:47:10 -0800371 LOG_ALWAYS_FATAL_IF(!mReportAtomFunction);
372 // Report one atom for each prediction time bucket.
Cody Heiner52db4742023-06-29 13:19:01 -0700373 for (size_t i = 0; i < mAtomFields.size(); ++i) {
Cody Heiner7b26dbe2023-11-14 14:47:10 -0800374 mReportAtomFunction(mAtomFields[i]);
Cody Heiner52db4742023-06-29 13:19:01 -0700375 }
376}
377
378} // namespace android