Instructions to use psikosen/snow_spike with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- MLX
How to use psikosen/snow_spike with MLX:
# Make sure mlx-lm is installed # pip install --upgrade mlx-lm # if on a CUDA device, also pip install mlx[cuda] # Generate text with mlx-lm from mlx_lm import load, generate model, tokenizer = load("psikosen/snow_spike") prompt = "Once upon a time in" text = generate(model, tokenizer, prompt=prompt, verbose=True) - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- LM Studio
- MLX LM
How to use psikosen/snow_spike with MLX LM:
Generate or start a chat session
# Install MLX LM uv tool install mlx-lm # Generate some text mlx_lm.generate --model "psikosen/snow_spike" --prompt "Once upon a time"
- Atomic Chat
Download src/optimize/sparse_patterns.py from psikosen/snow_spike: direct link, hf CLI and curl.
- Browser
- Download file 28.2 kB
-
https://huggingface.co/psikosen/snow_spike/resolve/main/src/optimize/sparse_patterns.py
- Command line
-
hf download hf://psikosen/snow_spike/src/optimize/sparse_patterns.py
-
curl -L -o sparse_patterns.py https://huggingface.co/psikosen/snow_spike/resolve/main/src/optimize/sparse_patterns.py
28.2 kB
| """ | |
| 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 | |
| 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 | |
| ) | |