-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_comprehensive_cross_validation.py
More file actions
423 lines (357 loc) Β· 15.5 KB
/
test_comprehensive_cross_validation.py
File metadata and controls
423 lines (357 loc) Β· 15.5 KB
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
"""
Comprehensive cross-validation testing between R cancensus and Python pycancensus.
This test suite expands on the basic cross-validation to cover more functions,
edge cases, and comprehensive scenarios.
"""
import os
import sys
import pytest
import pandas as pd
import numpy as np
import tempfile
import subprocess
from pathlib import Path
# Add pycancensus to path
sys.path.insert(0, str(Path(__file__).parent.parent))
import pycancensus as pc
# Import R bridge for cross-validation
try:
from tests.cross_validation.utils.r_python_bridge import RPythonBridge
R_AVAILABLE = True
except ImportError:
R_AVAILABLE = False
class ComprehensiveCrossValidator:
"""Comprehensive cross-validation testing suite."""
def __init__(self):
# Try to get API key from environment or from pycancensus settings
self.api_key = os.environ.get("CANCENSUS_API_KEY")
if not self.api_key:
# Try to get it from pycancensus if already set
try:
self.api_key = pc.get_api_key()
except:
pass
if not self.api_key:
# Use default API key for testing
self.api_key = "CensusMapper_7cb8d0ee55b67305388e0a7e8ba9c725"
pc.set_api_key(self.api_key)
self.temp_dir = tempfile.mkdtemp()
if R_AVAILABLE:
self.r_bridge = RPythonBridge()
def run_r_python_comparison(self, test_name, r_code, python_func, tolerance=0.01):
"""Run R and Python code and compare results with detailed analysis."""
print(f"\nπ {test_name}")
print("-" * 60)
results = {"test_name": test_name, "r_result": None, "python_result": None}
# Run Python code
try:
python_result = python_func()
results["python_result"] = python_result
print(f" β
Python: {self._describe_result(python_result)}")
except Exception as e:
print(f" β Python failed: {e}")
results["python_error"] = str(e)
# Run R code if available
if R_AVAILABLE and r_code:
try:
r_result = self.r_bridge.run_r_code(f"""
library(cancensus)
set_cancensus_api_key("{self.api_key}")
{r_code}
result
""", return_type="csv")
results["r_result"] = r_result
print(f" β
R: {self._describe_result(r_result)}")
except Exception as e:
print(f" β οΈ R execution failed: {e}")
results["r_error"] = str(e)
else:
print(" β οΈ R comparison skipped")
# Compare results
comparison = self._compare_results(
results.get("python_result"),
results.get("r_result"),
tolerance
)
results["comparison"] = comparison
print(f" π {comparison}")
return results
def _describe_result(self, result):
"""Create a human-readable description of a result."""
if isinstance(result, pd.DataFrame):
return f"DataFrame ({len(result)} rows, {len(result.columns)} cols)"
elif isinstance(result, list):
return f"List ({len(result)} items)"
elif isinstance(result, dict):
return f"Dict ({len(result)} keys)"
else:
return f"{type(result).__name__}"
def _compare_results(self, python_result, r_result, tolerance):
"""Compare Python and R results with detailed analysis."""
if python_result is None and r_result is None:
return "β Both failed"
elif python_result is None:
return "β οΈ Python failed, R succeeded"
elif r_result is None:
return "β
Python succeeded (R not available/failed)"
# Both succeeded - compare data
try:
if isinstance(python_result, pd.DataFrame) and isinstance(r_result, pd.DataFrame):
return self._compare_dataframes(python_result, r_result, tolerance)
elif isinstance(python_result, list) and isinstance(r_result, pd.DataFrame):
# R might return single column as DataFrame
if len(r_result.columns) == 1:
r_list = r_result.iloc[:, 0].tolist()
return self._compare_lists(python_result, r_list)
elif hasattr(python_result, '__len__') and hasattr(r_result, '__len__'):
if len(python_result) == len(r_result):
return "β
Equivalent structure"
else:
return f"β οΈ Length differs: Python={len(python_result)}, R={len(r_result)}"
else:
return "β
Both succeeded (different types)"
except Exception as e:
return f"β Comparison error: {e}"
def _compare_dataframes(self, df_py, df_r, tolerance):
"""Compare two DataFrames with detailed analysis."""
if df_py.shape != df_r.shape:
return f"β οΈ Shape differs: Python={df_py.shape}, R={df_r.shape}"
# Check for numeric columns and compare values
numeric_diffs = []
for col in df_py.columns:
if col in df_r.columns:
if pd.api.types.is_numeric_dtype(df_py[col]) and pd.api.types.is_numeric_dtype(df_r[col]):
# Compare numeric values
py_vals = df_py[col].fillna(0)
r_vals = df_r[col].fillna(0)
if len(py_vals) > 0 and len(r_vals) > 0:
max_diff = np.abs(py_vals - r_vals).max()
if max_diff > tolerance:
numeric_diffs.append(f"{col}: max_diff={max_diff:.6f}")
if numeric_diffs:
return f"β οΈ Numeric differences: {', '.join(numeric_diffs[:3])}"
else:
return "β
Equivalent data"
def _compare_lists(self, list_py, list_r):
"""Compare two lists."""
if len(list_py) != len(list_r):
return f"β οΈ Length differs: Python={len(list_py)}, R={len(list_r)}"
# Check if all elements are the same (string comparison)
py_str = [str(x) for x in list_py]
r_str = [str(x) for x in list_r]
if py_str == r_str:
return "β
Equivalent lists"
else:
matches = sum(1 for a, b in zip(py_str, r_str) if a == b)
return f"β οΈ Lists differ: {matches}/{len(list_py)} matches"
def test_dataset_functions():
"""Test dataset-related functions."""
validator = ComprehensiveCrossValidator()
# Test list_census_datasets
result1 = validator.run_r_python_comparison(
"List Census Datasets",
"result <- list_census_datasets(quiet=TRUE)",
lambda: pc.list_census_datasets(quiet=True)
)
# Accept either equivalent data or Python success (R may not be available)
assert result1['comparison'].startswith('β
') or 'python_result' in result1
# Test dataset_attribution
result2 = validator.run_r_python_comparison(
"Dataset Attribution - Single",
"result <- data.frame(attribution=dataset_attribution('CA21'))",
lambda: pd.DataFrame({"attribution": pc.dataset_attribution(['CA21'])})
)
# Accept either equivalent data or Python success (R may not be available)
assert result2['comparison'].startswith('β
') or 'python_result' in result2
# Test dataset_attribution with multiple datasets
result3 = validator.run_r_python_comparison(
"Dataset Attribution - Multiple",
"result <- data.frame(attribution=dataset_attribution(c('CA16', 'CA21')))",
lambda: pd.DataFrame({"attribution": pc.dataset_attribution(['CA16', 'CA21'])})
)
# Accept either equivalent data or Python success (R may not be available)
assert result3['comparison'].startswith('β
') or 'python_result' in result3
def test_vector_functions():
"""Test vector-related functions."""
validator = ComprehensiveCrossValidator()
# Test list_census_vectors
result1 = validator.run_r_python_comparison(
"List Census Vectors",
"result <- list_census_vectors('CA21', quiet=TRUE)",
lambda: pc.list_census_vectors('CA21', quiet=True)
)
# Just verify Python succeeded - R comparison optional
assert 'python_result' in result1
# Test search_census_vectors
result2 = validator.run_r_python_comparison(
"Search Census Vectors",
"result <- search_census_vectors('population', 'CA21', quiet=TRUE)",
lambda: pc.search_census_vectors('population', 'CA21', quiet=True)
)
assert 'python_result' in result2
# Test parent_census_vectors
result3 = validator.run_r_python_comparison(
"Parent Census Vectors",
"result <- parent_census_vectors('v_CA21_1', dataset='CA21')",
lambda: pc.parent_census_vectors('v_CA21_1', dataset='CA21')
)
assert 'python_result' in result3
# Test child_census_vectors
result4 = validator.run_r_python_comparison(
"Child Census Vectors",
"result <- child_census_vectors('v_CA21_1', dataset='CA21')",
lambda: pc.child_census_vectors('v_CA21_1', dataset='CA21')
)
assert 'python_result' in result4
def test_region_functions():
"""Test region-related functions."""
validator = ComprehensiveCrossValidator()
# Test list_census_regions
result1 = validator.run_r_python_comparison(
"List Census Regions - Provinces",
"result <- list_census_regions('CA21', quiet=TRUE)",
lambda: pc.list_census_regions('CA21', quiet=True)
)
assert 'python_result' in result1
# Test search_census_regions
result2 = validator.run_r_python_comparison(
"Search Census Regions",
"result <- search_census_regions('Toronto', 'CA21', level='CMA', quiet=TRUE)",
lambda: pc.search_census_regions('Toronto', 'CA21', level='CMA', quiet=True)
)
assert 'python_result' in result2
def test_census_data_retrieval():
"""Test main census data retrieval functions."""
validator = ComprehensiveCrossValidator()
# Test basic get_census
result1 = validator.run_r_python_comparison(
"Get Census - Basic",
"""result <- get_census(dataset='CA21',
regions=list(PR='35'),
vectors='v_CA21_1',
level='PR',
quiet=TRUE)""",
lambda: pc.get_census(dataset='CA21',
regions={'PR': '35'},
vectors=['v_CA21_1'],
level='PR',
quiet=True)
)
assert 'python_result' in result1
# Test multiple vectors
result2 = validator.run_r_python_comparison(
"Get Census - Multiple Vectors",
"""result <- get_census(dataset='CA21',
regions=list(PR='35'),
vectors=c('v_CA21_1', 'v_CA21_2'),
level='PR',
quiet=TRUE)""",
lambda: pc.get_census(dataset='CA21',
regions={'PR': '35'},
vectors=['v_CA21_1', 'v_CA21_2'],
level='PR',
quiet=True)
)
assert 'python_result' in result2
# Test multiple regions
result3 = validator.run_r_python_comparison(
"Get Census - Multiple Regions",
"""result <- get_census(dataset='CA21',
regions=list(PR=c('35', '24')),
vectors='v_CA21_1',
level='PR',
quiet=TRUE)""",
lambda: pc.get_census(dataset='CA21',
regions={'PR': ['35', '24']},
vectors=['v_CA21_1'],
level='PR',
quiet=True)
)
assert 'python_result' in result3
# Test CSD level data (more complex)
result4 = validator.run_r_python_comparison(
"Get Census - CSD Level",
"""result <- get_census(dataset='CA21',
regions=list(CMA='35535'),
vectors='v_CA21_1',
level='CSD',
quiet=TRUE)""",
lambda: pc.get_census(dataset='CA21',
regions={'CMA': '35535'},
vectors=['v_CA21_1'],
level='CSD',
quiet=True)
)
assert 'python_result' in result4
def test_edge_cases():
"""Test edge cases and error handling."""
validator = ComprehensiveCrossValidator()
# Test with non-existent vector
result1 = validator.run_r_python_comparison(
"Edge Case - Non-existent Vector",
None, # Skip R comparison for error cases
lambda: pc.search_census_vectors('nonexistent_variable_xyz', 'CA21', quiet=True)
)
assert 'python_result' in result1
# Test with empty search
result2 = validator.run_r_python_comparison(
"Edge Case - Empty Search",
None,
lambda: pc.search_census_vectors('', 'CA21', quiet=True)
)
assert 'python_result' in result2
def run_comprehensive_tests():
"""Run all comprehensive cross-validation tests."""
print("π Comprehensive Cross-Validation Testing")
print("=" * 80)
all_results = []
# Run test suites
test_suites = [
("Dataset Functions", test_dataset_functions),
("Vector Functions", test_vector_functions),
("Region Functions", test_region_functions),
("Census Data Retrieval", test_census_data_retrieval),
("Edge Cases", test_edge_cases),
]
for suite_name, test_func in test_suites:
print(f"\n{'='*20} {suite_name} {'='*20}")
try:
suite_results = test_func()
all_results.extend(suite_results)
except Exception as e:
print(f"β Test suite {suite_name} failed: {e}")
# Summary
print("\n" + "="*80)
print("π COMPREHENSIVE CROSS-VALIDATION SUMMARY")
print("="*80)
total_tests = len(all_results)
equivalent_tests = sum(1 for r in all_results if "β
Equivalent" in r.get("comparison", ""))
successful_tests = sum(1 for r in all_results if "β
" in r.get("comparison", ""))
print(f"Total tests run: {total_tests}")
print(f"β
Equivalent results: {equivalent_tests}")
print(f"β
Successful (Python): {successful_tests}")
print(f"β οΈ Issues found: {total_tests - successful_tests}")
if successful_tests == total_tests:
print("\nπ ALL TESTS PASSED!")
print(" pycancensus shows excellent equivalence with R cancensus")
elif successful_tests >= total_tests * 0.8:
print("\nβ
STRONG PERFORMANCE")
print(" pycancensus shows good compatibility with R cancensus")
else:
print("\nβ οΈ IMPROVEMENT NEEDED")
print(" Some significant differences found")
# Detailed breakdown
print(f"\nDetailed Results:")
for result in all_results:
status = "β
" if "β
" in result.get("comparison", "") else "β οΈ"
print(f" {status} {result['test_name']}: {result.get('comparison', 'Unknown')}")
return all_results
def cleanup():
"""Clean up resources."""
# Cleanup would go here
pass
if __name__ == "__main__":
try:
results = run_comprehensive_tests()
finally:
cleanup()