# ==============================================================================
# RIPPL: SOVEREIGN SCIML & AUTONOMOUS PHYSICS INTELLIGENCE FRAMEWORK
# ==============================================================================
# Master LLM System Context & Anti-Hallucination Guardrails
# Cross-Repo Integration: import rippl as rp; import rippl_adk as adk

SECTION 1: CRITICAL RULES & ANTI-HALLUCINATION GUARDRAILS
1. NO `from rippl import PINN` — that class does NOT exist. Use `rp.Solver(equation, domain, constraints).solve()` or `rp.run()`.
2. NO TensorFlow or DeepXDE — Rippl is strictly PyTorch and native Rust/C++ kernels.
3. NO manual training loops — never write `for epoch in range(...)`, `loss.backward()`, or `optimizer.step()`. Always use `rp.Solver.solve()` or `rp.run()`.
4. NO legacy mesh generation — never use Gmsh, Salome, ANSYS meshing scripts, or manual `np.meshgrid` element grids. Rippl is Zero-Meshing via continuous Signed Distance Fields (SDFs).
5. NO `rp.DirichletBC` — boundary conditions use `rp.Dirichlet(value=...)` or `rp.Neumann(flux=...)`.
6. Neural network architectures come from `rippl.nn` (e.g., `rnn.MLP`, `rnn.FourierNet`, `rnn.KAN`), NOT `rippl.models`.
7. Domain bounds are strictly `List[Tuple[float, float]]` (e.g., `[(0.0, 1.0), (0.0, 1.0)]`), NOT dictionaries.
8. For Surge Reduced Order Models: use `rp.surge.UniversalSurge` or algorithmic ROMs, NOT raw ad-hoc FNO training scripts.
9. For Digital Twins: use `rp.twins.Twin(domain, equation, model, mode=TwinMode.CONTINUOUS)` or `TwinBuilder`.
10. For Enterprise model export: always use `model.export("name.rpx", encrypt_payload=True)` for AES-256-GCM authenticated envelopes.
11. For Autonomous Agent Orchestration: use `import rippl_adk as adk`. Never introduce third-party LangChain/LangGraph dependencies.

SECTION 2: THE 7-LINE VIBE CODING PARADIGM
Rippl eliminates complex simulation boilerplate in favor of declarative, 7-line vibe coding:

Pattern A: Canonical 7-Line SciML Physics Solver
```python
import rippl as rp, rippl.nn as rnn
eq = rp.HeatEquation(alpha=0.1)
domain = rp.Domain(bounds=[(0, 1), (0, 1)])
solver = rp.Solver(equation=eq, domain=domain, constraints=[rp.Dirichlet(value=0.0)])
model = solver.solve(epochs=5000, model=rnn.MLP(in_dim=2, out_dim=1))
prediction = model(x=0.5, y=0.5)
model.export("heat_model.rpx", encrypt_payload=True, encrypt_key=b'ENTERPRISE_KEY_32_BYTES_LONG!')
```

Pattern B: 7-Line Zero-Meshing CAD Ingestion
```python
import rippl as rp
from rippl.cad.solver import CADSolver
from rippl.physics.operators import Laplacian
from rippl.core.equation import Equation

eq = Equation([Laplacian(field='T', spatial_dims=3)])
cad_solver = CADSolver(stl_path="turbomachine.stl", equation=eq, field_name='T')
model = cad_solver.solve(epochs=3000)
pred = model(x=0.15, y=0.22, z=0.08)
```

Pattern C: 7-Line Unified SciML + Level 5 RSI Agent
```python
import rippl as rp, rippl_adk as adk
domain, eq = rp.Domain(bounds=[(0, 1), (0, 1)]), rp.HeatEquation(alpha=0.1)
model = rp.Solver(eq, domain, [rp.Dirichlet(0.0)]).solve(epochs=1000, model=rp.nn.MLP(2, 1))
cad = rp.cad.CADSolver("impeller.stl", eq, field_name="T")
rom = rp.surge.UniversalSurge(model=model, latent_dim=32)
agent = adk.Agent(model="auto", tools=[cad.solve, rom.evaluate], self_healing=True)
res = adk.Verifiers.physics_residuals(tolerance=1e-4).verify(agent.run("Simulate impeller heat flux"))
```

SECTION 3: ARCHITECTURAL PILLARS & CORE CONCEPTS

1. ZERO-MESHING CAD INGESTION
   Rippl completely replaces classical tetrahedral/hexahedral meshing with mesh-free continuous geometry:
   - Direct ingestion of industry-standard `.stl` and `.step` files via `rp.cad.CADSolver`.
   - Native C++ / Rust kernels evaluate Signed Distance Fields (SDFs) and surface normals on the fly.
   - Eliminates mesh skewness, inverted elements, boundary layer meshing failures, and hours of CAD cleanup.

2. SURGE ROMs (REDUCED ORDER MODELS)
   - Universal Surge provides 0.42 ms latency for real-time aerodynamic and thermal field evaluations.
   - Continuous latent state rollouts with strict physical invariant projectors enforcing conservation laws (mass, momentum, energy).
   - Real-time Out-of-Distribution (OOD) rejection using Mahalanobis distance thresholds.

3. LEVEL 5 RSI SELF-HEALING (POWERED BY RIPPL ADK)
   - Autonomous engineering agents running with `self_healing=True`.
   - When missing capabilities or broken tool APIs are encountered, the runtime activates `AutoToolSynthesizer`.
   - The synthesized Python tool is verified inside the Win32 handle sandbox perimeter using `GoldenAssertionTest` suites.
   - Upon verification passing, the tool is atomically hot-swapped into the live `ToolRegistry`.
   - RLVR ground-truth verification via `adk.Verifiers` guarantees mathematical rigor through deterministic certificates (`InvariantCertificate`).

4. FAIL-CLOSED SAFETY & CRYPTOGRAPHY
   - Cyber-physical safety interlocks: Autonomous agent commands are intercepted; if physical residuals exceed defined thresholds, the system defaults to a fail-closed safe state.
   - Process sandboxing: Win32 handle confinement blocks symlink races, TOCTOU bypasses, and unauthorized filesystem operations. Any perimeter breach triggers an uncatchable `AgentSuicideError`.
   - RPX v3 Authenticated Packaging: Models are sealed with AES-256-GCM encryption, 96-bit cryptographic nonces, and DRM license enforcement.

SECTION 4: API SCHEMAS
### Function: `rippl.commands.run_unified_tests`
`def run_unified_tests()`
"""
Run all Rippl framework tests programmatically.
Ideal for Colab, SageMaker, or Databricks notebooks.
"""

### Function: `rippl.commands.build_docs`
`def build_docs(output_dir: str = 'docs')`
"""
Generate heavy HTML documentation for the entire Rippl framework.
"""

### Function: `rippl.commands.check_capabilities`
`def check_capabilities(asset_path: str)`
"""
Run a full capability check on a provided CAD/Asset file.
This proves Zero-Meshing, Solver Stability, and Digital Twin backwards-query.

Args:
    asset_path (str): Path to the .stl or .obj asset.
"""

### Class: `rippl.concurrency.ConcurrencyGuard`
"""
Limits the number of concurrent training jobs.
"""
Methods:
- `def __init__(self, max_concurrent: int = 2)`

### Class: `rippl.concurrency.JobStatus`
Methods:
- `def __init__(self, state: str, error: Optional[str] = None)`

### Class: `rippl.concurrency.Job`
"""
Asynchronous job representation.
"""
Methods:
- `def __init__(self, target_fn: Callable[[], Any], guard: Optional[ConcurrencyGuard] = None)`
- `def status(self) -> JobStatus`
- `def result(self, block: bool = False) -> Optional[Any]`

### Function: `rippl.concurrency.submit`
`def submit(domain, equation, model, backend: str = 'local', cluster_config: Optional[dict] = None, epochs: int = 5000, hard_bcs: bool = True, on_epoch: Optional[Callable[[int, float], None]] = None, guard: Optional[ConcurrencyGuard] = None) -> Job`

### Function: `rippl.convenience.save`
`def save(result, path: str)`
"""
Save a Rippl RunResult or model to an .rpx bundle.
"""

### Function: `rippl.convenience.load`
`def load(path: str) -> dict`
"""
Load a Rippl .rpx bundle.
"""

### Function: `rippl.convenience.export`
`def export(model: torch.nn.Module, path: str, format: str = 'torchscript', metadata: dict = None)`
"""
Export a trained Rippl model for production inference.
Handles TorchScript and ONNX formats, and generates a Model Card.
"""

### Function: `rippl.describe.describe`
`def describe(query: str = None) -> dict`
"""
Describe rippl capabilities. No LLM, no network calls.

Args:
    query: optional filter ("operators", "models", "physics",
           "training", "benchmarks", or specific PDE name)

Returns:
    dict of relevant framework information

Examples:
    rp.describe()                    # full overview
    rp.describe("heat")             # heat equation info
    rp.describe("operators")        # all operators
    rp.describe("training")         # training features
"""

### Function: `rippl.generate.list_operators`
`def list_operators()`

### Function: `rippl.generate.ask`
`def ask(prompt: str, model: str = 'llama3', max_retries: int = 3) -> dict`
"""
Generate a rippl System from natural language.

Args:
    prompt: natural language PDE description
    model: Ollama model name
    max_retries: validation retry attempts

Returns:
    dict with keys: system, config, description

Raises:
    GenerationError if validation fails after max_retries
    ImportError if ollama not installed

Example:
    result = rp.ask("heat equation on unit square, alpha=0.1")
    rp.run(result["system"], model=rnn.MLP(in_dim=2, out_dim=1))
"""

### Class: `rippl.generate.GenerationError`
Methods:

### Class: `rippl.ingest_profiles.IngestProfile`
Methods:

### Function: `rippl.ingest_profiles.save_profile`
`def save_profile(profile: IngestProfile) -> None`

### Function: `rippl.ingest_profiles.load_all`
`def load_all() -> dict`

### Function: `rippl.ingest_profiles.load_profile`
`def load_profile(name: str) -> IngestProfile`

### Function: `rippl.ingest_profiles.fetch`
`def fetch(name: str) -> dict`
"""
Resolves a named profile to real data via the appropriate DataSource.
"""

### Class: `rippl.load.LoadedModel`
Methods:
- `def predict(self, coords) -> np.ndarray`

### Function: `rippl.load.load`
`def load(path: str) -> LoadedModel`

### Class: `rippl.pipeline_ops.SubmitStatus`
Methods:

### Class: `rippl.pipeline_ops.Job`
Methods:
- `def __init__(self, domain, equation, model, backend = 'local', guard = None, **run_kwargs)`
- `def status(self) -> SubmitStatus`
- `def result(self, block: bool = True)`

### Class: `rippl.pipeline_ops.ConcurrencyGuard`
Methods:
- `def __init__(self, max_concurrent: int = 2)`

### Function: `rippl.pipeline_ops.submit`
`def submit(domain, equation, model, backend = 'local', guard = None, **run_kwargs) -> Job`

### Function: `rippl.registry.list_operators`
`def list_operators()`

### Function: `rippl.registry.list_models`
`def list_models()`

### Function: `rippl.registry.list_solvers`
`def list_solvers()`

### Class: `rippl.sources.ArraySource`
"""
DataSource wrapping in-memory NumPy arrays.
"""
Methods:
- `def __init__(self, coords: np.ndarray, fields: Dict[str, np.ndarray], topology: Optional[np.ndarray] = None)`
- `def fetch(self) -> Dict[str, Any]`

### Class: `rippl.sources.TabularSource`
"""
DataSource wrapping tabular files (e.g. CSV).
"""
Methods:
- `def __init__(self, filepath: str, coord_cols: list, field_cols: list)`
- `def fetch(self) -> Dict[str, Any]`

### Class: `rippl.sources.StreamSource`
"""
DataSource wrapping streaming inputs.
"""
Methods:
- `def __init__(self, generator_fn)`
- `def fetch(self) -> Dict[str, Any]`

### Class: `rippl.twins.TwinMode`
Methods:

### Class: `rippl.twins.TwinState`
Methods:

### Class: `rippl.twins.Twin`
Methods:
- `def __init__(self, domain, equation, model, mode: TwinMode = TwinMode.INFERENCE_ONLY, backend: str = 'local', rom = None, ood_sigma_threshold: float = 3.0, refit_epochs: int = 300, refit_window: int = 500)`
- `def feed(self, coords = None, values = None, params: Optional[dict] = None) -> None`
- `def refit(self) -> dict`
- `def predict(self, coords)`
- `def state(self) -> TwinState`

### Function: `rippl.utils.parse_equation`
`def parse_equation(eq_str: str) -> int`
"""
Validates the mathematical structure of the PDE string.
Returns the mapped integer op_code for the native Cython router.
"""

### Function: `rippl.utils.validate_boundary_conditions`
`def validate_boundary_conditions(bcs: list) -> bool`
"""
Ensures physical constraints are mathematically sound before execution.
"""

### Function: `rippl.visualize.visualize`
`def visualize(rpx_path: str)`

### Class: `rippl.RipplOp`
Methods:
- `def forward(ctx, input_tensor, op_code)`
- `def backward(ctx, grad_output)`

### Class: `rippl.PDE`
Methods:
- `def __init__(self, equations: list, bcs: list, domain = None)`

### Class: `rippl.DeepONet`
Methods:
- `def __init__(self, pde)`

### Class: `rippl.Pipeline`
Methods:
- `def __init__(self, model, config = None)`
- `def execute(self, epochs = 1000)`

### Class: `rippl.backend.__init__.SecurityCompilationError`
Methods:

### Function: `rippl.backend.__init__.spatial_sampling`
`def spatial_sampling(*args, **kwargs)`

### Function: `rippl.backend.__init__.coordinate_sorting`
`def coordinate_sorting(*args, **kwargs)`

### Function: `rippl.backend.__init__.enforce_security`
`def enforce_security()`

### Class: `rippl.cad.geometry.CADGeometry`
"""
Unified CAD geometry handler.

Parses CAD files into an SDF-based geometry representation
that plugs directly into rippl's training pipeline.

Supported backends:
  - trimesh (recommended): STL, OBJ, PLY, GLTF
  - numpy-stl (lightweight): STL only
  - manual: provide vertices + faces directly

Args:
    source: path to CAD file, or dict with {'vertices', 'faces'}
    scale:  normalize geometry to unit bounding box if True
    center: translate centroid to origin if True

Example:
    geo = CADGeometry("wing.stl")
    domain = geo.to_rippl_domain()
    pts = geo.sample_interior(n=5000)
    bpts = geo.sample_boundary(n=2000)
"""
Methods:
- `def __init__(self, source: Union[str, Path, dict], scale: bool = True, center: bool = True)`
- `def sdf(self, query_points: Union[torch.Tensor, np.ndarray]) -> torch.Tensor`
  - Compute signed distance function at query points.
- `def sample_interior(self, n: int, method: str = 'rejection', max_attempts: int = 10) -> torch.Tensor`
  - Sample n points strictly inside the geometry (SDF < 0).
- `def sample_boundary(self, n: int, tol: float = 0.01) -> torch.Tensor`
  - Sample n points on or near the boundary (|SDF| < tol).
- `def to_rippl_domain(self) -> 'Domain'`
  - Convert to rippl Domain object with SDF-based geometry.
- `def normal_vector(self, boundary_points: torch.Tensor) -> torch.Tensor`
  - Outward unit normal vectors at boundary points.
- `def bounds(self) -> List[Tuple[float, float]]`
- `def n_vertices(self) -> int`
- `def n_faces(self) -> int`

### Class: `rippl.cad.pipeline.CADGeometry`
Methods:
- `def __init__(self, mesh_data)`

### Class: `rippl.caddpf_bridge.PyDPFBridge`
"""
Bidirectional bridge between ANSYS DPF and rippl.

extract() → run rippl → inject() is the complete pipeline.

Args:
    result_file: path to ANSYS .rst or .cas result file
    server:      DPF server address (None = local)

Example:
    bridge = PyDPFBridge("simulation.rst")
    tensors = bridge.extract()
    # ... run rippl on tensors ...
    bridge.inject(solved_field, field_name='temperature')
"""
Methods:
- `def __init__(self, result_file: Optional[str] = None, server: Optional[str] = None)`
- `def extract(self) -> Dict[str, torch.Tensor]`
  - Extract geometry and boundary conditions from ANSYS model.
- `def to_rippl_constraints(self, extracted: Dict[str, torch.Tensor], field_name: str = 'u', bc_value: float = 0.0)`
  - Convert extracted ANSYS data to rippl Constraint objects.
- `def inject(self, field_tensor: torch.Tensor, node_coords: torch.Tensor, field_name: str = 'temperature', output_path: str = 'rippl_result.rst')`
  - Inject rippl-solved field back into ANSYS format.

### Class: `rippl.caddpf_bridge.MockPyDPFBridge`
Methods:
- `def __init__(self, *args, **kwargs)`
- `def extract(self)`
- `def to_rippl_constraints(self, *args, **kwargs)`
- `def inject(self, *args, **kwargs)`

### Class: `rippl.cad.solver.CADSolver`
Methods:
- `def __init__(self, stl_path: str, equation: Equation, field_name: str = 'T')`
  - Industrial Neural PDE Solver bridging CAD geometries with field-agnostic operators.
- `def solve(self, boundary_temp: float = 0.0, n_interior: int = 500, n_boundary: int = 200, epochs: int = 20, lr: float = 0.001, hard_bcs: bool = True, lbfgs_steps: int = 0, verbose: bool = False) -> dict`
  - Executes continuous optimization over the parsed CAD interior and boundary points.

### Function: `rippl.compiler.cache.cache_get`
`def cache_get(structural_key: str) -> Optional[Any]`

### Function: `rippl.compiler.cache.cache_put`
`def cache_put(structural_key: str, compiled_fn: Any) -> None`

### Function: `rippl.compiler.cache.cache_clear`
`def cache_clear() -> int`

### Function: `rippl.compiler.cache.cache_stats`
`def cache_stats() -> dict`

### Function: `rippl.compiler.canonical.apply_string_rewrites`
`def apply_string_rewrites(pde_string: str) -> str`
"""
Apply canonical string rewrites before SymPy parsing.
"""

### Function: `rippl.compiler.canonical.get_canonical_key`
`def get_canonical_key(pde_string: str) -> str`
"""
Get a stable canonical key for cache lookups.

Two mathematically equivalent strings produce the same key.
Uses string rewriting + SymPy simplification when available.
"""

### Function: `rippl.compiler.canonical.extract_parameters`
`def extract_parameters(pde_string: str) -> dict`
"""
Extract numeric parameters from a PDE string.

For cache efficiency, we separate structural form from parameters.
The cache key is based on structure. Parameters are substituted at runtime.

Example:
    "Derivative(u,t) - 0.1*Derivative(u,(x,2))"
    → structure: "Derivative(u,t) - PARAM_0*Derivative(u,(x,2))"
    → params: {'PARAM_0': 0.1}

When the same equation is called with alpha=0.2 instead of 0.1,
the structural cache hits and only the coefficient changes.
"""

### Function: `rippl.compiler.dag.build_residual_fn`
`def build_residual_fn(parsed: ParsedEquation) -> Callable`
"""
Build the .residual(fields, coords) function for a parsed equation.

Rather than generating code strings (fragile, security risk),
we build a closure that calls route_derivative for each
IR node and combines results according to the SymPy expression structure.

This approach:
- Is safe (no eval/exec on user-supplied strings)
- Is correct (SymPy handles the math, autograd handles the derivatives)
- Is efficient (grad calls are batched where possible)
- Works with torch.compile
"""

### Class: `rippl.compiler.equation.SymbolicEquation`
"""
A compiled PDE ready for evaluation.

Created by rp.parse(). Satisfies the .residual() contract
so it works transparently with rp.run() and CoupledSystem.

Usage:
    eq = rp.parse("Derivative(u,t) - 0.1*Derivative(u,(x,2))")
    result = rp.run(domain, eq, model, epochs=5000)

Attributes:
    pde_string:    Original equation string
    canonical_key: Cache key (structure only, no parameter values)
    backend:       'TRITON' if kernels available, 'PYTORCH' otherwise
    field_names:   ['u'] or ['u', 'v'] etc.
    coord_names:   ['x', 't'] etc.
    has_time:      Whether equation is time-dependent
"""
Methods:
- `def __init__(self, pde_string: str, canonical_key: str, parsed: Any, residual_fn: Any, backend: str = 'PYTORCH')`
- `def residual(self, fields: dict, coords: torch.Tensor) -> torch.Tensor`
  - Compute PDE residual.
- `def describe(self) -> str`
  - Human-readable equation summary.

### Class: `rippl.compiler.guardrails.GuardrailConfig`
Methods:

### Class: `rippl.compiler.guardrails.GuardrailViolation`
"""
Raised when a PDE string violates safety guardrails.
"""
Methods:

### Function: `rippl.compiler.guardrails.check_string_guardrails`
`def check_string_guardrails(pde_string: str, config: GuardrailConfig = DEFAULT_GUARDRAILS)`
"""
Fast pre-parse checks on the raw string. Zero SymPy overhead.
"""

### Function: `rippl.compiler.guardrails.check_sympy_guardrails`
`def check_sympy_guardrails(expr, config: GuardrailConfig = DEFAULT_GUARDRAILS)`
"""
Post-parse checks on the SymPy expression tree.
"""

### Class: `rippl.compiler.router.FusedLaplacian1DAutograd`
Methods:
- `def forward(ctx, field, dx)`
- `def backward(ctx, grad_output)`

### Function: `rippl.compiler.router.try_triton_laplacian`
`def try_triton_laplacian(field, coords, coord_idx, dx = 1.0)`
"""
INFERENCE ONLY. Never call during training.

The Triton fused_laplacian_1d computes a finite-difference stencil
over output field values. This is NOT the PINN Laplacian, which requires
torch.autograd.grad twice through the network graph.

Use cases:
  - Post-training visualization of solution smoothness
  - Fast evaluation of trained solution on regular grids
  - Never: computing PDE residuals during training
"""

### Function: `rippl.compiler.router.route_derivative`
`def route_derivative(field_tensor, coords, wrt, coord_names, create_graph = True)`
"""
Compute derivative using autograd ONLY.

The autograd path is the ONLY correct path for PINN training.
Triton kernels are not used here. They are used elsewhere for:
  - Fused linear+activation (fused_linear_tanh, fused_siren_layer)
  - Post-training inference acceleration
  - NOT for derivative computation
"""

### Function: `rippl.compiler.router.get_route_diagnostics`
`def get_route_diagnostics() -> dict`
"""
Return info about what kernels are available for routing.
Used by rp.compiler_status().
"""

### Class: `rippl.compiler.symbolic.OperatorType`
Methods:

### Class: `rippl.compiler.symbolic.IRNode`
"""
Single node in the execution DAG.
"""
Methods:

### Class: `rippl.compiler.symbolic.ParsedEquation`
"""
Result of parsing a PDE string.
"""
Methods:

### Class: `rippl.compiler.symbolic.EquationRegistry`
Methods:
- `def __init__(self)`
- `def register_fields(self, *args)`
- `def register_parameters(self, *args)`

### Function: `rippl.compiler.symbolic.extract_equation_components`
`def extract_equation_components(eq_str: str, registry: EquationRegistry) -> Dict[str, set[str]]`
"""
Safely parses an equation string and bins symbols into their physical roles.
Prevents parameters from being compiled as model outputs.
"""

### Function: `rippl.compiler.symbolic.parse_pde_string`
`def parse_pde_string(pde_string: str, registry: EquationRegistry = None) -> ParsedEquation`
"""
Parse a PDE string into a structured representation.

Supports:
    Derivative(u(x,t), t)
    Derivative(u(x,t), (x, 2))
    Derivative(u, x, x)         (equivalent to (x,2))
    0.1 * Derivative(u, (x,2))
    Any combination with +, -, *, /

Returns ParsedEquation with all information needed
for code generation.
"""

### Function: `rippl.compiler.__init__.register_fields`
`def register_fields(*args)`
"""
Register physical fields globally before parsing.
"""

### Function: `rippl.compiler.__init__.register_parameters`
`def register_parameters(*args)`
"""
Register physical parameters globally before parsing.
"""

### Function: `rippl.compiler.__init__.parse`
`def parse(pde_string: str, guardrails: GuardrailConfig = DEFAULT_GUARDRAILS, verbose: bool = False) -> SymbolicEquation`
"""
Parse a PDE string into an executable SymbolicEquation.

This is the universal entry point for the rippl physics engine.
Any LLM, researcher, or automated pipeline can call this with
any valid PDE and get a working solver back.

Args:
    pde_string: Mathematical expression as a string.

        Supported notations:
          'Derivative(u(x,t), t) - 0.1*Derivative(u(x,t), (x,2))'
          'u_t - 0.1*u_xx'
          'laplacian(T)'
          'wave(u, c)'
          'div(grad(phi)) + k**2 * phi'

    guardrails: Safety limits. Default allows most valid physics.
                Use STRICT_GUARDRAILS for LLM-agent pipelines.
    verbose:    Print compilation info.

Returns:
    SymbolicEquation with .residual(fields, coords) method.
    Use directly in rp.run():
        result = rp.run(domain, eq, model, epochs=5000)

Raises:
    GuardrailViolation: If the equation violates safety limits.
    ValueError:         If the string cannot be parsed.
"""

### Function: `rippl.compiler.__init__.compiler_status`
`def compiler_status() -> None`
"""
Print the current compiler and engine status.
Shows what is available vs what requires a Foundry key.
"""

### Class: `rippl.config.models.OperatorConfig`
Methods:

### Class: `rippl.config.models.EquationConfig`
Methods:

### Class: `rippl.config.models.DomainConfig`
Methods:

### Class: `rippl.config.models.NetworkConfig`
Methods:

### Function: `rippl.config.models.generate_json_schemas`
`def generate_json_schemas(out_dir = 'schemas/')`

### Class: `rippl.core.api.RipplProRequired`
Methods:

### Class: `rippl.core.api.Solver`
Methods:
- `def __init__(self, dom, eq, m = None)`
- `def solve(self, mode = 'pinn', parametric = False, param_bounds = None, **kw)`

### Function: `rippl.core.api.authenticate`
`def authenticate(api_key: str)`

### Function: `rippl.core.api.compile`
`def compile(m, backend = 'inductor', mode = 'max-autotune')`

### Function: `rippl.core.api.upscale`
`def upscale(coarse, fno_model, target_points: int)`
"""
Physics DLSS (Deep Learning Super Resolution) primitive.
Takes a coarse field, interpolates it to target_points,
and runs the FNO model on the upscaled coordinates/field.
"""

### Class: `rippl.core.api.RunConfig`
Methods:
- `def validate(self)`
- `def from_kwargs(cls, **kwargs) -> 'RunConfig'`

### Function: `rippl.core.api.run`
`def run(domain, equation, model, config: 'RunConfig' = None, **kwargs)`
"""
Train a physics-informed neural network.

Two calling conventions:

1. Legacy (unchanged, fully compatible):
   result = rp.run(domain, eq, model, epochs=5000, causal=True)

2. Config object (new):
   cfg = RunConfig(epochs=5000, causal=True)
   result = rp.run(domain, eq, model, config=cfg)
"""

### Function: `rippl.core.api.run_coupled`
`def run_coupled(coupled_system: 'CoupledSystem', epochs: int = 10000, lr: float = 0.0005, mgda_freq: int = 100, lbfgs_steps: int = 500, log: bool = False, device: str = None) -> dict`
"""
Train a CoupledSystem with MGDA-balanced multiphysics gradients.

Each physics domain is a separate MGDA objective.
Frank-Wolfe finds the Pareto-optimal combination each mgda_freq steps.
Prevents one physics domain from dominating the other.

Args:
    coupled_system: CoupledSystem with equations, domains, models
    epochs:         training epochs
    lr:             learning rate
    mgda_freq:      how often to recompute MGDA weights
    lbfgs_steps:    L-BFGS fine-tuning after Adam
    log:            print progress

Returns:
    dict with 'models', 'loss_history', 'final_losses', 'mgda_weights'
"""

### Class: `rippl.core.artifact.ArtifactCompiler`
Methods:
- `def __init__(self, engine)`
- `def save(self, path: str, format = 'safetensors')`

### Class: `rippl.core.boundaries.GeometryIncompatibilityWarning`
Methods:

### Function: `rippl.core.boundaries.compile_boundary_conditions`
`def compile_boundary_conditions(geometry, ansatz_type)`

### Function: `rippl.core.boundaries.route_exact_ansatz`
`def route_exact_ansatz(geometry)`

### Function: `rippl.core.boundaries.route_sdf_penalty_pipeline`
`def route_sdf_penalty_pipeline(geometry)`

### Function: `rippl.core.config.register_operator`
`def register_operator(name: str)`
"""
Decorator to register a physics operator class.

Args:
    name: The string identifier for the operator (e.g., 'laplacian').
"""

### Function: `rippl.core.config.register_solver`
`def register_solver(name: str)`
"""
Decorator to register a numerical solver function.

Args:
    name: The string identifier for the solver (e.g., 'wave_fd').
"""

### Function: `rippl.core.config.get_operator_class`
`def get_operator_class(name: str) -> Type`
"""
Retrieve an operator class by name.
"""

### Function: `rippl.core.config.get_solver_fn`
`def get_solver_fn(name: str) -> Callable`
"""
Retrieve a solver function by name.
"""

### Class: `rippl.core.config.ConfigParser`
"""
Parser for Rippl configuration files (YAML/JSON).
Handles serialization and deserialization of the entire system state.
"""
Methods:
- `def load(path_or_dict: Union[str, Dict[str, Any]]) -> Dict[str, Any]`
  - Load configuration from a file path or a dictionary.
- `def save(config: Dict[str, Any], path: str)`
  - Save configuration to a file.

### Function: `rippl.core.describe.describe`
`def describe(target: Any)`
"""
Deterministic CLI profiler for Rippl objects.
Replaces deprecated generative physics logic with structural introspection.
"""

### Function: `rippl.core.distributed.is_single_cpu`
`def is_single_cpu()`

### Function: `rippl.core.distributed.synchronize_rar_firing`
`def synchronize_rar_firing()`

### Function: `rippl.core.distributed.all_reduce`
`def all_reduce(tensor)`

### Function: `rippl.core.distributed.all_gather`
`def all_gather(tensor_list, tensor)`

### Class: `rippl.core.engine.Engine`
Methods:
- `def __init__(self, net: Union[dict, torch.nn.Module])`
- `def compile(self, backend = 'triton', mode = 'max-autotune')`
- `def save(self, path: str, format = 'safetensors')`
- `def validate(self, render = False)`
- `def fit(self, epochs: int, mode = 'pinn', use_amp = False, multi_gpu = False, **kwargs)`

### Class: `rippl.core.equation.Equation`
Methods:
- `def __init__(self, terms: List[Union[Operator, Tuple[float, Operator]]], forcing = None)`
- `def compute_residual(self, u, inputs, spatial_dims = None)`
- `def residual(self, fields, coords)`
  - Satisfies the equation protocol. Delegates to existing logic.
- `def compute_pointwise_residual(self, flds, x)`

### Class: `rippl.core.equation_system.EquationSystem`
"""
Groups multiple Equation objects.

equations: List of Equation instances.
weights: Optional list of weights for each equation's loss contribution.
"""
Methods:
- `def __init__(self, equations: List[Equation], weights: Optional[List[float]] = None)`
- `def compute_residuals(self, fields: Dict[str, torch.Tensor], coords: torch.Tensor, spatial_dims: int = None) -> List[torch.Tensor]`
  - Compute residuals for all equations in the system simultaneously.
- `def compute_loss(self, fields: Dict[str, torch.Tensor], coords: torch.Tensor, spatial_dims: int = None) -> torch.Tensor`
  - Calculate the scalar weighted MSE loss across all system residuals.

### Class: `rippl.core.exceptions.RipplError`
"""
Base exception for Rippl.
"""
Methods:

### Class: `rippl.core.exceptions.RipplValidationError`
"""
Raised when system validation fails.
"""
Methods:

### Class: `rippl.core.exceptions.PhysicsModelWarning`
"""
Warning for physics modeling issues.
"""
Methods:

### Class: `rippl.core.experiment.Experiment`
Methods:
- `def __init__(self, system: System, model, opt, use_hard_constraints: bool = False, adaptive_collocation: bool = False, causal_training: bool = False, causal_mode: str = 'continuous', causal_epsilon: Optional[float] = None, causal_bins: int = 10, adaptive_loss: bool = False, adaptive_loss_mode: str = 'gradient_norm', adaptive_loss_freq: int = 100, adaptive_loss_alpha: float = 0.9, conservation_laws: Optional[List] = None, validate: bool = False)`
- `def train(self, coords: torch.Tensor, epochs: int = 1, ntk_freq: int = 500, patience: int = 200, logger: Any = None, params: Dict[str, torch.Tensor] = None) -> Dict[str, Any]`
  - Run the training loop with Lazy NTK weighting and dynamic L-BFGS handoff.

### Class: `rippl.core.inverse.InverseParameter`
"""
Learnable PDE parameter as bounded nn.Parameter.
Supports transforms to ensure physical constraints (positivity, bounds).
"""
Methods:
- `def __init__(self, name: str, initial_value: float, bounds: tuple = None, transform: str = 'none', units: str = '')`
- `def get(self) -> torch.Tensor`
- `def bounds_penalty(self) -> torch.Tensor`

### Class: `rippl.core.inverse.DigitalTwin`
"""
Digital Twin interface: identify PDE parameters from sensor data.
"""
Methods:
- `def __init__(self, system, model, parameters: list, sensor_coords: torch.Tensor = None, sensor_fields: dict = None, data_weight: float = 1.0, physics_weight: float = 1.0)`
- `def from_csv(cls, system, model, parameters, csv_path: str, coord_cols: list, field_cols: dict, **kwargs)`
  - Load sensor data from CSV.
- `def train(self, epochs: int = 5000, lr: float = 0.001, use_recipe: bool = True) -> dict`
  - Joint optimization: model params + InverseParameter values.
- `def report(self) -> dict`
  - Returns identified parameter values with units.

### Class: `rippl.core.inverse.InverseProblem`
Methods:
- `def __init__(self, system, model, parameters: list, observed_coords: torch.Tensor, observed_values: dict, data_weight: float = 1.0)`
- `def train(self, epochs: int = 5000, lr: float = 0.001)`
- `def result(self)`

### Class: `rippl.core.nondim.ReferenceScales`
"""
Characteristic scales for non-dimensionalization.
All inputs normalized to O(1) before optimizer sees them.
All outputs denormalized before returning to user.
"""
Methods:
- `def __init__(self, L_ref: float = 1.0, U_ref: float = 1.0, T_ref: float = None, P_ref: float = None, rho_ref: float = 1.0, mu_ref: float = None, phi_ref: float = 1.0)`
- `def normalize_coords(self, coords: torch.Tensor, has_time: bool = True) -> torch.Tensor`
- `def denormalize_coords(self, coords: torch.Tensor, has_time: bool = True) -> torch.Tensor`
- `def normalize_field(self, field: torch.Tensor, field_type: str = 'generic') -> torch.Tensor`
- `def denormalize_field(self, field: torch.Tensor, field_type: str = 'generic') -> torch.Tensor`
- `def reynolds_number(self) -> float`
- `def report(self) -> dict`

### Class: `rippl.core.nondim.NondimSystem`
"""
Wraps System with automatic normalization/denormalization.
Intercepts coords before passing to model.
Denormalizes output before returning.
"""
Methods:
- `def __init__(self, system, scales: ReferenceScales)`
- `def normalize_constraints(self) -> list`
- `def wrap_model(self, model: torch.nn.Module) -> torch.nn.Module`

### Class: `rippl.core.nondim.NondimModelWrapper`
Methods:
- `def __init__(self, model, scales: ReferenceScales, has_time: bool = True, field_types: dict = None)`
- `def forward(self, coords: torch.Tensor)`

### Class: `rippl.core.nondim.AutoScaler`
Methods:
- `def __init__(self, L0: float = 1.0, U0: float = 1.0, T0: float = None, spatial_dims: int = None)`
- `def from_domain_equation(cls, domain, equation) -> 'AutoScaler'`
- `def get_state(self) -> dict`
- `def scale_inputs(self, coords: torch.Tensor) -> torch.Tensor`
- `def scale_outputs(self, u: Union[torch.Tensor, Dict[str, torch.Tensor]]) -> Union[torch.Tensor, Dict[str, torch.Tensor]]`

### Class: `rippl.core.operator_experiment.OperatorDataset`
Methods:
- `def __init__(self, input_functions: torch.Tensor, output_functions: torch.Tensor)`
- `def get_batch(self, batch_size) -> tuple`

### Class: `rippl.core.operator_experiment.OperatorExperiment`
Methods:
- `def __init__(self, model, dataset, system = None)`
- `def from_flywheel(cls, flywheel)`
  - Constructs OperatorExperiment from a trained flywheel's dataset.
- `def train(self, epochs = 1000, lr = 0.001, physics_weight = 0.0)`

### Class: `rippl.core.simulation.Simulation`
"""
Drives a System forward in time using the existing FD solvers.

Parameters
----------
system  : System  (domain.spatial_dims must be 1 or 2)
c       : wave speed
dt, dx  : time / spatial step
dy      : spatial step for 2-D (ignored in 1-D)
"""
Methods:
- `def __init__(self, system: System, tol: float = 0.01, seed: Optional[int] = None)`
- `def run(self, u0: torch.Tensor, v0: torch.Tensor, steps: int = 10, dt: float = 0.01) -> dict`
- `def visualize(trajectory: torch.Tensor, title: str = 'Wave field', interval: int = 80, repeat: bool = True) -> None`
  - Animate a trajectory tensor.

### Function: `rippl.core.simulation.run_system`
`def run_system(system: System, mode: str = 'sim', **kwargs)`
"""
High-level entry point for Rippl.

sim: returns trajectory tensor (B, T, ...)
exp: returns scalar loss
"""

### Function: `rippl.core.solver_registry.get_solver`
`def get_solver(equation)`
"""
Returns (solver_fn, extra_kwargs).
"""

### Function: `rippl.core.solver_registry.select_solver`
`def select_solver(equation) -> str`
"""
Inspect equation.terms and return a solver key.

Returns one of: 'wave', 'diffusion', 'advection', 'advdiff'
Raises NotImplementedError for unrecognised configurations.
"""

### Class: `rippl.core.system.IntConstraint`
Methods:

### Class: `rippl.core.system.Domain`
Methods:
- `def __init__(self, spatial_dims: int = 1, bounds: Optional[List[Tuple[float, float]]] = None, resolution: Optional[List[int]] = None, **kwargs)`
- `def build_grid(self, device = 'cpu')`
- `def generate_loader(self, batch_size = 2048, meth = 'sobol', sdf = None)`

### Class: `rippl.core.system.Constraint`
Methods:

### Class: `rippl.core.system.NeumannConstraint`
Methods:

### Class: `rippl.core.system.MovingBoundaryConstraint`
Methods:
- `def __init__(self, field: str, boundary_fn: Callable[[int, Optional[torch.nn.Module]], torch.Tensor], value: Union[Callable, torch.Tensor], type: str = 'dirichlet')`
- `def update(self, epoch: int, model: Optional[torch.nn.Module] = None)`

### Class: `rippl.core.system.System`
Methods:
- `def __init__(self, equation: Any, domain: Domain, constraints: Optional[List[Union[Constraint, NeumannConstraint]]] = None, fields: Optional[List[str]] = None, particular_solution: Optional[Callable] = None, scales: Optional['ReferenceScales'] = None)`
- `def validate_fields(self, field_dict: Dict[str, torch.Tensor]) -> None`
- `def validate(self) -> bool`
- `def set_seed(self, seed: Optional[int] = None)`
- `def summary(self) -> None`
- `def from_config(cls, config: Dict[str, Any]) -> 'System'`
- `def to_config(self) -> Dict[str, Any]`

### Class: `rippl.core.system.CoupledSystem`
"""
Native multiphysics coupling with MGDA gradient balancing.

Manages multiple physics domains that share boundary interfaces.
Routes competing loss gradients through MGDA Frank-Wolfe to find
Pareto-optimal update directions — physics domains don't fight each other.

Design principles:
1. Each physics domain has its own Equation and Domain
2. Shared interfaces are defined explicitly (fluid-solid boundary etc.)
3. Loss from each domain is a separate MGDA objective
4. The MGDA Gram matrix is computed in one fused kernel call

Example: Conjugate Heat Transfer (fluid + solid)
    fluid_eq  = Equation([NavierStokes(nu=1e-3)])
    solid_eq  = Equation([HeatDiffusion(alpha=1e-4)])
    fluid_dom = Domain(spatial_dims=2, bounds=[(0,1),(0.5,1)])
    solid_dom = Domain(spatial_dims=2, bounds=[(0,1),(0,0.5)])
    
    coupled = CoupledSystem(
        equations={'fluid': fluid_eq, 'solid': solid_eq},
        domains={'fluid': fluid_dom, 'solid': solid_dom},
        interfaces=[
            Interface(
                domain_a='fluid', domain_b='solid',
                location='y=0.5',
                conditions=['temperature_continuity', 'heat_flux_continuity']
            )
        ],
        models={'fluid': fluid_model, 'solid': solid_model},
    )
    result = rp.run_coupled(coupled, epochs=10000)
"""
Methods:
- `def __init__(self, equations: dict, domains: dict, models: dict, interfaces: list = None, constraints: dict = None, fields: dict = None, mgda_update_freq: int = 100)`
- `def compute_coupled_losses(self, coords_dict: dict, device) -> dict`
  - Compute per-domain physics losses + interface coupling losses.
- `def mgda_weights(self, losses: dict, all_params: list) -> dict`
  - Compute MGDA Pareto-optimal weights for all physics objectives.
- `def all_parameters(self) -> list`
  - Collect parameters from all domain models.

### Class: `rippl.core.system.Interface`
"""
Shared boundary between two physics domains.

Defines geometric location and physical coupling conditions.

Args:
    name:            identifier for this interface
    domain_a:        first domain name
    domain_b:        second domain name
    location:        geometric description ('y=0.5', 'x=1.0', etc.)
    conditions:      list of coupling conditions to enforce
    normal_direction_idx: 0=x, 1=y, 2=z for flux computations
"""
Methods:
- `def __init__(self, name: str, domain_a: str, domain_b: str, location: str, conditions: list = None, normal_direction_idx: int = 1)`
- `def sample_points(self, n: int = 500, n_dims: int = 2) -> 'torch.Tensor'`
  - Sample points on this interface.

### Class: `rippl.data.sensor.SensorDataset`
"""
Loads and preprocesses sensor data for PINN training.
Supports CSV, numpy arrays, torch tensors.
"""
Methods:
- `def __init__(self, coords: torch.Tensor, fields: dict, fidelity: float = 1.0, noise_std: float = 0.0)`
- `def from_csv(cls, path: str, coord_cols: list, field_cols: dict, fidelity: float = 1.0, noise_std: float = 0.0, filter_outliers: bool = True) -> 'SensorDataset'`
- `def from_numpy(cls, coords: np.ndarray, fields: dict, **kwargs) -> 'SensorDataset'`
- `def data_loss(self, model, device: str = 'cpu') -> torch.Tensor`
  - Weighted MSE loss between model predictions and sensor values.
- `def split(self, train_frac: float = 0.8) -> tuple`

### Class: `rippl.data.sensor.MultiFidelityFusion`
"""
Fuses multiple SensorDataset instances at different fidelity levels
with PDE physics loss.
"""
Methods:
- `def __init__(self, datasets: list, physics_weight: float = 1.0, auto_balance: bool = True)`
- `def total_data_loss(self, model, device = 'cpu') -> torch.Tensor`
- `def fusion_loss(self, model, physics_loss: torch.Tensor, device = 'cpu') -> torch.Tensor`

### Function: `rippl.datasets.generators.generate_sine_wave`
`def generate_sine_wave(grid: torch.Tensor, frequency: float = 1.0, phase: float = 0.0, amplitude: float = 1.0) -> torch.Tensor`
"""
Generate a sine wave on the given grid.

Args:
    grid (torch.Tensor): Spatial grid points. Shape (B, N, D) or (N, D).
    frequency (float): Frequency of the wave.
    phase (float): Phase shift.
    amplitude (float): Amplitude of the wave.
    
Returns:
    torch.Tensor: Sine wave values. Shape matches grid shape excluding last dim implies (B, N, 1) usually.
                  Assuming we want scalar field u(x), so (..., 1).
"""

### Function: `rippl.datasets.generators.generate_gaussian_bump`
`def generate_gaussian_bump(grid: torch.Tensor, center: Union[float, torch.Tensor] = 0.0, width: float = 0.1, amplitude: float = 1.0) -> torch.Tensor`
"""
Generate a Gaussian bump.

Args:
    grid (torch.Tensor): Spatial grid (..., D).
    center (float | torch.Tensor): Center position.
    width (float): Gaussian sigma/width.
    amplitude (float): Peak amplitude.
    
Returns:
    torch.Tensor: Gaussian values (..., 1).
"""

### Class: `rippl.deploy.deployment.DeploymentResult`
"""
Result of rp.deploy().

Attributes:
    backend:     Which backend was used (local/foundry/byoc)
    rpx_path:    Path to the sealed .rpx file (always present)
    url:         Inference endpoint URL (foundry backend)
    job_id:      K8s job ID (byoc backend)
    description: Human-readable deployment description
"""
Methods:
- `def predict(self, coords) -> 'np.ndarray'`
  - Run inference.

### Function: `rippl.deploy.deployment.deploy`
`def deploy(result, backend: str = 'local', rpx_path: str = None, description: str = '', cluster_config: Dict = None) -> DeploymentResult`
"""
Deploy a trained rippl model.

The seventh line of the API:
    domain   = rp.Domain(...)
    equation = rp.parse("...")
    model    = rnn.MLP(...)
    result   = rp.run(domain, equation, model, epochs=5000)
    endpoint = rp.deploy(result)

All deployment paths go through the .rpx format.
The .rpx file is encrypted and can only be executed
via the Foundry binary — not inspected or unpacked independently.

Args:
    result:         Output from rp.run()
    backend:        Where to deploy:
                      'local'   — HF Accelerate optimized local
                      'foundry' — Foundry managed endpoint
                      'byoc'    — Bring Your Own K8s Cluster
    rpx_path:       Where to save the .rpx file.
                    Defaults to ./rippl_artifacts/deploy.rpx
    description:    Stored in the .rpx metadata.
    cluster_config: K8s config for byoc backend.
                      {'namespace': 'rippl', 'gpu_type': 'A100',
                       'replicas': 1, 'kubeconfig': '~/.kube/config'}

Returns:
    DeploymentResult with .predict(coords) method.
"""

### Function: `rippl.diagnostics.energy.wave_energy`
`def wave_energy(u: torch.Tensor, v: torch.Tensor, c: float, dx: float, dim: int = 1) -> torch.Tensor`
"""
Compute the energy functional for the wave equation:
E = 0.5 * integral( u_t^2 + c^2 * |grad u|^2 ) dx

Args:
    u (torch.Tensor): Displacement field (B, N, 1).
    v (torch.Tensor): Velocity field u_t (B, N, 1).
    c (float): Wave speed.
    dx (float): Spatial step size.
    dim (int): Spatial dimensionality (implied 1D for now given shape).
    
Returns:
    torch.Tensor: Energy per batch item (B, 1).
"""

### Function: `rippl.diagnostics.metrics.l2_error`
`def l2_error(pred: torch.Tensor, target: torch.Tensor) -> float`
"""
Compute L2 error (Euclidean distance) between prediction and target.

Args:
    pred (torch.Tensor): Prediction tensor.
    target (torch.Tensor): Target tensor.
    
Returns:
    float: L2 error.
"""

### Function: `rippl.diagnostics.metrics.relative_l2_error`
`def relative_l2_error(pred: torch.Tensor, target: torch.Tensor, epsilon: float = 1e-08) -> float`
"""
Compute Relative L2 error: ||pred - target|| / ||target||.

Args:
    pred (torch.Tensor): Prediction.
    target (torch.Tensor): Target.
    epsilon (float): Small value to avoid division by zero.
    
Returns:
    float: Relative L2 error.
"""

### Class: `rippl.diagnostics.physics_validator.PhysicsValidator`
"""
Validator for PDE residuals, constraints, and conservation laws.
"""
Methods:
- `def __init__(self, system: System, model: torch.nn.Module, coords: torch.Tensor)`
- `def residual_stats(self) -> Dict[str, Any]`
  - Compute statistics for PDE residuals.
- `def constraint_satisfaction(self) -> Dict[int, Dict[str, Any]]`
  - Compute error for each constraint.
- `def conservation_check(self, laws: List, time_coords: torch.Tensor) -> Dict[str, Dict[str, Any]]`
  - Check conservation laws over time.
- `def full_report(self) -> Dict[str, Any]`
  - Runs all checks and prints formatted summary.
- `def export_report(self, path: str)`
  - Saves full_report() as JSON.
- `def extrapolation_warning(self, query_coords: torch.Tensor, threshold: float = 0.1) -> dict`

### Function: `rippl.diagnostics.spectral.spectral_error`
`def spectral_error(pred: torch.Tensor, target: torch.Tensor) -> float`
"""
Compute Relative L2 error in the frequency domain.
Useful for checking if high-frequency content is captured.

Args:
    pred (torch.Tensor): (B, N, ...)
    target (torch.Tensor): (B, N, ...)

Returns:
    float: Relative spectral error.
"""

### Function: `rippl.examples.advdiff_1d.main`
`def main()`

### Function: `rippl.examples.advection_1d.main`
`def main()`

### Function: `rippl.examples.burgers.run_burgers`
`def run_burgers()`

### Function: `rippl.examples.damped_wave.run_damped_wave`
`def run_damped_wave()`

### Function: `rippl.examples.diffusion_1d.main`
`def main()`

### Class: `rippl.examples.pinn_wave_1d.MLP`
Methods:
- `def forward(self, x, t)`

### Function: `rippl.examples.reaction_diffusion.run_rd_demo`
`def run_rd_demo()`

### Function: `rippl.export.exporter.export_model`
`def export_model(model: torch.nn.Module, path: str, format: str = 'torchscript', metadata: Optional[Dict[str, Any]] = None)`
"""
Export a trained Rippl model for production inference.
Handles TorchScript and ONNX formats, and generates a Model Card.

Args:
    model: The trained neural network to export.
    path: Directory where exported artifacts will be saved.
    format: Export format, either 'torchscript' (default) or 'onnx'.
    metadata: Optional dictionary containing 'pde', 'config', 'scales', and other model info.
"""

### Function: `rippl.export.quantize.quantize_model`
`def quantize_model(model: torch.nn.Module, calib_data: torch.Tensor, backend: str = 'fbgemm')`
"""
Performs INT8 static quantization on the PINN model.
Fuses Linear and Tanh layers for edge deployment.
"""

### Function: `rippl.export.quantize.export_rpx`
`def export_rpx(model: torch.nn.Module, path: str, calib_data: torch.Tensor, meta: Optional[Dict[str, Any]] = None)`
"""
Exports a quantized model as a .rpx (compressed JIT) artifact.
"""

### Class: `rippl.export.rpx.RPXFile`
"""
rippl eXecution Package v2.

Usage:
    # Save a training result
    rpx = RPXFile.from_result(
        result=result,
        equation=eq,
        domain=domain,
        description="Heat sink thermal analysis",
        tags=['thermal', 'aerospace'],
    )
    rpx.save('heat_sink.rpx', compile_model=True)
    
    # Load and inspect
    rpx = RPXFile.load('heat_sink.rpx')
    print(rpx.summary())
    
    # Get model for inference
    predictor = rpx.get_predictor()
    T = predictor(query_coords)
    
    # Continue training
    model = rpx.get_model()
    result = rp.run(rpx.domain, rpx.equation, model, epochs=5000)
    
    # In CLI — replay workflow
    # $ rippl replay heat_sink.rpx
"""
Methods:
- `def __init__(self)`
- `def from_result(cls, result: dict, equation = None, domain = None, description: str = '', tags: list = None, workflow: list = None, training_kwargs: dict = None) -> 'RPXFile'`
- `def save(self, path: str, compile_model: bool = False, quantize: bool = False, encrypt_payload: bool = False, encrypt_key: Optional[bytes] = None) -> str`
  - Save .rpx archive.
- `def load(cls, path: str) -> 'RPXFile'`
  - Load .rpx archive.
- `def get_model(self, decrypt_key: Optional[bytes] = None) -> torch.nn.Module`
  - Reconstruct model from architecture + weights.
- `def get_predictor(self, decrypt_key: Optional[bytes] = None)`
  - Get inference-ready model.
- `def domain(self)`
- `def equation(self)`
- `def get_equation(self)`
  - Get the equation that produced this .rpx.
- `def loss_history(self)`
- `def final_loss(self)`
- `def tags(self)`
- `def workflow(self)`
- `def summary(self) -> str`
  - Human-readable summary of .rpx contents.

### Function: `rippl.export.rpx.reconstruct_equation_from_ir`
`def reconstruct_equation_from_ir(ir_data: dict)`
"""
Reconstruct an executable equation from stored IR.

This is what makes .rpx files architecture-agnostic:
load the IR on any hardware, recompile for that hardware,
get the correct equation without retraining.
"""

### Function: `rippl.export.rpx.save_rpx`
`def save_rpx(result_or_model, path: str, equation = None, domain = None, description: str = '', tags: list = None, workflow: list = None, compile_model: bool = False) -> str`
"""
Save a result or model as .rpx. Quick convenience wrapper.
"""

### Function: `rippl.export.rpx.load_rpx`
`def load_rpx(path: str) -> RPXFile`
"""
Load .rpx file.
"""

### Class: `rippl.export.schema.RPXHeader`
"""
Parsed .rpx binary header.

Always 52 bytes. Prepended to the ZIP payload.
Never changes after creation (immutable).
"""
Methods:
- `def pack(self) -> bytes`
  - Serialize to 52 bytes.
- `def unpack(cls, data: bytes) -> 'RPXHeader'`
  - Deserialize from bytes.
- `def validate(self, context: str = '') -> None`
  - Validate header fields. Raises ValueError on any problem.
- `def is_encrypted(self) -> bool`
- `def is_compiled(self) -> bool`
- `def is_quantized(self) -> bool`
- `def has_ir(self) -> bool`
- `def is_signed(self) -> bool`
- `def set_flag(self, flag: int) -> 'RPXHeader'`
  - Return a new header with flag set.

### Function: `rippl.export.schema.compute_checksum`
`def compute_checksum(payload: bytes) -> bytes`
"""
SHA-256 checksum of payload bytes. Returns 32 bytes.
"""

### Function: `rippl.export.schema.verify_checksum`
`def verify_checksum(payload: bytes, expected: bytes) -> bool`
"""
Constant-time checksum comparison.
"""

### Function: `rippl.export.schema.make_header`
`def make_header(payload: bytes, encrypted: bool = False, compiled: bool = False, ir_stored: bool = False) -> RPXHeader`
"""
Build a complete RPXHeader for a payload.

Computes checksum from payload automatically.
Sets flags based on what features are present.
"""

### Function: `rippl.export.schema.detect_format`
`def detect_format(data: bytes) -> str`
"""
Detect whether file data is v2 (binary header) or legacy (ZIP).

Returns: 'v2', 'legacy_zip', 'unknown'
"""

### Function: `rippl.export.__init__.save_rpx`
`def save_rpx(model, path: str, metadata: dict = None)`

### Function: `rippl.export.__init__.load_rpx`
`def load_rpx(path: str) -> tuple`

### Class: `rippl.geometry.csg.Shape`
"""
Abstract base class for all CSG shapes.
"""
Methods:
- `def contains(self, points: torch.Tensor) -> torch.Tensor`
- `def sample_boundary(self, n: int) -> torch.Tensor`
- `def bounding_box(self) -> List[Tuple[float, float]]`

### Class: `rippl.geometry.csg.Circle`
Methods:
- `def __init__(self, center = 0.0, 0.0, radius = 1.0)`
- `def contains(self, points: torch.Tensor) -> torch.Tensor`
- `def bounding_box(self)`
- `def sample_boundary(self, n: int) -> torch.Tensor`

### Class: `rippl.geometry.csg.Rectangle`
Methods:
- `def __init__(self, x_min = 0.0, x_max = 1.0, y_min = 0.0, y_max = 1.0)`
- `def contains(self, points: torch.Tensor) -> torch.Tensor`
- `def bounding_box(self)`
- `def sample_boundary(self, n: int) -> torch.Tensor`

### Class: `rippl.geometry.csg.Sphere`
Methods:
- `def __init__(self, center = 0.0, 0.0, 0.0, radius = 1.0)`
- `def contains(self, points: torch.Tensor) -> torch.Tensor`
- `def bounding_box(self)`
- `def sample_boundary(self, n: int) -> torch.Tensor`

### Class: `rippl.geometry.csg.Box`
Methods:
- `def __init__(self, x_min = 0, x_max = 1, y_min = 0, y_max = 1, z_min = 0, z_max = 1)`
- `def contains(self, points: torch.Tensor) -> torch.Tensor`
- `def bounding_box(self)`
- `def sample_boundary(self, n: int) -> torch.Tensor`

### Class: `rippl.geometry.csg.Annulus`
Methods:
- `def __init__(self, center = 0.0, 0.0, r_inner = 0.5, r_outer = 1.0)`
- `def contains(self, points: torch.Tensor) -> torch.Tensor`
- `def bounding_box(self)`
- `def sample_boundary(self, n: int) -> torch.Tensor`

### Class: `rippl.geometry.csg.Ellipse`
Methods:
- `def __init__(self, center = 0.0, 0.0, a = 1.0, b = 0.5)`
- `def contains(self, points: torch.Tensor) -> torch.Tensor`
- `def bounding_box(self)`
- `def sample_boundary(self, n: int) -> torch.Tensor`

### Class: `rippl.geometry.csg.Union`
Methods:
- `def __init__(self, a, b)`
- `def contains(self, p)`
- `def bounding_box(self)`
- `def sample_boundary(self, n)`

### Class: `rippl.geometry.csg.Intersection`
Methods:
- `def __init__(self, a, b)`
- `def contains(self, p)`
- `def bounding_box(self)`
- `def sample_boundary(self, n)`

### Class: `rippl.geometry.csg.Difference`
Methods:
- `def __init__(self, a, b)`
- `def contains(self, p)`
- `def bounding_box(self)`
- `def sample_boundary(self, n)`

### Class: `rippl.geometry.csg.Complement`
Methods:
- `def __init__(self, shape)`
- `def contains(self, p)`
- `def bounding_box(self)`

### Class: `rippl.geometry.csg.BoundingBoxTree`
Methods:
- `def __init__(self, shape)`
- `def quick_reject(self, points: torch.Tensor) -> torch.Tensor`

### Class: `rippl.geometry.csg.CSGSampler`
Methods:
- `def __init__(self, shape: Shape, spatial_dims: int = 2)`
- `def sample_interior(self, n: int, method = 'sobol') -> torch.Tensor`
- `def sample_boundary(self, n: int) -> torch.Tensor`
- `def sample_with_time(self, n: int, t_range = 0, 1, method = 'sobol') -> torch.Tensor`
- `def estimate_volume(self, n_total = 100000) -> float`

### Class: `rippl.geometry.csg.CSGDomain`
Methods:
- `def __init__(self, shape: Shape, spatial_dims: int, t_range = 0, 1, resolution = None)`
- `def get_sampler(self) -> CSGSampler`
- `def to_collocation_points(self, n: int, has_time = True) -> torch.Tensor`

### Class: `rippl.geometry.csg.BoxSDF`
"""
Signed Distance Function for axis-aligned box.
Returns negative inside, positive outside.
Normal vectors and curvature available for adaptive sampling.
"""
Methods:
- `def __init__(self, bounds: list)`
- `def sdf(self, points: torch.Tensor) -> torch.Tensor`
  - (N, D) → (N, 1) signed distance. Negative inside.
- `def normal(self, points: torch.Tensor) -> torch.Tensor`
  - Outward unit normal at boundary points. (N, D)
- `def sample_interior(self, n: int) -> torch.Tensor`
- `def sample_boundary(self, n: int) -> torch.Tensor`

### Class: `rippl.geometry.csg.SphereSDF`
"""
Signed Distance Function for N-sphere.
2D: circle. 3D: sphere.
"""
Methods:
- `def __init__(self, center: tuple = 0.0, 0.0, radius: float = 1.0)`
- `def sdf(self, points: torch.Tensor) -> torch.Tensor`
  - (N, D) → (N, 1). Negative inside sphere.
- `def normal(self, points: torch.Tensor) -> torch.Tensor`
  - Outward unit normal. (N, D)
- `def curvature(self) -> float`
  - Mean curvature = 1/radius (constant for sphere).
- `def sample_interior(self, n: int) -> torch.Tensor`
- `def sample_boundary(self, n: int) -> torch.Tensor`

### Function: `rippl.io.checkpoint.save_checkpoint`
`def save_checkpoint(model: nn.Module, optimizer: Optional[optim.Optimizer], epoch: int, path: Union[str, Path], extra_data: Dict[str, Any] = Any) -> None`
"""
Save model and optimizer state to a file.

Args:
    model (nn.Module): The model to save.
    optimizer (Optional[optim.Optimizer]): The optimizer to save.
    epoch (int): Current epoch.
    path (Union[str, Path]): Path to save the checkpoint.
    extra_data (Dict[str, Any]): Additional data to save.
"""

### Function: `rippl.io.checkpoint.load_checkpoint`
`def load_checkpoint(model: nn.Module, optimizer: Optional[optim.Optimizer], path: Union[str, Path]) -> Dict[str, Any]`
"""
Load model and optimizer state from a file.

Args:
    model (nn.Module): Model to load weights into.
    optimizer (Optional[optim.Optimizer]): Optimizer to load state into.
    path (Union[str, Path]): Path to the checkpoint file.
    
Returns:
    Dict[str, Any]: The full checkpoint dictionary (including epoch, etc).
    
Raises:
    FileNotFoundError: If checkpoint file does not exist.
"""

### Function: `rippl.io.export.export_torchscript`
`def export_torchscript(model: nn.Module, sample_input: torch.Tensor, path: Union[str, Path]) -> None`
"""
Export model to TorchScript (Tracing).
"""

### Function: `rippl.io.export.export_onnx`
`def export_onnx(model: nn.Module, sample_input: torch.Tensor, path: Union[str, Path]) -> None`
"""
Export model to ONNX.
"""

### Function: `rippl.io.export.write_model_card`
`def write_model_card(config: Dict[str, Any], metrics: Dict[str, float], path: Union[str, Path]) -> None`
"""
Write a model card JSON file.
"""

### Function: `rippl.io.generic.from_arrays_with_edges`
`def from_arrays_with_edges(coords: np.ndarray, fields: Dict[str, np.ndarray], edges: Optional[np.ndarray] = None) -> Dict[str, Any]`
"""
Ingests array data with explicit topology/mesh edge index representation.
"""

### Class: `rippl.io.ingest.RipplIngestionPipeline`
"""
Converts arbitrary client data into rippl-native context.

Auto-detects input format from file extension and content.
Returns a canonical context dict ready for the Architecture Agent
or for direct use in a Python engagement script.

Usage:
    # From a file
    pipeline = RipplIngestionPipeline.from_file('/path/to/mesh.stl')
    context  = pipeline.to_rippl()
    domain   = context['domain']
    
    # From a vendor API (PyANSYS, PyFoam, etc.)
    pipeline = RipplIngestionPipeline.from_vendor_api('ansys', session=mapdl)
    context  = pipeline.to_rippl()
    
    # From multiple files
    pipeline = RipplIngestionPipeline()
    pipeline.add_geometry('/path/to/part.stl')
    pipeline.add_boundary_conditions('/path/to/bcs.csv')
    pipeline.add_materials({'steel': {'E': 210e9, 'nu': 0.3}})
    context = pipeline.to_rippl()
"""
Methods:
- `def __init__(self)`
- `def from_file(cls, path: str) -> 'RipplIngestionPipeline'`
  - Auto-detect format and ingest a single file.
- `def from_vendor_api(cls, vendor: str, **kwargs) -> 'RipplIngestionPipeline'`
  - Connect to a vendor's Python API to extract geometry and BCs.
- `def add_geometry(self, path: str) -> 'RipplIngestionPipeline'`
  - Add geometry from a CAD file (STL, STEP, OBJ).
- `def add_boundary_conditions(self, path_or_dict: Union[str, dict]) -> 'RipplIngestionPipeline'`
  - Add boundary conditions from CSV, JSON, or dict.
- `def add_materials(self, materials: dict) -> 'RipplIngestionPipeline'`
  - Add material property dictionary.
- `def add_field_data(self, path: str, field_name: str = None) -> 'RipplIngestionPipeline'`
  - Add existing simulation field data for warm start.
- `def to_rippl(self) -> dict`
  - Convert all ingested data to canonical rippl context.
- `def to_solver_context(self) -> str`
  - JSON string for Architecture Agent consumption.

### Function: `rippl.io.readers.from_csv`
`def from_csv(path: str, coord_cols: list = None, field_cols: list = None, bc_value_col: str = None) -> dict`
"""
Read CSV file into rippl-compatible dict.

Auto-detects coordinate columns (x, y, z, t) and field columns.

Returns:
    {
      'coords':   (N, d) numpy array,
      'fields':   {name: (N,) array},
      'bc_mask':  (N,) bool array or None,
    }
"""

### Function: `rippl.io.readers.from_hdf5`
`def from_hdf5(path: str, coord_key: str = 'coordinates', field_keys: list = None, bc_key: str = None) -> dict`
"""
Read HDF5 file into rippl-compatible dict.

Covers: OpenFOAM exports, FEniCS outputs, Fluent HDF5, custom telemetry.

Returns same dict structure as from_csv.
"""

### Function: `rippl.io.readers.from_vtk`
`def from_vtk(path: str) -> dict`
"""
Read VTK/VTU file into rippl-compatible dict.

Covers: OpenFOAM post-processing, ParaView exports, ANSYS results.
"""

### Function: `rippl.io.readers.from_json`
`def from_json(path: str) -> dict`
"""
Read JSON specification file.

Handles:
- BC specifications: {'boundary_conditions': [{'type': 'dirichlet', 'value': 0.0, 'coords': [...]}]}
- Material databases: {'materials': {'steel': {'E': 210e9, 'nu': 0.3}}}
- Problem specifications: {'equation': '...', 'domain': {...}}
"""

### Function: `rippl.io.readers.from_stl`
`def from_stl(path: str) -> dict`
"""
Read STL geometry file.

Returns geometry dict suitable for CADGeometry processing.
"""

### Function: `rippl.io.writers.to_csv`
`def to_csv(coords: np.ndarray, fields: Dict[str, np.ndarray], path: str, coord_names: list = None) -> str`
"""
Write simulation results to CSV.
"""

### Function: `rippl.io.writers.to_hdf5`
`def to_hdf5(coords: np.ndarray, fields: Dict[str, np.ndarray], path: str, metadata: dict = None) -> str`
"""
Write simulation results to HDF5.
"""

### Function: `rippl.io.writers.to_vtk`
`def to_vtk(coords: np.ndarray, fields: Dict[str, np.ndarray], path: str) -> str`
"""
Write simulation results to VTK for ParaView visualization.
"""

### Function: `rippl.kernels.dispatch.register_op`
`def register_op(signature: str, cuda_fn, cpu_fn, meta_fn, feature: Optional[str] = None)`
"""
Register one rippl kernel in the dispatch table.

Args:
    signature:  torch op signature string
                e.g. "fused_laplacian_1d(Tensor u, float dx) -> Tensor"
    cuda_fn:    Triton implementation (fires on CUDA tensors)
    cpu_fn:     PyTorch fallback (fires on CPU tensors)
    meta_fn:    shape inference (fires during torch.compile tracing)
    feature:    auth feature name (None = free, no gate)

The CUDA implementation automatically checks auth.
If auth fails: runs cpu_fn on GPU (correct, slower).
If auth passes: runs cuda_fn (Triton, fast).
"""

### Function: `rippl.kernels.dispatch.register_autograd`
`def register_autograd(op_name: str, backward_fn)`
"""
Register backward pass for a rippl op.
Required for ops that appear in the training graph.

Most physics kernels are applied to detached tensors
(reference solver data, RAR residuals) so backward
is not needed. Only neural network layer kernels need this.
"""

### Function: `rippl.kernels.oss_kernels.fused_linear_tanh`
`def fused_linear_tanh(x, w, b = None)`

### Function: `rippl.kernels.oss_kernels.fused_linear_gelu`
`def fused_linear_gelu(x, w, b = None)`

### Function: `rippl.kernels.oss_kernels.fused_causal_weights`
`def fused_causal_weights(residuals: torch.Tensor, times: torch.Tensor, eps: float = 1.0, n_bins: int = 100) -> torch.Tensor`
"""
Fused continuous causal weight computation.

w_i = exp(-eps * Σ_{j: t_j < t_i} r_j)

Called every training step in causal PINN training.
Replaces: cumulative sum + exp (2 separate PyTorch ops).

Args:
    residuals: (N,) pointwise PDE residuals, detached
    times:     (N,) time coordinate for each point, in [0, T]
    eps:       causal epsilon (larger = more aggressive causal weighting)
    n_bins:    number of time bins for approximation

Returns:
    (N,) causal weights, all positive, detached from autograd graph
"""

### Function: `rippl.kernels.oss_kernels.fused_siren_layer`
`def fused_siren_layer(x: torch.Tensor, weight: torch.Tensor, bias: Optional[torch.Tensor] = None, omega_0: float = 30.0) -> torch.Tensor`

### Function: `rippl.kernels.oss_kernels.fused_laplacian_1d`
`def fused_laplacian_1d(u: torch.Tensor, dx: float) -> torch.Tensor`

### Function: `rippl.kernels.oss_kernels.fused_residual_loss`
`def fused_residual_loss(residuals: torch.Tensor, weights: Optional[torch.Tensor] = None) -> torch.Tensor`

### Function: `rippl.kernels.oss_kernels.fused_laplacian_nd`
`def fused_laplacian_nd(u, dx, kappa = 1.0, dim = 1)`

### Function: `rippl.kernels.oss_kernels.fused_symplectic_update`
`def fused_symplectic_update(q, p, dV_dq, dt, mass = 1.0)`

### Function: `rippl.kernels.oss_kernels.fused_laplacian_curvilinear`
`def fused_laplacian_curvilinear(u, r, dr, coords = 'cylindrical')`

### Function: `rippl.kernels.pro_kernels.weno3_flux`
`def weno3_flux(u: torch.Tensor, dx: float) -> torch.Tensor`

### Function: `rippl.kernels.pro_kernels.weno5_flux`
`def weno5_flux(u: torch.Tensor, dx: float) -> torch.Tensor`

### Function: `rippl.kernels.pro_kernels.weno5_flux_euler`
`def weno5_flux_euler(rho: torch.Tensor, rhou: torch.Tensor, E: torch.Tensor, dx: float) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]`

### Function: `rippl.kernels.pro_kernels.fd4_derivative`
`def fd4_derivative(u: torch.Tensor, dx: float) -> torch.Tensor`

### Function: `rippl.kernels.pro_kernels.pareto_mgda_scale`
`def pareto_mgda_scale(grads: List[torch.Tensor]) -> torch.Tensor`

### Function: `rippl.kernels.pro_kernels.fused_weighted_mse`
`def fused_weighted_mse(pred: torch.Tensor, target: torch.Tensor, weights: torch.Tensor) -> torch.Tensor`

### Function: `rippl.kernels.pro_kernels.fused_boundary_loss`
`def fused_boundary_loss(pred: torch.Tensor, bc_values: torch.Tensor, bc_mask: torch.Tensor, weight: float = 100.0) -> torch.Tensor`

### Function: `rippl.kernels.pro_kernels.rar_topk_residuals`
`def rar_topk_residuals(residuals: torch.Tensor, k: int) -> torch.Tensor`

### Function: `rippl.kernels.pro_kernels.rar_3d_clustering`
`def rar_3d_clustering(points: torch.Tensor, k: int, num_clusters: int) -> torch.Tensor`

### Function: `rippl.kernels.pro_kernels.sobol_stratified_sample`
`def sobol_stratified_sample(n_points: int, n_dims: int, bounds: List[Tuple[float, float]], device: torch.device) -> torch.Tensor`

### Function: `rippl.kernels.pro_kernels.rans_fused_residual`
`def rans_fused_residual(residuals: dict, weights: Optional[torch.Tensor] = None) -> torch.Tensor`

### Function: `rippl.kernels.pro_kernels.rar_spatial_cluster_3d`
`def rar_spatial_cluster_3d(coords: torch.Tensor, residuals: torch.Tensor, k: int, percentile: float = 0.8) -> torch.Tensor`

### Function: `rippl.kernels.pro_kernels.fused_mgda_gram`
`def fused_mgda_gram(per_objective_grads: torch.Tensor) -> torch.Tensor`

### Function: `rippl.kernels.universal_pro.get_pro_callable`
`def get_pro_callable(name)`

### Class: `rippl.logging.logger.RipplLogger`
"""
Standard logging infrastructure for the Rippl framework.
Supports local JSON logging of loss curves and parameter histories,
with optional Weights & Biases (wandb) integration.
"""
Methods:
- `def __init__(self, path: str = 'logs', use_wandb: bool = False, project: str = 'rippl')`
  - Initialize the logger.
- `def log_epoch(self, epoch: int, losses: Dict[str, float], parameters: Optional[Dict[str, torch.Tensor]] = None)`
  - Record metrics for a training epoch.

### Class: `rippl.migrate.transpiler.ExtractedPDE`
Methods:

### Class: `rippl.migrate.transpiler.DeepXDETranspiler`
Methods:
- `def __init__(self)`
- `def parse(self, source: str)`
- `def visit_FunctionDef(self, node)`
- `def visit_Call(self, node)`
- `def to_rippl_script(self)`

### Class: `rippl.migrate.transpiler.ModulusTranspiler`
Methods:
- `def __init__(self)`
- `def parse(self, source: str)`
- `def visit_Call(self, node)`
- `def to_rippl_script(self)`

### Class: `rippl.migrate.transpiler.SciANNTranspiler`
Methods:
- `def __init__(self)`
- `def parse(self, source: str)`
- `def visit_Call(self, node)`
- `def to_rippl_script(self)`

### Function: `rippl.migrate.transpiler.migrate`
`def migrate(source: str, framework: str = 'auto') -> str`

### Class: `rippl.migrate.transpiler.MigrationError`
Methods:

### Class: `rippl.models.deeponet.DeepONet`
Methods:
- `def __init__(self, b_lay, t_lay, out = 1)`
- `def forward(self, u_s, q_c)`

### Class: `rippl.models.fno_oss.SpectralConv1d`
"""
1D Fourier Spectral Layer.
"""
Methods:
- `def __init__(self, in_channels: int, out_channels: int, modes: int)`
- `def forward(self, x: torch.Tensor) -> torch.Tensor`

### Class: `rippl.models.fno_oss.FNO1d`
"""
1D Fourier Neural Operator.
Input: (B, N, F_in) -> Transpose to (B, F_in, N) -> FNO Layers -> (B, F_out, N) -> Transpose back
"""
Methods:
- `def __init__(self, *args, **kwargs)`
- `def forward(self, x: torch.Tensor) -> torch.Tensor`
  - Args:

### Class: `rippl.models.hamiltonian.HamiltonianNN`
"""
Learns scalar Hamiltonian H(q, p).
Input: concatenated (q, p) of dim 2*n_dof
Output: scalar H

Args:
    n_dof: degrees of freedom (q and p each have n_dof dims)
    hidden: hidden layer width
    layers: number of hidden layers
"""
Methods:
- `def __init__(self, n_dof: int, hidden: int = 64, layers: int = 4)`
- `def forward(self, q: torch.Tensor, p: torch.Tensor) -> torch.Tensor`
  - Returns scalar Hamiltonian H(q,p). Shape: (batch, 1)
- `def equations_of_motion(self, q: torch.Tensor, p: torch.Tensor) -> tuple`
  - Returns (dq_dt, dp_dt) via Hamilton's equations.
- `def energy_error(self, q: torch.Tensor, p: torch.Tensor, H0: float) -> torch.Tensor`
  - Measures energy conservation: |H(q,p) - H0| / |H0|
- `def loss(self, q: torch.Tensor, p: torch.Tensor, dq_dt_true: torch.Tensor, dp_dt_true: torch.Tensor) -> torch.Tensor`
  - Training loss: MSE between predicted and true equations of motion.

### Class: `rippl.models.lagrangian.LagrangianNN`
"""
Learns the Lagrangian L(q, q_dot). 
Computes acceleration via M(q)*q_ddot + C(q, q_dot) = dL/dq
"""
Methods:
- `def __init__(self, n_dof: int, hidden: int = 32, layers: int = 2)`
- `def forward(self, q, q_dot)`
- `def acceleration(self, q, q_dot)`
- `def loss(self, q, q_dot, q_ddot_true)`

### Class: `rippl.models.neural_ode.ODEFunc`
"""
Right-hand side of ODE: dz/dt = f(z, t)
"""
Methods:
- `def __init__(self, dim: int, hidden: int = 64, layers: int = 3)`
- `def forward(self, t: torch.Tensor, z: torch.Tensor) -> torch.Tensor`

### Class: `rippl.models.neural_ode.NeuralODE`
"""
Neural ODE wrapper.
Integrates ODE from t_span[0] to t_span[1] using dopri5.

Args:
    ode_func: ODEFunc or any callable (t, z) → dz/dt
    method: ODE solver ("dopri5", "rk4", "euler")
    rtol, atol: solver tolerances
"""
Methods:
- `def __init__(self, ode_func: nn.Module, method: str = 'dopri5', rtol: float = 0.001, atol: float = 0.0001)`
- `def forward(self, z0: torch.Tensor, t_span: torch.Tensor) -> torch.Tensor`
  - Args:
- `def loss(self, z0: torch.Tensor, t_span: torch.Tensor, z_true: torch.Tensor) -> torch.Tensor`
  - MSE loss against observed trajectory.
- `def forward_stiff(self, z0: torch.Tensor, t_span: torch.Tensor, method: str = 'implicit_adams', rtol: float = 1e-06, atol: float = 1e-08) -> torch.Tensor`
  - Stiff ODE solver. Use for: chemical kinetics, stiff mechanics.

### Class: `rippl.nn.adaptivesampler.AdaptiveSamplingBlock`
"""
Adaptive sampling weight estimator.

Args:
    input_dim: Dimension of ``(u, coords)`` features.
    hidden: MLP hidden size.
    use_correction: Whether to apply the learnable refinement.
"""
Methods:
- `def __init__(self, input_dim: int = 2, hidden: int = 32, use_correction: bool = True, **kwargs)`
- `def forward(self, u: torch.Tensor, coords: Optional[torch.Tensor] = None, params: Optional[torch.Tensor] = None) -> torch.Tensor`
  - Compute normalised sampling weights.

### Class: `rippl.nn.boundary_block.BoundaryConditionBlock`
"""
Boundary condition enforcement block.

Args:
    bc_type: ``"dirichlet"``, ``"neumann"``, or ``"periodic"``.
    bc_value: Boundary value for Dirichlet/Neumann (default 0).
    boundary_width: Fractional width of the boundary strip (0–1) where
                    the NN correction is active.
    domain: Tuple ``(low, high)`` for the spatial domain.
    correction_hidden: MLP hidden size.
    use_correction: Whether to apply NN correction near boundary.
"""
Methods:
- `def __init__(self, bc_type: str = 'dirichlet', bc_value: float = 0.0, boundary_width: float = 0.1, domain: tuple = Any, 1.0, correction_hidden: int = 32, use_correction: bool = True, **kwargs)`
- `def forward(self, u: torch.Tensor, coords: Optional[torch.Tensor] = None, params: Optional[torch.Tensor] = None) -> torch.Tensor`
  - Apply boundary condition enforcement.

### Class: `rippl.nn.conservation_block.ConservationConstraintBlock`
"""
Conservation constraint block.

Args:
    mode: ``"mass"`` (integral of u) or ``"energy"`` (integral of u²).
    correction_hidden: MLP hidden size.
    use_correction: Whether to apply learned correction.
"""
Methods:
- `def __init__(self, mode: str = 'mass', correction_hidden: int = 32, use_correction: bool = True, **kwargs)`
- `def forward(self, u: torch.Tensor, coords: Optional[torch.Tensor] = None, params: Optional[torch.Tensor] = None, target_quantity: Optional[torch.Tensor] = None) -> Tuple[torch.Tensor, torch.Tensor]`
  - Project u to enforce conservation and return constraint violation.

### Class: `rippl.nn.embedding.PDEParameterEmbeddingBlock`
"""
Embeds a vector of PDE parameters and can modulate hidden features
via FiLM (Feature-wise Linear Modulation).

Args:
    param_dim: Dimension of the raw parameter vector.
    embed_dim: Dimension of the latent embedding.
    feature_dim: Dimension of the features to modulate (for FiLM head).
    hidden: Hidden size of embedding MLP.
"""
Methods:
- `def __init__(self, param_dim: int = 3, embed_dim: int = 16, feature_dim: int = 32, hidden: int = 32, **kwargs)`
- `def forward(self, u: Optional[torch.Tensor] = None, coords: Optional[torch.Tensor] = None, params: Optional[torch.Tensor] = None) -> torch.Tensor`
  - Embed PDE parameters.
- `def modulate(self, features: torch.Tensor, params: torch.Tensor) -> torch.Tensor`
  - FiLM modulation: ``γ * features + β``.

### Class: `rippl.nn.energy.EnergyAwareBlock`
"""
Energy-aware correction block for wave fields.

Args:
    c: Wave speed (default 1.0).
    spatial_dim: Number of spatial dimensions.
    gate_hidden: Hidden size of the gating MLP.
    potential: Potential function name (``"none"`` or ``"quadratic"``).
"""
Methods:
- `def __init__(self, c: float = 1.0, spatial_dim: int = 1, gate_hidden: int = 32, potential: str = 'none', **kwargs)`
- `def compute_energy(self, u: torch.Tensor, coords: torch.Tensor) -> torch.Tensor`
  - Compute total energy density.
- `def forward(self, u: torch.Tensor, coords: Optional[torch.Tensor] = None, params: Optional[torch.Tensor] = None) -> Tuple[torch.Tensor, torch.Tensor]`
  - Forward pass.

### Class: `rippl.nn.fno.SpectralConv1d`
"""
1D Fourier Spectral Layer.
"""
Methods:
- `def __init__(self, in_channels: int, out_channels: int, modes: int)`
- `def forward(self, x: torch.Tensor) -> torch.Tensor`

### Class: `rippl.nn.fno.FNO1d`
"""
1D Fourier Neural Operator.
Input: (B, N, F_in) -> Transpose to (B, F_in, N) -> FNO Layers -> (B, F_out, N) -> Transpose back
"""
Methods:
- `def __init__(self, input_dim: int, output_dim: int, modes: int, width: int, depth: int = 4, **kwargs)`
- `def forward(self, x: torch.Tensor) -> torch.Tensor`
  - Args:

### Class: `rippl.nn.fno.SpectralConv2d`
"""
2D Fourier Spectral Layer.
"""
Methods:
- `def __init__(self, in_channels: int, out_channels: int, modes1: int, modes2: int)`
- `def forward(self, x: torch.Tensor) -> torch.Tensor`

### Class: `rippl.nn.fno.FNO2d`
"""
2D Fourier Neural Operator.
Requires input (B, N, F_in) where N = H*W.
Uses 'resolution' from config to reshape.
"""
Methods:
- `def __init__(self, input_dim: int, output_dim: int, modes1: int, modes2: int, width: int, depth: int = 4, resolution: List[int] = [64, 64], **kwargs)`
- `def forward(self, x: torch.Tensor) -> torch.Tensor`
  - Args:

### Class: `rippl.nn.fno.FNO`
Methods:
- `def __init__(self, n_modes: int, width: int, input_dim: int, output_dim: int = 1, **kwargs)`
- `def forward(self, x: torch.Tensor) -> torch.Tensor`

### Class: `rippl.nn.fourier_features.FourierFeatures`
"""
Maps raw coordinates through sin/cos of random frequencies
BEFORE the main network, dramatically improving high-frequency
representation capacity without changing the architecture depth.
"""
Methods:
- `def __init__(self, in_dim: int, n_features: int = 128, sigma: float = 10.0)`
- `def forward(self, coords: torch.Tensor) -> torch.Tensor`

### Class: `rippl.nn.fourier_features.MultiScaleFourierMLP`
"""
Combines multiple Fourier feature bands at different frequencies
with an MLP backbone — resolves both low-frequency global structure
and high-frequency boundary-layer detail simultaneously.
"""
Methods:
- `def __init__(self, in_dim: int, out_dim: int, hidden: int = 128, layers: int = 5, sigmas: list = [1.0, 10.0, 100.0], n_features_per_band: int = 64)`
- `def forward(self, coords: torch.Tensor) -> torch.Tensor`

### Class: `rippl.nn.fourier_mlp.FourierMLP`
"""
MLP with Random Fourier Feature Mapping.
"""
Methods:
- `def __init__(self, input_dim: int, output_dim: int, hidden_layers: List[int], sigma: float = 1.0, mapping_size: int = 256, activation: str = 'tanh', **kwargs)`
  - Initialize Fourier MLP.
- `def forward(self, x: torch.Tensor) -> torch.Tensor`
  - Forward pass with Fourier mapping.

### Class: `rippl.nn.gradient.HybridGradientBlock`
"""
Hybrid gradient block: autograd ∇u + learned MLP correction.

Args:
    spatial_dim: Number of spatial dimensions.
    correction_hidden: MLP hidden size.
    use_correction: Toggle learnable correction.
"""
Methods:
- `def __init__(self, spatial_dim: int = 1, correction_hidden: int = 32, use_correction: bool = True, **kwargs)`
- `def forward(self, u: torch.Tensor, coords: Optional[torch.Tensor] = None, params: Optional[torch.Tensor] = None) -> torch.Tensor`
  - Compute hybrid gradient.

### Class: `rippl.nn.hamiltonian.HamiltonianBlock`
"""
Hamiltonian neural network block with symplectic integration.

Args:
    state_dim: Dimension of q (same for p, so phase space = 2 * state_dim).
    hidden: MLP hidden size.
"""
Methods:
- `def __init__(self, state_dim: int = 1, hidden: int = 32, **kwargs)`
- `def hamiltonian(self, q: torch.Tensor, p: torch.Tensor) -> torch.Tensor`
  - Evaluate H(q, p).
- `def step(self, state: torch.Tensor, dt: float = 0.01, params: Optional[torch.Tensor] = None) -> torch.Tensor`
  - Symplectic leapfrog step.
- `def forward(self, u: torch.Tensor, coords: Optional[torch.Tensor] = None, params: Optional[torch.Tensor] = None) -> torch.Tensor`
  - Return Hamilton's equations: ``[dq/dt, dp/dt]``.

### Class: `rippl.nn.hybrid_stepper.HybridTimeStepperBlock`
"""
Hybrid time-stepper: physics integrator + NN corrector.

Args:
    state_dim: Dimension of the state vector.
    method: ``"euler"`` or ``"rk2"``.
    correction_hidden: MLP hidden size.
    use_correction: Whether to add the NN corrector.
    default_dt: Default time step.
"""
Methods:
- `def __init__(self, state_dim: int = 1, method: str = 'rk2', correction_hidden: int = 32, use_correction: bool = True, default_dt: float = 0.01, **kwargs)`
- `def step(self, u: torch.Tensor, dt: Optional[float] = None, rhs_fn: Optional[Callable] = None, params: Optional[torch.Tensor] = None) -> torch.Tensor`
  - One integration step.
- `def forward(self, u: torch.Tensor, coords: Optional[torch.Tensor] = None, params: Optional[torch.Tensor] = None) -> torch.Tensor`
  - Single step using default RHS and dt.

### Class: `rippl.nn.laplacian.HybridLaplacianBlock`
"""
Hybrid Laplacian block combining a physics-based Laplacian with a
learnable MLP correction.

Args:
    mode: ``"point"`` (autograd) or ``"grid"`` (finite-difference).
    spatial_dim: Number of spatial dimensions (1, 2, or 3). Used in grid mode.
    dx: Grid spacing for FD stencil (grid mode only).
    correction_hidden: Hidden size of the correction MLP.
    correction_input_dim: Input feature dimension for the MLP (point mode).
    use_correction: Whether to add the learnable correction.
"""
Methods:
- `def __init__(self, mode: str = 'point', spatial_dim: int = 1, dx: float = 1.0, correction_hidden: int = 32, correction_input_dim: int = 2, use_correction: bool = True, **kwargs)`
- `def forward(self, u: torch.Tensor, coords: Optional[torch.Tensor] = None, params: Optional[torch.Tensor] = None) -> torch.Tensor`
  - Compute hybrid Laplacian.

### Class: `rippl.nn.mlp.MLP`
"""
Multi-Layer Perceptron (MLP) supporting (B, N, F) input.
Operates on the last dimension F.
"""
Methods:
- `def __init__(self, in_dim: Optional[int] = None, out_dim: Optional[int] = None, hidden: Optional[int] = None, layers: Optional[Union[int, List[int]]] = None, input_dim: Optional[int] = None, output_dim: Optional[int] = None, hidden_layers: Optional[List[int]] = None, activation: str = 'tanh', **kwargs)`
  - Initialize the MLP. Supporting both new and old API signatures.
- `def forward(self, x: torch.Tensor) -> torch.Tensor`
  - Forward pass.

### Class: `rippl.nn.multiscale_ff.MultiScaleFourierFeatureBlock`
"""
Multi-scale random Fourier feature block with learnable gating.

Args:
    input_dim: Dimension of input coordinates.
    n_scales: Number of frequency scales.
    base_sigma: Lowest-scale standard deviation of random frequencies.
    scale_factor: Multiplicative factor between consecutive scales.
    features_per_scale: Number of Fourier features per scale.
"""
Methods:
- `def __init__(self, input_dim: int = 1, n_scales: int = 4, base_sigma: float = 1.0, scale_factor: float = 2.0, features_per_scale: int = 16, **kwargs)`
- `def gates(self) -> torch.Tensor`
- `def forward(self, u: Optional[torch.Tensor] = None, coords: Optional[torch.Tensor] = None, params: Optional[torch.Tensor] = None) -> torch.Tensor`
  - Compute multi-scale Fourier features.

### Class: `rippl.nn.multi_field_mlp.MultiFieldMLP`
"""
Shared trunk with multiple heads for multi-field PINNs.

fields: List of field names (e.g. ["u", "v", "p"])
hidden: Number of neurons per hidden layer in the trunk.
layers: Number of hidden layers in the trunk.
"""
Methods:
- `def __init__(self, in_dim: int, fields: List[str], hidden: int = 50, layers: int = 4)`
- `def forward(self, x: torch.Tensor) -> Dict[str, torch.Tensor]`
  - Returns dict of field tensors {field: (N, 1)}.

### Class: `rippl.nn.nn_operator_wrapper.OperatorWrapperBlock`
"""
Wraps a grid-based operator model with point-evaluation adaptor.

Args:
    grid_model: An ``nn.Module`` that expects ``(B, C, *spatial)`` input.
    grid_shape: Tuple of spatial grid dimensions, e.g. ``(64,)`` or ``(32, 32)``.
    in_channels: Number of input channels.
    out_channels: Number of output channels.
"""
Methods:
- `def __init__(self, grid_model: Optional[nn.Module] = None, grid_shape: tuple = 64, in_channels: int = 1, out_channels: int = 1, **kwargs)`
- `def points_to_grid(self, u: torch.Tensor, coords: torch.Tensor) -> torch.Tensor`
  - Scatter point values onto a regular grid via nearest-neighbor binning.
- `def grid_to_points(self, grid: torch.Tensor, coords: torch.Tensor) -> torch.Tensor`
  - Sample grid at point locations via bilinear interpolation.
- `def forward(self, u: torch.Tensor, coords: Optional[torch.Tensor] = None, params: Optional[torch.Tensor] = None) -> torch.Tensor`
  - Point-cloud in → grid model → point-cloud out.

### Class: `rippl.nn.oscillator.HybridOscillatorBlock`
"""
Hybrid Duffing/harmonic oscillator block.

State vector ``s = [u, v]`` where ``v = du/dt``.

Args:
    omega: Natural frequency (default 1.0).
    alpha: Cubic nonlinearity coefficient (0 gives harmonic oscillator).
    damping: Initial damping coefficient.
    hidden: MLP hidden size.
    use_correction: Whether to add the MLP residual.
"""
Methods:
- `def __init__(self, omega: float = 1.0, alpha: float = 0.0, damping: float = 0.0, hidden: int = 32, use_correction: bool = True, **kwargs)`
- `def omega(self) -> torch.Tensor`
- `def step(self, state: torch.Tensor, dt: float = 0.01, params: Optional[torch.Tensor] = None) -> torch.Tensor`
  - Single RK2 (midpoint) integration step.
- `def forward(self, u: torch.Tensor, coords: Optional[torch.Tensor] = None, params: Optional[torch.Tensor] = None) -> torch.Tensor`
  - Continuous forward: given ``u`` as ``(B, 2)`` state ``[u, v]``,

### Class: `rippl.nn.residual.HybridWaveResidualBlock`
"""
Hybrid wave-equation residual block.

Computes ``a * u_tt + b * u_t − c * Lap(u) + correction(u)`` where the
Laplacian is computed via autograd and the correction is a small MLP
(deactivated by default so that analytic solutions give near-zero residual).

Args:
    a: Coefficient for u_tt (default 1.0).
    b: Coefficient for u_t (default 0.0).
    c: Coefficient for Laplacian(u) (wave speed squared, default 1.0).
    spatial_dim: Number of spatial dimensions.
    correction_hidden: MLP hidden size.
    use_correction: Toggle MLP correction on/off.
"""
Methods:
- `def __init__(self, a: float = 1.0, b: float = 0.0, c: float = 1.0, spatial_dim: int = 1, correction_hidden: int = 32, use_correction: bool = True, **kwargs)`
- `def residual(self, u: torch.Tensor, equation, inputs: torch.Tensor) -> torch.Tensor`
  - Delegate PDE residual to Equation, add MLP correction.
- `def loss(self, u: torch.Tensor, equation, inputs: torch.Tensor) -> torch.Tensor`
  - Return mean-squared residual.
- `def forward(self, u: torch.Tensor, equation = None, inputs: Optional[torch.Tensor] = None) -> torch.Tensor`

### Class: `rippl.nn.siren.SineLayer`
"""
Linear layer with Sine activation and specialized initialization.
"""
Methods:
- `def __init__(self, in_features: int, out_features: int, bias: bool = True, is_first: bool = False, omega_0: float = 30.0)`
- `def init_weights(self) -> None`
- `def forward(self, x: torch.Tensor) -> torch.Tensor`

### Class: `rippl.nn.siren.Siren`
"""
Sinusoidal Representation Network (SIREN).
"""
Methods:
- `def __init__(self, input_dim: int, output_dim: int, hidden_layers: List[int], omega_0: float = 30.0, **kwargs)`
  - Initialize SIREN.
- `def forward(self, x: torch.Tensor) -> torch.Tensor`
  - Forward pass.

### Class: `rippl.nn.siren.SIREN`
"""
Sinusoidal Representation Network (SIREN) with flexible config.
Used for smooth periodic functions and high-frequency PDEs.

Reference: Sitzmann et al. 2020, "Implicit Neural Representations
with Periodic Activation Functions", NeurIPS.
"""
Methods:
- `def __init__(self, in_features: int, out_features: int, hidden_features: int = 256, hidden_layers: int = 5, outermost_linear: bool = True, first_omega_0: float = 30.0, hidden_omega_0: float = 30.0, bias: bool = True)`
- `def forward(self, x: torch.Tensor) -> torch.Tensor`

### Function: `rippl.nn.siren.HighFreqSIREN`
`def HighFreqSIREN(in_dim: int, out_dim: int, hidden: int = 256, layers: int = 5, omega_0: float = 30.0) -> torch.nn.Module`
"""
SIREN optimized for high-frequency PDEs.

Standard SIREN uses omega_0=30 which handles frequencies up to ~10.
For problems with higher spatial frequencies (wave equation with k>>1,
Helmholtz with large k, turbulence), increase omega_0.

Rule of thumb: omega_0 ≈ max_expected_frequency * π

Examples:
    u = sin(10πx): use omega_0=30 (default handles this)
    u = sin(30πx): use omega_0=100
    Turbulence (Re=1000): use omega_0=300

Reference: Sitzmann et al. 2020, "Implicit Neural Representations
with Periodic Activation Functions", NeurIPS.
"""

### Class: `rippl.nn.spectral.SpectralHybridBlock`
"""
Hybrid spectral filtering block.

Args:
    n_modes: Number of Fourier modes to keep.
    cutoff: Hard cutoff frequency index (modes above are zeroed before
            learnable weighting). Set ``None`` to keep all.
    hidden: MLP hidden size.
    use_correction: Whether to apply the learnable amplitude MLP.
"""
Methods:
- `def __init__(self, n_modes: int = 64, cutoff: Optional[int] = None, hidden: int = 32, use_correction: bool = True, **kwargs)`
- `def get_spectrum(self, u: torch.Tensor) -> torch.Tensor`
  - Compute the real FFT spectrum of *u*.
- `def apply_filter(self, spectrum: torch.Tensor) -> torch.Tensor`
  - Apply physics cutoff + learnable frequency weights to a spectrum.
- `def forward(self, u: torch.Tensor, coords: Optional[torch.Tensor] = None, params: Optional[torch.Tensor] = None) -> torch.Tensor`
  - Forward pass: FFT → filter/correct → IFFT.

### Class: `rippl.nn.spectral_conv.SpectralConvBlock`
"""
FNO-style spectral convolution + local conv residual.

Args:
    in_channels: Input channels.
    out_channels: Output channels.
    modes: Number of Fourier modes to keep.
    use_local_conv: Whether to add the local conv residual path.
"""
Methods:
- `def __init__(self, in_channels: int = 1, out_channels: int = 1, modes: int = 16, use_local_conv: bool = True, **kwargs)`
- `def forward(self, u: torch.Tensor, coords: Optional[torch.Tensor] = None, params: Optional[torch.Tensor] = None) -> torch.Tensor`
  - Forward pass.

### Class: `rippl.nn.spectral_reg.SpectralRegularizationBlock`
"""
Spectral regularisation block returning a scalar loss term.

Args:
    cutoff: Mode index above which energy is penalised.
    penalty_weight: Multiplier for the penalty.
    norm: ``"l2"`` or ``"l1"`` penalty on high-frequency amplitudes.
"""
Methods:
- `def __init__(self, cutoff: int = 16, penalty_weight: float = 1.0, norm: str = 'l2', **kwargs)`
- `def forward(self, u: torch.Tensor, coords: Optional[torch.Tensor] = None, params: Optional[torch.Tensor] = None) -> torch.Tensor`
  - Compute spectral regularisation penalty.

### Class: `rippl.nn.wrappers.PDFWrapper`
"""
Wraps any rippl architecture to guarantee its output is a valid 
Probability Density Function (non-negative, integrates to 1.0).
Assumes uniform sampling over a unit volume for normalization.
"""
Methods:
- `def __init__(self, base_model: nn.Module, eps: float = 1e-08)`
- `def forward(self, *args, **kwargs)`

### Class: `rippl.physics.compressible_flow.CompressibleNavierStokes`
"""
Compressible high-speed flow operator (Navier-Stokes).
Supports density variations and shocks.
"""
Methods:
- `def __init__(self, mu = 1.0, gamma = 1.4, trainable = False)`
- `def signature(self)`
- `def compute(self, fields, coords)`

### Class: `rippl.physics.conservation.ConservationLaw`
Methods:
- `def __init__(self, name: str, quantity_fn: Callable, tolerance: float = 0.001)`
- `def loss(self, model, coords, domain) -> torch.Tensor`

### Class: `rippl.physics.conservation.ConservationMonitor`
Methods:
- `def __init__(self, laws: List[Union[str, Callable]], weight: float = 0.1, freq: int = 50, n_integration_pts: int = 4096, reference_values: Optional[Dict] = None)`
- `def initialize(self, model, domain, equation, device)`
- `def compute_violation_loss(self, model, domain, fields, coords, epoch) -> Optional[torch.Tensor]`
- `def last_violation(self)`

### Class: `rippl.physics.conservative.StreamFunctionModel`
"""
u=∂ψ/∂y, v=-∂ψ/∂x via autograd. Ensures divergence-free 2D velocity.
"""
Methods:
- `def __init__(self, base_model: nn.Module, coord_dims: Tuple[int, int] = 0, 1)`
- `def forward(self, coords: torch.Tensor) -> Dict[str, torch.Tensor]`

### Class: `rippl.physics.conservative.VectorPotentialModel`
"""
u=curl(A) via autograd. Ensures divergence-free 3D velocity.
"""
Methods:
- `def __init__(self, base_model: nn.Module, spatial_dims: Tuple[int, int, int] = 0, 1, 2)`
- `def forward(self, coords: torch.Tensor) -> Dict[str, torch.Tensor]`

### Function: `rippl.physics.conservative.verify_divergence_free`
`def verify_divergence_free(model: nn.Module, coords: torch.Tensor, tolerance: float = 1e-06) -> Dict[str, Any]`
"""
Computes divergence and checks if it's below tolerance.
"""

### Class: `rippl.physics.delta.DeltaSrc`
Methods:
- `def __init__(self, loc, mag = 1.0, bw = 0.05)`
- `def eval(self, x)`

### Class: `rippl.physics.delta.DeltaEq`
Methods:
- `def __init__(self, eq, src)`
- `def compute_loss(self, f, x)`
- `def compute_pointwise_residual(self, f, x)`

### Class: `rippl.physics.distance.AnsatzFactory`
Methods:
- `def dirichlet_1d(network: torch.nn.Module, a: float = 0.0, b: float = 0.0, domain_lo: float = 0.0, domain_hi: float = 1.0) -> torch.nn.Module`
  - Wraps network with exact Dirichlet BC enforcement.

### Class: `rippl.physics.elasticity.LinearElasticitySystem`
Methods:
- `def __init__(self, E = 1.0, nu = 0.3, dims = 2, body_force_x = 0.0, body_force_y = 0.0)`
- `def build_equation_system(self) -> EquationSystem`
- `def fields(self) -> list`
- `def suggested_model(self) -> MultiFieldMLP`

### Class: `rippl.physics.euler.EulerMassOperator`
"""
∂ρ/∂t + ∂(ρu)/∂x = 0
Conservative form of mass conservation.
"""
Methods:
- `def __init__(self, field_rho = 'rho', field_rhou = 'rhou')`
- `def signature(self)`
- `def forward(self, fields, coords, derived = None)`

### Class: `rippl.physics.euler.EulerMomentumOperator`
"""
∂(ρu)/∂t + ∂(ρu² + p)/∂x = 0
p = (γ-1)(E - 0.5 * ρu²)
"""
Methods:
- `def __init__(self, gamma = 1.4, field_rho = 'rho', field_rhou = 'rhou', field_E = 'E')`
- `def signature(self)`
- `def forward(self, fields, coords, derived = None)`

### Class: `rippl.physics.euler.EulerEnergyOperator`
"""
∂E/∂t + ∂((E+p)u)/∂x = 0
"""
Methods:
- `def __init__(self, gamma = 1.4, field_rho = 'rho', field_rhou = 'rhou', field_E = 'E')`
- `def signature(self)`
- `def forward(self, fields, coords, derived = None)`

### Class: `rippl.physics.euler.EulerSystem`
"""
Compressible Euler System (1D).

WARNING: inviscid — shocks expected. Use ArtificialViscosity or 
rippl-pro WENO for stable near-shock solutions.
"""
Methods:
- `def __init__(self, gamma = 1.4)`
- `def build_equation_system(self)`
- `def fields(self)`
- `def pressure(self, rho, rhou, E)`
  - p = (γ-1)(E - ½ρu²)
- `def mach_number(self, rho, rhou, E)`
  - M = |u|/c where c = sqrt(γp/ρ)

### Class: `rippl.physics.fractional.FractionalLaplacian`
"""
Spectral definition: (-Δ)^α u via Fourier transform.
(-Δ)^α u = F^{-1}(|ξ|^{2α} F(u))

Valid for periodic domains. Uses torch.fft.

Args:
    alpha: fractional order, α ∈ (0,1)
    field: field name
    spatial_dims: number of spatial dimensions
"""
Methods:
- `def __init__(self, alpha: float = 0.5, field: str = 'u', spatial_dims: int = 1)`
- `def signature(self) -> dict`
- `def forward(self, fields: dict, coords: torch.Tensor, derived: dict = None) -> torch.Tensor`

### Class: `rippl.physics.fractional.CaputoDerivative`
"""
Caputo fractional time derivative: D^α_t u, α ∈ (0,1).
Numerical approximation via L1 scheme (open-source standard).

D^α_t u(t) ≈ (1/Γ(2-α)) * Σ b_j [u(t_{n-j}) - u(t_{n-j-1})] / dt^α
where b_j = (j+1)^{1-α} - j^{1-α}

Args:
    alpha: fractional order, α ∈ (0,1)
    dt: time step for L1 scheme approximation
"""
Methods:
- `def __init__(self, alpha: float = 0.5, dt: float = 0.01, field: str = 'u')`
- `def signature(self) -> dict`
- `def forward(self, fields: dict, coords: torch.Tensor, derived: dict = None) -> torch.Tensor`

### Class: `rippl.physics.fractional.FractionalSystem`
"""
Convenience builder for fractional PDE systems.
"""
Methods:
- `def subdiffusion(alpha: float = 0.5, spatial_dims: int = 1, diffusivity: float = 1.0)`
  - Fractional subdiffusion: D^α_t u = d * Δu
- `def superdiffusion(alpha: float = 0.5, spatial_dims: int = 1, diffusivity: float = 1.0)`
  - Fractional superdiffusion: ∂u/∂t = -d * (-Δ)^α u

### Class: `rippl.physics.hamilton_jacobi.HamiltonianOperator`
"""
General Hamiltonian H(x, p) where p = ∇V.
User provides H as a callable.

Args:
    hamiltonian_fn: callable H(x, p) → scalar
        x: coordinates (N, D)
        p: gradient of value function (N, D)
    field: value function field name (default "V")
"""
Methods:
- `def __init__(self, hamiltonian_fn: callable, field: str = 'V', spatial_dims: int = None)`
- `def signature(self) -> dict`
- `def forward(self, fields, coords, derived = None)`

### Class: `rippl.physics.hamilton_jacobi.EikonalOperator`
"""
Eikonal equation: |∇V| = 1/c(x)
Residual: |∇V|² - 1/c(x)² = 0
Used for: wave front propagation, distance computation.

Args:
    speed_fn: callable c(x) → (N,1), wave speed field
    field: field name (default "V")
"""
Methods:
- `def __init__(self, speed_fn: callable = None, field: str = 'V', spatial_dims: int = None)`
- `def signature(self) -> dict`
- `def forward(self, fields, coords, derived = None)`

### Class: `rippl.physics.hamilton_jacobi.HJSystem`
"""
Convenience builder for Hamilton-Jacobi systems.
"""
Methods:
- `def optimal_control(running_cost: callable, dynamics: callable, field: str = 'V') -> 'Equation'`
  - HJB equation: -∂V/∂t = min_u [L(x,u) + f(x,u)·∇V]
- `def eikonal(speed_fn: callable = None, spatial_dims: int = 2) -> 'Equation'`
  - Returns Equation for eikonal: |∇V| = 1/c(x)

### Class: `rippl.physics.interface.Material`
Methods:
- `def get(self, prop: str, default: float = 1.0) -> float`

### Class: `rippl.physics.interface.InterfaceCondition`
Methods:
- `def sample_interface_points(self, domain, device) -> torch.Tensor`
- `def compute_loss(self, model, domain, device) -> torch.Tensor`

### Class: `rippl.physics.interface.InterfaceLayer`
Methods:
- `def __init__(self, conditions: List[InterfaceCondition], weight: float = 1.0)`
- `def compute_total_loss(self, model, domain, device) -> torch.Tensor`
- `def n_conditions(self)`

### Class: `rippl.physics.maxwell.FaradayOperator`
"""
∂B/∂t = -∇×E
"""
Methods:
- `def __init__(self, dims = 3)`
- `def signature(self)`
- `def forward(self, fields, coords, derived = None)`

### Class: `rippl.physics.maxwell.AmpereOperator`
"""
∂E/∂t = ∇×B - J
"""
Methods:
- `def __init__(self, current_fn = None, dims = 3)`
- `def signature(self)`
- `def forward(self, fields, coords, derived = None)`

### Class: `rippl.physics.maxwell.GaussElectricOperator`
"""
∇·E = ρ
"""
Methods:
- `def __init__(self, charge_fn = None)`
- `def signature(self)`
- `def forward(self, fields, coords, derived = None)`

### Class: `rippl.physics.maxwell.GaussMagneticOperator`
"""
∇·B = 0
"""
Methods:
- `def __init__(self)`
- `def signature(self)`
- `def forward(self, fields, coords, derived = None)`

### Class: `rippl.physics.maxwell.MaxwellSystem`
Methods:
- `def __init__(self, charge_fn = None, current_fn = None, dims = 3)`
- `def build_equation_system(self)`
- `def fields(self)`

### Class: `rippl.physics.maxwell.HelmholtzMaxwellSystem`
Methods:
- `def __init__(self, k = 1.0)`
- `def build_equation_system(self)`
- `def fields(self)`

### Class: `rippl.physics.navier_stokes.NavierStokesSystem`
Methods:
- `def __init__(self, rho = 1.0, mu = 0.01, dims = 2, pressure_gauge_coords = None, pressure_gauge_value = None)`
- `def build_equation_system(self) -> EquationSystem`
- `def fields(self) -> list`
- `def suggested_model(self) -> MultiFieldMLP`

### Class: `rippl.physics.nonlinear_solid.NonlinearElasticity`
"""
Nonlinear structural mechanics operator (e.g. Neo-Hookean).
For large deformations / plasticity.
"""
Methods:
- `def __init__(self, E = 1.0, nu = 0.3, trainable = False)`
- `def signature(self)`
- `def compute(self, fields, coords)`

### Class: `rippl.physics.parametric.ParametricWrapper`
"""
Wraps any model to accept PDE parameters as additional inputs.
Model input: cat([coords, params]) → solution u

Args:
    base_model: model expecting (N, coord_dim) input
    param_dim: number of PDE parameters
    param_bounds: list of (min, max) per parameter for normalization
"""
Methods:
- `def __init__(self, base_model: nn.Module, param_dim: int, param_bounds: list = None)`
- `def forward(self, coords: torch.Tensor, params: torch.Tensor) -> torch.Tensor`
  - Args:

### Class: `rippl.physics.parametric.ParametricSampler`
"""
Samples (coords, params) pairs for parametric PINN training.
Each batch contains multiple parameter values.
"""
Methods:
- `def __init__(self, domain, param_bounds: list, n_params_per_batch: int = 8)`
- `def sample(self, batch_size: int = 2048) -> tuple`
  - Returns (coords, params) tensors.

### Class: `rippl.physics.pde.PDESpec`
"""
Specification for a Partial Differential Equation (PDE).

Represents the equation:
a * u_tt + b * u_t + c * Laplacian(u) + f(u) - g(x, t) = 0 (residual term)

Attributes:
    a (float): Coefficient for the second time derivative term (u_tt).
    b (float): Coefficient for the first time derivative term (u_t).
    c (float): Coefficient for the spatial Laplacian term (Laplacian(u)).
    nonlinear_type (Optional[str]): Type of nonlinearity f(u). Currently supports 'linear' or None.
    forcing (Optional[Callable[[torch.Tensor], torch.Tensor]]): Forcing function g(x, t).
"""
Methods:

### Class: `rippl.physics.phase_field.CahnHilliardOperator`
"""
Cahn-Hilliard equation:
∂φ/∂t = M * ∇²[f'(φ) - ε²∇²φ]

Split into system:
∂φ/∂t = M * ∇²μ          (transport equation)
μ = f'(φ) - ε²∇²φ         (chemical potential)

Double-well: f(φ) = φ²(1-φ)²/4, f'(φ) = φ(1-φ)(1-2φ)

Args:
    M: mobility coefficient
    epsilon: interface width parameter
    field_phi: phase field name
    field_mu: chemical potential name
"""
Methods:
- `def __init__(self, M: float = 1.0, epsilon: float = 0.1, field_phi: str = 'phi', field_mu: str = 'mu')`
- `def signature(self) -> dict`
- `def forward(self, fields, coords, derived = None)`
- `def chemical_potential_residual(self, fields, coords, derived = None)`
  - μ - f'(φ) + ε²∇²φ = 0

### Class: `rippl.physics.phase_field.AllenCahnOperator`
"""
Allen-Cahn equation:
∂φ/∂t = -M[f'(φ) - ε²∇²φ]

Simpler than Cahn-Hilliard (2nd order vs 4th order).
Describes non-conserved order parameter dynamics.
"""
Methods:
- `def __init__(self, M: float = 1.0, epsilon: float = 0.1, field: str = 'phi')`
- `def signature(self) -> dict`
- `def forward(self, fields, coords, derived = None)`

### Class: `rippl.physics.phase_field.PhaseFieldSystem`
"""
Convenience builder for phase-field systems.
"""
Methods:
- `def cahn_hilliard(M = 1.0, epsilon = 0.1, spatial_dims = 1) -> 'EquationSystem'`
  - Returns EquationSystem for Cahn-Hilliard.
- `def allen_cahn(M = 1.0, epsilon = 0.1) -> 'Equation'`
  - Returns single Equation for Allen-Cahn.

### Class: `rippl.physics.quantum.GrossPitaevskiiOperator`
"""
Gross-Pitaevskii Equation (GPE):
iℏ∂ψ/∂t = [-ℏ²/2m ∇² + V + g|ψ|²]ψ
Split into real and imaginary parts.
"""
Methods:
- `def __init__(self, hbar = 1.0, mass = 1.0, g = 1.0, potential_fn = None, field_real = 'psi_real', field_imag = 'psi_imag', spatial_dims = 1)`
- `def signature(self)`
- `def forward(self, fields, coords, derived = None)`

### Class: `rippl.physics.quantum.GPESystem`
Methods:
- `def __init__(self, hbar = 1.0, mass = 1.0, g = 1.0, potential_fn = None, spatial_dims = 1)`
- `def build_equation_system(self)`
- `def fields(self)`
- `def norm_conservation_loss(self, model, x_grid, dx)`
  - |(∫|ψ|²dx) - 1|

### Class: `rippl.physics.reaction_diffusion.ReactionDiffusionOperator`
"""
General reaction-diffusion operator for one species.
∂u/∂t - D∇²u - R(u, v, ...) = 0

Args:
    diffusivity: D coefficient
    reaction_fn: callable R(fields, coords) → (N,1)
    field: species field name
    spatial_dims: spatial dimensions
"""
Methods:
- `def __init__(self, diffusivity: float, reaction_fn: callable, field: str = 'u', spatial_dims: int = None)`
- `def signature(self) -> dict`
- `def forward(self, fields, coords, derived = None)`

### Class: `rippl.physics.reaction_diffusion.TuringSystem`
"""
Turing pattern system (Gray-Scott model).
∂u/∂t = D_u∇²u - uv² + F(1-u)
∂v/∂t = D_v∇²v + uv² - (F+k)v
"""
Methods:
- `def __init__(self, D_u: float = 0.16, D_v: float = 0.08, F: float = 0.035, k: float = 0.065)`
- `def build_equation_system(self) -> 'EquationSystem'`
- `def fields(self)`

### Class: `rippl.physics.reaction_diffusion.FitzHughNagumoSystem`
"""
FitzHugh-Nagumo: simplified neuron model.
∂v/∂t = D∇²v + v - v³/3 - w + I_ext
∂w/∂t = ε(v + a - bw)
"""
Methods:
- `def __init__(self, D: float = 1.0, epsilon: float = 0.08, a: float = 0.7, b: float = 0.8, I_ext: float = 0.5)`
- `def build_equation_system(self) -> 'EquationSystem'`
- `def fields(self)`

### Class: `rippl.physics.reaction_diffusion.BrusselatorSystem`
"""
Brusselator model for chemical oscillations.
∂u/∂t = D_u∇²u + A - (B+1)u + u²v
∂v/∂t = D_v∇²v + Bu - u²v
"""
Methods:
- `def __init__(self, A: float = 1.0, B: float = 3.0, D_u: float = 1.0, D_v: float = 0.1)`
- `def build_equation_system(self) -> 'EquationSystem'`
- `def fields(self)`

### Function: `rippl.physics.residuals.build_residual_fn`
`def build_residual_fn(pde: PDESpec) -> Callable[[torch.Tensor, torch.Tensor], torch.Tensor]`
"""
Builds a residual function for the given PDE specification.

Args:
    pde (PDESpec): The PDE specification.
    
Returns:
    Callable[[torch.Tensor, torch.Tensor], torch.Tensor]: 
        Function that takes (model_output, inputs) and returns the residual.
        Inputs are assumed to be (B, D) where D = spatial_dims + 1 (time).
        Last column is time t.
        Output u is (B, 1).
"""

### Class: `rippl.physics.schrodinger.SchrodingerSystem`
Methods:
- `def __init__(self, potential_fn, hbar = 1.0, mass = 1.0, dims = 1)`
- `def build_equation_system(self) -> EquationSystem`
- `def norm_conservation_loss(self, model, coords_x) -> torch.Tensor`
- `def fields(self) -> list`
- `def suggested_model(self) -> MultiFieldMLP`

### Function: `rippl.physics.sdf_smooth.smooth_sdf_multiplier`
`def smooth_sdf_multiplier(sdf_values: torch.Tensor, delta: float = 0.05, method: str = 'tanh') -> torch.Tensor`
"""
Smooth the SDF multiplier near corners.

Standard multiplier: d(x)
Smooth multiplier:   d(x) * smooth_transition(d(x) / delta)

The smooth_transition function:
- Is 0 at d=0 (boundary still exactly satisfied)
- Approaches 1 as d → ∞ (recovers standard SDF far from boundary)
- Has continuous derivative everywhere

Args:
    sdf_values: Signed distance field values, (N,)
    delta:      Smoothing radius. Smaller = sharper transition but
                more sensitive to corner singularities.
                Typical range: 0.01 to 0.1 (as fraction of domain size)
    method:     Smoothing function type:
                  'tanh'       — tanh(d/delta), smooth, efficient
                  'sine'       — sine ramp over [0, delta], C∞
                  'polynomial' — cubic Hermite, C¹ only

Returns:
    (N,) smooth multiplier values. Zero at boundary, smooth elsewhere.
"""

### Function: `rippl.physics.sdf_smooth.detect_corner_regions`
`def detect_corner_regions(sdf_values: torch.Tensor, coords: torch.Tensor, curvature_threshold: float = 5.0) -> torch.Tensor`
"""
Identify collocation points near geometric corners.

A corner is detected where the SDF curvature (Laplacian of SDF)
is large. The Eikonal property |∇d|=1 means ∇²d ≈ curvature.

Returns:
    (N,) boolean tensor, True where point is near a corner
"""

### Function: `rippl.physics.sdf_smooth.corner_adaptive_delta`
`def corner_adaptive_delta(sdf_values: torch.Tensor, coords: torch.Tensor, delta_min: float = 0.01, delta_max: float = 0.1) -> torch.Tensor`
"""
Compute spatially-varying mollification radius.

Near corners: smaller delta (sharper transition)
Away from corners: larger delta (smoother transition)

This balances two competing needs:
- Accuracy: small delta recovers exact SDF behavior
- Stability: large delta avoids gradient discontinuities

Returns:
    (N,) spatially-varying delta values
"""

### Function: `rippl.physics.sdf_smooth.build_smooth_ansatz_multiplier`
`def build_smooth_ansatz_multiplier(sdf_values: torch.Tensor, coords: torch.Tensor, delta: float = 0.05, adaptive_delta: bool = True, method: str = 'tanh') -> torch.Tensor`
"""
Build the complete ansatz multiplier for hard BC enforcement.

This is the function φ(d) such that:
    u(x) = φ(d(x)) * network(x)
guarantees u(x) = 0 on ∂Ω (the boundary) while being smooth.

Args:
    sdf_values:     (N,) signed distance values
    coords:         (N, d) coordinate tensor (for corner detection)
    delta:          Base mollification radius
    adaptive_delta: Use spatially-varying delta (better for complex geometry)
    method:         Smoothing method ('tanh' recommended)

Returns:
    (N, 1) multiplier values
"""

### Function: `rippl.physics.shock.add_artificial_viscosity`
`def add_artificial_viscosity(equation, field = 'u', epsilon_max = 0.1, gradient_threshold = 10.0, spatial_dims = None)`
"""
Convenience function: adds ArtificialViscosity to an existing Equation.
Returns new Equation with AV term appended.
Does not modify original equation.
"""

### Class: `rippl.physics.shock.TVDScheme`
"""
Total Variation Diminishing scheme using open-source PyTorch ops.
No CUDA kernels. Uses torch.roll for stencils.

MinMod limiter: phi(r) = max(0, min(1, r))
Van Leer limiter: phi(r) = (r + |r|) / (1 + |r|)
Superbee limiter: phi(r) = max(0, min(2r,1), min(r,2))
"""
Methods:
- `def __init__(self, limiter: str = 'minmod')`
- `def apply(self, u: torch.Tensor, dx: float, direction: int = 0) -> torch.Tensor`

### Class: `rippl.physics.stochastic.StochasticTerm`
"""
Noise term for stochastic PDEs.
du = L[u]dt + σ(u,x,t) dW
where dW is Wiener process increment.

Args:
    sigma_fn: callable(u, coords) → noise magnitude (N,1)
              None defaults to additive white noise with sigma=noise_level
    noise_level: scalar noise magnitude when sigma_fn is None
    noise_type: "additive" or "multiplicative"
"""
Methods:
- `def __init__(self, sigma_fn = None, noise_level: float = 0.01, noise_type: str = 'additive')`
- `def sample(self, u: torch.Tensor, coords: torch.Tensor) -> torch.Tensor`
  - Sample noise realization. Returns (N,1) noise tensor.

### Class: `rippl.physics.stochastic.StochasticEquation`
"""
Wraps deterministic Equation with stochastic noise term.
Loss computed via Monte Carlo expectation over noise samples.
"""
Methods:
- `def __init__(self, base_equation, stochastic_term: StochasticTerm, n_samples: int = 10)`
- `def compute_loss(self, fields: dict, coords: torch.Tensor) -> torch.Tensor`
  - Monte Carlo estimate of stochastic residual.

### Class: `rippl.physics.stochastic.FokkerPlanckEquation`
"""
Fokker-Planck equation for probability density p(x,t):
∂p/∂t = -∂/∂x[μ(x)p] + (σ²/2)∂²p/∂x²

where μ(x) is drift and σ² is diffusion coefficient.
Constraint: ∫p dx = 1 (normalization), p ≥ 0 (positivity)

Args:
    drift_fn: callable(coords) → (N,1) drift μ(x)
    diffusion: scalar σ² diffusion coefficient
"""
Methods:
- `def __init__(self, drift_fn: callable, diffusion: float = 1.0)`
- `def compute_loss(self, fields: dict, coords: torch.Tensor) -> torch.Tensor`
- `def normalization_loss(self, model, x_grid: torch.Tensor, dx: float) -> torch.Tensor`
  - Enforces ∫p dx = 1 via quadrature.

### Class: `rippl.physics.stochastic.PDFWrapper`
"""
Enforces physical plausibility for probability density outputs.
p(x) > 0 via Softplus. ∫p dx ≈ 1 via batch normalization.
Required for Fokker-Planck and any PDF-valued PDE.
"""
Methods:
- `def __init__(self, model: torch.nn.Module, domain_volume: float = 1.0)`
- `def forward(self, coords: torch.Tensor) -> torch.Tensor`
- `def normalization_error(self, coords: torch.Tensor, dx: float) -> torch.Tensor`

### Class: `rippl.physics.operators.base.Operator`
"""
Abstract base: forward(fields, coords, derived) -> tensor.
"""
Methods:
- `def __init__(self, field: str = 'u')`
- `def forward(self, fields: Dict[str, torch.Tensor], coords: torch.Tensor, derived: Dict[str, torch.Tensor] = None) -> torch.Tensor`
  - Low-level tensor operation implementing the physics of the operator.
- `def compute(self, field: torch.Tensor, params: Dict[str, Any]) -> torch.Tensor`
  - Backward compatibility for compute().
- `def signature(self) -> Dict[str, Any]`

### Class: `rippl.physics.operators.electromagnetic.MaxwellOperator`
"""
Simplified Maxwell wave operator (TE/TM mode).
∇²E - (1/c²)∂²E/∂t² = 0
Covers: waveguides, resonators, antenna radiation, photonics.
"""
Methods:
- `def __init__(self, c: float = 1.0, spatial_dims: int = 2)`
- `def compute_pointwise_residual(self, fields, coords)`
- `def residual(self, fields, coords)`
- `def compute_loss(self, fields, coords)`

### Class: `rippl.physics.operators.elliptic.Laplacian`
Methods:
- `def __init__(self, field = 'u', spatial_dims = None)`
- `def signature(self) -> Dict[str, Any]`
- `def forward(self, fields, coords, derived = None)`

### Class: `rippl.physics.operators.elliptic.BiharmonicOperator`
"""
∇⁴u — plate bending, stream function. 4th order.
"""
Methods:
- `def __init__(self, field = 'u', spatial_dims = 2)`
- `def signature(self)`
- `def forward(self, fields, coords, derived = None)`

### Class: `rippl.physics.operators.elliptic.Gradient`
Methods:
- `def __init__(self, field = 'u', spatial_dims = None)`
- `def signature(self) -> Dict[str, Any]`
- `def forward(self, fields, coords, derived = None)`

### Class: `rippl.physics.operators.elliptic.Divergence`
Methods:
- `def __init__(self, field = 'u', spatial_dims = None)`
- `def signature(self) -> Dict[str, Any]`
- `def forward(self, fields, coords, derived = None)`

### Class: `rippl.physics.operators.elliptic.PressureGradient`
Methods:
- `def __init__(self, field_p = 'p', direction = 0)`
- `def signature(self)`
- `def forward(self, fields, coords, derived = None)`

### Class: `rippl.physics.operators.elliptic.VelocityDivergence`
Methods:
- `def __init__(self, field_u = 'u', field_v = 'v')`
- `def signature(self)`
- `def forward(self, fields, coords, derived = None)`

### Class: `rippl.physics.operators.elliptic.StrainTensor`
Methods:
- `def __init__(self, field_ux = 'ux', field_uy = 'uy')`
- `def signature(self)`
- `def forward(self, fields, coords, derived = None)`

### Class: `rippl.physics.operators.elliptic.StressTensor`
Methods:
- `def __init__(self, lame_lambda = 1.0, lame_mu = 1.0)`
- `def signature(self)`
- `def forward(self, fields, coords, derived = None)`

### Class: `rippl.physics.operators.elliptic.ElasticEquilibrium`
Methods:
- `def __init__(self, field_ux = 'ux', field_uy = 'uy', lame_lambda = 1.0, lame_mu = 1.0, body_force_x = 0.0, body_force_y = 0.0)`
- `def signature(self)`
- `def forward(self, fields, coords, derived = None)`

### Class: `rippl.physics.operators.elliptic.ArtificialViscosity`
"""
Dynamic diffusion injected where |∇u| exceeds threshold.
Prevents NaN in near-shock regions without custom CUDA kernels.
Uses open-source PyTorch ops only.

u_visc = epsilon(x) * Δu
epsilon(x) = epsilon_max * r(x) / (max(r) + 1e-8)
where r(x) = local residual magnitude

Only activates where |∇u| > gradient_threshold.
"""
Methods:
- `def __init__(self, field: str = 'u', epsilon_max: float = 0.1, gradient_threshold: float = 10.0, spatial_dims: int = None)`
- `def signature(self) -> dict`
- `def forward(self, fields: dict, coords: torch.Tensor, derived: dict = None) -> torch.Tensor`

### Class: `rippl.physics.operators.elliptic.HelmholtzOperator`
"""
Helmholtz: ∇²u + k²u = 0
Time-harmonic wave equation. k = wavenumber.
Residual: u_xx + u_yy + k²u (in 2D)
"""
Methods:
- `def __init__(self, k: float = 1.0, field: str = 'u', spatial_dims: int = None)`
- `def signature(self)`
- `def forward(self, fields, coords, derived = None)`

### Class: `rippl.physics.operators.elliptic.Curl`
"""
2D curl: ∇×F = v_x - u_y (scalar vorticity)
3D curl: (w_y-v_z, u_z-w_x, v_x-u_y) (vector)
Args:
    field_u, field_v, field_w: component field names
    dims: 2 or 3
"""
Methods:
- `def __init__(self, field_u = 'u', field_v = 'v', field_w = 'w', dims = 2)`
- `def signature(self)`
- `def forward(self, fields, coords, derived = None)`

### Class: `rippl.physics.operators.elliptic.VectorLaplacian`
"""
Vector Laplacian: ∇²F component-wise.
∇²(u,v) = (∇²u, ∇²v)
Used in NS viscous term for vector velocity fields.
"""
Methods:
- `def __init__(self, fields_list = None, spatial_dims = None)`
- `def signature(self)`
- `def forward(self, fields, coords, derived = None)`

### Class: `rippl.physics.operators.elliptic.EikonalOperator`
"""
Eikonal equation: |∇u| = 1
Covers: distance functions, wave front tracking,
        optimal control, geometric optics
"""
Methods:
- `def compute_pointwise_residual(self, fields, coords)`
- `def residual(self, fields, coords)`
- `def compute_loss(self, fields, coords)`

### Class: `rippl.physics.operators.geometric.LevelSetOperator`
"""
Tracks interface via Level Set Equation: ∂φ/∂t + v·∇φ = 0.
Supports constant velocity, field-based velocity, or callable velocity.
"""
Methods:
- `def __init__(self, velocity: Union[str, torch.Tensor, Callable] = None, field: str = 'phi', spatial_dims: int = None)`
- `def signature(self) -> Dict[str, Any]`
- `def forward(self, fields: Dict[str, torch.Tensor], coords: torch.Tensor, derived: Dict[str, torch.Tensor] = None) -> torch.Tensor`

### Class: `rippl.physics.operators.hyperbolic.Advection`
Methods:
- `def __init__(self, v: float, field: str = 'u')`
- `def signature(self) -> Dict[str, Any]`
- `def forward(self, fields, coords, derived = None)`

### Class: `rippl.physics.operators.hyperbolic.BurgersAdvection`
Methods:
- `def __init__(self, field = 'u', spatial_dim = 0)`
- `def signature(self)`
- `def forward(self, fields, coords, derived = None)`

### Class: `rippl.physics.operators.hyperbolic.NonlinearAdvection`
Methods:
- `def __init__(self, field_u = 'u', field_v = 'v')`
- `def signature(self)`
- `def forward(self, fields, coords, derived = None)`

### Class: `rippl.physics.operators.hyperbolic.WaveOperator`
"""
Wave equation: ∂²u/∂t² - c²∂²u/∂x² = 0
Covers: acoustic waves, seismic, electromagnetic propagation.
"""
Methods:
- `def __init__(self, c: float = 1.0, spatial_dims: int = 1)`
- `def compute_pointwise_residual(self, fields, coords)`
- `def residual(self, fields, coords)`
- `def compute_loss(self, fields, coords)`

### Class: `rippl.physics.operators.maxwell_frequency.FrequencyMaxwellResidual`
"""
2D frequency-domain Maxwell (TE polarization).

Solves for complex field amplitude E_z(x,y) at angular frequency ω.

Governing equation:
    ∇²E_z + k²E_z = -iωμJ_z
    where k² = ω²μεₒεᵣ - iωμσ

Real and imaginary parts are output as two separate channels.
The network output format: [E_z_real, E_z_imag]
"""
Methods:
- `def __init__(self, omega: float, epsilon_r: float = 1.0, mu_r: float = 1.0, sigma: float = 0.0, epsilon_0: float = 8.854e-12, mu_0: float = 1.257e-06, source_fn = None)`
- `def residual(self, fields: dict, coords: torch.Tensor) -> torch.Tensor`
  - Compute frequency-domain Maxwell residual.

### Class: `rippl.physics.operators.maxwell_frequency.PMLBoundaryCondition`
"""
Perfectly Matched Layer for open-domain electromagnetic problems.

The PML is an absorbing region near domain boundaries that
prevents artificial reflections from truncating an infinite domain.

The PML modifies the wave equation in the absorbing region by
adding a complex coordinate stretching: x → x + iσ(x)/ω

Implementation: adds a complex damping loss in the PML region.
Points inside the PML have their residual scaled by a complex factor.

Args:
    thickness:   PML thickness as fraction of domain size (default: 0.1)
    sigma_max:   Maximum absorption coefficient
    polynomial_order: Grading order (higher = more gradual)
"""
Methods:
- `def __init__(self, thickness: float = 0.1, sigma_max: float = 100.0, polynomial_order: int = 2)`
- `def pml_mask(self, coords: torch.Tensor, domain) -> torch.Tensor`
  - Compute PML absorption coefficient at each point.
- `def modify_residual(self, residual: torch.Tensor, coords: torch.Tensor, domain, omega: float) -> torch.Tensor`
  - Apply PML absorption to residual in the PML region.

### Class: `rippl.physics.operators.nonlinear.Nonlinear`
Methods:
- `def __init__(self, fn, field: str = 'u')`
- `def signature(self) -> Dict[str, Any]`
- `def forward(self, fields, coords, derived = None)`

### Class: `rippl.physics.operators.nonlinear.CahnHilliardOperator`
Methods:
- `def __init__(self, M: float = 1.0, epsilon: float = 0.1, field_phi: str = 'phi', field_mu: str = 'mu')`
- `def signature(self) -> dict`
- `def forward(self, fields, coords, derived = None)`
- `def chemical_potential_residual(self, fields, coords, derived = None)`

### Class: `rippl.physics.operators.nonlinear.AllenCahnOperator`
Methods:
- `def __init__(self, M: float = 1.0, epsilon: float = 0.1, field: str = 'phi')`
- `def signature(self) -> dict`
- `def forward(self, fields, coords, derived = None)`

### Class: `rippl.physics.operators.nonlinear.TuringOperator`
"""
Turing activator-inhibitor pattern formation.
∂u/∂t = Du∇²u + f(u,v)
"""
Methods:
- `def __init__(self, Du: float = 0.01, a: float = 0.1, b: float = 0.9)`
- `def compute_pointwise_residual(self, fields, coords)`
- `def residual(self, fields, coords)`
- `def compute_loss(self, fields, coords)`

### Class: `rippl.physics.operators.nonlinear.FitzHughNagumoOperator`
"""
FitzHugh-Nagumo model: cardiac action potential / excitable media.
∂v/∂t = ε(∇²v + v - v³/3 - w + I)
"""
Methods:
- `def __init__(self, eps: float = 0.1, a: float = 0.1, I_ext: float = 0.0)`
- `def compute_pointwise_residual(self, fields, coords)`
- `def residual(self, fields, coords)`
- `def compute_loss(self, fields, coords)`

### Class: `rippl.physics.operators.parabolic.TimeDerivative`
Methods:
- `def __init__(self, order: int = 1, field: str = None)`
- `def signature(self) -> Dict[str, Any]`
- `def forward(self, fields: dict, coords: torch.Tensor, derived: dict = None)`

### Class: `rippl.physics.operators.parabolic.Diffusion`
Methods:
- `def __init__(self, alpha: float, field: str = None)`
- `def signature(self) -> Dict[str, Any]`
- `def forward(self, fields: dict, coords, derived: dict = None)`

### Class: `rippl.physics.operators.quantum.SchrodingerKinetic`
Methods:
- `def __init__(self, hbar = 1.0, mass = 1.0, field_real = 'psi_real', field_imag = 'psi_imag')`
- `def signature(self)`
- `def forward(self, fields, coords, derived = None)`

### Class: `rippl.physics.operators.quantum.PotentialTerm`
Methods:
- `def __init__(self, potential_fn, field_real = 'psi_real', field_imag = 'psi_imag')`
- `def signature(self)`
- `def forward(self, fields, coords, derived = None)`

### Class: `rippl.physics.operators.quantum.SchrodingerTimeEvolution`
Methods:
- `def __init__(self, hbar = 1.0, field_real = 'psi_real', field_imag = 'psi_imag')`
- `def signature(self)`
- `def forward(self, fields, coords, derived = None)`

### Class: `rippl.physics.operators.quantum.GPEOperator`
"""
Gross-Pitaevskii equation for Bose-Einstein condensates.
iℏ∂ψ/∂t = -(ℏ²/2m)∇²ψ + V(x)ψ + g|ψ|²ψ
Simplified real form for PINN training.
"""
Methods:
- `def __init__(self, g: float = 1.0, hbar: float = 1.0, m: float = 1.0)`
- `def compute_pointwise_residual(self, fields, coords)`
- `def residual(self, fields, coords)`
- `def compute_loss(self, fields, coords)`

### Class: `rippl.physics.operators.source.Source`
Methods:
- `def __init__(self, fn, field: str = 'u')`
- `def signature(self) -> Dict[str, Any]`
- `def forward(self, fields, coords, derived = None)`

### Class: `rippl.physics.operators.source.SourceTerm`
"""
Generic source/forcing term: f(coords)
Adds arbitrary callable RHS to equation.
Residual contribution: -f(coords)
Usage: Equation([Laplacian(), SourceTerm(lambda x: x[:,0:1])])
means: u_xx = f(x)
"""
Methods:
- `def __init__(self, source_fn: callable = None, value: float = 0.0, field: str = 'u')`
- `def signature(self)`
- `def forward(self, fields, coords, derived = None)`

### Class: `rippl.pipeline.__init__.PipelineStep`
Methods:
- `def __init__(self, name: str, domain = None, equation = None, model = None, epochs: int = 1000, receives: dict = None, system = None, kwargs: dict = None)`
- `def execute(self, context: Dict[str, Any]) -> Dict[str, Any]`

### Class: `rippl.pipeline.__init__.PipelineResult`
Methods:
- `def __init__(self, step_results: Dict[str, Any])`

### Class: `rippl.pipeline.__init__.Pipeline`
"""
Manages sequential and iterative multi-physics coupling.
"""
Methods:
- `def __init__(self, steps: Optional[List[PipelineStep]] = None, coupling: str = 'sequential')`
- `def add(self, step: PipelineStep)`
- `def run(self, deploy_backend: str = 'local', verbose: bool = False) -> PipelineResult`
- `def run_sequential(self, initial_context: Dict[str, Any] = None) -> Dict[str, Any]`
- `def run_iterative(self, max_iterations: int = 5, tolerance: float = 0.0001, initial_context: Dict[str, Any] = None) -> Dict[str, Any]`

### Function: `rippl.plugins.registry.register_kernel`
`def register_kernel(name: str, cuda_fn: Optional[Callable] = None, cpu_fn: Optional[Callable] = None, fn: Optional[Callable] = None, signature: Optional[str] = None, ir_node_type = None, foundry_only: bool = False, description: str = '') -> None`
"""
Register a custom kernel with the rippl framework.

Args:
    name:         unique kernel name (accessible via get_kernel(name))
    cuda_fn:      CUDA/Triton implementation (optional)
    cpu_fn:       CPU/PyTorch fallback (required if signature provided)
    fn:           single callable (no dispatch — just register by name)
    signature:    torch.library op signature string
                  e.g. "my_op(Tensor u, float dx) -> Tensor"
                  If provided, registers in torch.ops.rippl namespace
    ir_node_type: IR node type this kernel handles (for auto-routing)
    foundry_only: if True, requires foundry key (soft degradation if missing)
    description:  human-readable description for rp.compiler_status()

Raises:
    ValueError: if name conflicts with built-in rippl kernel
    TypeError:  if neither fn nor cpu_fn is provided
"""

### Function: `rippl.plugins.registry.get_kernel`
`def get_kernel(name: str) -> Callable`
"""
Get a registered kernel by name.

Returns the appropriate implementation (CUDA or CPU)
based on current device availability and auth status.

Usage:
    op = rp.get_kernel('my_custom_laplacian')
    result = op(u_field, dx=0.01)
"""

### Function: `rippl.plugins.registry.list_kernels`
`def list_kernels() -> dict`
"""
List all registered user kernels.

Returns:
    dict mapping name → description
"""

### Class: `rippl.sampling.spectral.ChebyshevSampler`
Methods:
- `def __init__(self, dom, n_per_dim = 32)`
- `def sample(self)`

### Class: `rippl.sampling.spectral.LegendreSampler`
Methods:
- `def __init__(self, dom, n_per_dim = 32)`
- `def sample(self)`

### Function: `rippl.setup.ingest.from_dataframe`
`def from_dataframe(df: pd.DataFrame, coord_cols: List[str], field_cols: List[str], domain = None) -> Dict[str, Any]`
"""
Ingests data from a pandas DataFrame.
"""

### Function: `rippl.setup.ingest.from_arrays`
`def from_arrays(coords: np.ndarray, fields: Dict[str, np.ndarray], domain = None) -> Dict[str, Any]`
"""
Ingests data from numpy arrays.
"""

### Function: `rippl.setup.ingest.ingest`
`def ingest(data) -> Dict[str, Any]`
"""
Generic ingestion router.
"""

### Class: `rippl.setup.observe.HeatDiffusion`
Methods:
- `def __init__(self, trainable = True, k = 1.0)`
- `def residual(self, fields, coords)`

### Class: `rippl.setup.observe.WaveEquation`
Methods:
- `def __init__(self, trainable = True, c = 1.0)`
- `def residual(self, fields, coords)`

### Class: `rippl.setup.observe.LinearElasticity`
Methods:
- `def __init__(self, trainable = True, E = 1.0, nu = 0.3)`
- `def residual(self, fields, coords)`

### Class: `rippl.setup.observe.NavierStokes`
Methods:
- `def __init__(self, trainable = True, nu = 0.01)`
- `def residual(self, fields, coords)`

### Class: `rippl.setup.observe.ReactionDiffusion`
Methods:
- `def __init__(self, trainable = True, D = 1.0)`
- `def residual(self, fields, coords)`

### Class: `rippl.setup.observe.FrequencyMaxwellResidual`
Methods:
- `def __init__(self, trainable = True, omega = Any)`
- `def residual(self, fields, coords)`

### Class: `rippl.setup.observe.Template`
Methods:

### Class: `rippl.setup.observe.CandidateFit`
Methods:

### Class: `rippl.setup.observe.PhysicsSetup`
Methods:
- `def suggested_model(self)`
- `def unpack(self)`
- `def explain(self) -> str`

### Function: `rippl.setup.observe.observe`
`def observe(data, hint: Optional[str] = None, trial_epochs: int = 300) -> PhysicsSetup`

### Class: `rippl.solvers.fd_solver.FDSolver`
Methods:
- `def __init__(self, order = 2)`
- `def laplacian(self, u, dx, axis = 1)`

### Function: `rippl.solvers.fd_solver.solve_diffusion_fd_1d`
`def solve_diffusion_fd_1d(u0: torch.Tensor, steps: int, alpha: float, dt: float, dx: float, order: int = 2) -> torch.Tensor`
"""
Solve 1D Diffusion Equation u_t = alpha * u_xx using Finite Difference.
"""

### Function: `rippl.solvers.fd_solver.solve_advection_fd_1d`
`def solve_advection_fd_1d(u0: torch.Tensor, steps: int, v: float, dt: float, dx: float) -> torch.Tensor`
"""
Solve 1D Advection u_t = -v * u_x using Upwind.
"""

### Function: `rippl.solvers.fd_solver.solve_advdiff_fd_1d`
`def solve_advdiff_fd_1d(u0: torch.Tensor, steps: int, alpha: float, v: float, dt: float, dx: float) -> torch.Tensor`
"""
Solve Advection-Diffusion.
"""

### Function: `rippl.solvers.fd_solver.solve_wave_fd_1d`
`def solve_wave_fd_1d(u0: torch.Tensor, v0: torch.Tensor, c: float, dt: float, dx: float, steps: int, order: int = 2) -> torch.Tensor`
"""
Solve 1D Wave Equation u_tt = c^2 u_xx using Finite Difference.

Args:
    u0 (torch.Tensor): Initial position (B, N, 1).
    v0 (torch.Tensor): Initial velocity (B, N, 1).
    c (float): Wave speed.
    dt (float): Time step.
    dx (float): Spatial step.
    steps (int): Number of time steps.
    
Returns:
    torch.Tensor: Trajectory (B, steps+1, N, 1).
"""

### Function: `rippl.solvers.fd_solver.solve_wave_fd_2d`
`def solve_wave_fd_2d(u0: torch.Tensor, v0: torch.Tensor, c: float, dt: float, dx: float, dy: float, steps: int) -> torch.Tensor`
"""
Solve 2D Wave Equation using FD.

Args:
    u0 (torch.Tensor): (B, H, W, 1).
    v0 (torch.Tensor): (B, H, W, 1).
    c, dt, dx, dy: Parameters.
    steps: Time steps.
    
Returns:
    torch.Tensor: (B, steps+1, H, W, 1).
"""

### Function: `rippl.solvers.fd_solver.solve_reaction_diffusion_fd_1d`
`def solve_reaction_diffusion_fd_1d(u0: torch.Tensor, steps: int, alpha: float, equation, dt: float, dx: float) -> torch.Tensor`
"""
Solve 1D Reaction-Diffusion u_t = alpha*u_xx + f(u,x,t) using FD.
"""

### Function: `rippl.solvers.fd_solver.solve_damped_wave_fd_1d`
`def solve_damped_wave_fd_1d(u0: torch.Tensor, v0: torch.Tensor, beta: float, c: float, dt: float, dx: float, steps: int) -> torch.Tensor`
"""
Solve 1D Damped Wave Equation u_tt + beta*u_t = c^2*u_xx.
"""

### Function: `rippl.solvers.spectral_solver.solve_periodic_spectral_1d`
`def solve_periodic_spectral_1d(u0: torch.Tensor, a: float, dt: float, steps: int, L: float = Any) -> torch.Tensor`
"""
Solve linear advection u_t + a u_x = 0 using Spectral method.
Periodic BC is implied by Fourier basis.

Args:
    u0 (torch.Tensor): Initial condition (B, N, 1).
    a (float): Advection speed.
    dt (float): Time step.
    steps (int): Number of steps.
    L (float): Domain length (default 2pi).
    
Returns:
    torch.Tensor: (B, steps+1, N, 1).
"""

### Class: `rippl.surge.global_attention.GlobalVirtualNode`
"""
Every local node reads from and writes to one shared global token.
This propagates information across the ENTIRE geometry in one hop,
fixing the shockwave / long-range electrostatics failure mode that
a k=16 local graph cannot represent.

Memory cost: O(N) — linear in node count, not O(N^2).
"""
Methods:
- `def __init__(self, hidden_dim: int)`
- `def forward(self, node_features: torch.Tensor) -> torch.Tensor`
  - node_features: (N, hidden_dim)

### Class: `rippl.surge.global_attention.MultiScalePooling`
"""
Hierarchical coarsening: cluster nodes into K super-nodes via
farthest-point sampling, message-pass at the coarse scale,
then un-pool back to the original resolution.

This is the standard fix for long-range dependency capture in
large point clouds without O(N^2) attention cost.
"""
Methods:
- `def __init__(self, hidden_dim: int, n_clusters: int = 64)`
- `def forward(self, node_features: torch.Tensor, coords: torch.Tensor) -> torch.Tensor`

### Function: `rippl.surge.gnn.build_knn_graph`
`def build_knn_graph(coords, k = 4)`

### Class: `rippl.surge.gnn.SurgeGNN`
Methods:
- `def __init__(self, in_dim = 8, hidden_dim = 16, k = 4)`
- `def forward(self, node_features, coords, topology = None)`

### Class: `rippl.surge.gnn_operator.EdgeConv`
"""
Edge convolution layer for point cloud processing.

For each node i:
  Aggregates messages from neighbors j:
  m_ij = MLP([h_i, h_j - h_i])
  h_i' = max_j(m_ij)

This is the DGCNN-style edge convolution.
Pure PyTorch — no torch_geometric needed.
"""
Methods:
- `def __init__(self, in_features: int, out_features: int, k: int = 8)`
- `def get_knn_graph(self, pos: torch.Tensor) -> torch.Tensor`
  - Build k-nearest neighbor graph from positions.
- `def forward(self, h: torch.Tensor, pos: torch.Tensor, neighbors: Optional[torch.Tensor] = None) -> torch.Tensor`

### Class: `rippl.surge.gnn_operator.PhysicsGNN`
"""
Physics-informed Graph Neural Network for operator learning.

Learns to map (geometry + parameters) → solution field.
Works for any physics domain — no domain-specific knowledge encoded.

Input node features:
  [x, y, z,           (3D spatial position)
   sdf,               (signed distance to boundary, >0 inside)
   boundary_flag,     (1.0 if boundary node, 0.0 if interior)
   param_1, ..., param_k]  (problem parameters)

Output:
  Solution field value at each node (scalar or vector)
"""
Methods:
- `def __init__(self, n_params: int = 1, spatial_dims: int = 3, hidden_dim: int = 128, n_layers: int = 6, k_neighbors: int = 8, out_dim: int = 1)`
- `def forward(self, pos: torch.Tensor, sdf: torch.Tensor, boundary: torch.Tensor, params: torch.Tensor, neighbors: Optional[torch.Tensor] = None) -> torch.Tensor`

### Class: `rippl.surge.rom.Snapshot`
Methods:

### Class: `rippl.surge.rom.ROMReport`
Methods:

### Class: `rippl.surge.rom.ROMQueryResult`
Methods:

### Class: `rippl.surge.rom.POD_ROM`
Methods:
- `def __init__(self, snapshots: List[Snapshot])`
- `def query(self, params: Dict[str, float]) -> np.ndarray`
- `def mahalanobis_distance(self, params: Dict[str, float]) -> float`
- `def is_ood(self, params: Dict[str, float], sigma_threshold: float = 3.0) -> bool`
- `def query_confidence(self, params: Dict[str, float]) -> float`
- `def query_with_check(self, params: Dict[str, float]) -> ROMQueryResult`

### Class: `rippl.surge.rom.RBF_ROM`
Methods:
- `def __init__(self, params: List[Dict[str, float]], fields: List[Union[List[float], np.ndarray]])`
- `def query(self, params: Dict[str, float]) -> np.ndarray`

### Function: `rippl.surge.rom.fit`
`def fit(snapshots_or_params, fields_or_mode = None, mode = 'pod')`

### Class: `rippl.surge.surge_gnn.SurgeGNN`
"""
Geometry-aware SURGE neural operator.

Works for any combination of:
  - Any PDE satisfying the .residual() protocol
  - Any CAD geometry (STL/OBJ/STEP)
  - Any parameter space

The training pipeline:
  1. Load geometry, compute SDF
  2. For each (geometry_variation, parameters):
       Sample interior + boundary points
       Solve with rippl PINN
       Store (point_cloud, solution) pair
  3. Train PhysicsGNN on collected dataset
  4. Serve fast inference on new geometries

Args:
    equation_factory:  callable(params) → equation with .residual()
                      OR static equation object
    parameter_space:   {'param': (min, max)} — problem parameters
    geometry_path:     path to base geometry (STL/OBJ/STEP)
    geometry_factory:  optional callable(params) → geometry_path
                      for geometry that varies with parameters
    spatial_dims:      2 or 3
    n_interior:        collocation points per geometry
    n_boundary:        boundary points per geometry
"""
Methods:
- `def __init__(self, equation_factory, parameter_space: dict, geometry_path: str, geometry_factory: Optional[Callable] = None, spatial_dims: int = 3, n_interior: int = 2000, n_boundary: int = 500, k_neighbors: int = 8, hidden_dim: int = 128, n_gnn_layers: int = 6)`
- `def train(self, n_samples: int = 200, pinn_epochs: int = 2000, gnn_epochs: int = 500, batch_size: int = 4, lr: float = 0.001, device: Optional[str] = None, verbose: bool = True) -> dict`
  - Full SurgeGNN training pipeline.
- `def infer(self, params: dict, geometry_path: Optional[str] = None, n_query: int = 1000) -> dict`
  - Fast inference for new parameters (and optionally new geometry).
- `def benchmark_speedup(self, n_trials: int = 5) -> dict`
  - Measure speedup vs running full PINN.
- `def save(self, path: str)`
  - Save trained SurgeGNN operator.
- `def load(cls, path: str, equation_factory, geometry_path: str) -> 'SurgeGNN'`
  - Load a saved SurgeGNN operator.

### Class: `rippl.surge.universal.UniversalSurge`
"""
Universal SURGE operator.
Works for any equation with a .residual() method.

Args:
    equation_factory: callable(params) → equation with .residual()
                     OR a static equation (no parameters)
    parameter_space:  dict of {param_name: (min_val, max_val)}
                     Use {} for single fixed equation
    domain:           rippl Domain
    field_name:       solution field name
    nx:               number of spatial points for operator training
    operator_type:    'fno' (structured grid) or 'mlp' (parameter mapping)
"""
Methods:
- `def __init__(self, equation_factory, parameter_space: dict, domain: Domain, field_name: str = 'u', nx: int = 64, operator_type: str = 'fno')`
- `def train(self, n_samples: int = 500, pinn_epochs: int = 2000, operator_epochs: int = 500, batch_size: int = 32, lr: float = 0.001, device: Optional[str] = None, verbose: bool = True) -> dict`
  - Full SURGE training pipeline.
- `def infer(self, params: dict) -> torch.Tensor`
  - Fast inference for one parameter combination.
- `def infer_batch(self, params_list: list) -> torch.Tensor`
  - Batch inference — all parameter combinations at once.
- `def benchmark_speedup(self, n_benchmark: int = 10) -> dict`
  - Measure actual speedup vs rerunning PINN for each query.
- `def save(self, path: str)`
  - Save trained SURGE operator.
- `def load(cls, path: str, equation_factory, domain: Domain) -> 'UniversalSurge'`
  - Load a saved SURGE operator.

### Class: `rippl.surge.universal.SurgeFNOOperator`
"""
FNO-based operator: parameters → solution field.

Architecture:
  1. Project parameters to spatial embedding
  2. FNO layers in frequency domain
  3. Project to solution
"""
Methods:
- `def __init__(self, n_params, nx, n_modes = 16, width = 64)`
- `def forward(self, params)`

### Class: `rippl.surge.universal.SpectralConv1dSimple`
"""
Simple 1D spectral convolution for SURGE operator.
"""
Methods:
- `def __init__(self, in_channels, out_channels, n_modes)`
- `def forward(self, x)`

### Class: `rippl.surge.universal.SurgeMLPOperator`
"""
MLP-based operator for low-dimensional parameter spaces.
parameters → solution field via deep network.
"""
Methods:
- `def __init__(self, n_params, output_size, hidden = 256)`
- `def forward(self, params)`

### Class: `rippl.surge.__init__.PhysicallyInconsistentError`
Methods:

### Function: `rippl.surge.__init__.predict`
`def predict(cad_path: str, model_path: str)`

### Function: `rippl.testing.test_distributed.test_distributed_hardware_execution`
`def test_distributed_hardware_execution()`

### Function: `rippl.testing.test_distributed.test_mock_distributed_cpu_smoke`
`def test_mock_distributed_cpu_smoke()`

### Class: `rippl.training.accelerate_engine.AccelerateEngine`
"""
Thin Accelerate wrapper that preserves rippl's three-phase training recipe.

The key design constraint: we do NOT let Accelerate own the training loop.
We use Accelerate only for:
1. Device placement (model, optimizer, dataloader)
2. Mixed precision (automatic scaling)
3. Gradient synchronization across GPUs/nodes
4. Checkpoint saving/loading

rippl's Phase A/B/C recipe runs exactly as in single-GPU mode.
Accelerate is invisible infrastructure.

Args:
    precision: 'fp32', 'fp16', 'bf16', 'fp8'
    gradient_accumulation_steps: accumulate before sync (saves memory)
    log_with: 'wandb', 'tensorboard', None
"""
Methods:
- `def __init__(self, precision: str = 'fp32', gradient_accumulation_steps: int = 1, log_with: Optional[str] = None, project_name: str = 'rippl')`
- `def prepare(self, model, optimizer, loader)`
  - Prepare model, optimizer, and dataloader for distributed training.
- `def backward(self, loss: torch.Tensor)`
  - Backward pass via Accelerate (handles mixed precision scaling).
- `def clip_grad_norm(self, parameters, max_norm: float = 1.0)`
  - Gradient clipping compatible with mixed precision.
- `def is_gradient_sync_step(self) -> bool`
  - True when gradients will be synchronized this step.
- `def log_metrics(self, metrics: dict, step: int)`
  - Log metrics to configured logger (W&B, tensorboard, etc.)
- `def save_checkpoint(self, path: str, **state)`
  - Save checkpoint in Accelerate-compatible format.
- `def load_checkpoint(self, path: str)`
  - Load checkpoint.
- `def unwrap_model(self, model) -> torch.nn.Module`
  - Unwrap DDP/FSDP wrapper to get the base model.
- `def wait_for_everyone(self)`
  - Barrier synchronization across all processes.
- `def print(self, *args, **kwargs)`
  - Print only on main process.
- `def num_processes(self) -> int`
- `def process_index(self) -> int`
- `def broadcast_dynamic_shapes(self, tensor: torch.Tensor, pad_to_max: bool = True) -> Tuple[torch.Tensor, torch.Tensor]`
  - Broadcast tensor with dynamic shape across distributed processes.
- `def sync_rar_points(self, new_points: torch.Tensor) -> torch.Tensor`
  - Synchronize new RAR points across all distributed processes.
- `def synchronize_rar_firing(self, should_fire: bool) -> bool`

### Class: `rippl.training.adaptive.AdaptWt`
Methods:
- `def __init__(self, n, init = 1.0)`
- `def forward(self, r)`

### Class: `rippl.training.adaptive.TimeCurr`
Methods:
- `def __init__(self, t0, t1, stg = 5, pat = 500)`
- `def t_max(self)`
- `def step(self)`
- `def filter(self, x)`

### Class: `rippl.training.adaptive_sampler.AdaptiveCollocationSampler`
Methods:
- `def __init__(self, domain, n_points = 5000, n_candidates = 50000, update_freq = 500, device = 'cpu')`
- `def initial_sample(self) -> torch.Tensor`
- `def update(self, model, equation, epoch) -> torch.Tensor`
- `def current_points(self) -> torch.Tensor`

### Class: `rippl.training.adaptive_sampler.SelfAdaptiveWeights`
"""
Self-adaptive PINN training weights (McClenny & Braga-Neto 2022).
Tracks a learnable weight for each collocation point.
"""
Methods:
- `def __init__(self, n_points: int, init_value: float = 1.0)`
- `def forward(self, pointwise_residual: torch.Tensor) -> torch.Tensor`

### Class: `rippl.training.async_loader.AsyncCollocationLoader`
"""
Double-buffered async collocation point generator.

Generates collocation batches on CPU worker threads while
GPU trains on the previous batch. Eliminates GPU starvation.

Args:
    domain:        rippl Domain for bounds
    batch_size:    collocation points per batch
    n_workers:     number of CPU worker threads
    pin_memory:    use pinned memory for fast PCIe transfers
    prefetch_size: number of batches to pre-generate
"""
Methods:
- `def __init__(self, domain, batch_size: int = 2048, n_workers: int = 2, pin_memory: bool = True, prefetch_size: int = 4)`
- `def register_rar_fn(self, fn: Callable)`
  - Register a function that generates additional RAR points.
- `def next_batch(self, timeout: float = 5.0) -> torch.Tensor`
  - Get next pre-generated collocation batch.
- `def to_loader(self, device: torch.device, n_batches: int = 1) -> DataLoader`
  - Get a DataLoader using pre-generated batches.
- `def shutdown(self)`
  - Stop all worker threads cleanly.

### Function: `rippl.training.boundary_sampler.sample_boundary_layer`
`def sample_boundary_layer(domain, sdf_fn: Callable, n_points: int = 512, layer_thickness: float = None, n_candidates: int = 10000) -> torch.Tensor`
"""
Sample collocation points concentrated in the boundary layer.

Strategy:
1. Sample n_candidates points uniformly in the domain
2. Compute SDF at all candidates
3. Keep only points within layer_thickness of the boundary
4. If insufficient points, decrease thickness until n_points are obtained

Args:
    domain:          rippl Domain object
    sdf_fn:          Callable that computes signed distance at coords
    n_points:        Number of boundary layer points to return
    layer_thickness: Distance from boundary to include.
                     Auto-detects as 0.05 * min(domain_extent) if None
    n_candidates:    Candidates to evaluate (more = better coverage)

Returns:
    (n_points, d) tensor of boundary layer collocation points
"""

### Function: `rippl.training.boundary_sampler.sample_high_gradient_regions`
`def sample_high_gradient_regions(model: torch.nn.Module, domain, n_points: int = 256, n_candidates: int = 5000, field_name: str = 'u') -> torch.Tensor`
"""
Sample points where the solution gradient magnitude is largest.

These are regions of rapid spatial variation — physically important
for accuracy even if the PDE residual there is already small.

Args:
    model:        Trained/partially-trained rippl model
    domain:       rippl Domain
    n_points:     Points to return
    n_candidates: Candidates to evaluate
    field_name:   Which field to check gradient of

Returns:
    (n_points, d) tensor of high-gradient collocation points
"""

### Function: `rippl.training.boundary_sampler.combined_adaptive_sampling`
`def combined_adaptive_sampling(model: torch.nn.Module, domain, equation, n_total: int = 2048, tier_weights: tuple = 0.5, 0.3, 0.2, sdf_fn: Optional[Callable] = None, layer_thickness: Optional[float] = None, device: torch.device = None) -> torch.Tensor`
"""
Three-tier adaptive sampling combining RAR + boundary layer + gradient.

Tier weights sum to 1.0:
    tier_weights[0]: Standard RAR (interior residual-based)
    tier_weights[1]: Boundary layer densification (requires sdf_fn)
    tier_weights[2]: High-gradient region sampling

If sdf_fn is None, tier_weights[1] is redistributed to [0].

Args:
    model:          Current model
    domain:         rippl Domain
    equation:       rippl equation (for residual computation)
    n_total:        Total points to return
    tier_weights:   Fraction of points per tier
    sdf_fn:         Optional SDF function for boundary layer detection
    layer_thickness: Boundary layer thickness (auto if None)
    device:         Target device

Returns:
    (n_total, d) combined collocation tensor
"""

### Class: `rippl.training.callbacks.Callback`
"""
Base class for training callbacks.
"""
Methods:
- `def on_train_begin(self, logs: Dict[str, Any] = Any) -> None`
- `def on_epoch_end(self, epoch: int, logs: Dict[str, Any] = Any) -> None`
- `def on_train_end(self, logs: Dict[str, Any] = Any) -> None`

### Class: `rippl.training.callbacks.CheckpointCallback`
"""
Callback to save model checkpoints.
"""
Methods:
- `def __init__(self, save_dir: str, save_freq: int = 10, prefix: str = 'model')`
- `def on_epoch_end(self, epoch: int, logs: Dict[str, Any] = Any) -> None`

### Class: `rippl.training.callbacks.RARCallback`
"""
Residual-based Adaptive Refinement Callback using Sobol points.
"""
Methods:
- `def __init__(self, freq: int = 10, K: int = 100)`
- `def on_train_epoch_end(self, trainer, pl_module)`

### Class: `rippl.training.checkpoint.TrainingCheckpoint`
"""
Manages save/resume of PINN training state.

Usage:
    result = rp.run(
        domain, equation, model,
        epochs=10000,
        checkpoint_dir='./rippl_checkpoints',
        checkpoint_freq=500,  # save every 500 epochs
        resume=True,          # resume from latest if exists
    )
"""
Methods:
- `def __init__(self, checkpoint_dir: str = './rippl_checkpoints', freq: int = 500, max_keep: int = 5, prefix: str = 'rippl_ckpt')`
- `def should_save(self, epoch: int) -> bool`
- `def save(self, epoch: int, model: torch.nn.Module, optimizer: torch.optim.Optimizer, loss_history: list, config: Any = None, extra: Dict = None) -> str`
  - Save training state to disk.
- `def load_latest(self) -> Optional[Dict]`
  - Load the most recent checkpoint. Returns None if none exists.
- `def load(self, path: str) -> Optional[Dict]`
  - Load a specific checkpoint.
- `def restore(self, state: Dict, model: torch.nn.Module, optimizer: torch.optim.Optimizer) -> int`
  - Restore model + optimizer from checkpoint state.
- `def latest_epoch(self) -> int`
  - Return epoch of most recent checkpoint, or 0 if none.

### Class: `rippl.training.constraints.ConstraintCtx`
"""
Context manager for managing physics constraint applications during training.
"""
Methods:
- `def __init__(self, constraints: List[Any])`

### Class: `rippl.training.constraints.PhysicsConstraint`
"""
Enforces a physics-informed constraint (e.g. boundary or conservation).
"""
Methods:
- `def __init__(self, name: str, compute_fn: Callable[[Any, torch.Tensor], torch.Tensor], weight: float = 1.0)`
- `def compute_loss(self, model: torch.nn.Module, coords: torch.Tensor) -> torch.Tensor`

### Function: `rippl.training.constraints.apply_constraints`
`def apply_constraints(model: torch.nn.Module, constraints: List[PhysicsConstraint], coords: torch.Tensor) -> torch.Tensor`
"""
Computes total loss across all physics constraints.
"""

### Class: `rippl.training.constraint_impls.BaseConstraint`
"""
Base class for all Rippl constraints.
"""
Methods:
- `def compute_loss(self, model, device = 'cpu') -> torch.Tensor`

### Class: `rippl.training.constraint_impls.ObservationFit`
"""
Fits model output to observed data points.
Used for inverse problems and parameter identification.
"""
Methods:
- `def __init__(self, observations: List[Tuple[torch.Tensor, torch.Tensor]], weight: float = 1.0, field: str = 'u')`
- `def compute_loss(self, model, device = 'cpu') -> torch.Tensor`

### Class: `rippl.training.constraint_impls.Dirichlet`
Methods:
- `def __init__(self, coords: torch.Tensor, value: Union[Callable, torch.Tensor, float], field: str = 'u', weight: float = 1.0)`
- `def compute_loss(self, model, device = 'cpu') -> torch.Tensor`

### Class: `rippl.training.constraint_impls.Neumann`
Methods:
- `def __init__(self, coords: torch.Tensor, normal_dir: int, value: Union[Callable, torch.Tensor, float], field: str = 'u', weight: float = 1.0)`
- `def compute_loss(self, model, device = 'cpu') -> torch.Tensor`

### Class: `rippl.training.cuda_guard.CUDAGuard`
"""
Context manager that catches CUDA errors and recovers.

On OOM: reduces batch size, clears cache, retries.
On NaN: loads last checkpoint, reduces learning rate.
On device assert: resets CUDA context, reloads model.
"""
Methods:
- `def __init__(self, model: nn.Module, optimizer: torch.optim.Optimizer, checkpoint_fn: Optional[Callable] = None, reduce_on_oom: bool = True, verbose: bool = True)`
- `def safe_step(self, loss_fn: Callable[[], torch.Tensor], retry: bool = True) -> Optional[torch.Tensor]`
  - Execute one training step with hardware error protection.
- `def oom_count(self) -> int`
- `def nan_count(self) -> int`

### Function: `rippl.training.cuda_guard.check_gradient_health`
`def check_gradient_health(model: nn.Module, max_norm: float = 1000000.0, warn_norm: float = 1000.0) -> dict`
"""
Check gradient health after backward pass.

Returns dict with:
    'healthy':    bool — True if gradients are safe
    'max_grad':   float — maximum gradient value
    'has_nan':    bool — any NaN gradients
    'has_inf':    bool — any Inf gradients
    'exploding':  bool — gradients above warn_norm
"""

### Class: `rippl.training.curriculum.TemporalCurriculum`
"""
Temporal curriculum learning for time-dependent PDEs.

Filters collocation points to the current time window and expands
the window as training progresses.

Reference: Krishnapriyan et al. 2021, "Characterizing possible
failure modes in physics-informed neural networks."
"""
Methods:
- `def __init__(self, t_start: float, t_end: float, n_stages: int = 5, patience: int = 500)`
- `def t_max(self) -> float`
  - Returns the current maximum time threshold.
- `def filter_coords(self, coords: torch.Tensor) -> torch.Tensor`
  - Filters collocation points to retain only those within the current time window.
- `def step(self, loss_value: float = 0.0)`
  - Increments step counter. Advances to the next stage if epoch count

### Class: `rippl.training.distributed.DistributedTrainer`
Methods:
- `def __init__(self, model: torch.nn.Module, optimizer: torch.optim.Optimizer, **accelerator_kwargs)`
- `def prepare_dataloader(self, dataloader)`
- `def sync_dynamic_tensors(self, tensors_dict: Dict[str, torch.Tensor], pad_index: float = 0.0) -> Dict[str, torch.Tensor]`
  - Synchronize dynamic tensors across all ranks using pad_across_processes.
- `def step(self, loss: torch.Tensor)`
- `def print(self, *args, **kwargs)`
- `def is_main_process(self)`

### Class: `rippl.training.fbpinn.FBPINNSolver`
"""
Finite Basis Physics-Informed Neural Networks (FBPINN).
Decomposes domain into subdomains with overlapping windows.
Reference: Moseley et al. 2021
"""
Methods:
- `def __init__(self, domain, equation, n_subdomains: int = 10, overlap: float = 0.2, hidden_dim: int = 32)`
- `def window_fn(self, x: torch.Tensor, center: float) -> torch.Tensor`
  - w(x) = (1 - |x-center|/half)² * (1 + 2|x-center|/half) clamped to [0,1].
- `def forward(self, x: torch.Tensor) -> torch.Tensor`
- `def train_step(self, x: torch.Tensor, optimizer: torch.optim.Optimizer)`
- `def predict(self, x: torch.Tensor) -> torch.Tensor`

### Class: `rippl.training.fno_flywheel.FNOFlywheel`
"""
FNO Flywheel: uses high-fidelity FD solvers to generate datasets
for training Fourier Neural Operators.
"""
Methods:
- `def __init__(self, system, fno_model: FNO, n_train: int = 1000, n_test: int = 200, device: str = 'cpu')`
- `def generate_dataset(self, ic_fn: callable = None) -> tuple`
  - Generates random ICs and computes solutions via FD solver.
- `def train(self, epochs: int = 500, lr: float = 0.001, batch_size: int = 32) -> dict`
- `def evaluate(self, n_test: int = None) -> dict`
- `def pipeline(self, ic_fn: callable = None, train_epochs: int = 500, n_points: int = None, epochs: int = None, lr: float = 0.001, **kwargs) -> dict`

### Class: `rippl.training.inverse.TrainableParameter`
"""
A PDE parameter that will be identified during inverse training.

Usage:
    class MyPDE:
        def __init__(self):
            self.alpha = rp.trainable(0.1)  # initial guess
        
        def residual(self, fields, coords):
            u = fields['u']
            alpha = self.alpha.value  # use like a float
            ...
"""
Methods:
- `def __init__(self, initial_value: float, bounds: Optional[Tuple] = None)`
- `def value(self) -> torch.Tensor`
- `def item(self) -> float`

### Function: `rippl.training.inverse.collect_trainable_parameters`
`def collect_trainable_parameters(equation) -> List[nn.Parameter]`
"""
Extract all TrainableParameter instances from an equation object.
Returns their underlying nn.Parameter tensors for the optimizer.
"""

### Function: `rippl.training.inverse.record_identified_parameters`
`def record_identified_parameters(equation) -> Dict[str, float]`
"""
Extract current values of all identified parameters.
Called after training to report results.
"""

### Function: `rippl.training.inverse.compute_observation_loss`
`def compute_observation_loss(model: nn.Module, observations: List[Tuple[torch.Tensor, torch.Tensor]], weight: float = 1.0, field_index: int = 0) -> torch.Tensor`
"""
Compute data fidelity loss against sensor observations.

For each (sensor_coords, sensor_values) pair:
    L_obs = weight × ||model(sensor_coords) - sensor_values||²

This is summed over all observation sets.

Args:
    model:        The neural network
    observations: List of (coords, values) tuples
                  coords:  (N, d) tensor of sensor locations
                  values:  (N, 1) tensor of measured values
    weight:       Loss weight for data fidelity
    field_index:  Which output dimension to match (default: 0)

Returns:
    Scalar observation loss
"""

### Class: `rippl.training.inverse.InverseProblemConfig`
"""
Configuration for inverse problem training.
Extracted from RunConfig when inverse mode is active.
"""
Methods:
- `def __init__(self, observations: List[Tuple], observation_weight: float = 10.0, identify_parameters: bool = False, param_lr_multiplier: float = 0.1)`
- `def is_active(self) -> bool`

### Class: `rippl.training.lbfgs_config.LBFGSConfig`
"""
Validated LBFGS configurations for different PDE types.
"""
Methods:
- `def for_pde(pde_type: str) -> dict`

### Class: `rippl.training.lightning.RipplLightningEngine`
Methods:
- `def __init__(self, net)`
- `def forward(self, x)`
- `def training_step(self, batch, batch_idx)`
- `def configure_optimizers(self)`

### Class: `rippl.training.logger.RipplLogger`
"""
Logs training metrics, hyperparameters, and results.

Args:
    experiment_name: name for this run
    log_dir: directory to save logs (default: ./rippl_logs)
    use_wandb: enable W&B logging (requires wandb installed)
    project: W&B project name

Usage:
    logger = RipplLogger("heat_1d_experiment")
    logger.log_config({"lr": 5e-4, "epochs": 5000, "causal": True})
    logger.log_step(epoch=100, loss=0.001, pde_loss=0.0008)
    logger.log_result({"l2_error": 3.8e-4, "status": "PASS"})
    logger.finish()
"""
Methods:
- `def __init__(self, experiment_name: str, log_dir: str = './rippl_logs', use_wandb: bool = False, project: str = 'rippl')`
- `def log_config(self, config: dict)`
  - Log hyperparameters and experiment config.
- `def log_step(self, epoch: int, **metrics)`
  - Log per-epoch metrics.
- `def log_result(self, result: dict)`
  - Log final evaluation results.
- `def log_physics_report(self, report: dict)`
  - Log PhysicsValidator output.
- `def finish(self)`
- `def load(cls, path: str) -> dict`
  - Load a saved experiment log.
- `def loss_curve(self) -> list`
  - Return list of loss values over training.
- `def summary(self) -> dict`

### Function: `rippl.training.memory_guard.get_available_vram_gb`
`def get_available_vram_gb(device: torch.device) -> float`
"""
Get available VRAM in GB. Returns large number for CPU.
"""

### Function: `rippl.training.memory_guard.estimate_step_vram_gb`
`def estimate_step_vram_gb(model: torch.nn.Module, n_points: int, spatial_dims: int, order: int = 2) -> float`
"""
Rough estimate of peak VRAM for one training step.

For a PINN with second-order derivatives:
- Forward pass activations: n_points × hidden_dim × n_layers × 4 bytes
- First gradient (∂u/∂x): retain_graph → same as forward
- Second gradient (∂²u/∂x²): retain_graph → same again
- P-AMP FP32 copy: same as forward

Returns estimate in GB.
"""

### Function: `rippl.training.memory_guard.get_safe_chunk_size`
`def get_safe_chunk_size(model: torch.nn.Module, domain, device: torch.device, n_total: int = 2048) -> int`
"""
Compute largest safe chunk size for collocation processing.

Starts at n_total and halves until the estimated VRAM fits.
"""

### Function: `rippl.training.memory_guard.should_use_checkpointing`
`def should_use_checkpointing(model: torch.nn.Module, domain, device: torch.device) -> bool`
"""
Determine if gradient checkpointing should be enabled.

Enabled when:
- 3D or higher spatial problem
- Model has > 1M parameters
- CUDA device with limited VRAM
"""

### Function: `rippl.training.memory_guard.chunked_residual_loss`
`def chunked_residual_loss(model: torch.nn.Module, equation, domain, config, device: torch.device, chunk_size: int, use_ckpt: bool = False) -> torch.Tensor`
"""
Compute PDE residual loss over collocation points in chunks.

Accumulates gradients over chunks to handle large 3D problems
that would OOM with a single forward pass.

This is mathematically equivalent to the full-batch computation
because PDE residuals are pointwise — no batch normalization,
no cross-point interactions in the residual computation itself.
"""

### Class: `rippl.training.pamp.PhysicsAMP`
Methods:
- `def __init__(self, enabled = True, precision = 'bf16', model = None, n_points = 2048)`
- `def forward(self, model, coords)`
- `def residual(self, equation, fields, coords)`
- `def backward(self, loss)`
- `def optimizer_step(self, optimizer)`
- `def zero_grad(self, optimizer)`
- `def step(self, optimizer)`
- `def status(self) -> str`

### Function: `rippl.training.pamp.pamp_enabled_for_device`
`def pamp_enabled_for_device(device: torch.device) -> bool`
"""
Returns True if P-AMP should be enabled for this device.
Only beneficial on Ampere (sm_80+) or newer CUDA devices.
BF16 hardware support starts at Ampere.
"""

### Class: `rippl.training.pareto.MGDABalancer`
"""
Clean interface for MGDA multi-objective optimization.

The caller passes loss tensors. This class owns the graph lifecycle
internally -- retain_graph is never the caller's concern.

Usage:
    balancer = MGDABalancer(n_objectives=3)
    weights  = balancer.compute_weights(losses, model.parameters())
    total    = sum(w * L for w, L in zip(weights, losses))
    total.backward()

Memory: O(graph_size), not O(K -- graph_size).
This is the graph-detached Pareto scaling contribution.
"""
Methods:
- `def __init__(self, n_objectives: int, update_freq: int = 100)`
- `def compute_weights(self, losses: list, params, force_update: bool = False) -> list`
  - Compute Pareto-optimal weights for the given losses.

### Class: `rippl.training.pareto.ParetoBal`
Methods:
- `def __init__(self, n_obj = 3)`
- `def compute(self, model, loss_dict: dict, dev = 'cpu') -> torch.Tensor`

### Class: `rippl.training.pareto.ParetoLossBalancer`
Methods:
- `def __init__(self, n_objectives = 3)`

### Class: `rippl.training.pinn_recipe.PINNTrainingRecipe`
"""
Validated training strategy for PINNs.
Implements: constraint curriculum → lazy NTK Adam → dynamic LBFGS handoff.
Proven on wave equation (L2=1.36e-03) and heat equation (L2=4.17e-04).
"""
Methods:
- `def __init__(self, model: torch.nn.Module, loss_fn: callable, constraint_loss_fn: callable, device: torch.device, phase_a_epochs: int = 3000, phase_b_epochs: int = 10000, lbfgs_steps: int = 500, adam_lr: float = 0.0005, lbfgs_lr: float = 1.0, grad_clip: float = 1.0, ntk_freq: int = 500, plateau_patience: int = 300, plateau_factor: float = 0.5, min_lr: float = 1e-06, constraint_weight: float = 100.0, causal: bool = True, causal_mode: str = 'binned', causal_bins: int = 20, verbose: bool = True, log_freq: int = 1000, lbfgs_config: Optional[dict] = None)`
- `def run(self) -> dict`
  - Execute full training pipeline.

### Function: `rippl.training.reproducibility.set_deterministic_mode`
`def set_deterministic_mode(seed: int = 42) -> None`
"""
Activate all determinism locks.

This makes rippl training fully reproducible at the cost of
some performance (10-30% slower in some cases).

Sets:
  - Python random seed
  - NumPy random seed
  - PyTorch CPU seed
  - PyTorch CUDA seeds (all devices)
  - CUDA deterministic algorithms
  - cuDNN deterministic mode
"""

### Function: `rippl.training.reproducibility.release_deterministic_mode`
`def release_deterministic_mode() -> None`
"""
Release determinism constraints after training.
Restores performance optimizations for inference.
"""

### Class: `rippl.training.turbulence.TurbulenceCurriculum`
"""
Manages the Reynolds number schedule during PINN training.

The schedule function increases Re from Re_initial to Re_target
over curriculum_epochs, then holds at Re_target.

Schedule options:
    'linear':      Re increases linearly
    'cosine':      Cosine annealing (slow start, slow end)
    'exponential': Rapid increase (good for flow problems)
    'step':        Discrete steps at specified intervals
"""
Methods:
- `def __init__(self, Re_target: float, Re_initial: float = 1.0, curriculum_epochs: int = 3000, schedule: str = 'cosine', total_epochs: int = 10000)`
- `def get_Re(self, epoch: int) -> float`
  - Get current Reynolds number for this epoch.
- `def inject_Re(self, equation, epoch: int) -> float`
  - Update the equation's Reynolds number for this epoch.
- `def current_Re(self) -> Optional[float]`
- `def status(self, epoch: int) -> str`

### Class: `rippl.training.turbulence.WallFunctionBC`
"""
Wall function boundary conditions for RANS k-epsilon turbulence.

In high-Re flows, the near-wall region (viscous sublayer) requires
extremely fine mesh resolution in classical CFD. Wall functions
bypass this by providing algebraic profiles.

For PINNs, wall functions appear as additional constraints
on the velocity profile near walls.

The log-law of the wall:
    u⁺ = (1/κ) ln(y⁺) + B
    where u⁺ = u/u_τ (velocity in wall units)
          y⁺ = y u_τ / ν (distance in wall units)
          κ = 0.41 (von Kármán constant)
          B = 5.0 (log-law constant)
"""
Methods:
- `def __init__(self, wall_fn: Callable, u_tau: float = 1.0, nu: float = 0.0001, y_plus_min: float = 11.6)`
- `def compute_wall_loss(self, model: torch.nn.Module, coords: torch.Tensor) -> torch.Tensor`
  - Loss enforcing wall function profile near the wall.

### Class: `rippl.training.uq.MCDropoutWrapper`
"""
Monte Carlo Dropout Wrapper.
Inserts Dropout layers after every non-output linear layer.
"""
Methods:
- `def __init__(self, model: nn.Module, dropout_rate: float = 0.1)`
- `def forward(self, coords: torch.Tensor) -> torch.Tensor`
- `def predict_with_uncertainty(self, coords: torch.Tensor, n_samples: int = 50, device: str = 'cpu') -> Dict[str, torch.Tensor]`

### Class: `rippl.training.uq.DeepEnsemble`
Methods:
- `def __init__(self, models: List[nn.Module])`
- `def predict_with_uncertainty(self, coords: torch.Tensor, device: str = 'cpu') -> Dict[str, torch.Tensor]`

### Class: `rippl.training.uq.UncertaintyQuantifier`
Methods:
- `def __init__(self, model_or_ensemble, method: str = 'mc_dropout', n_samples: int = 50)`
- `def predict(self, coords: torch.Tensor, device: str = 'cpu') -> Dict[str, torch.Tensor]`
- `def confidence_interval(self, coords: torch.Tensor, alpha: float = 0.05, device: str = 'cpu') -> Dict[str, torch.Tensor]`
- `def epistemic_uncertainty(self, coords: torch.Tensor, device: str = 'cpu') -> torch.Tensor`
- `def high_uncertainty_regions(self, coords: torch.Tensor, threshold: float, device: str = 'cpu') -> torch.Tensor`

### Class: `rippl.training.uq.ProbabilisticExperiment`
Methods:
- `def __init__(self, system, model, method: str = 'mc_dropout', n_ensemble: int = 5, dropout_rate: float = 0.1, **experiment_kwargs)`
- `def train(self, **kwargs)`
- `def predict_with_uncertainty(self, coords: torch.Tensor, n_samples: int = 50)`
- `def uncertainty_report(self, coords: torch.Tensor, device: str = 'cpu') -> Dict[str, float]`

### Class: `rippl.training.vpinn.VPINN`
Methods:
- `def __init__(self, m, eq, dom, p = 5, n_el = 4)`
- `def loss(self, dev = 'cpu')`

### Class: `rippl.twins.api.TwinBuilder`
"""
7-Line API Builder for Continuous Digital Twins.
Provides a fluent interface to construct and wire up complex Twin pipelines
without exposing queue or threading internals to the user.
"""
Methods:
- `def __init__(self, equation, domain)`
- `def with_model(self, model: torch.nn.Module) -> 'TwinBuilder'`
  - Attach the Neural Network model to the Twin.
- `def with_iot_stream(self, broker: str, topic: str, field: str = 'u') -> 'TwinBuilder'`
  - Connect the Twin directly to live IoT sensors over MQTT.
- `def with_predictive_maintenance(self, critical_threshold: float, alert_threshold_hours: float, on_alert: Callable[[MaintenanceAlert], None]) -> 'TwinBuilder'`
  - Attach an ML tracker that projects future Time-to-Failure.
- `def on_anomaly(self, callback: Callable[[AnomalyReport], None]) -> 'TwinBuilder'`
  - Register a callback for when physical anomalies are detected.
- `def build(self) -> ContinuousDigitalTwin`
  - Construct the Twin and wire all internal pipelines together.

### Class: `rippl.twins.continuous.SensorReading`
Methods:

### Class: `rippl.twins.continuous.AnomalyReport`
Methods:

### Class: `rippl.twins.continuous.ContinuousDigitalTwin`
"""
Physics-informed digital twin with continuous sensor assimilation.

The key innovation over standard digital twins:
- Runs continuously, not in batch
- Backward query: given anomalous reading, WHERE is the source?
- Physics-constrained: anomaly detection respects PDE structure

The model weights encode the current physical state.
Assimilation keeps them consistent with sensor reality.
Physics loss keeps them consistent with governing equations.

Args:
    equation:    rippl Equation defining the PDE
    domain:      physical domain
    model:       neural network (pre-trained or fresh)
    physics_weight: relative weight of physics vs data loss
    sensor_buffer_size: max readings to keep in buffer
"""
Methods:
- `def __init__(self, equation, domain, model: torch.nn.Module, physics_weight: float = 1.0, data_weight: float = 10.0, sensor_buffer_size: int = 100, device: str = None)`
- `def ingest(self, coords: torch.Tensor, values: torch.Tensor, field: str = 'u')`
  - Ingest a new sensor reading.
- `def step(self, n_colloc: int = 500)`
  - One assimilation step: physics + data joint update.
- `def predict(self, coords: torch.Tensor, return_uncertainty: bool = False) -> torch.Tensor`
  - Forward query: predict field at arbitrary coordinates.
- `def locate_anomaly(self, observed_coords: torch.Tensor, observed_values: torch.Tensor, top_k: int = 5) -> AnomalyReport`
  - Backward query: given anomalous sensor readings,
- `def on_anomaly(self, callback: Callable[[AnomalyReport], None])`
  - Register callback for when anomaly is detected.
- `def start(self, steps_per_second: float = 10.0)`
  - Start continuous assimilation in background thread.
- `def stop(self)`
  - Stop continuous assimilation.
- `def step_count(self) -> int`

### Class: `rippl.twins.iot_stream.IoTStreamAdapter`
"""
Listens to live IoT telemetry over MQTT and instantly
pipes it into the Continuous Digital Twin via non-blocking queues.
"""
Methods:
- `def __init__(self, broker: str, topic: str, port: int = 1883, field: str = 'u')`
- `def attach(self, ingest_callback: Callable[[torch.Tensor, torch.Tensor, str], None])`
  - Attach the twin's ingest function.
- `def start(self)`

### Class: `rippl.twins.maintenance.MaintenanceAlert`
Methods:

### Class: `rippl.twins.maintenance.PredictiveMaintenanceTracker`
"""
Watches the Twin's physical discrepancy over time and uses
rolling regression to project exact Time-to-Failure (TTF).
"""
Methods:
- `def __init__(self, critical_threshold: float = 5.0, alert_threshold_hours: float = 24.0)`
- `def process_anomaly(self, report: AnomalyReport)`
  - Called automatically every time the Twin detects an anomaly.
- `def on_alert(self, callback: Callable[[MaintenanceAlert], None])`
  - Register a callback to trigger when failure is imminent.

### Function: `rippl.validation.analytical_solutions.taylor_green_vortex`
`def taylor_green_vortex(coords: torch.Tensor, nu: float = 0.01, t_decay: bool = True)`
"""
2D Taylor-Green vortex, exact NS solution.
coords: (N, 3) -> x, y, t
Returns u, v, p as (N,1) tensors.
"""

### Function: `rippl.validation.analytical_solutions.poiseuille_flow`
`def poiseuille_flow(coords: torch.Tensor, dp_dx: float = Any, mu: float = 1.0, H: float = 1.0)`
"""
Steady 2D channel flow between parallel plates at y=0, y=H.
"""

### Function: `rippl.validation.analytical_solutions.couette_flow`
`def couette_flow(coords: torch.Tensor, U_wall: float = 1.0, H: float = 1.0)`
"""
Steady 2D shear flow, bottom wall fixed, top wall moving at U_wall.
"""

### Function: `rippl.validation.analytical_solutions.manufactured_solution`
`def manufactured_solution(coords: torch.Tensor, expr: callable)`
"""
Method of Manufactured Solutions: pick ANY smooth function as the
'exact' solution, derive the source term that makes it satisfy the
PDE, and verify the solver recovers it. expr: callable(coords)->u
"""

### Class: `rippl.validation.convergence_ci.ConvergenceCIPipeline`
Methods:
- `def __init__(self, problem_name: str, domain_factory: Callable, equation_factory: Callable, exact_solution_fn: Callable, model_factory: Callable, resolutions: List[int] = [256, 512, 1024, 2048], expected_order: float = 1.0, order_tolerance: float = 0.5)`
- `def run(self, epochs: int = 2000, verbose: bool = True) -> Dict`

### Class: `rippl.validation.correlation_benchmark.CorrelationResult`
Methods:

### Class: `rippl.validation.correlation_benchmark.CorrelationBenchmark`
"""
Runs rippl on N geometries, compares ranking against
precomputed OpenFOAM results on the same geometries.

Usage:
    bench = CorrelationBenchmark(
        geometries=[...],            # list of CAD paths or Domain objects
        equation_factory=lambda geo: rp.parse(navier_stokes_str),
        openfoam_results=[...],      # list of OpenFOAMResult, same order
        objective_fn=lambda result: result['lift'] / result['drag'],
    )
    report = bench.run(epochs=2000, top_k_pct=0.10)
    print(report)
"""
Methods:
- `def __init__(self, geometries: List, equation_factory: Callable, openfoam_results: List, objective_fn: Callable, model_factory: Optional[Callable] = None)`
- `def run(self, epochs: int = 2000, top_k_pct: float = 0.1, n_bootstrap: int = 1000, verbose: bool = True) -> CorrelationResult`

### Function: `rippl.validation.error_norms.l2_error`
`def l2_error(u_pred: torch.Tensor, u_exact: torch.Tensor) -> float`
"""
Relative L2 error: ||u_pred - u_exact|| / ||u_exact||
"""

### Function: `rippl.validation.error_norms.h1_error`
`def h1_error(model, coords: torch.Tensor, u_exact: torch.Tensor, grad_exact_fn = None) -> float`
"""
Relative H1 error: includes both value AND gradient mismatch.
H1_norm^2 = L2_norm^2 + ||grad(u_pred) - grad(u_exact)||^2

grad_exact_fn: callable(coords) -> exact gradient tensor (N, d).
               If None, computed via autograd on u_exact (requires
               u_exact to have been produced with requires_grad coords).
"""

### Function: `rippl.validation.error_norms.convergence_rate`
`def convergence_rate(errors: list, resolutions: list) -> float`
"""
Fits log(error) vs log(N) and returns the slope — the empirical
convergence order. Should match theoretical expectation
(e.g., ~2 for second-order methods) within tolerance.
"""

### Class: `rippl.validation.openfoam_adapter.OpenFOAMResult`
Methods:

### Function: `rippl.validation.openfoam_adapter.load_openfoam_case`
`def load_openfoam_case(path: str, objective_key: Optional[str] = None, objective_fn: Optional[callable] = None) -> OpenFOAMResult`
"""
Load an OpenFOAM result, either from a VTK export or a
postProcessing forceCoeffs.dat style summary file.

Args:
    path:           Path to .vtu/.vtk export, or a directory
                     containing postProcessing/ output.
    objective_key:  Field name to extract as the scalar objective
                     (e.g. 'Cl', 'Cd') if present in a summary file.
    objective_fn:   Callable(fields) -> float, computes the objective
                     from the raw field arrays if no summary exists.
"""




SECTION 4: COMPLETE EXAMPLES

### Example 1: 1D Wave Equation (Basic PINN)
```python
import torch
import rippl as rp

domain = rp.Domain(spatial_dims=1, bounds=[(-1.0, 1.0), (0.0, 1.0)], resolution=[256, 100])
eq = rp.parse("u_tt - 4.0 * u_xx")

def ic_u(x): return torch.sin(torch.pi * x)
def ic_ut(x): return torch.zeros_like(x)
def bc_val(x): return torch.zeros_like(x)

constraints = [
    rp.Dirichlet('u', domain.bounds[0], bc_val, is_spatial=True),
    rp.Dirichlet('u', domain.bounds[1], ic_u, is_temporal=True),
    # Note: derivative constraints are not standard Dirichlet, this is just illustrative
]

model = rp.nn.SIREN(in_features=2, out_features=1, hidden_features=64, hidden_layers=3)
result = rp.run(domain, eq, model, config=rp.RunConfig(epochs=2000, device="cuda"))
```

### Example 2: Conjugate Heat Transfer (Coupled Multiphysics)
```python
import rippl as rp
import torch

fluid_dom = rp.Domain(spatial_dims=2, bounds=[(0, 1), (0.5, 1)])
solid_dom = rp.Domain(spatial_dims=2, bounds=[(0, 1), (0, 0.5)])

fluid_eq = rp.parse("T_t + u*T_x + v*T_y - 0.01*(T_xx + T_yy)")
solid_eq = rp.parse("T_t - 0.05*(T_xx + T_yy)")

coupled = rp.CoupledSystem(
    equations={'fluid': fluid_eq, 'solid': solid_eq},
    domains={'fluid': fluid_dom, 'solid': solid_dom},
    models={
        'fluid': rp.nn.MLP(3, 1, 64, 4),
        'solid': rp.nn.MLP(3, 1, 64, 4)
    },
    interfaces=[
        rp.Interface('interface1', 'fluid', 'solid', location='y=0.5', conditions=['continuity', 'heat_flux_continuity'])
    ]
)
result = rp.run(coupled, config=rp.RunConfig(epochs=5000))
```

### Example 3: Continuous Digital Twin with IoT
```python
import rippl as rp
from rippl.twins.api import TwinBuilder

eq = rp.parse("T_t - alpha * T_xx")
dom = rp.Domain(spatial_dims=1, bounds=[(0, 1)])
model = rp.nn.FNO1d(modes=16, width=64)

twin = (TwinBuilder(eq, dom)
        .with_model(model)
        .with_iot_stream(broker="mqtt://localhost:1883", topic="factory/motor/temp")
        .with_predictive_maintenance(critical_threshold=120.0, alert_threshold_hours=24.0, on_alert=print)
        .build())

twin.start() # Runs forever monitoring live stream
```

### Example 4: Surge ROM Generation
```python
import rippl as rp
from rippl.surge import UniversalSurge

def build_eq(params):
    return rp.parse(f"u_t - {params['nu']} * u_xx")
    
domain = rp.Domain(1, bounds=[(0, 1)])

rom = UniversalSurge(build_eq, params={'nu': [0.01, 0.05, 0.1]}, domain=domain)
rom.train(epochs=1000)

pred = rom.query({'nu': 0.03})
```
