""" 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)