Skip to content

Commit

Permalink
Fix pre-commit warnings
Browse files Browse the repository at this point in the history
  • Loading branch information
Takishima committed Apr 2, 2024
1 parent a95f2d0 commit cd9b408
Show file tree
Hide file tree
Showing 16 changed files with 83 additions and 112 deletions.
1 change: 1 addition & 0 deletions .codespell.allow
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,4 @@ braket
te
Ket
ket
lamda
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ repos:
hooks:
- id: pylint
args: ['--score=n', '--disable=no-member']
additional_dependencies: [pybind11>=2.6, numpy, requests, matplotlib, networkx, qiskit-terra, pyparsing]
additional_dependencies: [pybind11>=2.6, numpy, requests, matplotlib, networkx, pyparsing]

- repo: https://github.com/mgedmin/check-manifest
rev: '0.49'
Expand Down
50 changes: 20 additions & 30 deletions projectq/backends/_qasm.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Copyright 2020 ProjectQ-Framework (www.projectq.ch)
#
# Licensed under the Apache License, Version 2.0 (the "License");
Expand All @@ -12,6 +11,7 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Backend to convert ProjectQ commands to OpenQASM."""

from copy import deepcopy
Expand Down Expand Up @@ -57,7 +57,7 @@ def __init__(
"""
Initialize an OpenQASMBackend object.
Contrary to OpenQASM, ProjectQ does not impose the restriction that a programm must start with qubit/bit
Contrary to OpenQASM, ProjectQ does not impose the restriction that a program must start with qubit/bit
allocations and end with some measurements.
The user can configure what happens each time a FlushGate() is encountered by setting the `collate` and
Expand Down Expand Up @@ -168,7 +168,7 @@ def _store(self, cmd): # pylint: disable=too-many-branches,too-many-statements
n_controls = get_control_count(cmd)

def _format_angle(angle):
return '({})'.format(angle)
return f'({angle})'

_ccontrolled_gates_func = {
X: 'ccx',
Expand Down Expand Up @@ -223,8 +223,8 @@ def _format_angle(angle):
self._creg_dict[qb_id] = self._gen_bit_name(index)

if add:
self._output.append('qubit {};'.format(self._qreg_dict[qb_id]))
self._output.append('bit {};'.format(self._creg_dict[qb_id]))
self._output.append(f'qubit {self._qreg_dict[qb_id]};')
self._output.append(f'bit {self._creg_dict[qb_id]};')

elif gate == Deallocate:
qb_id = cmd.qubits[0][0].id
Expand All @@ -238,29 +238,25 @@ def _format_angle(angle):
assert len(cmd.qubits) == 1 and len(cmd.qubits[0]) == 1
qb_id = cmd.qubits[0][0].id

self._output.append('{} = measure {};'.format(self._creg_dict[qb_id], self._qreg_dict[qb_id]))
self._output.append(f'{self._creg_dict[qb_id]} = measure {self._qreg_dict[qb_id]};')

elif n_controls == 2:
targets = [self._qreg_dict[qb.id] for qureg in cmd.qubits for qb in qureg]
controls = [self._qreg_dict[qb.id] for qb in cmd.control_qubits]

try:
self._output.append('{} {};'.format(_ccontrolled_gates_func[gate], ','.join(controls + targets)))
self._output.append(f'{_ccontrolled_gates_func[gate]} {",".join(controls + targets)};')
except KeyError as err:
raise RuntimeError('Unable to perform {} gate with n=2 control qubits'.format(gate)) from err
raise RuntimeError(f'Unable to perform {gate} gate with n=2 control qubits') from err

elif n_controls == 1:
target_qureg = [self._qreg_dict[qb.id] for qureg in cmd.qubits for qb in qureg]

try:
if isinstance(gate, Ph):
self._output.append(
'{}{} {},{};'.format(
_controlled_gates_func[type(gate)],
_format_angle(-gate.angle / 2.0),
self._qreg_dict[cmd.control_qubits[0].id],
target_qureg[0],
)
f'{_controlled_gates_func[type(gate)]}{_format_angle(-gate.angle / 2.0)} '
f'{self._qreg_dict[cmd.control_qubits[0].id]},{target_qureg[0]};'
)
elif isinstance(
gate,
Expand All @@ -270,33 +266,27 @@ def _format_angle(angle):
),
):
self._output.append(
'{}{} {},{};'.format(
_controlled_gates_func[type(gate)],
_format_angle(gate.angle),
self._qreg_dict[cmd.control_qubits[0].id],
target_qureg[0],
)
f'{_controlled_gates_func[type(gate)]}{_format_angle(gate.angle)} '
f'{self._qreg_dict[cmd.control_qubits[0].id]},{target_qureg[0]};'
)
else:
self._output.append(
'{} {},{};'.format(
'{} {},{};'.format( # pylint: disable=consider-using-f-string
_controlled_gates_func[gate], self._qreg_dict[cmd.control_qubits[0].id], *target_qureg
)
)
except KeyError as err:
raise RuntimeError('Unable to perform {} gate with n=1 control qubits'.format(gate)) from err
raise RuntimeError(f'Unable to perform {gate} gate with n=1 control qubits') from err
else:
target_qureg = [self._qreg_dict[qb.id] for qureg in cmd.qubits for qb in qureg]
if isinstance(gate, Ph):
self._output.append(
'{}{} {};'.format(_gates_func[type(gate)], _format_angle(-gate.angle / 2.0), target_qureg[0])
)
self._output.append(f'{_gates_func[type(gate)]}{_format_angle(-gate.angle / 2.0)} {target_qureg[0]};')
elif isinstance(gate, (R, Rx, Ry, Rz)):
self._output.append(f'{_gates_func[type(gate)]}{_format_angle(gate.angle)} {target_qureg[0]};')
else:
self._output.append(
'{}{} {};'.format(_gates_func[type(gate)], _format_angle(gate.angle), target_qureg[0])
'{} {};'.format(_gates_func[gate], *target_qureg) # pylint: disable=consider-using-f-string
)
else:
self._output.append('{} {};'.format(_gates_func[gate], *target_qureg))

def _insert_openqasm_header(self):
self._output.append('OPENQASM 3;')
Expand All @@ -311,6 +301,6 @@ def _reset_after_flush(self):
self._output.clear()
self._insert_openqasm_header()
for qubit_name in self._qreg_dict.values():
self._output.append('qubit {};'.format(qubit_name))
self._output.append(f'qubit {qubit_name};')
for bit_name in self._creg_dict.values():
self._output.append('bit {};'.format(bit_name))
self._output.append(f'bit {bit_name};')
9 changes: 4 additions & 5 deletions projectq/backends/_qasm_test.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Copyright 2020 ProjectQ-Framework (www.projectq.ch)
#
# Licensed under the Apache License, Version 2.0 (the "License");
Expand Down Expand Up @@ -85,8 +84,8 @@ def test_qasm_allocate_deallocate(qubit_id_redux):
assert not backend._available_indices
qasm = '\n'.join(eng.backend.qasm)
for i in range(1, 6):
assert re.search(r'qubit\s+q{}'.format(i), qasm)
assert re.search(r'bit\s+c{}'.format(i), qasm)
assert re.search(fr'qubit\s+q{i}', qasm)
assert re.search(fr'bit\s+c{i}', qasm)

del qubit
eng.flush()
Expand Down Expand Up @@ -394,10 +393,10 @@ def _process(output):

def test_qasm_name_callback():
def _qubit(index):
return 'qubit_{}'.format(index)
return f'qubit_{index}'

def _bit(index):
return 'classical_bit_{}'.format(index)
return f'classical_bit_{index}'

eng = MainEngine(backend=OpenQASMBackend(qubit_callback=_qubit, bit_callback=_bit), engine_list=[])

Expand Down
14 changes: 4 additions & 10 deletions projectq/libs/qasm/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Copyright 2020 ProjectQ-Framework (www.projectq.ch)
#
# Licensed under the Apache License, Version 2.0 (the "License");
Expand All @@ -12,9 +11,8 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Contains functions/classes to handle OpenQASM
"""

"""Contains functions/classes to handle OpenQASM."""

try:
from ._parse_qasm_qiskit import read_qasm_file, read_qasm_str
Expand All @@ -28,15 +26,11 @@
)

def read_qasm_file(eng, filename):
"""
Dummy implementation
"""
"""Invalid implementation."""
# pylint: disable=unused-argument
raise RuntimeError(ERROR_MSG)

def read_qasm_str(eng, qasm_str):
"""
Dummy implementation
"""
"""Invalid implementation."""
# pylint: disable=unused-argument
raise RuntimeError(ERROR_MSG)
51 changes: 24 additions & 27 deletions projectq/libs/qasm/_parse_qasm_pyparsing.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Copyright 2020 ProjectQ-Framework (www.projectq.ch)
#
# Licensed under the Apache License, Version 2.0 (the "License");
Expand Down Expand Up @@ -96,7 +95,7 @@ def eval(self, _):

def __repr__(self): # pragma: nocover
"""Mainly for debugging."""
return 'QASMVersionOp({})'.format(self.version)
return f'QASMVersionOp({self.version})'


class IncludeOp:
Expand All @@ -121,11 +120,11 @@ def eval(self, _):
if self.fname in 'qelib1.inc, stdlib.inc':
pass
else: # pragma: nocover
raise RuntimeError('Invalid cannot read: {}! (unsupported)'.format(self.fname))
raise RuntimeError(f'Invalid cannot read: {self.fname}! (unsupported)')

def __repr__(self): # pragma: nocover
"""Mainly for debugging."""
return 'IncludeOp({})'.format(self.fname)
return f'IncludeOp({self.fname})'


# ==============================================================================
Expand Down Expand Up @@ -162,8 +161,8 @@ def eval(self, _):
def __repr__(self): # pragma: nocover
"""Mainly for debugging."""
if self.index is not None:
return 'Qubit({}[{}])'.format(self.name, self.index)
return 'Qubit({})'.format(self.name)
return f'Qubit({self.name}[{self.index}])'
return f'Qubit({self.name})'


# ==============================================================================
Expand Down Expand Up @@ -192,9 +191,9 @@ def __init__(self, type_t, nbits, name, init):
def __repr__(self): # pragma: nocover
"""Mainly for debugging."""
if self.init:
return "{}({}, {}, {}) = {}".format(self.__class__.__name__, self.type_t, self.nbits, self.name, self.init)
return f"{self.__class__.__name__}({self.type_t}, {self.nbits}, {self.name}) = {self.init}"

return "{}({}, {}, {})".format(self.__class__.__name__, self.type_t, self.nbits, self.name)
return f"{self.__class__.__name__}({self.type_t}, {self.nbits}, {self.name})"


# ------------------------------------------------------------------------------
Expand All @@ -215,7 +214,7 @@ def eval(self, eng):
if self.name not in _QISKIT_VARS:
_QISKIT_VARS[self.name] = eng.allocate_qureg(self.nbits)
else: # pragma: nocover
raise RuntimeError('Variable exist already: {}'.format(self.name))
raise RuntimeError(f'Variable exist already: {self.name}')


# ------------------------------------------------------------------------------
Expand All @@ -240,7 +239,7 @@ def eval(self, _):
if self.init: # pragma: nocover
init = parse_expr(self.init)

# The followings are OpenQASM 3.0
# The following are OpenQASM 3.0
if self.type_t in ('const', 'float', 'fixed', 'angle'): # pragma: nocover
_BITS_VARS[self.name] = float(init)
elif self.type_t in ('int', 'uint'): # pragma: nocover
Expand All @@ -252,7 +251,7 @@ def eval(self, _):
assert self.init is None
_BITS_VARS[self.name] = [False] * self.nbits
else: # pragma: nocover
raise RuntimeError('Variable exist already: {}'.format(self.name))
raise RuntimeError(f'Variable exist already: {self.name}')


# ==============================================================================
Expand Down Expand Up @@ -286,7 +285,7 @@ def eval(self, _):

def __repr__(self): # pragma: nocover
"""Mainly for debugging."""
return "GateDefOp({}, {}, {})\n\t{}".format(self.name, self.params, self.qparams, self.body)
return f"GateDefOp({self.name}, {self.params}, {self.qparams})\n\t{self.body}"


# ==============================================================================
Expand Down Expand Up @@ -323,8 +322,6 @@ def eval(self, eng):
# pylint: disable = pointless-statement, expression-not-assigned
# pylint: disable = global-statement

global _BITS_VARS

qubits = self.qubits.eval(eng)
if not isinstance(qubits, list):
Measure | qubits
Expand All @@ -345,7 +342,7 @@ def eval(self, eng):

def __repr__(self): # pragma: nocover
"""Mainly for debugging."""
return 'MeasureOp({}, {})'.format(self.qubits, self.bits)
return f'MeasureOp({self.qubits}, {self.bits})'


# ------------------------------------------------------------------------------
Expand Down Expand Up @@ -378,8 +375,8 @@ def eval(self, _):
def __repr__(self): # pragma: nocover
"""Mainly for debugging."""
if self.params:
return 'OpaqueOp({}, {})'.format(self.name, self.params)
return 'OpaqueOp({})'.format(self.name)
return f'OpaqueOp({self.name}, {self.params})'
return f'OpaqueOp({self.name})'


# ------------------------------------------------------------------------------
Expand All @@ -388,7 +385,7 @@ def __repr__(self): # pragma: nocover
class GateOp:
"""Gate applied to qubits operation."""

def __init__(self, s, loc, toks):
def __init__(self, string, loc, toks):
"""
Initialize a GateOp object.
Expand All @@ -401,7 +398,7 @@ def __init__(self, s, loc, toks):
self.params = []
self.qubits = [QubitProxy(qubit) for qubit in toks[1]]
else:
param_str = s[loc : s.find(';', loc)] # noqa: E203
param_str = string[loc : string.find(';', loc)] # noqa: E203
self.params = param_str[param_str.find('(') + 1 : param_str.rfind(')')].split(',') # noqa: E203
self.qubits = [QubitProxy(qubit) for qubit in toks[2]]

Expand Down Expand Up @@ -457,14 +454,14 @@ def eval(self, eng): # pylint: disable=too-many-branches
_BITS_VARS = bits_vars_bak
else: # pragma: nocover
if self.params:
gate_str = '{}({}) | {}'.format(self.name, self.params, self.qubits)
gate_str = f'{self.name}({self.params}) | {self.qubits}'
else:
gate_str = '{} | {}'.format(self.name, self.qubits)
raise RuntimeError('Unknown gate: {}'.format(gate_str))
gate_str = f'{self.name} | {self.qubits}'
raise RuntimeError(f'Unknown gate: {gate_str}')

def __repr__(self): # pragma: nocover
"""Mainly for debugging."""
return 'GateOp({}, {}, {})'.format(self.name, self.params, self.qubits)
return f'GateOp({self.name}, {self.params}, {self.qubits})'


# ==============================================================================
Expand Down Expand Up @@ -496,12 +493,12 @@ def eval(self, _):
value = parse_expr(self.value)
_BITS_VARS[self.var] = value
else:
raise RuntimeError('The variable {} is not defined!'.format(self.var))
raise RuntimeError(f'The variable {self.var} is not defined!')
return 0

def __repr__(self):
"""Mainly for debugging."""
return 'AssignOp({},{})'.format(self.var, self.value)
return f'AssignOp({self.var},{self.value})'


# ==============================================================================
Expand All @@ -520,7 +517,7 @@ def _parse_if_conditional(if_str):
level -= 1
if level == 0:
return if_str[start : start + idx] # noqa: E203
raise RuntimeError('Unbalanced parantheses in {}'.format(if_str)) # pragma: nocover
raise RuntimeError(f'Unbalanced parentheses in {if_str}') # pragma: nocover


class IfOp:
Expand Down Expand Up @@ -584,7 +581,7 @@ def eval(self, eng):

def __repr__(self): # pragma: nocover
"""Mainly for debugging."""
return "IfExpr({} {} {}) {{ {} }}".format(self.bit, self.binary_op, self.comp_expr, self.body)
return f"IfExpr({self.bit} {self.binary_op} {self.comp_expr}) {{ {self.body} }}"


# ==============================================================================
Expand Down
1 change: 0 additions & 1 deletion projectq/libs/qasm/_parse_qasm_pyparsing_test.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Copyright 2021 <Huawei Technologies Co., Ltd>
#
# Licensed under the Apache License, Version 2.0 (the "License");
Expand Down
Loading

0 comments on commit cd9b408

Please sign in to comment.