Package {xplaineff}


Type: Package
Title: Decomposing Global Feature Effects Based on Feature Interactions
Version: 0.1.0
Description: Implements the GADGET (Generalized Additive Decomposition of Global EffecTs) algorithm for interpretable machine learning. The package recursively partitions the feature space to minimize heterogeneity of feature effects (e.g., Accumulated Local Effects or Partial Dependence), producing a tree of regions where effects are more stable. It supports both ALE and PD strategies, works with 'mlr3' learners and provides visualization of the interaction tree and regional effect plots. The method is described in Herbinger, J., Wright, M. N., Nagler, T., Bischl, B., and Casalicchio, G. (2024), "Decomposing Global Feature Effects Based on Feature Interactions" https://jmlr.org/papers/volume25/23-0699/23-0699.pdf.
License: MIT + file LICENSE
Depends: R (≥ 4.3.0)
URL: https://github.com/mlr-org/xplaineff
BugReports: https://github.com/mlr-org/xplaineff/issues
Encoding: UTF-8
Imports: checkmate (≥ 2.3.2), cli (≥ 3.0.0), data.table (≥ 1.14.0), ggplot2 (≥ 3.5.2), ggraph (≥ 2.2.1), igraph (≥ 2.1.4), mlr3misc (≥ 0.14.0), patchwork (≥ 1.3.0), R6 (≥ 2.6.1), Rcpp (≥ 1.0.0)
LinkingTo: Rcpp, RcppArmadillo
RoxygenNote: 7.3.2
Suggests: testthat (≥ 3.0.0), iml (≥ 0.11.4), mlr3, mlr3learners, ranger, ISLR2, rpart, withr, xgboost
Config/testthat/edition: 3
Collate: 'EffectStrategy.R' 'AleStrategy.R' 'GadgetTree.R' 'Node.R' 'PdStrategy.R' 'RcppExports.R' 'calculate_ale.R' 'calculate_ale_fast.R' 'calculate_ale_heterogeneity.R' 'calculate_pd.R' 'categorical_split_utils.R' 'choose_operator.R' 'convert_tree_to_list.R' 'extract_split_info.R' 'factor_to_numeric.R' 'find_node_by_id.R' 'mean_center_ice.R' 'node_heterogeneity.R' 'node_transform_ale.R' 'order_categorical_levels.R' 'plot_regional_ale.R' 'plot_regional_pd.R' 'plot_tree_ale.R' 'plot_tree_pd.R' 'plot_tree_structure.R' 'plot_utils.R' 'prepare_layout_data.R' 'prepare_plot_data_ale.R' 'prepare_split_data_ale.R' 'prepare_split_data_pd.R' 'prepare_split_data_utils.R' 'search_best_split_ale.R' 'search_best_split_point_ale.R' 'track_split_condition.R' 'xplaineff_internal.R' 'xplaineff_package.R'
NeedsCompilation: yes
Packaged: 2026-09-04 08:21:15 UTC; zzz
Author: Zizheng Zhang [aut, cre]
Maintainer: Zizheng Zhang <Zizheng.Zhang@stat.uni-muenchen.de>
Repository: CRAN
Date/Publication: 2026-09-14 15:00:02 UTC

xplaineff: Generalized Additive Decomposition of Global EffecTs

Description

The **xplaineff** package implements the GADGET algorithm for interpretable machine learning. It builds a tree by recursively partitioning the feature space to minimize the heterogeneity of feature effects (e.g., Accumulated Local Effects or Partial Dependence), so that within each region the effects are more stable and easier to interpret.

Details

**Main components (user-facing):**

**Typical workflow:**

  1. Train a model (e.g., with mlr3).

  2. Create a tree: tree = GadgetTree$new(strategy = AleStrategy$new(), n_split = 3, min_node_size = 50).

  3. Fit: tree$fit(data, target_feature_name, ...). Strategy-specific ... arguments include:

    • AleStrategy: model (required), n_intervals = 10, predict_fun = NULL, order_method = "raw", ale_engine (default "auto"), categorical_split, and max_exhaustive_levels.

    • PdStrategy: either effect, or model with optional predict_fun, n_grid, pd_engine (default "auto"), categorical_split, and max_exhaustive_levels.

    • Both strategies accept feature_set and split_feature.

    • Tree parameters include impr_par, min_node_size, and n_quantiles.

  4. Visualize: tree$plot_tree_structure(), tree$plot(...), tree$extract_split_info().

For PD-based trees, either pass an effect object from iml::FeatureEffects(..., method = "ice") to tree$fit(effect = ..., data = ..., target_feature_name = ...), or pass a fitted model and let xplaineff compute PD/ICE internally.

Author(s)

Maintainer: Zizheng Zhang Zizheng.Zhang@stat.uni-muenchen.de

References

Herbinger, J., Wright, M. N., Nagler, T., Bischl, B., and Casalicchio, G. (2024). Decomposing Global Feature Effects Based on Feature Interactions. Journal of Machine Learning Research, 25(23-0699), 1–65. URL: https://jmlr.org/papers/volume25/23-0699/23-0699.pdf.

Apley, D.W. and Zhu, J. (2016). Visualizing the Effects of Predictors on the Response in Nonlinear and Generalized Linear Models. Journal of Computational and Graphical Statistics, 25(2), 590–600.

See Also

GadgetTree, AleStrategy, PdStrategy


AleStrategy: Generalized Additive Decomposition Based on ALE Effects

Description

ALE-based effect strategy (inherits from EffectStrategy). Given model and data, preprocesses to Z/Y via prepare_split_data_ale; transforms ALE effects per node; computes ALE-derivative heterogeneity; finds best split via search_best_split_ale; fits tree and plots ALE curves.

Format

[R6::R6Class] object inheriting from [EffectStrategy].

Details

Intended for use through GadgetTree$new(strategy = AleStrategy$new()) and tree$fit(...). Can be instantiated directly for custom pipelines.

Construction

“' s = AleStrategy$new(categorical_split = "ordered_prefix") “'

Super class

::EffectStrategy -> AleStrategy

Public fields

model

('any')
Fitted model (persistent after $fit()).

data

('data.frame()' or 'data.table()')
Data (persistent after $fit()).

target_feature_name

('character(1)')
Target variable name.

n_intervals

('integer(1)')
Intervals for numeric ALE.

predict_fun

('function()')
function(model, data) returning predictions.

order_method

('character(1)')
Categorical order: "mds", "pca", "random", "raw".

ale_engine

('character(1)')
ALE backend selected after $fit(): "cpp" or "r".

categorical_split

('character(1)')
Categorical split mode for ALE trees: "ordered_prefix" or "exhaustive".

max_exhaustive_levels

('integer(1)')
Maximum observed levels allowed for exhaustive categorical split search.

effect

('list()' or 'NULL')
Cached ALE effect used when $plot() omits effect.

Methods

Public methods


Method new()

Create an AleStrategy instance (calls super$initialize("ale")).

Usage
AleStrategy$new(
  categorical_split = "ordered_prefix",
  max_exhaustive_levels = 12L
)
Arguments
categorical_split

('character(1)')
Categorical split mode for ALE trees: "ordered_prefix" or "exhaustive".

max_exhaustive_levels

('integer(1)')
Maximum observed levels allowed for exhaustive categorical split search.


Method preprocess()

Preprocess to Z and Y via prepare_split_data_ale.

Usage
AleStrategy$preprocess(
  model,
  effect = NULL,
  data,
  target_feature_name,
  n_intervals,
  feature_set = NULL,
  split_feature = NULL,
  predict_fun = NULL,
  order_method = "raw",
  ale_engine = c("auto", "cpp", "r")
)
Arguments
model

('any')
Fitted model.

effect

('list()' or 'NULL')
Reserved for future extension. Currently unsupported.

data

('data.frame()' or 'data.table()')
Data.

target_feature_name

('character(1)')
Target variable name.

n_intervals

('integer(1)')
Intervals for numeric ALE.

feature_set

('character()' or 'NULL')
Features for ALE; NULL = all.

split_feature

('character()' or 'NULL')
Features for splitting; NULL = all.

predict_fun

('function()' or 'NULL')
Prediction function.

order_method

('character(1)')
Categorical order: "mds", "pca", "random", or "raw".

ale_engine

('character(1)')
ALE engine: "auto", "cpp", or "r".

Returns

('list()')
Z: split features; Y: ALE effect data.tables.


Method node_transform()

Subset ALE by node indices; handle single-interval and categorical.

Usage
AleStrategy$node_transform(Y, idx, grid = NULL, is_child = FALSE)
Arguments
Y

('list()')
ALE effect list from calculate_ale.

idx

('integer()')
Row indices in the node.

grid

('list()' or 'NULL')
Ignored for ALE; required by interface.

is_child

('logical(1)')
Whether the current node is a child node.

Returns

('list()')
Transformed ALE data.tables.


Method heterogeneity()

Compute ALE heterogeneity via calculate_ale_heterogeneity_cpp.

Usage
AleStrategy$heterogeneity(Y)
Arguments
Y

('list()')
ALE effect list from calculate_ale.

Returns

('numeric()')
Heterogeneity per feature.


Method get_child_objectives()

Compute left/right child objective values from split result. For ALE, extracts from split_info (computed during sweep).

Usage
AleStrategy$get_child_objectives(
  Z,
  Y,
  split_info,
  idx_left,
  idx_right,
  grid_left,
  grid_right
)
Arguments
Z

('data.frame()' or 'data.table()')
Split features.

Y

('list()')
ALE effect from calculate_ale.

split_info

('list()')
Split metadata.

idx_left, idx_right

('integer()')
Child row indices.

grid_left, grid_right

('list()')
Child grids.

Returns

('list()')
left_objective_value_j, right_objective_value_j, left_objective_value, right_objective_value.


Method find_best_split()

Find best split via search_best_split_ale.

Usage
AleStrategy$find_best_split(Z, Y, min_node_size, n_quantiles)
Arguments
Z

('data.frame()' or 'data.table()')
Split features.

Y

('list()')
ALE effect from calculate_ale.

min_node_size

('integer(1)')
Minimum node size.

n_quantiles

('integer(1)' or 'NULL')
Quantile candidates for numeric.

Returns

('list()' or 'data.frame()')
Best split info: split_feature, split_point, etc.


Method plot()

Plot ALE curves via plot_tree_ale.

Usage
AleStrategy$plot(
  tree,
  effect = NULL,
  data,
  target_feature_name,
  depth = NULL,
  node_id = NULL,
  features = NULL,
  show_plot = TRUE,
  show_point = TRUE,
  mean_center = TRUE,
  ...
)
Arguments
tree

('list()')
Depth-based list of Node objects.

effect

('list()' or 'NULL')
ALE effect; NULL = use cached effect.

data

('data.frame()' or 'data.table()')
Data.

target_feature_name

('character(1)')
Target variable name.

depth

('integer()' or 'NULL')
Depths to plot.

node_id

('integer()' or 'NULL')
Node IDs to plot.

features

('character()' or 'NULL')
Features to include.

show_plot, show_point, mean_center

('logical(1)')
Plot options.

...

Passed to plot_tree_ale.

Returns

('list()')
Nested list (depth -> node -> patchwork).


Method fit()

Fit tree: preprocess, create root, split recursively.

Usage
AleStrategy$fit(
  tree,
  model,
  effect = NULL,
  data,
  target_feature_name,
  n_intervals = 10,
  feature_set = NULL,
  split_feature = NULL,
  predict_fun = NULL,
  order_method = "raw",
  ale_engine = c("auto", "cpp", "r"),
  categorical_split = NULL,
  max_exhaustive_levels = NULL,
  ...
)
Arguments
tree

('GadgetTree')
Tree instance.

model

('any')
Fitted model.

effect

('list()' or 'NULL')
Reserved for future extension. Currently unsupported.

data

('data.frame()' or 'data.table()')
Data.

target_feature_name

('character(1)')
Target name.

n_intervals

('integer(1)')
Intervals for numeric ALE.

feature_set, split_feature

('character()' or 'NULL')
Feature subsets.

predict_fun

('function()' or 'NULL')
Prediction function.

order_method

('character(1)')
Categorical order.

ale_engine

('character(1)')
ALE engine: "auto", "cpp", or "r".

categorical_split

('character(1)' or 'NULL')
Categorical split mode for ALE trees; NULL keeps the current strategy setting.

max_exhaustive_levels

('integer(1)' or 'NULL')
Maximum observed levels allowed for exhaustive categorical split search; NULL keeps the current strategy setting.

...

Ignored.

Returns

('GadgetTree')
The tree, invisibly.


Method clean()

Sets data and model to NULL to free memory after fitting. effect is intentionally retained because plot() requires it post-fit.

Usage
AleStrategy$clean()

Method clone()

The objects of this class are cloneable with this method.

Usage
AleStrategy$clone(deep = FALSE)
Arguments
deep

Whether to make a deep clone.

See Also

calculate_ale_heterogeneity_cpp

Examples

ale_strat = AleStrategy$new()
ale_strat$categorical_split


EffectStrategy: Abstract base for effect-based tree strategies.

Description

EffectStrategy: Abstract base for effect-based tree strategies.

EffectStrategy: Abstract base for effect-based tree strategies.

Details

Defines the common interface and shared fit logic for AleStrategy and PdStrategy. Effect strategies implement ALE (Accumulated Local Effects) or PD (Partial Dependence) based tree growing. Not exported.

Public fields

name

('character(1)')
Strategy name (e.g. "ale", "pd").

tree_ref

('GadgetTree' or 'NULL')
Reference to the fitted tree; set after $fit().

fit_timing

('numeric()' or 'NULL')
Fit timing (seconds) for global/regional fits.

Methods

Public methods


Method new()

Create an EffectStrategy instance.

Usage
EffectStrategy$new(name)
Arguments
name

('character(1)')
Strategy identifier (e.g. "ale", "pd").


Method clean()

Optional post-fit cleanup to release retained objects. Default is no-op; subclasses override when needed (see AleStrategy$clean()).

Usage
EffectStrategy$clean()

Method clone()

The objects of this class are cloneable with this method.

Usage
EffectStrategy$clone(deep = FALSE)
Arguments
deep

Whether to make a deep clone.


GadgetTree: Regional feature-effect tree

Description

Wrapper for effect-based trees: given a strategy (pd/ale), fits tree via $fit(), plots effects via $plot(), extracts splits via $extract_split_info(). Delegates all effect logic to the strategy.

Format

[R6::R6Class] object.

Details

This class manages the overall tree structure and delegates effect-specific operations (such as splitting and plotting) to the provided strategy object. It is the main entry point for fitting and visualizing effect-based decision trees in the xplaineff package.

Construction

“' t = GadgetTree$new(strategy, n_split = 2, impr_par = 0.1, min_node_size = 10, n_quantiles = NULL) “' * 'strategy' :: ([AleStrategy] | [PdStrategy])
Effect strategy object. * 'n_split' :: 'integer(1)'
Maximum split depth, counted as splits along any root-to-leaf path. * 'impr_par' :: 'numeric(1)'
Improvement threshold. * 'min_node_size' :: 'integer(1)'
Minimum samples per node. * 'n_quantiles' :: 'integer(1)' or 'NULL'
Number of quantile cut points for numeric split candidates; 'NULL' = use all unique values.

Public fields

strategy

(PdStrategy | AleStrategy)
Effect-specific logic.

root

('Node')
Root node.

n_split

('integer(1)')
Maximum split depth, counted as splits along any root-to-leaf path.

impr_par

('numeric(1)')
Improvement threshold.

min_node_size

('integer(1)')
Minimum samples per node.

n_quantiles

('integer(1)' or 'NULL')
Number of quantile cut points for numeric split candidates.

split_benchmark

('list()')
Internal split timing records.

tree_list_cache

('list()' or 'NULL')
Cached depth-based tree list; invalidated on $fit().

Methods

Public methods


Method new()

Initialize tree parameters.

Usage
GadgetTree$new(
  strategy,
  n_split = 2,
  impr_par = 0.1,
  min_node_size = 10,
  n_quantiles = NULL
)
Arguments
strategy

(PdStrategy | AleStrategy)
Strategy object.

n_split

('integer(1)')
Maximum split depth, counted as splits along any root-to-leaf path.

impr_par

('numeric(1)')
Improvement threshold.

min_node_size

('integer(1)')
Minimum node size.

n_quantiles

('integer(1)' or 'NULL')
Number of quantile cut points for numeric split candidates.


Method fit()

Fit tree via strategy$fit().

Usage
GadgetTree$fit(
  data,
  target_feature_name,
  feature_set = NULL,
  split_feature = NULL,
  ...
)
Arguments
data

('data.frame()')
Data with features and target.

target_feature_name

('character(1)')
Target name.

feature_set

('character()' or 'NULL')
Features for effect; NULL = all.

split_feature

('character()' or 'NULL')
Features for splitting; NULL = all.

...

('list()')
Strategy-specific arguments passed to $fit(). For [AleStrategy]: model or effect, plus optional n_intervals, predict_fun, order_method, ale_engine, categorical_split, and max_exhaustive_levels. For [PdStrategy]: effect, or model with optional predict_fun, n_grid, pd_engine, categorical_split, and max_exhaustive_levels.

Returns

('GadgetTree')
The tree, invisibly.


Method plot()

Plot tree via strategy$plot().

Usage
GadgetTree$plot(
  data,
  target_feature_name,
  effect = NULL,
  depth = NULL,
  node_id = NULL,
  features = NULL,
  ...
)
Arguments
data

('data.frame()')
Data.

target_feature_name

('character(1)')
Target name.

effect

(R6 or 'list()' or 'NULL')
Optional effect object; omit or NULL uses strategy-cached effect from $fit().

depth

('integer()' or 'NULL')
Depths to plot.

node_id

('integer()' or 'NULL')
Node IDs to plot.

features

('character()' or 'NULL')
Features to plot.

...

Plot arguments.

Returns

('list()')
Nested list (depth -> node -> patchwork).


Method plot_tree_structure()

Converts root to depth-list and calls plot_tree_structure(). Prints graph.

Usage
GadgetTree$plot_tree_structure(
  label_wrap_width = 34L,
  node_spread_x = 1.55,
  node_spread_y = 1.12
)
Arguments
label_wrap_width

('integer(1)' or 'NULL')
Wrap node labels to this many characters per line; NULL disables wrapping.

node_spread_x, node_spread_y

('numeric(1)')
Layout stretch factors for the ggraph "tree" layout (larger values separate nodes).


Method extract_split_info()

Extract split info from tree.

Usage
GadgetTree$extract_split_info(include_timing = FALSE)
Arguments
include_timing

('logical(1)')
Whether to include internal split timings in the output.

Returns

('data.frame()')
Split info: depth, id, split_feature, split_value, int_imp, etc.


Method get_tree_list()

Get depth-based tree list (cached). Invalidated on $fit().

Usage
GadgetTree$get_tree_list()
Returns

('list()')
Depth-based list of nodes.


Method clone()

The objects of this class are cloneable with this method.

Usage
GadgetTree$clone(deep = FALSE)
Arguments
deep

Whether to make a deep clone.

Examples

tree = GadgetTree$new(strategy = PdStrategy$new(), n_split = 2L)
tree$n_split


Node: Tree Node for Effect-based Decision Trees (R6 class)

Description

Node: Tree Node for Effect-based Decision Trees (R6 class)

Node: Tree Node for Effect-based Decision Trees (R6 class)

Details

Represents a single node in an effect-based decision tree, storing split information, effect statistics, and child nodes. Uses grouped fields for clearer structure.

This class is used internally by GadgetTree and strategy objects to represent and manage nodes in effect-based decision trees. Each node stores split information, effect statistics, and references to its children.

Public fields

id

('integer(1)')
Node identifier within its depth level.

depth

('integer(1)')
Depth of the node (root starts at 1).

subset_idx

('integer()')
Row indices of data that fall into this node.

grid

('list()')
Grid values for each feature in this node.

parent

('list()' or 'NULL')
Parent info: id, child_type, split_feature, split_value, objective_value, int_imp. NULL for root.

split

('list()' or 'NULL')
Split info: feature, value. NULL for terminal nodes.

objective

('list()')
Objective: value (scalar), value_j (per-feature vector).

importance

('list()' or 'NULL')
Importance: imp (scalar), imp_j (per-feature). NULL for root and unsplit nodes.

children

('list()' or 'NULL')
Left and right child nodes (or NULL for terminal nodes).

stop_criterion_met

('logical(1)')
Whether the minimal node size or improvement threshold has been reached.

improvement_met

('logical(1)')
Whether the improvement-based stop criterion was met ('TRUE' = stop splitting).

strategy

(PdStrategy | AleStrategy)
Strategy for effect-specific operations.

Methods

Public methods


Method new()

Create a node from id, depth, subset indices, grid, and optional parent/objective metadata. Sets stop_criterion_met = FALSE.

Usage
Node$new(
  id,
  depth = NULL,
  subset_idx,
  grid,
  id_parent = NULL,
  child_type = NULL,
  objective_value_parent = NULL,
  objective_value_j = NULL,
  objective_value = NULL,
  improvement_met = FALSE,
  int_imp = NULL,
  int_imp_j = NULL,
  strategy = NULL
)
Arguments
id

('integer(1)')
Node identifier.

depth

('integer(1)' or 'NULL')
Node depth (root is 1).

subset_idx

('integer()')
Row indices of data in this node.

grid

('list()')
Grid values for each feature.

id_parent

('integer(1)' or 'NULL')
Parent node id.

child_type

('character(1)' or 'NULL')
Split direction ("<=", ">", "==", "!=", or "in").

objective_value_parent

('numeric(1)' or 'NULL')
Parent node's objective value.

objective_value_j

('numeric()' or 'NULL')
Objective values per feature.

objective_value

('numeric(1)' or 'NULL')
Total objective value.

improvement_met

('logical(1)')
Whether improvement threshold was met.

int_imp

('numeric(1)' or 'NULL')
Interaction importance.

int_imp_j

('numeric()' or 'NULL')
Interaction importance per feature.

strategy

(PdStrategy | AleStrategy or 'NULL')
Strategy; NULL not used in practice.


Method split_node()

Given Z, Y, root objectives, and tree params: checks stopping criteria; finds best split; creates and applies children; recurses into child nodes. Returns NULL if no valid split.

Usage
Node$split_node(
  Z,
  Y,
  objective_value_root_j,
  objective_value_root,
  min_node_size,
  n_quantiles,
  impr_par,
  depth,
  max_depth
)
Arguments
Z

('data.frame()' or 'data.table()')
Split features.

Y

('list()')
Effect list.

objective_value_root_j

('numeric()')
Root objective values per feature.

objective_value_root

('numeric(1)')
Root total objective value.

min_node_size

('integer(1)')
Minimum node size.

n_quantiles

('integer(1)' or 'NULL')
Quantiles for candidate split points.

impr_par

('numeric(1)')
Improvement threshold.

depth

('integer(1)')
Current node depth.

max_depth

('integer(1)')
Maximum tree depth.

Returns

('NULL')


Method find_best_split()

Given Z (subset by node indices), y_curr, and params: calls strategy$find_best_split and returns list with split_feature, split_value, is_categorical (and for AleStrategy: left/right_objective_value_j).

Usage
Node$find_best_split(Z, y_curr, min_node_size, n_quantiles)
Arguments
Z

('data.frame()' or 'data.table()')
Split features.

y_curr

('list()')
Effect list for current node.

min_node_size

('integer(1)')
Minimum node size.

n_quantiles

('integer(1)' or 'NULL')
Quantiles for candidate split points.

Returns

('list()' or 'NULL')
Best split info or NULL if no valid split.


Method create_children()

Given Z, Y, split_info, and root objectives: computes idx_left/right, child grids, objective values; checks improvement threshold; creates left/right Node instances and sets parent info. Returns list of left_child, right_child, int_imp, int_imp_j or NULL if improvement too small.

Usage
Node$create_children(
  z_split_feature,
  Y,
  split_info,
  objective_value_root_j,
  objective_value_root,
  impr_par
)
Arguments
z_split_feature

('numeric()')
Numeric vector. Values of the splitting feature of this split.

Y

('list()')
Effect list.

split_info

('list()')
Split information.

objective_value_root_j

('numeric()')
Root objective values per feature.

objective_value_root

('numeric(1)')
Root total objective value.

impr_par

('numeric(1)')
Improvement threshold.

Returns

('list()')
Left/right child nodes and split statistics.


Method create_child_grids()

Given split_feature, split_value, and is_categorical: partitions self$grid[[split_feature]] into left (<= or ==) and right (> or !=). Returns list grid_left, grid_right.

Usage
Node$create_child_grids(
  split_feature,
  split_value,
  is_categorical,
  split_levels = NULL
)
Arguments
split_feature

('character(1)')
Feature used for splitting.

split_value

('numeric(1)' or 'factor()')
Split value.

is_categorical

('logical(1)')
Whether the split feature is categorical.

split_levels

('character()' or 'NULL')
Left-side levels for explicit categorical level-set splits.

Returns

('list()')
grid_left, grid_right.


Method apply_split()

Given split_info and children_info: sets split_feature, split_value, int_imp, int_imp_j, children.

Usage
Node$apply_split(split_info, children_info)
Arguments
split_info

('list()')
Split information.

children_info

('list()')
Children information.

Returns

('NULL')


Method clone()

The objects of this class are cloneable with this method.

Usage
Node$clone(deep = FALSE)
Arguments
deep

Whether to make a deep clone.


PdStrategy: Generalized Additive Decomposition Based on PD Effects

Description

PD-based effect strategy (inherits from EffectStrategy). Given effect or model and data, preprocesses to Z/Y/grid; mean-centers effects per node; computes sum-of-variances heterogeneity; finds best split via C++; fits tree and plots PD/ICE. Character feature columns are coerced to factor before ICE/PD computation so they match split-matrix treatment and learner conventions (same as prepare_split_data_common).

Format

[R6::R6Class] object inheriting from [EffectStrategy].

Details

This class is used internally by the GadgetTree framework to implement partial dependence tree growing, splitting, and visualization. It is not intended to be used directly by end users, but can be instantiated for advanced customization.

Construction

“' s = PdStrategy$new(categorical_split = "one_vs_rest") “'

Super class

::EffectStrategy -> PdStrategy

Public fields

effect

('list()' or 'R6' or 'NULL')
Cached PD/ICE effect used when $plot() omits effect.

categorical_split

('character(1)')
Categorical split mode for PD trees: "one_vs_rest" or "exhaustive".

max_exhaustive_levels

('integer(1)')
Maximum observed levels allowed for exhaustive categorical split search.

Methods

Public methods


Method new()

Create a PdStrategy instance (calls super$initialize("pd")).

Usage
PdStrategy$new(categorical_split = "one_vs_rest", max_exhaustive_levels = 12L)
Arguments
categorical_split

('character(1)')
Categorical split mode for PD trees: "one_vs_rest" or "exhaustive".

max_exhaustive_levels

('integer(1)')
Maximum observed levels allowed for exhaustive categorical split search.


Method preprocess()

Preprocess to Z, Y, grid via prepare_split_data_pd.

Usage
PdStrategy$preprocess(
  effect,
  data,
  target_feature_name = NULL,
  feature_set = NULL,
  split_feature = NULL
)
Arguments
effect

(R6 or 'list()')
Effect object (e.g. FeatureEffect).

data

('data.frame()' or 'data.table()')
Data.

target_feature_name

('character(1)' or 'NULL')
Target variable name.

feature_set

('character()' or 'NULL')
Features for effect; NULL = all.

split_feature

('character()' or 'NULL')
Features for splitting; NULL = all.

Returns

('list()')
Z, Y, grid.


Method node_transform()

Subset and mean-center via re_mean_center_ice_cpp.

Usage
PdStrategy$node_transform(Y, idx, grid, is_child = FALSE)
Arguments
Y

('list()')
Effect matrices per feature.

idx

('integer()')
Sample indices in the node.

grid

('list()')
Feature grids; required for PD.

is_child

('logical(1)')
Ignored for PD; kept for API parity with AleStrategy.

Returns

('list()')
Mean-centered effect matrices.


Method heterogeneity()

Compute heterogeneity via node_heterogeneity.

Usage
PdStrategy$heterogeneity(Y)
Arguments
Y

('list()')
Effect matrices.

Returns

('numeric()')
Heterogeneity per feature.


Method get_child_objectives()

Compute left/right child objective values via node_transform and heterogeneity.

Usage
PdStrategy$get_child_objectives(
  Z,
  Y,
  split_info,
  idx_left,
  idx_right,
  grid_left,
  grid_right
)
Arguments
Z

('data.frame()' or 'data.table()')
Split features.

Y

('list()')
Effect matrices.

split_info

('list()')
Split metadata.

idx_left, idx_right

('integer()')
Child row indices.

grid_left, grid_right

('list()')
Child grids.

Returns

('list()')
left_objective_value_j, right_objective_value_j, left_objective_value, right_objective_value.


Method find_best_split()

Find best split via search_best_split_cpp.

Usage
PdStrategy$find_best_split(Z, Y, min_node_size, n_quantiles)
Arguments
Z

('data.frame()' or 'data.table()')
Split features.

Y

('list()')
Effect matrices.

min_node_size

('integer(1)')
Minimum node size.

n_quantiles

('integer(1)' or 'NULL')
Quantile candidates.

Returns

('data.frame()' or 'list()')
Best split info.


Method plot()

Plot PD/ICE tree via plot_tree_pd.

Usage
PdStrategy$plot(
  tree,
  effect = NULL,
  data,
  target_feature_name,
  depth = NULL,
  node_id = NULL,
  features = NULL,
  ...
)
Arguments
tree

('list()')
Depth-based list of Node objects.

effect

(R6 or 'list()' or 'NULL')
Effect object.

data

('data.frame()')
Data.

target_feature_name

('character(1)')
Target name.

depth

('integer()' or 'NULL')
Depths to plot.

node_id

('integer()' or 'NULL')
Node IDs to plot.

features

('character()' or 'NULL')
Features to plot.

...

Plot arguments.

Returns

('list()')
Nested list (depth -> node -> patchwork).


Method fit()

Fit tree: preprocess, create root, split recursively.

Usage
PdStrategy$fit(
  tree,
  effect = NULL,
  model = NULL,
  data,
  target_feature_name,
  feature_set = NULL,
  split_feature = NULL,
  predict_fun = NULL,
  n_grid = 20L,
  pd_engine = c("auto", "cpp", "r"),
  categorical_split = NULL,
  max_exhaustive_levels = NULL,
  ...
)
Arguments
tree

('GadgetTree')
Tree instance.

effect

(R6 or 'list()' or 'NULL')
Optional precomputed effect object.

model

('any')
Fitted model for internal PD/ICE computation.

data

('data.frame()')
Data.

target_feature_name

('character(1)')
Target name.

feature_set, split_feature

('character()' or 'NULL')
Feature subsets.

predict_fun

('function()' or 'NULL')
Optional prediction function.

n_grid

('integer(1)')
Number of grid points for numeric features.

pd_engine

('character(1)')
When computing ICE/PD from model: "auto", "cpp" (column-wise stacked newdata, xplaineff-style), or "r" (data.table::rbindlist).

categorical_split

('character(1)' or 'NULL')
Categorical split mode for PD trees; NULL keeps the current strategy setting.

max_exhaustive_levels

('integer(1)' or 'NULL')
Maximum observed levels allowed for exhaustive categorical split search; NULL keeps the current strategy setting.

...

Ignored.

Returns

('GadgetTree')
The tree, invisibly.


Method clean()

Drops tree_ref; effect cache is intentionally retained when present.

Usage
PdStrategy$clean()

Method clone()

The objects of this class are cloneable with this method.

Usage
PdStrategy$clone(deep = FALSE)
Arguments
deep

Whether to make a deep clone.

Examples

pd_strat = PdStrategy$new()
pd_strat$categorical_split


ALE for a single categorical feature.

Description

ALE for a single categorical feature.

Usage

ale_categorical_feature(
  model,
  data,
  X,
  feature,
  predict_fun = NULL,
  stacked = NULL,
  idx_lower = NULL,
  idx_upper = NULL,
  predictor = NULL
)

Arguments

model

('any')
Fitted model. See calculate_ale.

data

('data.frame()' or 'data.table()')
Training data.

X

('data.frame()' or 'data.table()')
Features (excl. target).

feature

('character(1)')
Feature name.

predict_fun

('function()' or 'NULL')
Prediction function.

stacked

('NULL' or [data.table::data.table()])
Shared 2n-row design matrix for batched categorical ALE (see numeric branch).

idx_lower

idx_upper ('integer()' or NULL)
Row halves in stacked: plus-vector / minus-vector predictions respectively.

predictor

('list()' or 'NULL')
Prediction wrapper from make_effect_predictor; NULL builds one from model and predict_fun.

Value

('data.table()')
ALE data with row_id, feat_val, d_l, interval_index, etc.


Fast ALE for a single feature.

Description

Fast ALE for a single feature.

Usage

ale_feature(
  data,
  X,
  stacked,
  idx_lower,
  idx_upper,
  feature,
  n_intervals = 10L,
  predictor
)

Arguments

data

('data.frame()' or 'data.table()')
Training data.

X

('data.table()')
Features (excl. target). Never modified.

stacked

('data.table()')
Pre-allocated 2n-row matrix shared across features; modified in-place per call.

idx_lower

('integer()')
Row indices for the lower/plus half of stacked (1..n).

idx_upper

('integer()')
Row indices for the upper/minus half of stacked ((n+1)..2n).

feature

('character(1)')
Feature name.

n_intervals

('integer(1)')
Number of intervals.

predictor

('list()')
Prediction function wrapper from make_effect_predictor.

Value

('data.table()')
ALE data with row_id, feat_val, d_l, interval_index, etc.


ALE for a single numeric feature.

Description

ALE for a single numeric feature.

Usage

ale_numeric_feature(
  model,
  data,
  X,
  feature,
  n_intervals = 10,
  predict_fun = NULL,
  stacked = NULL,
  idx_lower = NULL,
  idx_upper = NULL,
  predictor = NULL
)

Arguments

model

('any')
Fitted model. See calculate_ale.

data

('data.frame()' or 'data.table()')
Training data.

X

('data.frame()' or 'data.table()')
Features (excl. target).

feature

('character(1)')
Feature name.

n_intervals

('integer(1)')
Number of intervals.

predict_fun

('function()' or 'NULL')
Prediction function.

stacked

('NULL' or [data.table::data.table()])
Shared 2n-row design matrix; omit to allocate internally.

idx_lower

idx_upper ('integer()' or NULL)
Lower/upper half row indices inside stacked.

predictor

('list()' or 'NULL')
Prediction wrapper from make_effect_predictor; NULL builds one from model and predict_fun.

Value

('data.table()')
ALE data with row_id, feat_val, d_l, interval_index, etc.


Build per-feature interval statistics for ALE effect.

Description

Build per-feature interval statistics for ALE effect.

Usage

build_ale_interval_stats(effect, features)

Arguments

effect

('list()')
ALE effect data per feature (from calculate_ale).

features

('character()')
Feature names to include.

Value

('list()')
Statistics: K, offsets, tot_n, tot_s1, tot_s2, r_n, r_s1, r_s2, r_risks, d_l_mat, interval_idx_mat.


Build order and split candidates for ALE sweep.

Description

Build order and split candidates for ALE sweep.

Usage

build_ale_order_and_candidates(z, is_categorical, n_quantiles = NULL)

Arguments

z

('numeric()' or 'factor()')
Split feature values.

is_categorical

('logical(1)')
Whether z is categorical.

n_quantiles

('integer(1)' or 'NULL')
Quantiles for numeric features.

Value

('list()' or 'NULL')
ord_idx, z_sorted, n_obs, is_cand; for categorical also boundary_pos, levels_vec. NULL if no valid split.


Build node title for ALE or PD tree plots.

Description

Build node title for ALE or PD tree plots.

Usage

build_node_title(node, depth_idx, tree, style = c("ale", "pd"))

Arguments

node

('Node')
Node object.

depth_idx

('integer(1)')
Depth index.

tree

('list()')
Depth-based list of Node objects.

style

('character(1)')
"ale" or "pd" for format variant.

Value

('character(1)')
Title string.


Calculate Accumulated Local Effects (ALE)

Description

Given model, data, feature_set, target_feature_name, n_intervals, predict_fun: for each feature, computes finite differences (d_l) and per-interval stats (int_n, int_s1, int_s2). Numeric: quantile intervals; categorical: level-by-level prediction differences. Returns named list of data.tables (row_id, feat_val, d_l, interval_index, int_n, int_s1, int_s2, etc.).

Usage

calculate_ale(
  model,
  data,
  feature_set,
  target_feature_name,
  n_intervals = 10,
  predict_fun = NULL
)

Arguments

model

('any')
Fitted model with predict interface.

data

('data.frame()' or 'data.table()')
Training data.

feature_set

('character()')
Features to compute ALE for.

target_feature_name

('character(1)')
Target variable name.

n_intervals

('integer(1)')
Equal-frequency intervals for numeric features.

predict_fun

('function()' or 'NULL')
function(model, data) returning predictions; NULL = default.

Details

Numeric features: builds n_intervals quantile-based intervals, assigns each row to an interval, and computes finite differences between interval boundaries via predict_fun.

Categorical features: use factor levels as given (typically pre-ordered by order_categorical_levels in prepare_split_data_ale). For each row, d_l is the difference in predictions when the focal feature is set to the next vs. previous level; single-level factors get d_l = 0.

Sample-level columns (row_id, feat_val, d_l, etc.) support subsetting by node and downstream heterogeneity calculation.

Downstream plotting (prepare_plot_data_ale) aggregates these rows by (interval_index, x_left, x_right), cumulates d_l, and optionally mean-centers the cumulative curve; plot grids for categories derive from aggregated x_left values, not by re-evaluating calculate_ale.

Value

('list()')
Named list of data.tables per feature_set. Each has columns:

row_id

Row index in data.

feat_val

Feature value at that row.

x_left, x_right

Interval/category boundaries (numeric) or left/right category (factor).

d_l

Local effect (finite difference).

interval_index

Interval or category index.

int_n, int_s1, int_s2

Per-interval count and sum(d_l), sum(d_l^2) for heterogeneity.


Calculate ALE via C++ kernels

Description

Fast ALE path that keeps model prediction in R, while using C++ kernels for interval indexing and interval-wise aggregation. Numeric and categorical branches stack lower/upper (or plus/minus) configurations into 2n rows and call the predictor once per feature, matching the batched predict_newdata_fast pattern used in xplaineff::ale.

Usage

calculate_ale_fast(
  model,
  data,
  feature_set,
  target_feature_name,
  n_intervals = 10,
  predict_fun = NULL
)

Arguments

model

('any')
Fitted model with predict interface.

data

('data.frame()' or 'data.table()')
Training data.

feature_set

('character()')
Features to compute ALE for.

target_feature_name

('character(1)')
Target variable name.

n_intervals

('integer(1)')
Equal-frequency intervals for numeric features.

predict_fun

('function()' or 'NULL')
function(model, data) returning predictions; NULL = default.

Value

('list()')
Named list of ALE data.tables, same schema as calculate_ale().


Calculate ALE Heterogeneity

Description

Calculate ALE Heterogeneity

Usage

calculate_ale_heterogeneity_cpp(Y)

Arguments

Y

('list()' or 'data.frame()')
ALE effect data.

Value

('numeric()')
Heterogeneity value(s): vector per feature when Y is list, single value when Y is data.frame.


Calculate Partial Dependence Curves

Description

Computes ICE (Individual Conditional Expectation) matrices for each feature in feature_set and returns them in long-format data.tables.

Usage

calculate_pd(
  model,
  data,
  target_feature_name,
  feature_set = NULL,
  predict_fun = NULL,
  n_grid = 20L,
  pd_engine = c("auto", "cpp", "r")
)

Arguments

model

('any')
Fitted model with a predict interface.

data

('data.frame()' or 'data.table()')
Training data including the target column.

target_feature_name

('character(1)')
Name of the target variable; excluded from feature columns.

feature_set

('character()' or 'NULL')
Features to compute PD for; NULL = all non-target columns.

predict_fun

('function()' or 'NULL')
function(model, data) returning a numeric vector; NULL = default.

n_grid

('integer(1)')
Number of quantile-based grid points for numeric features.

pd_engine

('character(1)')
Backend: "auto" (default), "cpp", or "r". The "auto" backend may use an internal row-major full-ICE layout for native ranger regression models.

Value

('list()')
Named list with element results: a named list of data.tables, one per feature, each with columns .id, .type, .feature, .borders, .value.


Calculate Partial Dependence Matrices

Description

Internal matrix-form variant used by PdStrategy when effects are computed from a model. It avoids converting ICE matrices to long tables only to pivot them back to matrices before split search.

Usage

calculate_pd_matrix(
  model,
  data,
  target_feature_name,
  feature_set = NULL,
  predict_fun = NULL,
  n_grid = 20L,
  pd_engine = c("auto", "cpp", "r")
)

Arguments

model

('any')
Fitted model with a predict interface.

data

('data.frame()' or 'data.table()')
Training data including the target column.

target_feature_name

('character(1)')
Name of the target variable; excluded from feature columns.

feature_set

('character()' or 'NULL')
Features to compute PD for; NULL = all non-target columns.

predict_fun

('function()' or 'NULL')
function(model, data) returning a numeric vector; NULL = default.

n_grid

('integer(1)')
Number of quantile-based grid points for numeric features.

pd_engine

('character(1)')
Backend: "auto" (default), "cpp", or "r". The "auto" backend may use an internal row-major full-ICE layout for native ranger regression models.

Value

('list()')
Object of class xplaineff_pd_matrix with Y and grid.


Compute y-axis range for PD plots.

Description

Compute y-axis range for PD plots.

Usage

calculate_y_range(
  prepared_data,
  data,
  target_feature_name,
  mean_center = FALSE
)

Arguments

prepared_data

('list()')
Prepared effect data.

data

('data.frame()')
Original data.

target_feature_name

('character(1)')
Target column.

mean_center

('logical(1)')
If TRUE, ICE/PDP are on a centered scale; the raw target column is not merged into ylim. If FALSE, limits follow ICE/PD values and the target range (for overlays).

Value

('list()')
ymin, ymax.


Shared implementation for y-axis range from effect values.

Description

Shared implementation for y-axis range from effect values.

Usage

calculate_y_range_impl(effect_values, data = NULL, target_feature_name = NULL)

Arguments

effect_values

('numeric()')
Effect values (no NA).

data

('data.frame()' or 'NULL')
Original data; target values are always included in range when available.

target_feature_name

('character(1)' or 'NULL')
Target column.

Value

('list()')
ymin, ymax.


Return comparison operator for child relative to parent. Given parent_node and current_node: if current is left child returns <= (numeric) or = (categorical); if right returns > or !=.

Description

Return comparison operator for child relative to parent. Given parent_node and current_node: if current is left child returns <= (numeric) or = (categorical); if right returns > or !=.

Usage

choose_operator(parent_node, current_node)

Arguments

parent_node

('Node')
Node with children and split$value.

current_node

('Node')
One of the children.

Value

('character(1)')
"<=", ">", "=", or "!=".


Compute ICE Matrix (Dispatch)

Description

Dispatches ICE computation to the C++, R, or row-major backend based on pd_engine.

Usage

compute_ice(
  model,
  data,
  feature,
  grid,
  predict_fun = NULL,
  pd_engine = c("cpp", "r", "row_major"),
  base_data_dt = NULL,
  cols_list = NULL,
  feature_index = NULL,
  stacked_pd_cache = NULL,
  predictor = NULL,
  base_data_df = NULL
)

Arguments

model

('any')
Fitted model.

data

('data.frame()' or 'data.table()')
Feature data (target column already removed).

feature

('character(1)')
Name of the focal feature.

grid

('atomic vector')
Grid values for the focal feature.

predict_fun

('function()' or 'NULL')
Custom predict function; NULL = default.

pd_engine

('character(1)')
"cpp", "r", or internal "row_major".

base_data_dt

('data.table()' or 'NULL')
Pre-converted data.table of data; avoids repeated conversion.

cols_list

('list()' or 'NULL')
Pre-extracted column list of base_data_dt; used by the C++ path.

feature_index

('integer(1)' or 'NULL')
1-based column index of feature in base_data_dt; used by the C++ path.

stacked_pd_cache

('list()' or 'NULL')
Pre-allocated stacked data.table cache for the R path; NULL disables caching.

predictor

('list()' or 'NULL')
Prediction wrapper from make_effect_predictor; NULL builds one from model and predict_fun.

base_data_df

('data.frame()' or 'NULL')
Pre-converted data.frame of data; used by the row-major path.

Value

('matrix')
Numeric matrix of shape n_obs x length(grid) containing ICE predictions.


Compute ICE Matrix (C++ Backend)

Description

Uses cpp_pd_stack_newdata to build the stacked prediction table in C++. Prediction still runs through the shared predictor wrapper. Character and logical focal feature columns are unsupported in this path.

Usage

compute_ice_cpp(
  model,
  data,
  feature,
  grid,
  predict_fun = NULL,
  base_data_dt = NULL,
  cols_list = NULL,
  feature_index = NULL,
  predictor = NULL
)

Arguments

model

('any')
Fitted model.

data

('data.frame()' or 'data.table()')
Feature data (target removed).

feature

('character(1)')
Name of the focal feature.

grid

('atomic vector')
Grid values for the focal feature.

predict_fun

('function()' or 'NULL')
Custom predict function; NULL = default.

base_data_dt

('data.table()' or 'NULL')
Pre-converted data.table; avoids repeated conversion.

cols_list

('list()' or 'NULL')
Pre-extracted column list of base_data_dt.

feature_index

('integer(1)' or 'NULL')
1-based column index of feature in base_data_dt.

predictor

('list()' or 'NULL')
Prediction wrapper from make_effect_predictor; NULL builds one from model and predict_fun.

Value

('matrix')
Numeric matrix of shape n_obs x length(grid).


Compute ICE Matrix (Pure R)

Description

Builds a stacked prediction data.table by repeating each row once per grid value, replaces the focal feature column with each grid value, runs pd_predict, and reshapes predictions into a matrix.

Usage

compute_ice_r(
  model,
  data,
  feature,
  grid,
  predict_fun = NULL,
  base_data_dt = NULL,
  stacked_pd_cache = NULL,
  predictor = NULL
)

Arguments

model

('any')
Fitted model.

data

('data.frame()' or 'data.table()')
Feature data (target removed).

feature

('character(1)')
Name of the focal feature.

grid

('atomic vector')
Grid values for the focal feature.

predict_fun

('function()' or 'NULL')
Custom predict function; NULL = default.

base_data_dt

('data.table()' or 'NULL')
Pre-converted data.table; avoids repeated conversion.

stacked_pd_cache

('list()' or 'NULL')
Pre-allocated stacked table with elements stacked, max_g, n_obs; NULL disables caching.

predictor

('list()' or 'NULL')
Prediction wrapper from make_effect_predictor; NULL builds one from model and predict_fun.

Value

('matrix')
Numeric matrix of shape n_obs x length(grid).


Compute ICE Matrix (Row-Major Backend)

Description

Builds full ICE prediction data in observation-major order: all grid values for observation 1, then all grid values for observation 2, and so on. Prediction still runs through the shared predictor wrapper.

Usage

compute_ice_row_major(
  model,
  data,
  feature,
  grid,
  predict_fun = NULL,
  base_data_dt = NULL,
  base_data_df = NULL,
  predictor = NULL
)

Arguments

model

('any')
Fitted model.

data

('data.frame()' or 'data.table()')
Feature data (target removed).

feature

('character(1)')
Name of the focal feature.

grid

('atomic vector')
Grid values for the focal feature.

predict_fun

('function()' or 'NULL')
Custom predict function; NULL = default.

base_data_dt

('data.table()' or 'NULL')
Pre-converted data.table; avoids repeated conversion.

predictor

('list()' or 'NULL')
Prediction wrapper from make_effect_predictor; NULL builds one from model and predict_fun.

Value

('matrix')
Numeric matrix of shape n_obs x length(grid).


Convert Recursive Tree to Depth-based List

Description

Given root_node and optional max_depth: traverses children recursively, collects nodes by depth. Returns list of lists (depth 1, 2, ...), each element a list of Node objects at that depth.

Usage

convert_tree_to_list(root_node, max_depth = NULL)

Arguments

root_node

('Node' or 'NULL')
Root node of the tree.

max_depth

('integer(1)' or 'NULL')
Maximum depth to traverse; NULL = no limit.

Value

('list()')
List where each element is a depth level containing Node objects.


Create PD plots for one depth.

Description

Create PD plots for one depth.

Usage

create_plots_for_depth(
  tree,
  prepared_data,
  data,
  target_feature_name,
  depth_idx,
  nodes_to_render,
  color_ice,
  color_pd,
  show_plot,
  show_point,
  mean_center
)

Arguments

tree

('list()')
Depth-based list of Node objects.

prepared_data

('list()')
Prepared effect data per feature.

data

('data.frame()' or 'data.table()')
Original data.

target_feature_name

('character(1)')
Target column name.

depth_idx

('integer(1)')
Depth level.

nodes_to_render

('integer()')
Node indices to render.

color_ice, color_pd

('character(1)')
Colors for ICE and PDP.

show_plot, show_point, mean_center

('logical(1)')
Plot options.

Value

('list()')
Named list of patchwork objects per node.


Cumulative sum with NA as zero.

Description

Cumulative sum with NA as zero.

Usage

cumsum_na_as_zero(values)

Arguments

values

('numeric()')
Values to cumulatively sum; NA treated as 0.

Value

('numeric()')
Cumulative sum.


Ensure character columns are factors.

Description

Ensure character columns are factors.

Usage

ensure_factors(data, cols)

Arguments

data

('data.frame()' or 'data.table()')
Data to modify.

cols

('character()')
Column names to ensure as factor.

Value

('data.frame()' or 'data.table()')
Modified data (by reference for data.table).


Extract Split Information from Tree Structure

Description

Given tree (depth-list of Node objects) and optional split_benchmark: flattens nodes; builds one row per node (depth, id, n_obs, split_feature, split_value, int_imp, int_imp_j, etc.); merges timing if split_benchmark has node_id/depth. Returns data frame.

Usage

extract_split_info(tree, split_benchmark = NULL)

Arguments

tree

('list()')
Depth-based list of Node objects (from convert_tree_to_list).

split_benchmark

('data.frame()' or 'list()' or 'NULL')
Optional split timing info with columns node_id and depth.

Details

This function is used internally by the GadgetTree framework to extract and summarize the structure and statistics of effect-based decision trees. It is useful for interpretation, reporting, and benchmarking.

Value

('data.frame()')
One row per node: split feature/value, statistics, and (if available) timing.


Convert factor to numeric. Given f: if all level labels parse as numbers, uses as.numeric(as.character(f)); otherwise uses as.numeric(f) (level indices). Returns numeric vector.

Description

Convert factor to numeric. Given f: if all level labels parse as numbers, uses as.numeric(as.character(f)); otherwise uses as.numeric(f) (level indices). Returns numeric vector.

Usage

factor_to_numeric(f)

Arguments

f

('factor()')
Factor to convert.

Value

('numeric()')
Numeric vector.


Find node by id in a flat list.

Description

Given node_list and id: loops and returns first node with node$id == id, or NULL.

Usage

find_node_by_id(node_list, id)

Arguments

node_list

('list()')
List of Node objects (each with an id field).

id

('integer(1)')
Node id to look up.

Value

('Node' or 'NULL')
The node with matching id, or NULL if not found.


Internal ALE curve computation

Description

Given ALE data.table for one feature and mean_center: cumsums d_l by interval; optionally subtracts global mean. Returns data.table with x_grid and .value (cumulative ALE).

Usage

mean_center_ale(feat, mean_center = TRUE)

Arguments

feat

('data.table()')
Per-interval ALE derivatives and metadata.

mean_center

('logical(1)')
Whether to mean-center the ALE curve.

Value

('data.table()')
Cumulative ALE with x_grid and cumulative values in column d_l.


Build wide effect matrices from iml-style effect containers

Description

Expects effect$results as either a single data.frame or a named list of per-feature tables. Delegates pivoting to pivot_effect_to_wide.

Usage

mean_center_ice(effect, feature_set = NULL, mean_center = TRUE)

Arguments

effect

(R6 or 'list()')
Effect object with results field (e.g. from FeatureEffect).

feature_set

('character()' or 'NULL')
Features to include; NULL = all.

mean_center

('logical(1)')
Whether to mean-center each effect matrix row-wise.

Details

If effect$results is a data.frame, one feature is inferred from column names. If it is a named list, each element is pivoted separately.

Value

('list()')
Y: named list of matrices per feature; grid: column names (grid coordinates) per feature.


Compute heterogeneity per feature from effect matrices

Description

Given Y (list of numeric matrices): for each matrix, computes sum over columns of (sum of squares - (sum)^2/n) via node_heterogeneity_cpp. Returns numeric vector of length length(Y).

Usage

node_heterogeneity(Y)

Arguments

Y

('list()')
List of numeric matrices (ICE effect per feature).

Value

('numeric()')
Heterogeneity per feature, length length(Y).


Node Transform ALE

Description

Subsets ALE effect data to the current node's row indices and recomputes per-interval statistics. When is_child is TRUE, forces d_l = 0 for any feature whose values are constant in this node (single unique value).

Usage

node_transform_ale(Y, idx, is_child = FALSE)

Arguments

Y

('list()')
ALE effect data per feature.

idx

('integer()')
Sample indices in the current node.

is_child

('logical(1)')
Whether the current node is a child node; FALSE skips constant-feature zeroing.

Value

('list()')
Transformed ALE effects per feature.


Order Levels of a Categorical Feature

Description

Given x_cat (factor), data, feature, target_feature_name, order_method: builds KxK distance matrix from other features (ECDF diff for numeric, L1 for categorical); embeds in 1D via MDS/PCA/random/raw; reorders levels. Returns factor with reordered levels (or x_cat unchanged if K<=1 or no other features).

Usage

order_categorical_levels(
  x_cat,
  data,
  feature,
  target_feature_name,
  order_method = "raw"
)

Arguments

x_cat

('factor()')
Focal feature values; use droplevels() first.

data

('data.frame()' or 'data.table()')
Full dataset including target.

feature

('character(1)')
Name of the categorical feature in data.

target_feature_name

('character(1)')
Target column name; excluded from distance computation.

order_method

('character(1)')
"mds", "pca", "random", or "raw".

Details

For each pair of levels, a distance is computed from all other features (all columns in data except feature and target_feature_name):

The K \times K distance matrix is embedded in 1D via order_method; that 1D order defines the new level order. Single-level factors or no other features yield x_cat unchanged.

Value

('factor()')
Same as x_cat with reordered levels and ordered = TRUE; unchanged if nlevels(x_cat) <= 1 or no other features.


Build Feature Grid for Partial Dependence

Description

Returns grid values for a single feature column: factor levels (after droplevels), unique sorted values for character, or n_grid quantile-based numeric values.

Usage

pd_feature_grid(x, n_grid)

Arguments

x

('vector')
Feature column from the training data.

n_grid

('integer(1)')
Number of grid points for numeric features; ignored for factor/character.

Value

('atomic vector')
Grid values: character() for factor/character, numeric() otherwise.


Pack ICE Matrix into Long-Format data.table

Description

Converts an n_obs x length(grid) ICE matrix into a long-format data.table with one row per (observation, grid value) pair.

Usage

pd_pack_ice_result(ice, feature, grid)

Arguments

ice

('matrix')
ICE predictions; shape n_obs x length(grid).

feature

('character(1)')
Name of the focal feature; stored in the .feature column.

grid

('atomic vector')
Grid values used for this feature; stored in the .borders column.

Value

('data.table')
Columns: .id (observation index), .type ("ice"), .feature, .borders, .value (prediction).


Generate Predictions for New Data

Description

Calls predict_fun (or the default predict method) on newdata and extracts a numeric prediction vector via extract_numeric_prediction.

Usage

pd_predict(model, newdata, predict_fun = NULL)

Arguments

model

('any')
Fitted model.

newdata

('data.frame()' or 'data.table()')
New observations to predict.

predict_fun

('function()' or 'NULL')
function(model, data) returning predictions; NULL = default.

Value

('numeric()')
Numeric prediction vector of length nrow(newdata).


Pivot tabular effect data to wide numeric columns

Description

Uses data.table::dcast on data: rows indexed by id_cols (all columns except grid_col and value_col), columns by grid_col.

Usage

pivot_effect_to_wide(
  data,
  grid_col,
  value_col = ".value",
  drop_cols = c(".type", ".id"),
  mean_center = FALSE
)

Arguments

data

('data.frame')
Long-ish tabular effect results (ICE-style rows).

grid_col

('character(1)')
Column used as column axis after pivot (often feature grid or ".borders").

value_col

('character(1)')
Column holding curve values (typically ".value").

drop_cols

('character()')
Columns to drop from the wide table after pivot (metadata such as ".type", ".id").

mean_center

('logical(1)')
If TRUE, subtract the row mean from each row.

Value

('data.frame')
Wide numeric matrix-like frame (columns are grid cells).


Build per-feature ALE panels (mean curve only)

Description

Helper used by plot_tree_ale() to generate per-feature ALE mean panels (optionally with overlaid observation points).

Usage

plot_regional_ale(
  curves,
  color_ale = "lightcoral",
  target_feature_name,
  mean_center = TRUE,
  ymin = NULL,
  ymax = NULL,
  show_point = FALSE,
  point_values = NULL,
  x_limits = NULL
)

Arguments

curves

('list()')
Output of prepare_plot_data_ale for a node.

color_ale

('character(1)')
Color for ALE curves.

target_feature_name

('character(1)')
Target column name; used as the y-axis label (same convention as PD plots).

mean_center

('logical(1)')
Whether ALE curves are mean-centered; controls legend text ("Mean centered ALE" vs "ALE"), matching PD ICE/PDP labeling.

ymin, ymax

('numeric(1)' or 'NULL')
Y-axis limits.

show_point

('logical(1)')
Whether to add observation points.

point_values

('list()' or 'NULL')
Per-feature data.frames with x, y; used when show_point = TRUE.

x_limits

('list()' or 'NULL')
Per-feature x-axis: numeric c(xmin, xmax) or character (level order).

Value

('list()')
Named list of ggplot objects per feature.


Plot regional PD/ICE for one node.

Description

Plot regional PD/ICE for one node.

Usage

plot_regional_pd(
  prepared_data,
  origin_data,
  target_feature_name,
  node_idx,
  color_ice,
  color_pd,
  ymin,
  ymax,
  split_condition = NULL,
  show_point,
  mean_center
)

Arguments

prepared_data

('list()')
Prepared effect matrices per feature.

origin_data

('data.frame()')
Original data.

target_feature_name

('character(1)')
Target column.

node_idx

('integer(1)')
Node index.

color_ice, color_pd

('character(1)')
Colors.

ymin, ymax

('numeric(1)')
Y-axis limits.

split_condition

('character(1)' or 'NULL')
Split condition label.

show_point, mean_center

('logical(1)')
Plot options.

Value

('list()')
List of ggplot objects per feature.


Plot ALE curves for selected tree nodes

Description

External helper mirroring plot_tree_pd, used by AleStrategy$plot. Produces patchwork objects per node with ALE mean curves and optional observation points. Y-axis limits use global and node-specific cumulative ALE (d_l). When show_point = TRUE, the node subset response is merged into ylim so overlaid points are not clipped by coord_cartesian. x limits follow the global grid. Y-axis labels use target_feature_name, matching PD tree plots.

Usage

plot_tree_ale(
  tree,
  effect,
  data,
  target_feature_name,
  depth = NULL,
  node_id = NULL,
  features = NULL,
  color_ale = "lightgreen",
  show_plot = TRUE,
  show_point = TRUE,
  mean_center = TRUE,
  ...
)

Arguments

tree

('list()')
Depth-based list of Node objects.

effect

('list()')
Output of calculate_ale().

data

('data.frame()' or 'data.table()')
Data with features and target.

target_feature_name

('character(1)')
Target variable name.

depth

('integer()' or 'NULL')
Depth levels to render.

node_id

('integer()' or 'NULL')
Node IDs to render.

features

('character()' or 'NULL')
Feature subset.

color_ale

('character(1)')
Color for ALE curves.

show_plot, show_point, mean_center

('logical(1)')
Plot options.

...

Additional arguments passed to plotting helpers.

Value

('list()')
Nested list (depth -> node -> patchwork).


Plot PD/ICE tree by depth and node.

Description

Plot PD/ICE tree by depth and node.

Usage

plot_tree_pd(
  tree,
  effect,
  data,
  target_feature_name,
  color_ice = "lightblue",
  color_pd = "lightcoral",
  show_plot = TRUE,
  show_point = FALSE,
  mean_center = TRUE,
  depth = NULL,
  node_id = NULL,
  features = NULL
)

Arguments

tree

('list()')
Depth-based list of Node objects.

effect

(R6 or 'list()')
Effect object (e.g. FeatureEffect).

data

('data.frame()' or 'data.table()')
Data with features and target.

target_feature_name

('character(1)')
Target column name.

color_ice, color_pd

('character(1)')
Colors for ICE and PDP curves.

show_plot, show_point, mean_center

('logical(1)')
Plot options.

depth

('integer()' or 'NULL')
Depth levels to render.

node_id

('integer()' or 'NULL')
Node IDs to render.

features

('character()' or 'NULL')
Feature subset.

Value

('list()')
Nested list (depth -> node -> patchwork).


Visualize the Tree Structure

Description

Given tree (depth-list of Node objects): calls prepare_layout_data to build layout data; creates parent map; builds edge list; creates ggraph plot with nodes labeled by split info and edges representing tree hierarchy. Returns ggplot object.

Usage

plot_tree_structure(
  tree,
  label_wrap_width = 34L,
  node_spread_x = 1.55,
  node_spread_y = 1.12
)

Arguments

tree

('list()')
Depth-based list of Node objects.

label_wrap_width

('integer(1)' or 'NULL')
If not NULL, wrap each line of node labels to this many characters (see strwrap).

node_spread_x, node_spread_y

('numeric(1)')
Positive multipliers applied to the default "tree" layout coordinates to separate nodes.

Value

(ggplot)
Tree structure visualization.


Build layout data frame for tree structure plot

Description

Given tree (depth-list of Node objects): flattens to one row per node; extracts id, id_parent, split_feature, split_value, N, depth; builds label. Returns data frame for plot_tree_structure (ggraph).

Usage

prepare_layout_data(tree)

Arguments

tree

('list()')
Depth-based list of Node objects.

Value

('data.frame()')
Columns: id, node_id, id_parent, split_feature, split_value, label, depth, etc.


Prepare ALE Plot Data for One or More Nodes

Description

Given effect (from calculate_ale), idx (row indices or list of such), features, mean_center: subsets ALE rows by idx; calls mean_center_ale per feature for cumulative and optional centering. Returns named list of mean_effect data.tables (or nested list if idx is list).

Usage

prepare_plot_data_ale(
  effect,
  idx = NULL,
  features = names(effect),
  mean_center = TRUE
)

Arguments

effect

('list()')
List returned by calculate_ale().

idx

('integer()' or 'list()' or 'NULL')
Row indices (node subset); list of such vectors; or NULL for root.

features

('character()')
Features to include (default: all in effect).

mean_center

('logical(1)')
Whether to mean-center ALE curves.

Details

Rows are subset with effect[[feat]][row_id %in% idx] when idx is non-NULL.

mean_center_ale() builds plot grids from aggregated intervals: means sample-wise d_l within each (interval_index, x_left, x_right) group (delta_aggr), cumulates, then optionally subtracts a weighted scalar f_j0. Sample-wise d_l == 0 is mapped to NA before aggregation so exact zeros do not enter group means.

For categorical features, each row of mean_effect corresponds to one row of delta_aggr; x_grid uses as.character(delta_aggr$x_left), so the number of plotted points follows the number of distinct aggregated intervals after subsetting (not always one row per factor level). Factor x_grid still carries full levels(feat_val) for axis ordering.

Value

('list()')
Named list of mean_effect data.tables per feature; nested if idx is list.


Prepare ALE Data for Tree Splitting

Description

Given model, data, target_feature_name, n_intervals, and optional feature/split sets: validates features; converts character to factor and orders levels via order_categorical_levels; builds Z (data.table of split columns); calls calculate_ale for Y. Returns list Z, Y.

Usage

prepare_split_data_ale(
  model,
  data,
  target_feature_name,
  n_intervals,
  feature_set = NULL,
  split_feature = NULL,
  predict_fun = NULL,
  order_method = "raw",
  ale_engine = c("auto", "cpp", "r")
)

Arguments

model

('any')
Fitted model with predict interface.

data

('data.frame()' or 'data.table()')
Training data (features and target).

target_feature_name

('character(1)')
Name of the target variable.

n_intervals

('integer(1)')
Number of intervals for numeric ALE.

feature_set

('character()' or 'NULL')
Features to compute ALE for; NULL = all.

split_feature

('character()' or 'NULL')
Features for splitting; NULL = all.

predict_fun

('function()' or 'NULL')
function(model, data) returning predictions; NULL = default.

order_method

('character(1)')
Categorical level order: "mds", "pca", "random", or "raw".

ale_engine

('character(1)')
ALE engine: "auto", "cpp", or "r".

Details

Steps performed:

  1. Resolve feature_set and split_feature against feature columns (see GadgetTree/AleStrategy for target-column validation).

  2. For union(feature_set, split_feature), convert character columns to factor and order levels via order_categorical_levels (using droplevels internally).

  3. Build Z as data[split_feature] (data.table).

  4. Call calculate_ale(model, data, feature_set, ...) to get Y.

Stops with an error if any requested feature is missing from data.

Value

('list()')
Z: data.table of split features; Y: list of ALE effect data per feature.


Common preprocessing for ALE and PD split data.

Description

Resolves feature_set/split_feature, ensures factors, builds Z.

Usage

prepare_split_data_common(
  data,
  target_feature_name,
  feature_set,
  split_feature
)

Arguments

data

('data.frame()' or 'data.table()')
Data.

target_feature_name

('character(1)' or 'NULL')
Target column; NULL = all columns are features.

feature_set

('character()' or 'NULL')
Features; NULL = all.

split_feature

('character()' or 'NULL')
Split features; NULL = all.

Value

('list()')
data, Z, feature_set, split_feature.


Prepare PD Data for Tree Splitting

Description

Given effect, data, and optional feature/split sets: resolves features; converts character to factor; builds Z (split columns); calls mean_center_ice for Y and grid.

Usage

prepare_split_data_pd(
  effect,
  data,
  target_feature_name = NULL,
  feature_set = NULL,
  split_feature = NULL
)

Arguments

effect

(R6 or 'list()')
Effect object (e.g. FeatureEffect).

data

('data.frame()' or 'data.table()')
Training data.

target_feature_name

('character(1)' or 'NULL')
Target variable name; NULL = all columns are features.

feature_set

('character()' or 'NULL')
Features in effect; NULL = all non-target columns.

split_feature

('character()' or 'NULL')
Features for splitting; NULL = all.

Value

('list()')
Z: split-feature data.table; Y: mean-centered effects; grid: grid list.


Preprocess PD node data by depth.

Description

Preprocess PD node data by depth.

Usage

preprocess_node_data(tree, Y, grid_total, mean_center)

Arguments

tree

('list()')
Depth-based list of Node objects.

Y, grid_total

('list()')
Effect matrices and grid.

mean_center

('logical(1)')
Whether to mean-center.

Value

('list()')
Processed data per depth.


Resolve feature names against available columns.

Description

Resolve feature names against available columns.

Usage

resolve_split_features(requested, all_features, err_label)

Arguments

requested

('character()' or 'NULL')
Requested feature names; NULL = use all.

all_features

('character()')
Available feature names.

err_label

('character(1)')
Label for error message (e.g. "Features", "Split features").

Value

('character()')
Resolved feature names.


Find best ALE split across features.

Description

Find best ALE split across features.

Usage

search_best_split_ale(
  Z,
  effect,
  min_node_size = 1L,
  n_quantiles = NULL,
  active_effect_tol = active_effect_rel_tol(),
  categorical_split = c("ordered_prefix", "exhaustive"),
  max_exhaustive_levels = 12L
)

Arguments

Z

('data.frame()' or 'data.table()')
Split features.

effect

('list()')
ALE effect data per feature (from calculate_ale).

min_node_size

('integer(1)')
Minimum observations per node.

n_quantiles

('integer(1)' or 'NULL')
Quantiles for numeric split candidates.

active_effect_tol

('numeric(1)')
Relative threshold used to skip negligible effect components in this split search.

categorical_split

('character(1)')
Categorical split mode: "ordered_prefix" or "exhaustive".

max_exhaustive_levels

('integer(1)')
Maximum observed levels allowed for exhaustive categorical split search.

Value

('data.frame()')
Best split info with per-feature objective values.


Find best ALE split point for one feature.

Description

Find best ALE split point for one feature.

Usage

search_best_split_point_ale(
  z,
  effect,
  st_table,
  split_feat,
  is_categorical,
  n_quantiles = NULL,
  min_node_size = 1L,
  categorical_split = c("ordered_prefix", "exhaustive"),
  max_exhaustive_levels = 12L
)

Arguments

z

('numeric()' or 'factor()')
Split feature values.

effect

('list()')
ALE effect data (from calculate_ale).

st_table

('list()')
Precomputed interval statistics.

split_feat

('character(1)')
Name of split feature.

is_categorical

('logical(1)')
Whether z is categorical.

n_quantiles

('integer(1)' or 'NULL')
Quantiles for numeric features.

min_node_size

('integer(1)')
Minimum observations per child.

categorical_split

('character(1)')
Categorical split mode: "ordered_prefix" or "exhaustive".

max_exhaustive_levels

('integer(1)')
Maximum observed levels allowed for exhaustive categorical split search.

Value

('list()')
split_point, split_objective, objective_value_j, left_objective_value_j, right_objective_value_j, and split_levels.


Select depth indices to render based on tree, depth, and node_id.

Description

Select depth indices to render based on tree, depth, and node_id.

Usage

select_depths_to_render(tree, depth, node_id)

Arguments

tree

('list()')
Depth-based list of Node objects.

depth

('integer()' or 'NULL')
Depth levels to consider; NULL = all.

node_id

('integer()' or 'NULL')
Node IDs to render; NULL = all nodes at selected depths.

Value

('integer()')
Depth indices to render.


Subset columns from data.frame or data.table.

Description

Subset columns from data.frame or data.table.

Usage

take_cols(data, cols)

Arguments

data

('data.frame()' or 'data.table()')
Data.

cols

('character()')
Column names.

Value

('data.frame()' or 'data.table()')
Subset of columns.


Build path of split conditions from root to node

Description

Given node and tree (depth-list): walks parent chain via find_node_by_id; at each step builds condition string (e.g. "x <= 0.5") via choose_operator. Returns character vector of conditions (root to node).

Usage

track_split_condition(node, tree)

Arguments

node

('Node')
Node object with parent and depth.

tree

('list()')
Depth-based list of nodes (from convert_tree_to_list).

Value

('character()')
Conditions from root to node (e.g. "x <= 0.5").


Internal C++ helpers and package symbols

Description

Functions and symbols used internally by the package. Not intended for direct use.