Commit Graph

6114 Commits

Author SHA1 Message Date
Jake Lishman c004a8195d
Revert "Pin Aer to 0.9.1 in CI (#7421)" (#7427)
This reverts commit 1ecd16a0c1.

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2021-12-20 11:34:11 +00:00
Julien Gacon 6742941a62
Add the dark version of the IQX color scheme (#7186)
* add IQX dark circuit style

* add reno

* add tests, fix I gate

* img tests don't support ddt package

* adjust background color

* fix test

* try fixing tests pt 2

* don't modify comment in untouched test

* fix controlled classical and CX color

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2021-12-17 19:48:00 +00:00
Jake Lishman 1ecd16a0c1
Pin Aer to 0.9.1 in CI (#7421)
The recent release of Aer 0.10 has major performance regressions, and
appears to be causing Terra's CI to fail with timeouts on Mac and Linux.
2021-12-16 13:45:20 +00:00
Jake Lishman 3562e268c7
Fix registerless bit conditions in circuit_to_instruction (#7395)
* Fix registerless bit conditions in circuit_to_instruction

This version of the change is stable for backports, but a more thorough
refactor of `circuit_to_instruction` is in order to support multiple
registers, overlapping registers and remove the creation of unnecessary
registers.

* Fix ambiguous cross-reference

* Be consistent in writing conditions

Co-authored-by: Kevin Krsulich <kevin@krsulich.net>

Co-authored-by: Kevin Krsulich <kevin@krsulich.net>
2021-12-13 15:20:21 -05:00
Jake Lishman 309bfb173e
Fix register conditions in control-flow builders (#7389)
* Fix register conditions in control-flow builders

Previously, the only resources tracked by the builder interface were the
"wires" used in the DAG representation of the circuit.  This meant that
registers in conditions were not added to the circuit bodies of the
blocks that contained them.  This did not raise any exception at the
time of circuit creation, but would subsequently crash later routines
such as conversions to the DAG, because the registers would not exist.

This commit also adds warnings to all the builder-interface internal
objects, noting that they should not be used by the public.  This should
have been in the original release.

* Add extra test case for coverage

* Change useless sort into set

* Add release note explaining private-access policy

* Fix typo

Co-authored-by: Kevin Hartman <kevin@hart.mn>

Co-authored-by: Kevin Hartman <kevin@hart.mn>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2021-12-09 23:57:48 +00:00
Jake Lishman 5c4cd2bbcf
Fix ParameterVector handling in QPY serialization (#7381)
* Add ParameterVector handling to QPY serialisation

This adds special handling for `ParameterVectorElement` instances within
circuits on serialisation to QPY.  These needed to be recreated into
the correct class (as opposed to a raw `Parameter`) so that their sort
order in `QuantumCircuit.parameters` would remain the same after a QPY
round trip.  Without special handling, once there were 10 or more
elements in the vector, the naming (suffixed numbers with no leading
zeros) would cause the sort order to be wrong.

Co-authored-by: Matthew Treinish <mtreinish@kortar.org>

* Add parameter vector support to PauliEvolutionGate qpy

* Add release note

* Fix docs typo

* Rename PARAMETER_VECTOR -> PARAMETER_VECTOR_ELEMENT

* Support ParameterVectorElements in ParameterExpressions

* Add compat tests for parameter vector in parameter expression

* Fix lint

* Update releasenotes/notes/fix-paramater-vector-qpy-52b16ccefecf8b2e.yaml

Co-authored-by: Jake Lishman <jakelishman@gmail.com>

* Emit warning in deserialization if a parameter vector isn't fully serialized in a qpy file

* Serialize a ParameterVectorElement global phase correctly

* Update test/python/circuit/test_circuit_load_from_qpy.py

Co-authored-by: Julien Gacon <gaconju@gmail.com>

* Improve docs

* Apply suggestions from code review

Co-authored-by: Jake Lishman <jakelishman@gmail.com>

Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
Co-authored-by: Julien Gacon <gaconju@gmail.com>
2021-12-09 19:18:37 +00:00
Kevin Krsulich d9ab98f2b3
Fix InverseCancellation pass to handle gates of different names. (#7383)
As reported in GH-7378, the InverseCancellation optimization pass
previously assumed that inverse gate pairs would always share a
common name, but this is not universally true. This commit updates
the pass to search for runs containing any of the gate names in the
gates_to_cancel list, instead of only the first.

Co-authored-by: Bruno Schmitt <bruno.schmitt@epfl.ch>

Co-authored-by: Bruno Schmitt <bruno.schmitt@epfl.ch>
2021-12-08 23:51:13 +00:00
Matthew Treinish 9af5ca181e
Add QPY serialization for PauliEvolutionGate (#7374)
* WIP: Add qpy serialization for PauliEvolutionGate

This commit adds serialization for the PauliEvolutionGate class so that
we can exactly reproduce a PauliEvolutionGate over QPY. This works by
bumping the qpy format version and adding new structs to represent the
PauliEvolutionGate and all it's child attribute types.

* Fix handling of operator in PauliEvolutionGate

This commit fixes the handling of the operator attribute in the
PauliEvolutionGate. With this commit we can serialize a
PauliEvolutionGate correctly with the exception of it's synthesis class
which still needs to be supported.

* settings for synth

* Add support for custom synthesis classes

* Expand test coverage

* Add release notes

* Update release note

* fix param binding in PauliEvo

* allow time as an int

* Apply suggestions from code review

Co-authored-by: Jake Lishman <jake@binhbar.com>

* Update qiskit/circuit/qpy_serialization.py

Co-authored-by: Jake Lishman <jake@binhbar.com>

* Update qiskit/circuit/qpy_serialization.py

* Rerun with latest black

* Close buffers when finished

* Fix release note wording

* Fix lint

* Adjust tests around extra layer of gates

Co-authored-by: Julien Gacon <gaconju@gmail.com>
Co-authored-by: Jake Lishman <jake@binhbar.com>
2021-12-08 21:43:49 +00:00
Jake Lishman 89b324c456
Reinstate and deprecate loose measure and reset functions (#7376)
Previously, the `QuantumCircuit` methods `.measure` and `.reset` were
defined as regular functions in `circuit/measure.py` (m.m. `reset`) and
monkey-patched onto `QuantumCircuit`.  Commit 2cd42b493 removed the
monkey-patching by defining them as regular methods, but did not
implement a deprecation period for the functions.  This reinstates them,
with the deprecation warning.
2021-12-08 17:11:25 +00:00
Luciano Bello a34644f109
documentation update: c_if needs val (#7375) 2021-12-08 12:01:41 +00:00
Matthew Treinish 1a1235a720
Fix VM image used for Linux release jobs (#7358)
This commit fixes the VM image we use in azure pipelines for the release
CI jobs that run on linux. For some reason (likely just a copy and
paste error that never was corrected) previously these jobs were set to
run on Ubuntu 16.04 which is end of life now and no longer available on
azure pipelines. This was the source of an error during the 0.19.0
release as when CI went to run the job it failed because it couldn't
find the requested image. This commit fixes this issue by switching the
jobs to use 'ubuntu-latest' which will also be the latest available
ubuntu lts release on azure pipelines. Which version we run doesn't
really matter because the wheel jobs run in docker and the sdist jobs
just run python to create an sdist (which just creates a tarball of the
project's source code).

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2021-12-07 23:51:13 +00:00
Jake Lishman d38620a6f3
Fix copying control-flow bodies in builder interface (#7368)
There are a few places where the structure of an element of
`QuantumCircuit.data` is specifically assumed to be

    Tuple[Instruction, List[Qubit], List[Clbit]]

rather than the more abstract

    Tuple[Instruction, Sequence[Qubit], Sequence[Clbit]]

For performance reasons, the control-flow builders used tuples to store
their arguments internally, because this prevents any copying being
necessary, and allows the arguments to be put in sets.  Now, in lieu of
changing the `QuantumCircuit` data structure to be more abstract, which
would have performance implications, or to require the tuples, which may
create more bugs, we just make the builder interface convert its tuples
to lists on output.

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2021-12-07 21:20:47 +00:00
Jake Lishman 29c62c4bf5
Fix circuit instruction conversion with loose bits (#7365)
Previously, `circuit_to_instruction` and `circuit_to_gate` were finding
the number of bits in a circuit by summing the sizes of the registers.
This failed if any bits were not in a register, or in more than one
register.  Instead, we can simply ask the input circuit how many bits it
contains.
2021-12-07 12:30:21 -05:00
Jake Lishman 2af1016f7b
Bump black to the latest version (#7363) 2021-12-07 14:57:08 +00:00
Matthew Treinish 8c9e01d33f
Drop support for Python 3.6 (#7295)
* Drop support for Python 3.6

As has been advertised for some time the Qiskit 0.19.0 release is the
last release which supports Python 3.6 (which goes End of Life in
Decemeber). This commit drops support accordingly so that the minimum
supported Python version is 3.7.

* Add release note
2021-12-06 23:30:00 +00:00
Matthew Treinish 0248c77cb2
Bump version strings post release (#7357)
Now that qiskit-terra 0.19.0 is out the door we should bump the version
string on master to show the source version we're installing is newer
than what's been released.
2021-12-06 16:46:09 -05:00
Jake Lishman d5094eeca2
Prepare release notes for Qiskit Terra 0.19 (#7329)
* Move 0.19 release notes into subdirectory

* Add missing objects to imports and API docs

A few objects added in new features for the 0.19 cycle did not get added
into higher-level `__init__` files, either as imports or documentation
links.  This adds several documentation links in, and fixes some
cyclic imports that were previously hidden due to the objects not being
fully imported.

* Update incorrect deprecation notice

These deprecation notices were written in a PR that was originally
targetted for the 0.18 release but later got shifted to 0.19.

* Reorganise pulse documentation to avoid duplication

Previously, autosummary documentation files were being generated for
most objects in `qiskit.pulse` in two namespaces: `qiskit.pulse` and
(e.g.) `qiskit.pulse.library`.  In other cases, the module-level
documentation was not being generated at all.  This moves the
responsibility for defining all the definitions into the respective
submodules, and turns the `qiskit.pulse` docstring into a series of
`.. automodule::` calls.  The relevant module docstrings are merged
with any content that was already in the `qiskit.pulse` docstring, to
ensure that the displayed documentation on the `qiskit.pulse` page is
almost identical to what it was before.

Various Sphinx crossreferences within the `pulse` module (and referring
to it from elsewhere) were previously broken, in part because of the
duplication.  It should be more reliable when creating crossreferences
now.  The abstract base classes are also added in `.. autoclass::` calls
in suitable locations, since they are a common source of failed Sphinx
crossreferences elsewhere.

(It's easy to accidentally get the duplication when using `autosummary`.
If it does need to be used on more than one page, then only the
canonical path should use the `:toctree:` directive.  Pulse also had
more of this than other places because it's generally a bit more
thoroughly documented.)

* Reformat 0.19 release notes

This reformats the release notes for Terra 0.19, canonicalising the
style and ensuring that all Sphinx crossreferences link correctly.  In
some cases there is no suitable target for documentation (especially in
the case of removals), so these are left as simple monospaced font.

* Fix typo

Co-authored-by: Matthew Treinish <mtreinish@kortar.org>

* Clarify ExactReciprocal documentation

* Fix docs warning

* Move backend V2 note

* Move RZX calibration release note

* Revert restrictions filetypes in text drawer

These were added in gh-6487.  In general, there is no reason to enforce
that text must go into a file with a `.txt` extension; the extension is
a rather Windows-specific convention, and not necessary.

* Remove release notes already included in 0.18 backports

* Correct future warning in pauli_basis

* Rewrite release notes

Also rejig a type hint that Sphinx always attempted to resolve.

Co-authored-by: Matthew Treinish <mtreinish@kortar.org>

* Add 0.19 release prelude

* Remove unused import

* Updated grover reno

* Update releasenotes/notes/0.19/qaoa-parameters-49e4524ed2d3e875.yaml

* Update release notes

Co-authored-by: Matthew Treinish <mtreinish@kortar.org>

* Move another merged release note

* spelling

* Fix typos in documentation

Co-authored-by: Luciano Bello <bel@zurich.ibm.com>

* Reformat new release notes

* Update QASM3 note with new features

This adds some information on how the QASM 3 exporter works with the new
control-flow constructs, and removes the line saying it works with
``defcal``.  The latter is because we do not actually support this; we
can recognise "opaque" gates, but we can't emit anything sensible for
them, so we currently just fail loudly with a suitable error.

* Add BaseReadoutMitigator to documentation

* Updates from Luciano

Co-authored-by: Luciano Bello <bel@zurich.ibm.com>

* Update BasisTranslator release note

* Add an invisible code block

* Rewrite PulseGate pass release note

* Update release notes

Co-authored-by: Matthew Treinish <mtreinish@kortar.org>

* Remove note about type hints

* Fix PulseGate typos

* Revert default import of rzx_templates

This was made in order to simplify some import paths, but as a side
effect it caused ten `QuantumCircuit`s to be created on import of
`qiskit`, which spoiled the QPY backwards compatibility tests and likely
had import performance implications.

The import of this likely should not need to create circuits, but for
now, we revert its import rather than making a change this close to
release.

Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
Co-authored-by: Abby-Mitchell <abby.mitchell@btinternet.com>
Co-authored-by: Luciano Bello <bel@zurich.ibm.com>
2021-12-06 18:19:30 +00:00
Christopher J. Wood efd8b1388b
Add copy method to Options (#7353)
* Add copy method to Options

* black

* Convert Options.copy() to __copy__

* Update the test

* Remove stale release note

Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
2021-12-06 13:39:47 +00:00
Matthew Treinish 1a9f93804f
Start making the transpiler Target aware (#7227)
* Start making the BasisTranslator Target/BackendV2 aware

In #5885 we added the next version of the abstract Backend interface
BackendV2 which added the concept of a Target which represents a
compiler target for the transpiler. It contains all the information
about the constraints of a backend for the compiler to use and replaces
the combination of basis_gates, coupling_map, etc and expands the
representation to model more complex devices. However, in #5885 we only
introduced the interface and didn't modify the transpiler to use the
Target natively or any of the extra information it contains. This commit
is the start of the process of updated the transpiler to work with a
target natively. To start if a backend has a target that is now passed
through from transpile to the passmanager_config so we can start passing
it directly to passes as we enable it. Then the basis translator is
updated to work natively with a target instead of the basis gates list
it used before. In addition to using a target directly support is added
for heterogeneous gate sets so that target instructions can work on only
a subset of qargs.

Building off this in the future There are additional features in target
that we might want to expand support for in the BasisTranslator in the
future, such as supporting custom variants of the same gate, or handling
fixed angle rotation gate variants, etc.

* Deduplicate computation of non-global operations

The modifications to the BasisTranslator needed to compute operations in
the basis which weren't global for a particular target and accomplished
this via a dedicated helper function in the pass module. However the
BackendV2 class had an identical function for accomplishing this so it
could log a warning when basis gates were queried. This commit
deduplicates them and creates a dedicated method on the target for
returning the list (and caches it so it's only computed once per target).

* Add missing check for a dag calibration on the target path

* Rename extra_basis_transforms -> qarg_local_basis_transforms

* Make GateDirection and CheckGateDirection Target aware too

In debugging the basis translator changes we realized that we should be
relying on the GateDirection pass to fix directionality on non-symmetric
2q gates instead of trying to handle it natively in the basis translator
for now. To do this with a target we need to make the GateDirection and
CheckGateDirection passes target aware and update the basis translator
to treat all 2q gates as symmetric. This commit makes this change and
updates the preset pass managers to pass targets to GateDirection and
CheckGateDirection (also updates the rule determining if we need to run
them to leverage the target not the coupling map).

* Handle working with a non-global 1q basis

In the case of a non-global 1q basis where there are 1q gates only
available on a subset of qubits the basis translator was not correctly
able to translate multi-qubit gates. This was due to how the local basis
search was done just on the global target basis gates and the local
target basis gates for that argument, with multi-qubit gates the
translations also typically involve a 1q rotation. But if there are no
global 1q gates those rotation gates can't be translated and the search
fails. To address this the 1q local gates for the individual qubits in
the multi-qubit argument are added to the local search for non-global
multi-qubit gates.

* Also use target for gate direction in level 0

* Add release notes

* Consider all non-local subset operations for multiqubit non local gates

* Update qiskit/providers/backend.py

Co-authored-by: Kevin Krsulich <kevin@krsulich.net>

* Finish incomplete strict_direction docstring

* Adjust tests to be fp precision tolerant

* Relax tests further for windows

* Update qiskit/transpiler/target.py

Co-authored-by: Kevin Krsulich <kevin@krsulich.net>

* Correct detection of non-global ops with strict_direction=False

Co-authored-by: georgios-ts <45130028+georgios-ts@users.noreply.github.com>

* Fix handling of non-local subset searching

* Simplify target path in gate direction pass

* Rename extra_source_basis -> local_source_basis

* Rename incomplete_basis -> non_global_operations

* Rename qarg_with_incomplete -> qargs_with_non_global_operation and incomplete_source_basis -> qargs_local_source_basis

* Update target handling in transpile()

This fixes 2 issues found in review with the the transpile() functions
handling of target. First if a target kwarg is passed by a user that
target will be used instead of the backend for not just the target but
also all derived quantities (such as coupling_map and basis_gates).
Also previously the backend_properties field was not being correctly
built from a target (both for a backendv2 or a standalone target). So a
converter helper function was added to go from a target and build a
BackendPropeties object from the data contained in the target. This will
enable noise aware transpilation until the transpiler passes are all
target aware.

* Calculate qargs with non global operation once per pass instance

* Expand docstring to include non-global operation behavior description

* Add test assertion that it matches the target

* Add GateDirection to the optimization loop for level 3

Optimization level 3 is different from the other lower optimization
levels because it uses unitary synthesis by default. The unitary
synthesis pass is basis and coupling map to optimize the synthesized
circuit for a unitary to be hardware efficient. However when using a
target the basis gates and coupling map don't give a complete picture of
the device constraints (mainly the non-global gates if any). To account
for this we need to run the gate direction pass after unitary synthesis
to correct an incorrect decision the unitary synthesis pass might make
based on it's incomplete data. Once UnitarySynthesis is target aware we
probably do not require this anymore.

* Add tests of 5q ghz on non-linear non-global target with different entangling gates

* Use frozenset instead of tuple for local search and transformation tracking

* Fix copy paste error for gate error in _target_to_backend_properties

* Apply suggestions from code review

Co-authored-by: Kevin Krsulich <kevin@krsulich.net>

* Only run gate direction in level 3 with a target

* Move target overrides inside _parse_transpile_args()

Co-authored-by: Kevin Krsulich <kevin@krsulich.net>
Co-authored-by: georgios-ts <45130028+georgios-ts@users.noreply.github.com>
2021-12-04 00:24:52 +00:00
Jake Lishman 37684d48a7
Hack in SimpleNamespace-like functionality to Options (#7347)
* Hack in SimpleNamespace-like functionality to Options

This is an awful hack to support various SimpleNamespace-like operations
that qiskit-dynamics are using.  We need to transition downstream
packages to the new Options API, but in the meantime, this makes the
Options class behave as much like a SimpleNamespace as it can, while
still keeping the new instance attributes and methods.

* Suppress pylint bad assignment error

I was surprised at how little pylint complained about the actual
implementation, but it complains about the usage.

This could conceivably be called a pylint bug; because we override
`__setattr__`, pylint should perhaps recognise that general attribute
setting might be allowed.
2021-12-02 22:32:33 +00:00
Shelly Garion ae55844b2b
Readout mitigator classes (#6485)
* started BaseReadoutMitigator class

* formatting base_readout_mitigator_class

* add CompleteReadoutMitigator class

* update qiskit.result objects

* remove unnecessary methods from qiskit.result objects

* remove empty line

* remove unnecessary methods from base_readout_mitigator

* quasi_probablities function returns QuasiDistribution object

* changed diagonal type to Collable

* changed diagonal type to Callable

* updates following review

* style

* add init file

* unify API

* style

* fix lint errors

* add docs

* Initial mitigator tests

* Fixes to test mitigators

* Linting

* style of the test

* move mitigation out of quantum_info

* small fix in test

* add stddev upper bound based on gamma

* remove @staticmethod

* start tensored mitigation class

* temporary move methods to base class

* remove comment

* add new methods

* style

* add quasi_probabilities method in tensored mitigation

* add from_backend method

* Small fix to how the backend is called

* Adding script for Aer-based data generation for mitigator tests

* Rewriting the mitigator tests to be independent of Aer

* Additional tests and small bugfix

* Marginalization test working

* Some code restructure and bug fixes

* Different handling of stddev

* Added from_backend test (not working yet)

* from_backend bugfix

* Moving function to utils

* Documentation

* Linting

* fix import Aer in generate_data

* style

* fix lint errors

* more lint errors

* Test for expectation value

* Changes to ideal data in tests; all tests are now working

* More diagonal tests

* change stddev type to QuasiDistribution

* add release notes

* style

* some review comments

* refactor: complete --> correlated

* refactor: tensor --> local

* add qubits to init in correlated mitigation

* add qubits to init and from_backend in local mitigation

* use einsum directly on probs_vec in tensored mitigation

* update result Counts

* remove import

* refactor qubits --> self._qubits

* fix lint

* more refactor qubits --> self._qubits

* handle stddev_upper_bound

* handle docs

* add a test for expval stddev

* style for test

* fix lint

* Return quasi distributions with stddev

* Added test to detect current qubits-overwrite bug

* Changes to the handling of qubits in method (tests now work)

* Mitigator stddev test

* Break down counts_probability_vector

* Linting

* add docstrings

* minor changes in documentation foloowing review

* Small fixes and change to the way the qubits parameter is handled

* Mitigators now correctly handle qubit susbets

* Linting

* fix lint errors

* minor fixes

* Small fixes and error handling test

* minor fix in the test

* move the mitigation folder to qiskit.result.mitigation

* move the mitigation tests to test.python.result

* update import in mitigation files

* Attempting to fix cyclic dependancy error

* update import

* update import

* Attempting to fix cyclic dependancy error

* style

* updates following review comments

* remove generate data functions

* add more details in classes docstrings

* add more details in release notes

* move test_data to test_mitigators

* Update release note

Co-authored-by: Gadi Aleksandrowicz <gadia@il.ibm.com>
Co-authored-by: gadial <gadial@gmail.com>
Co-authored-by: Christopher Wood <cjwood@us.ibm.com>
2021-12-02 20:53:31 +00:00
Kevin Krsulich e77acc6aaf
Omit QuantumCircuit as a parameter when drawing ControlFlowOps. (#7345)
Most ControlFlowOps have at least one param of type QuantumCircuit
which qiskit.visualization.utils.get_param_str will attempt to
stringify and display as an instruction parameter. This largely
doesn't work, since the circuit's string will contain newlines, so
instead draw ControlFlowOps with only their name.

Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
2021-12-02 18:42:48 +00:00
Jake Lishman 9ba51b5cc9
Add control-flow builder interface (#7282)
* Add control-flow builder interface

This adds a builder interface for control-flow operations on
`QuantumCircuit` (such as `ForLoopOp`, `IfElseOp`, and `WhileLoopOp`).
The interface uses the same circuit methods, but they are now overloaded
so that if the ``body`` parameter is not given, they return a context
manager.  Entering one of these context managers pushes a scope into the
circuit, and captures all gate calls (and other scopes) and the
resources these use, and builds up the relevant operation at the end.
For example, you can now do:

    qc = QuantumCircuit(2, 2)
    with qc.for_loop(None, range(5)) as i:
        qc.rx(i * math.pi / 4, 0)

This will produce a `ForLoopOp` on `qc`, which knows that qubit 0 is the
only resource used within the loop body.  These context managers can be
nested, and will correctly determine their widths.  You can use
`break_loop` and `continue_loop` within a context, and it will expand to
be the correct width for its containing loop, even if it is nested in
further `if_test` blocks.

The `if_test` context manager provides a chained manager which, if
desired, can be used to create an `else` block, such as by

    qreg = QuantumRegister(2)
    creg = ClassicalRegister(2)
    qc = QuantumCircuit(qreg, creg)
    qc.h(0)
    qc.cx(0, 1)
    qc.measure(0, 0)
    with qc.if_test((creg, 0)) as else_:
        qc.x(1)
    with else_:
        qc.z(1)

The manager will ensure that the `if` and `else` bodies are defined over
the same set of resources.

This commit also ensures that instances of `ParameterExpression` added
to a circuit inside _all_ control flow instructions will correctly
propagate up to the top-level circuit.

* Fix linter complaints

* Fix typos

Co-authored-by: Kevin Hartman <kevin@hart.mn>

* Add extra error check

* Remove useless early return

* Document qubits, clbits in ControlFlowBlockBuilder.__init__

* Remove comment that is likely to stagnate

* Add extra else test

* Improve developer documentation in InstructionPlaceholder

* Remove expected failure from test

This branch contains the fix that this test depended on.

* Remove unused import

* Change order of for_loop parameters

This changes the parameter order of `QuantumCircuit.for_loop` to be

    indexset, [loop_parameter, [body, qubits, clbits]]

whereas previously it was

    loop_parameter, indexset, [body, qubits, clbits]

Similar changes were made within the constructor of `ForLoopOp` and its
parameters.  This is to improve ergonomics of the builder interface,
where it is not generally necessary to specify a loop variable, since
one is allocated for the user.

Co-authored-by: Kevin Hartman <kevin@hart.mn>
2021-12-02 17:06:18 +00:00
Christopher J. Wood efbf436297
Speed up passmanager if it is empty (#7334)
* Speed up passmanager if it is empty

* remove unneeded elif

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2021-12-02 11:47:33 +00:00
Takashi Imamichi 275a18d651
Fix performance regression of VQE by #7217 (#7338)
* Fix performance regression of VQE

* Update qiskit/opflow/converters/circuit_sampler.py

Co-authored-by: Julien Gacon <gaconju@gmail.com>

Co-authored-by: Julien Gacon <gaconju@gmail.com>
2021-12-02 10:39:36 +01:00
Jake Lishman c95ec37123
Fail safe in the QASM 3 exporter (#7336)
There were previously parts of the QASM 3 exporter where it attempted to
do its best guess at what should happen, even when this always produced
entirely incorrect results.  These were subroutine definitions with
parameters, opaque gates (`defcal`) and non-included gates with
parameters.

We now choose to fail loudly with a message that we do not currently
support certain features, rather than outputting a meaningless
programme.  For the parameterised gates, we now force the exporter to
output a separate definition for every instance of a gate if it cannot
be sure that it has the most general form to start with.  The code it
outputs looks silly (the gates take parameters, but do not use them in
their definitions, and each gate may be defined many times), but the
semantics of the programme will actually be correct.

See gh-7335 for the parameterisation problem.

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2021-12-02 03:59:43 +00:00
Matthew Treinish b68b712b94
Update top level provider documentation for BackendV2 (#7323)
* Update top level provider documentation for BackendV2

As a follow-on to #5885 this commit updates the top level
qiskit.providers module documentation for BackendV2. This primarily
consists of two things, updating the writing a provider section to use
BackendV2 instead of BackendV1 and adding a migration section on user
facing changes between BackendV1 and BackendV2.

* Apply suggestions from code review

Co-authored-by: Luciano Bello <bel@zurich.ibm.com>

* Update qiskit-aqt example wording

* Fix lint

Co-authored-by: Luciano Bello <bel@zurich.ibm.com>
2021-12-01 23:16:10 +00:00
Jake Lishman 2c402dd5c2
Add control flow support to QASM 3 exporter (#7299)
* Add control-flow support to QASM 3 exporter

This teaches the OpenQASM 3 exporter, AST and printer to handle the new
control-flow instructions, and output them to valid OpenQASM 3.

There are nodes in the temporary AST to represent these, but significant
extra changes were required as well to support scoping and scoped
look-ups.  This commit does not add a proper symbol table, nor a proper
type system, which is how these look-ups should be handled, but instead
makes a relatively quick hack to patch in looking up qubits and clbits
from outer scopes.  This is because the functionality is being added
close to release of Terra 0.19, and we don't want to (nor have time to)
make overarching changes to the whole infrastructure right now.

The most notable change is that the 'context' management of the exporter
is now a nested stack; the outer is for "outer" contexts, like the main
program and subroutine/gate definitions (where we don't expect to share
scoped variables or qubits), while the inner stacks are for control-flow
scoping (where we do).  To _very quickly_ support these look-ups, we add
a `_Scope` struct that includes a look-up map of bits.

While refactoring the bit-look-ups to support the scoped access, it
became trivial to support loose bits, and to break the old assumption
that all bits are always in registers.  The exporter now supports loose
classical bits and qubits, and registers with overlapping bits.  For
classical bits, the export will fail with the default settings if there
are overlapping bits because there is little backend support for
classical aliases, but the `alias_classical_registers` option will swap
the handling to the alias form used for quantum registers, which can
handle overlapping bits.

* Use generic Enum, not IntEnum

In this case, the values weren't meant to be interchangeable with
integers anyway, it's just that the integer width is the only payload
information in the type.  In Python 3.6, the inheritance would break
when using IntEnum with multiple inheritance (due to how it already
inherits from int and Enum), so the solution is just to swap the type.

* Build ast.FloatType lookup from enum values

* Fix typos in tests

* Swap skip to expectedFailure

* Use loop parameter in for-loop tests

* Use capital letters for enum constants

* Clarify dangling-else comment

* Fix missing enum name changes

Co-authored-by: Kevin Krsulich <kevin.krsulich@ibm.com>
2021-12-01 20:39:02 +00:00
Matthew Treinish 6b6c68318a
Fix arguments for RZXCalibrationBuilder and EchoRZXWeylDecomposition (#7331)
* Fix arguments for RZXCalibrationBuilder and EchoRZXWeylDecomposition

The RZXCalibrationBuilder and EchoRZXWeylDecomposition transpiler passes
were previously taking BaseBackend instances as arguments. Besides that
being a deprecated class which will be removed soon, it also is
incorrect because backend objects are not guaranteed to be pickleable so
when a pass manager runs in parallel processes this will cause an error.
This was never caught because these passes aren't part of any default
pass managers and their tests don't include running them as part of
transpile().

To fix this passes typically take the properties of a backend they
require. This is being reworked for BackendV2 in #5885 so a target
object can be used to encapsulate the model of a backend so we have a
single data structure to pass around, but until that is the minimum
backend version we need to also support taking the individual components
for BackendV1 and BaseBackend.

This commit changes the pass constructors to take only use the parameters
from the backend object used in the pass internals and stop requiring a
backend object be used to construct an instance of either pass.

* Deprecate backend for RZXCalibrationBuilder instead of removing
2021-12-01 17:57:04 +00:00
Matthew Treinish 3694fff80f
Add BackendV2 abstract class (#5885)
* Add BackendV2 abstract class

This commit adds a new abstract class that adds a new version of the
backend abstract class. The primary changes being made in this class are
that instead of using BackendConfiguration for immutable characteristics
of the backend those are instead exposed as read only attributes of the
Backend object itself. This also takes some time to improve how we
represent some core data about a backend. The primary example of this is
that basis gates are no longer a list of names but instead a list of
Gate objects.

* Adjust GateMap to be a dict instead of a graph

This commit reworks the GateMap class to be an internal dict of gate
instances to qargs (with optional properties) instead of building a
graph. The graph representation was inherently limited in that it
couldn't describe multiqubit gates involving > 2 qubits.

* Add fields from properties to v2 backend interface

This commit finishes by adding the defined optional methods for querying
the equivalent of the backend properties on the new backend v2
interface. The per gate properties were already defined in the gate map
class as optional fields for each gate entry so this defines methods for
the per qubit fields (t2, t1, freq, readout error and duration). While
not every backend supports these fields they're common ones that most
could implement (assuming the data is available). For any other backend
properties they can be custom fieldss in a subclass.

* Adjust GateMap structure

* Rename GateMap -> Target and drop readout error (as it'll be per instruction error)

* Add instruction durations method to target

* Add optional dt properties to backend object

* Add instruction durations method to backendv2

* Fix lint

* Rename max_experiments -> max_circuits

* Add two_q_gate option to Target.coupling_map()

* Add option for a list of qubits to t1, t2, and frequency

* Change list return to numpy array for t1 and t2

* Drop qubit frequency

* Add pulse to instruction durations

* Update units for dt and dtm

* Update qiskit/transpiler/target.py

Co-authored-by: Naoki Kanazawa <nkanazawa1989@gmail.com>

* Fix type hints for t1 and t2

* Fix transpile() to actually use BackendV2 correctly

* Add transpile() test case with BackendV2

* Add repr for InstructionProperties

* Tweak docs

* Replace get_qargs_from_name with get_instructions_for_qarg

* Add tests for target

* Fix black's insane formatting choice

* Add more target tests

* Cleanup debug prints

* Make Target a mapping

* Rename get_gate_from_name to get_instruction_from_name

* Fix test issue with rename of get_gate_from_name

* Add support for running schedule() with a backend v2

* Add method to update instruction properties in target

* Fix caching

* Add tests for new target methods

* Fix lint

* Add support for qargs being None in ideal simulator case

This commit adds support for a backend setting the qargs on an
instruction to None as a shorthand for everything. This is useful for
things like ideal simulator backends that don't have any constraints on
which qubits an instruction can run on and just have a set of supported
instructions and a number of qubits supported by the simulator.

* Add test for ideal sim target instruction_schedule_map() method

* Add release note

* Add BackendV2 to autodoc

* Drop distance() and distance() matrix from Target

* Fix leftovers in doc strings

* Add __str__ for target

* Add logging when instruction_names includes instructions not on all qubits

* Documentation fixes from code review

Co-authored-by: Naoki Kanazawa <nkanazawa1989@gmail.com>

* Use seconds everywhere

* Fixes from recent changes

* Add update_from_instruction_schedule_map() method

* Use defaultdict for _qarg_gate_map in target

* Explicitly add ScheduleBlock to backend.run()

* Tweak docs for target

* Add pulse channel abstract methods to BackendV2 class

* Fix lint

* Improve target's update_from_instruction_schedule_map

* Add timing constraints to the target

* Fix typos in release note

Co-authored-by: Ali Javadi-Abhari <ajavadia@users.noreply.github.com>

* Re-export FakeBackendV2 in qiskit.test.mock

* Update target docstring example

* Make properties optional on Target.add_instruction()

For the case of ideal simulators for each instruction they would have to
call something like add_instruction(XGate(), {None: None} which is
tedious for every instruction. This commit makes the properties argument
optional and if not specified default to {None: None} this enables ideal
simulators to just call add_instruction(XGate()) for each instruction
the simulator supports.

* Add docstring type to BackendV2.target attribute

* Make Target.instructions property return tuple and add operations

* Rename instruction property schedule -> calibration

* Add optional backend metadata as constructor kwargs

* More instruction->Operation renames

* Remove conditional and max_shots abstract properties

The conditional property isn't needed and should be included in the
target. The max_shots property should be expressed in the Option as
bounds or validation on setting.

* Add optional validators to Options object

This commit adds optional validators for the Options object. This lets a
user constructing an Options object (typically a Backend/provider
author) optionally set bounds for numeric values, types, or valid choices
for any field in the Options object. This will be validated when the
value is updated and shown in a human readable format in the __str__
output for the Options object.

* Include dt in output InstructionDurations from Target

Co-authored-by: itoko <15028342+itoko@users.noreply.github.com>

* Add QubitProperties class and qubits() backend method

This commit adds a new optional method to BackendV2 which when defined
by a BackendV2 subclass returns a QubitProperties class for the
specified Qubits. QubitProperties is a new data container class for the
properties of a qubit such as t1, t2 and frequency. This replaces the
previous optional methods t1 and t2 as the storage location for these
properties. Those methods are updated to work using qubits() directly.
The tests are also updated to validate these methods work as expected.

* Add instruction_properties() method

* Fix lint in mock backend

* Make provider backref optional and fix docstring

* Rename BackendV2.qubits() BackendV2.qubit_properties()

* Add note to QubitProperties docstring on subclassing

* Fix Options.set_validator() docstring

* Add missing **fields docstring to BackendV2 init

This is just copied from BackendV1 which has the same argument on it's
constructor.

* Remove t1/t2 methods from BackendV2 class

* Remove unused imports

* Remove properties field from Properties classes

* Apply suggestions from code review

Co-authored-by: Ali Javadi-Abhari <ajavadia@users.noreply.github.com>

* Rename InstructionProperties.length -> duration

* Docstring improvements and more instruction->operation

* Update releasenotes/notes/add-backend-v2-ce84c976fb13b038.yaml

Co-authored-by: Kevin Krsulich <kevin@krsulich.net>

* Rename and fix incomplete basis computation

* Tweak release note wording on custom attributes of backend

Co-authored-by: Kevin Krsulich <kevin@krsulich.net>

* Finish set_validator docstring on options class

* Update qiskit/providers/backend.py

Co-authored-by: Kevin Krsulich <kevin@krsulich.net>

* Apply suggestions from code review

This commit makes several changes found in code review.
It fixes a typo with __slots__ for QubitProperties, fixes string formatting
for a raised error, updates a list comprehension to a more performant syntax,
and fixes release note formatting.

Co-authored-by: Jake Lishman <jake@binhbar.com>

* Return dict .keys() directly for Target properties

This commit updates the return of a couple property methods on the
Target class to return dict.keys() instead of set(dict) as the keys
return type implements the abstract Set collections interface and
returns just a read only view of the dict's keys instead of a mutable
copy. For this api the lower overhead and read-only nature are better
choices than returning a set copy.

Co-authored-by: Jake Lishman <jake@binhbar.com>

* Fix stray use of properties attr in QubitProperties

* Update stray set() return for property

* Apply suggestions from code review

Co-authored-by: Kevin Krsulich <kevin@krsulich.net>

* Rename Target.get_qargs() -> qargs_for_operation_name()

* Fix lint

* Rename Target.coupling_map() -> build_coupling_map()

* Fix test name for discovery

* qarg -> qargs in target method arguments

* Add target to docs build

* Fix target docs

* Fix lint

* Tweak documentation for target to make intent and future clear

* Fix typo in QubitProperties docstring

Co-authored-by: Rathish Cholarajan <rathishc24@gmail.com>

Co-authored-by: Naoki Kanazawa <nkanazawa1989@gmail.com>
Co-authored-by: Ali Javadi-Abhari <ajavadia@users.noreply.github.com>
Co-authored-by: itoko <15028342+itoko@users.noreply.github.com>
Co-authored-by: Kevin Krsulich <kevin@krsulich.net>
Co-authored-by: Jake Lishman <jake@binhbar.com>
Co-authored-by: Rathish Cholarajan <rathishc24@gmail.com>
2021-12-01 14:25:20 +00:00
Matthew Treinish b807eb4421
Adjust imports in aqc plugin to avoid discovery overhead (#7327)
This commit tweaks the imports for the aqc plugin to make the optimizer
and other aqc method imports occur at run time only. Previously these
were done at the module level, which is normally best practice for many
reasons, but in this specific case doing plugin discovery causes the
module to be loaded (and the plugin class instaniated) even if the
plugin is not specified by the user. The imports for aqc are fairly
heavy as both the algorithms tree and scipy can be slow to load. To
avoid the overhead on discovery these imports are moved to runtime so we
only load them if the aqc plugin is used and these imports are needed.

Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
2021-12-01 12:17:23 +00:00
Julien Gacon 0196754635
Two-step transpilation for variational algorithms (#7217)
* first working version

* use additional kwarg, not dict

* add test

* add reno

* black & type hint in tests

* add more docs

* log based testing

* avoid enum and pass pass managers in transpile

* docs

* Apply suggestions from code review

Co-authored-by: Matthew Treinish <mtreinish@kortar.org>

* update docs

Co-authored-by: Luciano Bello <bel@zurich.ibm.com>
Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2021-11-30 21:56:12 +00:00
Luciano Bello fe0abaa749
Unroll3qOrMore before layout allocation stage in the levels 0, 1, and 2 (#7251)
* level 0

* level 0

* level 1 and 2

* level 1 and 2

* always unroll

* reduce diff

* reno

* _unroll3q without coupling map
2021-11-30 19:03:54 +00:00
Almudena Carrera Vazquez 4a94b770e3
Implement Qdrift as ProductFormula (#7281)
* cast qdrift as a product formula

* release note and minor style changes

* add test and modify error message

* change evo to evolution_circuit and delete suzuki check

* fix lint

* fixes from PR comments

* remove sampled_ops property

* seed the random generator

* Update qiskit/synthesis/evolution/qdrift.py

Co-authored-by: Julien Gacon <gaconju@gmail.com>

* fix constant coefficients and cyclic import

* fix small mistake in the construction of pauli_list

* remove old leftover comment

* num_gates should be int & add functional test

* update test and evolution time in sampled_ops

Co-authored-by: Julien Gacon <gaconju@gmail.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2021-11-29 17:30:05 +00:00
Luciano Bello a0e2a29a3a
Define __all__ for qiskit (#7274)
* Remove circuit submodule from qiskit/__init__ namespace

* __all__

* __all__

* reno

* add __version__

* how to fix

* Update releasenotes/notes/7274-6f57628a7995a461.yaml

Co-authored-by: Jake Lishman <jake@binhbar.com>

* remove user_config

* remove __version__

* Reinstate private names defined in module

Co-authored-by: Jake Lishman <jake@binhbar.com>
Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
2021-11-27 00:55:31 +00:00
Dani Guijo ec9876a071
Add add_bits parameter to QuantumCircuit.measure_all (#7305)
* Fixed issue #4158 by adding the add_creg parameter to the measure_all attribute in quantumcircuit

* Fixed issue #4158 by adding the add_creg parameter to measure_all

* Fixed issue #4158 adding add_creg to measure_all

* Fixed issue #4158 by adding add_creg parameter to measure_all

* Fixed issue #4158 by adding add_creg parameter to measure_all

* Fixed issue #4158 by adding add_creg parameter to measure_all

* Fixed issue #4158 by adding add_bits parameter to measure_all

* Fixed issue #4158 by adding add_bits parameter to measure_all

* Fixed issue #4158 by adding add_bits parameter to measure_all

* Fixed issue #4158 by adding add_bits parameter to measure_all

* Fixed issue #4158 by adding add_bits parameter to measure_all

* Fixed issue #4158 by adding add_bits parameter to measure_all

* Update measure_all-add_bits-8525317935197b90.yaml

* Reformat documentation and release note

Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2021-11-26 22:55:15 +00:00
Edwin Navarro c07c2cc986
Fix single clbit display in condition for all 3 circuit drawers (#7285)
* Get mpl and utils conditions working

* Almost on text drawer

* Finish text drawer

* Cleanup

* Finish latex and fix tests

* Working on measure with condition in utils

* Lint

* More lint

* Finish 7248 and 7284 plus measure issues

* Add mpl tests

* Fix mpl tests

* Add latex and text tests and bug fixes

* Lint and update image

* Reno and fix image

* Image

* Fix measure with registerless bit

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2021-11-26 21:42:42 +00:00
Kevin Hartman 413ec5e865
Rework RemoveFinalMeasurements pass (bug fixes) (#7196)
* Unit test RemoveFinalMeasurements pass.

* Rework calculation of final ops in RemoveFinalMeasurements.

* Rework creg and clbit elimination.

* Add remove_idle_cregs method to DAGCircuit.

* Use DAGCircuit.remove_idle_cregs.

* Remove wire from input/output_map on removal.

* Allow cregs with busy bits to be removed.

For now, just warn if a busy bit is left without any referencing cregs.

* Remove wires from DAGCircuit.clbit on removal.

* Support removal of individual clbits.

* Code cleanup and comments.

* Fix ignore of non-idle clbits.

* Fix scoping bug in remove_cregs.

* Fix bug with unreferenced clbit removal.

* Return early to avoid allocations.

* Improve unit testing for RemoveFinalMeasurements pass.

* Fix bug in remove_idle_clbits.

* Improve busy bit error message when removing idle bits.

* Remove unused imports.

* Fix comment typo.

* remove_clbits now ignores nonremovable bits for cleaner client code.

* Fix issues with QuantumCircuit.remove_final_measurements.

* Run black.

* Pylint fixes.

* Run black again.

* Handle individual clbits in QuantumCircuit.remove_final_measurements.

* Run black.

* Index into reg tuple in remove_final_measurements.

* Add test for QuantumCircuit.remove_final_measurements.

* Update QuantumCircuit.remove_final_measurements doc strings.

* Run black.

* Test remove_final_measurements properly recalculates clbit indicies.

* Fix typo in doc string.

* Map unreferenced clbits to empty reg list when recalculating clbit indices.

* Use sets to optimize creg and clbit lookup in QuantumCircuit.remove_final_measurements.

* Update docstring formatting for Sphinx

Co-authored-by: Jake Lishman <jake@binhbar.com>

* Remove redundant variable in _calc_final_ops

Co-authored-by: Matthew Treinish <mtreinish@kortar.org>

* Use add_bits and add_register to sync _clbit_indices.

* Don't clear data structures. Instead, create new empty ones.

* Remove unnecessary remove_edge call.

* Remove warning for busy clbits without reference.

* Unit test DAGCircuit.remove_(cregs|clbits).

* Kevin K's diabolical test.

* Update test/python/dagcircuit/test_dagcircuit.py

Co-authored-by: Kevin Krsulich <kevin@krsulich.net>

* Clarify single bit use in test_circuit_operations.

* Separate qubits and clbits in apply_operation_back calls.

Co-authored-by: Kevin Krsulich <kevin@krsulich.net>

* Address RemoveFinalMeasurements tests review comments.

* Use list equality in RemovalFinalMeasurements tests.

* Simplify behavior of DAGCircuit.remove_(cregs|clbits).

* Fix style issues.

* Style fixes.

* Improve remove_final_measurements description.

* Fix arg docstring syntax.

* Add release notes.

* Minor release note tweaks.

* Fix typo in unit test comment.

* Update remove_clbits docstring

Co-authored-by: Jake Lishman <jake@binhbar.com>

* Improve variable names in RemoveFinalMeasurements.

* Remove weird guard from _is_idle_wire.

* Address test review comments.

* Address release note review comments.

* Run black.

* Run black.

* Better incorrect type error messages.

* Run formatting.

Co-authored-by: Jake Lishman <jake@binhbar.com>
Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
Co-authored-by: Kevin Krsulich <kevin@krsulich.net>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2021-11-26 20:03:14 +00:00
Jintao YU 605283d67e
Fix Hoare optimizer failure for successive gates of three (#7278)
* Record deleted gates in  _multigate_optto

* Move come code from _multigate_opt to a subroutine

* Create a release note for the bug fix

* Rename max_idx to from_idx and update comments

* Remove reference to private function in release note

Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2021-11-26 18:40:02 +00:00
Abby Mitchell 8dbb7183c6
Add contents list and label descriptions to contributing docs (#7158)
* Update contributing docs

* fix typo

Co-authored-by: Jake Lishman <jake@binhbar.com>

* fix typo

Co-authored-by: Jake Lishman <jake@binhbar.com>

* Swapped 'good for community' label with 'help wanted'

* tweaked wording

* Fix minor typos

Co-authored-by: Jake Lishman <jake@binhbar.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2021-11-26 15:29:51 +00:00
Ikko Hamamura b74089e26a
Remove deprecated operators of BaseOperator (#7291)
* remove deprecated operations

* Update releasenotes/notes/remove-deprecated-ops-2fbd27abaee98c68.yaml

Co-authored-by: Matthew Treinish <mtreinish@kortar.org>

* remove some tests from qiskit/test/base.py

* Fix information in release note

Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
2021-11-25 20:11:21 +00:00
Abby Mitchell e0d0f687d9
Adapted grover.amplify to omit is_good_state check in certain cases (#7302)
* Refactored grover to omit is_good_state check in certain cases

* Removed redundant comments

* Tidied up comments

*  lint  and addressed some PR comments

* Refactored is_good_state check logic

* Refactored according to PR comments

* Added release note

*  Lint! 

* Add break

Co-authored-by: Julien Gacon <gaconju@gmail.com>

* Update reno wording

Co-authored-by: Julien Gacon <gaconju@gmail.com>

* Added class attribute _iterations_arg

* Tidied up tests

*  lint 

* Update qiskit/algorithms/amplitude_amplifiers/grover.py

* Fix typos

* Lint again!   

Co-authored-by: Julien Gacon <gaconju@gmail.com>
Co-authored-by: Jake Lishman <jake@binhbar.com>
Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
2021-11-25 13:39:49 +00:00
Matthew Treinish 7359d7a7e2
Move release note to the proper path (#7313)
In PR #7014 a new release note was added for the changes being made in
that PR to document the bump in the minimum version of symengine needed
for the next Qiskit release. However, the reno command was accidentally
run in the wrong directory (reno needs to be run from the repo root
directory) and the releasenote file ended up in the wrong location. This
means that we both have a file in the wrong place and that it won't show
up in the rendered release notes when we build the documentation. This
commit fixes this error and simply moves the release note to the proper
location so that it will be included in the release documentation.
2021-11-24 20:24:07 +00:00
Matthew Treinish 8332b67ab8
Remove fork of testtools internals for FullQiskitTestCase (#7311)
In #3982 we forked a bunch of internals around results handling and
attachments from the testtools library to enable better stdout, stderr,
and pylogging handling when running with stestr (which is our default
runner in CI). This was necessary at the time because testtools relied
on unittest2 (which was a rolling backport package from unittest to
bring new features from newer python's unittest to older python
versions) that has gone unmaintained for years and was causing
incompatibilities with stdlib unittest on newer python versions. However
as of the testtools 2.5.0 release it no longer depends on unittest2 and
instead inherits directly from unittest fixing the compatibility issues
we were facing previously. This means our fork of the result and
attachment handling from testtools is no longer necessary and we can
just use their TestCase. However, since we do not want to require the
use of testtools outside of running with stestr this commit retains the
same spit logic around when we use it to ensure that we're only
opportunistically using the library if it's installed. This enables
people to no have testtools (which honestly isn't the best maintained
library anymore) taint their code path unless it's already installed.

Fixes #7307
2021-11-24 16:21:43 +00:00
Anton Dekusar f6ab3a98ca
fix randomization (#7304)
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2021-11-23 22:13:03 +00:00
Jake Lishman ba8e3f34f0
Fix compatibility with Matplotlib 3.5 (#7301)
* Fix compatibility with Matplotlib 3.5

The problem was `qiskit.visualization.bloch.Arrow3D`, which subclassed
`matplotlib.patches.FancyArrowPatch` (a 2D patch), but not the 3D
machinery.  It is now made an unholy multiple-inherited abomination of
both the 2D patch and `mpl_toolkits.mplot3d.art3d.Patch3D`; the latter
is a relatively thin wrapper (in terms of attributes) around the 2D
patch, so this is not too terrible.

Matplotlib 3.5 calls the `Patch3D.do_3d_projection` method using a
deprecated parameter, triggering two warnings, unless the artist's
module appears to have come from `mpl_toolkits.mplot3d.art3d`, even if
the new calling convention is respected.  The warning is only triggered
when the figure is drawn, which may well be outside of our control, so
we cannot suppress the warnings.  Instead, we just lie about the module
the arrow patch was defined in, to trick it into not warning, because we
use the new calling convention.  This is supported at least as far back
as Matplotlib 3.3, which is the current minimum supported version.  The
nasty hack should be removable once Matplotlib 3.6 is the minimum
version because the deprecation period will expire.

* Remove useless word

Co-authored-by: Matthew Treinish <mtreinish@kortar.org>

Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2021-11-23 19:54:51 +00:00
Anton Dekusar f6b6395517
Approximate Quantum Compiler (#6727)
* initial version

* linting

* linting

* linting and black

* linting

* linting

* linting

* linting

* linting

* linting

* linting

* linting

* linting

* linting

* linting

* linting

* linting

* linting

* linting

* linting

* hello

* linting

* remove debugging

* changed variable names, defined d, and moved -1j/2 multiply to the end

* linting

* linting

* checking

* changed variable names

* corrected typo

* corrected typo

* commented

* typo

* typo

* check

* typo

* linting

* changed variable names and commented

* linting

* changed variable names and commented

* cleaning mvp

* cleaning mvp

* cleaning mvp

* added plugin

* code review

* fix types in cnot_structures.py

* more on documentation

* Update qiskit/transpiler/synthesis/aqc/approximate.py

* Update qiskit/transpiler/synthesis/aqc/cnot_unit_objective.py

Co-authored-by: Luciano Bello <bel@zurich.ibm.com>

* Update test/python/transpiler/aqc/sample_data.py

Co-authored-by: Luciano Bello <bel@zurich.ibm.com>

* code review

* fix cache

* updated plugin, more on documentation

* restructured documentation

* default configuration, aqc plugin setup

* added reno

* Update setup.py

Co-authored-by: Matthew Treinish <mtreinish@kortar.org>

* added a test where AQC is invoked via the plugin discovery interface

* added a test where AQC is invoked via pass manager

* update scipy in requirements.txt

* Update qiskit/transpiler/synthesis/aqc/aqc.py

Co-authored-by: Luciano Bello <bel@zurich.ibm.com>

* added tests for cnot networks

* added support for plugin configuration

Co-authored-by: Liam Madden <liam.madden2@ibm.com>
Co-authored-by: Luciano Bello <bel@zurich.ibm.com>
Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
2021-11-23 09:47:56 -05:00
Naoki Kanazawa 0a10008093
Remove deprecated code from pulse module (#7267)
* remove deprecated codes

* cleanup unittests

* fix format logic

* fix tests

* add reno

* lint / black

* remove documentation

* fix import

* readd docs

* readd inline and pad

* readd test
2021-11-22 14:27:15 +00:00
Matthew Treinish e42e90bbe1
Improve VF2Layout pass (#7276)
* Improve VF2Layout pass

This commit fixes some issues with the initial implementation of the
VF2Layout pass and improves the pass to make it suitable for use in the
preset pass managers. This includes several changes:

1. The vf2 pass was raising an exception if it was
   run with >2 qubit gates. This caused issues if we run with
   calibrations (or backends that support >2q gates) as vf2 layout is
   used as an opportunistic thing and if there is for example a 5q gate
   being used we shouldn't fail the entire transpile just because vf2
   can't deal with it. It's only an issue if the later passes can't
   either, it just means vf2 won't be able to find a perfect layout.

2. Add multiple trials to the pass and a mapping quality heusristic with
   basic noise awareness to the pass. For performance we should be using
   the vf2++ heursitic as it improves the performance and makes matches
   much easier to find, however this has the tradeoff as the vf2++
   heurstic orders the nodes by degree for the search which means when
   there are multiple mappings found (as in the case of a 1q gate only
   circuit) it would favor the qubits with highest degree which isn't
   desireable as these tend to be the noisest qubits. Now the pass will
   iterate over all the mappings found by retworkx.vf2_mapping() and
   score each of them, picking the best mapping. If a BackendProperties
   object is available it will factor in readout error for each qubit,
   if it's not it scores nodes with lower degree more favorably. A
   future optimization would be to look at 1q and 2q error rates on the
   device and pick based on that, but this gets tricky as to do this
   well we should weight this based on the number of operations on the
   qubits or edges which isn't as simple, so this is left for a future
   optimization

3. Add configurable limits to the pass. While VF2 is normally quite
   quick both to find mappings and to also determine if a mapping isn't
   feasible it isn't always. The edge cases can take quite a long time.
   If we're going to use this pass in the preset pass managers we need
   to be able to set limits on the execution. This commit enables the
   pass to be configured with limits on the number of trials to
   consider, how many internal state visits to use in vf2 before we give
   up (which can be used as a proxy for per trial timeout 1e7 is roughly
   20 seconds), and a total timeout which will be checked after each
   trial to ensure the total time spent in the pass doesn't exceed a
   certain amount of time. This gives us the necessary knobs to ensure
   that the pass doesn't spend too much time trying to find an ideal
   solution.

4. Using an Enum class for the stop conditions. Since there are a finite
   number of stop conditions for the pass, instead of using magic
   strings to determine this using an enum makes it easier for users to
   programmtically interact with the pass and it's return status. The
   value for the enums are the same strings as used before but this
   gives a slightly cleaner interface for interacting with the
   VF2LayoutStopReason value in the property set.

5. Add debug log messages to the pass. After changes 1-4 the internal
   logic and operation of the pass is sufficiently complicated that some
   logging is necessary to figure out how it's behaving. This commit
   adds a bunch of log messages to describe the operation as the pass
   operates all at the debug level because it's all only useful for
   debugging how the pass could have gone wrong and not generally useful
   for information for users.

This was originally split out from #7213 where these changes were
originally made incrementally as we experimented with making this pass
run by default for optimization levels >= 1.

* Set a default number of max trials

As was found by @nonhermitian in testing locally for trivial problems
with a large search space (like idle qubits in the interaction graph) we
were spending most of our time trying to run through the entire search
space to find all mappings and picking the best one. To address this
issue, this commit sets the default value of max_trials based on the
size of the graphs being used to set limits for these simple cases.

* Documentation improvements
2021-11-20 03:51:56 -05:00
Christopher J. Wood 93f7659327
Fix settings for base operator and subclasses (#7194)
* Fix settings

The abstract base class BaseOperator should not define settings, since these are inherit by subclasses which give errors when used with the runtime encoder/decoder because the subclasses are not reconstructable from these settings. This Fix removes settings from BaseOperator, and adds correct settings to QuantumChannel operators and DensityMatrix class so they can be correctly serialized and deserialized.

* Add docstring that is no longer inherited

Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
Co-authored-by: Kevin Krsulich <kevin.krsulich@ibm.com>
2021-11-20 02:10:55 +00:00