Skip to content

Learn a policy from logged episodes

When each decision changes what comes next, learn a policy from logged episodes, stay close to what the logs show, and judge it off-policy before anyone deploys it.

Advanced ~12 min10 steps

What runs in CodeSplash

You will be able to

  • Tell an episode problem from a one-off decision
  • Say why a policy learned from logs must stay near the logged actions
  • Read a policy comparison with intervals and effective sample size

Read first

01

When one decision shapes the next

Read

A bandit makes one decision and sees its reward. Many real problems run longer: a support agent picks the next reply, a clinician adjusts a dose each visit, a store reorders stock every week. Each choice changes the situation the next choice faces. One run of such choices, from start to finish, is an episode.

A policy for an episode problem says what to do in each situation. The best one isn't the one with the best next reward, but the one with the best total over the episode.

02

Why do the weights grow?

Predict

Predict first

In one-step off-policy evaluationOff-policy evaluationEstimates how a new decision policy would have done, using only logs from the current policy., each matching row is weighted by one over its propensity. In an episode, the new policy has to agree with the logged one at every step. What happens to an episode's weight as episodes get longer?

They stay about the sameThey multiply, so they get much largerThey cancel out
Reveal

They multiply. An episode's weight is the product of its per-step weights, so a few long episodes can carry most of the estimate. That is why the effective sample sizeEffective sample sizeHow many equally weighted units a weighted sample is worth. Unequal weights make it smaller than the real count. matters even more here, and why per-decision and doubly robust estimators exist: they use the weight only up to each step.

03

Compute an episode weight

Checkpoint

Check yourself

A two-step episode. At step one the logged action had propensity 0.5 and the new policy agrees with it. At step two the logged action had propensity 1/3 and the new policy agrees again. What is the episode's importance weight?

Show the answer

Answer: 6

Each step's weight is one over the propensity: 2, then 3. The episode's weight is their product, 2 × 3 = 6.

04

Learning without trying anything new

Read

You can't try actions on logs; you can only reweight what happened. Offline methods differ in how far they dare to stray from it:

  • Behavior cloning copies the logged choices. Safe, and never better than the logs.
  • Fitted Q iteration estimates the value of every action in every situation, then picks the best. It can prefer an action the logs barely tried, on the strength of a guess.
  • Conservative and implicit Q-learning (CQL, IQL) look for better actions but penalize, or never query, actions the logs don't support.
05

Check before you learn

In the app

Before learning anything, look at the logs: how many episodes, whether every action appears in each kind of situation, and whether the logging probabilities are recorded and never tiny.

Logged episodesRecorded · Python and R agreeRecorded 2026-11-21 · 24 values compared
R

60 episodes hold 640 decisions, 10.7 per episode on average; the average discounted return is 0.049. 100% of the judged decisions fall in state groups where every action was tried. The smallest logging probability is 0.100; 0.0% of decisions had one under 0.05.

Episodes
60
Decisions
640
Average discounted return
0.0487
Decisions where every action was tried
100.0%

Plots

Decisions per episodeHow is one numeric variable distributed?
View data
Decisions per episode
5
14
13
9
6
12
11
14
14
10
9
11
10
14
14
14
6
14
6
7
12
14
14
14
9
6
14
14
14
5
11
9
14
10
6
14
7
11
10
7
10
6
5
10
12
14
10
13
14
14
14
7
14
13
7
8
9
10
11
11
Discounted return per episode (γ = 0.95)How is one numeric variable distributed?
View data
Discounted return
0.5883
−0.5123
0.0537
0.2937
0.5089
0.1092
0.1675
−0.5123
−0.5123
0.2290
0.2937
0.1675
0.2290
−0.5123
0.0010
−0.5123
0.5089
−0.5123
0.5089
0.4334
0.1092
−0.5123
0.0010
−0.5123
0.2937
0.5089
−0.5123
−0.5123
−0.5123
0.5883
0.1675
0.2937
−0.5123
0.2290
0.5089
−0.5123
0.4334
0.1675
0.2290
0.4334
0.2290
0.5089
0.5883
0.2290
0.1092
−0.5123
0.2290
0.0537
−0.5123
−0.5123
−0.5123
0.4334
−0.5123
0.0537
0.4334
0.3618
0.2937
0.2290
0.1675
0.1675
Actions loggedHow often does each category occur?
View data
action
right
right
right
right
right
left
stay
left
right
right
stay
stay
right
right
stay
right
left
right
right
left
right
stay
right
right
stay
stay
right
left
stay
right
stay
right
right
left
right
right
right
right
stay
stay
right
right
right
right
right
right
right
right
right
right
right
right
stay
right
right
right
left
right
right
left

First 60 of 640 rows.

Assumptions

  • Episodes are in order — Each step appears once per episode.
  • Logging probabilities — The smallest logging probability is 0.100.
  • Every action tried — 100% of the judged decisions fall in state groups where every action was tried; 0 of 12 groups miss at least one action.

Episodes

SummaryValue
Episodes60
Decisions640
Decisions per episode (mean)10.667
Decisions per episode (median)11
Shortest episode5
Longest episode14
Discounted return (mean, γ = 0.95)0.0487
Discounted return (SD)0.3972
Reward per decision (mean)0.0156

Actions logged

actionDecisionsShareMean rewardMean logging probabilityJudged groups never trying it
left10816.9%−0.05000.23150
stay12219.1%−0.05000.20000
right41064.1%0.05240.63270

State groups where some action was never tried

State groupDecisionsActions triedNever tried

Groups with at least 10 decisions; numeric state columns are cut into at most 4 groups each. Largest groups first (up to 50).

Logging probabilities

SummaryValue
Smallest0.1000
Median0.5000
Largest0.7000
Share under 0.050
Outside (0, 1]0
  • 18 of 60 episodes end without done = true; Learn and Evaluate treat each as ending at its last row.
  • Rows ordered by episode (first appearance), then step. Returns are discounted by 0.95 per step from each episode's first decision. State groups: cell, weather today; a group is judged once it has 10 decisions.
The exact R script · R R version 4.5.1 (2025-06-13)
# Logged episodes
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method decide.trajectories 1.0.0 · spec e642cf16864dcda7
# Dataset: pol_corridor (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr) # cs_trajectories(): twin of codesplash.decide.trajectories (counting and averaging only)

# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/pol_corridor.parquet", col_select = c("episode", "step", "cell", "weather today", "action", "reward", "propensity", "done")))
n_input <- nrow(df)
df[["cell"]] <- factor(df[["cell"]], levels = c("c0", "c1", "c2", "c3", "c4", "c5"))  # stored level order
df[["weather today"]] <- factor(df[["weather today"]], levels = c("rain", "sun"))  # stored level order
df[["action"]] <- factor(df[["action"]], levels = c("left", "stay", "right"))  # stored level order
df[["done"]] <- factor(df[["done"]], levels = c("false", "true"))  # stored level order
df <- df[stats::complete.cases(df[c("episode", "step", "cell", "weather today", "action", "reward", "propensity", "done")]), , drop = FALSE]  # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
  warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("episode", "step", "cell", "weather today", "action", "reward", "propensity", "done"))  # infinite values stop the run (registry/errors.yaml)

# %% Inputs
ep_col <- "episode"
step_col <- "step"
a_col <- "action"
r_col <- "reward"
p_col <- "propensity" # optional: the logging probability of each logged action
done_col <- "done" # optional: true on the step that ended the episode
states <- c("cell", "weather today")
gamma <- as.numeric(0.95)
bins <- as.integer(4)
min_cell <- as.integer(10)
low <- as.numeric(0.05)

# Yes/no columns count as 1/0.
as_flag <- function(v) if (is.factor(v)) as.character(v) == "true" else as.numeric(v) != 0

ep_keys <- if (is.factor(df[[ep_col]])) as.character(df[[ep_col]]) else as.numeric(df[[ep_col]])
lv <- levels(df[[a_col]])
action <- as.character(df[[a_col]])
reward <- if (is.factor(df[[r_col]])) as.numeric(as_flag(df[[r_col]])) else as.numeric(df[[r_col]])
groups <- cs_trajectories_groups(lapply(states, function(c) {
  v <- df[[c]]
  list(name = c, values = if (is.factor(v)) as.character(v) else as.numeric(v), categorical = is.factor(v))
}), bins)

# %% Summarize
res <- cs_trajectories(ep_keys, as.numeric(df[[step_col]]), action, lv, reward, groups,
                       propensity = if (!is.null(p_col)) as.numeric(df[[p_col]]) else NULL,
                       done = if (!is.null(done_col)) as_flag(df[[done_col]]) else NULL,
                       gamma = gamma, low = low, min_cell = min_cell)
E <- res$n_episodes
n <- res$n_steps
if (length(lv) < 2) {
  warnings <- c(warnings, sprintf("Only one action appears in %s: a policy learned from these logs can only copy it, and no other action can be judged.", a_col))
}
if (res$max_length == 1) {
  warnings <- c(warnings, "Every episode has one decision: this is a one-step (bandit) problem, and the Decisions studio's off-policy evaluation fits it better.")
}
if (res$duplicate_steps > 0) {
  warnings <- c(warnings, sprintf("%d step value(s) repeat within an episode; Learn and Evaluate stop until each step is unique within its episode.", res$duplicate_steps))
}
if (!is.null(res$truncated_episodes) && res$truncated_episodes > 0) {
  warnings <- c(warnings, sprintf("%d of %d episodes end without %s = true; Learn and Evaluate treat each as ending at its last row.", res$truncated_episodes, E, done_col))
}
if (!is.null(res$early_done_episodes) && res$early_done_episodes > 0) {
  warnings <- c(warnings, sprintf("%d episode(s) mark %s = true before their last row; the rows after it are still counted here.", res$early_done_episodes, done_col))
}

# %% Checks
early <- if (is.null(res$early_done_episodes)) 0L else res$early_done_episodes
order_ok <- res$duplicate_steps == 0 && early == 0
assumptions <- list(list(
  key = "episode_order", label = "Episodes are in order", status = if (order_ok) "pass" else "warn",
  detail = if (order_ok) "Each step appears once per episode." else sprintf("%d repeated step value(s); %d episode(s) end before their last row.", res$duplicate_steps, early)
))
pct1 <- function(x) sprintf("%.1f%%", 100 * x)
pct0 <- function(x) sprintf("%.0f%%", 100 * x)
assumptions[[2]] <- if (is.null(p_col)) {
  list(key = "propensity", label = "Logging probabilities", status = "info",
       detail = "Not recorded. Learn can still run, but Evaluate and the doubly robust values need the logging probability of each action.")
} else if (res$invalid_propensity > 0) {
  list(key = "propensity", label = "Logging probabilities", status = "fail",
       detail = sprintf("%d decision(s) have a logging probability outside (0, 1].", res$invalid_propensity), statistic = res$invalid_propensity)
} else if (res$share_low_propensity > 0) {
  list(key = "propensity", label = "Logging probabilities", status = "warn",
       detail = sprintf("%s of decisions had a logging probability under %s (smallest %.3f): a few episodes can dominate off-policy estimates.",
                        pct1(res$share_low_propensity), sprintf("%g", low), res$min_propensity),
       statistic = res$min_propensity)
} else {
  list(key = "propensity", label = "Logging probabilities", status = "pass",
       detail = sprintf("The smallest logging probability is %.3f.", res$min_propensity), statistic = res$min_propensity)
}
assumptions[[3]] <- if (is.null(res$support_share)) {
  list(key = "support", label = "Every action tried", status = "info",
       detail = sprintf("No state group has %d decisions yet, so support can't be judged.", min_cell))
} else {
  list(key = "support", label = "Every action tried", status = if (res$support_share >= 0.9) "pass" else "warn",
       detail = sprintf("%s of the judged decisions fall in state groups where every action was tried; %d of %d groups miss at least one action.",
                        pct0(res$support_share), res$n_unsupported_groups, res$n_judged_groups),
       statistic = res$support_share)
}

# %% Result
summary <- paste0(
  sprintf("%s episodes hold %s decisions, %.1f per episode on average; the average discounted return is %.3f. ",
          format(E, big.mark = ","), format(n, big.mark = ","), res$mean_length, res$mean_return),
  if (!is.null(res$support_share)) sprintf("%s of the judged decisions fall in state groups where every action was tried.", pct0(res$support_share))
  else sprintf("No state group has %d decisions yet, so support can't be judged.", min_cell),
  if (!is.null(p_col)) sprintf(" The smallest logging probability is %.3f; %s of decisions had one under %s.", res$min_propensity,
                               pct1(res$share_low_propensity), sprintf("%g", low)) else ""
)
keys <- c("n_episodes", "n_steps", "mean_length", "median_length", "min_length", "max_length", "mean_return", "sd_return",
          "min_return", "max_return", "mean_reward", "duplicate_steps", "n_groups", "n_judged_groups", "n_unsupported_groups", "support_share")
values <- stats::setNames(lapply(keys, function(k) res[[k]]), keys)
values$n_actions <- length(lv)
# Without an end flag or logging probabilities these keys are null (nothing to count).
for (k in c("truncated_episodes", "early_done_episodes", "min_propensity", "median_propensity", "max_propensity", "share_low_propensity",
            "invalid_propensity")) values[k] <- list(res[[k]])
na_null <- function(x) if (is.null(x)) NA_real_ else x
metric_rows <- data.frame(
  metric = c("Episodes", "Decisions", "Decisions per episode (mean)", "Decisions per episode (median)", "Shortest episode", "Longest episode",
             sprintf("Discounted return (mean, γ = %s)", sprintf("%g", gamma)), "Discounted return (SD)", "Reward per decision (mean)"),
  value = c(E, n, res$mean_length, res$median_length, res$min_length, res$max_length, res$mean_return, na_null(res$sd_return), res$mean_reward)
)
action_cols <- list(list(key = "action", label = a_col, type = "string"), list(key = "rows", label = "Decisions", type = "integer"),
                    list(key = "share", label = "Share", type = "percent"), list(key = "mean_reward", label = "Mean reward", type = "number"))
if (!is.null(p_col)) action_cols[[length(action_cols) + 1]] <- list(key = "mean_propensity", label = "Mean logging probability", type = "number")
action_cols[[length(action_cols) + 1]] <- list(key = "groups_missing", label = "Judged groups never trying it", type = "integer")
action_keys <- vapply(action_cols, function(c) c$key, character(1))
action_rows <- lapply(res$actions, function(a) stats::setNames(lapply(action_keys, function(k) a[[k]]), action_keys))
tables <- list(
  list(key = "episodes", title = "Episodes",
       columns = list(list(key = "metric", label = "Summary", type = "string"), list(key = "value", label = "Value", type = "number")),
       rows = metric_rows),
  list(key = "actions", title = "Actions logged", columns = action_cols, rows = action_rows),
  list(key = "support", title = "State groups where some action was never tried",
       columns = list(list(key = "group", label = "State group", type = "string"), list(key = "rows", label = "Decisions", type = "integer"),
                      list(key = "seen", label = "Actions tried", type = "integer"), list(key = "missing", label = "Never tried", type = "string")),
       rows = res$unsupported,
       note = sprintf("Groups with at least %d decisions; numeric state columns are cut into at most %d groups each. Largest groups first (up to 50).", min_cell, bins))
)
if (!is.null(p_col)) {
  tables[[length(tables) + 1]] <- list(
    key = "propensity", title = "Logging probabilities",
    columns = list(list(key = "metric", label = "Summary", type = "string"), list(key = "value", label = "Value", type = "number")),
    rows = data.frame(metric = c("Smallest", "Median", "Largest", sprintf("Share under %s", sprintf("%g", low)), "Outside (0, 1]"),
                      value = c(res$min_propensity, res$median_propensity, res$max_propensity, res$share_low_propensity, res$invalid_propensity))
  )
}
cs_publish(list(
  method = "decide.trajectories",
  methodVersion = "1.0.0",
  title = "Logged episodes",
  engine = cs_engine_info("stats", "codesplashr"),
  n = n,
  summary = summary,
  statistics = list(
    list(key = "episodes", label = "Episodes", value = E, format = "integer"),
    list(key = "decisions", label = "Decisions", value = n, format = "integer"),
    list(key = "mean_return", label = "Average discounted return", value = res$mean_return),
    list(key = "support", label = "Decisions where every action was tried", value = res$support_share, format = "percent")
  ),
  tables = tables,
  assumptions = assumptions,
  warnings = warnings,
  notes = list(sprintf("Rows ordered by %s (first appearance), then %s. Returns are discounted by %s per step from each episode's first decision. State groups: %s; a group is judged once it has %d decisions.",
                       ep_col, step_col, sprintf("%g", gamma), paste(states, collapse = ", "), min_cell)),
  values = values,
  charts = list(
    cs_chart("lengths", "histogram", "Decisions per episode", list(x = cs_col("Decisions per episode", as.numeric(res$lengths)))),
    cs_chart("returns", "histogram", sprintf("Discounted return per episode (γ = %s)", sprintf("%g", gamma)), list(x = cs_col("Discounted return", res$returns))),
    cs_chart("actions", "bar", "Actions logged", list(x = cs_col(a_col, action, levels = lv)))
  )
))
Python

60 episodes hold 640 decisions, 10.7 per episode on average; the average discounted return is 0.049. 100% of the judged decisions fall in state groups where every action was tried. The smallest logging probability is 0.100; 0.0% of decisions had one under 0.05.

Episodes
60
Decisions
640
Average discounted return
0.0487
Decisions where every action was tried
100.0%

To keep this page light, the plots are shown once, under the R tab.

Assumptions

  • Episodes are in order — Each step appears once per episode.
  • Logging probabilities — The smallest logging probability is 0.100.
  • Every action tried — 100% of the judged decisions fall in state groups where every action was tried; 0 of 12 groups miss at least one action.

Episodes

SummaryValue
Episodes60
Decisions640
Decisions per episode (mean)10.667
Decisions per episode (median)11
Shortest episode5
Longest episode14
Discounted return (mean, γ = 0.95)0.0487
Discounted return (SD)0.3972
Reward per decision (mean)0.0156

Actions logged

actionDecisionsShareMean rewardMean logging probabilityJudged groups never trying it
left10816.9%−0.05000.23150
stay12219.1%−0.05000.20000
right41064.1%0.05240.63270

State groups where some action was never tried

State groupDecisionsActions triedNever tried

Groups with at least 10 decisions; numeric state columns are cut into at most 4 groups each. Largest groups first (up to 50).

Logging probabilities

SummaryValue
Smallest0.1000
Median0.5000
Largest0.7000
Share under 0.050
Outside (0, 1]0
  • 18 of 60 episodes end without done = true; Learn and Evaluate treat each as ending at its last row.
  • Rows ordered by episode (first appearance), then step. Returns are discounted by 0.95 per step from each episode's first decision. State groups: cell, weather today; a group is judged once it has 10 decisions.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Logged episodes
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method decide.trajectories 1.0.0 · spec e642cf16864dcda7
# Dataset: pol_corridor (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
import numpy as np
import pandas as pd

import codesplash as cs
from codesplash.decide import trajectories as tj  # twin of codesplashr::cs_trajectories (counting and averaging only)

# %% Data
df = pd.read_parquet("tests/parity/fixtures/pol_corridor.parquet", columns=["episode", "step", "cell", "weather today", "action", "reward", "propensity", "done"])
n_input = len(df)
df["cell"] = pd.Categorical(df["cell"], categories=["c0", "c1", "c2", "c3", "c4", "c5"])  # stored level order
df["weather today"] = pd.Categorical(df["weather today"], categories=["rain", "sun"])  # stored level order
df["action"] = pd.Categorical(df["action"], categories=["left", "stay", "right"])  # stored level order
df["done"] = pd.Categorical(df["done"], categories=["false", "true"])  # stored level order
df = df.dropna(subset=["episode", "step", "cell", "weather today", "action", "reward", "propensity", "done"])  # listwise deletion over the analysis columns
df["cell"] = df["cell"].cat.remove_unused_categories()
df["weather today"] = df["weather today"].cat.remove_unused_categories()
df["action"] = df["action"].cat.remove_unused_categories()
df["done"] = df["done"].cat.remove_unused_categories()
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
    warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
    cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["episode", "step", "cell", "weather today", "action", "reward", "propensity", "done"])  # infinite values stop the run (registry/errors.yaml)

# %% Inputs
ep_col, step_col, a_col, r_col = "episode", "step", "action", "reward"
p_col = "propensity"  # optional: the logging probability of each logged action
done_col = "done"  # optional: true on the step that ended the episode
states = ["cell", "weather today"]
gamma = float(0.95)
bins = int(4)
min_cell = int(10)
low = float(0.05)


def as_flag(s):
    """Yes/no columns count as 1/0."""
    return (s.astype(str) == "true").to_numpy() if isinstance(s.dtype, pd.CategoricalDtype) else (s.to_numpy(dtype=float) != 0)


ep_keys = df[ep_col].astype(str).tolist() if isinstance(df[ep_col].dtype, pd.CategoricalDtype) else df[ep_col].to_numpy(dtype=float).tolist()
levels = [str(x) for x in df[a_col].cat.categories]
action = df[a_col].astype(str).to_numpy()
reward = as_flag(df[r_col]).astype(float) if isinstance(df[r_col].dtype, pd.CategoricalDtype) else df[r_col].to_numpy(dtype=float)
groups = tj.state_groups(
    [(c, df[c].astype(str).tolist() if isinstance(df[c].dtype, pd.CategoricalDtype) else df[c].to_numpy(dtype=float), isinstance(df[c].dtype, pd.CategoricalDtype)) for c in states],
    bins,
)

# %% Summarize
res = tj.summarize(
    ep_keys, df[step_col].to_numpy(dtype=float), action, levels, reward, groups,
    propensity=df[p_col].to_numpy(dtype=float) if p_col else None,
    done=as_flag(df[done_col]) if done_col else None,
    gamma=gamma, low=low, min_cell=min_cell,
)
E, n = res["n_episodes"], res["n_steps"]
if len(levels) < 2:
    warnings.append(f"Only one action appears in {a_col}: a policy learned from these logs can only copy it, and no other action can be judged.")
if res["max_length"] == 1:
    warnings.append("Every episode has one decision: this is a one-step (bandit) problem, and the Decisions studio's off-policy evaluation fits it better.")
if res["duplicate_steps"]:
    warnings.append(f"{res['duplicate_steps']} step value(s) repeat within an episode; Learn and Evaluate stop until each step is unique within its episode.")
if res["truncated_episodes"]:
    warnings.append(f"{res['truncated_episodes']} of {E} episodes end without {done_col} = true; Learn and Evaluate treat each as ending at its last row.")
if res["early_done_episodes"]:
    warnings.append(f"{res['early_done_episodes']} episode(s) mark {done_col} = true before their last row; the rows after it are still counted here.")

# %% Checks
assumptions = []
order_ok = res["duplicate_steps"] == 0 and not res["early_done_episodes"]
assumptions.append({
    "key": "episode_order", "label": "Episodes are in order",
    "status": "pass" if order_ok else "warn",
    "detail": "Each step appears once per episode." if order_ok else
              f"{res['duplicate_steps']} repeated step value(s); {res['early_done_episodes'] or 0} episode(s) end before their last row.",
})
if not p_col:
    assumptions.append({"key": "propensity", "label": "Logging probabilities", "status": "info",
                        "detail": "Not recorded. Learn can still run, but Evaluate and the doubly robust values need the logging probability of each action."})
elif res["invalid_propensity"]:
    assumptions.append({"key": "propensity", "label": "Logging probabilities", "status": "fail",
                        "detail": f"{res['invalid_propensity']} decision(s) have a logging probability outside (0, 1].", "statistic": res["invalid_propensity"]})
elif res["share_low_propensity"] > 0:
    assumptions.append({"key": "propensity", "label": "Logging probabilities", "status": "warn",
                        "detail": f"{res['share_low_propensity']:.1%} of decisions had a logging probability under {low:g} (smallest {res['min_propensity']:.3f}): a few episodes can dominate off-policy estimates.",
                        "statistic": res["min_propensity"]})
else:
    assumptions.append({"key": "propensity", "label": "Logging probabilities", "status": "pass",
                        "detail": f"The smallest logging probability is {res['min_propensity']:.3f}.", "statistic": res["min_propensity"]})
if res["support_share"] is None:
    assumptions.append({"key": "support", "label": "Every action tried", "status": "info",
                        "detail": f"No state group has {min_cell} decisions yet, so support can't be judged."})
else:
    ok = res["support_share"] >= 0.9
    assumptions.append({"key": "support", "label": "Every action tried", "status": "pass" if ok else "warn",
                        "detail": f"{res['support_share']:.0%} of the judged decisions fall in state groups where every action was tried; "
                                  f"{res['n_unsupported_groups']} of {res['n_judged_groups']} groups miss at least one action.",
                        "statistic": res["support_share"]})

# %% Result
summary = (
    f"{E:,} episodes hold {n:,} decisions, {res['mean_length']:.1f} per episode on average; the average discounted return is {res['mean_return']:.3f}. "
    + (f"{res['support_share']:.0%} of the judged decisions fall in state groups where every action was tried."
       if res["support_share"] is not None else f"No state group has {min_cell} decisions yet, so support can't be judged.")
    + (f" The smallest logging probability is {res['min_propensity']:.3f}; {res['share_low_propensity']:.1%} of decisions had one under {low:g}." if p_col else "")
)
values = {k: res[k] for k in ["n_episodes", "n_steps", "mean_length", "median_length", "min_length", "max_length", "mean_return", "sd_return",
                              "min_return", "max_return", "mean_reward", "duplicate_steps", "n_groups", "n_judged_groups", "n_unsupported_groups",
                              "support_share"]}
values["n_actions"] = len(levels)
# Without an end flag or logging probabilities these keys are null (nothing to count).
for k in ["truncated_episodes", "early_done_episodes", "min_propensity", "median_propensity", "max_propensity", "share_low_propensity", "invalid_propensity"]:
    values[k] = res[k]
metric_rows = [
    {"metric": "Episodes", "value": E},
    {"metric": "Decisions", "value": n},
    {"metric": "Decisions per episode (mean)", "value": res["mean_length"]},
    {"metric": "Decisions per episode (median)", "value": res["median_length"]},
    {"metric": "Shortest episode", "value": res["min_length"]},
    {"metric": "Longest episode", "value": res["max_length"]},
    {"metric": f"Discounted return (mean, γ = {gamma:g})", "value": res["mean_return"]},
    {"metric": "Discounted return (SD)", "value": res["sd_return"]},
    {"metric": "Reward per decision (mean)", "value": res["mean_reward"]},
]
action_cols = [{"key": "action", "label": a_col, "type": "string"}, {"key": "rows", "label": "Decisions", "type": "integer"},
               {"key": "share", "label": "Share", "type": "percent"}, {"key": "mean_reward", "label": "Mean reward", "type": "number"}]
if p_col:
    action_cols.append({"key": "mean_propensity", "label": "Mean logging probability", "type": "number"})
action_cols.append({"key": "groups_missing", "label": "Judged groups never trying it", "type": "integer"})
tables = [
    {"key": "episodes", "title": "Episodes",
     "columns": [{"key": "metric", "label": "Summary", "type": "string"}, {"key": "value", "label": "Value", "type": "number"}],
     "rows": metric_rows},
    {"key": "actions", "title": "Actions logged",
     "columns": action_cols,
     "rows": [{k: a[k] for k in [c["key"] for c in action_cols]} for a in res["actions"]]},
    {"key": "support", "title": "State groups where some action was never tried",
     "columns": [{"key": "group", "label": "State group", "type": "string"}, {"key": "rows", "label": "Decisions", "type": "integer"},
                 {"key": "seen", "label": "Actions tried", "type": "integer"}, {"key": "missing", "label": "Never tried", "type": "string"}],
     "rows": res["unsupported"],
     "note": f"Groups with at least {min_cell} decisions; numeric state columns are cut into at most {bins} groups each. Largest groups first (up to 50)."},
]
if p_col:
    tables.append({"key": "propensity", "title": "Logging probabilities",
                   "columns": [{"key": "metric", "label": "Summary", "type": "string"}, {"key": "value", "label": "Value", "type": "number"}],
                   "rows": [{"metric": "Smallest", "value": res["min_propensity"]}, {"metric": "Median", "value": res["median_propensity"]},
                            {"metric": "Largest", "value": res["max_propensity"]}, {"metric": f"Share under {low:g}", "value": res["share_low_propensity"]},
                            {"metric": "Outside (0, 1]", "value": res["invalid_propensity"]}]})
cs.publish({
    "method": "decide.trajectories",
    "methodVersion": "1.0.0",
    "title": "Logged episodes",
    "engine": cs.engine_info("numpy", "pandas"),
    "n": n,
    "summary": summary,
    "statistics": [
        {"key": "episodes", "label": "Episodes", "value": E, "format": "integer"},
        {"key": "decisions", "label": "Decisions", "value": n, "format": "integer"},
        {"key": "mean_return", "label": "Average discounted return", "value": res["mean_return"]},
        {"key": "support", "label": "Decisions where every action was tried", "value": res["support_share"], "format": "percent"},
    ],
    "tables": tables,
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": [
        f"Rows ordered by {ep_col} (first appearance), then {step_col}. Returns are discounted by {gamma:g} per step from each episode's first decision. "
        f"State groups: {', '.join(states)}; a group is judged once it has {min_cell} decisions.",
    ],
    "values": values,
    "charts": [
        cs.chart("lengths", "histogram", "Decisions per episode", {"x": cs.col("Decisions per episode", res["lengths"].astype(float))}),
        cs.chart("returns", "histogram", f"Discounted return per episode (γ = {gamma:g})", {"x": cs.col("Discounted return", res["returns"])}),
        cs.chart("actions", "bar", "Actions logged", {"x": cs.col(a_col, list(action), levels=levels)}),
    ],
})

These 60 corridor episodes hold 640 decisions. 100% of the judged decisions fall in state groups where all three actions were tried, and the smallest logging probability is 0.10.

06

A fixed rule tries nothing new

Predict

Predict first

Now the same episodes logged by a fixed rule: right when it's sunny, stay when it rains. What happens to the share of decisions in state groups where every action was tried?

About the sameMuch lowerHigher
Reveal

It collapses. A fixed rule takes one action in each situation, so no group has seen both.

Logged episodesRecorded · Python and R agreeRecorded 2026-11-21 · 24 values compared
R

60 episodes hold 640 decisions, 10.7 per episode on average; the average discounted return is 0.049. 0% of the judged decisions fall in state groups where every action was tried. The smallest logging probability is 1.000; 0.0% of decisions had one under 0.05.

Episodes
60
Decisions
640
Average discounted return
0.0487
Decisions where every action was tried
0.0%

Plots

Decisions per episodeHow is one numeric variable distributed?
View data
Decisions per episode
5
14
13
9
6
12
11
14
14
10
9
11
10
14
14
14
6
14
6
7
12
14
14
14
9
6
14
14
14
5
11
9
14
10
6
14
7
11
10
7
10
6
5
10
12
14
10
13
14
14
14
7
14
13
7
8
9
10
11
11
Discounted return per episode (γ = 0.95)How is one numeric variable distributed?
View data
Discounted return
0.5883
−0.5123
0.0537
0.2937
0.5089
0.1092
0.1675
−0.5123
−0.5123
0.2290
0.2937
0.1675
0.2290
−0.5123
0.0010
−0.5123
0.5089
−0.5123
0.5089
0.4334
0.1092
−0.5123
0.0010
−0.5123
0.2937
0.5089
−0.5123
−0.5123
−0.5123
0.5883
0.1675
0.2937
−0.5123
0.2290
0.5089
−0.5123
0.4334
0.1675
0.2290
0.4334
0.2290
0.5089
0.5883
0.2290
0.1092
−0.5123
0.2290
0.0537
−0.5123
−0.5123
−0.5123
0.4334
−0.5123
0.0537
0.4334
0.3618
0.2937
0.2290
0.1675
0.1675
Actions loggedHow often does each category occur?
View data
rule
right
right
stay
stay
stay
stay
right
right
right
right
right
right
right
stay
right
stay
stay
right
right
stay
stay
right
right
right
right
right
stay
stay
stay
stay
right
right
stay
right
stay
right
right
right
stay
stay
right
stay
stay
right
stay
right
stay
stay
stay
right
right
right
stay
right
stay
stay
stay
right
right
stay

First 60 of 640 rows.

Assumptions

  • Episodes are in order — Each step appears once per episode.
  • Logging probabilities — The smallest logging probability is 1.000.
  • Every action tried — 0% of the judged decisions fall in state groups where every action was tried; 12 of 12 groups miss at least one action.

Episodes

SummaryValue
Episodes60
Decisions640
Decisions per episode (mean)10.667
Decisions per episode (median)11
Shortest episode5
Longest episode14
Discounted return (mean, γ = 0.95)0.0487
Discounted return (SD)0.3972
Reward per decision (mean)0.0156

Actions logged

ruleDecisionsShareMean rewardMean logging probabilityJudged groups never trying it
right39461.6%0.021116
stay24638.4%0.006916

State groups where some action was never tried

State groupDecisionsActions triedNever tried
cell: c2, weather today: sun951stay
cell: c1, weather today: sun781stay
cell: c3, weather today: sun751stay
cell: c4, weather today: sun651stay
cell: c2, weather today: rain561right
cell: c1, weather today: rain451right
cell: c4, weather today: rain451right
cell: c3, weather today: rain441right
cell: c5, weather today: sun411stay
cell: c0, weather today: sun401stay
cell: c5, weather today: rain291right
cell: c0, weather today: rain271right

Groups with at least 5 decisions; numeric state columns are cut into at most 4 groups each. Largest groups first (up to 50).

Logging probabilities

SummaryValue
Smallest1
Median1
Largest1
Share under 0.050
Outside (0, 1]0
  • 18 of 60 episodes end without done = true; Learn and Evaluate treat each as ending at its last row.
  • Rows ordered by episode (first appearance), then step. Returns are discounted by 0.95 per step from each episode's first decision. State groups: cell, weather today; a group is judged once it has 5 decisions.
The exact R script · R R version 4.5.1 (2025-06-13)
# Logged episodes
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method decide.trajectories 1.0.0 · spec 0506f18a2c852fab
# Dataset: pol_corridor (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr) # cs_trajectories(): twin of codesplash.decide.trajectories (counting and averaging only)

# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/pol_corridor.parquet", col_select = c("episode", "step", "cell", "weather today", "rule", "reward", "p_one", "done")))
n_input <- nrow(df)
df[["cell"]] <- factor(df[["cell"]], levels = c("c0", "c1", "c2", "c3", "c4", "c5"))  # stored level order
df[["weather today"]] <- factor(df[["weather today"]], levels = c("rain", "sun"))  # stored level order
df[["rule"]] <- factor(df[["rule"]], levels = c("right", "stay"))  # stored level order
df[["done"]] <- factor(df[["done"]], levels = c("false", "true"))  # stored level order
df <- df[stats::complete.cases(df[c("episode", "step", "cell", "weather today", "rule", "reward", "p_one", "done")]), , drop = FALSE]  # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
  warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("episode", "step", "cell", "weather today", "rule", "reward", "p_one", "done"))  # infinite values stop the run (registry/errors.yaml)

# %% Inputs
ep_col <- "episode"
step_col <- "step"
a_col <- "rule"
r_col <- "reward"
p_col <- "p_one" # optional: the logging probability of each logged action
done_col <- "done" # optional: true on the step that ended the episode
states <- c("cell", "weather today")
gamma <- as.numeric(0.95)
bins <- as.integer(4)
min_cell <- as.integer(5)
low <- as.numeric(0.05)

# Yes/no columns count as 1/0.
as_flag <- function(v) if (is.factor(v)) as.character(v) == "true" else as.numeric(v) != 0

ep_keys <- if (is.factor(df[[ep_col]])) as.character(df[[ep_col]]) else as.numeric(df[[ep_col]])
lv <- levels(df[[a_col]])
action <- as.character(df[[a_col]])
reward <- if (is.factor(df[[r_col]])) as.numeric(as_flag(df[[r_col]])) else as.numeric(df[[r_col]])
groups <- cs_trajectories_groups(lapply(states, function(c) {
  v <- df[[c]]
  list(name = c, values = if (is.factor(v)) as.character(v) else as.numeric(v), categorical = is.factor(v))
}), bins)

# %% Summarize
res <- cs_trajectories(ep_keys, as.numeric(df[[step_col]]), action, lv, reward, groups,
                       propensity = if (!is.null(p_col)) as.numeric(df[[p_col]]) else NULL,
                       done = if (!is.null(done_col)) as_flag(df[[done_col]]) else NULL,
                       gamma = gamma, low = low, min_cell = min_cell)
E <- res$n_episodes
n <- res$n_steps
if (length(lv) < 2) {
  warnings <- c(warnings, sprintf("Only one action appears in %s: a policy learned from these logs can only copy it, and no other action can be judged.", a_col))
}
if (res$max_length == 1) {
  warnings <- c(warnings, "Every episode has one decision: this is a one-step (bandit) problem, and the Decisions studio's off-policy evaluation fits it better.")
}
if (res$duplicate_steps > 0) {
  warnings <- c(warnings, sprintf("%d step value(s) repeat within an episode; Learn and Evaluate stop until each step is unique within its episode.", res$duplicate_steps))
}
if (!is.null(res$truncated_episodes) && res$truncated_episodes > 0) {
  warnings <- c(warnings, sprintf("%d of %d episodes end without %s = true; Learn and Evaluate treat each as ending at its last row.", res$truncated_episodes, E, done_col))
}
if (!is.null(res$early_done_episodes) && res$early_done_episodes > 0) {
  warnings <- c(warnings, sprintf("%d episode(s) mark %s = true before their last row; the rows after it are still counted here.", res$early_done_episodes, done_col))
}

# %% Checks
early <- if (is.null(res$early_done_episodes)) 0L else res$early_done_episodes
order_ok <- res$duplicate_steps == 0 && early == 0
assumptions <- list(list(
  key = "episode_order", label = "Episodes are in order", status = if (order_ok) "pass" else "warn",
  detail = if (order_ok) "Each step appears once per episode." else sprintf("%d repeated step value(s); %d episode(s) end before their last row.", res$duplicate_steps, early)
))
pct1 <- function(x) sprintf("%.1f%%", 100 * x)
pct0 <- function(x) sprintf("%.0f%%", 100 * x)
assumptions[[2]] <- if (is.null(p_col)) {
  list(key = "propensity", label = "Logging probabilities", status = "info",
       detail = "Not recorded. Learn can still run, but Evaluate and the doubly robust values need the logging probability of each action.")
} else if (res$invalid_propensity > 0) {
  list(key = "propensity", label = "Logging probabilities", status = "fail",
       detail = sprintf("%d decision(s) have a logging probability outside (0, 1].", res$invalid_propensity), statistic = res$invalid_propensity)
} else if (res$share_low_propensity > 0) {
  list(key = "propensity", label = "Logging probabilities", status = "warn",
       detail = sprintf("%s of decisions had a logging probability under %s (smallest %.3f): a few episodes can dominate off-policy estimates.",
                        pct1(res$share_low_propensity), sprintf("%g", low), res$min_propensity),
       statistic = res$min_propensity)
} else {
  list(key = "propensity", label = "Logging probabilities", status = "pass",
       detail = sprintf("The smallest logging probability is %.3f.", res$min_propensity), statistic = res$min_propensity)
}
assumptions[[3]] <- if (is.null(res$support_share)) {
  list(key = "support", label = "Every action tried", status = "info",
       detail = sprintf("No state group has %d decisions yet, so support can't be judged.", min_cell))
} else {
  list(key = "support", label = "Every action tried", status = if (res$support_share >= 0.9) "pass" else "warn",
       detail = sprintf("%s of the judged decisions fall in state groups where every action was tried; %d of %d groups miss at least one action.",
                        pct0(res$support_share), res$n_unsupported_groups, res$n_judged_groups),
       statistic = res$support_share)
}

# %% Result
summary <- paste0(
  sprintf("%s episodes hold %s decisions, %.1f per episode on average; the average discounted return is %.3f. ",
          format(E, big.mark = ","), format(n, big.mark = ","), res$mean_length, res$mean_return),
  if (!is.null(res$support_share)) sprintf("%s of the judged decisions fall in state groups where every action was tried.", pct0(res$support_share))
  else sprintf("No state group has %d decisions yet, so support can't be judged.", min_cell),
  if (!is.null(p_col)) sprintf(" The smallest logging probability is %.3f; %s of decisions had one under %s.", res$min_propensity,
                               pct1(res$share_low_propensity), sprintf("%g", low)) else ""
)
keys <- c("n_episodes", "n_steps", "mean_length", "median_length", "min_length", "max_length", "mean_return", "sd_return",
          "min_return", "max_return", "mean_reward", "duplicate_steps", "n_groups", "n_judged_groups", "n_unsupported_groups", "support_share")
values <- stats::setNames(lapply(keys, function(k) res[[k]]), keys)
values$n_actions <- length(lv)
# Without an end flag or logging probabilities these keys are null (nothing to count).
for (k in c("truncated_episodes", "early_done_episodes", "min_propensity", "median_propensity", "max_propensity", "share_low_propensity",
            "invalid_propensity")) values[k] <- list(res[[k]])
na_null <- function(x) if (is.null(x)) NA_real_ else x
metric_rows <- data.frame(
  metric = c("Episodes", "Decisions", "Decisions per episode (mean)", "Decisions per episode (median)", "Shortest episode", "Longest episode",
             sprintf("Discounted return (mean, γ = %s)", sprintf("%g", gamma)), "Discounted return (SD)", "Reward per decision (mean)"),
  value = c(E, n, res$mean_length, res$median_length, res$min_length, res$max_length, res$mean_return, na_null(res$sd_return), res$mean_reward)
)
action_cols <- list(list(key = "action", label = a_col, type = "string"), list(key = "rows", label = "Decisions", type = "integer"),
                    list(key = "share", label = "Share", type = "percent"), list(key = "mean_reward", label = "Mean reward", type = "number"))
if (!is.null(p_col)) action_cols[[length(action_cols) + 1]] <- list(key = "mean_propensity", label = "Mean logging probability", type = "number")
action_cols[[length(action_cols) + 1]] <- list(key = "groups_missing", label = "Judged groups never trying it", type = "integer")
action_keys <- vapply(action_cols, function(c) c$key, character(1))
action_rows <- lapply(res$actions, function(a) stats::setNames(lapply(action_keys, function(k) a[[k]]), action_keys))
tables <- list(
  list(key = "episodes", title = "Episodes",
       columns = list(list(key = "metric", label = "Summary", type = "string"), list(key = "value", label = "Value", type = "number")),
       rows = metric_rows),
  list(key = "actions", title = "Actions logged", columns = action_cols, rows = action_rows),
  list(key = "support", title = "State groups where some action was never tried",
       columns = list(list(key = "group", label = "State group", type = "string"), list(key = "rows", label = "Decisions", type = "integer"),
                      list(key = "seen", label = "Actions tried", type = "integer"), list(key = "missing", label = "Never tried", type = "string")),
       rows = res$unsupported,
       note = sprintf("Groups with at least %d decisions; numeric state columns are cut into at most %d groups each. Largest groups first (up to 50).", min_cell, bins))
)
if (!is.null(p_col)) {
  tables[[length(tables) + 1]] <- list(
    key = "propensity", title = "Logging probabilities",
    columns = list(list(key = "metric", label = "Summary", type = "string"), list(key = "value", label = "Value", type = "number")),
    rows = data.frame(metric = c("Smallest", "Median", "Largest", sprintf("Share under %s", sprintf("%g", low)), "Outside (0, 1]"),
                      value = c(res$min_propensity, res$median_propensity, res$max_propensity, res$share_low_propensity, res$invalid_propensity))
  )
}
cs_publish(list(
  method = "decide.trajectories",
  methodVersion = "1.0.0",
  title = "Logged episodes",
  engine = cs_engine_info("stats", "codesplashr"),
  n = n,
  summary = summary,
  statistics = list(
    list(key = "episodes", label = "Episodes", value = E, format = "integer"),
    list(key = "decisions", label = "Decisions", value = n, format = "integer"),
    list(key = "mean_return", label = "Average discounted return", value = res$mean_return),
    list(key = "support", label = "Decisions where every action was tried", value = res$support_share, format = "percent")
  ),
  tables = tables,
  assumptions = assumptions,
  warnings = warnings,
  notes = list(sprintf("Rows ordered by %s (first appearance), then %s. Returns are discounted by %s per step from each episode's first decision. State groups: %s; a group is judged once it has %d decisions.",
                       ep_col, step_col, sprintf("%g", gamma), paste(states, collapse = ", "), min_cell)),
  values = values,
  charts = list(
    cs_chart("lengths", "histogram", "Decisions per episode", list(x = cs_col("Decisions per episode", as.numeric(res$lengths)))),
    cs_chart("returns", "histogram", sprintf("Discounted return per episode (γ = %s)", sprintf("%g", gamma)), list(x = cs_col("Discounted return", res$returns))),
    cs_chart("actions", "bar", "Actions logged", list(x = cs_col(a_col, action, levels = lv)))
  )
))
Python

60 episodes hold 640 decisions, 10.7 per episode on average; the average discounted return is 0.049. 0% of the judged decisions fall in state groups where every action was tried. The smallest logging probability is 1.000; 0.0% of decisions had one under 0.05.

Episodes
60
Decisions
640
Average discounted return
0.0487
Decisions where every action was tried
0.0%

To keep this page light, the plots are shown once, under the R tab.

Assumptions

  • Episodes are in order — Each step appears once per episode.
  • Logging probabilities — The smallest logging probability is 1.000.
  • Every action tried — 0% of the judged decisions fall in state groups where every action was tried; 12 of 12 groups miss at least one action.

Episodes

SummaryValue
Episodes60
Decisions640
Decisions per episode (mean)10.667
Decisions per episode (median)11
Shortest episode5
Longest episode14
Discounted return (mean, γ = 0.95)0.0487
Discounted return (SD)0.3972
Reward per decision (mean)0.0156

Actions logged

ruleDecisionsShareMean rewardMean logging probabilityJudged groups never trying it
right39461.6%0.021116
stay24638.4%0.006916

State groups where some action was never tried

State groupDecisionsActions triedNever tried
cell: c2, weather today: sun951stay
cell: c1, weather today: sun781stay
cell: c3, weather today: sun751stay
cell: c4, weather today: sun651stay
cell: c2, weather today: rain561right
cell: c1, weather today: rain451right
cell: c4, weather today: rain451right
cell: c3, weather today: rain441right
cell: c5, weather today: sun411stay
cell: c0, weather today: sun401stay
cell: c5, weather today: rain291right
cell: c0, weather today: rain271right

Groups with at least 5 decisions; numeric state columns are cut into at most 4 groups each. Largest groups first (up to 50).

Logging probabilities

SummaryValue
Smallest1
Median1
Largest1
Share under 0.050
Outside (0, 1]0
  • 18 of 60 episodes end without done = true; Learn and Evaluate treat each as ending at its last row.
  • Rows ordered by episode (first appearance), then step. Returns are discounted by 0.95 per step from each episode's first decision. State groups: cell, weather today; a group is judged once it has 5 decisions.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Logged episodes
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method decide.trajectories 1.0.0 · spec 0506f18a2c852fab
# Dataset: pol_corridor (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
import numpy as np
import pandas as pd

import codesplash as cs
from codesplash.decide import trajectories as tj  # twin of codesplashr::cs_trajectories (counting and averaging only)

# %% Data
df = pd.read_parquet("tests/parity/fixtures/pol_corridor.parquet", columns=["episode", "step", "cell", "weather today", "rule", "reward", "p_one", "done"])
n_input = len(df)
df["cell"] = pd.Categorical(df["cell"], categories=["c0", "c1", "c2", "c3", "c4", "c5"])  # stored level order
df["weather today"] = pd.Categorical(df["weather today"], categories=["rain", "sun"])  # stored level order
df["rule"] = pd.Categorical(df["rule"], categories=["right", "stay"])  # stored level order
df["done"] = pd.Categorical(df["done"], categories=["false", "true"])  # stored level order
df = df.dropna(subset=["episode", "step", "cell", "weather today", "rule", "reward", "p_one", "done"])  # listwise deletion over the analysis columns
df["cell"] = df["cell"].cat.remove_unused_categories()
df["weather today"] = df["weather today"].cat.remove_unused_categories()
df["rule"] = df["rule"].cat.remove_unused_categories()
df["done"] = df["done"].cat.remove_unused_categories()
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
    warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
    cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["episode", "step", "cell", "weather today", "rule", "reward", "p_one", "done"])  # infinite values stop the run (registry/errors.yaml)

# %% Inputs
ep_col, step_col, a_col, r_col = "episode", "step", "rule", "reward"
p_col = "p_one"  # optional: the logging probability of each logged action
done_col = "done"  # optional: true on the step that ended the episode
states = ["cell", "weather today"]
gamma = float(0.95)
bins = int(4)
min_cell = int(5)
low = float(0.05)


def as_flag(s):
    """Yes/no columns count as 1/0."""
    return (s.astype(str) == "true").to_numpy() if isinstance(s.dtype, pd.CategoricalDtype) else (s.to_numpy(dtype=float) != 0)


ep_keys = df[ep_col].astype(str).tolist() if isinstance(df[ep_col].dtype, pd.CategoricalDtype) else df[ep_col].to_numpy(dtype=float).tolist()
levels = [str(x) for x in df[a_col].cat.categories]
action = df[a_col].astype(str).to_numpy()
reward = as_flag(df[r_col]).astype(float) if isinstance(df[r_col].dtype, pd.CategoricalDtype) else df[r_col].to_numpy(dtype=float)
groups = tj.state_groups(
    [(c, df[c].astype(str).tolist() if isinstance(df[c].dtype, pd.CategoricalDtype) else df[c].to_numpy(dtype=float), isinstance(df[c].dtype, pd.CategoricalDtype)) for c in states],
    bins,
)

# %% Summarize
res = tj.summarize(
    ep_keys, df[step_col].to_numpy(dtype=float), action, levels, reward, groups,
    propensity=df[p_col].to_numpy(dtype=float) if p_col else None,
    done=as_flag(df[done_col]) if done_col else None,
    gamma=gamma, low=low, min_cell=min_cell,
)
E, n = res["n_episodes"], res["n_steps"]
if len(levels) < 2:
    warnings.append(f"Only one action appears in {a_col}: a policy learned from these logs can only copy it, and no other action can be judged.")
if res["max_length"] == 1:
    warnings.append("Every episode has one decision: this is a one-step (bandit) problem, and the Decisions studio's off-policy evaluation fits it better.")
if res["duplicate_steps"]:
    warnings.append(f"{res['duplicate_steps']} step value(s) repeat within an episode; Learn and Evaluate stop until each step is unique within its episode.")
if res["truncated_episodes"]:
    warnings.append(f"{res['truncated_episodes']} of {E} episodes end without {done_col} = true; Learn and Evaluate treat each as ending at its last row.")
if res["early_done_episodes"]:
    warnings.append(f"{res['early_done_episodes']} episode(s) mark {done_col} = true before their last row; the rows after it are still counted here.")

# %% Checks
assumptions = []
order_ok = res["duplicate_steps"] == 0 and not res["early_done_episodes"]
assumptions.append({
    "key": "episode_order", "label": "Episodes are in order",
    "status": "pass" if order_ok else "warn",
    "detail": "Each step appears once per episode." if order_ok else
              f"{res['duplicate_steps']} repeated step value(s); {res['early_done_episodes'] or 0} episode(s) end before their last row.",
})
if not p_col:
    assumptions.append({"key": "propensity", "label": "Logging probabilities", "status": "info",
                        "detail": "Not recorded. Learn can still run, but Evaluate and the doubly robust values need the logging probability of each action."})
elif res["invalid_propensity"]:
    assumptions.append({"key": "propensity", "label": "Logging probabilities", "status": "fail",
                        "detail": f"{res['invalid_propensity']} decision(s) have a logging probability outside (0, 1].", "statistic": res["invalid_propensity"]})
elif res["share_low_propensity"] > 0:
    assumptions.append({"key": "propensity", "label": "Logging probabilities", "status": "warn",
                        "detail": f"{res['share_low_propensity']:.1%} of decisions had a logging probability under {low:g} (smallest {res['min_propensity']:.3f}): a few episodes can dominate off-policy estimates.",
                        "statistic": res["min_propensity"]})
else:
    assumptions.append({"key": "propensity", "label": "Logging probabilities", "status": "pass",
                        "detail": f"The smallest logging probability is {res['min_propensity']:.3f}.", "statistic": res["min_propensity"]})
if res["support_share"] is None:
    assumptions.append({"key": "support", "label": "Every action tried", "status": "info",
                        "detail": f"No state group has {min_cell} decisions yet, so support can't be judged."})
else:
    ok = res["support_share"] >= 0.9
    assumptions.append({"key": "support", "label": "Every action tried", "status": "pass" if ok else "warn",
                        "detail": f"{res['support_share']:.0%} of the judged decisions fall in state groups where every action was tried; "
                                  f"{res['n_unsupported_groups']} of {res['n_judged_groups']} groups miss at least one action.",
                        "statistic": res["support_share"]})

# %% Result
summary = (
    f"{E:,} episodes hold {n:,} decisions, {res['mean_length']:.1f} per episode on average; the average discounted return is {res['mean_return']:.3f}. "
    + (f"{res['support_share']:.0%} of the judged decisions fall in state groups where every action was tried."
       if res["support_share"] is not None else f"No state group has {min_cell} decisions yet, so support can't be judged.")
    + (f" The smallest logging probability is {res['min_propensity']:.3f}; {res['share_low_propensity']:.1%} of decisions had one under {low:g}." if p_col else "")
)
values = {k: res[k] for k in ["n_episodes", "n_steps", "mean_length", "median_length", "min_length", "max_length", "mean_return", "sd_return",
                              "min_return", "max_return", "mean_reward", "duplicate_steps", "n_groups", "n_judged_groups", "n_unsupported_groups",
                              "support_share"]}
values["n_actions"] = len(levels)
# Without an end flag or logging probabilities these keys are null (nothing to count).
for k in ["truncated_episodes", "early_done_episodes", "min_propensity", "median_propensity", "max_propensity", "share_low_propensity", "invalid_propensity"]:
    values[k] = res[k]
metric_rows = [
    {"metric": "Episodes", "value": E},
    {"metric": "Decisions", "value": n},
    {"metric": "Decisions per episode (mean)", "value": res["mean_length"]},
    {"metric": "Decisions per episode (median)", "value": res["median_length"]},
    {"metric": "Shortest episode", "value": res["min_length"]},
    {"metric": "Longest episode", "value": res["max_length"]},
    {"metric": f"Discounted return (mean, γ = {gamma:g})", "value": res["mean_return"]},
    {"metric": "Discounted return (SD)", "value": res["sd_return"]},
    {"metric": "Reward per decision (mean)", "value": res["mean_reward"]},
]
action_cols = [{"key": "action", "label": a_col, "type": "string"}, {"key": "rows", "label": "Decisions", "type": "integer"},
               {"key": "share", "label": "Share", "type": "percent"}, {"key": "mean_reward", "label": "Mean reward", "type": "number"}]
if p_col:
    action_cols.append({"key": "mean_propensity", "label": "Mean logging probability", "type": "number"})
action_cols.append({"key": "groups_missing", "label": "Judged groups never trying it", "type": "integer"})
tables = [
    {"key": "episodes", "title": "Episodes",
     "columns": [{"key": "metric", "label": "Summary", "type": "string"}, {"key": "value", "label": "Value", "type": "number"}],
     "rows": metric_rows},
    {"key": "actions", "title": "Actions logged",
     "columns": action_cols,
     "rows": [{k: a[k] for k in [c["key"] for c in action_cols]} for a in res["actions"]]},
    {"key": "support", "title": "State groups where some action was never tried",
     "columns": [{"key": "group", "label": "State group", "type": "string"}, {"key": "rows", "label": "Decisions", "type": "integer"},
                 {"key": "seen", "label": "Actions tried", "type": "integer"}, {"key": "missing", "label": "Never tried", "type": "string"}],
     "rows": res["unsupported"],
     "note": f"Groups with at least {min_cell} decisions; numeric state columns are cut into at most {bins} groups each. Largest groups first (up to 50)."},
]
if p_col:
    tables.append({"key": "propensity", "title": "Logging probabilities",
                   "columns": [{"key": "metric", "label": "Summary", "type": "string"}, {"key": "value", "label": "Value", "type": "number"}],
                   "rows": [{"metric": "Smallest", "value": res["min_propensity"]}, {"metric": "Median", "value": res["median_propensity"]},
                            {"metric": "Largest", "value": res["max_propensity"]}, {"metric": f"Share under {low:g}", "value": res["share_low_propensity"]},
                            {"metric": "Outside (0, 1]", "value": res["invalid_propensity"]}]})
cs.publish({
    "method": "decide.trajectories",
    "methodVersion": "1.0.0",
    "title": "Logged episodes",
    "engine": cs.engine_info("numpy", "pandas"),
    "n": n,
    "summary": summary,
    "statistics": [
        {"key": "episodes", "label": "Episodes", "value": E, "format": "integer"},
        {"key": "decisions", "label": "Decisions", "value": n, "format": "integer"},
        {"key": "mean_return", "label": "Average discounted return", "value": res["mean_return"]},
        {"key": "support", "label": "Decisions where every action was tried", "value": res["support_share"], "format": "percent"},
    ],
    "tables": tables,
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": [
        f"Rows ordered by {ep_col} (first appearance), then {step_col}. Returns are discounted by {gamma:g} per step from each episode's first decision. "
        f"State groups: {', '.join(states)}; a group is judged once it has {min_cell} decisions.",
    ],
    "values": values,
    "charts": [
        cs.chart("lengths", "histogram", "Decisions per episode", {"x": cs.col("Decisions per episode", res["lengths"].astype(float))}),
        cs.chart("returns", "histogram", f"Discounted return per episode (γ = {gamma:g})", {"x": cs.col("Discounted return", res["returns"])}),
        cs.chart("actions", "bar", "Actions logged", {"x": cs.col(a_col, list(action), levels=levels)}),
    ],
})

0% of the judged decisions are in fully supported groups, and 12 of 12 groups miss an action. No offline method can say what the other action would have done there.

07

Compare honestly

Reflect

A comparison table lists each learned or evaluated policy with its estimated value, its interval, the logged policy's value and the effective number of episodes. Two habits keep it honest:

  • When two intervals overlap, the data don't rank those policies.
  • When a value rests on a small share of episodes' worth of weight, the policy strays far from the logs, and the estimate is fragile.
08

Check your understanding

Checkpoint

Check yourself

Fitted Q iteration reports a much higher value than conservative Q-learning on the same episodes, and its estimate rests on very few effective episodes. What's the most likely reason?

Show the answer

Answer: b

Few effective episodes mean the new policy disagrees with the logs most of the time. The value behind those choices is a model's guess, not something the logs showed.

Check yourself

The best learned policy's interval lies wholly above the logged policy's value. What's the right next step?

Show the answer

Answer: b

Off-policy evaluation screens policies cheaply. It assumes the propensities are right and nothing unrecorded drove both the actions and the rewards. A small live trial checks those assumptions.

09

Try it

In the app

In Studios, open Policy learning. Start from Practice on a built-in environment to work where the best policy is known exactly, or from Learn from logged episodes with your own table: one row per decision, with the episode, step, state, action, reward and, ideally, the logging probability. Check runs the summary above on your data before you learn anything.

10

Recap

Recap
  • Episode problems need policies judged by their total reward, not the next one.
  • Episode weights multiply across steps, so watch the effective sample size.
  • Offline learning must stay near the logged actions; conservative methods are built to.
  • Overlapping intervals don't rank policies. Try a promising policy on a small share first.

Concepts in this lesson