Skip to content

API Reference: Representation Core

representation

╔══════════════════════════════════════════════════════════════════════════════╗ ║ MHRQI - Multi-scale Hierarchical Representation of Quantum Images ║ ║ Core Representation and Encoding ║ ║ ║ ║ Author: Keno S. Jose ║ ║ License: Apache 2.0 ║ ╚══════════════════════════════════════════════════════════════════════════════╝

MHRQI

Main class for Multi-scale Hierarchical Representation of Quantum Images. Encapsulates the quantum circuit, registers, and operations.

Source code in mhrqi/core/representation.py
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
class MHRQI:
    """
    Main class for Multi-scale Hierarchical Representation of Quantum Images.
    Encapsulates the quantum circuit, registers, and operations.
    """

    def __init__(self, depth, bit_depth=8):
        """
        Initialize an MHRQI instance.

        Args:
            depth: Hierarchy depth (log2 of image side)
            bit_depth: Bits for intensity encoding (default 8)
        """
        self.depth = depth
        self.bit_depth = bit_depth
        self.hierarchical_coord_matrix = None
        self.denoise_enabled = False

        self.pos_regs = []
        # Position qubits (2 per level: y and x)
        for k in range(depth):
            self.pos_regs.append(QuantumRegister(1, f"q_y_{k}"))
            self.pos_regs.append(QuantumRegister(1, f"q_x_{k}"))

        self.intensity_reg = QuantumRegister(bit_depth, "intensity")
        self.outcome_reg = QuantumRegister(1, "outcome")
        self.work_reg = QuantumRegister(2, "work")

        self.circuit = QuantumCircuit(
            *self.pos_regs, self.intensity_reg, self.outcome_reg, self.work_reg
        )

        # Place position qubits in uniform superposition
        for reg in self.pos_regs:
            self.circuit.h(reg[0])

    @property
    def qubits_to_measure(self):
        """Returns a list of qubits that should be measured for reconstruction."""
        qubits = []
        for reg in self.pos_regs:
            qubits.append(reg[0])
        qubits.extend(list(self.intensity_reg))
        qubits.extend(list(self.outcome_reg))
        return qubits

    def upload(self, hierarchical_coord_matrix, img):
        """
        Upload intensity values using MHRQI(basis) encoding.

        Args:
            hierarchical_coord_matrix: matrix of position states
            img: normalized image (0-1 range)
        """
        self.hierarchical_coord_matrix = hierarchical_coord_matrix
        controls = [reg[0] for reg in self.pos_regs]
        intensity_qubits = list(self.intensity_reg)
        and_ancilla = self.work_reg[0]

        for vec in hierarchical_coord_matrix:
            ctrl_states = list(vec)
            r, c = utils.compose_rc(vec, 2)  # d=2 for images
            pixel_value = float(img[r, c])
            intensity_int = int(pixel_value * (2**self.bit_depth - 1))
            intensity_bits = format(intensity_int, f"0{self.bit_depth}b")[::-1]

            _prepare_controls_on_states(self.circuit, controls, ctrl_states)

            if len(controls) > 0:
                self.circuit.mcx(controls, and_ancilla)
                for bit_idx, bit_val in enumerate(intensity_bits):
                    if bit_val == "1":
                        self.circuit.cx(and_ancilla, intensity_qubits[bit_idx])
                self.circuit.mcx(controls, and_ancilla)
            else:
                for bit_idx, bit_val in enumerate(intensity_bits):
                    if bit_val == "1":
                        self.circuit.x(intensity_qubits[bit_idx])

            _restore_controls(self.circuit, controls, ctrl_states)
        return self.circuit

    def lazy_upload(self, hierarchical_coord_matrix, image):
        """
        Fast basis upload using direct statevector initialization.

        Args:
            hierarchical_coord_matrix (list): List of hierarchical_coord_vectors for all pixels.
            image (np.ndarray): Normalized image array [0, 1].

        Returns:
            QuantumCircuit: The initialized circuit.
        """
        self.hierarchical_coord_matrix = hierarchical_coord_matrix
        qubit_to_idx = {q: i for i, q in enumerate(self.circuit.qubits)}
        pos_indices = [qubit_to_idx[reg[0]] for reg in self.pos_regs]
        intensity_indices = [qubit_to_idx[q] for q in self.intensity_reg]

        num_qubits = self.circuit.num_qubits
        dim = 2**num_qubits
        state = np.zeros(dim, dtype=complex)

        all_indices = pos_indices + intensity_indices
        is_sequential = all(all_indices[i] == i for i in range(len(all_indices)))

        if is_sequential:
            for hierarchical_coord_vector in hierarchical_coord_matrix:
                p = 0
                for i, val in enumerate(hierarchical_coord_vector):
                    if val:
                        p |= 1 << i

                r, c = utils.compose_rc(hierarchical_coord_vector, 2)
                pixel_value = float(image[r, c])
                intensity_int = int(pixel_value * (2**self.bit_depth - 1))

                base_idx = p
                intensity_offset = 0
                for bit_idx in range(self.bit_depth):
                    if (intensity_int >> bit_idx) & 1:
                        intensity_offset |= 1 << (len(pos_indices) + bit_idx)
                state[base_idx + intensity_offset] = 1.0
        else:
            warnings.warn("Qubits not sequential, falling back to gate-based upload.", stacklevel=2)
            return self.upload(hierarchical_coord_matrix, image)

        state_norm = np.linalg.norm(state)
        if state_norm > 0:
            state = state / state_norm

        self.circuit.append(SetStatevector(state), self.circuit.qubits)
        return self.circuit

    def simulate(self, shots=None, use_gpu=True, monte_carlo_seed=None):
        """
        Simulate the MHRQI circuit with optional Monte Carlo backend.

        Args:
            shots (int, optional): Number of shots. Returns statevector if None.
                If provided, uses Monte Carlo shot-based sampling.
            use_gpu (bool): Whether to use GPU acceleration (if available).
            monte_carlo_seed (int, optional): Seed for reproducible Monte Carlo sampling.

        Returns:
            MHRQIResult: Simulation results object.
        """
        if shots is None:
            # Statevector simulation (exact)
            backend = Aer.get_backend("statevector_simulator", device="GPU" if use_gpu else "CPU")
            transpiled = transpile(self.circuit, backend)
            raw = backend.run(transpiled).result().get_statevector()
        else:
            # Monte Carlo shot-based simulation
            qc_measure = self.circuit.copy()
            creg = ClassicalRegister(len(self.qubits_to_measure), "c")
            qc_measure.add_register(creg)
            qc_measure.measure(self.qubits_to_measure, creg)

            # Try GPU-accelerated backends first
            if use_gpu:
                try:
                    backend = AerSimulator(
                        method="statevector", device="GPU", cuStateVec_enable=True
                    )
                except Exception:
                    backend = Aer.get_backend("qasm_simulator")
            else:
                backend = Aer.get_backend("qasm_simulator")

            transpiled = transpile(qc_measure, backend)

            # Option 1: Use Qiskit's native sampling (traditional approach)
            try:
                raw = backend.run(transpiled, shots=shots).result().get_counts()
            except Exception as e:
                # Fallback to statevector + Monte Carlo if Qiskit sampling fails
                warnings.warn(f"Qiskit sampling failed ({e}); falling back to Monte Carlo backend.", stacklevel=2)
                statevector_backend = Aer.get_backend("statevector_simulator")
                sv_circuit = self.circuit.copy()
                sv_transpiled = transpile(sv_circuit, statevector_backend)
                statevector = statevector_backend.run(sv_transpiled).result().get_statevector()

                mc_simulator = MonteCarloSimulator(seed=monte_carlo_seed, use_gpu=use_gpu)
                raw = mc_simulator.sample_statevector(statevector, shots, self.qubits_to_measure)

        return MHRQIResult(
            raw, self.hierarchical_coord_matrix, self.bit_depth, self.denoise_enabled
        )

    def apply_denoising(self):
        """
        Apply hierarchical consistency denoising to the circuit.
        """
        _, denoise_qc = apply_denoising(
            self.circuit, self.pos_regs, self.intensity_reg, self.outcome_reg
        )
        self.denoise_enabled = True
        return denoise_qc

    def decode(self, results):
        """
        Decode simulation results into image bins.

        Args:
            results (dict or Statevector): Simulation results.

        Returns:
            dict: Reconstructed image bins.
        """
        # The actual decoding logic is now handled within MHRQIResult
        # This method might be removed or refactored depending on usage
        # For now, it can serve as a placeholder or direct call to MHRQIResult's decode
        mhrqi_result = MHRQIResult(
            results, self.hierarchical_coord_matrix, self.bit_depth, self.denoise_enabled
        )
        return mhrqi_result.decode()

qubits_to_measure property

Returns a list of qubits that should be measured for reconstruction.

__init__(depth, bit_depth=8)

Initialize an MHRQI instance.

Parameters:

Name Type Description Default
depth

Hierarchy depth (log2 of image side)

required
bit_depth

Bits for intensity encoding (default 8)

8
Source code in mhrqi/core/representation.py
 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
def __init__(self, depth, bit_depth=8):
    """
    Initialize an MHRQI instance.

    Args:
        depth: Hierarchy depth (log2 of image side)
        bit_depth: Bits for intensity encoding (default 8)
    """
    self.depth = depth
    self.bit_depth = bit_depth
    self.hierarchical_coord_matrix = None
    self.denoise_enabled = False

    self.pos_regs = []
    # Position qubits (2 per level: y and x)
    for k in range(depth):
        self.pos_regs.append(QuantumRegister(1, f"q_y_{k}"))
        self.pos_regs.append(QuantumRegister(1, f"q_x_{k}"))

    self.intensity_reg = QuantumRegister(bit_depth, "intensity")
    self.outcome_reg = QuantumRegister(1, "outcome")
    self.work_reg = QuantumRegister(2, "work")

    self.circuit = QuantumCircuit(
        *self.pos_regs, self.intensity_reg, self.outcome_reg, self.work_reg
    )

    # Place position qubits in uniform superposition
    for reg in self.pos_regs:
        self.circuit.h(reg[0])

apply_denoising()

Apply hierarchical consistency denoising to the circuit.

Source code in mhrqi/core/representation.py
263
264
265
266
267
268
269
270
271
def apply_denoising(self):
    """
    Apply hierarchical consistency denoising to the circuit.
    """
    _, denoise_qc = apply_denoising(
        self.circuit, self.pos_regs, self.intensity_reg, self.outcome_reg
    )
    self.denoise_enabled = True
    return denoise_qc

decode(results)

Decode simulation results into image bins.

Parameters:

Name Type Description Default
results dict or Statevector

Simulation results.

required

Returns:

Name Type Description
dict

Reconstructed image bins.

Source code in mhrqi/core/representation.py
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
def decode(self, results):
    """
    Decode simulation results into image bins.

    Args:
        results (dict or Statevector): Simulation results.

    Returns:
        dict: Reconstructed image bins.
    """
    # The actual decoding logic is now handled within MHRQIResult
    # This method might be removed or refactored depending on usage
    # For now, it can serve as a placeholder or direct call to MHRQIResult's decode
    mhrqi_result = MHRQIResult(
        results, self.hierarchical_coord_matrix, self.bit_depth, self.denoise_enabled
    )
    return mhrqi_result.decode()

lazy_upload(hierarchical_coord_matrix, image)

Fast basis upload using direct statevector initialization.

Parameters:

Name Type Description Default
hierarchical_coord_matrix list

List of hierarchical_coord_vectors for all pixels.

required
image ndarray

Normalized image array [0, 1].

required

Returns:

Name Type Description
QuantumCircuit

The initialized circuit.

Source code in mhrqi/core/representation.py
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
def lazy_upload(self, hierarchical_coord_matrix, image):
    """
    Fast basis upload using direct statevector initialization.

    Args:
        hierarchical_coord_matrix (list): List of hierarchical_coord_vectors for all pixels.
        image (np.ndarray): Normalized image array [0, 1].

    Returns:
        QuantumCircuit: The initialized circuit.
    """
    self.hierarchical_coord_matrix = hierarchical_coord_matrix
    qubit_to_idx = {q: i for i, q in enumerate(self.circuit.qubits)}
    pos_indices = [qubit_to_idx[reg[0]] for reg in self.pos_regs]
    intensity_indices = [qubit_to_idx[q] for q in self.intensity_reg]

    num_qubits = self.circuit.num_qubits
    dim = 2**num_qubits
    state = np.zeros(dim, dtype=complex)

    all_indices = pos_indices + intensity_indices
    is_sequential = all(all_indices[i] == i for i in range(len(all_indices)))

    if is_sequential:
        for hierarchical_coord_vector in hierarchical_coord_matrix:
            p = 0
            for i, val in enumerate(hierarchical_coord_vector):
                if val:
                    p |= 1 << i

            r, c = utils.compose_rc(hierarchical_coord_vector, 2)
            pixel_value = float(image[r, c])
            intensity_int = int(pixel_value * (2**self.bit_depth - 1))

            base_idx = p
            intensity_offset = 0
            for bit_idx in range(self.bit_depth):
                if (intensity_int >> bit_idx) & 1:
                    intensity_offset |= 1 << (len(pos_indices) + bit_idx)
            state[base_idx + intensity_offset] = 1.0
    else:
        warnings.warn("Qubits not sequential, falling back to gate-based upload.", stacklevel=2)
        return self.upload(hierarchical_coord_matrix, image)

    state_norm = np.linalg.norm(state)
    if state_norm > 0:
        state = state / state_norm

    self.circuit.append(SetStatevector(state), self.circuit.qubits)
    return self.circuit

simulate(shots=None, use_gpu=True, monte_carlo_seed=None)

Simulate the MHRQI circuit with optional Monte Carlo backend.

Parameters:

Name Type Description Default
shots int

Number of shots. Returns statevector if None. If provided, uses Monte Carlo shot-based sampling.

None
use_gpu bool

Whether to use GPU acceleration (if available).

True
monte_carlo_seed int

Seed for reproducible Monte Carlo sampling.

None

Returns:

Name Type Description
MHRQIResult

Simulation results object.

Source code in mhrqi/core/representation.py
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
def simulate(self, shots=None, use_gpu=True, monte_carlo_seed=None):
    """
    Simulate the MHRQI circuit with optional Monte Carlo backend.

    Args:
        shots (int, optional): Number of shots. Returns statevector if None.
            If provided, uses Monte Carlo shot-based sampling.
        use_gpu (bool): Whether to use GPU acceleration (if available).
        monte_carlo_seed (int, optional): Seed for reproducible Monte Carlo sampling.

    Returns:
        MHRQIResult: Simulation results object.
    """
    if shots is None:
        # Statevector simulation (exact)
        backend = Aer.get_backend("statevector_simulator", device="GPU" if use_gpu else "CPU")
        transpiled = transpile(self.circuit, backend)
        raw = backend.run(transpiled).result().get_statevector()
    else:
        # Monte Carlo shot-based simulation
        qc_measure = self.circuit.copy()
        creg = ClassicalRegister(len(self.qubits_to_measure), "c")
        qc_measure.add_register(creg)
        qc_measure.measure(self.qubits_to_measure, creg)

        # Try GPU-accelerated backends first
        if use_gpu:
            try:
                backend = AerSimulator(
                    method="statevector", device="GPU", cuStateVec_enable=True
                )
            except Exception:
                backend = Aer.get_backend("qasm_simulator")
        else:
            backend = Aer.get_backend("qasm_simulator")

        transpiled = transpile(qc_measure, backend)

        # Option 1: Use Qiskit's native sampling (traditional approach)
        try:
            raw = backend.run(transpiled, shots=shots).result().get_counts()
        except Exception as e:
            # Fallback to statevector + Monte Carlo if Qiskit sampling fails
            warnings.warn(f"Qiskit sampling failed ({e}); falling back to Monte Carlo backend.", stacklevel=2)
            statevector_backend = Aer.get_backend("statevector_simulator")
            sv_circuit = self.circuit.copy()
            sv_transpiled = transpile(sv_circuit, statevector_backend)
            statevector = statevector_backend.run(sv_transpiled).result().get_statevector()

            mc_simulator = MonteCarloSimulator(seed=monte_carlo_seed, use_gpu=use_gpu)
            raw = mc_simulator.sample_statevector(statevector, shots, self.qubits_to_measure)

    return MHRQIResult(
        raw, self.hierarchical_coord_matrix, self.bit_depth, self.denoise_enabled
    )

upload(hierarchical_coord_matrix, img)

Upload intensity values using MHRQI(basis) encoding.

Parameters:

Name Type Description Default
hierarchical_coord_matrix

matrix of position states

required
img

normalized image (0-1 range)

required
Source code in mhrqi/core/representation.py
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
def upload(self, hierarchical_coord_matrix, img):
    """
    Upload intensity values using MHRQI(basis) encoding.

    Args:
        hierarchical_coord_matrix: matrix of position states
        img: normalized image (0-1 range)
    """
    self.hierarchical_coord_matrix = hierarchical_coord_matrix
    controls = [reg[0] for reg in self.pos_regs]
    intensity_qubits = list(self.intensity_reg)
    and_ancilla = self.work_reg[0]

    for vec in hierarchical_coord_matrix:
        ctrl_states = list(vec)
        r, c = utils.compose_rc(vec, 2)  # d=2 for images
        pixel_value = float(img[r, c])
        intensity_int = int(pixel_value * (2**self.bit_depth - 1))
        intensity_bits = format(intensity_int, f"0{self.bit_depth}b")[::-1]

        _prepare_controls_on_states(self.circuit, controls, ctrl_states)

        if len(controls) > 0:
            self.circuit.mcx(controls, and_ancilla)
            for bit_idx, bit_val in enumerate(intensity_bits):
                if bit_val == "1":
                    self.circuit.cx(and_ancilla, intensity_qubits[bit_idx])
            self.circuit.mcx(controls, and_ancilla)
        else:
            for bit_idx, bit_val in enumerate(intensity_bits):
                if bit_val == "1":
                    self.circuit.x(intensity_qubits[bit_idx])

        _restore_controls(self.circuit, controls, ctrl_states)
    return self.circuit