-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathvisualizer.py
More file actions
1577 lines (1309 loc) · 55.9 KB
/
visualizer.py
File metadata and controls
1577 lines (1309 loc) · 55.9 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
from __future__ import annotations
"""
Matrix Visualization Module for GNN Processing Pipeline
This module provides matrix visualization capabilities for GNN models,
including heatmaps, statistics, and analysis of model parameters.
Specialized support for 3D tensors like POMDP transition matrices.
"""
import csv
import logging
from ..compat.viz_compat import MATPLOTLIB_AVAILABLE, np, plt, sns
from ..plotting.utils import safe_tight_layout
from .extract import (
convert_to_matrix,
)
from .extract import (
extract_matrix_data_from_parameters as extract_matrices_from_parameter_list,
)
logger = logging.getLogger(__name__)
try:
from matplotlib import cm
except ImportError:
cm = None
NUMPY_AVAILABLE = np is not None
SEABORN_AVAILABLE = sns is not None
import ast
from pathlib import Path
from typing import Any, Dict, List, Optional, Union
# Maximum figure dimension (inches) to prevent RendererAgg pixel overflow.
# At 300 DPI, 200 inches = 60,000 pixels — well within safe 32-bit limits.
_MAX_FIGURE_DIMENSION = 200
def _safe_figsize(width: float, height: float) -> tuple:
"""Clamp figure dimensions to prevent matplotlib RendererAgg overflow.
Large models can produce data-dependent figsize values that exceed
the renderer's pixel buffer capacity (e.g. 5 * 10,000 actions).
This helper caps both dimensions to _MAX_FIGURE_DIMENSION inches.
Args:
width: Desired figure width in inches.
height: Desired figure height in inches.
Returns:
Tuple of (clamped_width, clamped_height).
"""
clamped_w = min(max(width, 1), _MAX_FIGURE_DIMENSION)
clamped_h = min(max(height, 1), _MAX_FIGURE_DIMENSION)
if clamped_w != width or clamped_h != height:
logger.debug(
"Figure size clamped from (%.1f, %.1f) to (%.1f, %.1f) to prevent renderer overflow",
width,
height,
clamped_w,
clamped_h,
)
return (clamped_w, clamped_h)
class MatrixVisualizer:
"""
Handles matrix visualization for GNN models.
This class provides methods to extract matrix data from GNN parameters
and generate various visualizations including heatmaps, statistics,
and combined overviews. Specialized support for 3D tensors like
POMDP transition matrices (B matrix).
"""
# Maximum matrix cell count for which text annotations are shown
_ANNOTATION_CELL_LIMIT = 25
def export_matrix_to_csv(
self, matrix: np.ndarray, matrix_name: str, output_path: Path
) -> bool:
"""
Export matrix data to CSV format for accessibility.
Args:
matrix: Numpy array to export
matrix_name: Name of the matrix
output_path: Output path for CSV file
Returns:
True if successful
"""
try:
csv_path = output_path.with_suffix(".csv")
with open(csv_path, "w", newline="") as csvfile:
writer = csv.writer(csvfile)
# Write header with matrix info
writer.writerow([f"Matrix: {matrix_name}"])
writer.writerow([f"Shape: {matrix.shape}"])
writer.writerow([f"Data type: {matrix.dtype}"])
writer.writerow([]) # Empty row
# Write matrix data
if matrix.ndim == 1:
# Vector - write as single row
writer.writerow([f"Vector element {i}" for i in range(len(matrix))])
writer.writerow(matrix.tolist())
elif matrix.ndim == 2:
# Matrix - write with row/column headers
writer.writerow([f"Col {j}" for j in range(matrix.shape[1])])
for i, row in enumerate(matrix):
writer.writerow([f"Row {i}"] + row.tolist())
elif matrix.ndim == 3:
# POMDP B tensors use (next_state, previous_state, action).
for action in range(matrix.shape[2]):
writer.writerow([f"Action slice {action}"])
writer.writerow(
["Next \\ Previous"]
+ [f"Previous {j}" for j in range(matrix.shape[1])]
)
for next_state in range(matrix.shape[0]):
writer.writerow(
[f"Next {next_state}"]
+ matrix[next_state, :, action].tolist()
)
writer.writerow([])
return True
except Exception as e:
logger.error(f"Failed to export matrix to CSV: {e}")
return False
def extract_matrix_data_from_parameters(
self, parameters: Union[List[Dict], Dict]
) -> Dict[str, np.ndarray]:
"""Extract matrix data from parameters section."""
return extract_matrices_from_parameter_list(parameters)
def _convert_to_matrix(self, value: Any, name: str = "") -> Optional[np.ndarray]:
return convert_to_matrix(value, name)
def extract_from_parsed_gnn(
self, parsed_data: Dict[str, Any]
) -> Dict[str, np.ndarray]:
"""
Extract matrix data from parsed GNN structure.
Checks multiple locations:
- parameters field (primary location)
- InitialParameterization section
- matrices field
- variables with matrix values
Args:
parsed_data: Parsed GNN data dictionary
Returns:
Dictionary mapping matrix names to numpy arrays
"""
matrices = {}
# Primary: Extract from parameters field
parameters = parsed_data.get("parameters", [])
if parameters:
param_matrices = self.extract_matrix_data_from_parameters(parameters)
matrices.update(param_matrices)
# Secondary: Check InitialParameterization section
initial_params = parsed_data.get("InitialParameterization", {})
if isinstance(initial_params, dict):
for param_name, param_value in initial_params.items():
matrix = self._convert_to_matrix(param_value, param_name)
if matrix is not None:
matrices[param_name] = matrix
# Tertiary: Check matrices field
matrices_list = parsed_data.get("matrices", [])
if matrices_list:
for m_info in matrices_list:
if isinstance(m_info, dict):
m_name = m_info.get("name", f"matrix_{len(matrices)}")
m_data = m_info.get("data")
if m_data is not None:
matrix = self._convert_to_matrix(m_data, m_name)
if matrix is not None:
matrices[m_name] = matrix
return matrices
def generate_matrix_heatmap(
self,
matrix_name: str,
matrix: np.ndarray,
output_path: Path,
title: Optional[str] = None,
cmap: str = "viridis",
) -> bool:
"""
Generate a heatmap visualization for a matrix.
Args:
matrix_name: Name of the matrix
matrix: Numpy array representing the matrix
output_path: Output file path
title: Optional title for the plot
cmap: Colormap to use
Returns:
True if successful, False otherwise
"""
try:
# Reshape 1D vector to 2D for imshow if necessary
if matrix.ndim == 1:
matrix = matrix.reshape(1, -1)
plt.figure(figsize=(10, 8))
# Create heatmap
im = plt.imshow(matrix, cmap=cmap, aspect="auto")
# Add colorbar
cbar = plt.colorbar(im)
cbar.set_label("Value", rotation=270, labelpad=15)
# Add title
if title is None:
title = f"Matrix {matrix_name}"
plt.title(title, fontsize=16, fontweight="bold")
# Add axis labels
plt.xlabel("Column Index")
plt.ylabel("Row Index")
# Add text annotations for matrix values (skip for large matrices)
total_cells = matrix.shape[0] * matrix.shape[1]
if total_cells <= self._ANNOTATION_CELL_LIMIT:
for i in range(matrix.shape[0]):
for j in range(matrix.shape[1]):
value = float(matrix[i, j])
plt.text(
j,
i,
f"{value:.3f}",
ha="center",
va="center",
color="white" if value < 0.5 else "black",
fontsize=8,
fontweight="bold",
)
# Set axis ticks
plt.xticks(range(matrix.shape[1]))
plt.yticks(range(matrix.shape[0]))
safe_tight_layout()
# Ensure parent directory exists
try:
output_path.parent.mkdir(parents=True, exist_ok=True)
except OSError as e:
logger.debug("mkdir for %s: %s", output_path.parent, e)
plt.savefig(output_path, dpi=300, bbox_inches="tight")
plt.close()
# Export matrix data to CSV for accessibility
self.export_matrix_to_csv(matrix, matrix_name, output_path)
return True
except Exception as e:
logger.error(f"Error generating matrix heatmap for {matrix_name}: {e}")
plt.close()
return False
def create_heatmap(self, matrix: List[List[float]] | np.ndarray) -> bool:
try:
arr = np.array(matrix, dtype=float)
# Save to project output/test_artifacts to avoid polluting repo root
base_dir = Path.cwd() / "output" / "2_tests_output"
base_dir.mkdir(parents=True, exist_ok=True)
tmp_path = base_dir / "matrix_heatmap.png"
return self.generate_matrix_heatmap("matrix", arr, tmp_path)
except Exception:
return False
def generate_3d_tensor_visualization(
self,
tensor_name: str,
tensor: np.ndarray,
output_path: Path,
title: Optional[str] = None,
tensor_type: str = "transition",
) -> bool:
"""
Generate specialized visualization for 3D tensors like POMDP transition matrices.
Args:
tensor_name: Name of the tensor (e.g., 'B')
tensor: 3D numpy array
output_path: Output file path
title: Optional title for the plot
tensor_type: Type of tensor ('transition', 'likelihood', etc.)
Returns:
True if successful, False otherwise
"""
try:
if tensor.ndim != 3:
logger.warning(
f"Tensor {tensor_name} is not 3D (shape: {tensor.shape})"
)
return False
# Get dimensions
dim1, dim2, dim3 = tensor.shape
# Create figure with subplots for each slice (clamped to prevent overflow)
fig = plt.figure(figsize=_safe_figsize(5 * dim3, 8))
# Create subplot grid
gs = fig.add_gridspec(2, dim3, height_ratios=[3, 1], hspace=0.3, wspace=0.3)
# Generate titles based on tensor type
if tensor_type == "transition":
slice_titles = [f"Action {i}" for i in range(dim3)]
xlabel = "Previous State"
ylabel = "Next State"
main_title = f"POMDP Transition Matrix {tensor_name} (P(s'|s,u))"
else:
slice_titles = [f"Slice {i}" for i in range(dim3)]
xlabel = "Column"
ylabel = "Row"
main_title = f"3D Tensor {tensor_name}"
# Plot each slice as a heatmap
for i in range(dim3):
ax = fig.add_subplot(gs[0, i])
# Extract slice
slice_data = tensor[:, :, i]
# Create heatmap
im = ax.imshow(slice_data, cmap="Blues", aspect="auto", vmin=0, vmax=1)
# Add text annotations for small matrices
if (
slice_data.size <= self._ANNOTATION_CELL_LIMIT
): # Only add text for reasonably sized matrices
for row in range(slice_data.shape[0]):
for col in range(slice_data.shape[1]):
value = float(slice_data[row, col])
ax.text(
col,
row,
f"{value:.2f}",
ha="center",
va="center",
color="white" if value < 0.5 else "black",
fontsize=10,
fontweight="bold",
)
# Set labels
ax.set_title(slice_titles[i], fontweight="bold", fontsize=12)
ax.set_xlabel(xlabel)
ax.set_ylabel(ylabel)
# Set ticks
ax.set_xticks(range(slice_data.shape[1]))
ax.set_yticks(range(slice_data.shape[0]))
# Add colorbar for first slice only
if i == 0:
cbar = plt.colorbar(im, ax=ax, shrink=0.8)
cbar.set_label("Transition Probability", rotation=270, labelpad=15)
# Add summary statistics below
ax_summary = fig.add_subplot(gs[1, :])
ax_summary.axis("off")
# Calculate and display statistics
stats_text = self._generate_tensor_statistics(
tensor, tensor_name, tensor_type
)
ax_summary.text(
0.05,
0.5,
stats_text,
transform=ax_summary.transAxes,
fontsize=10,
verticalalignment="center",
bbox={
"boxstyle": "round,pad=0.3",
"facecolor": "lightgray",
"alpha": 0.8,
},
)
# Set main title
fig.suptitle(main_title, fontsize=16, fontweight="bold", y=0.95)
safe_tight_layout()
plt.savefig(output_path, dpi=300, bbox_inches="tight")
plt.close()
return True
except Exception as e:
logger.error(
f"Error generating 3D tensor visualization for {tensor_name}: {e}"
)
plt.close()
return False
def _generate_tensor_statistics(
self, tensor: np.ndarray, tensor_name: str, tensor_type: str
) -> str:
"""
Generate statistical summary for a 3D tensor.
Args:
tensor: 3D numpy array
tensor_name: Name of the tensor
tensor_type: Type of tensor
Returns:
Formatted statistics string
"""
dim1, dim2, dim3 = tensor.shape
# Basic statistics
mean_val = np.mean(tensor)
std_val = np.std(tensor)
min_val = np.min(tensor)
max_val = np.max(tensor)
# Transition-specific statistics
if tensor_type == "transition":
# POMDP transition tensors use (next_state, previous_state, action).
# Each previous-state/action column must sum over next_state.
column_sums = np.sum(tensor, axis=0)
valid_transitions = np.allclose(column_sums, 1.0, atol=1e-6)
# Calculate entropy of transitions
# Add small epsilon to avoid log(0)
epsilon = 1e-10
log_probs = np.log(tensor + epsilon)
entropy = -np.sum(tensor * log_probs, axis=0)
mean_entropy = np.mean(entropy)
stats = f"""Tensor {tensor_name} Statistics:
Shape: {dim1}×{dim2}×{dim3} (Next×Previous×Actions)
Mean: {mean_val:.3f}, Std: {std_val:.3f}
Range: [{min_val:.3f}, {max_val:.3f}]
Valid Transition Matrices: {"✓" if valid_transitions else "✗"}
Mean Transition Entropy: {mean_entropy:.3f} bits"""
else:
stats = f"""Tensor {tensor_name} Statistics:
Shape: {dim1}×{dim2}×{dim3}
Mean: {mean_val:.3f}, Std: {std_val:.3f}
Range: [{min_val:.3f}, {max_val:.3f}]"""
return stats
def generate_pomdp_transition_analysis(
self, tensor: np.ndarray, output_path: Path
) -> bool:
"""
Generate specialized analysis for POMDP transition matrices.
Args:
tensor: 3D numpy array representing transition matrix
output_path: Output file path
Returns:
True if successful, False otherwise
"""
try:
if tensor.ndim != 3:
logger.warning(f"Expected 3D tensor, got shape: {tensor.shape}")
return False
dim1, dim2, dim3 = tensor.shape
# Create comprehensive analysis figure with safe dimensions
try:
# Ensure sane figure dimensions and clear any stale figures
plt.close("all")
# Use very conservative figure size to avoid dimension overflow
# Keep it small to prevent pixel calculation overflow
safe_figsize = (12, 9) # Safe, tested dimensions
fig = plt.figure(figsize=safe_figsize, clear=True)
# Set DPI early and ensure it's safe
safe_dpi = 96 # Use a very safe, low DPI to prevent overflow
fig.set_dpi(safe_dpi)
except Exception:
return False
# Use a simpler approach without gridspec
# 1. Main transition matrices (top row)
for i in range(dim3):
ax = fig.add_subplot(3, 3, i + 1)
slice_data = tensor[:, :, i]
im = ax.imshow(slice_data, cmap="Blues", aspect="auto", vmin=0, vmax=1)
# Add text annotations
for row in range(slice_data.shape[0]):
for col in range(slice_data.shape[1]):
value = float(slice_data[row, col])
ax.text(
col,
row,
f"{value:.2f}",
ha="center",
va="center",
color="white" if value < 0.5 else "black",
fontsize=10,
fontweight="bold",
)
ax.set_title(f"Action {i} Transition Matrix", fontweight="bold")
ax.set_xlabel("Previous State")
ax.set_ylabel("Next State")
ax.set_xticks(range(dim2))
ax.set_yticks(range(dim1))
if i == 0:
cbar = plt.colorbar(im, ax=ax, shrink=0.8)
cbar.set_label("P(s'|s,u)", rotation=270, labelpad=15)
# 2. Transition entropy analysis (middle row)
ax_entropy = fig.add_subplot(3, 3, 4)
# Calculate entropy for each action
epsilon = 1e-10
log_probs = np.log(tensor + epsilon)
entropy = -np.sum(
tensor * log_probs, axis=0
) # Entropy per previous-state/action pair
mean_entropy_per_action = np.mean(
entropy, axis=0
) # Average entropy per action
actions = range(dim3)
entropy_colors = (
["skyblue", "lightcoral", "lightgreen"] * ((dim3 // 3) + 1)
)[:dim3]
bars = ax_entropy.bar(
actions, mean_entropy_per_action, color=entropy_colors, alpha=0.7
)
# Add value labels on bars
for bar, value in zip(bars, mean_entropy_per_action):
ax_entropy.text(
bar.get_x() + bar.get_width() / 2,
bar.get_height() + 0.01,
f"{value:.3f}",
ha="center",
va="bottom",
fontweight="bold",
)
ax_entropy.set_title("Transition Entropy by Action", fontweight="bold")
ax_entropy.set_xlabel("Action")
ax_entropy.set_ylabel("Mean Entropy (bits)")
ax_entropy.set_xticks(actions)
ax_entropy.grid(True, alpha=0.3)
# 3. Determinism analysis (bottom left)
ax_determinism = fig.add_subplot(3, 3, 7)
# Calculate determinism (max next-state probability per previous-state/action).
max_probs = np.max(tensor, axis=0)
mean_determinism_per_action = np.mean(
max_probs, axis=0
) # Average determinism per action
determinism_colors = (["gold", "orange", "red"] * ((dim3 // 3) + 1))[:dim3]
bars = ax_determinism.bar(
actions,
mean_determinism_per_action,
color=determinism_colors,
alpha=0.7,
)
for bar, value in zip(bars, mean_determinism_per_action):
ax_determinism.text(
bar.get_x() + bar.get_width() / 2,
bar.get_height() + 0.01,
f"{value:.3f}",
ha="center",
va="bottom",
fontweight="bold",
)
ax_determinism.set_title(
"Transition Determinism by Action", fontweight="bold"
)
ax_determinism.set_xlabel("Action")
ax_determinism.set_ylabel("Mean Max Probability")
ax_determinism.set_xticks(actions)
ax_determinism.grid(True, alpha=0.3)
# 4. State reachability (bottom middle)
ax_reachability = fig.add_subplot(3, 3, 8)
# Calculate reachability (how many states can be reached from each state)
reachability = np.sum(tensor > 0.01, axis=0) # Count reachable next states
mean_reachability_per_action = np.mean(reachability, axis=0)
reachability_colors = (
["lightblue", "lightgreen", "lightyellow"] * ((dim3 // 3) + 1)
)[:dim3]
bars = ax_reachability.bar(
actions,
mean_reachability_per_action,
color=reachability_colors,
alpha=0.7,
)
for bar, value in zip(bars, mean_reachability_per_action):
ax_reachability.text(
bar.get_x() + bar.get_width() / 2,
bar.get_height() + 0.01,
f"{value:.1f}",
ha="center",
va="bottom",
fontweight="bold",
)
ax_reachability.set_title("State Reachability by Action", fontweight="bold")
ax_reachability.set_xlabel("Action")
ax_reachability.set_ylabel("Mean Reachable States")
ax_reachability.set_xticks(actions)
ax_reachability.grid(True, alpha=0.3)
# 5. Matrix validation (bottom right)
ax_validation = fig.add_subplot(3, 3, 9)
ax_validation.axis("off")
# Validation checks
column_sums = np.sum(tensor, axis=0)
valid_transitions = np.allclose(column_sums, 1.0, atol=1e-6)
max_deviation = np.max(np.abs(column_sums - 1.0))
validation_text = f"""POMDP Transition Matrix Validation:
✓ Shape: {dim1}×{dim2}×{dim3}
✓ Valid Transition Matrices: {"Yes" if valid_transitions else "No"}
✓ Max Column Sum Deviation: {max_deviation:.6f}
✓ Probability Range: [{np.min(tensor):.3f}, {np.max(tensor):.3f}]
✓ Mean Entropy: {np.mean(entropy):.3f} bits
✓ Mean Determinism: {np.mean(max_probs):.3f}"""
ax_validation.text(
0.05,
0.5,
validation_text,
transform=ax_validation.transAxes,
fontsize=10,
verticalalignment="center",
bbox={
"boxstyle": "round,pad=0.3",
"facecolor": "lightgreen",
"alpha": 0.8,
},
)
# Set main title
fig.suptitle(
"POMDP Transition Matrix Analysis",
fontsize=16,
fontweight="bold",
y=0.95,
)
# Adjust layout manually instead of using tight_layout
fig.subplots_adjust(
top=0.92, bottom=0.08, left=0.08, right=0.95, hspace=0.4, wspace=0.3
)
for size, kwargs in [
(None, {"dpi": 96, "bbox_inches": "tight"}),
((8, 6), {"dpi": 72}),
((6, 4), {}),
]:
try:
if size:
fig.set_size_inches(*size)
plt.savefig(output_path, **kwargs)
break
except (RuntimeError, OSError, ValueError):
continue
else:
return False
plt.close()
return True
except Exception as e:
logger.error(f"Error generating POMDP transition analysis: {e}")
plt.close()
return False
def generate_matrix_analysis(
self,
parameters: List[Dict] | List[List[float]],
output_path: Path | None = None,
) -> bool:
"""
Generate comprehensive matrix analysis from parameters.
Args:
parameters: List of parameter dictionaries from GNN
output_path: Path where to save the analysis image
Returns:
bool: True if analysis was generated successfully
"""
# Convenience: if called with raw matrix-like and no output_path
if (
isinstance(parameters, list)
and parameters
and isinstance(parameters[0], list)
and output_path is None
):
# Default to project output/test_artifacts directory
base_dir = Path.cwd() / "output" / "2_tests_output"
base_dir.mkdir(parents=True, exist_ok=True)
output_path = base_dir / "matrix_analysis.png"
try:
arr = np.array(parameters, dtype=float)
return self.generate_matrix_heatmap("matrix", arr, output_path)
except Exception:
return False
if not MATPLOTLIB_AVAILABLE or not NUMPY_AVAILABLE:
# Create a simple text report instead
try:
with open(output_path.with_suffix(".txt"), "w") as f:
f.write("Matrix Analysis Report\n")
f.write("=====================\n\n")
f.write("Dependencies Status:\n")
f.write(f"- Matplotlib: {MATPLOTLIB_AVAILABLE}\n")
f.write(f"- NumPy: {NUMPY_AVAILABLE}\n")
f.write(f"- Seaborn: {SEABORN_AVAILABLE}\n\n")
f.write(f"Parameters found: {len(parameters)}\n")
for i, param in enumerate(parameters[:10]): # Show first 10
f.write(
f" {i + 1}. {param.get('name', 'unnamed')}: {param.get('type', 'unknown')}\n"
)
if len(parameters) > 10:
f.write(f" ... and {len(parameters) - 10} more\n")
return True
except Exception:
return False
try:
# Extract matrix data from parameters
matrices = (
self.extract_matrix_data_from_parameters(parameters)
if isinstance(parameters, list)
and parameters
and isinstance(parameters[0], dict)
else {}
)
if not matrices:
return False
# Create figure with subplots
n_matrices = len(matrices)
if n_matrices == 0:
return False
# Calculate grid dimensions
cols = min(3, n_matrices)
rows = (n_matrices + cols - 1) // cols
fig, axes = plt.subplots(rows, cols, figsize=_safe_figsize(15, 5 * rows))
if n_matrices == 1:
axes = [axes]
elif rows == 1:
axes = [axes] if not hasattr(axes, "__len__") else axes
else:
axes = axes.flatten()
# Generate visualizations for each matrix
for i, (name, matrix) in enumerate(matrices.items()):
if i >= len(axes):
break
ax = axes[i]
# Handle different matrix shapes
if matrix.ndim == 1:
# Vector - plot as bar chart
ax.bar(range(len(matrix)), matrix)
ax.set_title(f"{name} (Vector)")
elif matrix.ndim == 2:
# Matrix - plot as heatmap
if SEABORN_AVAILABLE:
sns.heatmap(
matrix,
ax=ax,
cmap="viridis",
annot=True if matrix.size <= 100 else False,
)
else:
im = ax.imshow(matrix, cmap="viridis", aspect="auto")
plt.colorbar(im, ax=ax)
ax.set_title(f"{name} (Matrix {matrix.shape})")
elif matrix.ndim == 3:
# 3D tensor - show first slice
if SEABORN_AVAILABLE:
sns.heatmap(
matrix[0],
ax=ax,
cmap="viridis",
annot=True if matrix[0].size <= 100 else False,
)
else:
im = ax.imshow(matrix[0], cmap="viridis", aspect="auto")
plt.colorbar(im, ax=ax)
ax.set_title(f"{name} (3D Tensor {matrix.shape}, slice 0)")
# Add statistics text
stats_text = f"Mean: {np.mean(matrix):.3f}\nStd: {np.std(matrix):.3f}"
ax.text(
0.02,
0.98,
stats_text,
transform=ax.transAxes,
verticalalignment="top",
bbox={"boxstyle": "round", "facecolor": "white", "alpha": 0.8},
)
# Hide unused subplots
for i in range(n_matrices, len(axes)):
axes[i].set_visible(False)
safe_tight_layout()
try:
output_path.parent.mkdir(parents=True, exist_ok=True)
except OSError as e:
logger.debug("mkdir for %s: %s", output_path.parent, e)
plt.savefig(output_path, dpi=300, bbox_inches="tight")
plt.close()
# Export CSV data for each matrix
csv_exports = []
for name, matrix in matrices.items():
csv_success = self.export_matrix_to_csv(matrix, name, output_path)
if csv_success:
csv_exports.append(output_path.with_suffix(".csv"))
return True
except Exception as e:
# Recovery: create error report
try:
with open(output_path.with_suffix(".txt"), "w") as f:
f.write("Matrix Analysis Failed\n")
f.write(f"Error: {str(e)}\n")
f.write(f"Parameters: {len(parameters)} found\n")
return True
except Exception:
return False
def generate_combined_matrix_overview(
self, matrices: Dict[str, np.ndarray], output_path: Path
) -> bool:
"""
Generate a combined overview of all matrices.
Args:
matrices: Dictionary of matrix name to numpy array mappings
output_path: Output file path
Returns:
True if successful, False otherwise
"""
try:
n_matrices = len(matrices)
if n_matrices == 0:
return True
# Separate 2D and 3D matrices
matrices_2d = {
name: matrix for name, matrix in matrices.items() if matrix.ndim == 2
}
matrices_3d = {
name: matrix for name, matrix in matrices.items() if matrix.ndim == 3
}
# Calculate layout
total_plots = len(matrices_2d) + len(matrices_3d)
if total_plots == 0:
return True
cols = min(3, total_plots)
rows = (total_plots + cols - 1) // cols
fig, axes = plt.subplots(
rows, cols, figsize=_safe_figsize(5 * cols, 4 * rows)
)
if total_plots == 1:
axes = [axes]
elif rows == 1:
axes = axes.reshape(1, -1)
# Flatten axes for easier indexing
axes_flat = axes.flatten() if hasattr(axes, "flatten") else [axes]
plot_idx = 0
# Plot 2D matrices
for matrix_name, matrix in matrices_2d.items():
if plot_idx >= len(axes_flat):
break
ax = axes_flat[plot_idx]
# Create heatmap
ax.imshow(matrix, cmap="viridis", aspect="auto")
# Add title
ax.set_title(f"Matrix {matrix_name}", fontweight="bold")
# Add text annotations for small matrices
if (
matrix.size <= self._ANNOTATION_CELL_LIMIT
): # Only add text for reasonably sized matrices
for row in range(matrix.shape[0]):
for col in range(matrix.shape[1]):
value = float(matrix[row, col])
ax.text(
col,
row,
f"{value:.2f}",
ha="center",
va="center",
color="white" if value < 0.5 else "black",
fontsize=8,
)
# Set axis labels
ax.set_xlabel("Column")
ax.set_ylabel("Row")
plot_idx += 1
# Plot 3D matrices (show first slice)
for matrix_name, matrix in matrices_3d.items():
if plot_idx >= len(axes_flat):
break
ax = axes_flat[plot_idx]
# Show first slice of 3D tensor
slice_data = matrix[:, :, 0]
ax.imshow(slice_data, cmap="Blues", aspect="auto")
# Add title
ax.set_title(f"Tensor {matrix_name} (Slice 0)", fontweight="bold")
# Add text annotations for small matrices
if slice_data.size <= self._ANNOTATION_CELL_LIMIT:
for row in range(slice_data.shape[0]):
for col in range(slice_data.shape[1]):
value = float(slice_data[row, col])
ax.text(
col,
row,
f"{value:.2f}",
ha="center",
va="center",
color="white" if value < 0.5 else "black",
fontsize=8,
)
# Set axis labels
ax.set_xlabel("Column")
ax.set_ylabel("Row")
plot_idx += 1
# Hide unused subplots
for i in range(plot_idx, len(axes_flat)):
axes_flat[i].set_visible(False)
safe_tight_layout()
plt.savefig(output_path, dpi=300, bbox_inches="tight")