# MATLAB-to-C++ port inventory

## Purpose

This document maps the MATLAB source into a dependency order for a one-to-one C++/SymEngine port. It does not redesign the solver. It keeps the current quantified charge-flow analysis (QFA) path separate from older or ancillary code until the compatibility policy is decided.

Domain background and thesis citations are in [`phd-thesis-simulator.md`](phd-thesis-simulator.md).

## Authoritative QFA flow

```text
architecture matrices
  → phase circuit graphs
  → exact tree, cut-set, and loop algebra
  → symbolic net charge A
  → symbolic pumped charge B
  → redistributed charge G and resistive charge Ar
  → conversion ratio m and component stress
  → ZSSL, ZFSL, ZSCC
  → capacitor and switch allocation optimizers
```

For the current Dickson path:

```text
dickson_hybrid_topology
  ├─ dickson_arch
  │    └─ dickson_matrix
  └─ generic_switched_capacitor_class
       ├─ SCC_Phase
       │    ├─ phase_conv
       │    └─ fun_cutset
       ├─ tree_ph_scc
       │    ├─ build_tree
       │    └─ full_tree
       ├─ solve_charge_vectors
       ├─ short_edge
       ├─ fun_cutset
       ├─ fun_loop
       ├─ inM2loopM
       ├─ matrix_2_expon
       └─ D3_matrix_addition
```

The wrapper exports symbolic `ratio`, `vc`, `vr`, `is`, `Y_ssl`, `Y_fsl`, `f_ssl`, `f_fsl`, `f_esr`, phase charge data, and numerical substitution functions.

## Source inventory

### Current QFA core

| MATLAB file | Role | Port status |
|---|---|---|
| `generic_switched_capacitor_class.m` | Topology-independent QFA orchestrator. Builds phase models and produces symbolic charge flow, conversion, stress, SSL, FSL, ESR, and combined resistance/transresistance models. | Required core; absent from C++. |
| `SCC_Phase.m` | Stores one phase graph and its `a`, `b`, redistributed `r/G`, and resistive `ar` vectors. | Required core; absent from C++. |
| `solve_charge_vectors.m` | Multiphase symbolic solve for net charge matrices `A` and conversion-ratio vector `m`. | Required core; absent from C++. |
| `tree_ph_scc.m` | Selects a valid phase tree for the generic solver. | Required core; absent from C++. |
| `phase_conv.m` | Contracts conducting switch branches to form each phase circuit. | Required graph primitive; absent from C++. |
| `build_tree.m` | Current spanning-tree implementation used by QFA helpers. | Required graph primitive; absent from C++. |
| `full_tree.m` | Tests whether a selected edge set forms a full tree. | Required graph primitive; absent from C++. |
| `fun_cutset.m` | Produces fundamental cut-set matrices. | Required graph primitive; absent from C++. |
| `fun_loop.m` | Produces fundamental loop matrices. | Required graph primitive; absent from C++. |
| `short_edge.m` | Shorts a selected branch before pumped-charge solving. | Required graph primitive; absent from C++. |
| `inM2loopM.m` | Converts incidence matrices to loop equations used for voltage stress. | Required symbolic primitive; absent from C++. |
| `matrix_2_expon.m` | Converts charge-vector terms into outer-product coefficient matrices. | Required symbolic reduction; absent from C++. |
| `D3_matrix_addition.m` | Applies capacitor or resistance weights to 3-D coefficient matrices. | Required symbolic reduction; absent from C++. |

### Architecture generators and QFA wrappers

| MATLAB file | Role | Port status |
|---|---|---|
| `dickson_matrix.m` | Dickson capacitor and two-phase switch incidence matrices. | Partial C++ port and 5-stage matrix fixture exist. |
| `dickson_arch.m` | Produces `ArchDef.Acaps`, interleaved `Asw`, and `Asw_act`. | C++ type exists; implementation is TODO. |
| `dickson_hybrid_topology.m` | Current Dickson QFA entry point and symbolic result adapter. | C++ scaffold returns metadata only. |
| `hybrid_topology.m` | Generic `ArchDef` to QFA topology wrapper. | Required generic interface; absent from C++. |
| `ladder_matrix.m` | Ladder incidence matrices. | Required topology variant; absent from C++. |
| `ladder_arch.m` | Ladder `ArchDef` adapter. | Required topology variant; absent from C++. |
| `ladder_hybrid_topology.m` | Ladder QFA wrapper. | Required topology variant; absent from C++. |
| `ladder_float_matrix.m` | Floating-ladder incidence matrices. | Required topology variant; absent from C++. |
| `ladder_float_topology.m` | Floating-ladder QFA wrapper. | Required topology variant; absent from C++. |
| `single_scc_arch.m` | Fixed single-stage architecture. | Required topology fixture/variant; absent from C++. |
| `scc11_topology.m` | SCC 1:1 topology wrapper. | Required topology variant; absent from C++. |

### QFA optimization

| MATLAB file | Consumes | Produces | Port status |
|---|---|---|---|
| `dickson_optimizer.m` | `topology.f_ssl`, `topology.ratio`, selected outputs/current weights. | Relative capacitor allocation and objective value. | Earlier/simple SSL optimizer; absent from C++. |
| `dickson_optimizer_ssl.m` | `f_ssl`, `N_caps`, output selection, duty distribution, optional ripple/efficiency constraint. | Relative capacitor allocation and minimum SSL figure of merit. | Current extended SSL optimizer; absent from C++. |
| `dickson_optimizer_fsl.m` | `f_fsl`, `N_sw`, ratio, duty distribution, switch unit-area resistance weights. | Relative switch-area allocation and minimum FSL figure of merit. | Current FSL optimizer; absent from C++. |

These optimizers depend on symbolic substitution and constrained minimization. Their input symbol ordering is currently implicit through MATLAB `symvar`; the C++ port must expose an explicit stable order while preserving MATLAB results.

### Separate older implementation/performance flow

| MATLAB file | Role | Relationship to QFA port |
|---|---|---|
| `generate_topology.m` | Mike Seeman analytical topology generator for Series-Parallel, Ladder, Dickson, Cockcroft-Walton, Doubler, and Fibonacci families. Produces `ac/ar/vc/vcb/vr/vrb`. | Separate topology schema; do not merge into the current graph-based QFA model. |
| `implement_topology.m` | Assigns capacitor and switch technologies and relative sizes using the older topology schema. | Downstream legacy flow. |
| `techlib.m` | Capacitor and switch technology records. | Data source for the older implementation flow. |
| `evaluate_loss.m` | Calculates output resistance, regulation, parasitic loss, total loss, and efficiency for a concrete implementation. | Numerical evaluation after model/component selection; not QFA model generation. |
| `optimize_loss.m` | Uses `fmincon` to optimize switching frequency and switch area through `evaluate_loss`. | Numerical optimization after implementation selection. |

A one-to-one port can preserve this flow, but it must remain a separate compatibility module unless ticket #22 establishes an explicit bridge between schemas.

### Legacy or alternate solver generations

| MATLAB file | Evidence | Port treatment |
|---|---|---|
| `SCC.m` | File declares `classdef SCC_node` but uses constructor `SCC`; no repository caller. Uses two-phase-only solver. | Preserve only after current QFA path; classify behavior under compatibility policy. |
| `SCC_node.m` | Older `SCC_node` class; no repository caller. Uses two-phase-only solver and contains additional evaluation helpers. | Preserve only after current QFA path. |
| `solve_2ph_charge_vectors.m` | Used by old `SCC`/`SCC_node`; replaced by `solve_charge_vectors` in generic QFA class. | Legacy compatibility layer. |
| `tree_2ph_scc.m` | Used by old `SCC`/`SCC_node`; replaced by `tree_ph_scc` in generic class. | Legacy compatibility layer. |
| `build_tree_new.m` | No inbound repository calls. | Experimental/alternate tree implementation; port after behavior policy. |
| `build_tree_old.m` | No inbound repository calls. | Legacy tree implementation. |
| `conv_on.m` | Filename and declared function name differ; duplicates the `phase_conv` name and has no inbound call. | Legacy/defect case for ticket #22. |
| `short_node.m` | No inbound repository call found. | Preserve as unused helper after core parity. |

### Ancillary analysis

| MATLAB file | Role | Port treatment |
|---|---|---|
| `solve_zeq.m` | Symbolic equivalent impedance from loop and cut-set matrices. | Port before `get_poles`. |
| `get_poles.m` | Estimates parasitic LC natural frequency and Q for a concrete topology and components. | Port after QFA and optimizer parity; not part of symbolic charge-flow derivation. |

## Required C++ data contracts

The first C++ interfaces must preserve these MATLAB structures before adding browser serialization:

1. **Architecture definition**
   - `Acaps`: oriented capacitor incidence matrix.
   - `Asw`: oriented global switch incidence matrix.
   - `Asw_act`: phase-by-switch activation matrix.
2. **Phase model**
   - active and inactive switch incidence;
   - source and load branches;
   - phase-local switch indices;
   - symbolic `A`, `B`, `G/r`, and `Ar` matrices.
3. **QFA model**
   - ordered symbolic vectors for `D`, `C`, `Ron`, and `Resr`;
   - conversion vector `m`;
   - capacitor/switch voltage and current stress;
   - `ZSSL`, `ZFSL`, ESR contribution, and combined `ZSCC`;
   - output and phase ordering metadata.
4. **Topology adapter**
   - the fields currently exported by `dickson_hybrid_topology` and the other QFA wrappers;
   - explicit substitution APIs that replace implicit `symvar` ordering.
5. **Optimizer adapter**
   - figures of merit for selected outputs and duty distributions;
   - constrained relative capacitor and switch-area allocation.

## One-to-one port order

### Stage 0 — Repair the MATLAB reference

Before porting an affected module, repair confirmed MATLAB defects and add characterization tests. Working and corrected MATLAB behavior is the C++ parity oracle. Follow [`matlab-compatibility-ledger.md`](matlab-compatibility-ledger.md).

Completion criterion: the next MATLAB dependency layer loads and has tests for every behavior that the C++ layer will reproduce.

### Stage 1 — Exact matrix and graph foundation

Port and test integer/rational matrix representation, branch ordering, `phase_conv`, `build_tree`, `full_tree`, `fun_cutset`, `fun_loop`, `short_edge`, `short_node`, and `inM2loopM`.

Completion criterion: MATLAB and C++ produce equivalent contracted phase graphs, trees, cut-set matrices, and loop matrices for the same architecture.

### Stage 2 — Architecture contract

Complete `dickson_matrix`, `dickson_arch`, `single_scc_arch`, then ladder/floating-ladder generators. Preserve `Acaps`, `Asw`, and `Asw_act` ordering exactly.

Completion criterion: every architecture generator has matrix parity for representative stage counts and options.

### Stage 3 — Phase and symbolic charge solving

Port `SCC_Phase`, `tree_ph_scc`, and `solve_charge_vectors`. Implement exact SymEngine linear solves for `A`, `B`, `G/r`, and `Ar` without floating-point substitution.

Completion criterion: C++ symbolic matrices are algebraically equivalent to MATLAB for thesis examples and repository topology fixtures.

### Stage 4 — Generic QFA model

Port `generic_switched_capacitor_class`, including conversion ratio, SSL, FSL, ESR, combined impedance/transresistance, and normalized stress calculations. Port `matrix_2_expon` and `D3_matrix_addition` as model reductions.

Completion criterion: the complete symbolic QFA bundle is equivalent after canonical substitution; expression strings need not match.

### Stage 5 — Topology adapters

Port `hybrid_topology`, `dickson_hybrid_topology`, `ladder_hybrid_topology`, `ladder_float_topology`, and `scc11_topology` without changing their observable fields or output ordering.

Completion criterion: each MATLAB entry point has a corresponding C++ entry point and equivalent symbolic outputs.

### Stage 6 — QFA optimizers

Port the simple and extended Dickson SSL optimizers and the FSL optimizer. Keep symbolic model construction separate from constrained numerical optimization.

Completion criterion: identical objective construction, constraints, relative allocations, and substituted objective values for fixed cases.

### Stage 7 — Older implementation/performance flow

Port `generate_topology`, `implement_topology`, `techlib`, `evaluate_loss`, and `optimize_loss` as a distinct compatibility namespace. Add a schema bridge only if explicitly decided.

Completion criterion: old MATLAB workflows remain reproducible without changing the current QFA model.

### Stage 8 — Legacy and ancillary behavior

Port old two-phase classes/solvers, alternate tree implementations, unused helpers, `solve_zeq`, and `get_poles` according to the compatibility policy.

Completion criterion: every retained MATLAB public function is either represented in C++ or explicitly documented as intentionally unsupported.

### Stage 9 — WebAssembly packaging

Package the already-parity-tested native C++/SymEngine API for WebAssembly. Browser serialization must not redefine the symbolic model.

Completion criterion: native and WebAssembly builds return symbolically equivalent models with identical ordering metadata.

## Existing C++ scaffold

The existing port contains:

- a partial `dickson_matrix` implementation;
- a 5-stage incidence-matrix test;
- an `ArchDef` declaration with an unimplemented `dickson_arch`;
- a `Topology` declaration and incomplete `dickson_hybrid_topology`;
- a basic Emscripten/SymEngine build scaffold.

No current C++ module implements phase graph contraction, cut-set/loop algebra, symbolic charge solving, the generic QFA model, or optimizer behavior.

## Decisions deferred to other map tickets

- Symbol and branch ordering, canonical equivalence, and SymEngine parity rules: ticket #21.
- Literal MATLAB defects versus intended thesis behavior and old/new schema compatibility: ticket #22.
- Numerical and thesis validation after symbolic parity: ticket #23.
- WebAssembly ABI and reproducible browser build after native parity: ticket #24.
