From 3d2124db0642ff3c5be870016b08fe757ce1e284 Mon Sep 17 00:00:00 2001 From: Purva Thakre Date: Thu, 19 Oct 2023 13:55:07 -0500 Subject: [PATCH 01/24] all pylint issues in tests/ --- .pylintrc | 2 +- .../test_completely_bounded_trace_norm.py | 2 +- tests/test_channel_ops/test_dual_channel.py | 4 ++-- tests/test_nonlocal_games/test_xor_game.py | 1 - 4 files changed, 4 insertions(+), 5 deletions(-) diff --git a/.pylintrc b/.pylintrc index 0b0132032..598784e9f 100644 --- a/.pylintrc +++ b/.pylintrc @@ -204,7 +204,7 @@ redefining-builtins-modules=six.moves,past.builtins,future.builtins,builtins,io [FORMAT] # Maximum number of characters on a single line. -max-line-length=100 +max-line-length=120 # Regexp for a line that is allowed to be longer than the limit. ignore-long-lines=^\s*(# )??$ diff --git a/tests/test_channel_metrics/test_completely_bounded_trace_norm.py b/tests/test_channel_metrics/test_completely_bounded_trace_norm.py index 6dadc8674..86c920be0 100644 --- a/tests/test_channel_metrics/test_completely_bounded_trace_norm.py +++ b/tests/test_channel_metrics/test_completely_bounded_trace_norm.py @@ -16,7 +16,7 @@ def test_cb_trace_norm_unitaries_channel(): """The diamond norm of phi = id- U id U* is the diameter of the smallest circle that contains the eigenvalues of U.""" U = 1 / np.sqrt(2) * np.array([[1, 1], [-1, 1]]) # Hadamard gate phi = kraus_to_choi([[np.eye(2), np.eye(2)], [U, -U]]) - lam, eigv = np.linalg.eig(U) + lam, _ = np.linalg.eig(U) dist = np.abs(lam[:, None] - lam[None, :]) # all to all distance diameter = np.max(dist) np.testing.assert_equal( diff --git a/tests/test_channel_ops/test_dual_channel.py b/tests/test_channel_ops/test_dual_channel.py index 815819e53..5d927ddd2 100644 --- a/tests/test_channel_ops/test_dual_channel.py +++ b/tests/test_channel_ops/test_dual_channel.py @@ -75,8 +75,8 @@ def test_dual_channel_choi_dims(): def test_dual_channel_nonsquare_matrix(): """Dual of a channel that transposes 3x2 matrices.""" - choi = swap_operator([2, 3]) - choi_dual = dual_channel(choi, dims=[[3, 2], [2, 3]]) + choi1 = swap_operator([2, 3]) + choi_dual = dual_channel(choi1, dims=[[3, 2], [2, 3]]) expected_choi_dual = np.array( [ [1, 0, 0, 0, 0, 0], diff --git a/tests/test_nonlocal_games/test_xor_game.py b/tests/test_nonlocal_games/test_xor_game.py index 4a5b92316..43c41bc14 100644 --- a/tests/test_nonlocal_games/test_xor_game.py +++ b/tests/test_nonlocal_games/test_xor_game.py @@ -3,7 +3,6 @@ import numpy as np -from toqito.nonlocal_games.nonlocal_game import NonlocalGame from toqito.nonlocal_games.xor_game import XORGame From 140293a8aab23c27fc9cc8885e39f06eb1514774 Mon Sep 17 00:00:00 2001 From: Purva Thakre Date: Mon, 23 Oct 2023 14:02:58 -0500 Subject: [PATCH 02/24] state_props:eof --- toqito/state_props/entanglement_of_formation.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/toqito/state_props/entanglement_of_formation.py b/toqito/state_props/entanglement_of_formation.py index 469924b13..7ea13fe67 100644 --- a/toqito/state_props/entanglement_of_formation.py +++ b/toqito/state_props/entanglement_of_formation.py @@ -1,5 +1,6 @@ """Computes the entanglement of formation of a bipartite quantum state.""" +from __future__ import annotations import numpy as np import scipy @@ -65,7 +66,7 @@ def entanglement_of_formation(rho: np.ndarray, dim: list[int] | int = None) -> f # User can specify dimension as integer. if isinstance(dim, int): - dim = np.array([dim, max(dim_x, dim_y) / dim], dtype=int) + dim = np.array([dim, max(dim_x, dim_y) / dim], dtype=int) # pylint: disable=redefined-variable-type if abs(dim[1] - np.round(dim[1])) >= 2 * max(dim_x, dim_y) * eps: raise ValueError( "Invalid dimension: If `dim` is provided as a " @@ -87,7 +88,7 @@ def entanglement_of_formation(rho: np.ndarray, dim: list[int] | int = None) -> f # Start computing entanglement-of-formation. if min(dim_x, dim_y) == 1: rho = rho[:] - dim = [x for x in dim] + dim = [int(x) for x in dim] return von_neumann_entropy(partial_trace(rho * rho.conj().T, [1], dim)) # Case: :code:`rho` is a density matrix. From bff37f8a2cbc52c79466f35d87453d0e3a9a021f Mon Sep 17 00:00:00 2001 From: Purva Thakre Date: Thu, 26 Oct 2023 19:09:04 -0500 Subject: [PATCH 03/24] python install --- .pylintrc | 2 +- pyproject.toml | 2 +- setup.py | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/.pylintrc b/.pylintrc index 598784e9f..f181bc3e6 100644 --- a/.pylintrc +++ b/.pylintrc @@ -54,7 +54,7 @@ unsafe-load-any-extension=no extension-pkg-allow-list= # Minimum supported python version -py-version = 3.7.2 +py-version = 3.10 # Control the amount of potential inferred values when inferring a single # object. This can help the performance when dealing with large functions or diff --git a/pyproject.toml b/pyproject.toml index cbe35ff47..7c3f94fb3 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -36,7 +36,7 @@ keywords = ["quantum information", "quantum computing", "nonlocal games"] [tool.poetry.dependencies] -python = "^3.9" +python = "^3.10" cvxpy = "^1.2.1" cvxopt = "^1.2.5" numpy = "^1.19.4" diff --git a/setup.py b/setup.py index ea090e337..2c5039dcb 100644 --- a/setup.py +++ b/setup.py @@ -3,7 +3,7 @@ with open("README.md", "r") as fh: long_description = fh.read() -requirements = ["cvx", "cvxpy", "numpy", "picos", "scipy", "scikit-image"] +requirements = ["cvx", "cvxpy", "cvxopt", "numpy", "picos", "scipy", "scikit-image", "pytest", "pytest-cov"] setuptools.setup( name="toqito", @@ -23,7 +23,7 @@ "License :: OSI Approved :: BSD License", "Operating System :: OS Independent", ], - python_requires=">=3.9", + python_requires=">=3.10", install_requires=requirements, test_suite="tests", ) From dbada540fbe1c960d22e4017bfb6b13c9746d396 Mon Sep 17 00:00:00 2001 From: Purva Thakre Date: Thu, 26 Oct 2023 19:10:59 -0500 Subject: [PATCH 04/24] pylint userwarning --- .pylintrc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.pylintrc b/.pylintrc index f181bc3e6..866ff04f5 100644 --- a/.pylintrc +++ b/.pylintrc @@ -513,7 +513,7 @@ preferred-modules= # Exceptions that will emit a warning when being caught. Defaults to # "Exception" -overgeneral-exceptions=Exception +overgeneral-exceptions=builtins.Exception [TYPING] From 0ae0f6a025ef6ef3ac53a846f1debdbe9a5370fc Mon Sep 17 00:00:00 2001 From: Purva Thakre Date: Thu, 26 Oct 2023 19:14:03 -0500 Subject: [PATCH 05/24] remove exception and from future annotations --- toqito/state_props/entanglement_of_formation.py | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/toqito/state_props/entanglement_of_formation.py b/toqito/state_props/entanglement_of_formation.py index 7ea13fe67..f81f67d73 100644 --- a/toqito/state_props/entanglement_of_formation.py +++ b/toqito/state_props/entanglement_of_formation.py @@ -1,7 +1,5 @@ """Computes the entanglement of formation of a bipartite quantum state.""" -from __future__ import annotations - import numpy as np import scipy @@ -66,7 +64,7 @@ def entanglement_of_formation(rho: np.ndarray, dim: list[int] | int = None) -> f # User can specify dimension as integer. if isinstance(dim, int): - dim = np.array([dim, max(dim_x, dim_y) / dim], dtype=int) # pylint: disable=redefined-variable-type + dim = np.array([dim, max(dim_x, dim_y) / dim], dtype=int) if abs(dim[1] - np.round(dim[1])) >= 2 * max(dim_x, dim_y) * eps: raise ValueError( "Invalid dimension: If `dim` is provided as a " From da6ee7b0352333bace193d7d3da175c205aff68d Mon Sep 17 00:00:00 2001 From: Purva Thakre Date: Thu, 26 Oct 2023 19:45:02 -0500 Subject: [PATCH 06/24] import lines --- toqito/channel_ops/dual_channel.py | 1 - toqito/matrix_props/__init__.py | 1 - 2 files changed, 2 deletions(-) diff --git a/toqito/channel_ops/dual_channel.py b/toqito/channel_ops/dual_channel.py index 533231dfd..c645c5cbc 100644 --- a/toqito/channel_ops/dual_channel.py +++ b/toqito/channel_ops/dual_channel.py @@ -4,7 +4,6 @@ import numpy as np from toqito.helper import channel_dim -from toqito.matrix_props import is_square from toqito.perms import swap diff --git a/toqito/matrix_props/__init__.py b/toqito/matrix_props/__init__.py index 7750d9ec1..3334efb58 100644 --- a/toqito/matrix_props/__init__.py +++ b/toqito/matrix_props/__init__.py @@ -18,6 +18,5 @@ from toqito.matrix_props.majorizes import majorizes from toqito.matrix_props.sk_norm import sk_operator_norm from toqito.matrix_props.is_block_positive import is_block_positive -from toqito.matrix_props.is_orthonormal import is_orthonormal from toqito.matrix_props.trace_norm import trace_norm from toqito.matrix_props.is_diagonally_dominant import is_diagonally_dominant From f32af52f558cfe6f69fb42b66fb6e09b4fa54942 Mon Sep 17 00:00:00 2001 From: Purva Thakre Date: Thu, 26 Oct 2023 19:58:23 -0500 Subject: [PATCH 07/24] matrix_props/is_positive_def --- toqito/matrix_props/is_positive_definite.py | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/toqito/matrix_props/is_positive_definite.py b/toqito/matrix_props/is_positive_definite.py index 5144c3a48..4ed5b181c 100644 --- a/toqito/matrix_props/is_positive_definite.py +++ b/toqito/matrix_props/is_positive_definite.py @@ -1,10 +1,10 @@ """Is matrix a positive definite matrix.""" import numpy as np -from toqito.matrix_props import is_hermitian +from toqito.matrix_props import is_hermitian # pylint: disable=unused-import -def is_positive_definite(mat: np.ndarray, rtol: float = 1e-05, atol: float = 1e-08) -> bool: +def is_positive_definite(mat: np.ndarray) -> bool: r""" Check if matrix is positive definite (PD) [WikPD]_. @@ -54,8 +54,6 @@ def is_positive_definite(mat: np.ndarray, rtol: float = 1e-05, atol: float = 1e- https://en.wikipedia.org/wiki/Definiteness_of_a_matrix :param mat: Matrix to check. - :param rtol: The relative tolerance parameter (default 1e-05). - :param atol: The absolute tolerance parameter (default 1e-08). :return: Return :code:`True` if matrix is positive definite, and :code:`False` otherwise. """ if np.array_equal(mat, mat.conj().T): From 319f6e2540cae9b809c8c4f1f362725cf7dbc43e Mon Sep 17 00:00:00 2001 From: Purva Thakre Date: Fri, 27 Oct 2023 16:01:18 -0500 Subject: [PATCH 08/24] fixes Make parameter typing consistent in doc examples #209 --- .../state_metrics/fidelity_of_separability.py | 26 +++++++------------ 1 file changed, 9 insertions(+), 17 deletions(-) diff --git a/toqito/state_metrics/fidelity_of_separability.py b/toqito/state_metrics/fidelity_of_separability.py index f401572d7..d35332f85 100644 --- a/toqito/state_metrics/fidelity_of_separability.py +++ b/toqito/state_metrics/fidelity_of_separability.py @@ -122,27 +122,19 @@ def fidelity_of_separability( “The Theory of Quantum Information” Cambridge University Press, 2018 - Args: - input_state_rho: the density matrix for the bipartite state of interest. - input_state_rho_dims: the dimensions of System A & B respectively in + :param input_state_rho: the density matrix for the bipartite state of interest. + :param input_state_rho_dims: the dimensions of System A & B respectively in the input state density matrix. It is assumed that the first quantity in this list is the dimension of System A. - k: value for k-extendibility. - verbosity_option: Parameter option for `picos`. Default value is `verbosity = 2`. + :param k: value for k-extendibility. + :param verbosity_option: Parameter option for `picos`. Default value is `verbosity = 2`. For more info, visit https://picos-api.gitlab.io/picos/api/picos.modeling.options.html#option-verbosity. - solver_option: Optimization option for `picos` solver. Default option is `solver_option="cvxopt"` + :param solver_option: Optimization option for `picos` solver. Default option is `solver_option="cvxopt"` For more info, visit https://picos-api.gitlab.io/picos/api/picos.modeling.options.html#option-solver. - Raises: - AssertionError: - * If the provided dimensions are not for a bipartite density matrix. - TypeError: - * If the matrix is not a density matrix (square matrix that is \n - PSD with trace 1). - TypeError: - * If the input state is entangled or a mixed state. - Returns: - Optimized value of the SDP when maximized over a set of linear operators - subject to some constraints. + :raises AssertionError: If the provided dimensions are not for a bipartite density matrix. + :raises TypeError: If the matrix is not a density matrix (square matrix that is PSD with trace 1). + :raises TypeError: the input state is entangled or a mixed state. + :return: Optimized value of the SDP when maximized over a set of linear operators subject to some constraints. """ # rho is relabelled as rho_{AB} where A >= B. if not is_density(input_state_rho): From 455348239d2e8d4c4d707729c9c17388e6c4976f Mon Sep 17 00:00:00 2001 From: Purva Thakre Date: Fri, 27 Oct 2023 16:14:59 -0500 Subject: [PATCH 09/24] state_metrics/fid_of_sep --- .../state_metrics/fidelity_of_separability.py | 31 ++++++++++++------- 1 file changed, 19 insertions(+), 12 deletions(-) diff --git a/toqito/state_metrics/fidelity_of_separability.py b/toqito/state_metrics/fidelity_of_separability.py index d35332f85..48a7d0cc1 100644 --- a/toqito/state_metrics/fidelity_of_separability.py +++ b/toqito/state_metrics/fidelity_of_separability.py @@ -12,7 +12,7 @@ from toqito.state_props import is_pure, is_separable -def fidelity_of_separability( +def fidelity_of_separability(# pylint: disable-msg=too-many-locals input_state_rho: np.ndarray, input_state_rho_dims: list[int], k: int = 1, @@ -127,14 +127,18 @@ def fidelity_of_separability( the input state density matrix. It is assumed that the first quantity in this list is the dimension of System A. :param k: value for k-extendibility. - :param verbosity_option: Parameter option for `picos`. Default value is `verbosity = 2`. - For more info, visit https://picos-api.gitlab.io/picos/api/picos.modeling.options.html#option-verbosity. - :param solver_option: Optimization option for `picos` solver. Default option is `solver_option="cvxopt"` - For more info, visit https://picos-api.gitlab.io/picos/api/picos.modeling.options.html#option-solver. + :param verbosity_option: Parameter option for `picos`. Default value is + `verbosity = 2`. For more info, visit + https://picos-api.gitlab.io/picos/api/picos.modeling.options.html#option-verbosity. + :param solver_option: Optimization option for `picos` solver. Default option is + `solver_option="cvxopt"`. For more info, visit + https://picos-api.gitlab.io/picos/api/picos.modeling.options.html#option-solver. :raises AssertionError: If the provided dimensions are not for a bipartite density matrix. - :raises TypeError: If the matrix is not a density matrix (square matrix that is PSD with trace 1). + :raises TypeError: If the matrix is not a density matrix (square matrix that + is PSD with trace 1). :raises TypeError: the input state is entangled or a mixed state. - :return: Optimized value of the SDP when maximized over a set of linear operators subject to some constraints. + :return: Optimized value of the SDP when maximized over a set of linear operators subject + to some constraints. """ # rho is relabelled as rho_{AB} where A >= B. if not is_density(input_state_rho): @@ -148,13 +152,13 @@ def fidelity_of_separability( # Infer the dimension of Alice and Bob's system. # subsystem-dimensions in rho_AB - dim_A, dim_B = input_state_rho_dims + dim_A, dim_B = input_state_rho_dims # pylint: disable-msg=invalid-name # Extend the number of dimensions based on the level `k`. # new dims for AB with k-extendibility in subsystem B - dim_direct_sum_AB_k = [dim_A] + [dim_B] * (k) + dim_direct_sum_AB_k = [dim_A] + [dim_B] * (k) # pylint: disable-msg=invalid-name # new dims for a linear op acting on the space of sigma_AB_k - dim_op_sigma_AB_k = dim_A * dim_B**k + dim_op_sigma_AB_k = dim_A * dim_B**k # pylint: disable-msg=invalid-name # A list of the symmetrically extended subsystems based on the level `k`. sub_sys_ext = list(range(2, 2 + k - 1)) @@ -163,8 +167,11 @@ def fidelity_of_separability( # defining the problem objective: Re[Tr[X_AB]] problem = picos.Problem(verbosity=verbosity_option) - linear_op_AB = picos.ComplexVariable("x_AB", input_state_rho.shape) - sigma_AB_k = picos.HermitianVariable("s_AB_k", (dim_op_sigma_AB_k, dim_op_sigma_AB_k)) + linear_op_AB = picos.ComplexVariable( # pylint: disable-msg=invalid-name + "x_AB", input_state_rho.shape) + sigma_AB_k = picos.HermitianVariable( # pylint: disable-msg=invalid-name + "s_AB_k", ( + dim_op_sigma_AB_k, dim_op_sigma_AB_k)) problem.set_objective("max", 0.5 * picos.trace(linear_op_AB + linear_op_AB.H)) From 384b209c8d0739f25faad071069f900ee898b458 Mon Sep 17 00:00:00 2001 From: Purva Thakre Date: Fri, 27 Oct 2023 16:17:51 -0500 Subject: [PATCH 10/24] channel_props/is_trace_preserving --- toqito/channel_props/is_trace_preserving.py | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/toqito/channel_props/is_trace_preserving.py b/toqito/channel_props/is_trace_preserving.py index 2b0aac9b4..1c0d1700c 100644 --- a/toqito/channel_props/is_trace_preserving.py +++ b/toqito/channel_props/is_trace_preserving.py @@ -100,9 +100,8 @@ def is_trace_preserving( k_r = np.concatenate(phi_r, axis=0) mat = k_l.conj().T @ k_r + elif dim is None: + mat = partial_trace(phi, [sys - 1]) else: - if dim == None: - mat = partial_trace(phi, [sys - 1]) - else: - mat = partial_trace(phi, [sys - 1], dim) + mat = partial_trace(phi, [sys - 1], dim) return is_identity(np.array(mat), rtol=rtol, atol=atol) From 3f96c296997fc352b4fdcdd86b599ee43840c7a4 Mon Sep 17 00:00:00 2001 From: Purva Thakre Date: Fri, 27 Oct 2023 16:22:40 -0500 Subject: [PATCH 11/24] nonlocalgame --- toqito/nonlocal_games/nonlocal_game.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/toqito/nonlocal_games/nonlocal_game.py b/toqito/nonlocal_games/nonlocal_game.py index bc4641879..ebeaddef5 100644 --- a/toqito/nonlocal_games/nonlocal_game.py +++ b/toqito/nonlocal_games/nonlocal_game.py @@ -88,8 +88,7 @@ def from_bcs_game(cls, constraints: list[np.ndarray], reps: int = 1) -> "Nonloca :return: An instance of a nonlocal game object. """ - num_constraints = len(constraints) - if num_constraints == 0: + if (num_constraints := len(constraints)) == 0: raise ValueError("At least 1 constraint is required") num_variables = constraints[0].ndim From 9f3cee1306c203c69134f60a61e09bb5d748808e Mon Sep 17 00:00:00 2001 From: Purva Thakre Date: Fri, 27 Oct 2023 17:06:19 -0500 Subject: [PATCH 12/24] useless suppression --- .../state_metrics/fidelity_of_separability.py | 23 ++++++++++--------- 1 file changed, 12 insertions(+), 11 deletions(-) diff --git a/toqito/state_metrics/fidelity_of_separability.py b/toqito/state_metrics/fidelity_of_separability.py index 48a7d0cc1..47169f0f9 100644 --- a/toqito/state_metrics/fidelity_of_separability.py +++ b/toqito/state_metrics/fidelity_of_separability.py @@ -12,7 +12,7 @@ from toqito.state_props import is_pure, is_separable -def fidelity_of_separability(# pylint: disable-msg=too-many-locals +def fidelity_of_separability(# pylint: disable = missing-type-doc input_state_rho: np.ndarray, input_state_rho_dims: list[int], k: int = 1, @@ -124,21 +124,22 @@ def fidelity_of_separability(# pylint: disable-msg=too-many-locals :param input_state_rho: the density matrix for the bipartite state of interest. :param input_state_rho_dims: the dimensions of System A & B respectively in - the input state density matrix. It is assumed that the first - quantity in this list is the dimension of System A. + the input state density matrix. It is assumed that the first + quantity in this list is the dimension of System A. :param k: value for k-extendibility. :param verbosity_option: Parameter option for `picos`. Default value is - `verbosity = 2`. For more info, visit - https://picos-api.gitlab.io/picos/api/picos.modeling.options.html#option-verbosity. + `verbosity = 2`. For more info, visit + https://picos-api.gitlab.io/picos/api/picos.modeling.options.html#option-verbosity. :param solver_option: Optimization option for `picos` solver. Default option is - `solver_option="cvxopt"`. For more info, visit - https://picos-api.gitlab.io/picos/api/picos.modeling.options.html#option-solver. + `solver_option="cvxopt"`. For more info, visit + https://picos-api.gitlab.io/picos/api/picos.modeling.options.html#option-solver. :raises AssertionError: If the provided dimensions are not for a bipartite density matrix. - :raises TypeError: If the matrix is not a density matrix (square matrix that - is PSD with trace 1). - :raises TypeError: the input state is entangled or a mixed state. + :raises ValueError: If the matrix is not a density matrix (square matrix that + is PSD with trace 1). + :raises ValueError: the input state is entangled. + :raises ValueError: the input state is a mixed state. :return: Optimized value of the SDP when maximized over a set of linear operators subject - to some constraints. + to some constraints. """ # rho is relabelled as rho_{AB} where A >= B. if not is_density(input_state_rho): From b23aa8038aaf8f2a1ebd489bde93ab8e77c7ef43 Mon Sep 17 00:00:00 2001 From: Purva Thakre Date: Sun, 29 Oct 2023 16:34:21 -0500 Subject: [PATCH 13/24] quick fixes --- .../completely_bounded_trace_norm.py | 2 +- .../fidelity_of_separability.py | 39 +++++++++---------- toqito/channels/partial_trace.py | 9 +++-- toqito/channels/partial_transpose.py | 6 +-- toqito/helper/npa_hierarchy.py | 2 +- toqito/matrix_ops/inner_product.py | 3 +- toqito/matrix_ops/outer_product.py | 3 +- toqito/matrix_ops/vectors_from_gram_matrix.py | 8 +++- toqito/matrix_props/sk_norm.py | 15 +++---- toqito/perms/perfect_matchings.py | 4 +- toqito/random/random_povm.py | 5 +-- .../state_metrics/fidelity_of_separability.py | 6 +-- toqito/state_opt/ppt_distinguishability.py | 4 +- toqito/state_opt/state_exclusion.py | 11 ++++-- toqito/state_props/is_product.py | 3 +- toqito/state_props/is_separable.py | 16 ++++---- toqito/states/basis.py | 2 +- 17 files changed, 69 insertions(+), 69 deletions(-) diff --git a/toqito/channel_metrics/completely_bounded_trace_norm.py b/toqito/channel_metrics/completely_bounded_trace_norm.py index 642367b95..c583a832d 100644 --- a/toqito/channel_metrics/completely_bounded_trace_norm.py +++ b/toqito/channel_metrics/completely_bounded_trace_norm.py @@ -44,7 +44,7 @@ def completely_bounded_trace_norm(phi: np.ndarray) -> float: if is_quantum_channel(phi): return 1 - elif is_completely_positive(phi): + if is_completely_positive(phi): v = apply_channel(np.eye(dim_ly), dual_channel(phi)) return trace_norm(v) diff --git a/toqito/channel_metrics/fidelity_of_separability.py b/toqito/channel_metrics/fidelity_of_separability.py index 61de99a44..efd48c697 100644 --- a/toqito/channel_metrics/fidelity_of_separability.py +++ b/toqito/channel_metrics/fidelity_of_separability.py @@ -14,7 +14,7 @@ def fidelity_of_separability( - psi: np.ndarray, psi_dims: list[int], k: int = 1, verbosity_option=2, solver_option="cvxopt" + psi: np.ndarray, psi_dims: list[int], k: int = 1, verbosity_option: int=2, solver_option: str="cvxopt" ) -> float: r""" Define the first benchmark introduced in Appendix I of [Phil23.1]_ . @@ -113,28 +113,25 @@ def fidelity_of_separability( “The Theory of Quantum Information” Cambridge University Press, 2018 - Args: - psi: the density matrix for the tripartite state of interest psi_{BAR} - psi_dims: the dimensions of System A, B, & R in + + :param psi: the density matrix for the tripartite state of interest psi_{BAR} + :param psi_dims: the dimensions of System A, B, & R in the input state density matrix. It is assumed that the first quantity in this list is the dimension of System B. - k: value for k-extendibility. - verbosity_option: Parameter option for `picos`. Default value is `verbosity = 2`. - For more info, visit https://picos-api.gitlab.io/picos/api/picos.modeling.options.html#option-verbosity - solver_option: Optimization option for `picos` solver. Default option is `solver_option="cvxopt"` - For more info, visit https://picos-api.gitlab.io/picos/api/picos.modeling.options.html#option-solver - Raises: - AssertionError: - * If the provided dimensions are not for a tripartite density - matrix. - TypeError: - * If the matrix is not a density matrix (square matrix that is \n - PSD with trace 1). - TypeError: - * If the input state is a mixed state. - Returns: - Optimized value of the SDP when maximized over a set of linear - operators subject to some constraints. + :param k: value for k-extendibility. + :param verbosity_option: Parameter option for `picos`. Default value is + `verbosity = 2`. For more info, visit + https://picos-api.gitlab.io/picos/api/picos.modeling.options.html#option-verbosity. + :param solver_option: Optimization option for `picos` solver. Default option is + `solver_option="cvxopt"`. For more info, visit + https://picos-api.gitlab.io/picos/api/picos.modeling.options.html#option-solver. + :raises AssertionError: If the provided dimensions are not for a tripartite density matrix. + :raises ValueError: If the matrix is not a density matrix (square matrix that + is PSD with trace 1). + :raises ValueError: the input state is entangled. + :raises ValueError: the input state is a mixed state. + :return: Optimized value of the SDP when maximized over a set of linear + operators subject to some constraints. """ if not is_density(psi): raise ValueError("Provided input state is not a density matrix.") diff --git a/toqito/channels/partial_trace.py b/toqito/channels/partial_trace.py index 365035bd8..392b12008 100644 --- a/toqito/channels/partial_trace.py +++ b/toqito/channels/partial_trace.py @@ -12,7 +12,7 @@ def partial_trace( input_mat: np.ndarray | Variable, - sys: int | list[int] = [1], + sys: int | list[int] = None, dim: int | list[int] = None, ) -> np.ndarray | Expression: r""" @@ -130,6 +130,9 @@ def partial_trace( equal. :return: The partial trace of matrix :code:`input_mat`. """ + if not isinstance(sys, int): + if sys is None: + sys = [1] # If the input matrix is a CVX variable for an SDP, we convert it to a numpy array, # perform the partial trace, and convert it back to a CVX variable. if isinstance(input_mat, Variable): @@ -145,10 +148,10 @@ def partial_trace( if isinstance(dim, list): dim = np.array(dim) - num_sys = len(dim) + # Allow the user to enter a single number for dim. - if num_sys == 1: + if (num_sys := len(dim)) == 1: dim = np.array([dim[0], len(input_mat) / dim[0]]) if np.abs(dim[1] - np.round(dim[1])) >= 2 * len(input_mat) * np.finfo(float).eps: raise ValueError( diff --git a/toqito/channels/partial_transpose.py b/toqito/channels/partial_transpose.py index 6386f79d7..c3b6e991e 100644 --- a/toqito/channels/partial_transpose.py +++ b/toqito/channels/partial_transpose.py @@ -12,7 +12,7 @@ def partial_transpose( rho: np.ndarray | Variable, - sys: list[int] | np.ndarray | int = [1], + sys: list[int] | np.ndarray | int = 1, dim: list[int] | np.ndarray = None, ) -> np.ndarray | Expression: r"""Compute the partial transpose of a matrix [WikPtrans]_. @@ -135,9 +135,9 @@ def partial_transpose( if isinstance(sys, int): sys = np.array([sys]) - num_sys = max(dim.shape) + # Allow the user to enter a single number for dim. - if num_sys == 1: + if (num_sys := max(dim.shape)) == 1: dim = np.array([dim, list(rho.shape)[0] / dim]) if np.abs(dim[1] - np.round(dim[1]))[0] >= 2 * list(rho.shape)[0] * np.finfo(float).eps: raise ValueError( diff --git a/toqito/helper/npa_hierarchy.py b/toqito/helper/npa_hierarchy.py index 509817549..aa8f43d30 100644 --- a/toqito/helper/npa_hierarchy.py +++ b/toqito/helper/npa_hierarchy.py @@ -124,7 +124,7 @@ def _get_nonlocal_game_params( return a_out, a_in, b_out, b_in -def npa_constraints( +def npa_constraints(# pylint: disable=too-many-locals assemblage: dict[tuple[int, int], cvxpy.Variable], k: int | str = 1, referee_dim: int = 1 ) -> list[cvxpy.constraints.constraint.Constraint]: r""" diff --git a/toqito/matrix_ops/inner_product.py b/toqito/matrix_ops/inner_product.py index 7929e84a7..dde9210ac 100644 --- a/toqito/matrix_ops/inner_product.py +++ b/toqito/matrix_ops/inner_product.py @@ -33,7 +33,8 @@ def inner_product(v1: np.ndarray, v2: np.ndarray) -> float: https://en.wikipedia.org/wiki/Inner_product_space :raises ValueError: Vector dimensions are mismatched. - :param args: v1 and v2, both vectors of dimenstions :math:`(n,1)` where :math:`n>1`. + :param v1: v1 and v2, both vectors of dimenstions :math:`(n,1)` where :math:`n>1`. + :param v2: v1 and v2, both vectors of dimenstions :math:`(n,1)` where :math:`n>1`. :return: The computed inner product. """ # Check for dimensional validity diff --git a/toqito/matrix_ops/outer_product.py b/toqito/matrix_ops/outer_product.py index 65521f0fe..f73554f42 100644 --- a/toqito/matrix_ops/outer_product.py +++ b/toqito/matrix_ops/outer_product.py @@ -35,7 +35,8 @@ def outer_product(v1: np.ndarray, v2: np.ndarray) -> np.ndarray: https://en.wikipedia.org/wiki/Outer_product :raises ValueError: Vector dimensions are mismatched. - :param args: v1 and v2, both vectors of dimensions :math:`(n,1)` where :math:`n>1`. + :param v1: v1 and v2, both vectors of dimenstions :math:`(n,1)` where :math:`n>1`. + :param v2: v1 and v2, both vectors of dimenstions :math:`(n,1)` where :math:`n>1`. :return: The computed outer product. """ # Check for dimensional validity diff --git a/toqito/matrix_ops/vectors_from_gram_matrix.py b/toqito/matrix_ops/vectors_from_gram_matrix.py index 47c7013a5..bf296cb94 100644 --- a/toqito/matrix_ops/vectors_from_gram_matrix.py +++ b/toqito/matrix_ops/vectors_from_gram_matrix.py @@ -3,14 +3,18 @@ def vectors_from_gram_matrix(gram: np.ndarray) -> list[np.ndarray]: - """Obtain the corresponding ensemble of states from the Gram matrix.""" + """Obtain the corresponding ensemble of states from the Gram matrix. + + :param gram: Input Gram matrix. + :return: list of ensemble states + """ dim = gram.shape[0] # If matrix is PD, can do Cholesky decomposition: try: decomp = np.linalg.cholesky(gram) return [decomp[i][:] for i in range(dim)] # Otherwise, need to do eigendecomposition: - except Exception: + except Exception: # pylint: disable=broad-except print("Matrix is not positive semidefinite. Using eigendecomposition as alternative.") d, v = np.linalg.eig(gram) return [np.sqrt(np.diag(d)) @ v[i].conj().T for i in range(dim)] diff --git a/toqito/matrix_props/sk_norm.py b/toqito/matrix_props/sk_norm.py index 074e243ba..909143d3c 100644 --- a/toqito/matrix_props/sk_norm.py +++ b/toqito/matrix_props/sk_norm.py @@ -17,7 +17,7 @@ from toqito.states import max_entangled -def sk_operator_norm( +def sk_operator_norm( # pylint: disable=too-many-locals mat: np.ndarray, k: int = 1, dim: int | list[int] = None, @@ -227,7 +227,7 @@ def sk_operator_norm( return op_norm * lower_bound, op_norm * upper_bound # Start the semidefinite programming approach for getting upper bounds. - if effort >= 1 and ( + if effort >= 1 and (# pylint: disable=too-many-boolean-expressions (lower_bound + tol < upper_bound and is_positive) or (is_positive and is_trans_exact and k == 1) ): @@ -328,7 +328,7 @@ def __target_is_proved( # Schmidt vectors of the other sub-system. This optimization is equivalent to # a generalized eigenvalue problem. The algorithm terminates when an iteration # cannot improve the lower bound by more than tol. -def __lower_bound_sk_norm_randomized( +def __lower_bound_sk_norm_randomized(# pylint: disable=too-many-locals mat: np.ndarray, k: int = 1, dim: int | list[int] = None, @@ -350,8 +350,7 @@ def __lower_bound_sk_norm_randomized( opt_vec = None if start_vec is not None: singular_vals, vt_mat, u_mat = schmidt_decomposition(start_vec, dim) - s_rank = len(singular_vals) - if s_rank > k: + if (s_rank := len(singular_vals)) > k: warnings.warn( f"The Schmidt rank of the initial vector is {s_rank}, which is larger than k={k}. \ Using a randomly-generated intial vector instead." @@ -383,8 +382,7 @@ def __lower_bound_sk_norm_randomized( for p in range(2): # If Schmidt rank is not full, we will have numerical problems; go to # lower Schmidt rank iteration. - s_rank = schmidt_rank(opt_vec, dim) - if s_rank < k: + if (s_rank := schmidt_rank(opt_vec, dim)) < k: return __lower_bound_sk_norm_randomized(mat, s_rank, dim, tol, opt_vec) # Fix one of the parties and optimize over the other party. @@ -399,9 +397,8 @@ def __lower_bound_sk_norm_randomized( largest_eigval, largest_eigvec = scipy.linalg.eigh( a_mat, b=b_mat, subset_by_index=[a_mat.shape[0] - 1, a_mat.shape[0] - 1] ) - new_sk_lower_bound = np.real(largest_eigval[0]) - if new_sk_lower_bound >= sk_lower_bound + tol: + if (new_sk_lower_bound := np.real(largest_eigval[0])) >= sk_lower_bound + tol: it_lower_bound_improved = True sk_lower_bound = new_sk_lower_bound diff --git a/toqito/perms/perfect_matchings.py b/toqito/perms/perfect_matchings.py index 9c6638d7b..ffef0e9a0 100644 --- a/toqito/perms/perfect_matchings.py +++ b/toqito/perms/perfect_matchings.py @@ -37,10 +37,8 @@ def perfect_matchings(num: list[int] | int | np.ndarray) -> np.ndarray: if isinstance(num, list): num = np.array(num) - len_num = len(num) - # Base case, `num = 2`: only one perfect matching. - if len_num == 2: + if (len_num := len(num)) == 2: return num # There are no perfect matchings of an odd number of objects. diff --git a/toqito/random/random_povm.py b/toqito/random/random_povm.py index 85d8a62d3..97a83272d 100644 --- a/toqito/random/random_povm.py +++ b/toqito/random/random_povm.py @@ -49,10 +49,7 @@ def random_povm(dim: int, num_inputs: int, num_outputs: int) -> np.ndarray: povms = [] gram_vectors = np.random.normal(size=(num_inputs, num_outputs, dim, dim)) for input_block in gram_vectors: - normalizer = sum( - [np.array(output_block).T.conj() @ output_block for output_block in input_block] - ) - + normalizer = sum(np.array(output_block).T.conj() @ output_block for output_block in input_block) u_mat, d_mat, _ = np.linalg.svd(normalizer) output_povms = [] diff --git a/toqito/state_metrics/fidelity_of_separability.py b/toqito/state_metrics/fidelity_of_separability.py index 47169f0f9..66e4fb334 100644 --- a/toqito/state_metrics/fidelity_of_separability.py +++ b/toqito/state_metrics/fidelity_of_separability.py @@ -12,12 +12,12 @@ from toqito.state_props import is_pure, is_separable -def fidelity_of_separability(# pylint: disable = missing-type-doc +def fidelity_of_separability( input_state_rho: np.ndarray, input_state_rho_dims: list[int], k: int = 1, - verbosity_option=2, - solver_option="cvxopt", + verbosity_option: int=2, + solver_option: str ="cvxopt", ) -> float: r""" Define the first benchmark introduced in Appendix H of [Phil23]_. diff --git a/toqito/state_opt/ppt_distinguishability.py b/toqito/state_opt/ppt_distinguishability.py index d261f4238..0d45794cb 100644 --- a/toqito/state_opt/ppt_distinguishability.py +++ b/toqito/state_opt/ppt_distinguishability.py @@ -125,7 +125,7 @@ def ppt_distinguishability( def primal_problem( - states: list[np.ndarray], probs: list[float] = None, dist_method="min-error" + states: list[np.ndarray], probs: list[float] = None, dist_method: str="min-error" ) -> float: r""" Calculate primal problem for PPT distinguishability. @@ -204,7 +204,7 @@ def primal_problem( def dual_problem( - states: list[np.ndarray], probs: list[float] = None, dist_method="min-error" + states: list[np.ndarray], probs: list[float] = None, dist_method: str="min-error" ) -> float: r""" Calculate dual problem for PPT distinguishability. diff --git a/toqito/state_opt/state_exclusion.py b/toqito/state_opt/state_exclusion.py index 8f9b865c5..648c6b333 100644 --- a/toqito/state_opt/state_exclusion.py +++ b/toqito/state_opt/state_exclusion.py @@ -6,7 +6,7 @@ def state_exclusion( - vectors: list[np.ndarray], probs: list[float] = None, solver: str = "cvxopt", primal_dual="dual" + vectors: list[np.ndarray], probs: list[float] = None, solver: str = "cvxopt", primal_dual: str ="dual" ) -> tuple[float, list[picos.HermitianVariable]]: r""" Compute probability of single state exclusion. @@ -86,16 +86,19 @@ def state_exclusion( Physical Review A 89.2 (2014): 022336. arXiv:1306.4683 - :param states: A list of states provided as vectors. + :param vectors: A list of states provided as vectors. :param probs: Respective list of probabilities each state is selected. If no probabilities are provided, a uniform probability distribution is assumed. + :param solver: Optimization option for `picos` solver. Default option is + `solver_option="cvxopt"`. + :param primal_dual: Option for the optimization problem :return: The optimal probability with which Bob can guess the state he was not given from `states` along with the optimal set of measurements. """ if primal_dual == "primal": return _min_error_primal(vectors, probs, solver) - else: - return _min_error_dual(vectors, probs, solver) + + return _min_error_dual(vectors, probs, solver) def _min_error_primal(vectors: list[np.ndarray], probs: list[float] = None, solver: str = "cvxopt"): diff --git a/toqito/state_props/is_product.py b/toqito/state_props/is_product.py index 5c9b6f251..0aeb2257d 100644 --- a/toqito/state_props/is_product.py +++ b/toqito/state_props/is_product.py @@ -88,11 +88,10 @@ def _is_product(rho: np.ndarray, dim: int | list[int] = None) -> list[int, bool] # If there are only two subsystems, just use the Schmidt decomposition. if num_sys == 2: singular_vals, u_mat, vt_mat = schmidt_decomposition(rho, dim, 2) - ipv = singular_vals[1] <= np.prod(dim) * np.spacing(singular_vals[0]) # Provide this even if not requested, since it is needed if this # function was called as part of its recursive algorithm (see below) - if ipv: + if (ipv := singular_vals[1] <= np.prod(dim) * np.spacing(singular_vals[0])): u_mat = u_mat * np.sqrt(singular_vals[0]) vt_mat = vt_mat * np.sqrt(singular_vals[0]) dec = [u_mat[:, 0], vt_mat[:, 0]] diff --git a/toqito/state_props/is_separable.py b/toqito/state_props/is_separable.py index b1a439396..2c554390d 100644 --- a/toqito/state_props/is_separable.py +++ b/toqito/state_props/is_separable.py @@ -7,7 +7,7 @@ from toqito.channels import realignment from toqito.matrix_props import is_positive_semidefinite, trace_norm -from toqito.perms import swap + from toqito.state_props import in_separable_ball, is_ppt from toqito.state_props.has_symmetric_extension import has_symmetric_extension @@ -161,10 +161,11 @@ def is_separable( # For the rest of the block-matrix tests, we need the 2-dimensional subsystem to be the # first subsystem, so swap accordingly. - if dim[0] > 2: - Xt = swap(state, [1, 2], dim) - else: - Xt = state + #if dim[0] > 2: + # Xt = swap(state, [1, 2], dim) + #else: + # Xt = state + # commented out because pylint flagged this as an unused variable # Check the proximity of X with the maximally mixed state. if in_separable_ball(state): @@ -182,7 +183,6 @@ def is_separable( return True # The search for symmetric extensions. - for _ in range(2, level): - if has_symmetric_extension(state, level): - return True + if any(has_symmetric_extension(state, level) for _ in range(2, level)): + return True return False diff --git a/toqito/states/basis.py b/toqito/states/basis.py index 4d1c6ada5..43ec6b27d 100644 --- a/toqito/states/basis.py +++ b/toqito/states/basis.py @@ -48,7 +48,7 @@ def basis(dim: int, pos: int) -> np.ndarray: "Invalid: The `pos` variable needs to be less than `dim` for ket function." ) - ret = np.array(list(map(int, list(f"{0:0{dim}}")))) + ret = np.array(list(int(x) for x in list(f"{0:0{dim}}"))) ret[pos] = 1 ret = ret.conj().T.reshape(-1, 1) return ret From 95dad08129314f12f286ac077dee5dccb116ef6a Mon Sep 17 00:00:00 2001 From: Purva Thakre Date: Sun, 29 Oct 2023 17:04:21 -0500 Subject: [PATCH 14/24] all redefinition disabled --- toqito/channels/partial_trace.py | 4 ++-- toqito/channels/realignment.py | 2 +- toqito/matrices/gell_mann.py | 2 +- toqito/matrices/pauli.py | 2 +- toqito/matrix_props/is_block_positive.py | 2 +- toqito/matrix_props/sk_norm.py | 4 ++-- toqito/nonlocal_games/nonlocal_game.py | 2 +- toqito/perms/permute_systems.py | 2 +- toqito/perms/swap.py | 2 +- toqito/state_opt/optimal_clone.py | 2 +- toqito/state_opt/symmetric_extension_hierarchy.py | 4 ++-- toqito/state_props/entanglement_of_formation.py | 4 ++-- toqito/state_props/has_symmetric_extension.py | 2 +- toqito/state_props/is_separable.py | 2 +- toqito/state_props/schmidt_rank.py | 2 +- toqito/state_props/sk_vec_norm.py | 2 +- 16 files changed, 20 insertions(+), 20 deletions(-) diff --git a/toqito/channels/partial_trace.py b/toqito/channels/partial_trace.py index 392b12008..3b7e21a82 100644 --- a/toqito/channels/partial_trace.py +++ b/toqito/channels/partial_trace.py @@ -169,7 +169,7 @@ def partial_trace( for idx in sys: prod_dim_sys *= dim[idx] elif isinstance(sys, int): - prod_dim_sys = np.prod(dim[sys]) + prod_dim_sys = np.prod(dim[sys])# pylint: disable=redefined-variable-type else: raise ValueError( "Invalid: The variable `sys` must either be of type int or of a list of ints." @@ -179,7 +179,7 @@ def partial_trace( sub_sys_vec = prod_dim * np.ones(int(sub_prod)) / sub_prod if isinstance(sys, list): - sys = np.array(sys) + sys = np.array(sys)# pylint: disable=redefined-variable-type if isinstance(sys, int): sys = np.array([sys]) set_diff = list(set(list(range(1, num_sys + 1))) - set(sys + 1)) diff --git a/toqito/channels/realignment.py b/toqito/channels/realignment.py index 6416edb6e..6e3999240 100644 --- a/toqito/channels/realignment.py +++ b/toqito/channels/realignment.py @@ -79,7 +79,7 @@ def realignment(input_mat: np.ndarray, dim: int | list[int] = None) -> np.ndarra dim = np.array([dim, dim]) dim_x = np.array([[dim[0][1], dim[0][0]], [dim[1][0], dim[1][1]]]) - dim_x = np.int_(dim_x) + dim_x = np.int_(dim_x)# pylint: disable=redefined-variable-type dim_y = np.array([[dim[1][0], dim[0][0]], [dim[0][1], dim[1][1]]]) x_tmp = swap(input_mat, [1, 2], dim, True) diff --git a/toqito/matrices/gell_mann.py b/toqito/matrices/gell_mann.py index 18eff9228..c4513f3c8 100644 --- a/toqito/matrices/gell_mann.py +++ b/toqito/matrices/gell_mann.py @@ -117,6 +117,6 @@ def gell_mann(ind: int, is_sparse: bool = False) -> np.ndarray | scipy.sparse.cs raise ValueError("Gell-Mann index values can only be values from 0 to 8 (inclusive).") if is_sparse: - gm_op = scipy.sparse.csr_matrix(gm_op) + gm_op = scipy.sparse.csr_matrix(gm_op)# pylint: disable=redefined-variable-type return gm_op diff --git a/toqito/matrices/pauli.py b/toqito/matrices/pauli.py index d1907051c..0fb6a0023 100644 --- a/toqito/matrices/pauli.py +++ b/toqito/matrices/pauli.py @@ -97,7 +97,7 @@ def pauli( pauli_mat = np.identity(2) if is_sparse: - pauli_mat = sparse.csr_matrix(pauli_mat) + pauli_mat = sparse.csr_matrix(pauli_mat)# pylint: disable=redefined-variable-type return pauli_mat diff --git a/toqito/matrix_props/is_block_positive.py b/toqito/matrix_props/is_block_positive.py index 173e65c85..156574dc3 100644 --- a/toqito/matrix_props/is_block_positive.py +++ b/toqito/matrix_props/is_block_positive.py @@ -68,7 +68,7 @@ def is_block_positive( # Allow the user to enter in a single integer for dimension. if isinstance(dim, int): - dim = np.array([dim, dim_xy / dim]) + dim = np.array([dim, dim_xy / dim])# pylint: disable=redefined-variable-type if np.abs(dim[1] - np.round(dim[1])) >= 2 * dim_xy * np.finfo(float).eps: raise ValueError( "If `dim` is a scalar, it must evenly divide the length of the matrix." diff --git a/toqito/matrix_props/sk_norm.py b/toqito/matrix_props/sk_norm.py index 909143d3c..661a5a6f7 100644 --- a/toqito/matrix_props/sk_norm.py +++ b/toqito/matrix_props/sk_norm.py @@ -93,7 +93,7 @@ def sk_operator_norm( # pylint: disable=too-many-locals # Allow the user to enter in a single integer for dimension. if isinstance(dim, int): - dim = np.array([dim, dim_xy / dim]) + dim = np.array([dim, dim_xy / dim])# pylint: disable=redefined-variable-type if np.abs(dim[1] - np.round(dim[1])) >= 2 * dim_xy * np.finfo(float).eps: raise ValueError( "If `dim` is a scalar, it must evenly divide the length of the matrix." @@ -132,7 +132,7 @@ def sk_operator_norm( # pylint: disable=too-many-locals # comes from Theorem 4.13 in [1] lower_bound = k / min(dim) # our most basic upper bound - upper_bound = 1 + upper_bound = 1# pylint: disable=redefined-variable-type # break out of the function if the target value has already been met if __target_is_proved(lower_bound, upper_bound, op_norm, tol, target): diff --git a/toqito/nonlocal_games/nonlocal_game.py b/toqito/nonlocal_games/nonlocal_game.py index ebeaddef5..abb95876f 100644 --- a/toqito/nonlocal_games/nonlocal_game.py +++ b/toqito/nonlocal_games/nonlocal_game.py @@ -122,7 +122,7 @@ def from_bcs_game(cls, constraints: list[np.ndarray], reps: int = 1) -> "Nonloca bin_a = [int(x) for x in np.binary_repr(a_ans)] truth_assignment = np.zeros(num_variables, dtype=np.int8) truth_assignment[-len(bin_a) :] = bin_a - truth_assignment = tuple(truth_assignment) + truth_assignment = tuple(truth_assignment)# pylint: disable=redefined-variable-type for y_ques in range(num_variables): # The verifier can only accept the answer if Bob's truth assignment diff --git a/toqito/perms/permute_systems.py b/toqito/perms/permute_systems.py index d6d057e60..f2f3937be 100644 --- a/toqito/perms/permute_systems.py +++ b/toqito/perms/permute_systems.py @@ -209,7 +209,7 @@ def permute_systems( # If the dimensions are specified, ensure they are given to the # recursive calls as flattened lists. if len(dim[0][:]) == 1: - dim = functools.reduce(operator.iconcat, dim, []) + dim = functools.reduce(operator.iconcat, dim, [])# pylint: disable=redefined-variable-type row_perm = permute_systems(vec_arg, perm, dim[0][:], False, inv_perm) diff --git a/toqito/perms/swap.py b/toqito/perms/swap.py index 21447f027..c2a3f46d3 100644 --- a/toqito/perms/swap.py +++ b/toqito/perms/swap.py @@ -157,7 +157,7 @@ def swap( # Swap the indicated subsystems. perm = np.array(range(1, num_sys + 1)) - sys = np.array(sys) - 1 + sys = np.array(sys) - 1# pylint: disable=redefined-variable-type perm[sys] = perm[sys[::-1]] diff --git a/toqito/state_opt/optimal_clone.py b/toqito/state_opt/optimal_clone.py index dc968b71a..98199b6ca 100644 --- a/toqito/state_opt/optimal_clone.py +++ b/toqito/state_opt/optimal_clone.py @@ -133,7 +133,7 @@ def optimal_clone( else: # The permutation vector `perm` contains elements of the # sequence from: https://oeis.org/A023123 - q_a = tensor(q_a, num_reps) + q_a = tensor(q_a, num_reps)# pylint: disable=redefined-variable-type perm = [] for i in range(1, num_spaces + 1): perm.append(i) diff --git a/toqito/state_opt/symmetric_extension_hierarchy.py b/toqito/state_opt/symmetric_extension_hierarchy.py index e9c53c227..e4bfa8a96 100644 --- a/toqito/state_opt/symmetric_extension_hierarchy.py +++ b/toqito/state_opt/symmetric_extension_hierarchy.py @@ -169,7 +169,7 @@ def symmetric_extension_hierarchy( # Allow the user to enter in a single integer for dimension. if isinstance(dim, int): - dim = np.array([dim, dim_xy / dim]) + dim = np.array([dim, dim_xy / dim])# pylint: disable=redefined-variable-type if np.abs(dim[1] - np.round(dim[1])) >= 2 * dim_xy * np.finfo(float).eps: raise ValueError("If `dim` is a scalar, it must evenly divide the length of the state.") dim[1] = int(np.round(dim[1])) @@ -177,7 +177,7 @@ def symmetric_extension_hierarchy( dim_x, dim_y = int(dim[0]), int(dim[1]) dim_list = [dim_x] + [dim_y] * level - dim_list = np.int_(dim_list) + dim_list = np.int_(dim_list)# pylint: disable=redefined-variable-type # The `sys_list` variable contains the numbering pertaining to the symmetrically extended # spaces. sys_list = list(range(2, 2 + level - 1)) diff --git a/toqito/state_props/entanglement_of_formation.py b/toqito/state_props/entanglement_of_formation.py index f81f67d73..a4764574e 100644 --- a/toqito/state_props/entanglement_of_formation.py +++ b/toqito/state_props/entanglement_of_formation.py @@ -63,8 +63,8 @@ def entanglement_of_formation(rho: np.ndarray, dim: list[int] | int = None) -> f dim = round_dim # User can specify dimension as integer. - if isinstance(dim, int): - dim = np.array([dim, max(dim_x, dim_y) / dim], dtype=int) + if isinstance(dim, int): + dim = np.array([dim, max(dim_x, dim_y) / dim], dtype=int) # pylint: disable=redefined-variable-type if abs(dim[1] - np.round(dim[1])) >= 2 * max(dim_x, dim_y) * eps: raise ValueError( "Invalid dimension: If `dim` is provided as a " diff --git a/toqito/state_props/has_symmetric_extension.py b/toqito/state_props/has_symmetric_extension.py index bdff1773f..aca2f7312 100644 --- a/toqito/state_props/has_symmetric_extension.py +++ b/toqito/state_props/has_symmetric_extension.py @@ -108,7 +108,7 @@ def has_symmetric_extension( # Allow the user to enter in a single integer for dimension. if isinstance(dim, int): - dim = np.array([dim, len_mat / dim]) + dim = np.array([dim, len_mat / dim])# pylint: disable=redefined-variable-type if np.abs(dim[1] - np.round(dim[1])) >= 2 * len_mat * np.finfo(float).eps: raise ValueError( "If `dim` is a scalar, it must evenly divide the length of the matrix." diff --git a/toqito/state_props/is_separable.py b/toqito/state_props/is_separable.py index 2c554390d..716e6052e 100644 --- a/toqito/state_props/is_separable.py +++ b/toqito/state_props/is_separable.py @@ -76,7 +76,7 @@ def is_separable( dim = int(np.round(np.sqrt(state_len))) if isinstance(dim, int): - dim = np.array([dim, state_len / dim]) + dim = np.array([dim, state_len / dim])# pylint: disable=redefined-variable-type if np.abs(dim[1] - np.round(dim[1])) >= 2 * state_len * eps: raise ValueError("The parameter `dim` must evenly divide the length of the state.") dim[1] = np.round(dim[1]) diff --git a/toqito/state_props/schmidt_rank.py b/toqito/state_props/schmidt_rank.py index 33d9c560c..5e36e1110 100644 --- a/toqito/state_props/schmidt_rank.py +++ b/toqito/state_props/schmidt_rank.py @@ -92,7 +92,7 @@ def schmidt_rank(rho: np.ndarray, dim: int | list[int] | np.ndarray = None) -> f if dim is None: dim = slv if isinstance(dim, int): - dim = np.array([dim, len(rho) / dim], dtype=int) + dim = np.array([dim, len(rho) / dim], dtype=int)# pylint: disable=redefined-variable-type dim[1] = np.round(dim[1]) return np.linalg.matrix_rank(np.reshape(rho, dim[::-1])) diff --git a/toqito/state_props/sk_vec_norm.py b/toqito/state_props/sk_vec_norm.py index 65d1c0487..e59fc874a 100644 --- a/toqito/state_props/sk_vec_norm.py +++ b/toqito/state_props/sk_vec_norm.py @@ -59,7 +59,7 @@ def sk_vector_norm(rho: np.ndarray, k: int = 1, dim: int | list[int] = None) -> # Allow the user to enter in a single integer for dimension. if isinstance(dim, int): - dim = np.array([dim, dim_xy / dim]) + dim = np.array([dim, dim_xy / dim])# pylint: disable=redefined-variable-type if np.abs(dim[1] - np.round(dim[1])) >= 2 * dim_xy * np.finfo(float).eps: raise ValueError("If `dim` is a scalar, it must evenly divide the length of the state.") dim[1] = int(np.round(dim[1])) From f9dca8b56b67534735a32ed3e67ee47190253959 Mon Sep 17 00:00:00 2001 From: Purva Thakre Date: Sun, 29 Oct 2023 17:23:27 -0500 Subject: [PATCH 15/24] all unsubscriptable object --- toqito/state_props/has_symmetric_extension.py | 2 +- toqito/state_props/is_ppt.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/toqito/state_props/has_symmetric_extension.py b/toqito/state_props/has_symmetric_extension.py index aca2f7312..a99846fff 100644 --- a/toqito/state_props/has_symmetric_extension.py +++ b/toqito/state_props/has_symmetric_extension.py @@ -117,7 +117,7 @@ def has_symmetric_extension( dim = np.int_(dim) - dim_x, dim_y = int(dim[0]), int(dim[1]) + dim_x, dim_y = int(dim[0]), int(dim[1])# pylint: disable=unsubscriptable-object # In certain situations, we don't need semidefinite programming. if level == 1 or len_mat <= 6 and ppt: if not ppt: diff --git a/toqito/state_props/is_ppt.py b/toqito/state_props/is_ppt.py index cd4502436..9e72214d8 100644 --- a/toqito/state_props/is_ppt.py +++ b/toqito/state_props/is_ppt.py @@ -83,7 +83,7 @@ def is_ppt(mat: np.ndarray, sys: int = 2, dim: int | list[int] = None, tol: floa sqrt_rho_dims = np.int_(sqrt_rho_dims) if dim is None: - dim = [[sqrt_rho_dims[0], sqrt_rho_dims[0]], [sqrt_rho_dims[1], sqrt_rho_dims[1]]] + dim = [[sqrt_rho_dims[0], sqrt_rho_dims[0]], [sqrt_rho_dims[1], sqrt_rho_dims[1]]]# pylint: disable=unsubscriptable-object if tol is None: tol = np.sqrt(eps) return is_positive_semidefinite(partial_transpose(mat, [sys - 1], dim), tol) From 8d59bbdb5e1019ff11b8375982bc0ff7837d2eae Mon Sep 17 00:00:00 2001 From: Purva Thakre Date: Sun, 29 Oct 2023 17:45:46 -0500 Subject: [PATCH 16/24] possibly unbalanced tuples --- toqito/matrix_props/sk_norm.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/toqito/matrix_props/sk_norm.py b/toqito/matrix_props/sk_norm.py index 661a5a6f7..a39271b3f 100644 --- a/toqito/matrix_props/sk_norm.py +++ b/toqito/matrix_props/sk_norm.py @@ -253,7 +253,7 @@ def sk_operator_norm( # pylint: disable=too-many-locals elif k == 1: # we can also get decent lower bounds from the SDP results when k=1 # See Theorem 5.2.8 of [2] - roots, _ = scipy.special.roots_jacobi(1, dim[1] - 2, 1) + roots, _ = scipy.special.roots_jacobi(1, dim[1] - 2, 1)# pylint: disable=unbalanced-tuple-unpacking gs = min(1 - roots) xmineig = min(eig_val) lower_bound = max( @@ -294,7 +294,7 @@ def sk_operator_norm( # pylint: disable=too-many-locals upper_bound = min(upper_bound, np.real(cvx_optval)) - roots, _ = scipy.special.roots_jacobi(np.floor(j / 2) + 1, dim[1] - 2, j % 2) + roots, _ = scipy.special.roots_jacobi(np.floor(j / 2) + 1, dim[1] - 2, j % 2)# pylint: disable=unbalanced-tuple-unpacking gs = min(1 - roots) lower_bound = max( lower_bound, From a2126cb2dd635fe7e5962bc8ba258772b820e76c Mon Sep 17 00:00:00 2001 From: Purva Thakre Date: Sun, 29 Oct 2023 17:56:19 -0500 Subject: [PATCH 17/24] unnecessary-list-index-lookup --- toqito/state_opt/ppt_distinguishability.py | 8 ++++---- toqito/state_opt/state_distinguishability.py | 4 ++-- toqito/state_opt/symmetric_extension_hierarchy.py | 4 ++-- toqito/state_props/is_mutually_unbiased_basis.py | 6 +++--- 4 files changed, 11 insertions(+), 11 deletions(-) diff --git a/toqito/state_opt/ppt_distinguishability.py b/toqito/state_opt/ppt_distinguishability.py index 0d45794cb..7e7b97e45 100644 --- a/toqito/state_opt/ppt_distinguishability.py +++ b/toqito/state_opt/ppt_distinguishability.py @@ -191,8 +191,8 @@ def primal_problem( meas.append(cvxpy.Variable((dim_x, dim_x), PSD=True)) constraints.append(partial_transpose(meas[i], sys_list, dim_list) >> 0) - for i, _ in enumerate(states): - obj_func.append(probs[i] * cvxpy.trace(states[i].conj().T @ meas[i])) + for i, item in enumerate(states): + obj_func.append(probs[i] * cvxpy.trace(item.conj().T @ meas[i])) constraints.append(sum(meas) == np.identity(dim_x)) @@ -262,10 +262,10 @@ def dual_problem( # dim_list = [3, 3] if dist_method == "min-error": - for i, _ in enumerate(states): + for i, item in enumerate(states): meas.append(cvxpy.Variable((dim_x, dim_x), PSD=True)) constraints.append( - cvxpy.real(y_var - probs[i] * states[i]) + cvxpy.real(y_var - probs[i] * item) >> partial_transpose(meas[i], sys=sys_list, dim=dim_list) ) diff --git a/toqito/state_opt/state_distinguishability.py b/toqito/state_opt/state_distinguishability.py index f940e85d1..1d1c04720 100644 --- a/toqito/state_opt/state_distinguishability.py +++ b/toqito/state_opt/state_distinguishability.py @@ -120,8 +120,8 @@ def state_distinguishability( measurements.append(cvxpy.Variable((dim_x, dim_x), PSD=True)) # Objective function is the inner product between the states and measurements. - for i, _ in enumerate(states): - obj_func.append(probs[i] * cvxpy.trace(states[i].conj().T @ measurements[i])) + for i, item in enumerate(states): + obj_func.append(probs[i] * cvxpy.trace(item.conj().T @ measurements[i])) constraints.append(sum(measurements) == np.identity(dim_x)) diff --git a/toqito/state_opt/symmetric_extension_hierarchy.py b/toqito/state_opt/symmetric_extension_hierarchy.py index e4bfa8a96..65e23e890 100644 --- a/toqito/state_opt/symmetric_extension_hierarchy.py +++ b/toqito/state_opt/symmetric_extension_hierarchy.py @@ -184,7 +184,7 @@ def symmetric_extension_hierarchy( sym = symmetric_projection(dim_y, level) dim_xyy = np.prod(dim_list) - for k, _ in enumerate(states): + for k, item in enumerate(states): meas.append(cvxpy.Variable((dim_xy, dim_xy), PSD=True)) x_var.append(cvxpy.Variable((dim_xyy, dim_xyy), PSD=True)) constraints.append(partial_trace(x_var[k], sys_list, dim_list) == meas[k]) @@ -196,7 +196,7 @@ def symmetric_extension_hierarchy( for sys in range(level - 1): constraints.append(partial_transpose(x_var[k], [sys + 2], dim_list) >> 0) - obj_func.append(probs[k] * cvxpy.trace(states[k].conj().T @ meas[k])) + obj_func.append(probs[k] * cvxpy.trace(item.conj().T @ meas[k])) constraints.append(sum(meas) == np.identity(dim_xy)) diff --git a/toqito/state_props/is_mutually_unbiased_basis.py b/toqito/state_props/is_mutually_unbiased_basis.py index ac0859ac3..6f571b6be 100644 --- a/toqito/state_props/is_mutually_unbiased_basis.py +++ b/toqito/state_props/is_mutually_unbiased_basis.py @@ -84,12 +84,12 @@ def is_mutually_unbiased_basis(vec_list: list[np.ndarray | list[float | Any]]) - raise ValueError("There must be at least two bases provided as input.") dim = vec_list[0][0].shape[0] - for i, _ in enumerate(vec_list): - for j, _ in enumerate(vec_list): + for i, item in enumerate(vec_list): + for j, item2 in enumerate(vec_list): for k in range(dim): if i != j: if not np.isclose( - np.abs(np.inner(vec_list[i][k].conj().T[0], vec_list[j][k].conj().T[0])) + np.abs(np.inner(item[k].conj().T[0], item2[k].conj().T[0])) ** 2, 1 / dim, ): From f7e81652c1d0587360e274841b7c1719dcafe949 Mon Sep 17 00:00:00 2001 From: Purva Thakre Date: Mon, 30 Oct 2023 10:35:05 -0500 Subject: [PATCH 18/24] black reformatter no pylint issues --- .../fidelity_of_separability.py | 6 +++++- toqito/channels/partial_trace.py | 6 ++---- toqito/channels/partial_transpose.py | 1 - toqito/channels/realignment.py | 2 +- toqito/helper/npa_hierarchy.py | 2 +- toqito/matrices/gell_mann.py | 2 +- toqito/matrices/pauli.py | 2 +- toqito/matrix_ops/vectors_from_gram_matrix.py | 4 ++-- toqito/matrix_props/is_block_positive.py | 2 +- toqito/matrix_props/is_positive_definite.py | 2 +- toqito/nonlocal_games/xor_game.py | 5 +++-- toqito/perms/permute_systems.py | 2 +- toqito/perms/swap.py | 2 +- toqito/random/random_povm.py | 4 +++- .../state_metrics/fidelity_of_separability.py | 19 ++++++++++--------- toqito/state_opt/optimal_clone.py | 2 +- toqito/state_opt/ppt_distinguishability.py | 4 ++-- toqito/state_opt/state_exclusion.py | 7 +++++-- .../symmetric_extension_hierarchy.py | 4 ++-- toqito/state_props/has_symmetric_extension.py | 4 ++-- .../state_props/is_mutually_unbiased_basis.py | 3 +-- toqito/state_props/is_product.py | 2 +- toqito/state_props/is_separable.py | 6 +++--- toqito/state_props/schmidt_rank.py | 2 +- toqito/state_props/sk_vec_norm.py | 2 +- 25 files changed, 52 insertions(+), 45 deletions(-) diff --git a/toqito/channel_metrics/fidelity_of_separability.py b/toqito/channel_metrics/fidelity_of_separability.py index efd48c697..33660ed7b 100644 --- a/toqito/channel_metrics/fidelity_of_separability.py +++ b/toqito/channel_metrics/fidelity_of_separability.py @@ -14,7 +14,11 @@ def fidelity_of_separability( - psi: np.ndarray, psi_dims: list[int], k: int = 1, verbosity_option: int=2, solver_option: str="cvxopt" + psi: np.ndarray, + psi_dims: list[int], + k: int = 1, + verbosity_option: int = 2, + solver_option: str = "cvxopt", ) -> float: r""" Define the first benchmark introduced in Appendix I of [Phil23.1]_ . diff --git a/toqito/channels/partial_trace.py b/toqito/channels/partial_trace.py index 3b7e21a82..162b84ceb 100644 --- a/toqito/channels/partial_trace.py +++ b/toqito/channels/partial_trace.py @@ -148,8 +148,6 @@ def partial_trace( if isinstance(dim, list): dim = np.array(dim) - - # Allow the user to enter a single number for dim. if (num_sys := len(dim)) == 1: dim = np.array([dim[0], len(input_mat) / dim[0]]) @@ -169,7 +167,7 @@ def partial_trace( for idx in sys: prod_dim_sys *= dim[idx] elif isinstance(sys, int): - prod_dim_sys = np.prod(dim[sys])# pylint: disable=redefined-variable-type + prod_dim_sys = np.prod(dim[sys]) # pylint: disable=redefined-variable-type else: raise ValueError( "Invalid: The variable `sys` must either be of type int or of a list of ints." @@ -179,7 +177,7 @@ def partial_trace( sub_sys_vec = prod_dim * np.ones(int(sub_prod)) / sub_prod if isinstance(sys, list): - sys = np.array(sys)# pylint: disable=redefined-variable-type + sys = np.array(sys) # pylint: disable=redefined-variable-type if isinstance(sys, int): sys = np.array([sys]) set_diff = list(set(list(range(1, num_sys + 1))) - set(sys + 1)) diff --git a/toqito/channels/partial_transpose.py b/toqito/channels/partial_transpose.py index c3b6e991e..d9b217aee 100644 --- a/toqito/channels/partial_transpose.py +++ b/toqito/channels/partial_transpose.py @@ -135,7 +135,6 @@ def partial_transpose( if isinstance(sys, int): sys = np.array([sys]) - # Allow the user to enter a single number for dim. if (num_sys := max(dim.shape)) == 1: dim = np.array([dim, list(rho.shape)[0] / dim]) diff --git a/toqito/channels/realignment.py b/toqito/channels/realignment.py index 6e3999240..be8f9d71a 100644 --- a/toqito/channels/realignment.py +++ b/toqito/channels/realignment.py @@ -79,7 +79,7 @@ def realignment(input_mat: np.ndarray, dim: int | list[int] = None) -> np.ndarra dim = np.array([dim, dim]) dim_x = np.array([[dim[0][1], dim[0][0]], [dim[1][0], dim[1][1]]]) - dim_x = np.int_(dim_x)# pylint: disable=redefined-variable-type + dim_x = np.int_(dim_x) # pylint: disable=redefined-variable-type dim_y = np.array([[dim[1][0], dim[0][0]], [dim[0][1], dim[1][1]]]) x_tmp = swap(input_mat, [1, 2], dim, True) diff --git a/toqito/helper/npa_hierarchy.py b/toqito/helper/npa_hierarchy.py index aa8f43d30..d2c010c3a 100644 --- a/toqito/helper/npa_hierarchy.py +++ b/toqito/helper/npa_hierarchy.py @@ -124,7 +124,7 @@ def _get_nonlocal_game_params( return a_out, a_in, b_out, b_in -def npa_constraints(# pylint: disable=too-many-locals +def npa_constraints( # pylint: disable=too-many-locals assemblage: dict[tuple[int, int], cvxpy.Variable], k: int | str = 1, referee_dim: int = 1 ) -> list[cvxpy.constraints.constraint.Constraint]: r""" diff --git a/toqito/matrices/gell_mann.py b/toqito/matrices/gell_mann.py index c4513f3c8..f3e796f20 100644 --- a/toqito/matrices/gell_mann.py +++ b/toqito/matrices/gell_mann.py @@ -117,6 +117,6 @@ def gell_mann(ind: int, is_sparse: bool = False) -> np.ndarray | scipy.sparse.cs raise ValueError("Gell-Mann index values can only be values from 0 to 8 (inclusive).") if is_sparse: - gm_op = scipy.sparse.csr_matrix(gm_op)# pylint: disable=redefined-variable-type + gm_op = scipy.sparse.csr_matrix(gm_op) # pylint: disable=redefined-variable-type return gm_op diff --git a/toqito/matrices/pauli.py b/toqito/matrices/pauli.py index 0fb6a0023..9c7017201 100644 --- a/toqito/matrices/pauli.py +++ b/toqito/matrices/pauli.py @@ -97,7 +97,7 @@ def pauli( pauli_mat = np.identity(2) if is_sparse: - pauli_mat = sparse.csr_matrix(pauli_mat)# pylint: disable=redefined-variable-type + pauli_mat = sparse.csr_matrix(pauli_mat) # pylint: disable=redefined-variable-type return pauli_mat diff --git a/toqito/matrix_ops/vectors_from_gram_matrix.py b/toqito/matrix_ops/vectors_from_gram_matrix.py index bf296cb94..1abfd2743 100644 --- a/toqito/matrix_ops/vectors_from_gram_matrix.py +++ b/toqito/matrix_ops/vectors_from_gram_matrix.py @@ -4,7 +4,7 @@ def vectors_from_gram_matrix(gram: np.ndarray) -> list[np.ndarray]: """Obtain the corresponding ensemble of states from the Gram matrix. - + :param gram: Input Gram matrix. :return: list of ensemble states """ @@ -14,7 +14,7 @@ def vectors_from_gram_matrix(gram: np.ndarray) -> list[np.ndarray]: decomp = np.linalg.cholesky(gram) return [decomp[i][:] for i in range(dim)] # Otherwise, need to do eigendecomposition: - except Exception: # pylint: disable=broad-except + except Exception: # pylint: disable=broad-except print("Matrix is not positive semidefinite. Using eigendecomposition as alternative.") d, v = np.linalg.eig(gram) return [np.sqrt(np.diag(d)) @ v[i].conj().T for i in range(dim)] diff --git a/toqito/matrix_props/is_block_positive.py b/toqito/matrix_props/is_block_positive.py index 156574dc3..d88f27657 100644 --- a/toqito/matrix_props/is_block_positive.py +++ b/toqito/matrix_props/is_block_positive.py @@ -68,7 +68,7 @@ def is_block_positive( # Allow the user to enter in a single integer for dimension. if isinstance(dim, int): - dim = np.array([dim, dim_xy / dim])# pylint: disable=redefined-variable-type + dim = np.array([dim, dim_xy / dim]) # pylint: disable=redefined-variable-type if np.abs(dim[1] - np.round(dim[1])) >= 2 * dim_xy * np.finfo(float).eps: raise ValueError( "If `dim` is a scalar, it must evenly divide the length of the matrix." diff --git a/toqito/matrix_props/is_positive_definite.py b/toqito/matrix_props/is_positive_definite.py index 4ed5b181c..48f7fd46c 100644 --- a/toqito/matrix_props/is_positive_definite.py +++ b/toqito/matrix_props/is_positive_definite.py @@ -1,7 +1,7 @@ """Is matrix a positive definite matrix.""" import numpy as np -from toqito.matrix_props import is_hermitian # pylint: disable=unused-import +from toqito.matrix_props import is_hermitian # pylint: disable=unused-import def is_positive_definite(mat: np.ndarray) -> bool: diff --git a/toqito/nonlocal_games/xor_game.py b/toqito/nonlocal_games/xor_game.py index 4253a145b..eea9999ed 100644 --- a/toqito/nonlocal_games/xor_game.py +++ b/toqito/nonlocal_games/xor_game.py @@ -211,8 +211,9 @@ def quantum_value(self) -> float: for x_alice in range(alice_in): for y_bob in range(bob_in): - d_mat[x_alice, y_bob] = self.prob_mat[x_alice, y_bob] * \ - (-1) ** (self.pred_mat[x_alice, y_bob]) + d_mat[x_alice, y_bob] = self.prob_mat[x_alice, y_bob] * (-1) ** ( + self.pred_mat[x_alice, y_bob] + ) u_vec = cvxpy.Variable(alice_in, complex=False) v_vec = cvxpy.Variable(bob_in, complex=False) diff --git a/toqito/perms/permute_systems.py b/toqito/perms/permute_systems.py index f2f3937be..4b23acfbc 100644 --- a/toqito/perms/permute_systems.py +++ b/toqito/perms/permute_systems.py @@ -209,7 +209,7 @@ def permute_systems( # If the dimensions are specified, ensure they are given to the # recursive calls as flattened lists. if len(dim[0][:]) == 1: - dim = functools.reduce(operator.iconcat, dim, [])# pylint: disable=redefined-variable-type + dim = functools.reduce(operator.iconcat, dim, []) # pylint: disable=redefined-variable-type row_perm = permute_systems(vec_arg, perm, dim[0][:], False, inv_perm) diff --git a/toqito/perms/swap.py b/toqito/perms/swap.py index c2a3f46d3..a504355ae 100644 --- a/toqito/perms/swap.py +++ b/toqito/perms/swap.py @@ -157,7 +157,7 @@ def swap( # Swap the indicated subsystems. perm = np.array(range(1, num_sys + 1)) - sys = np.array(sys) - 1# pylint: disable=redefined-variable-type + sys = np.array(sys) - 1 # pylint: disable=redefined-variable-type perm[sys] = perm[sys[::-1]] diff --git a/toqito/random/random_povm.py b/toqito/random/random_povm.py index 97a83272d..95c51edaf 100644 --- a/toqito/random/random_povm.py +++ b/toqito/random/random_povm.py @@ -49,7 +49,9 @@ def random_povm(dim: int, num_inputs: int, num_outputs: int) -> np.ndarray: povms = [] gram_vectors = np.random.normal(size=(num_inputs, num_outputs, dim, dim)) for input_block in gram_vectors: - normalizer = sum(np.array(output_block).T.conj() @ output_block for output_block in input_block) + normalizer = sum( + np.array(output_block).T.conj() @ output_block for output_block in input_block + ) u_mat, d_mat, _ = np.linalg.svd(normalizer) output_povms = [] diff --git a/toqito/state_metrics/fidelity_of_separability.py b/toqito/state_metrics/fidelity_of_separability.py index 66e4fb334..f07f284cf 100644 --- a/toqito/state_metrics/fidelity_of_separability.py +++ b/toqito/state_metrics/fidelity_of_separability.py @@ -16,8 +16,8 @@ def fidelity_of_separability( input_state_rho: np.ndarray, input_state_rho_dims: list[int], k: int = 1, - verbosity_option: int=2, - solver_option: str ="cvxopt", + verbosity_option: int = 2, + solver_option: str = "cvxopt", ) -> float: r""" Define the first benchmark introduced in Appendix H of [Phil23]_. @@ -153,13 +153,13 @@ def fidelity_of_separability( # Infer the dimension of Alice and Bob's system. # subsystem-dimensions in rho_AB - dim_A, dim_B = input_state_rho_dims # pylint: disable-msg=invalid-name + dim_A, dim_B = input_state_rho_dims # pylint: disable-msg=invalid-name # Extend the number of dimensions based on the level `k`. # new dims for AB with k-extendibility in subsystem B - dim_direct_sum_AB_k = [dim_A] + [dim_B] * (k) # pylint: disable-msg=invalid-name + dim_direct_sum_AB_k = [dim_A] + [dim_B] * (k) # pylint: disable-msg=invalid-name # new dims for a linear op acting on the space of sigma_AB_k - dim_op_sigma_AB_k = dim_A * dim_B**k # pylint: disable-msg=invalid-name + dim_op_sigma_AB_k = dim_A * dim_B**k # pylint: disable-msg=invalid-name # A list of the symmetrically extended subsystems based on the level `k`. sub_sys_ext = list(range(2, 2 + k - 1)) @@ -169,10 +169,11 @@ def fidelity_of_separability( # defining the problem objective: Re[Tr[X_AB]] problem = picos.Problem(verbosity=verbosity_option) linear_op_AB = picos.ComplexVariable( # pylint: disable-msg=invalid-name - "x_AB", input_state_rho.shape) - sigma_AB_k = picos.HermitianVariable( # pylint: disable-msg=invalid-name - "s_AB_k", ( - dim_op_sigma_AB_k, dim_op_sigma_AB_k)) + "x_AB", input_state_rho.shape + ) + sigma_AB_k = picos.HermitianVariable( # pylint: disable-msg=invalid-name + "s_AB_k", (dim_op_sigma_AB_k, dim_op_sigma_AB_k) + ) problem.set_objective("max", 0.5 * picos.trace(linear_op_AB + linear_op_AB.H)) diff --git a/toqito/state_opt/optimal_clone.py b/toqito/state_opt/optimal_clone.py index 98199b6ca..2c419e981 100644 --- a/toqito/state_opt/optimal_clone.py +++ b/toqito/state_opt/optimal_clone.py @@ -133,7 +133,7 @@ def optimal_clone( else: # The permutation vector `perm` contains elements of the # sequence from: https://oeis.org/A023123 - q_a = tensor(q_a, num_reps)# pylint: disable=redefined-variable-type + q_a = tensor(q_a, num_reps) # pylint: disable=redefined-variable-type perm = [] for i in range(1, num_spaces + 1): perm.append(i) diff --git a/toqito/state_opt/ppt_distinguishability.py b/toqito/state_opt/ppt_distinguishability.py index 7e7b97e45..f67bc9303 100644 --- a/toqito/state_opt/ppt_distinguishability.py +++ b/toqito/state_opt/ppt_distinguishability.py @@ -125,7 +125,7 @@ def ppt_distinguishability( def primal_problem( - states: list[np.ndarray], probs: list[float] = None, dist_method: str="min-error" + states: list[np.ndarray], probs: list[float] = None, dist_method: str = "min-error" ) -> float: r""" Calculate primal problem for PPT distinguishability. @@ -204,7 +204,7 @@ def primal_problem( def dual_problem( - states: list[np.ndarray], probs: list[float] = None, dist_method: str="min-error" + states: list[np.ndarray], probs: list[float] = None, dist_method: str = "min-error" ) -> float: r""" Calculate dual problem for PPT distinguishability. diff --git a/toqito/state_opt/state_exclusion.py b/toqito/state_opt/state_exclusion.py index 648c6b333..ce1d8f008 100644 --- a/toqito/state_opt/state_exclusion.py +++ b/toqito/state_opt/state_exclusion.py @@ -6,7 +6,10 @@ def state_exclusion( - vectors: list[np.ndarray], probs: list[float] = None, solver: str = "cvxopt", primal_dual: str ="dual" + vectors: list[np.ndarray], + probs: list[float] = None, + solver: str = "cvxopt", + primal_dual: str = "dual", ) -> tuple[float, list[picos.HermitianVariable]]: r""" Compute probability of single state exclusion. @@ -97,7 +100,7 @@ def state_exclusion( """ if primal_dual == "primal": return _min_error_primal(vectors, probs, solver) - + return _min_error_dual(vectors, probs, solver) diff --git a/toqito/state_opt/symmetric_extension_hierarchy.py b/toqito/state_opt/symmetric_extension_hierarchy.py index 65e23e890..0d0937950 100644 --- a/toqito/state_opt/symmetric_extension_hierarchy.py +++ b/toqito/state_opt/symmetric_extension_hierarchy.py @@ -169,7 +169,7 @@ def symmetric_extension_hierarchy( # Allow the user to enter in a single integer for dimension. if isinstance(dim, int): - dim = np.array([dim, dim_xy / dim])# pylint: disable=redefined-variable-type + dim = np.array([dim, dim_xy / dim]) # pylint: disable=redefined-variable-type if np.abs(dim[1] - np.round(dim[1])) >= 2 * dim_xy * np.finfo(float).eps: raise ValueError("If `dim` is a scalar, it must evenly divide the length of the state.") dim[1] = int(np.round(dim[1])) @@ -177,7 +177,7 @@ def symmetric_extension_hierarchy( dim_x, dim_y = int(dim[0]), int(dim[1]) dim_list = [dim_x] + [dim_y] * level - dim_list = np.int_(dim_list)# pylint: disable=redefined-variable-type + dim_list = np.int_(dim_list) # pylint: disable=redefined-variable-type # The `sys_list` variable contains the numbering pertaining to the symmetrically extended # spaces. sys_list = list(range(2, 2 + level - 1)) diff --git a/toqito/state_props/has_symmetric_extension.py b/toqito/state_props/has_symmetric_extension.py index a99846fff..e66a20d24 100644 --- a/toqito/state_props/has_symmetric_extension.py +++ b/toqito/state_props/has_symmetric_extension.py @@ -108,7 +108,7 @@ def has_symmetric_extension( # Allow the user to enter in a single integer for dimension. if isinstance(dim, int): - dim = np.array([dim, len_mat / dim])# pylint: disable=redefined-variable-type + dim = np.array([dim, len_mat / dim]) # pylint: disable=redefined-variable-type if np.abs(dim[1] - np.round(dim[1])) >= 2 * len_mat * np.finfo(float).eps: raise ValueError( "If `dim` is a scalar, it must evenly divide the length of the matrix." @@ -117,7 +117,7 @@ def has_symmetric_extension( dim = np.int_(dim) - dim_x, dim_y = int(dim[0]), int(dim[1])# pylint: disable=unsubscriptable-object + dim_x, dim_y = int(dim[0]), int(dim[1]) # pylint: disable=unsubscriptable-object # In certain situations, we don't need semidefinite programming. if level == 1 or len_mat <= 6 and ppt: if not ppt: diff --git a/toqito/state_props/is_mutually_unbiased_basis.py b/toqito/state_props/is_mutually_unbiased_basis.py index 6f571b6be..e705c9c94 100644 --- a/toqito/state_props/is_mutually_unbiased_basis.py +++ b/toqito/state_props/is_mutually_unbiased_basis.py @@ -89,8 +89,7 @@ def is_mutually_unbiased_basis(vec_list: list[np.ndarray | list[float | Any]]) - for k in range(dim): if i != j: if not np.isclose( - np.abs(np.inner(item[k].conj().T[0], item2[k].conj().T[0])) - ** 2, + np.abs(np.inner(item[k].conj().T[0], item2[k].conj().T[0])) ** 2, 1 / dim, ): return False diff --git a/toqito/state_props/is_product.py b/toqito/state_props/is_product.py index 0aeb2257d..c2c0a09ee 100644 --- a/toqito/state_props/is_product.py +++ b/toqito/state_props/is_product.py @@ -91,7 +91,7 @@ def _is_product(rho: np.ndarray, dim: int | list[int] = None) -> list[int, bool] # Provide this even if not requested, since it is needed if this # function was called as part of its recursive algorithm (see below) - if (ipv := singular_vals[1] <= np.prod(dim) * np.spacing(singular_vals[0])): + if ipv := singular_vals[1] <= np.prod(dim) * np.spacing(singular_vals[0]): u_mat = u_mat * np.sqrt(singular_vals[0]) vt_mat = vt_mat * np.sqrt(singular_vals[0]) dec = [u_mat[:, 0], vt_mat[:, 0]] diff --git a/toqito/state_props/is_separable.py b/toqito/state_props/is_separable.py index 716e6052e..e669a674f 100644 --- a/toqito/state_props/is_separable.py +++ b/toqito/state_props/is_separable.py @@ -76,7 +76,7 @@ def is_separable( dim = int(np.round(np.sqrt(state_len))) if isinstance(dim, int): - dim = np.array([dim, state_len / dim])# pylint: disable=redefined-variable-type + dim = np.array([dim, state_len / dim]) # pylint: disable=redefined-variable-type if np.abs(dim[1] - np.round(dim[1])) >= 2 * state_len * eps: raise ValueError("The parameter `dim` must evenly divide the length of the state.") dim[1] = np.round(dim[1]) @@ -161,9 +161,9 @@ def is_separable( # For the rest of the block-matrix tests, we need the 2-dimensional subsystem to be the # first subsystem, so swap accordingly. - #if dim[0] > 2: + # if dim[0] > 2: # Xt = swap(state, [1, 2], dim) - #else: + # else: # Xt = state # commented out because pylint flagged this as an unused variable diff --git a/toqito/state_props/schmidt_rank.py b/toqito/state_props/schmidt_rank.py index 5e36e1110..21a4cbcb4 100644 --- a/toqito/state_props/schmidt_rank.py +++ b/toqito/state_props/schmidt_rank.py @@ -92,7 +92,7 @@ def schmidt_rank(rho: np.ndarray, dim: int | list[int] | np.ndarray = None) -> f if dim is None: dim = slv if isinstance(dim, int): - dim = np.array([dim, len(rho) / dim], dtype=int)# pylint: disable=redefined-variable-type + dim = np.array([dim, len(rho) / dim], dtype=int) # pylint: disable=redefined-variable-type dim[1] = np.round(dim[1]) return np.linalg.matrix_rank(np.reshape(rho, dim[::-1])) diff --git a/toqito/state_props/sk_vec_norm.py b/toqito/state_props/sk_vec_norm.py index e59fc874a..a79b1e580 100644 --- a/toqito/state_props/sk_vec_norm.py +++ b/toqito/state_props/sk_vec_norm.py @@ -59,7 +59,7 @@ def sk_vector_norm(rho: np.ndarray, k: int = 1, dim: int | list[int] = None) -> # Allow the user to enter in a single integer for dimension. if isinstance(dim, int): - dim = np.array([dim, dim_xy / dim])# pylint: disable=redefined-variable-type + dim = np.array([dim, dim_xy / dim]) # pylint: disable=redefined-variable-type if np.abs(dim[1] - np.round(dim[1])) >= 2 * dim_xy * np.finfo(float).eps: raise ValueError("If `dim` is a scalar, it must evenly divide the length of the state.") dim[1] = int(np.round(dim[1])) From 3e67401fa4463c46f6d2a8ed1b5a5420584da6c6 Mon Sep 17 00:00:00 2001 From: Purva Thakre Date: Mon, 30 Oct 2023 10:42:11 -0500 Subject: [PATCH 19/24] black reformatter pylint issues --- toqito/matrix_props/sk_norm.py | 18 +++++++++++------- toqito/nonlocal_games/nonlocal_game.py | 4 +++- .../state_props/entanglement_of_formation.py | 6 ++++-- toqito/state_props/is_ppt.py | 5 ++++- 4 files changed, 22 insertions(+), 11 deletions(-) diff --git a/toqito/matrix_props/sk_norm.py b/toqito/matrix_props/sk_norm.py index a39271b3f..297b82664 100644 --- a/toqito/matrix_props/sk_norm.py +++ b/toqito/matrix_props/sk_norm.py @@ -17,7 +17,7 @@ from toqito.states import max_entangled -def sk_operator_norm( # pylint: disable=too-many-locals +def sk_operator_norm( # pylint: disable=too-many-locals mat: np.ndarray, k: int = 1, dim: int | list[int] = None, @@ -93,7 +93,7 @@ def sk_operator_norm( # pylint: disable=too-many-locals # Allow the user to enter in a single integer for dimension. if isinstance(dim, int): - dim = np.array([dim, dim_xy / dim])# pylint: disable=redefined-variable-type + dim = np.array([dim, dim_xy / dim]) # pylint: disable=redefined-variable-type if np.abs(dim[1] - np.round(dim[1])) >= 2 * dim_xy * np.finfo(float).eps: raise ValueError( "If `dim` is a scalar, it must evenly divide the length of the matrix." @@ -132,7 +132,7 @@ def sk_operator_norm( # pylint: disable=too-many-locals # comes from Theorem 4.13 in [1] lower_bound = k / min(dim) # our most basic upper bound - upper_bound = 1# pylint: disable=redefined-variable-type + upper_bound = 1 # pylint: disable=redefined-variable-type # break out of the function if the target value has already been met if __target_is_proved(lower_bound, upper_bound, op_norm, tol, target): @@ -227,7 +227,7 @@ def sk_operator_norm( # pylint: disable=too-many-locals return op_norm * lower_bound, op_norm * upper_bound # Start the semidefinite programming approach for getting upper bounds. - if effort >= 1 and (# pylint: disable=too-many-boolean-expressions + if effort >= 1 and ( # pylint: disable=too-many-boolean-expressions (lower_bound + tol < upper_bound and is_positive) or (is_positive and is_trans_exact and k == 1) ): @@ -253,7 +253,9 @@ def sk_operator_norm( # pylint: disable=too-many-locals elif k == 1: # we can also get decent lower bounds from the SDP results when k=1 # See Theorem 5.2.8 of [2] - roots, _ = scipy.special.roots_jacobi(1, dim[1] - 2, 1)# pylint: disable=unbalanced-tuple-unpacking + roots, _ = scipy.special.roots_jacobi( # pylint: disable=unbalanced-tuple-unpacking + 1, dim[1] - 2, 1 + ) gs = min(1 - roots) xmineig = min(eig_val) lower_bound = max( @@ -294,7 +296,9 @@ def sk_operator_norm( # pylint: disable=too-many-locals upper_bound = min(upper_bound, np.real(cvx_optval)) - roots, _ = scipy.special.roots_jacobi(np.floor(j / 2) + 1, dim[1] - 2, j % 2)# pylint: disable=unbalanced-tuple-unpacking + roots, _ = scipy.special.roots_jacobi( # pylint: disable=unbalanced-tuple-unpacking + np.floor(j / 2) + 1, dim[1] - 2, j % 2 + ) gs = min(1 - roots) lower_bound = max( lower_bound, @@ -328,7 +332,7 @@ def __target_is_proved( # Schmidt vectors of the other sub-system. This optimization is equivalent to # a generalized eigenvalue problem. The algorithm terminates when an iteration # cannot improve the lower bound by more than tol. -def __lower_bound_sk_norm_randomized(# pylint: disable=too-many-locals +def __lower_bound_sk_norm_randomized( # pylint: disable=too-many-locals mat: np.ndarray, k: int = 1, dim: int | list[int] = None, diff --git a/toqito/nonlocal_games/nonlocal_game.py b/toqito/nonlocal_games/nonlocal_game.py index abb95876f..b2980cfe7 100644 --- a/toqito/nonlocal_games/nonlocal_game.py +++ b/toqito/nonlocal_games/nonlocal_game.py @@ -122,7 +122,9 @@ def from_bcs_game(cls, constraints: list[np.ndarray], reps: int = 1) -> "Nonloca bin_a = [int(x) for x in np.binary_repr(a_ans)] truth_assignment = np.zeros(num_variables, dtype=np.int8) truth_assignment[-len(bin_a) :] = bin_a - truth_assignment = tuple(truth_assignment)# pylint: disable=redefined-variable-type + truth_assignment = tuple( # pylint: disable=redefined-variable-type + truth_assignment + ) for y_ques in range(num_variables): # The verifier can only accept the answer if Bob's truth assignment diff --git a/toqito/state_props/entanglement_of_formation.py b/toqito/state_props/entanglement_of_formation.py index a4764574e..585ed9572 100644 --- a/toqito/state_props/entanglement_of_formation.py +++ b/toqito/state_props/entanglement_of_formation.py @@ -63,8 +63,10 @@ def entanglement_of_formation(rho: np.ndarray, dim: list[int] | int = None) -> f dim = round_dim # User can specify dimension as integer. - if isinstance(dim, int): - dim = np.array([dim, max(dim_x, dim_y) / dim], dtype=int) # pylint: disable=redefined-variable-type + if isinstance(dim, int): + dim = np.array( # pylint: disable=redefined-variable-type + [dim, max(dim_x, dim_y) / dim], dtype=int + ) if abs(dim[1] - np.round(dim[1])) >= 2 * max(dim_x, dim_y) * eps: raise ValueError( "Invalid dimension: If `dim` is provided as a " diff --git a/toqito/state_props/is_ppt.py b/toqito/state_props/is_ppt.py index 9e72214d8..f0154a0a0 100644 --- a/toqito/state_props/is_ppt.py +++ b/toqito/state_props/is_ppt.py @@ -83,7 +83,10 @@ def is_ppt(mat: np.ndarray, sys: int = 2, dim: int | list[int] = None, tol: floa sqrt_rho_dims = np.int_(sqrt_rho_dims) if dim is None: - dim = [[sqrt_rho_dims[0], sqrt_rho_dims[0]], [sqrt_rho_dims[1], sqrt_rho_dims[1]]]# pylint: disable=unsubscriptable-object + dim = [ + [sqrt_rho_dims[0], sqrt_rho_dims[0]], # pylint: disable=unsubscriptable-object + [sqrt_rho_dims[1], sqrt_rho_dims[1]], # pylint: disable=unsubscriptable-object + ] if tol is None: tol = np.sqrt(eps) return is_positive_semidefinite(partial_transpose(mat, [sys - 1], dim), tol) From a07e2146c4efff4535e6cab63073d56d125624a8 Mon Sep 17 00:00:00 2001 From: Purva Thakre Date: Mon, 30 Oct 2023 11:28:13 -0500 Subject: [PATCH 20/24] test useless supression --- toqito/matrices/gell_mann.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/toqito/matrices/gell_mann.py b/toqito/matrices/gell_mann.py index f3e796f20..18eff9228 100644 --- a/toqito/matrices/gell_mann.py +++ b/toqito/matrices/gell_mann.py @@ -117,6 +117,6 @@ def gell_mann(ind: int, is_sparse: bool = False) -> np.ndarray | scipy.sparse.cs raise ValueError("Gell-Mann index values can only be values from 0 to 8 (inclusive).") if is_sparse: - gm_op = scipy.sparse.csr_matrix(gm_op) # pylint: disable=redefined-variable-type + gm_op = scipy.sparse.csr_matrix(gm_op) return gm_op From 9fed2601929fe8f9921e9e47a7707287970d419e Mon Sep 17 00:00:00 2001 From: Purva Thakre Date: Mon, 30 Oct 2023 13:49:27 -0500 Subject: [PATCH 21/24] Fixes https://github.com/vprusso/toqito/pull/205#discussion_r1376353634 --- toqito/matrix_ops/vectors_from_gram_matrix.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/toqito/matrix_ops/vectors_from_gram_matrix.py b/toqito/matrix_ops/vectors_from_gram_matrix.py index 1abfd2743..1fb1f9993 100644 --- a/toqito/matrix_ops/vectors_from_gram_matrix.py +++ b/toqito/matrix_ops/vectors_from_gram_matrix.py @@ -14,7 +14,7 @@ def vectors_from_gram_matrix(gram: np.ndarray) -> list[np.ndarray]: decomp = np.linalg.cholesky(gram) return [decomp[i][:] for i in range(dim)] # Otherwise, need to do eigendecomposition: - except Exception: # pylint: disable=broad-except + except np.linalg.LinAlgError: print("Matrix is not positive semidefinite. Using eigendecomposition as alternative.") d, v = np.linalg.eig(gram) return [np.sqrt(np.diag(d)) @ v[i].conj().T for i in range(dim)] From bd0b9b385b855e2f4b6e20f5a4e683487e4d1d78 Mon Sep 17 00:00:00 2001 From: Purva Thakre Date: Mon, 30 Oct 2023 13:58:13 -0500 Subject: [PATCH 22/24] Fixes https://github.com/vprusso/toqito/pull/205#discussion_r1376335278 --- toqito/channels/partial_transpose.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/toqito/channels/partial_transpose.py b/toqito/channels/partial_transpose.py index d9b217aee..6eded4be5 100644 --- a/toqito/channels/partial_transpose.py +++ b/toqito/channels/partial_transpose.py @@ -12,7 +12,7 @@ def partial_transpose( rho: np.ndarray | Variable, - sys: list[int] | np.ndarray | int = 1, + sys: list[int] | np.ndarray | int = None, dim: list[int] | np.ndarray = None, ) -> np.ndarray | Expression: r"""Compute the partial transpose of a matrix [WikPtrans]_. @@ -113,6 +113,9 @@ def partial_transpose( :raises ValueError: If matrix dimensions are not square. :returns: The partial transpose of matrix :code:`rho`. """ + if not isinstance(sys, int): + if sys is None: + sys = [1] # If the input matrix is a CVX variable for an SDP, we convert it to a # numpy array, perform the partial transpose, and convert it back to a CVX # variable. @@ -131,7 +134,7 @@ def partial_transpose( if isinstance(dim, list): dim = np.array(dim) if isinstance(sys, list): - sys = np.array(sys) + sys = np.array(sys) # pylint: disable=redefined-variable-type if isinstance(sys, int): sys = np.array([sys]) From 6af61806b5b5eae4b175e21d3a80b1a3248dc89d Mon Sep 17 00:00:00 2001 From: Purva Thakre Date: Mon, 30 Oct 2023 14:04:39 -0500 Subject: [PATCH 23/24] Fixes https://github.com/vprusso/toqito/pull/205#discussion_r1376361171 --- .../state_metrics/fidelity_of_separability.py | 34 +++++++++---------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/toqito/state_metrics/fidelity_of_separability.py b/toqito/state_metrics/fidelity_of_separability.py index f07f284cf..4bd997f44 100644 --- a/toqito/state_metrics/fidelity_of_separability.py +++ b/toqito/state_metrics/fidelity_of_separability.py @@ -153,53 +153,53 @@ def fidelity_of_separability( # Infer the dimension of Alice and Bob's system. # subsystem-dimensions in rho_AB - dim_A, dim_B = input_state_rho_dims # pylint: disable-msg=invalid-name + dim_a, dim_b = input_state_rho_dims # Extend the number of dimensions based on the level `k`. # new dims for AB with k-extendibility in subsystem B - dim_direct_sum_AB_k = [dim_A] + [dim_B] * (k) # pylint: disable-msg=invalid-name - # new dims for a linear op acting on the space of sigma_AB_k - dim_op_sigma_AB_k = dim_A * dim_B**k # pylint: disable-msg=invalid-name + dim_direct_sum_ab_k = [dim_a] + [dim_b] * (k) + # new dims for a linear op acting on the space of sigma_ab_k + dim_op_sigma_ab_k = dim_a * dim_b**k # A list of the symmetrically extended subsystems based on the level `k`. sub_sys_ext = list(range(2, 2 + k - 1)) # unitary permutation operator in B1,B2,...,Bk - permutation_op = symmetric_projection(dim_B, k) + permutation_op = symmetric_projection(dim_b, k) # defining the problem objective: Re[Tr[X_AB]] problem = picos.Problem(verbosity=verbosity_option) - linear_op_AB = picos.ComplexVariable( # pylint: disable-msg=invalid-name - "x_AB", input_state_rho.shape + linear_op_ab = picos.ComplexVariable( + "x_ab", input_state_rho.shape ) - sigma_AB_k = picos.HermitianVariable( # pylint: disable-msg=invalid-name - "s_AB_k", (dim_op_sigma_AB_k, dim_op_sigma_AB_k) + sigma_ab_k = picos.HermitianVariable( + "s_ab_k", (dim_op_sigma_ab_k, dim_op_sigma_ab_k) ) - problem.set_objective("max", 0.5 * picos.trace(linear_op_AB + linear_op_AB.H)) + problem.set_objective("max", 0.5 * picos.trace(linear_op_ab + linear_op_ab.H)) problem.add_constraint( picos.block( [ - [input_state_rho, linear_op_AB], - [linear_op_AB.H, picos.partial_trace(sigma_AB_k, sub_sys_ext, dim_direct_sum_AB_k)], + [input_state_rho, linear_op_ab], + [linear_op_ab.H, picos.partial_trace(sigma_ab_k, sub_sys_ext, dim_direct_sum_ab_k)], ] ) >> 0 ) - problem.add_constraint(sigma_AB_k >> 0) - problem.add_constraint(picos.trace(sigma_AB_k) == 1) + problem.add_constraint(sigma_ab_k >> 0) + problem.add_constraint(picos.trace(sigma_ab_k) == 1) # k-extendible constraint: problem.add_constraint( - (picos.I(dim_A) @ permutation_op) * sigma_AB_k * (picos.I(dim_A) @ permutation_op) - == sigma_AB_k + (picos.I(dim_a) @ permutation_op) * sigma_ab_k * (picos.I(dim_a) @ permutation_op) + == sigma_ab_k ) # PPT constraint: sys = [] for i in range(1, k): sys = sys + [i] - problem.add_constraint(picos.partial_transpose(sigma_AB_k, sys, dim_direct_sum_AB_k) >> 0) + problem.add_constraint(picos.partial_transpose(sigma_ab_k, sys, dim_direct_sum_ab_k) >> 0) solution = problem.solve(solver=solver_option) return solution.value**2 From 0861b4ac38e8122a99d2ca0b933a4fa209bff469 Mon Sep 17 00:00:00 2001 From: Purva Thakre Date: Mon, 30 Oct 2023 16:42:38 -0500 Subject: [PATCH 24/24] fixes https://github.com/vprusso/toqito/pull/205#discussion_r1376691812 + black reformatter --- toqito/matrix_props/sk_norm.py | 9 +++++---- toqito/state_metrics/fidelity_of_separability.py | 12 ++++-------- 2 files changed, 9 insertions(+), 12 deletions(-) diff --git a/toqito/matrix_props/sk_norm.py b/toqito/matrix_props/sk_norm.py index 297b82664..c497eee76 100644 --- a/toqito/matrix_props/sk_norm.py +++ b/toqito/matrix_props/sk_norm.py @@ -227,10 +227,11 @@ def sk_operator_norm( # pylint: disable=too-many-locals return op_norm * lower_bound, op_norm * upper_bound # Start the semidefinite programming approach for getting upper bounds. - if effort >= 1 and ( # pylint: disable=too-many-boolean-expressions - (lower_bound + tol < upper_bound and is_positive) - or (is_positive and is_trans_exact and k == 1) - ): + bool_cond = [ + (effort >= 1 and lower_bound + tol < upper_bound and is_positive), + (effort >= 1 and is_positive and is_trans_exact and k == 1), + ] + if any(bool_cond): rho = cvxpy.Variable((prod_dim, prod_dim), hermitian=True, name="rho") objective = cvxpy.Maximize(cvxpy.real(cvxpy.trace(mat @ rho))) diff --git a/toqito/state_metrics/fidelity_of_separability.py b/toqito/state_metrics/fidelity_of_separability.py index 4bd997f44..e7206b082 100644 --- a/toqito/state_metrics/fidelity_of_separability.py +++ b/toqito/state_metrics/fidelity_of_separability.py @@ -157,9 +157,9 @@ def fidelity_of_separability( # Extend the number of dimensions based on the level `k`. # new dims for AB with k-extendibility in subsystem B - dim_direct_sum_ab_k = [dim_a] + [dim_b] * (k) + dim_direct_sum_ab_k = [dim_a] + [dim_b] * (k) # new dims for a linear op acting on the space of sigma_ab_k - dim_op_sigma_ab_k = dim_a * dim_b**k + dim_op_sigma_ab_k = dim_a * dim_b**k # A list of the symmetrically extended subsystems based on the level `k`. sub_sys_ext = list(range(2, 2 + k - 1)) @@ -168,12 +168,8 @@ def fidelity_of_separability( # defining the problem objective: Re[Tr[X_AB]] problem = picos.Problem(verbosity=verbosity_option) - linear_op_ab = picos.ComplexVariable( - "x_ab", input_state_rho.shape - ) - sigma_ab_k = picos.HermitianVariable( - "s_ab_k", (dim_op_sigma_ab_k, dim_op_sigma_ab_k) - ) + linear_op_ab = picos.ComplexVariable("x_ab", input_state_rho.shape) + sigma_ab_k = picos.HermitianVariable("s_ab_k", (dim_op_sigma_ab_k, dim_op_sigma_ab_k)) problem.set_objective("max", 0.5 * picos.trace(linear_op_ab + linear_op_ab.H))