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