-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathanalyzer.py
More file actions
1985 lines (1725 loc) · 77 KB
/
analyzer.py
File metadata and controls
1985 lines (1725 loc) · 77 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
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
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Analysis analyzer module for GNN statistical analysis.
"""
import json
import logging
import re
import sys
import time
from datetime import datetime
from pathlib import Path
from typing import Any, Dict, List, Optional, cast
import numpy as np
logger = logging.getLogger(__name__)
# Import visualization libraries with error handling
try:
import scipy.stats as stats
SCIPY_AVAILABLE = True
except ImportError:
SCIPY_AVAILABLE = False
stats = cast(Any, None)
from .viz_base import MATPLOTLIB_AVAILABLE, plt
try:
import seaborn as sns
SEABORN_AVAILABLE = True
except ImportError:
sns = cast(Any, None)
SEABORN_AVAILABLE = False
def perform_statistical_analysis(
file_path: Path, verbose: bool = False
) -> Dict[str, Any]:
"""Perform comprehensive statistical analysis on a GNN file."""
try:
with open(file_path, "r") as f:
content = f.read()
# Extract structural elements
variables = extract_variables(content)
connections = extract_connections(content)
sections = extract_sections(content)
# Calculate statistics
var_stats = calculate_variable_statistics(variables)
conn_stats = calculate_connection_statistics(connections)
section_stats = calculate_section_statistics(sections)
# Analyze distributions
distributions = analyze_distributions(variables, connections)
# Calculate correlations
correlations = calculate_correlations(variables, connections)
return {
"file_path": str(file_path),
"file_name": file_path.name,
"file_size": file_path.stat().st_size,
"line_count": len(content.splitlines()),
"variables": variables,
"connections": connections,
"sections": sections,
"variable_statistics": var_stats,
"connection_statistics": conn_stats,
"section_statistics": section_stats,
"distributions": distributions,
"correlations": correlations,
"analysis_timestamp": datetime.now().isoformat(),
}
except Exception as e:
raise RuntimeError(f"Failed to analyze {file_path}: {e}") from e
def extract_variables(content: str) -> List[Dict[str, Any]]:
"""Extract variables for statistical analysis."""
variables: list[Any] = []
# Look for variable definitions
var_patterns: list[Any] = [
r"(\w+)\s*:\s*(\w+)", # name: type
r"(\w+)\s*=\s*([^;\n]+)", # name = value
r"(\w+)\s*\[([^\]]+)\]", # name[dimensions]
]
for pattern in var_patterns:
matches = re.finditer(pattern, content)
for match in matches:
variables.append(
{
"name": match.group(1),
"definition": match.group(0),
"line": content[: match.start()].count("\n") + 1,
"type": match.group(2) if ":" in match.group(0) else "unknown",
}
)
return variables
def extract_connections(content: str) -> List[Dict[str, Any]]:
"""Extract connections for statistical analysis."""
connections: list[Any] = []
seen: set[Any] = set() # Deduplicate connections
# 1. Parse GNN ## Connections section directly (highest priority)
connections_section = re.search(
r"##\s*Connections\s*\n(.*?)(?=\n##\s|\Z)", content, re.DOTALL
)
if connections_section:
section_text = connections_section.group(1)
section_start_line = content[: connections_section.start()].count("\n") + 2
for i, line in enumerate(section_text.strip().split("\n")):
line = line.strip()
if not line or line.startswith("#"):
continue
# GNN connection operators: > (directional), - (bidirectional), < (reverse)
gnn_match = re.match(r"(\w+)\s*([>\-<])\s*(\w+)", line)
if gnn_match:
src, op, tgt = (
gnn_match.group(1),
gnn_match.group(2),
gnn_match.group(3),
)
conn_type = (
"directional"
if op == ">"
else "bidirectional"
if op == "-"
else "reverse"
)
key = (src, tgt, conn_type)
if key not in seen:
seen.add(key)
connections.append(
{
"source": src,
"target": tgt,
"connection": line,
"connection_type": conn_type,
"line": section_start_line + i,
}
)
# 2. Also look for generic connection patterns outside the section
conn_patterns: list[Any] = [
(r"(\w+)\s*->\s*(\w+)", "directional"), # source -> target
(r"(\w+)\s*→\s*(\w+)", "directional"), # source → target
(r"(\w+)\s*connects\s*(\w+)", "association"), # source connects target
]
for pattern, conn_type in conn_patterns:
matches = re.finditer(pattern, content)
for match in matches:
key = (match.group(1), match.group(2), conn_type)
if key not in seen:
seen.add(key)
connections.append(
{
"source": match.group(1),
"target": match.group(2),
"connection": match.group(0),
"connection_type": conn_type,
"line": content[: match.start()].count("\n") + 1,
}
)
return connections
def extract_sections(content: str) -> List[Dict[str, Any]]:
"""Extract sections for statistical analysis."""
sections: list[Any] = []
# Look for section headers
section_patterns: list[Any] = [
r"^#+\s+(.+)$", # Markdown headers
r"^(\w+):\s*$", # Section labels
]
for pattern in section_patterns:
matches = re.finditer(pattern, content, re.MULTILINE)
for match in matches:
sections.append(
{
"name": match.group(1),
"line": content[: match.start()].count("\n") + 1,
}
)
return sections
def calculate_variable_statistics(variables: List[Dict[str, Any]]) -> Dict[str, Any]:
"""Calculate statistics for variables."""
if not variables:
return {"count": 0, "types": {}, "average_line": 0}
stats: dict[str, Any] = {
"count": len(variables),
"types": {},
"average_line": np.mean([var.get("line", 0) for var in variables]),
"line_std": np.std([var.get("line", 0) for var in variables]),
}
# Count types
for var in variables:
var_type = var.get("type", "unknown")
stats["types"][var_type] = stats["types"].get(var_type, 0) + 1
return stats
def calculate_connection_statistics(
connections: List[Dict[str, Any]],
) -> Dict[str, Any]:
"""Calculate statistics for connections."""
if not connections:
return {"count": 0, "average_line": 0}
stats: dict[str, Any] = {
"count": len(connections),
"average_line": np.mean([conn.get("line", 0) for conn in connections]),
"line_std": np.std([conn.get("line", 0) for conn in connections]),
}
return stats
def calculate_section_statistics(sections: List[Dict[str, Any]]) -> Dict[str, Any]:
"""Calculate statistics for sections."""
if not sections:
return {"count": 0, "average_line": 0}
stats: dict[str, Any] = {
"count": len(sections),
"average_line": np.mean([section.get("line", 0) for section in sections]),
"line_std": np.std([section.get("line", 0) for section in sections]),
}
return stats
def count_type_distribution(variables: List[Dict[str, Any]]) -> Dict[str, int]:
"""Count distribution of variable types."""
type_counts: dict[Any, Any] = {}
for var in variables:
var_type = var.get("type", "unknown")
type_counts[var_type] = type_counts.get(var_type, 0) + 1
return type_counts
def build_connectivity_matrix(
connections: List[Dict[str, Any]],
) -> Dict[str, List[str]]:
"""Build connectivity matrix from connections."""
connectivity: dict[Any, Any] = {}
for conn in connections:
source = conn.get("source", "")
target = conn.get("target", "")
if source not in connectivity:
connectivity[source] = []
connectivity[source].append(target)
return connectivity
def analyze_distributions(
variables: List[Dict[str, Any]], connections: List[Dict[str, Any]]
) -> Dict[str, Any]:
"""Analyze distributions of model elements."""
analysis: dict[str, Any] = {
"variable_distribution": {},
"connection_distribution": {},
"complexity_metrics": {},
}
# Analyze variable distribution
if variables:
var_lines = [var.get("line", 0) for var in variables]
analysis["variable_distribution"] = {
"mean": float(np.mean(var_lines)),
"std": float(np.std(var_lines)),
"min": float(np.min(var_lines)),
"max": float(np.max(var_lines)),
"median": float(np.median(var_lines)),
}
if SCIPY_AVAILABLE and len(var_lines) > 2:
analysis["variable_distribution"]["skewness"] = float(stats.skew(var_lines))
analysis["variable_distribution"]["kurtosis"] = float(
stats.kurtosis(var_lines)
)
counts = np.unique(var_lines, return_counts=True)[1]
analysis["variable_distribution"]["entropy"] = float(stats.entropy(counts))
# Analyze connection distribution
if connections:
conn_lines = [conn.get("line", 0) for conn in connections]
analysis["connection_distribution"] = {
"mean": float(np.mean(conn_lines)),
"std": float(np.std(conn_lines)),
"min": float(np.min(conn_lines)),
"max": float(np.max(conn_lines)),
"median": float(np.median(conn_lines)),
}
if SCIPY_AVAILABLE and len(conn_lines) > 2:
analysis["connection_distribution"]["skewness"] = float(
stats.skew(conn_lines)
)
analysis["connection_distribution"]["kurtosis"] = float(
stats.kurtosis(conn_lines)
)
counts = np.unique(conn_lines, return_counts=True)[1]
analysis["connection_distribution"]["entropy"] = float(
stats.entropy(counts)
)
# Calculate complexity metrics
analysis["complexity_metrics"] = {
"total_elements": len(variables) + len(connections),
"variable_complexity": len(variables),
"connection_complexity": len(connections),
"density": len(connections) / max(len(variables), 1),
"cyclomatic_complexity": len(connections) - len(variables) + 2,
}
return analysis
def calculate_correlations(
variables: List[Dict[str, Any]], connections: List[Dict[str, Any]]
) -> Dict[str, Any]:
"""Calculate correlations between model elements."""
correlations: dict[str, Any] = {
"variable_connection_correlation": 0.0,
"line_position_correlation": 0.0,
}
if variables and connections:
# Calculate correlation between number of variables and connections
var_count = len(variables)
conn_count = len(connections)
correlations["variable_connection_correlation"] = conn_count / max(var_count, 1)
# Calculate line position correlation
var_lines = [var.get("line", 0) for var in variables]
conn_lines = [conn.get("line", 0) for conn in connections]
if len(var_lines) > 1 and len(conn_lines) > 1:
try:
with np.errstate(divide="ignore", invalid="ignore"):
correlation_matrix = np.corrcoef(var_lines, conn_lines)
val = correlation_matrix[0, 1]
correlations["line_position_correlation"] = (
0.0 if np.isnan(val) else float(val)
)
except Exception as e:
logger.debug(f"Correlation computation failed, defaulting to 0.0: {e}")
correlations["line_position_correlation"] = 0.0
return correlations
def calculate_cyclomatic_complexity(
variables: List[Dict[str, Any]], connections: List[Dict[str, Any]]
) -> float:
"""Calculate cyclomatic complexity of the model."""
return len(connections) - len(variables) + 2
def calculate_cognitive_complexity(
variables: List[Dict[str, Any]], connections: List[Dict[str, Any]]
) -> float:
"""Calculate cognitive complexity of the model."""
# Cognitive complexity considers nesting, branching, and logical operators
complexity = 0.0
# Base complexity from number of elements
complexity += len(variables) * 0.5
complexity += len(connections) * 1.0
# Additional complexity for high connectivity
if variables and connections:
density = len(connections) / len(variables)
if density > 2.0:
complexity += density * 0.5
return complexity
def calculate_structural_complexity(
variables: List[Dict[str, Any]], connections: List[Dict[str, Any]]
) -> float:
"""Calculate structural complexity of the model."""
# Structural complexity considers the graph structure
complexity = 0.0
# Base complexity
complexity += len(variables) * 0.3
complexity += len(connections) * 0.7
# Graph density penalty
if variables and connections:
density = len(connections) / len(variables)
if density > 1.5:
complexity += density * 0.2
return complexity
def calculate_complexity_metrics(
file_path: Path, verbose: bool = False
) -> Dict[str, Any]:
"""Calculate comprehensive complexity metrics for a GNN file."""
try:
with open(file_path, "r") as f:
content = f.read()
variables = extract_variables(content)
connections = extract_connections(content)
metrics: dict[str, Any] = {
"file_path": str(file_path),
"file_name": file_path.name,
"cyclomatic_complexity": calculate_cyclomatic_complexity(
variables, connections
),
"cognitive_complexity": calculate_cognitive_complexity(
variables, connections
),
"structural_complexity": calculate_structural_complexity(
variables, connections
),
"maintainability_index": calculate_maintainability_index(
content, variables, connections
),
"technical_debt": calculate_technical_debt(content, variables, connections),
"analysis_timestamp": datetime.now().isoformat(),
}
return metrics
except Exception as e:
raise RuntimeError(
f"Failed to calculate complexity metrics for {file_path}: {e}"
) from e
def calculate_maintainability_index(
content: str, variables: List[Dict[str, Any]], connections: List[Dict[str, Any]]
) -> float:
"""Calculate maintainability index."""
# Simplified maintainability index calculation
lines = len(content.splitlines())
complexity = len(variables) + len(connections)
if lines == 0:
return 100.0
# Higher index = more maintainable
maintainability = 171 - 5.2 * np.log(complexity) - 0.23 * np.log(lines)
return cast("float", max(0.0, min(100.0, maintainability)))
def calculate_technical_debt(
content: str, variables: List[Dict[str, Any]], connections: List[Dict[str, Any]]
) -> float:
"""Calculate technical debt score."""
debt = 0.0
# Complexity debt
if len(variables) > 20:
debt += (len(variables) - 20) * 0.1
if len(connections) > 50:
debt += (len(connections) - 50) * 0.05
# Documentation debt (simplified)
if len(content) < 1000: # Assuming short content means poor documentation
debt += 0.5
return debt
def run_performance_benchmarks(
file_path: Path, verbose: bool = False
) -> Dict[str, Any]:
"""Run performance benchmarks on a GNN file using actual implementation metrics."""
try:
with open(file_path, "r") as f:
content = f.read()
start_time = time.perf_counter()
variables = extract_variables(content)
connections = extract_connections(content)
end_time = time.perf_counter()
real_parse_time = end_time - start_time
# Calculate real memory usage footprint
memory_usage = (
sys.getsizeof(content)
+ sys.getsizeof(variables)
+ sys.getsizeof(connections)
)
for var in variables:
memory_usage += sys.getsizeof(var)
for conn in connections:
memory_usage += sys.getsizeof(conn)
complexity = len(variables) + len(connections)
# Actual performance metrics replacing simulated data
benchmarks: dict[str, Any] = {
"file_path": str(file_path),
"file_name": file_path.name,
"parse_time": real_parse_time,
"memory_usage": memory_usage,
"complexity_score": complexity,
"estimated_runtime": complexity * 0.01,
"benchmark_timestamp": datetime.now().isoformat(),
}
return benchmarks
except Exception as e:
raise RuntimeError(f"Failed to run benchmarks for {file_path}: {e}") from e
def perform_model_comparisons(
statistical_analyses: List[Dict[str, Any]], verbose: bool = False
) -> Dict[str, Any]:
"""Perform comparisons between multiple models."""
if len(statistical_analyses) < 2:
return {"error": "Need at least 2 models for comparison"}
comparisons: dict[str, Any] = {
"model_count": len(statistical_analyses),
"complexity_comparison": {},
"size_comparison": {},
"structure_comparison": {},
"comparison_timestamp": datetime.now().isoformat(),
}
# Compare complexity metrics
complexity_scores: list[Any] = []
file_sizes: list[Any] = []
variable_counts: list[Any] = []
connection_counts: list[Any] = []
for analysis in statistical_analyses:
complexity_metrics = analysis.get("distributions", {}).get(
"complexity_metrics", {}
)
complexity_scores.append(complexity_metrics.get("total_elements", 0))
file_sizes.append(analysis.get("file_size", 0))
variable_counts.append(len(analysis.get("variables", [])))
connection_counts.append(len(analysis.get("connections", [])))
comparisons["complexity_comparison"] = {
"mean": np.mean(complexity_scores),
"std": np.std(complexity_scores),
"min": np.min(complexity_scores),
"max": np.max(complexity_scores),
}
comparisons["size_comparison"] = {
"mean": np.mean(file_sizes),
"std": np.std(file_sizes),
"min": np.min(file_sizes),
"max": np.max(file_sizes),
}
comparisons["structure_comparison"] = {
"variable_counts": {
"mean": np.mean(variable_counts),
"std": np.std(variable_counts),
},
"connection_counts": {
"mean": np.mean(connection_counts),
"std": np.std(connection_counts),
},
}
return comparisons
def generate_analysis_summary(results: Dict[str, Any]) -> str:
"""Generate a summary report of analysis results."""
summary = f"""
# Analysis Summary
**Generated**: {datetime.now().strftime("%Y-%m-%d %H:%M:%S")}
## Processing Results
- **Files Processed**: {results.get("processed_files", 0)}
- **Success**: {results.get("success", False)}
- **Errors**: {len(results.get("errors", []))}
## Analysis Results
- **Statistical Analyses**: {len(results.get("statistical_analysis", []))}
- **Complexity Metrics**: {len(results.get("complexity_metrics", []))}
- **Performance Benchmarks**: {len(results.get("performance_benchmarks", []))}
- **Model Comparisons**: {len(results.get("model_comparisons", []))}
## Error Summary
"""
errors = results.get("errors", [])
if errors:
for error in errors:
if isinstance(error, dict):
summary += f"- **{error.get('file', 'Unknown')}**: {error.get('error', 'Unknown error')}\n"
else:
summary += f"- {error}\n"
else:
summary += "- No errors encountered\n"
summary += "\n## Model Statistics\n"
# Add statistics from analyses
analyses = results.get("statistical_analysis", [])
if analyses:
total_variables = sum(
len(analysis.get("variables", [])) for analysis in analyses
)
total_connections = sum(
len(analysis.get("connections", [])) for analysis in analyses
)
summary += f"- Total variables across all models: {total_variables}\n"
summary += f"- Total connections across all models: {total_connections}\n"
summary += (
f"- Average variables per model: {total_variables / len(analyses):.1f}\n"
)
summary += f"- Average connections per model: {total_connections / len(analyses):.1f}\n"
return summary
def generate_matrix_visualizations(
parsed_data: Dict[str, Any], output_dir: Path, model_name: str
) -> List[str]:
"""Generate heatmaps for model matrices."""
visualizations: list[Any] = []
if not MATPLOTLIB_AVAILABLE:
return visualizations
matrices = parsed_data.get("matrices", [])
# Extract matrices from parsed data (A, B, C, D maps)
for i, matrix_info in enumerate(matrices):
matrix_data = matrix_info.get("data")
if matrix_data is not None and isinstance(matrix_data, np.ndarray):
matrix_name = matrix_info.get("name", f"matrix_{i}")
plt.figure(figsize=(10, 8))
if SEABORN_AVAILABLE and sns is not None:
sns.heatmap(matrix_data, annot=matrix_data.size < 100, cmap="viridis")
else:
# Recovery to matplotlib imshow
plt.imshow(matrix_data, cmap="viridis", aspect="auto")
plt.colorbar()
# Add annotations if small enough
if matrix_data.size < 100:
for r in range(matrix_data.shape[0]):
for c in range(matrix_data.shape[1]):
plt.text(
c,
r,
f"{matrix_data[r, c]:.2g}",
ha="center",
va="center",
color="w",
)
plt.title(f"{model_name} - {matrix_name}")
plot_file = output_dir / f"{model_name}_{matrix_name}_heatmap.png"
plt.savefig(plot_file, bbox_inches="tight")
plt.close()
visualizations.append(str(plot_file))
return visualizations
def visualize_simulation_results(
execution_results: Dict[str, Any], output_dir: Path
) -> List[str]:
"""Visualize actual simulation data from execution results."""
visualizations: list[Any] = []
if not MATPLOTLIB_AVAILABLE:
return visualizations
# Example: Visualize belief evolution if traces are present
details = execution_results.get("execution_details", [])
for detail in details:
model_name = detail.get("model_name", "unknown")
framework = detail.get("framework", "unknown")
impl_dir = Path(detail.get("implementation_directory", ""))
# Look for simulation data (e.g., traces.json or simulation_dump.json)
trace_files = list(impl_dir.glob("**/traces.json")) + list(
impl_dir.glob("**/simulation_data/*.json")
)
for trace_file in trace_files:
try:
with open(trace_file, "r") as f:
data = json.load(f)
# Local Helper for attaching robust context
def apply_chart_metadata(
framework: str = framework, data: dict = data
) -> None:
try:
meta_parts: list[Any] = [
f"Generated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}",
f"FW: {framework}",
]
if "num_timesteps" in data:
meta_parts.append(f"T={data.get('num_timesteps')}")
elif "time_steps" in data:
meta_parts.append(f"T={data.get('time_steps')}")
if "model_parameters" in data and data["model_parameters"].get(
"num_states"
):
meta_parts.append(
f"|S|={data['model_parameters']['num_states']}"
)
plt.figtext(
0.99,
0.01,
" | ".join(meta_parts),
ha="right",
va="bottom",
fontsize=8,
color="gray",
alpha=0.6,
)
except Exception as e:
logger.debug(f"Metadata application failed: {e}")
# Plot traces (e.g., belief over time)
if "beliefs" in data or "states" in data:
plt.figure(figsize=(10, 6))
# Simplified plotting logic for arbitrary trace data
beliefs = np.array(data.get("beliefs", data.get("states", [])))
if beliefs.ndim == 2:
for i in range(min(10, beliefs.shape[1])):
plt.plot(beliefs[:, i], label=f"State {i}")
plt.title(f"Belief Evolution - {model_name} ({framework})")
plt.legend()
fw_viz_dir = output_dir / framework
fw_viz_dir.mkdir(parents=True, exist_ok=True)
plot_file = (
fw_viz_dir / f"{model_name}_{framework}_belief_trace.png"
)
apply_chart_metadata()
plt.savefig(plot_file)
plt.close()
visualizations.append(str(plot_file))
# Plot JSD / distance tracking (Belief Convergence)
distances: list[Any] = []
try:
from scipy.spatial.distance import jensenshannon
for t in range(1, len(beliefs)):
p = np.array(beliefs[t - 1]).flatten()
q = np.array(beliefs[t]).flatten()
p = np.clip(p, 1e-12, None)
q = np.clip(q, 1e-12, None)
p = p / np.sum(p)
q = q / np.sum(q)
if np.allclose(p, q, atol=1e-8):
val = 0.0
else:
# Suppress scipy runtime warnings for edge-case slight negatives
import warnings
with warnings.catch_warnings():
warnings.simplefilter("ignore", RuntimeWarning)
val = jensenshannon(p, q)
if np.isnan(val) or val < 0:
val = 0.0
distances.append(val)
ylabel = "Jensen-Shannon Divergence"
except ImportError:
for t in range(1, len(beliefs)):
p = np.array(beliefs[t - 1]).flatten()
q = np.array(beliefs[t]).flatten()
distances.append(np.linalg.norm(q - p))
ylabel = "Euclidean Distance"
if distances:
plt.figure(figsize=(10, 6))
plt.plot(
range(1, len(beliefs)),
distances,
label="Belief Update Magnitude",
color="teal",
)
plt.title(
f"Belief Convergence Tracker - {model_name} ({framework})"
)
plt.xlabel("Timestep")
plt.ylabel(ylabel)
plt.legend()
fw_viz_dir = output_dir / framework
fw_viz_dir.mkdir(parents=True, exist_ok=True)
plot_file = (
fw_viz_dir
/ f"{model_name}_{framework}_belief_convergence.png"
)
apply_chart_metadata()
plt.savefig(plot_file)
plt.close()
visualizations.append(str(plot_file))
# Plot Free Energy trajectories
if "free_energy" in data or "efe" in data or "F" in data:
plt.figure(figsize=(10, 6))
fe = data.get("free_energy", data.get("efe", data.get("F", [])))
if isinstance(fe, list) and len(fe) > 0:
plt.plot(
fe,
label="Free Energy",
color="purple",
marker="o",
markersize=4,
)
plt.title(
f"Free Energy Trajectory - {model_name} ({framework})"
)
plt.xlabel("Timestep")
plt.ylabel("Free Energy / Expected Free Energy")
plt.legend()
plot_file = (
output_dir / f"{model_name}_{framework}_free_energy.png"
)
apply_chart_metadata()
plt.savefig(plot_file)
plt.close()
visualizations.append(str(plot_file))
# Plot Precision Dynamics
if "precision" in data or "gamma" in data or "w" in data:
plt.figure(figsize=(10, 6))
prec = data.get("precision", data.get("gamma", data.get("w", [])))
if isinstance(prec, list) and len(prec) > 0:
plt.plot(
prec,
label="Precision Dynamics",
color="orange",
linestyle="--",
marker="x",
)
plt.title(f"Precision Dynamics - {model_name} ({framework})")
plt.xlabel("Timestep")
plt.ylabel("Precision (Gamma/w)")
plt.legend()
plot_file = (
output_dir / f"{model_name}_{framework}_precision.png"
)
apply_chart_metadata()
plt.savefig(plot_file)
plt.close()
visualizations.append(str(plot_file))
# Plot Action History Frequency Maps
if "actions" in data or "u" in data:
plt.figure(figsize=(8, 6))
actions = data.get("actions", data.get("u", []))
if isinstance(actions, list) and len(actions) > 0:
# flatten if nested
if isinstance(actions[0], list):
flat_actions = [a[0] if len(a) > 0 else 0 for a in actions]
else:
flat_actions = actions
unique_actions, counts = np.unique(
flat_actions, return_counts=True
)
plt.bar(
range(len(unique_actions)),
counts,
tick_label=[str(a) for a in unique_actions],
color="coral",
alpha=0.8,
)
plt.title(
f"Action Selection Frequencies - {model_name} ({framework})"
)
plt.xlabel("Action Variant")
plt.ylabel("Frequency")
fw_viz_dir = output_dir / framework
fw_viz_dir.mkdir(parents=True, exist_ok=True)
plot_file = (
fw_viz_dir
/ f"{model_name}_{framework}_action_frequencies.png"
)
apply_chart_metadata()
plt.savefig(plot_file)
plt.close()
visualizations.append(str(plot_file))
except Exception as e:
logging.getLogger(__name__).debug(
f"Failed to visualize trace file {trace_file}: {e}"
)
continue
return visualizations
def parse_matrix_data(matrix_str: str) -> Optional[np.ndarray]:
"""Parse matrix data from string representation."""
try:
# Simplified parsing logic for moving to analyzer
import re
numbers = re.findall(r"[-+]?\d*\.\d+|\d+", matrix_str)
if len(numbers) >= 1:
return np.array([float(n) for n in numbers])
return None
except Exception as e:
logger.debug(f"Failed to extract numeric array from value: {e}")
return None
def analyze_framework_outputs(
execution_output_dir: Path,
logger: Optional[logging.Logger] = None,
allowed_frameworks: Optional[set[str]] = None,
) -> Dict[str, Any]:
"""
Analyze and compare outputs from the current execution framework scope.
Args:
execution_output_dir: Directory containing execution results (e.g., output/12_execute_output)
logger: Optional logger instance
allowed_frameworks: Optional normalized framework names to include
Returns:
Dictionary with framework comparison results
"""
import json
import logging
if logger is None:
logger = logging.getLogger(__name__)
results: dict[str, Any] = {
"timestamp": datetime.now().isoformat(),
"frameworks": {},
"comparisons": {},
"metrics": {},
}
# Read execution summary - check summaries/ subfolder first, recovery to root
execution_summary_file = (
execution_output_dir / "summaries" / "execution_summary.json"
)
if not execution_summary_file.exists():
execution_summary_file = execution_output_dir / "execution_summary.json"
if not execution_summary_file.exists():
logger.warning(f"Execution summary not found at {execution_summary_file}")
return results
try:
with open(execution_summary_file, "r") as f:
execution_summary = json.load(f)
execution_details = execution_summary.get("execution_details", [])
# Group by framework
framework_data: dict[Any, Any] = {}
for detail in execution_details:
framework = str(detail.get("framework", "unknown"))
framework = framework.lower().replace(".", "_").replace(" ", "_")
if allowed_frameworks and framework not in allowed_frameworks:
continue
if framework not in framework_data:
framework_data[framework] = []
framework_data[framework].append(detail)
# Extract metrics from each framework
for framework, details in framework_data.items():
framework_results: dict[str, Any] = {
"success_count": sum(1 for d in details if d.get("success", False)),
"total_count": len(details),
"execution_times": [d.get("execution_time", 0) for d in details],
"output_files": [d.get("output_file", "") for d in details],
"implementation_dirs": [