evlib 0.8.6

Event Camera Data Processing Library
Documentation
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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
# Architecture

evlib architecture overview: a high-performance event camera processing library with Rust core and Python bindings.

## Design Philosophy

### Core Principles

1. **Rust Backend, Python Frontend**: Leverage Rust's performance and safety with Python's ease of use
2. **Zero-Copy Operations**: Minimize memory allocations and data copying
3. **Real Data Validation**: All features tested with real event camera datasets
4. **Production Ready**: Robust error handling and edge case management

### Performance Strategy

- **Complex algorithms in Rust**: Voxel grids, neural networks, file I/O
- **Simple operations in Python**: Basic array manipulations, plotting
- **Honest benchmarking**: Document real performance characteristics

## System Architecture

### High-Level Overview

```
┌─────────────────────────────────────────────────────────────┐
│                    Python Frontend                          │
│  ┌─────────────┐ ┌─────────────┐ ┌─────────────┐          │
│  │   evlib.    │ │   evlib.    │ │   evlib.    │          │
│  │ formats     │ │ represent-  │ │ processing  │   ...    │
│  │             │ │ ations      │ │             │          │
│  └─────────────┘ └─────────────┘ └─────────────┘          │
└─────────────────────────────────────────────────────────────┘
           │                    │                    │
           │                    │                    │
           ▼                    ▼                    ▼
┌─────────────────────────────────────────────────────────────┐
│                     PyO3 Bindings                           │
└─────────────────────────────────────────────────────────────┘
           │                    │                    │
           │                    │                    │
           ▼                    ▼                    ▼
┌─────────────────────────────────────────────────────────────┐
│                     Rust Core                               │
│  ┌─────────────┐ ┌─────────────┐ ┌─────────────┐          │
│  │ ev_formats  │ │ ev_repre-   │ │ ev_process- │   ...    │
│  │             │ │ sentations  │ │ ing         │          │
│  └─────────────┘ └─────────────┘ └─────────────┘          │
└─────────────────────────────────────────────────────────────┘
```

### Module Hierarchy

```
evlib/
├── src/                           # Rust source code
│   ├── ev_core/                  # Core data structures
│   │   ├── mod.rs               # Event arrays, validation
│   │   └── types.rs             # Type definitions
│   ├── ev_formats/               # File I/O operations
│   │   ├── mod.rs               # Public API
│   │   ├── text.rs              # Text file loading
│   │   └── hdf5.rs              # HDF5 file operations
│   ├── ev_representations/       # Event representations
│   │   ├── mod.rs               # Public API
│   │   ├── voxel_grid.rs        # Standard voxel grids
│   │   └── smooth_voxel.rs      # Smooth voxel grids
│   ├── ev_processing/            # Neural networks
│   │   ├── mod.rs               # Public API
│   │   ├── e2vid.rs             # E2VID implementations
│   │   └── pytorch_loader.rs    # PyTorch model loading
│   ├── ev_transforms/            # Spatial transformations
│   │   ├── mod.rs               # Public API
│   │   ├── flip.rs              # Flip operations
│   │   └── noise.rs             # Noise addition
│   ├── ev_visualization/         # Visualization
│   │   ├── mod.rs               # Public API
│   │   ├── terminal.rs          # Terminal visualization
│   │   └── web_server.rs        # Web visualization
│   ├── ev_tracking/              # Event tracking
│   │   ├── mod.rs               # Public API
│   │   └── etap.rs              # ETAP integration
│   └── lib.rs                    # Python bindings
└── python/                       # Python package structure
    └── evlib/                    # Python module
        ├── __init__.py          # Package initialization
        ├── formats.py           # File format wrappers
        ├── representations.py   # Representation wrappers
        ├── processing.py        # Processing wrappers
        ├── augmentation.py      # Augmentation wrappers
        └── visualization.py     # Visualization wrappers
```

## Data Flow Architecture

### Event Data Pipeline

```
┌─────────────┐    ┌─────────────┐    ┌─────────────┐    ┌─────────────┐
│   Raw       │    │   Parsed    │    │   Filtered  │    │   Processed │
│   Files     │───►│   Events    │───►│   Events    │───►│   Output    │
│             │    │             │    │             │    │             │
└─────────────┘    └─────────────┘    └─────────────┘    └─────────────┘
      │                    │                    │                    │
      │                    │                    │                    │
      ▼                    ▼                    ▼                    ▼
┌─────────────┐    ┌─────────────┐    ┌─────────────┐    ┌─────────────┐
│ Text/HDF5   │    │ Event       │    │ Time/Space  │    │ Voxel Grid  │
│ Files       │    │ Arrays      │    │ Windowing   │    │ Representa- │
│             │    │ (xs,ys,ts,ps│    │             │    │ tions       │
└─────────────┘    └─────────────┘    └─────────────┘    └─────────────┘
```

### Memory Management

```
┌─────────────────────────────────────────────────────────────┐
│                     Memory Layout                            │
│                                                             │
│  ┌─────────────┐ ┌─────────────┐ ┌─────────────┐          │
│  │ Event Data  │ │ Voxel Grid  │ │ Model       │          │
│  │ (Stack)     │ │ (Heap)      │ │ Weights     │          │
│  │             │ │             │ │ (Heap)      │          │
│  │ xs: u16[]   │ │ f32[][][]   │ │ PyTorch     │          │
│  │ ys: u16[]   │ │             │ │ Model       │          │
│  │ ts: f64[]   │ │             │ │             │          │
│  │ ps: i8[]    │ │             │ │             │          │
│  └─────────────┘ └─────────────┘ └─────────────┘          │
└─────────────────────────────────────────────────────────────┘
```

## Core Components

### Event Data Structure

```rust
// src/ev_core/types.rs
#[derive(Debug, Clone)]
pub struct EventData {
    pub xs: Vec<u16>,      // X coordinates
    pub ys: Vec<u16>,      // Y coordinates
    pub ts: Vec<f64>,      // Timestamps
    pub ps: Vec<i8>,       // Polarities
}

impl EventData {
    pub fn new(xs: Vec<u16>, ys: Vec<u16>, ts: Vec<f64>, ps: Vec<i8>) -> Self {
        Self { xs, ys, ts, ps }
    }

    pub fn len(&self) -> usize {
        self.xs.len()
    }

    pub fn validate(&self) -> Result<(), EventError> {
        // Comprehensive validation
    }
}
```

### File I/O Architecture

```rust
// src/ev_formats/mod.rs
pub trait EventLoader {
    fn load_events(&self, path: &str, config: &LoadConfig) -> Result<EventData, FormatError>;
}

pub struct TextLoader;
pub struct HDF5Loader;

impl EventLoader for TextLoader {
    fn load_events(&self, path: &str, config: &LoadConfig) -> Result<EventData, FormatError> {
        // Text file parsing with filtering
    }
}

impl EventLoader for HDF5Loader {
    fn load_events(&self, path: &str, config: &LoadConfig) -> Result<EventData, FormatError> {
        // HDF5 file loading with filtering
    }
}
```

### Representation Architecture

```rust
// src/ev_representations/mod.rs
pub trait EventRepresentation {
    type Output;

    fn create(&self, events: &EventData, config: &RepresentationConfig) -> Self::Output;
}

pub struct VoxelGrid;
pub struct SmoothVoxelGrid;

impl EventRepresentation for VoxelGrid {
    type Output = Array3<f32>;

    fn create(&self, events: &EventData, config: &RepresentationConfig) -> Self::Output {
        // Voxel grid creation
    }
}
```

## PyO3 Integration

### Binding Architecture

```rust
// src/lib.rs
use pyo3::prelude::*;

#[pymodule]
fn evlib(_py: Python, m: &PyModule) -> PyResult<()> {
    // Core module
    m.add_function(wrap_pyfunction!(load_events, m)?)?;

    // Representations
    m.add_function(wrap_pyfunction!(create_voxel_grid, m)?)?;
    m.add_function(wrap_pyfunction!(create_smooth_voxel_grid, m)?)?;

    // Processing
    m.add_function(wrap_pyfunction!(events_to_video, m)?)?;

    Ok(())
}
```

### Type Conversion

```rust
// Convert Python types to Rust types
#[pyfunction]
fn load_events(
    file_path: String,
    t_start: Option<f64>,
    t_end: Option<f64>,
    // ... other parameters
) -> PyResult<(Vec<u16>, Vec<u16>, Vec<f64>, Vec<i8>)> {

    // Create load configuration
    let config = LoadConfig {
        t_start,
        t_end,
        ..Default::default()
    };

    // Load events
    let events = ev_formats::load_events(&file_path, &config)
        .map_err(|e| PyErr::new::<pyo3::exceptions::PyIOError, _>(e.to_string()))?;

    // Convert to Python types
    Ok((events.xs, events.ys, events.ts, events.ps))
}
```

## Neural Network Integration

### Model Loading Architecture

```rust
// src/ev_processing/mod.rs
pub enum ModelBackend {
    PyTorch(PyTorchModel),
    ONNX(OnnxModel),
}

pub struct PyTorchModel {
    model: tch::CModule,
}

pub struct OnnxModel {
    session: ort::Session,
}

impl ModelBackend {
    pub fn load(path: &str, backend: &str) -> Result<Self, ModelError> {
        match backend {
            "pytorch" => Ok(ModelBackend::PyTorch(PyTorchModel::load(path)?)),
            "onnx" => Ok(ModelBackend::ONNX(OnnxModel::load(path)?)),
            _ => Err(ModelError::UnsupportedBackend(backend.to_string())),
        }
    }

    pub fn predict(&self, input: &Array3<f32>) -> Result<Array3<f32>, ModelError> {
        match self {
            ModelBackend::PyTorch(model) => model.predict(input),
            ModelBackend::ONNX(model) => model.predict(input),
        }
    }
}
```

### E2VID Integration

```rust
// src/ev_processing/e2vid.rs
pub struct E2VIDModel {
    backend: ModelBackend,
    config: E2VIDConfig,
}

impl E2VIDModel {
    pub fn new(model_path: &str) -> Result<Self, ModelError> {
        let backend = ModelBackend::load(model_path, "pytorch")?;
        let config = E2VIDConfig::default();
        Ok(Self { backend, config })
    }

    pub fn events_to_video(&self, events: &EventData) -> Result<Array3<f32>, ModelError> {
        // Convert events to voxel grid
        let voxel_grid = VoxelGrid.create(events, &self.config.voxel_config);

        // Run inference
        self.backend.predict(&voxel_grid)
    }
}
```

## Performance Optimization

### Memory Layout

```rust
// Optimize for cache locality
#[repr(C)]
pub struct EventBatch {
    pub count: usize,
    pub xs: *mut u16,
    pub ys: *mut u16,
    pub ts: *mut f64,
    pub ps: *mut i8,
}

// SIMD operations for bulk processing
use std::simd::*;

pub fn process_events_simd(events: &[Event]) -> Vec<ProcessedEvent> {
    // Vectorized processing
}
```

### Parallel Processing

```rust
use rayon::prelude::*;

pub fn create_voxel_grid_parallel(events: &EventData, config: &VoxelConfig) -> Array3<f32> {
    // Parallel voxel grid creation
    events.par_chunks(1000)
        .map(|chunk| process_chunk(chunk, config))
        .reduce(|| Array3::zeros((config.bins, config.height, config.width)),
                |acc, chunk| acc + chunk)
}
```

## Error Handling

### Error Types

```rust
// src/ev_core/error.rs
#[derive(Debug, thiserror::Error)]
pub enum EventError {
    #[error("Invalid event data: {0}")]
    InvalidData(String),

    #[error("Array length mismatch: expected {expected}, got {actual}")]
    ArrayLengthMismatch { expected: usize, actual: usize },

    #[error("Timestamp order violation at index {index}")]
    TimestampOrderViolation { index: usize },
}

#[derive(Debug, thiserror::Error)]
pub enum FormatError {
    #[error("File not found: {0}")]
    FileNotFound(String),

    #[error("Invalid file format: {0}")]
    InvalidFormat(String),

    #[error("HDF5 error: {0}")]
    HDF5Error(#[from] hdf5::Error),
}
```

### Error Propagation

```rust
// Consistent error handling across modules
pub fn load_events(path: &str, config: &LoadConfig) -> Result<EventData, FormatError> {
    let raw_data = read_file(path)?;
    let events = parse_events(raw_data)?;
    let validated = events.validate()
        .map_err(|e| FormatError::InvalidFormat(e.to_string()))?;
    Ok(validated)
}
```

## Testing Architecture

### Test Organization

```
tests/
├── integration/           # End-to-end tests
│   ├── test_pipeline.py  # Full pipeline tests
│   └── test_models.py    # Model integration tests
├── unit/                 # Unit tests
│   ├── test_formats.py   # File I/O tests
│   ├── test_reprs.py     # Representation tests
│   └── test_core.py      # Core functionality tests
├── benchmarks/           # Performance benchmarks
│   ├── test_benchmarks.py
│   └── benchmark_utils.py
└── data/                 # Test data
    ├── slider_depth/     # Primary test dataset
    └── synthetic/        # Generated test data
```

### Test Data Management

```rust
// src/testing/mod.rs
pub struct TestDataset {
    pub name: String,
    pub events: EventData,
    pub metadata: DatasetMetadata,
}

impl TestDataset {
    pub fn slider_depth() -> Self {
        // Load standard test dataset
    }

    pub fn synthetic(config: &SyntheticConfig) -> Self {
        // Generate synthetic events
    }
}
```

## Build System

### Maturin Configuration

```toml
# pyproject.toml
[build-system]
requires = ["maturin>=1.3.2"]
build-backend = "maturin"

[project]
name = "evlib"
dynamic = ["version"]
dependencies = [
    "numpy>=1.24.0",
]

[tool.maturin]
bindings = "pyo3"
features = ["pyo3/extension-module"]
```

### Feature Flags

```toml
# Cargo.toml
[features]
default = ["hdf5"]
hdf5 = ["dep:hdf5"]
pytorch = ["dep:tch"]
cuda = ["tch/cuda"]
mkl = ["tch/mkl"]
```

## Documentation Architecture

### API Documentation

```rust
/// Load events from file with filtering options
///
/// # Arguments
///
/// * `file_path` - Path to event file
/// * `t_start` - Start time filter (optional)
/// * `t_end` - End time filter (optional)
///
/// # Returns
///
/// Event arrays (xs, ys, ts, ps)
///
/// # Errors
///
/// Returns `FormatError` if file cannot be loaded or parsed
///
/// # Examples
///
/// ```rust
/// let events = load_events("data/slider_depth/events.txt", Some(0.0), Some(1.0))?;
/// ```
pub fn load_events(
    file_path: &str,
    t_start: Option<f64>,
    t_end: Option<f64>
) -> Result<EventData, FormatError> {
    // Implementation
}
```

### Cross-Language Documentation

- **Rust docs**: `cargo doc --open`
- **Python docs**: Generated from docstrings
- **User guides**: Markdown documentation
- **Examples**: Jupyter notebooks

## Deployment Architecture

### Package Distribution

```
┌─────────────────────────────────────────────────────────────┐
│                    PyPI Distribution                         │
│                                                             │
│  ┌─────────────┐ ┌─────────────┐ ┌─────────────┐          │
│  │ Linux       │ │ macOS       │ │ Windows     │          │
│  │ x86_64      │ │ x86_64      │ │ x86_64      │          │
│  │ aarch64     │ │ aarch64     │ │             │          │
│  └─────────────┘ └─────────────┘ └─────────────┘          │
└─────────────────────────────────────────────────────────────┘
```

### CI/CD Pipeline

```yaml
# .github/workflows/ci.yml
name: CI
on: [push, pull_request]

jobs:
  test:
    strategy:
      matrix:
        os: [ubuntu-latest, macos-latest, windows-latest]
        python-version: ["3.10", "3.11", "3.12"]

    steps:
      - uses: actions/checkout@v4
      - name: Set up Python
        uses: actions/setup-python@v4
        with:
          python-version: ${{ matrix.python-version }}
      - name: Install dependencies
        run: |
          pip install maturin
          maturin develop
      - name: Run tests
        run: pytest
```

## Future Architecture Considerations

### Planned Enhancements

1. **GPU Acceleration**: CUDA/OpenCL support for voxel grid creation
2. **Distributed Processing**: Multi-node event processing
3. **Real-time Streaming**: Live event camera integration
4. **Advanced Models**: Transformer-based architectures
5. **Language Bindings**: C++, Julia, R support

### Scalability

- **Memory management**: Streaming large datasets
- **Parallel processing**: Multi-GPU support
- **Cloud deployment**: Containerized processing
- **Edge computing**: Embedded device support

---

*This architecture balances performance, maintainability, and ease of use while providing a solid foundation for event-based vision applications.*