Skip to content

viewer.potential_export — quantum-region potential export

tempura/viewer/potential_export.py exports the per-gate quantum-region basis potentials for the browser viewer, so the page can recombine them interactively as the user drags voltage sliders.

Browser-side superposition

Rather than baking in one voltage configuration, the exporter writes each gate's basis field on the quantum-region plane as a separate array, plus the plane geometry and a shared voltage range. The viewer then forms the superposition \(\phi = \sum_i V_i\,\phi_i\) on the fly — the same linearity the solver exploits, moved to the client. Optional per-gate footprint masks are written alongside for overlays.

export_quantum_region_potential_view(...) validates that every basis array and footprint matches the plane's \((n_y, n_x)\) shape, writes the binary assets and a potential.json manifest, and returns a QuantumRegionPotentialExportManifest listing the files.

API

potential_export

Export quantum region basis potentials for the standalone TypeScript viewer.

QuantumRegionPotentialExportManifest dataclass

Paths written by :func:export_quantum_region_potential_view.

Attributes:

Name Type Description
dataset_name str

Dataset label stored in potential.json.

potential_json_path Path

Path to the potential metadata file.

asset_paths tuple[Path, ...]

Paths to binary array assets referenced by potential.json.

Source code in tempura/viewer/potential_export.py
20
21
22
23
24
25
26
27
28
29
30
31
32
33
@dataclass(frozen=True)
class QuantumRegionPotentialExportManifest:
    """Paths written by :func:`export_quantum_region_potential_view`.

    Attributes:
        dataset_name: Dataset label stored in ``potential.json``.
        potential_json_path: Path to the potential metadata file.
        asset_paths: Paths to binary array assets referenced by
            ``potential.json``.
    """

    dataset_name: str
    potential_json_path: Path
    asset_paths: tuple[Path, ...]

export_quantum_region_potential_view(basis_quantum_region, plane, out_dir, *, gate_footprints=None, dataset_name=None, voltage_range=(-1.0, 1.0), overwrite=True, verbose=False)

Export per-gate quantum region basis potentials for browser-side recombination.

Parameters:

Name Type Description Default
basis_quantum_region dict[str, ndarray]

Mapping of gate name to (ny, nx) quantum region basis array.

required
plane QuantumRegionPlaneData

Extracted quantum region plane metadata.

required
out_dir str | Path

Output directory for the exported bundle.

required
gate_footprints dict[str, ndarray] | None

Optional per-gate footprint masks on the same (ny, nx) plane as basis_quantum_region.

None
dataset_name str | None

Optional dataset label stored in potential.json.

None
voltage_range tuple[float, float]

Shared slider range written to metadata.

(-1.0, 1.0)
overwrite bool

If False, refuse to write into a non-empty directory.

True
verbose bool

If True, print progress messages.

False

Returns:

Type Description
QuantumRegionPotentialExportManifest

Manifest describing the files written.

Raises:

Type Description
ValueError

If no gate potentials are provided or shapes are invalid.

FileExistsError

If overwrite is disabled and the destination exists.

Source code in tempura/viewer/potential_export.py
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
def export_quantum_region_potential_view(
    basis_quantum_region: dict[str, np.ndarray],
    plane: QuantumRegionPlaneData,
    out_dir: str | Path,
    *,
    gate_footprints: dict[str, np.ndarray] | None = None,
    dataset_name: str | None = None,
    voltage_range: tuple[float, float] = (-1.0, 1.0),
    overwrite: bool = True,
    verbose: bool = False,
) -> QuantumRegionPotentialExportManifest:
    """Export per-gate quantum region basis potentials for browser-side recombination.

    Args:
        basis_quantum_region: Mapping of gate name to ``(ny, nx)`` quantum region basis array.
        plane: Extracted quantum region plane metadata.
        out_dir: Output directory for the exported bundle.
        gate_footprints: Optional per-gate footprint masks on the same
            ``(ny, nx)`` plane as ``basis_quantum_region``.
        dataset_name: Optional dataset label stored in ``potential.json``.
        voltage_range: Shared slider range written to metadata.
        overwrite: If ``False``, refuse to write into a non-empty directory.
        verbose: If ``True``, print progress messages.

    Returns:
        Manifest describing the files written.

    Raises:
        ValueError: If no gate potentials are provided or shapes are invalid.
        FileExistsError: If ``overwrite`` is disabled and the destination exists.
    """

    def _log(message: str) -> None:
        """Print one export progress message when verbose output is enabled."""
        if verbose:
            print(message)

    if not basis_quantum_region:
        raise ValueError(
            "At least one quantum region gate basis array is required for export."
        )

    vmin, vmax = (float(voltage_range[0]), float(voltage_range[1]))
    if vmin >= vmax:
        raise ValueError("voltage_range must be an increasing (min, max) pair.")

    out_path = Path(out_dir)
    if out_path.exists():
        if not out_path.is_dir():
            raise FileExistsError(f"Output path is not a directory: {out_path}")
        if not overwrite and any(out_path.iterdir()):
            raise FileExistsError(
                f"Output directory already exists and is not empty: {out_path}"
            )
    else:
        out_path.mkdir(parents=True, exist_ok=True)

    arrays_dir = out_path / "arrays"
    arrays_dir.mkdir(parents=True, exist_ok=True)

    dataset_name = dataset_name or out_path.name or "potential_dataset"
    asset_paths: list[Path] = []
    gates_payload = []
    expected_shape = (plane.ny, plane.nx)
    gate_footprints = gate_footprints or {}
    for gate_name, arr in basis_quantum_region.items():
        potential = np.asarray(arr, dtype=float)
        if potential.shape != expected_shape:
            raise ValueError(
                f"quantum region basis for {gate_name!r} must have shape {expected_shape}; "
                f"got {potential.shape}."
            )
        file_path = arrays_dir / f"{safe_file_stem(gate_name)}__potential.bin"
        write_float32_array(file_path, potential)
        asset_paths.append(file_path)
        _log(f"[export_quantum_region_potential_view] Exporting gate {gate_name!r}...")
        gate_payload = {
            "id": gate_name,
            "potential": array_ref(file_path, potential.shape, dtype="float32"),
        }

        footprint = gate_footprints.get(gate_name)
        if footprint is not None:
            footprint_arr = np.asarray(footprint, dtype=np.uint16)
            if footprint_arr.shape != expected_shape:
                raise ValueError(
                    f"Gate footprint for {gate_name!r} must have shape {expected_shape}; "
                    f"got {footprint_arr.shape}."
                )
            footprint_path = arrays_dir / f"{safe_file_stem(gate_name)}__footprint.bin"
            write_uint16_array(footprint_path, footprint_arr)
            asset_paths.append(footprint_path)
            gate_payload["footprint"] = array_ref(
                footprint_path,
                footprint_arr.shape,
                dtype="uint16",
            )

        gates_payload.append(gate_payload)

    metadata = {
        "version": 1,
        "dataset_name": dataset_name,
        "plane": {
            "nx": plane.nx,
            "ny": plane.ny,
            "x_values": [float(v) for v in plane.x_values],
            "y_values": [float(v) for v in plane.y_values],
            "z": float(plane.z_value),
        },
        "voltage_range": [vmin, vmax],
        "gates": gates_payload,
    }
    potential_json_path = out_path / "potential.json"
    potential_json_path.write_text(json.dumps(metadata, indent=2) + "\n")
    _log(f"[export_quantum_region_potential_view] Wrote {potential_json_path}")

    return QuantumRegionPotentialExportManifest(
        dataset_name=dataset_name,
        potential_json_path=potential_json_path,
        asset_paths=tuple(asset_paths),
    )