evlib 0.12.0

Event Camera Data Processing Library
Documentation
# Quick Start

Get up and running with evlib in 5 minutes!

## Basic Event Loading

```python
import evlib
import polars as pl

# Load events from a text file (returns Polars LazyFrame)
events = evlib.load_events("data/slider_depth/events.txt")
df = events.collect()  # Get DataFrame if needed
print(f"Loaded {len(df)} events")

# Access data columns
xs = df['x'].to_numpy()
ys = df['y'].to_numpy()
ts = df['t'].to_numpy()
ps = df['polarity'].to_numpy()
```

## Event Filtering

The `evlib.filtering` module provides ready-made lazy filters. You can also write filters directly as Polars expressions; remember `t` is a Duration column.

```python
import evlib
import evlib.filtering as evf
import polars as pl

events = evlib.load_events("data/slider_depth/events.txt")

# Time window filtering (t_start/t_end are in seconds)
filtered_events = evf.filter_by_time(events, t_start=0.0, t_end=1.0)
df = filtered_events.collect()

# Spatial bounds filtering
spatial_events = evf.filter_by_roi(events, x_min=100, x_max=500, y_min=100, y_max=300)
df = spatial_events.collect()

# Polarity filtering
pos_events = evf.filter_by_polarity(events, polarity=1)   # Positive events only
neg_events = evf.filter_by_polarity(events, polarity=-1)  # Negative events only

# Or write the same filters as Polars expressions directly:
expr_filtered = events.filter(
    (pl.col('t').dt.total_microseconds() / 1_000_000).is_between(0.0, 1.0)
    & pl.col('x').is_between(100, 500)
    & (pl.col('polarity') == 1)
)
df = expr_filtered.collect()
```

## Event Representations

```python
import evlib
import evlib.representations as evr

events = evlib.load_events("data/slider_depth/events.txt")

# Voxel grid (Zhu et al. 2019 event volume)
voxel_df = evr.create_voxel_grid(events, height=480, width=640, n_time_bins=5)
print(f"Voxel grid entries: {len(voxel_df)}")

# Event frame (tonic to_frame semantics)
frame_df = evr.create_event_frame(events, height=480, width=640, n_time_bins=10)
print(f"Event frame entries: {len(frame_df)}")

# Stacked histogram (RVT-compatible)
hist_df = evr.create_stacked_histogram(
    events, height=480, width=640, bins=10, window_duration_ms=50.0
)
print(f"Stacked histogram entries: {len(hist_df)}")
```

## Event Visualization

```python
import numpy as np

# Load events first
events = evlib.load_events("data/slider_depth/events.txt")
df = events.collect()
xs = df['x'].to_numpy()
ys = df['y'].to_numpy()
ts = df['t'].to_numpy()
ps = df['polarity'].to_numpy()

print(f"Loaded {len(df)} events for visualization")
print(f"Event data shape: x={xs.shape}, y={ys.shape}, t={ts.shape}, p={ps.shape}")

# Note: For actual plotting, install matplotlib and use:
# import matplotlib.pyplot as plt
# plt.scatter(xs[:10000], ys[:10000], c=ps[:10000], cmap='RdBu_r', s=0.1)
# plt.show()
```

## Event Augmentation

```python
import numpy as np

# Load events first
events = evlib.load_events("data/slider_depth/events.txt")
df = events.collect()
xs = df['x'].to_numpy()
ys = df['y'].to_numpy()
ps = df['polarity'].to_numpy()

# Spatial flip using numpy
xs_flipped = 640 - 1 - xs  # Horizontal flip
ys_flipped = ys.copy()
ps_aug = ps.copy()

print(f"Original events: {len(xs)}")
print(f"Flipped coordinates: x_max={xs_flipped.max()}, x_min={xs_flipped.min()}")

# Note: For timestamp-based augmentation, handle the duration[μs] format properly
# or convert to numeric values first
```

## Neural Network Models

E2VID and RVT models are available in Python via `evlib.models` (requires `pip install evlib[torch]`):

```python notest
from evlib.models import E2VID, RVT
```

For RVT-identical preprocessing, use `evlib.rvt.process_sequence(...)`, which offers four backends (`polars`, `rust`, `cuda`, `metal`).

## File Format Support

### Text Files
```python
# Standard format: t x y polarity
# 0.1 320 240 1
# 0.2 321 241 -1
events = evlib.load_events("data/slider_depth/events.txt")
df = events.collect()
xs, ys, ts, ps = df['x'].to_numpy(), df['y'].to_numpy(), df['t'].to_numpy(), df['polarity'].to_numpy()
```

### HDF5 Files
```python
import numpy as np

# Load events first
events = evlib.load_events("data/slider_depth/events.txt")
df = events.collect()

# Ensure correct dtypes for save function
xs = df['x'].to_numpy().astype(np.int64)
ys = df['y'].to_numpy().astype(np.int64)
ps = df['polarity'].to_numpy().astype(np.int64)
# Convert Duration timestamps to seconds (float64)
ts = df['t'].dt.total_seconds().to_numpy().astype(np.float64)

# Save events to HDF5 format
output_path = "quickstart_output.h5"
evlib.formats.save_events_to_hdf5(xs, ys, ts, ps, output_path)
print(f"Successfully saved {len(xs)} events to HDF5 format")

# Note: For loading HDF5 files, use existing dataset files
# The save function uses internal type conversions for efficiency
# To continue working with the data, use the original DataFrame:
print(f"Working with {len(df)} events from original DataFrame")
```

### Custom Column Mapping
```python
# For files with different column order: x y polarity t
# Note: Column mapping not currently supported in this version
# Use standard format: t x y polarity
events = evlib.load_events("data/slider_depth/events.txt")
df = events.collect()
xs, ys, ts, ps = df['x'].to_numpy(), df['y'].to_numpy(), df['t'].to_numpy(), df['polarity'].to_numpy()
```

## Performance Tips

### When to Use evlib vs NumPy

SUCCESS: **Use evlib for:**
- Large datasets (>100k events)
- Complex event processing algorithms
- Memory-efficient operations
- Production event processing pipelines

SUCCESS: **Use NumPy for:**
- Simple array operations
- Small datasets (<10k events)
- Rapid prototyping
- Maximum single-operation speed

### Example Performance Comparison
```python
import time
import numpy as np

# Large dataset example
events = evlib.load_events("data/slider_depth/events.txt")  # 1M+ events
start = time.time()
df = events.collect()
load_time = time.time() - start

print(f"Data loading: {load_time:.3f}s for {len(df):,} events")
print(f"Loading rate: {len(df)/load_time:.0f} events/sec")
print(f"Event columns: {df.columns}")
```

## Error Handling

```python
try:
    events = evlib.load_events("nonexistent.txt")
except OSError as e:
    print(f"File error: {e}")

# Example with valid file
try:
    events = evlib.load_events("data/slider_depth/events.txt")
    df = events.collect()
    print(f"Successfully loaded {len(df)} events")
except OSError as e:
    print(f"Error loading events: {e}")
```

## Next Steps

- [Loading Data Guide]../user-guide/loading-data.md
- [Event Representations Guide]../user-guide/representations.md
- [Performance Guide]performance.md