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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
import unittest
import numpy as np
import tempfile
import os
import pickle
import shutil
from unittest.mock import Mock, patch
from sklearn.decomposition import PCA
from sklearn.cluster import AgglomerativeClustering

# Import the implementations to test
# Assuming canonical implementation is in 'canonical.py' and generated in 'generated.py'
try:
    from presto.canonical import Atom as CanonicalAtom
    from presto.atom import Atom as GeneratedAtom
    # Import Presto class for reference
    from presto.presto import Presto
except ImportError:
    # Fallback if modules are named differently
    print("Warning: Could not import canonical/generated modules. Adjust import paths as needed.")
    CanonicalAtom = None
    GeneratedAtom = None
    Presto = None


class TestAtomFunctionalEquivalence(unittest.TestCase):
    """
    Test suite to verify functional equivalence between canonical and generated Atom implementations.
    
    This suite tests all public methods of the Atom class by comparing outputs from both implementations
    when given identical inputs. Tests use small, representative datasets for efficiency.
    """
    
    def setUp(self):
        """Set up test fixtures with small sample data."""
        # Create small representative embeddings for testing
        np.random.seed(42)  # For reproducible test data
        
        # Small 2D embeddings (10 points each, 2 dimensions)
        self.embedding1 = np.random.rand(10, 2).astype(np.float32)
        self.embedding2 = np.random.rand(10, 2).astype(np.float32) + 1.0
        self.embedding3 = np.random.rand(10, 2).astype(np.float32) + 2.0
        
        # Test data list
        self.test_embeddings = [self.embedding1, self.embedding2, self.embedding3]
        
        # Common parameters for testing
        self.test_seed = 42
        self.test_epsilon = 0.5
        self.test_linkage = 'complete'
        
        # Create temporary directory for file operations
        self.temp_dir = tempfile.mkdtemp()
        
        # Pre-computed small MMS matrix for testing (3x3 symmetric matrix)
        self.test_mms = np.array([
            [0.0, 0.8, 1.2],
            [0.8, 0.0, 0.6],
            [1.2, 0.6, 0.0]
        ])
        
    def tearDown(self):
        """Clean up temporary files."""
        shutil.rmtree(self.temp_dir, ignore_errors=True)
    
    def test_atom_initialization_with_list(self):
        """Test Atom initialization with list of embeddings."""
        canonical_atom = CanonicalAtom(data=self.test_embeddings, seed=self.test_seed)
        generated_atom = GeneratedAtom(data=self.test_embeddings, seed=self.test_seed)
        
        # Compare basic attributes
        self.assertEqual(canonical_atom.multiverse_size, generated_atom.multiverse_size,
                        "Multiverse size mismatch")
        self.assertEqual(canonical_atom.seed, generated_atom.seed,
                        "Seed mismatch")
        self.assertEqual(len(canonical_atom.data), len(generated_atom.data),
                        "Data length mismatch")
        
        # Compare data arrays
        for i, (canonical_emb, generated_emb) in enumerate(zip(canonical_atom.data, generated_atom.data)):
            np.testing.assert_array_equal(canonical_emb, generated_emb,
                                        f"Embedding {i} data mismatch")
    
    def test_atom_initialization_with_folder(self):
        """Test Atom initialization with folder path."""
        # Create test pickle files
        for i, embedding in enumerate(self.test_embeddings):
            file_path = os.path.join(self.temp_dir, f"embedding_{i}.pkl")
            with open(file_path, 'wb') as f:
                pickle.dump(embedding, f)
        
        canonical_atom = CanonicalAtom(data=self.temp_dir, seed=self.test_seed)
        generated_atom = GeneratedAtom(data=self.temp_dir, seed=self.test_seed)
        
        # Compare attributes
        self.assertEqual(canonical_atom.multiverse_size, generated_atom.multiverse_size,
                        "Multiverse size mismatch when loading from folder")
        self.assertEqual(len(canonical_atom.data), len(generated_atom.data),
                        "Data length mismatch when loading from folder")
        
        # Compare loaded data
        for i, (canonical_emb, generated_emb) in enumerate(zip(canonical_atom.data, generated_atom.data)):
            np.testing.assert_array_equal(canonical_emb, generated_emb,
                                        f"Loaded embedding {i} data mismatch")
    
    @patch('presto.Presto')  # Mock the Presto class from presto.py
    def test_compute_mms_functional_equivalence(self, mock_presto):
        """Test compute_mms method functional equivalence."""
        # Mock Presto class to return deterministic distances
        mock_distances = [0.8, 1.2, 0.6]  # Distances for 3 embeddings (3 choose 2 = 3 pairs)
        
        def mock_presto_factory():
            mock_instance = Mock()
            mock_instance.fit_transform.side_effect = mock_distances
            return mock_instance
        
        mock_presto.return_value = mock_presto_factory()
        
        # Initialize atoms
        canonical_atom = CanonicalAtom(data=self.test_embeddings, seed=self.test_seed)
        generated_atom = GeneratedAtom(data=self.test_embeddings, seed=self.test_seed)
        
        # Test parameters
        test_params = {
            'projector': PCA,
            'n_projections': 1,
            'score_type': 'aggregate',
            'n_components': 2,
            'normalize': False,
            'max_homology_dim': 1,
            'resolution': 50,
            'normalization_approx_iterations': 100,
            'parallelize': False  # Use False for deterministic testing
        }
        
        # Compute MMS on both implementations
        canonical_atom.compute_mms(**test_params)
        generated_atom.compute_mms(**test_params)
        
        # Compare MMS matrices
        self.assertIsInstance(canonical_atom.MMS, type(generated_atom.MMS),
                            "MMS matrix type mismatch")
        
        if canonical_atom.MMS is not None and generated_atom.MMS is not None:
            np.testing.assert_array_almost_equal(
                canonical_atom.MMS, generated_atom.MMS,
                decimal=10, err_msg="MMS matrices do not match"
            )
            
            # Verify matrix properties
            self.assertEqual(canonical_atom.MMS.shape, generated_atom.MMS.shape,
                           "MMS matrix shape mismatch")
            self.assertTrue(np.allclose(canonical_atom.MMS, canonical_atom.MMS.T),
                          "Canonical MMS matrix not symmetric")
            self.assertTrue(np.allclose(generated_atom.MMS, generated_atom.MMS.T),
                          "Generated MMS matrix not symmetric")
    
    def test_save_and_load_mms_functional_equivalence(self):
        """Test save_mms and load_mms methods functional equivalence."""
        # Initialize atoms and set a test MMS
        canonical_atom = CanonicalAtom(data=self.test_embeddings, seed=self.test_seed)
        generated_atom = GeneratedAtom(data=self.test_embeddings, seed=self.test_seed)
        
        canonical_atom.MMS = self.test_mms.copy()
        generated_atom.MMS = self.test_mms.copy()
        
        # Test save_mms
        canonical_path = os.path.join(self.temp_dir, "canonical_mms.pkl")
        generated_path = os.path.join(self.temp_dir, "generated_mms.pkl")
        
        canonical_atom.save_mms(canonical_path)
        generated_atom.save_mms(generated_path)
        
        # Verify files were created
        self.assertTrue(os.path.exists(canonical_path), "Canonical MMS file not saved")
        self.assertTrue(os.path.exists(generated_path), "Generated MMS file not saved")
        
        # Load and compare saved data
        with open(canonical_path, 'rb') as f:
            canonical_saved = pickle.load(f)
        with open(generated_path, 'rb') as f:
            generated_saved = pickle.load(f)
        
        np.testing.assert_array_equal(canonical_saved, generated_saved,
                                    "Saved MMS matrices do not match")
        
        # Test load_mms by setting MMS from file path
        new_canonical_atom = CanonicalAtom(data=self.test_embeddings, seed=self.test_seed)
        new_generated_atom = GeneratedAtom(data=self.test_embeddings, seed=self.test_seed)
        
        new_canonical_atom.MMS = canonical_path
        new_generated_atom.MMS = generated_path
        
        np.testing.assert_array_equal(new_canonical_atom.MMS, new_generated_atom.MMS,
                                    "Loaded MMS matrices do not match")
    
    def test_cluster_functional_equivalence(self):
        """Test cluster method functional equivalence."""
        canonical_atom = CanonicalAtom(data=self.test_embeddings, seed=self.test_seed)
        generated_atom = GeneratedAtom(data=self.test_embeddings, seed=self.test_seed)
        
        # Set identical MMS matrices
        canonical_atom.MMS = self.test_mms.copy()
        generated_atom.MMS = self.test_mms.copy()
        
        # Perform clustering with identical parameters
        canonical_clustering = canonical_atom.cluster(epsilon=self.test_epsilon, linkage=self.test_linkage)
        generated_clustering = generated_atom.cluster(epsilon=self.test_epsilon, linkage=self.test_linkage)
        
        # Compare clustering results
        self.assertIsInstance(canonical_clustering, AgglomerativeClustering,
                            "Canonical clustering should return AgglomerativeClustering")
        self.assertIsInstance(generated_clustering, AgglomerativeClustering,
                            "Generated clustering should return AgglomerativeClustering")
        
        # Compare cluster labels (main output)
        np.testing.assert_array_equal(canonical_clustering.labels_, generated_clustering.labels_,
                                    "Cluster labels do not match")
        
        # Compare number of clusters
        canonical_n_clusters = len(np.unique(canonical_clustering.labels_))
        generated_n_clusters = len(np.unique(generated_clustering.labels_))
        self.assertEqual(canonical_n_clusters, generated_n_clusters,
                        "Number of clusters mismatch")
        
        # Compare stored parameters
        self.assertEqual(canonical_atom.epsilon, generated_atom.epsilon,
                        "Stored epsilon parameter mismatch")
        self.assertEqual(canonical_atom.linkage, generated_atom.linkage,
                        "Stored linkage parameter mismatch")
    
    def test_compute_set_cover_functional_equivalence(self):
        """Test compute_set_cover method functional equivalence."""
        canonical_atom = CanonicalAtom(data=self.test_embeddings, seed=self.test_seed)
        generated_atom = GeneratedAtom(data=self.test_embeddings, seed=self.test_seed)
        
        # Set identical MMS matrices
        canonical_atom.MMS = self.test_mms.copy()
        generated_atom.MMS = self.test_mms.copy()
        
        # Compute set cover with identical parameters
        canonical_set_cover = canonical_atom.compute_set_cover(epsilon=self.test_epsilon)
        generated_set_cover = generated_atom.compute_set_cover(epsilon=self.test_epsilon)
        
        # Compare set cover results
        self.assertIsInstance(canonical_set_cover, dict,
                            "Canonical set cover should return dict")
        self.assertIsInstance(generated_set_cover, dict,
                            "Generated set cover should return dict")
        
        # Compare keys (representative indices)
        self.assertEqual(set(canonical_set_cover.keys()), set(generated_set_cover.keys()),
                        "Set cover representative keys do not match")
        
        # Compare values (covered indices for each representative)
        for key in canonical_set_cover.keys():
            canonical_covered = sorted(canonical_set_cover[key])
            generated_covered = sorted(generated_set_cover[key])
            self.assertEqual(canonical_covered, generated_covered,
                           f"Covered indices for representative {key} do not match")
        
        # Verify coverage completeness for both implementations
        canonical_all_covered = set()
        generated_all_covered = set()
        
        for covered_list in canonical_set_cover.values():
            canonical_all_covered.update(covered_list)
        for covered_list in generated_set_cover.values():
            generated_all_covered.update(covered_list)
        
        expected_all_indices = set(range(len(self.test_embeddings)))
        self.assertEqual(canonical_all_covered, expected_all_indices,
                        "Canonical set cover doesn't cover all embeddings")
        self.assertEqual(generated_all_covered, expected_all_indices,
                        "Generated set cover doesn't cover all embeddings")
        self.assertEqual(canonical_all_covered, generated_all_covered,
                        "Overall coverage sets do not match")
    
    def test_static_methods_functional_equivalence(self):
        """Test static utility methods functional equivalence."""
        # Test validate_distance_matrix
        valid_matrix = self.test_mms.copy()
        shape = (3, 3)
        
        canonical_validated = CanonicalAtom.validate_distance_matrix(valid_matrix, shape)
        generated_validated = GeneratedAtom.validate_distance_matrix(valid_matrix, shape)
        
        np.testing.assert_array_equal(canonical_validated, generated_validated,
                                    "Validated matrices do not match")
        
        # Test file_id_sorter
        test_filenames = ["file_10.pkl", "file_2.pkl", "file_100.pkl", "no_number.pkl"]
        
        canonical_sorted = sorted(test_filenames, key=CanonicalAtom.file_id_sorter)
        generated_sorted = sorted(test_filenames, key=GeneratedAtom.file_id_sorter)
        
        self.assertEqual(canonical_sorted, generated_sorted,
                        "File sorting results do not match")
        
        # Test _load_data with pickle file
        test_data = self.test_mms.copy()
        test_file = os.path.join(self.temp_dir, "test_data.pkl")
        
        with open(test_file, 'wb') as f:
            pickle.dump(test_data, f)
        
        canonical_loaded = CanonicalAtom._load_data(test_file)
        generated_loaded = GeneratedAtom._load_data(test_file)
        
        np.testing.assert_array_equal(canonical_loaded, generated_loaded,
                                    "Loaded data does not match")
    
    def test_edge_cases_functional_equivalence(self):
        """Test edge cases and error handling functional equivalence."""
        # Test with single embedding
        single_embedding = [self.embedding1]
        
        canonical_atom = CanonicalAtom(data=single_embedding, seed=self.test_seed)
        generated_atom = GeneratedAtom(data=single_embedding, seed=self.test_seed)
        
        self.assertEqual(canonical_atom.multiverse_size, generated_atom.multiverse_size,
                        "Single embedding multiverse size mismatch")
        
        # Test invalid data type
        with self.assertRaises(TypeError):
            CanonicalAtom(data=123, seed=self.test_seed)
        with self.assertRaises(TypeError):
            GeneratedAtom(data=123, seed=self.test_seed)
        
        # Test invalid MMS type - both implementations should raise FileNotFoundError 
        # when trying to load a non-existent file path
        canonical_atom = CanonicalAtom(data=self.test_embeddings, seed=self.test_seed)
        generated_atom = GeneratedAtom(data=self.test_embeddings, seed=self.test_seed)
        
        with self.assertRaises(FileNotFoundError):
            canonical_atom.MMS = "invalid_type"
        with self.assertRaises(FileNotFoundError):
            generated_atom.MMS = "invalid_type"


class TestAtomWithRandomness(unittest.TestCase):
    """
    Test suite for functions with randomness, focusing on structural properties
    rather than exact value comparisons.
    """
    
    def setUp(self):
        """Set up test fixtures."""
        np.random.seed(42)
        self.test_embeddings = [
            np.random.rand(8, 2).astype(np.float32),
            np.random.rand(8, 2).astype(np.float32) + 1,
            np.random.rand(8, 2).astype(np.float32) + 2
        ]
        self.test_seed = 42
    
    @patch('presto.Presto')
    def test_mms_computation_with_fixed_seed(self, mock_presto):
        """Test MMS computation reproducibility with fixed seed."""
        canonical_atom1 = CanonicalAtom(data=self.test_embeddings, seed=self.test_seed)
        canonical_atom2 = CanonicalAtom(data=self.test_embeddings, seed=self.test_seed)
        
        generated_atom1 = GeneratedAtom(data=self.test_embeddings, seed=self.test_seed)
        generated_atom2 = GeneratedAtom(data=self.test_embeddings, seed=self.test_seed)
        
        # Set up identical mock behavior
        mock_distances = [0.5, 0.7, 0.3]
        
        def create_mock_presto():
            mock_instance = Mock()
            mock_instance.fit_transform.side_effect = mock_distances
            return mock_instance
        
        mock_presto.return_value = create_mock_presto()
        
        # Compute MMS with identical parameters
        params = {'parallelize': False, 'n_projections': 1}
        
        canonical_atom1.compute_mms(**params)
        canonical_atom2.compute_mms(**params)
        generated_atom1.compute_mms(**params)
        generated_atom2.compute_mms(**params)
        
        # Verify reproducibility within each implementation
        np.testing.assert_array_equal(canonical_atom1.MMS, canonical_atom2.MMS,
                                    "Canonical implementation not reproducible")
        np.testing.assert_array_equal(generated_atom1.MMS, generated_atom2.MMS,
                                    "Generated implementation not reproducible")
        
        # Verify equivalence between implementations
        np.testing.assert_array_equal(canonical_atom1.MMS, generated_atom1.MMS,
                                    "MMS matrices differ between implementations")


if __name__ == '__main__':
    # Create a test suite combining all test cases
    test_suite = unittest.TestLoader().loadTestsFromTestCase(TestAtomFunctionalEquivalence)
    test_suite.addTests(unittest.TestLoader().loadTestsFromTestCase(TestAtomWithRandomness))
    
    # Run the tests with detailed output
    runner = unittest.TextTestRunner(verbosity=2, buffer=True)
    result = runner.run(test_suite)
    
    # Print summary
    print(f"\n{'='*60}")
    print(f"TEST SUMMARY")
    print(f"{'='*60}")
    print(f"Tests run: {result.testsRun}")
    print(f"Failures: {len(result.failures)}")
    print(f"Errors: {len(result.errors)}")
    print(f"Success rate: {((result.testsRun - len(result.failures) - len(result.errors)) / result.testsRun * 100):.1f}%")
    
    if result.failures:
        print(f"\nFAILURES:")
        for test, traceback in result.failures:
            error_msg = traceback.split('AssertionError: ')[-1].split('\n')[0]
            print(f"- {test}: {error_msg}")
    
    if result.errors:
        print(f"\nERRORS:")
        for test, traceback in result.errors:
            error_msg = traceback.split('\n')[-2]
            print(f"- {test}: {error_msg}")