diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 77e1a916..0144b207 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -31,6 +31,7 @@ concurrency: jobs: Checks: + if: github.repository_owner == 'qiskit-community' runs-on: ${{ matrix.os }} strategy: matrix: @@ -77,6 +78,9 @@ jobs: python tools/check_copyright.py -check if: ${{ !cancelled() }} shell: bash + - run: make spell + if: ${{ !cancelled() }} + shell: bash - name: Style Check run: | make style @@ -101,6 +105,7 @@ jobs: if: ${{ !cancelled() }} shell: bash Algorithms: + if: github.repository_owner == 'qiskit-community' runs-on: ${{ matrix.os }} strategy: fail-fast: false @@ -142,10 +147,14 @@ jobs: run-slow: ${{ contains(github.event.pull_request.labels.*.name, 'run_slow') }} python-version: ${{ matrix.python-version }} if: ${{ !cancelled() }} + - name: Deprecation Messages + run: | + mkdir ./ci-artifact-data + python tools/extract_deprecation.py -file out.txt -output ./ci-artifact-data/alg.dep + shell: bash - name: Coverage combine run: | coverage3 combine - mkdir ./ci-artifact-data mv .coverage ./ci-artifact-data/alg.dat if: ${{ matrix.os == 'ubuntu-latest' && matrix.python-version == 3.8 }} shell: bash @@ -154,12 +163,13 @@ jobs: name: ${{ matrix.os }}-${{ matrix.python-version }} path: ./ci-artifact-data/* Tutorials: + if: github.repository_owner == 'qiskit-community' runs-on: ${{ matrix.os }} strategy: fail-fast: false matrix: - os: [ ubuntu-latest ] - python-version: [ 3.8, 3.11 ] + os: [ubuntu-latest] + python-version: [3.8, 3.11] steps: - uses: actions/checkout@v3 with: @@ -178,8 +188,6 @@ jobs: python-version: ${{ matrix.python-version }} if: ${{ !startsWith(github.ref, 'refs/heads/stable') && !startsWith(github.base_ref, 'stable/') }} - uses: ./.github/actions/install-algorithms - with: - os: ${{ matrix.os }} - name: Install Dependencies run: | pip install jupyter qiskit-terra[visualization] @@ -202,7 +210,8 @@ jobs: name: tutorials${{ matrix.python-version }} path: docs/_build/html/artifacts/tutorials.tar.gz Deprecation_Messages_and_Coverage: - needs: [Checks, Algorithms] + if: github.repository_owner == 'qiskit-community' + needs: [Checks, Algorithms, Tutorials] runs-on: ubuntu-latest strategy: matrix: @@ -216,9 +225,41 @@ jobs: with: name: ubuntu-latest-3.8 path: /tmp/u38 + - uses: actions/download-artifact@v3 + with: + name: ubuntu-latest-3.9 + path: /tmp/u39 + - uses: actions/download-artifact@v3 + with: + name: ubuntu-latest-3.10 + path: /tmp/u310 + - uses: actions/download-artifact@v3 + with: + name: ubuntu-latest-3.11 + path: /tmp/u311 + - uses: actions/download-artifact@v3 + with: + name: macos-latest-3.8 + path: /tmp/m38 + - uses: actions/download-artifact@v3 + with: + name: macos-latest-3.11 + path: /tmp/m311 + - uses: actions/download-artifact@v3 + with: + name: windows-2019-3.8 + path: /tmp/w38 + - uses: actions/download-artifact@v3 + with: + name: windows-2019-3.11 + path: /tmp/w311 - name: Install Dependencies run: pip install -U coverage coveralls diff-cover shell: bash + - name: Combined Deprecation Messages + run: | + sort -f -u /tmp/u38/alg.dep /tmp/u39/alg.dep /tmp/u310/alg.dep /tmp/u311/alg.dep /tmp/m38/alg.dep /tmp/m311/alg.dep /tmp/w38/alg.dep /tmp/w311/alg.dep || true + shell: bash - name: Coverage combine run: coverage3 combine /tmp/u38/alg.dat shell: bash diff --git a/.pylintdict b/.pylintdict index e69de29b..86e8d542 100644 --- a/.pylintdict +++ b/.pylintdict @@ -0,0 +1,370 @@ +adam +ae +aer +al +algo +algorithmerror +allclose +amsgrad +ansatz +ansatzes +ansatz's +ap +apl +arg +argmax +args +armijo +arxiv +autosummary +ba +backend +backends +barison +barkoutsos +batchsize +bergholm +bfgs +bielza +bitstring +bitstrings +boltzmann +bool +boyer +brassard +broyden +callables +cambridge +cancelled +carleo +carlo +chernoff +chuang +clopper +cobyla +codebase +coeffs +combinatorial +concha +configs +confint +córcoles +crs +currentmodule +customizable +cvar +dataclass +dataframe +deriv +dicts +diederik +dimensionality +disp +dobsicek +docstring +doi +dp +dt +dω +eda +egger +eigen +eigenphase +eigenproblem +eigensolver +eigensolvers +eigenstate +eigenstates +entangler +enum +eps +et +euler +eval +evals +evolutions +evolutionsynthesis +evolver +evolvers +excitations +exponentiated +exponentiating +fae +failsafe +farhi +fi +fidelities +filippo +fletcher +fm +fmin +formatter +fourier +frac +f'spsa +ftol +fujii +func +functools +gacon +gambetta +gaussian +generalised +getter +getters +giuseppe +globals +gogolin +goldfarb +goldstone +gqt +grinko +grover +gsls +gtol +gutmann +hadamard +hadfield +hamiltonian +hamiltonians +havlíček +hessians +hilbert +hopkins +hoyer +https +hyperparameters +idx +im +imag +initializer +inplace +interatomic +ints +iprint +iqft +ising +iteratively +iz +izaac +izz +jac +jacobian +jones +july +kandala +killoran +kingma +kitagawa +kraft +kth +kumar +kwarg +kwargs +langle +larrañaga +lcu +len +leq +lin +linalg +loglik +loglikelihood +lr +lsb +lse +marecek +mathcal +mathrm +maxcut +maxfail +maxfev +maxfun +maxiter +maxiters +maxmp +mcz +michael +minimised +minimizer +minwidth +mitarai +mle +modelspace +monte +mosca +mprev +nabla +nakaji +nakanishi +nan +nannicini +nathan +ndarray +negoro +nelder +nevals +newtons's +nfev +nfevs +nft +nielsen +njev +nlopt +nones +nosignatures +np +num +numpy +objval +observables +oct +onodera +optimizer's +optimizers +otimes +o'brien +param +parameterizations +parametrization +parametrizations +parametrize +parametrized +params +pauli +paulis +pearson +pedro +peruzzo +polyfit +postprocess +powell +pre +preconditioner +preprint +preprocess +preprocesses +priori +proj +pvqd +pxd +py +qae +qaoa +qasm +qdrift +qfi +qfis +qfi's +qgt +qgts +qgt's +qiskit +qiskit's +qn +qnspsa +qpe +quadratically +quant +quantile +qubit +qubits +rangle +raymond +reddi +representable +resamplings +rescale +rescaled +rescaling +retval +rhobeg +rightarrow +robert +rosen +runarsson +rz +sanjiv +sashank +satyen +schrödinger +schroediger +schroedinger +schuld +scikit +scipy +sdg +seealso +shanno +skquant +sle +slsqp +soloviev +spall +spedalieri +spsa +sqrt +statefn +statevector +statevectors +stddev +stdout +stefano +steppable +stepsize +str +subcircuits +subclasses +subcomponents +subspaces +suzuki +swappable +tanaka +tapp +tarasinski +tavernelli +temme +terhal +terra +th +timestep +timesteps +tnc +toctree +todo +tol +trainability +transpile +transpiled +trotterization +trotterized +uncompute +unitaries +univariate +uno +unscaled +utils +variational +vec +vectorized +vicentini +ville +vqd +vqe +wavefunction +woerner +wrt +xatol +xopt +xtol +yamamoto +yao +york +yy +yz +zi +zoufal +zz +θ +ψ +ω diff --git a/Makefile b/Makefile index 1f0326f9..2ace92c1 100644 --- a/Makefile +++ b/Makefile @@ -57,7 +57,7 @@ test_ci: stestr run --concurrency $(CONCURRENCY) spell: - pylint -rn --disable=all --enable=spelling --spelling-dict=en_US --spelling-private-dict-file=.pylintdict qiskit_algorithms test tools + pylint -rn --disable=all --enable=spelling --spelling-dict=en_US qiskit_algorithms test tools sphinx-build -M spelling docs docs/_build -W -T --keep-going $(SPHINXOPTS) copyright: diff --git a/docs/conf.py b/docs/conf.py index b7bb39b8..10cde338 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -91,6 +91,9 @@ "**": "_static/images/logo.png", } +spelling_word_list_filename = "../.pylintdict" +spelling_filters = ["lowercase_filter.LowercaseFilter"] + templates_path = ["_templates"] # Number figures, tables and code-blocks if they have a caption. diff --git a/docs/lowercase_filter.py b/docs/lowercase_filter.py new file mode 100644 index 00000000..e7b3d2f2 --- /dev/null +++ b/docs/lowercase_filter.py @@ -0,0 +1,29 @@ +# This code is part of a Qiskit project. +# +# (C) Copyright IBM 2021, 2023. +# +# This code is licensed under the Apache License, Version 2.0. You may +# obtain a copy of this license in the LICENSE.txt file in the root directory +# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. +# +# Any modifications or derivative works of this code must retain this +# copyright notice, and modified files need to carry a notice indicating +# that they have been altered from the originals. + +""" Implements a Lower Case Filter for Sphinx spelling """ + +from enchant import tokenize + + +class LowercaseFilter(tokenize.Filter): + """Lower Case Filter""" + + def _split(self, word): + """Filter method for sub-tokenization of tokens. + + This method must be a tokenization function that will split the + given word into sub-tokens according to the needs of the filter. + The default behavior is not to split any words. + """ + # Don't split, just lower case to test against lowercase dict + return super()._split(word.lower()) diff --git a/pyproject.toml b/pyproject.toml index d1ffad6c..2114abe3 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -73,4 +73,5 @@ enable = [ ] [tool.pylint.spelling] -spelling-private-dict-file = ".local-spellings" +spelling-private-dict-file = ".pylintdict" +spelling-store-unknown-words = "n" diff --git a/qiskit_algorithms/amplitude_estimators/ae.py b/qiskit_algorithms/amplitude_estimators/ae.py index e6f96207..836ae753 100644 --- a/qiskit_algorithms/amplitude_estimators/ae.py +++ b/qiskit_algorithms/amplitude_estimators/ae.py @@ -48,7 +48,7 @@ class AmplitudeEstimation(AmplitudeEstimator): .. note:: This class does not support the :attr:`.EstimationProblem.is_good_state` property, - as for phase estimation-based QAE, the oracle that identifes the good states + as for phase estimation-based QAE, the oracle that identifies the good states must be encoded in the Grover operator. To set custom oracles, the :attr:`.EstimationProblem.grover_operator` attribute can be set directly. @@ -159,7 +159,7 @@ def evaluate_measurements( """Evaluate the results from the circuit simulation. Given the probabilities from statevector simulation of the QAE circuit, compute the - probabilities that the measurements y/gridpoints a are the best estimate. + probabilities that the measurements y/grid-points a are the best estimate. Args: circuit_results: The circuit result from the QAE circuit. Can be either a counts dict @@ -167,7 +167,7 @@ def evaluate_measurements( threshold: Measurements with probabilities below the threshold are discarded. Returns: - Dictionaries containing the a gridpoints with respective probabilities and + Dictionaries containing the a grid-points with respective probabilities and y measurements with respective probabilities, in this order. """ # compute grid sample and measurement dicts @@ -276,7 +276,7 @@ def loglikelihood(a): right_of_qae = np.sin(np.pi * (y + 1) / M) ** 2 bubbles = [left_of_qae, qae, right_of_qae] - # Find global maximum amongst the two local maxima + # Find global maximum among the two local maxima a_opt = qae loglik_opt = loglikelihood(a_opt) for a, b in zip(bubbles[:-1], bubbles[1:]): diff --git a/qiskit_algorithms/amplitude_estimators/estimation_problem.py b/qiskit_algorithms/amplitude_estimators/estimation_problem.py index ecf0f001..7b0c3d76 100644 --- a/qiskit_algorithms/amplitude_estimators/estimation_problem.py +++ b/qiskit_algorithms/amplitude_estimators/estimation_problem.py @@ -171,8 +171,8 @@ def grover_operator(self) -> QuantumCircuit | None: return self._grover_operator # build the reflection about the bad state: a MCZ with open controls (thus X gates - # around the controls) and X gates around the target to change from a phaseflip on - # |1> to a phaseflip on |0> + # around the controls) and X gates around the target to change from a phase flip on + # |1> to a phase flip on |0> num_state_qubits = self.state_preparation.num_qubits - self.state_preparation.num_ancillas oracle = QuantumCircuit(num_state_qubits) diff --git a/qiskit_algorithms/amplitude_estimators/mlae.py b/qiskit_algorithms/amplitude_estimators/mlae.py index 4fb9fd18..a49a8508 100644 --- a/qiskit_algorithms/amplitude_estimators/mlae.py +++ b/qiskit_algorithms/amplitude_estimators/mlae.py @@ -225,7 +225,7 @@ def compute_mle( ) -> float | tuple[float, list[float]]: """Compute the MLE via a grid-search. - This is a stable approach if sufficient gridpoints are used. + This is a stable approach if sufficient grid-points are used. Args: circuit_results: A list of circuit outcomes. Can be counts or statevectors. diff --git a/qiskit_algorithms/eigensolvers/vqd.py b/qiskit_algorithms/eigensolvers/vqd.py index 6339dd29..c4db44dd 100644 --- a/qiskit_algorithms/eigensolvers/vqd.py +++ b/qiskit_algorithms/eigensolvers/vqd.py @@ -53,12 +53,12 @@ class VQD(VariationalAlgorithm, Eigensolver): the k eigenvalues of the Hamiltonian :math:`H` of a given system. The algorithm computes excited state energies of generalised hamiltonians - by optimising over a modified cost function where each succesive eigenvalue + by optimizing over a modified cost function where each successive eigenvalue is calculated iteratively by introducing an overlap term with all the previously computed eigenstates that must be minimised, thus ensuring higher energy eigenstates are found. - An instance of VQD requires defining three algorithmic sub-components: + An instance of VQD requires defining three algorithmic subcomponents: an integer k denoting the number of eigenstates to calculate, a trial state (a.k.a. ansatz) which is a :class:`QuantumCircuit`, and one instance (or list of) classical :mod:`~qiskit_algorithms.optimizers`. diff --git a/qiskit_algorithms/gradients/reverse/reverse_qgt.py b/qiskit_algorithms/gradients/reverse/reverse_qgt.py index 78bd8342..46a2e2d0 100644 --- a/qiskit_algorithms/gradients/reverse/reverse_qgt.py +++ b/qiskit_algorithms/gradients/reverse/reverse_qgt.py @@ -157,7 +157,7 @@ def _run_unique( grad_coeffs = [coeff for coeff, _ in deriv] grad_states = [phi.evolve(gate) for _, gate in deriv] - # compute the digaonal element L_{j, j} + # compute the diagonal element L_{j, j} metric[j, j] += _l_term(grad_coeffs, grad_states, grad_coeffs, grad_states) # compute the off diagonal elements L_{i, j} diff --git a/qiskit_algorithms/optimizers/gradient_descent.py b/qiskit_algorithms/optimizers/gradient_descent.py index 8ac10fe9..17426a3f 100644 --- a/qiskit_algorithms/optimizers/gradient_descent.py +++ b/qiskit_algorithms/optimizers/gradient_descent.py @@ -98,13 +98,13 @@ def f(x): def learning_rate(): power = 0.6 constant_coeff = 0.1 - def powerlaw(): + def power_law(): n = 0 while True: yield constant_coeff * (n ** power) n += 1 - return powerlaw() + return power_law() def f(x): return (np.linalg.norm(x) - 1) ** 2 @@ -157,7 +157,7 @@ def grad(x): evaluated_gradient = grad(ask_data.x_center) optimizer.state.njev += 1 - optmizer.state.nit += 1 + optimizer.state.nit += 1 tell_data = TellData(eval_jac=evaluated_gradient) optimizer.tell(ask_data=ask_data, tell_data=tell_data) @@ -197,7 +197,7 @@ def __init__( perturbation in both directions (defaults to 1e-2 if required). Ignored when we have an explicit function for the gradient. Raises: - ValueError: If ``learning_rate`` is an array and its lenght is less than ``maxiter``. + ValueError: If ``learning_rate`` is an array and its length is less than ``maxiter``. """ super().__init__(maxiter=maxiter) self.callback = callback @@ -250,7 +250,7 @@ def perturbation(self, perturbation: float | None) -> None: def _callback_wrapper(self) -> None: """ - Wraps the callback function to accomodate GradientDescent. + Wraps the callback function to accommodate GradientDescent. Will call :attr:`~.callback` and pass the following arguments: current number of function values, current parameters, current function value, @@ -295,7 +295,7 @@ def ask(self) -> AskData: def tell(self, ask_data: AskData, tell_data: TellData) -> None: """ - Updates :attr:`.~GradientDescentState.x` by an ammount proportional to the learning + Updates :attr:`.~GradientDescentState.x` by an amount proportional to the learning rate and value of the gradient at that point. Args: diff --git a/qiskit_algorithms/optimizers/scipy_optimizer.py b/qiskit_algorithms/optimizers/scipy_optimizer.py index ff0ef2a9..a5661993 100644 --- a/qiskit_algorithms/optimizers/scipy_optimizer.py +++ b/qiskit_algorithms/optimizers/scipy_optimizer.py @@ -116,7 +116,7 @@ def minimize( jac: Callable[[POINT], POINT] | None = None, bounds: list[tuple[float, float]] | None = None, ) -> OptimizerResult: - # Remove ignored parameters to supress the warning of scipy.optimize.minimize + # Remove ignored parameters to suppress the warning of scipy.optimize.minimize if self.is_bounds_ignored: bounds = None if self.is_gradient_ignored: diff --git a/qiskit_algorithms/optimizers/spsa.py b/qiskit_algorithms/optimizers/spsa.py index 33f6e47f..7e1092b1 100644 --- a/qiskit_algorithms/optimizers/spsa.py +++ b/qiskit_algorithms/optimizers/spsa.py @@ -291,9 +291,9 @@ def calibrate( modelspace: bool = False, max_evals_grouped: int = 1, ) -> tuple[Callable, Callable]: - r"""Calibrate SPSA parameters with a powerseries as learning rate and perturbation coeffs. + r"""Calibrate SPSA parameters with a power series as learning rate and perturbation coeffs. - The powerseries are: + The power series are: .. math:: @@ -306,15 +306,15 @@ def calibrate( stability_constant: The value of `A`. target_magnitude: The target magnitude for the first update step, defaults to :math:`2\pi / 10`. - alpha: The exponent of the learning rate powerseries. - gamma: The exponent of the perturbation powerseries. + alpha: The exponent of the learning rate power series. + gamma: The exponent of the perturbation power series. modelspace: Whether the target magnitude is the difference of parameter values or function values (= model space). max_evals_grouped: The number of grouped evaluations supported by the loss function. Defaults to 1, i.e. no grouping. Returns: - tuple(generator, generator): A tuple of powerseries generators, the first one for the + tuple(generator, generator): A tuple of power series generators, the first one for the learning rate and the second one for the perturbation. """ logger.info("SPSA: Starting calibration of learning rate and perturbation.") @@ -327,7 +327,7 @@ def calibrate( steps = 25 points = [] for _ in range(steps): - # compute the random directon + # compute the random direction pert = bernoulli_perturbation(dim) points += [initial_point + c * pert, initial_point - c * pert] @@ -359,7 +359,7 @@ def calibrate( ) logger.info(" -- Perturbation: c / (n ^ gamma) with c = %s, gamma = %s", c, gamma) - # set up the powerseries + # set up the power series def learning_rate(): return powerseries(a, alpha, stability_constant) @@ -664,7 +664,7 @@ def bernoulli_perturbation(dim, perturbation_dims=None): def powerseries(eta=0.01, power=2, offset=0): - """Yield a series decreasing by a powerlaw.""" + """Yield a series decreasing by a power law.""" n = 1 while True: diff --git a/qiskit_algorithms/optimizers/steppable_optimizer.py b/qiskit_algorithms/optimizers/steppable_optimizer.py index 26c9331b..e9ffda9b 100644 --- a/qiskit_algorithms/optimizers/steppable_optimizer.py +++ b/qiskit_algorithms/optimizers/steppable_optimizer.py @@ -69,9 +69,9 @@ class OptimizerState: nfev: int | None """Number of function evaluations so far in the optimization.""" njev: int | None - """Number of jacobian evaluations so far in the opimization.""" + """Number of jacobian evaluations so far in the optimization.""" nit: int | None - """Number of optmization steps performed so far in the optimization.""" + """Number of optimization steps performed so far in the optimization.""" class SteppableOptimizer(Optimizer): @@ -81,7 +81,7 @@ class SteppableOptimizer(Optimizer): This family of optimizers uses the `ask and tell interface `_. When using this interface the user has to call :meth:`~.ask` to get information about - how to evaluate the fucntion (we are asking the optimizer about how to do the evaluation). + how to evaluate the function (we are asking the optimizer about how to do the evaluation). This information is typically the next points at which the function is evaluated, but depending on the optimizer it can also determine whether to evaluate the function or its gradient. Once the function has been evaluated, the user calls the method :meth:`~..tell` @@ -130,7 +130,7 @@ def grad(x): evaluated_gradient = grad(ask_data.x_center) optimizer.state.njev += 1 - optmizer.state.nit += 1 + optimizer.state.nit += 1 cf = TellData(eval_jac=evaluated_gradient) optimizer.tell(ask_data=ask_data, tell_data=tell_data) @@ -180,7 +180,7 @@ def ask(self) -> AskData: It is the first method inside of a :meth:`~.step` in the optimization process. Returns: - An object containing the data needed to make the funciton evaluation to advance the + An object containing the data needed to make the function evaluation to advance the optimization process. """ @@ -217,7 +217,7 @@ def evaluate(self, ask_data: AskData) -> TellData: def _callback_wrapper(self) -> None: """ - Wraps the callback function to accomodate each optimizer. + Wraps the callback function to accommodate each optimizer. """ pass diff --git a/qiskit_algorithms/optimizers/umda.py b/qiskit_algorithms/optimizers/umda.py index b7750bb7..e7eba0c6 100644 --- a/qiskit_algorithms/optimizers/umda.py +++ b/qiskit_algorithms/optimizers/umda.py @@ -48,7 +48,7 @@ class UMDA(Optimizer): have been obtained [1]. UMDA seems to provide very good solutions for those circuits in which the number of layers is not big. - The optimization process can be personalized depending on the paremeters chosen in the + The optimization process can be personalized depending on the parameters chosen in the initialization. The main parameter is the population size. The bigger it is, the final result will be better. However, this increases the complexity of the algorithm and the runtime will be much heavier. In the work [1] different experiments have been performed where population diff --git a/qiskit_algorithms/phase_estimators/phase_estimation.py b/qiskit_algorithms/phase_estimators/phase_estimation.py index 5285dada..bf84b736 100644 --- a/qiskit_algorithms/phase_estimators/phase_estimation.py +++ b/qiskit_algorithms/phase_estimators/phase_estimation.py @@ -183,7 +183,7 @@ def estimate_from_pe_circuit(self, pe_circuit: QuantumCircuit) -> PhaseEstimatio pe_circuit: The phase estimation circuit. Returns: - An instance of qiskit_algorithms.phase_estimator_result.PhaseEstimationResult. + A phase estimation result. Raises: AlgorithmError: Primitive job failed. @@ -223,7 +223,7 @@ def estimate( computational basis. Returns: - An instance of qiskit_algorithms.phase_estimator_result.PhaseEstimationResult. + A phase estimation result. """ pe_circuit = self.construct_circuit(unitary, state_preparation) diff --git a/qiskit_algorithms/phase_estimators/phase_estimation_result.py b/qiskit_algorithms/phase_estimators/phase_estimation_result.py index 5712c273..25d54760 100644 --- a/qiskit_algorithms/phase_estimators/phase_estimation_result.py +++ b/qiskit_algorithms/phase_estimators/phase_estimation_result.py @@ -70,7 +70,7 @@ def phase(self) -> float: r"""Return the most likely phase as a number in :math:`[0.0, 1.0)`. 1.0 corresponds to a phase of :math:`2\pi`. This selects the phase corresponding - to the bit string with the highesest probability. This is the most likely phase. + to the bit string with the highest probability. This is the most likely phase. """ if isinstance(self.phases, dict): binary_phase_string = max(self.phases, key=self.phases.get) diff --git a/qiskit_algorithms/state_fidelities/base_state_fidelity.py b/qiskit_algorithms/state_fidelities/base_state_fidelity.py index fc98febb..834b42dd 100644 --- a/qiskit_algorithms/state_fidelities/base_state_fidelity.py +++ b/qiskit_algorithms/state_fidelities/base_state_fidelity.py @@ -179,7 +179,7 @@ def _construct_circuits( self._check_qubits_match(circuit_1, circuit_2) # re-parametrize input circuits - # TODO: make smarter checks to avoid unnecesary reparametrizations + # TODO: make smarter checks to avoid unnecessary re-parametrizations parameters_1 = ParameterVector("x", circuit_1.num_parameters) parametrized_circuit_1 = circuit_1.assign_parameters(parameters_1) parameters_2 = ParameterVector("y", circuit_2.num_parameters) diff --git a/qiskit_algorithms/time_evolvers/pvqd/pvqd.py b/qiskit_algorithms/time_evolvers/pvqd/pvqd.py index b1ca9d69..0585f547 100644 --- a/qiskit_algorithms/time_evolvers/pvqd/pvqd.py +++ b/qiskit_algorithms/time_evolvers/pvqd/pvqd.py @@ -283,7 +283,7 @@ def evaluate_loss(displacement: np.ndarray | list[np.ndarray]) -> float | np.nda def evaluate_gradient(displacement: np.ndarray) -> np.ndarray: """Evaluate the gradient with the parameter-shift rule. - This is hardcoded here since the gradient framework does not support computing + This is hard-coded here since the gradient framework does not support computing gradients for overlaps. Args: diff --git a/qiskit_algorithms/time_evolvers/trotterization/trotter_qrte.py b/qiskit_algorithms/time_evolvers/trotterization/trotter_qrte.py index 549a9651..a36ddff6 100644 --- a/qiskit_algorithms/time_evolvers/trotterization/trotter_qrte.py +++ b/qiskit_algorithms/time_evolvers/trotterization/trotter_qrte.py @@ -65,7 +65,7 @@ def __init__( should be 1 to obtain a number of time-steps equal to ``num_timesteps`` and an evaluation of :attr:`.TimeEvolutionProblem.aux_operators` at every time-step. If ``reps`` is larger than 1, the true number of time-steps will be ``num_timesteps * reps``. - num_timesteps: The number of time-steps the full evolution time is devided into + num_timesteps: The number of time-steps the full evolution time is divided into (repetitions of ``product_formula``) estimator: An estimator primitive used for calculating expectation values of ``TimeEvolutionProblem.aux_operators``. diff --git a/test/eigensolvers/test_vqd.py b/test/eigensolvers/test_vqd.py index 7ab235b4..46b22a31 100644 --- a/test/eigensolvers/test_vqd.py +++ b/test/eigensolvers/test_vqd.py @@ -115,7 +115,7 @@ def test_full_spectrum(self): @data(H2_SPARSE_PAULI) def test_beta_autoeval(self, op): - """Test beta autoevaluation for different operator types.""" + """Test beta auto-evaluation for different operator types.""" with self.assertLogs(level="INFO") as logs: vqd = VQD( diff --git a/test/minimum_eigensolvers/test_sampling_vqe.py b/test/minimum_eigensolvers/test_sampling_vqe.py index d60c9838..3ae889fc 100644 --- a/test/minimum_eigensolvers/test_sampling_vqe.py +++ b/test/minimum_eigensolvers/test_sampling_vqe.py @@ -259,7 +259,7 @@ def store_intermediate_result(eval_count, parameters, mean, metadata): def test_aggregation(self): """Test the aggregation works.""" - # test a custom aggregration that just uses the best measurement + # test a custom aggregation that just uses the best measurement def best_measurement(measurements): res = min(measurements, key=lambda meas: meas[1])[1] return res diff --git a/test/optimizers/test_gradient_descent.py b/test/optimizers/test_gradient_descent.py index e43b112c..d8ca30d2 100644 --- a/test/optimizers/test_gradient_descent.py +++ b/test/optimizers/test_gradient_descent.py @@ -89,7 +89,7 @@ def callback(*args): self.assertIsInstance(history[0][3], float) # norm of the gradient def test_minimize(self): - """Test setting the learning rate as iterator and minimizing the funciton.""" + """Test setting the learning rate as iterator and minimizing the function.""" def learning_rate(): power = 0.6 diff --git a/test/optimizers/test_spsa.py b/test/optimizers/test_spsa.py index 32d4a4bb..51a9e503 100644 --- a/test/optimizers/test_spsa.py +++ b/test/optimizers/test_spsa.py @@ -80,7 +80,7 @@ def objective(x): self.assertEqual(result.nfev, expected_nfev) # function evaluations def test_recalibrate_at_optimize(self): - """Test SPSA calibrates anew upon each optimization run, if no autocalibration is set.""" + """Test SPSA calibrates anew upon each optimization run, if no auto-calibration is set.""" def objective(x): return -(x**2) diff --git a/test/utils/test_validate_initial_point.py b/test/utils/test_validate_initial_point.py index 0264c45e..9a8f1549 100644 --- a/test/utils/test_validate_initial_point.py +++ b/test/utils/test_validate_initial_point.py @@ -43,7 +43,7 @@ def test_with_no_initial_point(self): np.testing.assert_array_almost_equal(initial_point, [0.430278]) def test_with_mismatched_params(self): - """Test with mistmatched parameters and bounds..""" + """Test with mismatched parameters and bounds..""" self.ansatz.parameter_bounds = None with self.assertRaises(ValueError): _ = validate_initial_point([1.0, 2.0], self.ansatz) diff --git a/tools/extract_deprecation.py b/tools/extract_deprecation.py new file mode 100644 index 00000000..5a61d982 --- /dev/null +++ b/tools/extract_deprecation.py @@ -0,0 +1,98 @@ +# This code is part of a Qiskit project. +# +# (C) Copyright IBM 2021, 2023. +# +# This code is licensed under the Apache License, Version 2.0. You may +# obtain a copy of this license in the LICENSE.txt file in the root directory +# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. +# +# Any modifications or derivative works of this code must retain this +# copyright notice, and modified files need to carry a notice indicating +# that they have been altered from the originals. + +""" Extract deprecation messages from input """ + +from typing import List +import sys +import os +import argparse + + +class DeprecationExtractor: + """Extract deprecation messages""" + + def __init__(self, in_file: str, out_file: str) -> None: + self._input_filename = in_file + self._output_filename = out_file + self._messages = None # type: List[str] + + def extract_messages(self) -> bool: + """ + extract deprecation + Returns: + bool: if messages were found + """ + + self._messages = None + messages = set() + with open(self._input_filename, "rt", encoding="utf8", errors="ignore") as file: + for line in file: + if line.find("DeprecationWarning:") > 0: + messages.add(line.strip()) + + if messages: + self._messages = sorted(messages) + return True + + return False + + def save_to_output(self, force_create: bool) -> bool: + """ + save messages to file if they exist + Args: + force_create: create file even if it is empty + Returns: + bool: if messages were saved + """ + if self._output_filename: + # create file even if it is empty + if self._messages or force_create: + with open(self._output_filename, "w", encoding="utf8") as file: + if self._messages: + file.write("\n".join(self._messages)) + return True + + return False + + def print_messages(self) -> None: + """print messages""" + if self._messages: + print("---------------------") + print("Deprecation Messages:") + print("---------------------") + for line in self._messages: + print(line) + + +def _check_file(path) -> str: + if not os.path.isfile(path): + raise argparse.ArgumentTypeError(f"file: '{path}' doesn't exist.") + + return path + + +if __name__ == "__main__": + PARSER = argparse.ArgumentParser(description="Qiskit Extract Deprecation Messages Tool") + PARSER.add_argument( + "-file", type=_check_file, required=True, metavar="file", help="Input file." + ) + PARSER.add_argument("-output", metavar="output", help="Output file.") + + ARGS = PARSER.parse_args() + + OBJ = DeprecationExtractor(ARGS.file, ARGS.output) + OBJ.extract_messages() + OBJ.save_to_output(True) + OBJ.print_messages() + + sys.exit(0)