Add measurement_keys property #7674
Open
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
This adds
measurement_keys
andcontrol_keys
properties toCircuit
,Gate
,Operation
, andMoment
, and any subclasses that require them, as an alternative to the corresponding protocols. These properties are cached for fast lookup (except on non-frozen circuits), which is critical since these methods are used in many performance-critical areas like commutativity checks in circuit construction and transformers.The change makes circuit construction about 15% faster in most cases because of the caching and elimination of protocol overhead. Allows for better code completion and less need to store results in temp local variables since the properties are cached (see the changes in
circuit.earliest_available_moment()
for example), resulting in cleaner, easier to write code that is performant by default.The code is made backwards compatible by having the base classes of
Gate
andOperation
return the results of the protocol, but overridden in subclasses where the keys are known. It also ensures forward consistency by having the protocols check the property values by default. This approach also allows protocols to prime the object's property cache for future use.The protocols are no longer used in cirq codebase outside of backward compatibility requirements, and could optionally be marked for deprecation for v2 in a future PR. Or we can leave them in place as alternative ways to get the keys, similar to how
numpy
classes frequently have member methods and package-level functions that alias them. One advantage of the deprecation route is that the base class implementations of these properties could then simply returnfrozenset()
rather than delegating to the protocols, which would further improve performance.Resolves #7469