Skip to content

Which input matters?

Rank inputs with tornado and spider charts, then use Sobol indices and Morris screening when inputs interact.

Applied ~11 min9 steps

What runs in CodeSplash

You will be able to

  • Read a tornado chart, and name what it assumes
  • Tell first-order from total Sobol indices
  • Use Morris screening when a model is slow to run

Read first

01

Where should you look next?

Read

You have limited time to refine your model. Which input's forecast is worth improving?

Sensitivity analysis ranks inputs by how much they move a KPI. It tells you what to measure, where to hedge, and what you can stop worrying about.

02

One at a time

Predict

Predict first

A tornado chartTornado chartMoves each input alone between a low and a high value and ranks inputs by how far the result moves. moves each input alone, from a low to a high value, with the others held at base. Base profit is 3,733. Which input do you expect to swing profit most?

DemandPriceUnit cost
Reveal

demand, with a swing of 3,682. The bars are sorted, which gives the shape its name.

03

Read the chart

In the app
Sensitivity (Tornado): ProfitRecorded · Python and R agreeRecorded 2026-11-25 · 22 values compared
R

demand moves Profit the most.

Base case
3733.33
Largest effect
3681.87

Plots

TornadoWhich uncertain inputs move the outcome most when each is varied alone?
View data
KPI at high valueInputKPI at low value
4766.67demand1084.79
2853.33unit_cost4613.33
4625.40price2947.72

One-way sensitivity (largest swing first)

InputLow valueHigh valueKPI at lowKPI at highSwing
demand743.691256.311084.794766.673681.87
unit_cost5.2006.8004613.332853.331,760
price9.54811.2252947.724625.401677.68
  • Inputs are set by their quantile functions; the base case uses each input's base value (its mean unless set).
The exact R script · R R version 4.5.1 (2025-06-13)
# Sensitivity analysis of a scenario model
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method simulate.sensitivity 1.0.0 · spec 7d839170de4c7937
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr) # cs_sim_*: sensitivity designs on the shared random stream (twin of codesplash.sim)

# %% Model
model <- cs_sim_load("{\"inputs\":[{\"name\":\"demand\",\"dist\":\"normal\",\"params\":{\"mean\":1000,\"sd\":200},\"min\":0},{\"name\":\"price\",\"dist\":\"triangular\",\"params\":{\"min\":9,\"mode\":10,\"max\":12}},{\"name\":\"unit_cost\",\"dist\":\"uniform\",\"params\":{\"min\":5,\"max\":7}}],\"decisions\":[{\"name\":\"order\",\"value\":1100,\"min\":600,\"max\":1600}],\"formulas\":[{\"name\":\"sales\",\"expr\":\"min(demand, order)\"},{\"name\":\"profit\",\"expr\":\"price * sales - unit_cost * order\"}],\"kpis\":[{\"name\":\"profit\",\"label\":\"Profit\"}],\"correlations\":[]}")
ANALYSIS <- "tornado" # tornado | spider | sobol | morris
KPI <- "" # empty = the model's first KPI
if (!nzchar(KPI)) KPI <- NULL
warnings <- list(); tables <- list(); charts <- list()
labels <- list()
for (k in model$kpis) labels[[as.character(k$name)]] <- if (!is.null(k$label) && nzchar(k$label)) k$label else as.character(k$name)
col_of <- function(rows, key) vapply(rows, function(r) as.numeric(r[[key]]), numeric(1))
chr_of <- function(rows, key) vapply(rows, function(r) as.character(r[[key]]), character(1))

# %% Analyze
values <- list(analysis = ANALYSIS)
if (ANALYSIS == "tornado") {
  # One input at a time at its low / high value, everything else at its base case.
  res <- cs_sim_tornado(model, KPI, 10, 90, FALSE)
  rows <- res$rows
  for (r in rows) {
    nm <- r$input
    values[[sprintf("swing[%s]", nm)]] <- r$swing
    values[[sprintf("kpi_low[%s]", nm)]] <- r$kpi_low
    values[[sprintf("kpi_high[%s]", nm)]] <- r$kpi_high
    values[[sprintf("low_value[%s]", nm)]] <- r$low_value
    values[[sprintf("high_value[%s]", nm)]] <- r$high_value
  }
  values$top_input <- if (length(rows)) rows[[1]]$input else NA
  values$top_value <- if (length(rows)) rows[[1]]$swing else NA
  tables[[1]] <- list(
    key = "tornado", title = "One-way sensitivity (largest swing first)",
    columns = list(
      list(key = "input", label = "Input", type = "string"), list(key = "low_value", label = "Low value", type = "number"),
      list(key = "high_value", label = "High value", type = "number"), list(key = "kpi_low", label = "KPI at low", type = "number"),
      list(key = "kpi_high", label = "KPI at high", type = "number"), list(key = "swing", label = "Swing", type = "number")
    ),
    rows = rows
  )
  charts[[1]] <- cs_chart(
    "tornado", "tornado", "Tornado",
    list(input = cs_col("Input", chr_of(rows, "input")), low = cs_col("KPI at low value", col_of(rows, "kpi_low")),
         high = cs_col("KPI at high value", col_of(rows, "kpi_high"))),
    controls = list(base = res$base)
  )
} else if (ANALYSIS == "spider") {
  changes <- c(-50, -25, -10, 0, 10, 25, 50)
  res <- cs_sim_spider(model, KPI, changes, FALSE)
  rows <- res$rows
  for (r in rows) values[[sprintf("spider[%s,%s]", r$input, sprintf("%g", r$change))]] <- r$kpi
  ins <- unique(chr_of(rows, "input"))
  rng <- vapply(ins, function(nm) {
    k <- col_of(Filter(function(r) r$input == nm, rows), "kpi")
    max(k) - min(k)
  }, numeric(1))
  ord <- order(-rng, seq_along(ins))
  values$top_input <- if (length(ins)) ins[ord[1]] else NA
  values$top_value <- if (length(ins)) unname(rng[ord[1]]) else NA
  if (length(res$skipped)) warnings <- c(warnings, sprintf("Left out (base value 0, so a percentage change is undefined): %s.", paste(res$skipped, collapse = ", ")))
  tables[[1]] <- list(
    key = "spider", title = "KPI as each input changes from its base value",
    columns = list(list(key = "input", label = "Input", type = "string"), list(key = "change", label = "Change (%)", type = "number"),
                   list(key = "value", label = "Input value", type = "number"), list(key = "kpi", label = "KPI", type = "number")),
    rows = rows
  )
  charts[[1]] <- cs_chart(
    "spider", "spider", "Spider",
    list(change = cs_col("Change from base (%)", col_of(rows, "change")), kpi = cs_col("KPI", col_of(rows, "kpi")),
         input = cs_col("Input", chr_of(rows, "input")))
  )
} else if (ANALYSIS == "sobol") {
  # Saltelli A/B/AB_i design from the shared stream; Saltelli (2010) first-order, Jansen total indices.
  # Equivalent idiom: sensitivity::soboljansen(model, X1, X2, nboot) — with R's own random draws.
  res <- cs_sim_sobol(model, KPI, 1024, 1, 200, 0.95)
  rows <- res$rows
  for (r in rows) for (key in c("s1", "st", "s1_low", "s1_high", "st_low", "st_high")) values[[sprintf("%s[%s]", key, r$input)]] <- r[[key]]
  st <- col_of(rows, "st")
  top <- which.max(st)
  values$top_input <- if (length(rows)) rows[[top]]$input else NA
  values$top_value <- if (length(rows)) st[top] else NA
  values$variance <- res$variance
  values$evaluations <- res$evaluations
  tables[[1]] <- list(
    key = "sobol", title = "Sobol indices",
    columns = list(
      list(key = "input", label = "Input", type = "string"), list(key = "s1", label = "First order S₁", type = "number"),
      list(key = "s1_low", label = "S₁ low", type = "number"), list(key = "s1_high", label = "S₁ high", type = "number"),
      list(key = "st", label = "Total S_T", type = "number"), list(key = "st_low", label = "S_T low", type = "number"),
      list(key = "st_high", label = "S_T high", type = "number")
    ),
    rows = rows
  )
  srt <- rows[order(-st, seq_along(rows))]
  charts[[1]] <- cs_chart(
    "sobol", "importance-bar", "Total-effect Sobol indices",
    list(feature = cs_col("Input", chr_of(srt, "input")), importance = cs_col("Total index S_T", col_of(srt, "st")),
         low = cs_col("Lower", col_of(srt, "st_low")), high = cs_col("Upper", col_of(srt, "st_high"))),
    controls = list(top = 20)
  )
  if (sum(col_of(rows, "s1")) > 1.05 || any(col_of(rows, "s1") < -0.05)) {
    warnings <- c(warnings, "Some first-order indices are outside [0, 1] beyond sampling noise — increase N for stable estimates.")
  }
  if (length(model$correlations)) warnings <- c(warnings, "Sobol indices treat inputs as independent; the model's correlations are ignored here.")
} else {
  res <- cs_sim_morris(model, KPI, 20, 4, 1)
  rows <- res$rows
  for (r in rows) for (key in c("mu", "mu_star", "sigma")) values[[sprintf("%s[%s]", key, r$input)]] <- r[[key]]
  values$top_input <- if (length(rows)) rows[[1]]$input else NA
  values$top_value <- if (length(rows)) rows[[1]]$mu_star else NA
  values$evaluations <- res$evaluations
  tables[[1]] <- list(
    key = "morris", title = "Morris elementary effects",
    columns = list(list(key = "input", label = "Input", type = "string"), list(key = "mu_star", label = "μ* (mean |effect|)", type = "number"),
                   list(key = "mu", label = "μ", type = "number"), list(key = "sigma", label = "σ", type = "number")),
    rows = rows
  )
  charts[[1]] <- cs_chart(
    "morris", "scatter", "Morris: importance (μ*) vs interaction / non-linearity (σ)",
    list(x = cs_col("μ* (mean |elementary effect|)", col_of(rows, "mu_star")), y = cs_col("σ", col_of(rows, "sigma")),
         color = cs_col("Input", chr_of(rows, "input"))),
    controls = list(fit = "none")
  )
}
values$kpi <- res$kpi
values$kpi_label <- if (!is.null(labels[[res$kpi]])) labels[[res$kpi]] else res$kpi
values$base <- if (is.null(res$base)) NA else res$base
values$n_factors <- if (ANALYSIS != "spider") length(rows) else length(unique(chr_of(rows, "input")))

# %% Result
names_map <- c(tornado = "Tornado", spider = "Spider", sobol = "Sobol indices", morris = "Morris screening")
stats_list <- list()
if (!is.na(values$base)) stats_list[[length(stats_list) + 1]] <- list(key = "base", label = "Base case", value = values$base)
if (!is.na(values$top_value)) stats_list[[length(stats_list) + 1]] <- list(key = "top_value", label = "Largest effect", value = values$top_value)
if (!is.null(values$evaluations)) stats_list[[length(stats_list) + 1]] <- list(key = "evaluations", label = "Model evaluations", value = values$evaluations, format = "integer")
cs_publish(list(
  method = "simulate.sensitivity",
  methodVersion = "1.0.0",
  title = sprintf("Sensitivity (%s): %s", names_map[[ANALYSIS]], values$kpi_label),
  engine = cs_engine_info("stats", "jsonlite"),
  summary = if (!is.na(values$top_input)) sprintf("%s moves %s the most.", values$top_input, values$kpi_label) else "No inputs to analyze.",
  statistics = stats_list,
  tables = tables,
  charts = charts,
  warnings = warnings,
  notes = "Inputs are set by their quantile functions; the base case uses each input's base value (its mean unless set).",
  values = values
))
Python

demand moves Profit the most.

Base case
3733.33
Largest effect
3681.87

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

One-way sensitivity (largest swing first)

InputLow valueHigh valueKPI at lowKPI at highSwing
demand743.691256.311084.794766.673681.87
unit_cost5.2006.8004613.332853.331,760
price9.54811.2252947.724625.401677.68
  • Inputs are set by their quantile functions; the base case uses each input's base value (its mean unless set).
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Sensitivity analysis of a scenario model
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method simulate.sensitivity 1.0.0 · spec 7d839170de4c7937
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
import json

import numpy as np

import codesplash as cs
from codesplash.sim import mc, sens  # sensitivity designs on the shared random stream (twin of R cs_sim_*)

# %% Model
model = mc.load(json.loads("{\"inputs\":[{\"name\":\"demand\",\"dist\":\"normal\",\"params\":{\"mean\":1000,\"sd\":200},\"min\":0},{\"name\":\"price\",\"dist\":\"triangular\",\"params\":{\"min\":9,\"mode\":10,\"max\":12}},{\"name\":\"unit_cost\",\"dist\":\"uniform\",\"params\":{\"min\":5,\"max\":7}}],\"decisions\":[{\"name\":\"order\",\"value\":1100,\"min\":600,\"max\":1600}],\"formulas\":[{\"name\":\"sales\",\"expr\":\"min(demand, order)\"},{\"name\":\"profit\",\"expr\":\"price * sales - unit_cost * order\"}],\"kpis\":[{\"name\":\"profit\",\"label\":\"Profit\"}],\"correlations\":[]}"))
ANALYSIS = "tornado"  # tornado | spider | sobol | morris
KPI = "" or None  # empty = the model's first KPI
warnings, tables, charts = [], [], []
labels = {str(k["name"]): (k.get("label") or str(k["name"])) for k in model["kpis"]}

# %% Analyze
values = {"analysis": ANALYSIS}
if ANALYSIS == "tornado":
    # One input at a time at its low / high value, everything else at its base case.
    res = sens.tornado(model, KPI, 10, 90, False)
    rows = res["rows"]
    for r in rows:
        nm = r["input"]
        values[f"swing[{nm}]"] = r["swing"]
        values[f"kpi_low[{nm}]"] = r["kpi_low"]
        values[f"kpi_high[{nm}]"] = r["kpi_high"]
        values[f"low_value[{nm}]"] = r["low_value"]
        values[f"high_value[{nm}]"] = r["high_value"]
    top = rows[0] if rows else None
    values.update({"top_input": top["input"] if top else None, "top_value": top["swing"] if top else None})
    tables.append({
        "key": "tornado", "title": "One-way sensitivity (largest swing first)",
        "columns": [
            {"key": "input", "label": "Input", "type": "string"}, {"key": "low_value", "label": "Low value", "type": "number"},
            {"key": "high_value", "label": "High value", "type": "number"}, {"key": "kpi_low", "label": "KPI at low", "type": "number"},
            {"key": "kpi_high", "label": "KPI at high", "type": "number"}, {"key": "swing", "label": "Swing", "type": "number"},
        ],
        "rows": rows,
    })
    charts.append(cs.chart(
        "tornado", "tornado", "Tornado",
        {"input": cs.col("Input", [r["input"] for r in rows]), "low": cs.col("KPI at low value", [r["kpi_low"] for r in rows]),
         "high": cs.col("KPI at high value", [r["kpi_high"] for r in rows])},
        controls={"base": res["base"]},
    ))
elif ANALYSIS == "spider":
    changes = [-50, -25, -10, 0, 10, 25, 50]
    res = sens.spider(model, KPI, changes, False)
    rows = res["rows"]
    for r in rows:
        values[f"spider[{r['input']},{r['change']:g}]"] = r["kpi"]
    ranges = {}
    for r in rows:
        lo, hi = ranges.get(r["input"], (np.inf, -np.inf))
        ranges[r["input"]] = (min(lo, r["kpi"]), max(hi, r["kpi"]))
    order = sorted(ranges, key=lambda nm: -(ranges[nm][1] - ranges[nm][0]))
    values.update({"top_input": order[0] if order else None, "top_value": (ranges[order[0]][1] - ranges[order[0]][0]) if order else None})
    if res["skipped"]:
        warnings.append("Left out (base value 0, so a percentage change is undefined): " + ", ".join(res["skipped"]) + ".")
    tables.append({
        "key": "spider", "title": "KPI as each input changes from its base value",
        "columns": [{"key": "input", "label": "Input", "type": "string"}, {"key": "change", "label": "Change (%)", "type": "number"},
                    {"key": "value", "label": "Input value", "type": "number"}, {"key": "kpi", "label": "KPI", "type": "number"}],
        "rows": rows,
    })
    charts.append(cs.chart(
        "spider", "spider", "Spider",
        {"change": cs.col("Change from base (%)", [r["change"] for r in rows]), "kpi": cs.col("KPI", [r["kpi"] for r in rows]),
         "input": cs.col("Input", [r["input"] for r in rows])},
    ))
elif ANALYSIS == "sobol":
    # Saltelli A/B/AB_i design from the shared stream; Saltelli (2010) first-order, Jansen total indices.
    # Equivalent idiom: SALib.sample.sobol + SALib.analyze.sobol (Python) / sensitivity::soboljansen (R).
    res = sens.sobol(model, KPI, int(1024), int(1), int(200), 0.95)
    rows = res["rows"]
    for r in rows:
        for key in ("s1", "st", "s1_low", "s1_high", "st_low", "st_high"):
            values[f"{key}[{r['input']}]"] = r[key]
    top = max(rows, key=lambda r: r["st"]) if rows else None
    values.update({"top_input": top["input"] if top else None, "top_value": top["st"] if top else None, "variance": res["variance"], "evaluations": res["evaluations"]})
    tables.append({
        "key": "sobol", "title": "Sobol indices",
        "columns": [
            {"key": "input", "label": "Input", "type": "string"}, {"key": "s1", "label": "First order S₁", "type": "number"},
            {"key": "s1_low", "label": "S₁ low", "type": "number"}, {"key": "s1_high", "label": "S₁ high", "type": "number"},
            {"key": "st", "label": "Total S_T", "type": "number"}, {"key": "st_low", "label": "S_T low", "type": "number"},
            {"key": "st_high", "label": "S_T high", "type": "number"},
        ],
        "rows": rows,
    })
    srt = sorted(rows, key=lambda r: -r["st"])
    charts.append(cs.chart(
        "sobol", "importance-bar", "Total-effect Sobol indices",
        {"feature": cs.col("Input", [r["input"] for r in srt]), "importance": cs.col("Total index S_T", [r["st"] for r in srt]),
         "low": cs.col("Lower", [r["st_low"] for r in srt]), "high": cs.col("Upper", [r["st_high"] for r in srt])},
        controls={"top": 20},
    ))
    if sum(r["s1"] for r in rows) > 1.05 or any(r["s1"] < -0.05 for r in rows):
        warnings.append("Some first-order indices are outside [0, 1] beyond sampling noise — increase N for stable estimates.")
    if model["correlations"]:
        warnings.append("Sobol indices treat inputs as independent; the model's correlations are ignored here.")
else:
    res = sens.morris(model, KPI, int(20), int(4), int(1))
    rows = res["rows"]
    for r in rows:
        for key in ("mu", "mu_star", "sigma"):
            values[f"{key}[{r['input']}]"] = r[key]
    top = rows[0] if rows else None
    values.update({"top_input": top["input"] if top else None, "top_value": top["mu_star"] if top else None, "evaluations": res["evaluations"]})
    tables.append({
        "key": "morris", "title": "Morris elementary effects",
        "columns": [{"key": "input", "label": "Input", "type": "string"}, {"key": "mu_star", "label": "μ* (mean |effect|)", "type": "number"},
                    {"key": "mu", "label": "μ", "type": "number"}, {"key": "sigma", "label": "σ", "type": "number"}],
        "rows": rows,
    })
    charts.append(cs.chart(
        "morris", "scatter", "Morris: importance (μ*) vs interaction / non-linearity (σ)",
        {"x": cs.col("μ* (mean |elementary effect|)", [r["mu_star"] for r in rows]), "y": cs.col("σ", [r["sigma"] for r in rows]),
         "color": cs.col("Input", [r["input"] for r in rows])},
        controls={"fit": "none"},
    ))
values["kpi"] = res["kpi"]
values["kpi_label"] = labels.get(res["kpi"], res["kpi"])
values["base"] = res.get("base")
values["n_factors"] = len(rows) if ANALYSIS != "spider" else len({r["input"] for r in rows})

# %% Result
names = {"tornado": "Tornado", "spider": "Spider", "sobol": "Sobol indices", "morris": "Morris screening"}
cs.publish({
    "method": "simulate.sensitivity",
    "methodVersion": "1.0.0",
    "title": f"Sensitivity ({names[ANALYSIS]}): {values['kpi_label']}",
    "engine": cs.engine_info("numpy", "scipy"),
    "summary": f"{values['top_input']} moves {values['kpi_label']} the most." if values.get("top_input") else "No inputs to analyze.",
    "statistics": [s for s in [
        {"key": "base", "label": "Base case", "value": values.get("base")} if values.get("base") is not None else None,
        {"key": "top_value", "label": "Largest effect", "value": values.get("top_value")} if values.get("top_value") is not None else None,
        {"key": "evaluations", "label": "Model evaluations", "value": values.get("evaluations"), "format": "integer"} if values.get("evaluations") else None,
    ] if s],
    "tables": tables,
    "charts": charts,
    "warnings": warnings,
    "notes": ["Inputs are set by their quantile functions; the base case uses each input's base value (its mean unless set)."],
    "values": values,
})

Each input moves between its 10th and 90th percentiles. Look at the demand bar, and notice that it isn't balanced around the base: high demand hits the stock limit, while low demand keeps hurting. A lopsided bar means the response isn't linear.

Also on the Sensitivity step: a spider chart moves each input by the same percentage. Its largest range belongs to price, not demand. A given percentage of price moves profit more, but price is less uncertain. The two charts answer different questions.

04

What it can't see

Read

Tornado and spider charts change one input while the rest stay at base. If inputs work together, they miss it.

Sobol indicesSobol indexThe share of output variance due to an input, alone (first order) or with its interactions (total order). are different. They vary everything at once, and split the KPI's variance:

  • First-order: the share due to this input alone.
  • Total: the share due to this input, including its interactions.

A large gap between the two means the input matters through its interactions.

05

Spot the interaction

In the app

Ishigami's test function is built with strong interactions.

Sensitivity (Sobol indices): yRecorded · Python and R agreeRecorded 2026-11-25 · 27 values compared
R

x1 moves y the most.

Largest effect
0.5797
Model evaluations
10,240

Plots

Total-effect Sobol indicesWhich features does the model rely on most?
View data
InputUpperTotal index S_TLower
x10.62100.57970.5197
x20.47110.44720.4226
x30.27290.25040.2353

Sobol indices

InputFirst order S₁S₁ lowS₁ highTotal S_TS_T lowS_T high
x10.31560.24030.36360.57970.51970.6210
x20.42860.37260.48280.44720.42260.4711
x3−0.0134−0.04830.02660.25040.23530.2729
  • Inputs are set by their quantile functions; the base case uses each input's base value (its mean unless set).
The exact R script · R R version 4.5.1 (2025-06-13)
# Sensitivity analysis of a scenario model
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method simulate.sensitivity 1.0.0 · spec c01966dd82c109ff
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr) # cs_sim_*: sensitivity designs on the shared random stream (twin of codesplash.sim)

# %% Model
model <- cs_sim_load("{\"inputs\":[{\"name\":\"x1\",\"dist\":\"uniform\",\"params\":{\"min\":-3.141592653589793,\"max\":3.141592653589793}},{\"name\":\"x2\",\"dist\":\"uniform\",\"params\":{\"min\":-3.141592653589793,\"max\":3.141592653589793}},{\"name\":\"x3\",\"dist\":\"uniform\",\"params\":{\"min\":-3.141592653589793,\"max\":3.141592653589793}}],\"decisions\":[],\"formulas\":[{\"name\":\"y\",\"expr\":\"sin(x1) + 7 * sin(x2) ^ 2 + 0.1 * x3 ^ 4 * sin(x1)\"}],\"kpis\":[{\"name\":\"y\",\"label\":\"y\"}]}")
ANALYSIS <- "sobol" # tornado | spider | sobol | morris
KPI <- "" # empty = the model's first KPI
if (!nzchar(KPI)) KPI <- NULL
warnings <- list(); tables <- list(); charts <- list()
labels <- list()
for (k in model$kpis) labels[[as.character(k$name)]] <- if (!is.null(k$label) && nzchar(k$label)) k$label else as.character(k$name)
col_of <- function(rows, key) vapply(rows, function(r) as.numeric(r[[key]]), numeric(1))
chr_of <- function(rows, key) vapply(rows, function(r) as.character(r[[key]]), character(1))

# %% Analyze
values <- list(analysis = ANALYSIS)
if (ANALYSIS == "tornado") {
  # One input at a time at its low / high value, everything else at its base case.
  res <- cs_sim_tornado(model, KPI, 10, 90, FALSE)
  rows <- res$rows
  for (r in rows) {
    nm <- r$input
    values[[sprintf("swing[%s]", nm)]] <- r$swing
    values[[sprintf("kpi_low[%s]", nm)]] <- r$kpi_low
    values[[sprintf("kpi_high[%s]", nm)]] <- r$kpi_high
    values[[sprintf("low_value[%s]", nm)]] <- r$low_value
    values[[sprintf("high_value[%s]", nm)]] <- r$high_value
  }
  values$top_input <- if (length(rows)) rows[[1]]$input else NA
  values$top_value <- if (length(rows)) rows[[1]]$swing else NA
  tables[[1]] <- list(
    key = "tornado", title = "One-way sensitivity (largest swing first)",
    columns = list(
      list(key = "input", label = "Input", type = "string"), list(key = "low_value", label = "Low value", type = "number"),
      list(key = "high_value", label = "High value", type = "number"), list(key = "kpi_low", label = "KPI at low", type = "number"),
      list(key = "kpi_high", label = "KPI at high", type = "number"), list(key = "swing", label = "Swing", type = "number")
    ),
    rows = rows
  )
  charts[[1]] <- cs_chart(
    "tornado", "tornado", "Tornado",
    list(input = cs_col("Input", chr_of(rows, "input")), low = cs_col("KPI at low value", col_of(rows, "kpi_low")),
         high = cs_col("KPI at high value", col_of(rows, "kpi_high"))),
    controls = list(base = res$base)
  )
} else if (ANALYSIS == "spider") {
  changes <- c(-50, -25, -10, 0, 10, 25, 50)
  res <- cs_sim_spider(model, KPI, changes, FALSE)
  rows <- res$rows
  for (r in rows) values[[sprintf("spider[%s,%s]", r$input, sprintf("%g", r$change))]] <- r$kpi
  ins <- unique(chr_of(rows, "input"))
  rng <- vapply(ins, function(nm) {
    k <- col_of(Filter(function(r) r$input == nm, rows), "kpi")
    max(k) - min(k)
  }, numeric(1))
  ord <- order(-rng, seq_along(ins))
  values$top_input <- if (length(ins)) ins[ord[1]] else NA
  values$top_value <- if (length(ins)) unname(rng[ord[1]]) else NA
  if (length(res$skipped)) warnings <- c(warnings, sprintf("Left out (base value 0, so a percentage change is undefined): %s.", paste(res$skipped, collapse = ", ")))
  tables[[1]] <- list(
    key = "spider", title = "KPI as each input changes from its base value",
    columns = list(list(key = "input", label = "Input", type = "string"), list(key = "change", label = "Change (%)", type = "number"),
                   list(key = "value", label = "Input value", type = "number"), list(key = "kpi", label = "KPI", type = "number")),
    rows = rows
  )
  charts[[1]] <- cs_chart(
    "spider", "spider", "Spider",
    list(change = cs_col("Change from base (%)", col_of(rows, "change")), kpi = cs_col("KPI", col_of(rows, "kpi")),
         input = cs_col("Input", chr_of(rows, "input")))
  )
} else if (ANALYSIS == "sobol") {
  # Saltelli A/B/AB_i design from the shared stream; Saltelli (2010) first-order, Jansen total indices.
  # Equivalent idiom: sensitivity::soboljansen(model, X1, X2, nboot) — with R's own random draws.
  res <- cs_sim_sobol(model, KPI, 2048, 2, 50, 0.95)
  rows <- res$rows
  for (r in rows) for (key in c("s1", "st", "s1_low", "s1_high", "st_low", "st_high")) values[[sprintf("%s[%s]", key, r$input)]] <- r[[key]]
  st <- col_of(rows, "st")
  top <- which.max(st)
  values$top_input <- if (length(rows)) rows[[top]]$input else NA
  values$top_value <- if (length(rows)) st[top] else NA
  values$variance <- res$variance
  values$evaluations <- res$evaluations
  tables[[1]] <- list(
    key = "sobol", title = "Sobol indices",
    columns = list(
      list(key = "input", label = "Input", type = "string"), list(key = "s1", label = "First order S₁", type = "number"),
      list(key = "s1_low", label = "S₁ low", type = "number"), list(key = "s1_high", label = "S₁ high", type = "number"),
      list(key = "st", label = "Total S_T", type = "number"), list(key = "st_low", label = "S_T low", type = "number"),
      list(key = "st_high", label = "S_T high", type = "number")
    ),
    rows = rows
  )
  srt <- rows[order(-st, seq_along(rows))]
  charts[[1]] <- cs_chart(
    "sobol", "importance-bar", "Total-effect Sobol indices",
    list(feature = cs_col("Input", chr_of(srt, "input")), importance = cs_col("Total index S_T", col_of(srt, "st")),
         low = cs_col("Lower", col_of(srt, "st_low")), high = cs_col("Upper", col_of(srt, "st_high"))),
    controls = list(top = 20)
  )
  if (sum(col_of(rows, "s1")) > 1.05 || any(col_of(rows, "s1") < -0.05)) {
    warnings <- c(warnings, "Some first-order indices are outside [0, 1] beyond sampling noise — increase N for stable estimates.")
  }
  if (length(model$correlations)) warnings <- c(warnings, "Sobol indices treat inputs as independent; the model's correlations are ignored here.")
} else {
  res <- cs_sim_morris(model, KPI, 20, 4, 2)
  rows <- res$rows
  for (r in rows) for (key in c("mu", "mu_star", "sigma")) values[[sprintf("%s[%s]", key, r$input)]] <- r[[key]]
  values$top_input <- if (length(rows)) rows[[1]]$input else NA
  values$top_value <- if (length(rows)) rows[[1]]$mu_star else NA
  values$evaluations <- res$evaluations
  tables[[1]] <- list(
    key = "morris", title = "Morris elementary effects",
    columns = list(list(key = "input", label = "Input", type = "string"), list(key = "mu_star", label = "μ* (mean |effect|)", type = "number"),
                   list(key = "mu", label = "μ", type = "number"), list(key = "sigma", label = "σ", type = "number")),
    rows = rows
  )
  charts[[1]] <- cs_chart(
    "morris", "scatter", "Morris: importance (μ*) vs interaction / non-linearity (σ)",
    list(x = cs_col("μ* (mean |elementary effect|)", col_of(rows, "mu_star")), y = cs_col("σ", col_of(rows, "sigma")),
         color = cs_col("Input", chr_of(rows, "input"))),
    controls = list(fit = "none")
  )
}
values$kpi <- res$kpi
values$kpi_label <- if (!is.null(labels[[res$kpi]])) labels[[res$kpi]] else res$kpi
values$base <- if (is.null(res$base)) NA else res$base
values$n_factors <- if (ANALYSIS != "spider") length(rows) else length(unique(chr_of(rows, "input")))

# %% Result
names_map <- c(tornado = "Tornado", spider = "Spider", sobol = "Sobol indices", morris = "Morris screening")
stats_list <- list()
if (!is.na(values$base)) stats_list[[length(stats_list) + 1]] <- list(key = "base", label = "Base case", value = values$base)
if (!is.na(values$top_value)) stats_list[[length(stats_list) + 1]] <- list(key = "top_value", label = "Largest effect", value = values$top_value)
if (!is.null(values$evaluations)) stats_list[[length(stats_list) + 1]] <- list(key = "evaluations", label = "Model evaluations", value = values$evaluations, format = "integer")
cs_publish(list(
  method = "simulate.sensitivity",
  methodVersion = "1.0.0",
  title = sprintf("Sensitivity (%s): %s", names_map[[ANALYSIS]], values$kpi_label),
  engine = cs_engine_info("stats", "jsonlite"),
  summary = if (!is.na(values$top_input)) sprintf("%s moves %s the most.", values$top_input, values$kpi_label) else "No inputs to analyze.",
  statistics = stats_list,
  tables = tables,
  charts = charts,
  warnings = warnings,
  notes = "Inputs are set by their quantile functions; the base case uses each input's base value (its mean unless set).",
  values = values
))
Python

x1 moves y the most.

Largest effect
0.5797
Model evaluations
10,240

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

Sobol indices

InputFirst order S₁S₁ lowS₁ highTotal S_TS_T lowS_T high
x10.31560.24030.36360.57970.51970.6210
x20.42860.37260.48280.44720.42260.4711
x3−0.0134−0.04830.02660.25040.23530.2729
  • Inputs are set by their quantile functions; the base case uses each input's base value (its mean unless set).
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Sensitivity analysis of a scenario model
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method simulate.sensitivity 1.0.0 · spec c01966dd82c109ff
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
import json

import numpy as np

import codesplash as cs
from codesplash.sim import mc, sens  # sensitivity designs on the shared random stream (twin of R cs_sim_*)

# %% Model
model = mc.load(json.loads("{\"inputs\":[{\"name\":\"x1\",\"dist\":\"uniform\",\"params\":{\"min\":-3.141592653589793,\"max\":3.141592653589793}},{\"name\":\"x2\",\"dist\":\"uniform\",\"params\":{\"min\":-3.141592653589793,\"max\":3.141592653589793}},{\"name\":\"x3\",\"dist\":\"uniform\",\"params\":{\"min\":-3.141592653589793,\"max\":3.141592653589793}}],\"decisions\":[],\"formulas\":[{\"name\":\"y\",\"expr\":\"sin(x1) + 7 * sin(x2) ^ 2 + 0.1 * x3 ^ 4 * sin(x1)\"}],\"kpis\":[{\"name\":\"y\",\"label\":\"y\"}]}"))
ANALYSIS = "sobol"  # tornado | spider | sobol | morris
KPI = "" or None  # empty = the model's first KPI
warnings, tables, charts = [], [], []
labels = {str(k["name"]): (k.get("label") or str(k["name"])) for k in model["kpis"]}

# %% Analyze
values = {"analysis": ANALYSIS}
if ANALYSIS == "tornado":
    # One input at a time at its low / high value, everything else at its base case.
    res = sens.tornado(model, KPI, 10, 90, False)
    rows = res["rows"]
    for r in rows:
        nm = r["input"]
        values[f"swing[{nm}]"] = r["swing"]
        values[f"kpi_low[{nm}]"] = r["kpi_low"]
        values[f"kpi_high[{nm}]"] = r["kpi_high"]
        values[f"low_value[{nm}]"] = r["low_value"]
        values[f"high_value[{nm}]"] = r["high_value"]
    top = rows[0] if rows else None
    values.update({"top_input": top["input"] if top else None, "top_value": top["swing"] if top else None})
    tables.append({
        "key": "tornado", "title": "One-way sensitivity (largest swing first)",
        "columns": [
            {"key": "input", "label": "Input", "type": "string"}, {"key": "low_value", "label": "Low value", "type": "number"},
            {"key": "high_value", "label": "High value", "type": "number"}, {"key": "kpi_low", "label": "KPI at low", "type": "number"},
            {"key": "kpi_high", "label": "KPI at high", "type": "number"}, {"key": "swing", "label": "Swing", "type": "number"},
        ],
        "rows": rows,
    })
    charts.append(cs.chart(
        "tornado", "tornado", "Tornado",
        {"input": cs.col("Input", [r["input"] for r in rows]), "low": cs.col("KPI at low value", [r["kpi_low"] for r in rows]),
         "high": cs.col("KPI at high value", [r["kpi_high"] for r in rows])},
        controls={"base": res["base"]},
    ))
elif ANALYSIS == "spider":
    changes = [-50, -25, -10, 0, 10, 25, 50]
    res = sens.spider(model, KPI, changes, False)
    rows = res["rows"]
    for r in rows:
        values[f"spider[{r['input']},{r['change']:g}]"] = r["kpi"]
    ranges = {}
    for r in rows:
        lo, hi = ranges.get(r["input"], (np.inf, -np.inf))
        ranges[r["input"]] = (min(lo, r["kpi"]), max(hi, r["kpi"]))
    order = sorted(ranges, key=lambda nm: -(ranges[nm][1] - ranges[nm][0]))
    values.update({"top_input": order[0] if order else None, "top_value": (ranges[order[0]][1] - ranges[order[0]][0]) if order else None})
    if res["skipped"]:
        warnings.append("Left out (base value 0, so a percentage change is undefined): " + ", ".join(res["skipped"]) + ".")
    tables.append({
        "key": "spider", "title": "KPI as each input changes from its base value",
        "columns": [{"key": "input", "label": "Input", "type": "string"}, {"key": "change", "label": "Change (%)", "type": "number"},
                    {"key": "value", "label": "Input value", "type": "number"}, {"key": "kpi", "label": "KPI", "type": "number"}],
        "rows": rows,
    })
    charts.append(cs.chart(
        "spider", "spider", "Spider",
        {"change": cs.col("Change from base (%)", [r["change"] for r in rows]), "kpi": cs.col("KPI", [r["kpi"] for r in rows]),
         "input": cs.col("Input", [r["input"] for r in rows])},
    ))
elif ANALYSIS == "sobol":
    # Saltelli A/B/AB_i design from the shared stream; Saltelli (2010) first-order, Jansen total indices.
    # Equivalent idiom: SALib.sample.sobol + SALib.analyze.sobol (Python) / sensitivity::soboljansen (R).
    res = sens.sobol(model, KPI, int(2048), int(2), int(50), 0.95)
    rows = res["rows"]
    for r in rows:
        for key in ("s1", "st", "s1_low", "s1_high", "st_low", "st_high"):
            values[f"{key}[{r['input']}]"] = r[key]
    top = max(rows, key=lambda r: r["st"]) if rows else None
    values.update({"top_input": top["input"] if top else None, "top_value": top["st"] if top else None, "variance": res["variance"], "evaluations": res["evaluations"]})
    tables.append({
        "key": "sobol", "title": "Sobol indices",
        "columns": [
            {"key": "input", "label": "Input", "type": "string"}, {"key": "s1", "label": "First order S₁", "type": "number"},
            {"key": "s1_low", "label": "S₁ low", "type": "number"}, {"key": "s1_high", "label": "S₁ high", "type": "number"},
            {"key": "st", "label": "Total S_T", "type": "number"}, {"key": "st_low", "label": "S_T low", "type": "number"},
            {"key": "st_high", "label": "S_T high", "type": "number"},
        ],
        "rows": rows,
    })
    srt = sorted(rows, key=lambda r: -r["st"])
    charts.append(cs.chart(
        "sobol", "importance-bar", "Total-effect Sobol indices",
        {"feature": cs.col("Input", [r["input"] for r in srt]), "importance": cs.col("Total index S_T", [r["st"] for r in srt]),
         "low": cs.col("Lower", [r["st_low"] for r in srt]), "high": cs.col("Upper", [r["st_high"] for r in srt])},
        controls={"top": 20},
    ))
    if sum(r["s1"] for r in rows) > 1.05 or any(r["s1"] < -0.05 for r in rows):
        warnings.append("Some first-order indices are outside [0, 1] beyond sampling noise — increase N for stable estimates.")
    if model["correlations"]:
        warnings.append("Sobol indices treat inputs as independent; the model's correlations are ignored here.")
else:
    res = sens.morris(model, KPI, int(20), int(4), int(2))
    rows = res["rows"]
    for r in rows:
        for key in ("mu", "mu_star", "sigma"):
            values[f"{key}[{r['input']}]"] = r[key]
    top = rows[0] if rows else None
    values.update({"top_input": top["input"] if top else None, "top_value": top["mu_star"] if top else None, "evaluations": res["evaluations"]})
    tables.append({
        "key": "morris", "title": "Morris elementary effects",
        "columns": [{"key": "input", "label": "Input", "type": "string"}, {"key": "mu_star", "label": "μ* (mean |effect|)", "type": "number"},
                    {"key": "mu", "label": "μ", "type": "number"}, {"key": "sigma", "label": "σ", "type": "number"}],
        "rows": rows,
    })
    charts.append(cs.chart(
        "morris", "scatter", "Morris: importance (μ*) vs interaction / non-linearity (σ)",
        {"x": cs.col("μ* (mean |elementary effect|)", [r["mu_star"] for r in rows]), "y": cs.col("σ", [r["sigma"] for r in rows]),
         "color": cs.col("Input", [r["input"] for r in rows])},
        controls={"fit": "none"},
    ))
values["kpi"] = res["kpi"]
values["kpi_label"] = labels.get(res["kpi"], res["kpi"])
values["base"] = res.get("base")
values["n_factors"] = len(rows) if ANALYSIS != "spider" else len({r["input"] for r in rows})

# %% Result
names = {"tornado": "Tornado", "spider": "Spider", "sobol": "Sobol indices", "morris": "Morris screening"}
cs.publish({
    "method": "simulate.sensitivity",
    "methodVersion": "1.0.0",
    "title": f"Sensitivity ({names[ANALYSIS]}): {values['kpi_label']}",
    "engine": cs.engine_info("numpy", "scipy"),
    "summary": f"{values['top_input']} moves {values['kpi_label']} the most." if values.get("top_input") else "No inputs to analyze.",
    "statistics": [s for s in [
        {"key": "base", "label": "Base case", "value": values.get("base")} if values.get("base") is not None else None,
        {"key": "top_value", "label": "Largest effect", "value": values.get("top_value")} if values.get("top_value") is not None else None,
        {"key": "evaluations", "label": "Model evaluations", "value": values.get("evaluations"), "format": "integer"} if values.get("evaluations") else None,
    ] if s],
    "tables": tables,
    "charts": charts,
    "warnings": warnings,
    "notes": ["Inputs are set by their quantile functions; the base case uses each input's base value (its mean unless set)."],
    "values": values,
})

Check yourself

On the card, x3 has a first-order index near zero and a total index near a quarter. What does that mean?

Show the answer

Answer: b

A tornado chart would call x3 irrelevant. Its total index shows that it isn't. That's why first-order and total indices are reported together.

06

Read the intervals

Predict

Predict first

On the stocking model with 2,560 evaluations, demand's first-order index comes out above its total index. By definition, total can't be smaller. What's going on?

Interactions must be negativeIt's simulation error from a small sampleThe model is broken
Reveal

Simulation error. These indices are estimates, and a small base sample leaves them rough. The bootstrap intervals overlap, so read those and raise the sample size before you trust a gap. The ranking is steadier: demand still comes first.

07

A cheaper screen

Checkpoint

Morris screening uses far fewer model runs: 60 here. It records how much the KPI changes for small steps in each input, across random starting points. A large mean means the input matters. A large spread means nonlinearity or interactions.

Check yourself

Your model takes a minute per run and has 40 inputs. What's a sensible order?

Show the answer

Answer: a

Sobol needs N × (inputs + 2) evaluations. Screening first keeps that affordable.

Check yourself

A tornado chart ranks demand first. You then narrow your demand forecast, and the demand bar shrinks. What changed?

Show the answer

Answer: b

Sensitivity reflects both how strongly an input acts and how uncertain it is. Change the range you assume, and the ranking can change.

08

Try it

In the app

In Scenarios & optimization, open the Sensitivity step and choose an analysis. Include decisions as well, and you can compare what you control with what you don't.

09

Recap

Recap
  • Tornado and spider charts vary one input at a time, around a base case.
  • Sobol indices vary everything, and a gap between total and first-order shows interactions.
  • Morris screening is a cheap first pass.
  • Rankings depend on the ranges you assume.

Concepts in this lesson