## ----knitr-setup, include = FALSE-----------------------------------------------------------------
knitr::opts_chunk$set(
    comment = "#",
    prompt = FALSE,
    tidy = FALSE,
    cache = FALSE,
    collapse = TRUE
)

old <- options(width = 100L)

## ----inner-pipeline-------------------------------------------------------------------------------
library(pipeflow)

inner <- pip_new("coefficients") |>
    pip_add("input", \(input_df = NULL) input_df) |>
    pip_add("fit",
        \(data = ~input, xVar = "x", yVar = "y") {
            lm(paste(yVar, "~", xVar), data = data)
        }
    ) |>
    pip_add("coefs",
        \(fit = ~fit, digits = 3) {
            round(coefficients(fit), digits)
        }
    )

inner

## ----as-function----------------------------------------------------------------------------------
f_inner <- as.function(inner, out = "coefs")

formals(f_inner) |> str()

## -------------------------------------------------------------------------------------------------
params <- list(input_df = iris, xVar = "Sepal.Length", yVar = "Sepal.Width")
pip_set_params(inner, params) |> pip_run()

inner[["coefs", "out"]]

do.call(f_inner, params)

## ----outer-all------------------------------------------------------------------------------------
outer_all <- pip_new("analysis") |>
    pip_add("df", \(df = NULL) df) |>
    pip_add(
        "inner_run",
        as.function(inner, out = "coefs"),  # coefs is returned from inner run
        params = list(input_df = ~df)       # df is passed to the inner pipeline
    )

outer_all

## ----outer-all-params-----------------------------------------------------------------------------
pip_get_params(outer_all) |> str()

## ----run-outer-all--------------------------------------------------------------------------------
outer_all |>
    pip_set_params(
        list(df = iris, xVar = "Sepal.Length", yVar = "Sepal.Width")
    ) |>
    pip_run()

outer_all[["inner_run", "out"]]

## ----out-function---------------------------------------------------------------------------------
f_summary <- as.function(
    inner,
    out = \(p) list(
        r2 = summary(p[["fit", "out"]])$r.squared,
        coefs = p[["coefs", "out"]]
    )
)

f_summary(input_df = iris, xVar = "Sepal.Length", yVar = "Sepal.Width")

## ----outer-pipeline-------------------------------------------------------------------------------
outer <- pip_new("full analysis") |>
    pip_add("df", \(df = NULL) df) |>
    pip_add(
        "split_df",
        \(df = ~df, byVar = "by") split(df, f = df[[byVar]]),
        exec = "split"
    ) |>
    pip_add(
        "inner_run",
        as.function(inner, out = "coefs"),
        params = list(input_df = ~split_df)    # bind to split data
    ) |>
    pip_add(
        "combine",
        \(coefs = ~inner_run) as.data.frame(do.call(rbind, coefs)),
        exec = "reduce"
    )

outer

## ----outer-params---------------------------------------------------------------------------------
pip_get_params(outer) |> str()

## ----run-outer------------------------------------------------------------------------------------
outer |>
    pip_set_params(
        list(
            df = iris,
            xVar = "Sepal.Length",
            yVar = "Sepal.Width",
            byVar = "Species"
        )
    ) |>
    pip_run()

## ----inner-run-out--------------------------------------------------------------------------------
outer[["inner_run", "out"]]

## ----combine-out----------------------------------------------------------------------------------
outer[["combine", "out"]]

## ----change-param---------------------------------------------------------------------------------
pip_set_params(outer, params = list(xVar = "Petal.Length"))

outer

## ----toy-inner------------------------------------------------------------------------------------
runs <- new.env()
runs$square <- runs$scale <- 0L
count <- function(step) runs[[step]] <- runs[[step]] + 1L
n_runs <- function() unlist(mget(c("square", "scale"), envir = runs))

toy_inner <- pip_new("toy inner") |>
    pip_add("input", \(x = NULL) x) |>
    pip_add("square", \(x = ~input) {
        count("square")
        x^2
    }) |>
    pip_add("scale", \(sq = ~square, factor = 1) {
        count("scale")
        sq * factor
    })

## ----toy-outer------------------------------------------------------------------------------------
toy_outer <- pip_new("toy outer") |>
    pip_add(
        "numbers",
        \(values = list(a = 1:3, b = 4:6)) values,
        exec = "split"
    ) |>
    pip_add(
        "inner_run",
        as.function(toy_inner, out = "scale"),
        params = list(x = ~numbers)
    )

pip_run(toy_outer, lgr = NULL)
n_runs()

## ----toy-param------------------------------------------------------------------------------------
pip_set_params(toy_outer, list(factor = 10))
pip_run(toy_outer, lgr = NULL)
n_runs()

## ----toy-input------------------------------------------------------------------------------------
pip_set_params(toy_outer, list(values = list(a = 1:4, b = 4:6)))
pip_run(toy_outer, lgr = NULL)
n_runs()

toy_outer[["inner_run", "out"]]

## ----toy-inner-pips-------------------------------------------------------------------------------
inner_pips <- pip_inner(toy_outer, "inner_run")
names(inner_pips)

inner_pips[["a"]]

## ----parallel-inner, eval = .Platform$OS.type == "unix"-------------------------------------------
par_outer <- pip_clone(outer) |>
    pip_replace(
        "inner_run",
        as.function(inner, out = "coefs", cache = FALSE),
        params = list(input_df = ~split_df),
        keep_params = TRUE
    )

mc2 <- \(X, FUN) parallel::mclapply(X, FUN, mc.cores = 2)
pip_run(par_outer, map = mc2)

par_outer[["combine", "out"]]

## ----manual---------------------------------------------------------------------------------------
# Helper to run inner pipeline
run_inner_pip <- function(pip, name, df) {
    pip$name <- sprintf("coefs for *%s*", name)

    # Set data subset for inner pipeline and run it
    pip_set_params(pip, list(input_df = df)) |> pip_run(lgr = NULL)

    pip[["coefs", "out"]]
}

manual <- pip_new("full analysis") |>
    pip_add("df", \(df = NULL) df) |>
    pip_add(
        "split_df",
        \(df = ~df, byVar = "by") split(df, f = df[[byVar]])
    ) |>
    pip_add(
        "inner_run",
        \(dfList = ~split_df, ...) {
            p <- pip_clone(inner)

            # Forward the parameters of the step to the inner pipeline
            pip_set_params(p, list(...))

            Map(
                f = run_inner_pip,
                name = names(dfList),
                df = dfList,
                MoreArgs = list(pip = p)
            )
        },
        params = pip_get_params(inner) # <--- default parameters of inner
    ) |>
    pip_add(
        "combine",
        \(coefs = ~inner_run) as.data.frame(do.call(rbind, coefs))
    )

manual

## ----manual-run-----------------------------------------------------------------------------------
manual |>
    pip_set_params(
        list(
            df = iris,
            xVar = "Sepal.Length",
            yVar = "Sepal.Width",
            byVar = "Species"
        )
    ) |>
    pip_run()

manual[["combine", "out"]]

## ----include = FALSE----------------------------------------------------------
options(old)

