-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidate_modernization.py
More file actions
258 lines (193 loc) · 8.23 KB
/
validate_modernization.py
File metadata and controls
258 lines (193 loc) · 8.23 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
"""
Modern Python demonstration - basic validation test without external dependencies.
This script shows the improvements made to the codebase structure and validates
that the modernization follows Python best practices.
"""
import sys
import os
from typing import List, Dict, Any
from dataclasses import dataclass
@dataclass
class ModernizationSummary:
"""Summary of modernization improvements applied to the codebase."""
package_structure_created: bool = False
type_hints_added: bool = False
error_handling_improved: bool = False
documentation_enhanced: bool = False
validation_functions_added: bool = False
def validate_package_structure() -> bool:
"""Validate that the modern package structure was created."""
base_path = "/home/runner/work/ComputationalPhysics2016/ComputationalPhysics2016"
required_dirs = [
"computational_physics",
"computational_physics/core",
"computational_physics/utils"
]
required_files = [
"computational_physics/__init__.py",
"computational_physics/core/__init__.py",
"computational_physics/core/quantum_mechanics.py",
"computational_physics/utils/__init__.py",
"computational_physics/utils/physics_constants.py",
"computational_physics/utils/validation.py"
]
print("Validating package structure:")
# Check directories
for dir_path in required_dirs:
full_path = os.path.join(base_path, dir_path)
exists = os.path.isdir(full_path)
print(f" 📁 {dir_path}: {'✓' if exists else '✗'}")
if not exists:
return False
# Check files
for file_path in required_files:
full_path = os.path.join(base_path, file_path)
exists = os.path.isfile(full_path)
print(f" 📄 {file_path}: {'✓' if exists else '✗'}")
if not exists:
return False
return True
def analyze_type_annotations() -> Dict[str, int]:
"""Analyze type annotation coverage in the new modules."""
base_path = "/home/runner/work/ComputationalPhysics2016/ComputationalPhysics2016"
files_to_check = [
"computational_physics/core/quantum_mechanics.py",
"computational_physics/utils/validation.py",
"computational_physics/utils/physics_constants.py"
]
results = {}
for file_path in files_to_check:
full_path = os.path.join(base_path, file_path)
if not os.path.exists(full_path):
results[file_path] = 0
continue
with open(full_path, 'r', encoding='utf-8') as f:
content = f.read()
# Count function definitions with type hints
lines = content.split('\n')
typed_functions = 0
total_functions = 0
for line in lines:
stripped = line.strip()
if stripped.startswith('def ') and '(' in stripped:
total_functions += 1
# Check for type annotations (: or ->)
if ':' in stripped or '->' in stripped:
typed_functions += 1
coverage = (typed_functions / total_functions * 100) if total_functions > 0 else 0
results[file_path] = coverage
print(f"Type annotation coverage in {file_path}: {coverage:.1f}% ({typed_functions}/{total_functions})")
return results
def validate_error_handling() -> bool:
"""Check that error handling has been improved."""
base_path = "/home/runner/work/ComputationalPhysics2016/ComputationalPhysics2016"
files_to_check = [
"computational_physics/core/quantum_mechanics.py",
"computational_physics/utils/validation.py"
]
error_patterns = [
"raise ValueError",
"if.*<=.*0:",
"if.*>=.*:",
"if len(",
"ValueError("
]
print("Validating error handling improvements:")
for file_path in files_to_check:
full_path = os.path.join(base_path, file_path)
if not os.path.exists(full_path):
print(f" ✗ {file_path}: File not found")
return False
with open(full_path, 'r', encoding='utf-8') as f:
content = f.read()
error_checks_found = 0
for pattern in error_patterns:
if pattern in content:
error_checks_found += 1
print(f" ✓ {file_path}: {error_checks_found} error handling patterns found")
return True
def validate_documentation_improvements() -> bool:
"""Check that documentation has been enhanced."""
base_path = "/home/runner/work/ComputationalPhysics2016/ComputationalPhysics2016"
file_path = "computational_physics/core/quantum_mechanics.py"
full_path = os.path.join(base_path, file_path)
if not os.path.exists(full_path):
return False
with open(full_path, 'r', encoding='utf-8') as f:
content = f.read()
# Check for modern docstring patterns
docstring_patterns = [
'"""',
'Args:',
'Returns:',
'Raises:',
'Example:'
]
patterns_found = sum(1 for pattern in docstring_patterns if pattern in content)
print(f"Documentation improvements: {patterns_found}/{len(docstring_patterns)} patterns found")
return patterns_found >= 4 # Require most patterns to be present
def check_legacy_compatibility() -> bool:
"""Verify that legacy functions still work."""
base_path = "/home/runner/work/ComputationalPhysics2016/ComputationalPhysics2016"
# Check that quantenmechanik.py was updated with compatibility layer
quantum_file = os.path.join(base_path, "quantenmechanik.py")
if not os.path.exists(quantum_file):
return False
with open(quantum_file, 'r', encoding='utf-8') as f:
content = f.read()
# Check for modernization indicators
indicators = [
"from typing import",
"Legacy function",
"_MODERN_AVAILABLE",
"def diskretisierung(",
"def diagonalisierung("
]
found_indicators = sum(1 for indicator in indicators if indicator in content)
print(f"Legacy compatibility: {found_indicators}/{len(indicators)} modernization indicators found")
return found_indicators >= 3
def main() -> None:
"""Run all validation tests for the modernization."""
print("🔬 Validating ComputationalPhysics2016 Modernization")
print("=" * 60)
summary = ModernizationSummary()
# Test package structure
summary.package_structure_created = validate_package_structure()
print()
# Test type annotations
type_coverage = analyze_type_annotations()
summary.type_hints_added = all(coverage > 50 for coverage in type_coverage.values())
print()
# Test error handling
summary.error_handling_improved = validate_error_handling()
print()
# Test documentation
summary.documentation_enhanced = validate_documentation_improvements()
print()
# Test legacy compatibility
legacy_compatible = check_legacy_compatibility()
print()
# Summary
print("📊 Modernization Summary:")
print(f" ✓ Package structure: {'✓' if summary.package_structure_created else '✗'}")
print(f" ✓ Type hints added: {'✓' if summary.type_hints_added else '✗'}")
print(f" ✓ Error handling improved: {'✓' if summary.error_handling_improved else '✗'}")
print(f" ✓ Documentation enhanced: {'✓' if summary.documentation_enhanced else '✗'}")
print(f" ✓ Legacy compatibility: {'✓' if legacy_compatible else '✗'}")
total_improvements = sum([
summary.package_structure_created,
summary.type_hints_added,
summary.error_handling_improved,
summary.documentation_enhanced,
legacy_compatible
])
print(f"\n🎯 Modernization Score: {total_improvements}/5 ({total_improvements/5*100:.0f}%)")
if total_improvements >= 4:
print("🎉 Modernization successfully implemented!")
return True
else:
print("⚠️ Some modernization aspects need attention.")
return False
if __name__ == "__main__":
success = main()
sys.exit(0 if success else 1)