read_log.R 1.91 KB
Newer Older
Keisuke ANDO's avatar
Keisuke ANDO committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#' Read log file
#' 
#' @param path log file path
#' @return Parsed tibble of log file in \code{path}
#' @export
#' @examples 
#' rcg <- read_log("data/20220405162804-HELIOS_base_3-vs-enemy_2.rcg")
#' rcl <- read_log("data/20220304142841-HELIOS_base_1-vs-ThunderLeague_1.rcl")
read_log <- function(path) {
  ext <- path |> path() |> path_ext()
  
  if (ext == "rcg") {
    return(read_rcg(path))
  }
  if (ext == "rcl") {
    return(read_rcl(path))
  }
  
  stop("Not supported format: ", path)
}

#' @rdname read_log
#' @export 
read_rcg <- function(path) {
  rcg <- path |>
    read_file() |>
    parse_json(simplifyVector = TRUE, flatten = TRUE) |>
    as_tibble() |>
    filter(type == "show") |>
    select(time,stime,players, ball.x, ball.y, ball.vx, ball.vy) |>
    unnest(players) |>
    select(time:capacity, ball.x:ball.vy) |>
    rename(step = time) |>
    rename_with(stringr::str_replace, pattern = "\\.", replacement = "_")
  
  return(rcg)
}

#' @rdname read_log
#' @export
read_rcl <- function(path) {
  rcl <- path |>
    read_lines() |>
    as_tibble() |>
    mutate(
      step     = value |> stringr::str_extract("\\d+") |> as.numeric(),
      agent    = value |> stringr::str_extract("\\w+_([0-9]{1,2}|Coach)(?!\\))"),
      team     = agent |> stringr::str_remove("_([0-9]{1,2}|Coach)"),
      unum     = agent |> stringr::str_extract("([0-9]{1,2}|Coach)$"),
      commands = value |>
        stringr::str_extract("\\(.+\\)$") |>
        purrr::map(~ .x |>
                     stringr::str_split("\\(|\\)", simplify = TRUE) |>
                     stringr::str_trim() |>
                     purrr::discard(~ .x == "")),
    ) |>
    unnest(commands) |>
    mutate(
      commands = commands |> stringr::str_split("\\ ", n = 2),
      command  = commands |> purrr::map_chr(1),
      args     = commands |> purrr::map(~ .x[-1]),
    ) |>
    select(
      step,
      team,
      unum,
      command,
      args
    )
  
  return(rcl)
}