Validates the internal consistency of a ParameterTable and its containing QuantumCircuit. Intended for use in testing. Raises: CircuitError: if QuantumCircuit and ParameterTable are inconsistent.
(circuit)
| 37 | |
| 38 | |
| 39 | def raise_if_parameter_table_invalid(circuit): |
| 40 | """Validates the internal consistency of a ParameterTable and its |
| 41 | containing QuantumCircuit. Intended for use in testing. |
| 42 | |
| 43 | Raises: |
| 44 | CircuitError: if QuantumCircuit and ParameterTable are inconsistent. |
| 45 | """ |
| 46 | |
| 47 | # Assert parameters present in circuit match those in table. |
| 48 | circuit_parameters = { |
| 49 | parameter |
| 50 | for instruction in circuit._data |
| 51 | for param in instruction.operation.params |
| 52 | for parameter in param.parameters |
| 53 | if isinstance(param, ParameterExpression) |
| 54 | } |
| 55 | if isinstance(circuit.global_phase, ParameterExpression): |
| 56 | circuit_parameters |= circuit.global_phase.parameters |
| 57 | table_parameters = set(circuit._data.unsorted_parameters()) |
| 58 | |
| 59 | if circuit_parameters != table_parameters: |
| 60 | raise CircuitError( |
| 61 | "Circuit/ParameterTable Parameter mismatch. " |
| 62 | f"Circuit parameters: {circuit_parameters}. " |
| 63 | f"Table parameters: {table_parameters}." |
| 64 | ) |
| 65 | |
| 66 | # Assert parameter locations in table are present in circuit. |
| 67 | circuit_instructions = [instr.operation for instr in circuit._data] |
| 68 | |
| 69 | for parameter in table_parameters: |
| 70 | instr_list = circuit._data._raw_parameter_table_entry(parameter) |
| 71 | for instr_index, param_index in instr_list: |
| 72 | if instr_index is None: |
| 73 | # Global phase. |
| 74 | expression = circuit.global_phase |
| 75 | instr = "<global phase>" |
| 76 | else: |
| 77 | instr = circuit.data[instr_index].operation |
| 78 | if instr not in circuit_instructions: |
| 79 | raise CircuitError( |
| 80 | f"ParameterTable instruction not present in circuit: {instr}." |
| 81 | ) |
| 82 | expression = instr.params[param_index] |
| 83 | |
| 84 | if not isinstance(expression, ParameterExpression): |
| 85 | raise CircuitError( |
| 86 | "ParameterTable instruction does not have a " |
| 87 | f"ParameterExpression at param_index {param_index}: {instr}." |
| 88 | ) |
| 89 | |
| 90 | if parameter not in expression.parameters: |
| 91 | raise CircuitError( |
| 92 | "ParameterTable instruction parameters does not match ParameterTable key." |
| 93 | f"\nInstruction parameters: {expression.parameters}" |
| 94 | f"\nParameterTable key: {parameter}." |
| 95 | ) |
| 96 |
no test coverage detected