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