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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
"""
Compression techniques for spike patterns in spiking neural networks.

This module provides methods for efficiently compressing and decompressing
spike patterns to reduce memory usage and improve computational performance.
"""

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

from ..utils.common import SpikeState
from .sparse_patterns import SparsePattern, SparseFormat, convert_to_sparse, convert_from_sparse


class CompressionScheme(Enum):
    """Enumeration of supported compression schemes."""
    RUN_LENGTH = "run_length"      # Run-length encoding
    DELTA = "delta"                # Delta encoding
    DICTIONARY = "dictionary"      # Dictionary-based compression
    HUFFMAN = "huffman"            # Huffman coding
    HYBRID = "hybrid"              # Combination of multiple methods


@dataclass
class CompressedPattern:
    """
    Data class for compressed spike pattern.
    
    Attributes:
        scheme: Compression scheme used
        data: Compressed data
        original_shape: Shape of the original pattern
        codebook: Optional codebook for dictionary-based compression
        metadata: Additional metadata
    """
    scheme: CompressionScheme
    data: Any
    original_shape: Tuple[int, ...]
    codebook: Optional[Dict] = None
    metadata: Optional[Dict] = None


def encode_spike_pattern(
    spike_pattern: List[List[Tuple[int, SpikeState]]],
    scheme: CompressionScheme = CompressionScheme.HYBRID,
    codebook: Optional[Dict] = None
) -> CompressedPattern:
    """
    Compress a spike pattern using the specified scheme.
    
    Args:
        spike_pattern: Spike pattern to compress
        scheme: Compression scheme to use
        codebook: Optional codebook for dictionary-based compression
        
    Returns:
        Compressed pattern
    """
    # 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
    original_shape = (n_neurons, max_time + 1)
    
    # Create metadata
    metadata = {
        'n_neurons': n_neurons,
        'max_time': max_time + 1,
        'original_size': _estimate_original_size(spike_pattern)
    }
    
    if scheme == CompressionScheme.RUN_LENGTH:
        # Run-length encoding
        compressed_data = _run_length_encode(spike_pattern)
        
    elif scheme == CompressionScheme.DELTA:
        # Delta encoding
        compressed_data = _delta_encode(spike_pattern)
        
    elif scheme == CompressionScheme.DICTIONARY:
        # Dictionary-based compression
        if codebook is None:
            # Create codebook if not provided
            codebook = _create_pattern_codebook([spike_pattern])
        
        compressed_data = _dictionary_encode(spike_pattern, codebook)
        
    elif scheme == CompressionScheme.HUFFMAN:
        # Huffman coding
        compressed_data, huffman_tree = _huffman_encode(spike_pattern)
        # Store Huffman tree in codebook
        codebook = {'huffman_tree': huffman_tree}
        
    elif scheme == CompressionScheme.HYBRID:
        # Hybrid approach combining multiple methods
        # First convert to sparse representation
        sparse_pattern = convert_to_sparse(
            spike_pattern, 
            format=SparseFormat.BINARY_MASK,
            compress_values=True
        )
        
        # Then apply run-length encoding to the binary masks
        compressed_data = _hybrid_encode(sparse_pattern)
        
    else:
        raise ValueError(f"Unsupported compression scheme: {scheme}")
    
    # Update metadata with compressed size
    metadata['compressed_size'] = _estimate_compressed_size(compressed_data)
    metadata['compression_ratio'] = (metadata['original_size'] / metadata['compressed_size'] 
                                   if metadata['compressed_size'] > 0 else float('inf'))
    
    return CompressedPattern(
        scheme=scheme,
        data=compressed_data,
        original_shape=original_shape,
        codebook=codebook,
        metadata=metadata
    )


def decode_spike_pattern(
    compressed_pattern: CompressedPattern
) -> List[List[Tuple[int, SpikeState]]]:
    """
    Decompress a spike pattern.
    
    Args:
        compressed_pattern: Compressed pattern to decode
        
    Returns:
        Original spike pattern
    """
    scheme = compressed_pattern.scheme
    compressed_data = compressed_pattern.data
    original_shape = compressed_pattern.original_shape
    codebook = compressed_pattern.codebook
    
    if scheme == CompressionScheme.RUN_LENGTH:
        # Run-length decoding
        return _run_length_decode(compressed_data, original_shape)
        
    elif scheme == CompressionScheme.DELTA:
        # Delta decoding
        return _delta_decode(compressed_data, original_shape)
        
    elif scheme == CompressionScheme.DICTIONARY:
        # Dictionary-based decompression
        if codebook is None:
            raise ValueError("Codebook is required for dictionary-based decompression")
        
        return _dictionary_decode(compressed_data, codebook, original_shape)
        
    elif scheme == CompressionScheme.HUFFMAN:
        # Huffman decoding
        if codebook is None or 'huffman_tree' not in codebook:
            raise ValueError("Huffman tree is required for Huffman decoding")
        
        return _huffman_decode(compressed_data, codebook['huffman_tree'], original_shape)
        
    elif scheme == CompressionScheme.HYBRID:
        # Hybrid approach decoding
        sparse_pattern = _hybrid_decode(compressed_data)
        return convert_from_sparse(sparse_pattern)
        
    else:
        raise ValueError(f"Unsupported compression scheme: {scheme}")


def _estimate_original_size(spike_pattern: List[List[Tuple[int, SpikeState]]]) -> int:
    """
    Estimate the memory size of the original spike pattern.
    
    Args:
        spike_pattern: Spike pattern to measure
        
    Returns:
        Estimated size in bytes
    """
    # Count total spikes
    total_spikes = sum(len(neuron) for neuron in spike_pattern)
    
    # Each spike is a tuple (time, state)
    # time is an int (8 bytes), state is an enum (1 byte)
    spike_size = 9  # bytes
    
    # Each neuron list has overhead
    neuron_overhead = 8  # bytes
    
    # Calculate total size
    total_size = (total_spikes * spike_size) + (len(spike_pattern) * neuron_overhead)
    
    return total_size


def _estimate_compressed_size(compressed_data: Any) -> int:
    """
    Estimate the memory size of compressed data.
    
    Args:
        compressed_data: Compressed data to measure
        
    Returns:
        Estimated size in bytes
    """
    if isinstance(compressed_data, (bytes, bytearray)):
        return len(compressed_data)
    elif isinstance(compressed_data, (list, tuple)):
        return len(pickle.dumps(compressed_data))
    elif isinstance(compressed_data, dict):
        return len(pickle.dumps(compressed_data))
    elif isinstance(compressed_data, str):
        return len(compressed_data.encode('utf-8'))
    else:
        # Fall back to pickle size
        return len(pickle.dumps(compressed_data))


def _run_length_encode(spike_pattern: List[List[Tuple[int, SpikeState]]]) -> List:
    """
    Compress spike pattern using run-length encoding.
    
    Args:
        spike_pattern: Spike pattern to compress
        
    Returns:
        Run-length encoded data
    """
    encoded_data = []
    
    for neuron_idx, neuron_spikes in enumerate(spike_pattern):
        if not neuron_spikes:
            # Empty neuron - store as special case
            encoded_data.append((neuron_idx, []))
            continue
        
        # Sort spikes by time
        sorted_spikes = sorted(neuron_spikes, key=lambda x: x[0])
        
        # Run-length encode the spike train
        neuron_encoded = []
        current_state = None
        run_start = -1
        run_length = 0
        
        for t, state in sorted_spikes:
            if state != current_state:
                # State changed, store the previous run
                if current_state is not None:
                    neuron_encoded.append((run_start, run_length, current_state.value))
                
                # Start new run
                current_state = state
                run_start = t
                run_length = 1
            else:
                # Continue the current run if times are consecutive
                if t == run_start + run_length:
                    run_length += 1
                else:
                    # Non-consecutive time, store the previous run
                    neuron_encoded.append((run_start, run_length, current_state.value))
                    
                    # Start new run
                    run_start = t
                    run_length = 1
        
        # Store the last run
        if current_state is not None:
            neuron_encoded.append((run_start, run_length, current_state.value))
        
        # Store the encoded data for this neuron
        encoded_data.append((neuron_idx, neuron_encoded))
    
    return encoded_data


def _run_length_decode(
    encoded_data: List,
    original_shape: Tuple[int, ...]
) -> List[List[Tuple[int, SpikeState]]]:
    """
    Decompress run-length encoded spike pattern.
    
    Args:
        encoded_data: Run-length encoded data
        original_shape: Shape of the original pattern
        
    Returns:
        Decoded spike pattern
    """
    n_neurons = original_shape[0]
    
    # Initialize empty spike trains
    spike_pattern = [[] for _ in range(n_neurons)]
    
    # Decode each neuron
    for neuron_idx, neuron_encoded in encoded_data:
        if not neuron_encoded:
            # Empty neuron
            continue
        
        # Decode runs
        for run_start, run_length, state_value in neuron_encoded:
            state = SpikeState(state_value)
            
            # Expand the run
            for t in range(run_start, run_start + run_length):
                spike_pattern[neuron_idx].append((t, state))
    
    return spike_pattern


def _delta_encode(spike_pattern: List[List[Tuple[int, SpikeState]]]) -> List:
    """
    Compress spike pattern using delta encoding.
    
    Args:
        spike_pattern: Spike pattern to compress
        
    Returns:
        Delta encoded data
    """
    encoded_data = []
    
    for neuron_idx, neuron_spikes in enumerate(spike_pattern):
        if not neuron_spikes:
            # Empty neuron - store as special case
            encoded_data.append((neuron_idx, []))
            continue
        
        # Sort spikes by time
        sorted_spikes = sorted(neuron_spikes, key=lambda x: x[0])
        
        # Delta encode the spike train
        neuron_encoded = []
        prev_time = None
        
        for t, state in sorted_spikes:
            if prev_time is None:
                # First spike - store absolute time
                delta = t
            else:
                # Subsequent spikes - store time difference
                delta = t - prev_time
            
            # Store delta and state
            neuron_encoded.append((delta, state.value))
            prev_time = t
        
        # Store the encoded data for this neuron
        encoded_data.append((neuron_idx, neuron_encoded))
    
    return encoded_data


def _delta_decode(
    encoded_data: List,
    original_shape: Tuple[int, ...]
) -> List[List[Tuple[int, SpikeState]]]:
    """
    Decompress delta encoded spike pattern.
    
    Args:
        encoded_data: Delta encoded data
        original_shape: Shape of the original pattern
        
    Returns:
        Decoded spike pattern
    """
    n_neurons = original_shape[0]
    
    # Initialize empty spike trains
    spike_pattern = [[] for _ in range(n_neurons)]
    
    # Decode each neuron
    for neuron_idx, neuron_encoded in encoded_data:
        if not neuron_encoded:
            # Empty neuron
            continue
        
        # Decode deltas
        current_time = 0
        
        for delta, state_value in neuron_encoded:
            current_time += delta
            state = SpikeState(state_value)
            
            # Add spike
            spike_pattern[neuron_idx].append((current_time, state))
    
    return spike_pattern


def _create_pattern_codebook(
    spike_patterns: List[List[List[Tuple[int, SpikeState]]]],
    max_patterns: int = 1000
) -> Dict:
    """
    Create a codebook for dictionary-based compression.
    
    Args:
        spike_patterns: List of spike patterns to analyze
        max_patterns: Maximum number of patterns to include in the codebook
        
    Returns:
        Codebook for compression
    """
    # Extract common sub-patterns
    pattern_counts = {}
    
    # Limit the number of patterns to analyze
    patterns_to_analyze = spike_patterns[:max_patterns]
    
    # Extract and count sub-patterns
    for pattern in patterns_to_analyze:
        for neuron_idx, neuron_spikes in enumerate(pattern):
            if len(neuron_spikes) < 2:
                # Skip neurons with 0 or 1 spike
                continue
            
            # Sort spikes by time
            sorted_spikes = sorted(neuron_spikes, key=lambda x: x[0])
            
            # Extract sub-patterns of 2-5 consecutive spikes
            for window_size in range(2, 6):
                for i in range(len(sorted_spikes) - window_size + 1):
                    sub_pattern = tuple(sorted_spikes[i:i+window_size])
                    
                    # Count occurrences
                    if sub_pattern in pattern_counts:
                        pattern_counts[sub_pattern] += 1
                    else:
                        pattern_counts[sub_pattern] = 1
    
    # Select most common sub-patterns for the codebook
    max_codes = 256  # Maximum number of codes (for 8-bit encoding)
    
    if len(pattern_counts) <= max_codes:
        # All patterns fit in the codebook
        selected_patterns = list(pattern_counts.keys())
    else:
        # Select the most common patterns
        selected_patterns = [
            pattern for pattern, _ in 
            sorted(pattern_counts.items(), key=lambda x: x[1], reverse=True)[:max_codes]
        ]
    
    # Create codebook
    codebook = {}
    for i, pattern in enumerate(selected_patterns):
        codebook[pattern] = i
    
    return codebook


def _dictionary_encode(
    spike_pattern: List[List[Tuple[int, SpikeState]]],
    codebook: Dict
) -> List:
    """
    Compress spike pattern using dictionary-based encoding.
    
    Args:
        spike_pattern: Spike pattern to compress
        codebook: Codebook mapping sub-patterns to codes
        
    Returns:
        Dictionary encoded data
    """
    encoded_data = []
    
    for neuron_idx, neuron_spikes in enumerate(spike_pattern):
        if not neuron_spikes:
            # Empty neuron - store as special case
            encoded_data.append((neuron_idx, []))
            continue
        
        # Sort spikes by time
        sorted_spikes = sorted(neuron_spikes, key=lambda x: x[0])
        
        # Try to encode using the codebook
        neuron_encoded = []
        i = 0
        
        while i < len(sorted_spikes):
            # Try to match the longest possible sub-pattern
            matched = False
            
            for window_size in range(5, 1, -1):  # Try longest first
                if i + window_size <= len(sorted_spikes):
                    sub_pattern = tuple(sorted_spikes[i:i+window_size])
                    
                    if sub_pattern in codebook:
                        # Found a match, encode it
                        code = codebook[sub_pattern]
                        neuron_encoded.append(('C', code))
                        i += window_size
                        matched = True
                        break
            
            if not matched:
                # No match found, encode the individual spike
                t, state = sorted_spikes[i]
                neuron_encoded.append(('S', (t, state.value)))
                i += 1
        
        # Store the encoded data for this neuron
        encoded_data.append((neuron_idx, neuron_encoded))
    
    return encoded_data


def _dictionary_decode(
    encoded_data: List,
    codebook: Dict,
    original_shape: Tuple[int, ...]
) -> List[List[Tuple[int, SpikeState]]]:
    """
    Decompress dictionary encoded spike pattern.
    
    Args:
        encoded_data: Dictionary encoded data
        codebook: Codebook mapping codes to sub-patterns
        original_shape: Shape of the original pattern
        
    Returns:
        Decoded spike pattern
    """
    n_neurons = original_shape[0]
    
    # Initialize empty spike trains
    spike_pattern = [[] for _ in range(n_neurons)]
    
    # Invert codebook for decoding
    inverted_codebook = {code: pattern for pattern, code in codebook.items()}
    
    # Decode each neuron
    for neuron_idx, neuron_encoded in encoded_data:
        if not neuron_encoded:
            # Empty neuron
            continue
        
        for entry_type, entry_data in neuron_encoded:
            if entry_type == 'C':
                # Codebook entry
                code = entry_data
                if code in inverted_codebook:
                    sub_pattern = inverted_codebook[code]
                    for t, state_wrapped in sub_pattern:
                        state = SpikeState(state_wrapped.value if hasattr(state_wrapped, 'value') else state_wrapped)
                        spike_pattern[neuron_idx].append((t, state))
            else:
                # Single spike
                t, state_value = entry_data
                state = SpikeState(state_value)
                spike_pattern[neuron_idx].append((t, state))
    
    return spike_pattern


class HuffmanNode:
    """Node in a Huffman tree."""
    
    def __init__(self, value=None, count=0):
        self.value = value  # None for internal nodes
        self.count = count
        self.left = None
        self.right = None
        self.code = ''


def _build_huffman_tree(frequencies: Dict) -> HuffmanNode:
    """
    Build a Huffman tree from frequency data.
    
    Args:
        frequencies: Dictionary mapping values to frequencies
        
    Returns:
        Root of the Huffman tree
    """
    # Create leaf nodes
    nodes = [HuffmanNode(value, count) for value, count in frequencies.items()]
    
    # Build tree bottom-up
    while len(nodes) > 1:
        # Sort nodes by frequency
        nodes.sort(key=lambda x: x.count)
        
        # Take two nodes with lowest frequencies
        left = nodes.pop(0)
        right = nodes.pop(0)
        
        # Create parent node
        parent = HuffmanNode(count=left.count + right.count)
        parent.left = left
        parent.right = right
        
        # Add parent back to the list
        nodes.append(parent)
    
    # Return root node
    return nodes[0] if nodes else None


def _build_huffman_codes(node: HuffmanNode, code: str = '') -> Dict:
    """
    Build Huffman codes from a Huffman tree.
    
    Args:
        node: Current node in the tree
        code: Current code path
        
    Returns:
        Dictionary mapping values to binary codes
    """
    codes = {}
    
    if node:
        # Leaf node: store the code
        if node.value is not None:
            codes[node.value] = code
        
        # Traverse left (add 0)
        if node.left:
            codes.update(_build_huffman_codes(node.left, code + '0'))
        
        # Traverse right (add 1)
        if node.right:
            codes.update(_build_huffman_codes(node.right, code + '1'))
    
    return codes


def _huffman_encode(spike_pattern: List[List[Tuple[int, SpikeState]]]) -> Tuple[bytes, HuffmanNode]:
    """
    Compress spike pattern using Huffman coding.
    
    Args:
        spike_pattern: Spike pattern to compress
        
    Returns:
        Huffman encoded data and Huffman tree
    """
    # Count frequencies of time values and states
    time_freq = {}
    state_freq = {}
    
    for neuron_spikes in spike_pattern:
        for t, state in neuron_spikes:
            # Count time value frequency
            if t in time_freq:
                time_freq[t] += 1
            else:
                time_freq[t] = 1
            
            # Count state frequency
            state_val = state.value
            if state_val in state_freq:
                state_freq[state_val] += 1
            else:
                state_freq[state_val] = 1
    
    # Build Huffman trees
    time_tree = _build_huffman_tree(time_freq)
    state_tree = _build_huffman_tree(state_freq)
    
    # Build Huffman codes
    time_codes = _build_huffman_codes(time_tree)
    state_codes = _build_huffman_codes(state_tree)
    
    # Encode the data
    encoded_strings = []
    
    # First encode the number of neurons
    n_neurons = len(spike_pattern)
    encoded_strings.append(bin(n_neurons)[2:].zfill(16))  # 16 bits for neuron count
    
    # Encode each neuron
    for neuron_idx, neuron_spikes in enumerate(spike_pattern):
        # Encode neuron index
        encoded_strings.append(bin(neuron_idx)[2:].zfill(16))  # 16 bits for neuron index
        
        # Encode spike count
        spike_count = len(neuron_spikes)
        encoded_strings.append(bin(spike_count)[2:].zfill(16))  # 16 bits for spike count
        
        # Encode each spike
        for t, state in neuron_spikes:
            time_code = time_codes.get(t, '')
            state_code = state_codes.get(state.value, '')
            
            # Add codes to the encoded string
            encoded_strings.append(time_code)
            encoded_strings.append(state_code)
    
    # Combine all encoded strings
    encoded_binary = ''.join(encoded_strings)
    
    # Pad to a multiple of 8 bits
    padding = 8 - (len(encoded_binary) % 8) if len(encoded_binary) % 8 != 0 else 0
    encoded_binary += '0' * padding
    
    # Convert binary string to bytes
    encoded_bytes = bytearray()
    for i in range(0, len(encoded_binary), 8):
        byte = encoded_binary[i:i+8]
        encoded_bytes.append(int(byte, 2))
    
    return bytes(encoded_bytes), (time_tree, state_tree)


def _huffman_decode(
    encoded_bytes: bytes,
    huffman_tree: Tuple[HuffmanNode, HuffmanNode],
    original_shape: Tuple[int, ...]
) -> List[List[Tuple[int, SpikeState]]]:
    """
    Decompress Huffman encoded spike pattern.
    
    Args:
        encoded_bytes: Huffman encoded data
        huffman_tree: Huffman trees for decoding (time_tree, state_tree)
        original_shape: Shape of the original pattern
        
    Returns:
        Decoded spike pattern
    """
    # Convert bytes to binary string
    encoded_binary = ''.join(bin(byte)[2:].zfill(8) for byte in encoded_bytes)
    
    # Unpack Huffman trees
    time_tree, state_tree = huffman_tree
    
    # Decode the data
    time_decoder = _create_huffman_decoder(time_tree)
    state_decoder = _create_huffman_decoder(state_tree)
    
    # Initialize spike pattern
    n_neurons = original_shape[0]
    spike_pattern = [[] for _ in range(n_neurons)]
    
    # Read number of neurons (16 bits)
    pos = 0
    read_neurons = int(encoded_binary[pos:pos+16], 2)
    pos += 16
    
    # Ensure consistent with expected neurons
    assert read_neurons == n_neurons, f"Neuron count mismatch: {read_neurons} != {n_neurons}"
    
    # Read each neuron
    while pos < len(encoded_binary) - 32:  # Ensure we have enough bits left
        # Read neuron index (16 bits)
        neuron_idx = int(encoded_binary[pos:pos+16], 2)
        pos += 16
        
        if neuron_idx >= n_neurons:
            break  # Invalid neuron index
        
        # Read spike count (16 bits)
        spike_count = int(encoded_binary[pos:pos+16], 2)
        pos += 16
        
        # Read each spike
        for _ in range(spike_count):
            # Decode time
            t, bits_read = time_decoder(encoded_binary[pos:])
            pos += bits_read
            
            # Decode state
            state_value, bits_read = state_decoder(encoded_binary[pos:])
            pos += bits_read
            
            # Add spike to the pattern
            state = SpikeState(state_value)
            spike_pattern[neuron_idx].append((t, state))
    
    return spike_pattern


def _create_huffman_decoder(tree: HuffmanNode) -> Callable:
    """
    Create a function that decodes a Huffman-encoded binary string.
    
    Args:
        tree: Huffman tree for decoding
        
    Returns:
        Decoding function
    """
    def decode_fn(binary_str: str) -> Tuple[Any, int]:
        """
        Decode binary string to a value.
        
        Args:
            binary_str: Binary string to decode
            
        Returns:
            Decoded value and number of bits read
        """
        node = tree
        bits_read = 0
        
        if not binary_str:
            return None, 0
        
        for bit in binary_str:
            if bit == '0':
                node = node.left
            else:  # bit == '1'
                node = node.right
                
            bits_read += 1
            
            if node and node.value is not None:
                # Reached a leaf node
                return node.value, bits_read
        
        # Failed to decode
        return None, bits_read
    
    return decode_fn


def _hybrid_encode(sparse_pattern: SparsePattern) -> Dict:
    """
    Hybrid encoding combining multiple compression techniques.
    
    Args:
        sparse_pattern: Sparse pattern to encode
        
    Returns:
        Hybrid encoded data
    """
    # Ensure input is in binary mask format for best results
    if sparse_pattern.format != SparseFormat.BINARY_MASK:
        sparse_pattern = convert_to_sparse(
            convert_from_sparse(sparse_pattern),
            format=SparseFormat.BINARY_MASK,
            compress_values=True
        )
    
    # Get binary masks
    binary_masks = sparse_pattern.data
    non_empty_times = sparse_pattern.metadata.get('non_empty_times', []) if sparse_pattern.metadata else []
    
    # Create compressed representation
    compressed_data = {
        'shape': sparse_pattern.shape,
        'format': 'hybrid',
        'non_empty_times': non_empty_times,
        'masks': {}
    }
    
    # Process each mask
    for t, mask in binary_masks.items():
        # Apply run-length encoding to each mask
        runs = []
        current_run = {'value': 0, 'start': 0, 'length': 0}
        
        for i, val in enumerate(mask):
            if val == current_run['value']:
                # Extend current run
                current_run['length'] += 1
            else:
                # Store current run if non-zero
                if current_run['value'] != 0:
                    runs.append((current_run['start'], current_run['length'], current_run['value']))
                
                # Start new run
                current_run = {'value': val, 'start': i, 'length': 1}
        
        # Store last run if non-zero
        if current_run['value'] != 0:
            runs.append((current_run['start'], current_run['length'], current_run['value']))
        
        # Store compressed mask
        compressed_data['masks'][t] = runs
    
    # Apply zlib compression to the serialized data
    serialized = pickle.dumps(compressed_data)
    compressed_bytes = zlib.compress(serialized)
    
    # Encode as base64 for easier storage
    base64_data = base64.b64encode(compressed_bytes).decode('ascii')
    
    # Create final hybrid encoded data
    return {
        'data': base64_data,
        'format': 'hybrid',
        'original_shape': sparse_pattern.shape
    }


def _hybrid_decode(encoded_data: Dict) -> SparsePattern:
    """
    Decode data compressed with hybrid encoding.
    
    Args:
        encoded_data: Hybrid encoded data
        
    Returns:
        Sparse pattern
    """
    # Extract base64 data
    base64_data = encoded_data['data']
    original_shape = encoded_data['original_shape']
    
    # Decode base64, decompress with zlib, and unpickle
    compressed_bytes = base64.b64decode(base64_data)
    decompressed = zlib.decompress(compressed_bytes)
    compressed_data = pickle.loads(decompressed)
    
    # Extract components
    shape = compressed_data['shape']
    non_empty_times = compressed_data['non_empty_times']
    compressed_masks = compressed_data['masks']
    
    # Reconstruct binary masks
    binary_masks = {}
    
    for t, runs in compressed_masks.items():
        # Create empty mask
        mask = np.zeros(shape[0], dtype=np.int8)
        
        # Fill with run-length encoded data
        for start, length, value in runs:
            mask[start:start+length] = value
        
        binary_masks[t] = mask
    
    # Create metadata
    metadata = {
        'n_spikes': sum(np.count_nonzero(mask) for mask in binary_masks.values()),
        'non_empty_times': non_empty_times
    }
    
    # Create sparse pattern
    return SparsePattern(
        format=SparseFormat.BINARY_MASK,
        data=binary_masks,
        shape=shape,
        metadata=metadata
    )


def measure_compression_ratio(
    original: List[List[Tuple[int, SpikeState]]],
    compressed: CompressedPattern
) -> float:
    """
    Measure compression ratio between original and compressed patterns.
    
    Args:
        original: Original spike pattern
        compressed: Compressed pattern
        
    Returns:
        Compression ratio (higher is better)
    """
    # Estimate original size
    original_size = _estimate_original_size(original)
    
    # Get compressed size
    compressed_size = compressed.metadata.get('compressed_size', 0)
    if compressed_size == 0:
        # Calculate if not already in metadata
        compressed_size = _estimate_compressed_size(compressed.data)
    
    # Calculate ratio
    if compressed_size > 0:
        return original_size / compressed_size
    else:
        return float('inf')  # Avoid division by zero


def batch_compress_patterns(
    spike_patterns: List[List[List[Tuple[int, SpikeState]]]],
    scheme: CompressionScheme = CompressionScheme.HYBRID,
    shared_codebook: bool = True
) -> List[CompressedPattern]:
    """
    Compress multiple spike patterns efficiently.
    
    Args:
        spike_patterns: List of spike patterns to compress
        scheme: Compression scheme to use
        shared_codebook: Whether to use a shared codebook
        
    Returns:
        List of compressed patterns
    """
    # Create shared codebook if requested
    codebook = None
    if shared_codebook and scheme == CompressionScheme.DICTIONARY:
        codebook = _create_pattern_codebook(spike_patterns)
    
    # Compress each pattern
    compressed_patterns = []
    
    for pattern in spike_patterns:
        compressed = encode_spike_pattern(pattern, scheme, codebook)
        compressed_patterns.append(compressed)
    
    return compressed_patterns


def create_pattern_codebook(
    spike_patterns: List[List[List[Tuple[int, SpikeState]]]],
    max_patterns: int = 1000
) -> Dict:
    """
    Create a codebook for dictionary-based compression.
    
    This is a public wrapper for the internal function.
    
    Args:
        spike_patterns: List of spike patterns to analyze
        max_patterns: Maximum number of patterns to include in the codebook
        
    Returns:
        Codebook for compression
    """
    return _create_pattern_codebook(spike_patterns, max_patterns)