# Fitting Step-Selection Functions with `amt`

#### Johannes Signer

#### 2023-03-28

## About

This vignette briefly introduces how one can fit a Step-Selection Function (SSF) with the `amt` package. We will be using the example data of one red deer from northern Germany and one covariate: a forest cover map. For a more through discussion see also Fieberg et al. 20201 and supplement B.

## Getting the data ready

First we load the required libraries and the relocation data (called `deer`)

    library(lubridate)
    library(amt)
    data("deer")
    deer

    ## # A tibble: 826 × 4
    ##          x_       y_ t_                  burst_
    ##  *    <dbl>    <dbl> <dttm>               <dbl>
    ##  1 4314068. 3445807. 2008-03-30 00:01:47      1
    ##  2 4314053. 3445768. 2008-03-30 06:00:54      1
    ##  3 4314105. 3445859. 2008-03-30 12:01:47      1
    ##  4 4314044. 3445785. 2008-03-30 18:01:24      1
    ##  5 4313015. 3445858. 2008-03-31 00:01:23      1
    ##  6 4312860. 3445857. 2008-03-31 06:01:45      1
    ##  7 4312854. 3445856. 2008-03-31 12:01:11      1
    ##  8 4312858. 3445858. 2008-03-31 18:01:55      1
    ##  9 4312745. 3445862. 2008-04-01 00:01:24      1
    ## 10 4312651. 3446024. 2008-04-01 06:00:54      1
    ## # … with 816 more rows

In order to continue, we need a regular sampling rate. To check the current sampling rate, we use `summarize_sampling_rate`:

    summarize_sampling_rate(deer)

    ## # A tibble: 1 × 9
    ##     min    q1 median  mean    q3   max    sd     n unit
    ##   <dbl> <dbl>  <dbl> <dbl> <dbl> <dbl> <dbl> <int> <chr>
    ## 1  5.96  6.00   6.01  11.5  6.02 3924.  137.   825 hour

The median sampling rate is 6h, which is what we aimed for.

Next, we have to get the environmental covariates. A forest layer is included in the package. Note, that this a regular `SpatRast`.

    sh_forest <- get_sh_forest()
    sh_forest

    ## class       : SpatRaster
    ## dimensions  : 720, 751, 1  (nrow, ncol, nlyr)
    ## resolution  : 25, 25  (x, y)
    ## extent      : 4304725, 4323500, 3437725, 3455725  (xmin, xmax, ymin, ymax)
    ## coord. ref. : +proj=laea +lat_0=52 +lon_0=10 +x_0=4321000 +y_0=3210000 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs
    ## source(s)   : memory
    ## name        : forest
    ## min value   :      0
    ## max value   :      1

## Prepare Data for SSF

### Steps

Before fitting a SSF we have to do some data preparation. First, we change from a point representation to a step representation, using the function `steps_by_burst`, which in contrast to the `steps` function accounts for bursts.

    ssf1 <- deer |> steps_by_burst()

### Control/random steps

The generic function `random_steps` provides a methods for a `track_xy*`, where each observed step is paired with `n_control` control steps (i.e., steps that share the same starting location but have different turn angles and step lengths). The distributions for drawing step lengths and turning angles are usually obtained by fitting known parametric distribution to the observed step length and turn angles.

The function `random_steps` has seven arguments. For most use cases the defaults are just fine, but there might situation where the user wants to adjust some of the arguments. The arguments are:

1. `x`: This is the `track_xy*` for which the random steps are created. That is, for each step in `x` `n_control` random steps are created.
2. `n_control`: The number of random steps that should be created for each observed step.
3. `sl_distr`: This is the distribution of the step lengths. By default a gamma distribution is fit to the observed step lengths of the `x`. But any `amt_distr` is suitable here. 2
4. `ta_distr`: This is the turn angle distribution, with the default being a von Mises distribution.
5. `rand_sl`: These are the random step lengths, by default 1e5 random numbers from the distribution fitted in 33.
6. `rand_ta`: These are the random turn angles, by default 1e4 random numbers from the distribution fitted in 4.
7. `include_observed`: This argument is by default `TRUE` and indicates if the observed steps should be included or not.

#### The default situation

In most situations the following code snippet should work4.

    ssf1 <- ssf1 |> random_steps(n_control = 15)

#### A exponential distribution for step lengths

todo

### Extract covariates

As a last step, we have to extract the covariates at the end point of each step. We can do this with `extract_covariates`.

    ssf1 <- ssf1 |> extract_covariates(sh_forest)

Since the forest layers is coded as `1 = forest` and `2 != forest`, we create a factor with appropriate levels. We also calculate the log of the step length and the cosine of the turn angle, which we may use later for a integrated step selection function.

    ssf1 <- ssf1 |>
      mutate(forest = factor(forest, levels = 1:0, labels = c("forest", "non-forest")),
             cos_ta = cos(ta_),
            log_sl = log(sl_))

## Fitting SSF

Now all pieces are there to fit a SSF. We will use `fit_clogit`, which is a wrapper around `survival::clogit`.

    m0 <- ssf1 |> fit_clogit(case_ ~ forest + strata(step_id_))
    m1 <- ssf1 |> fit_clogit(case_ ~ forest + forest:cos_ta + forest:log_sl + log_sl * cos_ta + strata(step_id_))
    m2 <- ssf1 |> fit_clogit(case_ ~ forest + forest:cos_ta + forest:log_sl + log_sl + cos_ta + strata(step_id_))
    summary(m0)

    ## Call:
    ## coxph(formula = Surv(rep(1, 12144L), case_) ~ forest + strata(step_id_),
    ##     data = data, method = "exact")
    ##
    ##   n= 12144, number of events= 759
    ##
    ##                     coef exp(coef) se(coef)      z Pr(>|z|)
    ## forestnon-forest -0.5108    0.6000   0.1085 -4.708 2.51e-06 ***
    ## ---
    ## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
    ##
    ##                  exp(coef) exp(-coef) lower .95 upper .95
    ## forestnon-forest       0.6      1.667    0.4851    0.7422
    ##
    ## Concordance= 0.529  (se = 0.007 )
    ## Likelihood ratio test= 21.51  on 1 df,   p=4e-06
    ## Wald test            = 22.16  on 1 df,   p=3e-06
    ## Score (logrank) test = 22.26  on 1 df,   p=2e-06

    summary(m1)

    ## Call:
    ## coxph(formula = Surv(rep(1, 12144L), case_) ~ forest + forest:cos_ta +
    ##     forest:log_sl + log_sl * cos_ta + strata(step_id_), data = data,
    ##     method = "exact")
    ##
    ##   n= 12144, number of events= 759
    ##
    ##                             coef exp(coef) se(coef)      z Pr(>|z|)
    ## forestnon-forest         0.76794   2.15533  0.32705  2.348 0.018869 *
    ## log_sl                   0.16276   1.17675  0.04928  3.303 0.000957 ***
    ## cos_ta                  -0.23534   0.79030  0.20481 -1.149 0.250534
    ## forestnon-forest:cos_ta -0.26713   0.76557  0.11822 -2.260 0.023844 *
    ## forestnon-forest:log_sl -0.24073   0.78605  0.05745 -4.191 2.78e-05 ***
    ## log_sl:cos_ta            0.01519   1.01531  0.03424  0.444 0.657310
    ## ---
    ## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
    ##
    ##                         exp(coef) exp(-coef) lower .95 upper .95
    ## forestnon-forest           2.1553     0.4640    1.1353    4.0917
    ## log_sl                     1.1768     0.8498    1.0684    1.2961
    ## cos_ta                     0.7903     1.2653    0.5290    1.1807
    ## forestnon-forest:cos_ta    0.7656     1.3062    0.6072    0.9652
    ## forestnon-forest:log_sl    0.7861     1.2722    0.7023    0.8797
    ## log_sl:cos_ta              1.0153     0.9849    0.9494    1.0858
    ##
    ## Concordance= 0.605  (se = 0.012 )
    ## Likelihood ratio test= 88.02  on 6 df,   p=<2e-16
    ## Wald test            = 86.24  on 6 df,   p=<2e-16
    ## Score (logrank) test = 88.42  on 6 df,   p=<2e-16

    summary(m2)

    ## Call:
    ## coxph(formula = Surv(rep(1, 12144L), case_) ~ forest + forest:cos_ta +
    ##     forest:log_sl + log_sl + cos_ta + strata(step_id_), data = data,
    ##     method = "exact")
    ##
    ##   n= 12144, number of events= 759
    ##
    ##                             coef exp(coef) se(coef)      z Pr(>|z|)
    ## forestnon-forest         0.77568   2.17206  0.32638  2.377 0.017473 *
    ## log_sl                   0.16230   1.17622  0.04926  3.295 0.000984 ***
    ## cos_ta                  -0.15543   0.85604  0.09746 -1.595 0.110758
    ## forestnon-forest:cos_ta -0.27050   0.76300  0.11798 -2.293 0.021862 *
    ## forestnon-forest:log_sl -0.24206   0.78501  0.05735 -4.221 2.43e-05 ***
    ## ---
    ## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
    ##
    ##                         exp(coef) exp(-coef) lower .95 upper .95
    ## forestnon-forest            2.172     0.4604    1.1457    4.1180
    ## log_sl                      1.176     0.8502    1.0680    1.2954
    ## cos_ta                      0.856     1.1682    0.7072    1.0362
    ## forestnon-forest:cos_ta     0.763     1.3106    0.6055    0.9615
    ## forestnon-forest:log_sl     0.785     1.2739    0.7015    0.8784
    ##
    ## Concordance= 0.603  (se = 0.012 )
    ## Likelihood ratio test= 87.82  on 5 df,   p=<2e-16
    ## Wald test            = 85.59  on 5 df,   p=<2e-16
    ## Score (logrank) test = 87.55  on 5 df,   p=<2e-16

### Interpretation of coefficients

See the discussion in Fieberg et al 2021.

## A note on piping

All steps described above, could easily be wrapped into one piped workflow:

    m1 <- deer |>
      steps_by_burst() |> random_steps(n = 15) |>
      extract_covariates(sh_forest) |>
      mutate(forest = factor(forest, levels = 1:0, labels = c("forest", "non-forest")),
             cos_ta = cos(ta_),
             log_sl = log(sl_)) |>
      fit_clogit(case_ ~ forest + forest:cos_ta + forest:sl_ + sl_ * cos_ta + strata(step_id_))

    summary(m1)

    ## Call:
    ## coxph(formula = Surv(rep(1, 12144L), case_) ~ forest + forest:cos_ta +
    ##     forest:sl_ + sl_ * cos_ta + strata(step_id_), data = data,
    ##     method = "exact")
    ##
    ##   n= 12144, number of events= 759
    ##
    ##                               coef  exp(coef)   se(coef)      z Pr(>|z|)
    ## forestnon-forest        -0.0330127  0.9675262  0.1408828 -0.234 0.814731
    ## sl_                      0.0008085  1.0008088  0.0001600  5.054 4.33e-07 ***
    ## cos_ta                  -0.3528147  0.7027074  0.1115603 -3.163 0.001564 **
    ## forestnon-forest:cos_ta -0.2475250  0.7807307  0.1180669 -2.096 0.036040 *
    ## forestnon-forest:sl_    -0.0011685  0.9988322  0.0002031 -5.753 8.76e-09 ***
    ## sl_:cos_ta               0.0004514  1.0004515  0.0001336  3.379 0.000727 ***
    ## ---
    ## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
    ##
    ##                         exp(coef) exp(-coef) lower .95 upper .95
    ## forestnon-forest           0.9675     1.0336    0.7341    1.2752
    ## sl_                        1.0008     0.9992    1.0005    1.0011
    ## cos_ta                     0.7027     1.4231    0.5647    0.8744
    ## forestnon-forest:cos_ta    0.7807     1.2809    0.6194    0.9840
    ## forestnon-forest:sl_       0.9988     1.0012    0.9984    0.9992
    ## sl_:cos_ta                 1.0005     0.9995    1.0002    1.0007
    ##
    ## Concordance= 0.612  (se = 0.013 )
    ## Likelihood ratio test= 117.9  on 6 df,   p=<2e-16
    ## Wald test            = 121.7  on 6 df,   p=<2e-16
    ## Score (logrank) test = 127.9  on 6 df,   p=<2e-16

## Session

    sessioninfo::session_info()

    ## ─ Session info ───────────────────────────────────────────────────────────────
    ##  setting  value
    ##  version  R version 4.2.2 Patched (2022-11-10 r83330)
    ##  os       Ubuntu 22.04.2 LTS
    ##  system   x86_64, linux-gnu
    ##  ui       X11
    ##  language (EN)
    ##  collate  C
    ##  ctype    en_US.UTF-8
    ##  tz       Europe/Berlin
    ##  date     2023-03-28
    ##  pandoc   2.19.2 @ /usr/lib/rstudio/resources/app/bin/quarto/bin/tools/ (via rmarkdown)
    ##
    ## ─ Packages ───────────────────────────────────────────────────────────────────
    ##  package      * version  date (UTC) lib source
    ##  amt          * 0.2.1.0  2023-03-28 [1] local
    ##  backports      1.4.1    2021-12-13 [5] CRAN (R 4.2.0)
    ##  boot           1.3-28.1 2022-11-22 [3] CRAN (R 4.2.2)
    ##  bslib          0.4.2    2022-12-16 [3] CRAN (R 4.2.2)
    ##  cachem         1.0.7    2023-02-24 [5] CRAN (R 4.2.2)
    ##  checkmate      2.1.0    2022-04-21 [5] CRAN (R 4.2.0)
    ##  circular       0.4-95   2022-04-26 [3] CRAN (R 4.2.2)
    ##  class          7.3-21   2023-01-23 [6] CRAN (R 4.2.2)
    ##  classInt       0.4-9    2023-02-28 [3] CRAN (R 4.2.2)
    ##  cli            3.6.0    2023-01-09 [5] CRAN (R 4.2.2)
    ##  codetools      0.2-19   2023-02-01 [6] CRAN (R 4.2.2)
    ##  colorspace     2.1-0    2023-01-23 [5] CRAN (R 4.2.2)
    ##  data.table     1.14.8   2023-02-17 [3] CRAN (R 4.2.2)
    ##  DBI            1.1.3    2022-06-18 [5] CRAN (R 4.2.1)
    ##  digest         0.6.31   2022-12-11 [3] CRAN (R 4.2.2)
    ##  dplyr        * 1.1.0    2023-01-29 [5] CRAN (R 4.2.2)
    ##  e1071          1.7-13   2023-02-01 [3] CRAN (R 4.2.2)
    ##  evaluate       0.20     2023-01-17 [5] CRAN (R 4.2.2)
    ##  fansi          1.0.4    2023-01-22 [5] CRAN (R 4.2.2)
    ##  farver         2.1.1    2022-07-06 [5] CRAN (R 4.2.1)
    ##  fastmap        1.1.1    2023-02-24 [5] CRAN (R 4.2.2)
    ##  fitdistrplus   1.1-8    2022-03-10 [3] CRAN (R 4.2.2)
    ##  generics       0.1.3    2022-07-05 [5] CRAN (R 4.2.1)
    ##  ggforce        0.4.1    2022-10-04 [3] CRAN (R 4.2.2)
    ##  ggplot2      * 3.4.1    2023-02-10 [3] CRAN (R 4.2.2)
    ##  ggraph       * 2.1.0    2022-10-09 [3] CRAN (R 4.2.2)
    ##  ggrepel        0.9.3    2023-02-03 [3] CRAN (R 4.2.2)
    ##  glue           1.6.2    2022-02-24 [5] CRAN (R 4.2.0)
    ##  graphlayouts   0.8.4    2022-11-24 [3] CRAN (R 4.2.2)
    ##  gridExtra      2.3      2017-09-09 [3] CRAN (R 4.2.2)
    ##  gtable         0.3.1    2022-09-01 [5] CRAN (R 4.2.1)
    ##  highr          0.10     2022-12-22 [3] CRAN (R 4.2.2)
    ##  htmltools      0.5.4    2022-12-07 [5] CRAN (R 4.2.2)
    ##  igraph         1.4.0    2023-02-10 [3] CRAN (R 4.2.2)
    ##  jquerylib      0.1.4    2021-04-26 [3] CRAN (R 4.2.2)
    ##  jsonlite       1.8.4    2022-12-06 [3] CRAN (R 4.2.2)
    ##  KernSmooth     2.23-20  2021-05-03 [6] CRAN (R 4.2.0)
    ##  knitr        * 1.42     2023-01-25 [5] CRAN (R 4.2.2)
    ##  labeling       0.4.2    2020-10-20 [5] CRAN (R 4.2.0)
    ##  lattice        0.20-45  2021-09-22 [6] CRAN (R 4.2.0)
    ##  lifecycle      1.0.3    2022-10-07 [5] CRAN (R 4.2.1)
    ##  lubridate    * 1.9.2    2023-02-10 [3] CRAN (R 4.2.2)
    ##  magrittr       2.0.3    2022-03-30 [5] CRAN (R 4.2.0)
    ##  MASS           7.3-58.2 2023-01-23 [6] CRAN (R 4.2.2)
    ##  Matrix         1.5-3    2022-11-11 [6] CRAN (R 4.2.2)
    ##  munsell        0.5.0    2018-06-12 [3] CRAN (R 4.2.2)
    ##  mvtnorm        1.1-3    2021-10-08 [3] CRAN (R 4.2.2)
    ##  pillar         1.8.1    2022-08-19 [5] CRAN (R 4.2.1)
    ##  pkgconfig      2.0.3    2019-09-22 [3] CRAN (R 4.2.2)
    ##  polyclip       1.10-4   2022-10-20 [3] CRAN (R 4.2.2)
    ##  proxy          0.4-27   2022-06-09 [3] CRAN (R 4.2.2)
    ##  purrr          1.0.1    2023-01-10 [5] CRAN (R 4.2.2)
    ##  R6             2.5.1    2021-08-19 [5] CRAN (R 4.2.0)
    ##  rbibutils      2.2.13   2023-01-13 [3] CRAN (R 4.2.2)
    ##  Rcpp           1.0.10   2023-01-22 [5] CRAN (R 4.2.2)
    ##  Rdpack         2.4      2022-07-20 [3] CRAN (R 4.2.2)
    ##  rlang          1.0.6    2022-09-24 [5] CRAN (R 4.2.1)
    ##  rmarkdown      2.20     2023-01-19 [5] CRAN (R 4.2.2)
    ##  rstudioapi     0.14     2022-08-22 [5] CRAN (R 4.2.1)
    ##  sass           0.4.5    2023-01-24 [5] CRAN (R 4.2.2)
    ##  scales         1.2.1    2022-08-20 [5] CRAN (R 4.2.1)
    ##  sessioninfo    1.2.2    2021-12-06 [3] CRAN (R 4.2.2)
    ##  sf             1.0-9    2022-11-08 [3] CRAN (R 4.2.2)
    ##  survival       3.5-3    2023-02-12 [3] CRAN (R 4.2.2)
    ##  terra          1.7-12   2023-02-21 [3] Github (rspatial/terra@b79b4b0)
    ##  tibble         3.1.8    2022-07-22 [5] CRAN (R 4.2.2)
    ##  tidygraph    * 1.2.3    2023-02-01 [3] CRAN (R 4.2.2)
    ##  tidyr          1.3.0    2023-01-24 [5] CRAN (R 4.2.2)
    ##  tidyselect     1.2.0    2022-10-10 [5] CRAN (R 4.2.1)
    ##  timechange     0.2.0    2023-01-11 [5] CRAN (R 4.2.2)
    ##  tweenr         2.0.2    2022-09-06 [3] CRAN (R 4.2.2)
    ##  units          0.8-1    2022-12-10 [3] CRAN (R 4.2.2)
    ##  utf8           1.2.3    2023-01-31 [5] CRAN (R 4.2.2)
    ##  vctrs          0.5.2    2023-01-23 [5] CRAN (R 4.2.2)
    ##  viridis        0.6.2    2021-10-13 [5] CRAN (R 4.2.0)
    ##  viridisLite    0.4.1    2022-08-22 [5] CRAN (R 4.2.1)
    ##  withr          2.5.0    2022-03-03 [5] CRAN (R 4.2.0)
    ##  xfun           0.37     2023-01-31 [5] CRAN (R 4.2.2)
    ##  yaml           2.3.7    2023-01-23 [5] CRAN (R 4.2.2)
    ##
    ##  [1] /tmp/RtmpEE1aXl/Rinst11aff69feb4c3
    ##  [2] /tmp/RtmpTZF65G/temp_libpathf4f475febbc9
    ##  [3] /home/jsigner/R/x86_64-pc-linux-gnu-library/4.2
    ##  [4] /usr/local/lib/R/site-library
    ##  [5] /usr/lib/R/site-library
    ##  [6] /usr/lib/R/library
    ##
    ## ──────────────────────────────────────────────────────────────────────────────

1. https://www.biorxiv.org/content/10.1101/2020.11.12.379834v4↩︎

2. See also `?fit_distr`.↩︎

3. Note, this possible because of the Glivenko-Cantelli theorem and works as long as the sample from the original distribution (the sample you provide here) is large enough.↩︎

4. And how it was implemented in `amt` up to version 0.0.6. This should be backward compatible and not break existing code.↩︎