File size: 28,166 Bytes
1e12712
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
"""
Sparse spike pattern optimization for spiking neural networks.

This module provides efficient representations and operations for sparse
spike patterns, which can significantly reduce memory usage and improve
computational performance for networks with sparse activity.
"""

import numpy as np
from typing import List, Tuple, Dict, Union, Optional, Set, Any
from enum import Enum
import mlx.core as mx
from dataclasses import dataclass
import time

from ..utils.common import SpikeState


class SparseFormat(Enum):
    """Enumeration of supported sparse pattern formats."""
    COO = "coordinate_format"       # Coordinate format (i, t, s)
    CSR = "compressed_sparse_row"   # Compressed sparse row format
    CSC = "compressed_sparse_column"  # Compressed sparse column format
    DICTIONARY = "dictionary"       # Dictionary-based format
    BINARY_MASK = "binary_mask"     # Binary mask format for binary spikes


@dataclass
class SparsePattern:
    """
    Data class for handling sparse spike patterns with different formats.
    
    Attributes:
        format: Format of the sparse representation
        data: The sparse representation data
        shape: The shape of the original dense representation
        metadata: Additional metadata for the sparse pattern
    """
    format: SparseFormat
    data: Any
    shape: Tuple[int, ...]
    metadata: Optional[Dict[str, Any]] = None
    

def convert_to_sparse(
    spike_pattern: List[List[Tuple[int, SpikeState]]],
    format: SparseFormat = SparseFormat.COO,
    compress_values: bool = False
) -> SparsePattern:
    """
    Convert a dense spike pattern to sparse representation.
    
    Args:
        spike_pattern: Spike pattern as list of neuron spike trains
        format: Which sparse format to use
        compress_values: Whether to compress spike state values
        
    Returns:
        SparsePattern with the requested format
    """
    # Get shape information
    n_neurons = len(spike_pattern)
    max_time = max([t for neuron in spike_pattern for t, _ in neuron]) if any(spike_pattern) else 0
    shape = (n_neurons, max_time + 1)
    
    if format == SparseFormat.COO:
        # Coordinate format - list of (neuron_idx, time, state_value)
        data = []
        for neuron_idx, neuron_spikes in enumerate(spike_pattern):
            for t, state in neuron_spikes:
                # Compress values if requested (saves memory)
                value = state.value if not compress_values else _compress_state(state)
                data.append((neuron_idx, t, value))
        
        # Add metadata
        metadata = {
            'n_spikes': len(data),
            'density': len(data) / (shape[0] * shape[1]) if shape[0] * shape[1] > 0 else 0,
            'compress_values': compress_values
        }
        
        return SparsePattern(format=format, data=data, shape=shape, metadata=metadata)
    
    elif format == SparseFormat.CSR:
        # Compressed Sparse Row format
        row_ptr = [0]
        col_indices = []
        values = []
        
        # Collect all spikes for each neuron (row)
        for neuron_idx, neuron_spikes in enumerate(spike_pattern):
            for t, state in neuron_spikes:
                col_indices.append(t)
                value = state.value if not compress_values else _compress_state(state)
                values.append(value)
            row_ptr.append(len(values))
        
        data = (row_ptr, col_indices, values)
        metadata = {
            'n_spikes': len(values),
            'density': len(values) / (shape[0] * shape[1]) if shape[0] * shape[1] > 0 else 0,
            'compress_values': compress_values
        }
        
        return SparsePattern(format=format, data=data, shape=shape, metadata=metadata)
    
    elif format == SparseFormat.CSC:
        # Compressed Sparse Column format (time as column)
        col_ptr = [0]
        row_indices = []
        values = []
        
        # First, collect all spikes by time step
        spikes_by_time = {}
        for neuron_idx, neuron_spikes in enumerate(spike_pattern):
            for t, state in neuron_spikes:
                if t not in spikes_by_time:
                    spikes_by_time[t] = []
                value = state.value if not compress_values else _compress_state(state)
                spikes_by_time[t].append((neuron_idx, value))
        
        # Sort by time and create CSC representation
        for t in range(shape[1]):
            if t in spikes_by_time:
                for neuron_idx, value in spikes_by_time[t]:
                    row_indices.append(neuron_idx)
                    values.append(value)
            col_ptr.append(len(values))
        
        data = (col_ptr, row_indices, values)
        metadata = {
            'n_spikes': len(values),
            'density': len(values) / (shape[0] * shape[1]) if shape[0] * shape[1] > 0 else 0,
            'compress_values': compress_values
        }
        
        return SparsePattern(format=format, data=data, shape=shape, metadata=metadata)
    
    elif format == SparseFormat.DICTIONARY:
        # Dictionary with (neuron_idx, time) as keys and state_value as values
        data = {}
        for neuron_idx, neuron_spikes in enumerate(spike_pattern):
            for t, state in neuron_spikes:
                value = state.value if not compress_values else _compress_state(state)
                data[(neuron_idx, t)] = value
        
        metadata = {
            'n_spikes': len(data),
            'density': len(data) / (shape[0] * shape[1]) if shape[0] * shape[1] > 0 else 0,
            'compress_values': compress_values
        }
        
        return SparsePattern(format=format, data=data, shape=shape, metadata=metadata)
    
    elif format == SparseFormat.BINARY_MASK:
        # Binary mask format - only works well for binary spikes
        # Create time-indexed representation
        binary_masks = {}
        for t in range(shape[1]):
            binary_masks[t] = np.zeros(shape[0], dtype=np.int8)
        
        # Fill in the masks
        for neuron_idx, neuron_spikes in enumerate(spike_pattern):
            for t, state in neuron_spikes:
                if t < shape[1]:
                    # In binary mask format, we typically only represent positive spikes
                    if state == SpikeState.POSITIVE:
                        binary_masks[t][neuron_idx] = 1
                    elif state == SpikeState.NEGATIVE and not compress_values:
                        binary_masks[t][neuron_idx] = -1
        
        # Remove empty time steps to save space
        non_empty_masks = {t: mask for t, mask in binary_masks.items() if np.any(mask)}
        
        metadata = {
            'n_spikes': sum(np.count_nonzero(mask) for mask in non_empty_masks.values()),
            'density': sum(np.count_nonzero(mask) for mask in non_empty_masks.values()) / (shape[0] * shape[1]) 
                      if shape[0] * shape[1] > 0 else 0,
            'compress_values': compress_values,
            'non_empty_times': sorted(non_empty_masks.keys())
        }
        
        return SparsePattern(format=format, data=non_empty_masks, shape=shape, metadata=metadata)
    
    else:
        raise ValueError(f"Unsupported sparse format: {format}")


def _compress_state(state: SpikeState) -> int:
    """
    Helper function to compress spike state into smallest possible representation.
    
    Args:
        state: The spike state to compress
        
    Returns:
        Compressed integer representation (1 for positive, -1 for negative, 0 for neutral)
    """
    if state == SpikeState.POSITIVE:
        return 1
    elif state == SpikeState.NEGATIVE:
        return -1
    else:  # NEUTRAL
        return 0


def _decompress_state(value: int) -> SpikeState:
    """
    Helper function to decompress spike state from compressed representation.
    
    Args:
        value: Compressed integer representation
        
    Returns:
        Original SpikeState
    """
    if value == 1:
        return SpikeState.POSITIVE
    elif value == -1:
        return SpikeState.NEGATIVE
    else:  # 0
        return SpikeState.NEUTRAL


def convert_from_sparse(
    sparse_pattern: SparsePattern
) -> List[List[Tuple[int, SpikeState]]]:
    """
    Convert a sparse spike pattern back to dense representation.
    
    Args:
        sparse_pattern: Sparse pattern to convert
        
    Returns:
        Spike pattern as list of neuron spike trains
    """
    n_neurons = sparse_pattern.shape[0]
    compress_values = sparse_pattern.metadata.get('compress_values', False) if sparse_pattern.metadata else False
    
    # Initialize empty spike trains for each neuron
    spike_pattern = [[] for _ in range(n_neurons)]
    
    if sparse_pattern.format == SparseFormat.COO:
        for neuron_idx, t, value in sparse_pattern.data:
            if neuron_idx < n_neurons:
                state = _decompress_state(value) if compress_values else SpikeState(value)
                spike_pattern[neuron_idx].append((t, state))
    
    elif sparse_pattern.format == SparseFormat.CSR:
        row_ptr, col_indices, values = sparse_pattern.data
        for neuron_idx in range(n_neurons):
            start, end = row_ptr[neuron_idx], row_ptr[neuron_idx + 1] if neuron_idx + 1 < len(row_ptr) else len(col_indices)
            for i in range(start, end):
                t = col_indices[i]
                value = values[i]
                state = _decompress_state(value) if compress_values else SpikeState(value)
                spike_pattern[neuron_idx].append((t, state))
    
    elif sparse_pattern.format == SparseFormat.CSC:
        col_ptr, row_indices, values = sparse_pattern.data
        # Create a mapping from (neuron, time) to value
        neuron_time_to_value = {}
        for t in range(len(col_ptr) - 1):
            start, end = col_ptr[t], col_ptr[t+1]
            for i in range(start, end):
                neuron_idx = row_indices[i]
                value = values[i]
                if neuron_idx < n_neurons:
                    neuron_time_to_value[(neuron_idx, t)] = value
        
        # Create spike trains
        for (neuron_idx, t), value in neuron_time_to_value.items():
            state = _decompress_state(value) if compress_values else SpikeState(value)
            spike_pattern[neuron_idx].append((t, state))
        
        # Sort spike trains by time
        for neuron_idx in range(n_neurons):
            spike_pattern[neuron_idx].sort(key=lambda x: x[0])
    
    elif sparse_pattern.format == SparseFormat.DICTIONARY:
        for (neuron_idx, t), value in sparse_pattern.data.items():
            if neuron_idx < n_neurons:
                state = _decompress_state(value) if compress_values else SpikeState(value)
                spike_pattern[neuron_idx].append((t, state))
        
        # Sort spike trains by time
        for neuron_idx in range(n_neurons):
            spike_pattern[neuron_idx].sort(key=lambda x: x[0])
    
    elif sparse_pattern.format == SparseFormat.BINARY_MASK:
        binary_masks = sparse_pattern.data
        for t, mask in binary_masks.items():
            for neuron_idx, val in enumerate(mask):
                if val != 0 and neuron_idx < n_neurons:
                    state = SpikeState.POSITIVE if val > 0 else SpikeState.NEGATIVE
                    spike_pattern[neuron_idx].append((t, state))
        
        # Sort spike trains by time
        for neuron_idx in range(n_neurons):
            spike_pattern[neuron_idx].sort(key=lambda x: x[0])
    
    else:
        raise ValueError(f"Unsupported sparse format: {sparse_pattern.format}")
    
    return spike_pattern


def compute_sparse_similarity(
    sparse_pattern1: SparsePattern,
    sparse_pattern2: SparsePattern,
    tolerance: int = 2
) -> float:
    """
    Compute similarity between sparse spike patterns directly, without conversion to dense.
    
    This is much more efficient than converting to dense and then computing similarity.
    
    Args:
        sparse_pattern1: First sparse pattern
        sparse_pattern2: Second sparse pattern
        tolerance: Time window for considering spikes as coincident
        
    Returns:
        Similarity score (0 to 1, higher is more similar)
    """
    # Special case for empty patterns
    if (sparse_pattern1.metadata and sparse_pattern1.metadata.get('n_spikes', 0) == 0 and
        sparse_pattern2.metadata and sparse_pattern2.metadata.get('n_spikes', 0) == 0):
        return 1.0  # Two empty patterns are considered identical
    
    if (sparse_pattern1.metadata and sparse_pattern1.metadata.get('n_spikes', 0) == 0) or (
        sparse_pattern2.metadata and sparse_pattern2.metadata.get('n_spikes', 0) == 0):
        return 0.0  # One empty, one non-empty pattern
    
    # Convert both patterns to COO format for easier comparison
    # If already in COO format, this is a no-op
    coo1 = _ensure_coo_format(sparse_pattern1)
    coo2 = _ensure_coo_format(sparse_pattern2)
    
    # Create time-indexed representation of patterns
    def create_time_indexed_pattern(coo_data):
        indexed_pattern = {}
        for neuron_idx, t, value in coo_data:
            if t not in indexed_pattern:
                indexed_pattern[t] = []
            indexed_pattern[t].append((neuron_idx, value))
        return indexed_pattern
    
    indexed1 = create_time_indexed_pattern(coo1)
    indexed2 = create_time_indexed_pattern(coo2)
    
    # Count matching patterns
    match_count = 0
    total_patterns = 0
    
    # For each time point in pattern 1
    for t1, neurons1 in indexed1.items():
        # Look for matching patterns in a window around t1
        found_match = False
        for t2 in range(t1 - tolerance, t1 + tolerance + 1):
            if t2 in indexed2:
                neurons2 = indexed2[t2]
                # Check if the activated neurons match
                neuron_set1 = {(n, v) for n, v in neurons1}
                neuron_set2 = {(n, v) for n, v in neurons2}
                
                # Compute Jaccard similarity between the two sets
                intersection = len(neuron_set1.intersection(neuron_set2))
                union = len(neuron_set1.union(neuron_set2))
                
                if union > 0 and intersection / union > 0.5:  # More than 50% match
                    match_count += 1
                    found_match = True
                    break
        
        if found_match:
            total_patterns += 1
    
    # Add patterns from pattern 2 that didn't match with pattern 1
    for t2 in indexed2:
        found_in_range = False
        for t1 in range(t2 - tolerance, t2 + tolerance + 1):
            if t1 in indexed1:
                found_in_range = True
                break
        
        if not found_in_range:
            total_patterns += 1
    
    # Calculate similarity score
    if total_patterns == 0:
        return 1.0  # Both patterns are empty
    
    similarity = match_count / total_patterns
    return similarity


def _ensure_coo_format(sparse_pattern: SparsePattern) -> List[Tuple[int, int, int]]:
    """
    Helper function to ensure a sparse pattern is in COO format.
    
    Args:
        sparse_pattern: Sparse pattern in any format
        
    Returns:
        Data in COO format
    """
    if sparse_pattern.format == SparseFormat.COO:
        return sparse_pattern.data
    
    # Convert to COO format
    if sparse_pattern.format == SparseFormat.CSR:
        row_ptr, col_indices, values = sparse_pattern.data
        coo_data = []
        for neuron_idx in range(len(row_ptr) - 1):
            start, end = row_ptr[neuron_idx], row_ptr[neuron_idx + 1]
            for i in range(start, end):
                t = col_indices[i]
                value = values[i]
                coo_data.append((neuron_idx, t, value))
        return coo_data
    
    elif sparse_pattern.format == SparseFormat.CSC:
        col_ptr, row_indices, values = sparse_pattern.data
        coo_data = []
        for t in range(len(col_ptr) - 1):
            start, end = col_ptr[t], col_ptr[t+1]
            for i in range(start, end):
                neuron_idx = row_indices[i]
                value = values[i]
                coo_data.append((neuron_idx, t, value))
        return coo_data
    
    elif sparse_pattern.format == SparseFormat.DICTIONARY:
        return [(*key, value) for key, value in sparse_pattern.data.items()]
    
    elif sparse_pattern.format == SparseFormat.BINARY_MASK:
        binary_masks = sparse_pattern.data
        coo_data = []
        for t, mask in binary_masks.items():
            for neuron_idx, val in enumerate(mask):
                if val != 0:
                    coo_data.append((neuron_idx, t, val))
        return coo_data
    
    else:
        raise ValueError(f"Unsupported sparse format: {sparse_pattern.format}")


def filter_by_activity(
    sparse_pattern: SparsePattern,
    activity_threshold: float = 0.0,
    min_active_neurons: int = 0
) -> SparsePattern:
    """
    Filter a sparse pattern to keep only time steps with significant activity.
    
    This is useful for further compressing patterns with sparse activity.
    
    Args:
        sparse_pattern: Sparse pattern to filter
        activity_threshold: Activity threshold as fraction of neurons
        min_active_neurons: Minimum number of active neurons to keep a time step
        
    Returns:
        Filtered sparse pattern
    """
    if sparse_pattern.metadata and sparse_pattern.metadata.get('n_spikes', 0) == 0:
        return sparse_pattern  # Nothing to filter for empty pattern
    
    n_neurons = sparse_pattern.shape[0]
    absolute_threshold = max(min_active_neurons, int(activity_threshold * n_neurons))
    
    # Convert to COO format for easier filtering
    coo_data = _ensure_coo_format(sparse_pattern)
    
    # Count activity per time step
    activity_counts = {}
    for _, t, _ in coo_data:
        activity_counts[t] = activity_counts.get(t, 0) + 1
    
    # Filter time steps
    active_times = {t for t, count in activity_counts.items() if count >= absolute_threshold}
    
    # Apply filter
    filtered_data = [(n, t, v) for n, t, v in coo_data if t in active_times]
    
    # Update metadata
    metadata = sparse_pattern.metadata.copy() if sparse_pattern.metadata else {}
    metadata.update({
        'n_spikes': len(filtered_data),
        'original_n_spikes': len(coo_data),
        'active_times': sorted(list(active_times)),
        'activity_threshold': activity_threshold,
        'min_active_neurons': min_active_neurons
    })
    
    # Create new sparse pattern in COO format
    return SparsePattern(
        format=SparseFormat.COO,
        data=filtered_data,
        shape=sparse_pattern.shape,
        metadata=metadata
    )


def batch_sparse_operations(
    sparse_patterns: List[SparsePattern],
    operation: str = 'merge',
    max_batch_size: int = 100
) -> Union[SparsePattern, List[SparsePattern]]:
    """
    Perform batch operations on multiple sparse patterns efficiently.
    
    Args:
        sparse_patterns: List of sparse patterns to process
        operation: Operation to perform ('merge', 'average', 'max', 'union')
        max_batch_size: Maximum batch size for processing
        
    Returns:
        Result of the batch operation
    """
    if not sparse_patterns:
        return []
    
    # Process in batches
    results = []
    for i in range(0, len(sparse_patterns), max_batch_size):
        batch = sparse_patterns[i:i+max_batch_size]
        
        if operation == 'merge':
            # Merge all patterns in the batch into a single pattern
            merged = _merge_sparse_patterns(batch)
            results.append(merged)
        
        elif operation == 'average':
            # Average all patterns in the batch
            avg = _average_sparse_patterns(batch)
            results.append(avg)
        
        elif operation == 'max':
            # Take maximum value across all patterns
            max_pattern = _max_sparse_patterns(batch)
            results.append(max_pattern)
        
        elif operation == 'union':
            # Take union of all patterns (logical OR)
            union_pattern = _union_sparse_patterns(batch)
            results.append(union_pattern)
        
        else:
            raise ValueError(f"Unsupported batch operation: {operation}")
    
    # Return a single result if operation produces one pattern per batch
    if operation in ['merge', 'average', 'max', 'union']:
        if len(results) == 1:
            return results[0]
        else:
            # Recursively combine results from each batch
            return batch_sparse_operations(results, operation, max_batch_size)
    
    # Otherwise return list of results
    return results


def _merge_sparse_patterns(
    sparse_patterns: List[SparsePattern]
) -> SparsePattern:
    """
    Merge multiple sparse patterns into one, maintaining separate time windows.
    
    Args:
        sparse_patterns: List of sparse patterns to merge
        
    Returns:
        Merged sparse pattern
    """
    if not sparse_patterns:
        return None
    
    # Special case for single pattern
    if len(sparse_patterns) == 1:
        return sparse_patterns[0]
    
    # Determine maximum time across all patterns
    max_time = max([pattern.shape[1] for pattern in sparse_patterns])
    n_neurons = max([pattern.shape[0] for pattern in sparse_patterns])
    
    # Convert all to COO format
    coo_data_list = [_ensure_coo_format(pattern) for pattern in sparse_patterns]
    
    # Perform time offset for each pattern to separate them
    merged_data = []
    time_offset = 0
    pattern_boundaries = [0]
    
    for coo_data in coo_data_list:
        offset_data = [(n, t + time_offset, v) for n, t, v in coo_data]
        merged_data.extend(offset_data)
        
        # Update time offset for next pattern
        if coo_data:
            max_pattern_time = max([t for _, t, _ in coo_data])
            time_offset += max_pattern_time + 1
        pattern_boundaries.append(time_offset)
    
    # Create metadata
    metadata = {
        'n_spikes': len(merged_data),
        'original_patterns': len(sparse_patterns),
        'pattern_boundaries': pattern_boundaries,
        'operation': 'merge'
    }
    
    # Create new sparse pattern
    return SparsePattern(
        format=SparseFormat.COO,
        data=merged_data,
        shape=(n_neurons, time_offset),
        metadata=metadata
    )


def _average_sparse_patterns(
    sparse_patterns: List[SparsePattern]
) -> SparsePattern:
    """
    Average multiple sparse patterns.
    
    Args:
        sparse_patterns: List of sparse patterns to average
        
    Returns:
        Averaged sparse pattern
    """
    if not sparse_patterns:
        return None
    
    # Special case for single pattern
    if len(sparse_patterns) == 1:
        return sparse_patterns[0]
    
    # Determine common shape
    max_neurons = max([pattern.shape[0] for pattern in sparse_patterns])
    max_time = max([pattern.shape[1] for pattern in sparse_patterns])
    common_shape = (max_neurons, max_time)
    
    # Convert to COO format
    coo_data_list = [_ensure_coo_format(pattern) for pattern in sparse_patterns]
    
    # Create a dictionary to aggregate values
    agg_values = {}
    for pattern_idx, coo_data in enumerate(coo_data_list):
        for n, t, v in coo_data:
            if (n, t) not in agg_values:
                agg_values[(n, t)] = []
            agg_values[(n, t)].append(v)
    
    # Calculate averages
    avg_data = []
    for (n, t), values in agg_values.items():
        avg_value = sum(values) / len(sparse_patterns)  # Average across all patterns
        if avg_value != 0:  # Only include non-zero values
            avg_data.append((n, t, avg_value))
    
    # Create metadata
    metadata = {
        'n_spikes': len(avg_data),
        'original_patterns': len(sparse_patterns),
        'operation': 'average'
    }
    
    # Create new sparse pattern
    return SparsePattern(
        format=SparseFormat.COO,
        data=avg_data,
        shape=common_shape,
        metadata=metadata
    )


def _max_sparse_patterns(
    sparse_patterns: List[SparsePattern]
) -> SparsePattern:
    """
    Take maximum value across all sparse patterns.
    
    Args:
        sparse_patterns: List of sparse patterns
        
    Returns:
        Maximum sparse pattern
    """
    if not sparse_patterns:
        return None
    
    # Special case for single pattern
    if len(sparse_patterns) == 1:
        return sparse_patterns[0]
    
    # Determine common shape
    max_neurons = max([pattern.shape[0] for pattern in sparse_patterns])
    max_time = max([pattern.shape[1] for pattern in sparse_patterns])
    common_shape = (max_neurons, max_time)
    
    # Convert to COO format
    coo_data_list = [_ensure_coo_format(pattern) for pattern in sparse_patterns]
    
    # Create a dictionary to find maximum values
    max_values = {}
    for coo_data in coo_data_list:
        for n, t, v in coo_data:
            if (n, t) not in max_values or abs(v) > abs(max_values[(n, t)]):
                max_values[(n, t)] = v
    
    # Create max data
    max_data = [(n, t, v) for (n, t), v in max_values.items()]
    
    # Create metadata
    metadata = {
        'n_spikes': len(max_data),
        'original_patterns': len(sparse_patterns),
        'operation': 'max'
    }
    
    # Create new sparse pattern
    return SparsePattern(
        format=SparseFormat.COO,
        data=max_data,
        shape=common_shape,
        metadata=metadata
    )


def _union_sparse_patterns(
    sparse_patterns: List[SparsePattern]
) -> SparsePattern:
    """
    Take union of all sparse patterns (logical OR).
    
    Args:
        sparse_patterns: List of sparse patterns
        
    Returns:
        Union sparse pattern
    """
    if not sparse_patterns:
        return None
    
    # Special case for single pattern
    if len(sparse_patterns) == 1:
        return sparse_patterns[0]
    
    # Determine common shape
    max_neurons = max([pattern.shape[0] for pattern in sparse_patterns])
    max_time = max([pattern.shape[1] for pattern in sparse_patterns])
    common_shape = (max_neurons, max_time)
    
    # Convert to Binary Mask format for efficient union
    binary_masks = {}
    
    # Initialize masks for all time steps
    for t in range(max_time):
        binary_masks[t] = np.zeros(max_neurons, dtype=np.int8)
    
    # Combine all patterns
    for pattern in sparse_patterns:
        if pattern.format == SparseFormat.BINARY_MASK:
            # Directly update from binary mask
            for t, mask in pattern.data.items():
                if t < max_time:
                    # Union operation - take highest value (1 for spike, 0 for no spike)
                    for neuron_idx, val in enumerate(mask):
                        if neuron_idx < max_neurons and val != 0:
                            if abs(val) > abs(binary_masks[t][neuron_idx]):
                                binary_masks[t][neuron_idx] = val
        else:
            # Convert other formats to COO and then update
            coo_data = _ensure_coo_format(pattern)
            for n, t, v in coo_data:
                if n < max_neurons and t < max_time:
                    # Union operation - take highest value
                    if abs(v) > abs(binary_masks[t][n]):
                        binary_masks[t][n] = v
    
    # Remove empty time steps
    non_empty_masks = {t: mask for t, mask in binary_masks.items() if np.any(mask)}
    
    # Create metadata
    metadata = {
        'n_spikes': sum(np.count_nonzero(mask) for mask in non_empty_masks.values()),
        'original_patterns': len(sparse_patterns),
        'non_empty_times': sorted(non_empty_masks.keys()),
        'operation': 'union'
    }
    
    # Create new sparse pattern
    return SparsePattern(
        format=SparseFormat.BINARY_MASK,
        data=non_empty_masks,
        shape=common_shape,
        metadata=metadata
    )