Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Change QuantumCircuit.metadata to always be a dict #9849

Merged
merged 12 commits into from
Apr 18, 2023

Conversation

ihincks
Copy link
Contributor

@ihincks ihincks commented Mar 24, 2023

Summary

The QuantumCircuit.metadata return annotation was previously just dict, whereas None is a valid value. This means that static type checkers would have no problems with statements like circuit.metadata.get("name", 0).

Edit:

The scope of this PR has changed. Instead of changing the annotation type to match the implementation, it now changes the implementation to match the annotation. In particular, the metadata attribute is always a dictionary now, and trying to set it to None emits a warning.

The QuantumCircuit.metadata return annotation was previously just ``dict``, whereas
``None`` is a valid value. This means that static type checkers would have no
problems with statements like ``circuit.metadata.get("name", 0)``.
@ihincks ihincks added the mypy Work related to support improving type hints in Qiskti code label Mar 24, 2023
@ihincks ihincks requested a review from a team as a code owner March 24, 2023 13:40
@qiskit-bot
Copy link
Collaborator

Thank you for opening a new pull request.

Before your PR can be merged it will first need to pass continuous integration tests and be reviewed. Sometimes the review process can be slow, so please be patient.

While you're waiting, please feel free to review other open PRs. While only a subset of people are authorized to approve pull requests for merging, everyone is encouraged to review open pull requests. Doing reviews helps reduce the burden on the core team and helps make the project's code better for everyone.

One or more of the the following people are requested to review this:

  • @Qiskit/terra-core

@CLAassistant
Copy link

CLAassistant commented Mar 24, 2023

CLA assistant check
All committers have signed the CLA.

@CLAassistant
Copy link

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you sign our Contributor License Agreement before we can accept your contribution.
You have signed the CLA already but the status is still pending? Let us recheck it.

@coveralls
Copy link

coveralls commented Mar 24, 2023

Pull Request Test Coverage Report for Build 4693325326

  • 10 of 10 (100.0%) changed or added relevant lines in 4 files are covered.
  • 21 unchanged lines in 3 files lost coverage.
  • Overall coverage decreased (-0.02%) to 85.752%

Files with Coverage Reduction New Missed Lines %
qiskit/assembler/assemble_circuits.py 1 98.89%
crates/qasm2/src/lex.rs 2 91.14%
crates/qasm2/src/parse.rs 18 96.65%
Totals Coverage Status
Change from base Build 4692324070: -0.02%
Covered Lines: 70278
Relevant Lines: 81955

💛 - Coveralls

Copy link
Member

@jakelishman jakelishman left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

tbh I think it might be more appropriate to fix QuantumCircuit to initialise metadata to {} if it's not given. It's a bit of a nuisance that we don't already do that.

@ihincks
Copy link
Contributor Author

ihincks commented Mar 24, 2023

That would be my preference too, I just didn't want to stir anything up. Is there any concern at all about the extra few bytes/circuit this would incur? If not I can make the change.

Previous to this change, the QuantumCircuit.metadata could be set to, and return
None instead of a dictionary.
@ihincks ihincks changed the title Include None in QuantumCircuit.metadata return annotation Change QuantumCircuit.metadata to always be a dict Mar 24, 2023
Copy link
Member

@jakelishman jakelishman left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for this - I'll be very happy to see the back of this typing weirdness, and from internal discussions, so will many other people.

Could you also add a release note with a "deprecations" note about the setter and an "upgrade" note about the narrowing of the getter return type?

(The command is reno new --edit quantumcircuit-metadata or similar)

qiskit/circuit/quantumcircuit.py Outdated Show resolved Hide resolved
@jakelishman
Copy link
Member

The jillions of test failures are suggesting that we need to make the same change to DAGCircuit.metadata and DAGDependency.metadata, I'm fairly sure. Anywhere doing an explicit .metadata = None (there's a couple, e.g. in dagdependency.py and dagcircuit.py) will want updating to be .metadata = {}.

I just searched for .\metadata = in the repo to turn up the bad cases.

@ihincks
Copy link
Contributor Author

ihincks commented Mar 24, 2023

Sure I can change the other two classes, too. I made the latest commits before seeing your comment.

@ihincks
Copy link
Contributor Author

ihincks commented Mar 24, 2023

ihincks added a commit to ihincks/qiskit-aer that referenced this pull request Mar 24, 2023
mergify bot pushed a commit to Qiskit/qiskit-aer that referenced this pull request Mar 27, 2023
* Ensure QuantumCircuit.metadata is always a dict

This is for compatibility with Qiskit/qiskit#9849

* fix order

* fix typo :(

* revert object->object() change

* make backportable
@ihincks
Copy link
Contributor Author

ihincks commented Apr 3, 2023

Is there anything I need to be doing with this PR right now to move it along?

@jakelishman
Copy link
Member

Oh, sorry Ian. The last run failed some tests (though the logs have since been cleaned) and there's currently a merge conflict. Do you happen to remember what the failing tests were about? If it's Aer, then we'll possibly need to put in a temporary warning catch for cases where that warning is being triggered specifically by Aer. We're not able to deploy any bugfixes to it at the moment because we've hit our storage limit on PyPI (though we're in the process of trying to get the cap raised for us).

@ihincks
Copy link
Contributor Author

ihincks commented Apr 6, 2023

All of the ones that I have seen failing are of the flavour

testtools.testresult.real._StringException: Traceback (most recent call last):
  File "/tmp/terra-tests/test/python/algorithms/optimizers/test_optimizer_aqgd.py", line 78, in test_list
    result = vqe.compute_minimum_eigenvalue(operator=self.qubit_op)
  File "/home/vsts/work/1/s/qiskit/algorithms/minimum_eigen_solvers/vqe.py", line 548, in compute_minimum_eigenvalue
    fun=energy_evaluation, x0=initial_point, jac=gradient, bounds=bounds
  File "/home/vsts/work/1/s/qiskit/algorithms/optimizers/aqgd.py", line 330, in minimize
    objval, gradient = self._compute_objective_fn_and_gradient(params, fun)
  File "/home/vsts/work/1/s/qiskit/algorithms/optimizers/aqgd.py", line 156, in _compute_objective_fn_and_gradient
    values = np.array(obj(param_sets_to_eval.reshape(-1)))
  File "/home/vsts/work/1/s/qiskit/algorithms/minimum_eigen_solvers/vqe.py", line 621, in energy_evaluation
    sampled_expect_op = self._circuit_sampler.convert(expect_op, params=param_bindings)
  File "/home/vsts/work/1/s/qiskit/opflow/converters/circuit_sampler.py", line 213, in convert
    sampled_statefn_dicts = self.sample_circuits(circuit_sfns=circs, param_bindings=p_b)
  File "/home/vsts/work/1/s/qiskit/opflow/converters/circuit_sampler.py", line 333, in sample_circuits
    ready_circs, had_transpiled=self._transpile_before_bind
  File "/home/vsts/work/1/s/qiskit/utils/quantum_instance.py", line 725, in execute
    max_job_retries=self._max_job_retries,
  File "/home/vsts/work/1/s/qiskit/utils/run_circuits.py", line 282, in run_circuits
    results.append(job.result())
  File "/home/vsts/work/1/s/test-job/lib/python3.7/site-packages/qiskit_aer/jobs/utils.py", line 41, in _wrapper
    return func(self, *args, **kwargs)
  File "/home/vsts/work/1/s/test-job/lib/python3.7/site-packages/qiskit_aer/jobs/aerjob.py", line 106, in result
    return self._future.result(timeout=timeout)
  File "/opt/hostedtoolcache/Python/3.7.16/x64/lib/python3.7/concurrent/futures/_base.py", line 428, in result
    return self.__get_result()
  File "/opt/hostedtoolcache/Python/3.7.16/x64/lib/python3.7/concurrent/futures/_base.py", line 384, in __get_result
    raise self._exception
  File "/opt/hostedtoolcache/Python/3.7.16/x64/lib/python3.7/concurrent/futures/thread.py", line 57, in run
    result = self.fn(*self.args, **self.kwargs)
  File "/home/vsts/work/1/s/test-job/lib/python3.7/site-packages/qiskit_aer/backends/aerbackend.py", line 463, in _execute_circuits_job
    circ.metadata = metadata
  File "/home/vsts/work/1/s/qiskit/circuit/quantumcircuit.py", line 471, in metadata
    DeprecationWarning,
DeprecationWarning: Setting metadata to None was deprecated in Terra 0.24.0 and this ability will be removed in a future release. Instead, set metadata to an empty dictionary.

@jakelishman jakelishman added this to the 0.24.0 milestone Apr 6, 2023
hhorii pushed a commit to hhorii/qiskit-aer that referenced this pull request Apr 7, 2023
* Ensure QuantumCircuit.metadata is always a dict

This is for compatibility with Qiskit/qiskit#9849

* fix order

* fix typo :(

* revert object->object() change

* make backportable
hhorii pushed a commit to hhorii/qiskit-aer that referenced this pull request Apr 7, 2023
* Ensure QuantumCircuit.metadata is always a dict

This is for compatibility with Qiskit/qiskit#9849

* fix order

* fix typo :(

* revert object->object() change

* make backportable
@mtreinish
Copy link
Member

That error is from aer. This will be blocked until qiskit-aer 0.12.1 is released, the only option is to filter the warning (since it's in 479 place we'd probably want to do it globally for all aer calls). Normally I'd be opposed to doing this globally since doing that means we're essentially ignoring the downstream impact of the deprecation. But since you've already fixed it in aer it probably is ok in this case.

This will be fixed in Aer in the near future in a backwards-compatible
manner, so in order to put the fix out into Terra while Aer's deployment
issues are worked out (run out of space on PyPI!), we can add a very
targetted warning suppression to the tests.
Copy link
Member

@jakelishman jakelishman left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is fine by me now, but since I pushed the last couple of commits to sort out the warning filters in the test and the stacklevel (after checking with Ian), I'll wait for a second approver to merge.

@mtreinish mtreinish self-assigned this Apr 17, 2023
Copy link
Member

@mtreinish mtreinish left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@mtreinish mtreinish added this pull request to the merge queue Apr 18, 2023
@ihincks
Copy link
Contributor Author

ihincks commented Apr 18, 2023

🎉 thanks for all of your help

Merged via the queue into Qiskit:main with commit 971a203 Apr 18, 2023
king-p3nguin pushed a commit to king-p3nguin/qiskit-terra that referenced this pull request May 22, 2023
* Fix QuantumCircuit.metadata return annotation

The QuantumCircuit.metadata return annotation was previously just ``dict``, whereas
``None`` is a valid value. This means that static type checkers would have no
problems with statements like ``circuit.metadata.get("name", 0)``.

* Change QuantumCircuit.metadata to always be dictionary

Previous to this change, the QuantumCircuit.metadata could be set to, and return
None instead of a dictionary.

* Fix cases where QuantumCircuit.metadata is set to None by a DAG

* Added release notes

* Minor updates

* Change default metadata value of DAGCircuit/Dependency to {}

Previously it was None

* fix typos

* Fix stacklevel of emitted warning

* Add warning suppression for Aer behaviour

This will be fixed in Aer in the near future in a backwards-compatible
manner, so in order to put the fix out into Terra while Aer's deployment
issues are worked out (run out of space on PyPI!), we can add a very
targetted warning suppression to the tests.

---------

Co-authored-by: Jake Lishman <[email protected]>
hhorii added a commit to Qiskit/qiskit-aer that referenced this pull request Jun 13, 2023
* Bump version strings to prepare for release

* Remove redundant wheel dep from pyproject.toml (#1741)

Remove the redundant `wheel` dependency, as it is added by the backend automatically.

Listing it explicitly in the documentation was a historical mistake and has been fixed since,
see: [pypa/setuptools@f7d30a9](pypa/setuptools@f7d30a9).

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>

* add code-formatting with black for python and with clang-format for c++ (#1630)

* add black and clang-format

* apply black and clang-format

* manually format codes that were not covered in black and clang-format

* add targets of clang-format and clean up tox.ini

* apply black with new configuration

* Update CONTRIBUTING.md

Co-authored-by: Matthew Treinish <[email protected]>

* Update .github/workflows/tests.yml

Co-authored-by: Matthew Treinish <[email protected]>

* reformat qiskit_aer, test, tools, and setup.py with length 100

---------

Co-authored-by: Matthew Treinish <[email protected]>

* Add git blame ignore file (#1745)

This commit adds a new file with the SHA1 of commits to ignore when
running git blame. This is important because of the recent adoption of
black and clang-format as our code formatting tool in #1630 we caused a
large amount of code churn to change the code formatting. However, using
the ignore file is a local opt-in feature for git and not something we
can enable globally by default. To facilitate this a section is added to
the bottom of the contributing guide to document how this file can be
used.

* deploy documentation in qiskit.org/ecosystem (#1748)

* deploy documentation in qiskit.org/ecosystem

* comment

* Remove a release note in an invalid location (#1750)

Essentially equivalent content is already incorporated in #1739.

* Fix how to reference to config.cuStateVec_enable (#1749)

* Fix how to reference to config.cuStateVec_enable

* Add a release note

* Update fix-cuStateVec_enable-0936f2269466e3be.yaml

---------

Co-authored-by: Hiroshi Horii <[email protected]>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>

* use `omp_set_max_active_levels` instead of `omp_set_nested` (#1752)

omp_set_nested was deprecated since OpenMP 3.0 and this commit
replaces it with omp_set_max_active_levels.

* use omp_set_max_active_levels instead of omp_set_nested
* use omp_set_nested in WIN
* Update releasenotes/notes/use_omp_set_max_active_levels-7e6c1d301c4434a6.yaml
* use _OPENMP to select omp_set_max_active_levels or omp_set_nested
---------

Co-authored-by: Jake Lishman <[email protected]>

* Ensure QuantumCircuit.metadata is always a dict (#1761)

* Ensure QuantumCircuit.metadata is always a dict

This is for compatibility with Qiskit/qiskit#9849

* fix order

* fix typo :(

* revert object->object() change

* make backportable

* Add Tutorials to Documentation Page (#1768)

* Add tutorials

* Add pandoc installation

---------

Co-authored-by: Hiroshi Horii <[email protected]>

* Defer gathering backends until they are needed (#1760)

* Defer gathering backends until they are needed

* Disable the not-an-iterable warning

Pylint infers _get_backends to always return None, even if we add type
annotations. Suppress the warning.

* Add @staticmethod to AerProvider._get_backends

---------

Co-authored-by: Hiroshi Horii <[email protected]>

* Fix wrong set of parameters in circuits with barriers (#1775)

* Fix wrong set of parameters in circuits with barriers

`AerCircuit` is created from a circuit by iterating its instrucitons
while skpping barrier. This leads inconsistency with positions of
parameter bindings. This commit adds barrier instruction to the class
and keeps positions of parameter bindings.

* fix lint error in test

* remove unused variable in test

* Add API docs for QuantumCircuit methods (#1753)

* Add new doc for circuit method apis

* Remove QuantumCircuit description

---------

Co-authored-by: Hiroshi Horii <[email protected]>

* Resolve regression from introduction of AER::Config (#1747)

This commit reduces redundant copy in `AER::Transpile::CircuitOptimization`.
Since 0.12.0, configuration is `AER::Config` instead of `json_t`. This new class
has many fields and then its copy overheads become high. Reduction of
redundant copy improves performance especially for low-qubit simulation.

* Remove REQUIRED to find PythonLibs in FindPybind11 (#1786)

* pin the version of scikit-build to 0.17.2

* Pin scikit-build version by 0.17.2

Co-authored-by: Matthew Treinish <[email protected]>

* remove REQUIRED to find PythonLibs in FindPybind11

---------

Co-authored-by: Matthew Treinish <[email protected]>

* Remove Sampler.close, assert DeprecationWarning of opflow, and update dependency (#1804)

Since qiskit-terra 0.24, `Sampler` does not have `close()` but Aer's `Sampler` still have the method. This commit takes the method as well as upgrade of Python versions in tutorial tests from 3.7 to 3.8.

* rm close
* assert DeprecationWarning
* update dependency

* Fix setting MPI processes and ranks (#1808)

0.12.0 accidentally removed MPI support if application does not use qobj. This commit reverts the change.

* Fix library path to cuQuantum and cuTENSOR (#1801)

Co-authored-by: Hiroshi Horii <[email protected]>

* Activate jQuery in docs (#1802)

Sphinx 6 no longer activates jQuery by default but `qiskit_sphinx_theme` still uses it.
This commits enables jQuery by adding the theme to extensions in conf.py.

---------

Co-authored-by: Hiroshi Horii <[email protected]>

* fix cuQuantum static linking (#1812)

Co-authored-by: Hiroshi Horii <[email protected]>

* Update standard_errors.py (#1799)

There was a typo in the rendering of the mathematical text on Depolarizing Error Page (https://qiskit.org/ecosystem/aer/stubs/qiskit_aer.noise.depolarizing_error.html)

Co-authored-by: Hiroshi Horii <[email protected]>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>

* Add implicit cast of argument types (#1770)

* Add implicit cast of argument types

Since 0.12.0, AerConfig is used to configure simulation, which
is directly bound to a AER::Config object through pybind.
This change requires application to specify strictly correct types
of configuration options. This commit allows implicit casting
to arguments if application specifies them with wrong types.
This commit resolves #1754.

* does not warning in cast of numpy classes if they are compatible with expected type
* fix lint issue
* simplify class checking

* Fix handling of None in noise model construction from BackendV2 (#1818)

Fixes `NoiseModel.from_backend` not to fail when calling it with a V2 backend having
faulty qubits such that T1 and T2 are `None` in the `target.qubit_properties`. 

* fix handling of None in noise model construction from BackendV2
* add reno
* simplify a bit
* update docs

* Add Getting Started page (#1780)

This commit adds documentation "Getting Started" page.

* Add Get Started page
* Remove unused class

---------
Co-authored-by: Hiroshi Horii <[email protected]>

* avoid kernel crash from blas call errors (#1791)

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>

* fix fail of qobj run without run_options (#1792)

* fix fail of qobj run without run_options

* fix lint error

---------

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>

* Support parameterized global phase (#1814)

* Support parameterized global phase

Though `ParameterExpression` can be set to `QuantumCircuit.global_phase`,
Aer does not bind parameter values to it in simulation phase. This commit fixes
this problem by resolving values of `global_phase` with specified `parameter_binds`
in `AerSimulator.run`.

* define AER::CONFIG::GLOBAL_PHASE_POS and its pybind
* fix lint issues
---------
Co-authored-by: Jun Doi <[email protected]>

* check parameter_binds arguments for parameterized circuits (#1817)

Aer raises an error if `parameter_binds` is not specified though circuits have parameters.
This resolves the following issue:
#1773

* Set the number of qubits with the coupling map (#1825)

* Set n_qubits from coupling map

* Add a test and release notes

* Fix lint

---------

Co-authored-by: Hiroshi Horii <[email protected]>

* Fixing some typos (#1827)

* Update aer_densitymatrix.py

* Update aer_statevector.py

* Update README.md

* Update CONTRIBUTING.md

---------

Co-authored-by: Hiroshi Horii <[email protected]>

* Use transpile and run instead of execute in docstring (#1830)

* use transpile and run instead of execute in docstring

* use backend.run instead of execute in README

* use fake_provider for noise_model example

* Revert edits on README.md

* Update examples in docstring for qiskit_aer.noise

* Fix depolarizing noise model example

* Remove incorrect markup in noise/__init__.py

---------

Co-authored-by: Hiroshi Horii <[email protected]>

* Fix typos in aer_simulator, qasm_simulator docs (#1833)

* Fix typos.

* Add missing aer_simulator options.

* Update reference to SaveProbabilities according comment to PR.

* Upgrade to qiskit_sphinx_theme 1.12 (#1822)

* Warn if approximation=False and shots=None in Estimator (#1823)

* fix 1820

* rm unnecessary comment

* update docs

---------

Co-authored-by: Hiroshi Horii <[email protected]>

* Fix the grouping index bug in Estimator (#1839)

* Fix the bug

* lint

* Validate parameters of each gate in a circuit (#1834)

This commit adds checks of arguments (A number of qubits, clbits,
and parameters) for each gate to prevent from unexpected memory access
when a user defines wrong custom gate with a number of a standard gate.

* validate parameters of each gate in a circuit
* fix lint error
* fix lint error

* Correct a type of variance from complex to real (#1767)

Previously Aer Estimator wrongly returned a complex value as variance of estimation values.
This commit fixes this behavior to return a real value.

* update version in docs/conf.py

* Do not use circuit metadata to internally manage simulation results (#1772)

* Stop using circuit metadata to internaly manage simulation results

This fixes `AerSimulator` to use circuit metadata to maintain mapping
from input and output of an executor call. This fixes an issue
#1723.

* add index of AER::Circuit and ExperimentResult

* add a link to an input circuit in each experiment result

* fix MPI build break (#1842)

* Batch QuantumCircuit with multiple parameter_binds (#1840)

`Estimator` in Aer did not use parameter bindings appropriately. Backend is called multiple times 
to simulate a circuit with multiple parameter-sets. This commit is to call backend once for multiple
parameter-sets for a circuit.

* WIP
* refactor
* lint
* add reno

* add release note with prelude

* *Support initialize with int (#1841)

Previously `QuantumCircuit.initialize` was not correctly preocessed
if initial state is specified with single `int` value. This commit
fixes this issue by decomposing initialize instructions.

---------

Co-authored-by: Sam James <[email protected]>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
Co-authored-by: Matthew Treinish <[email protected]>
Co-authored-by: Luciano Bello <[email protected]>
Co-authored-by: derwind <[email protected]>
Co-authored-by: Jake Lishman <[email protected]>
Co-authored-by: Ian Hincks <[email protected]>
Co-authored-by: Hitomi Takahashi <[email protected]>
Co-authored-by: Jonathan Coates <[email protected]>
Co-authored-by: Ikko Hamamura <[email protected]>
Co-authored-by: Jun Doi <[email protected]>
Co-authored-by: Eric Arellano <[email protected]>
Co-authored-by: Deji Oyerinde <[email protected]>
Co-authored-by: Toshinari Itoko <[email protected]>
Co-authored-by: INNAN Nouhaila <[email protected]>
Co-authored-by: Davide Gessa <[email protected]>
Co-authored-by: Oleksii Borodenko <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
mypy Work related to support improving type hints in Qiskti code
Projects
None yet
Development

Successfully merging this pull request may close these issues.

6 participants