Quickstart

This quickstart guide will get you up and running with TranCIT: Transient Causal Interaction Toolbox analysis in just a few minutes.

We’ll cover the most common use cases with the class-based API, which provides clean interfaces and robust error handling.

Installation Check

First, verify your installation:

import trancit
print(f"TranCIT version: {trancit.__version__}")

If this works, you’re ready to go! If not, see the Installation guide.

Basic Causality Analysis

The simplest way to analyze causal relationships is using the DCSCalculator class:

 1import numpy as np
 2from trancit import DCSCalculator, generate_signals
 3
 4# Generate synthetic bivariate time series data
 5data, _, _ = generate_signals(
 6    T=1000, Ntrial=20, h=0.1,
 7    gamma1=0.5, gamma2=0.5,
 8    Omega1=1.0, Omega2=1.2
 9)
10
11print(f"Data shape: {data.shape}")  # (2, 1000, 20) = (variables, time, trials)
12
13# Create DCS calculator
14calculator = DCSCalculator(model_order=4, time_mode="inhomo")
15
16# Perform analysis
17result = calculator.analyze(data)
18
19# Access results
20print(f"Causal Strength shape: {result.causal_strength.shape}")
21print(f"Transfer Entropy shape: {result.transfer_entropy.shape}")
22print(f"Granger Causality shape: {result.granger_causality.shape}")
23
24# Display mean causality values
25print(f"Mean DCS (X→Y): {result.causal_strength[:, 0].mean():.4f}")
26print(f"Mean DCS (Y→X): {result.causal_strength[:, 1].mean():.4f}")

Key Points:

  • model_order=4: Number of time lags to include in the VAR model

  • time_mode="inhomo": Use time-inhomogeneous analysis (recommended)

  • Results contain causality measures with shape (n_time_points, 2) where column 0 is Y→X and column 1 is X→Y

Pipeline-Based Event Analysis

For event-based analysis (detecting and analyzing specific time windows), use the PipelineOrchestrator:

 1import numpy as np
 2from trancit import generate_signals, PipelineOrchestrator
 3from trancit.config import (
 4    PipelineConfig, PipelineOptions, DetectionParams,
 5    CausalParams, BicParams, OutputParams
 6)
 7
 8# Generate synthetic data
 9data, _, _ = generate_signals(
10    T=1200, Ntrial=20, h=0.1,
11    gamma1=0.5, gamma2=0.5,
12    Omega1=1.0, Omega2=1.2
13)
14
15# Prepare signals for pipeline
16original_signal = np.mean(data, axis=2)  # Average across trials
17detection_signal = original_signal * 1.5  # Amplify for event detection
18
19# Configure the analysis pipeline
20config = PipelineConfig(
21    options=PipelineOptions(
22        detection=True,           # Enable event detection
23        bic=False,               # Skip BIC model selection (faster)
24        causal_analysis=True,    # Enable causality analysis
25        bootstrap=False,         # Skip bootstrap (faster)
26        save_flag=False,         # Don't save intermediate results
27        debiased_stats=False     # Skip debiased analysis
28    ),
29    detection=DetectionParams(
30        thres_ratio=2.0,         # Detection threshold (higher = fewer events)
31        align_type="peak",       # Align events to peaks
32        l_extract=150,           # Length of extracted windows
33        l_start=75,              # Start offset within windows
34        remove_artif=True        # Remove artifact-contaminated trials
35    ),
36    causal=CausalParams(
37        ref_time=75,             # Reference time for rDCS calculation
38        estim_mode="OLS"         # Ordinary Least Squares estimation
39    ),
40    bic=BicParams(morder=4),
41    output=OutputParams(file_keyword="quickstart_example")
42)
43
44# Run the analysis pipeline
45orchestrator = PipelineOrchestrator(config)
46
47try:
48    result = orchestrator.run(original_signal, detection_signal)
49
50    # Access results
51    if result.results.get("CausalOutput"):
52        causal_output = result.results["CausalOutput"]["OLS"]
53
54        if "DCS" in causal_output:
55            dcs_values = causal_output["DCS"]
56            print(f"DCS shape: {dcs_values.shape}")
57            print(f"Number of events detected: {dcs_values.shape[0]}")
58            print(f"Mean DCS (X→Y): {dcs_values[:, 1].mean():.4f}")
59            print(f"Mean DCS (Y→X): {dcs_values[:, 0].mean():.4f}")
60
61        if "TE" in causal_output:
62            te_values = causal_output["TE"]
63            print(f"Mean TE (X→Y): {te_values[:, 1].mean():.4f}")
64            print(f"Mean TE (Y→X): {te_values[:, 0].mean():.4f}")
65
66        if "rDCS" in causal_output:
67            rdcs_values = causal_output["rDCS"]
68            print(f"Mean rDCS (X→Y): {rdcs_values[:, 1].mean():.4f}")
69            print(f"Mean rDCS (Y→X): {rdcs_values[:, 0].mean():.4f}")
70    else:
71        print("No causal output generated - check signal characteristics")
72
73except Exception as e:
74    print(f"Pipeline analysis failed: {e}")
75    print("Tip: Try adjusting thres_ratio or using simpler configuration")

Key Pipeline Components:

  • Event Detection: Finds time windows of interest based on signal characteristics

  • Snapshot Extraction: Extracts fixed-length windows around detected events

  • Causality Analysis: Computes GC, TE, DCS, and rDCS for each event window

  • Bootstrap Analysis: Optional statistical significance testing

Different Types of Analysis

DCS provides several specialized calculators for different causality measures:

 1from trancit import (
 2    DCSCalculator,              # Dynamic Causal Strength
 3    TransferEntropyCalculator,  # Information-theoretic measure
 4    GrangerCausalityCalculator, # Linear causality detection
 5    RelativeDCSCalculator       # Event-based relative causality
 6)
 7
 8# Sample bivariate data
 9data = np.random.randn(2, 500, 15)
10
11# 1. Dynamic Causal Strength Analysis
12dcs_calc = DCSCalculator(model_order=3, time_mode="inhomo")
13dcs_result = dcs_calc.analyze(data)
14print(f"DCS computed for {dcs_result.causal_strength.shape[0]} time points")
15
16# 2. Transfer Entropy Analysis
17te_calc = TransferEntropyCalculator(model_order=3)
18te_result = te_calc.analyze(data)
19print(f"TE computed: {te_result.transfer_entropy.shape}")
20
21# 3. Granger Causality Analysis
22gc_calc = GrangerCausalityCalculator(model_order=3)
23gc_result = gc_calc.analyze(data)
24print(f"GC p-values shape: {gc_result.pvalues.shape}")
25
26# 4. Relative DCS (requires event data and statistics)
27# This is typically used within the pipeline, but can be used standalone
28# rdcs_calc = RelativeDCSCalculator(model_order=3, reference_time=25)
29# rdcs_result = rdcs_calc.analyze(event_data, event_stats)

Working with Real Data

Here’s how to apply DCS to your own time series data:

 1import numpy as np
 2from trancit import DCSCalculator
 3from trancit.utils.preprocess import normalize_data
 4
 5# Load your data (example with NumPy)
 6# Your data should have shape (n_variables, n_timepoints, n_trials)
 7# For DCS: n_variables must be 2 (bivariate analysis)
 8
 9# Example: loading data from a file
10# data = np.load('my_time_series.npy')  # Shape should be (2, T, N)
11
12# For demonstration, create sample data
13np.random.seed(42)
14
15# Simulate two coupled time series
16T, N = 1000, 25  # 1000 time points, 25 trials
17
18# Generate correlated signals (simple example)
19noise1 = np.random.randn(T, N)
20noise2 = np.random.randn(T, N)
21
22signal1 = np.zeros((T, N))
23signal2 = np.zeros((T, N))
24
25# Create coupling: X influences Y with delay
26for t in range(3, T):
27    signal1[t] = 0.7 * signal1[t-1] - 0.1 * signal1[t-2] + noise1[t]
28    signal2[t] = 0.6 * signal2[t-1] + 0.3 * signal1[t-3] + noise2[t]  # Y depends on past X
29
30# Arrange in DCS format: (n_vars, n_time, n_trials)
31data = np.array([signal1.T, signal2.T])
32
33print(f"Data shape: {data.shape}")
34
35# Optional: normalize your data
36data_normalized = normalize_data(data, method="zscore", axis=1)
37
38# Perform DCS analysis
39calculator = DCSCalculator(model_order=5, time_mode="inhomo")
40
41try:
42    result = calculator.analyze(data_normalized)
43
44    print("Analysis successful!")
45    print(f"X→Y causality: {result.causal_strength[:, 1].mean():.4f}")
46    print(f"Y→X causality: {result.causal_strength[:, 0].mean():.4f}")
47
48    # Plot results (optional)
49    try:
50        import matplotlib.pyplot as plt
51
52        plt.figure(figsize=(12, 4))
53        plt.subplot(1, 2, 1)
54        plt.plot(result.causal_strength[:, 1], label='X→Y', alpha=0.7)
55        plt.plot(result.causal_strength[:, 0], label='Y→X', alpha=0.7)
56        plt.xlabel('Time')
57        plt.ylabel('Causal Strength')
58        plt.legend()
59        plt.title('Dynamic Causal Strength')
60
61        plt.subplot(1, 2, 2)
62        plt.plot(result.transfer_entropy[:, 1], label='X→Y', alpha=0.7)
63        plt.plot(result.transfer_entropy[:, 0], label='Y→X', alpha=0.7)
64        plt.xlabel('Time')
65        plt.ylabel('Transfer Entropy')
66        plt.legend()
67        plt.title('Transfer Entropy')
68
69        plt.tight_layout()
70        plt.show()
71
72    except ImportError:
73        print("Install matplotlib to plot results: pip install matplotlib")
74
75except Exception as e:
76    print(f"Analysis failed: {e}")
77    print("Check your data format and try adjusting model_order")

Common Troubleshooting

Issue: “Input data must be bivariate”

  • DCS is designed for analyzing relationships between two time series

  • Ensure your data has shape (2, n_timepoints, n_trials)

Issue: “Insufficient observations”

  • Your time series is too short for the chosen model order

  • Try reducing model_order or collecting more data

  • Rule of thumb: need at least model_order * 10 time points

Issue: “Singular matrix errors”

  • Your data may have perfect correlations or insufficient variation

  • Try normalizing your data: normalize_data(data, method="zscore")

  • Consider adding small amount of noise for numerical stability

Issue: Pipeline finds no events

  • Your thres_ratio might be too high - try lowering it (e.g., 1.5 instead of 3.0)

  • Check if your detection signal has sufficient variability

  • Visualize your signal to understand its characteristics

What’s Next?

Now that you understand the basics:

  • Explore Examples: Check out examples/basic_usage.py and examples/lfp_pipeline.py

  • Read API Documentation: See API Reference for complete class and function references

  • Learn Advanced Features: Check Examples for specialized use cases

  • Understand the Science: Read about the theoretical background in our scientific paper

Configuration Tips:

  • Start with model_order=3 or 4 for most applications

  • Use time_mode="inhomo" for non-stationary signals (recommended)

  • Enable bootstrap=True in pipeline for statistical significance testing

  • Use BIC model selection for automatic model order selection

Need help? Check our ../TROUBLESHOOTING guide or open an issue on GitHub.