---
title: "Big Data Derby 2022"
subtitle: "Data Analysis"
output:
  html_document:
    toc_depth: 5
    number_sections: true
    df_print: paged
    code_folding: hide
    css: ../input/css-rmd/estilo.css
    code_download: true
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, eval = TRUE, fig.align = "center",
                      fig.width = 5.5, fig.height = 4.5, warning = FALSE,
                      message = FALSE)
```



# Competition

- [Big Data Derby 2022](https://www.kaggle.com/competitions/big-data-derby-2022/overview)

<center>
<img src = "https://github.com/competencias-dataScience/images-derby/blob/main/derby_kaggle.png?raw=true" width = 500/>
</center>

#  Team of collaborators

- [Edimer David Jaramillo](https://www.kaggle.com/edimer)
- [Paola Betancur García](https://www.kaggle.com/pabega)

# Supporting Information

- [Script of R with data processing](https://www.kaggle.com/code/edimer/dataprocessing-nyra?scriptVersionId=110641160)
- [Glossary](https://www.kaggle.com/datasets/edimer/glosary-variables)
- [Data full obtained with preview above](https://www.kaggle.com/datasets/edimer/nyra-full-complete)

# Notebook configuration

## Libraries

- The libraries used for the complete execution of the notebook are detailed below.

```{r}
# Data manipulate and graphics
library(tidyverse)
library(data.table)
library(lubridate)
library(gganimate)
library(hrbrthemes)
library(readxl)
library(latex2exp)


# Distance geospataial and modeling
library(geosphere)
library(splines)
library(corrr)

# Print data frames
library(DT)
```

## Theme and colors

- The theme is configured for all graphics and the color palette to use.

```{r}

# Theme and colors
theme_black <- theme_modern_rc() + theme(
  legend.position = "top",
  strip.text = element_text(colour = 'white', size = 10),
  axis.text.x = element_text(size = 7),
  axis.text.y = element_text(size = 7),
  legend.key.width = unit(0.5, 'cm')
)

colores <-
  c("#00674a",
    "#d8a91d",
    "#ebebeb",
    "#2f8bd2",
    "#c2541d",
    "#ca1b1d")
```

# Introduction

Hundreds of horse races have been held over time, and there is currently a concern for the welfare of these animals. In this industry, the breeding of a large number of horses is required and there is a high turnover of these due to loss of performance, diseases, injuries, among others. Knowledge of the influence of other types of factors on animal welfare and horse performance could help predict or determine the conditions in which the individual is found. Some of these factors are the climatic conditions at the time of the race, and biological and physical aspects. For example, various researchers have studied the effect of speed variation over time in thoroughbred racing. In this case, it has been found that in short races, a higher speed at the beginning and at the end could be optimal; in medium-distance races, a better result has been observed when a constant rhythm is maintained, while in endurance races it has been considered that a constant speed, or even a gradual reduction, could favor the animal, thus trying to maintain homeostasis (self-regulation). of the organism). Under this premise, our objective was to analyze the variability in the acceleration of the horse through conventional statistical metrics, mechanical parameters and rates of change between positive and negative accelerations.

# Variables

```{r}
variables <- read_excel("../input/glosary-variables/Glosario.xlsx", sheet = "English") %>% 
  select(1:3) 
variables %>% 
  datatable(
    rownames = FALSE,
    extensions = c('Buttons', 'FixedColumns'),
    options = list(
      dom = 'Bfrtip',
      buttons = c('excel'),
      scrollX = TRUE,
      fixedColumns = list(leftColumns = 1)
    )
  )
```


# Methods

## Summary methods

<center>
<img src = "https://github.com/competencias-dataScience/images-derby/blob/main/img4.png?raw=true" width = 800/>
</center>

## Mathematical formulas

### Distance (d)

- [Spherical Trigonometry](https://en.wikipedia.org/wiki/Spherical_trigonometry)

<center>
<img src = "https://github.com/competencias-dataScience/images-derby/blob/main/img1.PNG?raw=true" width = 500/>
</center>

- The trigonometric function [*versine*](https://es.wikipedia.org/wiki/Verseno) is related to the [*semiverse*](https://es.wikipedia.org/wiki/F%C3%B3rmula_del_semiverseno) function, with which it is possible to calculate distances for spherical surfaces. In the particular case of the [*Haversine*](https://en.wikipedia.org/wiki/Haversine_formula) distance, given a [central angle](https://en.wikipedia.org/wiki/Central_angle) $theta$ between two points on a sphere (e.g., the earth):

$$\theta = \frac{d}{r}$$

Where:

- $d$ is the distance between two points
- $r$ is the radius of the sphere. **Note:** the radius of the earth used in the calculations is $6378137\ m$

The *haversine* ($h$) can be computed from the latitude ($\gamma$) and longitude ($phi$) of two points through the following expression:

$$h(\theta) = h(\gamma_2 -\gamma_1)+(1-h(\gamma_1 - \gamma_2)-h(\gamma_1 + \gamma_2)) \cdot h(\phi_2 - \phi_1)$$

The function *haversine ($h$)* applied to central angles as to differences (distances) between coordinates, is:

$$h(\theta) = sin^2 \left( \frac{\theta}{2} \right ) =  \frac{1-cos(\theta)}{2}$$

To obtain the distance $d$, we apply the [inverse](https://en.wikipedia.org/wiki/Versine#ahav) of the *haversine*:

$$d = h^{-1} = r\ archav(h) = 2r\ arcsin(\sqrt{h})$$

<center>
<img src = "https://github.com/competencias-dataScience/images-derby/blob/main/img2.PNG?raw=true" width = 500/>
</center>

### Displacement

- $D_{ai}$: accumulated displacement

$$D_{ai} =  \sum \left ( \frac{d_i}{\sum_{i}^{n}d_i} \right ) \rightarrow [0, 1]$$

- Since speed is the derivative of displacement (distance), the latter can be obtained by integrating the speed:

$$D(t) = \int_{0}^{t}\frac{dD}{dt}dt + D(0) \\
= \int_{0}^{t}S(t)dt + D(0) $$

### speed (S)

$$S =  \frac{\Delta D}{t}$$

- Since acceleration is the derivative of speed, the latter can be obtained by integrating the acceleration:

$$S(t) = \int_{0}^{t}\frac{dA}{dt}dt + A(0)$$

### Acceleration (A)

$$A =   \frac{\Delta S}{t} =  \frac{S_t - S_{t-1}}{t}$$

- To interpret the graph it is necessary to consider the following:

$$si\ S_{t} - S_{t-1} > 0 \rightarrow \ \Uparrow S \rightarrow +A$$

$$si\ S_{t} - S_{t-1} < 0 \rightarrow \ \Downarrow S \rightarrow -A$$

$$si\ S_{t} - S_{t-1} = 0 \rightarrow =S \rightarrow A = 0$$

- In formal terms it can be expressed as follows:

$$A(t) = \frac{dS}{dt}=\frac{d^2d}{dt^2}$$

### Drag Force and Power

- The [Reynolds number](https://www.grc.nasa.gov/www/k-12/airplane/reynolds.html) expresses the ratio between the inertial forces (resistance to change or motion) and the viscous forces present in the fluid ([see conservation of momentum in steady flows](https://www.grc.nasa.gov/www/k-12/airplane/conmo.html)). The [Reynolds number](https://es.wikipedia.org/wiki/N%C3%BAmero_de_Reynolds) is defined as follows:

$$Re = \frac{\rho L v}{\mu}$$

Where:

- $\rho$: density of air equal to $1.29 kg m^{-3}$.
- $L$: [*characteristic length*](https://es.wikipedia.org/wiki/Longitud_caracter%C3%ADstica) 
- $v$: speed in $m s^{-1}$$.
- $\mu$: dynamic viscosity of air equal to $17.4 × 10^{-6}$ $Pascal\ seconds$$.

The Reynolds number allows to establish whether a flow follows a laminar or turbulent pattern. When this number is greater than 1000 the [drag equation](https://www.grc.nasa.gov/www/k-12/rocket/drageq.html) provides an acceptable estimate of the drag force. The magnitude of the drag force is given by the following expression:


$$F = \frac{1}{2}C_d \rho Av^2$$

Where:

- $C_d$: [*drag coefficient*](https://www.grc.nasa.gov/www/k-12/rocket/dragco.html)
- $\rho$: air density equal to $1.29 kg m^{-3}$
- $A$: area frontal 
- $v^3$: speed

We can calculate the mechanical power required to overcome the *drag force* as follows:

$$P = \frac{1}{2}C_d \rho A v^3$$

Where:

- $C_d$: [*drag coefficient*](https://www.grc.nasa.gov/www/k-12/rocket/dragco.html).
- $\rho$:  air density equal to $1.29 kg m^{-3}$.
- $A$: frontal area 
- $v^3$: speed

## Derived variables

### Accumulated acceleration (%)

- To avoid that negative and positive numbers end up canceling each other out in the denominator of the above mathematical expression, it is proposed to calculate the accumulated acceleration with the square of the accelerations, thus ensuring that the result is bounded between 0 and 1:

$$A_{ai}^2 =  \sum \left ( \frac{A_i^2}{\sum_{i}^{n}A_i^2} \right ) \rightarrow [0, 1]$$

### Relative times

- To calculate the relative time ($tr$) we take each *trakus_index* and divide by the maximum:

$$tr_i = \frac{i}{max(i)}$$


### Rate acceleration

- We discretize the time of the run into $(n)$ equal parts, regardless of the number of trakus you have recorded in the cerrera. The rate we are calculating can be expressed as follows:

$$\lambda_i = \frac{max(|A_i|)}{min(|A_i|)}$$

Where $i = 1, 2, ...,n$ y $A$ is the acceleration.

$$If\ \lambda_i  > 1 \rightarrow \  A_+ > A_{-}$$

$$If\ \lambda_i  < 1 \rightarrow \  A_+ < A_{-}$$

$$If\ \lambda_i  \thickapprox 1 \rightarrow \  A_+ \thickapprox A_{-}$$

- We propose this metric as an important element of judgment to elucidate what is the optimal behavior of a horse in a race. To the extent that the horse manages to maintain a rate above 1, its results seem to be more favorable.


## Data

```{r}
data_complete <- read_rds("../input/nyra-full-complete/dataFull_speed_forces_energySpend.rds")
data_complete %>% head()
```


## Data processing

With the positions (latitude and longitude) of the horses, the distances were calculated through different methods. Finally we use the *haversine distance* for all our calculations, however we compare the results with different speeds (see methods). We calculate accelerations, drag force, power, energy expenditure, calories and digestible energy. All calculations are presented in the [Script of R with data processing.](https://www.kaggle.com/code/edimer/dataprocessing-nyra?scriptVersionId=110641160)

## Exploratory Data Analysis (EDA) 

- All our analyzes were aimed at evaluating the variation in the locomotion pattern of the horse. Based on the background of scientific articles found in the references, we set out to analyze the variation in the change of acceleration of horses.
- Descriptive metrics for the horse and jockey were summarized in a table that could be used to describe race characteristics.


# Results and discusion

## Statistical summary Horses

- General descriptive summary:

```{r}
data_complete %>% 
  group_by(track_id, race_date, race_number, horse_name) %>% 
  summarise(position_finish = unique(position_at_finish),
            distance_race = unique(distance_id),
            n_trakus = n(),
            time_race = n_trakus * 0.25,
            run_up_distance = unique(run_up_distance),
            post_time = unique(post_time),
            jockey = unique(jockey),
            purse = unique(purse),
            weight_carried = unique(weight_carried),
            track_condition = unique(track_condition),
            course_type = unique(course_type),
            race_type = unique(race_type),
            odds = unique(odds),
            tmax = unique(tmax),
            tmin = unique(tmin),
            tavg = unique(tavg)) %>% 
  ungroup() %>% 
  arrange(race_date) %>%
  mutate(across(where(is.numeric), round, digits = 2)) %>%
  unite(track_id, race_date, race_number,
        col = "new_id", sep = "/") %>% 
  datatable(
    rownames = FALSE,
    extensions = c('Buttons', 'FixedColumns'),
    options = list(
      dom = 'Bfrtip',
      buttons = c('excel'),
      scrollX = TRUE,
      fixedColumns = list(leftColumns = 3),
      language = list(url = '//cdn.datatables.net/plug-ins/1.10.11/i18n/Spanish.json')
    )
  )
```


 - Summary of the biomechanical pattern of the horse in racing

```{r}
data_complete %>% 
  group_by(track_id, race_date, race_number, horse_name) %>% 
  summarise(position = unique(position_at_finish),
            distance = unique(distance_id),
            average_displac = mean(dist_haversine, na.rm = TRUE),
            sd_displac = sd(dist_haversine, na.rm = TRUE),
            median_displac = median(dist_haversine, na.rm = TRUE),
            min_displac = min(dist_haversine, na.rm = TRUE),
            max_displac = max(dist_haversine, na.rm = TRUE),
            average_speed = mean(speed_haversine, na.rm = TRUE),
            median_speed = median(speed_haversine, na.rm = TRUE),
            sd_speed = sd(speed_haversine, na.rm = TRUE),
            min_speed = min(speed_haversine, na.rm = TRUE),
            max_speed = max(speed_haversine, na.rm = TRUE),
            average_acceler = mean(acceleration, na.rm = TRUE),
            median_acceler = median(acceleration, na.rm = TRUE),
            sd_acceler = sd(acceleration, na.rm = TRUE),
            min_acceler = min(acceleration, na.rm = TRUE),
            max_acceler = max(acceleration, na.rm = TRUE),
            rate_minmax_accel = abs(max_acceler) / abs(min_acceler)) %>% 
  ungroup() %>% 
  arrange(race_date) %>%
  mutate(across(where(is.numeric), round, digits = 2)) %>%
  unite(track_id, race_date, race_number,
        col = "new_id", sep = "/") %>% 
  datatable(
    rownames = FALSE,
    extensions = c('Buttons', 'FixedColumns'),
    options = list(
      dom = 'Bfrtip',
      buttons = c('excel'),
      scrollX = TRUE,
      fixedColumns = list(leftColumns = 3),
      language = list(url = '//cdn.datatables.net/plug-ins/1.10.11/i18n/Spanish.json')
    )
  )
```

## Trends Karak

### Displacement

```{r, fig.width=8}
data_complete %>% 
  filter(horse_name == "Karak") %>% 
  ggplot(aes(x = trakus_index, y = dist_haversine, color = new_id)) +
  geom_point(alpha = 0.5) +
  geom_smooth(method = "gam",
              formula = y ~ bs(x, df = 6),
              color = colores[5],
              se = FALSE) +
  geom_smooth(method = "gam",
              formula = y ~ ns(x, df = 6),
              color = colores[4],
              se = FALSE) +
  scale_color_manual(values = colores) +
  theme_black +
  labs(x = "Trakus index", y = "Distance (m)", color = "")
```


### Speed

```{r}
data_complete %>% 
  filter(horse_name == "Karak") %>% 
  ggplot(aes(x = time_relative, y = speed_haversine, color = new_id)) +
  geom_point(alpha = 0.5) +
  geom_smooth(method = "gam",
              formula = y ~ bs(x, df = 6),
              color = colores[5],
              se = FALSE) +
  geom_smooth(method = "gam",
              formula = y ~ ns(x, df = 6),
              color = colores[4],
              se = FALSE) +
  scale_color_manual(values = colores) +
  theme_black +
  labs(x = "Time relative", y = "Speed (m/s)", color = "")
```


### Acceleration

```{r}
data_complete %>% 
  filter(horse_name == "Karak") %>% 
  group_by(new_id) %>% 
  mutate(lag_speed = lag(speed_haversine, n = 1)) %>% 
  ungroup() %>% 
  mutate(acceleration = (speed_haversine - lag_speed) / 0.25) %>% 
  ggplot(aes(x = time_relative, y = acceleration, color = new_id)) +
  geom_line(aes(group = 1)) +
  geom_smooth(method = "gam",
              formula = y ~ bs(x, df = 3),
              color = colores[5],
              se = FALSE) +
  geom_hline(yintercept = 0, lty = 2, color = colores[4]) +
  scale_color_manual(values = colores) +
  theme_black +
  labs(x = "Time relative", y = "Acceleration (m/s2)", color = "")
```


### Drag Force (*N*)

```{r}
data_complete %>% 
  filter(horse_name == "Karak") %>% 
  group_by(new_id) %>% 
  mutate(lag_speed = lag(speed_haversine, n = 1)) %>% 
  ungroup() %>% 
  mutate(acceleration = (speed_haversine - lag_speed) / 0.25) %>% 
  ggplot(aes(x = time_relative, y = drag_force, color = new_id)) +
  geom_line(aes(group = 1)) +
  geom_smooth(method = "gam",
              formula = y ~ bs(x, df = 3),
              color = colores[5],
              se = FALSE) +
  scale_color_manual(values = colores) +
  theme_black +
  labs(x = "Time relative", y = "Force (N)", color = "")
```

### Spend Energy

```{r}
data_complete %>% 
  filter(horse_name == "Karak") %>% 
  group_by(new_id) %>% 
  mutate(lag_speed = lag(speed_haversine, n = 1)) %>% 
  ungroup() %>% 
  mutate(acceleration = (speed_haversine - lag_speed) / 0.25) %>% 
  ggplot(aes(x = time_relative, y = spend_energy, color = new_id)) +
  geom_line(aes(group = 1)) +
  geom_smooth(method = "gam",
              formula = y ~ bs(x, df = 3),
              color = colores[5],
              se = FALSE) +
  scale_color_manual(values = colores) +
  theme_black +
  labs(x = "Time relative", y = "Spend Energy (J)", color = "")
```

### Power (Kw)

```{r}
data_complete %>% 
  filter(horse_name == "Karak") %>% 
  group_by(new_id) %>% 
  mutate(lag_speed = lag(speed_haversine, n = 1)) %>% 
  ungroup() %>% 
  mutate(acceleration = (speed_haversine - lag_speed) / 0.25) %>% 
  ggplot(aes(x = time_relative, y = power_req, color = new_id)) +
  geom_line(aes(group = 1)) +
  geom_smooth(method = "gam",
              formula = y ~ bs(x, df = 3),
              color = colores[5],
              se = FALSE) +
  scale_color_manual(values = colores) +
  theme_black +
  labs(x = "Time relative", y = "Power required", color = "")
```

### Calories (J)

```{r}
data_complete %>% 
  filter(horse_name == "Karak") %>% 
  group_by(new_id) %>% 
  mutate(lag_speed = lag(speed_haversine, n = 1)) %>% 
  ungroup() %>% 
  mutate(acceleration = (speed_haversine - lag_speed) / 0.25) %>% 
  ggplot(aes(x = time_relative, y = calories, color = new_id)) +
  geom_line(aes(group = 1)) +
  geom_smooth(method = "gam",
              formula = y ~ bs(x, df = 3),
              color = colores[5],
              se = FALSE) +
  scale_color_manual(values = colores) +
  theme_black +
  labs(x = "Time relative", y = "Calories", color = "")
```

## Locomotion heterogeneity

```{r}
data_complete %>% 
  filter(horse_name == "Karak") %>% 
  group_by(new_id) %>% 
  mutate(lag_speed = lag(speed_haversine, n = 1)) %>% 
  ungroup() %>% 
  mutate(acceleration = (speed_haversine - lag_speed) / 0.25) %>% 
  ggplot(aes(x = trakus_index, y = acceleration, color = new_id)) +
  facet_wrap(~new_id) +
  geom_line() +
  geom_smooth(method = "gam",
              formula = y ~ bs(x, df = 3),
              color = colores[5],
              se = FALSE) +
  geom_hline(yintercept = 0, lty = 2, color = colores[4]) +
  scale_color_manual(values = colores) +
  theme_black +
  theme(legend.position = "none") +
  labs(x = "Trakus index", y = "Acceleration (m/s2)", color = "")
```


### Accumulated acceleration (1)

```{r}
data_complete %>% 
  filter(horse_name == "Karak") %>% 
  group_by(new_id) %>%
  mutate(time_relative = trakus_index / max(trakus_index)) %>%
  ungroup() %>% 
  filter(!is.na(acceleration)) %>% 
  group_by(new_id) %>% 
  mutate(accel_percent = acceleration^2 / sum(acceleration^2),
         accel_acum = cumsum(accel_percent)) %>% 
  ungroup() %>% 
  ggplot(aes(x = time_relative, y = accel_acum, color = new_id)) +
  geom_line() +
  scale_color_manual(values = colores) +
  labs(x = "Time relative (%)", y = "Cumulative acceleration (m/s2)2",
       color = "") +
  theme_black +
  geom_vline(xintercept = 0.3333333, color = "white", lty = 2) + 
  geom_vline(xintercept = 0.7333333, color = "white", lty = 2)
```


### Accumulated acceleration (2)

```{r}
data_complete %>% 
  filter(horse_name == "Karak") %>% 
  group_by(new_id) %>%
  ungroup() %>% 
  filter(!is.na(acceleration)) %>% 
  group_by(new_id) %>% 
  mutate(accel_percent = acceleration^2 / sum(acceleration^2),
         accel_acum = cumsum(accel_percent)) %>% 
  ungroup() %>% 
  ggplot(aes(x = time_relative, y = acceleration, color = type_accel)) +
  facet_wrap(~new_id) +
  geom_line(aes(group = type_accel)) +
  scale_color_manual(values = colores) +
  labs(x = "Time relative (%)", y = "Cumulative acceleration (m/s2)2",
       color = "") +
  theme_black 
```


### Accumulated acceleration (3)

```{r}
data_complete %>% 
  filter(horse_name == "Karak") %>% 
  group_by(new_id) %>%
  ungroup() %>% 
  filter(!is.na(acceleration)) %>% 
  ggplot(aes(x = time_relative, y = acceleration, color = type_accel)) +
  facet_wrap(~new_id) +
  geom_line(aes(group = type_accel), alpha = 0.4) +
  geom_smooth(method = "gam",
              formula = y ~ bs(x, df = 10),
              se = TRUE) +
  scale_color_manual(values = colores) +
  labs(x = "Time relative (%)", y = "Acceleration (m/s2)",
       color = "") +
  theme_black 
```


### Acceleration rate  (n = 10)

```{r}
data_complete %>% 
  filter(horse_name == "Karak") %>% 
  group_by(new_id) %>%
  mutate(cut_timerelat = as.numeric(cut(time_relative, breaks = 10, include.lowest = TRUE,
                             right = FALSE))) %>%
  ungroup() %>% 
  group_by(cut_timerelat, new_id) %>% 
  summarise(min_acceler = min(acceleration, na.rm = TRUE),
            max_acceler = max(acceleration, na.rm = TRUE),
            rate_minmax_accel = abs(max_acceler) / abs(min_acceler),
            N = n()) %>% 
  ungroup() %>% 
  ggplot(aes(x = cut_timerelat, y = rate_minmax_accel)) +
  geom_line(aes(color = new_id, group = new_id)) +
  scale_y_log10() +
  scale_color_manual(values = colores) +
  scale_x_continuous(n.breaks = 10) +
  geom_hline(yintercept = 1, lty = 2, color = "gray60") +
  labs(x = "Snippet race", y = TeX(r'($\lambda_1 (ms^{-2})$)'),
       color = "") +
  theme_black
```

### Acceleration rate  (n = 30)

```{r}
data_complete %>% 
  filter(horse_name == "Karak") %>% 
  group_by(new_id) %>%
  mutate(cut_timerelat = as.numeric(cut(time_relative, breaks = 30, include.lowest = TRUE,
                             right = FALSE))) %>%
  ungroup() %>% 
  group_by(cut_timerelat, new_id) %>% 
  summarise(min_acceler = min(acceleration, na.rm = TRUE),
            max_acceler = max(acceleration, na.rm = TRUE),
            rate_minmax_accel = abs(max_acceler) / abs(min_acceler),
            N = n()) %>% 
  ungroup() %>% 
  ggplot(aes(x = cut_timerelat, y = rate_minmax_accel)) +
  geom_line(aes(color = new_id, group = new_id)) +
  scale_y_log10() +
  scale_color_manual(values = colores) +
  scale_x_continuous(n.breaks = 10) +
  geom_hline(yintercept = 1, lty = 2, color = "gray60") +
  labs(x = "Snippet race", y = TeX(r'($\lambda_1 (ms^{-2})$)'),
       color = "") +
  theme_black
```

### Average variation (n = 10)

```{r}
table_sup <- 
  data_complete %>% 
  filter(horse_name == "Karak") %>% 
  group_by(new_id) %>%
  mutate(cut_timerelat = as.numeric(cut(time_relative, breaks = 10, include.lowest = TRUE,
                             right = FALSE))) %>%
  ungroup() %>% 
  filter(!is.na(acceleration)) %>% 
  group_by(cut_timerelat, new_id) %>% 
  summarise(average_speed = mean(speed_haversine, na.rm = TRUE)) %>% 
  ungroup()

data_complete %>% 
  filter(horse_name == "Karak") %>%  
  mutate(type_accel = if_else(type_accel == "+",
                              true = "Positive",
                              false = "Negative")) %>%                                                 
  group_by(new_id) %>%
  mutate(cut_timerelat = as.numeric(cut(time_relative, breaks = 10, include.lowest = TRUE,
                             right = FALSE))) %>%
  ungroup() %>% 
  filter(!is.na(acceleration)) %>% 
  group_by(cut_timerelat, new_id, type_accel) %>% 
  summarise(average_accel = mean(abs(acceleration))) %>% 
  ungroup() %>% 
  pivot_wider(names_from = type_accel, values_from = average_accel) %>% 
  mutate(rate_avg_accel = Positive / Negative) %>% 
  left_join(x = ., y = table_sup) %>% 
  ggplot(aes(x = cut_timerelat, y = rate_avg_accel, color = average_speed)) +
  facet_grid(~new_id) +
  geom_point(size = 1.5) +
  geom_line(aes(group = new_id)) +
  scale_color_viridis_c() +
  scale_y_log10() +
  # scale_x_log10() +
  geom_hline(yintercept = 1, lty = 2, color = "gray60") +
  labs(x = "Snippet race", y = "lambda",
       color = "Speed") +
  theme_black
```


## Associations

### Lag Acceleration

```{r}
data_complete %>% 
  filter(horse_name == "Karak") %>% 
  group_by(new_id) %>%
  mutate(lag_accel = lag(acceleration, n = 1)) %>% 
  ggplot(aes(x = lag_accel, y = acceleration, color = time_relative)) +
  facet_wrap(~new_id, scales = "free") +
  geom_point(alpha = 0.5) +
  scale_color_viridis_c() +
  geom_smooth(method = "lm", color = colores[3]) +
  labs(x = "Acceleration (m/s2)  - Lag(1)", y = "Acceleration (m/s2)",
       color = "") +
  theme_black
```

# References

- **scientific article**
  -   [Speed, pacing strategy and aerodynamic drafting in Thoroughbred horse racing](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3391435/)
  -   [Equine Energetics. II. Energy Expenditure in Horses During Submaximal Exercise](https://academic.oup.com/jas/article-lookup/doi/10.2527/jas1986.633822x)
  -   [Changes in Thoroughbred speed and stride characteristics over successive race starts and their association with musculoskeletal injury](https://beva.onlinelibrary.wiley.com/doi/full/10.1111/evj.13581)
  -   [The energy requirements of racehorses in training](https://pubmed.ncbi.nlm.nih.gov/33367221/)
  -   [Energy requirements of a racehorse](https://hygain.com.au/blogs/library/energy-requirements-racehorse)
  -   [External mechanical work in the galloping racehorse](https://royalsocietypublishing.org/doi/10.1098/rsbl.2018.0709)
  - [Speed and incline during thoroughbred horse racing: racehorse speed supports a metabolic power constraint to incline running but not to decline running](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3424062/)  
  - [Optimal speed in Thoroughbred horse racing](https://journals.plos.org/plosone/article?id=10.1371/journal.pone.0235024) 
  - [The effect of curve running on distal limb kinematics in the Thoroughbred racehorse](https://journals.plos.org/plosone/article?id=10.1371/journal.pone.0244105#:~:text=Running%20on%20a%20curve%20leads,smaller%20radius%20of%20the%20curve.)
  - [Aerodynamic drag in cycling: Methods of assessment](https://www.researchgate.net/publication/51660070_Aerodynamic_drag_in_cycling_Methods_of_assessment)
- **Posts (blogs):**
  -   [Risk factors for equine fractures in Thoroughbred flat racing in North America](https://www.sciencedirect.com/science/article/abs/pii/S0167587716306535)
  -   [New York Task Force on Racehorse Health and Safety](https://www.gaming.ny.gov/pdf/NY%20Task%20Force%20on%20Racehorse%20Health%20and%20Safety.pdf)
  - [Biomechanics of locomotion in the athletic horse](https://veteriankey.com/biomechanics-of-locomotion-in-the-athletic-horse/)
- **Physical and mathematical support material (NASA):**
  - [The Drag Equation](https://www.grc.nasa.gov/www/k-12/rocket/drageq.html)
  - [Falling Object with Air Resistance](https://www1.grc.nasa.gov/beginners-guide-to-aeronautics/falling-object-with-air-resistance/)
  - [Motion of Free Falling Object](https://www1.grc.nasa.gov/beginners-guide-to-aeronautics/motion-of-free-falling-object/#:~:text=An%20object%20that%20falls%20through,Newton's%20second%20law%20of%20motion.)
  - [Reynolds Number](https://www.grc.nasa.gov/www/k-12/airplane/reynolds.html)  
