quil_rs/instruction/
calibration.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
use crate::{
    instruction::{
        write_expression_parameter_string, write_instruction_block, Expression, GateModifier,
        Instruction, Qubit,
    },
    quil::{Quil, INDENT},
    validation::identifier::{validate_identifier, IdentifierValidationError},
};

use super::{write_qubit_parameters, Gate};

pub trait CalibrationSignature {
    type Signature<'a>
    where
        Self: 'a;

    fn signature(&self) -> Self::Signature<'_>;
    fn has_signature(&self, signature: &Self::Signature<'_>) -> bool;
}

#[derive(Clone, Debug, Default, PartialEq)]
pub struct Calibration {
    pub identifier: CalibrationIdentifier,
    pub instructions: Vec<Instruction>,
}

impl Calibration {
    /// Builds a new calibration definition.
    pub fn new(
        identifier: CalibrationIdentifier,
        instructions: Vec<Instruction>,
    ) -> Result<Self, IdentifierValidationError> {
        Ok(Self {
            identifier,
            instructions,
        })
    }
}

impl CalibrationSignature for Calibration {
    type Signature<'a> = (&'a str, &'a [Expression], &'a [Qubit]);

    fn signature(&self) -> Self::Signature<'_> {
        self.identifier.signature()
    }

    fn has_signature(&self, signature: &Self::Signature<'_>) -> bool {
        self.identifier.has_signature(signature)
    }
}

impl Quil for Calibration {
    fn write(
        &self,
        f: &mut impl std::fmt::Write,
        fall_back_to_debug: bool,
    ) -> crate::quil::ToQuilResult<()> {
        self.identifier.write(f, fall_back_to_debug)?;
        write!(f, ":")?;
        for instruction in &self.instructions {
            write!(f, "\n{INDENT}")?;
            instruction.write(f, fall_back_to_debug)?;
        }
        Ok(())
    }
}

/// Unique identifier for a calibration definition within a program
#[derive(Clone, Debug, Default, PartialEq)]
pub struct CalibrationIdentifier {
    /// The modifiers applied to the gate
    pub modifiers: Vec<GateModifier>,

    /// The name of the gate
    pub name: String,

    /// The parameters of the gate - these are the variables in the calibration definition
    pub parameters: Vec<Expression>,

    /// The qubits on which the gate is applied
    pub qubits: Vec<Qubit>,
}

impl CalibrationIdentifier {
    /// Builds a new calibration identifier.
    ///
    /// # Errors
    ///
    /// Returns an error if the given name isn't a valid Quil identifier.
    pub fn new(
        name: String,
        modifiers: Vec<GateModifier>,
        parameters: Vec<Expression>,
        qubits: Vec<Qubit>,
    ) -> Result<Self, IdentifierValidationError> {
        validate_identifier(name.as_str())?;
        Ok(Self {
            modifiers,
            name,
            parameters,
            qubits,
        })
    }

    pub fn matches(&self, gate: &Gate) -> bool {
        // Filter out non-matching calibrations: check rules 1-4
        if self.name != gate.name
            || self.modifiers != gate.modifiers
            || self.parameters.len() != gate.parameters.len()
            || self.qubits.len() != gate.qubits.len()
        {
            return false;
        }

        let fixed_qubits_match = self
            .qubits
            .iter()
            .enumerate()
            .all(|(calibration_index, _)| {
                match (
                    &self.qubits[calibration_index],
                    &gate.qubits[calibration_index],
                ) {
                    // Placeholders never match
                    (Qubit::Placeholder(_), _) | (_, Qubit::Placeholder(_)) => false,
                    // If they're both fixed, test if they're fixed to the same qubit
                    (Qubit::Fixed(calibration_fixed_qubit), Qubit::Fixed(gate_fixed_qubit)) => {
                        calibration_fixed_qubit == gate_fixed_qubit
                    }
                    // If the calibration is variable, it matches any fixed qubit
                    (Qubit::Variable(_), _) => true,
                    // If the calibration is fixed, but the gate's qubit is variable, it's not a match
                    (Qubit::Fixed(_), _) => false,
                }
            });
        if !fixed_qubits_match {
            return false;
        }

        let fixed_parameters_match =
            self.parameters
                .iter()
                .enumerate()
                .all(|(calibration_index, _)| {
                    let calibration_parameters =
                        self.parameters[calibration_index].clone().into_simplified();
                    let gate_parameters =
                        gate.parameters[calibration_index].clone().into_simplified();
                    match (calibration_parameters, gate_parameters) {
                        // If the calibration is variable, it matches any fixed qubit
                        (Expression::Variable(_), _) => true,
                        // If the calibration is fixed, but the gate's qubit is variable, it's not a match
                        (calib, gate) => calib == gate,
                    }
                });
        fixed_parameters_match
    }
}

impl CalibrationSignature for CalibrationIdentifier {
    type Signature<'a> = (&'a str, &'a [Expression], &'a [Qubit]);

    fn signature(&self) -> Self::Signature<'_> {
        (
            self.name.as_str(),
            self.parameters.as_slice(),
            self.qubits.as_slice(),
        )
    }

    fn has_signature(&self, signature: &Self::Signature<'_>) -> bool {
        let (name, parameters, qubits) = signature;
        self.name == *name && self.parameters == *parameters && self.qubits == *qubits
    }
}

impl Quil for CalibrationIdentifier {
    fn write(
        &self,
        f: &mut impl std::fmt::Write,
        fall_back_to_debug: bool,
    ) -> crate::quil::ToQuilResult<()> {
        write!(f, "DEFCAL {}", self.name)?;
        write_expression_parameter_string(f, fall_back_to_debug, &self.parameters)?;
        write_qubit_parameters(f, fall_back_to_debug, &self.qubits)?;
        Ok(())
    }
}

#[derive(Clone, Debug, PartialEq)]
pub struct MeasureCalibrationDefinition {
    pub identifier: MeasureCalibrationIdentifier,
    pub instructions: Vec<Instruction>,
}

impl MeasureCalibrationDefinition {
    pub fn new(identifier: MeasureCalibrationIdentifier, instructions: Vec<Instruction>) -> Self {
        Self {
            identifier,
            instructions,
        }
    }
}

impl CalibrationSignature for MeasureCalibrationDefinition {
    type Signature<'a> = (Option<&'a Qubit>, &'a str);

    fn signature(&self) -> Self::Signature<'_> {
        self.identifier.signature()
    }

    fn has_signature(&self, signature: &Self::Signature<'_>) -> bool {
        self.identifier.has_signature(signature)
    }
}

impl Quil for MeasureCalibrationDefinition {
    fn write(
        &self,
        f: &mut impl std::fmt::Write,
        fall_back_to_debug: bool,
    ) -> crate::quil::ToQuilResult<()> {
        self.identifier.write(f, fall_back_to_debug)?;
        writeln!(f, ":")?;

        write_instruction_block(f, fall_back_to_debug, &self.instructions)?;
        writeln!(f)?;
        Ok(())
    }
}

/// A unique identifier for a measurement calibration definition within a program
#[derive(Clone, Debug, Default, PartialEq)]
pub struct MeasureCalibrationIdentifier {
    /// The qubit which is the target of measurement, if any
    pub qubit: Option<Qubit>,

    /// The memory region name to which the measurement result is written
    pub parameter: String,
}

impl MeasureCalibrationIdentifier {
    pub fn new(qubit: Option<Qubit>, parameter: String) -> Self {
        Self { qubit, parameter }
    }
}

impl CalibrationSignature for MeasureCalibrationIdentifier {
    type Signature<'a> = (Option<&'a Qubit>, &'a str);

    fn signature(&self) -> Self::Signature<'_> {
        (self.qubit.as_ref(), self.parameter.as_str())
    }

    fn has_signature(&self, signature: &Self::Signature<'_>) -> bool {
        let (qubit, parameter) = signature;
        self.qubit.as_ref() == *qubit && self.parameter == *parameter
    }
}

impl Quil for MeasureCalibrationIdentifier {
    fn write(
        &self,
        f: &mut impl std::fmt::Write,
        fall_back_to_debug: bool,
    ) -> crate::quil::ToQuilResult<()> {
        write!(f, "DEFCAL MEASURE")?;
        if let Some(qubit) = &self.qubit {
            write!(f, " ")?;
            qubit.write(f, fall_back_to_debug)?;
        }
        write!(f, " {}", self.parameter,)?;
        Ok(())
    }
}

#[cfg(test)]
mod test_measure_calibration_definition {
    use super::MeasureCalibrationDefinition;
    use crate::expression::Expression;
    use crate::instruction::calibration::MeasureCalibrationIdentifier;
    use crate::instruction::{Gate, Instruction, Qubit};
    use crate::quil::Quil;
    use insta::assert_snapshot;
    use rstest::rstest;

    #[rstest]
    #[case(
        "With Fixed Qubit",
        MeasureCalibrationDefinition {
            identifier: MeasureCalibrationIdentifier {
                qubit: Some(Qubit::Fixed(0)),
                parameter: "theta".to_string(),
            },
            instructions: vec![Instruction::Gate(Gate {
                name: "X".to_string(),
                parameters: vec![Expression::Variable("theta".to_string())],
                qubits: vec![Qubit::Fixed(0)],
                modifiers: vec![],

            })]},
    )]
    #[case(
        "With Variable Qubit",
        MeasureCalibrationDefinition {
            identifier: MeasureCalibrationIdentifier {
                qubit: Some(Qubit::Variable("q".to_string())),
                parameter: "theta".to_string(),
            },
            instructions: vec![Instruction::Gate(Gate {
                name: "X".to_string(),
                parameters: vec![Expression::Variable("theta".to_string())],
                qubits: vec![Qubit::Variable("q".to_string())],
                modifiers: vec![],
            })]},
    )]
    fn test_display(
        #[case] description: &str,
        #[case] measure_cal_def: MeasureCalibrationDefinition,
    ) {
        insta::with_settings!({
            snapshot_suffix => description,
        }, {
            assert_snapshot!(measure_cal_def.to_quil_or_debug())
        })
    }
}