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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
"""
Tests for the optimization module.

This test suite verifies the functionality of the optimization module,
including sparse representations, MLX accelerated batch processing,
activity-triggered computation, and compression techniques.
"""

import unittest
import numpy as np
import time
from typing import List, Tuple, Dict

from src.utils.common import SpikeState
from src.optimize.sparse_patterns import (
    SparseFormat, SparsePattern, convert_to_sparse, convert_from_sparse,
    compute_sparse_similarity, filter_by_activity, batch_sparse_operations
)
from src.optimize.mlx_batch import (
    MLXBatchProcessor, batch_process_spikes, run_mlx_accelerated,
    get_device_optimized_batch_size, copy_to_device, process_in_batches
)
from src.optimize.activity_triggered import (
    ActivityThreshold, ActivityTrigger, ActivityTriggeredComputation,
    trigger_on_activity, compile_active_pathway, create_activity_triggered_network
)
from src.optimize.compression import (
    CompressionScheme, encode_spike_pattern, decode_spike_pattern,
    measure_compression_ratio, batch_compress_patterns, create_pattern_codebook
)


class TestSparsePatterns(unittest.TestCase):
    """Test case for sparse pattern functionality."""
    
    def setUp(self):
        """Set up test fixtures."""
        # Create a simple spike pattern for testing
        self.spike_pattern = [
            [(0, SpikeState.POSITIVE), (5, SpikeState.NEGATIVE)],
            [(1, SpikeState.POSITIVE), (3, SpikeState.POSITIVE), (4, SpikeState.NEGATIVE)],
            []  # Empty neuron
        ]
    
    def test_convert_to_sparse(self):
        """Test conversion to sparse format."""
        # Test conversion to COO format
        sparse_coo = convert_to_sparse(self.spike_pattern, format=SparseFormat.COO)
        self.assertEqual(sparse_coo.format, SparseFormat.COO)
        self.assertEqual(len(sparse_coo.data), 5)  # 5 spikes total
        
        # Test conversion to CSR format
        sparse_csr = convert_to_sparse(self.spike_pattern, format=SparseFormat.CSR)
        self.assertEqual(sparse_csr.format, SparseFormat.CSR)
        row_ptr, col_indices, values = sparse_csr.data
        self.assertEqual(len(row_ptr), 4)  # n_neurons + 1
        self.assertEqual(len(col_indices), 5)  # 5 spikes total
        
        # Test conversion to binary mask format
        sparse_binary = convert_to_sparse(self.spike_pattern, format=SparseFormat.BINARY_MASK)
        self.assertEqual(sparse_binary.format, SparseFormat.BINARY_MASK)
        self.assertIn(0, sparse_binary.data)  # Should have time step 0
        self.assertIn(5, sparse_binary.data)  # Should have time step 5
    
    def test_convert_from_sparse(self):
        """Test conversion from sparse format."""
        # Convert to sparse and back to original format
        for format_type in [SparseFormat.COO, SparseFormat.CSR, SparseFormat.CSC, 
                           SparseFormat.DICTIONARY, SparseFormat.BINARY_MASK]:
            sparse = convert_to_sparse(self.spike_pattern, format=format_type)
            reconstructed = convert_from_sparse(sparse)
            
            # Compare reconstructed pattern with original
            self.assertEqual(len(reconstructed), len(self.spike_pattern))
            
            # Count total spikes in original and reconstructed
            original_spikes = sum(len(neuron) for neuron in self.spike_pattern)
            reconstructed_spikes = sum(len(neuron) for neuron in reconstructed)
            
            self.assertEqual(reconstructed_spikes, original_spikes)
    
    def test_compute_sparse_similarity(self):
        """Test sparse pattern similarity computation."""
        # Create two slightly different patterns
        pattern1 = self.spike_pattern
        pattern2 = [
            [(0, SpikeState.POSITIVE), (5, SpikeState.NEGATIVE)],
            [(1, SpikeState.POSITIVE), (3, SpikeState.POSITIVE)],  # Missing one spike
            []
        ]
        
        # Convert to sparse format
        sparse1 = convert_to_sparse(pattern1, format=SparseFormat.COO)
        sparse2 = convert_to_sparse(pattern2, format=SparseFormat.COO)
        
        # Compute similarity directly on sparse patterns
        similarity = compute_sparse_similarity(sparse1, sparse2)
        
        # Similarity should be high but not 1.0
        self.assertLess(similarity, 1.0)
        self.assertGreater(similarity, 0.5)
    
    def test_filter_by_activity(self):
        """Test filtering by activity threshold."""
        # Convert to sparse
        sparse = convert_to_sparse(self.spike_pattern, format=SparseFormat.COO)
        
        # Filter with threshold
        filtered = filter_by_activity(sparse, activity_threshold=0.5)
        
        # Check results
        self.assertEqual(filtered.format, SparseFormat.COO)
        self.assertLessEqual(len(filtered.data), len(sparse.data))
    
    def test_batch_sparse_operations(self):
        """Test batch operations on sparse patterns."""
        # Create multiple patterns
        patterns = [self.spike_pattern for _ in range(3)]
        
        # Convert to sparse
        sparse_patterns = [convert_to_sparse(p, format=SparseFormat.COO) for p in patterns]
        
        # Test merge operation
        merged = batch_sparse_operations(sparse_patterns, operation='merge')
        self.assertEqual(merged.format, SparseFormat.COO)
        
        # The merged pattern should have all spikes from all patterns
        total_spikes = sum(sum(len(neuron) for neuron in p) for p in patterns)
        self.assertEqual(len(merged.data), total_spikes)
        
        # Test average operation
        avg = batch_sparse_operations(sparse_patterns, operation='average')
        self.assertEqual(avg.format, SparseFormat.COO)


class TestMLXBatch(unittest.TestCase):
    """Test case for MLX accelerated batch processing."""
    
    def setUp(self):
        """Set up test fixtures."""
        # Create spike patterns for testing
        self.spike_patterns = []
        
        for i in range(5):
            pattern = []
            for j in range(10):  # 10 neurons
                spikes = []
                for t in range(0, 20, 5):  # Spikes at times 0, 5, 10, 15
                    if (i + j + t) % 3 == 0:
                        spikes.append((t, SpikeState.POSITIVE))
                    elif (i + j + t) % 3 == 1:
                        spikes.append((t, SpikeState.NEGATIVE))
                pattern.append(spikes)
            self.spike_patterns.append(pattern)
    
    def test_batch_processor_creation(self):
        """Test MLXBatchProcessor initialization."""
        processor = MLXBatchProcessor()
        self.assertGreater(processor.batch_size, 0)
    
    def test_batch_process_spikes(self):
        """Test batch processing of spike patterns."""
        # Define a simple processing function
        def count_spikes(pattern):
            if not pattern:
                return 0
            return sum(len(neuron) for neuron in pattern)
        
        # Process patterns in batch
        results = batch_process_spikes(
            self.spike_patterns,
            count_spikes,
            batch_size=2  # Small batch size for testing
        )
        
        # Verify results
        self.assertEqual(len(results), len(self.spike_patterns))
        for pattern, result in zip(self.spike_patterns, results):
            expected = sum(len(neuron) for neuron in pattern)
            self.assertEqual(result, expected)
    
    def test_run_mlx_accelerated(self):
        """Test MLX accelerated function execution."""
        # Define a simple function
        def vector_sum(x):
            return np.sum(x, axis=0)
        
        # Create test data
        data = np.random.rand(10, 5)
        
        # Run with MLX acceleration
        result = run_mlx_accelerated(vector_sum, data)
        
        # Verify results
        expected = vector_sum(data)
        np.testing.assert_allclose(result, expected, rtol=1e-5)
    
    def test_get_device_optimized_batch_size(self):
        """Test batch size optimization based on device."""
        batch_size = get_device_optimized_batch_size(100, 100)
        self.assertGreater(batch_size, 0)
    
    def test_process_in_batches(self):
        """Test processing data in batches."""
        # Create test data
        data = list(range(10))
        
        # Define processing function
        def square(items):
            return [x**2 for x in items]
        
        # Process in batches
        results = process_in_batches(data, square, batch_size=3)
        
        # Verify results
        expected = [x**2 for x in data]
        self.assertEqual(results, expected)


class TestActivityTriggered(unittest.TestCase):
    """Test case for activity-triggered computation."""
    
    def setUp(self):
        """Set up test fixtures."""
        # Create spike patterns for testing
        self.spike_pattern = []
        
        for j in range(10):  # 10 neurons
            spikes = []
            if j < 3:  # Only first 3 neurons are active
                for t in range(0, 20, 5):  # Spikes at times 0, 5, 10, 15
                    spikes.append((t, SpikeState.POSITIVE))
            self.spike_pattern.append(spikes)
    
    def test_activity_trigger_creation(self):
        """Test activity trigger initialization."""
        trigger = ActivityTrigger(
            threshold_type=ActivityThreshold.RELATIVE,
            threshold_value=0.1
        )
        self.assertEqual(trigger.threshold_type, ActivityThreshold.RELATIVE)
        self.assertEqual(trigger.threshold_value, 0.1)
    
    def test_activity_triggered_computation(self):
        """Test activity-triggered computation management."""
        # Create manager
        manager = ActivityTriggeredComputation()
        
        # Test with active neurons
        active_neurons = [0, 1, 2]  # 3 out of 10 neurons are active
        should_trigger = manager.should_trigger(active_neurons, 10)
        
        # Should trigger with default settings (threshold 0.1)
        self.assertTrue(should_trigger)
        
        # Update stats and check again
        manager.update_stats(0.3)  # 30% activity
        should_trigger = manager.should_trigger(active_neurons, 10)
        
        # Should not trigger due to cooldown
        self.assertFalse(should_trigger)
    
    def test_trigger_on_activity(self):
        """Test triggering computation based on activity."""
        # Define a computation function
        def compute_fn(pattern):
            return sum(len(neuron) for neuron in pattern)
        
        # Create trigger config
        trigger = ActivityTrigger(
            threshold_type=ActivityThreshold.ABSOLUTE,
            threshold_value=2  # At least 2 active neurons
        )
        
        # Test with activity threshold met
        result = trigger_on_activity(
            self.spike_pattern,
            compute_fn,
            trigger_config=trigger,
            default_result=0
        )
        
        # Should compute and return non-default result
        expected = sum(len(neuron) for neuron in self.spike_pattern)
        self.assertEqual(result, expected)
        
        # Test with very high threshold
        trigger = ActivityTrigger(
            threshold_type=ActivityThreshold.ABSOLUTE,
            threshold_value=20  # More than active neurons
        )
        
        result = trigger_on_activity(
            self.spike_pattern,
            compute_fn,
            trigger_config=trigger,
            default_result=0
        )
        
        # Should return default result
        self.assertEqual(result, 0)


class TestCompression(unittest.TestCase):
    """Test case for spike pattern compression."""
    
    def setUp(self):
        """Set up test fixtures."""
        # Create a spike pattern for testing
        self.spike_pattern = []
        
        for j in range(10):  # 10 neurons
            spikes = []
            for t in range(0, 20, 5):  # Spikes at times 0, 5, 10, 15
                if (j + t) % 3 == 0:
                    spikes.append((t, SpikeState.POSITIVE))
                elif (j + t) % 3 == 1:
                    spikes.append((t, SpikeState.NEGATIVE))
            self.spike_pattern.append(spikes)
    
    def test_encode_decode_pattern(self):
        """Test encoding and decoding for all compression schemes."""
        for scheme in [CompressionScheme.RUN_LENGTH, CompressionScheme.DELTA,
                      CompressionScheme.HUFFMAN, CompressionScheme.HYBRID]:
            # Skip dictionary for now as it requires a codebook
            if scheme == CompressionScheme.DICTIONARY:
                continue
                
            # Encode the pattern
            compressed = encode_spike_pattern(self.spike_pattern, scheme=scheme)
            
            # Decode the pattern
            reconstructed = decode_spike_pattern(compressed)
            
            # Verify reconstructed pattern has same number of neurons
            self.assertEqual(len(reconstructed), len(self.spike_pattern))
            
            # Count total spikes in original and reconstructed
            original_spikes = sum(len(neuron) for neuron in self.spike_pattern)
            reconstructed_spikes = sum(len(neuron) for neuron in reconstructed)
            
            # Spikes should match
            self.assertEqual(reconstructed_spikes, original_spikes)
    
    def test_compression_ratio(self):
        """Test compression ratio measurement."""
        # Encode with different schemes
        compressed_run_length = encode_spike_pattern(
            self.spike_pattern, scheme=CompressionScheme.RUN_LENGTH)
        compressed_hybrid = encode_spike_pattern(
            self.spike_pattern, scheme=CompressionScheme.HYBRID)
        
        # Measure compression ratios
        ratio_run_length = measure_compression_ratio(self.spike_pattern, compressed_run_length)
        ratio_hybrid = measure_compression_ratio(self.spike_pattern, compressed_hybrid)
        
        # Verify ratios are positive
        self.assertGreater(ratio_run_length, 0)
        self.assertGreater(ratio_hybrid, 0)
    
    def test_batch_compress_patterns(self):
        """Test batch compression of multiple patterns."""
        # Create multiple patterns
        patterns = [self.spike_pattern for _ in range(3)]
        
        # Compress in batch
        compressed_patterns = batch_compress_patterns(
            patterns, scheme=CompressionScheme.RUN_LENGTH)
        
        # Verify results
        self.assertEqual(len(compressed_patterns), len(patterns))
        for compressed in compressed_patterns:
            self.assertEqual(compressed.scheme, CompressionScheme.RUN_LENGTH)
    
    def test_create_pattern_codebook(self):
        """Test creation of pattern codebook."""
        # Create multiple patterns
        patterns = [self.spike_pattern for _ in range(3)]
        
        # Create codebook
        codebook = create_pattern_codebook(patterns, max_patterns=10)
        
        # Verify codebook is non-empty
        self.assertGreater(len(codebook), 0)
        
        # Test encoding with the codebook
        compressed = encode_spike_pattern(
            self.spike_pattern, 
            scheme=CompressionScheme.DICTIONARY,
            codebook=codebook
        )
        
        # Verify encoding
        self.assertEqual(compressed.scheme, CompressionScheme.DICTIONARY)
        self.assertIsNotNone(compressed.codebook)
        
        # Test decoding
        reconstructed = decode_spike_pattern(compressed)
        
        # Verify reconstruction
        original_spikes = sum(len(neuron) for neuron in self.spike_pattern)
        reconstructed_spikes = sum(len(neuron) for neuron in reconstructed)
        self.assertEqual(reconstructed_spikes, original_spikes)


if __name__ == '__main__':
    unittest.main()