oxirs-vec 0.2.4

Vector index abstractions for semantic similarity and AI-augmented querying
Documentation
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
#!/usr/bin/env python3
"""
Test suite for OxiRS Vector Search Python bindings.

This comprehensive test suite validates the functionality of the Python bindings,
including vector operations, store management, analytics, and SPARQL integration.
"""

import pytest
import numpy as np
import tempfile
import os
from typing import List, Dict, Any

# Import OxiRS Vector Search (will be mocked if not available)
try:
    import oxirs_vec
    OXIRS_AVAILABLE = True
except ImportError:
    OXIRS_AVAILABLE = False
    
    # Mock classes for testing when OxiRS is not available
    class MockVectorStore:
        def __init__(self, *args, **kwargs):
            self.vectors = {}
            self.metadata = {}
        
        def index_resource(self, id: str, content: str, metadata=None):
            self.vectors[id] = np.random.rand(128).astype(np.float32)
            self.metadata[id] = metadata or {}
        
        def similarity_search(self, query: str, limit=10, **kwargs):
            return [{"id": f"doc_{i}", "score": 0.8 - i*0.1, "metadata": {}} 
                   for i in range(min(limit, len(self.vectors)))]
    
    class MockModule:
        VectorStore = MockVectorStore
        VectorSearchError = Exception
    
    oxirs_vec = MockModule()

@pytest.fixture
def vector_store():
    """Create a test vector store."""
    if OXIRS_AVAILABLE:
        return oxirs_vec.VectorStore(
            embedding_strategy="tf_idf",
            index_type="memory"
        )
    else:
        return oxirs_vec.VectorStore()

@pytest.fixture
def sample_documents():
    """Sample documents for testing."""
    return [
        ("doc1", "Machine learning and artificial intelligence research"),
        ("doc2", "Deep neural networks for computer vision applications"), 
        ("doc3", "Natural language processing with transformer models"),
        ("doc4", "Reinforcement learning algorithms and applications"),
        ("doc5", "Computer graphics and 3D rendering techniques"),
        ("doc6", "Database systems and query optimization"),
        ("doc7", "Distributed computing and cloud architectures"),
        ("doc8", "Cybersecurity and encryption algorithms"),
        ("doc9", "Data science and statistical analysis methods"),
        ("doc10", "Software engineering and design patterns")
    ]

@pytest.fixture
def sample_vectors():
    """Generate sample vectors for testing."""
    np.random.seed(42)  # For reproducible tests
    return np.random.rand(100, 128).astype(np.float32)

class TestVectorStore:
    """Test vector store functionality."""
    
    def test_vector_store_creation(self):
        """Test vector store creation with different configurations."""
        if not OXIRS_AVAILABLE:
            pytest.skip("OxiRS not available")
        
        # Test different embedding strategies
        strategies = ["tf_idf", "sentence_transformer", "openai"]
        for strategy in strategies:
            try:
                store = oxirs_vec.VectorStore(embedding_strategy=strategy)
                assert store is not None
            except oxirs_vec.EmbeddingError:
                # Some strategies might not be available in test environment
                pass
    
    def test_index_resource(self, vector_store, sample_documents):
        """Test indexing text resources."""
        # Index documents
        for doc_id, content in sample_documents:
            metadata = {"category": "tech", "length": len(content)}
            vector_store.index_resource(doc_id, content, metadata)
        
        # Verify indexing
        if OXIRS_AVAILABLE:
            stats = vector_store.get_stats()
            assert stats["total_vectors"] == len(sample_documents)
    
    def test_similarity_search(self, vector_store, sample_documents):
        """Test similarity search functionality."""
        # Index documents
        for doc_id, content in sample_documents:
            vector_store.index_resource(doc_id, content)
        
        # Search for similar content
        results = vector_store.similarity_search(
            "machine learning", 
            limit=5, 
            threshold=0.1
        )
        
        assert len(results) <= 5
        assert all(isinstance(r, dict) for r in results)
        assert all("id" in r and "score" in r for r in results)
        
        # Check score ordering (should be descending)
        scores = [r["score"] for r in results]
        assert scores == sorted(scores, reverse=True)
    
    def test_vector_operations(self, vector_store, sample_vectors):
        """Test direct vector operations."""
        if not OXIRS_AVAILABLE:
            pytest.skip("OxiRS not available")
        
        # Index vectors
        vector_ids = [f"vec_{i}" for i in range(len(sample_vectors))]
        metadata_list = [{"index": i, "category": i % 5} for i in range(len(sample_vectors))]
        
        vector_store.index_batch(vector_ids, sample_vectors, metadata_list)
        
        # Test vector search
        query_vector = sample_vectors[0]  # Use first vector as query
        results = vector_store.vector_search(
            query_vector, 
            limit=10, 
            metric="cosine"
        )
        
        assert len(results) <= 10
        assert results[0]["id"] == "vec_0"  # Should find itself first
        assert results[0]["score"] >= 0.99  # Should be very similar to itself
    
    def test_get_vector(self, vector_store, sample_vectors):
        """Test vector retrieval."""
        if not OXIRS_AVAILABLE:
            pytest.skip("OxiRS not available")
        
        # Index a vector
        test_id = "test_vector"
        test_vector = sample_vectors[0]
        vector_store.index_vector(test_id, test_vector)
        
        # Retrieve the vector
        retrieved = vector_store.get_vector(test_id)
        assert retrieved is not None
        np.testing.assert_array_almost_equal(retrieved, test_vector, decimal=5)
    
    def test_remove_vector(self, vector_store, sample_vectors):
        """Test vector removal."""
        if not OXIRS_AVAILABLE:
            pytest.skip("OxiRS not available")
        
        # Index a vector
        test_id = "removable_vector"
        vector_store.index_vector(test_id, sample_vectors[0])
        
        # Verify it exists
        assert vector_store.get_vector(test_id) is not None
        
        # Remove it
        removed = vector_store.remove_vector(test_id)
        assert removed == True
        
        # Verify it's gone
        assert vector_store.get_vector(test_id) is None
    
    def test_store_persistence(self, vector_store, sample_documents):
        """Test saving and loading vector stores."""
        if not OXIRS_AVAILABLE:
            pytest.skip("OxiRS not available")
        
        # Index some data
        for doc_id, content in sample_documents[:5]:
            vector_store.index_resource(doc_id, content)
        
        # Save to temporary file
        with tempfile.NamedTemporaryFile(delete=False, suffix='.bin') as f:
            temp_path = f.name
        
        try:
            vector_store.save(temp_path)
            
            # Load from file
            loaded_store = oxirs_vec.VectorStore.load(temp_path)
            
            # Verify data is preserved
            original_stats = vector_store.get_stats()
            loaded_stats = loaded_store.get_stats()
            assert original_stats["total_vectors"] == loaded_stats["total_vectors"]
            
        finally:
            # Clean up
            if os.path.exists(temp_path):
                os.unlink(temp_path)

class TestUtilityFunctions:
    """Test utility functions."""
    
    def test_compute_similarity(self):
        """Test similarity computation."""
        if not OXIRS_AVAILABLE:
            pytest.skip("OxiRS not available")
        
        # Create test vectors
        vec1 = np.array([1.0, 0.0, 0.0], dtype=np.float32)
        vec2 = np.array([0.0, 1.0, 0.0], dtype=np.float32)
        vec3 = np.array([1.0, 0.0, 0.0], dtype=np.float32)
        
        # Test different metrics
        cosine_sim = oxirs_vec.compute_similarity(vec1, vec2, "cosine")
        assert abs(cosine_sim - 0.0) < 1e-6  # Orthogonal vectors
        
        cosine_sim_same = oxirs_vec.compute_similarity(vec1, vec3, "cosine")
        assert abs(cosine_sim_same - 1.0) < 1e-6  # Identical vectors
        
        euclidean_dist = oxirs_vec.compute_similarity(vec1, vec2, "euclidean")
        assert euclidean_dist > 0  # Should be positive distance
    
    def test_normalize_vector(self):
        """Test vector normalization."""
        if not OXIRS_AVAILABLE:
            pytest.skip("OxiRS not available")
        
        # Create test vector
        vector = np.array([3.0, 4.0, 0.0], dtype=np.float32)
        normalized = oxirs_vec.normalize_vector(vector)
        
        # Check normalization
        norm = np.linalg.norm(normalized)
        assert abs(norm - 1.0) < 1e-6
        
        # Check direction preservation
        expected = np.array([0.6, 0.8, 0.0], dtype=np.float32)
        np.testing.assert_array_almost_equal(normalized, expected, decimal=5)
    
    def test_batch_normalize(self):
        """Test batch vector normalization."""
        if not OXIRS_AVAILABLE:
            pytest.skip("OxiRS not available")
        
        # Create test vectors
        vectors = np.array([
            [3.0, 4.0, 0.0],
            [1.0, 0.0, 0.0],
            [0.0, 0.0, 1.0]
        ], dtype=np.float32)
        
        normalized = oxirs_vec.batch_normalize(vectors)
        
        # Check that all vectors are normalized
        norms = np.linalg.norm(normalized, axis=1)
        np.testing.assert_array_almost_equal(norms, [1.0, 1.0, 1.0], decimal=5)

class TestVectorAnalytics:
    """Test vector analytics functionality."""
    
    def test_analytics_creation(self):
        """Test analytics engine creation."""
        if not OXIRS_AVAILABLE:
            pytest.skip("OxiRS not available")
        
        analytics = oxirs_vec.VectorAnalytics()
        assert analytics is not None
    
    def test_vector_analysis(self, sample_vectors):
        """Test vector distribution analysis."""
        if not OXIRS_AVAILABLE:
            pytest.skip("OxiRS not available")
        
        analytics = oxirs_vec.VectorAnalytics()
        labels = [f"cluster_{i % 5}" for i in range(len(sample_vectors))]
        
        analysis = analytics.analyze_vectors(sample_vectors, labels)
        
        # Check analysis results
        assert "num_vectors" in analysis
        assert "dimension" in analysis
        assert "sparsity" in analysis
        assert analysis["num_vectors"] == len(sample_vectors)
        assert analysis["dimension"] == sample_vectors.shape[1]
    
    def test_optimization_recommendations(self):
        """Test optimization recommendations."""
        if not OXIRS_AVAILABLE:
            pytest.skip("OxiRS not available")
        
        analytics = oxirs_vec.VectorAnalytics()
        recommendations = analytics.get_recommendations()
        
        assert isinstance(recommendations, list)
        for rec in recommendations:
            assert "type" in rec
            assert "priority" in rec
            assert "description" in rec
            assert "expected_improvement" in rec

class TestSparqlIntegration:
    """Test SPARQL integration functionality."""
    
    def test_sparql_search_creation(self, vector_store):
        """Test SPARQL search interface creation."""
        if not OXIRS_AVAILABLE:
            pytest.skip("OxiRS not available")
        
        sparql_search = oxirs_vec.SparqlVectorSearch(vector_store)
        assert sparql_search is not None
    
    def test_function_registration(self, vector_store):
        """Test custom function registration."""
        if not OXIRS_AVAILABLE:
            pytest.skip("OxiRS not available")
        
        sparql_search = oxirs_vec.SparqlVectorSearch(vector_store)
        
        # Register a custom function
        sparql_search.register_function(
            "vec:customSimilarity",
            arity=2,
            description="Custom similarity function"
        )
        
        # Should not raise an exception
        assert True
    
    def test_sparql_query_execution(self, vector_store, sample_documents):
        """Test SPARQL query execution."""
        if not OXIRS_AVAILABLE:
            pytest.skip("OxiRS not available")
        
        # Index some RDF-like content
        for doc_id, content in sample_documents[:5]:
            vector_store.index_resource(f"http://example.org/{doc_id}", content)
        
        sparql_search = oxirs_vec.SparqlVectorSearch(vector_store)
        
        # Simple SPARQL query with vector extensions
        query = """
        SELECT ?resource WHERE {
            ?resource vec:similar("machine learning", 3, 0.1) .
        }
        """
        
        try:
            results = sparql_search.execute_query(query)
            assert "bindings" in results
            assert "variables" in results
            assert "execution_time_ms" in results
        except Exception as e:
            # SPARQL parsing might not be fully implemented in test environment
            pytest.skip(f"SPARQL execution not available: {e}")

class TestErrorHandling:
    """Test error handling and edge cases."""
    
    def test_invalid_embedding_strategy(self):
        """Test invalid embedding strategy handling."""
        if not OXIRS_AVAILABLE:
            pytest.skip("OxiRS not available")
        
        with pytest.raises(oxirs_vec.EmbeddingError):
            oxirs_vec.VectorStore(embedding_strategy="invalid_strategy")
    
    def test_invalid_similarity_metric(self):
        """Test invalid similarity metric handling."""
        if not OXIRS_AVAILABLE:
            pytest.skip("OxiRS not available")
        
        vec1 = np.array([1.0, 0.0], dtype=np.float32)
        vec2 = np.array([0.0, 1.0], dtype=np.float32)
        
        with pytest.raises(oxirs_vec.VectorSearchError):
            oxirs_vec.compute_similarity(vec1, vec2, "invalid_metric")
    
    def test_dimension_mismatch(self):
        """Test dimension mismatch handling."""
        if not OXIRS_AVAILABLE:
            pytest.skip("OxiRS not available")
        
        vec1 = np.array([1.0, 0.0], dtype=np.float32)
        vec2 = np.array([0.0, 1.0, 0.0], dtype=np.float32)  # Different dimension
        
        with pytest.raises((oxirs_vec.VectorSearchError, ValueError)):
            oxirs_vec.compute_similarity(vec1, vec2, "cosine")

class TestPerformance:
    """Performance and benchmark tests."""
    
    def test_large_batch_indexing(self):
        """Test indexing large batches of vectors."""
        if not OXIRS_AVAILABLE:
            pytest.skip("OxiRS not available")
        
        # Generate large batch
        batch_size = 10000
        dimension = 256
        vectors = np.random.rand(batch_size, dimension).astype(np.float32)
        vector_ids = [f"vec_{i}" for i in range(batch_size)]
        
        store = oxirs_vec.VectorStore(
            embedding_strategy="tf_idf",
            index_type="memory"
        )
        
        # Time the indexing operation
        import time
        start_time = time.time()
        store.index_batch(vector_ids, vectors)
        end_time = time.time()
        
        indexing_time = end_time - start_time
        vectors_per_second = batch_size / indexing_time
        
        print(f"Indexed {batch_size} vectors in {indexing_time:.2f}s")
        print(f"Throughput: {vectors_per_second:.0f} vectors/second")
        
        # Verify indexing
        stats = store.get_stats()
        assert stats["total_vectors"] == batch_size
    
    def test_search_performance(self):
        """Test search performance with varying parameters."""
        if not OXIRS_AVAILABLE:
            pytest.skip("OxiRS not available")
        
        # Create store with performance-oriented configuration
        store = oxirs_vec.VectorStore(
            embedding_strategy="tf_idf",
            index_type="hnsw",
            max_connections=32,
            ef_construction=400
        )
        
        # Index test data
        n_vectors = 1000
        dimension = 128
        vectors = np.random.rand(n_vectors, dimension).astype(np.float32)
        vector_ids = [f"vec_{i}" for i in range(n_vectors)]
        store.index_batch(vector_ids, vectors)
        
        # Optimize for search
        store.optimize()
        
        # Benchmark search operations
        query_vector = np.random.rand(dimension).astype(np.float32)
        
        import time
        search_times = []
        n_queries = 100
        
        for _ in range(n_queries):
            start_time = time.time()
            results = store.vector_search(query_vector, limit=10)
            end_time = time.time()
            search_times.append(end_time - start_time)
        
        avg_search_time = np.mean(search_times) * 1000  # Convert to ms
        std_search_time = np.std(search_times) * 1000
        
        print(f"Average search time: {avg_search_time:.2f}±{std_search_time:.2f}ms")
        print(f"Queries per second: {1000 / avg_search_time:.0f}")
        
        # Performance assertion (should be fast)
        assert avg_search_time < 100  # Should be under 100ms

if __name__ == "__main__":
    # Run tests with pytest
    import subprocess
    import sys
    
    # Check if pytest is available
    try:
        import pytest
        print("Running OxiRS Vector Search Python binding tests...")
        result = pytest.main([__file__, "-v", "--tb=short"])
        sys.exit(result)
    except ImportError:
        print("pytest not available. Running basic tests...")
        
        # Run basic tests without pytest
        store = oxirs_vec.VectorStore() if OXIRS_AVAILABLE else MockVectorStore()
        docs = [
            ("doc1", "Machine learning"),
            ("doc2", "Deep learning"),
            ("doc3", "Neural networks")
        ]
        
        for doc_id, content in docs:
            store.index_resource(doc_id, content)
        
        results = store.similarity_search("AI", limit=2)
        print(f"Search results: {results}")
        print("Basic tests completed successfully!")