| | | 1 | | using System.Collections.Generic; |
| | | 2 | | using System.Linq; |
| | | 3 | | using MathNet.Numerics; |
| | | 4 | | using ReFlex.Core.Common.Components; |
| | | 5 | | |
| | | 6 | | namespace ReFlex.Core.Interactivity.Util; |
| | | 7 | | |
| | | 8 | | /// <summary>Fits real timestamped measurements and creates forecasts without updating track state.</summary> |
| | | 9 | | internal static class ContactMotion |
| | | 10 | | { |
| | | 11 | | public static (Point3 Velocity, Point3 Acceleration, int Count) Estimate( |
| | | 12 | | IEnumerable<(double Time, Interaction Measurement)> measurements, double lastSeenTime, int sampleCount, bool use |
| | 1220 | 13 | | { |
| | 1220 | 14 | | var samples = measurements.TakeLast(sampleCount) |
| | 4516 | 15 | | .Select(sample => (sample.Time, Position: sample.Measurement.Position)).ToArray(); |
| | 1220 | 16 | | if (samples.Length < 2) |
| | 206 | 17 | | return (new Point3(), new Point3(), samples.Length); |
| | | 18 | | |
| | | 19 | | // Center times at the newest measurement: the fitted linear coefficient is v(now), |
| | | 20 | | // not the average velocity half-way between measurements. Gaps retain their duration. |
| | 1014 | 21 | | var span = lastSeenTime - samples[0].Time; |
| | | 22 | | // Normalize the independent variable for well-conditioned fits, then recover derivatives per second. |
| | 4104 | 23 | | var times = samples.Select(sample => (sample.Time - lastSeenTime) / span).ToArray(); |
| | 1014 | 24 | | var order = useAcceleration && samples.Length >= 3 ? 2 : 1; |
| | 4104 | 25 | | var x = Fit.Polynomial(times, samples.Select(sample => (double)sample.Position.X).ToArray(), order); |
| | 4104 | 26 | | var y = Fit.Polynomial(times, samples.Select(sample => (double)sample.Position.Y).ToArray(), order); |
| | 4104 | 27 | | var z = Fit.Polynomial(times, samples.Select(sample => (double)sample.Position.Z).ToArray(), order); |
| | 1014 | 28 | | var velocity = new Point3((float)(x[1] / span), (float)(y[1] / span), (float)(z[1] / span)); |
| | 1014 | 29 | | var acceleration = order == 2 |
| | 1014 | 30 | | ? new Point3((float)(2 * x[2] / (span * span)), |
| | 1014 | 31 | | (float)(2 * y[2] / (span * span)), (float)(2 * z[2] / (span * span))) |
| | 1014 | 32 | | : new Point3(); |
| | 1014 | 33 | | return (velocity, acceleration, samples.Length); |
| | 1220 | 34 | | } |
| | | 35 | | |
| | | 36 | | public static InteractionVelocity Forecast(Point3 position, |
| | | 37 | | (Point3 Velocity, Point3 Acceleration, int Count) motion, float accelerationWeight, float horizon) |
| | 1220 | 38 | | { |
| | 1220 | 39 | | var forecast = new InteractionVelocity(); |
| | 1220 | 40 | | forecast.Update(position, motion.Velocity, motion.Acceleration, accelerationWeight, horizon); |
| | 1220 | 41 | | return forecast; |
| | 1220 | 42 | | } |
| | | 43 | | } |