| Title: | Simulation and Analysis for Temporal Network Analysis |
|---|---|
| Description: | Simulation tools for temporal network analysis (TNA) research. Generates synthetic datasets with known ground-truth parameters for testing and validating statistical methods: Markov chain sequences, latent profiles, latent classes, regression, factor analysis, and sequence cluster structures. All simulation functions return list(data, params) for JSON-serializable access to ground-truth parameters. |
| Authors: | Mohammed Saqr [aut, cre] |
| Maintainer: | Mohammed Saqr <[email protected]> |
| License: | MIT + file LICENSE |
| Version: | 0.4.1 |
| Built: | 2026-10-08 22:22:20 UTC |
| Source: | https://github.com/mohsaqr/Saqrlab |
Apply a function to a list of TNA models or datasets, with optional parallel processing.
batch_apply( object_list, fun, parallel = FALSE, cores = NULL, progress = TRUE, simplify = FALSE, ... )batch_apply( object_list, fun, parallel = FALSE, cores = NULL, progress = TRUE, simplify = FALSE, ... )
object_list |
A list of TNA model objects or data frames. |
fun |
A function to apply to each element. |
parallel |
Logical. Whether to use parallel processing. Default: FALSE. |
cores |
Integer or NULL. Number of cores for parallel processing. Default: NULL. |
progress |
Logical. Whether to show progress messages. Default: TRUE. |
simplify |
Logical. Whether to simplify results if possible. Default: FALSE. |
... |
Additional arguments passed to |
This is a general-purpose function for batch operations on model lists. It handles errors gracefully, returning NULL for failed operations.
A list of results from applying fun to each element.
If simplify = TRUE and results are atomic, returns a simplified vector.
batch_fit_models for fitting multiple models.
## Not run: # Extract transition matrices from multiple models trans_mats <- batch_apply(models, extract_transition_matrix) # Compare each model to a reference ref_model <- models[[1]] comparisons <- batch_apply( models[-1], function(m) compare_networks(ref_model, m)$metrics$correlation ) # Extract centralities with simplification centralities <- batch_apply( models, function(m) tna::centralities(m), simplify = FALSE ) ## End(Not run)## Not run: # Extract transition matrices from multiple models trans_mats <- batch_apply(models, extract_transition_matrix) # Compare each model to a reference ref_model <- models[[1]] comparisons <- batch_apply( models[-1], function(m) compare_networks(ref_model, m)$metrics$correlation ) # Extract centralities with simplification centralities <- batch_apply( models, function(m) tna::centralities(m), simplify = FALSE ) ## End(Not run)
Fit TNA models to multiple datasets at once, with optional parallel processing.
batch_fit_models( data_list, model_type = c("tna", "ftna", "ctna", "atna"), parallel = FALSE, cores = NULL, progress = TRUE, ... )batch_fit_models( data_list, model_type = c("tna", "ftna", "ctna", "atna"), parallel = FALSE, cores = NULL, progress = TRUE, ... )
data_list |
A list of data frames, each containing sequence data. |
model_type |
Character. Type of model to fit: "tna", "ftna", "ctna", or "atna". Default: "tna". |
parallel |
Logical. Whether to use parallel processing. Default: FALSE. |
cores |
Integer or NULL. Number of cores to use for parallel processing.
If NULL, uses |
progress |
Logical. Whether to show progress messages. Default: TRUE. |
... |
Additional arguments passed to the model fitting function. |
This function provides a convenient way to fit TNA models to many datasets, such as when running simulations or analyzing multiple groups.
For parallel processing on Windows, set up a parallel backend first using
the future package.
A list of fitted model objects, with the same names/indices as
data_list. Failed fits are returned as NULL with a warning.
fit_network_model for fitting a single model,
batch_apply for applying functions to model lists.
## Not run: # Generate multiple datasets datasets <- lapply(1:10, function(i) { simulate_sequences(trans_mat, init_probs, max_seq_length = 20, num_rows = 100) }) # Fit models in sequence models <- batch_fit_models(datasets, model_type = "tna") # Fit models in parallel models <- batch_fit_models(datasets, model_type = "tna", parallel = TRUE, cores = 4) # Check results sapply(models, function(m) if (!is.null(m)) "OK" else "Failed") ## End(Not run)## Not run: # Generate multiple datasets datasets <- lapply(1:10, function(i) { simulate_sequences(trans_mat, init_probs, max_seq_length = 20, num_rows = 100) }) # Fit models in sequence models <- batch_fit_models(datasets, model_type = "tna") # Fit models in parallel models <- batch_fit_models(datasets, model_type = "tna", parallel = TRUE, cores = 4) # Check results sapply(models, function(m) if (!is.null(m)) "OK" else "Failed") ## End(Not run)
Compare centrality measures between two TNA networks using correlation or rank-based methods.
compare_centralities( model1, model2, measures = c("OutStrength", "InStrength", "Betweenness"), method = c("both", "correlation", "rank") )compare_centralities( model1, model2, measures = c("OutStrength", "InStrength", "Betweenness"), method = c("both", "correlation", "rank") )
model1 |
A TNA model object (the reference/original model). |
model2 |
A TNA model object (the comparison/simulated model). |
measures |
Character vector. Centrality measures to compare. Options: "OutStrength", "InStrength", "Betweenness", "Closeness", or "all". Default: c("OutStrength", "InStrength", "Betweenness"). |
method |
Character. Comparison method: "correlation" (Pearson), "rank" (Spearman), or "both". Default: "both". |
Centrality measures are extracted from the TNA model objects using
tna::centralities(). The function compares how well the centrality
profiles are preserved between the original and simulated/comparison model.
A list containing:
correlations: Named list of correlation values by measure.
centrality_comparison: Data frame with centrality values for each state.
summary: Character summary of the comparison.
compare_networks() for full network comparison.
## Not run: # Compare centrality profiles between models comparison <- compare_centralities(model_original, model_simulated) print(comparison$correlations) ## End(Not run)## Not run: # Compare centrality profiles between models comparison <- compare_centralities(model_original, model_simulated) print(comparison$correlations) ## End(Not run)
Calculate metrics for how well edges from an original network are recovered in a simulated/comparison network.
compare_edge_recovery( original, simulated, threshold = 0.01, return_edges = FALSE ) calculate_edge_recovery(...)compare_edge_recovery( original, simulated, threshold = 0.01, return_edges = FALSE ) calculate_edge_recovery(...)
original |
A TNA model object (the original/ground truth model). |
simulated |
A TNA model object (the simulated/recovered model). |
threshold |
Numeric. Minimum edge weight to consider an edge as "present". Default: 0.01. |
return_edges |
Logical. Whether to return detailed edge-level results. Default: FALSE. |
... |
Arguments passed to |
This function treats edge recovery as a binary classification problem:
True Positive: Edge present in both original and simulated.
False Positive: Edge present in simulated but not original.
False Negative: Edge present in original but not simulated.
True Negative: Edge absent in both.
An edge is considered "present" if its weight exceeds the threshold.
A list containing:
true_positives: Number of edges correctly present in both.
false_positives: Number of edges present in simulated but not original.
false_negatives: Number of edges present in original but not simulated.
true_negatives: Number of edges correctly absent in both.
precision: TP / (TP + FP).
recall: TP / (TP + FN), also known as sensitivity.
f1_score: Harmonic mean of precision and recall.
accuracy: (TP + TN) / total edges.
jaccard: TP / (TP + FP + FN), Jaccard similarity.
edges: (Optional) Data frame with edge-level results.
compare_networks() for full network comparison,
run_bootstrap_iteration() for bootstrap evaluation.
## Not run: # Calculate edge recovery recovery <- compare_edge_recovery(model_original, model_simulated) print(sprintf("Precision: %.2f, Recall: %.2f", recovery$precision, recovery$recall)) ## End(Not run)## Not run: # Calculate edge recovery recovery <- compare_edge_recovery(model_original, model_simulated) print(sprintf("Precision: %.2f, Recall: %.2f", recovery$precision, recovery$recall)) ## End(Not run)
Run multiple simulations comparing how well different TNA model types
recover the true transition structure, using tna::compare() for each
comparison. Supports any model type available in the tna package.
compare_estimation( models = c("tna", "ftna"), n_simulations = 1000, n_sequences = 200, seq_length = 25, n_states = 6, na_range = c(0, 5), scaling = "minmax", seed = NULL, verbose = TRUE, parallel = FALSE, cores = parallel::detectCores() - 1 )compare_estimation( models = c("tna", "ftna"), n_simulations = 1000, n_sequences = 200, seq_length = 25, n_states = 6, na_range = c(0, 5), scaling = "minmax", seed = NULL, verbose = TRUE, parallel = FALSE, cores = parallel::detectCores() - 1 )
models |
Character vector. Model types to compare. Any model function exported by tna package works: "tna", "ftna", "ctna", "atna", "sna", "tsn". Default: c("tna", "ftna"). |
n_simulations |
Integer. Number of simulations to run. Default: 1000. |
n_sequences |
Integer. Number of sequences per simulation. Default: 200. |
seq_length |
Integer. Maximum sequence length. Default: 25. |
n_states |
Integer. Number of states. Default: 6. |
na_range |
Integer vector of length 2. Range of NAs per sequence for varying lengths. Default: c(0, 5). |
scaling |
Character. Scaling for tna::compare(). Default: "minmax". |
seed |
Integer or NULL. Random seed. Default: NULL. |
verbose |
Logical. Print progress. Default: TRUE. |
parallel |
Logical. Use parallel processing. Default: FALSE. |
cores |
Integer. Number of cores for parallel. Default: detectCores() - 1. |
For each simulation:
Generate random transition probabilities (ground truth)
Simulate sequences with optional NAs (varying lengths)
Fit all specified model types
Compare each to ground truth using tna::compare()
Collect metrics (Pearson, Spearman, Kendall, Euclidean, etc.)
Available model types (any tna package model):
tna: Standard transition network analysis (probabilities)
ftna: Frequency-based TNA (raw counts)
ctna: Concurrent TNA
atna: Absorbing TNA
sna: Sequential network analysis
tsn: Time-series network
Any other model function exported by tna package
A list containing:
Side-by-side comparison of key metrics across models.
Data frame with mean/sd of all metrics by model type.
Data frame with all simulation results.
Models ranked by Pearson correlation (best to worst).
Model with highest Pearson correlation.
Parameters used for the simulation.
## Not run: # Compare 2 models (default: tna vs ftna) results <- compare_estimation(n_simulations = 100, seed = 42) # Compare 3 models results <- compare_estimation( models = c("tna", "ftna", "ctna"), n_simulations = 100, seed = 42 ) # Compare all 4 models results <- compare_estimation( models = c("tna", "ftna", "ctna", "atna"), n_simulations = 500, parallel = TRUE, seed = 42 ) # View results results$comparison # Side-by-side metrics results$ranking # Best to worst results$winner # Top performer ## End(Not run)## Not run: # Compare 2 models (default: tna vs ftna) results <- compare_estimation(n_simulations = 100, seed = 42) # Compare 3 models results <- compare_estimation( models = c("tna", "ftna", "ctna"), n_simulations = 100, seed = 42 ) # Compare all 4 models results <- compare_estimation( models = c("tna", "ftna", "ctna", "atna"), n_simulations = 500, parallel = TRUE, seed = 42 ) # View results results$comparison # Side-by-side metrics results$ranking # Best to worst results$winner # Top performer ## End(Not run)
Perform side-by-side comparison of multiple TNA model types (tna, atna, ctna, ftna) using comprehensive sampling analysis. Uses a statistically correct approach: comparing models built on independent data subsets (sample vs remaining).
compare_network_estimation( data, model_types = c("tna", "ftna"), model_scaling = NULL, sampling_percent = 0.3, iterations = 100, seed = NULL, verbose = TRUE ) compare_tna_models( data, model_types = c("tna", "ftna"), model_scaling = NULL, sampling_percent = 0.3, iterations = 100, seed = NULL, verbose = TRUE )compare_network_estimation( data, model_types = c("tna", "ftna"), model_scaling = NULL, sampling_percent = 0.3, iterations = 100, seed = NULL, verbose = TRUE ) compare_tna_models( data, model_types = c("tna", "ftna"), model_scaling = NULL, sampling_percent = 0.3, iterations = 100, seed = NULL, verbose = TRUE )
data |
A data frame containing sequence data. |
model_types |
Character vector of model types to compare. Valid types are "tna", "atna", "ctna", "ftna". Default: c("tna", "ftna"). |
model_scaling |
A named list specifying scaling for each model type. Example: list(tna = "minmax", ftna = "skip"). If NULL, uses default scaling. |
sampling_percent |
Numeric value between 0 and 1 indicating the proportion of data to sample. Default: 0.3. |
iterations |
Integer specifying the number of sampling iterations for each model. Default: 100. |
seed |
Integer seed for reproducible random sampling. Default: NULL. |
verbose |
Logical. Print progress messages. Default: TRUE. |
The function workflow:
For each model type, builds a model from the data.
Runs sampling analysis comparing sample vs remaining subsets.
Combines all results for comparison.
This approach is statistically correct because it compares models built on independent data subsets, providing a true measure of estimation stability.
A list containing:
Data frame with all iteration results including model_type column.
Data frame with aggregated metrics by model type.
Models ranked by mean Pearson correlation.
Model with highest Pearson correlation.
Parameters used for the comparison.
## Not run: library(tna) data(group_regulation) # Compare tna and ftna models results <- compare_network_estimation(group_regulation) results$ranking results$winner # Compare all model types results <- compare_network_estimation( group_regulation, model_types = c("tna", "atna", "ctna", "ftna"), iterations = 100 ) # Plot results plot(results) # Default histogram plot(results, metric_name = "Pearson") ## End(Not run)## Not run: library(tna) data(group_regulation) # Compare tna and ftna models results <- compare_network_estimation(group_regulation) results$ranking results$winner # Compare all model types results <- compare_network_estimation( group_regulation, model_types = c("tna", "atna", "ctna", "ftna"), iterations = 100 ) # Plot results plot(results) # Default histogram plot(results, metric_name = "Pearson") ## End(Not run)
Compare two TNA network models using multiple metrics including correlation, RMSE, and edge-level differences.
compare_networks( model1, model2, metrics = c("correlation", "rmse", "edge_diff"), scaling = c("none", "minmax", "zscore"), include_self = TRUE, threshold = 0.05 )compare_networks( model1, model2, metrics = c("correlation", "rmse", "edge_diff"), scaling = c("none", "minmax", "zscore"), include_self = TRUE, threshold = 0.05 )
model1 |
A TNA model object (the reference/original model). |
model2 |
A TNA model object (the comparison/simulated model). |
metrics |
Character vector. Metrics to compute. Options: "correlation" (Pearson correlation), "rmse" (root mean square error), "mae" (mean absolute error), "edge_diff" (proportion with large differences), "cosine" (cosine similarity), or "all" to compute everything. Default: c("correlation", "rmse", "edge_diff"). |
scaling |
Character. How to scale edge weights before comparison. Options: "none" (no scaling), "minmax" (min-max normalization to 0-1), "zscore" (z-score standardization). Default: "none". |
include_self |
Logical. Whether to include self-loops in comparison. Default: TRUE. |
threshold |
Numeric. Threshold for considering an edge as "different" in edge_diff metric. Default: 0.05. |
This function extracts edge weights from both models and computes various comparison metrics. Edge weights are extracted from the transition matrices stored in the TNA model objects.
A list with class "tna_comparison" containing:
metrics: Named list of computed metrics.
edge_comparison: Data frame comparing edges from both models.
summary: Character summary of the comparison.
compare_centralities() for comparing centrality profiles,
compare_edge_recovery() for edge recovery metrics.
## Not run: # Generate original data and fit model original_data <- simulate_sequences(trans_mat, init_probs, 20, 200) model_original <- tna::tna(original_data) # Simulate from fitted model and fit new model sim_data <- simulate_sequences( transition_matrix = model_original$weights, initial_probabilities = model_original$initial, max_seq_length = 20, num_rows = 200 ) model_sim <- tna::tna(sim_data) # Compare the models comparison <- compare_networks(model_original, model_sim) print(comparison$metrics) ## End(Not run)## Not run: # Generate original data and fit model original_data <- simulate_sequences(trans_mat, init_probs, 20, 200) model_original <- tna::tna(original_data) # Simulate from fitted model and fit new model sim_data <- simulate_sequences( transition_matrix = model_original$weights, initial_probabilities = model_original$initial, max_seq_length = 20, num_rows = 200 ) model_sim <- tna::tna(sim_data) # Compare the models comparison <- compare_networks(model_original, model_sim) print(comparison$metrics) ## End(Not run)
Run multiple simulations assessing split-half reliability under varying
data conditions (number of sequences, sequence length, number of states).
Uses tna::reliability() for each simulation with randomly sampled
parameters from user-specified ranges.
compare_reliability( n_simulations = 1000, n_sequences = c(50, 500), seq_length = c(10, 50), n_states = 6, alpha = 1, diag_c = 0, na_range = c(0, 5), model_type = "tna", reliability_iter = 100, reliability_split = 0.5, scaling = "none", seed = NULL, verbose = TRUE, parallel = FALSE, cores = parallel::detectCores() - 1 )compare_reliability( n_simulations = 1000, n_sequences = c(50, 500), seq_length = c(10, 50), n_states = 6, alpha = 1, diag_c = 0, na_range = c(0, 5), model_type = "tna", reliability_iter = 100, reliability_split = 0.5, scaling = "none", seed = NULL, verbose = TRUE, parallel = FALSE, cores = parallel::detectCores() - 1 )
n_simulations |
Integer. Number of simulations to run. Default: 1000. |
n_sequences |
Integer or integer vector of length 2. Number of sequences per simulation. If length 2, each simulation samples a random integer in that range. Default: c(50, 500). |
seq_length |
Integer or integer vector of length 2. Sequence length. If length 2, each simulation samples a random integer in that range. Default: c(10, 50). |
n_states |
Integer or integer vector of length 2. Number of states. If length 2, each simulation samples a random integer in that range. Default: 6. |
alpha |
Numeric or numeric vector of length 2. Dirichlet concentration
parameter for |
diag_c |
Numeric or numeric vector of length 2. Diagonal boost for
|
na_range |
Integer vector of length 2. Range of NAs per sequence. Default: c(0, 5). |
model_type |
Character. Which model to fit. Default: "tna". |
reliability_iter |
Integer. Number of iterations for
|
reliability_split |
Numeric. Split proportion for
|
scaling |
Character. Scaling for |
seed |
Integer or NULL. Random seed. Default: NULL. |
verbose |
Logical. Print progress. Default: TRUE. |
parallel |
Logical. Use parallel processing. Default: FALSE. |
cores |
Integer. Number of cores for parallel. Default: detectCores() - 1. |
For each simulation:
Randomly sample n_sequences, seq_length, n_states from
user-specified ranges.
Generate ground truth via generate_probabilities().
Simulate sequences via simulate_sequences() with those
parameters and NAs.
Fit a TNA model (e.g., tna::tna(sequences)).
Run tna::reliability() on the fitted model.
Extract the $summary table (22 metrics with
mean/sd/median/min/max/q25/q75).
Append simulation parameters as columns.
A list of class "tna_reliability_comparison" containing:
Data frame with all simulation results (one row per metric per simulation, with parameter columns).
Data frame with mean/sd aggregated across simulations grouped by metric.
List of input parameters for reference.
## Not run: # Quick test res <- compare_reliability( n_simulations = 10, reliability_iter = 20, seed = 42 ) print(res) # Vary number of states too res <- compare_reliability( n_simulations = 100, n_states = c(3, 8), reliability_iter = 50, seed = 42 ) plot(res) # Parallel execution res <- compare_reliability( n_simulations = 500, parallel = TRUE, seed = 42 ) ## End(Not run)## Not run: # Quick test res <- compare_reliability( n_simulations = 10, reliability_iter = 20, seed = 42 ) print(res) # Vary number of states too res <- compare_reliability( n_simulations = 100, n_states = c(3, 8), reliability_iter = 50, seed = 42 ) plot(res) # Parallel execution res <- compare_reliability( n_simulations = 500, parallel = TRUE, seed = 42 ) ## End(Not run)
Perform cross-validation by testing different TNA model types on the same data, allowing comparison of model performance.
cross_validate_tna( data, model_types = c("relative", "frequency", "co-occurrence"), sampling_percent = 0.3, iterations = 50, seed = NULL, verbose = TRUE )cross_validate_tna( data, model_types = c("relative", "frequency", "co-occurrence"), sampling_percent = 0.3, iterations = 50, seed = NULL, verbose = TRUE )
data |
A data frame containing sequence data. |
model_types |
Character vector of model types to test. Default: c("relative", "frequency", "co-occurrence"). |
sampling_percent |
Proportion of data for sampling. Default: 0.3. |
iterations |
Number of iterations per model type. Default: 50. |
seed |
Random seed for reproducibility. Default: NULL. |
verbose |
Logical. Print progress. Default: TRUE. |
A list containing cross-validation results for each model type.
## Not run: data(group_regulation, package = "tna") cv_results <- cross_validate_tna( group_regulation, model_types = c("relative", "frequency"), iterations = 30 ) ## End(Not run)## Not run: data(group_regulation, package = "tna") cv_results <- cross_validate_tna( group_regulation, model_types = c("relative", "frequency"), iterations = 30 ) ## End(Not run)
Write a tidy simulation data.frame to CSV. A list of
saqr_sim objects (or a single one) is first flattened with
tidy_simulation_results; a data.frame is written
as-is.
export_simulation(x, file)export_simulation(x, file)
x |
A |
file |
Character scalar. Path of the CSV file to write. |
The file path, invisibly.
s <- run_scenario("power_ttest", seed = 1) path <- tempfile(fileext = ".csv") export_simulation(s, path)s <- run_scenario("power_ttest", seed = 1) path <- tempfile(fileext = ".csv") export_simulation(s, path)
Fit a TNA (Temporal Network Analysis) model to sequence data using one of several available model types.
fit_network_model(sequences, model_type, group = NULL)fit_network_model(sequences, model_type, group = NULL)
sequences |
Data frame of sequences. Each row is a sequence, each column is a time point. For group models, should include a grouping column. |
model_type |
Character. Type of model to fit. One of:
|
group |
Character or NULL. Name of the grouping column for group_tna
models. Required when |
This function is a wrapper around the tna package's model fitting functions. It provides a unified interface for fitting different types of TNA models.
For group_tna models, the sequences data frame must contain a column
identifying the group membership of each sequence, specified by the group
parameter.
A fitted TNA model object of the appropriate class.
## Not run: # Generate some sequence data trans_mat <- matrix(c( 0.7, 0.2, 0.1, 0.3, 0.5, 0.2, 0.2, 0.3, 0.5 ), nrow = 3, byrow = TRUE) rownames(trans_mat) <- colnames(trans_mat) <- c("A", "B", "C") init_probs <- c(A = 0.5, B = 0.3, C = 0.2) sequences <- simulate_sequences( transition_matrix = trans_mat, initial_probabilities = init_probs, max_seq_length = 20, num_rows = 100 ) # Fit different model types model_tna <- fit_network_model(sequences, "tna") model_ftna <- fit_network_model(sequences, "ftna") # Fit group model long_data <- simulate_long_data(n_groups = 5, actors_per_group = 10) wide_data <- long_to_wide(long_data, id_col = "Actor") # Add group column back actor_groups <- unique(long_data[, c("Actor", "Group")]) wide_data <- merge(wide_data, actor_groups, by = "Actor") model_group <- fit_network_model(wide_data, "group_tna", group = "Group") ## End(Not run)## Not run: # Generate some sequence data trans_mat <- matrix(c( 0.7, 0.2, 0.1, 0.3, 0.5, 0.2, 0.2, 0.3, 0.5 ), nrow = 3, byrow = TRUE) rownames(trans_mat) <- colnames(trans_mat) <- c("A", "B", "C") init_probs <- c(A = 0.5, B = 0.3, C = 0.2) sequences <- simulate_sequences( transition_matrix = trans_mat, initial_probabilities = init_probs, max_seq_length = 20, num_rows = 100 ) # Fit different model types model_tna <- fit_network_model(sequences, "tna") model_ftna <- fit_network_model(sequences, "ftna") # Fit group model long_data <- simulate_long_data(n_groups = 5, actors_per_group = 10) wide_data <- long_to_wide(long_data, id_col = "Actor") # Add group column back actor_groups <- unique(long_data[, c("Actor", "Group")]) wide_data <- merge(wide_data, actor_groups, by = "Actor") model_group <- fit_network_model(wide_data, "group_tna", group = "Group") ## End(Not run)
Generate a grid of parameter combinations for simulation studies using various sampling methods. Can be called with no arguments for a demo grid.
generate_param_grid(param_ranges = NULL, n = 10, method = "random") create_param_grid(...)generate_param_grid(param_ranges = NULL, n = 10, method = "random") create_param_grid(...)
param_ranges |
Named list of parameter ranges. Each element can be:
If NULL (default), uses demo ranges for TNA simulation:
|
n |
Integer. Number of parameter combinations to generate. Default: 10. |
method |
Character. Sampling method. One of:
Default: "random". |
... |
Arguments passed to |
Method Details:
"random": Draws uniform random values within each range. Integer parameters (detected when min and max are both integers) are rounded.
"grid": Creates a regular grid with approximately n^(1/d) points per
dimension (where d is the number of parameters). If the resulting grid
exceeds n points, it is randomly subsampled.
"lhs": Uses Latin Hypercube Sampling for space-filling designs that provide better coverage of the parameter space than random sampling.
Categorical parameters are sampled uniformly with replacement for all methods.
A data frame with n rows and columns for each parameter.
# Simplest usage: demo grid with default TNA parameters grid <- generate_param_grid() head(grid) # Define custom parameter ranges ranges <- list( num_rows = c(50, 500), # Integer parameter max_seq_length = c(10, 100), # Integer parameter stability_prob = c(0.7, 1.0) # Continuous parameter ) # Random sampling grid_random <- generate_param_grid(ranges, n = 20, method = "random") # Latin Hypercube Sampling grid_lhs <- generate_param_grid(ranges, n = 20, method = "lhs") # Grid sampling grid_regular <- generate_param_grid(ranges, n = 20, method = "grid")# Simplest usage: demo grid with default TNA parameters grid <- generate_param_grid() head(grid) # Define custom parameter ranges ranges <- list( num_rows = c(50, 500), # Integer parameter max_seq_length = c(10, 100), # Integer parameter stability_prob = c(0.7, 1.0) # Continuous parameter ) # Random sampling grid_random <- generate_param_grid(ranges, n = 20, method = "random") # Latin Hypercube Sampling grid_lhs <- generate_param_grid(ranges, n = 20, method = "lhs") # Grid sampling grid_regular <- generate_param_grid(ranges, n = 20, method = "grid")
Generate random transition probabilities and initial state probabilities for a Markov chain using the seqHMM package.
generate_probabilities( n_states = 8, states = NULL, alpha = 1, diag_c = 0, seed = NULL, possible_state_names = NULL )generate_probabilities( n_states = 8, states = NULL, alpha = 1, diag_c = 0, seed = NULL, possible_state_names = NULL )
n_states |
Integer. Number of states in the Markov chain. Default: 5. |
states |
Character vector. Names for the states.
Must have at least |
alpha |
Numeric. Dirichlet concentration parameter passed to
|
diag_c |
Numeric. Diagonal boost added before row normalisation,
passed to |
seed |
Integer or NULL. Random seed for reproducibility. Default: NULL. |
possible_state_names |
Deprecated. Use |
The transition probabilities are generated using
seqHMM::simulate_transition_probs() and initial probabilities using
seqHMM::simulate_initial_probs().
A list containing:
Named numeric vector of initial state probabilities.
Square matrix of transition probabilities with row and column names set to state names.
Character vector of state names used.
## Not run: # Generate probabilities for 4 states with default names probs <- generate_probabilities(n_states = 4, seed = 42) # Generate probabilities with custom state names probs <- generate_probabilities( n_states = 4, states = c("A", "B", "C", "D", "E"), seed = 123 ) # View initial probabilities probs$initial_probs # View transition matrix probs$transition_probs # Old parameter name still works probs <- generate_probabilities( n_states = 3, possible_state_names = c("X", "Y", "Z") ) ## End(Not run)## Not run: # Generate probabilities for 4 states with default names probs <- generate_probabilities(n_states = 4, seed = 42) # Generate probabilities with custom state names probs <- generate_probabilities( n_states = 4, states = c("A", "B", "C", "D", "E"), seed = 123 ) # View initial probabilities probs$initial_probs # View transition matrix probs$transition_probs # Old parameter name still works probs <- generate_probabilities( n_states = 3, possible_state_names = c("X", "Y", "Z") ) ## End(Not run)
Retrieve names from the global names dataset, with optional filtering by region.
get_global_names(n = NULL, regions = "all", seed = NULL)get_global_names(n = NULL, regions = "all", seed = NULL)
n |
Integer or NULL. Number of names to return. If NULL, returns all matching names. Default: NULL. |
regions |
Character vector. Regions to sample from. Can be:
Default: "all". |
seed |
Integer or NULL. Random seed for reproducibility. Default: NULL. |
Character vector of names.
list_name_regions for available regions,
GLOBAL_NAMES for the full dataset.
# Get 20 random names from all regions get_global_names(20, seed = 42) # Get 10 names from Arab region get_global_names(10, regions = "arab") # Get 15 names from any African region get_global_names(15, regions = "africa") # Get names from multiple regions get_global_names(20, regions = c("east_asia", "south_asia")) # Get all Nordic names get_global_names(regions = "nordic")# Get 20 random names from all regions get_global_names(20, seed = 42) # Get 10 names from Arab region get_global_names(10, regions = "arab") # Get 15 names from any African region get_global_names(15, regions = "africa") # Get names from multiple regions get_global_names(20, regions = c("east_asia", "south_asia")) # Get all Nordic names get_global_names(regions = "nordic")
Retrieve learning action verbs by category, with options for random selection and combining multiple categories.
get_learning_states(categories = "all", n = NULL, seed = NULL)get_learning_states(categories = "all", n = NULL, seed = NULL)
categories |
Character vector specifying which categories to include. Options: "metacognitive", "cognitive", "behavioral", "social", "motivational", "affective", or "all" for all categories. Default: "all". |
n |
Integer or NULL. If specified, randomly sample n verbs from the selected categories. If NULL, return all verbs. Default: NULL. |
seed |
Integer or NULL. Random seed for reproducible sampling. Default: NULL. |
Character vector of learning state verbs.
# All metacognitive verbs get_learning_states("metacognitive") # 10 random verbs from all categories get_learning_states(n = 10, seed = 42) # 5 verbs from cognitive and behavioral get_learning_states(c("cognitive", "behavioral"), n = 5) # Self-regulated learning focus (metacognitive + motivational) get_learning_states(c("metacognitive", "motivational"))# All metacognitive verbs get_learning_states("metacognitive") # 10 random verbs from all categories get_learning_states(n = 10, seed = 42) # 5 verbs from cognitive and behavioral get_learning_states(c("cognitive", "behavioral"), n = 5) # Self-regulated learning focus (metacognitive + motivational) get_learning_states(c("metacognitive", "motivational"))
Retrieve the argument-lists for a named scenario. With
case = NULL the full list of argument-lists is returned; with an
integer case the single argument-list for that case is returned,
ready to do.call() against the scenario's simulator.
get_scenario(scenario, case = NULL)get_scenario(scenario, case = NULL)
scenario |
Character scalar. The scenario name (see
|
case |
Integer scalar or |
When case = NULL, a list of named argument-lists. When
case is an integer, a single named argument-list.
get_scenario("power_ttest") get_scenario("power_ttest", case = 1)get_scenario("power_ttest") get_scenario("power_ttest", case = 1)
A collection of ~1000 culturally diverse names from around the world, organized by region for use in social network simulations.
GLOBAL_NAMESGLOBAL_NAMES
A named list of character vectors, with each element containing names from a specific region.
Regions are organized geographically and include:
Europe:
western_europe: UK, Ireland, France, Germany, Netherlands, Belgium
eastern_europe: Russia, Ukraine, Poland, Czech, Romania, Hungary, Bulgaria
southern_europe: Spain, Italy, Portugal, Greece
nordic: Sweden, Norway, Denmark, Finland, Iceland
Middle East & Central Asia:
arab: Gulf states, Levant, Egypt
persian: Iran, Afghanistan, Tajikistan
turkish: Turkey, Azerbaijan
central_asia: Kazakhstan, Uzbekistan, Kyrgyzstan, Turkmenistan
Asia:
south_asia: India, Pakistan, Bangladesh, Sri Lanka, Nepal
east_asia: China, Japan, Korea, Mongolia
southeast_asia: Vietnam, Thailand, Indonesia, Philippines, Malaysia
Africa:
west_africa: Nigeria, Ghana, Senegal, Mali
east_africa: Kenya, Ethiopia, Tanzania, Somalia, Uganda
southern_africa: South Africa, Zimbabwe, Botswana, Namibia
north_africa: Morocco, Algeria, Tunisia, Libya
central_africa: DRC, Cameroon, Congo
Americas:
north_america: USA, Canada
latin_america: Mexico, Central America, South America, Brazil
caribbean: Jamaica, Haiti, Cuba, Trinidad, Dominican Republic
indigenous_americas: Native American, First Nations, Mayan, Incan
Oceania:
australia_nz: Australia, New Zealand
pacific_islands: Hawaii, Samoa, Tonga, Fiji, PNG
indigenous_oceania: Maori, Aboriginal Australian
Other:
jewish_hebrew: Hebrew/Jewish names
armenian_georgian: Armenia, Georgia
get_global_names for sampling names,
list_name_regions for exploring available regions.
# View all region names names(GLOBAL_NAMES) # View names from a specific region GLOBAL_NAMES$arab GLOBAL_NAMES$east_asia # Count names per region sapply(GLOBAL_NAMES, length) # Total names available sum(sapply(GLOBAL_NAMES, length))# View all region names names(GLOBAL_NAMES) # View names from a specific region GLOBAL_NAMES$arab GLOBAL_NAMES$east_asia # Count names per region sapply(GLOBAL_NAMES, length) # Total names available sum(sapply(GLOBAL_NAMES, length))
The 9 standard group regulation (SSRL) actions used in collaborative learning research.
GROUP_REGULATION_ACTIONSGROUP_REGULATION_ACTIONS
A character vector of 9 actions.
These actions represent Socially Shared Regulation of Learning (SSRL):
Adjusting strategies based on feedback
Building and maintaining group unity
Reaching group agreement
Mutually regulating each other's learning
Engaging in group discussion
Expressing or regulating emotions
Tracking and evaluating progress
Planning group activities and strategies
Integrating and combining ideas
GROUP_REGULATION_ACTIONS # Use in simulation data <- simulate_long_data( n_groups = 10, states = GROUP_REGULATION_ACTIONS, seed = 42 )GROUP_REGULATION_ACTIONS # Use in simulation data <- simulate_long_data( n_groups = 10, states = GROUP_REGULATION_ACTIONS, seed = 42 )
Take an existing complete data.frame and inject missing values
(NA) into target columns under a chosen, well-defined missingness
mechanism. This is a transformer, not a generator: the returned object
is the same data.frame with some cells replaced by NA, carrying an
attached "missing_info" attribute that records exactly which cells
were made missing and how. Useful for testing imputation methods and
missing-data-aware estimators against a known ground truth.
The three mechanisms follow the standard Rubin taxonomy:
"MCAR"Missing Completely At Random. Each cell of the
target columns is independently set missing with probability
prop.
"MAR"Missing At Random. The probability that a target
cell is missing depends on an observed predictor column,
never on the to-be-missing value itself. Probabilities are calibrated
(via a rank/logistic weighting on the predictor) so the average
missing fraction is approximately prop.
"MNAR"Missing Not At Random. The probability that a
target cell is missing depends on that cell's own (numeric) value:
larger values are more likely to go missing. Calibrated so the
average missing fraction per column is approximately prop.
inject_missingness( data, mechanism = c("MCAR", "MAR", "MNAR"), prop = 0.1, cols = NULL, predictor = NULL, seed = NULL )inject_missingness( data, mechanism = c("MCAR", "MAR", "MNAR"), prop = 0.1, cols = NULL, predictor = NULL, seed = NULL )
data |
A data.frame, or a |
mechanism |
Character. One of |
prop |
Numeric scalar in |
cols |
Character vector of target column names, or |
predictor |
Character scalar naming the observed column that drives
missingness under |
seed |
Integer or |
The input data.frame with NAs injected into the target
columns. The returned object additionally carries an attribute
"missing_info", a list with elements:
mechanismThe resolved mechanism string.
propThe requested target proportion.
colsThe target column names actually used.
n_missingTotal number of cells set missing.
realized_propRealized fraction of target cells set
missing (n_missing / (nrow * length(cols))).
indicatorA logical matrix (nrow(data) x
length(cols)) marking the cells that were injected as
TRUE, with column names matching cols.
df <- simulate_prediction( n = 500, coefs = c("(Intercept)" = 1, x1 = 2, x2 = -1), seed = 1 )$data # MCAR: 20% of every column missing at random mcar <- inject_missingness(df, mechanism = "MCAR", prop = 0.2, seed = 7) attr(mcar, "missing_info")$realized_prop str(attr(mcar, "missing_info")) # MAR: missingness in y driven by observed x1 mar <- inject_missingness(df, mechanism = "MAR", prop = 0.2, cols = "y", predictor = "x1", seed = 7) colSums(is.na(mar)) # MNAR: large y-values more likely missing mnar <- inject_missingness(df, mechanism = "MNAR", prop = 0.2, cols = "y", seed = 7) attr(mnar, "missing_info")$n_missingdf <- simulate_prediction( n = 500, coefs = c("(Intercept)" = 1, x1 = 2, x2 = -1), seed = 1 )$data # MCAR: 20% of every column missing at random mcar <- inject_missingness(df, mechanism = "MCAR", prop = 0.2, seed = 7) attr(mcar, "missing_info")$realized_prop str(attr(mcar, "missing_info")) # MAR: missingness in y driven by observed x1 mar <- inject_missingness(df, mechanism = "MAR", prop = 0.2, cols = "y", predictor = "x1", seed = 7) colSums(is.na(mar)) # MNAR: large y-values more likely missing mnar <- inject_missingness(df, mechanism = "MNAR", prop = 0.2, cols = "y", seed = 7) attr(mnar, "missing_info")$n_missing
Predefined collections of student learning action verbs organized by category. These can be used as state names when generating TNA networks to simulate realistic student learning behavior sequences.
LEARNING_STATESLEARNING_STATES
A named list with 8 categories of learning verbs.
The verbs are organized into seven categories based on learning science:
Self-regulation and awareness actions: planning, monitoring, evaluating one's own learning.
Mental processing actions: understanding, analyzing, synthesizing information.
Observable study actions: reading, writing, practicing, note-taking.
Interaction and collaboration actions: discussing, helping, teaching, asking.
Effort and persistence actions: focusing, persisting, engaging, striving.
Emotional and attitudinal states: enjoying, coping, managing stress, curiosity.
Socially shared regulation of learning (SSRL): collaborative planning, monitoring, adapting in groups.
Learning Management System actions: viewing content, accessing resources, submitting assignments, forum posts.
# Get all available categories names(get_learning_states()) # Get cognitive verbs only get_learning_states("cognitive") # Get multiple categories get_learning_states(c("metacognitive", "cognitive")) # Get all verbs combined get_learning_states("all") # Random selection of 8 verbs get_learning_states(n = 8) # Random 6 verbs from social and cognitive get_learning_states(c("social", "cognitive"), n = 6)# Get all available categories names(get_learning_states()) # Get cognitive verbs only get_learning_states("cognitive") # Get multiple categories get_learning_states(c("metacognitive", "cognitive")) # Get all verbs combined get_learning_states("all") # Random selection of 8 verbs get_learning_states(n = 8) # Random 6 verbs from social and cognitive get_learning_states(c("social", "cognitive"), n = 6)
Display a summary of all available learning state categories and the number of verbs in each.
list_learning_categories()list_learning_categories()
A data frame with category names and verb counts.
list_learning_categories()list_learning_categories()
Display all available regions and shortcuts for selecting names from GLOBAL_NAMES.
list_name_regions()list_name_regions()
A data frame with region names, counts, and example names.
list_name_regions()list_name_regions()
Return a tidy catalogue of the built-in scenario presets. Each
scenario is a hard-coded recipe of argument-lists targeting one
simulate_* function. Print the result directly.
list_scenarios()list_scenarios()
A base data.frame with one row per scenario and columns
scenario, description, simulator (the target
simulate_* function) and n_cases (number of argument-lists
in the recipe).
list_scenarios()list_scenarios()
Return the catalogue of simulation types reachable through
simulate, one row per type, with the underlying function name
and a one-line description. Print it directly.
Note: this lists the explicit-parameter simulators (those returning a
saqr_sim). The separate simulate_data entry
point provides random, seed-driven generation and returns a bare
data.frame; it is not part of this catalogue.
list_simulators()list_simulators()
A base data.frame with one row per simulator and columns:
typeThe type string passed to simulate.
functionThe name of the underlying simulator function.
descriptionA short one-line description.
list_simulators()list_simulators()
Create publication-ready plots for network estimation comparison results. Default is a histogram optimized for high iteration counts.
plot_network_estimation( results, metric_name = "Pearson", plot_type = "histogram", show_stats = TRUE, bins = NULL )plot_network_estimation( results, metric_name = "Pearson", plot_type = "histogram", show_stats = TRUE, bins = NULL )
results |
A network_estimation object or data frame with individual results. |
metric_name |
Character. Metric to plot. Default: "Pearson". |
plot_type |
Character. One of "histogram" (default), "boxplot", "density", "bar", or "ridgeline". |
show_stats |
Logical. Show mean/median statistics. Default: TRUE. |
bins |
Integer. Number of bins for histogram. Default: auto-calculated based on iterations (uses Sturges' rule). |
The histogram plot is optimized for high iteration counts (100+) and shows:
Turquoise bars with density overlay
Green vertical line for mean
Orange dotted line for median
Subtitle with exact mean and median values
A ggplot object.
## Not run: results <- compare_network_estimation(group_regulation, iterations = 100) # Default histogram plot_network_estimation(results) # Different metrics plot_network_estimation(results, metric_name = "Spearman") plot_network_estimation(results, metric_name = "Euclidean") # Different plot types plot_network_estimation(results, plot_type = "boxplot") plot_network_estimation(results, plot_type = "density") ## End(Not run)## Not run: results <- compare_network_estimation(group_regulation, iterations = 100) # Default histogram plot_network_estimation(results) # Different metrics plot_network_estimation(results, metric_name = "Spearman") plot_network_estimation(results, metric_name = "Euclidean") # Different plot types plot_network_estimation(results, plot_type = "boxplot") plot_network_estimation(results, plot_type = "density") ## End(Not run)
Create a visualization showing the distribution of a single metric's values across all sampling iterations.
plot_sampling_distribution(individual_results, category, metric)plot_sampling_distribution(individual_results, category, metric)
individual_results |
Data frame of raw metric values from iterations,
as returned by |
category |
The category of the metric to plot (e.g., "Correlations"). |
metric |
The specific metric name to plot (e.g., "Pearson"). |
A ggplot object showing the distribution.
## Not run: library(tna) model <- tna(group_regulation) results <- run_sampling_analysis(model, iterations = 100) # Plot Pearson correlation distribution plot_sampling_distribution( results$individual, category = "Correlations", metric = "Pearson" ) ## End(Not run)## Not run: library(tna) model <- tna(group_regulation) results <- run_sampling_analysis(model, iterations = 100) # Plot Pearson correlation distribution plot_sampling_distribution( results$individual, category = "Correlations", metric = "Pearson" ) ## End(Not run)
Visualize the distribution of metrics from TNA model comparisons. Supports multiple plot types including histogram (default), boxplot, ridgeline, bar, and density plots.
plot_tna_comparison( results, plot_type = "histogram", metric_name = "Pearson", model_types = NULL, binwidth = NULL )plot_tna_comparison( results, plot_type = "histogram", metric_name = "Pearson", model_types = NULL, binwidth = NULL )
results |
A data frame containing comparison results from
|
plot_type |
Character string specifying the plot type: "histogram" (default), "boxplot", "ridgeline", "bar", or "density". |
metric_name |
Character string specifying a single metric to plot. Default: "Pearson". If NULL, all metrics will be plotted. |
model_types |
Character vector specifying the models to include. If NULL (default), all models in the data will be used. |
binwidth |
Numeric value for histogram bin width. If NULL (default), calculated automatically. |
Available plot types:
Box plots showing distribution by model type.
Ridge line plots for density comparison.
Bar plots with mean values and error bars.
Histogram with density overlay (requires metric_name).
Density plots with mean/median lines (requires metric_name).
A ggplot object.
## Not run: library(tna) data(group_regulation) # Run comparison results <- compare_tna_models( group_regulation, model_types = c("tna", "atna"), iterations = 30 ) # Boxplot of Pearson correlation plot_tna_comparison(results$individual, "boxplot", metric_name = "Pearson") # Histogram of single metric plot_tna_comparison(results$individual, "histogram", metric_name = "Pearson") # All metrics as bar chart plot_tna_comparison(results$individual, "bar") ## End(Not run)## Not run: library(tna) data(group_regulation) # Run comparison results <- compare_tna_models( group_regulation, model_types = c("tna", "atna"), iterations = 30 ) # Boxplot of Pearson correlation plot_tna_comparison(results$individual, "boxplot", metric_name = "Pearson") # Histogram of single metric plot_tna_comparison(results$individual, "histogram", metric_name = "Pearson") # All metrics as bar chart plot_tna_comparison(results$individual, "bar") ## End(Not run)
Plot method for network_estimation objects. Default is histogram with density overlay showing mean and median values.
## S3 method for class 'network_estimation' plot(x, metric_name = "Pearson", plot_type = "histogram", ...)## S3 method for class 'network_estimation' plot(x, metric_name = "Pearson", plot_type = "histogram", ...)
x |
A network_estimation object from compare_network_estimation(). |
metric_name |
Character. Metric to plot. Default: "Pearson". |
plot_type |
Character. Plot type: "histogram" (default), "boxplot", "density", "bar", or "ridgeline". |
... |
Additional arguments (currently unused). |
A ggplot object.
## Not run: results <- compare_network_estimation(group_regulation) plot(results) # Histogram of Pearson correlation plot(results, metric_name = "Spearman") plot(results, plot_type = "boxplot") ## End(Not run)## Not run: results <- compare_network_estimation(group_regulation) plot(results) # Histogram of Pearson correlation plot(results, metric_name = "Spearman") plot(results, plot_type = "boxplot") ## End(Not run)
Plot Method for TNA Reliability Comparison
## S3 method for class 'tna_reliability_comparison' plot(x, metric = "Pearson", type = "scatter", ...)## S3 method for class 'tna_reliability_comparison' plot(x, metric = "Pearson", type = "scatter", ...)
x |
A |
metric |
Character. Metric to plot. Default: "Pearson". |
type |
Character. Plot type: "scatter", "boxplot", or "histogram". Default: "scatter". |
... |
Additional arguments (ignored). |
Print Network Estimation Results
## S3 method for class 'network_estimation' print(x, ...)## S3 method for class 'network_estimation' print(x, ...)
x |
A network_estimation object. |
... |
Additional arguments (unused). |
Print Method for TNA Reliability Comparison
## S3 method for class 'tna_reliability_comparison' print(x, ...)## S3 method for class 'tna_reliability_comparison' print(x, ...)
x |
A |
... |
Additional arguments (ignored). |
Performs a single bootstrap evaluation run: generates sequences, fits a TNA model, runs bootstrap analysis, and computes classification metrics for edge detection compared to ground truth stable transitions.
run_bootstrap_iteration( trans_matrix = NULL, init_probs = NULL, stable_transitions, seq_length = 20, n_sequences = 100, stability_prob = 0.95, unstable_mode = "random_jump", unstable_random_transition_prob = 0.5, unstable_perturb_noise = 0.5, unlikely_prob_threshold = 0.1, na_range = c(0, 0), include_na = TRUE, consistency_range = c(0.75, 1.25), level = 0.05, transition_matrix = NULL, initial_probabilities = NULL, max_seq_length = NULL, num_rows = NULL, min_na = NULL, max_na = NULL ) evaluate_bootstrap(...)run_bootstrap_iteration( trans_matrix = NULL, init_probs = NULL, stable_transitions, seq_length = 20, n_sequences = 100, stability_prob = 0.95, unstable_mode = "random_jump", unstable_random_transition_prob = 0.5, unstable_perturb_noise = 0.5, unlikely_prob_threshold = 0.1, na_range = c(0, 0), include_na = TRUE, consistency_range = c(0.75, 1.25), level = 0.05, transition_matrix = NULL, initial_probabilities = NULL, max_seq_length = NULL, num_rows = NULL, min_na = NULL, max_na = NULL ) evaluate_bootstrap(...)
trans_matrix |
Square numeric matrix of transition probabilities. Rows must sum to 1. Row names define state names. |
init_probs |
Named numeric vector of initial state probabilities. Must sum to 1. |
stable_transitions |
List of character vectors. Each vector contains two state names defining a stable (ground truth) transition pair. |
seq_length |
Integer. Maximum length of each sequence. |
n_sequences |
Integer. Number of sequences to generate. |
stability_prob |
Numeric in (0 to 1). Probability of following stable transitions. |
unstable_mode |
Character. Mode for unstable transitions: "random_jump", "perturb_prob", or "unlikely_jump". |
unstable_random_transition_prob |
Numeric in (0 to 1). Probability of unstable action. |
unstable_perturb_noise |
Numeric in (0 to 1). Noise factor for perturbation mode. |
unlikely_prob_threshold |
Numeric in (0 to 1). Threshold for unlikely transitions. |
na_range |
Integer vector of length 2 (min, max) or single integer (min=max). Range of NA values per sequence. Default: c(0, 0). |
include_na |
Logical. Whether to include NAs. |
consistency_range |
Numeric vector of length 2. Range for bootstrap consistency analysis (e.g., c(0.75, 1.25)). |
level |
Numeric in (0,1). Significance level for p-value threshold (e.g., 0.05). |
transition_matrix |
Deprecated. Use |
initial_probabilities |
Deprecated. Use |
max_seq_length |
Deprecated. Use |
num_rows |
Deprecated. Use |
min_na |
Deprecated. Use |
max_na |
Deprecated. Use |
... |
Arguments passed to |
The function:
Generates sequences using simulate_sequences_advanced().
Fits a TNA model and runs bootstrap analysis.
Creates a ground truth matrix from stable_transitions.
Compares bootstrap-significant edges to ground truth.
Computes TP, TN, FP, FN and derived metrics per edge.
An edge is considered "significant" if its p-value < level.
A list containing:
Data frame with per-edge results including ground truth, bootstrap significance, TP/TN/FP/FN, p-values, and metrics.
Raw bootstrap summary from tna::bootstrap.
Matrix of true positives by edge.
Matrix of true negatives by edge.
Matrix of false positives by edge.
Matrix of false negatives by edge.
Returns NULL if bootstrap fails.
## Not run: # Create transition matrix trans_mat <- matrix(c( 0.6, 0.3, 0.1, 0.2, 0.6, 0.2, 0.1, 0.2, 0.7 ), nrow = 3, byrow = TRUE) rownames(trans_mat) <- colnames(trans_mat) <- c("A", "B", "C") init_probs <- c(A = 0.33, B = 0.34, C = 0.33) # Define ground truth stable edges stable <- list(c("A", "B"), c("B", "C")) # Run single bootstrap evaluation result <- run_bootstrap_iteration( trans_matrix = trans_mat, init_probs = init_probs, stable_transitions = stable, seq_length = 30, n_sequences = 100, stability_prob = 0.95, unstable_mode = "random_jump", unstable_random_transition_prob = 0.5, na_range = c(0, 5), include_na = TRUE, consistency_range = c(0.75, 1.25), level = 0.05 ) # Old parameter names still work result <- run_bootstrap_iteration( transition_matrix = trans_mat, initial_probabilities = init_probs, stable_transitions = stable, max_seq_length = 30, num_rows = 100 ) ## End(Not run)## Not run: # Create transition matrix trans_mat <- matrix(c( 0.6, 0.3, 0.1, 0.2, 0.6, 0.2, 0.1, 0.2, 0.7 ), nrow = 3, byrow = TRUE) rownames(trans_mat) <- colnames(trans_mat) <- c("A", "B", "C") init_probs <- c(A = 0.33, B = 0.34, C = 0.33) # Define ground truth stable edges stable <- list(c("A", "B"), c("B", "C")) # Run single bootstrap evaluation result <- run_bootstrap_iteration( trans_matrix = trans_mat, init_probs = init_probs, stable_transitions = stable, seq_length = 30, n_sequences = 100, stability_prob = 0.95, unstable_mode = "random_jump", unstable_random_transition_prob = 0.5, na_range = c(0, 5), include_na = TRUE, consistency_range = c(0.75, 1.25), level = 0.05 ) # Old parameter names still work result <- run_bootstrap_iteration( transition_matrix = trans_mat, initial_probabilities = init_probs, stable_transitions = stable, max_seq_length = 30, num_rows = 100 ) ## End(Not run)
Simulate and analyze edge recovery across multiple bootstrap runs. Aggregates results to compute overall performance metrics and edge-level significance.
run_bootstrap_simulation( Model, stable_transitions, num_runs, seq_length = 20, n_sequences = 100, stability_prob = 0.95, unstable_mode = "random_jump", unstable_random_transition_prob = 0.5, unstable_perturb_noise = 0.5, unlikely_prob_threshold = 0.1, na_range = c(0, 0), include_na = TRUE, consistency_range = c(0.75, 1.25), level = 0.05, num_cores = parallel::detectCores() - 1, max_seq_length = NULL, num_rows = NULL, min_na = NULL, max_na = NULL )run_bootstrap_simulation( Model, stable_transitions, num_runs, seq_length = 20, n_sequences = 100, stability_prob = 0.95, unstable_mode = "random_jump", unstable_random_transition_prob = 0.5, unstable_perturb_noise = 0.5, unlikely_prob_threshold = 0.1, na_range = c(0, 0), include_na = TRUE, consistency_range = c(0.75, 1.25), level = 0.05, num_cores = parallel::detectCores() - 1, max_seq_length = NULL, num_rows = NULL, min_na = NULL, max_na = NULL )
Model |
A TNA model object with |
stable_transitions |
List of character vectors defining ground truth stable transitions. Each vector contains two state names (from, to). |
num_runs |
Integer. Number of simulation runs to perform. |
seq_length |
Integer. Maximum sequence length. |
n_sequences |
Integer. Number of sequences per run. |
stability_prob |
Numeric in (0 to 1). Probability of following stable transitions. Default: 0.95. |
unstable_mode |
Character. Mode for unstable transitions: "random_jump", "perturb_prob", or "unlikely_jump". Default: "random_jump". |
unstable_random_transition_prob |
Numeric in (0 to 1). Probability of unstable action. Default: 0.5. |
unstable_perturb_noise |
Numeric in (0 to 1). Noise for perturbation mode. Default: 0.5. |
unlikely_prob_threshold |
Numeric in (0 to 1). Threshold for unlikely transitions. Default: 0.1. |
na_range |
Integer vector of length 2 (min, max) or single integer. Range of NA values per sequence. Default: c(0, 0). |
include_na |
Logical. Whether to include NAs. Default: TRUE. |
consistency_range |
Numeric vector of length 2. Bootstrap consistency range. Default: c(0.75, 1.25). |
level |
Numeric in (0,1). Significance level. Default: 0.05. |
num_cores |
Integer. Number of cores for parallel processing. Default: detectCores() - 1. |
max_seq_length |
Deprecated. Use |
num_rows |
Deprecated. Use |
min_na |
Deprecated. Use |
max_na |
Deprecated. Use |
For each run, the function calls run_bootstrap_iteration() and accumulates
TP/TN/FP/FN counts. After all runs, it computes:
Overall Performance: Aggregated sensitivity (TPR), specificity (TNR), false positive rate (FPR), and false negative rate (FNR).
Edge Significance: For each edge, the number of times it was detected as significant, average p-value, average weight, and recovery rate.
Parallel processing uses parallel::mclapply().
A list containing:
List with:
overall_performance: Data frame with Sensitivity, Specificity, FPR, FNR.
edge_significance: Data frame with per-edge recovery rates and statistics.
List with:
list_of_summaries: Bootstrap summaries from each run.
list_of_per_edge_performance: Per-edge results from each run.
Number of successfully completed runs.
## Not run: # First create a TNA model from some data trans_mat <- matrix(c( 0.6, 0.3, 0.1, 0.2, 0.6, 0.2, 0.1, 0.2, 0.7 ), nrow = 3, byrow = TRUE) rownames(trans_mat) <- colnames(trans_mat) <- c("A", "B", "C") # Create a mock Model object Model <- list( weights = trans_mat, inits = c(A = 0.33, B = 0.34, C = 0.33) ) # Define stable transitions stable <- list(c("A", "B"), c("B", "C")) # Run bootstrap simulation results <- run_bootstrap_simulation( Model = Model, stable_transitions = stable, num_runs = 50, seq_length = 30, n_sequences = 100, stability_prob = 0.95, unstable_mode = "random_jump", num_cores = 4 ) # View overall performance results$aggregated_summary$overall_performance # View edge-level results results$aggregated_summary$edge_significance # Old parameter names still work results <- run_bootstrap_simulation( Model = Model, stable_transitions = stable, num_runs = 50, max_seq_length = 30, num_rows = 100 ) ## End(Not run)## Not run: # First create a TNA model from some data trans_mat <- matrix(c( 0.6, 0.3, 0.1, 0.2, 0.6, 0.2, 0.1, 0.2, 0.7 ), nrow = 3, byrow = TRUE) rownames(trans_mat) <- colnames(trans_mat) <- c("A", "B", "C") # Create a mock Model object Model <- list( weights = trans_mat, inits = c(A = 0.33, B = 0.34, C = 0.33) ) # Define stable transitions stable <- list(c("A", "B"), c("B", "C")) # Run bootstrap simulation results <- run_bootstrap_simulation( Model = Model, stable_transitions = stable, num_runs = 50, seq_length = 30, n_sequences = 100, stability_prob = 0.95, unstable_mode = "random_jump", num_cores = 4 ) # View overall performance results$aggregated_summary$overall_performance # View edge-level results results$aggregated_summary$edge_significance # Old parameter names still work results <- run_bootstrap_simulation( Model = Model, stable_transitions = stable, num_runs = 50, max_seq_length = 30, num_rows = 100 ) ## End(Not run)
Execute bootstrap simulations across a grid of parameter combinations. Useful for studying how different settings affect edge recovery performance.
run_grid_simulation( Model, stable_transitions, num_runs, n_sequences_vec = NULL, seq_length_vec = NULL, na_range_list = list(list(min = 0, max = 0)), stability_prob = 0.95, unstable_mode = "random_jump", unstable_random_transition_prob = 0.5, unstable_perturb_noise = 0.5, unlikely_prob_threshold = 0.1, include_na = TRUE, consistency_range = c(0.75, 1.25), level = 0.05, num_cores = parallel::detectCores() - 1, num_rows_vec = NULL, max_seq_length_vec = NULL )run_grid_simulation( Model, stable_transitions, num_runs, n_sequences_vec = NULL, seq_length_vec = NULL, na_range_list = list(list(min = 0, max = 0)), stability_prob = 0.95, unstable_mode = "random_jump", unstable_random_transition_prob = 0.5, unstable_perturb_noise = 0.5, unlikely_prob_threshold = 0.1, include_na = TRUE, consistency_range = c(0.75, 1.25), level = 0.05, num_cores = parallel::detectCores() - 1, num_rows_vec = NULL, max_seq_length_vec = NULL )
Model |
A TNA model object with |
stable_transitions |
List of character vectors defining ground truth stable transitions. |
num_runs |
Integer. Number of bootstrap runs per parameter combination. |
n_sequences_vec |
Numeric vector. Values of n_sequences to test. |
seq_length_vec |
Numeric vector. Values of seq_length to test. |
na_range_list |
List of lists. Each inner list has |
stability_prob |
Numeric. Fixed stability probability. Default: 0.95. |
unstable_mode |
Character. Fixed unstable mode. Default: "random_jump". |
unstable_random_transition_prob |
Numeric. Fixed unstable probability. Default: 0.5. |
unstable_perturb_noise |
Numeric. Fixed perturbation noise. Default: 0.5. |
unlikely_prob_threshold |
Numeric. Fixed unlikely threshold. Default: 0.1. |
include_na |
Logical. Whether to include NAs. Default: TRUE. |
consistency_range |
Numeric vector of length 2. Bootstrap consistency range. Default: c(0.75, 1.25). |
level |
Numeric. Significance level. Default: 0.05. |
num_cores |
Integer. Number of cores for parallel processing. Default: detectCores() - 1. |
num_rows_vec |
Deprecated. Use |
max_seq_length_vec |
Deprecated. Use |
The function creates a full factorial grid from:
n_sequences_vec x seq_length_vec x na_range_list
For each combination, it runs run_bootstrap_simulation() and stores
the results along with the parameter values used.
Progress messages are printed to track execution.
A named list where each element corresponds to a parameter combination.
Names follow the pattern nr<n_sequences>_sl<seq_length>_na<min>-<max>.
Each element contains:
Aggregated performance and edge significance.
Per-run details.
Number of successful runs.
The parameter values used for this combination.
## Not run: # Create a model trans_mat <- matrix(c( 0.6, 0.3, 0.1, 0.2, 0.6, 0.2, 0.1, 0.2, 0.7 ), nrow = 3, byrow = TRUE) rownames(trans_mat) <- colnames(trans_mat) <- c("A", "B", "C") Model <- list( weights = trans_mat, inits = c(A = 0.33, B = 0.34, C = 0.33) ) stable <- list(c("A", "B"), c("B", "C")) # Run grid search grid_results <- run_grid_simulation( Model = Model, stable_transitions = stable, num_runs = 20, n_sequences_vec = c(50, 100, 200), seq_length_vec = c(20, 30, 50), na_range_list = list( list(min = 0, max = 0), list(min = 0, max = 5), list(min = 5, max = 10) ), num_cores = 4 ) # Analyze results summarize_grid_results(grid_results) # Old parameter names still work grid_results <- run_grid_simulation( Model = Model, stable_transitions = stable, num_runs = 20, num_rows_vec = c(50, 100, 200), max_seq_length_vec = c(20, 30, 50) ) ## End(Not run)## Not run: # Create a model trans_mat <- matrix(c( 0.6, 0.3, 0.1, 0.2, 0.6, 0.2, 0.1, 0.2, 0.7 ), nrow = 3, byrow = TRUE) rownames(trans_mat) <- colnames(trans_mat) <- c("A", "B", "C") Model <- list( weights = trans_mat, inits = c(A = 0.33, B = 0.34, C = 0.33) ) stable <- list(c("A", "B"), c("B", "C")) # Run grid search grid_results <- run_grid_simulation( Model = Model, stable_transitions = stable, num_runs = 20, n_sequences_vec = c(50, 100, 200), seq_length_vec = c(20, 30, 50), na_range_list = list( list(min = 0, max = 0), list(min = 0, max = 5), list(min = 5, max = 10) ), num_cores = 4 ) # Analyze results summarize_grid_results(grid_results) # Old parameter names still work grid_results <- run_grid_simulation( Model = Model, stable_transitions = stable, num_runs = 20, num_rows_vec = c(50, 100, 200), max_seq_length_vec = c(20, 30, 50) ) ## End(Not run)
Run TNA simulations comparing fitted models to original data. Supports multiple model types, comparison modes, and parallel processing.
run_network_simulation( original_data_list, sim_params = NULL, models = c("tna"), comparisons = c("original"), num_runs = 3, parallel = FALSE, scaling = "minmax" )run_network_simulation( original_data_list, sim_params = NULL, models = c("tna"), comparisons = c("original"), num_runs = 3, parallel = FALSE, scaling = "minmax" )
original_data_list |
A list of data frames containing original sequence data, or a single data frame. Used as reference for comparisons. |
sim_params |
Simulation parameters. Can be:
|
models |
Character vector of model types to simulate. Options: "tna", "ftna", "ctna", "atna". Default: c("tna"). |
comparisons |
Character vector of comparison types. Options:
Default: c("original"). |
num_runs |
Integer. Number of simulation runs per parameter set. Default: 3. |
parallel |
Logical. Whether to use parallel processing. Default: FALSE. |
scaling |
Character. Scaling method for comparisons. Options: "none", "minmax", "zscore". Default: "minmax". |
For each parameter combination and original dataset, the function:
Extracts transition probabilities from the original TNA model.
Generates simulated sequences using those probabilities.
Fits the specified model types to the simulated sequences.
Computes comparison metrics against reference models.
Parallel processing uses the future.apply package when enabled.
A list containing:
Data frame of all comparison metrics from all runs.
Aggregated summary statistics by model and comparison type.
List of simulation parameters used.
## Not run: # Create some original sequence data trans_mat <- matrix(c( 0.7, 0.2, 0.1, 0.3, 0.5, 0.2, 0.2, 0.3, 0.5 ), nrow = 3, byrow = TRUE) rownames(trans_mat) <- colnames(trans_mat) <- c("A", "B", "C") init_probs <- c(A = 0.5, B = 0.3, C = 0.2) original_data <- simulate_sequences( trans_matrix = trans_mat, init_probs = init_probs, seq_length = 30, n_sequences = 100 ) # Run simulations comparing tna and ftna models results <- run_network_simulation( original_data_list = original_data, sim_params = list(seq_length = 30, n_sequences = 100), models = c("tna", "ftna"), comparisons = c("original"), num_runs = 5 ) # View summary statistics results$summary_stats ## End(Not run)## Not run: # Create some original sequence data trans_mat <- matrix(c( 0.7, 0.2, 0.1, 0.3, 0.5, 0.2, 0.2, 0.3, 0.5 ), nrow = 3, byrow = TRUE) rownames(trans_mat) <- colnames(trans_mat) <- c("A", "B", "C") init_probs <- c(A = 0.5, B = 0.3, C = 0.2) original_data <- simulate_sequences( trans_matrix = trans_mat, init_probs = init_probs, seq_length = 30, n_sequences = 100 ) # Run simulations comparing tna and ftna models results <- run_network_simulation( original_data_list = original_data, sim_params = list(seq_length = 30, n_sequences = 100), models = c("tna", "ftna"), comparisons = c("original"), num_runs = 5 ) # View summary statistics results$summary_stats ## End(Not run)
Perform comprehensive TNA model analysis through repeated sampling and statistical comparison. Uses a statistically correct sampling procedure by comparing models built on independent data subsets (sample vs remaining).
run_sampling_analysis( model, sampling_percent = 0.3, iterations = 100, seed = NULL, model_scaling = NULL, verbose = TRUE )run_sampling_analysis( model, sampling_percent = 0.3, iterations = 100, seed = NULL, model_scaling = NULL, verbose = TRUE )
model |
A TNA model object created with tna() or related functions. |
sampling_percent |
Numeric value between 0 and 1 specifying the proportion of data to use for the sample model. Default: 0.3. |
iterations |
Integer specifying the number of sampling iterations. Default: 100. |
seed |
Integer seed for reproducible random sampling. Default: NULL. |
model_scaling |
Character string to override the model's scaling: NULL (default) uses original model's scaling, "skip" forces no scaling, or valid TNA scaling options ("minmax", "max", "rank"). |
verbose |
Logical. Print progress messages. Default: TRUE. |
This function implements a statistically correct sampling procedure:
Data Splitting: For each iteration, splits the original data into:
Sample set (specified percentage)
Remaining set (complement)
Model Building: Builds TNA models on both datasets using the original model's type and configurable scaling.
Model Comparison: Compares sample model vs remaining model using TNA's compare() function, providing metrics across categories:
Correlations (Pearson, Spearman, Kendall)
Dissimilarities (Euclidean, Manhattan, etc.)
Similarities (Cosine, Jaccard, etc.)
Result Aggregation: Collects metrics across all iterations and computes summary statistics (mean, sd, median, quartiles).
This approach is statistically superior to comparing sample vs original because it compares models built on independent data subsets, providing a true measure of sampling variability and model stability.
A list containing:
Data frame with aggregated summary statistics by metric.
Data frame with raw metric values from each iteration.
Parameters used for the analysis.
## Not run: library(tna) model <- tna(group_regulation) # Basic analysis with defaults results <- run_sampling_analysis(model, iterations = 50) results$aggregated # With custom parameters results <- run_sampling_analysis( model, sampling_percent = 0.4, iterations = 100, seed = 42 ) ## End(Not run)## Not run: library(tna) model <- tna(group_regulation) # Basic analysis with defaults results <- run_sampling_analysis(model, iterations = 50) results$aggregated # With custom parameters results <- run_sampling_analysis( model, sampling_percent = 0.4, iterations = 100, seed = 42 ) ## End(Not run)
Execute every case of a scenario by do.call()-ing its
argument-list against the scenario's simulator. Returns a named list of
the resulting saqr_sim objects, labelled case1,
case2, ...
run_scenario(scenario, seed = NULL)run_scenario(scenario, seed = NULL)
scenario |
Character scalar. The scenario name (see
|
seed |
Integer scalar or |
A named list of saqr_sim objects, one per case, named
case1, case2, ...
s <- run_scenario("power_ttest", seed = 1) s$case1s <- run_scenario("power_ttest", seed = 1) s$case1
Take a TNA model, sample a percentage of its data, and re-estimate a new TNA model from the sampled data using the same parameters.
sample_tna(model, sampling_percent = 0.3, model_type = NULL, scaling = NULL)sample_tna(model, sampling_percent = 0.3, model_type = NULL, scaling = NULL)
model |
A TNA model object or data frame containing sequence data. |
sampling_percent |
Numeric value between 0 and 1 indicating the proportion of data to sample. Default: 0.3. |
model_type |
Character string specifying the model type. If NULL, uses the type from the original model. Default: NULL. |
scaling |
Character string specifying the scaling method. If NULL, uses the scaling from the original model. Default: NULL. |
A new TNA model object estimated from the sampled data.
## Not run: library(tna) model <- tna(group_regulation) sampled <- sample_tna(model, 0.3) ## End(Not run)## Not run: library(tna) model <- tna(group_regulation) sampled <- sample_tna(model, 0.3) ## End(Not run)
Intelligently select learning states based on the number of nodes needed, optionally biasing toward specific categories.
select_states( n_states, primary_categories = NULL, secondary_categories = NULL, primary_ratio = 0.6, seed = NULL ) smart_select_states(...)select_states( n_states, primary_categories = NULL, secondary_categories = NULL, primary_ratio = 0.6, seed = NULL ) smart_select_states(...)
n_states |
Integer. Number of states needed. |
primary_categories |
Character vector. Categories to prioritize. Default: NULL (balanced selection). |
secondary_categories |
Character vector. Categories to supplement with. Default: NULL (use all remaining). |
primary_ratio |
Numeric (0 to 1). Proportion of states from primary categories. Default: 0.6. |
seed |
Integer or NULL. Random seed. Default: NULL. |
... |
Arguments passed to |
Selection logic:
If n_states <= 5: Single category or balanced small set
If n_states 6-10: 1-2 categories prioritized
If n_states 11-20: Multiple categories with primary focus
If n_states > 20: All categories combined
Character vector of selected learning states.
# 5 states focused on self-regulation select_states(5, primary_categories = "metacognitive") # 10 states: mostly cognitive, some behavioral select_states(10, primary_categories = "cognitive", secondary_categories = "behavioral" ) # 15 states: balanced across categories select_states(15, seed = 42)# 5 states focused on self-regulation select_states(5, primary_categories = "metacognitive") # 10 states: mostly cognitive, some behavioral select_states(10, primary_categories = "cognitive", secondary_categories = "behavioral" ) # 15 states: balanced across categories select_states(15, seed = 42)
A single discoverable entry point over every explicit-parameter
simulator in the package. You pass the simulation type plus the
named arguments that simulator expects, and simulate() forwards them
straight through, returning that simulator's saqr_sim object
unchanged. Use list_simulators to see the available types.
For random, seed-driven generation (where the seed picks both the data and
the structural parameters) and a bare data.frame return, use the
separate simulate_data entry point instead.
simulate(type, ..., seed = NULL)simulate(type, ..., seed = NULL)
type |
Character scalar. The simulation type. One of the values in the
|
... |
Named arguments passed straight through to the matching
simulator. See the help page of the underlying simulator (e.g.
|
seed |
Integer or NULL. Random seed, forwarded to the target simulator. |
The saqr_sim object returned by the dispatched
simulator (with $data, $params, $type, $seed).
list_simulators for the catalogue of types,
simulate_data for random seed-driven generation.
simulate("ttest", n_a = 50, n_b = 50, mean_a = 0, mean_b = 0.5, seed = 1) simulate("anova", n = 30, means = c(10, 12, 15), seed = 1)simulate("ttest", n_a = 50, n_b = 50, mean_a = 0, mean_b = 0.5, seed = 1) simulate("anova", n = 30, means = c(10, 12, 15), seed = 1)
Generate data for a one-way ANOVA with fully specified
group means and standard deviations. Designed so that
aov(score ~ group, data = r$data) recovers the true group effects
at large n.
simulate_anova(n, means, sds = 1, labels = NULL, seed = NULL)simulate_anova(n, means, sds = 1, labels = NULL, seed = NULL)
n |
Integer or integer vector. If a single value, the per-group sample
size (equal groups). If a vector, must have length equal to
|
means |
Numeric vector. Population mean for each group. |
sds |
Numeric scalar or vector. Standard deviation(s) for each group. Scalar is recycled. Default: 1. |
labels |
Character vector or NULL. Group labels. Default:
|
seed |
Integer or NULL. Random seed. |
A saqr_sim object with:
$datadata.frame with columns group (factor) and
score (numeric).
$paramslist with means, sds (as vector),
n (per-group sizes), labels, eta_squared (true
population ).
r <- simulate_anova(n = 30, means = c(10, 12, 15), seed = 1) summary(aov(score ~ group, data = r$data)) r$params$eta_squared # Unequal groups and heteroscedastic r2 <- simulate_anova(n = c(50, 30, 20), means = c(5, 5, 10), sds = c(1, 2, 3), seed = 42)r <- simulate_anova(n = 30, means = c(10, 12, 15), seed = 1) summary(aov(score ~ group, data = r$data)) r$params$eta_squared # Unequal groups and heteroscedastic r2 <- simulate_anova(n = c(50, 30, 20), means = c(5, 5, 10), sds = c(1, 2, 3), seed = 42)
Generate multivariate data from a mixture of Gaussians with fully specified cluster centers and standard deviations. Designed for testing clustering algorithms where the ground truth is known.
simulate_clusters(n, centers, sds = 1, props = NULL, seed = NULL)simulate_clusters(n, centers, sds = 1, props = NULL, seed = NULL)
n |
Integer or integer vector. If a single value, the total sample
size (allocated by |
centers |
Numeric matrix ( |
sds |
Numeric scalar, vector of length |
props |
Numeric vector of length |
seed |
Integer or NULL. Random seed. |
A saqr_sim object with:
$datadata.frame with columns x1...xd and
integer column true_cluster (1...k).
$paramslist with centers (matrix),
sds (k x d matrix), props (normalised), n
(per-cluster sizes).
centers <- matrix(c(0, 0, 5, 5, 10, 0), nrow = 3, byrow = TRUE) r <- simulate_clusters(n = 300, centers = centers, seed = 1) plot(x2 ~ x1, data = r$data, col = r$data$true_cluster) r$params$centers # Per-cluster sizes and SDs r2 <- simulate_clusters(n = c(100, 50, 150), centers = centers, sds = c(0.5, 1.0, 2.0), seed = 42)centers <- matrix(c(0, 0, 5, 5, 10, 0), nrow = 3, byrow = TRUE) r <- simulate_clusters(n = 300, centers = centers, seed = 1) plot(x2 ~ x1, data = r$data, col = r$data$true_cluster) r$params$centers # Per-cluster sizes and SDs r2 <- simulate_clusters(n = c(100, 50, 150), centers = centers, sds = c(0.5, 1.0, 2.0), seed = 42)
Generate multivariate normal data from an explicit correlation
(or covariance) matrix. Designed so that cor(r$data) recovers
sigma at large n.
simulate_correlation(n, sigma, means = NULL, var_names = NULL, seed = NULL)simulate_correlation(n, sigma, means = NULL, var_names = NULL, seed = NULL)
n |
Integer. Sample size. |
sigma |
Numeric matrix. Either a correlation matrix (all diagonal = 1) or a covariance matrix. Must be symmetric and positive-definite (or near-PD; corrected internally). |
means |
Numeric vector or NULL. Population means for each variable. Default: all zeros. |
var_names |
Character vector or NULL. Variable names. Default:
|
seed |
Integer or NULL. Random seed. |
A saqr_sim object with:
$datadata.frame with columns x1...xp.
$paramslist with sigma (the input matrix),
means, is_correlation (logical).
# Correlation matrix R <- matrix(c(1, 0.6, 0.3, 0.6, 1, 0.5, 0.3, 0.5, 1), nrow = 3) r <- simulate_correlation(n = 200, sigma = R, seed = 1) cor(r$data) # should approximate R r$params$sigma # the true matrix # With means and custom names r2 <- simulate_correlation(n = 500, sigma = R, means = c(10, 20, 30), var_names = c("IQ", "GPA", "income"), seed = 42)# Correlation matrix R <- matrix(c(1, 0.6, 0.3, 0.6, 1, 0.5, 0.3, 0.5, 1), nrow = 3) r <- simulate_correlation(n = 200, sigma = R, seed = 1) cor(r$data) # should approximate R r$params$sigma # the true matrix # With means and custom names r2 <- simulate_correlation(n = 500, sigma = R, means = c(10, 20, 30), var_names = c("IQ", "GPA", "income"), seed = 42)
Generate synthetic datasets suitable for common statistical analyses. Each dataset type contains real signal so the intended analysis works out of the box. Different seeds produce structurally different datasets (varying n, effect sizes, number of groups/variables).
simulate_data(type, seed = NULL, complexity = "clean", ..., n_batch = NULL)simulate_data(type, seed = NULL, complexity = "clean", ..., n_batch = NULL)
type |
Character string specifying the dataset type. One of:
|
seed |
Integer or NULL. Random seed. Also determines structural parameters (n, effect sizes, etc.). Default: NULL. |
complexity |
Character. Controls edge-case injection for stress testing.
|
... |
Optional overrides for structural parameters (n, n_groups, etc.). |
n_batch |
Integer or NULL. When provided, returns a list of |
A data.frame (single dataset) or a list (when n_batch is
non-NULL or type = "batch"). Each dataset has attributes type,
info, and complexity. Batch items additionally have seed and
batch_id.
simulate_sequences(), simulate_igraph()
# Single clean dataset d <- simulate_data("ttest", seed = 42) # With edge cases d <- simulate_data("correlation", seed = 1, complexity = "auto") d <- simulate_data("ttest", seed = 1, complexity = c("na", "outliers")) # Batch of 100 ttest datasets batch <- simulate_data("ttest", seed = 1, n_batch = 100) # All types, 1000 datasets each all_batches <- simulate_data("batch", seed = 1)# Single clean dataset d <- simulate_data("ttest", seed = 42) # With edge cases d <- simulate_data("correlation", seed = 1, complexity = "auto") d <- simulate_data("ttest", seed = 1, complexity = c("na", "outliers")) # Batch of 100 ttest datasets batch <- simulate_data("ttest", seed = 1, n_batch = 100) # All types, 1000 datasets each all_batches <- simulate_data("batch", seed = 1)
Generate a simulated edge list for social network analysis. Creates random connections between nodes with weights and class assignments.
simulate_edge_list( n_nodes = 20, n_edges = NULL, edge_density = 3, n_classes = 3, directed = TRUE, allow_self_loops = FALSE, weight_range = c(0.1, 1), names = NULL, class_probs = NULL, seed = NULL )simulate_edge_list( n_nodes = 20, n_edges = NULL, edge_density = 3, n_classes = 3, directed = TRUE, allow_self_loops = FALSE, weight_range = c(0.1, 1), names = NULL, class_probs = NULL, seed = NULL )
n_nodes |
Integer. Number of nodes (people) in the network. Default: 20. |
n_edges |
Integer or NULL. Number of edges to generate. If NULL,
calculated as |
edge_density |
Numeric. Average number of edges per node when |
n_classes |
Integer. Number of classes/groups (2-10). Default: 3. |
directed |
Logical. Whether edges are directed. Default: TRUE. |
allow_self_loops |
Logical. Whether to allow self-connections. Default: FALSE. |
weight_range |
Numeric vector of length 2. Range for edge weights. Default: c(0.1, 1.0). |
names |
Character vector or NULL. Custom node names. If NULL, uses
names from |
class_probs |
Numeric vector or NULL. Probability of each class. Must
sum to 1 and have length |
seed |
Integer or NULL. Random seed for reproducibility. Default: NULL. |
The function generates a random social network edge list with:
Nodes named using diverse global names (or custom names)
Random edges between nodes
Weights uniformly distributed in the specified range
Class assignments based on specified probabilities
For undirected networks, each edge appears once (no duplicate A-B, B-A pairs).
A data frame with columns:
Character. Name of the source node.
Character. Name of the target node.
Numeric. Edge weight in the specified range.
Integer. Class assignment (1 to n_classes).
GLOBAL_NAMES, get_global_names
# Basic usage with defaults edges <- simulate_edge_list(seed = 42) head(edges) # Larger network with 5 classes edges <- simulate_edge_list( n_nodes = 50, n_classes = 5, edge_density = 4, seed = 123 ) # Custom names and specific number of edges edges <- simulate_edge_list( n_nodes = 10, n_edges = 30, names = c("Alice", "Bob", "Carol", "Dave", "Eve", "Frank", "Grace", "Hank", "Ivy", "Jack"), n_classes = 2, seed = 42 ) # Undirected network with unequal class distribution edges <- simulate_edge_list( n_nodes = 30, directed = FALSE, n_classes = 3, class_probs = c(0.5, 0.3, 0.2), seed = 42 ) # View class distribution table(edges$class)# Basic usage with defaults edges <- simulate_edge_list(seed = 42) head(edges) # Larger network with 5 classes edges <- simulate_edge_list( n_nodes = 50, n_classes = 5, edge_density = 4, seed = 123 ) # Custom names and specific number of edges edges <- simulate_edge_list( n_nodes = 10, n_edges = 30, names = c("Alice", "Bob", "Carol", "Dave", "Eve", "Frank", "Grace", "Hank", "Ivy", "Jack"), n_classes = 2, seed = 42 ) # Undirected network with unequal class distribution edges <- simulate_edge_list( n_nodes = 30, directed = FALSE, n_classes = 3, class_probs = c(0.5, 0.3, 0.2), seed = 42 ) # View class distribution table(edges$class)
Generate multivariate normal data from an explicit factor model
for factor analysis parameter recovery testing. The implied covariance
matrix is fully specified and
stored in the return value for direct comparison with estimated covariances.
simulate_fa(loadings, phi = NULL, psi = NULL, n, seed = NULL)simulate_fa(loadings, phi = NULL, psi = NULL, n, seed = NULL)
loadings |
Numeric matrix of dimension |
phi |
Numeric matrix of dimension |
psi |
Numeric vector of length |
n |
Positive integer. Sample size. |
seed |
Integer or NULL. Random seed. |
A named list with elements:
datadata.frame with columns y1...yp.
paramslist with loadings, phi, psi,
and sigma_implied (the model-implied covariance
matrix).
# Two orthogonal factors, 6 indicators (3 per factor) loadings <- matrix(c(0.8, 0.7, 0.6, 0, 0, 0, 0, 0, 0, 0.8, 0.7, 0.6), nrow = 6, ncol = 2) # byrow = FALSE (default) r <- simulate_fa(loadings = loadings, n = 500, seed = 1) r$data # data.frame: y1..y6 r$params$sigma_implied # implied covariance matrix # Oblique model phi <- matrix(c(1, 0.4, 0.4, 1), nrow = 2) r2 <- simulate_fa(loadings = loadings, phi = phi, n = 500, seed = 1)# Two orthogonal factors, 6 indicators (3 per factor) loadings <- matrix(c(0.8, 0.7, 0.6, 0, 0, 0, 0, 0, 0, 0.8, 0.7, 0.6), nrow = 6, ncol = 2) # byrow = FALSE (default) r <- simulate_fa(loadings = loadings, n = 500, seed = 1) r$data # data.frame: y1..y6 r$params$sigma_implied # implied covariance matrix # Oblique model phi <- matrix(c(1, 0.4, 0.4, 1), nrow = 2) r2 <- simulate_fa(loadings = loadings, phi = phi, n = 500, seed = 1)
Simulate group TNA network objects (fitted group_tna models) for simulation studies with grouped/clustered data. Each network contains multiple groups (e.g., classrooms, teams) with their own transition patterns.
simulate_group_tna_networks( n_groups = 5, n_actors = 10, n_states = 8, seq_length_range = c(10, 30), use_learning_states = TRUE, categories = NULL, seed = NULL, verbose = TRUE, actors_per_group = NULL, min_seq_length = NULL, max_seq_length = NULL, learning_categories = NULL, ... ) generate_group_tna_networks(...)simulate_group_tna_networks( n_groups = 5, n_actors = 10, n_states = 8, seq_length_range = c(10, 30), use_learning_states = TRUE, categories = NULL, seed = NULL, verbose = TRUE, actors_per_group = NULL, min_seq_length = NULL, max_seq_length = NULL, learning_categories = NULL, ... ) generate_group_tna_networks(...)
n_groups |
Integer. Number of groups in the network. Default: 5. |
n_actors |
Integer or integer vector. Number of actors per group.
Accepts: single integer (fixed size), two integers like |
n_states |
Integer. Number of states/actions in the network. Default: 5. |
seq_length_range |
Integer vector of length 2. Range for sequence lengths per actor (min, max). Default: c(10, 30). |
use_learning_states |
Logical. If TRUE, uses learning action verbs as state names. Default: TRUE. |
categories |
Character vector or NULL. Which categories of learning verbs to use. Options: "metacognitive", "cognitive", "behavioral", "social", "motivational", "affective", "group_regulation", or "all". If NULL (default), randomly selects one category. |
seed |
Integer or NULL. Random seed for reproducibility. Default: NULL. |
verbose |
Logical. If TRUE, prints progress messages. Default: TRUE. |
actors_per_group |
Deprecated. Use |
min_seq_length |
Deprecated. Use |
max_seq_length |
Deprecated. Use |
learning_categories |
Deprecated. Use |
... |
Arguments passed to |
This function generates a single group TNA network with multiple groups.
It simulates long-format sequence data with group structure, converts it
to wide format, and fits a group TNA model using tna::group_model().
Use Cases:
Simulating classroom-level learning behavior data
Generating team collaboration sequences
Creating multi-group datasets for method comparison
A group_tna model object (class "group_tna") containing:
List of TNA networks, one per group
The underlying wide-format data
The grouping variable name
simulate_tna_networks for individual TNA models,
simulate_long_data for generating long-format group data,
fit_network_model for model fitting.
## Not run: # Generate a group TNA network with 4 groups, 15 actors each group_net <- simulate_group_tna_networks( n_groups = 4, n_actors = 15, n_states = 5, seed = 42 ) # Variable group sizes using range notation var_net <- simulate_group_tna_networks( n_groups = 5, n_actors = c(8, 15), seq_length_range = c(5, 25), seed = 123 ) # With specific learning category ssrl_net <- simulate_group_tna_networks( n_groups = 6, n_actors = c(10, 20), categories = "group_regulation", seed = 456 ) # Access individual group networks names(group_net) group_net[[1]]$weights # Old parameter names still work group_net <- simulate_group_tna_networks( actors_per_group = 10, min_seq_length = 5, max_seq_length = 20, seed = 42 ) ## End(Not run)## Not run: # Generate a group TNA network with 4 groups, 15 actors each group_net <- simulate_group_tna_networks( n_groups = 4, n_actors = 15, n_states = 5, seed = 42 ) # Variable group sizes using range notation var_net <- simulate_group_tna_networks( n_groups = 5, n_actors = c(8, 15), seq_length_range = c(5, 25), seed = 123 ) # With specific learning category ssrl_net <- simulate_group_tna_networks( n_groups = 6, n_actors = c(10, 20), categories = "group_regulation", seed = 456 ) # Access individual group networks names(group_net) group_net[[1]]$weights # Old parameter names still work group_net <- simulate_group_tna_networks( actors_per_group = 10, min_seq_length = 5, max_seq_length = 20, seed = 42 ) ## End(Not run)
Generate longitudinal data from a linear latent growth-curve model. Each subject draws a random intercept and slope from a bivariate normal with specified means, standard deviations, and correlation, then
with time coded 0..(n_time - 1). The result is returned in
long format. Designed so that the mean per-subject slope recovers
slope_mean and the spread of per-subject intercepts recovers
intercept_sd at large n.
simulate_growth( n = 200, n_time = 5, intercept_mean = 0, slope_mean = 1, intercept_sd = 1, slope_sd = 0.5, intercept_slope_cor = 0, residual_sd = 1, seed = NULL )simulate_growth( n = 200, n_time = 5, intercept_mean = 0, slope_mean = 1, intercept_sd = 1, slope_sd = 0.5, intercept_slope_cor = 0, residual_sd = 1, seed = NULL )
n |
Integer. Number of subjects. Default: 200. |
n_time |
Integer >= 2. Number of measurement occasions per subject. Default: 5. |
intercept_mean |
Numeric. Mean of subject intercepts |
slope_mean |
Numeric. Mean of subject slopes |
intercept_sd |
Positive numeric. Standard deviation of subject intercepts. Default: 1. |
slope_sd |
Positive numeric. Standard deviation of subject slopes. Default: 0.5. |
intercept_slope_cor |
Numeric in |
residual_sd |
Positive numeric. Level-1 (occasion) residual standard
deviation |
seed |
Integer or NULL. Random seed. |
A saqr_sim object with:
$datalong-format data.frame with columns subject
(factor), time (numeric, 0..n_time-1), and y
(numeric).
$paramslist with means (intercept/slope),
sds (intercept/slope), correlation, residual_sd,
n_time, subject_intercepts (true ), and
subject_slopes (true ).
r <- simulate_growth(n = 300, n_time = 6, slope_mean = 2, intercept_sd = 1.5, seed = 1) print(r) head(r) # Correlated intercepts and slopes r2 <- simulate_growth(n = 250, intercept_slope_cor = 0.5, seed = 42) r2$params$correlationr <- simulate_growth(n = 300, n_time = 6, slope_mean = 2, intercept_sd = 1.5, seed = 1) print(r) head(r) # Correlated intercepts and slopes r2 <- simulate_growth(n = 250, intercept_slope_cor = 0.5, seed = 42) r2$params$correlation
Generate observed symbol sequences from a discrete hidden
Markov model (HMM). For each sequence a latent state path is drawn from
the Markov chain defined by init (initial distribution) and
trans (state transition matrix); each hidden state then emits an
observed symbol according to the emission matrix. The true latent
paths are returned in $params$hidden_paths for parameter-recovery
testing.
simulate_hmm( n_sequences = 50, seq_length = 30, n_states = 2, n_symbols = 3, trans = NULL, emission = NULL, init = NULL, seed = NULL )simulate_hmm( n_sequences = 50, seq_length = 30, n_states = 2, n_symbols = 3, trans = NULL, emission = NULL, init = NULL, seed = NULL )
n_sequences |
Integer. Number of sequences to simulate. Default: 50. |
seq_length |
Integer. Length (number of time points) of each sequence. Default: 30. |
n_states |
Integer. Number of hidden states. Default: 2. |
n_symbols |
Integer. Number of observable symbols. Default: 3. |
trans |
Numeric matrix ( |
emission |
Numeric matrix ( |
init |
Numeric vector (length |
seed |
Integer or NULL. Random seed. |
The within-sequence latent recursion is inherently sequential and
is implemented with Reduce(..., accumulate = TRUE) over the time
index; the work across sequences is vectorised with Map/vapply.
A saqr_sim object with:
$datalong-format data.frame with columns
sequence_id (integer), time (integer, 1...seq_length),
and symbol (integer observed symbol in 1...n_symbols).
$paramslist with trans, emission,
init, n_states, n_symbols, and
hidden_paths (an n_sequences x seq_length integer matrix
of the TRUE latent state sequences).
r <- simulate_hmm(n_sequences = 100, seq_length = 40, seed = 1) print(r) r$params$trans r$params$emission head(as.data.frame(r)) # Explicit three-state model tr <- matrix(c(0.8, 0.1, 0.1, 0.1, 0.8, 0.1, 0.1, 0.1, 0.8), nrow = 3, byrow = TRUE) em <- matrix(c(0.7, 0.2, 0.1, 0.1, 0.7, 0.2, 0.2, 0.1, 0.7), nrow = 3, byrow = TRUE) r2 <- simulate_hmm(n_sequences = 80, seq_length = 50, n_states = 3, n_symbols = 3, trans = tr, emission = em, seed = 42) summary(r2)r <- simulate_hmm(n_sequences = 100, seq_length = 40, seed = 1) print(r) r$params$trans r$params$emission head(as.data.frame(r)) # Explicit three-state model tr <- matrix(c(0.8, 0.1, 0.1, 0.1, 0.8, 0.1, 0.1, 0.1, 0.8), nrow = 3, byrow = TRUE) em <- matrix(c(0.7, 0.2, 0.1, 0.1, 0.7, 0.2, 0.2, 0.1, 0.7), nrow = 3, byrow = TRUE) r2 <- simulate_hmm(n_sequences = 80, seq_length = 50, n_states = 3, n_symbols = 3, trans = tr, emission = em, seed = 42) summary(r2)
Generate a transition matrix with multiple node types for hierarchical (HTNA), multilevel (MLNA), or multi-type (MTNA) network analysis. By default creates a 25-node matrix (5 nodes x 5 types) using learning category names.
simulate_htna(), simulate_mlna(), and simulate_mtna() are aliases that
produce identical output - use whichever name fits your analysis context.
simulate_htna( n_nodes = 5, n_types = 5, type_names = c("Metacognitive", "Cognitive", "Behavioral", "Social", "Motivational"), within_prob = 0.4, between_prob = 0.15, weight_range = c(0, 1), allow_self_loops = FALSE, categories = c("metacognitive", "cognitive", "behavioral", "social", "motivational"), seed = NULL ) simulate_mlna( n_nodes = 5, n_types = 5, type_names = c("Metacognitive", "Cognitive", "Behavioral", "Social", "Motivational"), within_prob = 0.4, between_prob = 0.15, weight_range = c(0, 1), allow_self_loops = FALSE, categories = c("metacognitive", "cognitive", "behavioral", "social", "motivational"), seed = NULL ) simulate_mtna( n_nodes = 5, n_types = 5, type_names = c("Metacognitive", "Cognitive", "Behavioral", "Social", "Motivational"), within_prob = 0.4, between_prob = 0.15, weight_range = c(0, 1), allow_self_loops = FALSE, categories = c("metacognitive", "cognitive", "behavioral", "social", "motivational"), seed = NULL )simulate_htna( n_nodes = 5, n_types = 5, type_names = c("Metacognitive", "Cognitive", "Behavioral", "Social", "Motivational"), within_prob = 0.4, between_prob = 0.15, weight_range = c(0, 1), allow_self_loops = FALSE, categories = c("metacognitive", "cognitive", "behavioral", "social", "motivational"), seed = NULL ) simulate_mlna( n_nodes = 5, n_types = 5, type_names = c("Metacognitive", "Cognitive", "Behavioral", "Social", "Motivational"), within_prob = 0.4, between_prob = 0.15, weight_range = c(0, 1), allow_self_loops = FALSE, categories = c("metacognitive", "cognitive", "behavioral", "social", "motivational"), seed = NULL ) simulate_mtna( n_nodes = 5, n_types = 5, type_names = c("Metacognitive", "Cognitive", "Behavioral", "Social", "Motivational"), within_prob = 0.4, between_prob = 0.15, weight_range = c(0, 1), allow_self_loops = FALSE, categories = c("metacognitive", "cognitive", "behavioral", "social", "motivational"), seed = NULL )
n_nodes |
Integer. Number of nodes per type. Default: 5. |
n_types |
Integer. Number of node types. Default: 5. |
type_names |
Character vector. Names for node types. Default uses learning categories: "Metacognitive", "Cognitive", "Behavioral", "Social", "Motivational". |
within_prob |
Numeric. Probability of edges within each type. Default: 0.4. |
between_prob |
Numeric. Probability of edges between types. Default: 0.15. |
weight_range |
Numeric vector of length 2. Range for edge weights. Default: c(0, 1). |
allow_self_loops |
Logical. Allow diagonal entries. Default: FALSE. |
categories |
Character vector. Learning state categories for node names. Can be single (same for all types) or one per type. Default: matches type_names. |
seed |
Integer or NULL. Random seed. Default: NULL. |
A list containing:
Numeric transition matrix (rows sum to 1).
Named list mapping type names to node names (for plot_htna/plot_mlna).
Character vector of type names.
Integer vector of node counts per type.
simulate_matrix, simulate_tna_matrix
# Default: 5 types x 5 nodes = 25 node matrix net <- simulate_htna(seed = 42) net$matrix net$node_types # List format for plot_htna/plot_mlna # Custom number of types net <- simulate_htna(n_nodes = 4, n_types = 3, seed = 42) # Custom type names net <- simulate_mlna( n_nodes = 6, type_names = c("Macro", "Meso", "Micro"), seed = 42 ) # Use with tna package: # plot_htna(net$matrix, net$node_types, layout = "polygon") # plot_mlna(net$matrix, layers = net$node_types)# Default: 5 types x 5 nodes = 25 node matrix net <- simulate_htna(seed = 42) net$matrix net$node_types # List format for plot_htna/plot_mlna # Custom number of types net <- simulate_htna(n_nodes = 4, n_types = 3, seed = 42) # Custom type names net <- simulate_mlna( n_nodes = 6, type_names = c("Macro", "Meso", "Micro"), seed = 42 ) # Use with tna package: # plot_htna(net$matrix, net$node_types, layout = "polygon") # plot_mlna(net$matrix, layers = net$node_types)
Generate an igraph network object using common graph algorithms with realistic node names from human names or learning states.
simulate_igraph( n = NULL, model = c("er", "ba", "ws", "sbm", "reg", "grg", "ff"), name_source = c("human", "states"), regions = "all", categories = "all", names = NULL, directed = FALSE, weighted = FALSE, weights = c(0.1, 1), p = 0.1, m = NULL, power = 1, m_ba = 2, nei = 2, p_rewire = 0.05, blocks = 3, p_within = 0.3, p_between = 0.05, k = 4, radius = 0.25, fw = 0.35, bw = 0.32, seed = NULL )simulate_igraph( n = NULL, model = c("er", "ba", "ws", "sbm", "reg", "grg", "ff"), name_source = c("human", "states"), regions = "all", categories = "all", names = NULL, directed = FALSE, weighted = FALSE, weights = c(0.1, 1), p = 0.1, m = NULL, power = 1, m_ba = 2, nei = 2, p_rewire = 0.05, blocks = 3, p_within = 0.3, p_between = 0.05, k = 4, radius = 0.25, fw = 0.35, bw = 0.32, seed = NULL )
n |
Integer or NULL. Number of nodes. If NULL (default), randomly selects between 20-50 nodes. |
model |
Character. Graph generation algorithm:
Default: "er". |
name_source |
Character. Source for node names:
Default: "human". |
regions |
Character vector. Regions to sample human names from (only used
when name_source = "human"). Can be specific regions (e.g., "arab", "east_asia"),
shortcuts (e.g., "europe", "africa", "asia"), or "all". See |
categories |
Character vector. Learning state categories (only used when name_source = "states"). Options: "metacognitive", "cognitive", "behavioral", "social", "motivational", "affective", "group_regulation", "lms", or "all". Default: "all". |
names |
Character vector or NULL. Custom node names. Overrides name_source if provided. Default: NULL. |
directed |
Logical. If TRUE, generate directed network. Default: FALSE. |
weighted |
Logical. If TRUE, add random edge weights. Default: FALSE. |
weights |
Numeric vector of length 2. Weight range [min, max]. Default: c(0.1, 1.0). |
p |
Numeric. Edge probability for Erdos-Renyi model. Default: 0.1. |
m |
Integer or NULL. Fixed number of edges for Erdos-Renyi. Overrides p if provided. Default: NULL. |
power |
Numeric. Attachment power for Barabasi-Albert. Default: 1. |
m_ba |
Integer. Edges per new vertex for Barabasi-Albert. Default: 2. |
nei |
Integer. Neighborhood size for Watts-Strogatz. Default: 2. |
p_rewire |
Numeric. Rewiring probability for Watts-Strogatz. Default: 0.05. |
blocks |
Integer. Number of blocks for SBM. Default: 3. |
p_within |
Numeric. Within-block edge probability for SBM. Default: 0.3. |
p_between |
Numeric. Between-block edge probability for SBM. Default: 0.05. |
k |
Integer. Degree for regular graphs. Default: 4. |
radius |
Numeric. Connection radius for geometric random graph. Default: 0.25. |
fw |
Numeric. Forward burning probability for Forest Fire. Default: 0.35. |
bw |
Numeric. Backward burning factor for Forest Fire. Default: 0.32. |
seed |
Integer or NULL. Random seed for reproducibility. Default: NULL. |
This function wraps igraph's graph generation algorithms and adds:
Meaningful node names (human names or learning states)
Optional edge weights
Block/community attributes for SBM
The generated networks are suitable for social network analysis, teaching network concepts, or testing TNA methods.
An igraph object with vertex names and optional edge weights.
simulate_network for statnet network objects,
simulate_matrix for adjacency matrices,
simulate_tna_network for fitted TNA models.
library(igraph) # Default: Erdos-Renyi with human names from all regions g <- simulate_igraph(n = 15, seed = 42) V(g)$name # Diverse names like "Yuki", "Omar", "Priya" plot(g) # Names from specific regions g_arab <- simulate_igraph(n = 15, regions = "arab", seed = 42) V(g_arab)$name # Arab names g_africa <- simulate_igraph(n = 20, regions = "africa", seed = 42) V(g_africa)$name # African names from all sub-regions # Use learning state names instead g_states <- simulate_igraph(n = 10, name_source = "states", seed = 42) V(g_states)$name # Action verbs like "Plan", "Monitor", "Evaluate" # Scale-free network (Barabasi-Albert) g_sf <- simulate_igraph(n = 50, model = "ba", m_ba = 2, seed = 42) degree_distribution(g_sf) # Small-world network (Watts-Strogatz) g_sw <- simulate_igraph(n = 30, model = "ws", nei = 4, p_rewire = 0.1, seed = 42) # Community structure (Stochastic Block Model) g_sbm <- simulate_igraph(n = 30, model = "sbm", blocks = 3, p_within = 0.5, p_between = 0.05, seed = 42) V(g_sbm)$block # Community assignments # Weighted network with custom names g_custom <- simulate_igraph( n = 10, model = "er", weighted = TRUE, names = c("Alice", "Bob", "Carol", "Dave", "Eve", "Frank", "Grace", "Heidi", "Ivan", "Judy"), seed = 42 ) E(g_custom)$weightlibrary(igraph) # Default: Erdos-Renyi with human names from all regions g <- simulate_igraph(n = 15, seed = 42) V(g)$name # Diverse names like "Yuki", "Omar", "Priya" plot(g) # Names from specific regions g_arab <- simulate_igraph(n = 15, regions = "arab", seed = 42) V(g_arab)$name # Arab names g_africa <- simulate_igraph(n = 20, regions = "africa", seed = 42) V(g_africa)$name # African names from all sub-regions # Use learning state names instead g_states <- simulate_igraph(n = 10, name_source = "states", seed = 42) V(g_states)$name # Action verbs like "Plan", "Monitor", "Evaluate" # Scale-free network (Barabasi-Albert) g_sf <- simulate_igraph(n = 50, model = "ba", m_ba = 2, seed = 42) degree_distribution(g_sf) # Small-world network (Watts-Strogatz) g_sw <- simulate_igraph(n = 30, model = "ws", nei = 4, p_rewire = 0.1, seed = 42) # Community structure (Stochastic Block Model) g_sbm <- simulate_igraph(n = 30, model = "sbm", blocks = 3, p_within = 0.5, p_between = 0.05, seed = 42) V(g_sbm)$block # Community assignments # Weighted network with custom names g_custom <- simulate_igraph( n = 10, model = "er", weighted = TRUE, names = c("Alice", "Bob", "Carol", "Dave", "Eve", "Frank", "Grace", "Heidi", "Ivan", "Judy"), seed = 42 ) E(g_custom)$weight
Generate item-response data under a known IRT model with
ground-truth item and person parameters. Supports the 1PL (Rasch), 2PL,
3PL dichotomous models and the graded response model (GRM) for ordered
polytomous items. Designed so that, at large n_persons, item
proportion-correct recovers item difficulty (negatively) and person total
score recovers true ability (positively).
Response probabilities are computed for the whole person-by-item grid in
one vectorised pass (outer() / matrix ops) and responses are drawn
with a single comparison against a uniform random matrix – no loops.
simulate_irt( n_persons = 500, n_items = 20, model = c("2PL", "1PL", "3PL", "GRM"), n_categories = 2, a = NULL, b = NULL, c = NULL, theta = NULL, seed = NULL )simulate_irt( n_persons = 500, n_items = 20, model = c("2PL", "1PL", "3PL", "GRM"), n_categories = 2, a = NULL, b = NULL, c = NULL, theta = NULL, seed = NULL )
n_persons |
Integer. Number of persons (rows). Default: 500. |
n_items |
Integer. Number of items (columns). Default: 20. |
model |
Character. One of |
n_categories |
Integer. Number of response categories. Must be 2 for
the dichotomous models (1PL/2PL/3PL) and |
a |
Numeric vector of length |
b |
Numeric vector of length |
c |
Numeric vector of length |
theta |
Numeric vector of length |
seed |
Integer or NULL. Random seed. |
A saqr_sim object with:
$datadata.frame with n_persons rows and columns
item1...itemJ. Values are 0/1 for dichotomous
models and 0...n_categories - 1 for GRM.
$paramslist with model, a, b,
c (as used), theta (true abilities), thresholds
(GRM category thresholds matrix, NULL otherwise), and
n_categories.
# 2PL with default auto-generated parameters fit <- simulate_irt(n_persons = 500, n_items = 20, model = "2PL", seed = 1) print(fit) fit$params$b # Recover difficulty: easier items are answered correctly more often prop_correct <- colMeans(as.data.frame(fit)) cor(prop_correct, fit$params$b) # strongly negative # Recover ability: higher total score tracks higher true theta total <- rowSums(as.data.frame(fit)) cor(total, fit$params$theta) # strongly positive # Rasch (1PL): discrimination fixed at 1 simulate_irt(n_persons = 300, n_items = 10, model = "1PL", seed = 2) # Graded response model with 4 ordered categories simulate_irt(n_persons = 400, n_items = 8, model = "GRM", n_categories = 4, seed = 3)# 2PL with default auto-generated parameters fit <- simulate_irt(n_persons = 500, n_items = 20, model = "2PL", seed = 1) print(fit) fit$params$b # Recover difficulty: easier items are answered correctly more often prop_correct <- colMeans(as.data.frame(fit)) cor(prop_correct, fit$params$b) # strongly negative # Recover ability: higher total score tracks higher true theta total <- rowSums(as.data.frame(fit)) cor(total, fit$params$theta) # strongly positive # Rasch (1PL): discrimination fixed at 1 simulate_irt(n_persons = 300, n_items = 10, model = "1PL", seed = 2) # Graded response model with 4 ordered categories simulate_irt(n_persons = 400, n_items = 8, model = "GRM", n_categories = 4, seed = 3)
Generate synthetic binary-indicator data with known latent class structure. All item response probabilities are explicitly specified.
simulate_lca(item_probs, class_probs, n, seed = NULL)simulate_lca(item_probs, class_probs, n, seed = NULL)
item_probs |
Numeric matrix of dimension |
class_probs |
Numeric vector of length |
n |
Positive integer. Total sample size. |
seed |
Integer or NULL. Random seed for reproducibility. |
A named list with elements:
datadata.frame with binary columns item1...itemm
and integer column true_class (labels 1...K).
paramslist with item_probs and class_probs
(as supplied, un-normalised).
item_probs <- matrix(c(0.9, 0.1, 0.9, 0.1, 0.1, 0.9, 0.1, 0.9), nrow = 4, ncol = 2) r <- simulate_lca(item_probs = item_probs, class_probs = c(0.5, 0.5), n = 200, seed = 1) r$data # data.frame r$params # ground-truth parametersitem_probs <- matrix(c(0.9, 0.1, 0.9, 0.1, 0.1, 0.9, 0.1, 0.9), nrow = 4, ncol = 2) r <- simulate_lca(item_probs = item_probs, class_probs = c(0.5, 0.5), n = 200, seed = 1) r$data # data.frame r$params # ground-truth parameters
Generate simulated sequence data in long format, matching the structure of
group_regulation_long in the tna package. Creates realistic educational
data with actors nested in groups, groups nested in courses.
simulate_long_data( n_groups = 5, n_actors = 10, n_courses = 3, n_states = 9, states = NULL, use_learning_states = TRUE, categories = "group_regulation", seq_length_range = c(10, 30), achiever_levels = c("High", "Low"), achiever_probs = c(0.5, 0.5), start_time = "2025-01-01 10:00:00", time_interval_range = c(60, 600), trans_matrix = NULL, init_probs = NULL, seed = NULL, actors_per_group = NULL, actions = NULL, action_categories = NULL, n_actions = NULL, transition_probs = NULL, initial_probs = NULL )simulate_long_data( n_groups = 5, n_actors = 10, n_courses = 3, n_states = 9, states = NULL, use_learning_states = TRUE, categories = "group_regulation", seq_length_range = c(10, 30), achiever_levels = c("High", "Low"), achiever_probs = c(0.5, 0.5), start_time = "2025-01-01 10:00:00", time_interval_range = c(60, 600), trans_matrix = NULL, init_probs = NULL, seed = NULL, actors_per_group = NULL, actions = NULL, action_categories = NULL, n_actions = NULL, transition_probs = NULL, initial_probs = NULL )
n_groups |
Integer. Number of groups. Default: 5. |
n_actors |
Integer or integer vector of length 2. If single integer, exact number of actors per group. If vector c(min, max), random sizes in that range. Default: 10. |
n_courses |
Integer or character vector. Number of courses or specific course names (e.g., c("A", "B", "C")). Groups are distributed evenly across courses. Default: 3. |
n_states |
Integer. Number of actions to sample when using categories.
Ignored if |
states |
Character vector. The action/state names to use. If NULL,
uses learning states based on |
use_learning_states |
Logical. If TRUE and |
categories |
Character vector. Categories of learning states
to use when |
seq_length_range |
Integer vector of length 2. Range for sequence lengths per actor (min, max). Default: c(10, 30). |
achiever_levels |
Character vector. Levels for the Achiever variable. Default: c("High", "Low"). |
achiever_probs |
Numeric vector. Probabilities for each achiever level. Must sum to 1. Default: c(0.5, 0.5). |
start_time |
POSIXct or character. Start time for timestamps. Default: "2025-01-01 10:00:00". |
time_interval_range |
Numeric vector of length 2. Range for time intervals between actions in seconds (min, max). Default: c(60, 600). |
trans_matrix |
Matrix or NULL. Custom transition probability matrix. If NULL, generates random probabilities. Default: NULL. |
init_probs |
Numeric vector or NULL. Custom initial probabilities. If NULL, generates random probabilities. Default: NULL. |
seed |
Integer or NULL. Random seed for reproducibility. Default: NULL. |
actors_per_group |
Deprecated. Use |
actions |
Deprecated. Use |
action_categories |
Deprecated. Use |
n_actions |
Deprecated. Use |
transition_probs |
Deprecated. Use |
initial_probs |
Deprecated. Use |
The data structure follows a nested hierarchy:
Courses contain multiple Groups
Groups contain multiple Actors (e.g., 10 per group)
Actors have multiple Actions over time
This matches the structure of group_regulation_long from the tna package:
Each group has a fixed number of actors
Groups are distributed across courses
Actors within a group share the same course
Built-in Group Regulation Actions: When categories = "group_regulation",
uses the 9 SSRL (Socially Shared Regulation of Learning) actions:
adapt, cohesion, consensus, coregulate, discuss, emotion, monitor, plan, synthesis.
A tibble (data frame) with columns:
Integer. Actor identifier (1 to n_actors).
Character. Achievement level (e.g., "High", "Low").
Numeric. Group identifier (1 to n_groups).
Character. Course identifier.
POSIXct. Timestamp of the action.
Character. The action/state performed.
simulate_onehot_data for one-hot encoded format,
simulate_sequences for generating wide-format sequences,
get_learning_states for available learning states,
simulate_tna_networks for generating TNA network objects.
## Not run: # Basic usage: 5 groups, 10 actors each, 3 courses (new defaults) data <- simulate_long_data(seed = 42) # Explicit new parameter names data <- simulate_long_data( n_groups = 10, n_actors = 15, n_states = 6, categories = c("metacognitive", "cognitive"), seq_length_range = c(15, 40), seed = 42 ) # Check structure length(unique(data$Actor)) # 50 actors length(unique(data$Group)) # 5 groups table(table(data$Actor, data$Group) > 0) # 10 actors per group # Variable group sizes data <- simulate_long_data( n_groups = 30, n_actors = c(8, 12), states = c("Read", "Write", "Discuss", "Plan", "Review"), seed = 456 ) # Using specific learning state categories data <- simulate_long_data( n_groups = 50, n_actors = 10, categories = c("metacognitive", "cognitive"), n_states = 8, seed = 789 ) # Old parameter names still work (backward compatible) data <- simulate_long_data( actors_per_group = 10, actions = c("A", "B", "C"), seed = 42 ) ## End(Not run)## Not run: # Basic usage: 5 groups, 10 actors each, 3 courses (new defaults) data <- simulate_long_data(seed = 42) # Explicit new parameter names data <- simulate_long_data( n_groups = 10, n_actors = 15, n_states = 6, categories = c("metacognitive", "cognitive"), seq_length_range = c(15, 40), seed = 42 ) # Check structure length(unique(data$Actor)) # 50 actors length(unique(data$Group)) # 5 groups table(table(data$Actor, data$Group) > 0) # 10 actors per group # Variable group sizes data <- simulate_long_data( n_groups = 30, n_actors = c(8, 12), states = c("Read", "Write", "Discuss", "Plan", "Review"), seed = 456 ) # Using specific learning state categories data <- simulate_long_data( n_groups = 50, n_actors = 10, categories = c("metacognitive", "cognitive"), n_states = 8, seed = 789 ) # Old parameter names still work (backward compatible) data <- simulate_long_data( actors_per_group = 10, actions = c("A", "B", "C"), seed = 42 ) ## End(Not run)
Generate synthetic multilevel time-series data suitable for testing longitudinal models: multilevel VAR (mlVAR), random-intercept cross-lagged panel models (RI-CLPM), latent growth curves, and similar.
The data-generating process is a VAR(1) model with three layers:
Autoregressive and cross-lagged effects via matrix
B. At each time point, y(t) = mu_i + B (y(t-1) - mu_i)
+ innovation.
Within-time correlations among innovations, given
by the Cholesky of contemporaneous.
Person-specific means mu_i drawn from
N(grand_means, between).
simulate_longitudinal( n = 50L, tp = 50L, vars = 4L, temporal = NULL, contemporaneous = NULL, between = NULL, grand_means = NULL, innovation_sd = 1, beeps_per_day = NULL, ar_range = c(0.2, 0.5), cross_range = c(0.05, 0.2), n_cross = NULL, complexity = "clean", seed = NULL )simulate_longitudinal( n = 50L, tp = 50L, vars = 4L, temporal = NULL, contemporaneous = NULL, between = NULL, grand_means = NULL, innovation_sd = 1, beeps_per_day = NULL, ar_range = c(0.2, 0.5), cross_range = c(0.05, 0.2), n_cross = NULL, complexity = "clean", seed = NULL )
n |
Integer. Number of subjects (persons). Default 50. |
tp |
Integer. Number of time points per subject. Default 50. |
vars |
Integer or character vector. If integer, the number of
variables (named |
temporal |
Numeric matrix ( |
contemporaneous |
Numeric matrix ( |
between |
Numeric matrix ( |
grand_means |
Numeric vector of length |
innovation_sd |
Numeric scalar or vector of length |
beeps_per_day |
Integer or NULL. If non-NULL, adds |
ar_range |
Numeric vector of length 2. When |
cross_range |
Numeric vector of length 2. When |
n_cross |
Integer. When |
complexity |
Character. Edge-case injection, same semantics as
|
seed |
Integer or NULL. Random seed. |
The temporal matrix B must be stationary (all eigenvalues inside the
unit circle). If an auto-generated or user-supplied B violates this,
it is rescaled by 0.95 / max(Mod(eigen(B)$values)).
For ESM-style data with beeps_per_day, the first observation of each
day is treated as a new starting point (no carry-over from previous day's
last beep), matching the assumption in most ESM-VAR software.
A saqr_sim object with:
$datadata.frame with columns id, time
(or day/beep), and V1...Vp.
$paramslist with temporal (B matrix),
contemporaneous (innovation correlation),
between (person-mean covariance), grand_means,
innovation_sd, n, tp, var_names.
# Basic: 30 subjects, 60 time points, 3 variables r <- simulate_longitudinal(n = 30, tp = 60, vars = 3, seed = 42) head(r$data) r$params$temporal # the true VAR(1) matrix # Explicit temporal structure B <- matrix(c(0.4, 0.0, 0.1, 0.2, 0.3, 0.0, 0.0, -0.1, 0.5), nrow = 3, byrow = TRUE) r2 <- simulate_longitudinal(n = 50, tp = 100, vars = 3, temporal = B, seed = 1) # ESM structure with days and beeps r3 <- simulate_longitudinal(n = 40, tp = 70, vars = 4, beeps_per_day = 7, seed = 7) head(r3$data) # has day + beep columns # With edge-case injection r4 <- simulate_longitudinal(n = 30, tp = 50, vars = 3, complexity = c("na", "outliers"), seed = 5)# Basic: 30 subjects, 60 time points, 3 variables r <- simulate_longitudinal(n = 30, tp = 60, vars = 3, seed = 42) head(r$data) r$params$temporal # the true VAR(1) matrix # Explicit temporal structure B <- matrix(c(0.4, 0.0, 0.1, 0.2, 0.3, 0.0, 0.0, -0.1, 0.5), nrow = 3, byrow = TRUE) r2 <- simulate_longitudinal(n = 50, tp = 100, vars = 3, temporal = B, seed = 1) # ESM structure with days and beeps r3 <- simulate_longitudinal(n = 40, tp = 70, vars = 4, beeps_per_day = 7, seed = 7) head(r3$data) # has day + beep columns # With edge-case injection r4 <- simulate_longitudinal(n = 30, tp = 50, vars = 3, complexity = c("na", "outliers"), seed = 5)
Generate synthetic continuous-indicator data with known latent profile structure. All distributional parameters are explicitly specified so that parameter recovery can be verified in tests.
simulate_lpa(means, sds, props, n, seed = NULL)simulate_lpa(means, sds, props, n, seed = NULL)
means |
Numeric matrix of dimension |
sds |
Numeric matrix of dimension |
props |
Numeric vector of length |
n |
Positive integer. Total sample size. |
seed |
Integer or NULL. Random seed for reproducibility. |
A named list with elements:
datadata.frame with columns y1...yp and
true_profile (integer 1...K).
paramslist with means, sds (full matrix),
and props (as supplied, un-normalised).
means <- matrix(c(0, 0, 10, 10), nrow = 2, ncol = 2) r <- simulate_lpa(means = means, sds = 0.5, props = c(0.5, 0.5), n = 200, seed = 1) r$data # data.frame r$params # ground-truth parametersmeans <- matrix(c(0, 0, 10, 10), nrow = 2, ncol = 2) r <- simulate_lpa(means = means, sds = 0.5, props = c(0.5, 0.5), n = 200, seed = 1) r$data # data.frame r$params # ground-truth parameters
Generate a simple transition matrix for TNA/Markov network analysis. Each call randomly selects a learning category for node names.
simulate_matrix( n_nodes = 9, matrix_type = c("transition", "frequency", "co-occurrence", "adjacency"), edge_prob = 0.3, weighted = TRUE, weight_range = c(0, 1), directed = TRUE, allow_self_loops = FALSE, names = NULL, seed = NULL )simulate_matrix( n_nodes = 9, matrix_type = c("transition", "frequency", "co-occurrence", "adjacency"), edge_prob = 0.3, weighted = TRUE, weight_range = c(0, 1), directed = TRUE, allow_self_loops = FALSE, names = NULL, seed = NULL )
n_nodes |
Integer. Number of nodes. Default: 9. |
matrix_type |
Character. Type of matrix to generate:
Default: "transition". |
edge_prob |
Numeric. Probability of edges existing. Default: 0.3. |
weighted |
Logical. If TRUE, generates weighted edges. Default: TRUE. |
weight_range |
Numeric vector of length 2. Range for edge weights. Default: c(0, 1). |
directed |
Logical. If TRUE, generates directed matrix. Default: TRUE. |
allow_self_loops |
Logical. If TRUE, allows diagonal entries. Default: FALSE. |
names |
Character vector or NULL. Custom node names. If NULL, randomly selects learning states from a random category. Default: NULL. |
seed |
Integer or NULL. Random seed for reproducibility. Default: NULL. |
This function generates a simple network matrix. Each call randomly picks one learning category (metacognitive, cognitive, behavioral, social, motivational, affective, or group_regulation) and uses verbs from that category as node names.
For matrices with multiple node types, use simulate_htna.
A numeric matrix with row and column names set to learning states.
simulate_htna for multi-type matrices
# Simple 9-node transition matrix mat <- simulate_matrix(seed = 42) mat rowSums(mat) # Rows sum to 1 # Frequency matrix mat <- simulate_matrix(n_nodes = 5, matrix_type = "frequency", seed = 42) # Co-occurrence matrix (symmetric) mat <- simulate_matrix(n_nodes = 6, matrix_type = "co-occurrence", seed = 42) isSymmetric(mat) # TRUE # Custom names mat <- simulate_matrix(n_nodes = 4, names = c("A", "B", "C", "D"), seed = 42)# Simple 9-node transition matrix mat <- simulate_matrix(seed = 42) mat rowSums(mat) # Rows sum to 1 # Frequency matrix mat <- simulate_matrix(n_nodes = 5, matrix_type = "frequency", seed = 42) # Co-occurrence matrix (symmetric) mat <- simulate_matrix(n_nodes = 6, matrix_type = "co-occurrence", seed = 42) isSymmetric(mat) # TRUE # Custom names mat <- simulate_matrix(n_nodes = 4, names = c("A", "B", "C", "D"), seed = 42)
Generate data for a two-level model where level-1 units are nested within clusters. The outcome follows
where the first predictor carries the fixed slope, cluster random
intercepts with
, and (optionally) a
cluster random slope on the
first predictor. Designed so that the intraclass correlation and fixed
slope are recovered at large n_clusters.
simulate_mlm( n_clusters = 30, cluster_size = 20, intercept = 0, slope = 0.5, residual_sd = 1, icc = 0.1, n_predictors = 1, random_slope = FALSE, slope_sd = 0, seed = NULL )simulate_mlm( n_clusters = 30, cluster_size = 20, intercept = 0, slope = 0.5, residual_sd = 1, icc = 0.1, n_predictors = 1, random_slope = FALSE, slope_sd = 0, seed = NULL )
n_clusters |
Integer. Number of level-2 clusters. Default: 30. |
cluster_size |
Integer scalar or integer vector of length
|
intercept |
Numeric. Fixed intercept |
slope |
Numeric. Fixed slope |
residual_sd |
Positive numeric. Level-1 residual standard deviation
|
icc |
Numeric in |
n_predictors |
Integer >= 1. Number of level-1 predictors
( |
random_slope |
Logical. If |
slope_sd |
Non-negative numeric. Standard deviation of the random
slope |
seed |
Integer or NULL. Random seed. |
A saqr_sim object with:
$datadata.frame with columns cluster_id (factor),
y (numeric), and x1..xK (numeric predictors).
$paramslist with intercept, slope,
betas (full fixed-effect vector), icc, tau00,
residual_sd, slope_sd, random_slope,
cluster_size, cluster_intercepts (true ),
and cluster_slopes (true , NULL unless
random_slope).
r <- simulate_mlm(n_clusters = 40, cluster_size = 25, slope = 0.8, icc = 0.2, seed = 1) print(r) r$params$tau00 # Unbalanced clusters with a random slope r2 <- simulate_mlm(n_clusters = 30, cluster_size = sample(10:30, 30, TRUE), random_slope = TRUE, slope_sd = 0.3, seed = 42) summary(r2)r <- simulate_mlm(n_clusters = 40, cluster_size = 25, slope = 0.8, icc = 0.2, seed = 1) print(r) r$params$tau00 # Unbalanced clusters with a random slope r2 <- simulate_mlm(n_clusters = 30, cluster_size = sample(10:30, 30, TRUE), random_slope = TRUE, slope_sd = 0.3, seed = 42) summary(r2)
Generate a statnet network object using common graph algorithms with realistic node names from human names or learning states.
simulate_network( n = NULL, model = c("er", "ba", "ws", "sbm", "reg", "grg", "ff"), name_source = c("human", "states"), regions = "all", categories = "all", names = NULL, directed = FALSE, weighted = FALSE, weights = c(0.1, 1), p = 0.1, m = NULL, power = 1, m_ba = 2, nei = 2, p_rewire = 0.05, blocks = 3, p_within = 0.3, p_between = 0.05, k = 4, radius = 0.25, fw = 0.35, bw = 0.32, seed = NULL )simulate_network( n = NULL, model = c("er", "ba", "ws", "sbm", "reg", "grg", "ff"), name_source = c("human", "states"), regions = "all", categories = "all", names = NULL, directed = FALSE, weighted = FALSE, weights = c(0.1, 1), p = 0.1, m = NULL, power = 1, m_ba = 2, nei = 2, p_rewire = 0.05, blocks = 3, p_within = 0.3, p_between = 0.05, k = 4, radius = 0.25, fw = 0.35, bw = 0.32, seed = NULL )
n |
Integer or NULL. Number of nodes. If NULL (default), randomly selects between 20-50 nodes. |
model |
Character. Graph generation algorithm:
Default: "er". |
name_source |
Character. Source for node names:
Default: "human". |
regions |
Character vector. Regions to sample human names from (only used
when name_source = "human"). Can be specific regions (e.g., "arab", "east_asia"),
shortcuts (e.g., "europe", "africa", "asia"), or "all". See |
categories |
Character vector. Learning state categories (only used when name_source = "states"). Options: "metacognitive", "cognitive", "behavioral", "social", "motivational", "affective", "group_regulation", "lms", or "all". Default: "all". |
names |
Character vector or NULL. Custom node names. Overrides name_source if provided. Default: NULL. |
directed |
Logical. If TRUE, generate directed network. Default: FALSE. |
weighted |
Logical. If TRUE, add random edge weights. Default: FALSE. |
weights |
Numeric vector of length 2. Weight range [min, max]. Default: c(0.1, 1.0). |
p |
Numeric. Edge probability for Erdos-Renyi model. Default: 0.1. |
m |
Integer or NULL. Fixed number of edges for Erdos-Renyi. Overrides p if provided. Default: NULL. |
power |
Numeric. Attachment power for Barabasi-Albert. Default: 1. |
m_ba |
Integer. Edges per new vertex for Barabasi-Albert. Default: 2. |
nei |
Integer. Neighborhood size for Watts-Strogatz. Default: 2. |
p_rewire |
Numeric. Rewiring probability for Watts-Strogatz. Default: 0.05. |
blocks |
Integer. Number of blocks for SBM. Default: 3. |
p_within |
Numeric. Within-block edge probability for SBM. Default: 0.3. |
p_between |
Numeric. Between-block edge probability for SBM. Default: 0.05. |
k |
Integer. Degree for regular graphs. Default: 4. |
radius |
Numeric. Connection radius for geometric random graph. Default: 0.25. |
fw |
Numeric. Forward burning probability for Forest Fire. Default: 0.35. |
bw |
Numeric. Backward burning factor for Forest Fire. Default: 0.32. |
seed |
Integer or NULL. Random seed for reproducibility. Default: NULL. |
This function generates networks using igraph algorithms internally, then converts to statnet's network class. The resulting object is compatible with all sna and network package functions.
Vertex names are stored in the "vertex.names" attribute and can be accessed
with network.vertex.names().
A network object (class "network") with vertex names and optional edge weights.
simulate_igraph for igraph objects,
simulate_matrix for adjacency matrices,
simulate_edge_list for edge list data frames.
## Not run: library(network) library(sna) # Default: Erdos-Renyi with human names net <- simulate_network(n = 20, seed = 42) class(net) # "network" network.vertex.names(net) # Diverse human names # Names from specific regions net_asia <- simulate_network(n = 20, regions = "asia", seed = 42) network.vertex.names(net_asia) # Asian names # Use learning state names instead net_states <- simulate_network(n = 15, name_source = "states", seed = 42) network.vertex.names(net_states) # Action verbs # Scale-free for SNA analysis net_sf <- simulate_network(n = 50, model = "ba", seed = 42) betweenness(net_sf) closeness(net_sf) # Community structure net_sbm <- simulate_network(n = 30, model = "sbm", blocks = 3, seed = 42) # Weighted network net_w <- simulate_network(n = 20, model = "er", weighted = TRUE, seed = 42) net_w %e% "weight" # Edge weights ## End(Not run)## Not run: library(network) library(sna) # Default: Erdos-Renyi with human names net <- simulate_network(n = 20, seed = 42) class(net) # "network" network.vertex.names(net) # Diverse human names # Names from specific regions net_asia <- simulate_network(n = 20, regions = "asia", seed = 42) network.vertex.names(net_asia) # Asian names # Use learning state names instead net_states <- simulate_network(n = 15, name_source = "states", seed = 42) network.vertex.names(net_states) # Action verbs # Scale-free for SNA analysis net_sf <- simulate_network(n = 50, model = "ba", seed = 42) betweenness(net_sf) closeness(net_sf) # Community structure net_sbm <- simulate_network(n = 30, model = "sbm", blocks = 3, seed = 42) # Weighted network net_w <- simulate_network(n = 20, model = "er", weighted = TRUE, seed = 42) net_w %e% "weight" # Edge weights ## End(Not run)
Generate simulated sequence data in one-hot encoded format. Creates the same
hierarchical structure as simulate_long_data (Actor, Achiever,
Group, Course, Time) but with binary 0/1 columns for each state instead of
a categorical Action column.
simulate_onehot_data( n_groups = 5, n_actors = 10, n_courses = 3, n_states = 9, states = NULL, use_learning_states = TRUE, categories = "group_regulation", seq_length_range = c(10, 30), achiever_levels = c("High", "Low"), achiever_probs = c(0.5, 0.5), start_time = "2025-01-01 10:00:00", time_interval_range = c(60, 600), trans_matrix = NULL, init_probs = NULL, sort_states = FALSE, state_prefix = "", seed = NULL, actors_per_group = NULL, actions = NULL, action_categories = NULL, n_actions = NULL, transition_probs = NULL, initial_probs = NULL )simulate_onehot_data( n_groups = 5, n_actors = 10, n_courses = 3, n_states = 9, states = NULL, use_learning_states = TRUE, categories = "group_regulation", seq_length_range = c(10, 30), achiever_levels = c("High", "Low"), achiever_probs = c(0.5, 0.5), start_time = "2025-01-01 10:00:00", time_interval_range = c(60, 600), trans_matrix = NULL, init_probs = NULL, sort_states = FALSE, state_prefix = "", seed = NULL, actors_per_group = NULL, actions = NULL, action_categories = NULL, n_actions = NULL, transition_probs = NULL, initial_probs = NULL )
n_groups |
Integer. Number of groups. Default: 5. |
n_actors |
Integer or integer vector of length 2. If single integer, exact number of actors per group. If vector c(min, max), random sizes in that range. Default: 10. |
n_courses |
Integer or character vector. Number of courses or specific course names (e.g., c("A", "B", "C")). Groups are distributed evenly across courses. Default: 3. |
n_states |
Integer. Number of actions to sample when using categories.
Ignored if |
states |
Character vector. The action/state names to use. If NULL,
uses learning states based on |
use_learning_states |
Logical. If TRUE and |
categories |
Character vector. Categories of learning states
to use when |
seq_length_range |
Integer vector of length 2. Range for sequence lengths per actor (min, max). Default: c(10, 30). |
achiever_levels |
Character vector. Levels for the Achiever variable. Default: c("High", "Low"). |
achiever_probs |
Numeric vector. Probabilities for each achiever level. Must sum to 1. Default: c(0.5, 0.5). |
start_time |
POSIXct or character. Start time for timestamps. Default: "2025-01-01 10:00:00". |
time_interval_range |
Numeric vector of length 2. Range for time intervals between actions in seconds (min, max). Default: c(60, 600). |
trans_matrix |
Matrix or NULL. Custom transition probability matrix. If NULL, generates random probabilities. Default: NULL. |
init_probs |
Numeric vector or NULL. Custom initial probabilities. If NULL, generates random probabilities. Default: NULL. |
sort_states |
Logical. Sort state columns alphabetically. Default: FALSE. |
state_prefix |
Character. Prefix for state column names. Default: "". |
seed |
Integer or NULL. Random seed for reproducibility. Default: NULL. |
actors_per_group |
Deprecated. Use |
actions |
Deprecated. Use |
action_categories |
Deprecated. Use |
n_actions |
Deprecated. Use |
transition_probs |
Deprecated. Use |
initial_probs |
Deprecated. Use |
This function internally calls simulate_long_data to generate
the base data, then applies an internal one-hot helper to convert the
Action column to one-hot encoded columns.
Each row will have exactly one state column with value 1, and all others with value 0, representing the action performed at that time point.
A tibble (data frame) with columns:
Integer. Actor identifier (1 to n_actors).
Character. Achievement level (e.g., "High", "Low").
Numeric. Group identifier (1 to n_groups).
Character. Course identifier.
POSIXct. Timestamp of the action.
Integer (0/1). One column per state, with 1 indicating the active state for that row.
simulate_long_data for categorical Action format,
Nestimate::action_to_onehot() for converting existing long data,
simulate_sequences for generating wide-format sequences.
## Not run: # Basic usage with new standardized params data <- simulate_onehot_data(n_groups = 5, n_actors = 3, seed = 42) head(data) # Custom states with prefix data <- simulate_onehot_data( n_groups = 3, states = c("Read", "Write", "Think"), state_prefix = "state_", seed = 123 ) names(data) # Verify one-hot encoding (each row sums to 1) state_cols <- setdiff(names(data), c("Actor", "Achiever", "Group", "Course", "Time")) all(rowSums(data[, state_cols]) == 1) # TRUE # Old parameter names still work (backward compatible) data <- simulate_onehot_data( actors_per_group = 5, actions = c("A", "B", "C"), seed = 42 ) ## End(Not run)## Not run: # Basic usage with new standardized params data <- simulate_onehot_data(n_groups = 5, n_actors = 3, seed = 42) head(data) # Custom states with prefix data <- simulate_onehot_data( n_groups = 3, states = c("Read", "Write", "Think"), state_prefix = "state_", seed = 123 ) names(data) # Verify one-hot encoding (each row sums to 1) state_cols <- setdiff(names(data), c("Actor", "Achiever", "Group", "Course", "Time")) all(rowSums(data[, state_cols]) == 1) # TRUE # Old parameter names still work (backward compatible) data <- simulate_onehot_data( actors_per_group = 5, actions = c("A", "B", "C"), seed = 42 ) ## End(Not run)
Generate a regression dataset with both continuous and
categorical predictors, a non-linear term, and known ground-truth
coefficients. A richer version of simulate_regression for
testing prediction workflows.
simulate_prediction( n, coefs, cat_levels = NULL, cat_effects = NULL, error_sd = 1, predictor_means = NULL, predictor_sds = NULL, seed = NULL )simulate_prediction( n, coefs, cat_levels = NULL, cat_effects = NULL, error_sd = 1, predictor_means = NULL, predictor_sds = NULL, seed = NULL )
n |
Integer. Sample size. |
coefs |
Named numeric vector. Must include names matching continuous
predictors (e.g. |
cat_levels |
Named list. Each element is a character vector of factor
levels for a categorical predictor. Default: |
cat_effects |
Named list of numeric vectors. Effect of each level
(same length and names as |
error_sd |
Positive numeric. Residual standard deviation. Default: 1. |
predictor_means |
Named numeric vector or NULL. Means for continuous predictors. Default: all zeros. |
predictor_sds |
Named numeric vector or NULL. SDs for continuous predictors. Default: all ones. |
seed |
Integer or NULL. Random seed. |
A saqr_sim object with:
$datadata.frame with columns y, continuous
predictors, and categorical predictors (factors).
$paramslist with coefs, cat_effects,
error_sd, predictor_means, predictor_sds,
r_squared (population ).
r <- simulate_prediction( n = 200, coefs = c("(Intercept)" = 5, x1 = 2, x2 = -1), cat_levels = list(treatment = c("control", "drug_a", "drug_b")), cat_effects = list(treatment = c(0, 3, 5)), error_sd = 2, seed = 42 ) summary(lm(y ~ ., data = r$data)) r$params$r_squaredr <- simulate_prediction( n = 200, coefs = c("(Intercept)" = 5, x1 = 2, x2 = -1), cat_levels = list(treatment = c("control", "drug_a", "drug_b")), cat_effects = list(treatment = c(0, 3, 5)), error_sd = 2, seed = 42 ) summary(lm(y ~ ., data = r$data)) r$params$r_squared
Generate a dataset suitable for linear regression with
fully specified ground-truth coefficients and predictor standard
deviations. Designed so that lm(y ~ ., data = r$data) recovers
the true coefficients at large n.
simulate_regression(coefs, predictor_sds, error_sd, n, seed = NULL)simulate_regression(coefs, predictor_sds, error_sd, n, seed = NULL)
coefs |
Named numeric vector. May include |
predictor_sds |
Named numeric vector. Names must exactly match the
non-intercept names in |
error_sd |
Positive numeric. Standard deviation of the residuals. |
n |
Positive integer. Sample size. |
seed |
Integer or NULL. Random seed. |
A named list with elements:
datadata.frame with column y and one column per
predictor.
paramslist with coefs, predictor_sds, and
error_sd.
coefs <- c("(Intercept)" = 2, x1 = 3, x2 = -1) r <- simulate_regression(coefs = coefs, predictor_sds = c(x1 = 1, x2 = 1), error_sd = 0.5, n = 500, seed = 42) coef(lm(y ~ ., data = r$data)) # should be close to c(2, 3, -1)coefs <- c("(Intercept)" = 2, x1 = 3, x2 = -1) r <- simulate_regression(coefs = coefs, predictor_sds = c(x1 = 1, x2 = 1), error_sd = 0.5, n = 500, seed = 42) coef(lm(y ~ ., data = r$data)) # should be close to c(2, 3, -1)
Generate wide-format sequence data where each row is drawn from one of K Markov chains (clusters), each governed by its own transition matrix. Supports explicit matrix supply or automatic random generation.
simulate_seq_clusters( trans_list = NULL, props = NULL, n = 300L, seq_length = 20L, init_probs = NULL, n_clusters = 3L, n_states = 10L, states = NULL, seed = NULL )simulate_seq_clusters( trans_list = NULL, props = NULL, n = 300L, seq_length = 20L, init_probs = NULL, n_clusters = 3L, n_states = 10L, states = NULL, seed = NULL )
trans_list |
Named or unnamed list of square numeric transition matrices,
or |
props |
Numeric vector of mixing proportions (need not sum to 1;
normalised internally). Length must equal |
n |
Positive integer. Total number of sequences to generate. |
seq_length |
Positive integer. Number of time-points per sequence
(columns |
init_probs |
Either a numeric vector of initial state probabilities
shared across clusters, a list of per-cluster vectors, or |
n_clusters |
Positive integer. Number of clusters when
|
n_states |
Positive integer. Number of states when
|
states |
Character vector of state names when |
seed |
Integer or |
A named list with elements:
datadata.frame with columns T1...T{seq_length}
(character state labels) and true_cluster (integer 1...K).
paramslist with trans_list (the K matrices used),
props (normalised mixing proportions), and init_probs
(per-cluster initial probability vectors as a list).
m1 <- matrix(c(0.8, 0.2, 0.3, 0.7), nrow = 2, byrow = TRUE, dimnames = list(c("A","B"), c("A","B"))) m2 <- matrix(c(0.2, 0.8, 0.7, 0.3), nrow = 2, byrow = TRUE, dimnames = list(c("A","B"), c("A","B"))) r <- simulate_seq_clusters(trans_list = list(m1, m2), n = 100, seed = 1) head(r$data) r$params$propsm1 <- matrix(c(0.8, 0.2, 0.3, 0.7), nrow = 2, byrow = TRUE, dimnames = list(c("A","B"), c("A","B"))) m2 <- matrix(c(0.2, 0.8, 0.7, 0.3), nrow = 2, byrow = TRUE, dimnames = list(c("A","B"), c("A","B"))) r <- simulate_seq_clusters(trans_list = list(m1, m2), n = 100, seed = 1) head(r$data) r$params$props
Generate sequences of states from a Markov chain. Can either use provided transition matrix and initial probabilities, or auto-generate random ones with optional learning state names.
simulate_sequences( n_sequences = 1000, seq_length = 20, n_states = 8, states = NULL, use_learning_states = TRUE, categories = "all", smart_select = TRUE, trans_matrix = NULL, init_probs = NULL, na_range = c(0, 0), include_na = TRUE, include_params = FALSE, seed = NULL, num_rows = NULL, max_seq_length = NULL, state_names = NULL, learning_categories = NULL, transition_matrix = NULL, initial_probabilities = NULL, min_na = NULL, max_na = NULL, return_params = NULL )simulate_sequences( n_sequences = 1000, seq_length = 20, n_states = 8, states = NULL, use_learning_states = TRUE, categories = "all", smart_select = TRUE, trans_matrix = NULL, init_probs = NULL, na_range = c(0, 0), include_na = TRUE, include_params = FALSE, seed = NULL, num_rows = NULL, max_seq_length = NULL, state_names = NULL, learning_categories = NULL, transition_matrix = NULL, initial_probabilities = NULL, min_na = NULL, max_na = NULL, return_params = NULL )
n_sequences |
Integer. Number of sequences (rows) to generate. Default: 1000. |
seq_length |
Integer. Maximum length of each sequence. Default: 20. |
n_states |
Integer. Number of states when auto-generating probabilities.
Ignored if |
states |
Character vector. Names for states when auto-generating.
If NULL, uses letters (A, B, C, ...) or learning states if enabled.
Ignored if |
use_learning_states |
Logical. If TRUE and auto-generating, uses realistic learning action verbs as state names. Default: TRUE. |
categories |
Character vector. Categories of learning states
to use. Options: "metacognitive", "cognitive", "behavioral", "social",
"motivational", "affective", "group_regulation", or "all".
Only used if |
smart_select |
Logical. If TRUE, intelligently selects learning states
based on n_states. Only used if |
trans_matrix |
Square numeric matrix of transition probabilities.
Rows must sum to 1. Row names define state names. If NULL, random
probabilities are generated based on |
init_probs |
Named numeric vector of initial state probabilities. Must sum to 1. If NULL, random probabilities are generated. Default: NULL. |
na_range |
Integer vector of length 2 (min, max) or single integer (min=max). Range of NA values per sequence. Default: c(0, 0). |
include_na |
Logical. Whether to include NAs in sequences. Default: TRUE. |
include_params |
Logical. If TRUE, returns a list with sequences and the generating parameters. Default: FALSE. |
seed |
Integer or NULL. Random seed for reproducibility. Default: NULL. |
num_rows |
Deprecated. Use |
max_seq_length |
Deprecated. Use |
state_names |
Deprecated. Use |
learning_categories |
Deprecated. Use |
transition_matrix |
Deprecated. Use |
initial_probabilities |
Deprecated. Use |
min_na |
Deprecated. Use |
max_na |
Deprecated. Use |
return_params |
Deprecated. Use |
The function generates sequences by:
Sampling an initial state from init_probs.
For each subsequent position, sampling the next state based on
the current state's row in trans_matrix.
If include_na is TRUE, trailing NAs are added to achieve a
random number of NAs within na_range.
Auto-generation mode: When trans_matrix is NULL, the function
automatically generates random transition probabilities and initial
probabilities using seqHMM::simulate_transition_probs() and
seqHMM::simulate_initial_probs().
Learning States: When use_learning_states = TRUE, state names are
drawn from a curated collection of 180+ student learning action verbs:
metacognitive: Plan, Monitor, Evaluate, Reflect, ...
cognitive: Read, Study, Analyze, Summarize, ...
behavioral: Practice, Annotate, Research, Review, ...
social: Collaborate, Discuss, Explain, Share, ...
motivational: Focus, Persist, Explore, Strive, ...
affective: Enjoy, Appreciate, Cope, Curious, ...
group_regulation: Adapt, Cohesion, Consensus, ...
If include_params = FALSE (default), a data frame with n_sequences
rows and seq_length columns. Each row is a sequence of state names,
potentially with trailing NAs.
If include_params = TRUE, a list containing:
sequences: The data frame of sequences.
transition_matrix: The transition probability matrix used.
initial_probabilities: The initial probabilities used.
state_names: The state names used.
simulate_sequences_advanced for sequences with stability modes,
simulate_long_data for long-format educational data,
get_learning_states for available learning state verbs,
simulate_tna_networks for generating complete TNA networks.
## Not run: # Simplest usage: all defaults (1000 sequences, 20 length, 5 states, learning states) sequences <- simulate_sequences(seed = 42) # Explicit new parameter names sequences <- simulate_sequences( n_sequences = 100, seq_length = 15, n_states = 6, use_learning_states = TRUE, categories = c("metacognitive", "cognitive"), seed = 42 ) # Method 1: Provide your own transition matrix trans_mat <- matrix(c( 0.7, 0.2, 0.1, 0.3, 0.5, 0.2, 0.2, 0.3, 0.5 ), nrow = 3, byrow = TRUE) rownames(trans_mat) <- colnames(trans_mat) <- c("A", "B", "C") init_probs <- c(A = 0.5, B = 0.3, C = 0.2) sequences <- simulate_sequences( trans_matrix = trans_mat, init_probs = init_probs, seq_length = 20, n_sequences = 100 ) # Method 2: Auto-generate with letter names sequences <- simulate_sequences( seq_length = 20, n_sequences = 100, n_states = 5, use_learning_states = FALSE, seed = 42 ) # Method 3: Auto-generate with learning state names sequences <- simulate_sequences( seq_length = 25, n_sequences = 150, n_states = 6, use_learning_states = TRUE, categories = c("metacognitive", "cognitive"), seed = 123 ) # Method 4: Get sequences AND the generating parameters result <- simulate_sequences( seq_length = 20, n_sequences = 100, n_states = 4, use_learning_states = TRUE, include_params = TRUE, seed = 42 ) result$sequences # The sequences result$transition_matrix # The random transition matrix result$state_names # e.g., c("Plan", "Monitor", "Read", "Practice") # Method 5: Custom state names sequences <- simulate_sequences( seq_length = 20, n_sequences = 100, n_states = 4, states = c("Explore", "Learn", "Practice", "Master"), seed = 42 ) # Old parameter names still work (backward compatible) sequences <- simulate_sequences( num_rows = 100, max_seq_length = 15, state_names = c("A", "B", "C"), seed = 42 ) ## End(Not run)## Not run: # Simplest usage: all defaults (1000 sequences, 20 length, 5 states, learning states) sequences <- simulate_sequences(seed = 42) # Explicit new parameter names sequences <- simulate_sequences( n_sequences = 100, seq_length = 15, n_states = 6, use_learning_states = TRUE, categories = c("metacognitive", "cognitive"), seed = 42 ) # Method 1: Provide your own transition matrix trans_mat <- matrix(c( 0.7, 0.2, 0.1, 0.3, 0.5, 0.2, 0.2, 0.3, 0.5 ), nrow = 3, byrow = TRUE) rownames(trans_mat) <- colnames(trans_mat) <- c("A", "B", "C") init_probs <- c(A = 0.5, B = 0.3, C = 0.2) sequences <- simulate_sequences( trans_matrix = trans_mat, init_probs = init_probs, seq_length = 20, n_sequences = 100 ) # Method 2: Auto-generate with letter names sequences <- simulate_sequences( seq_length = 20, n_sequences = 100, n_states = 5, use_learning_states = FALSE, seed = 42 ) # Method 3: Auto-generate with learning state names sequences <- simulate_sequences( seq_length = 25, n_sequences = 150, n_states = 6, use_learning_states = TRUE, categories = c("metacognitive", "cognitive"), seed = 123 ) # Method 4: Get sequences AND the generating parameters result <- simulate_sequences( seq_length = 20, n_sequences = 100, n_states = 4, use_learning_states = TRUE, include_params = TRUE, seed = 42 ) result$sequences # The sequences result$transition_matrix # The random transition matrix result$state_names # e.g., c("Plan", "Monitor", "Read", "Practice") # Method 5: Custom state names sequences <- simulate_sequences( seq_length = 20, n_sequences = 100, n_states = 4, states = c("Explore", "Learn", "Practice", "Master"), seed = 42 ) # Old parameter names still work (backward compatible) sequences <- simulate_sequences( num_rows = 100, max_seq_length = 15, state_names = c("A", "B", "C"), seed = 42 ) ## End(Not run)
Generate sequences of states from a Markov chain with advanced stability and instability modes. Supports stable transitions, probability perturbation, and unlikely jump modes.
simulate_sequences_advanced( n_sequences = 1000, seq_length = 20, n_states = 8, states = NULL, use_learning_states = TRUE, categories = "all", trans_matrix = NULL, init_probs = NULL, stable_transitions = NULL, stability_prob = 0.95, unstable_mode = "unlikely_jump", unstable_random_transition_prob = 0.4, unstable_perturb_noise = 0.5, unlikely_prob_threshold = 0.1, na_range = c(0, 0), include_na = TRUE, seed = NULL, transition_matrix = NULL, initial_probabilities = NULL, num_rows = NULL, max_seq_length = NULL, min_na = NULL, max_na = NULL )simulate_sequences_advanced( n_sequences = 1000, seq_length = 20, n_states = 8, states = NULL, use_learning_states = TRUE, categories = "all", trans_matrix = NULL, init_probs = NULL, stable_transitions = NULL, stability_prob = 0.95, unstable_mode = "unlikely_jump", unstable_random_transition_prob = 0.4, unstable_perturb_noise = 0.5, unlikely_prob_threshold = 0.1, na_range = c(0, 0), include_na = TRUE, seed = NULL, transition_matrix = NULL, initial_probabilities = NULL, num_rows = NULL, max_seq_length = NULL, min_na = NULL, max_na = NULL )
n_sequences |
Integer. Number of sequences (rows) to generate. Default: 1000. |
seq_length |
Integer. Maximum length of each sequence. Default: 20. |
n_states |
Integer. Number of states when auto-generating probabilities.
Ignored if |
states |
Character vector. Names for states when auto-generating.
If NULL, uses letters (A, B, C, ...) or learning states if enabled.
Ignored if |
use_learning_states |
Logical. If TRUE and auto-generating, uses realistic learning action verbs as state names. Default: TRUE. |
categories |
Character vector. Categories of learning states to use.
Only used if |
trans_matrix |
Square numeric matrix of transition probabilities. Rows must sum to 1. Row names define state names. If NULL, random probabilities are generated. Default: NULL. |
init_probs |
Named numeric vector of initial state probabilities. Must sum to 1. If NULL, random probabilities are generated. Default: NULL. |
stable_transitions |
List of character vectors. Each vector contains two state names defining a stable transition pair (from, to). Default: NULL (no stable transitions). |
stability_prob |
Numeric in (0 to 1). Probability of following a stable transition when in a stable state. Default: 0.95. |
unstable_mode |
Character. Mode for unstable transitions. One of:
Default: "unlikely_jump". |
unstable_random_transition_prob |
Numeric in (0 to 1). Probability of taking an unstable action. Default: 0.4. |
unstable_perturb_noise |
Numeric in (0 to 1). Noise factor for probability perturbation mode. Default: 0.5. |
unlikely_prob_threshold |
Numeric in (0 to 1). Threshold below which transitions are considered "unlikely". Default: 0.1. |
na_range |
Integer vector of length 2 (min, max) or single integer (min=max). Range of NA values per sequence. Default: c(0, 0). |
include_na |
Logical. Whether to include NAs in sequences. Default: TRUE. |
seed |
Integer or NULL. Random seed for reproducibility. Default: NULL. |
transition_matrix |
Deprecated. Use |
initial_probabilities |
Deprecated. Use |
num_rows |
Deprecated. Use |
max_seq_length |
Deprecated. Use |
min_na |
Deprecated. Use |
max_na |
Deprecated. Use |
The function extends basic Markov chain simulation with:
Stable Transitions: If the current state has a defined stable transition
and a random draw is below stability_prob, the sequence follows the stable
transition directly.
Unstable Modes (when not following stable transitions):
"random_jump": With probability unstable_random_transition_prob,
jump uniformly to any state.
"perturb_prob": Multiply transition probabilities by random noise
in range [1-noise, 1+noise], then renormalize.
"unlikely_jump": With probability unstable_random_transition_prob,
jump to a state with transition probability below threshold.
NAs are added at the end of sequences, preserving at least 2 non-NA values.
A data frame with n_sequences rows and seq_length columns.
Each row is a sequence of state names, potentially with trailing NAs.
## Not run: # Simplest usage: all defaults sequences <- simulate_sequences_advanced(seed = 42) # Create a 4-state transition matrix trans_mat <- matrix(c( 0.6, 0.2, 0.1, 0.1, 0.1, 0.7, 0.1, 0.1, 0.1, 0.1, 0.6, 0.2, 0.2, 0.1, 0.1, 0.6 ), nrow = 4, byrow = TRUE) rownames(trans_mat) <- colnames(trans_mat) <- c("A", "B", "C", "D") init_probs <- c(A = 0.25, B = 0.25, C = 0.25, D = 0.25) # Define stable transitions: A->B and C->D are "stable" stable <- list(c("A", "B"), c("C", "D")) # Generate sequences with unlikely_jump mode sequences <- simulate_sequences_advanced( trans_matrix = trans_mat, init_probs = init_probs, seq_length = 30, n_sequences = 100, stable_transitions = stable, stability_prob = 0.95, unstable_mode = "unlikely_jump", unstable_random_transition_prob = 0.3, na_range = c(0, 5) ) # Old parameter names still work (backward compatible) sequences <- simulate_sequences_advanced( transition_matrix = trans_mat, initial_probabilities = init_probs, max_seq_length = 30, num_rows = 100 ) ## End(Not run)## Not run: # Simplest usage: all defaults sequences <- simulate_sequences_advanced(seed = 42) # Create a 4-state transition matrix trans_mat <- matrix(c( 0.6, 0.2, 0.1, 0.1, 0.1, 0.7, 0.1, 0.1, 0.1, 0.1, 0.6, 0.2, 0.2, 0.1, 0.1, 0.6 ), nrow = 4, byrow = TRUE) rownames(trans_mat) <- colnames(trans_mat) <- c("A", "B", "C", "D") init_probs <- c(A = 0.25, B = 0.25, C = 0.25, D = 0.25) # Define stable transitions: A->B and C->D are "stable" stable <- list(c("A", "B"), c("C", "D")) # Generate sequences with unlikely_jump mode sequences <- simulate_sequences_advanced( trans_matrix = trans_mat, init_probs = init_probs, seq_length = 30, n_sequences = 100, stable_transitions = stable, stability_prob = 0.95, unstable_mode = "unlikely_jump", unstable_random_transition_prob = 0.3, na_range = c(0, 5) ) # Old parameter names still work (backward compatible) sequences <- simulate_sequences_advanced( transition_matrix = trans_mat, initial_probabilities = init_probs, max_seq_length = 30, num_rows = 100 ) ## End(Not run)
Generate right-censored survival data from a Cox
proportional-hazards generative model. The hazard for subject is
where is a parametric baseline hazard (Weibull, exponential,
or Gompertz). Event times are drawn by inverse-CDF sampling given each
subject's linear predictor, then administrative/exponential censoring is
applied so that roughly censoring_rate of observations are
censored. Designed so that coxph(Surv(time, status) ~ ., data)
recovers betas at large n.
simulate_survival( n = 300, n_covariates = 2, betas = NULL, baseline = c("weibull", "exponential", "gompertz"), lambda = 0.1, shape = 1, censoring_rate = 0.3, covariate_type = c("normal", "binary"), seed = NULL )simulate_survival( n = 300, n_covariates = 2, betas = NULL, baseline = c("weibull", "exponential", "gompertz"), lambda = 0.1, shape = 1, censoring_rate = 0.3, covariate_type = c("normal", "binary"), seed = NULL )
n |
Integer. Number of subjects. Default: 300. |
n_covariates |
Integer. Number of covariates |
betas |
Numeric vector or NULL. True log hazard ratios, one per
covariate. When NULL, a moderate alternating sequence is auto-generated
(e.g. |
baseline |
Character. Baseline hazard family: |
lambda |
Positive numeric. Baseline scale parameter. Default: 0.1. |
shape |
Positive numeric. Baseline shape parameter. For Weibull this is the Weibull shape; for Gompertz the level parameter; ignored for exponential. Default: 1. |
censoring_rate |
Numeric in [0, 1). Target proportion of censored observations. Default: 0.3. |
covariate_type |
Character. Covariate distribution: |
seed |
Integer or NULL. Random seed. |
Inverse-CDF event times use the closed-form survival inverse for
each baseline. With and linear predictor
:
Weibull ;
exponential ;
Gompertz .
A saqr_sim object with:
$datadata.frame with columns time (numeric event
or censoring time), status (1 = event, 0 = censored), and
X1...Xp (covariates).
$paramslist with betas (true log hazard ratios),
baseline, lambda, shape, covariate_type,
and realized_censoring_rate.
r <- simulate_survival(n = 400, n_covariates = 2, seed = 1) print(r) r$params$betas r$params$realized_censoring_rate head(as.data.frame(r)) # Binary covariates, exponential baseline, explicit effects r2 <- simulate_survival(n = 500, betas = c(0.8, -0.5), baseline = "exponential", covariate_type = "binary", seed = 42) summary(r2)r <- simulate_survival(n = 400, n_covariates = 2, seed = 1) print(r) r$params$betas r$params$realized_censoring_rate head(as.data.frame(r)) # Binary covariates, exponential baseline, explicit effects r2 <- simulate_survival(n = 500, betas = c(0.8, -0.5), baseline = "exponential", covariate_type = "binary", seed = 42) summary(r2)
Simulate complete TNA datasets including simulated sequences, fitted models, and generating probabilities. This function combines the full simulation workflow: probability generation -> sequence simulation -> model fitting.
Use simulate_tna_networks if you only need the fitted models.
Supports using realistic learning action verbs as state names for educational research simulations.
simulate_tna_datasets( n_datasets = 1, n_states = 8, n_sequences = 100, seq_length = 30, states = NULL, use_learning_states = TRUE, categories = NULL, smart_select = TRUE, na_range = c(0, 0), model_type = "tna", use_advanced = FALSE, stable_transitions = NULL, stability_prob = 0.95, unstable_mode = "random_jump", unstable_random_transition_prob = 0.5, include_data = TRUE, include_probs = TRUE, seed = NULL, verbose = TRUE, state_names = NULL, learning_categories = NULL, num_rows = NULL, max_seq_length = NULL, min_na = NULL, max_na = NULL, include_probabilities = NULL ) generate_tna_datasets(...) generate_sequence_data(...)simulate_tna_datasets( n_datasets = 1, n_states = 8, n_sequences = 100, seq_length = 30, states = NULL, use_learning_states = TRUE, categories = NULL, smart_select = TRUE, na_range = c(0, 0), model_type = "tna", use_advanced = FALSE, stable_transitions = NULL, stability_prob = 0.95, unstable_mode = "random_jump", unstable_random_transition_prob = 0.5, include_data = TRUE, include_probs = TRUE, seed = NULL, verbose = TRUE, state_names = NULL, learning_categories = NULL, num_rows = NULL, max_seq_length = NULL, min_na = NULL, max_na = NULL, include_probabilities = NULL ) generate_tna_datasets(...) generate_sequence_data(...)
n_datasets |
Integer. Number of datasets to generate. Default: 1. |
n_states |
Integer. Number of states in each network. Default: 5. |
n_sequences |
Integer. Number of sequences to simulate per network. Default: 100. |
seq_length |
Integer. Maximum length of each sequence. Default: 30. |
states |
Character vector. Names for the states. If NULL and
|
use_learning_states |
Logical. If TRUE, uses learning action verbs as state names (e.g., "Plan", "Monitor", "Read"). Default: TRUE. |
categories |
Character vector. Which categories of learning
verbs to use. Options: "metacognitive", "cognitive", "behavioral",
"social", "motivational", "affective", "group_regulation", or "all".
If NULL and |
smart_select |
Logical. If TRUE, intelligently selects learning states
based on n_states (small networks use fewer categories).
Only used if |
na_range |
Integer vector of length 2 (min, max) or single integer. Range of NA values per sequence. Default: c(0, 0). |
model_type |
Character. Type of TNA model to fit. One of: "tna", "ftna", "ctna", "atna". Default: "tna". |
use_advanced |
Logical. If TRUE, uses |
stable_transitions |
List of character vectors defining stable
transitions (only used if |
stability_prob |
Numeric (0 to 1). Probability of following stable
transitions (only used if |
unstable_mode |
Character. Mode for unstable transitions:
"random_jump", "perturb_prob", or "unlikely_jump".
(Only used if |
unstable_random_transition_prob |
Numeric (0 to 1). Probability of
unstable action (only used if |
include_data |
Logical. If TRUE, includes the generating sequence data in the output. Default: TRUE. |
include_probs |
Logical. If TRUE, includes the generating transition matrix and initial probabilities in the output. Default: TRUE. |
seed |
Integer or NULL. Random seed for reproducibility. If NULL, no seed is set. Default: NULL. |
verbose |
Logical. If TRUE, prints progress messages. Default: TRUE. |
state_names |
Deprecated. Use |
learning_categories |
Deprecated. Use |
num_rows |
Deprecated. Use |
max_seq_length |
Deprecated. Use |
min_na |
Deprecated. Use |
max_na |
Deprecated. Use |
include_probabilities |
Deprecated. Use |
... |
Arguments passed to |
The function generates sequence data by:
Generating random transition and initial probabilities using
seqHMM::simulate_transition_probs() and seqHMM::simulate_initial_probs().
Simulating sequences from those probabilities using either
simulate_sequences() or simulate_sequences_advanced().
Fitting a TNA model to the sequences using fit_network_model().
Learning States: When use_learning_states = TRUE, state names are
drawn from a curated collection of 180+ student learning action verbs
organized into 7 categories:
metacognitive: Plan, Monitor, Evaluate, Reflect, Regulate, ...
cognitive: Read, Study, Analyze, Summarize, Memorize, ...
behavioral: Practice, Annotate, Research, Review, Write, ...
social: Collaborate, Discuss, Explain, Share, Teach, ...
motivational: Focus, Persist, Explore, Strive, Commit, ...
affective: Enjoy, Appreciate, Cope, Manage, Curious, ...
group_regulation: Adapt, Cohesion, Consensus, Coregulate, ...
A list of length n_datasets. Each element is a list containing:
The fitted TNA model object.
The generating transition matrix
(if include_probs = TRUE).
The generating initial probabilities
(if include_probs = TRUE).
The simulated sequence data frame
(if include_data = TRUE).
List of parameters used for this network.
simulate_tna_networks for generating TNA network objects,
get_learning_states for retrieving learning state verbs,
select_states for intelligent state selection,
list_learning_categories for viewing available categories,
simulate_sequences for basic sequence simulation,
fit_network_model for model fitting.
## Not run: # Simplest usage - generates 1 dataset with sequences + model + probabilities data <- simulate_tna_datasets(seed = 42) data[[1]]$sequences # The sequence data data[[1]]$model # The fitted TNA model data[[1]]$transition_probs # The generating probabilities # Generate 5 datasets with learning states data <- simulate_tna_datasets( n_datasets = 5, n_states = 4, seed = 42 ) # Generate with specific learning category learning_data <- simulate_tna_datasets( n_datasets = 5, n_states = 6, categories = c("metacognitive", "cognitive"), seed = 42 ) # View the state names learning_data[[1]]$params$state_names # e.g., c("Plan", "Monitor", "Read", "Practice", "Discuss", "Focus") # Generate with letter names (disable learning states) letter_data <- simulate_tna_datasets( n_datasets = 5, n_states = 8, use_learning_states = FALSE, seed = 123 ) ## End(Not run)## Not run: # Simplest usage - generates 1 dataset with sequences + model + probabilities data <- simulate_tna_datasets(seed = 42) data[[1]]$sequences # The sequence data data[[1]]$model # The fitted TNA model data[[1]]$transition_probs # The generating probabilities # Generate 5 datasets with learning states data <- simulate_tna_datasets( n_datasets = 5, n_states = 4, seed = 42 ) # Generate with specific learning category learning_data <- simulate_tna_datasets( n_datasets = 5, n_states = 6, categories = c("metacognitive", "cognitive"), seed = 42 ) # View the state names learning_data[[1]]$params$state_names # e.g., c("Plan", "Monitor", "Read", "Practice", "Discuss", "Focus") # Generate with letter names (disable learning states) letter_data <- simulate_tna_datasets( n_datasets = 5, n_states = 8, use_learning_states = FALSE, seed = 123 ) ## End(Not run)
Simulate a transition matrix with node groupings, compatible with
tna::plot_htna() (hierarchical) and tna::plot_mlna() (multilevel)
visualizations. By default creates a 25-node matrix (5 nodes x 5 types)
using learning category names.
This is a convenience wrapper around simulate_htna.
simulate_tna_matrix( nodes_per_group = 5, group_names = c("Metacognitive", "Cognitive", "Behavioral", "Social", "Motivational"), n_groups = 5, edge_prob_range = c(0, 1), self_loops = FALSE, use_learning_states = TRUE, categories = c("metacognitive", "cognitive", "behavioral", "social", "motivational"), within_prob = 0.4, between_prob = 0.15, node_prefix = "N", seed = NULL, verbose = TRUE, learning_categories = NULL ) generate_tna_matrix(...)simulate_tna_matrix( nodes_per_group = 5, group_names = c("Metacognitive", "Cognitive", "Behavioral", "Social", "Motivational"), n_groups = 5, edge_prob_range = c(0, 1), self_loops = FALSE, use_learning_states = TRUE, categories = c("metacognitive", "cognitive", "behavioral", "social", "motivational"), within_prob = 0.4, between_prob = 0.15, node_prefix = "N", seed = NULL, verbose = TRUE, learning_categories = NULL ) generate_tna_matrix(...)
nodes_per_group |
Integer. Number of nodes per group. Default: 5. |
group_names |
Character vector. Names for each group. Default uses learning categories: "Metacognitive", "Cognitive", "Behavioral", "Social", "Motivational". |
n_groups |
Integer. Number of groups. Default: 5. |
edge_prob_range |
Numeric vector of length 2. Range for edge weights
|
self_loops |
Logical. Allow self-loops (diagonal elements). Default: FALSE. |
use_learning_states |
Logical. Use learning state verbs as node names. Default: TRUE. |
categories |
Character vector. Categories for node names, one per group. Default: c("metacognitive", "cognitive", "behavioral", "social", "motivational"). |
within_prob |
Numeric. Probability of edges within each group. Default: 0.4. |
between_prob |
Numeric. Probability of edges between groups. Default: 0.15. |
node_prefix |
Character. Prefix for node names when not using learning states. Default: "N". |
seed |
Integer or NULL. Random seed. Default: NULL. |
verbose |
Logical. Print progress messages. Default: TRUE. |
learning_categories |
Deprecated. Use |
... |
Arguments passed to |
This function generates a random transition matrix and node groupings. The output can be used with both hierarchical and multilevel TNA plots:
For plot_htna(): use net$node_types directly
For plot_mlna(): use layers = net$node_types
A list with two elements:
Square transition matrix (rows sum to 1) with named rows/columns.
Named list mapping group names to node names.
Use as node_types for plot_htna() or as layers for plot_mlna().
simulate_htna for the underlying function,
simulate_matrix for basic matrix simulation,
simulate_tna_networks for TNA model objects.
## Not run: # Default: 5 groups x 5 nodes = 25 node matrix net <- simulate_tna_matrix(seed = 42) net$matrix net$node_types # Metacognitive, Cognitive, Behavioral, Social, Motivational # Use with plot_htna plot_htna(net$matrix, net$node_types, layout = "polygon") # Use with plot_mlna plot_mlna(net$matrix, layers = net$node_types) # Custom group names (3 groups) net <- simulate_tna_matrix( nodes_per_group = 6, group_names = c("Macro", "Meso", "Micro"), seed = 42 ) # Custom categories per group net <- simulate_tna_matrix( nodes_per_group = 4, group_names = c("Teacher", "Student", "System"), categories = c("metacognitive", "cognitive", "behavioral"), seed = 123 ) ## End(Not run)## Not run: # Default: 5 groups x 5 nodes = 25 node matrix net <- simulate_tna_matrix(seed = 42) net$matrix net$node_types # Metacognitive, Cognitive, Behavioral, Social, Motivational # Use with plot_htna plot_htna(net$matrix, net$node_types, layout = "polygon") # Use with plot_mlna plot_mlna(net$matrix, layers = net$node_types) # Custom group names (3 groups) net <- simulate_tna_matrix( nodes_per_group = 6, group_names = c("Macro", "Meso", "Micro"), seed = 42 ) # Custom categories per group net <- simulate_tna_matrix( nodes_per_group = 4, group_names = c("Teacher", "Student", "System"), categories = c("metacognitive", "cognitive", "behavioral"), seed = 123 ) ## End(Not run)
Generate a single fitted TNA network model with learning state names. This is the simplest way to get a ready-to-use tna model object.
simulate_tna_network( n_states = 9, n_sequences = NULL, seq_length = 25, categories = c("metacognitive", "cognitive"), seed = NULL )simulate_tna_network( n_states = 9, n_sequences = NULL, seq_length = 25, categories = c("metacognitive", "cognitive"), seed = NULL )
n_states |
Integer. Number of states (8-10 recommended). Default: 9. |
n_sequences |
Integer or NULL. Number of sequences to simulate. If NULL (default), randomly selects between 600-1200. |
seq_length |
Integer. Length of each sequence. Default: 25. |
categories |
Character vector. Learning state categories to use. Options: "metacognitive", "cognitive", "behavioral", "social", "motivational", "affective", "group_regulation", "lms", or "all". Default: c("metacognitive", "cognitive"). |
seed |
Integer or NULL. Random seed for reproducibility. Default: NULL. |
This function provides the simplest interface for generating a TNA network:
Selects learning state names from specified categories
Generates random transition probabilities
Simulates Markov chain sequences
Fits and returns a tna model
The returned model is 100% compatible with all tna package functions.
A tna model object (class "tna") ready for use with all tna functions:
plot(), centralities(), communities(), etc.
simulate_tna_networks for generating multiple networks,
simulate_sequences for generating sequences without fitting,
fit_network_model for fitting models to existing data.
library(Saqrlab) # Generate a network (simplest usage) model <- simulate_tna_network(seed = 42) # Use with tna functions ## Not run: library(tna) plot(model) centralities(model) communities(model) ## End(Not run) # Custom configuration model <- simulate_tna_network( n_states = 8, n_sequences = 300, categories = "group_regulation", seed = 123 ) # Access model components model$weights model$initial_probslibrary(Saqrlab) # Generate a network (simplest usage) model <- simulate_tna_network(seed = 42) # Use with tna functions ## Not run: library(tna) plot(model) centralities(model) communities(model) ## End(Not run) # Custom configuration model <- simulate_tna_network( n_states = 8, n_sequences = 300, categories = "group_regulation", seed = 123 ) # Access model components model$weights model$initial_probs
Simulate multiple TNA network objects (fitted models) for simulation studies.
This function creates TNA model objects by simulating sequence data and
fitting models. For generating raw sequence data with associated probabilities,
use simulate_tna_datasets. For group TNA models, use
simulate_group_tna_networks.
simulate_tna_networks( n_networks = 1, n_states = 8, n_sequences = 100, seq_length = 30, model_type = "tna", use_learning_states = TRUE, categories = NULL, seed = NULL, verbose = TRUE, num_sequences = NULL, max_seq_length = NULL, learning_categories = NULL, ... ) generate_tna_networks(...)simulate_tna_networks( n_networks = 1, n_states = 8, n_sequences = 100, seq_length = 30, model_type = "tna", use_learning_states = TRUE, categories = NULL, seed = NULL, verbose = TRUE, num_sequences = NULL, max_seq_length = NULL, learning_categories = NULL, ... ) generate_tna_networks(...)
n_networks |
Integer. Number of networks to generate. Default: 1. |
n_states |
Integer. Number of states/actions in each network. Default: 5. |
n_sequences |
Integer. Number of sequences to simulate per network. Default: 100. |
seq_length |
Integer. Maximum length of each sequence. Default: 30. |
model_type |
Character. Type of TNA model to fit: "tna", "ftna", "ctna", "atna". Default: "tna". |
use_learning_states |
Logical. If TRUE, uses learning action verbs as state names. Default: TRUE. |
categories |
Character vector or NULL. Which categories of learning verbs to use. Options: "metacognitive", "cognitive", "behavioral", "social", "motivational", "affective", "group_regulation", or "all". If NULL (default), randomly selects one category. |
seed |
Integer or NULL. Random seed for reproducibility. Default: NULL. |
verbose |
Logical. If TRUE, prints progress messages. Default: TRUE. |
num_sequences |
Deprecated. Use |
max_seq_length |
Deprecated. Use |
learning_categories |
Deprecated. Use |
... |
Arguments passed to |
This function differs from simulate_tna_datasets in that it
returns only the fitted model objects, not the underlying sequence data or
generating probabilities. Use this when you need TNA network objects for
simulation studies or method comparisons.
Random Category Selection: When categories = NULL and
use_learning_states = TRUE, a random learning category is selected.
Available categories: metacognitive, cognitive, behavioral, social,
motivational, affective, group_regulation.
A list of length n_networks containing fitted TNA model objects.
Each element is a tna model object (class "tna").
simulate_group_tna_networks for group TNA models,
simulate_tna_datasets for generating complete datasets with
probabilities, fit_network_model for model fitting,
get_learning_states for learning state verbs.
## Not run: # Generate 5 TNA networks with random learning category nets <- simulate_tna_networks(n_networks = 5, seed = 42) # Generate networks with specific category meta_nets <- simulate_tna_networks( n_networks = 3, n_states = 6, categories = "metacognitive", seed = 123 ) # Generate filtered TNA networks ftna_nets <- simulate_tna_networks( n_networks = 5, model_type = "ftna", seed = 456 ) # Use the networks plot(nets[[1]]) tna::centralities(nets[[1]]) # Old parameter names still work nets <- simulate_tna_networks( n_networks = 3, num_sequences = 50, max_seq_length = 25, seed = 42 ) ## End(Not run)## Not run: # Generate 5 TNA networks with random learning category nets <- simulate_tna_networks(n_networks = 5, seed = 42) # Generate networks with specific category meta_nets <- simulate_tna_networks( n_networks = 3, n_states = 6, categories = "metacognitive", seed = 123 ) # Generate filtered TNA networks ftna_nets <- simulate_tna_networks( n_networks = 5, model_type = "ftna", seed = 456 ) # Use the networks plot(nets[[1]]) tna::centralities(nets[[1]]) # Old parameter names still work nets <- simulate_tna_networks( n_networks = 3, num_sequences = 50, max_seq_length = 25, seed = 42 ) ## End(Not run)
Generate data for a two-group comparison with fully specified
ground-truth means and standard deviations. Designed so that
t.test(score ~ group, data = r$data) recovers the true difference
at large n.
simulate_ttest( n_a, n_b, mean_a, mean_b, sd_a = 1, sd_b = sd_a, labels = c("A", "B"), seed = NULL )simulate_ttest( n_a, n_b, mean_a, mean_b, sd_a = 1, sd_b = sd_a, labels = c("A", "B"), seed = NULL )
n_a |
Integer. Sample size for group A. |
n_b |
Integer. Sample size for group B. |
mean_a |
Numeric. Population mean for group A. |
mean_b |
Numeric. Population mean for group B. |
sd_a |
Positive numeric. Standard deviation for group A. Default: 1. |
sd_b |
Positive numeric. Standard deviation for group B. Default:
same as |
labels |
Character vector of length 2. Group labels. Default:
|
seed |
Integer or NULL. Random seed. |
A saqr_sim object with:
$datadata.frame with columns group (factor) and
score (numeric).
$paramslist with mean_a, mean_b, sd_a,
sd_b, n_a, n_b, cohens_d (true Cohen's d
based on pooled SD).
r <- simulate_ttest(n_a = 50, n_b = 50, mean_a = 100, mean_b = 105, seed = 1) t.test(score ~ group, data = r$data) r$params$cohens_dr <- simulate_ttest(n_a = 50, n_b = 50, mean_a = 100, mean_b = 105, seed = 1) t.test(score ~ group, data = r$data) r$params$cohens_d
Summarize results from run_grid_simulation(), filtering by parameter ranges
and computing aggregated performance metrics. Provides detailed summaries
at both the setting level and across all selected settings.
summarize_grid_results( grid_results_list, n_sequences_range = NULL, seq_length_range = NULL, min_na_range = NULL, max_na_range = NULL, level_context = 0.05, print_output = TRUE, print_aggregated_overall = TRUE, print_aggregated_edges = TRUE, print_settings_summary = TRUE, num_rows_range = NULL, max_seq_length_range = NULL ) analyze_grid_results(...)summarize_grid_results( grid_results_list, n_sequences_range = NULL, seq_length_range = NULL, min_na_range = NULL, max_na_range = NULL, level_context = 0.05, print_output = TRUE, print_aggregated_overall = TRUE, print_aggregated_edges = TRUE, print_settings_summary = TRUE, num_rows_range = NULL, max_seq_length_range = NULL ) analyze_grid_results(...)
grid_results_list |
List output from |
n_sequences_range |
Numeric vector of length 2 (min, max) or NULL. Filter settings by n_sequences. |
seq_length_range |
Numeric vector of length 2 (min, max) or NULL. Filter settings by seq_length. |
min_na_range |
Numeric vector of length 2 (min, max) or NULL. Filter settings by min_na. |
max_na_range |
Numeric vector of length 2 (min, max) or NULL. Filter settings by max_na. |
level_context |
Numeric. Significance level used for calculations (for context in output). Default: 0.05. |
print_output |
Logical. Master switch for console printing. Default: TRUE. |
print_aggregated_overall |
Logical. Print averaged overall performance metrics across selected settings. Default: TRUE. |
print_aggregated_edges |
Logical. Print aggregated edge significance summary. Default: TRUE. |
print_settings_summary |
Logical. Print summary table for each selected setting. Default: TRUE. |
num_rows_range |
Deprecated. Use |
max_seq_length_range |
Deprecated. Use |
... |
Arguments passed to |
The function performs comprehensive analysis:
Filtering: Selects settings where all parameters fall within specified ranges.
Aggregation from Input Summaries: Extracts and averages overall performance
and edge significance from the original aggregated_summary in each setting.
Run-Level Metrics: Recomputes TP/TN/FP/FN counts from per-edge data, then calculates Sensitivity, Specificity, FPR, FNR, Accuracy, and MCC per run.
Setting-Level Metrics: Two approaches:
Mean/Median/SD of run-level metrics.
Metrics computed from total counts across all runs (more robust).
The selected_settings_summary_df uses approach #2 for the most accurate
overall metrics per setting.
A list containing:
Number of settings matching the filter criteria.
List with:
overall_performance: Averaged metrics across settings.
edge_significance: Aggregated edge-level statistics.
Data frame with per-setting metrics calculated from total TP/TN/FP/FN counts.
List with detailed run-level data:
all_raw_summaries: Combined bootstrap summaries.
all_per_edge_performance: Combined per-edge results.
run_level_performance_metrics: Metrics per run.
setting_level_summary_stats: Mean/Median/SD of run metrics.
Returns NULL (invisibly) if no settings match.
## Not run: # After running grid simulation grid_results <- run_grid_simulation(...) # Analyze all results analysis <- summarize_grid_results(grid_results) # Filter to specific parameter ranges analysis_filtered <- summarize_grid_results( grid_results, n_sequences_range = c(100, 200), seq_length_range = c(30, 50), max_na_range = c(0, 5) ) # Access the detailed run-level metrics run_metrics <- analysis$compiled_individual_runs$run_level_performance_metrics # Access setting-level summary setting_summary <- analysis$selected_settings_summary_df # Old parameter names still work analysis_filtered <- summarize_grid_results( grid_results, num_rows_range = c(100, 200), max_seq_length_range = c(30, 50) ) ## End(Not run)## Not run: # After running grid simulation grid_results <- run_grid_simulation(...) # Analyze all results analysis <- summarize_grid_results(grid_results) # Filter to specific parameter ranges analysis_filtered <- summarize_grid_results( grid_results, n_sequences_range = c(100, 200), seq_length_range = c(30, 50), max_na_range = c(0, 5) ) # Access the detailed run-level metrics run_metrics <- analysis$compiled_individual_runs$run_level_performance_metrics # Access setting-level summary setting_summary <- analysis$selected_settings_summary_df # Old parameter names still work analysis_filtered <- summarize_grid_results( grid_results, num_rows_range = c(100, 200), max_seq_length_range = c(30, 50) ) ## End(Not run)
Compute aggregate statistics across multiple TNA network models.
summarize_networks( model_list, include = c("density", "centrality", "edges"), threshold = 0.01, centrality_measures = c("OutStrength", "InStrength") )summarize_networks( model_list, include = c("density", "centrality", "edges"), threshold = 0.01, centrality_measures = c("OutStrength", "InStrength") )
model_list |
A list of TNA model objects. |
include |
Character vector. What to include in the summary. Options: "density" (network density), "centrality" (centrality measures), "edges" (edge weight statistics), or "all" for everything. Default: c("density", "centrality", "edges"). |
threshold |
Numeric. Minimum edge weight to consider present for density calculation. Default: 0.01. |
centrality_measures |
Character vector. Which centrality measures to summarize. Default: c("OutStrength", "InStrength"). |
This function is useful for summarizing results from simulation studies where many networks are generated. It provides both per-network and aggregate statistics.
A list containing:
summary_table: Data frame with per-network statistics.
aggregate: Named list of aggregate statistics across all networks.
n_networks: Number of networks summarized.
summarize_simulation() for simulation result summaries,
batch_fit_models() for fitting multiple models.
## Not run: # Generate and fit multiple networks datasets <- lapply(1:20, function(i) { simulate_sequences(trans_mat, init_probs, 20, 100) }) models <- batch_fit_models(datasets) # Summarize networks network_summary <- summarize_networks(models) print(network_summary$aggregate) ## End(Not run)## Not run: # Generate and fit multiple networks datasets <- lapply(1:20, function(i) { simulate_sequences(trans_mat, init_probs, 20, 100) }) models <- batch_fit_models(datasets) # Summarize networks network_summary <- summarize_networks(models) print(network_summary$aggregate) ## End(Not run)
Compute summary statistics for simulation results, optionally grouped by parameter combinations or other factors.
summarize_simulation( results, by = NULL, metrics = c("mean", "sd", "ci"), value_cols = NULL, na.rm = TRUE )summarize_simulation( results, by = NULL, metrics = c("mean", "sd", "ci"), value_cols = NULL, na.rm = TRUE )
results |
A data frame of simulation results, typically from
|
by |
Character vector. Column names to group by when computing summaries. Default: NULL (compute overall summary). |
metrics |
Character vector. Which summary metrics to compute. Options: "mean" (arithmetic mean), "sd" (standard deviation), "median" (median value), "ci" (95 percent confidence interval), "min" (minimum), "max" (maximum), "n" (count), or "all" to compute all metrics. Default: c("mean", "sd", "ci"). |
value_cols |
Character vector. Names of columns containing numeric values to summarize. If NULL, auto-detects numeric columns. Default: NULL. |
na.rm |
Logical. Whether to remove NA values when computing statistics. Default: TRUE. |
This function provides flexible summarization of simulation results. It automatically detects numeric columns and computes requested statistics.
Confidence intervals are computed as mean +/- 1.96 * SE, where SE = sd / sqrt(n).
A data frame with summary statistics. If by is specified,
contains one row per unique combination of grouping variables.
summarize_networks() for summarizing network metrics,
run_network_simulation() for running simulations.
## Not run: # Run a simulation results <- run_network_simulation(trans_mat, init_probs, num_rows_values = c(50, 100, 200), n_runs = 20) # Overall summary summarize_simulation(results) # Summary by sample size summarize_simulation(results, by = "num_rows") # Summary with all metrics summarize_simulation(results, by = "num_rows", metrics = "all") ## End(Not run)## Not run: # Run a simulation results <- run_network_simulation(trans_mat, init_probs, num_rows_values = c(50, 100, 200), n_runs = 20) # Overall summary summarize_simulation(results) # Summary by sample size summarize_simulation(results, by = "num_rows") # Summary with all metrics summarize_simulation(results, by = "num_rows", metrics = "all") ## End(Not run)
Stack the $data of several saqr_sim objects
into a single tidy data.frame. Each sim contributes its rows plus a
.case column (the list name) and one column per scalar (length-1)
ground-truth parameter in $params. Non-scalar parameters (matrices,
vectors) are skipped. Columns are unioned across cases, so cases with
different parameter sets still bind safely.
tidy_simulation_results(x)tidy_simulation_results(x)
x |
A named list of |
A single base data.frame with all data rows stacked, a
.case column, and one column per scalar parameter.
s <- run_scenario("power_ttest", seed = 1) tidy_simulation_results(s)s <- run_scenario("power_ttest", seed = 1) tidy_simulation_results(s)
Compare a method's point estimates to the known true values that
generated a simulation, matched by name. This is the core
"did my method recover the truth I simulated?" check of the simulation
laboratory: feed in a saqr_sim object (or a plain named list /
vector of true values) and a named vector of estimates, and get back a tidy
one-row-per-parameter table of errors and tolerance flags.
validate_recovery( sim, estimates, params = NULL, tolerance = 0.1, relative = TRUE ) ## S3 method for class 'recovery_result' print(x, ...) ## S3 method for class 'recovery_result' summary(object, ...)validate_recovery( sim, estimates, params = NULL, tolerance = 0.1, relative = TRUE ) ## S3 method for class 'recovery_result' print(x, ...) ## S3 method for class 'recovery_result' summary(object, ...)
sim |
A |
estimates |
A named numeric vector (or named list of scalars) of point estimates produced by a fitted method. Names are matched against the (flattened) names of the truth. |
params |
Optional character vector restricting which parameter names to
compare. Default |
tolerance |
Positive numeric. Threshold a parameter must fall within to
count as recovered. Interpreted as a relative tolerance when
|
relative |
Logical. If |
x |
A |
... |
Further arguments (ignored). |
object |
A |
An S3 object of class c("recovery_result", "data.frame") with
one row per compared parameter and columns:
parameterParameter name (flattened, e.g. coefs.x1).
trueTrue value from the simulation.
estimateEstimated value.
abs_errorabs(estimate - true).
rel_errorabs_error / abs(true), NA when
true == 0.
within_tolLogical recovery flag (see relative).
Use summary.recovery_result for a one-row scorecard.
# t-test: recover the true Cohen's d sim <- simulate_ttest(n_a = 200, n_b = 200, mean_a = 0, mean_b = 0.5, sd_a = 1, sd_b = 1, seed = 1) fit <- t.test(score ~ group, data = sim$data) d_hat <- unname(fit$estimate[2] - fit$estimate[1]) # mean_b - mean_a validate_recovery(sim, estimates = c(cohens_d = d_hat)) # Regression: recover known coefficients from lm() rsim <- simulate_regression( coefs = c("(Intercept)" = 1, x1 = 2, x2 = -1.5), predictor_sds = c(x1 = 1, x2 = 1), error_sd = 1, n = 2000, seed = 7 ) fit_lm <- lm(y ~ x1 + x2, data = rsim$data) est <- stats::setNames(coef(fit_lm), paste0("coefs.", names(coef(fit_lm)))) validate_recovery(rsim, estimates = est)# t-test: recover the true Cohen's d sim <- simulate_ttest(n_a = 200, n_b = 200, mean_a = 0, mean_b = 0.5, sd_a = 1, sd_b = 1, seed = 1) fit <- t.test(score ~ group, data = sim$data) d_hat <- unname(fit$estimate[2] - fit$estimate[1]) # mean_b - mean_a validate_recovery(sim, estimates = c(cohens_d = d_hat)) # Regression: recover known coefficients from lm() rsim <- simulate_regression( coefs = c("(Intercept)" = 1, x1 = 2, x2 = -1.5), predictor_sds = c(x1 = 1, x2 = 1), error_sd = 1, n = 2000, seed = 7 ) fit_lm <- lm(y ~ x1 + x2, data = rsim$data) est <- stats::setNames(coef(fit_lm), paste0("coefs.", names(coef(fit_lm)))) validate_recovery(rsim, estimates = est)
Validate simulation parameters and set defaults for missing values. Ensures parameter relationships are valid (e.g., min_na <= max_na).
validate_sim_params(params)validate_sim_params(params)
params |
List of simulation parameters. May include:
|
The function performs the following validations:
Sets default values for missing parameters.
Ensures max_na <= seq_length.
Ensures min_na <= max_na.
Ensures min_na < seq_length.
Both new (seq_length, n_sequences) and old (max_seq_length, num_rows)
parameter names are supported for backward compatibility.
A list of validated parameters with defaults applied.
# Validate with defaults params <- validate_sim_params(list()) # Validate custom parameters (new names) params <- validate_sim_params(list( seq_length = 50, n_sequences = 200, min_na = 2, max_na = 10 )) # Old parameter names still work params <- validate_sim_params(list( max_seq_length = 50, num_rows = 200 ))# Validate with defaults params <- validate_sim_params(list()) # Validate custom parameters (new names) params <- validate_sim_params(list( seq_length = 50, n_sequences = 200, min_na = 2, max_na = 10 )) # Old parameter names still work params <- validate_sim_params(list( max_seq_length = 50, num_rows = 200 ))