Skip to main content
Apps

Investigating Horse Gait Mathematics and Building an iOS Sensor App

My daughter rides horses, and I’m an engineer. Watching her ride, I found myself wondering whether the sensors in an iPhone and Apple Watch could detect which gait a horse is in. What started as a casual question turned into a deep investigation of equestrian biomechanics, signal processing, and the surprisingly rich mathematics hidden in the way horses move.

The Physics of Horse Gaits

A horse has four natural gaits: walk, trot, canter, and gallop. To most riders these feel obviously different, but what makes them distinct from a physics perspective is far less intuitive. Each gait is defined not by speed but by the sequence and timing of footfalls, the proportion of the stride that each hoof spends on the ground (the duty factor), and the phase relationships between the four limbs.

Walk

The walk is a four-beat lateral-sequence gait. The footfalls occur in the order: left hind, left fore, right hind, right fore, with each hoof striking independently at roughly quarter intervals of the stride. The duty factor is high (0.60-0.70), meaning each leg is on the ground for 60-70% of the stride. There is no aerial phase; at least two hooves are always in contact with the ground, and often three. Stride frequency is typically 0.8-0.9 Hz at speeds of 1.4-1.8 m/s. From the rider’s perspective, the walk produces a gentle, rolling motion with relatively low vertical displacement.

Trot

The trot is a two-beat diagonal gait. Diagonal pairs of legs (left hind with right fore, then right hind with left fore) strike the ground simultaneously, separated by a moment of suspension when all four hooves are airborne. The duty factor drops to 0.30-0.55 depending on speed. Stride frequency is higher at around 1.4-1.5 Hz, with typical speeds of 3.0-5.0 m/s.

The trot is critical for biomechanical analysis because its symmetry makes asymmetries easy to detect. In a sound horse, the left and right diagonal pairs produce identical force profiles. Any difference between them suggests lameness or muscular imbalance. This is why veterinary gait analysis systems like the Lameness Locator focus primarily on the trot.

Canter

The canter is an asymmetric three-beat gait with a leading leg. In right-lead canter, the footfall sequence is: left hind, then right hind and left fore together, then right fore (the leading leg), followed by a suspension phase. The duty factor is around 0.30 and stride frequency is 1.8-2.0 Hz at speeds of 3.3-6.0 m/s.

Because the canter is asymmetric, the forces on left and right limbs are unequal. The trailing forelimb bears up to 1.5 times bodyweight while the other limbs experience up to 1.2 times bodyweight. The leading limbs are more involved in braking while the trailing limbs provide propulsion. This asymmetry has important implications for training; horses need to canter equally on both leads to avoid uneven muscular development.

Gallop

The gallop extends the canter’s three-beat pattern into four distinct beats, as the diagonal pair that struck together in canter now separates. The duty factor drops to about 0.20 and stride frequency reaches 2.2-3.0 Hz at speeds above 10 m/s. At racing speed, a Thoroughbred’s stride length can reach 7.3 metres with a frequency of 2.24 strides per second. The gallop has the longest aerial phase of any gait, with all four hooves off the ground simultaneously.

Why Horses Change Gaits

The classic study by Hoyt and Taylor (1981, published in Nature) established that horses change gaits to minimize energy consumption. They trained horses to walk, trot, and gallop on a treadmill and measured oxygen consumption at each speed. The relationship between metabolic cost and speed turned out to be U-shaped for each gait: walking is efficient at low speeds, trotting at medium speeds, and galloping at high speeds. Left to choose freely, horses naturally transition between gaits at the speeds where the energy curves cross.

Whether the trigger for gait transition is metabolic cost or peak musculoskeletal force is still debated. Some evidence suggests that peak forces on bones and tendons, rather than energy expenditure alone, determine when a horse switches gait. Either way, the transitions are not arbitrary; they are optimized by evolution.

Central Pattern Generators

The gaits themselves are generated by neural circuits in the spinal cord called Central Pattern Generators (CPGs). These are networks of coupled oscillators that can produce rhythmic motor patterns even when isolated from the brain and sensory input. In 1993, Collins and Stewart showed that the symmetries of quadruped gaits could be reproduced by coupling four nonlinear oscillators and varying the coupling strength.

A striking demonstration of the genetic basis of gait comes from Icelandic horses. Those homozygous for a nonsense mutation in the DMRT3 gene naturally pace (a lateral two-beat gait) rather than trot (a diagonal two-beat gait). A single genetic change affecting spinal cord interneurons fundamentally rewires the CPG and alters which gaits a horse can produce. Icelandic horses are also known for a fifth gait, the tölt, a four-beat lateral gait that is remarkably smooth for the rider because there is no moment of suspension. We experienced this first-hand on a trip to Reykjavik, where my daughter rode Icelandic ponies and tried the tölt. It is a strange sensation to watch: the horse covers ground at trotting speed but the rider barely moves in the saddle. From a signal processing perspective, the tölt is fascinating because it should produce a very different harmonic signature from the trot despite similar speeds, with energy distributed across four beats rather than concentrated in two.

More recent robotics research has confirmed the CPG model. A 2017 study in Scientific Reports demonstrated that a quadruped robot with a simple CPG controller spontaneously transitions between walk, trot, and gallop as speed increases, using only local load sensing in each leg. No pre-programmed gait patterns were needed; the gaits emerged from the physical dynamics of the system.

The Limit-Cycle Oscillator Model

What I found most useful for sensor-based detection is that a horse can be modelled as a limit-cycle oscillator. Each gait produces a characteristic pattern of oscillation frequency, beat count, left-right symmetry, and vertical-rotational coupling. The rider sitting on top is essentially a movable mass riding this oscillator. Crookedness, rein imbalance, lead issues, and tension all appear as measurable distortions in the oscillation pattern.

This framing leads directly to spectral analysis. If the horse is an oscillator, its motion should decompose into a fundamental frequency (the stride frequency) and harmonics, and the relative power of those harmonics should be different for each gait. And that is exactly what happens.

How Harmonics Distinguish the Gaits

The key insight is that the number of vertical oscillations per stride is determined by the number of ground-contact events. In the trot, diagonal pairs strike the ground twice per stride, so the rider’s centre of mass rises and falls twice per stride. The dominant energy in the vertical acceleration signal is therefore at twice the stride frequency, which is the second harmonic (H2). In the canter, there are three distinct support phases per stride, making the third harmonic (H3) prominent. In the walk, all four beats are roughly equal, so energy is spread more evenly across harmonics.

This is not a heuristic. It follows directly from the physics of ground reaction forces. Each ground contact generates a vertical impulse that accelerates the body upward. The number and timing of these impulses per stride determines the frequency content of the vertical acceleration waveform.

The harmonic ratio approach is well-established in human gait biomechanics for assessing smoothness and symmetry. In human walking, a perfectly symmetrical gait produces only even harmonics in the anteroposterior and craniocaudal directions and only odd harmonics in the mediolateral direction. While this specific formulation has not been widely applied to equine gaits in the published literature, the underlying spectral decomposition principle is the same.

Combined with other features, the gaits separate cleanly across multiple dimensions simultaneously:

FeatureWalkTrotCanterGallop
H2 ratioLowHigh (1.2-2.5)MediumLow
H3 ratioLowLowHigh (1.0-2.0)Medium
XY coherenceLowHigh (0.7+)LowLow
Z-yaw coherenceLowLowHigh (0.6+)High
Spectral entropyLowLow-midMidHigh (0.6-0.9)

The XY coherence (forward versus lateral acceleration) captures left-right symmetry: high in trot because diagonal pairs produce mirror-image forces, low in canter because the gait is inherently asymmetric. The Z-yaw coherence (vertical versus rotational) captures vertical-rotational coupling: high in canter and gallop because the asymmetric footfall pattern induces a yawing motion synchronized with the vertical bounce.

Dynamic Similarity and Scaling

One complication is that horses of different sizes produce different frequencies for the same gait. This is predictable using the Froude number, a dimensionless parameter from fluid dynamics that Alexander adapted for animal locomotion: Fr = v^2 / (g * L), where v is speed, g is gravity, and L is leg length (approximated by height at the withers).

Alexander showed that animals of different sizes traveling at the same Froude number exhibit dynamically similar gaits, meaning their relative stride length (stride length / leg length) and duty factor are approximately constant. Animals typically transition from walk to trot around Fr = 1.0 and from trot to asymmetric gaits around Fr = 2.0-3.0.

A 2006 study in the Journal of Experimental Biology tested this directly in 21 horses ranging from 86 to 714 kg. At equal Froude numbers, the relative stride length and duty factor were independent of body mass, confirming that the scaling principle holds across the full range of horse sizes. This is the theoretical basis for using wither height to personalize gait detection parameters.

From Theory to Sensors

With this mathematical framework in mind, I set out to see whether the sensors in an iPhone and Apple Watch worn by the rider could capture these signatures. Both devices contain accelerometers, gyroscopes, and magnetometers, and Apple’s CoreMotion framework provides fused data including a gravity-free acceleration vector and a device attitude quaternion at 100 Hz. GPS provides a secondary speed constraint at roughly 1 Hz.

The Rider-Mounted Sensor Question

Most published equine gait analysis uses sensors mounted directly on the horse: on the poll, withers, sacrum, or limbs. The Lameness Locator uses accelerometers on the head and sacrum. The EquiMoves system uses eight IMUs across the body. These placements give direct measurements of the horse’s motion.

My approach uses rider-mounted sensors instead. A 2023 study by Davidsson et al., published in Animals, showed that a phone in the rider’s pocket can classify five Icelandic horse gaits with 94.4% accuracy using a Bi-LSTM model. A 2025 study testing rider-worn accelerometers at four body locations (knee, backbone, chest, arm) achieved 89.7-98.3% accuracy depending on the amount of training data.

The trade-off is clear. Horse-mounted sensors give cleaner signals and can detect subtleties like individual limb timing. Rider-mounted sensors are practical (no equipment on the horse, no risk of interference with natural movement) but measure the horse’s motion indirectly, filtered through the rider’s body. The rider’s own movements (posting the trot, shifting weight, arm motion) become a confounding signal.

Research has shown that riders measurably affect horse kinematics. Rising trot induces asymmetry in back movement that mimics a push-off lameness in the hind limb of the sitting diagonal. Rider posture asymmetry produces asymmetric saddle forces. These effects mean my system is measuring a horse-rider system, not the horse alone.

Coordinate Transformation

The phone sits in a pocket at an arbitrary orientation, so raw accelerometer axes are meaningless. I built a FrameTransformer that uses the attitude quaternion from CoreMotion to rotate the acceleration into a horse-relative frame where Z is vertical, X is forward-back, and Y is left-right. It auto-calibrates after 0.5 seconds of data and monitors for drift, flagging if the phone moves more than 20 degrees from its calibrated orientation.

Windowing

Horse gaits have stride frequencies as low as 0.8 Hz (walk), so windows must be long enough to capture at least two full strides. I use a 256-sample sliding window at 100 Hz, giving 2.56 seconds per window with a new FFT computed every 0.25 seconds. This provides roughly four classification updates per second.

Stage 1: Spectral Analysis

The first stage of the classifier is an FFTProcessor that runs a real FFT via Apple’s Accelerate framework on each window.

Stride frequency is found as the dominant peak in the vertical power spectrum between 0.5 and 6 Hz. Sub-bin accuracy is achieved via quadratic interpolation across the peak and its neighbors.

Harmonic ratios H2 and H3 are computed as the power at 2x and 3x the stride frequency divided by the power at the stride frequency itself. As discussed above, these are the primary discriminators: a strong H2 points to trot (two vertical oscillations per stride), a strong H3 points to canter (three support phases per stride).

Spectral entropy measures how spread out the energy is across frequencies, on a scale of 0 to 1. Walk and trot have clean, concentrated energy (low entropy). Gallop is chaotic and distributed (high entropy), reflecting the breakdown of regular periodic structure at high speed.

Coherence between signal pairs is computed using a Welch method with 128-sample segments. X-Y coherence (forward versus lateral) measures left-right symmetry. Z-yaw coherence (vertical versus rotational) measures vertical-rotational coupling.

For canter lead detection, a Hilbert transform extracts the instantaneous phase of the lateral acceleration and yaw rate. The phase difference tells you which leg is leading: approximately +90 degrees for left lead, -90 degrees for right lead. This is a novel aspect of the approach; the published literature on canter lead detection from IMU sensors is sparse, with most systems focusing on lameness at trot rather than lead identification at canter.

Stage 2: Hidden Markov Model

The spectral features are good discriminators but noisy when used alone. If I classified each window independently, the display would flicker between gaits constantly. The second stage solves this with a GaitHMM that enforces physically valid transitions using a Bayesian state machine.

The use of HMMs for equine gait analysis has direct precedent. Pfau et al. (2008) applied HMMs to trunk-mounted inertial sensor data in galloping Thoroughbreds and achieved 91-97% stride detection accuracy, noting that HMMs are easy to implement and produce consistent results with limited training data.

The HMM has five states: stationary, walk, trot, canter, and gallop. Only adjacent transitions are allowed:

Stationary <-> Walk <-> Trot <-> Canter <-> Gallop

This constraint reflects the physical reality that a horse must pass through intermediate gaits. The self-transition probability is 0.90, meaning the model resists changing state without sustained evidence. In dressage mode this increases to 0.95, since collected work involves more subtle gait variations that should not trigger false transitions.

Each feature is modelled as a Gaussian distribution per gait state. The log-probabilities from all features are summed (working in log-space avoids floating point underflow with small probability products). The forward algorithm propagates state probabilities over time:

a(t,j) = [sum over i: a(t-1,i) * A(i,j)] * B(j, observation)

where A is the transition matrix and B is the emission probability. The result is normalised at each step. A gait change is only committed when the new state exceeds 0.7 probability, which prevents spurious transitions from brief signal anomalies.

GPS speed acts as a post-emission sanity constraint. Each gait has expected speed bounds:

GaitSpeed range
Stationary0 m/s
Walk0.4-1.7 m/s (1.5-6 km/h)
Trot1.7-3.5 m/s (6-12.5 km/h)
Canter3.5-5.5 m/s (12.5-20 km/h)
Gallop> 5.5 m/s (> 20 km/h)

Note that these speed ranges for rider-perceived gaits are lower than the biomechanical literature reports for horses measured on treadmills (e.g., dressage horses trot at 3.2-4.9 m/s). This is because the speeds above represent GPS-measured ground speed of a ridden horse, which includes the effects of turns, circles, and collected work that reduce average speed below the horse’s straight-line potential.

If the GPS speed contradicts the spectral classification, the HMM penalises the unlikely state. The penalty strength scales with GPS accuracy: strong when accuracy is below 5 metres, negligible when accuracy exceeds 50 metres. This means the system trusts GPS in open fields but gracefully ignores it under tree cover or inside an indoor arena where GPS wanders.

Personalisation Through Dynamic Similarity

As discussed in the scaling section, a 12-hand Shetland pony and a 17-hand warmblood produce very different sensor readings even in the same gait. The Froude number framework predicts this: shorter legs mean higher stride frequencies and shorter strides for the same gait at the same Froude number.

I built a horse profile system with biomechanical priors for over 30 breeds. Each breed has custom expected frequency ranges, stride length coefficients, and engagement baselines derived from the dynamic similarity principle. These priors shift the HMM’s emission distributions so that a pony trotting at 3.5 Hz is correctly classified, where the same frequency from a warmblood would suggest canter.

Individual horses can be further tuned with per-horse adjustments: a frequency offset of up to 0.5 Hz, custom speed bounds for each gait, a transition stickiness multiplier, and a canter sensitivity control. Young and senior horses automatically get wider thresholds, reflecting the observation that gait regularity varies with age and joint stiffness. Vertical RMS is normalised by the horse’s weight so that a heavy horse does not register artificially high energy readings.

The stride length calculation uses the formula: stride = k * height * (RMS(Z) / g)^0.25, where height is measured at the withers, RMS(Z) is the vertical acceleration amplitude, g is gravity, and k is a gait-specific coefficient adjusted per breed (approximately 2.2 for walk up to 4.0 for gallop). This is informed by the dynamic similarity research showing that relative stride length scales predictably with the Froude number across horse sizes.

Biomechanics Beyond Gait Classification

The same sensor data that classifies gaits also contains information about the quality of the horse’s movement:

Symmetry and lameness proxy. In trot, a sound horse produces symmetric left-right acceleration profiles. Any persistent difference between left and right diagonal pairs shows up as a bias in lateral acceleration RMS. While a rider-mounted phone cannot match the sub-millimetre sensitivity of dedicated veterinary systems like the Lameness Locator (which measures head and pelvic vertical displacement directly), it can flag gross asymmetries that warrant professional assessment. Research has shown that even experienced veterinarians have poor inter-observer agreement when subjectively scoring mild lameness, making any objective measurement valuable.

Rhythm and regularity. The coefficient of variation of stride-to-stride timing measures how consistent the horse’s rhythm is. A well-schooled horse in steady-state trot produces remarkably regular stride timing. Irregularity can indicate pain, tension, fatigue, or loss of balance. A recent study confirmed that all horse gaits are organised according to small-integer ratios: walk and trot exhibit an isochronous 1:1 structure, while canter is characterised by 1:1, 1:2, and 2:1 ratios between its three beats.

Impulsion and engagement. Forward acceleration at the stride frequency, normalised by vertical acceleration and scaled by breed and height, provides a proxy for impulsion, the energetic forward thrust that riders and trainers seek. Higher impulsion means the horse is pushing more powerfully from behind.

Rein balance. Persistent lateral acceleration bias indicates the horse is carrying more weight to one side. This can result from the rider’s asymmetry, the horse’s natural crookedness, or uneven rein contact.

Canter lead consistency. Tracking lead changes over a session reveals whether the horse maintains its lead through corners and circles or drops leads unexpectedly.

The Data Flow

The complete pipeline flows as follows:

MotionManager (100Hz) -> GaitAnalyzer
                           |-- FrameTransformer (quaternion -> horse frame)
                           |-- FFTProcessor (256-sample window -> feature vector)
                           |-- GaitHMM (feature vector -> gait state + confidence)
                           |-- GaitSegment creation (on gait change)
                                |
                         RideTracker (orchestrator)
                           |-- Live UI properties (currentGait, confidence, etc.)
                           |-- Ride model (gaitSegments relationship)

Each GaitSegment stores the gait type, stride frequency, harmonic ratios, entropy, coherence, stride length, lead (left or right for canter), rhythm score, and biomechanical metrics including impulsion and engagement.

What the Apple Watch Adds

The Apple Watch on the rider’s wrist captures something the phone in a pocket cannot: how the rider’s arm moves. In a balanced trot, both arms should move symmetrically. In canter, the inside arm naturally moves differently from the outside. The watch’s accelerometer and gyroscope provide an arm symmetry score and yaw energy measurement that feed into the feature vector alongside the phone’s body-centre data.

This dual-sensor approach is unusual in the published literature. Most studies use either horse-mounted IMUs or a single phone. The combination of seat-level data (phone) with arm-level data (watch) provides two measurement points on the rider without any equipment on the horse. A 2020 study in Pervasive and Mobile Computing compared a smartwatch on the saddle versus the rider’s wrist and found only a negligible accuracy difference, suggesting that rider-worn sensors are a viable alternative to direct horse attachment.

What I Have Learned So Far

This project has taught me that the gap between “this should work in theory” and “this works on a moving horse” is substantial. Horses are not machines; they drift between gaits, they stumble, they spook sideways. The rider shifts their weight, adjusts their position, posts the trot. All of this shows up in the sensor data as noise that the system needs to handle gracefully.

The two-stage classifier has been the most important architectural decision. The FFT stage provides rich discriminative features grounded in the physics of oscillatory motion. The HMM stage turns noisy per-window classifications into stable, physically coherent gait tracking. The 0.90 self-transition probability and 0.7 confidence threshold together mean the system settles into states and transitions cleanly, matching what the rider actually feels.

The published literature is trending toward deep learning approaches (LSTM and 1D CNN models) applied to raw sensor data, and these achieve high classification accuracy (94-97%). However, they require large labelled training datasets, offer limited interpretability, and can be prone to overfitting on small equine datasets. The physics-informed feature extraction approach I have taken requires less data, produces interpretable intermediate results (you can inspect the harmonic ratios and coherence values to understand why a classification was made), and runs efficiently on mobile hardware using Apple’s vDSP framework.

I have also learned to respect the constraints of mobile processing. Running FFTs, coherence calculations, and Hilbert transforms four times per second on a phone is feasible only because Apple’s Accelerate framework offloads the heavy computation to dedicated hardware. A naive implementation in pure Swift would drain the battery in minutes.

What Is Next

The system currently detects gaits, computes stride metrics, identifies canter leads, and measures basic symmetry. There is much more I want to explore: transition quality scoring, training load accumulation, rhythm consistency tracking, and using the data over multiple sessions to spot trends in a horse’s way of going. The mathematics says these should all be derivable from the same sensor data. Whether the real-world signal quality is good enough remains to be seen.

If nothing else, this project has given me a completely new way of thinking about riding. Every stride is data, every transition is a state change, and every horse is a beautiful, complicated oscillator.

References

  • Hoyt, D. F. & Taylor, C. R. (1981). Gait and the energetics of locomotion in horses. Nature, 292, 239-240.
  • Robilliard, J. J., Pfau, T. & Wilson, A. M. (2007). Gait characterisation and classification in horses. Journal of Experimental Biology, 210(2), 187-197.
  • Pfau, T., Ferrari, M., Parsons, K. & Wilson, A. (2008). A hidden Markov model-based stride segmentation technique applied to equine inertial sensor trunk movement data. Journal of Biomechanics, 41(1), 216-220.
  • Braganca, F. M. et al. (2020). Improving gait classification in horses by using inertial measurement unit generated data and machine learning. Scientific Reports, 10, 17379.
  • Davidsson, H. B. et al. (2023). Efficient development of gait classification models for five-gaited horses based on mobile phone sensors. Animals, 13(1), 183.
  • Griffin, T. M. et al. (2006). Dynamically similar locomotion in horses. Journal of Experimental Biology, 209(3), 455-465.
  • Owaki, D. et al. (2017). A quadruped robot exhibiting spontaneous gait transitions from walking to trotting to galloping. Scientific Reports, 7, 277.
  • Andersson, L. S. et al. (2012). Mutations in DMRT3 affect locomotion in horses and spinal circuit function in mice. Nature, 488, 642-646.