diff --git a/benchmarks/scripts/benchmark_clifford_circuit.py b/benchmarks/scripts/benchmark_clifford_circuit.py index 643eff790..2ce8c1f7e 100644 --- a/benchmarks/scripts/benchmark_clifford_circuit.py +++ b/benchmarks/scripts/benchmark_clifford_circuit.py @@ -23,15 +23,17 @@ from tensorflow_quantum.core.ops import tfq_simulate_ops from tensorflow_quantum.core.serialize.serializer import serialize_circuit -from models.random_clifford_circuit import random_clifford_circuit -import flags -import benchmark_util +from benchmarks.scripts.models.random_clifford_circuit import ( + random_clifford_circuit) + +from benchmarks.scripts import flags +from benchmarks.scripts import benchmark_util SEED = 48510234 SRC = os.path.dirname(os.path.realpath(__file__)) os.environ['TEST_REPORT_FILE_PREFIX'] = os.path.join(SRC, 'reports/') -TEST_PARAMS_1 = flags.TEST_FLAGS(n_qubits=3, n_moments=5, op_density=0.99) -TEST_PARAMS_2 = flags.TEST_FLAGS(n_qubits=4, n_moments=5, op_density=0.99) +TEST_PARAMS_1 = flags.test_flags(n_qubits=3, n_moments=5, op_density=0.99) +TEST_PARAMS_2 = flags.test_flags(n_qubits=4, n_moments=5, op_density=0.99) ALL_PARAMS = [TEST_PARAMS_1, TEST_PARAMS_2] @@ -42,12 +44,11 @@ class CliffordBenchmarksTest(tf.test.TestCase, parameterized.TestCase): ("params_1", TEST_PARAMS_1), ("params_2", TEST_PARAMS_2), ) - def testBenchmarkCliffordCircuitEager(self, params): + def test_benchmark_clifford_circuit_eager(self, params): """Test that Op constructs and runs correctly.""" proto_file_path = os.path.join( - SRC, "reports/", - "CliffordBenchmarks.benchmark_clifford_circuit_{}_{}_{}".format( - params.n_qubits, params.n_moments, params.batch_size)) + SRC, "reports/", f"CliffordBenchmarks.benchmark_clifford_circuit_" + f"{params.n_qubits}_{params.n_moments}_{params.batch_size}") self.addCleanup(os.remove, proto_file_path) bench = CliffordBenchmarks(params=params) @@ -55,9 +56,8 @@ def testBenchmarkCliffordCircuitEager(self, params): res = benchmark_util.read_benchmark_entry(proto_file_path) self.assertEqual( - res.name, - "CliffordBenchmarks.benchmark_clifford_circuit_{}_{}_{}".format( - params.n_qubits, params.n_moments, params.batch_size)) + res.name, f"CliffordBenchmarks.benchmark_clifford_circuit_" + f"{params.n_qubits}_{params.n_moments}_{params.batch_size}") self.assertEqual( res.extras.get("n_qubits").double_value, params.n_qubits) self.assertEqual( @@ -77,7 +77,7 @@ class CliffordBenchmarks(tf.test.Benchmark): def __init__(self, params=None): """Pull in command line flags or use provided flags.""" - super(CliffordBenchmarks, self).__init__() + super().__init__() # Allow input params for testing purposes. self.params = params if params else flags.FLAGS @@ -113,11 +113,11 @@ def benchmark_clifford_circuit_eager(self): 'batch_size': self.params.batch_size, "min_time": min(deltas), } - name = "benchmark_clifford_circuit_{}_{}_{}".format( - self.params.n_qubits, self.params.n_moments, self.params.batch_size) + name = (f"benchmark_clifford_circuit_{self.params.n_qubits}_" + f"{self.params.n_moments}_{self.params.batch_size}") full_path = os.path.join(os.environ['TEST_REPORT_FILE_PREFIX'], - "{}.{}".format(self.__class__.__name__, name)) + f"{self.__class__.__name__}.{name}") if os.path.exists(full_path): os.remove(full_path) diff --git a/benchmarks/scripts/benchmark_op_gradients.py b/benchmarks/scripts/benchmark_op_gradients.py index 89b04cfd1..d90d57c83 100644 --- a/benchmarks/scripts/benchmark_op_gradients.py +++ b/benchmarks/scripts/benchmark_op_gradients.py @@ -23,8 +23,6 @@ import numpy as np from tensorflow_quantum.core.ops import tfq_simulate_ops -import benchmark_util -import flags from tensorflow_quantum.python import util from tensorflow_quantum.python.differentiators import ( @@ -32,13 +30,16 @@ parameter_shift, ) +from benchmarks.scripts import benchmark_util +from benchmarks.scripts import flags + SRC = os.path.dirname(os.path.realpath(__file__)) os.environ['TEST_REPORT_FILE_PREFIX'] = os.path.join(SRC, 'reports/') -TEST_PARAMS_1 = flags.TEST_FLAGS(n_symbols=4, +TEST_PARAMS_1 = flags.test_flags(n_symbols=4, n_qubits=3, n_moments=5, op_density=0.9) -TEST_PARAMS_2 = flags.TEST_FLAGS(n_symbols=3, +TEST_PARAMS_2 = flags.test_flags(n_symbols=3, n_qubits=4, n_moments=5, op_density=0.6) @@ -58,13 +59,14 @@ class GradientBenchmarksTest(tf.test.TestCase, parameterized.TestCase): ], 'params': [TEST_PARAMS_1, TEST_PARAMS_2] }))) - def testBenchmarkGradient(self, diff, params): + def test_benchmark_gradient(self, diff, params): """Test that op constructs and runs correctly.""" - bench_name = "GradientBenchmarks.{}_{}_{}_{}_{}".format( - diff.__class__.__name__, params.n_qubits, params.n_moments, - params.batch_size, params.n_symbols) - proto_file_path = os.path.join(SRC, "reports/", "{}".format(bench_name)) + bench_name = ( + f"GradientBenchmarks.{diff.__class__.__name__}_" + f"{params.n_qubits}_{params.n_moments}_{params.batch_size}_" + f"{params.n_symbols}") + proto_file_path = os.path.join(SRC, "reports/", bench_name) self.addCleanup(os.remove, proto_file_path) bench = GradientBenchmarks(params=params) @@ -93,7 +95,7 @@ class GradientBenchmarks(tf.test.Benchmark): def __init__(self, params=None): """Pull in command line flags or use provided flags.""" - super(GradientBenchmarks, self).__init__() + super().__init__() self.params = params if params else flags.FLAGS self.setup() @@ -110,7 +112,8 @@ def setup(self): replace=True))) symbol_names = list(symbol_names) - circuit_batch, resolver_batch = util.random_symbol_circuit_resolver_batch( + circuit_batch, resolver_batch = \ + util.random_symbol_circuit_resolver_batch( qubits=qubits, symbols=symbol_names, batch_size=self.params.batch_size, @@ -151,12 +154,11 @@ def _benchmark_tfq_differentiator(self, differentiator, params): deltas[i] = time.perf_counter() - start # Name benchmark logs by differentiator classname. - name = "{}_{}_{}_{}_{}".format(differentiator.__class__.__name__, - params.n_qubits, params.n_moments, - params.batch_size, params.n_symbols) + name = (f"{differentiator.__class__.__name__}_{params.n_qubits}_" + f"{params.n_moments}_{params.batch_size}_{params.n_symbols}") full_path = os.path.join(os.environ['TEST_REPORT_FILE_PREFIX'], - "{}.{}".format(self.__class__.__name__, name)) + f"{self.__class__.__name__}.{name}") if os.path.exists(full_path): os.remove(full_path) diff --git a/benchmarks/scripts/benchmark_random_circuit.py b/benchmarks/scripts/benchmark_random_circuit.py index 51d4ccfbf..d696d01d5 100644 --- a/benchmarks/scripts/benchmark_random_circuit.py +++ b/benchmarks/scripts/benchmark_random_circuit.py @@ -23,14 +23,14 @@ from tensorflow_quantum.core.ops import tfq_simulate_ops from tensorflow_quantum.core.serialize.serializer import serialize_circuit -import flags -import benchmark_util +from benchmarks.scripts import flags +from benchmarks.scripts import benchmark_util SEED = 63536323 SRC = os.path.dirname(os.path.realpath(__file__)) os.environ['TEST_REPORT_FILE_PREFIX'] = os.path.join(SRC, 'reports/') -TEST_PARAMS_1 = flags.TEST_FLAGS(n_rows=3, n_cols=5, n_moments=5) -TEST_PARAMS_2 = flags.TEST_FLAGS(n_rows=4, n_cols=4, n_moments=20) +TEST_PARAMS_1 = flags.test_flags(n_rows=3, n_cols=5, n_moments=5) +TEST_PARAMS_2 = flags.test_flags(n_rows=4, n_cols=4, n_moments=20) def make_random_circuit(n_rows, n_cols, depth): @@ -49,12 +49,12 @@ class RandomCircuitBenchmarksTest(tf.test.TestCase, parameterized.TestCase): ("params_1", TEST_PARAMS_1), ("params_2", TEST_PARAMS_2), ) - def testBenchmarkRandomCircuit(self, params): + def test_benchmark_random_circuit(self, params): """Test that Op constructs and runs correctly.""" proto_file_path = os.path.join( SRC, "reports/", - "RandomCircuitBenchmarks.benchmark_random_circuit_{}_{}_{}".format( - params.n_rows, params.n_cols, params.n_moments)) + f"RandomCircuitBenchmarks.benchmark_random_circuit_" + f"{params.n_rows}_{params.n_cols}_{params.n_moments}") self.addCleanup(os.remove, proto_file_path) bench = RandomCircuitBenchmarks(params=params) @@ -62,9 +62,8 @@ def testBenchmarkRandomCircuit(self, params): res = benchmark_util.read_benchmark_entry(proto_file_path) self.assertEqual( - res.name, - "RandomCircuitBenchmarks.benchmark_random_circuit_{}_{}_{}".format( - params.n_rows, params.n_cols, params.n_moments)) + res.name, f"RandomCircuitBenchmarks.benchmark_random_circuit_" + f"{params.n_rows}_{params.n_cols}_{params.n_moments}") self.assertEqual(res.extras.get("n_rows").double_value, params.n_rows) self.assertEqual(res.extras.get("n_cols").double_value, params.n_cols) self.assertEqual( @@ -77,7 +76,7 @@ def testBenchmarkRandomCircuit(self, params): ("params_1", TEST_PARAMS_1), ("params_2", TEST_PARAMS_2), ) - def testRandomCircuitParams(self, params): + def test_random_circuit_params(self, params): """Ensure that the random circuits are structured as advertised.""" circuit = make_random_circuit(params.n_rows, params.n_cols, params.n_moments) @@ -95,7 +94,7 @@ class RandomCircuitBenchmarks(tf.test.Benchmark): def __init__(self, params=None): """Pull in command line flags or use provided flags.""" - super(RandomCircuitBenchmarks, self).__init__() + super().__init__() # Allow input params for testing purposes. self.params = params if params else flags.FLAGS @@ -106,7 +105,8 @@ def _simulate_circuit(self, circuit, params): [[0]] * params.batch_size) def benchmark_random_circuit(self): - """Benchmark simulator performance on a classically intractable circuit.""" + """Benchmark simulator performance on + a classically intractable circuit.""" circuit = make_random_circuit(self.params.n_rows, self.params.n_cols, self.params.n_moments) @@ -128,10 +128,10 @@ def benchmark_random_circuit(self): "min_time": min(deltas), } - name = "benchmark_random_circuit_{}_{}_{}".format( - self.params.n_rows, self.params.n_cols, self.params.n_moments) + name = (f"benchmark_random_circuit_{self.params.n_rows}_" + f"{self.params.n_cols}_{self.params.n_moments}") full_path = os.path.join(os.environ['TEST_REPORT_FILE_PREFIX'], - "{}.{}".format(self.__class__.__name__, name)) + f"{self.__class__.__name__}.{name}") if os.path.exists(full_path): os.remove(full_path) diff --git a/benchmarks/scripts/benchmark_util.py b/benchmarks/scripts/benchmark_util.py index 5b4bea2e5..776ad326e 100644 --- a/benchmarks/scripts/benchmark_util.py +++ b/benchmarks/scripts/benchmark_util.py @@ -14,10 +14,18 @@ # ============================================================================== """Utility functions for benchmark tools.""" import tensorflow as tf -import test_log_pb2 +from tensorflow.core.util import test_log_pb2 def read_benchmark_entry(f): + """Reads a benchmark entry from a file. + + Args: + f: File path to read from. + + Returns: + The first entry in the benchmark file. + """ s = tf.io.gfile.GFile(f, "rb").read() entries = test_log_pb2.BenchmarkEntries.FromString(s) return entries.entry[0] diff --git a/benchmarks/scripts/benchmark_util_test.py b/benchmarks/scripts/benchmark_util_test.py index bece69897..7acdbf9cf 100644 --- a/benchmarks/scripts/benchmark_util_test.py +++ b/benchmarks/scripts/benchmark_util_test.py @@ -18,8 +18,8 @@ import tensorflow as tf -import test_log_pb2 -import benchmark_util +from tensorflow.core.util import test_log_pb2 +from benchmarks.scripts import benchmark_util def _make_dummy_benchmark_report(): diff --git a/benchmarks/scripts/flags.py b/benchmarks/scripts/flags.py index eaf7e78e2..254ff6b38 100644 --- a/benchmarks/scripts/flags.py +++ b/benchmarks/scripts/flags.py @@ -84,7 +84,7 @@ lower_bound=0) -def TEST_FLAGS(**kwargs): +def test_flags(**kwargs): """Create a set of test flags by kwarg assignment. This constructs a named tuple that mimics the interface of absl.flags. diff --git a/benchmarks/scripts/models/random_clifford_circuit.py b/benchmarks/scripts/models/random_clifford_circuit.py index a08a667b5..abb7eb8e9 100644 --- a/benchmarks/scripts/models/random_clifford_circuit.py +++ b/benchmarks/scripts/models/random_clifford_circuit.py @@ -12,6 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== +"""Module for generating random Clifford circuits.""" from typing import Iterable diff --git a/benchmarks/scripts/models/random_clifford_circuit_test.py b/benchmarks/scripts/models/random_clifford_circuit_test.py index c6d968ea0..ecd5ebd08 100644 --- a/benchmarks/scripts/models/random_clifford_circuit_test.py +++ b/benchmarks/scripts/models/random_clifford_circuit_test.py @@ -12,13 +12,15 @@ # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== +"""Tests for the random Clifford circuit generator.""" from absl.testing import parameterized import cirq import numpy as np import tensorflow as tf -from random_clifford_circuit import random_clifford_circuit +from benchmarks.scripts.models.random_clifford_circuit import ( + random_clifford_circuit) class RandomCliffordCircuitTest(parameterized.TestCase, tf.test.TestCase): diff --git a/docs/tutorials/hello_many_worlds.ipynb b/docs/tutorials/hello_many_worlds.ipynb index 5530596eb..7c1779695 100644 --- a/docs/tutorials/hello_many_worlds.ipynb +++ b/docs/tutorials/hello_many_worlds.ipynb @@ -17,10 +17,7 @@ "cellView": "form", "colab": {}, "colab_type": "code", - "id": "iiQkM5ZgQ8r2", - "vscode": { - "languageId": "python" - } + "id": "iiQkM5ZgQ8r2" }, "outputs": [], "source": [ @@ -141,10 +138,7 @@ "metadata": { "colab": {}, "colab_type": "code", - "id": "enZ300Bflq80", - "vscode": { - "languageId": "python" - } + "id": "enZ300Bflq80" }, "outputs": [], "source": [ @@ -191,10 +185,7 @@ "metadata": { "colab": {}, "colab_type": "code", - "id": "2yQdmhQLCrzQ", - "vscode": { - "languageId": "python" - } + "id": "2yQdmhQLCrzQ" }, "outputs": [], "source": [ @@ -217,10 +208,7 @@ "metadata": { "colab": {}, "colab_type": "code", - "id": "Ps-pd2mndXs7", - "vscode": { - "languageId": "python" - } + "id": "Ps-pd2mndXs7" }, "outputs": [], "source": [ @@ -249,10 +237,7 @@ "metadata": { "colab": {}, "colab_type": "code", - "id": "VMq7EayNRyQb", - "vscode": { - "languageId": "python" - } + "id": "VMq7EayNRyQb" }, "outputs": [], "source": [ @@ -280,10 +265,7 @@ "colab": {}, "colab_type": "code", "id": "hrSnOCi3ehr_", - "scrolled": true, - "vscode": { - "languageId": "python" - } + "scrolled": true }, "outputs": [], "source": [ @@ -300,10 +282,7 @@ "metadata": { "colab": {}, "colab_type": "code", - "id": "OZ0lWFXv6pII", - "vscode": { - "languageId": "python" - } + "id": "OZ0lWFXv6pII" }, "outputs": [], "source": [ @@ -331,10 +310,7 @@ "colab": {}, "colab_type": "code", "id": "1gLQjA02mIyy", - "scrolled": true, - "vscode": { - "languageId": "python" - } + "scrolled": true }, "outputs": [], "source": [ @@ -361,10 +337,7 @@ "metadata": { "colab": {}, "colab_type": "code", - "id": "aX_vEmCKmpQS", - "vscode": { - "languageId": "python" - } + "id": "aX_vEmCKmpQS" }, "outputs": [], "source": [ @@ -395,10 +368,7 @@ "metadata": { "colab": {}, "colab_type": "code", - "id": "1fsVZhF5lIXp", - "vscode": { - "languageId": "python" - } + "id": "1fsVZhF5lIXp" }, "outputs": [], "source": [ @@ -421,10 +391,7 @@ "metadata": { "colab": {}, "colab_type": "code", - "id": "RsfF53UCJtr9", - "vscode": { - "languageId": "python" - } + "id": "RsfF53UCJtr9" }, "outputs": [], "source": [ @@ -442,7 +409,7 @@ " }).real\n", " ])\n", "\n", - "print('cirq batch results: \\n {}'.format(np.array(cirq_results)))" + "print(f'cirq batch results: \\n {np.array(cirq_results)}')" ] }, { @@ -461,10 +428,7 @@ "metadata": { "colab": {}, "colab_type": "code", - "id": "kGZVdcZ6y9lC", - "vscode": { - "languageId": "python" - } + "id": "kGZVdcZ6y9lC" }, "outputs": [], "source": [ @@ -522,10 +486,7 @@ "metadata": { "colab": {}, "colab_type": "code", - "id": "N-j7SCl-51-q", - "vscode": { - "languageId": "python" - } + "id": "N-j7SCl-51-q" }, "outputs": [], "source": [ @@ -560,10 +521,7 @@ "metadata": { "colab": {}, "colab_type": "code", - "id": "1v4CK2jD6pIj", - "vscode": { - "languageId": "python" - } + "id": "1v4CK2jD6pIj" }, "outputs": [], "source": [ @@ -591,10 +549,7 @@ "metadata": { "colab": {}, "colab_type": "code", - "id": "kZbYRTe16pIm", - "vscode": { - "languageId": "python" - } + "id": "kZbYRTe16pIm" }, "outputs": [], "source": [ @@ -631,10 +586,7 @@ "metadata": { "colab": {}, "colab_type": "code", - "id": "UfHF8NNE6pIr", - "vscode": { - "languageId": "python" - } + "id": "UfHF8NNE6pIr" }, "outputs": [], "source": [ @@ -667,10 +619,7 @@ "metadata": { "colab": {}, "colab_type": "code", - "id": "Zvt2YGmZ6pIu", - "vscode": { - "languageId": "python" - } + "id": "Zvt2YGmZ6pIu" }, "outputs": [], "source": [ @@ -700,10 +649,7 @@ "metadata": { "colab": {}, "colab_type": "code", - "id": "Xs6EMhah6pIz", - "vscode": { - "languageId": "python" - } + "id": "Xs6EMhah6pIz" }, "outputs": [], "source": [ @@ -731,10 +677,7 @@ "metadata": { "colab": {}, "colab_type": "code", - "id": "ERXNPe4F6pI4", - "vscode": { - "languageId": "python" - } + "id": "ERXNPe4F6pI4" }, "outputs": [], "source": [ @@ -777,10 +720,7 @@ "metadata": { "colab": {}, "colab_type": "code", - "id": "ciMIJAuH6pJA", - "vscode": { - "languageId": "python" - } + "id": "ciMIJAuH6pJA" }, "outputs": [], "source": [ @@ -820,10 +760,7 @@ "metadata": { "colab": {}, "colab_type": "code", - "id": "_VYfzHffWo7n", - "vscode": { - "languageId": "python" - } + "id": "_VYfzHffWo7n" }, "outputs": [], "source": [ @@ -852,10 +789,7 @@ "metadata": { "colab": {}, "colab_type": "code", - "id": "6nk2Yr3e6pJJ", - "vscode": { - "languageId": "python" - } + "id": "6nk2Yr3e6pJJ" }, "outputs": [], "source": [ @@ -888,10 +822,7 @@ "metadata": { "colab": {}, "colab_type": "code", - "id": "Lwphqvs96pJO", - "vscode": { - "languageId": "python" - } + "id": "Lwphqvs96pJO" }, "outputs": [], "source": [ @@ -914,10 +845,7 @@ "metadata": { "colab": {}, "colab_type": "code", - "id": "dtPYqbNi8zeZ", - "vscode": { - "languageId": "python" - } + "id": "dtPYqbNi8zeZ" }, "outputs": [], "source": [ @@ -936,10 +864,7 @@ "metadata": { "colab": {}, "colab_type": "code", - "id": "azE-qV0OaC1o", - "vscode": { - "languageId": "python" - } + "id": "azE-qV0OaC1o" }, "outputs": [], "source": [ @@ -977,10 +902,7 @@ "metadata": { "colab": {}, "colab_type": "code", - "id": "RoIlb7r7j5SY", - "vscode": { - "languageId": "python" - } + "id": "RoIlb7r7j5SY" }, "outputs": [], "source": [ @@ -1026,10 +948,7 @@ "metadata": { "colab": {}, "colab_type": "code", - "id": "aYskLTacs8Ku", - "vscode": { - "languageId": "python" - } + "id": "aYskLTacs8Ku" }, "outputs": [], "source": [ @@ -1070,10 +989,7 @@ "metadata": { "colab": {}, "colab_type": "code", - "id": "hta0G3Nc6pJY", - "vscode": { - "languageId": "python" - } + "id": "hta0G3Nc6pJY" }, "outputs": [], "source": [ @@ -1107,10 +1023,7 @@ "metadata": { "colab": {}, "colab_type": "code", - "id": "n_aTG4g3-y0F", - "vscode": { - "languageId": "python" - } + "id": "n_aTG4g3-y0F" }, "outputs": [], "source": [ @@ -1136,10 +1049,7 @@ "metadata": { "colab": {}, "colab_type": "code", - "id": "IMHjiKit6pJg", - "vscode": { - "languageId": "python" - } + "id": "IMHjiKit6pJg" }, "outputs": [], "source": [ @@ -1177,10 +1087,7 @@ "metadata": { "colab": {}, "colab_type": "code", - "id": "4gw_L3JG0_G0", - "vscode": { - "languageId": "python" - } + "id": "4gw_L3JG0_G0" }, "outputs": [], "source": [ @@ -1212,10 +1119,7 @@ "metadata": { "colab": {}, "colab_type": "code", - "id": "nFuGA73MAA4p", - "vscode": { - "languageId": "python" - } + "id": "nFuGA73MAA4p" }, "outputs": [], "source": [ @@ -1237,10 +1141,7 @@ "metadata": { "colab": {}, "colab_type": "code", - "id": "Cf_G-GdturLL", - "vscode": { - "languageId": "python" - } + "id": "Cf_G-GdturLL" }, "outputs": [], "source": [ @@ -1277,10 +1178,7 @@ "metadata": { "colab": {}, "colab_type": "code", - "id": "uXmH0TQ76pJt", - "vscode": { - "languageId": "python" - } + "id": "uXmH0TQ76pJt" }, "outputs": [], "source": [ diff --git a/docs/tutorials/quantum_reinforcement_learning.ipynb b/docs/tutorials/quantum_reinforcement_learning.ipynb index d12e254a5..fb1a059f0 100644 --- a/docs/tutorials/quantum_reinforcement_learning.ipynb +++ b/docs/tutorials/quantum_reinforcement_learning.ipynb @@ -1370,7 +1370,7 @@ }, { "cell_type": "code", - "execution_count": 42, + "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" @@ -1493,8 +1493,7 @@ " episode_reward_history.append(episode_reward)\n", " if (episode + 1) % 10 == 0:\n", " avg_rewards = np.mean(episode_reward_history[-10:])\n", - " print(\"Episode {}/{}, average last 10 rewards {}\".format(\n", - " episode + 1, n_episodes, avg_rewards))\n", + " print(f\"Episode {episode + 1}/{n_episodes}, average last 10 rewards {avg_rewards}\")\n", " if avg_rewards >= 500.0:\n", " break" ] diff --git a/docs/tutorials/research_tools.ipynb b/docs/tutorials/research_tools.ipynb index ae6d8e2be..9be3ba364 100644 --- a/docs/tutorials/research_tools.ipynb +++ b/docs/tutorials/research_tools.ipynb @@ -574,7 +574,7 @@ " step=epoch)\n", "\n", " if epoch % 10 == 0:\n", - " print('Epoch {}, took {}(s)'.format(epoch, time.time() - t))\n", + " print(f'Epoch {epoch}, took {time.time() - t}(s)')\n", " t = time.time()" ] }, diff --git a/tensorflow_quantum/core/ops/batch_util.py b/tensorflow_quantum/core/ops/batch_util.py index 75f148424..1eedde12d 100644 --- a/tensorflow_quantum/core/ops/batch_util.py +++ b/tensorflow_quantum/core/ops/batch_util.py @@ -118,15 +118,15 @@ def _fixed_circuit_plus_pauli_string_measurements(circuit, pauli_string): def _validate_inputs(circuits, param_resolvers, simulator, sim_type): """Type check and sanity check inputs.""" if not isinstance(circuits, (list, tuple, np.ndarray)): - raise TypeError('circuits must be a list or array.' - ' Given: {}'.format(type(circuits))) + raise TypeError( + f'circuits must be a list or array. Given: {type(circuits)}') if any(not isinstance(x, cirq.Circuit) for x in circuits): raise TypeError('circuits must contain cirq.Circuit objects') if not isinstance(param_resolvers, (list, tuple, np.ndarray)): raise TypeError('param_resolvers must be a list or array.' - ' Given: {}'.format(type(param_resolvers))) + f' Given: {type(param_resolvers)}') if any(not isinstance(x, cirq.ParamResolver) for x in param_resolvers): raise TypeError('param_resolvers must contain cirq.ParamResolvers.') @@ -139,7 +139,7 @@ def _validate_inputs(circuits, param_resolvers, simulator, sim_type): if not isinstance(simulator, cirq.SimulatesFinalState): raise TypeError('For analytic operations only' ' cirq.SimulatesFinalState' - ' is required. Given: {}'.format(type(simulator))) + f' is required. Given: {type(simulator)}') elif sim_type == 'expectation': if not isinstance(simulator, @@ -149,12 +149,12 @@ def _validate_inputs(circuits, param_resolvers, simulator, sim_type): raise TypeError('For expectation operations a ' 'cirq.sim.simulator.SimulatesExpectationValues ' 'or cirq.DensityMatrixSimulator' - 'is required. Given: {}'.format(type(simulator))) + f' is required. Given: {type(simulator)}') elif sim_type == 'sample': if not isinstance(simulator, cirq.Sampler): raise TypeError('For sample based operations a cirq.Sampler is ' - 'required. Given: {}'.format(type(simulator))) + f'required. Given: {type(simulator)}') else: raise ValueError('Invalid simulator type specified.') @@ -251,8 +251,7 @@ def batch_calculate_expectation(circuits, param_resolvers, ops, simulator): return np.zeros((0, 0), dtype=np.float32) if not isinstance(ops, (list, tuple, np.ndarray)): - raise TypeError('ops must be a list or array.' - ' Given: {}'.format(type(ops))) + raise TypeError(f'ops must be a list or array. Given: {type(ops)}') if len(ops) != len(circuits): raise ValueError('Shape of ops and circuits do not match.') @@ -263,7 +262,7 @@ def batch_calculate_expectation(circuits, param_resolvers, ops, simulator): for x in sub_list: if not isinstance(x, cirq.PauliSum): raise TypeError('ops must contain only cirq.PauliSum objects.' - ' Given: {}'.format(type(x))) + f' Given: {type(x)}') all_exp_vals = np.ones(shape=(len(circuits), len(ops[0])), dtype=np.float32) * -2 @@ -325,8 +324,7 @@ def batch_calculate_sampled_expectation(circuits, param_resolvers, ops, return np.zeros((0, 0), dtype=np.float32) if not isinstance(ops, (list, tuple, np.ndarray)): - raise TypeError('ops must be a list or array.' - ' Given: {}'.format(type(ops))) + raise TypeError(f'ops must be a list or array. Given: {type(ops)}') if len(ops) != len(circuits): raise ValueError('Shape of ops and circuits do not match.') @@ -349,7 +347,7 @@ def batch_calculate_sampled_expectation(circuits, param_resolvers, ops, for x in sub_list: if not isinstance(x, cirq.PauliSum): raise TypeError('ops must contain only cirq.PauliSum objects.' - ' Given: {}'.format(type(x))) + f' Given: {type(x)}') all_exp_vals = np.full((len(circuits), len(ops[0])), -2, dtype=np.float32) @@ -404,8 +402,7 @@ def batch_sample(circuits, param_resolvers, n_samples, simulator): return np.zeros((0, 0, 0), dtype=np.int8) if not isinstance(n_samples, int): - raise TypeError('n_samples must be an int.' - 'Given: {}'.format(type(n_samples))) + raise TypeError(f'n_samples must be an int.Given: {type(n_samples)}') if n_samples <= 0: raise ValueError('n_samples must be > 0.') diff --git a/tensorflow_quantum/core/ops/circuit_execution_ops.py b/tensorflow_quantum/core/ops/circuit_execution_ops.py index d82a1c83d..18e449f39 100644 --- a/tensorflow_quantum/core/ops/circuit_execution_ops.py +++ b/tensorflow_quantum/core/ops/circuit_execution_ops.py @@ -35,7 +35,7 @@ class TFQStateVectorSimulator(enum.Enum): def _check_quantum_concurrent(quantum_concurrent): if not isinstance(quantum_concurrent, bool): raise TypeError("quantum_concurrent must be type bool." - " Given: {}".format(str(type(quantum_concurrent)))) + f" Given: {type(quantum_concurrent)}") def get_expectation_op( @@ -146,9 +146,9 @@ def get_expectation_op( " Use " "tf.get_sampled_expectation_op() instead.") - raise TypeError("Backend {} is invalid. Expected a " + raise TypeError(f"Backend {backend} is invalid. Expected a " "cirq.sim.simulator.SimulatesExpectationValues " - "or None.".format(backend)) + "or None.") def get_sampling_op( @@ -239,8 +239,8 @@ def get_sampling_op( lambda: tfq_utility_ops.padded_to_ragged(op( programs, symbol_names, symbol_values, num_samples))) - raise TypeError("Backend {} is invalid. Expected a Cirq.Sampler " - "or None.".format(backend)) + raise TypeError( + f"Backend {backend} is invalid. Expected a Cirq.Sampler or None.") def get_state_op( @@ -329,8 +329,9 @@ def get_state_op( lambda: tfq_utility_ops.padded_to_ragged(op( programs, symbol_names, symbol_values))) - raise TypeError("Backend {} is invalid. Expected a Cirq.SimulatesFinalState" - " or None.".format(backend)) + raise TypeError( + f"Backend {backend} is invalid. Expected a Cirq.SimulatesFinalState" + " or None.") def get_sampled_expectation_op( @@ -447,5 +448,4 @@ def get_sampled_expectation_op( num_samples)) raise TypeError( - "Backend {} is invalid. Expected a Cirq.Sampler or None.".format( - backend)) + f"Backend {backend} is invalid. Expected a Cirq.Sampler or None.") diff --git a/tensorflow_quantum/core/ops/cirq_ops.py b/tensorflow_quantum/core/ops/cirq_ops.py index 472f9173b..c1ca97c72 100644 --- a/tensorflow_quantum/core/ops/cirq_ops.py +++ b/tensorflow_quantum/core/ops/cirq_ops.py @@ -322,8 +322,9 @@ def cirq_sampled_expectation(programs, symbol_names, symbol_values, 'int64.') if not (num_samples.shape == pauli_sums.shape): raise TypeError('num_samples tensor must have the same shape ' - 'as pauli_sums tensor. got: {} expected: {}'.format( - num_samples.shape, pauli_sums.shape)) + f'as pauli_sums tensor. got: {num_samples.shape}' + f' expected: {pauli_sums.shape}') + if tf.less_equal(num_samples, 0).numpy().any(): raise TypeError('num_samples contains sample value <= 0.') diff --git a/tensorflow_quantum/core/ops/tfq_utility_ops_test.py b/tensorflow_quantum/core/ops/tfq_utility_ops_test.py index 8faf14aaf..613704fe2 100644 --- a/tensorflow_quantum/core/ops/tfq_utility_ops_test.py +++ b/tensorflow_quantum/core/ops/tfq_utility_ops_test.py @@ -246,7 +246,7 @@ def test_resolve_parameters_consistency_basic(self): circuit = cirq.Circuit() symbols = [] for n, q in enumerate(qubits): - new_bit = sympy.Symbol("bit_{}".format(n)) + new_bit = sympy.Symbol(f"bit_{n}") circuit += cirq.X(q)**new_bit symbols.append(new_bit) symbol_names = [str(s) for s in symbols] diff --git a/tensorflow_quantum/core/serialize/op_serializer.py b/tensorflow_quantum/core/serialize/op_serializer.py index bdb1effc5..3a8f573b4 100644 --- a/tensorflow_quantum/core/serialize/op_serializer.py +++ b/tensorflow_quantum/core/serialize/op_serializer.py @@ -33,9 +33,9 @@ def qubit_to_proto(qubit): """Return proto representation of a GridQubit.""" if isinstance(qubit, cirq.GridQubit): - return '{}_{}'.format(qubit.row, qubit.col) + return f'{qubit.row}_{qubit.col}' if isinstance(qubit, cirq.LineQubit): - return '{}'.format(qubit.x) + return f'{qubit.x}' raise ValueError('Unsupported qubit type:' + str(type(qubit))) @@ -187,8 +187,8 @@ def to_proto( gate = op.gate if not isinstance(gate, self.gate_type): raise ValueError( - 'Gate of type {} but serializer expected type {}'.format( - type(gate), self.gate_type)) + f'Gate of type {type(gate)} but serializer expected type ' + f'{self.gate_type}') if not self.can_serialize_predicate(op): return None @@ -215,8 +215,8 @@ def _value_from_gate(self, op, arg): value = getattr(gate, op_getter, None) if value is None and arg.required: raise ValueError( - 'Gate {!r} does not have attribute or property {}'.format( - gate, op_getter)) + f'Gate {gate!r} does not have attribute or property ' + f'{op_getter}') elif callable(op_getter): value = op_getter(op) @@ -237,14 +237,13 @@ def _check_type(self, value, arg): if arg.serialized_type == float: if not isinstance(value, (float, int)): raise ValueError( - 'Expected type convertible to float but was {}'.format( - type(value))) + f'Expected type convertible to float but was {type(value)}') elif arg.serialized_type == List[bool]: if (not isinstance(value, (list, tuple, np.ndarray)) or not all(isinstance(x, (bool, np.bool_)) for x in value)): - raise ValueError('Expected type List[bool] but was {}'.format( - type(value))) + raise ValueError( + f'Expected type List[bool] but was {type(value)}') elif value is not None and not isinstance(value, arg.serialized_type): raise ValueError( - 'Argument {} had type {} but gate returned type {}'.format( - arg.serialized_name, arg.serialized_type, type(value))) + f'Argument {arg.serialized_name} had type ' + f'{arg.serialized_type} but gate returned type {type(value)}') diff --git a/tensorflow_quantum/core/serialize/serializable_gate_set.py b/tensorflow_quantum/core/serialize/serializable_gate_set.py index bdf1e97b1..93b01d9ae 100644 --- a/tensorflow_quantum/core/serialize/serializable_gate_set.py +++ b/tensorflow_quantum/core/serialize/serializable_gate_set.py @@ -165,8 +165,7 @@ def serialize_op( op, msg, arg_function_language=arg_function_language) if proto_msg is not None: return proto_msg - raise ValueError('Cannot serialize op {!r} of type {}'.format( - op, gate_type)) + raise ValueError(f'Cannot serialize op {op!r} of type {gate_type}') def deserialize(self, proto, device=None): """Deserialize a Circuit from a cirq_google.api.v2.Program. @@ -183,8 +182,9 @@ def deserialize(self, proto, device=None): if not proto.HasField('language') or not proto.language.gate_set: raise ValueError('Missing gate set specification.') if proto.language.gate_set != self.gate_set_name: - raise ValueError('Gate set in proto was {} but expected {}'.format( - proto.language.gate_set, self.gate_set_name)) + raise ValueError(f'Gate set in proto was {proto.language.gate_set} ' + f'but expected {self.gate_set_name}') + which = proto.WhichOneof('program') if which == 'circuit': circuit = self._deserialize_circuit( @@ -214,9 +214,8 @@ def deserialize_op( gate_id = operation_proto.gate.id if gate_id not in self.deserializers.keys(): - raise ValueError('Unsupported serialized gate with id "{}".' - '\n\noperation_proto:\n{}'.format( - gate_id, operation_proto)) + raise ValueError(f'Unsupported serialized gate with id "{gate_id}".' + f'\n\noperation_proto:\n{operation_proto}') return self.deserializers[gate_id].from_proto( operation_proto, arg_function_language=arg_function_language) diff --git a/tensorflow_quantum/core/serialize/serializer.py b/tensorflow_quantum/core/serialize/serializer.py index 73b38ee16..323e70025 100644 --- a/tensorflow_quantum/core/serialize/serializer.py +++ b/tensorflow_quantum/core/serialize/serializer.py @@ -598,8 +598,8 @@ def _identity_gate_serializer(): def _identity_check(x): if x.gate.num_qubits() != 1: raise ValueError("Multi-Qubit identity gate not supported." - "Given: {}. To work around this, use " - "cirq.I.on_each instead.".format(str(x))) + f"Given: {x}. To work around this, use " + "cirq.I.on_each instead.") return True # Here `args` is used for two reasons. 1. GateOpSerializer doesn't work well diff --git a/tensorflow_quantum/datasets/cluster_state.py b/tensorflow_quantum/datasets/cluster_state.py index ff859f286..4a782e046 100644 --- a/tensorflow_quantum/datasets/cluster_state.py +++ b/tensorflow_quantum/datasets/cluster_state.py @@ -64,8 +64,8 @@ def excited_cluster_states(qubits): """ if not isinstance(qubits, (tuple, list, np.ndarray)): - raise TypeError('qubits must be a list or np.ndarray. ' - 'Given: {}.'.format(type(qubits))) + raise TypeError( + f'qubits must be a list or np.ndarray. Given: {type(qubits)}.') for qubit in qubits: if not isinstance(qubit, cirq.GridQubit): diff --git a/tensorflow_quantum/datasets/spin_system.py b/tensorflow_quantum/datasets/spin_system.py index 4a180a68f..1e18e901e 100644 --- a/tensorflow_quantum/datasets/spin_system.py +++ b/tensorflow_quantum/datasets/spin_system.py @@ -234,13 +234,12 @@ def tfi_chain(qubits, boundary_condition="closed", data_dir=None): nspins = len(qubits) depth = nspins // 2 if nspins not in supported_n: - raise ValueError("Supported number of spins are {}, received {}".format( - supported_n, nspins)) + raise ValueError( + f"Supported number of spins are {supported_n}, received {nspins}") if boundary_condition not in supported_bc: - raise ValueError( - "Supported boundary conditions are {}, received {}".format( - supported_bc, boundary_condition)) + raise ValueError(f"Supported boundary conditions are {supported_bc}, " + f"received {boundary_condition}") data_path = _download_spin_data('TFI_chain', boundary_condition, nspins, data_dir) @@ -461,13 +460,12 @@ def xxz_chain(qubits, boundary_condition="closed", data_dir=None): nspins = len(qubits) depth = nspins // 2 if nspins not in supported_n: - raise ValueError("Supported number of spins are {}, received {}".format( - supported_n, nspins)) + raise ValueError( + f"Supported number of spins are {supported_n}, received {nspins}") if boundary_condition not in supported_bc: - raise ValueError( - "Supported boundary conditions are {}, received {}".format( - supported_bc, boundary_condition)) + raise ValueError(f"Supported boundary conditions are {supported_bc}, " + f"received {boundary_condition}") data_path = _download_spin_data('XXZ_chain', boundary_condition, nspins, data_dir) @@ -704,13 +702,12 @@ def tfi_rectangular(qubits, boundary_condition="torus", data_dir=None): depth = int(np.ceil(nspins / 2)) if nspins not in supported_n: - raise ValueError("Supported number of spins are {}, received {}".format( - supported_n, nspins)) + raise ValueError( + f"Supported number of spins are {supported_n}, received {nspins}") if boundary_condition not in supported_bc: - raise ValueError( - "Supported boundary conditions are {}, received {}".format( - supported_bc, boundary_condition)) + raise ValueError(f"Supported boundary conditions are {supported_bc}, " + f"received {boundary_condition}") data_path = _download_spin_data('TFI_rect', boundary_condition, nspins, data_dir) diff --git a/tensorflow_quantum/python/differentiators/differentiator.py b/tensorflow_quantum/python/differentiators/differentiator.py index a64278ab2..862a04106 100644 --- a/tensorflow_quantum/python/differentiators/differentiator.py +++ b/tensorflow_quantum/python/differentiators/differentiator.py @@ -125,10 +125,10 @@ def generate_differentiable_op(self, *, sampled_op=None, analytic_op=None): for key in expected_signature: if not any(key in s for s in signature): raise ValueError('unexpected signature for analytic_op. ' - 'Given arg: {}.'.format(str(key)) + '' - 'The signature should contain: {}.'.format( - list(expected_signature)) + '' - ' Given: {}'.format(list(signature)) + '' + f'Given arg: {key}.' + '' + 'The signature should contain: ' + f'{list(expected_signature)}' + '' + f' Given: {list(signature)}' + '' 'Note: noisy ops should use sampled_op') if 'num_samples' in signature: @@ -146,9 +146,9 @@ def generate_differentiable_op(self, *, sampled_op=None, analytic_op=None): for key in expected_signature: if not any(key in s for s in signature): raise ValueError('unexpected signature for sampled_op. ' - 'Given arg: {}.'.format(str(key)) + '' - 'The signature should contain: {}.'.format( - list(expected_signature))) + f'Given arg: {key}.' + '' + 'The signature should contain: ' + f'{list(expected_signature)}') @tf.custom_gradient def op_wrapper_analytic(programs, symbol_names, symbol_values, diff --git a/tensorflow_quantum/python/differentiators/linear_combination.py b/tensorflow_quantum/python/differentiators/linear_combination.py index 3a94580a9..aa27e9b3a 100644 --- a/tensorflow_quantum/python/differentiators/linear_combination.py +++ b/tensorflow_quantum/python/differentiators/linear_combination.py @@ -76,12 +76,12 @@ def __init__(self, weights, perturbations): """ if not isinstance(weights, (np.ndarray, list, tuple)): raise TypeError("weights must be a numpy array, list or tuple." - "Got {}".format(type(weights))) + f"Got {type(weights)}") if not all([isinstance(weight, numbers.Real) for weight in weights]): raise TypeError("Each weight in weights must be a real number.") if not isinstance(perturbations, (np.ndarray, list, tuple)): raise TypeError("perturbations must be a numpy array," - " list or tuple. Got {}".format(type(weights))) + f" list or tuple. Got {type(weights)}") if not all([ isinstance(perturbation, numbers.Real) for perturbation in perturbations diff --git a/tensorflow_quantum/python/layers/circuit_construction/elementary.py b/tensorflow_quantum/python/layers/circuit_construction/elementary.py index 260689beb..6f7c12507 100644 --- a/tensorflow_quantum/python/layers/circuit_construction/elementary.py +++ b/tensorflow_quantum/python/layers/circuit_construction/elementary.py @@ -109,8 +109,8 @@ def call(self, inputs, *, append=None, prepend=None): inputs = util.convert_to_tensor(inputs) if not tf.is_tensor(inputs): - raise TypeError("Circuits cannot be parsed with " - "given input: {}".format(inputs)) + raise TypeError( + f"Circuits cannot be parsed with given input: {inputs}") batch_dim = tf.gather(tf.shape(inputs), 0) @@ -122,7 +122,7 @@ def call(self, inputs, *, append=None, prepend=None): append = util.convert_to_tensor(append) if not tf.is_tensor(append): raise TypeError("Append circuits cannot be parsed with " - "given input: {}".format(append)) + f"given input: {append}") return tfq_utility_ops.append_circuit(inputs, append) @@ -133,7 +133,7 @@ def call(self, inputs, *, append=None, prepend=None): prepend = util.convert_to_tensor(prepend) if not tf.is_tensor(prepend): raise TypeError( - "Prepend circuits cannot be parsed with given input: {}".format( - prepend)) + f"Prepend circuits cannot be parsed with given input: {prepend}" + ) return tfq_utility_ops.append_circuit(prepend, inputs) diff --git a/tensorflow_quantum/python/layers/circuit_executors/expectation.py b/tensorflow_quantum/python/layers/circuit_executors/expectation.py index b8b627b9c..8b620df50 100644 --- a/tensorflow_quantum/python/layers/circuit_executors/expectation.py +++ b/tensorflow_quantum/python/layers/circuit_executors/expectation.py @@ -361,7 +361,7 @@ def call(self, if not tf.is_tensor(repetitions): raise TypeError("repetitions cannot be parsed to int32 tensor" - " given input: {}".format(repetitions)) + f" given input: {repetitions}") if values_empty: # No symbol_values were provided. So we assume the user wants us diff --git a/tensorflow_quantum/python/layers/circuit_executors/input_checks.py b/tensorflow_quantum/python/layers/circuit_executors/input_checks.py index ed1308d82..6487a9586 100644 --- a/tensorflow_quantum/python/layers/circuit_executors/input_checks.py +++ b/tensorflow_quantum/python/layers/circuit_executors/input_checks.py @@ -70,7 +70,7 @@ def expand_circuits(inputs, dtype=tf.dtypes.string) if not tf.is_tensor(symbol_names): raise TypeError("symbol_names cannot be parsed to string" - " tensor given input: {}".format(symbol_names)) + f" tensor given input: {symbol_names}") # Ingest and promote symbol_values. if isinstance(symbol_values, (list, tuple, np.ndarray)): @@ -78,7 +78,7 @@ def expand_circuits(inputs, dtype=tf.dtypes.float32) if not tf.is_tensor(symbol_values): raise TypeError("symbol_values cannot be parsed to float32" - " tensor given input: {}".format(symbol_values)) + f" tensor given input: {symbol_values}") symbol_batch_dim = tf.gather(tf.shape(symbol_values), 0) @@ -97,8 +97,7 @@ def expand_circuits(inputs, inputs, deterministic_proto_serialize=deterministic_proto_serialize) if not tf.is_tensor(inputs): - raise TypeError( - "circuits cannot be parsed with given input: {}".format(inputs)) + raise TypeError(f"circuits cannot be parsed with given input: {inputs}") if symbols_empty: # No symbol_values were provided. so we must tile up the @@ -161,6 +160,6 @@ def expand_operators(operators=None, if not tf.is_tensor(operators): raise TypeError("operators cannot be parsed to string tensor" - " given input: {}".format(operators)) + f" given input: {operators}") return operators diff --git a/tensorflow_quantum/python/layers/circuit_executors/sample.py b/tensorflow_quantum/python/layers/circuit_executors/sample.py index 5ae1525c2..ed99b7c81 100644 --- a/tensorflow_quantum/python/layers/circuit_executors/sample.py +++ b/tensorflow_quantum/python/layers/circuit_executors/sample.py @@ -193,7 +193,7 @@ def call(self, if not tf.is_tensor(repetitions): raise TypeError("repetitions cannot be parsed to int32 tensor" - " tensor given input: {}".format(repetitions)) + f" tensor given input: {repetitions}") inputs, symbol_names, symbol_values = input_checks.expand_circuits( inputs, symbol_names, symbol_values) diff --git a/tensorflow_quantum/python/layers/circuit_executors/sampled_expectation.py b/tensorflow_quantum/python/layers/circuit_executors/sampled_expectation.py index 744825d89..5c2b9b7ee 100644 --- a/tensorflow_quantum/python/layers/circuit_executors/sampled_expectation.py +++ b/tensorflow_quantum/python/layers/circuit_executors/sampled_expectation.py @@ -319,7 +319,7 @@ def call(self, if not tf.is_tensor(repetitions): raise TypeError("repetitions cannot be parsed to int32 tensor" - " given input: {}".format(repetitions)) + f" given input: {repetitions}") if values_empty: # No symbol_values were provided. So we assume the user wants us diff --git a/tensorflow_quantum/python/layers/high_level/controlled_pqc.py b/tensorflow_quantum/python/layers/high_level/controlled_pqc.py index 7a48f84b5..d5c1f30aa 100644 --- a/tensorflow_quantum/python/layers/high_level/controlled_pqc.py +++ b/tensorflow_quantum/python/layers/high_level/controlled_pqc.py @@ -160,7 +160,7 @@ def __init__(self, # Ingest model_circuit. if not isinstance(model_circuit, cirq.Circuit): raise TypeError("model_circuit must be a cirq.Circuit object." - " Given: {}".format(model_circuit)) + f" Given: {model_circuit}") self._symbols_list = list( sorted(util.get_circuit_symbols(model_circuit))) @@ -181,7 +181,7 @@ def __init__(self, raise TypeError("operators must be a cirq.PauliSum or " "cirq.PauliString, or a list, tuple, " "or np.array containing them. " - "Got {}.".format(type(operators))) + f"Got {type(operators)}.") if not all([ isinstance(op, (cirq.PauliString, cirq.PauliSum)) for op in operators @@ -199,7 +199,7 @@ def __init__(self, if not self._analytic and not isinstance(repetitions, numbers.Integral): raise TypeError("repetitions must be a positive integer value." - " Given: {}".format(repetitions)) + f" Given: {repetitions}") if not self._analytic and repetitions <= 0: raise ValueError("Repetitions must be greater than zero.") diff --git a/tensorflow_quantum/python/layers/high_level/noisy_controlled_pqc.py b/tensorflow_quantum/python/layers/high_level/noisy_controlled_pqc.py index d14d87940..3400562f0 100644 --- a/tensorflow_quantum/python/layers/high_level/noisy_controlled_pqc.py +++ b/tensorflow_quantum/python/layers/high_level/noisy_controlled_pqc.py @@ -168,7 +168,7 @@ def __init__(self, # Ingest model_circuit. if not isinstance(model_circuit, cirq.Circuit): raise TypeError("model_circuit must be a cirq.Circuit object." - " Given: {}".format(model_circuit)) + f" Given: {model_circuit}") self._symbols_list = list( sorted(util.get_circuit_symbols(model_circuit))) @@ -189,7 +189,7 @@ def __init__(self, raise TypeError("operators must be a cirq.PauliSum or " "cirq.PauliString, or a list, tuple, " "or np.array containing them. " - "Got {}.".format(type(operators))) + f"Got {type(operators)}.") if not all([ isinstance(op, (cirq.PauliString, cirq.PauliSum)) for op in operators @@ -206,7 +206,7 @@ def __init__(self, "using noisy simulation.") if not isinstance(repetitions, numbers.Integral): raise TypeError("repetitions must be a positive integer value." - " Given: {}".format(repetitions)) + f" Given: {repetitions}") if repetitions <= 0: raise ValueError("Repetitions must be greater than zero.") @@ -226,7 +226,7 @@ def __init__(self, "noisy estimates.") if not isinstance(sample_based, bool): raise TypeError("sample_based must be either True or False." - " received: {}".format(type(sample_based))) + f" received: {type(sample_based)}") if not sample_based: self._executor = differentiator.generate_differentiable_op( diff --git a/tensorflow_quantum/python/layers/high_level/noisy_pqc.py b/tensorflow_quantum/python/layers/high_level/noisy_pqc.py index 676fe718c..ce62be523 100644 --- a/tensorflow_quantum/python/layers/high_level/noisy_pqc.py +++ b/tensorflow_quantum/python/layers/high_level/noisy_pqc.py @@ -177,7 +177,7 @@ def __init__( # Ingest model_circuit. if not isinstance(model_circuit, cirq.Circuit): raise TypeError("model_circuit must be a cirq.Circuit object." - " Given: {}".format(model_circuit)) + f" Given: {model_circuit}") self._symbols_list = list( sorted(util.get_circuit_symbols(model_circuit))) @@ -196,7 +196,7 @@ def __init__( raise TypeError("operators must be a cirq.PauliSum or " "cirq.PauliString, or a list, tuple, " "or np.array containing them. " - "Got {}.".format(type(operators))) + f"Got {type(operators)}.") if not all([ isinstance(op, (cirq.PauliString, cirq.PauliSum)) for op in operators @@ -212,7 +212,7 @@ def __init__( "using noisy simulation.") if not isinstance(repetitions, numbers.Integral): raise TypeError("repetitions must be a positive integer value." - " Given: {}".format(repetitions)) + f" Given: {repetitions}") if repetitions <= 0: raise ValueError("Repetitions must be greater than zero.") @@ -232,7 +232,7 @@ def __init__( "noisy estimates.") if not isinstance(sample_based, bool): raise TypeError("sample_based must be either True or False." - " received: {}".format(type(sample_based))) + f" received: {type(sample_based)}") if not sample_based: self._executor = differentiator.generate_differentiable_op( diff --git a/tensorflow_quantum/python/layers/high_level/pqc.py b/tensorflow_quantum/python/layers/high_level/pqc.py index 78987b24f..bc34c3e97 100644 --- a/tensorflow_quantum/python/layers/high_level/pqc.py +++ b/tensorflow_quantum/python/layers/high_level/pqc.py @@ -210,7 +210,7 @@ def __init__( # Ingest model_circuit. if not isinstance(model_circuit, cirq.Circuit): raise TypeError("model_circuit must be a cirq.Circuit object." - " Given: {}".format(model_circuit)) + f" Given: {model_circuit}") self._symbols_list = list( sorted(util.get_circuit_symbols(model_circuit))) @@ -229,7 +229,7 @@ def __init__( raise TypeError("operators must be a cirq.PauliSum or " "cirq.PauliString, or a list, tuple, " "or np.array containing them. " - "Got {}.".format(type(operators))) + f"Got {type(operators)}.") if not all([ isinstance(op, (cirq.PauliString, cirq.PauliSum)) for op in operators @@ -245,7 +245,7 @@ def __init__( self._analytic = True if not self._analytic and not isinstance(repetitions, numbers.Integral): raise TypeError("repetitions must be a positive integer value." - " Given: {}".format(repetitions)) + f" Given: {repetitions}") if not self._analytic and repetitions <= 0: raise ValueError("Repetitions must be greater than zero.") if not self._analytic: diff --git a/tensorflow_quantum/python/util.py b/tensorflow_quantum/python/util.py index dab705082..4fba81b65 100644 --- a/tensorflow_quantum/python/util.py +++ b/tensorflow_quantum/python/util.py @@ -324,9 +324,10 @@ def recur(items_to_convert, curr_type=None): serializer.serialize_circuit(item).SerializeToString( deterministic=deterministic_proto_serialize)) else: - raise TypeError("Incompatible item passed into " - "convert_to_tensor. Tensor detected type: {}. " - "got: {}".format(curr_type, type(item))) + raise TypeError( + "Incompatible item passed into " + f"convert_to_tensor. Tensor detected type: {curr_type}. " + f"got: {type(item)}") return tensored_items # This will catch impossible dimensions @@ -393,7 +394,7 @@ def from_tensor(tensor_to_convert): tensor_to_convert = tensor_to_convert.numpy() if not isinstance(tensor_to_convert, (np.ndarray, list, tuple)): raise TypeError("tensor_to_convert received bad " - "type {}".format(type(tensor_to_convert))) + f"type {type(tensor_to_convert)}") tensor_to_convert = np.array(tensor_to_convert) python_items = np.empty(tensor_to_convert.shape, dtype=object) curr_type = None @@ -469,9 +470,9 @@ def _symbols_in_op(op): return ret raise ValueError( - "Attempted to scan for symbols in circuit with unsupported" - " ops inside.", "Expected op found in " - "tfq.util.get_supported_gates but found: {}.".format(str(op)), + "Attempted to scan for symbols in circuit with unsupported " + "ops inside. Expected op found in " + f"tfq.util.get_supported_gates but found: {op}. " "Please make sure circuits contain only ops found in " "tfq.util.get_supported_gates().") @@ -711,8 +712,7 @@ def check_commutability(pauli_sum): if not cirq.commutes(term1, term2): raise ValueError("Given an operator has non-commutable " "terms, whose exponentiation is not " - "supported yet: {} and {}".format( - term1, term2)) + f"supported yet: {term1} and {term2}") def exp_identity(param, c, zeroth_qubit): @@ -779,8 +779,8 @@ def exponential(operators, coefficients=None): if len(coefficients) != len(operators): raise ValueError("the number of operators should be the same as that " - "of coefficients. Got {} operators and {} coefficients" - "".format(len(operators), len(coefficients))) + f"of coefficients. Got {len(operators)} operators and " + f"{len(coefficients)} coefficients") coefficients = [ sympy.Symbol(s) if isinstance(s, str) else s @@ -805,8 +805,7 @@ def exponential(operators, coefficients=None): for op in pauli_sum: if abs(op.coefficient.imag) > 1e-9: raise TypeError('exponential only supports real ' - 'coefficients: got ' - '{}'.format(op.coefficient)) + f'coefficients: got {op.coefficient}') # Create a circuit with exponentiating `op` with param c = op.coefficient.real if len(op.gate.pauli_mask) == 0: diff --git a/tensorflow_quantum/python/util_test.py b/tensorflow_quantum/python/util_test.py index dc3f89874..00715899b 100644 --- a/tensorflow_quantum/python/util_test.py +++ b/tensorflow_quantum/python/util_test.py @@ -33,8 +33,8 @@ def _single_to_tensor(item): if not isinstance(item, (cirq.PauliSum, cirq.PauliString, cirq.Circuit)): - raise TypeError("Item must be a Circuit or PauliSum. Got {}.".format( - type(item))) + raise TypeError( + f"Item must be a Circuit or PauliSum. Got {type(item)}.") if isinstance(item, (cirq.PauliSum, cirq.PauliString)): return serializer.serialize_paulisum(item).SerializeToString( deterministic=True)