Commit Graph

1041 Commits

Author SHA1 Message Date
Matthew Treinish f6a343b3fc
Fix handling of global ideal gates for target build_coupling_map() (#8977)
* Fix handling of global ideal gates for target build_coupling_map()

This commit fixes the handling of the `build_coupling_map()` method so
that it correctly handles edge cases around a mix of ideal globally
available gates and gates that have qubit/connectivity constraints.
Previously, the method would incorrectly treat the presence of a
globally defined ideal gate as meaning there were no connectivity
constraints, even if that global gate was only on 1 qubit. While if the
gate operates on two qubits this is correct behavior.

Fixes #8971

* Add test for single qarg non-ideal case
2022-10-31 17:29:30 +01:00
Matthew Treinish 77588ff3d3
Fix backend primitives on backends with job size limit (#8955)
* Fix backend primitives on backends with job size limit

This commit fixes an oversight in the initial implementation of the
BackendSampler and BackendEstimator class. When targeting real backends
most backends have job size limits that prevent sending an arbitrary
number of circuits in a single job (for example aqt provider backends
can only take a single circuit at once). In such cases the backend
primitive class ignored this constraint and would send as many circuits
as was passed to `run()` to the backend at once. This commit fixes this
by checking if the backend has a job size limit and chunking the
circuits into multiple jobs.

* Update releasenotes/notes/fix-max_circuits-backend-primitives-c70590bca557001f.yaml

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

* Add release note for monitor removal

* Update estimator tests to count mock backend.run() calls

* Unify run path between primitives

Co-authored-by: Jake Lishman <jake@binhbar.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-10-31 11:08:09 +00:00
Jake Lishman bb93592dd8
Fix zero-operand gates and instructions (#8272)
* Fix zero-operand gates and instructions

A few checks in different places didn't account for zero-operand gates
being possible.  In most uses, there never would be anything useful
here, but it can occasionally be useful to create a "global-phase"
instruction, especially if this is later going to have controls applied
to it.  This is well-formed within the Qiskit data model; spectator
qubits implicitly undergo the identity, so this corresponds to the
global phase being multiplied by the identity on _all_ qubits.

* Fix controlled-gate qubit-number documentation

* Add ScalarOp test

* Be stricter about allowed num_ctrl_qubits

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-10-29 09:27:23 +00:00
Matthew Treinish b6f8cab2f5
Deprecate Python 3.7 support (#8942)
This commit deprecates Python 3.7 support. During the deprecation window
we will continue to fully support Python 3.7 and test it in CI, but it will
emit a warning that we will be removing support for 3.7 in the future to
inform users to upgrade to Python 3.8 or newer. The removal will occur
during the qiskit-terra 0.25.0 release as it is the first release scheduled
to occur after the upstream Python EoL date in June 2023. [1]

[1] https://devguide.python.org/versions/

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-10-28 22:46:30 +00:00
Kevin J. Sung 8b58a8f41e
add QuantumCircuit.from_instructions (#9006)
* add QuantumCircuit.from_instructions

* simplify loop

* handle both cases in just one method

* delete stray import

* fix type annotation

* address comments

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-10-28 21:29:33 +00:00
Jake Lishman 351da447f7
Speed up `random_circuit` (#8983)
* Speed up `random_circuit`

There is no need to use the slower `append` (which adds a lot of
checking overhead for large circuits) since we fully control the
construction of the circuit.

This also overhauls all the randomisation components to produce all the
necessary randomness for a given layer in a single go.  This massively
reduces the Python-space and Numpy-dispatch overhead of the nested loop.

The changes to the randomisation in this new form mean that on average,
more gates will be generated per circuit, because the output will choose
1q gates more frequently than it chooses 2q, which in turn will be more
frequent than 3q, but each layer of the "depth" still has to involve
every qubit.  The change is because the likelihood of choosing a gate
with a given number of qubits is now proportional to how many different
gates of that number of qubits there are in the options.

For sample timings, the call `random_circuit(433, 1000, seed=1)` went
from 15.2s on my machine (macOS Python 3.10, Intel i7 @ 2.3 GHz) down to
2.3s, so a speed-up of about 6-7x.

* Add test of large-circuit condition generation

* Use all gates in the standard library

This deliberately does not use the `get_standard_gate_name_mapping`
function, in order to avoid changes to that function breaking RNG
compatibility in this unrelated function.

* Fix docstring

* Add comments on algorithm

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-10-28 20:20:06 +00:00
Jake Lishman b45afea036
Add missing equivalences for XX{Plus,Minus}YYGate (#9017)
* Add missing equivalences for XX{Plus,Minus}YYGate

These are just copied from the `_define` method on the classes.  The
equivalence-library tests are updated (since `subTest` doesn't isolate
correctly with `testtools`) to print out all the names of the tests
being run, so it's clear that the existing test now tests these
definitions.

* Use default parameters to beat the scoping weirdness

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-10-28 12:58:11 +00:00
Matthew Treinish 72ba2ee259
Fix transpile() with a Target containing an ideal Measure (#8995)
This commit fixes an oversight in the transpile() function when running
with a Target (either directly or via a backend) that contains a
Measurement operation that is ideal (either globally or locally) with no
properties defined. This was not handled correctly in the function used
to convert a Target to a BackendProperties payload for passes that are
not yet target aware and this would cause an exception to be raised.
This commit fixes this edge case and excludes readout properties from
the generated BackendProperties in this case.

Fixes #8969

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-10-28 05:28:20 +00:00
Julien Gacon aab18fcd69
Fix `VQD` for `k>2` (#8989)
* Fix vqd for k>2

Also ensure the optimal circuits from previous iterations are only constructed once and recognizable by the primitive caches.

* Remove empty parameter list

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-10-27 09:01:21 +00:00
Edwin Navarro de35b90ddb
Fix manifest entry for mpl styles (#9004)
* Fix manifest entry and reno

* Improve release note

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-10-26 22:51:28 +00:00
Ikko Hamamura be1e697613
fix #8992 (#8998) 2022-10-26 08:40:52 +00:00
Matthew Treinish 6580d96879
Fix VF2Layout and VF2PostLayout handling of instructions without error (#8978)
* Fix VF2Layout and VF2PostLayout handling of instructions without error

This commit fixes an issue in the VF2Layout and VF2PostLayout pass where
the passes would potentially error in cases when a target was specified
and there were instructions present without any error rates defined. In
such cases the instructions should be treated as ideal (having no error)
and the passes shouldn't fail. In cases where there are no error rates
in the target for VF2Layout the first perfect match should be used, and
for VF2PostLayout it should effectively be a no-op and not select a new
layout.

Fixes #8970

* Add missing comma to comment

* Exit early if score is 0

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-10-25 21:51:24 +00:00
Will Shanks 0ba7a438bd
Avoid skipping channels in pulse visualizer (#8974)
* Modify pulse visualizer test to fail due to missing channel

Reproduces #8981

* Avoid skipping channels in pulse visualizer

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-10-24 04:45:49 +00:00
Jake Lishman 6aad914189
Remove tweedledum as a core dependency (#8947)
* Remove tweedledum as a core dependency

Maintenance on tweedledum has stagnated in recent months, and is no
longer stable enough on our Tier-1 (and other) supported platforms,
especially as further Python versions are released.  This work was
heralded by gh-8738, which contains more context on the change.

* Add tweedledum pylint suppressions

I couldn't get `.pylintrc`'s `ignore{,d}-modules` options to work right
for this, so I just resorted to localised suppressions.

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-10-20 18:17:04 +00:00
Matthew Treinish ef9259ded6
Fix parallel dispatch with target argument in transpile() (#8952)
* Fix parallel dispatch with target argument in transpile()

If a custom target was specified when calling the transpile() function
with more than one circuit the parallel dispatch of the shared custom
target would fail because the basis_gates created from the target was a
dict keys type. Pickle is unable to serialize a dict keys object
apparently and this would cause an exception to be raised. This commit
fixes this by casting the basis_gates from the target as a list so that
it can be serialized.

* Use unittest.mock.patch.dict to set parallel execution in tests

* Fix parallel flag for test

* Fix parallel test setup

In the previous patches we were attempting to use
unittest.mock.patch.dict to override the env variable used to control
parallel execution in qiskit. However, the issue with doing this is that
the env variable is read at import time and stored in a global variable
as we don't expect the env variable to change dynamically during the
execution of a script. To workaround this the mocks are removed and
instead a setUp() method is added to the test class to override the
whatever the environment default is and instead hardcode parallel_map to
run in parallel for the test and then switch it back to the earlier
value after the test finishes. This lets us dynamically adjust the
default behavior for parallel execution for this test class.

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-10-20 14:40:13 +00:00
Matthew Treinish ffabc2e844
Make UnrollCustomDefinitions pass target aware (#8784)
* Make UnrollCustomDefinitions pass target aware

This commit makes the UnrollCustomDefinitions transpiler pass target
aware. A new kwarg, target is added to the pass constructor and if
specified the Target object passed in is used to check if the target
backend supports the gates in the circuit instead of the basis_gates
list.

Part of #7113

* Apply suggested doc fixes from code review

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

* Simplify custom gate detection logic in pass

This commit simplifies and deduplicates the logic for the pass around
detecting whether a particular instruciton is supported.

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>
2022-10-20 00:23:20 +00:00
Christopher J. Wood 58d339aa3e
Fix Statevector.evolve and DensityMatrix.evolve for mixed dimension subsystems (#8900)
* Fix bug in OpShape.compose

* Fix bug in Statevector.evolve

Fixes bug where Statevector.evolve was reshaping subsystems incorrectly if subsystems had different dimensions.

* Add additional tests

* Add reno

* fix reno rst links

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-10-19 22:29:29 +00:00
Naoki Kanazawa b10c2ad296
Add singledispatchmethod to dependency (#8944)
* add singledispatchmethod to dependency

* Fixup release note

Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-10-19 18:36:07 +00:00
Jake Lishman 514e383946
Fix classical-bit handling in control-flow StochasticSwap (#8906)
* Fix classical-bit handling in control-flow StochasticSwap

Previously we were expanding control-flow blocks to be full-width over
_all_ wires, and only contracting the qubits back again, without
changing the clbits given as node arguments.  This modifies the

The changes in most of the tests are necessary because the tests were
testing behaviour that should be considered incorrect.  The principal
new test of all this behaviour is the additional assertions added in
`_visit_block` in the random tests; these uniformly fail without this
patch, and succeed with it.

* Add integration tests of some post-transpile work

These are general integration tests for QPY and OpenQASM 3 dumping, with
a particular emphasis on making sure control-flow constructs don't
invalidate these two operations.

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-10-19 16:30:46 +00:00
WQ a53fc9a1a0
fix hinton visualization bug (#8447)
* fix hinton visualization bug

* added release note for fix-hinton-bug

* remove issues and add more details

* correct set ylim

* Fix display and labelling of Hinton plot

The state labels in `plot_state_hinton` did not align with the correct
matrix entries.  This also updates the plot to display entries in the
natural "matrix" ordering, i.e. the same way that Numpy would display
the matrix if directly printed.  Previously, it was effectively a
transpose of what it should have been, with incorrect labels.

* Fixup release note

Co-authored-by: Junye Huang <h.jun.ye@gmail.com>
Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-10-19 00:49:34 +00:00
Jake Lishman 3bebd0f078
Fix single-bit-condition equality in QuantumCircuit and DAGCircuit (#8930)
* Fix single-bit-condition equality in QuantumCircuit and DAGCircuit

Previously, the `condition` of a given operation would not be converted
into bit indices in order do the semantic-equality checking that the
rest of the qargs and cargs get in a circuit.  This caused loose-bit
comparisons to produce false negatives.

* Improve temporary variable names

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

Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
2022-10-18 18:40:25 +00:00
Jake Lishman 64c5eb6725
Fix `BarrierBeforeFinalMeasurements` with loose bits (#8924)
We simply need to consider loose bits as well when constructing the new
DAG layer.  This isn't `DAGCircuit.copy_empty_like` because we don't
want things like metadata and global phase.

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-10-18 03:08:38 +00:00
Matthew Treinish 3a073c7c5e
Fix handling of globally defined operations in Target (#8925)
This commit fixes the handling in the target for working with
instructions defined globally in the target. It adds handling to the
operation_names_for_qargs() and operations_for_qargs() methods to build
outputs that include globally defined operations instead of ignoring
them. Additionally the add_instruction() method is updated to validate
the input qargs to ensure that only valid qubits and qargs are allowed
to be added to the target for an instruction.

Fixes #8914

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-10-18 01:33:57 +00:00
Matthew Treinish 3fb8939728
Fix qpy custom ControlledGate with overloaded _define() (#8927)
This commit fixes a bug in the QPY serialization of ControlledGate
subclasses that defined custom _define() methods. The _define() method
is the typical way to provide a custom definition in Gate classes. While
ControlledGate class provides an alternative interface that handles
custom control states at initialization, but the _define() interface is
still valid even if it doesn't account for this. In #8571 we updated the
QPY serialization code to use the _definition() method directly to
correctly handle the open control case. But this fix neglected the case
where people were providing definitions via the mechanism from Gate.
This commit fixes this assumption by ensuring we load the definition
that comes from _define() which will fix the serialization of these
custom subclasses.

Fixes #8794

Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-10-18 00:01:16 +00:00
Matthew Treinish 696e53d6c0
Deprecate lists for argument input on transpile() (#8835)
* Deprecate lists for argument input on transpile()

Right now the support for the argument broadcasting with list inputs for
various transpiler options on the transpile() function causes a
significant performance overhead to support, primarily do to how we have
to handle the multiple arguments across a parallel dispatch boundary. It
also significantly increases the code complexity of the function to
support more than one input for each argument (except circuits). The
utility of doing this type of argument handling is quite limited since a
similar result can be achieved with a for loop and would like be simpler
for users to reason about. When weighing all these factors the best path
forward is to just remove this functionality. This commit starts the
process of removing this feature by marking it as deprecated. Once the
deprecation cycle is complete we can greatly simplify the code in
transpile and primarily replace it with a call to
generate_preset_pass_manager() and passmanager.run() (the only thing I
think we'll have to handle out of band is faulty qubits defined in a
BackendProperties for BackendV1).

Related to #7741

* Update qiskit/compiler/transpiler.py

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

* Update qiskit/compiler/transpiler.py

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

* Fix release note typo

Co-authored-by: Kevin Hartman <kevin@hart.mn>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-10-17 21:37:58 +00:00
Jake Lishman c34e0b93dc
Fix loose-bit handling in QPY (#8928)
A typo in clbit-reconstruction was generating the incorrect number of
loose clbits in circuits that contained registers and loose bits, and
had more qubits than clbits.  A bug elsewhere in the code caused
circuits with _no_ registers to be deserialised as containing registers,
since the `QuantumCircuit(int, int)` constructor actually does produce
two registers (slightly surprisingly, perhaps).
2022-10-17 18:37:20 +00:00
Christopher J. Wood 8ccfda5a18
Fix pauli_basis deprecation (#8905) 2022-10-14 15:06:39 +00:00
Matthew Treinish 3292a03e5f
Foward port release note updates for 0.22.0 release (#8901)
As part of the 0.22.0 release process we updated the release notes on
the stable branch alone with bumping the version string for the package.
This commit forward ports those changes from the stable branch to main.
This will make it easier for us to backport any subsequent changes to
the release notes as part of a potential 0.22.1 release.

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-10-14 12:05:47 +00:00
Edwin Navarro af459aa409
Return `DAGOpNode` from `dagcircuit.replace_block_with_op` (#8799)
* Return new_node from dagcircuit.replace_block_with_op

* Update doc string

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-10-13 20:34:51 +00:00
Matthew Treinish ad07847081
Fix transpile() for control flow operations with a Target/BackendV2 (#8852)
* Fix transpile() for control flow operations with a Target/BackendV2

This commit fixes an issue when compiling with circuits that have
control flow operations and are running transpile() with a BackendV2
instance or a custom Target. In these cases the transpile() operation
would fail to run because the Target didn't have a provision to
recognize a global variable width operation as part of the target.
Previously all operations in the target needed to have an instance of an
Operation so that the parameters and number of qubits could be verified.
Each of these operation instances would be assigned a unique name. But,
for control flow operations they're defined over a variable number of
qubits and all have the same name (this is a similar problem for gates
like mcx too). Not being able to fully represent the control flow
operations in a target was preventing running transpile() on a circuit
with control flow. This commit fixes this by adding support to the
target to represent globally defined operations by passing the class
into Target.add_instruction instead of an instance of that class. When
the class is received the Target class will treat that operation
name and class as always being valid for the target for all qubits and
parameters. This can then be used to represent control flow operations
in the target and run transpile() with control flow operations.

Fixes #8824

* Simplify test slightly

* Add release note

* Add coupling map target test

* Raise if instruction class and properties are both set

* Only return global gates if they exist

* Change UserWarning to a comment

* Revert change to instructions() getter

* Add release note about coupling map api change

* Fix lint and logic bug

* Add back nested while_loop to transpile() test
2022-10-12 22:40:59 +00:00
Jim Garrison 43cf42e712
Fix deprecation warning for `deprecated_functionality` (#8851)
* Fix deprecation warning for `deprecated_functionality`

* Emit the deprecation warning inline to avoid cyclic import

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-10-12 18:29:57 +00:00
Christopher J. Wood e6d23d5305
Fix pauli.evolve dtype casting error (#8877)
* Fix pauli phase evolve

* Update for unsigned int phases

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-10-12 17:06:36 +00:00
Matthew Treinish af82b4d0e1
Bump main branch version post rc tag (#8850)
* Bump main branch version post rc tag

Now that the first release candidate for the 0.22.0 release has been
tagged, the stable branch for the 0.22 series has been created and we
can start developing the 0.23.0 release on main. This commit bumps all
the version strings from 0.22.0 to 0.23.0 (and the backport branch for
mergify to 0.22) accordingly to differentiate the main branch from
0.22.*.

* Move release notes to dedicated directory too

* Update Cargo too

Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
2022-10-07 15:44:33 -04:00
Jake Lishman b5a3747f87
Remove tweedledum from macOS arm64 immediately (#8849)
In gh-8818 we prevented macOS arm64 from attempting to use tweedledum
1.1.1 as no arm64 wheels are supplied for that version.  In fact, the
"arm64" and "universal2" wheels supplied for 1.1.0 are actually
mislabelled x86_64 wheels as well, and so there is no working binary
version of tweedledum for arm64, and the sdist build process works only
rarely for most people.

Since the work of gh-8738 makes `tweedledum` _effectively_ optional for
`import qiskit` with immediate effect, and the only way to have a
working installation on M1 mac is essentially to have already manually
built `tweedledum` from source, the effects of immediately removing the
requirement from arm64 macs only should be very slight at worst, and a
good quality of life improvement for normal M1 users.

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-10-07 15:00:16 +00:00
Jake Lishman 90b158c7e0
Modify preset pass managers for control-flow support (#8830)
* Modify present pass managers for control-flow support

This adds control-flow support to the level 0 and level 1 pass managers
directly, including neatly erroring out at runtime if the pass manager
was constructed with options that are not yet compatible with control
flow.  In general, we assume that plugins from outside of Terra are safe
for control flow - it's highly likely that this is not in fact the case,
but it's better to do things this way so an external plugin _can_
support control flow, as opposed to forbidding them from doing so.

Level 2 and level 3 both contain optimisations that are incompatible
with control flow right now, and so immediately error if an input
circuit has control flow.  The failing optimisations are ones that
involve a two-pass process of "block collection" followed by "block
replacement"; we have no updated any of the "block collection" analysis
passes to be safe for control flow, since we would also likely need to
communicate the control-flow structure through the property set, which
is not a path we're going down just yet.

In order to construct pass managers with nested flow control (e.g. the
routing-pass stages contain conditionals, but the entire routing stage
needs to be conditioned on the presence of control flow), there is a new
`PassManager` method `to_flow_controller`.  This produces a
`FlowControllerLinear` with the same content as the pass manager, such
that it can then itself be conditioned as a complete block, and embedded
into other pass managers.

* Remove unused import

* Fix nested `FlowController` instances forgetting passes

gh-6962 added support for nested `FlowController` instances.  It did
not, however, propagate any `DAGCircuit` output by its internal passes
into the transpilation loop, which meant that if a pass returned a new
DAG rather than mutating the input, the changes would be thrown away.
Similar behaviour was occuring with the pass "normalisation" step;
incorrect classes would raise an error, but if the normalisation needed
to raise a single pass to a list, the result would not be re-bound into
the nested controller.

* Reinstate `is not None` in trivial_layout conditions

* Add release notes for transpiler control-flow support

* Update out-of-date layout condition comments

* Make working/not-working split clearer in internal lookup

* Add tests of preset pass managers

* Update release notes

* Fix incorrect tests
2022-10-07 13:34:54 +00:00
Matthew Treinish 3bb60b4c1e
Fix handling of 1q gates in UnitarySynthesis with target (#8847)
This commit fixes a bug in the UnitarySynthesis pass with 1q gates and a
Target set. Previously the pass unconditionally expected that it would
only ever encounter 2 or more qubits when it was running on a node if
the target was set. This would cause a failure if it ever encountered a
1q node in the dag. This commit fixes the handling so the pass will
synthesize 1 qubit unitaries it encounters too.

Fixes #8845

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-10-07 00:22:07 +00:00
Matthew Treinish 50db8f5643
Fix DenseLayout when loose bits are present in input circuit (#8843)
* Fix DenseLayout when loose bits are present in input circuit

This commit fixes the DenseLayout transpiler pass to correctly handle
when an input circuit contains loose bits. Previously the pass would
incorrectly assume there was always a register in the circuit and only
construct the output layout with registers. This caused the pass to
return an empty layout if there were no quantum registers present in the
circuit, even if there were qubits in the circuit. This commit fixes
this by creating the layout per qubit and then only adding the registers
as metadata to the layout after the fact.

* Add release note
2022-10-06 18:56:16 +00:00
Matthew Treinish b7e6329a96
Fix reverse permutation for transpiled circuits in Operator.from_circuit (#8802)
* Fix reverse permutation for transpiled circuits in Operator.from_circuit

This commit fixes a bug in the Operator.from_circuit() constructor
method for Layout's generated by transpile(). The transpiler would set
the _layout property for an output circuit to be the mapping from the
input circuit's virtual qubits to the physical qubits (also the output
circuit's qubit index). This is useful for visualization and visually
tracking the permutation assuming you have the original circuit. However
for the `Operator.from_circuit()` constructor method which will reverse
the permutation caused by layout in the generated matrix this is not
sufficient information since we need to order of the original circuits
qubits. To fix this issue this commit changes the `_layout` attribute of
the QuantumCircuit class to store both the initial layout as before and
also a mapping of qubit objects to indices from the original circuit.
Using this extra information we can reliably handle the qubit
permutation in the constructor.

Fixes #8800

* Update bip mapper test for new _layout format

Didn't see this locally because cplex is not installed.

* Remove stray debug prints

* Use a dataclass for _layout attribute

This commit updates the _layout QuantumCircuit attribute to store a new
dataclass, TranspileLayout, which currently stores the initial_layout
used by the transpiler and the initial qubit mapping which maps the
qubit object to it's position index in the circuit. For 0.23.0 we plan
to make the circuit layout attribute public and having a proper
container class will make it easier to do this in a way where we can
evolve the interface over time if needed (likely adding a final_layout
attribute in the near future). Right now the class isn't advertised or
re-exported as the interface is still private/internal but we can make
it a public interface at the same time we add a public getter for the
circuit layout.

* Disable bogus runtime import cyclic-import pylint error

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-10-05 11:59:55 +00:00
Jake Lishman 5528991e17
Resolve classical conditions in `QuantumCircuit.while_loop` (#8833)
* Resolve classical conditions in `QuantumCircuit.while_loop`

This makes the behaviour match that of `if_test`; the omission here was
just a bug.

* Fix faulty while-loop tests

These tests were not previously valid; they should have been rejected
because the conditions were not actually in the circuit.
2022-10-04 17:31:12 +00:00
Matthew Treinish 86fb555871
Add support for custom backend transpiler stages (#8648)
* Add support for custom backend transpiler stages

This commit adds initial support to the transpiler and backend
interfaces for backends to specify custom transpiler stages. There are
often specific hardware compilation requirements that a general purpose
transpiler's preset pass manager can't account for. While we strive to
provide interfaces to outline all the hardware constraints via the
Target class and general purposes passes to fit and optimize an input
circuit to the target backend there are some constraints that aren't
easily addressed in a general purpose way. For such cases having an
interface for a specific backend which has the necessary context of its
own constraints to provide custom compilation steps to integrate into
the pipeline is a necessary feature. The two initial examples of this
are custom basis gate translation and custom scheduling. This commit
adds two new hook point methods for BackendV2 objects,
get_post_translation_stage() and get_scheduling_stage(). These allow
for backends to specify custom PassManager objects that will run after
the translation stage and for the scheduling stage by default when
compilation is targetting the backend. This should enable backends with
custom hardware specific requirements to influence the compilation
process so that any required custom steps to ensure the output circuit
is executable. In the future we may add additional hook points in a
similar manner to enable backends to assert more hardware-specific
compilation where the need arises.

Closes #8329

* Remove stray optimization level args from pm config

* Fix tests

* Apply suggestions from code review

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

* Pivot backend transpiler hook points to leverage plugins

Since in qiskit-terra 0.22.0 we're adding a plugin interface for
transpiler stages already, the more natural fit for enabling backends to
inject custom passes into a pass maanger is via that plugin interface.
This commit updates the hook points to return a plugin method name that
a backend should use by default. This will provide the same level of
flexibility but also export any custom stages as standalone methods that
users can call into if they need to and also advertise the custom stage
methods along with all other installed methods.

* Apply suggestions from code review

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

* Update qiskit/providers/__init__.py

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

* Update release note

* Update qiskit/providers/backend.py

Co-authored-by: John Lapeyre <jlapeyre@users.noreply.github.com>

* Rename transpile() option and reword doc

* Rename hook methods backend_

* Update qiskit/compiler/transpiler.py

Co-authored-by: John Lapeyre <jlapeyre@users.noreply.github.com>

Co-authored-by: Jake Lishman <jake@binhbar.com>
Co-authored-by: Kevin Krsulich <kevin@krsulich.net>
Co-authored-by: John Lapeyre <jlapeyre@users.noreply.github.com>
2022-10-04 09:59:52 +00:00
Jake Lishman 2a8cf79fbe
Update GateDirection and checker for control flow (#8822)
* Update GateDirection and checker for control flow

These are largely straightforwards, but since each pass has essentially
two separate versions, it became simpler to refactor them out when doing
the recursion, rather than using internal closures.  As part of the
refactor, we also swap to using `Target.instruction_supported` to check
for validity - this method was added after the passes were originally
made target-aware.

* Avoid duplicate iteration through all nodes

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>
2022-10-01 07:43:00 +00:00
Paul Nation c701b1020d
plot_histogram now a valid histogram, plot_distribution for non-discrete data (#8762)
* updates and black

* fix for single-bar value and label

* add plot_distribution

* fix for checking for distribution classes since they dict based

* change y label to quasi-probability

* Add release note

* Update releasenotes/notes/plot-hist-797bfaeea2156c53.yaml

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

* Update releasenotes/notes/plot-hist-797bfaeea2156c53.yaml

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

* Allow all but negative distributions to plot_histogram

* just allow all

* Add PendingDeprecationWarning on plot_histogram() with a distribution input

Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-10-01 04:40:17 +00:00
Paul Nation 5f3c9969db
Sampled expectation value for distributions (#8748)
* Add base code

* Add tests

* Add more tests

* move files to results and move imports

* fix test

* add more tests

* change from dict to counts

* Run black

* Convert sampled exp val function to rust

This commit rewrites the python implementation of the expectation value
calculation to rust. The rust implementation should be significantly
faster to compute the expectation value.

* Fix lint

* ignore cyclic import warning since inside func

* black

* Add some checks on inputs

* Add release note

* Speed up bitstring access in rust code

This commit fixes the primary bottleneck in the rust expectation value
calculation. The bit string access of the nth position previously used
in the code was O(n) and for large numbers of qubits this access could
add up in aggregate while computing the expectation value (even
with profiling overhead for 127 qubit this was still roughly .3
seconds for calling the rust function). This commit adjusts how we
access the nth character of the bit string to be O(1) and removing that
bottlneck and for 127 qubit bit string provides a ~3x speedup. The
tradeoff is that this isn't safe (in that there is potential incorrect
behavior) if someone injects random unicode characters in the bitstring.
However as this is unlikely making the change is worth it considering
the speed up. After this commit the largest bottleneck is conversion
overhead from python->rust and memory management of the temp rust
object, at ~59% of the time to run the sampled_expval_complex()
function, which is hard to workaround. Although, there might be further
tuning to reduce the time required for the remaining 41%.

* Update qiskit/result/sampled_expval.py

If this works then yes indeed.  Each operator appears to be coded differently so happy there is some overlap here

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

* explain raw dict inputs

* Update test/python/result/test_sampled_expval.py

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

* Apply suggestions from code review

Co-authored-by: John Lapeyre <jlapeyre@users.noreply.github.com>

* Make oper_table_size a const variable instead of a magic number

Co-authored-by: John Lapeyre <jlapeyre@users.noreply.github.com>

Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
Co-authored-by: John Lapeyre <jlapeyre@users.noreply.github.com>
Co-authored-by: Julien Gacon <gaconju@gmail.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-10-01 02:15:56 +00:00
Luciano Bello 2b8a9e0ec8
"cregbundle set to False" warning should not raised when no classical bits are involved (#8689)
* "cregbundle set to False" warning should not raised when no classical bits are involved

* add link to the issue/PR

* wrapping

* compare result

* test resull

* handle default in a consist way

* comparison

* remove warning

* set default mpl and latex

* adjust test

* Apply suggestions from code review

Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-10-01 01:08:23 +00:00
Alexander Ivrii 389203c929
Implementing pluggable HighLevelSynthesis (#8548)
* Initial implementation of pluggable HighLevelSynthesis

* typo

* black

* fix merge error

* Reorganizing entry points for high-level-synthesis plugins based on the comments

* fixing some typos

* HLSConfig now accepts a list of methods for each operation; also allowing to specify these lists in config's __init__

* running black

* removing hls_config from __str__ in PassManagerConfig

* Adding abc interface for high-level-synthesis plugins

* improving docs and comments

* fix

* adding tests; removing print statements

* removing external test file

* remove redundant print

* Passing HLSConfig in all transpiler optimization levels

* Fix for is_parameterized as Operations don't have to support this

* Replacing node.op.copy by copy.deepcopy(node.op) to avoid Operations implementing copy method

* release notes

* adding a link to HLSConfig class

* Temporarily removing high-level-synthesis from optimization loop

* Adding example from release notes to HighLevelSynthesis documentation

* fixing random typo

* adding references to documentation:

* Further trying to improve documentation following the review comments

* removing usused import

* minor docs changes

* Docs consolidation following review comments

* added test

* fixing title underline in docs

* minor output tweaks

* Update setup.py

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

Co-authored-by: Kevin Krsulich <kevin@krsulich.net>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-09-30 20:08:21 +00:00
Julien Gacon 259e14e08b
Switch to primitive support in QNSPSA (#8682)
* switch to primitive support in QNSPSA

* attempt to fix sphinx & cyclic import

* add comment about sampler passed positionally

* Update typehints

* revert import

* Apply suggestions from code review

Co-authored-by: ElePT <epenatap@gmail.com>
Co-authored-by: ElePT <57907331+ElePT@users.noreply.github.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
Co-authored-by: Steve Wood <40241007+woodsp-ibm@users.noreply.github.com>
2022-09-30 06:20:15 +00:00
Matthew Treinish 6f84c70aa2
Add BackendSampler for Sampler from an arbitrary backend (#8668)
* Add BackendSampler for Sampler from an arbitrary backend

This commit adds a new Sampler implementation to qiskit-terra,
BackendSampler. This sampler implementation enables a sampler object
to be constructed from any backend object. It can be used to enable
backends from providers that don't have native primitive implementations
(which is most providers) to leverage tooling built on primtives. The
API works exactly the same as other sampler implementations except it
takes a required argument on the constructor `backend` which is used
to specify the `Backend` object to execute circuits on.

Co-authored-by: Takashi Imamichi <31178928+t-imamichi@users.noreply.github.com>
Co-authored-by: Ikko Hamamura <ikkoham@users.noreply.github.com>

* Update qiskit/primitives/backend_sampler.py

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

* Remove unused method

* Update qiskit/primitives/backend_sampler.py

Co-authored-by: Takashi Imamichi <31178928+t-imamichi@users.noreply.github.com>

* Update API for primitive interface changes

* Fix initial statevector handling in basic aer

* Fix type hints

* follow new interfaces

* remove deprecated methods

* remove deprecated methods

Co-authored-by: Takashi Imamichi <31178928+t-imamichi@users.noreply.github.com>
Co-authored-by: Ikko Hamamura <ikkoham@users.noreply.github.com>
Co-authored-by: Jake Lishman <jake@binhbar.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-09-30 02:32:18 +00:00
Julien Gacon 16b5df146c
Sampler-based VQE for diagonal operators, plus QAOA (#8669)
* plain optimization works

* support for auxops

* add first round of tests

* cast to real

* lint & more tests

* add VariationalAlgo inheritance

* batching and diagonal estimator as BaseEstimator

* add gradient support

* remove gradient support for now

* fix test filename

* fix old and new batching

* fix broadcasting from a single long array

* add slsqp batch test

* Put Sampler first (no quote intended)

* Add QAOA based on primitives.

* Add QAOA based on primitives.

* force kwargs; match function names with vqe

* remove usused imports

* formatting

* remove usused imports

* Apply suggestions from code review

Remove redundant tests and gates

Co-authored-by: ElePT <57907331+ElePT@users.noreply.github.com>

* correct docs and typehints

* Correct docstring and error text

Co-authored-by: Steve Wood <40241007+woodsp-ibm@users.noreply.github.com>

* update docstrings

* add callback to samplingvqe

* fix merge conflicts

* remove edit to base estimator

* formatting

* update _run for DiagonalEstimator based on BaseEstimator updates

* remove unused import

* bring sampling vqe in line with vqe

* fix docstring indentation

* Correct copyright/

Co-authored-by: Steve Wood <40241007+woodsp-ibm@users.noreply.github.com>

* Fix copyright.

Co-authored-by: Steve Wood <40241007+woodsp-ibm@users.noreply.github.com>

* Use QuasiDistribution typehint, rather than Mapping.

* add callback test fro sampling vqe

* Test initial point is used for QAOA

* formatting

* Test scipy optimizer callable

* Test QAOA with random initial point

* update samplingvqe and qaoa docstrings and add releasenote

* add release note for SamplingVQE and QAOA

* fix hyperlink in docstring

* fix typehints, docstrings, errors

* Convert baseoperator operators inside qaoa

* repeat all SamplingVQE tests with BaseOperator and PauliSumOp instances

Co-authored-by: Declan Millar <declan.millar@ibm.com>
Co-authored-by: ElePT <57907331+ElePT@users.noreply.github.com>
Co-authored-by: Steve Wood <40241007+woodsp-ibm@users.noreply.github.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-09-29 23:45:01 +00:00
Jake Lishman 0d1bea0398
Add control-flow support to "properties" transpiler passes (#8763)
* Add control-flow support to "properties" transpiler passes

This adds control-flow support to the `DAGCircuit` methods `depth` and
`size`, to `QuantumCiruit.depth`, and to the transpiler pass
`ContainsInstruction`.  Together, these are the basis of the principal
transpiler passes that calculate properties of circuits for other
passes.

Depth and size are not fully defined for control-flow operations, so
these methods return hints to the value.

* Fix condition-bit handling

* Add comment on recursive call in QuantumCircuit.depth

This also removes the `weight` parameter, since it's not really required
- it's simpler just to do the multiplication where the control-flow
blocks are encountered.

* Refuse to provide depth and size hints for control-flow by default

Since `depth` and `size` do not have exact meanings once control flow is
present, we decided to have the default for the public methods on
`QuantumCircuit` and `DAGCircuit` be "raise an error" if control flow is
present, and have the user specifically ask for it to get the new
hinting behaviour.  The transpiler passes always use the new hints,
because they always need to account for the inner operations when
evaluating the quality of the output of an optimisation pass.

* Add release note

* Revert changes to `QuantumCircuit.depth`

We decided to avoid putting these user-facing changes onto
`QuantumCircuit` for the initial release, when we don't have time to
also make all the other "properties" methods of `QuantumCircuit`
control-flow recursive.  I originally made the changes this way because
it was simpler for me when making the `DAGCircuit.depth` call
recursive, but due to how the caching in the `weight_fn` evolved over
the course of that implementation, the `DAGCircuit` method can be made
directly recursive.

* Rewrite release note

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

* Update documentation

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

* Make `DAGCircuit.depth` directly self-recursive

In a previous iteration of this implementation, we called
`QuantumCircuit.depth` and had that be the directly recursive call.
Since we chose not to expose control-flow modifications to the
`QuantumCircuit.{depth,size,count_ops}` methods (being more
user-visible, and the concepts aren't fully defined), this meant the
`DAGCircuit` method needed to become recursive itself.

* Swap `DAGCircuit.size` to sum if-else blocks, not max

* Update qiskit/dagcircuit/dagcircuit.py

* Add comment on control-flow property tests

* Fix typos

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

* Add recurse kwarg to analysis passes

* Make error message more descriptive

Co-authored-by: Kevin Krsulich <kevin.krsulich@ibm.com>
Co-authored-by: ewinston <ewinston@us.ibm.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-09-29 19:52:36 +00:00
Takashi Imamichi 5b35a3d386
Remove a validation check of circuits for `BaseSampler` (follow-up of #8678) (#8708)
* relax a check of measurements for Sampler

* fix a test

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-09-29 14:13:13 +00:00