This commit removes the pkgutil namespace hooks that are used for
extending the `qiskit.*` and `qiskit.providers.*` namespaces from
external packages. These were previously used to enable the elements
packaging model where different parts of qiskit lived in separate python
packages under a shared namespace. This is no longer being used and
leaving the namespace extendable by external packages carries a risk of
issues or other accidental cross-interactions when an external package
gets loaded as part of Qiskit.
* Allow barriers in overlap circuit inputs
* Minor fixes plus test with barriers
* Check parameter number on barrier test, similar to other non-failing tests.
* test order
* Add release note
* added registers to layout in sabre_layout pass
* Add reno and test
* Fix layout method in test
* Set transpiler seed
* modified reference circuit for test
---------
Co-authored-by: Elena Peña Tapia <epenatap@gmail.com>
Co-authored-by: Elena Peña Tapia <57907331+ElePT@users.noreply.github.com>
In #10754 3 legacy scheduling passes were accidently deleted. These
passes were incorrectly identified as deprecated, however they were
never marked as deprecating just pending future deprecation. They were
intended to be be promoted from a pending deprecation to a full
deprecation in #8023 but we never took that step because there were
objections at the time as they still served a purpose. #10754 likely
missed this as the only indication in the deprecation decorator was a
kwarg that said `pending=True`, and this was the only indication that
these passes weren't actually deprecated yet. This commit restores these
passes on the 0.45.0 branch in the interest of unblocking the 0.45.0
release ASAP. We can handle forward porting this PR to main as needed
after the 0.45.0 release is tagged.
(cherry picked from commit aa272e9ef7)
Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
`QuantumCircuit._append` is the actual append primitive and is allowed
in inner-loop appends (and for `QuantumCircuit` to assume that it's
callable from other methods), so it's important that the "ensure built"
check happens there, not in `append`.
* Deprecate PauliList estimator observables
Deprecates using a `PauliList` as an observable that is implicitly converted to a `SparsePauliOp` with coefficients 1 when calling `Estimator.run`. Users should instead explicitly convert the argument using `SparsePauliOp(pauli_list)` first.
* Revert algorithms_test_case.py
* Update test/python/algorithms/algorithms_test_case.py
Co-authored-by: Takashi Imamichi <31178928+t-imamichi@users.noreply.github.com>
* Update test/python/primitives/test_estimator.py
---------
Co-authored-by: Takashi Imamichi <31178928+t-imamichi@users.noreply.github.com>
Co-authored-by: ikkoham <ikkoham@users.noreply.github.com>
* Deprecate legacy primitive attributes
These attributes should have already been deprecated when the Estimator and Sampler run signatures were changed to take circuits instead of indices.
* Deprecate attributes set during init
* Fix attribute access
* fix attribute access
* simplify
* Simplify __getattr__ conditional
---------
Co-authored-by: Takashi Imamichi <31178928+t-imamichi@users.noreply.github.com>
* Collect classical registers using a set (#10496)
This adds a test case that adds multiple conditions on the same
register. The test case is fixed by using a set to collect the
classical registers in collapse_to_operation.
* Add release note
---------
Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
This commit updates the qpy load() function to ensure we are raising a
descriptive error message when a user attempts to load a qpy version
that's not supported by this version of qiskit. Previously it would
fail but with a hard to understand internal error message which was just
confusing and not helpful. For example, when trying to load a QPY
version 10 payload with qiskit 0.25.2 (which only supported up to
version 9) it would raise an error message like:
```
Invalid payload format data kind 'b'p''."
```
which doesn't tell you anything meaningful unless you are intimately
familiar with the QPY file format and how the load() function works.
With this commit it now checks if the version number is supported
immediately and if it's too new it will raise an error message that says
exactly that. So in the above scenario instead of that error message it
will say:
```
The QPY format version being read, 10, isn't supported by this Qiskit
version. Please upgrade your version of Qiskit to load this QPY payload.
```
* Always run vf2 scoring serially
The VF2Layout and VF2PostLayout passes' Rust scoring function has the
option to use a parallel iterator for computing the score of a layout
given a sufficiently large circuit (both in number of 2q interactions or
qubits). Previously the scoring would be multithreaded if there were >
50 qubits or > 50 2q interactions in the circuit. However, as recent
testing has shown in most cases the performance of doing this operation
in parallel is much worse than serial execution. To address this issue,
this commit just always uses the serial version. The parallel option is
left in place for now just in case someone was manually calling the
scoring function with the parallel option set to ``True``.
* Add release note
* fix zordering and labels outside of plot
* lint and reno
* Changed reference image for state city
* correct visual of negative real value bars
* added release notes for negative real bars fix
* remove debug print statement in plot_state_city
* fix with tox eblack
* append rho to title
Co-authored-by: Luciano Bello <bel@zurich.ibm.com>
---------
Co-authored-by: Luciano Bello <bel@zurich.ibm.com>
This commit fixes an issue with the Barrier class's
broadcast_arguments() method. Previously the Barrier class was
overriding broadcast_arguments(), however this custom implementation
resulted in an identical output to the Instruction's implementation
(its parent class) but stripped out all the error checking to determine
if the arguments aligned with the size of the instruction. This could
result in creating a corrupt circuit that had a mismatch between the
barrier width and the number of qargs. For example:
```
circuit = QuantumCircuit(1)
circuit.append(Barrier(42), [0])
```
would not error despite trying to add a 42 qubit barrier on qubit 0.
This would result in weird errors such as invalid qpy generation that
are confusing to debug. This commit fixes this by deleting the
broadcast_arguments() implementation for Barrier so it will just
depend on the inherited implementation from Instruction which will
return an identical result but check the instruction is valid.
* add check for backend version to get backend name
* move backend_interface_version
* check backend is None before get version
* Update qiskit/utils/backend_utils.py
Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
* Update releasenotes/notes/fix_backend_name-e84661707058b529.yaml
Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
---------
Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
* List support for coupling map in pass manager
* remove redundant checks for coupling list in preset pass manager
* remove duplicate release note
* add seed to the coupling list test case
* Fix up release note
---------
Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
In the lead up to the 0.45.0rc1 release we used the merge queue to
pipeline the last 2 PRs that merged for the tag. However, this resulted
in a single release note file merging before we could move it into the
0.45/ subdirectory. This commit fixes this so that the final PR for
0.45.0rc1 is correctly grouped in the 0.45 release notes subdirectory.
For the 0.45.0 release we're going to push release candidates prior to
the release to enable testing before we cut the final release. In
preparation for tagging the first release candidate this commit updates
the version string to indicate it's a release candidate. This commit
should be the final commit on main for 0.45.0rc1 and what gets tagged as
0.45.0rc1 post-merge.
* Fixed issue10554 by modifying _parse_initial_layout in transpile to normalize input of range to a list
* Added test and bugfix note
* Handle consumable iterables
* Fix release-note cross references
---------
Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
* Add base-gate callback to `CUGate.params` return
This causes item-setting in `CUGate.params` to forward those sets on to
the `UGate` in its `base_gate` unless they are setting the `gamma`
parameter, which is not shared.
`CUGate` breaks several assumptions and components of the
`ControlledGate` interface, including by having more parameters than its
`base_gate`; `ControlledGate` assumes that its subclasses will not have
a separate `_params` field, but instead will always just view onto their
`base_gate._params`. This commit changes the behaviour of the `params`
getter to create a temporary list that backreferences to the base gate,
satisfying the requirement.
Co-authored-by: Richard Rodenbusch <rrodenbusch@gmail.com>
* Handle sliced assignments
---------
Co-authored-by: Richard Rodenbusch <rrodenbusch@gmail.com>
* Defining and synthesizing AnnotatedOperation
* reworking annotated operation tests
* cleaning up annotated operation
* running black
* lint
* adding recurse argument and fixing the way definition is handled
* treating the case when there is no definition
* lint
* black
* removing duplicated line resulting from merge
* improving comments
* fix to merge conflicts
* black; additional fixes for prelim support of coupling map with annotated operations
* calling substitude_node with propagate_conditions=False
* black
* removing unused imports
* improving documentation of AnnotatedOperation
* minor
* release notes
* release notes typos
* restoring recursion; starting to combine UnrollCustomDefinitions
* merging in unroll_custom_definitions
* adding compatibility tests with UnrollCustomDefinitions and Unroller
* using default session equivalence library by default
* removing propagate_condition=False
* adjusting HLS options in common.py
* Removing UCD from preset pass managers as it has been replaced by HLS
* release notes
* changing default equivalence library back to empty
* typo
* fix annotations
* removing deprecated instruction from test
* removing unnecessary conversions from dag to circuit and back, and setting copy_operations to False
* fix for control-annotations for high-level-objects
* tests for inverse/control modifiers applied to high level objects
* fixes and tests for power modifiers applied to high level objects
* fixing merge problems
* lint and improving redundant conversions
* removing top_level_only
* typo
* Removed code deprecated in 0.22 [transpiler and providers] (#10813)
* Removed the argument 'qubit_channel_mapping' in the class 'qiskit.transpiler.passes.calibration.rzx_builder.RZXCalibrationBuilder'
* Replaced the argument 'qobj[Qobj]' in 'qiskit.providers.aer.QasmSimulator.run()' with 'qcirc[QuantumCircuit]'
* Altered the test files accordingly
* Added a release note
* Update release note and change input argument variable name
* Edited the docstring for the arg run_input
* Update qiskit/providers/basicaer/qasm_simulator.py
Formatted the docstring of .run() fnction as per the review suggestion
Co-authored-by: Luciano Bello <bel@zurich.ibm.com>
* Update releasenotes/notes/remove-deprecated-code-in-0.22.0-139fa09ee0cc6df9.yaml
Added extra detail on the version of ``qiskit-terra`` from which ``qubit_channel_mapping`` was depreciated
Co-authored-by: Luciano Bello <bel@zurich.ibm.com>
* Update releasenotes/notes/remove-deprecated-code-in-0.22.0-139fa09ee0cc6df9.yaml
Better formatted the release notes
Co-authored-by: Luciano Bello <bel@zurich.ibm.com>
* Update qiskit/providers/basicaer/qasm_simulator.py
Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
---------
Co-authored-by: Luciano Bello <bel@zurich.ibm.com>
Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
* Fix build filter coupling map with mix ideal/physical targets
This commit fixes a small issue in the Target.build_coupling_map method
with filter_idle_qubits=True. Previously the internal method used to
filter the idle qubits from the coupling map's creation was not
accounting for the case that an instruction in the target could be
ideal. This was never caught because normally if you have an ideal fixed
width instruction in the target that is modelling a simulator which
doesn't have any connectivity constraints and the function would never
be called. But in targets that have a mix of both ideal globally
defined and physical gates the filter code couldn't handle the None used
to represent an ideal globally available gate. This commit fixes that
handling to just ignore the global gate like the normal coupling map
construction does.
* Fix lint
* add overlap function
* Add tests
* add release note
* add checks for meas+reset
* update docstring
* spelling
* apply review comments
main change: check if circuits are unitary by checking if all operations are of type ``Gate``
* apply changes from review
- do not allow U/V
- allow setting parameter prefixes
---------
Co-authored-by: Julien Gacon <gaconju@gmail.com>
* fixed_issue_10837 by taking backend from the user and passing it to measure function of macros.py in qiskit/qiskit/pulse
* removing backend argumnet from inner function.
Since, get_measure_schedule is an innner function , so backend from lower_gates will be available to the inner function, so backend argument in the inner function is redundant :)
Co-authored-by: Kento Ueda <38037695+to24toro@users.noreply.github.com>
* Fixed typo repetation of CircuitPulseDef, and removal of backend argument from the function call of get_measure_schedule
* Adding relevant docstrings in the changed methods
* fixed lint
* Added tests to use BackendV2.
* Apply suggestion in docstring.
Co-authored-by: Kento Ueda <38037695+to24toro@users.noreply.github.com>
* Apply suggestion in docstring.
Co-authored-by: Kento Ueda <38037695+to24toro@users.noreply.github.com>
* Apply suggestion in docstring.
Co-authored-by: Kento Ueda <38037695+to24toro@users.noreply.github.com>
* Apply suggestion in docstring.
Co-authored-by: Kento Ueda <38037695+to24toro@users.noreply.github.com>
* added a release note
* applied suggestions
* checked lint
* added suggestions in the release note
* Update releasenotes/notes/Adding-BackendV2-support-to-schedule-of-qiskit.compiler.scheduler-a0366d3397c73af0.yaml
Co-authored-by: Naoki Kanazawa <nkanazawa1989@gmail.com>
---------
Co-authored-by: Kento Ueda <38037695+to24toro@users.noreply.github.com>
Co-authored-by: Naoki Kanazawa <nkanazawa1989@gmail.com>
* Refactor internals of pass manager and flow controllers.
This PR introduces two changes for
* remove tight coupling of flow controller to pass runner instance,
* remove pass normalization.
PropertySet becomes context var so that flow controllers can be instantiated
without coupling to a pass runner instance. BasePass becomes an iterable
of length 1 to skip normalization. The decoupling of property set from
pass runner allows pass manager to directly broadcast pass runner
in the multithread, rather than distributing self and craete
multiple pass runner in each thread.
* Replace class attribute PASS_RUNNER with property method.
This allows subclass to dispatch different pass runner type depending on the target code.
* Refactor passmanager module
- Add OptimizerTask as a protocol for the pass and flow controller. These are in principle the same object that inputs and outputs IR with optimization.
- A task gains execute method that takes IR and property set. This makes property set local to iteration of the passes.
- Drop dependency on pass runner. Now pass manager has a single linear flow controller.
- Pass manager gain responsibility of compiler frontend and backend as pass runner dependency is removed. This allows flow controllers to be still type agnostic.
- Drop future property set, as this is no longer necessary because optimization task has the execute method explicitly taking the property set.
* Refactor transpiler passmanager
- Remove pass runner baseclass and replace RunningPassmanager baseclass with FlowControllerLiner
- Implemented frontoend and backend functionality in transpiler Pass manager
* Rename module: base_pass -> base_optimization_tasks
* Backward compatibility fix
- Move handling of required passes to generic pass itself. This makes optimizer tasks the composite pattern-like for more readability.
- Readd MetaPass to transpiler BasePass as a metaclass which implements predefined equivalence check for all passes. This is necessary to take care of duplicated pass run, which is prohibited in circuit pass manager.
- Add FlowControllerMeta that allows users to subclass FlowController, while delegating the pass control to BaseFlowController.
- Readd count to pass manager callback
- Add PassState that manages the state of execution including PropertySet. This is a portable namespace that can be shared across passes.
* Update module documentation
* Update release note
* lint fix
* OptimizationTask -> Task
In multi-IR realm task can be something other than optimization. For example IR conversion. Name should not limit operation on subclass.
* Typo fix FlowControllerLiner -> FlowControllerLinear
* Use RunState value. Set 0 to success case.
* Separate property set from pass state. Now Task.execute method has two arguments for property set and pass state. Lifetime of property set data is entire execution of the pass manager, while that of pass state is execution of a single pass.
* Pending deprecate fenced_property_set and remove usage.
* Pending deprecate FencedObject baseclass and remove usage.
* Add some inline comments.
* Convert RunState to raw Enum
* Change the policy for the use of multiple IRs. Just updated module documentation, no actual code change. Future developer must not introduce strict type check on IR (at least in base classes in the module).
* Updated interface of base controller. Namely .append() and .passes are moved to particular subclass and the baseclass is now agnostic to construction of task pipeline. This adds more flexibility to design of conditioned pipelines.
Note that PassState is also renamed to WorkflowStatus because this is sort of global mutable variable, rather than local status information of a particular pass.
* Remove FlowControllerMeta and turn FlowController into a subclass of BaseController.
* Remove dependency on controller_factory method and deprecate.
* Update release note
* Readd code change in #10835
Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
* typehint fix
* doc fix
* move FencedPropertySet class back to transpiler.fencedobjs
* Temporary: add lint ignore
* Fix example code in class doc
* Tweaks to documentation
* Change baseclass of the MetaPass and revert f28cad9
* Update interface of execute and use generator feature.
- Add new container class PassmanagerMetadata
- Rename propertyset with compilation_status
- Provide metadata with the iter_tasks instead of property_set
- Send metadata through generator
- Turn metadata required, and let pass manager create metadata
- Return metadata from execute along with the IR
* Update deprecations
* Delay instantiation of FlowControllerLinear until execution of pass manager
* Stop wrapping a list of tasks with flow controller linear.
* Remove flow_controller_conditions from base controller append and add stacklevel to deprecation warning
* Misc updates
* disable cyclic-import
* Remove typecheck
* Rename `PassmanagerMetadata` to `PassManagerState`
This is primarily to avoid a potential conflict with the terminology
`metadata` that's associated with the `input_program`, and because the
object is the state object for a pass-manager execution. There is still
a risk of confusion with `RunState`, but since that's a subcomponent of
`PassManagerState`, it feels fair enough.
* Correct warning stacklevel
---------
Co-authored-by: Luciano Bello <bel@zurich.ibm.com>
Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
* Fix override bug and testing
* Preliminary changes
* First attempts
* Work on x_index
* Early testing
* Cleanup getattr
* Complete adding exprs
* Add exprs to mpl
* Work on spacing
* Spacing changes
* Finish initial mpl expressions
* Exprs fully implemented mpl, pre-test
* Add exprs to text drawer
* Minor text fixes and update tests for cregbundle False
* Add tests
* Lint
* Fix test
* Adjust switch test
* Lint again
* Add expr_len kwarg and minor fixes
* Update for 10842 changes
* Lint
* Update refs for minor switch spacing
* Minor cleanup
* Only call QASM3Builder once
* Remove spurious print
* Minor documentation tweaks
* For mpl, adjust switch/expr spacing, fix 1 qarg flow ops, fix top level flow op layers
* Add tests for 1 qarg, nested expr, and for range
* Lint
* Fold on text test
* Remove wire_map from get_layered
---------
Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
This has been against the documented typing of the functions for some
time, but some scheduling methods have mistakenly been passing `None`.
There is no need to support `None` here; the empty tuple `()` is equally
immutable and a CPython singleton, so there are neither mutability nor
memory benefits to supporting both, and removing `None` as an input is a
simple way to remove a(n admittedly cheap) branch from the appender
methods.
Co-authored-by: Luciano Bello <bel@zurich.ibm.com>
* V0 of changing to IQP color
* Rename alternative color tests
- iqx -> iqp
- add test for clifford
* update Clifford reference img
* add reno
* fix reference image
* Pending deprecate IQX
* fix IQX style deprecation
* actually do fix the deprecation
* docs
* in quantumcircuit
* updates iqp name in json
---------
Co-authored-by: Luciano Bello <luciano@debian.org>
* fix to commutative analysis to avoid unsound optimizations
* release notes
* improving release notes and adding co-author
Co-authored-by: Randl <zheltonozhskiy@gmail.com>
* replacing .i by .id in one of the added tests
* dummy commit
---------
Co-authored-by: Randl <zheltonozhskiy@gmail.com>
Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
* Deprecate Unroller pass
* small fix
* black
* add release note
* fix test
* fix test again
* fix test again
* fix visualization tests
* update visual tests
* try to fix circuits
* Adjust qpy backwards compat tests to handle change in control definition
In this PR by switching the internal use of the Unroller to the
BasisTranslator for the add_control.py module results in a different
definition for the generated controlled gate than was done in previous
releases this causes the qpy backwards compat tests to fail. The qpy
backwards compatibility tests generate qpy files with every historical
release of qiskit (that had qpy support) and valdiates that if we load
those qpy files with the current state of the main branch (plus a PR
under test) that the loaded circuits are identical to running the same
code to generate the circuit. However, because of this divergence due to
an internal change in add_control() the circuits are no longer 100%
identical, but are still equivalent. To address this, a new option is
added to the test suite to give an option when this situation occurs to
test for unitary equivalence instead of a instruction for instruction
identical circuit. This is then used for the control circuits.
* Expand release notes
* Ensure we are explicitly warning on transpile()
This commit adds an explicit user facing warning for places where the
transpiler is typically invoked by users. The normal entry point for
users that are using the unroller is to call
`transpile(..., translation_method="unroller")` and they don't work
directly with the `Unroller` pass. This means the deprecation warning
would be hidden from most users because the warning would not point to
user code and the default filters will suppress it. This commit adds an
explicit warning to transpile() and generate_preset_pass_manager() when
the unroller is requested as the translation method to ensure users see
the warning and know how to adjust.
* Apply suggestions from code review
Co-authored-by: Elena Peña Tapia <57907331+ElePT@users.noreply.github.com>
---------
Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
Co-authored-by: Elena Peña Tapia <57907331+ElePT@users.noreply.github.com>
* filter backend_prop when does not match the size of the device
* NoiseAdaptiveLayout to consider inconsistencies in backend
* extend docstring with the warning that the parameter might be ignored
* remove the ginfo.gate and just find two-qubit gates
* edge_set
* deepcopy
* extend test
* Attempt to fix docs build error
---------
Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
* Singleton parameterless controlled gates
This commit adds a new class SingletonControlledGate which is very
similar to the SingletonGate class, but instead can be used in place of
the ControlledGate class as a parent class. This enables a controlled
gate class to work as a singleton if there is no custom control state
specified. This new class has a large amount of duplication with the
SingletonGate class, but because of how the inheritance tree is built
up here there is no avoiding this as we need to specialize for adding
singleton support and SingletonGate is at the same level as
ControlledGate.
With the introduction of this new class all the standard library
ControlledGate instances are updated so they inherit from
SingletonControlledGate instead of ControlledGate. This should
significantly reduce the memory footprint of repeated instances of these
gates in circuits.
* Fix failing test cases
* Apply suggestions from code review
Co-authored-by: Kevin Hartman <kevin@hart.mn>
* Fixes from rebase
* Fix cyclic imports caused by eager definition population
* Fix tests
* Remove unused changes to ControlledGate
* Expand deepcopy test assertions
* Update release notes
---------
Co-authored-by: Kevin Hartman <kevin@hart.mn>
* Use only discrete-basis translations in `GateDirection`
This makes it a little more likely that it'll be possible to use the
transpiler when targetting a discrete basis, such as a Clifford
simulator. We still in general do not offer full support for
discrete-basis translation, and certainly not for optimal discrete-basis
transpilation, but this is a relatively easy change that makes us
marginally more reliable with them.
* Fix global phase in tests
* adding SabreStartingLayoutUsingVF2 analysis pass
* fixing imports
* bug fix
* fixing test after changing some of the options
* renaming
* adding target; more renaming; tests
* release notes
* applying suggestions from code review
* removing debug print
* Update qiskit/transpiler/passes/layout/sabre_pre_layout.py
I didn't know this existed :)
Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
* adding missing :
* collecting edges into a set
* adjusting error_rate with respect to distance
* letting coupling_map be either coupling map or target, for consistency with other passes
* apply suggestions from code review
* Update qiskit/transpiler/passes/layout/sabre_pre_layout.py
Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
---------
Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
The warning was previously emitted with a `stacklevel` that blamed the
caller of `warnings.warn`, which would not be shown to users with the
default warning filters. This moves the stack level up to blame the
caller of `timeline_drawer`.
* Added NormalizeRXAngle and RXCalibrationBuilder passes to build single-pulse RX gate calibrations
* Fixed a typo in documentation
* Removed all cross-references in the documentation
* Added URL links back
* Added cross references back to the release note
* Shorten the cross references in the release note
* Fixed normalize_rx_angle.py based on the comments
* Update qiskit/transpiler/passes/optimization/normalize_rx_angle.py
Edit the doc so that it looks nicer in html
Co-authored-by: Naoki Kanazawa <nkanazawa1989@gmail.com>
* Reformat the doc of NormalizeRXAngle
* Try to pass the doc test
* Addressed feedback and comments from the code review
* Yet another attempt to fix docs error
* Fix docs
* Add 'atol=resolution/2' to np.isclose() tests for SX and X
* fix typo
* Elaborate on quantize_angles()
* Add a demo with a QuantumVolume circuit
* Check pulse.pulse_type==Drag instead of isinstance(pulse, Drag)
---------
Co-authored-by: Naoki Kanazawa <nkanazawa1989@gmail.com>
* Rewrite singleton handling including `SingletonInstruction`
This is a large rewrite of the singleton gate handling, building off the
work done across the library to make the initial implementation work.
There are two main purposes to this commit:
* Make `SingletonInstruction` available in addition to `SingletonGate`,
and have these be easy to maintain in conjunction, not need to
duplicate overrides between them, and not require inheritors to do any
nasty multiple inheritance or the like.
* Fix regressions in the construction time of `SingletonGate` instances.
In the end, this turned into a fairly complete rewrite that completely
switches out the method of defining the classes; it transpires that the
previous way of having the "immutable overrides" on _all_ instances of
the classes was the main source of slowdown, with `__setattr__` being a
large problem. The previous method was far easier from an
implementation perspective, but the runtime costs ended up being too
high.
This new form takes a vastly different strategy, explained in detail in
`qiskit/circuit/singleton.py`. The gist is that we instead make the
singleton instance a _subclass_ of the class object we're creating, and
only it contains the overrides to make itself immutable. We get around
the instantiation problem (`__init__` isn't special and doesn't
skip the forbidden `__setattr__`) by constructing an instance of the
_base_ class, and then dynamically switching in the overrides
afterwards. Since the overrides and the dynamic singleton type of the
instance are designed to be co-operative (including in `__slots__`
layout), this can be done safely.
* Make singleton documentation public
* Add tests of new singleton behaviour
* Fix typos
Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
---------
Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
* Defining and synthesizing AnnotatedOperation
* reworking annotated operation tests
* cleaning up annotated operation
* running black
* lint
* adding recurse argument and fixing the way definition is handled
* treating the case when there is no definition
* lint
* black
* removing duplicated line resulting from merge
* improving comments
* fix to merge conflicts
* black; additional fixes for prelim support of coupling map with annotated operations
* calling substitude_node with propagate_conditions=False
* black
* removing unused imports
* improving documentation of AnnotatedOperation
* minor
* release notes
* release notes typos
* removing propagate_conditions
* applying suggestions from review
* tests for full transpiler flow, with and without backend
* not replace dag.op when op did not change
This formalises the concept of global phase within control-flow scopes,
and teaches the control-flow builders to treat modifications to the
global phase as being conditional on the control-flow block being
entered.
* Add apply_layout method to SparsePauliOp
This commit adds a new method, `apply_layout`, to the `SparsePauliOp`
class. It takes in either a `TranspileLayout` object or a list of
indices that represent a layout transformation caused by the transpiler
and then returns a new SparsePauliOp object that applies a matching
transformation.
* Fix docs typo
* Update releasenotes/notes/sparse-pauli-op-apply-layout-43149125d29ad015.yaml
* Apply suggestions from code review
Co-authored-by: Kevin Hartman <kevin@hart.mn>
* Fix release note typo
---------
Co-authored-by: Kevin Hartman <kevin@hart.mn>
* Fix hash of `Parameter` and `ParameterExpression`
This fixes the construction paths for `Parameter` and its hash such that
it will now correctly hash equal to any `ParameterExpression`s that it
compares equal to. This is a requirement of the Python data model for
hashmaps and hashsets, which previously we were breaking. In order to
achieve this, we slightly modify the hash key such that the `Parameter`
instances are no longer a part of the hash of `ParameterExpression`,
which means we can use the same hashing strategy for both.
This rearrangement has the benefit of removing the requirement for the
`__new__` overrides on `Parameter` and `ParameterVectorElement`.
* Add type hint
Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
* Tweak documentation wording
---------
Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
* Removed deprecated references to Rho in plot_state_hinton, plot_bloch_multivector, plot_state_city, plot_state_paulivec, and plot_state_qsphere. Removed scheduler.utils as functions were moved to pulse/macros and pulse/utils
* Added release note
* Lint check suggestions implemented, unused import of deprecate_arg removed
* Release note section changed to upgrade
* Update releasenotes/notes/remove_depreciated_0.15_code-ee5c7d343e310888.yaml
* reno
---------
Co-authored-by: Luciano Bello <bel@zurich.ibm.com>
Co-authored-by: Luciano Bello <luciano@debian.org>
Internally, it removes all use of the deprecated `Bit` properties
`Bit.index` and `Bit.register`. This is achieved by making it possible
for generator functions to accept the complete `QuantumCircuit` program
as a keyword argument, if they advertise that they can handle this by
setting a special `accepts_program` attribute on themselves to `True`.
This somewhat convoluted setup is because the generator functions are
supposed to be arbitrary and user-definable in custom stylesheets, so
we cannot unilaterally change the call signature.
* Improve the ergonomics of the TranspileLayout class
This commit updates the TranspileLayout class to make it easier to work
with. The TranspileLayout class was orginally just an a container class
that took the information returned from the transpiler needed to reverse
the transpiler layout permutation (in the absence of ancillas) so that
`QuantumCircuit.from_circuit()` could compare Operator instances across
a `transpile()`. However, the internal data structures used by the
transpiler are hard to work with, and don't map well to the normal
reasoning around how the transpiler transforms the circuit. To improve
the usability of the class this commit adds 4 new methods to the class:
- initial_layout_list() and final_layout_list() which compute a list
form of the initial_layout and final_layout respectively
- full_layout() which generates a list that maps the input circuits
qubit positions in the input circuit to the final position at
the end of the circuit (which is what most people think of when they
hear "final layout")
- permute_sparse_pauli_op() which takes in a SparsePauliOp object and
permutes it based on the full layout. This is especially useful when
combined with the Estimator primitive
To implement these functions a few extra pieces of information are
needed to fully implement them. The first is we need to know the number
of original circuit qubits. This is used to account for any ancillas
that are added in the circuit, once we have the input circuit count we
can use the original_qubit_indices attribute to discern which qubits in
the initial layout are from the original circuit and which are ancillas.
The second piece of information needed is the list of qubits in the
output circuit. as this is needed to look up the position of the virtual
qubit in the final_layout. These are both added as optional private
attributes to the TranspileLayout class and there are some small changes
to the pass manager and QPY to accomodate them.
Similarly the change in the TranspileLayout class requires a new QPY
version to include the missing details that were not being serialized
in QPY and weren't representable in the previous payload format.
Fixes#10826Fixes#10818
* Handle None for the private TranspileLayout fields in QPY
* Add test for full_layout with ancillas
* Rework interface to be more consistent
This commit reworks the names of the new methods added in this API to be
more self consistent. It uses the format '*_index_layout' to replace the
`*_layout_list` name. Similarly new methods `*_virtual_layout` are added
for methods that return layout objects.
* Apply suggestions from code review
Co-authored-by: Jake Lishman <jake@binhbar.com>
* Remove permute_sparse_pauli_op()
This commit remove the TranspileLayout.permute_sparse_pauli_op() method.
This was a bit out of place on the TranspileLayout class, and it will
instead be replaced in a follow-up PR by a apply_layout() method on the
SparePauliOp class that takes in a TranspileLayout object.
* Update docs
* Fix docs build post-rebase
* Fix docs issues
---------
Co-authored-by: Jake Lishman <jake@binhbar.com>
* Add skip_check option to UnitaryGate
This commit adds a new option to the unitary gate class's constructor,
skip_check, which is used to skip the checking on the input unitary.
When creating a unitary gates when you know the input is already unitary
checking that the input matrix is unitary is wasted CPU time. This new
option enables a user to assert the input is unitary and skip this
checking (at their own risk). The primary use case for this is the
consolidate blocks pass which is creating a large number of UnitaryGate
objects and matrix is always going to be unitary. This new flag is used
in ConsolidateBlocks to speed up the creation of gate objects.
* Rename argument check_input
* Fix rebase issues
* Update qiskit/circuit/library/generalized_gates/unitary.py
* Pending-deprecate duplicate circuit methods
* Missed some old methods
* may darkness rule (aka "run black")
* Deprecate and id not i
* use id over i
* capture Aer's usage of QuantumCircuit.i
* catch warning, don't assert
* try fix errors
Co-authored-by: Elena Peña Tapia <57907331+ElePT@users.noreply.github.com>
* Attempt 2 of ?
Co-authored-by: Elena Peña Tapia <57907331+ElePT@users.noreply.github.com>
* Attempt 3 of 3 (hopefully)
* redundant "+"
* Filter the deprecation warning globally
* add reno
---------
Co-authored-by: Elena Peña Tapia <57907331+ElePT@users.noreply.github.com>
* Fix override bug and testing
* Preliminary changes
* First attempts
* Work on x_index
* Early testing
* Cleanup getattr
* Complete adding exprs
* First fix for cregbundle control flow
* Finish basic cregbundle mods
* Finish all cregbundle except wire_map bug
* Move carg check to circuit_vis and change text tests to circuit_drawer
* Move mpl tests to use circuit_drawer and update images for cregbundle changes
* Change mpl tests to circuit_drawer
* Fix flow_wire_map and tranpile bug
* Final cleanup
* Missing outputs on mpl tests
* Fix output
* Restore tests and move carg check to text and mpl and make circuit
* Prepare final cregbundle fix
* Update ref images
* Fixing refs
* Update refs again
* Final mods
* Incorporate mtreinish changes
* Add reno
* Fix if_else_op test
* Lint
* Fix target == expr bug in text
* Review fixes and outer_circuit, wire_map fixes
* Remove png
* Minor changes
* Fix for_loop measure placement bug
---------
Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
We have compiled extensions that are built against the Numpy C API. The
Numpy transition guide for developers of downstream packages[^1]
encourages us to put in this pin until we have wheels built against the
newer version, which is not expected to be fully ABI compatible (but
extensions built against Numpy 2 _should_ work with older Numpys).
Note that this won't prevent package managers from resolving _older_
versions of Qiskit (which don't have the pin) along with Numpy 2, but
there's not a vast amount we can do about that now.
[^1]: https://github.com/numpy/numpy/issues/24300
* Update gate_map.py
Update the gate_map.py to migrate the visualization modules from matplotlib to rustworkx.graphviz
* Removed has_rustworkx instances
* Added release notes
* Update test_gate_map.py
Updated tests for the modified gate_map.py file
* Formatted gate_map.py
* Format test_gate_map.py
* Added release notes for the fix of #9031
* Update gate_map.py
* Update test_gate_map.py
Test file updated so that all tests can be passed.
* Update test_gate_map.py
* Update gate_map.py for rerunning tests.
* Update test_clifford.py
* Update gate_map.py to reuse rx.draw_graphiz
* Update test_gate_map.py to omit qubit_visualization
* Update test_gate_map.py to fix formatting changes
* Update gate_map.py
* Update gate_map.py
* Update gate_map.py
* Update test_gate_map.py
* Update test_gate_map.py
* Update gate_map.py
* Update gate_map.py
* Update gate_map.py
* Update gate_map.py
* Update gate_map.py
* Update gate_map.py
* Update gate_map.py
* Update test_gate_map.py
* Update test_gate_map.py to add rx import
* Update test_gate_map.py
* Update test_gate_map.py
* Update test_gate_map.py to fix imports
* Update test_gate_map.py to add HAS_GRAPHVIZ to all tests
* Update test_graph_matplotlib_drawer.py to have HAS_GRAPHVIZ
* Update test_graph_matplotlib_drawer.py to add HAS_GRAPHVIZ import to test_font_color function
* Update test_graph_matplotlib_drawer.py to add GRAPHVIZ check to the class
* Update test_graph_matplotlib_drawer.py to add HAS_GRAPHVIZ to both gate_plot_map and test_gate_plot_map import to test_font_color function
* Update test_graph_matplotlib_drawer.py
* Update test_graph_matplotlib_drawer.py
* Update test_graph_matplotlib_drawer.py
* Fixed the `font_color` parameter in `gate_map.py/plot_gate_map()`
The font_color parameter can now accept hex values as well.
* Modify color_edge function to increase speed
* Update gate_map.py to fix formatting
* Update gate_map.py to shift seaborn import to `plot_error_map`
* Add HAS_SEABORN to test_plot_error_map
* Reformat gate_map.py
* Fixed node autoscaling in `gate_map.py` graphs
* Add return type to `test_from_gate_with_cyclic_definition ` in `test_clifford.py`
* Update update-gate_map-visualizations-6ea907a0502fdc1a.yaml
* Rename update-gate_map-visualizations-6ea907a0502fdc1a.yaml to update-gate-map-visualizations-6ea907a0502fdc1a.yaml
* Update update-gate-map-visualizations-6ea907a0502fdc1a.yaml
* Update update-gate-map-visualizations-6ea907a0502fdc1a.yaml
* Update pauli_op.py to use np.prod
`np.product` is deprecated and is causing test fails.
* Update operator.py to use np.prod
`np.product` is deprecated and is causing test fails.
* Update pauli_sum_op.py to use np.prod
`np.product` is deprecated and is causing test fails.
* Update random.py to use np.product
`np.product` is deprecated and is causing test fails.
* Update chi.py to use np.prod
`np.product` is deprecated and is causing test fails.
* Replace np.product with np.prod
`np.product` is deprecated and is causing test fails.
* Update ptm.py to use np.prod
`np.product` is deprecated and is causing test fails.
* Update stinespring.py to use np.prod
`np.product` is deprecated and is causing test fails.
* Update superop.py to use np.prod
`np.product` is deprecated and is causing test fails.
* Update transformations.py to use np.prod
`np.product` is deprecated and is causing test fails.
* Update densitymatrix.py to use np.prod
`np.product` is deprecated and is causing test fails.
* Update random.py to use np.prod
`np.product` is deprecated and is causing test fails.
* Update statevector.py to use np.prod
`np.product` is deprecated and is causing test fails.
* Update local_readout_mitigator.py to use np.prod
`np.product` is deprecated and is causing test fails.
* Update unitary_synthesis.py to use np.prod
`np.product` is deprecated and is causing test fails.
* Update test_random.py to use np.prod
`np.product` is deprecated and is causing test fails.
* Update test_scalar_op.py to use np.prod
`np.product` is deprecated and is causing test fails.
* Update test_random.py to use np.prod
`np.product` is deprecated and is causing test fails.
* Update test_clifford.py to remove debugging code
* Move matplotlib imports to occur at run time
* Apply suggestions from code review
* Move matplotlib_close_if_inline to runtime import too
* Flatten parallel edges
Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
* Fix 1 qubit backend handling
* Fix qubit label and font sizes
* new reference images
* Adjust font scaling
* Update reference images
* Remove unrelated reference file update
* Improve formatting
* Adjust pixel scaling factor
* Update reference images with formatting changes
---------
Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
Co-authored-by: Luciano Bello <bel@zurich.ibm.com>
* fix random statevector distribution
* add citation and release note
* mention Haar measure in doc and use link in release note
* cite better reference
* Format reference
---------
Co-authored-by: Julien Gacon <gaconju@gmail.com>
* Add sign() method to ParameterExpression
This method allows applying the sign operation to an expression with
possibly unassigned parameters.
* Update releasenotes/notes/added-sign-feature-parameterexpression-57693dd69103dc8c.yaml
Co-authored-by: Will Shanks <wshaos@posteo.net>
* Update releasenotes/notes/added-sign-feature-parameterexpression-57693dd69103dc8c.yaml
Co-authored-by: Will Shanks <wshaos@posteo.net>
* Update releasenotes/notes/added-sign-feature-parameterexpression-57693dd69103dc8c.yaml
Co-authored-by: Will Shanks <wshaos@posteo.net>
---------
Co-authored-by: Will Shanks <wshaos@posteo.net>
Co-authored-by: Will Shanks <willshanks@us.ibm.com>
* Use singletons for standard library unparameterized, non-controlled gates
This commit adds a new class SingletonGate which is a Gate subclass that
reuses a single instance by default for all instances of a particular
class. This greatly reduces the memory overhead and significant improves
the construction speed for making multiple instances of the same gate.
The tradeoff is in the flexibility of use because it precludes having
any potentially mutable state in the shared instance. This is a large
change to the data model of qiskit because it previously could be
assumed that any gate instance was unique and there weren't any
unintended side effects from modifying it in isolation (for example
doing XGate().label = 'foo' wouldn't potentially break other code).
To limit the impact around this instances of SingletonGate do not allow
mutation of an existing instance. This can (and likely will) cause
unexpected issues as usage of the class is released. Specifically what
used to be valid will now raise an exception because it is a shared
instance. This is evident from the code modifications necessary to
most of the Qiskit code base to enable working with instances of
SingletonGates. The knock on effects of this downstream are likely
significant and managing how we roll this feature out is going to be
equally if not more important than the feature itself. This is why
I'm not personally convinced we want to do all this commit includes
in a single release. I've opened this as a pull request primarily to
start the conversation on how we want to do the roll out to try and
minimize and notify downstream users of the potential breakage to
avoid issues. The primary issue I have is this doesn't really follow
the Qiskit deprecation policy as there is no user facing notification
or documentation of this pending change and code that worked in the
previously release will not work in the release with this feature.
For some aspects of this change (primarily the setters on gate
attributes) this can easily be handled by deprecating it in planned
singleton standard library gates and waiting the necessary amount of
time. But the more fundamental data model changes are hard to announce
ahead of time. We can have a release note about it coming in the future
but it will end up being very abstract and users will not necessarily
be able to act on it ahead of time without concrete examples to test
with. This was an issue for me in developing this feature as I couldn't
anticipate where API breakages would occur until I switched over all the
standard library gates, and there still might be others.
Due to the large performance gains this offers and also in the
interest of testing the API implications of using singleton gates the
unparameterized and non-controlled gates available in
qiskit.circuit.library.standard_gates are all updated to be subclasses
of singleton gates. In aggregate this is causing construction to be
roughly 6x faster and building circuits comprised solely of these gates
consume 1/4th the memory as before. But it also exposed a large number
of internal changes we needed to make to the wider circuit, QPY, qasm2,
dagcircuit, transpiler, converters, and test modules to support working
with singleton gates.
Besides this there are a couple seemingly unrelated API changes in
this PR and it is caused by inconsistencies in the Instruction/Gate
API that were preventing this from working. The first which is the
ECRGate class was missing a label kwarg in the parent. Similarly
all Gate classes and subclasses were missing duration and unit
kwargs on their constructors. These are necessary to be able to use
these fields on singletons because we need an interface to construct
an instance that has the state set so we avoid the use of the global
shared instance. In the release notes I labeled these as bugfixes,
because in all the cases the parent clases were exposing these
interfaces and it primarily is an oversight that they were missing
in these places. But personally this does seem more like something
we'd normally document as a feature rather than a bugfix.
A follow up PR will add a SingletonControlledGate class which will
be similar to SingletonGate but will offer two singleton instance
based on the value of ctrl_state (and also handle nested labels
and other nested mutable state in the base gate). We can then update
the standard library gates like CXGate, and CHGate to also be
singletons. The ctrl state attribute is primarily why these gates
were not included in this commit.
* Fix Python 3.8 compatibility
There are some differences in how the inspect stdlib module behaves
between python 3.8 and newer versions of python. This was causing
divergence in the test and qpy behavior where inspect was used to
determine different aspects of a gate (either whether label was
supported as an arg or find the number of free parameters). This commit
fixes this by adjusting the code to handle both newer versions of
inspect as well as older ones.
* Simplify qpy deserialization label handling
* Remove unused classmethod decorator
* Fix lint
* Fix timeline drawer on output of legacy DD pass
* Fix doc build
* Add methods to deal with mutability of singleton gates
This commit adds two methods to the SingletonGate class, mutable and
to_mutable. The mutable() method is a property method that returns
whether a particular instance is mutable or a shared singleton instance.
The second method to_mutable() returns a mutable copy of the gate.
* Disallow custom attribute on singleton instances
This commit adds a __setattr__ method to the singleton gate class to
ensure that custom attributes are not settable for a shared singleton
instance. It prevents addign a custom attribute if the instance is in
singleton mode and will raise a NotImplementedError to avoid silently
sharing state in the single shared instance.
* Fix rebase error
* Fix rebase issues
* Fix module docstring
* Add .mutable and .to_mutable() to Instruction
To unify the access patterns between SingletonGates and other
instructions this commit adds a common property mutable and method
to_mutable() to check if any Instruction (not just singletons) are
mutable or not and to get a mutable copy. For things that don't inherit
from SingletonGate these are hard coded to `True` and to return a copy
as by default every Instruction is mutable, only `SingletonGate` objects
are different in this regard.
* Unify handling of gates in scheduling passes
Previously we were explicitly handling the SingletonGate class in the
scheduling passes. But with the introduction of mutable and to_mutable()
on Instruction we don't need to condition on gates being singleton or
not and we can just handle them in the same manner as other
instructions. This commit implements this change.
* Remove unnecessary deepcopy in substitute_node_wtih_dag
* Fix logic for SingletonGate.copy
Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
* Update Singleton Gate class docstring
* Remove unused imports
* Update release notes
* Fix release note typos
Co-authored-by: Jake Lishman <jake@binhbar.com>
* Improve setattr performance
* Fix deepcopy logic
* Add check for kwargs up front
* Fix docs typos
* Add comment on to_mutable __init__ call
* Fix lint
* Handle positional initialization arguments in SingletonGate
If there are any positional arguments set when initializing a new
SingletonGate subclass those were not being handled correctly before. If
there is a positional argument being set that would indicate at least a
label is being set and indicates a mutable instance should be returned
instead of the immutable singleton. This commit adds the missing check
to the __new__ logic and also adds a test to verify the behavior is
correct.
---------
Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
Co-authored-by: Jake Lishman <jake@binhbar.com>
The pass was accessing the circuit calibrations incorrectly, resulting in
an error when one of the gates in the dynamical decoupling sequence had
a pulse gate calibration.
When assigning parameters in a heavily parametrised circuit, a
significant amount of time was spent constructing a new set of all the
`Parameter` instances used in a circuit. This completely dominated the
execution time for the case of binding a single parameter out of a
many-parameters circuit in place.
This modifies the internal-only method
`QuantumCircuit._unsorted_parameters` to directly return the set object
already constructed by the `ParameterTable` tracking the operations,
which makes the function close to free to call, at the cost that
internal users of that function must take care not to mutate the output.
This is not generally a problem, since no code in Terra outside of
`QuantumCircuit` uses that method (nor should it!), and `QuantumCircuit`
never needs to mutate that set.
This specialises `Parameter.assign` to more efficiently handle parameter
assignment via `QuantumCircuit.assign_parameters`. The assignment can
either be of `self`, and therefore should just return the value lifted
to a `ParameterExpression`, or it's not of `self`, in which case we need
to raise an error to match the superclass implementation.
The overhead of all the checks that go on during the regular
`ParameterExpression.assign` (delegating to `subs` or `bind`) are a
sizeable chunk of the cost of assignment in PEC-style circuits.
* Fix GateDirection
* Fix black
* Add note about qubit index assumption to class docstring
---------
Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
* Add option to SabreLayout to specify starting layouts
The SabreLayout pass typically starts with each layout trial with a
random starting layout. However, in some cases starting with a specific
starting layout can result in better output quality than starting with
a fully random layout. To use this feature an analysis pass can set a
new `sabre_starting_layout` field in the property set before
`SabreLayout` with a list of layout objects that will add additional
trials using each layout as a starting layout.
* Fix lint
* Combine random layout and partial layouts
* Expand property set docs
Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
* Simplify branching logic for parallelism
* Use a slice for starting_layout in a trial
* Update releasenotes/notes/seed-sabre-with-layout-17d46e1a6f516b0e.yaml
Co-authored-by: Jake Lishman <jake@binhbar.com>
* Make starting layout variable names plural
The starting layout is a list and can have more than one entry. To make
this clearer, this commit renames starting_layout -> starting_layouts
and sabre_starting_layout -> sabre_starting_layouts.
* Update releasenotes/notes/seed-sabre-with-layout-17d46e1a6f516b0e.yaml
Co-authored-by: Jake Lishman <jake@binhbar.com>
* Update property set key in test
* Update test to only use partial layout
---------
Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
Co-authored-by: Jake Lishman <jake@binhbar.com>
* Remove deprecated BIPMapping pass
This commit removes the deprecated BIPMapping pass. It was deprecated in
qiskit-terra 0.24.0 and the minimum deprecation period has elapsed for
the Qiskit 0.45.0 release. This pass has been moved to an external
plugin that can be installed separately and integrated into the
transpiler more cleanly than a single pass and also separates the
optional dependency on the proprietary CPLEX into a separate package.
* Apply suggestions from code review
Co-authored-by: Kevin Hartman <kevin@hart.mn>
* Remove additional uses of BIPMapping
There were still two locations where the BIPMapping pass was being used.
First the dedicated unit tests, and then also import redirects for the
docs and easier access. This commit removes these locations so nothing
left is using the BIPMapping pass.
* Update optionals documentation
* Update install commands
---------
Co-authored-by: Kevin Hartman <kevin@hart.mn>
* Adding h, u and p to the BasicAer
* typo
* reno
* reno
* Update releasenotes/notes/h_basic_aer-3fc5e6776f0de9c1.yaml
---------
Co-authored-by: Luciano Bello <bel@zurich.ibm.com>
* Removal: Removing num_ancilla_qubits property from PolynomialPauliRotations class
removed function and deprecate_func from polynomial_pauli_rotations.py
added release note with upgrade notice
* Fixing release note to properly resolve property
* Fix release notes
Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
---------
Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
* Add fast-path construction to `DAGCircuit` methods
This optimises the constructor functions
`DAGCircuit.apply_operation_back`, `apply_operation_front` and `compose`
by giving callers a way to skip the validity checking when passing
known-good values. In most cases when we're operating on the DAG, we
are certain that we're already upholding the invariants of the data
structure by nature of having a `copy_empty_like` or similar, and the
user should not pay a runtime price for what we should catch during
testing.
* Check for possibility of bits before iterating
---------
Co-authored-by: John Lapeyre <jlapeyre@users.noreply.github.com>
The custom `decay` heuristic is supposed to penalise increases in depth
in the output. The output space of qubits are the physical qubits, so
the depth is defined in relation to those. Since its introduction in
gh-4537, this heuristic has instead been tracking the depth on the
virtual qubits, which due to the swaps is not necessarily related to the
depth in the output.
Notably, this commit actually makes the depth for routing large
volumetric circuits slightly _worse_ on average (at least for heavy-hex
topologies). This may be because the effect on the heuristic is
overweighted, or that the depth tracking resets after each gate is
routed (and occasionally in between) to be flat across all qubits,
rather than reflecting the actual depth each qubit is subject to.
This commit modifies the the preset pass manager construction to by
default use the UnrollCustomDefinitions and BasisTranslator passes to
perform the unrolling of operations that operate on >= 3 qubits. This is
done by leveraging the min_qubits argument added to those passes in this
commit which lets you set a minimum number of qubit arguments to
translate operations for.
Previously, this was handled by the Unroll3qOrMore pass which works by
iterating over the DAG and finding all operations with >= 3 qubits and
recursively unrolling them until the output is all in terms of 1 or 2
qubit operations. This works fine, but has undesireable runtime
performance characteristics because standard gates repeatedly have to
build new DAGs to substitute in. For example, if you had a circuit with
50k CCXGates that would result in 50k new DAGs being created from
scratch for each instance of CCXGate. A previous attempt was made to
add a translation cache to that pass in #10703 but as was discussed in
code review caching the circuit is unsound as it's possible for a custom
gate object to be constructed such that it would be cached and return an
invalid substitution circuit. By leveraging the basis translator
we only build as many substition DAGs as needed.
* Handle final comments with no terminating newline in OpenQASM 2
Previously, if an OpenQASM 2 program to be parsed ended in a comment
with no terminating '\n', the lexer would fail to notice the end of the
file and would instead attempt to emit the second '/' of the comment
introduction as a 'Slash` token.
* Run `cargo fmt`
* Testing extra cases
---------
Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
---------
Co-authored-by: Luciano Bello <bel@zurich.ibm.com>
Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
* __qiskit_version__ deprecation
* reno
* reno feature
* PackageNotFoundError
* revert stacklevel=2
* revert change in test
* remove OrderedDict
* other qiskit.__qiskit_version__ packages have their own __version__
* wording in the reno
* qiskit-terra == qiskit in version libraries
* lint
* readjust test
* raise an exception with a custom gate with no qubits or with one-or-more clbits
* QASM2ExportError
* test_circuit_raises_invalid_custom_gate_1
* test_circuit_raises_invalid_custom_gate_2
* reno
* revert
* revert
* adapt test
* reno
* conflicts
* Move OpenQASM 2 exporter to `qiskit.qasm2`
This gets us into a position where the interface is similar between the
`qasm2`, `qasm3` and `qpy` modules (all of which do vaguely similar
things at an abstract level), which are in turn similar to functionality
in the Python standard libraries.
This commit simply moves the code from `QuantumCircuit.qasm` over to the
new location. Some idiosyncrasies and additional bits of features that
we do not intend to support long term (e.g. formatted output) are not
brought over, but `QuantumCircuit.qasm` continues to perform those
jobs until it is deprecated and removed.
* Use 'text' instead of unknown 'qasm2' highlighter
* Fix lint import cycle
* Fix Sphinx typos
* Fix for new unitary decomposition
* Apply suggestions from code review
Co-authored-by: Luciano Bello <bel@zurich.ibm.com>
---------
Co-authored-by: Luciano Bello <bel@zurich.ibm.com>
* Do not use Bit.index in quantum_info/operators/symplectic/pauli.py
* bugfix
* Fix cross-reference
---------
Co-authored-by: Jake Lishman <jake@binhbar.com>
* Update text.py
* Update utils.py
* Fix test using text
* Lint
* Lint
* Fix if with body bug and first tests
* Finish tests
* Reno
* Output=text
* Cleanup
* Fix repr and repr_html issue with jupyter
* Cache _single_string to fix __repr__ and _repr_html__ issue
* Get circuits from blocks and fix inner_wire_map
* Fix gate on qubit issue and add test
* Lint
* First work on transpiled nested
* Fix condition for flow ops
* Intermediate flow_wire_map testing
* Fix clbit bug
* Finish transpiled bits bug
* Final fix for conditions and transpiles
* Fix review issues 1
* Revert wire_order test
* Fix control gates with wire_map and test changes
* Further case and else
* Fix review items 2
This commit updates the preset pass manager construction to only use
plugins for the init stage. To accomplish this the previously hard
coded built-in pass manager used for each optimization level are
refactored to be in a plugin named "default". One thing that is changed
in this PR is that the use of `generate_control_flow_options_check()`
is moved to the `pre_init` stage. The reason for this is because the way
the init stage was being constructed in the preset pass managers was to
do initial checking of any methods, and this was unconditionally being
run. This is a more logical fit for pre_init stage because it should run
before any specified plugin.
Fixes: #10687Fixes: #8661
* Initial: Optimization stage as a plugin.
* CI: Added fix to preset_passmanager test
* Simplify inner translation stage creation logic
This commit changes the plugin construction logic slightly to adjust
how the embedded translation stage is created. After #10621 merged we
only need to use the plugin interface to get the translation stage pass
manager.
* Update documentation
---------
Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
* Migrate layout stage to plugins
This commit updates the preset pass manager construction to only use
plugins for the layout stage. To accomplish this the previously hard
coded built-in layout methods, trivial, dense, noise adpative, and
sabre are migrated to be exposed as built-in plugins. Additionally, the
special case of layout_method=None has been centralized into a standard
default method plugin, as the pass construction in this case involved
extra steps for each optimization level. This simplifies the preset pass
manager construction as now the layout stage is solely built via
plugins.
Fixes#9455
* Remove unnecessary if statement
* Handle invalid optimization levels in plugins
* Remove unused variable post-rebase
* Fix performance of Sabre rust<->Python boundary
In #10366 the SabreLayout and SabreSwap passes were refactored to
support nested control flow blocks. As part of that refactor a new
struct SabreResult was created to store the nested results for each
block. This new class however resulted in PyO3 cloning the full swap map
on every access. Since we have at least 1 access per gate in the circuit
(and another one for each swap) this extra clone() adds a lot of extra
overhead for deep circuits. In extreme cases this regression could be
quite extreme. To address this the result format is changed to be a
tuple (as it was originally), while this is less ergonomic the advantage
it provides is that for nested objects it moves the rust object to the
pyo3 interface so we avoid a copy as Python owns the object on the
return. However, for control flow blocks we're still using the
SabreResult class as it simplifies the internal implementation (which is
why #10366 introduced the struct). The potential impact of this is
mitigated by switching to only a single clone per control flow block,
by only accessing the SabreResult object's attribute on each recursive
call. However, if it is an issue in the future we can work on flattening
the nested structure before returning it to python to avoid any clones.
Fixes#10650
* Simplify recursive call logic in _apply_sabre_result
This commit simplifies the logic in the recursive call logic in
_apply_sabre_result to always use a tuple so we avoid an isinstance
check.
Co-authored-by: Kevin Hartman <kevin@hart.mn>
---------
Co-authored-by: Kevin Hartman <kevin@hart.mn>
* Fix Sparse pauli setter to update dimension info
* Fix Sparse pauli setter to verify dimension info
Value error will be raised if:
1. Number of qubits are not equal
2. Number of elements in PauliList are not equal
* Add tests
* Add release note
---------
Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
Co-authored-by: Ikko Hamamura <ikkoham@users.noreply.github.com>
* Move metapackage shim for combined releases
Now that Qiskit 0.44.0 has been released, the Qiskit project is now what
was formerly qiskit-terra. However, because Python packaging lacks a
clean mechanism to enable one package superseding another we're not able
to stop shipping a qiskit-terra package that owns the qiskit python
namespace without introducing a lot of potential user friction. So
moving forward the qiskit project will release 2 packages an inner
qiskit-terra which still contains all the library code and public facing
qiskit package which installs that inner package only. To enable this
workflow this commit migrates the metapackage setup.py into the terra
repository and setups build automation to publish a qiskit package in
addition to the inner terra package on each release tag.
* some follow up on https://github.com/Qiskit/qiskit-terra/pull/10530 (#19)
* some follow up on https://github.com/Qiskit/qiskit-terra/pull/10530
* extend some badges
* This Qiskit contains the building blocks for creating and working with quantum circuits, programs, and algorithms. -> This framework allows for building, transforming, and visualizing quantum circuits.
* The explanation of the Bell state is moving to IBM Quantun learning platform
* I think examples/ should eventually be replaced by proper tutorials
* Add StackOverflow as a forum
* Remove link to https://github.com/Qiskit/qiskit-tutorials
* Update README.md
Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
* Update README.md
* Update README.md
* broken lines in badges
* doi
---------
Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
* Expand lint checks to entire qiskit_pkg dir
* Unify extras in terra setup.py
* Update CI lint job
* Remove unused json imports
* Cleanup manifest file
* Finish comment
---------
Co-authored-by: Luciano Bello <bel@zurich.ibm.com>
* Fix multiple nested custom controlled gates in QPY
When a circuit contained multiple custom controlled gates that in turn
had custom definitions, the QPY serialisation could fail to write out
some of the inner instructions correctly. This led to an invalid QPY
file that could not be read back.
* Remove local warning-suppression import
* add draw method to Operator class
* add _ipython_display_ to operator class
* (fix) check type of state in TextMatrix to allow the use of Operators
* add Operator drawer tests
* eblack, elint changes
* add reno
* (fix) replace repr output, change ValueError to f-string
* (fix) remove duplicate 'latex' option in test_operator
* fix lint, build errors
* add condition to TextMatrix to hide dims for qubit operator
* (fix) remove elif statement in TextMatrix to avoid unhandled else branch
Raising the minimum Rust version lets us access workspace dependencies,
which are a convenient way of managing shared metadata between the
different crates in the project, which deduplicates a good amount of
our metadata. This also lets us share the PyO3 version and minimum
feature set between crates, reducing the number of places that need to
be updated on a Python version bump.
`Cargo.lock` is completely regenerated for this commit with the new
unification, with the minor tweak of having run
cargo update -p 'indexmap@2.0.0' --precise '1.9.3'
This is required to unify the `hashbrown` versions down to 0.12.3
between our dependencies and `pyo3`, which otherwise transitively
depends on `hashbrown ^0.14` via pulling in `indexmap 2.0`. This caused
a build failure, since the `hashbrown` types that PyO3 adds `impl`s of
its traits to are not the same types that our extension modules attempt
to use with it.
* Implemented a type check in copy method of QuantumCircuit class
* Made copy method code more efficient and added a circuit operation test
* Corrected and made clear documentation of copy method - QuantumCircuit
* Fix wording
---------
Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
* Force decimal points in OpenQASM 2 floats
The letter of the OpenQASM 2 specification has a regex defining
floating-point literals that requires a decimal point, even in the
presence of an exponential component. This is unusual for most
programming languages, but Qiskit's exporter should follow the spec as
close as we can to increase interop. Our parser accepts floats with an
exponent and no decimal point as a minor syntax extension, unless in
strict mode.
* Simplify English
* Fix final_layout when VF2PostLayout finds a better layout
This commit fixes a bug in the preset pass managers when VF2PostLayout
is run and finds a better layout to use. In these cases the ApplyLayout
was updating the layout but we never updated the final layout to reflect
these changes. This would result in an incorrect final layout because
the input positions of the qubits were incorrect after re-applying the
layout. This commit fixes this by adding code to ApplyLayout to also
update final_layout, if one is set, to reflect the new initial layout
found by VF2PostLayout.
Fixes#10457
* Remove stray debug print
* Use a list instead of a dict
* Add assertion on vf2postlayout being used in compiler.transpile tests
* Actually assert a post layout is set
The new parser would allow a `barrier;` statement, implicitly
broadcasting it across all qubits in scope. This is technically not
supported by the OpenQASM 2 specification, but is a useful
quality-of-life extension to the specification (in the same way that
Qiskit interprets barriers, and the OpenQASM 3 specification defines the
`barrier;` statement). The precise rule is added to the new parser's
`strict` mode.
The OpenQASM 2 _exporter_ similarly should not have been putting out
`barrier;` statements. These could only occur in Qiskit when a barrier
was explicitly constructed with zero elements (as opposed to the call
`QuantumCircuit.barrier()`, which has the all-in-scope behaviour), and
consequently have no actual meaning or effect. The exporter is modified
to simply skip such instructions, for as long as Qiskit permits the
qubitless barrier statement.
* raise an exception with a custom gate with no qubits or with one-or-more clbits
* QASM2ExportError
* test_circuit_raises_invalid_custom_gate_1
* test_circuit_raises_invalid_custom_gate_2
* reno
* Split error messages to be more specific
* Fix testing bug
* Fixup release note
---------
Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
For the 0.25.0 release we're going to push release candidates prior to
the release to enable testing before we cut the final release. In
preparation for tagging the first release candidate this commit updates
the version string to indicate it's a release candidate. This commit
should be what gets tagged as 0.25.0rc1.
* Allow control flow in opt levels 2 and 3.
* Add release note.
* Enable testing for opt 2 and 3.
* Remove guard on translation_method='synthesis'.
* Fix test for synthesis guard.
* Skip o3 qpy full path transpile test on windows
In CI we're seeing a reliable failure on windows when scipy is calling
LAPACK. This appears to be unrelated to the change in this PR branch and
is isolated to specific windows environments. This commit adds a skip
condition to skip that one test to workaround the failure in CI. The
wider issue with scipy compatibility on windows is being tracked in
issue #10345, when we have a conclusion to that and can reliably run
this test we should remove this skip condition.
---------
Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
* Initial: Introducing speedup by calculating matrix
* Lint: Reformat using Black
* Fix: Added `basis_count` and `outside_basis`
* Fix: Use `Operator` if `to_matrix` is unavailable.
* Fix: Default to Operator when necessary
- Will default to previous method when blocks have more than 2 qubits.
- This is a temporary measure.
* Lint: Removed Cyclic import
* Docs: Added release note.
* Docs: Added reference to the issue.
* Fix: Move `block_to_matrix` to ~.passes.utils
* Lint: Fixed cyclical import and order
* CI: Removed type checking
* Add: Exceptions on `_block_to_matrix`
* Docs: Fix release note.
* Fix: Change import path for block_to_matrix
* Update qiskit/transpiler/passes/utils/block_to_matrix.py
---------
Co-authored-by: ewinston <ewinston@us.ibm.com>
* Add `Expr` support to OpenQASM 3 exporter
This adds support for `Expr` nodes in `condition` fields and
`SwitchCaseOp.target`. The general `c_if` condition checking is lifted
into an `Expr` node as part of the OQ3 export, so the form of them
automatically becomes like the new-style outputs, depending on how
`expr.lift_legacy_condition` chooses to raise them to `Expr` nodes.
As part of the refactor of the `Expression` subtree of the temporary
AST, I removed `SubroutineCall`. Its definition was severely
out-of-date (a form from before even the initial arXiv draft), where it
was statement-like instead of expression-like. There is currently no
support in Qiskit for representing these sorts of subroutines properly,
and the OQ3 exporter would produce invalid OQ3 if it encountered
something that it thought should be a a subroutine call. This commit
fixes that bug, correctly raising an exception that non-unitary
instructions are not yet supported for export.
This commit also removes the special casing from the `CXGate` into the
exporter itself; it was more convenient in the new structure of some
internal components, and it's a data model we don't want to support
anyway.
* Use `IntegerLiteral` for `Uint` values
This is what the QSS stack expects (they don't like bitstring literals
in expressions yet), and is more in line with what we used to do anyway.
* Fix quotes
* Add test of no spurious casts
* Support control flow in ConsolidateBlocks
* Add release note for support control flow in ConsolidateBlocks
* Move imports from inside function to top level
* Make construction of ConsolidateBlocks for control flow ops more efficient
* Do IfElseOp test without builder interface
Before, we used the builder interface for an ifelse op. Some details of
the circuit built, in particular the mapping of wires is not deterministic.
We could have used canonicalize_control_flow. But instead we construct the
IfElseOp manually. This removes the complexity of the builder interface from
this test.
* Linting
* Avoid cyclic import
* Try to fix cyclic import (in lint tool only)
* Reuse top-level consolidation pass and add tests
* Before, we created an new ConsolidationPass when descending into control flow
blocks. With this commit, we use the existing pass.
* Add some tests for cases where consolidation should not happen.
* Remove argument `decomposer` from constructor of ConsolidateBlocks
This was added in a previous commit in the series of commits for this
PR. The code has been redesigned so that this argument is no longer
necessary.
* Remove cruft accidentally left
In the first version of the associated PR, we created a new pass
when descending into control flow blocks. These lines were included to
support that construction and are no longer needed.
* Move function-level import to module level
Remove unused import in tests
* Write loop more concisely
* Update releasenotes/notes/add-control-flow-to-consolidate-blocks-e013e28007170377.yaml
Co-authored-by: Jake Lishman <jake@binhbar.com>
* Use assertion in tests with better diagnostics
* Remove reference to decomposer from docstring to ConsolidateBlocks
The previous doc string was a bit imprecise. It also referred to a decomposer which although
implied, is not meant to be accessible by the user.
* Use more informative tests for ConsolidateBlocks with control flow
* Simplify test in test_consolidate_blocks and factor
* Gates used in testing ConsolidateBlocks with control flow ops were copied
from another test in the file. They complicate the test, and removing them does
not weaken the test at all.
* Factor some code within a test into a function
* Factor more code in test
* Use clbit in circuit as test bit when appending IfElse
This has no effect on the test. But, previously, we used a clbit taken
from an unrelated circuit. This might give the impression that there is
some significance to this unexpected choice.
* In test, use bits in circuit as specifiers when appending gate to that circuit
Previously we used qubits and clbits from an unrelated circuit to specify which
bits to apply an IfElse to when appending. Here, we use bits from the same circuit that we are
appending the gate to. This does not change the test. But again, one might look for
significance in the previous unusual choice.
Qiskit considers two registers of the same length and the same name to be the
same register. The previous behavior depended on this choice.
* In a test, don't use qubits from unrelated circuit when constructing circuit
This has no effect on the test. As in the previous commits, the choice was
unusual and might imply some significance. The more natural choice is to
create new qubits by specifying the number.
* Factor code in test to simplify test
* Simplify remaining control flow op tests for ConsolidateBlocks
These simplifications are similar to those made for the first test.
* Run black
* Update test/python/transpiler/test_consolidate_blocks.py
Co-authored-by: Jake Lishman <jake@binhbar.com>
---------
Co-authored-by: Jake Lishman <jake@binhbar.com>
* Remove deprecated args from mpl drawer
* Reno mod
* Convert to wire_map, node_data, etc
* Lint
* Minor changes to match flow changes
* Cleanup
* Fix layer width per node and comments
* Lint
* Adjust layer num loading
* Revert n_lines
* Lint
* Add glob_data
* Lint and cleanup
* Initial PR for if-else
* Unused arg
* Lint
* Iniital box fold
* Fold flow boxes
* Add reno
* Fix initial mpl and window load
* Move figure, mpl, and style info to draw()
* Comments
* Change font vars and fix ax
* Make patches_mod global
* Minor fixes after pre merege
* Lint
* Add while
* Add for loop
* Finish SwitchCase and cleanup and utils gate_span
* Cleanup
* Fix gate_span bug and comments
* Fix layer bug by using all qubits in _get_layered
* Added final release note and deleted old one
* Minor spacing changes
* Add ipynb/mpl/circuit tests and references
* Lint
* Minor comments
* Adjust for_loop test
* Add test for IfElseOp with body
* Lint
* Update state_city image
* Comments, PORDER changes, cleanup
* Adjust MASK zorder
* Fix text color issue with other styles
* Final fixes
This reverts commit fbd64d95d9. The follow
on PR to this one #10127 which is making internal refactors to the pass
manager code now that's it a standalone module is still undergoing
active review and the scope of the PR is sufficiently large that it
likely won't be viable for the pending 0.25.0 release. This commit
temporarily reverts #10124 which was the first step of creating a module
by porting the pass manager code in it's current form to a standalone
module so that we're not committed to the API as part of the 0.25.0
release to give more time for #10127 to finalize what the eventual
`qiskit.passmanager` API will look like.
This revert should itself be reverted after 0.25.0rc1 is tagged and
the main branch opens up for 0.45.0 development. As this revert is
not an indication that we did not want #10124 it's just to avoid
committing to the API prematurely.
* Add flatten option to the NLocal family
This commit adds a new flag `flatten` to the circuit library elements in
the NLocal family. This flag is used to avoid the nested wrapping of the
output that is done by default in the output of these gates. This is
done primarily in the interest of performance. The runtime
performance of bind_parameters() is vastly improved with a flattened
output compared to the nested object. For example, running:
```
qc = EfficientSU2(100, entanglement="linear", reps=100)
qc.measure_all()
qc.bind_parameters({x: math.pi / 2 for x in qc.parameters})
```
the runtime of `bind_parameters()` went from ~390 seconds with the
wrapped output to ~0.5 seconds with the flattened output. I think given
these results longer term we might want to flip the default behavior to
only wrap on user request (likely for visualization as that's the only
use case I can think of for the wrapped output). The default value
is set to `None` in this PR to facilitate this change. In 0.26/0.45 we
can emit a warning if `flatten` is `None` to warn that the default will
change in a future release.
* Add missing nlocal subclasses
* Add setter
* Fix lint
* Fix flatten for EvolvedOperatorAnsatz
* Improve parameter-binding performance of large instructions
Previously, the parameter-assignment methods of `QuantumCircuit` had
poor performance when an instruction had a complex definition that
involved many of the parameters being bound. The strategy of binding
each parameter separately led to each definition being copied and
rebound multiple times, with each rebinding being recursive all the way
down.
This commit makes the definition rebinding happen only once per
instruction, and updates the data model used to make it a complete
recursion through `QuantumCircuit.assign_parameters`. This has the side
effect of fixing an issue where internal global phases would not be
updated.
The algorithmic change that enables this (just rebind the definition at
the end) is rather simpler than the length of this patch suggests. This
is just because the previous structure of separating out a single
`_assign_parameter` method made it harder to restructure the logic
without introducing unpleasant stateful coupling between the driver and
helper methods. Instead, I inlined most of the helper functions into
the driver body, so we can treat some components of the binding in a
per-parameter way and some in a per-operation way, in whatever way is
better.
* Fix lint
* Reduce overhead from input normalisation
This reduces several costs in the input normalisation, and makes the
calculation of some properties lazy for the sequence-like inputs; for
many close-to-hardware circuits such as those used in PEC, the sequence
form of parameter input is more natural, and almost no instructions will
have internally parametrised definitions, nor will there be a
parametrised global phase or calibrations. In these cases, we can avoid
overhead from eagerly normalising the input into the forms that's easier
for these less-common assignment operations to use.
As a side-effect of the abstraction, we can also avoid making several
dictionary copies, and just use the mapping abstraction to filter the
dictionary during iteration on the fly.
This also takes the opportunity to improve the performance of sorting
large vectors of parameters. In practice, I don't think this had a huge
impact on performance, but in principle it's rather more efficient now
and results in many fewer Python function calls during a sort.
* Address Ruff's generator concern
* Add comment on new keyword arguments
* adding reverse collection direction and test
* propagating options to CollectAndCollapse, CollectLinearFunctions and CollectCliffords passes
* reno
* test for clifford collection pass
* adding option split_layers
* propagating options and adding tests
* imrpoving tests and release notes
* temporarily removing release notes
* reinstating release notes
* reno fix
* change suggestion in review comments
* correct fix this time
* using condition_resources instead of condition_bits
* Update qiskit/dagcircuit/collect_blocks.py
This is nice!
Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
---------
Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
* add support for Discriminator and Kernel
* make Kernel and Discriminator hashable
* correct _assert_nested_dict_equal()
Co-authored-by: Will Shanks <wshaos@posteo.net>
* ensure b does not have extra keys
Co-authored-by: Will Shanks <wshaos@posteo.net>
* devide _read_kernel_and_discriminator and _write_kernel_and_discriminator
* update docs
* add tests testing Kernel/Discriminator equality
* add a qpy compatibility test
* add releasenote
* improve hashing in Kernel/Discriminator
* rm hashing from Kernel/Discriminator
* use write/read_sequence() to serialize lists
* add (de)serializer for dict and list
---------
Co-authored-by: Will Shanks <wshaos@posteo.net>
Co-authored-by: Will Shanks <willshanks@us.ibm.com>
As part of this minor refactor, this updates the logic to no longer
silently override conditions on the replacement `op`. The method gains
a `propagate_condition` argument analogous to the same argument in
`substitute_node_with_dag`, which can be set `False` to specify that the
caller is aware that the new operation should implement the same
conditional logic.
* fix measure_v2
* modify measure_all
* dispatch backend
* add test of the builder with backendV2
* reconfigure test codes and some func
* refactoring
* add reno
* fix _measure_v2
* fix backend.meas_map in measure_v2
* fix reno
* delete get_qubit_channels from utils
* add get_qubits_channels in qubit_channels
* recostruct test about the builder with backendV2
* add meas_map to Target class
* fix after mergin main branch
* fix documents about meas_map
* format target.py
* add reno
* add meas_map to target in convert_to_target
* add the more description about meas_map
* Update releasenotes/notes/enable_target_aware_meas_map-0d8542402a74e9d8.yaml
Co-authored-by: Naoki Kanazawa <nkanazawa1989@gmail.com>
* fix test_meas_map
* remove format_meas_map
* rename meas_map in target to concurrent_measuments
* change reno
* remove Unused Union Dict
* concurrent_measurements set as getattr(configuration, meas_map)
* Update qiskit/transpiler/target.py
Co-authored-by: Naoki Kanazawa <nkanazawa1989@gmail.com>
* Update qiskit/transpiler/target.py
Co-authored-by: Naoki Kanazawa <nkanazawa1989@gmail.com>
* format
---------
Co-authored-by: Naoki Kanazawa <nkanazawa1989@gmail.com>
* Added locate_bit method
* Changed transpilers passes to use find_bit method
* New changes, still need to fix
* Adding find_bit method to transpiler passes
* Added DAGCircuit method to get mapping of Qubit and Clbit to positional index Issue#9389
* added release notes for issue#9389
* fixed some formatting issues
* fixes for run, lint and doc errors
* updated releasenote and bip_model.py
* variable fix in bip_model.py
* reverted changes of bip_model.py
* revised files for updated usage of find_bit
* added changes to files noted
* Add test coverage
* Update releasenotes/notes/add-method-for-mapping-qubit-clbit-to-positional-index-6cd43a42f56eb549.yaml
---------
Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
* Add `Expr` support to the control-flow builders
This is generally relatively straightforwards; anywhere where we examine
the resources used by an operation, we need to update to account for
classical resources potentially being tied up in `ControlFlowOp` fields
in `Expr` nodes as well.
This also has the side effect of fixing a bug where a nested
`SwitchCaseOp.target` wasn't considered in the scope building for _all_
control-flow operations, which could incorrectly cause some registers to
be missed in outer scopes.
* Remove out-of-date comment
* Remove list argument broadcasting and simplify transpile()
This commit updates the transpile() function to no longer support
broadcast of lists of arguments. This functionality was deprecated in
the 0.23.0 release. As part of this removal the internals of the
transpile() function are simplified so we don't need to handle
broadcasting, building preset pass managers, parallel dispatch, etc
anymore as this functionality (without broadcasting) already exists
through the transpiler API. Besides greatly simplifying the transpile()
code and using more aspects of the public APIs that exist in the
qiskit.transpiler module, this commit also should fix the overhead we
have around parallel execution due to the complexity of supporting
broadcasting. This overhead was partially addressed before in #7789
which leveraged shared memory to minimize the serialization time
necessary for IPC but by using `PassManager.run()` internally now all of
that overhead is removed as the initial fork will have all the necessary
context in each process from the start.
Three seemingly unrelated changes made here were necessary to support our
current transpile() API without building custom pass manager
construction.
The first is the handling of layout from intlist. The
current Layout class is dependent on a circuit because it maps Qubit
objects to a physical qubit index. Ideally the layout structure would
just map virtual indices to physical indices (see #8060 for a similar
issue, also it's worth noting this is how the internal NLayout and QPY
represent layout), but because of the existing API the construction of
a Layout is dependent on a circuit. For the initial_layout argument when
running with multiple circuits to avoid the need to broadcasting the
layout construction for supported input types that need the circuit to
lookup the Qubit objects the SetLayout pass now supports taking in an
int list and will construct a Layout object at run time. This
effectively defers the Layout object creation for initial_layout to
run time so it can be built as a function of the circuit as the API
demands.
The second is the FakeBackend class used in some tests was constructing
invalid backends in some cases. This wasn't caught in the previous
structure because the backends were not actually being parsed by
transpile() previously which masked this issue. This commit fixes that
issue because PassManagerConfig.from_backend() was failing because of
the invalid backend construction.
The third issue is a new _skip_target private argument to
generate_preset_pass_manager() and PassManagerConfig. This was necessary
to recreate the behavior of transpile() when a user provides a BackendV2
and either `basis_gates` or `coupling_map` arguments. In general the
internals of the transpiler treat a target as higher priority because it
has more complete and restrictive constraints than the
basis_gates/coupling map objects. However, for transpile() if a
backendv2 is passed in for backend paired with coupling_map and/or
basis_gates the expected workflow is that the basis_gates and
coupling_map arguments take priority and override the equivalent
attributes from the backend. To facilitate this we need to block pulling
the target from the backend This should only be needed for a short
period of time as when #9256 is implemented we'll just build a single
target from the arguments as needed.
Fixes#7741
* Fix _skip_target logic
* Fix InstructionScheduleMap handling with backendv2
* Fix test failure caused by exception being raised later
* Fix indentation error
* Update qiskit/providers/fake_provider/fake_backend.py
Co-authored-by: John Lapeyre <jlapeyre@users.noreply.github.com>
* Fix standalone dt argument handling
* Remove unused code
* Fix lint
* Remove duplicate import in set_layout.py
A duplicate import slipped through in the most recent rebase.
This commit fixes that oversight and removes the duplicate.
* Update release notes
Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
* Adjust logic for _skip_transpile to check if None
* Simplify check cmap code
* Only check backend if it exists
---------
Co-authored-by: John Lapeyre <jlapeyre@users.noreply.github.com>
Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
* Deprecate Instruction.qasm
* Deprecate all `qasm` methods for Instruction and subclasses.
* Move code for generating OpenQASM 2 strings to `QuantumCircuit`.
* Test that deprecation warnings are raised.
* Add release note.
* Fix lint errors
* Fix still more lint errors
* Revert replacing old code with new inside deprecated method
In x.py in class C3SXGate the method `qasm` has been deprecated. It's
ok and simpler to deprecated code in this method. The two deprecated
pieces will be removed together.
* Revert formatting change
`for (param, value) in ...` was replaced with `for param, value in ...`.
This commit reverts that change.
* Remove method has_qasm2 from HamiltonianGate and simplify a deprecation message
* The method has_qasm2 was added in a previous commit (not in main). It is
removed with this commit.
* An additional message was added to the deprecation warning for HamiltonianGate.qasm.
It is removed with this commit
* A test has been updated to reflect these changes.
* Simplify hack for name c3sqrtx
c3sqrtx is the name we need to use with OpenQASM2 for qiskit's c3sx.
This makes the hack a bit less wordy and perhaps more palatble. The gate's
name is no longer changed before calling a function on it, then changed back.
* Remove intermediate variable introduced with this 10399
PR 10399 (not merged) changed a method call inside a Python f-string statement
into a call outside, introducing a variable, and use of that variable inside the
f-string. This commit makes a more minimal change.
Now we only replace the method call with an ordinary function call.
* Restore blank line inadvertently removed
* Factor out creation of "custom" qasm2 operation statement
* Remove addition_message from deprecation in x.py
* Update documentation for error thrown by QuantumCircuit.qasm
The docstring states that a CircuitError is raised if a gate cannot be converted to qasm2.
But this is now handled ultimately by the qasm2 exporter.
* Rename variable from name_param to qasm2_call
* Update call from QasmError to QASM2ExportError
* Remove unused import
* Add decompose_dag method to DAGCircuit class
* Don't clean up idle wires within function
* Add tests for DAGCircuit.separable_circuits
* Add ordering and QuantumCircuit equivalency tests. Add release note.
* Code style changes
* Update release note
* Clean up documentation
* Return a DAG for any partition with at least one qubit, even if empty
* Adjust tests to new flag
* peer review
* peer review
* fix var name
* test against dagcircuits
* lint
* test remove_idle_wires
* improve release note
* Update separable_circuits docstring
* Sort the dag circuits in tests to prevent them breaking in future
* minor cleanup
* minor cleanup
* Fix sorting
* Fix type-hint resolution
* black
* unused import
---------
Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
* Initial commit.
* Downgrade hashbrown to 0.12.3 for compat with Rustworkx.
* Implement gen_swap_epilogue.
* Add Python wrappers for structs.
* Implement DAG -> SabreDAG.
* Apply block results in sabre_swap.py.
* Fix node ID lookup issue.
Previously, we were using original DAG node IDs to look up nodes
in the expanded nested DAGs, but these IDs are of course not the
same.
* Fix bug where block circuits started out non-empty!
* Move DAG building and result application to functions.
* Implement control flow handling for Sabre layout.
* Fix qreg indexing bug for new swaps versus routed gates.
* Run Python formatting.
* Fix bug where root_dag was used instead of mapped_dag.
* Fix bug where swap_epilogue was in terms of physical bits instead of logical.
* Add more tests from stochastic swap.
* Fix bug mapping inner block qubits to outer circuit qubits.
* Update sabre swap testing.
* Update TODOs.
* Fix bug where a 2Q CF nodes would be mistakenly added to the extended set.
* Port more testing from stochastic swap.
* Run formatting.
* Port remaining stochastic swap tests.
* Mark Sabre routing and layout as known good for CF.
* Add random circuit valid output testing for Sabre.
* Run cargo fmt.
* Fix lint issues.
* Fix lint issues.
* Update 'test_invalid_methods_raise_on_control_flow'
* Make gen_swap_epilogue consume 'from_layout'.
* Add release note.
* Update TODO comment about num_qubits.
* Add comment about forward DAG.
* Explicitly mark NodeBlockResults as a mapping.
* Use closure instead of lambda noun.
* Add comment to make gate placement handling clearer.
* Use hashbrown::HashMap in SabreDAG.
* Add caching of circuit_to_dag.
* Simplify parameters to _build_sabre_dag.
- Makes it more explicit that the num_qubits used in a SabreDAG
should be the number of physical qubits on the device.
- We no longer pass clbit indices because they are always local to
the block, i.e. there's no current reason for them to be consistent
across the root DAG and inner blocks, like we must do for qubits.
* Copy cregs during empty_dag.
* Comment-out assert.
* Use intersection_update.
* Remove unused import.
* Add caching for block dict.
* Fix import order.
* Follow types consistently in test.
* Refactor output of OpenQASM 3 exporter to use fewer aliases
This removes spurious `_loose_bit` "registers" from the OpenQASM 3
output, and instead emits loose bits with individual `bit` and
`qubit` declarations. Non-overlapping registers are emitted using
regular `bit[n]` and `qubit[n]` definitions when possible, and we only
resort to aliasing if we must to describe the structure.
This avoids introducing structure to the definitions that does not exist
in the original program, making round-trips and interactions with other
OQ3 consumers more straightforwards. It's better not to use advanced
features that don't map to hardware particularly well when it's not
necessary.
On the technical side, all bits are now properly tracked in the symbol
table. Previously, there was a lot of code duplication, internal state
tracking and magic inferences that attempted to "guess" how a
qubit/clbit should be referred to. Instead, we just properly add them
as variables to the symbol table, which also drastically reduces the
number of objects that effectively reserve names that the user may not
use.
* Remove unnecessary empty init
* Fix typo
Co-authored-by: Ian Hincks <ian.hincks@ibm.com>
* Add explicit test of old option
---------
Co-authored-by: Ian Hincks <ian.hincks@ibm.com>
* Remove cyclic-definition handling from `Clifford.from_circuit`
This reliance on `RecursionError` could lead to CPython crashing, when
the user had raised the recursion limit beyond what their operating
system could actually support in terms of Python frames. This was
particularly an issue with Windows when in a context that `jedi` is
active (such as in an IPython session, or if `seaborn` was imported),
since `jedi` unilaterally sets the recursion limit to 3000, while
CPython tends to overflow the stack on Windows at around 2700 frames.
Recursive `definition` fields are not valid data in the Qiskit model, as
the definition is supposed to be hierarchical, and a decomposition in
terms of gates that do not involve the current one in any form. For
defining equivalences that may involve cycles, one should use the
`EquivalenceLibrary` objects that Terra manages, and the transpiler
takes advantage of via the `BasisTranslator`.
* Remove unused import
* fix 1q bug
* formatting
* restrict 2q gates from apply_a2
* Add check that decomposition includes qsd2q gates before optimizing them
Co-authored-by: jsmallz333 <90203920+jsmallz333@users.noreply.github.com>
* Apply suggestions from code review
Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
* Add release note for fix to issue 10036
* avoid creating unitary gate if initial gate is 2q
* remove debug code
* Change "certain" to "trivial"
This was requested in a review comment.
---------
Co-authored-by: John Lapeyre <jlapeyre@users.noreply.github.com>
Co-authored-by: jsmallz333 <90203920+jsmallz333@users.noreply.github.com>
Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
* add initial tests
* tests passing
* remove debug code
* fix test for clbits
* formatting
* Lift creation of PassManager out of loop
In _handle_control_flow_ops, a new PassManager was created for each ControlFlowOp
found. This commit moves the creation out of the loop over nodes. This should be
a bit more efficient.
I also considered mapped_blocks.clear() rather than reallocating. But in some
simpler tests of clearing rather than reallocating, this is actually less performant.
I think reallocating renders the code slightly more understandable.
* Test commutative cancellation does not cross block boundaries
These were requested in a review comment. The previous commit was
also requested in a review comment.
* Add release note for commutative cancellation in control flow blocks
* Include CommutativeAnalysis pass explicitly when doing control flow blocks
A new PassManager for CommutativeCancellation is constructed when descending into control flow blocks.
This commit explicitly includes a CommutativeAnalysis pass in this construction rather than relying on
`requires`. This change, while not necessary, is made for consistency with other explicit constructions
of PassManagers containing these passes.
* Use existing CommutativeCancellation pass in control flow op blocks
A previous commit made a copy of the pass being used in the parent context to be used
in the blocks of a control flow op. With this commit, we reuse the existing pass,
as it is immutable.
* Move import of PassManager from method to top of file
* Revert commit f8c2aaf because I missed a fix already to go
* Update qiskit/transpiler/passes/optimization/commutative_cancellation.py
Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
---------
Co-authored-by: John Lapeyre <jlapeyre@users.noreply.github.com>
Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
* Add mid-circuit measurement before conditional operation in random_circuit
* fixed format
* Update releasenotes/notes/fix_9016-2e8bc2cb10b5e204.yaml
Co-authored-by: Eric Arellano <14852634+Eric-Arellano@users.noreply.github.com>
---------
Co-authored-by: Luciano Bello <bel@zurich.ibm.com>
Co-authored-by: Kevin Krsulich <kevin@krsulich.net>
Co-authored-by: Eric Arellano <14852634+Eric-Arellano@users.noreply.github.com>
Co-authored-by: Kevin Krsulich <kevin.krsulich@ibm.com>
* contructing linear functions from circuits with barriers and delays; adding __eq__ method
* adding linear function extend_with_identity method
* constructing linear functions from nested circuits
* reorganizing code; constructing linear functions from cliffords (when possible)
* tests for linear functions from cliffords
* linear function from permutation gate
* simplifying condition for checking whether clifford is a linear function
* linear function from another
* pass over release notes
* black
* pylint fixes
* update docstring
* more docstring fixes
* adding pretty-printing functions for linear functions
* adding pretty-printing functions to the release notes
* adding pseudo-random tests
* moving import to the top of the file
* Fix to __eq__ as suggested in review
---------
Co-authored-by: Shelly Garion <46566946+ShellyGarion@users.noreply.github.com>
* added test to plot_histogram with dataset starting with zero
* fixed plot_histogram
* added docs
---------
Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
* Adding depth-5n -CX-CZ- synthesis algorithm
Adding the synthesis algorithm that jointly synthesize a CNOT circuit and CZ circuit in depth 5n by inserting P gates to the CNOT network.
Reference: D. Maslove and W. Yang, "CNOT circuits need little help to implement arbitrary Hadamard-free Clifford transformations they generate," 2022.
https://arxiv.org/abs/2210.16195
* Adding some test cases
* Fixing formatting and docstrings. Updating synth_clifford_depth_lnn
* Update test_clifford_decompose_layers.py
* Fixing some imports
* Fixing more formatting issues
* Add parameter type documentation and minor changes
* adding release note
* Update __init__.py for API
* Updating function name from synth_cx_cz_line_my to synth_cx_cz_depth_line_my
* Updating release note for function name change
* Stylistic changes addressing comments
* Fixing doc strings and adding example to release notes
* Update cx-cz release note with Alex's suggestions
---------
Co-authored-by: Alexander Ivrii <alexi@il.ibm.com>
* add schmidt_decomposition function to states/utils.py
* doc: add docstrings to schmidt_decomposition function
* tox -eblack
* lint changes
* fix qubit ordering definitions in docstring
* add abstol condition to save singular values
* add schmidt_decomposition to __init__.py files in .quantum_info and .quantum_info.states
* add tests for schmidt_decomposition function
* tox lint test
* correct test ordering
* (docs) add schmidt_decomposition to __init__.py docstring
* relabel subsystems in schmidt_decomposition for little-endian consistency
* (test) add test for individual elements of Schmidt decomposition
* tox and lint
* (test) add schmidt component check for 3-level system
* (docs) add reno
* (test) change assertions for schmidt_decomposition tests to AlmostEqual
* (docs) add note to docstring to clarify system partition to perform the decomposition
* (chore) fix typos, lint changes
* separate test functions, check for state with diffprob amps
* eblack lint changes
* Adding the feature of calculating entanglement measures negativity and logarithmic negativity
* Update docstring of negativity
* Modified the negativity function, where we have removed log negativity
* Modified the doc string of negativity function
* Edited the SVD calculation in the code
---------
Co-authored-by: Payal D. Solanki <solankipayal290696@gmail.com>
* Add `HAS_PYGMENTS` lazy tester
This somehow slipped through my nets when I added all the lazy testers.
We hope to drop support for the custom Pygments lexers in the future,
but in the mean time, this is the correct way to test for things, and
having an extra lazy tester doesn't hurt us.
* Remove unused import
* Add support for QuantumCircuit.layout to qpy
This commit adds the missing support for QuantumCircuit.layout to the
qpy format. This necessitates bumping the QPY format version to 8 to
accomodate the extra data needed for representing the details of the
layout. The tricky piece with representing the 3 TranspileLayout
attributes is representing the virtual bits in the initial layout
because there is no guarantee that the input circuit's registers are in
the output circuit (typically they are not when transpile() is used).
Fixes#10112
* Fix handling of empty layout
* Expand test coverage
* Fix lint
* Add qpy compat tests
* Fix compat tests
* Add release notes
* Adjust layout creation to be register independent
* Finish docs
* Only check layout in compat tests with circuits
* Fix typos
* Fix doc typo in qiskit/qpy/__init__.py
Co-authored-by: John Lapeyre <jlapeyre@users.noreply.github.com>
* Adjust introduction version for layout qpy compat tests
* Unify qpy compat test version filter style
* Add new line to layout error message
* Simplify serialization logic
Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
* Doc fixes
* Improve test coverage
* Don't reuse bits between initial layout and circuit in qpy compat tests.
* Update qiskit/qpy/__init__.py
* Fix test typo
* Use a register in compat tests for consistent equality
* Update test/python/qpy/test_circuit_load_from_qpy.py
---------
Co-authored-by: John Lapeyre <jlapeyre@users.noreply.github.com>
Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
The recursion inside the `CheckMap` pass was based on a custom
`DAGCircuit.compose` solution, rather than the more standard
qubit-argument-binding setup we normally use. This did not pass in the
clbit ordering to the composition, which could cause it to fail to map
nested conditional statements.
Instead, we can just enter each DAG naturally, and use the regular wire
map to access the physical indices being referred to.
* Add SymbolicPulse counterparts to the discrete library, and start deprecation process.
* Typo fix
* Release notes styling
* Docs and style corrections
* autosummary update to avoid name clashes
* Remove deprecation section from release notes
* Minor changes to Square()
* Deprecate namespace packaging hooks
This commit official deprecates the pkgutil namespace hooks that are
used for extending the `qiskit.*` and `qiskit.providers.*` namespaces
from external packages. These were previously used to enable the
elements packaging model where different parts of qiskit lived in
separate python packages under a shared namespace. This is no longer
being used and leaving the namespace extendable by external packages
carries a risk of issues or other accidental cross-interactions when an
external package gets loaded as part of Qiskit.
Fixes ##8809
* Update releasenotes/notes/deprecate-namespace-a2ac600f140755e2.yaml
Co-authored-by: Jake Lishman <jake@binhbar.com>
---------
Co-authored-by: Jake Lishman <jake@binhbar.com>
* Allow multiplication of SparsePauliOp and ParameterExpression
* Add unit tests for SparsePauliOp and ParameterExpression multiplication
* Add release note for the new feature
* Added classical_predecessors method
* add accesed method
* Added classsical_successor method
* Added classical predecessors and successors method
* added tol command
* successors method
* add test classical_successor method
* changed DagOutNode
* Apply suggestions from code review from @atharva-satpute. Thanks!
Co-authored-by: atharva-satpute <55058959+atharva-satpute@users.noreply.github.com>
* add assertRaises on test methods
* correct typo variable name
* change the descrption
* change the text on the example
* change the format of yaml
* new example
* new suggestions
* fix test
* new test example and change the release note
* Fixup release note
* Fix typo
---------
Co-authored-by: Maldoalberto <amaldonador1300@alumno.ipn.mx>
Co-authored-by: Maldoalberto <Alberto.Maldonado.Romo@ibm.com>
Co-authored-by: Luciano Bello <bel@zurich.ibm.com>
Co-authored-by: atharva-satpute <55058959+atharva-satpute@users.noreply.github.com>
Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
This commit removes the deprecated circuit_cregs argument from the
InstructionSet class. This argument was deprecated in the 0.19.0
release and has been supersceded by the resource_requester.
* Add standard 1q Pauli equivalences to standard library
This makes `transpile` a little more reliable in cases where people are
trying to use it to convert to a constrained basis. We can't
necessarily recognise _all_ possible transformations into an incomplete
basis, but simple Pauli relations are things people may well expect.
* Fix test setup
* added test for inner sequencial custom gates
* fixed quantum circuit qasm test
* fixed qasm method
* added a function to rename the operation
* updated test docstring
* updated recheck operation.name comment
* eblack fix test
* added docs
* lint test
* updated test string format
* Fixup release note
---------
Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
The primitives still need to support the legacy
`qiskit.opflow.PauliSumOp` while that object is deprecated but not
removed. However, we do not want the import of `qiskit.primitives` to
need to import `opflow` to do that, since that will cause the
deprecation warnings emitted by the import of `opflow` to be hidden
(they'll be blamed on Qiskit library code, so hidden by default).
All type-hint usage we can hide behind the `TYPE_CHECKING` static
analysis gate. For cases where we were actively runtime type-checking
an object, we can gate the `isinstance` check behind a check that
`qiskit.opflow` is already imported; the object cannot be a `PauliSumOp`
if the module isn't initialised.
* Improve casting and error message for `ParameterExpression`
Previously, we assumed that the only reason a cast of
`ParameterExpression` to `complex`/`float`/`int` could fail was because
of unbound parameters, and emitted an error accordingly. This is not
the case; a fully bound complex value will still fail to convert to
`float`.
This PR improves the error messages in these cases, and works around a
difference of Sympy and Symengine, where the latter will fail to convert
real-valued expressions that were symbollically complex at some point in
their binding history to `float`. Sympy more reliably reduces values
down to real-only values when the imaginary part is exactly cancelled,
which is a use-case our users tend to expect.
* Fix typo in test
* Update releasenotes/notes/parameter-float-cast-48f3731fec5e47cd.yaml
Co-authored-by: Kevin Hartman <kevin@hart.mn>
---------
Co-authored-by: Kevin Hartman <kevin@hart.mn>
* fix measure_v2
* modify measure_all
* dispatch backend
* add test of the builder with backendV2
* reconfigure test codes and some func
* refactoring
* add reno
* fix _measure_v2
* fix backend.meas_map in measure_v2
* fix reno
* delete get_qubit_channels from utils
* add get_qubits_channels in qubit_channels
* recostruct test about the builder with backendV2
* fix descriptions of test_macros
* fix descriptions of test_macros again
* delete import of backendV2 in utils
* revert no need to modify code
* Update releasenotes/notes/fix-dispatching-backends-28aff96f726ca9c5.yaml
Co-authored-by: Naoki Kanazawa <nkanazawa1989@gmail.com>
* Update a commnet in qiskit/pulse/builder.py
Co-authored-by: Naoki Kanazawa <nkanazawa1989@gmail.com>
* remove import TYPE_CHECKING
* removed test_builder.py utils.py and test_analyzation.py from pull request
---------
Co-authored-by: Naoki Kanazawa <nkanazawa1989@gmail.com>
* Use stable Python C API for building Rust extension
This commit tweaks the rust extension code to start using the PyO3 abi3
flag to build binaries that are compatible with all python versions, not
just a single release. Previously, we were building against the version
specific C API and that resulted in needing abinary file for each
supported python version on each supported platform/architecture. By
using the abi3 feature flag and marking the wheels as being built with
the limited api we can reduce our packaging overhead to just having one
wheel file per supported platform/architecture.
The only real code change needed here was to update the memory
marginalization function. PyO3's abi3 feature is incompatible with
returning a big int object from rust (the C API they use for that
conversion isn't part of the stable C API). So this commit updates the
function to convert to create a python int manually using the PyO3 api
where that was being done before.
Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
* Set minimum version on abi3 flag to Python 3.8
* Fix lint
* Use py_limited_api="auto" on RustExtension
According to the docs for the setuptools-rust RustExtension class:
https://setuptools-rust.readthedocs.io/en/latest/reference.html#setuptools_rust.RustExtension
The best setting to use for the py_limited_api argument is `"auto"` as
this will use the setting in the PyO3 module to determine the correct
value to set. This commit updates the setup.py to follow the
recommendation in the docs.
* Update handling of phase input to expval rust calls
The pauli_expval module in Rust that Statevector and DensityMatrix
leverage when computing defines the input type of the phase argument as
Complex64. Previously, the quantum info code in the Statevector and
DensityMatrix classes were passing in a 1 element ndarray for this
parameter. When using the the version specific Python C API in pyo3 it
would convert the single element array to a scalar value. However when
using abi3 this handling was not done (or was not done correctly) and
this caused the tests to fail. This commit updates the quantum info
module to pass the phase as a complex value instead of a 1 element numpy
array to bypass this behavior change in PyO3 when using abi3.
Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
* Set py_limited_api explicitly to True
* DNM: Test cibuildwheel works with abi3
* Add abi3audit to cibuildwheel repair step
* Force setuptools to use abi3 tag
* Add wheel to sdist build
* Workaround abiaudit3 not moving wheels and windows not having a default repair command
* Add source of setup.py hack
* Add comment about pending pyo3 abi3 bigint support
* Revert "DNM: Test cibuildwheel works with abi3"
This reverts commit 8ca24cf1e4.
* Add release note
* Simplify setting abi3 tag in built wheels
* Update releasenotes/notes/use-abi3-4a935e0557d3833b.yaml
Co-authored-by: Jake Lishman <jake@binhbar.com>
* Update release note
* Update releasenotes/notes/use-abi3-4a935e0557d3833b.yaml
---------
Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
Co-authored-by: Jake Lishman <jake@binhbar.com>
* * Added support for targets without a coupling map.
* * Removed restrictive raise.
* * Changed order of target and coupling map
* Apply suggestions from code review
Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
---------
Co-authored-by: Matthew Treinish <mtreinish@kortar.org>
* activate filter method in ScheduleBlock class
* use functools.singledispatch
* add tests for filter method in ScheduleBlock class
* filter out empty schedule_blocks
* update doc
* rm logical_and
* add catch-TypeError functions decorated with singledispatch
* use pulse builder in test
* make another test function for nested block
* add a release note
* Rm optional args
Co-authored-by: Naoki Kanazawa <nkanazawa1989@gmail.com>
* add warning
Co-authored-by: Naoki Kanazawa <nkanazawa1989@gmail.com>
* update the release note
Co-authored-by: Naoki Kanazawa <nkanazawa1989@gmail.com>
* activate exclude method in ScheduleBlock class
---------
Co-authored-by: Naoki Kanazawa <nkanazawa1989@gmail.com>
* Fix QuantumCircuit.draw() not outputting pdf in latex mode
* Added bugfix release note; moved import to the top
* Fixup release note
---------
Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
* Assign circuit parameters as int/float to instructions
* Do not test that fully bound parameters are still ParameterExpressions
* Change int to float in qasm output
pi_check casts integers to floats but not integers inside
ParameterExpressions.
* Workaround symengine ComplexDouble not supporting float
* black
* Update releasenotes/notes/circuit-assign-parameter-to-concrete-value-7cad75c97183257f.yaml
Co-authored-by: Jake Lishman <jake@binhbar.com>
* Update releasenotes/notes/circuit-assign-parameter-to-concrete-value-7cad75c97183257f.yaml
Co-authored-by: Jake Lishman <jake@binhbar.com>
* Restore assigned parameter value type check to tests
* Add test to check type and value of simple circuit parameter assignment
* Add consistency check between assigned instruction data and calibrations dict keys
* Add regression test
* Add upgrade note
* Remove support for complex instruction parameter assignment
* Restore complex assignment
Complex assignment maybe not be supported but allowing it in the
parameter assignment step lets validate_parameters get the value and
raise an appropriate exception.
* black
* More specific assertion methods
* Use exact floating-point check
---------
Co-authored-by: Jake Lishman <jake@binhbar.com>
Co-authored-by: John Lapeyre <jlapeyre@users.noreply.github.com>
Co-authored-by: Jake Lishman <jake.lishman@ibm.com>
* Fix unitary synthesis for parameterized basis gates in Target
Replace parameterized RXX with RXX(pi / 2) and parameterized RZX with RZX(pi / 4).
* Run black
* Fix dict ordering problem between linux and windows
* Remove unused import
* Try using seed in call to transpile to fix CI fail
Linux and MacOS give one result and Windows another
* Add comments explaining no symbolic gates can be sent to 2q decomposers
* Make test for synthesis in with parameterized basis gate less strict
Windows on the one hand, and MacOS and Linux on other give different circuits
in a simple test of synthesis. Both are correct. This commit makes the test less strict.
* Add release note for fix-issue-10082
* Fix PassManagerConfig.from_backend with BackendV1 and no CouplingMap
This commit fixes an issue in the PassManagerConfig.from_backend
constructor method when using BackendV1 based simulator backends. The
pass was incorrectly handling the case when the backend configuration
didn't have a coupling map defined and incorrectly creating a coupling
map with 0 qubits instead of using None to indicate the lack of
connectivity. This has been fixed so the coupling map creation is
skipped if there is no coupling map attribute in the backend's
configuration.
Fixes#10171
* Fix tests
* Fix top-level `switch` statements in `QuantumCircuit.compose`
The register-mapping code was not being applied to `SwitchCaseOp.target`
in the same way that it is for conditions. This commit does not change
any behaviour about recursing into _nested_ control-flow blocks, which
still likely have problems with composition.
* Apply suggestions from review
The previous logic around building a `Layout` object from an
`initial_layout` was still couched in the "registers own bits" model, so
could not cope with loose bits. It's most convenient to just build the
mapping ourselves during the parsing, since the logic is quite specific
to the form of the `initial_layout` argument, rather than being
something that's inherently tied to the `Layout` class.