Skip to main content

quantrs2_ml/torchquantum/gates/two_qubit/special/
tqphaseshift2_traits.rs

1//! # TQPhaseShift2 - Trait Implementations
2//!
3//! This module contains trait implementations for `TQPhaseShift2`.
4//!
5//! ## Implemented Traits
6//!
7//! - `Default`
8//! - `TQModule`
9//! - `TQOperator`
10//!
11//! 🤖 Generated with [SplitRS](https://github.com/cool-japan/splitrs)
12
13use crate::error::{MLError, Result};
14use crate::torchquantum::{
15    CType, NParamsEnum, OpHistoryEntry, TQDevice, TQModule, TQOperator, TQParameter, WiresEnum,
16};
17use scirs2_core::ndarray::{Array2, ArrayD, IxDyn};
18
19use super::types::TQPhaseShift2;
20
21impl Default for TQPhaseShift2 {
22    fn default() -> Self {
23        Self::new(true, true)
24    }
25}
26
27impl TQModule for TQPhaseShift2 {
28    fn forward(&mut self, _qdev: &mut TQDevice) -> Result<()> {
29        Err(MLError::InvalidConfiguration(
30            "Use apply() instead of forward() for operators".to_string(),
31        ))
32    }
33    fn parameters(&self) -> Vec<TQParameter> {
34        self.params.iter().cloned().collect()
35    }
36    fn n_wires(&self) -> Option<usize> {
37        Some(2)
38    }
39    fn set_n_wires(&mut self, _n_wires: usize) {}
40    fn is_static_mode(&self) -> bool {
41        self.static_mode
42    }
43    fn static_on(&mut self) {
44        self.static_mode = true;
45    }
46    fn static_off(&mut self) {
47        self.static_mode = false;
48    }
49    fn name(&self) -> &str {
50        "PhaseShift2"
51    }
52    fn zero_grad(&mut self) {
53        if let Some(ref mut p) = self.params {
54            p.zero_grad();
55        }
56    }
57}
58
59impl TQOperator for TQPhaseShift2 {
60    fn num_wires(&self) -> WiresEnum {
61        WiresEnum::Fixed(2)
62    }
63    fn num_params(&self) -> NParamsEnum {
64        NParamsEnum::Fixed(1)
65    }
66    fn get_matrix(&self, params: Option<&[f64]>) -> Array2<CType> {
67        let phi = params
68            .and_then(|p| p.first().copied())
69            .or_else(|| self.params.as_ref().map(|p| p.data[[0, 0]]))
70            .unwrap_or(0.0);
71        let phi = if self.inverse { -phi } else { phi };
72        let exp_i_phi = CType::from_polar(1.0, phi);
73        Array2::from_shape_vec(
74            (4, 4),
75            vec![
76                CType::new(1.0, 0.0),
77                CType::new(0.0, 0.0),
78                CType::new(0.0, 0.0),
79                CType::new(0.0, 0.0),
80                CType::new(0.0, 0.0),
81                CType::new(1.0, 0.0),
82                CType::new(0.0, 0.0),
83                CType::new(0.0, 0.0),
84                CType::new(0.0, 0.0),
85                CType::new(0.0, 0.0),
86                CType::new(1.0, 0.0),
87                CType::new(0.0, 0.0),
88                CType::new(0.0, 0.0),
89                CType::new(0.0, 0.0),
90                CType::new(0.0, 0.0),
91                exp_i_phi,
92            ],
93        )
94        .unwrap_or_else(|_| Array2::eye(4).mapv(|x| CType::new(x, 0.0)))
95    }
96    fn apply(&mut self, qdev: &mut TQDevice, wires: &[usize]) -> Result<()> {
97        self.apply_with_params(qdev, wires, None)
98    }
99    fn apply_with_params(
100        &mut self,
101        qdev: &mut TQDevice,
102        wires: &[usize],
103        params: Option<&[f64]>,
104    ) -> Result<()> {
105        if wires.len() < 2 {
106            return Err(MLError::InvalidConfiguration(
107                "PhaseShift2 gate requires exactly 2 wires".to_string(),
108            ));
109        }
110        let matrix = self.get_matrix(params);
111        qdev.apply_two_qubit_gate(wires[0], wires[1], &matrix)?;
112        if qdev.record_op {
113            qdev.record_operation(OpHistoryEntry {
114                name: "phaseshift2".to_string(),
115                wires: wires.to_vec(),
116                params: params.map(|p| p.to_vec()),
117                inverse: self.inverse,
118                trainable: self.trainable,
119            });
120        }
121        Ok(())
122    }
123    fn has_params(&self) -> bool {
124        self.has_params
125    }
126    fn trainable(&self) -> bool {
127        self.trainable
128    }
129    fn inverse(&self) -> bool {
130        self.inverse
131    }
132    fn set_inverse(&mut self, inverse: bool) {
133        self.inverse = inverse;
134    }
135}