Package {sltree}


Type: Package
Title: Structure Learning for Semiparametric/Latent Tree Models
Version: 0.1.1
Description: Learns the structure of Gaussian latent tree models (LTMs), discrete LTMs, parametric mixed LTMs, and semiparametric tree models using information distances and a bottom-up tree reconstruction algorithm. Gaussian models and parametric mixed models with binary and conditionally Gaussian variables use Pearson-correlation-based distances. Discrete models use determinant-based distances and require the same number of observed states across variables. Semiparametric models accommodate continuous, binary, and ordinal variables, with latent correlations estimated under a Gaussian copula model using Kendall's tau and bridge functions. Utilities are provided for data simulation, tree visualization and export, and topology comparison using the Robinson-Foulds distance. The semiparametric framework allowing observed internal nodes is described in Zhou et al. (2026) <doi:10.1016/j.artint.2026.104499>. Earlier structure-learning methods assuming that all observed variables are leaf nodes are described for discrete models in Wang et al. (2017) <doi:10.4310/SII.2017.v10.n4.a11> and for parametric mixed models in Zhou et al. (2020) https://jmlr.org/papers/v21/20-365.html.
License: GPL-3
Copyright: See the file inst/COPYRIGHTS.
Encoding: UTF-8
Collate: 'RcppExports.R' 'data_generation.R' 'information_distance.R' 'learn.R' 'ltree_accessors.R' 'ltree_export.R' 'ltree_plot.R' 'ltree_state.R' 'preset_models.R' 'sls_internal.R' 'sls.R' 'sltree-package.R' 'tree_structure.R'
Imports: utils, stats, methods, grDevices, graphics, igraph (≥ 1.2.5), mvtnorm, pcaPP, Rcpp
LinkingTo: Rcpp
Suggests: Matrix, pcalg, graph, visNetwork, testthat (≥ 3.0.0), knitr, rmarkdown
Depends: R (≥ 3.6.0)
NeedsCompilation: yes
Config/testthat/edition: 3
VignetteBuilder: knitr
Config/roxygen2/version: 8.1.1
Packaged: 2026-11-12 18:32:25 UTC; 13006
Author: Can Zhou [aut, cre], Shuai Wang [aut], Xiaofei Wang [aut], Jianhua Guo [aut], Key Program of the National Natural Science Foundation of China [fnd] (Grant No. 12431009), National Natural Science Foundation of China [fnd] (Grant No. 12171076, 12226003, 12601508), National Key Research and Development Program of China [fnd] (Grant No. 2020YFA0714100), Basic Research Program of Jiangsu [fnd] (Grant No. BK20230439), Alan Genz [ctb, cph] (TVPACK BVND), R Core Team [cph] (Brent_fmin), Mingze Huang [ctb, cph] (latentcor), Grace Yoon [ctb, cph] (latentcor), Christian Müller [ctb, cph] (latentcor), Irina Gaynanova [ctb, cph] (latentcor)
Maintainer: Can Zhou <zhouc@nau.edu.cn>
Repository: CRAN
Date/Publication: 2026-12-04 18:10:57 UTC

sltree: Structure Learning of Semiparametric/Latent Tree Models

Description

Learns the structure of Gaussian latent tree models (LTMs), discrete LTMs, parametric mixed LTMs, and semiparametric tree models using information distances and a bottom-up tree reconstruction algorithm. Gaussian models and parametric mixed models with binary and conditionally Gaussian variables use Pearson-correlation-based distances. Discrete models use determinant-based distances and require the same number of observed states across variables. Semiparametric models accommodate continuous, binary, and ordinal variables, with latent correlations estimated under a Gaussian copula model using Kendall's tau and bridge functions. Utilities are provided for data simulation, tree visualization and export, and topology comparison using the Robinson-Foulds distance. The semiparametric framework allowing observed internal nodes is described in Zhou et al. (2026). Earlier structure-learning methods assuming that all observed variables are leaf nodes are described for discrete models in Wang et al. (2017) and for parametric mixed models in Zhou et al. (2020).

Details

See sls, latent_correlation, learn_sltree.

Author(s)

Maintainer: Can Zhou zhouc@nau.edu.cn

Authors:

Other contributors:

References

Zhou, C., Li, N., Wang, S., Wang, X. and Guo, J. (2026). Learning semi-parametric tree models from mixed data. Artificial Intelligence, 353, 104499. doi:10.1016/j.artint.2026.104499

Zhou, C., Wang, X. and Guo, J. (2020). Learning Mixed Latent Tree Models. Journal of Machine Learning Research, 21(249), 1–35. https://jmlr.org/papers/v21/20-365.html

Wang, X., Guo, J., Hao, L. and Zhang, N. L. (2017). Spectral methods for learning discrete latent tree models. Statistics and Its Interface, 10(4), 677–698. doi:10.4310/SII.2017.v10.n4.a11


Extract Edges and Vertices from a Latent Tree

Description

edges_from_ltree extracts the edges from a latent tree structure ('ltree' object). vertices_from_ltree extracts the vertices from a latent tree. The vertices are either node names or node IDs, depending on the 'use_node_names' parameter.

Usage

edges_from_ltree(tree, use_node_names = FALSE)

vertices_from_ltree(tree, use_node_names = FALSE)

Arguments

tree

A 'ltree' object representing a latent tree structure.

use_node_names

Logical; return node names instead of node IDs.

Value

edges_from_ltree returns a data frame with two columns: "nodes" and "parent", representing the edges. vertices_from_ltree returns a character vector containing the vertices (nodes) of the latent tree.


Randomly generate a mixed latent tree structure

Description

Generate a tree by Poisson branching and optionally mark nodes of degree at least 3 as latent.

Usage

generate_latent_tree(
  variable_type = "Gaussian",
  latent_probability = 0.5,
  branching_rates = c(2, 2, 1, 0.5, 0.05)
)

Arguments

variable_type

Observed variable type: "Gaussian", "continuous", "binary", "ordinal", or "discrete"; use "mixed" to sample discrete, ordinal, or binary type independently for each observed node.

latent_probability

Probability that a node with degree >= 3 is set as a latent node.

branching_rates

Non-negative, finite Poisson branching means for successive levels. The last value is reused for deeper levels and must be less than 1. Generation stops with an error before exceeding 100,000 nodes.

Value

A three-column data frame nodes/type/parent ("" for the root), as used by simulate_ltree_data.

See Also

simulate_ltree_data, latent_tree_models


Infer Variable Types in a Dataset

Description

Classifies each column as binary, continuous or ordinal from its values.

Usage

infer_variable_types(x)

Arguments

x

A data frame or matrix where each column represents a variable. Must not contain NA values or non-numeric data. Binary variables should only contain 0 or 1. Ordinal variables should only contain consecutive integers starting from 0 (i.e., 0, 1, 2, ...).

Details

Value

A character vector of types for all variables with possible values: "binary", "continuous", or "ordinal".

Examples

data <- data.frame(
  binary_var = c(0, 1, 0, 1),
  ordinal_var = c(0, 1, 2, 1),
  continuous_var = c(1.5, 2.3, 4.1, 3.7)
)
infer_variable_types(data)


Computing information distance.

Description

information_distance returns a numeric information-distance matrix. The input of information_distance is a n by p numeric matrix or data frame, which is a sample of latent tree models (LTM). Where n is the sample size and p is the number of observed variables. The column names of the input will be assigned to column and row names of the result (information distance matrix).

Usage

information_distance(
  data,
  type = c("semiparametric", "gaussian", "discrete", "mixed", "stm"),
  use_near_pd = FALSE,
  maxit = 10000
)

Arguments

data

a n by p numeric matrix or data frame, with one numeric vector per data-frame column and no missing or infinite values.

type

A character scalar selecting one of four model classes (matched by match.arg): "semiparametric" (default; alias "stm") estimates latent Gaussian-copula correlation for continuous/binary/ordinal data via latent_correlation; "gaussian" and "mixed" use Pearson correlation for Gaussian and parametric binary/conditional-Gaussian models, respectively; "discrete" uses the absolute-determinant distance and requires the same number of observed states in every column.

use_near_pd

Logical; for correlation-based distances, whether to project the estimated correlation matrix onto the nearest positive-definite correlation matrix before computing the distance. Requires Matrix.

maxit

Maximum number of iterations passed to nearPD when use_near_pd = TRUE.

Details

The information distance is additive along path on LTM. Let x,y be two nodes (random variables) in LTM. For Gaussian and parametric mixed LTM (type = "gaussian" or type = "mixed"), the information distance d_{xy} between x and y is

d_{xy} = -log(|\rho_{xy}|),

where \rho_{xy} is the Pearson correlation coefficient of x and y. For discrete LTM (type = "discrete"), the information distance d_{xy} is

d_{xy} = -log(\frac{|\det(P_{xy})|} {\sqrt{\det(P_{xx})\det(P_{yy})}}),

where P_{xy} = (P(x=a,y=b)) is the joint probability matrix and P_{xx} and P_{yy} are diagonal marginal probability matrices. All observed variables must have the same number of observed states (at least two), so that every joint probability matrix is square. State counts are determined from distinct values present in each column. Singular joint matrices yield a distance capped at -log(.Machine$double.xmin). For semi-parametric tree models (type = "semiparametric", the default; alias "stm"), the information distance d_{xy} is

d_{xy} = -log(|\rho_{xy}|),

where \rho_{xy} is the latent Pearson correlation coefficient of x and y. The coefficient \rho_{xy} is estimated with a bridge function F(\cdot) that connects the latent correlation to the population Kendall's \tau (see latent_correlation).

Value

A numeric p by p information-distance matrix; its row and column names are taken from the columns of data.

Examples

x <- data.frame(continuous = c(-1.8, -1.2, -0.4, 0.2, 0.8, 1.5),
                binary = c(0, 0, 0, 1, 1, 1),
                ordinal = c(0, 0, 1, 1, 2, 2))
information_distance(x, type = "semiparametric")

categorical <- data.frame(a = c(2, 1, 0, 2, 1, 0),
                          b = c(2, 2, 1, 1, 0, 0))
information_distance(categorical, type = "discrete")

Is this object an ltree latent tree?

Description

Checks whether an object has class ltree.

Usage

is_ltree(tree)

Arguments

tree

An R object.

Value

TRUE or FALSE.


Latent correlation matrix for mixed data

Description

Estimates the latent Pearson correlations of continuous, binary and ordinal variables under a Gaussian copula model.

Usage

latent_correlation(x, variable_types)

Arguments

x

A data frame or matrix where each column represents a variable. Must not contain NA values. Binary variables should contain only 0 and 1. Ordinal variables should contain consecutive integers starting from 0.

variable_types

A character vector specifying the type of each variable in x. Must contain values "continuous", "binary", or "ordinal".

Details

Each ordinal variable is split into binary indicators, one per cut point. Kendall's tau-a is computed for all pairs and mapped to the latent correlation by inverting the bridge functions of Fan et al. (2017). For ordinal variables the estimates are averaged over cut points.

Value

A symmetric latent Pearson-correlation matrix with one row and column per variable in x.

References

Fan, J., Liu, H., Ning, Y. and Zou, H. (2017). High dimensional semiparametric latent graphical model for mixed data. Journal of the Royal Statistical Society: Series B, 79(2), 405–421. doi:10.1111/rssb.12168

Huang, M., M\"uller, C. L. and Gaynanova, I. (2021). latentcor: An R package for estimating latent correlations from mixed data types. Journal of Open Source Software, 6(65), 3634. doi:10.21105/joss.03634

Examples

set.seed(1)
data <- data.frame(
  continuous_var = rnorm(100),
  binary_var = rep(0:1, length.out = 100),
  ordinal_var = rep(0:3, length.out = 100)
)
variable_types <- c("continuous", "binary", "ordinal")
latent_correlation(data, variable_types)


Preset latent tree models

Description

Six fixed latent tree structures. Each tree is a three-column data frame nodes/type/parent ("" is the root).

Usage

latent_tree_models(model_id = NULL)

Arguments

model_id

An integer from 1 to 6, or NULL to return all models.

Value

A three-column data frame, or a list named model1 through model6 when model_id = NULL.

See Also

simulate_ltree_data, generate_latent_tree

Examples

m1 <- latent_tree_models(1)
all_models <- latent_tree_models()

Learn a latent tree under one of four statistical models

Description

Estimates the information distance for the chosen model and recovers the tree with sls. Semi-parametric, Gaussian and discrete trees may have observed internal nodes; in the parametric mixed model every observed node is a leaf.

Usage

learn_sltree(
  x,
  tau1 = 3,
  tau2 = 5,
  allow_observed_internal = NULL,
  epsilon_init = 0.1,
  step_size = 0.1,
  relation_tolerance = 0.1,
  use_near_pd = NULL,
  maxit = 10000,
  return_intermediate = FALSE,
  model = c("stm", "gaussian", "discrete", "mixed", "semiparametric")
)

Arguments

x

Numeric data frame or matrix with at least three columns and two rows; it must contain no NA, infinite, or constant columns.

tau1, tau2

distance thresholds for the SLS algorithm.

allow_observed_internal

Whether observed variables may be internal nodes. NULL (default) uses TRUE for "stm", "gaussian" and "discrete", and FALSE for "mixed". A value that conflicts with the model gives a warning.

epsilon_init, step_size, relation_tolerance

SLS tolerance-search parameters.

use_near_pd

Whether to project the correlation matrix with Matrix::nearPD. NULL (default) uses TRUE for "stm" and FALSE for the other models. Requires Matrix.

maxit

maximum number of iterations for Matrix::nearPD.

return_intermediate

logical; if TRUE, also return the estimated correlation and distance matrices, variable types, settings and timings.

model

One of

  • "stm" (default): semi-parametric tree model for continuous, binary and ordinal data, with latent correlations estimated from Kendall's tau (Zhou et al., 2026).

  • "gaussian": Gaussian latent tree with Pearson correlations; all columns continuous.

  • "discrete": discrete latent tree with the determinant-based distance; all columns coded 0, 1, ... with the same number of states.

  • "mixed": parametric mixed latent tree of Zhou et al. (2020) for binary and conditionally Gaussian variables; ordinal variables are not supported.

  • "semiparametric": same as "stm".

Value

If return_intermediate = FALSE, an ltree. Otherwise a list with tree, correlation, distance, variable_types, model, allow_observed_internal, use_near_pd, and run_time.

See Also

information_distance, sls, latent_correlation, robinson_foulds_distance

Examples

set.seed(1234)
n <- 400
h <- rnorm(n)
gaussian_x <- as.data.frame(replicate(4, 0.8 * h + 0.6 * rnorm(n)))
names(gaussian_x) <- paste0("V", 1:4)
stm_x <- data.frame(
  V1 = exp(gaussian_x$V1),
  V2 = gaussian_x$V2^3,
  V3 = as.integer(gaussian_x$V3 > 0),
  V4 = findInterval(gaussian_x$V4, c(-0.5, 0.5))
)
est_stm <- learn_sltree(stm_x, model = "stm", use_near_pd = FALSE)

est_gaussian <- learn_sltree(gaussian_x, model = "gaussian")

h_binary <- rbinom(n, 1, 0.5)
discrete_x <- as.data.frame(replicate(4, rbinom(n, 1, 0.1 + 0.8 * h_binary)))
names(discrete_x) <- paste0("V", 1:4)
est_discrete <- learn_sltree(discrete_x, model = "discrete")

binary_and_gaussian_x <- data.frame(
  V1 = rnorm(n, mean = 2 * h_binary - 1, sd = 0.6),
  V2 = rnorm(n, mean = 2 * h_binary - 1, sd = 0.6),
  V3 = discrete_x$V3,
  V4 = discrete_x$V4
)
est_mixed <- learn_sltree(binary_and_gaussian_x, model = "mixed")
edges_from_ltree(est_stm)

Create a Latent Tree Object from Edge Set

Description

Creates an ltree object from the edge set of a directed latent tree.

Usage

ltree_from_edge(edge, node_types = NULL)

Arguments

edge

A two-column matrix or data frame, representing the edge set of a directed latent tree structure. The first column contains the node labels (with observed nodes labeled as "V1", "V2", ..., and latent nodes as "H1", "H2", ...). The second column contains the parent nodes, with the root node having an empty string as its parent.

node_types

A character vector of length equal to the number of nodes, indicating node types. If named, names must be exactly the node identifiers and values are reordered to match edge; otherwise values follow row order. Identifiers beginning with "H" must have latent type.

Value

A list of class ltree with components

observed_nodes A character vector containing all observed nodes of the latent tree structure.
latent_nodes A character vector containing all latent nodes of the latent tree structure.
internal_nodes A character vector containing all internal nodes of the latent tree structure.
node_metadata A data frame with 4 columns, where: The first column is a character vector containing all nodes of the latent tree model; The second column records "latent" for latent nodes and "observed_<type>" for observed nodes, such as "observed_continuous", "observed_binary", or "observed_ordinal"; The third column is an integer vector indicating the degree of each node; The fourth column is an integer vector indicating the number of observed nodes among the child nodes of each node.
parent_by_node A character vector indicating the parent node of each node. This is a named vector, where the names attribute is all nodes. "" means that the node has no parent node.
children_by_node A named list in which each element is a set of child nodes of this node.
observed_descendants A named list in which each element is a set of observed descendant nodes of this node.
active_nodes A character vector indicating the active set in the current step of structure learning algorithm, that is, the nodes whose structure need to be explored in the current step.
discovered_nodes A character vector containing the nodes whose structure has been found.
distance A placeholder matrix for the observed nodes, with zero diagonal and all off-diagonal entries equal to one. These values are not information distances estimated from the edge list.
node_types A named character vector with node identifiers as names. Types are "continuous", "Gaussian", "binary", "ordinal", "count", "categorical", "nominal", "discrete", or "latent".
node_names A named character vector indicate nodes name, where its names attribute vector is nodes labels.

The components active_nodes, discovered_nodes, and distance are used in structure learning algorithm.

Examples

edges <- data.frame(
  node = c("V1", "V2", "V3", "V4", "V5", "H1", "H2"),
  parent = c("H1", "V1", "H1", "H2", "H2", "", "H1"),
  stringsAsFactors = FALSE
)
node_types <- rep(c("ordinal", "continuous", "latent"), c(2, 3, 2))
tree <- ltree_from_edge(edges, node_types)

Plot a latent tree

Description

Draws a latent tree on the current graphics device. Latent nodes are circles and observed nodes are boxes coloured by type (continuous green, discrete amber). A legend of node types is drawn below the tree.

Usage

## S3 method for class 'ltree'
plot(
  x,
  vertex.size = 24,
  edge.width = 2,
  vertex.label.cex = 0.9,
  layout = NULL,
  direction = c("LR", "RL", "UD", "DU"),
  vertex.color = NULL,
  vertex.frame.color = NULL,
  legend = TRUE,
  edge.args = list(),
  vertex.args = list(),
  label.args = list(),
  legend.args = list(),
  par.args = list(),
  ...
)

Arguments

x

An ltree object.

vertex.size, edge.width, vertex.label.cex

Vertex size, edge width and label size. Large trees are scaled down together with their labels, so set label size with vertex.label.cex rather than label.args.

layout

Optional two-column matrix of vertex coordinates. By default nodes are placed by a tree layout that avoids overlaps.

direction

Direction of the default tree layout: "LR" (left to right, default), "RL", "UD" (top down), or "DU". Ignored when layout is supplied.

vertex.color, vertex.frame.color

Fill and border colours of the vertices, given as one colour for all vertices, one colour per vertex (in the order of vertices_from_ltree(x)), a vector named by node name (x$node_names) to recolour selected vertices, or a vector named by node type ("latent", "continuous", "discrete") to change the colour of a whole type. The legend follows single-colour and per-type settings.

legend

Logical; whether to draw the node-type legend. Default TRUE.

edge.args

Named list of extra arguments for segments, which draws the edges (e.g. list(lty = 2, col = "black")).

vertex.args

Named list of extra arguments for polygon, which draws every vertex shape (e.g. list(lwd = 2)).

label.args

Named list of extra arguments for text, which draws the vertex labels (e.g. list(font = 2, family = "serif")).

legend.args

Named list of extra arguments for legend (e.g. list(x = "topright", title = "Node type")). By default the legend is a single row centred below the tree.

par.args

Named list of graphical parameters set with par while drawing and restored afterwards (e.g. list(bg = "white", mar = c(1, 1, 3, 1))).

...

Further arguments passed to title, such as main, sub, xlab, ylab, cex.main, or col.main. Margins are enlarged automatically for main, sub, xlab, and ylab.

Details

Argument names follow igraph (vertex.*, edge.*) and base graphics (main, xlab, col.main, ...). Other arguments of the underlying graphics functions go in the *.args lists, which replace the defaults; a NULL entry removes a default.

Value

x, invisibly.

Examples

tree <- view_ltree(1, type = "summary")
plot(tree)
plot(tree, main = "Preset tree 1", direction = "UD", legend = FALSE)
plot(tree, vertex.color = c(latent = "grey60"), vertex.frame.color = "black")
plot(tree, edge.args = list(lty = 2),
     legend.args = list(x = "topright", title = "Node type"))


Print a latent tree

Description

Prints the nodes and edges of an ltree object.

Usage

## S3 method for class 'ltree'
print(x, ...)

Arguments

x

An ltree object.

...

Ignored.

Value

x, invisibly.


Compute Robinson-Foulds (rf) Distance Between Two Latent Trees

Description

robinson_foulds_distance computes the Robinson-Foulds distance between two undirected latent tree structures. The rf distance measures the topological difference between trees. A distance of 0 indicates identical tree structures (ignoring root position and hidden node names).

Usage

robinson_foulds_distance(reference_tree, estimated_tree)

Arguments

reference_tree

An 'ltree' object representing the reference tree. Must include 'observed_nodes', 'internal_nodes', and 'observed_descendants'.

estimated_tree

An 'ltree' object representing the estimated tree. Must include 'observed_nodes', 'internal_nodes', and 'observed_descendants'.

Details

This function compares two trees based on their topologies. The names of latent nodes and the root node do not affect the rf distance.

Value

A non-negative numeric value giving the RF distance.

See Also

ltree_from_edge for constructing latent tree structures.


Save a latent tree to HTML, EPS and/or PNG

Description

save_ltree writes an interactive HTML file with visNetwork and EPS and PNG images with plot.ltree.

Usage

save_ltree(
  tree,
  file = "tree",
  html = TRUE,
  eps = TRUE,
  png = TRUE,
  width = 12,
  height = 7,
  plot_args = list(),
  png_args = list(),
  eps_args = list(),
  html_args = list(),
  ...
)

Arguments

tree

A ltree object, or a single integer from 1 to 6 selecting a tree from latent_tree_models.

file

Output path, preferably without an extension. By default "<file>.png", "<file>.eps", and "<file>.html" are all written. A trailing .png, .eps, or .html is removed before the three output names are constructed.

html, eps, png

Logical; which formats to write. All three default to TRUE. Set a format to FALSE to suppress it.

width, height

EPS/PNG size in inches (PNG is rendered at 150 dpi unless png_args sets res).

plot_args

Named list of extra arguments forwarded to plot.ltree for the EPS and PNG images (e.g. list(main = "True tree", direction = "UD")).

png_args

Named list of extra arguments for png (e.g. list(res = 300, bg = "white")).

eps_args

Named list of extra arguments for postscript (e.g. list(family = "serif")).

html_args

Named list of extra arguments for visNetwork::visSave (e.g. list(selfcontained = FALSE), which also avoids the need for pandoc).

...

Extra arguments forwarded to the interactive visNetwork viewer for the HTML; see the interactive options in view_ltree (e.g. direction, legend).

Value

Invisibly, a named character vector of the files written.

See Also

plot.ltree, view_ltree

Examples

model <- latent_tree_models(1)
true_tree <- ltree_from_edge(model[, -2], setNames(model[, 2], model[, 1]))
out_dir <- tempfile("sltree-example-")
dir.create(out_dir)

out_png_only <- file.path(out_dir, "png_only")
save_ltree(true_tree, out_png_only, html = FALSE, eps = FALSE)
out_print <- file.path(out_dir, "print")
save_ltree(true_tree, out_print, html = FALSE, png_args = list(res = 300))
if(requireNamespace("visNetwork", quietly = TRUE)) {
  out_preset1 <- file.path(out_dir, "preset1")
  save_ltree(1, out_preset1, html_args = list(selfcontained = FALSE))
  out_titled <- file.path(out_dir, "titled")
  save_ltree(true_tree, out_titled, plot_args = list(main = "True tree"),
             html_args = list(selfcontained = FALSE))
}

# Clean up the files and directories created by this example
unlink(out_dir, recursive = TRUE)

Generate mixed observed data from a given latent tree

Description

Assign edge correlations, generate latent Gaussian data along the tree, and transform observed variables according to their declared types.

Usage

simulate_ltree_data(n, model, rho_lower = 0.2, rho_upper = 0.8)

Arguments

n

Observed sample size (number of rows), an integer of at least 2.

model

Valid rooted latent tree model (three-column data frame, see generate_latent_tree or latent_tree_models). Node identifiers must be unique; latent nodes use type "latent_Gaussian".

rho_lower, rho_upper

Bounds of the uniform distribution for edge correlations.

Value

A list with data, edge_correlations, and gaussian_correlation.

See Also

generate_latent_tree, learn_sltree


Structure learning for semi-parametric latent trees

Description

Input all information distances between the observed variables, sls outputs a latent tree structure, where leaf nodes are observed variables and latent nodes are latent or observed variables. The result has one root, leaf degree 1, and latent-node degree at least 3. The root has an empty parent identifier.

Usage

sls(
  distance,
  allow_observed_internal = TRUE,
  epsilon_init = 0.1,
  epsilon_max = max(distance),
  tau1 = 3,
  tau2 = 5,
  step_size = 0.1,
  relation_tolerance = 0.1,
  node_types = NULL,
  node_names = NULL
)

Arguments

distance

A finite, symmetric, non-negative numeric matrix with a zero diagonal and at least three rows/columns.

allow_observed_internal

A logical scalar indicates whether the observed variables can be internal nodes. The default is TRUE.

epsilon_init, epsilon_max, step_size

Finite numeric scalars. Thresholds must be non-negative and step_size must be strictly positive. Search grids requiring more than one million steps are rejected.

tau1

A numeric scalar. tau1 is the upper bound on the information distance between sibling pair. If the information distance between two nodes is greater than tau1, they are considered to be not a sibling pair, and the judgment step is skipped to save time.

tau2

A numeric scalar. The greater the information distance, the greater the error. All information distances greater than tau2 are considered unreliable. But tau2 should not be too small, otherwise it will result in too little information available.

relation_tolerance

A numeric scalar. The threshold for judging whether the differences of information distances are different.

node_types

An optional character vector of node display types. Recognized continuous, Gaussian, and discrete-type labels are preserved; unrecognized values are treated as "continuous".

node_names

A character vector with one display name per node.

Details

The SLS algorithm is a bottom-up structure learning algorithm based on an additive information distance. The SLS algorithm determines the basic sibling pair by using a prescribed threshold (i.e. argument epsilon). For fixed values of the thresholds epsilon and tau2, the algorithm may not produce a complete tree. To obtain a complete tree structure, sls starts the value of the threshold epsilon from epsilon_init. Then increase epsilon (if epsilon is less than epsilon_max) with the step size step_size until the SLS algorithm obtains a tree. If no tree is obtained for values up to epsilon_max, sls returns a latent class model.

Let V be the set of observed nodes. For u,v \in V, let d_{uv} be the information distance between u and v. Let \Phi_{uvw} = d_{uw} - d_{vw} be the difference of information distance. Particularly, if the difference

|\Phi_{uvw} - \Phi_{uvz}| < epsilon

for w,z \in V \ {u,v}, we judge that {u,v} is a sibling pair.

Since a longer distance estimate is less accurate for a given number of samples, not all estimated distances are reliable for structure learning. The algorithm considers possible sibling pairs {u,v} whose estimated distances d_{uv}, d_{uw}, d_{vw} are controlled by two thresholds tau1, tau2. In particular, for each pair of nodes {u,v} satisfied d_{uv} < tau1, the estimated difference \Phi_{uvw} was computed only for node

w in K_{uv} = {w \in V \ {u,v} | max(d_{uw}, d_{vw}) < tau2}

. Furthermore, if the difference

|\Phi_{uvw} - \Phi_{uvz}| < epsilon

for any w,z \in K_{uv} and d_{uv} < tau1, we consider {u,v} to be a sibling pair.

Value

sls returns a ltree object containing the following components: observed_nodes, latent_nodes, internal_nodes, node_metadata, parent_by_node, children_by_node, observed_descendants, active_nodes, discovered_nodes, distance, node_types, and node_names. See ltree_from_edge for more details about tree structure.

See Also

ltree_from_edge for more details about tree structure. information_distance for getting information distance.

Examples


if (requireNamespace("pcalg", quietly = TRUE) &&
    requireNamespace("graph", quietly = TRUE) &&
    requireNamespace("Matrix", quietly = TRUE)) {
  set.seed(1)

  model <- latent_tree_models(4)
  data <- simulate_ltree_data(n = 5e4, model = model)
  x <- data$data

  variable_types <- infer_variable_types(x)
  distance <- information_distance(x, type = "semiparametric",
                                   use_near_pd = TRUE)

  est_tree <- sls(distance, tau1 = 3, tau2 = 5,
                  node_types = variable_types, node_names = colnames(x))
  edges_hat <- edges_from_ltree(est_tree)

  view_ltree(est_tree, "plot")
  if (requireNamespace("visNetwork", quietly = TRUE)) {
    widget <- view_ltree(est_tree, "interactive")
    if (interactive()) {
      print(widget)
    }
  }

  true_tree <- ltree_from_edge(model[, -2], setNames(model[, 2], model[, 1]))
  robinson_foulds_distance(true_tree, est_tree)
}


View a latent tree

Description

Shows an ltree object or one of the six preset trees as an interactive HTML widget, a static plot, or a printed summary.

Usage

view_ltree(tree, type = c("interactive", "plot", "summary"), ...)

Arguments

tree

An ltree object, or a single integer from 1 to 6 selecting a tree from latent_tree_models.

type

Display type: "interactive" (default) returns the interactive visNetwork widget, "plot" draws a static image, and "summary" prints the tree structure. When type is not given and visNetwork is not installed, a static plot is drawn instead, with a message.

...

Display options: see the section Interactive options for type = "interactive", and plot.ltree for type = "plot". When the default falls back to a static plot, only the options shared by both views (direction, legend, vertex.color, vertex.frame.color, main, and sub) are passed on.

Value

For the interactive view, a visNetwork htmlwidget, which is displayed when printed. Otherwise, the displayed ltree object invisibly. A preset number is converted to an ltree before display.

Interactive options

direction

"UD" (top down, default), "DU", "LR", or "RL".

legend, legend.args

Whether to show the node-type legend (default TRUE), and a named list of extra arguments for visNetwork::visLegend (e.g. list(position = "left")).

vertex.color, vertex.frame.color

Fill and border colours, in the same forms as for plot.ltree.

vertex.args, edge.args

Named lists of extra arguments for visNetwork::visNodes and visNetwork::visEdges (e.g. list(font = list(size = 20)) or list(width = 3, color = list(color = "black"))). Nested lists are merged with the defaults.

layout

"tree" (default; fixed Reingold-Tilford coordinates) or "hierarchical" (visNetwork's own layout).

edge_style

"curved" (default) or "straight".

level_sep, node_spacing, tree_spacing

Spacing in pixels between depths, between siblings, and between subtrees ("hierarchical" only). Defaults 150, 130, and 60.

height, width

Widget size; defaults "97vh" and "100%".

other arguments

Passed to visNetwork::visNetwork, e.g. main, submain, footer, background.

See Also

save_ltree, learn_sltree, latent_tree_models

Examples

if(requireNamespace("visNetwork", quietly = TRUE)) {
  widget <- view_ltree(1, type = "interactive")
  if (interactive()) {
    print(widget)
  }

  widget2 <- view_ltree(1, direction = "LR",
                        vertex.args = list(font = list(size = 20)))
  if (interactive()) {
    print(widget2)
  }
}
view_ltree(1, "plot")
view_ltree(1, "plot", direction = "UD", main = "Preset tree 1")
view_ltree(1, "summary")