Examples
This section demonstrates practical use cases of the trancit package, ranging from basic synthetic simulations to real-world analysis pipelines.
All examples are available in the examples/ directory in the source code.
You can also explore them directly on GitHub:
Basic Usage Script
The basic_usage.py script demonstrates an end-to-end workflow using synthetic data. It includes:
Signal simulation
Minimal configuration of the pipeline
Running detection and analysis
Inspecting outputs (e.g., DCS values)
1"""
2Basic Usage Example for TranCIT: Transient Causal Interaction
3
4This example demonstrates the basic usage of the TranCIT package for
5causal inference in time series data.
6"""
7
8import numpy as np
9
10from trancit import PipelineOrchestrator, generate_signals
11from trancit.config import (
12 BicParams,
13 CausalParams,
14 DetectionParams,
15 MonteCParams,
16 OutputParams,
17 PipelineConfig,
18 PipelineOptions,
19)
20
21
22def main() -> None:
23 """
24 Demonstrate basic usage of the TranCIT package.
25
26 This function shows how to:
27 1. Generate synthetic time series data
28 2. Configure the analysis pipeline
29 3. Run the causal analysis
30 4. Access and interpret results
31 """
32 print("TranCIT: Transient Causal Interaction - Basic Usage Example")
33 print("=" * 60)
34
35 # Step 1: Generate synthetic data
36 print("\n1. Generating synthetic time series data...")
37 data = generate_synthetic_data()
38 print(f"Generated data shape: {data.shape}")
39
40 # Step 2: Prepare signals for analysis
41 print("\n2. Preparing signals for analysis...")
42 original_signal, detection_signal = prepare_signals(data)
43 print(f"Original signal shape: {original_signal.shape}")
44 print(f"Detection signal shape: {detection_signal.shape}")
45
46 # Step 3: Configure analysis pipeline
47 print("\n3. Configuring analysis pipeline...")
48 config = create_pipeline_config()
49 print("Configuration created successfully.")
50
51 # Step 4: Run analysis
52 print("\n4. Running causal analysis...")
53 results = run_analysis(original_signal, detection_signal, config)
54
55 # Step 5: Display results
56 print("\n5. Analysis results:")
57 display_results(results)
58
59
60def generate_synthetic_data() -> np.ndarray:
61 """
62 Generate synthetic time series data for demonstration.
63
64 Returns
65 -------
66 np.ndarray
67 Synthetic data with shape (2, T, Ntrial)
68 """
69 # Parameters for synthetic data generation
70 T = 1200 # Total time points
71 Ntrial = 20 # Number of trials
72 h = 0.1 # Time step
73 gamma1 = 0.5 # Damping coefficient 1
74 gamma2 = 0.5 # Damping coefficient 2
75 Omega1 = 1.0 # Natural frequency 1
76 Omega2 = 1.2 # Natural frequency 2
77
78 # Generate coupled oscillator signals
79 data, _, _ = generate_signals(
80 T=T,
81 Ntrial=Ntrial,
82 h=h,
83 gamma1=gamma1,
84 gamma2=gamma2,
85 Omega1=Omega1,
86 Omega2=Omega2,
87 )
88
89 return data
90
91
92def prepare_signals(data: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
93 """
94 Prepare signals for causal analysis.
95
96 Parameters
97 ----------
98 data : np.ndarray
99 Raw time series data with shape (2, T, Ntrial)
100
101 Returns
102 -------
103 tuple[np.ndarray, np.ndarray]
104 original_signal: Trial-averaged signal
105 detection_signal: Signal for event detection
106 """
107 # Compute trial-averaged signal
108 original_signal = np.mean(data, axis=2)
109
110 # Create detection signal (amplified version for event detection)
111 detection_signal = original_signal * 1.5
112
113 return original_signal, detection_signal
114
115
116def create_pipeline_config() -> PipelineConfig:
117 """
118 Create configuration for the analysis pipeline.
119
120 Returns
121 -------
122 PipelineConfig
123 Configured pipeline settings
124 """
125 return PipelineConfig(
126 options=PipelineOptions(
127 detection=True,
128 bic=False,
129 causal_analysis=True,
130 bootstrap=False,
131 save_flag=False,
132 debiased_stats=False,
133 ),
134 detection=DetectionParams(
135 thres_ratio=2.0,
136 align_type="peak",
137 l_extract=150,
138 l_start=75,
139 remove_artif=True,
140 ),
141 bic=BicParams(morder=4),
142 causal=CausalParams(ref_time=75, estim_mode="OLS"),
143 monte_carlo=MonteCParams(n_btsp=50),
144 output=OutputParams(file_keyword="example_run"),
145 )
146
147
148def run_analysis(
149 original_signal: np.ndarray,
150 detection_signal: np.ndarray,
151 config: PipelineConfig,
152) -> dict:
153 """
154 Run the causal analysis pipeline.
155
156 Parameters
157 ----------
158 original_signal : np.ndarray
159 Original time series data
160 detection_signal : np.ndarray
161 Signal used for event detection
162 config : PipelineConfig
163 Pipeline configuration
164
165 Returns
166 -------
167 dict
168 Analysis results
169 """
170 try:
171 # Run the complete analysis pipeline
172 orchestrator = PipelineOrchestrator(config)
173 pipeline_result = orchestrator.run(original_signal, detection_signal)
174
175 results = pipeline_result.results
176 pipeline_result.config
177 pipeline_result.event_snapshots
178
179 print("✓ Pipeline completed successfully!")
180 return results
181
182 except Exception as e:
183 print(f"✗ Pipeline failed with error: {e}")
184 raise
185
186
187def display_results(results: dict) -> None:
188 """
189 Display and interpret analysis results.
190
191 Parameters
192 ----------
193 results : dict
194 Results from the analysis pipeline
195 """
196 print(f"Number of detected events: {len(results.get('locs', []))}")
197 print(f"Model order used: {results.get('morder', 'N/A')}")
198
199 if results.get("CausalOutput"):
200 causal_output = results["CausalOutput"]["OLS"]
201
202 # Display DCS results
203 if "DCS" in causal_output:
204 dcs_values = causal_output["DCS"]
205 print(f"DCS result shape: {dcs_values.shape}")
206 print(f"Mean DCS (X→Y): {np.mean(dcs_values[:, 0]):.4f}")
207 print(f"Mean DCS (Y→X): {np.mean(dcs_values[:, 1]):.4f}")
208
209 # Display Transfer Entropy results
210 if "TE" in causal_output:
211 te_values = causal_output["TE"]
212 print(f"Transfer Entropy shape: {te_values.shape}")
213 print(f"Mean TE (X→Y): {np.mean(te_values[:, 0]):.4f}")
214 print(f"Mean TE (Y→X): {np.mean(te_values[:, 1]):.4f}")
215
216 # Display rDCS results
217 if "rDCS" in causal_output:
218 rdcs_values = causal_output["rDCS"]
219 print(f"Relative DCS shape: {rdcs_values.shape}")
220 print(f"Mean rDCS (X→Y): {np.mean(rdcs_values[:, 0]):.4f}")
221 print(f"Mean rDCS (Y→X): {np.mean(rdcs_values[:, 1]):.4f}")
222 else:
223 print("No causal output available.")
224
225
226if __name__ == "__main__":
227 main()
Reproducing a Scientific Figure (Jupyter Notebook)
The notebook dcs_introduction.ipynb shows how to replicate Figure 4 from the associated scientific paper [https://www.frontiersin.org/journals/network-physiology/articles/10.3389/fnetp.2023.1085347/full]. It highlights:
A more complex setup with real signal dynamics
Visual interpretation of detection windows and causal strength
Parameter tuning for reproducibility
You can open the notebook locally or online:
Advanced Pipeline Example
For a more advanced and modular demonstration, check out lfp_pipeline.py. This script includes:
Example of real neural signal preprocessing
Flexible parameter configuration using dataclasses
Logging and structure suitable for batch jobs or publication workflows
More Coming Soon!
More examples will be added over time. Contributions are welcome — see the contributing guide for details!