R/copy.R

Defines functions do_copy_run copy_run_files copy_run

Documented in copy_run copy_run_files

#' Copy run directories
#'
#' Functions for exporting/copying run directories and run artifact files.
#'
#' @inheritParams run_info
#'
#' @param to Name of parent directory to copy run(s) into. Defaults to the
#'   current working directory.
#'
#' @param rename Rename run directory after copying. If not specified this
#'   defaults to the basename of the run directory (e.g.
#'   "2017-09-24T10-54-00Z").
#'
#' @details Use `copy_run` to copy one or more run directories.
#'
#'   Use `copy_run_files` to copy only files saved/generated by training run
#'   scripts (e.g. saved models, checkpoints, etc.).
#'
#' @return Logical vector indicating which operation succeeded for each of the
#'   run directories specified.
#'
#' @family run management
#'
#' @examples \dontrun{
#'
#' # export a run directory to the current working directory
#' copy_run("runs/2017-09-24T10-54-00Z")
#'
#' # export to the current working directory then rename
#' copy_run("runs/2017-09-24T10-54-00Z", rename = "best-run")
#'
#' # export artifact files only to the current working directory then rename
#' copy_run_files("runs/2017-09-24T10-54-00Z", rename = "best-model")
#'
#' # export 3 best eval_acc to a "best-runs" directory
#' copy_run(ls_runs(order = eval_acc)[1:3,], to = "best-runs")
#'
#' }
#' @export
copy_run <- function(run_dir, to = ".", rename = NULL) {
  do_copy_run(run_dir, to, rename)
}


#' @rdname copy_run
#' @export
copy_run_files <- function(run_dir, to = ".", rename = NULL) {
  do_copy_run(run_dir, to, rename, remove_dirs = c("tfruns.d", "logs", "plots"))
}

do_copy_run <- function(run_dir, to = ".", rename = NULL, remove_dirs = NULL) {

  # resolve run_dir
  run_dir <- as_run_dir(run_dir)

  # rename must be the same length as run_dir
  if (!is.null(rename) && length(rename) != length(run_dir))
    stop("The rename parameter must have the same length as the run_dir parameter")

  # to must be length 1
  if (length(to) != 1)
    stop("You must pass a single 'to' directory to copy_run")

  # create to if it doesn't exist
  if (!utils::file_test("-d",to))
    dir.create(to, recursive = TRUE)

  # copy to targets
  result <- file.copy(run_dir, to, recursive = TRUE, overwrite = TRUE, copy.date = TRUE)

  # note targets (for rename/remove below)
  targets <- file.path(to, basename(run_dir))

  # perform renames if requested
  if (!is.null(rename)) {
    renames <- file.path(to, rename)
    unlink(renames, recursive = TRUE)
    result <- file.rename(targets, renames)
    targets <- renames
  }

  # perform removes if requested
  if (!is.null(remove_dirs)) {
    for (target in targets)
      unlink(file.path(target, remove_dirs), recursive = TRUE)
  }

  # return
  invisible(result)
}

Try the tfruns package in your browser

Any scripts or data that you put into this service are public.

tfruns documentation built on May 29, 2024, 7:31 a.m.