Skip to content

Commit

Permalink
Add blacken-docs and pyupgrade to pre-commit configuration (#441)
Browse files Browse the repository at this point in the history
* Add `blacken-docs` and `pyupgrade` to pre-commit configuration

* Apply new pre-commit hooks and fix related issues.

* Update CHANGELOG

* Fix unit tests failures

* Fix pre-commit failure

* Generalise the use of f-strings

* Fix IonQ tests

* Run `pyupgrade` before `isort` and `black`
  • Loading branch information
Takishima committed Jul 19, 2022
1 parent 8d9e465 commit 6bbda53
Show file tree
Hide file tree
Showing 240 changed files with 625 additions and 894 deletions.
14 changes: 13 additions & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -35,14 +35,19 @@ repos:
- id: end-of-file-fixer
- id: mixed-line-ending
- id: trailing-whitespace
- id: fix-encoding-pragma

# Changes tabs to spaces
- repo: https://github.com/Lucas-C/pre-commit-hooks
rev: v1.1.13
hooks:
- id: remove-tabs

- repo: https://github.com/asottile/pyupgrade
rev: v2.34.0
hooks:
- id: pyupgrade
args: [--py36-plus, --keep-mock]

- repo: https://github.com/PyCQA/isort
rev: 5.10.1
hooks:
Expand All @@ -57,6 +62,13 @@ repos:
# This is a slow hook, so only run this if --hook-stage manual is passed
stages: [manual]

- repo: https://github.com/asottile/blacken-docs
rev: v1.12.1
hooks:
- id: blacken-docs
args: [-S, -l, '120']
additional_dependencies: [black==22.3.0]

- repo: https://gitlab.com/PyCQA/flake8
rev: 3.9.2
hooks:
Expand Down
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

- Update `docker/setup-qemu-action` GitHub action to v2
- Fixed CentOS 7 configuration issue
- Added two new pre-commit hooks: `blacken-docs` and `pyupgrade`
- Remove deprecated `setup_requires` field in setup.cfg
- Fixed installation issue with newer versions of `setuptool-scm`and Python¨ 3.6

Expand Down
55 changes: 33 additions & 22 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,10 @@ Examples
.. code-block:: python
from projectq import MainEngine # import the main compiler engine
from projectq.ops import H, Measure # import the operations we want to perform (Hadamard and measurement)
from projectq.ops import (
H,
Measure,
) # import the operations we want to perform (Hadamard and measurement)
eng = MainEngine() # create a default compiler (the back-end is a simulator)
qubit = eng.allocate_qubit() # allocate a quantum register with 1 qubit
Expand All @@ -52,7 +55,7 @@ Examples
Measure | qubit # measure the qubit
eng.flush() # flush all gates (and execute measurements)
print("Measured {}".format(int(qubit))) # converting a qubit to int or bool gives access to the measurement result
print(f"Measured {int(qubit)}") # converting a qubit to int or bool gives access to the measurement result
ProjectQ features a lean syntax which is close to the mathematical notation used in quantum physics. For example, a rotation of a qubit around the x-axis is usually specified as:
Expand Down Expand Up @@ -80,9 +83,7 @@ Instead of simulating a quantum program, one can use our resource counter (as a
from projectq.ops import QFT
from projectq.setups import linear
compiler_engines = linear.get_engine_list(num_qubits=16,
one_qubit_gates='any',
two_qubit_gates=(CNOT, Swap))
compiler_engines = linear.get_engine_list(num_qubits=16, one_qubit_gates='any', two_qubit_gates=(CNOT, Swap))
resource_counter = ResourceCounter()
eng = MainEngine(backend=resource_counter, engine_list=compiler_engines)
qureg = eng.allocate_qureg(16)
Expand Down Expand Up @@ -112,12 +113,13 @@ To run a program on the IBM Quantum Experience chips, all one has to do is choos
import projectq.setups.ibm
from projectq.backends import IBMBackend
token='MY_TOKEN'
device='ibmq_16_melbourne'
compiler_engines = projectq.setups.ibm.get_engine_list(token=token,device=device)
eng = MainEngine(IBMBackend(token=token, use_hardware=True, num_runs=1024,
verbose=False, device=device),
engine_list=compiler_engines)
token = 'MY_TOKEN'
device = 'ibmq_16_melbourne'
compiler_engines = projectq.setups.ibm.get_engine_list(token=token, device=device)
eng = MainEngine(
IBMBackend(token=token, use_hardware=True, num_runs=1024, verbose=False, device=device),
engine_list=compiler_engines,
)
**Running a quantum program on AQT devices**
Expand All @@ -129,12 +131,13 @@ To run a program on the AQT trapped ion quantum computer, choose the `AQTBackend
import projectq.setups.aqt
from projectq.backends import AQTBackend
token='MY_TOKEN'
device='aqt_device'
compiler_engines = projectq.setups.aqt.get_engine_list(token=token,device=device)
eng = MainEngine(AQTBackend(token=token,use_hardware=True, num_runs=1024,
verbose=False, device=device),
engine_list=compiler_engines)
token = 'MY_TOKEN'
device = 'aqt_device'
compiler_engines = projectq.setups.aqt.get_engine_list(token=token, device=device)
eng = MainEngine(
AQTBackend(token=token, use_hardware=True, num_runs=1024, verbose=False, device=device),
engine_list=compiler_engines,
)
**Running a quantum program on a AWS Braket provided device**
Expand All @@ -150,13 +153,21 @@ IonQ from IonQ and the state vector simulator SV1:
creds = {
'AWS_ACCESS_KEY_ID': 'your_aws_access_key_id',
'AWS_SECRET_KEY': 'your_aws_secret_key',
}
}
s3_folder = ['S3Bucket', 'S3Directory']
device='IonQ'
eng = MainEngine(AWSBraketBackend(use_hardware=True, credentials=creds, s3_folder=s3_folder,
num_runs=1024, verbose=False, device=device),
engine_list=[])
device = 'IonQ'
eng = MainEngine(
AWSBraketBackend(
use_hardware=True,
credentials=creds,
s3_folder=s3_folder,
num_runs=1024,
verbose=False,
device=device,
),
engine_list=[],
)
.. note::
Expand Down
6 changes: 3 additions & 3 deletions docs/conf.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# projectq documentation build configuration file, created by
# sphinx-quickstart on Tue Nov 29 11:51:46 2016.
Expand Down Expand Up @@ -533,6 +532,7 @@ def linkcode_resolve(domain, info):
import projectq.setups.ibm as ibm_setup
from projectq import MainEngine
eng = MainEngine(engine_list=ibm_setup.get_engine_list())
# eng uses the default Simulator backend
Expand Down Expand Up @@ -560,10 +560,10 @@ def linkcode_resolve(domain, info):
os.mkdir(docgen_path)

for desc in descriptions:
fname = os.path.join(docgen_path, 'projectq.{}.rst'.format(desc.name))
fname = os.path.join(docgen_path, f'projectq.{desc.name}.rst')
lines = None
if os.path.exists(fname):
with open(fname, 'r') as fd:
with open(fname) as fd:
lines = [line[:-1] for line in fd.readlines()]

new_lines = desc.get_ReST()
Expand Down
25 changes: 12 additions & 13 deletions docs/package_description.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Copyright 2017 ProjectQ-Framework (www.projectq.ch)
#
# Licensed under the Apache License, Version 2.0 (the "License");
Expand Down Expand Up @@ -52,7 +51,7 @@ def __init__( # pylint: disable=too-many-arguments
if pkg_name not in PackageDescription.package_list:
PackageDescription.package_list.append(pkg_name)

self.module = importlib.import_module('projectq.{}'.format(self.name))
self.module = importlib.import_module(f'projectq.{self.name}')
self.module_special_members = module_special_members

self.submodule_special_members = submodule_special_members
Expand All @@ -72,7 +71,7 @@ def __init__( # pylint: disable=too-many-arguments
self.subpackages = []
self.submodules = []
for name, obj in sub:
if '{}.{}'.format(self.name, name) in PackageDescription.package_list:
if f'{self.name}.{name}' in PackageDescription.package_list:
self.subpackages.append((name, obj))
else:
self.submodules.append((name, obj))
Expand Down Expand Up @@ -115,19 +114,19 @@ def get_ReST(self): # pylint: disable=invalid-name,too-many-branches,too-many-s
new_lines.append(' :maxdepth: 1')
new_lines.append('')
for name, _ in self.subpackages:
new_lines.append(' projectq.{}.{}'.format(self.name, name))
new_lines.append(f' projectq.{self.name}.{name}')
new_lines.append('')
else:
submodule_has_index = True
new_lines.append('.. autosummary::')
new_lines.append('')
if self.submodules:
for name, _ in self.submodules:
new_lines.append('\tprojectq.{}.{}'.format(self.name, name))
new_lines.append(f'\tprojectq.{self.name}.{name}')
new_lines.append('')
if self.members:
for name, _ in self.members:
new_lines.append('\tprojectq.{}.{}'.format(self.name, name))
new_lines.append(f'\tprojectq.{self.name}.{name}')
new_lines.append('')

if self.submodules:
Expand All @@ -142,27 +141,27 @@ def get_ReST(self): # pylint: disable=invalid-name,too-many-branches,too-many-s
new_lines.append('.. autosummary::')
new_lines.append('')
for name, _ in self.submodules:
new_lines.append(' projectq.{}.{}'.format(self.name, name))
new_lines.append(f' projectq.{self.name}.{name}')
new_lines.append('')

for name, _ in self.submodules:
new_lines.append(name)
new_lines.append('^' * len(new_lines[-1]))
new_lines.append('')
new_lines.append('.. automodule:: projectq.{}.{}'.format(self.name, name))
new_lines.append(f'.. automodule:: projectq.{self.name}.{name}')
new_lines.append(' :members:')
if self.submodule_special_members:
new_lines.append(' :special-members: {}'.format(self.submodule_special_members))
new_lines.append(f' :special-members: {self.submodule_special_members}')
new_lines.append(' :undoc-members:')
new_lines.append('')

new_lines.append('Module contents')
new_lines.append('-' * len(new_lines[-1]))
new_lines.append('')
new_lines.append('.. automodule:: projectq.{}'.format(self.name))
new_lines.append(f'.. automodule:: projectq.{self.name}')
new_lines.append(' :members:')
new_lines.append(' :undoc-members:')
new_lines.append(' :special-members: {}'.format(self.module_special_members))
new_lines.append(f' :special-members: {self.module_special_members}')
new_lines.append(' :imported-members:')
new_lines.append('')

Expand All @@ -174,9 +173,9 @@ def get_ReST(self): # pylint: disable=invalid-name,too-many-branches,too-many-s
new_lines.append(title)
new_lines.append('^' * len(title))
new_lines.append('')
new_lines.append('.. automodule:: projectq.{}.{}'.format(self.name, name))
new_lines.append(f'.. automodule:: projectq.{self.name}.{name}')
for param in params:
new_lines.append(' {}'.format(param))
new_lines.append(f' {param}')
new_lines.append('')

return new_lines[:-1]
7 changes: 5 additions & 2 deletions docs/tutorials.rst
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,10 @@ To check out the ProjectQ syntax in action and to see whether the installation w
.. code-block:: python
from projectq import MainEngine # import the main compiler engine
from projectq.ops import H, Measure # import the operations we want to perform (Hadamard and measurement)
from projectq.ops import (
H,
Measure,
) # import the operations we want to perform (Hadamard and measurement)
eng = MainEngine() # create a default compiler (the back-end is a simulator)
qubit = eng.allocate_qubit() # allocate 1 qubit
Expand All @@ -248,6 +251,6 @@ To check out the ProjectQ syntax in action and to see whether the installation w
Measure | qubit # measure the qubit
eng.flush() # flush all gates (and execute measurements)
print("Measured {}".format(int(qubit))) # output measurement result
print(f"Measured {int(qubit)}") # output measurement result
Which creates random bits (0 or 1).
3 changes: 1 addition & 2 deletions examples/aqt.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# pylint: skip-file

"""Example of running a quantum circuit using the AQT APIs."""
Expand Down Expand Up @@ -40,7 +39,7 @@ def run_entangle(eng, num_qubits=3):
# access the probabilities via the back-end:
# results = eng.backend.get_probabilities(qureg)
# for state in results:
# print("Measured {} with p = {}.".format(state, results[state]))
# print(f"Measured {state} with p = {results[state]}.")
# or plot them directly:
histogram(eng.backend, qureg)
plt.show()
Expand Down
1 change: 0 additions & 1 deletion examples/bellpair_circuit.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# pylint: skip-file

"""Example implementation of a quantum circuit generating a Bell pair state."""
Expand Down
1 change: 0 additions & 1 deletion examples/control_tester.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Copyright 2021 ProjectQ-Framework (www.projectq.ch)
#
# Licensed under the Apache License, Version 2.0 (the "License");
Expand Down
7 changes: 3 additions & 4 deletions examples/gate_zoo.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# pylint: skip-file

"""Showcase most of the quantum gates available in ProjectQ."""
Expand Down Expand Up @@ -95,12 +94,12 @@ def add(x, y):
# generate latex code to draw the circuit
s = drawing_engine.get_latex()
prefix = 'zoo'
with open('{}.tex'.format(prefix), 'w') as f:
with open(f'{prefix}.tex', 'w') as f:
f.write(s)

# compile latex source code and open pdf file
os.system('pdflatex {}.tex'.format(prefix))
openfile('{}.pdf'.format(prefix))
os.system(f'pdflatex {prefix}.tex')
openfile(f'{prefix}.pdf')


def openfile(filename):
Expand Down
1 change: 0 additions & 1 deletion examples/grover.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# pylint: skip-file

"""Example implementation of Grover's algorithm."""
Expand Down
3 changes: 1 addition & 2 deletions examples/hws4.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# pylint: skip-file

"""Example of a 4-qubit phase function."""
Expand Down Expand Up @@ -30,4 +29,4 @@ def f(a, b, c, d):

eng.flush()

print("Shift is {}".format(8 * int(x4) + 4 * int(x3) + 2 * int(x2) + int(x1)))
print(f"Shift is {8 * int(x4) + 4 * int(x3) + 2 * int(x2) + int(x1)}")
3 changes: 1 addition & 2 deletions examples/hws6.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# pylint: skip-file

"""Example of a 6-qubit phase function."""
Expand Down Expand Up @@ -44,4 +43,4 @@ def f(a, b, c, d, e, f):
All(Measure) | qubits

# measurement result
print("Shift is {}".format(sum(int(q) << i for i, q in enumerate(qubits))))
print(f"Shift is {sum(int(q) << i for i, q in enumerate(qubits))}")
3 changes: 1 addition & 2 deletions examples/ibm.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# pylint: skip-file

"""Example of running a quantum circuit using the IBM QE APIs."""
Expand Down Expand Up @@ -40,7 +39,7 @@ def run_entangle(eng, num_qubits=3):
# access the probabilities via the back-end:
# results = eng.backend.get_probabilities(qureg)
# for state in results:
# print("Measured {} with p = {}.".format(state, results[state]))
# print(f"Measured {state} with p = {results[state]}.")
# or plot them directly:
histogram(eng.backend, qureg)
plt.show()
Expand Down
2 changes: 1 addition & 1 deletion examples/ibmq_tutorial.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@
" # access the probabilities via the back-end:\n",
" # results = eng.backend.get_probabilities(qureg)\n",
" # for state in results:\n",
" # print(\"Measured {} with p = {}.\".format(state, results[state]))\n",
" # print(f\"Measured {state} with p = {results[state]}.\")\n",
" # or plot them directly:\n",
" histogram(eng.backend, qureg)\n",
" plt.show()\n",
Expand Down
3 changes: 1 addition & 2 deletions examples/ionq.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Copyright 2021 ProjectQ-Framework (www.projectq.ch)
#
# Licensed under the Apache License, Version 2.0 (the "License");
Expand Down Expand Up @@ -53,7 +52,7 @@ def run_entangle(eng, num_qubits=3):
# access the probabilities via the back-end:
# results = eng.backend.get_probabilities(qureg)
# for state in results:
# print("Measured {} with p = {}.".format(state, results[state]))
# print(f"Measured {state} with p = {results[state]}.")
# or plot them directly:
histogram(eng.backend, qureg)
plt.show()
Expand Down

0 comments on commit 6bbda53

Please sign in to comment.