summaryrefslogtreecommitdiff
path: root/examples/example_quick_start.py
blob: d5c45e4dcf4f6cc49ed69ee30cb8190a0d134024 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
"""
Quick start example demonstrating the simplified transivent API.

This shows the two main entry points:
1. detect() - for custom time-series data
2. detect_from_wfm() - for Wfm files with XML sidecars
"""

import numpy as np
from transivent import detect, detect_from_wfm, EventPlotter

print("=" * 60)
print("TRANSIVENT QUICK START")
print("=" * 60)

# ============================================================================
# EXAMPLE 1: Detect events in custom time-series data
# ============================================================================
print("\n[Example 1] Custom time-series data")
print("-" * 60)

# Generate synthetic data
np.random.seed(42)
duration = 0.05  # 50 ms
sampling_rate = 2_000_000  # 2 MHz
n_points = int(duration * sampling_rate)
t = np.linspace(0, duration, n_points)

# Background noise
x = np.random.randn(n_points) * 0.1

# Add synthetic negative spikes
spike_times = [0.01, 0.023, 0.037, 0.045]
spike_amplitudes = [-1.5, -2.0, -0.8, -1.2]
spike_width = 50

for spike_t, amp in zip(spike_times, spike_amplitudes):
    spike_idx = int(spike_t * sampling_rate)
    spike_start = max(0, spike_idx - spike_width // 2)
    spike_end = min(n_points, spike_idx + spike_width // 2)
    x[spike_start:spike_end] += amp * np.exp(
        -0.5 * ((np.arange(spike_start, spike_end) - spike_idx) / (spike_width / 4))**2
    )

print(f"Generated synthetic data: {n_points} points at {sampling_rate/1e6:.1f} MHz")

# Detect events
results = detect(
    t, x,
    name="Synthetic Data",
    detection_snr=3.0,
    min_event_keep_snr=6.0,
    signal_polarity=-1,  # Negative spikes
    save_plots=False,
)

events = results["events"]
print(f"✓ Found {len(events)} events")
print(f"✓ Noise level: {results['global_noise']:.3e}")

for i, (start, end) in enumerate(events):
    duration_us = (end - start) * 1e6
    print(f"    Event {i+1}: {start:.6f}s to {end:.6f}s ({duration_us:.2f} µs)")

# Access other results
print(f"✓ Results contain: {list(results.keys())}")

# ============================================================================
# EXAMPLE 2: Advanced - Build custom pipeline with building blocks
# ============================================================================
print("\n[Example 2] Custom pipeline with building blocks")
print("-" * 60)

from transivent.analysis import (
    calculate_initial_background,
    estimate_noise,
    detect_initial_events,
)

# Manual pipeline for advanced control
smooth_n = 101
bg_initial = calculate_initial_background(t, x, smooth_n, filter_type="gaussian")
global_noise = estimate_noise(x, bg_initial)
print(f"✓ Calculated background (smooth_n={smooth_n})")
print(f"✓ Estimated noise: {global_noise:.3e}")

# ============================================================================
# EXAMPLE 3: Visualize events
# ============================================================================
print("\n[Example 3] Visualizing events")
print("-" * 60)

if results["plot"] is not None and len(events) > 0:
    event_plotter = EventPlotter(
        results["plot"],
        events,
        bg_clean=results["bg_clean"],
        global_noise=results["global_noise"],
    )
    print(f"✓ Created event plotter for {len(events)} events")
    print(f"✓ Can call event_plotter.plot_events_grid(max_events=16)")
    print(f"✓ Can call event_plotter.save('path.png')")

# ============================================================================
# EXAMPLE 4: Using Wfm files (if you have them)
# ============================================================================
print("\n[Example 4] Wfm file format (for reference)")
print("-" * 60)
print("""
To analyze Wfm files with XML sidecars:

    results = detect_from_wfm(
        name="data.Wfm.bin",
        sampling_interval=5e-7,
        data_path="/path/to/data/",
        detection_snr=3.0,
    )
    
    events = results["events"]
    print(f"Found {len(events)} events")
""")

print("\n" + "=" * 60)
print("QUICK START COMPLETE")
print("=" * 60)
print("\nKey takeaways:")
print("  1. Use detect() for any time-series data")
print("  2. Use detect_from_wfm() for proprietary Wfm files")
print("  3. All results are returned as a dict")
print("  4. Access building blocks via transivent.analysis for custom pipelines")
print("\nFor more info, see the README or run the other examples.")