flow-gates 0.1.1

Package for drawing and interacting with gates in flow cytometry data
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
# flow-gates

A comprehensive Rust library for working with gates in flow cytometry data analysis. This library provides tools for creating, managing, and applying gates to flow cytometry data, supporting the GatingML 2.0 standard for gate definitions and hierarchies.

## Features

- **Multiple Gate Types**: Polygon, Rectangle, and Ellipse geometries
- **Gate Hierarchies**: Parent-child relationships for sequential gating strategies
- **Efficient Event Filtering**: Spatial indexing (R*-tree) for fast point-in-gate queries
- **Comprehensive Statistics**: Detailed statistical analysis of gated populations
- **GatingML 2.0 Support**: Import/export gates in standard XML format
- **Thread-Safe Storage**: Concurrent gate management with optional persistence
- **Zero-Copy Operations**: Efficient data access using slices where possible

## Installation

Add this to your `Cargo.toml`:

```toml
[dependencies]
flow-gates = { path = "../flow-gates" }
flow-fcs = { path = "../flow-fcs" }  # Required for FCS file support
```

## Quick Start

### Creating a Gate

```rust
use flow_gates::*;
use flow_gates::geometry::*;

// Create a polygon gate from coordinates
let coords = vec![
    (100.0, 200.0),
    (300.0, 200.0),
    (300.0, 400.0),
    (100.0, 400.0),
];
let geometry = create_polygon_geometry(coords, "FSC-A", "SSC-A")?;

let gate = Gate::new(
    "lymphocytes",
    "Lymphocytes",
    geometry,
    "FSC-A",
    "SSC-A",
);
```

### Filtering Events

```rust
use flow_gates::{filter_events_by_gate, Gate};
use flow_fcs::Fcs;

// Load FCS file
let fcs = Fcs::from_file("data.fcs")?;

// Filter events by gate
let event_indices = filter_events_by_gate(&fcs, &gate, None)?;

println!("Found {} events in gate", event_indices.len());
```

### Calculating Statistics

```rust
use flow_gates::GateStatistics;

let stats = GateStatistics::calculate(&fcs, &gate)?;

println!("Event count: {}", stats.event_count);
println!("Percentage: {:.2}%", stats.percentage);
println!("X parameter mean: {:.2}", stats.x_stats.mean);
println!("Y parameter median: {:.2}", stats.y_stats.median);
```

## Core Concepts

### Gates

A `Gate` represents a region of interest in 2D parameter space. Each gate has:

- **Geometry**: The shape (polygon, rectangle, or ellipse)
- **Parameters**: Two channels (x and y) the gate operates on
- **Mode**: Scope (global, file-specific, or file group)
- **ID and Name**: Unique identifier and human-readable name

### Gate Types

#### Polygon Gates

Polygon gates are defined by a series of vertices forming a closed or open polygon:

```rust
use flow_gates::{Gate, GateGeometry, GateNode, geometry::*};

let coords = vec![
    (100.0, 200.0),
    (300.0, 200.0),
    (300.0, 400.0),
    (100.0, 400.0),
];
let geometry = create_polygon_geometry(coords, "FSC-A", "SSC-A")?;

let gate = Gate::new("polygon-gate", "Polygon", geometry, "FSC-A", "SSC-A");
```

#### Rectangle Gates

Rectangle gates are axis-aligned rectangular regions:

```rust
let coords = vec![(100.0, 200.0), (500.0, 600.0)];
let geometry = create_rectangle_geometry(coords, "FSC-A", "SSC-A")?;

let gate = Gate::new("rect-gate", "Rectangle", geometry, "FSC-A", "SSC-A");
```

#### Ellipse Gates

Ellipse gates are elliptical regions with optional rotation:

```rust
let coords = vec![
    (300.0, 400.0),  // Center
    (500.0, 400.0),  // Right point (defines radius_x and angle)
    (300.0, 600.0),  // Top point (defines radius_y)
];
let geometry = create_ellipse_geometry(coords, "FSC-A", "SSC-A")?;

let gate = Gate::new("ellipse-gate", "Ellipse", geometry, "FSC-A", "SSC-A");
```

### Gate Modes

Gates can be scoped to apply globally or to specific files:

```rust
use flow_gates::GateMode;

// Global gate (applies to all files)
let global_gate = Gate::new(/* ... */);
// Gate mode defaults to Global

// File-specific gate
let mut file_gate = Gate::new(/* ... */);
file_gate.mode = GateMode::FileSpecific { guid: "file-123".into() };

// File group gate
let mut group_gate = Gate::new(/* ... */);
group_gate.mode = GateMode::FileGroup {
    guids: vec!["file-1".into(), "file-2".into()],
};
```

## Advanced Usage

### Gate Hierarchies

Gate hierarchies allow sequential gating where child gates are applied to events that pass parent gates:

```rust
use flow_gates::GateHierarchy;

let mut hierarchy = GateHierarchy::new();

// Build hierarchy: root -> parent -> child
hierarchy.add_child("root-gate", "parent-gate");
hierarchy.add_child("parent-gate", "child-gate");

// Get chain from root to a specific gate
let chain = hierarchy.get_chain_to_root("child-gate");
// Returns: ["root-gate", "parent-gate", "child-gate"]

// Get ancestors
let ancestors = hierarchy.get_ancestors("child-gate");
// Returns: ["parent-gate", "root-gate"]

// Get descendants
let descendants = hierarchy.get_descendants("root-gate");
// Returns: ["parent-gate", "child-gate"]
```

### Hierarchical Event Filtering

Filter events through a chain of gates:

```rust
use flow_gates::{filter_events_by_hierarchy, GateHierarchy};

// Build gate chain from hierarchy
let gate_chain: Vec<&Gate> = hierarchy
    .get_chain_to_root("child-gate")
    .iter()
    .filter_map(|id| storage.get(id.as_ref()))
    .collect();

// Filter through hierarchy
let indices = filter_events_by_hierarchy(&fcs, &gate_chain, None, None)?;
```

### Spatial Indexing for Performance

For repeated filtering operations, use a spatial index:

```rust
use flow_gates::{EventIndex, filter_events_by_gate};

// Build index once
let x_slice = fcs.get_parameter_events_slice("FSC-A")?;
let y_slice = fcs.get_parameter_events_slice("SSC-A")?;
let index = EventIndex::build(x_slice, y_slice)?;

// Reuse index for multiple gates (much faster!)
let indices1 = filter_events_by_gate(&fcs, &gate1, Some(&index))?;
let indices2 = filter_events_by_gate(&fcs, &gate2, Some(&index))?;
let indices3 = filter_events_by_gate(&fcs, &gate3, Some(&index))?;
```

### Gate Storage

Thread-safe gate storage with optional persistence:

```rust
use flow_gates::gate_storage::GateStorage;
use std::path::PathBuf;

// Create storage with auto-save
let storage = GateStorage::with_save_path(PathBuf::from("gates.json"));

// Load existing gates
storage.load()?;

// Insert gates
storage.insert(gate1);
storage.insert(gate2);

// Query gates
let file_gates = storage.gates_for_file("file-guid");
let param_gates = storage.gates_for_parameters("FSC-A", "SSC-A");
let specific_gates = storage.gates_for_file_and_parameters(
    "file-guid",
    "FSC-A",
    "SSC-A",
);

// Manual save (auto-save is enabled by default)
storage.save()?;
```

### GatingML Import/Export

Export gates to GatingML 2.0 format:

```rust
use flow_gates::gates_to_gatingml;

let gates = vec![gate1, gate2, gate3];
let xml = gates_to_gatingml(&gates)?;

// Save to file
std::fs::write("gates.xml", xml)?;
```

Import gates from GatingML format:

```rust
use flow_gates::gatingml_to_gates;

let xml = std::fs::read_to_string("gates.xml")?;
let gates = gatingml_to_gates(&xml)?;
```

## Application Integration Examples

### Example 1: Basic Gate Application

```rust
use flow_gates::*;
use flow_fcs::Fcs;

fn apply_gate_to_file(fcs_path: &str, gate: &Gate) -> Result<Vec<usize>> {
    // Load FCS file
    let fcs = Fcs::from_file(fcs_path)?;
    
    // Filter events
    let indices = filter_events_by_gate(&fcs, gate, None)?;
    
    Ok(indices)
}
```

### Example 2: Hierarchical Gating Pipeline

```rust
use flow_gates::*;
use flow_fcs::Fcs;

fn hierarchical_gating(
    fcs: &Fcs,
    hierarchy: &GateHierarchy,
    storage: &GateStorage,
    target_gate_id: &str,
) -> Result<Vec<usize>> {
    // Get gate chain from hierarchy
    let chain_ids = hierarchy.get_chain_to_root(target_gate_id);
    
    // Resolve gates from storage
    let gate_chain: Vec<&Gate> = chain_ids
        .iter()
        .filter_map(|id| storage.get(id.as_ref()))
        .collect();
    
    // Filter through hierarchy
    filter_events_by_hierarchy(fcs, &gate_chain, None, None)
}
```

### Example 3: Batch Processing with Caching

```rust
use flow_gates::*;
use flow_fcs::Fcs;
use std::sync::Arc;
use std::collections::HashMap;

struct SimpleFilterCache {
    cache: Arc<dashmap::DashMap<FilterCacheKey, Arc<Vec<usize>>>>,
}

impl FilterCache for SimpleFilterCache {
    fn get(&self, key: &FilterCacheKey) -> Option<Arc<Vec<usize>>> {
        self.cache.get(key).map(|entry| entry.value().clone())
    }
    
    fn insert(&self, key: FilterCacheKey, value: Arc<Vec<usize>>) {
        self.cache.insert(key, value);
    }
}

fn batch_process_with_cache(
    fcs: &Fcs,
    gates: &[Gate],
    file_guid: &str,
) -> Result<HashMap<String, Vec<usize>>> {
    let cache = SimpleFilterCache {
        cache: Arc::new(dashmap::DashMap::new()),
    };
    
    let mut results = HashMap::new();
    
    for gate in gates {
        let chain = vec![gate];
        let indices = filter_events_by_hierarchy(
            fcs,
            &chain,
            Some(&cache),
            Some(file_guid),
        )?;
        
        results.insert(gate.id.to_string(), indices);
    }
    
    Ok(results)
}
```

### Example 4: Statistics Dashboard

```rust
use flow_gates::*;
use flow_fcs::Fcs;

fn generate_statistics_report(
    fcs: &Fcs,
    gates: &[Gate],
) -> Result<Vec<(String, GateStatistics)>> {
    let mut report = Vec::new();
    
    for gate in gates {
        let stats = GateStatistics::calculate(fcs, gate)?;
        report.push((gate.name.clone(), stats));
    }
    
    Ok(report)
}

fn print_statistics_report(report: &[(String, GateStatistics)]) {
    for (name, stats) in report {
        println!("Gate: {}", name);
        println!("  Events: {}", stats.event_count);
        println!("  Percentage: {:.2}%", stats.percentage);
        println!("  Centroid: ({:.2}, {:.2})", stats.centroid.0, stats.centroid.1);
        println!("  X Parameter:");
        println!("    Mean: {:.2}", stats.x_stats.mean);
        println!("    Median: {:.2}", stats.x_stats.median);
        println!("    Std Dev: {:.2}", stats.x_stats.std_dev);
        println!("  Y Parameter:");
        println!("    Mean: {:.2}", stats.y_stats.mean);
        println!("    Median: {:.2}", stats.y_stats.median);
        println!("    Std Dev: {:.2}", stats.y_stats.std_dev);
        println!();
    }
}
```

### Example 5: Interactive Gate Editor Integration

```rust
use flow_gates::*;
use flow_gates::geometry::*;

// User draws polygon on plot
fn create_gate_from_user_drawing(
    points: Vec<(f32, f32)>,
    x_param: &str,
    y_param: &str,
    gate_id: &str,
    gate_name: &str,
) -> Result<Gate> {
    // Create geometry from user-drawn points
    let geometry = create_polygon_geometry(points, x_param, y_param)?;
    
    // Create gate
    let gate = Gate::new(gate_id, gate_name, geometry, x_param, y_param);
    
    // Validate
    if !gate.geometry.is_valid(x_param, y_param)? {
        return Err(GateError::invalid_geometry("Invalid gate geometry"));
    }
    
    Ok(gate)
}

// Update gate after user edits
fn update_gate_geometry(
    gate: &mut Gate,
    new_points: Vec<(f32, f32)>,
) -> Result<()> {
    let geometry = create_polygon_geometry(
        new_points,
        gate.x_parameter_channel_name(),
        gate.y_parameter_channel_name(),
    )?;
    
    gate.geometry = geometry;
    
    Ok(())
}
```

## Performance Considerations

### Spatial Indexing

For repeated filtering operations on the same dataset, use `EventIndex`:

- **Build time**: O(n log n) - one-time cost
- **Query time**: O(log n) per gate - much faster than O(n) linear scan
- **Memory**: O(n) - stores all event points

### Caching

Implement the `FilterCache` trait for your application to cache filter results:

```rust
use flow_gates::{FilterCache, FilterCacheKey};
use std::sync::Arc;

struct MyFilterCache {
    // Your cache implementation
}

impl FilterCache for MyFilterCache {
    fn get(&self, key: &FilterCacheKey) -> Option<Arc<Vec<usize>>> {
        // Retrieve from cache
    }
    
    fn insert(&self, key: FilterCacheKey, value: Arc<Vec<usize>>) {
        // Store in cache
    }
}
```

## Error Handling

The library uses `GateError` for all error conditions. Most operations return `Result<T, GateError>`:

```rust
use flow_gates::{GateError, Result};

match create_polygon_geometry(coords, "FSC-A", "SSC-A") {
    Ok(geometry) => {
        // Use geometry
    }
    Err(GateError::InvalidGeometry { message }) => {
        eprintln!("Invalid geometry: {}", message);
    }
    Err(e) => {
        eprintln!("Error: {}", e);
    }
}
```

## Thread Safety

Most types in this library are thread-safe:

- `GateStorage`: Thread-safe concurrent access
- `EventIndex`: Immutable after construction, safe to share
- `Gate`, `GateGeometry`, `GateNode`: Clone to share between threads
- `GateHierarchy`: Use synchronization primitives for concurrent access

## License

MIT

## Contributing

Contributions are welcome! Please feel free to submit a Pull Request.