sdim.circuit_io

  1from .circuit import Circuit
  2from .unitary import *
  3import cirq
  4import numpy as np
  5import os
  6import re
  7import shlex
  8
  9
 10# How write_circuit writes a gate parameter, and how read_circuit reads it back:
 11#   - text:                          key="text", with backslashes and double quotes escaped;
 12#   - None, booleans and numbers:    key=value, unquoted, the repr of the plain Python value (also for
 13#                                    NumPy scalars and subclasses of int and float);
 14#   - an N2 prob_dist (any sequence): key="[p0, p1, ...]", read back as a float64 array;
 15#   - anything else:                 key="str(value)", read back as text.
 16# Older versions wrote every value as key="str(value)".  For those files (and quoted values in
 17# general), prob, a and scalar are read as numbers and prob_dist as an array; the rest stays text.
 18_NUMBER_PARAMS = {"prob", "a", "scalar"}
 19_FLOAT_LIST_PARAMS = {"prob_dist"}
 20_LITERALS = {"None": None, "True": True, "False": False}
 21
 22# One whitespace-separated token of a gate line as write_circuit writes it: a word (gate name or
 23# qudit index), key="text" (only \\ and \" escaped, as shlex reads them) or key=text.
 24_TOKEN = re.compile(r'([^\s"\'\\=]+)(?:=(?:"((?:[^"\\]|\\.)*)"|([^\s"\'\\]*)))?(?=\s|$)')
 25
 26
 27def _format_param(key, value) -> str:
 28    """
 29    Formats one gate parameter for a .chp line (see the table above).
 30
 31    Floats are written with repr, which reads back as the same float.  A prob_dist is written as
 32    a bracketed, comma-separated list on one line, like str() of a list of floats.  Subclasses of
 33    int and float (an IntEnum, ...) are written as the plain int or float, since their own repr
 34    need not read back as a number.
 35    """
 36    if isinstance(value, np.generic):
 37        value = value.item()
 38    if key in _FLOAT_LIST_PARAMS and value is not None and not isinstance(value, str):
 39        text = "[" + ", ".join(repr(float(v)) for v in np.asarray(value, dtype=float).reshape(-1)) + "]"
 40    elif value is None or isinstance(value, bool):  # bool cannot be subclassed
 41        return f"{key}={value!r}"
 42    elif isinstance(value, int):
 43        return f"{key}={int(value)!r}"
 44    elif isinstance(value, float):
 45        return f"{key}={float(value)!r}"
 46    else:
 47        text = str(value)
 48    if "\n" in text or "\r" in text:
 49        raise ValueError(f"Cannot write gate parameter {key}={text!r}: a .chp line cannot hold a line break.")
 50    return key + '="' + text.replace("\\", "\\\\").replace('"', '\\"') + '"'
 51
 52
 53def _split_gate_line(line: str) -> list:
 54    """
 55    Splits a gate line into its tokens, like shlex.split, and tells which values were quoted.
 56
 57    Returns a list of (word, value, quoted): value is None for a token without '=', otherwise
 58    word is the key.  A line that write_circuit would not write (single quotes, a backslash or
 59    a quote outside a value, ...) is split by shlex.split, with every value taken as quoted text,
 60    which is how older versions read every line.
 61    """
 62    tokens = []
 63    position = 0
 64    while True:
 65        while position < len(line) and line[position].isspace():
 66            position += 1
 67        if position == len(line):
 68            return tokens
 69        match = _TOKEN.match(line, position)
 70        if match is None:
 71            break
 72        word, quoted_text, bare_text = match.groups()
 73        if quoted_text is not None:
 74            tokens.append((word, re.sub(r'\\(["\\])', r"\1", quoted_text), True))
 75        else:
 76            tokens.append((word, bare_text, False))
 77        position = match.end()
 78    tokens = []
 79    for part in shlex.split(line):
 80        if "=" in part:
 81            key, value = part.split("=", 1)
 82            tokens.append((key, value, True))
 83        else:
 84            tokens.append((part, None, True))
 85    return tokens
 86
 87
 88def _parse_number(text: str):
 89    """text as an int, or else as a float; None if it is neither."""
 90    try:
 91        return int(text)
 92    except ValueError:
 93        pass
 94    try:
 95        return float(text)
 96    except ValueError:
 97        return None
 98
 99
100def _parse_float_list(text: str):
101    """Reads a prob_dist written by _format_param, or by older versions (str() of a list or a short array)."""
102    body = text.strip()
103    if body.startswith("[") and body.endswith("]"):
104        body = body[1:-1]
105    items = [item for item in re.split(r"[\s,]+", body) if item]
106    return np.array([float(item) for item in items], dtype=np.float64)
107
108
109def _parse_param(key: str, text: str, quoted: bool, cache: dict):
110    """
111    Converts the text of a gate parameter back to its value (see the table above).
112
113    An unquoted value is None, True, False, an int or a float when it reads as one, and text
114    otherwise.  A quoted value is text, except that prob, a and scalar become numbers and
115    prob_dist a float array (None for "None").  Text that does not convert is returned as it
116    is, so the gate reports it the same way it did before.  Equal prob_dist texts share one array.
117    """
118    if key in _FLOAT_LIST_PARAMS:
119        if text == "None":
120            return None
121        if text not in cache:
122            try:
123                cache[text] = _parse_float_list(text)
124            except ValueError:
125                return text
126        return cache[text]
127    if not quoted:
128        if text in _LITERALS:
129            return _LITERALS[text]
130        number = _parse_number(text)
131        return text if number is None else number
132    if key in _NUMBER_PARAMS:
133        number = _parse_number(text)
134        return text if number is None else number
135    return text
136
137
138def read_circuit(filename):
139    """
140    Reads a circuit from a file and creates a Circuit object.
141
142    The file holds an optional comment, a line with only '#', an optional dimension line
143    "d <dimension>" (with "qudits=<n>" in files written by write_circuit), then one gate per line:
144    the gate name, its qudit indices (negative ones count back from the end), and its parameters
145    as key="text" or key=value (see write_circuit for which values come back with which type).
146    Files written by older versions hold only key="text": prob, a / scalar and prob_dist are read
147    from them as numbers, and the other parameters as text.  The file is read as UTF-8.
148
149    Args:
150        filename (str): Path to the file, absolute or relative to the current working directory.
151            A relative path that does not exist there is looked up relative to the folder above
152            the sdim package (the repository root in a source checkout), as older versions did.
153
154    Returns:
155        Circuit: A Circuit object representing the circuit described in the file.
156
157    Raises:
158        FileNotFoundError: If the file exists in neither place.
159        ValueError: If the file has no line with only '#', a gate has more than two qudit indices,
160            or a gate line is not a valid gate (Circuit.add_gate rejects it).
161    """
162    path = filename
163    if not os.path.exists(path):
164        # Older versions resolved every name against the folder above the package.
165        script_dir = os.path.dirname(os.path.realpath(__file__))
166        fallback = os.path.join(script_dir, '..', filename)
167        if os.path.exists(fallback):
168            path = fallback
169
170    with open(path, 'r', encoding='utf-8') as file:
171        lines = file.readlines()
172
173    # Find the line with only '#'
174    start_index = next((i for i, line in enumerate(lines) if line.strip() == '#'), None)
175    if start_index is None:
176        raise ValueError(f"{filename} has no line with only '#' before the gates.")
177
178    # Extract the non-blank lines after '#'
179    gate_lines = [line for line in lines[start_index + 1:] if line.strip()]
180
181    # Default dimension and qudit count (the qudit count is otherwise the largest index + 1)
182    dimension = 2
183    declared_qudits = 0
184
185    # Check the line immediately after '#'
186    if gate_lines:
187        parts = gate_lines[0].split()
188        if parts[0].upper() == 'D':
189            dimension = int(parts[1])
190            for part in parts[2:]:
191                if part.lower().startswith('qudits='):
192                    declared_qudits = int(part.split('=', 1)[1])
193            gate_lines = gate_lines[1:]
194
195    # Parse every gate line: qudit indices are the integer arguments (negative ones count from the end),
196    # parameters are key=value.
197    gates = []
198    prob_dist_cache = {}
199    for line in gate_lines:
200        tokens = _split_gate_line(line)
201        gate_name = tokens[0][0].upper()
202        gate_qubits = [int(word) for word, value, _ in tokens[1:]
203                       if value is None and (word.isdigit() or word[:1] == "-" and word[1:].isdigit())]
204        if len(gate_qubits) > 2:
205            raise ValueError(f"Unexpected number of arguments for gate {gate_name}")
206        params_dict = None
207        for key, value, quoted in tokens[1:]:
208            if value is None:
209                continue
210            if not key:
211                raise ValueError("Extra parameter doesn't have the correct format.")
212            if params_dict is None:
213                params_dict = dict()
214            params_dict[key] = _parse_param(key, value, quoted, prob_dist_cache)
215        gates.append((gate_name, gate_qubits, params_dict, line.strip()))
216
217    # Negative indices count back from the end, so they leave a declared count as it is; without one, -k needs k qudits.
218    num_qudits = max([declared_qudits, 1] + [q + 1 if q >= 0 else 0 if declared_qudits else -q
219                                             for _, qubits, _, _ in gates for q in qubits])
220    circuit = Circuit(num_qudits, dimension)
221
222    # Append the gates to the circuit
223    for gate_name, gate_qubits, params_dict, line in gates:
224        try:
225            if params_dict is not None:
226                circuit.add_gate(gate_name, *gate_qubits, **params_dict)
227            else:
228                circuit.add_gate(gate_name, *gate_qubits)
229        except ValueError as error:
230            raise ValueError(f"{filename}: gate line {line!r}: {error}") from error
231
232    return circuit
233
234def write_circuit(circuit: Circuit, output_file: str = "random_circuit.chp", comment: str = "", directory: str = None):
235    """
236    Writes a Circuit object to a file in the .chp format.
237
238    Every gate parameter is written, and read_circuit reads the circuit back with the same
239    gates and qudit count.  Parameters that are numbers, booleans or None come back with the
240    same value and type (a NumPy scalar, or a subclass of int or float such as an IntEnum, as
241    the matching Python int, float or bool), and an N2 prob_dist as a float64 array with the same
242    entries.  Text comes back as the same text, except under the keys prob, a and scalar, where
243    text that reads as a number comes back as that number (prob="0.1" as the float 0.1, a="2"
244    as the int 2), the way files of older versions are read; the simulators convert these
245    parameters to numbers anyway.  A value of any other type is written as its str() and comes
246    back as that text (under prob, a and scalar, as a number when the text reads as one).
247    The file is written as UTF-8.
248
249    Args:
250        circuit (Circuit): The Circuit object to write.
251        output_file (str): The name of the output file. Defaults to "random_circuit.chp".
252        comment (str): An optional comment to include at the beginning of the file.
253        directory (str): Optional directory to save the file in, created if needed. If None, uses
254            circuits/ in the current working directory, which is the repository's circuits/ folder
255            when run from the root of a source checkout. (Older versions wrote to the circuits/
256            folder next to the sdim package, which for an installed package is in site-packages.)
257
258    Returns:
259        str: The path to the written file.
260    """
261    chp_content = ""
262    if comment:
263        chp_content += f"{comment}\n#\n"
264    else:
265        chp_content += "Randomly-generated Clifford group quantum circuit\n#\n"
266    # Older readers take the dimension from the second token and ignore the rest of the line.
267    chp_content += f"d {circuit.dimension} qudits={circuit.num_qudits}\n"
268
269    for gate in circuit.operations:
270        gate_str = gate.gate_name
271        if gate.target_index is not None:
272            gate_str += f" {gate.qudit_index} {gate.target_index}"
273        elif gate.qudit_index is not None:
274            gate_str += f" {gate.qudit_index}"
275        # Writing extra parameters
276        if not (gate.params is None):
277            for key, value in gate.params.items():
278                gate_str += " " + _format_param(key, value)
279
280        chp_content += f"{gate_str}\n"
281
282    if directory is None:
283        # Not next to the package, which for an installed sdim is inside site-packages.
284        directory = 'circuits'
285
286    # Create the directory if it doesn't exist
287    os.makedirs(directory, exist_ok=True)
288
289    # Join the directory with the output file name
290    output_path = os.path.join(directory, output_file)
291
292    # Write the content to the .chp file
293    with open(output_path, "w", encoding="utf-8") as file:
294        file.write(chp_content)
295
296    return output_path
297
298
299class GeneralizedSwapGate(cirq.Gate):
300    """Swaps two qudits of dimension d: |i, j> -> |j, i>."""
301
302    def __init__(self, d):
303        super(GeneralizedSwapGate, self).__init__()
304        self.d = d
305
306    def _qid_shape_(self):
307        return (self.d, self.d)
308
309    def _unitary_(self):
310        d = self.d
311        swap = np.zeros((d * d, d * d), dtype=np.complex128)
312        for i in range(d):
313            for j in range(d):
314                swap[j * d + i, i * d + j] = 1
315        return swap
316
317    def __pow__(self, exponent):
318        if exponent in (1, -1):
319            return self
320        return NotImplemented
321
322    def _circuit_diagram_info_(self, args):
323        return (f"SWAP_{self.d}", f"SWAP_{self.d}")
324
325
326def circuit_to_cirq_circuit(circuit, measurement=False, print_circuit=False, ignore_noise=True):
327    """
328    Converts a Circuit object to a Cirq Circuit object.
329
330    With measurement=True, every measurement record of sdim becomes a Cirq measurement with key
331    f"m_{qudit}": M, M_X (H_INV, measure, H, which leaves the qudit in the matching X
332    eigenstate) and RESET (the pre-reset outcome, then cirq.ResetChannel).  The k-th instance of
333    key f"m_{q}" in Cirq's records is then measurement round k of qudit q in sdim's results.
334    With measurement=False, M and M_X are left out and RESET is only the reset channel.
335    TICK, DETECTOR and LOGICAL_OBSERVABLE do not act on the state and are skipped.
336    The noise gates N1 and N2 are left out as well, so the result is the noiseless circuit,
337    unless ignore_noise=False.
338
339    Args:
340        circuit (Circuit): The Circuit object to convert.
341        measurement (bool): Whether to include measurement gates. Defaults to False.
342        print_circuit (bool): Whether to print the Cirq circuit. Defaults to False.
343        ignore_noise (bool): Leave out the noise gates N1 and N2. Defaults to True; with False,
344            a noise gate raises NotImplementedError.
345
346    Returns:
347        cirq.Circuit: The equivalent Cirq Circuit object.
348
349    Raises:
350        NotImplementedError: For a noise gate (N1, N2) when ignore_noise=False.
351    """
352    d = circuit.dimension
353    # Create a list of qudits.
354    qudits = [cirq.LineQid(i, dimension=d) for i in range(circuit.num_qudits)]
355
356    # Create the generalized gates.
357    gate_map = {
358        "I": IdentityGate(d),
359        "H": GeneralizedHadamardGate(d),
360        "P": GeneralizedPhaseShiftGate(d),
361        "CNOT": GeneralizedCNOTGate(d),
362        "X": GeneralizedXPauliGate(d),
363        "Z": GeneralizedZPauliGate(d),
364        "H_INV": GeneralizedHadamardGateInverse(d),
365        "P_INV": GeneralizedPhaseShiftGateInverse(d),
366        "CNOT_INV": GeneralizedCNOTGateInverse(d),
367        "X_INV": GeneralizedXPauliGateInverse(d),
368        "Z_INV": GeneralizedZPauliGateInverse(d),
369        "CZ": GeneralizedCZGate(d),
370        "CZ_INV": GeneralizedCZGateInverse(d),
371        "SWAP": GeneralizedSwapGate(d),
372    }
373
374    # Create a Cirq circuit.
375    cirq_circuit = cirq.Circuit()
376
377    # Apply each gate in the circuit.
378    for op in circuit.operations:
379        if op.name in ("TICK", "DETECTOR", "LOGICAL_OBSERVABLE"):
380            continue
381        if op.name in ("N1", "N2"):
382            if ignore_noise:
383                continue
384            raise NotImplementedError(
385                f"Noise gate {op.name} has no Cirq equivalent here; with ignore_noise=True (the default) "
386                "it is left out and the circuit is converted without noise."
387            )
388        if op.name in ("M", "M_X", "RESET"):
389            qudit = qudits[op.qudit_index]
390            if measurement:
391                if op.name == "M_X":
392                    cirq_circuit.append(gate_map["H_INV"].on(qudit))
393                cirq_circuit.append(cirq.measure(qudit, key=f'm_{op.qudit_index}'))
394                if op.name == "M_X":
395                    cirq_circuit.append(gate_map["H"].on(qudit))
396            if op.name == "RESET":
397                cirq_circuit.append(cirq.ResetChannel(dimension=d).on(qudit))
398            continue
399
400        # Choose the appropriate gate.
401        if op.name in gate_map:
402            gate = gate_map[op.name]
403        elif op.name == "MUL":
404            if op.params is None:
405                raise ValueError("Multiplication gate requires an 'a' parameter.")
406            scalar = op.params.get("a", op.params.get("scalar"))
407            if scalar is None:
408                raise ValueError("Multiplication gate requires an 'a' parameter.")
409            # Only a mod d matters (the simulators reduce it too).
410            gate = GeneralizedMultiplicationGate(d, int(scalar) % d)
411        else:
412            raise NotImplementedError(f"Gate {op.name} not implemented")
413
414        # Add the gate to the Cirq circuit.
415        if op.target_index is None:
416            # Single-qudit gate.
417            cirq_circuit.append(gate.on(qudits[op.qudit_index]))
418        else:
419            # Two-qudit gate.
420            cirq_circuit.append(gate.on(qudits[op.qudit_index], qudits[op.target_index]))
421    for qudit in qudits:
422        if not any(op.qubits[0] == qudit for op in cirq_circuit.all_operations()):
423            # Append identity to qudits with no gates
424            cirq_circuit.append(IdentityGate(d).on(qudit))
425    if print_circuit:
426        print(cirq_circuit)
427    return cirq_circuit
428
429def cirq_statevector_from_circuit(circuit, print_circuit=False, ignore_noise=True):
430    """
431    Simulates a Circuit object using Cirq and returns the final state vector.
432
433    Measurements and noise are left out (see circuit_to_cirq_circuit), and RESET is applied as a
434    reset channel.
435
436    Args:
437        circuit (Circuit): The Circuit object to simulate.
438        print_circuit (bool): Whether to print the Cirq circuit. Defaults to False.
439        ignore_noise (bool): Leave out the noise gates N1 and N2. Defaults to True; with False,
440            a noise gate raises NotImplementedError.
441
442    Returns:
443        np.ndarray: The final state vector given by the Cirq simulator.
444    """
445    # Start with an initial state. For a quantum computer, this is usually the state |0...0>.
446    cirq_circuit = circuit_to_cirq_circuit(circuit, print_circuit=print_circuit, ignore_noise=ignore_noise)
447    # Simulate the Cirq circuit.
448    simulator = cirq.Simulator()
449    result = simulator.simulate(cirq_circuit)
450    
451    # Return the final state vector.
452    return result.final_state_vector
def read_circuit(filename):
139def read_circuit(filename):
140    """
141    Reads a circuit from a file and creates a Circuit object.
142
143    The file holds an optional comment, a line with only '#', an optional dimension line
144    "d <dimension>" (with "qudits=<n>" in files written by write_circuit), then one gate per line:
145    the gate name, its qudit indices (negative ones count back from the end), and its parameters
146    as key="text" or key=value (see write_circuit for which values come back with which type).
147    Files written by older versions hold only key="text": prob, a / scalar and prob_dist are read
148    from them as numbers, and the other parameters as text.  The file is read as UTF-8.
149
150    Args:
151        filename (str): Path to the file, absolute or relative to the current working directory.
152            A relative path that does not exist there is looked up relative to the folder above
153            the sdim package (the repository root in a source checkout), as older versions did.
154
155    Returns:
156        Circuit: A Circuit object representing the circuit described in the file.
157
158    Raises:
159        FileNotFoundError: If the file exists in neither place.
160        ValueError: If the file has no line with only '#', a gate has more than two qudit indices,
161            or a gate line is not a valid gate (Circuit.add_gate rejects it).
162    """
163    path = filename
164    if not os.path.exists(path):
165        # Older versions resolved every name against the folder above the package.
166        script_dir = os.path.dirname(os.path.realpath(__file__))
167        fallback = os.path.join(script_dir, '..', filename)
168        if os.path.exists(fallback):
169            path = fallback
170
171    with open(path, 'r', encoding='utf-8') as file:
172        lines = file.readlines()
173
174    # Find the line with only '#'
175    start_index = next((i for i, line in enumerate(lines) if line.strip() == '#'), None)
176    if start_index is None:
177        raise ValueError(f"{filename} has no line with only '#' before the gates.")
178
179    # Extract the non-blank lines after '#'
180    gate_lines = [line for line in lines[start_index + 1:] if line.strip()]
181
182    # Default dimension and qudit count (the qudit count is otherwise the largest index + 1)
183    dimension = 2
184    declared_qudits = 0
185
186    # Check the line immediately after '#'
187    if gate_lines:
188        parts = gate_lines[0].split()
189        if parts[0].upper() == 'D':
190            dimension = int(parts[1])
191            for part in parts[2:]:
192                if part.lower().startswith('qudits='):
193                    declared_qudits = int(part.split('=', 1)[1])
194            gate_lines = gate_lines[1:]
195
196    # Parse every gate line: qudit indices are the integer arguments (negative ones count from the end),
197    # parameters are key=value.
198    gates = []
199    prob_dist_cache = {}
200    for line in gate_lines:
201        tokens = _split_gate_line(line)
202        gate_name = tokens[0][0].upper()
203        gate_qubits = [int(word) for word, value, _ in tokens[1:]
204                       if value is None and (word.isdigit() or word[:1] == "-" and word[1:].isdigit())]
205        if len(gate_qubits) > 2:
206            raise ValueError(f"Unexpected number of arguments for gate {gate_name}")
207        params_dict = None
208        for key, value, quoted in tokens[1:]:
209            if value is None:
210                continue
211            if not key:
212                raise ValueError("Extra parameter doesn't have the correct format.")
213            if params_dict is None:
214                params_dict = dict()
215            params_dict[key] = _parse_param(key, value, quoted, prob_dist_cache)
216        gates.append((gate_name, gate_qubits, params_dict, line.strip()))
217
218    # Negative indices count back from the end, so they leave a declared count as it is; without one, -k needs k qudits.
219    num_qudits = max([declared_qudits, 1] + [q + 1 if q >= 0 else 0 if declared_qudits else -q
220                                             for _, qubits, _, _ in gates for q in qubits])
221    circuit = Circuit(num_qudits, dimension)
222
223    # Append the gates to the circuit
224    for gate_name, gate_qubits, params_dict, line in gates:
225        try:
226            if params_dict is not None:
227                circuit.add_gate(gate_name, *gate_qubits, **params_dict)
228            else:
229                circuit.add_gate(gate_name, *gate_qubits)
230        except ValueError as error:
231            raise ValueError(f"{filename}: gate line {line!r}: {error}") from error
232
233    return circuit

Reads a circuit from a file and creates a Circuit object.

The file holds an optional comment, a line with only '#', an optional dimension line "d " (with "qudits=" in files written by write_circuit), then one gate per line: the gate name, its qudit indices (negative ones count back from the end), and its parameters as key="text" or key=value (see write_circuit for which values come back with which type). Files written by older versions hold only key="text": prob, a / scalar and prob_dist are read from them as numbers, and the other parameters as text. The file is read as UTF-8.

Arguments:
  • filename (str): Path to the file, absolute or relative to the current working directory. A relative path that does not exist there is looked up relative to the folder above the sdim package (the repository root in a source checkout), as older versions did.
Returns:

Circuit: A Circuit object representing the circuit described in the file.

Raises:
  • FileNotFoundError: If the file exists in neither place.
  • ValueError: If the file has no line with only '#', a gate has more than two qudit indices, or a gate line is not a valid gate (Circuit.add_gate rejects it).
def write_circuit( circuit: sdim.circuit.Circuit, output_file: str = 'random_circuit.chp', comment: str = '', directory: str = None):
235def write_circuit(circuit: Circuit, output_file: str = "random_circuit.chp", comment: str = "", directory: str = None):
236    """
237    Writes a Circuit object to a file in the .chp format.
238
239    Every gate parameter is written, and read_circuit reads the circuit back with the same
240    gates and qudit count.  Parameters that are numbers, booleans or None come back with the
241    same value and type (a NumPy scalar, or a subclass of int or float such as an IntEnum, as
242    the matching Python int, float or bool), and an N2 prob_dist as a float64 array with the same
243    entries.  Text comes back as the same text, except under the keys prob, a and scalar, where
244    text that reads as a number comes back as that number (prob="0.1" as the float 0.1, a="2"
245    as the int 2), the way files of older versions are read; the simulators convert these
246    parameters to numbers anyway.  A value of any other type is written as its str() and comes
247    back as that text (under prob, a and scalar, as a number when the text reads as one).
248    The file is written as UTF-8.
249
250    Args:
251        circuit (Circuit): The Circuit object to write.
252        output_file (str): The name of the output file. Defaults to "random_circuit.chp".
253        comment (str): An optional comment to include at the beginning of the file.
254        directory (str): Optional directory to save the file in, created if needed. If None, uses
255            circuits/ in the current working directory, which is the repository's circuits/ folder
256            when run from the root of a source checkout. (Older versions wrote to the circuits/
257            folder next to the sdim package, which for an installed package is in site-packages.)
258
259    Returns:
260        str: The path to the written file.
261    """
262    chp_content = ""
263    if comment:
264        chp_content += f"{comment}\n#\n"
265    else:
266        chp_content += "Randomly-generated Clifford group quantum circuit\n#\n"
267    # Older readers take the dimension from the second token and ignore the rest of the line.
268    chp_content += f"d {circuit.dimension} qudits={circuit.num_qudits}\n"
269
270    for gate in circuit.operations:
271        gate_str = gate.gate_name
272        if gate.target_index is not None:
273            gate_str += f" {gate.qudit_index} {gate.target_index}"
274        elif gate.qudit_index is not None:
275            gate_str += f" {gate.qudit_index}"
276        # Writing extra parameters
277        if not (gate.params is None):
278            for key, value in gate.params.items():
279                gate_str += " " + _format_param(key, value)
280
281        chp_content += f"{gate_str}\n"
282
283    if directory is None:
284        # Not next to the package, which for an installed sdim is inside site-packages.
285        directory = 'circuits'
286
287    # Create the directory if it doesn't exist
288    os.makedirs(directory, exist_ok=True)
289
290    # Join the directory with the output file name
291    output_path = os.path.join(directory, output_file)
292
293    # Write the content to the .chp file
294    with open(output_path, "w", encoding="utf-8") as file:
295        file.write(chp_content)
296
297    return output_path

Writes a Circuit object to a file in the .chp format.

Every gate parameter is written, and read_circuit reads the circuit back with the same gates and qudit count. Parameters that are numbers, booleans or None come back with the same value and type (a NumPy scalar, or a subclass of int or float such as an IntEnum, as the matching Python int, float or bool), and an N2 prob_dist as a float64 array with the same entries. Text comes back as the same text, except under the keys prob, a and scalar, where text that reads as a number comes back as that number (prob="0.1" as the float 0.1, a="2" as the int 2), the way files of older versions are read; the simulators convert these parameters to numbers anyway. A value of any other type is written as its str() and comes back as that text (under prob, a and scalar, as a number when the text reads as one). The file is written as UTF-8.

Arguments:
  • circuit (Circuit): The Circuit object to write.
  • output_file (str): The name of the output file. Defaults to "random_circuit.chp".
  • comment (str): An optional comment to include at the beginning of the file.
  • directory (str): Optional directory to save the file in, created if needed. If None, uses circuits/ in the current working directory, which is the repository's circuits/ folder when run from the root of a source checkout. (Older versions wrote to the circuits/ folder next to the sdim package, which for an installed package is in site-packages.)
Returns:

str: The path to the written file.

class GeneralizedSwapGate(cirq.ops.raw_types.Gate):
300class GeneralizedSwapGate(cirq.Gate):
301    """Swaps two qudits of dimension d: |i, j> -> |j, i>."""
302
303    def __init__(self, d):
304        super(GeneralizedSwapGate, self).__init__()
305        self.d = d
306
307    def _qid_shape_(self):
308        return (self.d, self.d)
309
310    def _unitary_(self):
311        d = self.d
312        swap = np.zeros((d * d, d * d), dtype=np.complex128)
313        for i in range(d):
314            for j in range(d):
315                swap[j * d + i, i * d + j] = 1
316        return swap
317
318    def __pow__(self, exponent):
319        if exponent in (1, -1):
320            return self
321        return NotImplemented
322
323    def _circuit_diagram_info_(self, args):
324        return (f"SWAP_{self.d}", f"SWAP_{self.d}")

Swaps two qudits of dimension d: |i, j> -> |j, i>.

GeneralizedSwapGate(d)
303    def __init__(self, d):
304        super(GeneralizedSwapGate, self).__init__()
305        self.d = d
d
@value.alternative(requires='_num_qubits_', implementation=_backwards_compatibility_num_qubits)
def num_qubits(self) -> int:
414    @value.alternative(requires='_num_qubits_', implementation=_backwards_compatibility_num_qubits)
415    def num_qubits(self) -> int:
416        """The number of qubits this gate acts on."""
417        raise NotImplementedError

The number of qubits this gate acts on.

def circuit_to_cirq_circuit(circuit, measurement=False, print_circuit=False, ignore_noise=True):
327def circuit_to_cirq_circuit(circuit, measurement=False, print_circuit=False, ignore_noise=True):
328    """
329    Converts a Circuit object to a Cirq Circuit object.
330
331    With measurement=True, every measurement record of sdim becomes a Cirq measurement with key
332    f"m_{qudit}": M, M_X (H_INV, measure, H, which leaves the qudit in the matching X
333    eigenstate) and RESET (the pre-reset outcome, then cirq.ResetChannel).  The k-th instance of
334    key f"m_{q}" in Cirq's records is then measurement round k of qudit q in sdim's results.
335    With measurement=False, M and M_X are left out and RESET is only the reset channel.
336    TICK, DETECTOR and LOGICAL_OBSERVABLE do not act on the state and are skipped.
337    The noise gates N1 and N2 are left out as well, so the result is the noiseless circuit,
338    unless ignore_noise=False.
339
340    Args:
341        circuit (Circuit): The Circuit object to convert.
342        measurement (bool): Whether to include measurement gates. Defaults to False.
343        print_circuit (bool): Whether to print the Cirq circuit. Defaults to False.
344        ignore_noise (bool): Leave out the noise gates N1 and N2. Defaults to True; with False,
345            a noise gate raises NotImplementedError.
346
347    Returns:
348        cirq.Circuit: The equivalent Cirq Circuit object.
349
350    Raises:
351        NotImplementedError: For a noise gate (N1, N2) when ignore_noise=False.
352    """
353    d = circuit.dimension
354    # Create a list of qudits.
355    qudits = [cirq.LineQid(i, dimension=d) for i in range(circuit.num_qudits)]
356
357    # Create the generalized gates.
358    gate_map = {
359        "I": IdentityGate(d),
360        "H": GeneralizedHadamardGate(d),
361        "P": GeneralizedPhaseShiftGate(d),
362        "CNOT": GeneralizedCNOTGate(d),
363        "X": GeneralizedXPauliGate(d),
364        "Z": GeneralizedZPauliGate(d),
365        "H_INV": GeneralizedHadamardGateInverse(d),
366        "P_INV": GeneralizedPhaseShiftGateInverse(d),
367        "CNOT_INV": GeneralizedCNOTGateInverse(d),
368        "X_INV": GeneralizedXPauliGateInverse(d),
369        "Z_INV": GeneralizedZPauliGateInverse(d),
370        "CZ": GeneralizedCZGate(d),
371        "CZ_INV": GeneralizedCZGateInverse(d),
372        "SWAP": GeneralizedSwapGate(d),
373    }
374
375    # Create a Cirq circuit.
376    cirq_circuit = cirq.Circuit()
377
378    # Apply each gate in the circuit.
379    for op in circuit.operations:
380        if op.name in ("TICK", "DETECTOR", "LOGICAL_OBSERVABLE"):
381            continue
382        if op.name in ("N1", "N2"):
383            if ignore_noise:
384                continue
385            raise NotImplementedError(
386                f"Noise gate {op.name} has no Cirq equivalent here; with ignore_noise=True (the default) "
387                "it is left out and the circuit is converted without noise."
388            )
389        if op.name in ("M", "M_X", "RESET"):
390            qudit = qudits[op.qudit_index]
391            if measurement:
392                if op.name == "M_X":
393                    cirq_circuit.append(gate_map["H_INV"].on(qudit))
394                cirq_circuit.append(cirq.measure(qudit, key=f'm_{op.qudit_index}'))
395                if op.name == "M_X":
396                    cirq_circuit.append(gate_map["H"].on(qudit))
397            if op.name == "RESET":
398                cirq_circuit.append(cirq.ResetChannel(dimension=d).on(qudit))
399            continue
400
401        # Choose the appropriate gate.
402        if op.name in gate_map:
403            gate = gate_map[op.name]
404        elif op.name == "MUL":
405            if op.params is None:
406                raise ValueError("Multiplication gate requires an 'a' parameter.")
407            scalar = op.params.get("a", op.params.get("scalar"))
408            if scalar is None:
409                raise ValueError("Multiplication gate requires an 'a' parameter.")
410            # Only a mod d matters (the simulators reduce it too).
411            gate = GeneralizedMultiplicationGate(d, int(scalar) % d)
412        else:
413            raise NotImplementedError(f"Gate {op.name} not implemented")
414
415        # Add the gate to the Cirq circuit.
416        if op.target_index is None:
417            # Single-qudit gate.
418            cirq_circuit.append(gate.on(qudits[op.qudit_index]))
419        else:
420            # Two-qudit gate.
421            cirq_circuit.append(gate.on(qudits[op.qudit_index], qudits[op.target_index]))
422    for qudit in qudits:
423        if not any(op.qubits[0] == qudit for op in cirq_circuit.all_operations()):
424            # Append identity to qudits with no gates
425            cirq_circuit.append(IdentityGate(d).on(qudit))
426    if print_circuit:
427        print(cirq_circuit)
428    return cirq_circuit

Converts a Circuit object to a Cirq Circuit object.

With measurement=True, every measurement record of sdim becomes a Cirq measurement with key f"m_{qudit}": M, M_X (H_INV, measure, H, which leaves the qudit in the matching X eigenstate) and RESET (the pre-reset outcome, then cirq.ResetChannel). The k-th instance of key f"m_{q}" in Cirq's records is then measurement round k of qudit q in sdim's results. With measurement=False, M and M_X are left out and RESET is only the reset channel. TICK, DETECTOR and LOGICAL_OBSERVABLE do not act on the state and are skipped. The noise gates N1 and N2 are left out as well, so the result is the noiseless circuit, unless ignore_noise=False.

Arguments:
  • circuit (Circuit): The Circuit object to convert.
  • measurement (bool): Whether to include measurement gates. Defaults to False.
  • print_circuit (bool): Whether to print the Cirq circuit. Defaults to False.
  • ignore_noise (bool): Leave out the noise gates N1 and N2. Defaults to True; with False, a noise gate raises NotImplementedError.
Returns:

cirq.Circuit: The equivalent Cirq Circuit object.

Raises:
  • NotImplementedError: For a noise gate (N1, N2) when ignore_noise=False.
def cirq_statevector_from_circuit(circuit, print_circuit=False, ignore_noise=True):
430def cirq_statevector_from_circuit(circuit, print_circuit=False, ignore_noise=True):
431    """
432    Simulates a Circuit object using Cirq and returns the final state vector.
433
434    Measurements and noise are left out (see circuit_to_cirq_circuit), and RESET is applied as a
435    reset channel.
436
437    Args:
438        circuit (Circuit): The Circuit object to simulate.
439        print_circuit (bool): Whether to print the Cirq circuit. Defaults to False.
440        ignore_noise (bool): Leave out the noise gates N1 and N2. Defaults to True; with False,
441            a noise gate raises NotImplementedError.
442
443    Returns:
444        np.ndarray: The final state vector given by the Cirq simulator.
445    """
446    # Start with an initial state. For a quantum computer, this is usually the state |0...0>.
447    cirq_circuit = circuit_to_cirq_circuit(circuit, print_circuit=print_circuit, ignore_noise=ignore_noise)
448    # Simulate the Cirq circuit.
449    simulator = cirq.Simulator()
450    result = simulator.simulate(cirq_circuit)
451    
452    # Return the final state vector.
453    return result.final_state_vector

Simulates a Circuit object using Cirq and returns the final state vector.

Measurements and noise are left out (see circuit_to_cirq_circuit), and RESET is applied as a reset channel.

Arguments:
  • circuit (Circuit): The Circuit object to simulate.
  • print_circuit (bool): Whether to print the Cirq circuit. Defaults to False.
  • ignore_noise (bool): Leave out the noise gates N1 and N2. Defaults to True; with False, a noise gate raises NotImplementedError.
Returns:

np.ndarray: The final state vector given by the Cirq simulator.