-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathprocessor.py
More file actions
736 lines (624 loc) · 28.9 KB
/
processor.py
File metadata and controls
736 lines (624 loc) · 28.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
#!/usr/bin/env python3
"""
Enhanced Render processor module for GNN code generation with POMDP-aware processing.
This module provides comprehensive rendering capabilities that:
1. Extract POMDP state spaces from GNN specifications
2. Modularly inject them into framework-specific renderers
3. Create implementation-specific output subfolders
4. Provide structured documentation and results
"""
import json
import logging
import sys
from datetime import datetime
from pathlib import Path
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union
if TYPE_CHECKING:
from gnn.types import GNNInternalRepresentation
try:
import numpy as np
NUMPY_AVAILABLE = True
except ImportError:
np = None # type: ignore[assignment]
NUMPY_AVAILABLE = False
# Ensure src and project root are on the path for cross-module imports
_src_path = Path(__file__).parent.parent
_project_root = _src_path.parent
if str(_src_path) not in sys.path:
sys.path.insert(0, str(_src_path))
if str(_project_root) not in sys.path:
sys.path.insert(0, str(_project_root))
logger = logging.getLogger(__name__)
def validate_pomdp_for_rendering(pomdp_space: Any) -> Tuple[bool, List[str]]:
"""
Validate POMDP space for rendering requirements.
Args:
pomdp_space: Extracted POMDP space object
Returns:
Tuple of (is_valid, error_messages)
"""
errors = []
# Check basic dimensions
if not hasattr(pomdp_space, 'num_states') or pomdp_space.num_states is None:
errors.append("Missing number of states")
elif isinstance(pomdp_space.num_states, list):
if any(n <= 0 for n in pomdp_space.num_states):
errors.append("Invalid state dimensions (must be positive)")
elif pomdp_space.num_states <= 0:
errors.append("Invalid number of states (must be positive)")
if not hasattr(pomdp_space, 'num_observations') or pomdp_space.num_observations is None:
errors.append("Missing number of observations")
if not hasattr(pomdp_space, 'num_actions') or pomdp_space.num_actions is None:
errors.append("Missing number of actions")
return len(errors) == 0, errors
def normalize_matrices(pomdp_space: Any, logger: logging.Logger) -> Any:
"""
Normalize probability matrices in POMDP space.
Ensures that:
- A matrix (observation model): columns sum to 1 over the observation dimension
- B matrix (transition model): columns sum to 1 over the next-state dimension (per action)
Handles 2D arrays, 3D arrays, and list-of-arrays (factorial) structures.
Args:
pomdp_space: POMDP space object with optional A_matrix and B_matrix attributes
logger: Logger instance
Returns:
POMDP space with normalized matrices, or the original object unchanged
if normalization fails (normalization error logged as warning)
"""
def _normalize_columns(matrix: np.ndarray) -> np.ndarray:
"""Normalize columns so each sums to 1. Works on 2D arrays."""
m = np.asarray(matrix, dtype=np.float64)
if m.ndim != 2:
return m
col_sums = m.sum(axis=0, keepdims=True)
# Avoid division by zero: replace zero-sum columns with uniform
zero_mask = col_sums == 0
col_sums[zero_mask] = 1.0
m = m / col_sums
# Fill zero-sum columns with uniform distribution
if np.any(zero_mask):
uniform = np.ones(m.shape[0], dtype=np.float64) / m.shape[0]
for col_idx in np.where(zero_mask.flatten())[0]:
m[:, col_idx] = uniform
return m
try:
# Normalize A matrix (Observation model)
# Columns should sum to 1.0 over the observation dimension
if hasattr(pomdp_space, 'A_matrix') and pomdp_space.A_matrix is not None:
A = pomdp_space.A_matrix
if isinstance(A, list) and len(A) > 0 and isinstance(A[0], np.ndarray):
# Factorial structure: list of per-modality arrays
pomdp_space.A_matrix = [_normalize_columns(a) for a in A]
logger.debug(f"Normalized {len(A)} A-matrix modalities")
elif isinstance(A, np.ndarray):
if A.ndim == 2:
pomdp_space.A_matrix = _normalize_columns(A)
elif A.ndim == 3:
# 3D: (obs, states, factors) — normalize over axis 0 per slice
for i in range(A.shape[2]):
A[:, :, i] = _normalize_columns(A[:, :, i])
pomdp_space.A_matrix = A
logger.debug("Normalized A matrix")
# Normalize B matrix (Transition model)
# Columns should sum to 1.0 over next-state dimension, per action
if hasattr(pomdp_space, 'B_matrix') and pomdp_space.B_matrix is not None:
B = pomdp_space.B_matrix
if isinstance(B, list) and len(B) > 0 and isinstance(B[0], np.ndarray):
# Factorial structure: list of per-factor transition arrays
normalized_B = []
for b in B:
b = np.asarray(b, dtype=np.float64)
if b.ndim == 3:
# (next_state, current_state, action)
for a_idx in range(b.shape[2]):
b[:, :, a_idx] = _normalize_columns(b[:, :, a_idx])
elif b.ndim == 2:
b = _normalize_columns(b)
normalized_B.append(b)
pomdp_space.B_matrix = normalized_B
logger.debug(f"Normalized {len(B)} B-matrix factors")
elif isinstance(B, np.ndarray):
B = np.asarray(B, dtype=np.float64)
if B.ndim == 3:
# (next_state, current_state, action)
for a_idx in range(B.shape[2]):
B[:, :, a_idx] = _normalize_columns(B[:, :, a_idx])
elif B.ndim == 2:
B = _normalize_columns(B)
pomdp_space.B_matrix = B
logger.debug("Normalized B matrix")
except Exception as e:
logger.warning(f"Matrix normalization failed: {e}")
return pomdp_space
def process_render(
target_dir: Path,
output_dir: Path,
verbose: bool = False,
frameworks: Optional[List[str]] = None,
strict_validation: bool = True,
**kwargs: Any,
) -> Union[bool, int]:
"""
Process render for GNN specifications with POMDP-aware processing.
This enhanced processor:
1. Extracts POMDP state spaces from GNN files
2. Modularly injects them into framework-specific renderers
3. Creates implementation-specific output subfolders
4. Provides structured documentation and results
Args:
target_dir: Directory containing GNN files to process
output_dir: Output directory for rendered files
verbose: Enable verbose logging
frameworks: List of frameworks to render for (default: all)
strict_validation: Enable strict POMDP validation
Returns:
True if processing succeeded, False otherwise
"""
try:
logger.info(f"Processing GNN files in: {target_dir}")
logger.info(f"Output directory: {output_dir}")
# Ensure output directory exists
output_dir.mkdir(parents=True, exist_ok=True)
# Import POMDP processing capabilities
try:
# Try multiple import strategies
try:
from gnn.pomdp_extractor import extract_pomdp_from_file
from render.pomdp_processor import POMDPRenderProcessor
except ImportError:
# Recovery to src-prefixed imports
from src.gnn.pomdp_extractor import extract_pomdp_from_file
from src.render.pomdp_processor import POMDPRenderProcessor
pomdp_available = True
except ImportError as e:
logger.warning(f"POMDP processing modules not available: {e}")
logger.info("Falling back to basic rendering")
pomdp_available = False
# Find GNN files
gnn_files = []
for pattern in ['*.md', '*.json', '*.yaml', '*.yml']:
gnn_files.extend(target_dir.glob(pattern))
if not gnn_files:
logger.warning(f"No GNN files found in {target_dir}")
# Exit-code 2: no input. Distinguishes "nothing to render" from
# "rendered successfully".
return 2
logger.info(f"Found {len(gnn_files)} GNN files to process")
# Processing configuration — frameworks=None means all frameworks
if frameworks:
logger.info(f"Target frameworks: {frameworks}")
else:
logger.info("Target frameworks: all available")
results = {}
success_count = 0
total_framework_successes = 0
total_framework_attempts = 0
if pomdp_available:
# Use POMDP-aware processing
for gnn_file in gnn_files:
try:
logger.info(f"Processing: {gnn_file}")
# Extract POMDP state space from GNN file
pomdp_space = extract_pomdp_from_file(gnn_file, strict_validation=strict_validation)
if pomdp_space is None:
logger.warning(f"Could not extract POMDP from {gnn_file}, trying basic rendering")
# Fall back to basic processing for this file
file_result = _process_single_gnn_file_basic(gnn_file, output_dir, verbose, **kwargs)
results[str(gnn_file)] = file_result
if file_result['success']:
success_count += 1
continue
logger.info(f"Extracted POMDP '{pomdp_space.model_name}' with {pomdp_space.num_states} states, {pomdp_space.num_observations} observations, {pomdp_space.num_actions} actions")
# Validate POMDP space
is_valid, validation_errors = validate_pomdp_for_rendering(pomdp_space)
if not is_valid:
if strict_validation:
err_msg = (
f"POMDP validation failed (strict); skipping render for {gnn_file.name}: "
f"{validation_errors}"
)
logger.error(err_msg)
results[str(gnn_file)] = {
"overall_success": False,
"framework_results": {},
"error": err_msg,
"validation_failed_strict": True,
}
continue
logger.warning(
f"POMDP validation failed for {gnn_file.name}: {validation_errors}; "
"continuing because strict_validation=False"
)
# Normalize matrices
pomdp_space = normalize_matrices(pomdp_space, logger)
# Create file-specific output directory
file_output_dir = output_dir / gnn_file.stem
# Create processor with file-specific directory
file_processor = POMDPRenderProcessor(file_output_dir)
# Process POMDP for all frameworks
processing_result = file_processor.process_pomdp_for_all_frameworks(
pomdp_space, gnn_file_path=gnn_file, frameworks=frameworks, **kwargs
)
processing_result['base_output_dir'] = str(file_output_dir)
results[str(gnn_file)] = processing_result
if processing_result['overall_success']:
success_count += 1
logger.info(f"Successfully processed {gnn_file.name}")
else:
logger.error(f"Failed to process {gnn_file.name}")
# Count framework-level successes
for _, result in processing_result['framework_results'].items():
total_framework_attempts += 1
if result['success']:
total_framework_successes += 1
except Exception as e:
error_msg = f"Error processing {gnn_file}: {e}"
logger.error(error_msg)
results[str(gnn_file)] = {
'overall_success': False,
'framework_results': {},
'error': error_msg
}
else:
# Use basic rendering
for gnn_file in gnn_files:
try:
logger.info(f"Processing (basic): {gnn_file}")
file_result = _process_single_gnn_file_basic(gnn_file, output_dir, verbose, **kwargs)
results[str(gnn_file)] = file_result
if file_result['success']:
success_count += 1
logger.info(f"Processed {gnn_file.name}")
else:
logger.error(f"Failed to process {gnn_file.name}")
except Exception as e:
error_msg = f"Error processing {gnn_file}: {e}"
logger.error(error_msg)
results[str(gnn_file)] = {
'success': False,
'error': error_msg
}
# Create overall processing summary
summary = {
'timestamp': datetime.now().isoformat(),
'processing_type': 'POMDP-aware rendering' if pomdp_available else 'Basic rendering',
'total_files': len(gnn_files),
'successful_files': success_count,
'failed_files': len(gnn_files) - success_count,
'total_framework_attempts': total_framework_attempts,
'successful_framework_renderings': total_framework_successes,
'framework_success_rate': (total_framework_successes / total_framework_attempts * 100) if total_framework_attempts > 0 else 0,
'configuration': {
'frameworks': frameworks or 'all',
'strict_validation': strict_validation,
'verbose': verbose,
'pomdp_processing_available': pomdp_available
},
'file_results': results
}
summary_file = output_dir / 'render_processing_summary.json'
with open(summary_file, 'w') as f:
json.dump(summary, f, indent=2)
# Create overview documentation
_create_overview_documentation(output_dir, summary)
logger.info("Render processing completed")
logger.info(f"Files: {success_count}/{len(gnn_files)} successful")
if pomdp_available:
logger.info(f"Framework renderings: {total_framework_successes}/{total_framework_attempts} successful ({summary['framework_success_rate']:.1f}%)")
logger.info(f"Summary saved to: {summary_file}")
# Consider rendering successful if:
# 1. At least one file was processed successfully, OR
# 2. At least 80% of framework renderings succeeded
if pomdp_available and total_framework_attempts > 0:
framework_success_rate = (total_framework_successes / total_framework_attempts) * 100
return framework_success_rate >= 80.0 or success_count > 0
# Non-POMDP path: guard against trivially-"successful" zero-file runs
# (len(gnn_files) == 0 and success_count == 0 satisfies == but is a skip,
# not a success). Phase 1.1 flags this as exit-code 2 upstream, but keep
# the defense here in case the caller bypasses the earlier check.
if len(gnn_files) == 0:
return 2
return success_count == len(gnn_files)
except Exception as e:
logger.error(f"Render processing failed: {e}")
return False
def _process_single_gnn_file_basic(gnn_file: Path, output_dir: Path, verbose: bool, **kwargs) -> Dict[str, Any]:
"""
Basic processing for a single GNN file without POMDP extraction.
Args:
gnn_file: GNN file to process
output_dir: Output directory
verbose: Enable verbose logging
**kwargs: Additional processing options
Returns:
Processing result dictionary
"""
try:
# Import basic generators
from .generators import (
generate_activeinference_jl_code,
generate_bnlearn_code,
generate_discopy_code,
generate_pymdp_code,
generate_rxinfer_code,
)
# Create basic model data from filename
model_data = {
'model_name': gnn_file.stem,
'variables': [],
'connections': []
}
# Create file-specific output directory
file_output_dir = output_dir / gnn_file.stem
file_output_dir.mkdir(parents=True, exist_ok=True)
generated_files = []
# Generate code for each framework
frameworks = {
'pymdp': (generate_pymdp_code, '.py'),
'rxinfer': (generate_rxinfer_code, '.jl'),
'activeinference_jl': (generate_activeinference_jl_code, '.jl'),
'discopy': (generate_discopy_code, '.py'),
'bnlearn': (generate_bnlearn_code, '.py')
}
for framework_name, (generator_func, extension) in frameworks.items():
try:
# Create framework subdirectory
framework_dir = file_output_dir / framework_name
framework_dir.mkdir(parents=True, exist_ok=True)
# Generate code
code = generator_func(model_data)
if code:
output_file = framework_dir / f"{gnn_file.stem}_{framework_name}{extension}"
with open(output_file, 'w') as f:
f.write(code)
generated_files.append(str(output_file))
except Exception as e:
logger.warning(f"Failed to generate {framework_name} code for {gnn_file}: {e}")
return {
'success': len(generated_files) > 0,
'message': f"Generated {len(generated_files)} files" if generated_files else "No files generated",
'generated_files': generated_files,
'output_directory': str(file_output_dir)
}
except Exception as e:
return {
'success': False,
'message': f"Basic processing failed: {e}",
'generated_files': []
}
def _create_overview_documentation(output_dir: Path, summary: Dict[str, Any]) -> None:
"""
Create overview documentation for the rendering results.
Args:
output_dir: Output directory
summary: Processing summary data
"""
try:
doc_content = f"""# GNN Rendering Results
Generated: {summary['timestamp']}
Processing Type: **{summary['processing_type']}**
## Summary
- **Total Files**: {summary['total_files']}
- **Successfully Processed**: {summary['successful_files']}
- **Failed**: {summary['failed_files']}
"""
if summary['total_framework_attempts'] > 0:
doc_content += f"""- **Framework Renderings**: {summary['successful_framework_renderings']}/{summary['total_framework_attempts']} ({summary['framework_success_rate']:.1f}% success rate)
"""
doc_content += f"""
## Configuration
- **Frameworks**: {summary['configuration']['frameworks']}
- **Strict Validation**: {summary['configuration']['strict_validation']}
- **Verbose**: {summary['configuration']['verbose']}
- **POMDP Processing**: {'✅ Available' if summary['configuration'].get('pomdp_processing_available', False) else '❌ Not Available'}
## File Results
"""
for file_path, result in summary['file_results'].items():
file_name = Path(file_path).name
if result.get('overall_success', result.get('success', False)):
doc_content += f"- ✅ **{file_name}** - Successfully processed\n"
# Add framework details if available
if 'framework_results' in result:
for framework, framework_result in result['framework_results'].items():
status = "✅" if framework_result['success'] else "❌"
doc_content += f" - {status} {framework}: {framework_result.get('message', 'N/A')}\n"
else:
error_msg = result.get('error', result.get('message', 'Unknown error'))
doc_content += f"- ❌ **{file_name}** - {error_msg}\n"
doc_content += f"""
## Output Structure
The rendered files are organized in implementation-specific subfolders:
```
{output_dir}/
├── [model_name]/
│ ├── pymdp/ # PyMDP Python simulations
│ ├── rxinfer/ # RxInfer.jl Julia simulations
│ ├── activeinference_jl/ # ActiveInference.jl Julia simulations
│ ├── jax/ # JAX Python simulations
│ └── discopy/ # DisCoPy categorical diagrams
└── render_processing_summary.json # Detailed results
```
## Generated Files
Each framework subdirectory contains:
- Main simulation/diagram script
- Framework-specific README.md with model details
- Configuration files (if applicable)
## Next Steps
1. Navigate to specific framework directories to find generated code
2. Follow framework-specific READMEs for execution instructions
3. Check the processing summary JSON for detailed results and any warnings
---
*Generated by GNN Render Processor v1.0*
"""
doc_file = output_dir / 'README.md'
with open(doc_file, 'w') as f:
f.write(doc_content)
logger.info(f"Created overview documentation: {doc_file}")
except Exception as e:
logger.warning(f"Failed to create overview documentation: {e}")
def render_gnn_spec(
gnn_spec: "Union[GNNInternalRepresentation, Dict[str, Any]]",
target: str,
output_directory: Union[str, Path],
options: Optional[Dict[str, Any]] = None
) -> Tuple[bool, str, List[str]]:
"""
Render a GNN specification to a target language with POMDP awareness.
Args:
gnn_spec: GNN specification dictionary
target: Target language/environment
output_directory: Output directory for generated code
options: Additional options
Returns:
Tuple of (success, message, output_files: List[str])
"""
try:
output_dir = Path(output_directory)
output_dir.mkdir(parents=True, exist_ok=True)
# Generator-based renderers: target → (generator_name, file_suffix)
_GENERATOR_TARGETS = {
"pymdp": ("generate_pymdp_code", "_pymdp.py"),
"rxinfer": ("generate_rxinfer_code", "_rxinfer.jl"),
"activeinference_jl": ("generate_activeinference_jl_code", "_activeinference.jl"),
"discopy": ("generate_discopy_code", "_discopy.py"),
"bnlearn": ("generate_bnlearn_code", "_bnlearn.py"),
}
target_lower = target.lower()
model_name = gnn_spec.get('model_name', 'model')
files = []
if target_lower in _GENERATOR_TARGETS:
gen_name, suffix = _GENERATOR_TARGETS[target_lower]
from . import generators
generate_fn = getattr(generators, gen_name)
code = generate_fn(gnn_spec)
output_file = output_dir / f"{model_name}{suffix}"
if code:
output_file.write_text(code)
files.append(str(output_file))
elif target_lower == "rxinfer_toml":
try:
from .rxinfer import render_gnn_to_rxinfer_toml
success, msg, art = render_gnn_to_rxinfer_toml(gnn_spec, output_dir)
if success:
return True, msg, art
except ImportError:
return False, "RxInfer TOML renderer not available", []
elif target_lower == "discopy_combined":
try:
from .discopy import render_gnn_to_discopy
output_file = output_dir / f"{model_name}_discopy.py"
success, msg, _warnings = render_gnn_to_discopy(gnn_spec, output_file)
return (True, msg, [str(output_file)]) if success else (False, msg, [])
except ImportError:
return False, "DisCoPy renderer not available", []
elif target_lower in ("jax", "jax_pomdp"):
try:
from .jax.jax_renderer import render_gnn_to_jax
output_file = output_dir / f"{model_name}_jax.py"
success, msg, art = render_gnn_to_jax(gnn_spec, output_file)
if success:
return True, msg, art
except ImportError:
return False, "JAX renderer not available", []
else:
return False, f"Unsupported target: {target}", []
if files:
return True, f"Successfully generated {target} code", files
else:
return False, f"Failed to generate {target} code", []
except Exception as e:
return False, f"Error rendering {target}: {e}", []
def get_module_info() -> Dict[str, Any]:
"""Get information about the render module."""
# Import here (not at module top) to avoid circular init when this module is
# imported before ``render/__init__.py`` finishes loading.
try:
from . import __version__ as _version
except Exception: # noqa: BLE001
_version = "unknown"
return {
"name": "Render Module",
"version": _version,
"description": "POMDP-aware code generation for GNN specifications",
"supported_targets": ["pymdp", "rxinfer", "activeinference_jl", "jax", "discopy", "bnlearn"],
"available_targets": ["pymdp", "rxinfer", "activeinference_jl", "discopy", "bnlearn"],
"features": [
"POMDP state space extraction",
"Modular framework injection",
"Implementation-specific output directories",
"PyMDP code generation",
"RxInfer.jl code generation",
"ActiveInference.jl code generation",
"JAX code generation",
"DisCoPy categorical diagram generation",
"bnlearn bayesian network generation",
"Structured documentation generation"
],
"supported_formats": ["python", "julia", "python_script"],
"processing_modes": ["basic", "pomdp_aware"]
}
AVAILABLE_RENDERERS: Dict[str, Dict[str, Any]] = {
"pymdp": {
"name": "PyMDP",
"description": "Python Markov Decision Process library for Active Inference",
"language": "Python",
"file_extension": ".py",
"supported_features": ["POMDP", "MDP", "Belief State Updates", "Active Inference"],
"function": "render_gnn_to_pymdp",
"output_format": "python",
"pomdp_compatible": True
},
"rxinfer": {
"name": "RxInfer.jl",
"description": "Julia reactive message passing inference engine",
"language": "Julia",
"file_extension": ".jl",
"supported_features": ["Message Passing", "Probabilistic Programming", "Bayesian Inference"],
"function": "render_gnn_to_rxinfer",
"output_format": "julia",
"pomdp_compatible": True
},
"activeinference_jl": {
"name": "ActiveInference.jl",
"description": "Julia Active Inference library",
"language": "Julia",
"file_extension": ".jl",
"supported_features": ["Free Energy Minimization", "Active Inference", "POMDP"],
"function": "render_gnn_to_activeinference_jl",
"output_format": "julia",
"pomdp_compatible": True
},
"jax": {
"name": "JAX",
"description": "High-performance numerical computing with automatic differentiation",
"language": "Python",
"file_extension": ".py",
"supported_features": ["GPU Acceleration", "Automatic Differentiation", "JIT Compilation"],
"function": "render_gnn_to_jax",
"output_format": "python",
"pomdp_compatible": True
},
"discopy": {
"name": "DisCoPy",
"description": "Python library for computing with string diagrams",
"language": "Python",
"file_extension": ".py",
"supported_features": ["Categorical Diagrams", "String Diagrams", "Compositional Models"],
"function": "render_gnn_to_discopy",
"output_format": "python",
"pomdp_compatible": True
},
"bnlearn": {
"name": "bnlearn",
"description": "Python package for learning the graphical structure of Bayesian networks",
"language": "Python",
"file_extension": ".py",
"supported_features": ["Structure Learning", "Parameter Learning", "Exact Inference", "Causal Discovery"],
"function": "render_gnn_to_bnlearn",
"output_format": "python",
"pomdp_compatible": True
}
}
def get_available_renderers() -> Dict[str, Dict[str, Any]]:
"""Get information about available renderers."""
return AVAILABLE_RENDERERS