pub struct Tensor {
pub data: Vec<Complex<f64>>,
pub shape: Vec<usize>,
pub indices: Vec<String>,
}
Expand description
Tensor representing a quantum gate or state
Fields§
§data: Vec<Complex<f64>>
Tensor data in row-major order
shape: Vec<usize>
Shape of the tensor (dimensions)
indices: Vec<String>
Labels for each index
Implementations§
Source§impl Tensor
impl Tensor
Sourcepub fn new(
data: Vec<Complex<f64>>,
shape: Vec<usize>,
indices: Vec<String>,
) -> Self
pub fn new( data: Vec<Complex<f64>>, shape: Vec<usize>, indices: Vec<String>, ) -> Self
Create a new tensor
Examples found in repository?
examples/tensor_network_demo.rs (lines 43-47)
25fn demo_basic_tensor_network() -> quantrs2_core::error::QuantRS2Result<()> {
26 println!("--- Basic Tensor Network Construction ---");
27
28 // Create simple tensors
29 let identity = Tensor::identity(2, "in".to_string(), "out".to_string());
30 println!(
31 "Created identity tensor: rank={}, size={}",
32 identity.rank(),
33 identity.size()
34 );
35
36 // Create Hadamard tensor
37 let h_data = vec![
38 C64::new(1.0 / 2.0_f64.sqrt(), 0.0),
39 C64::new(1.0 / 2.0_f64.sqrt(), 0.0),
40 C64::new(1.0 / 2.0_f64.sqrt(), 0.0),
41 C64::new(-1.0 / 2.0_f64.sqrt(), 0.0),
42 ];
43 let h_tensor = Tensor::new(
44 h_data,
45 vec![2, 2],
46 vec!["h_in".to_string(), "h_out".to_string()],
47 );
48
49 // Build tensor network
50 let mut tn = TensorNetwork::new();
51 let id_idx = tn.add_tensor(identity);
52 let h_idx = tn.add_tensor(h_tensor);
53
54 // Connect tensors
55 tn.add_bond(id_idx, "out".to_string(), h_idx, "h_in".to_string())?;
56
57 println!("Built tensor network with {} tensors and {} bonds", 2, 1);
58 println!();
59
60 Ok(())
61}
Sourcepub fn identity(dim: usize, in_label: String, out_label: String) -> Self
pub fn identity(dim: usize, in_label: String, out_label: String) -> Self
Create an identity tensor
Examples found in repository?
examples/tensor_network_demo.rs (line 29)
25fn demo_basic_tensor_network() -> quantrs2_core::error::QuantRS2Result<()> {
26 println!("--- Basic Tensor Network Construction ---");
27
28 // Create simple tensors
29 let identity = Tensor::identity(2, "in".to_string(), "out".to_string());
30 println!(
31 "Created identity tensor: rank={}, size={}",
32 identity.rank(),
33 identity.size()
34 );
35
36 // Create Hadamard tensor
37 let h_data = vec![
38 C64::new(1.0 / 2.0_f64.sqrt(), 0.0),
39 C64::new(1.0 / 2.0_f64.sqrt(), 0.0),
40 C64::new(1.0 / 2.0_f64.sqrt(), 0.0),
41 C64::new(-1.0 / 2.0_f64.sqrt(), 0.0),
42 ];
43 let h_tensor = Tensor::new(
44 h_data,
45 vec![2, 2],
46 vec!["h_in".to_string(), "h_out".to_string()],
47 );
48
49 // Build tensor network
50 let mut tn = TensorNetwork::new();
51 let id_idx = tn.add_tensor(identity);
52 let h_idx = tn.add_tensor(h_tensor);
53
54 // Connect tensors
55 tn.add_bond(id_idx, "out".to_string(), h_idx, "h_in".to_string())?;
56
57 println!("Built tensor network with {} tensors and {} bonds", 2, 1);
58 println!();
59
60 Ok(())
61}
Sourcepub fn rank(&self) -> usize
pub fn rank(&self) -> usize
Get the rank (number of indices)
Examples found in repository?
examples/tensor_network_demo.rs (line 32)
25fn demo_basic_tensor_network() -> quantrs2_core::error::QuantRS2Result<()> {
26 println!("--- Basic Tensor Network Construction ---");
27
28 // Create simple tensors
29 let identity = Tensor::identity(2, "in".to_string(), "out".to_string());
30 println!(
31 "Created identity tensor: rank={}, size={}",
32 identity.rank(),
33 identity.size()
34 );
35
36 // Create Hadamard tensor
37 let h_data = vec![
38 C64::new(1.0 / 2.0_f64.sqrt(), 0.0),
39 C64::new(1.0 / 2.0_f64.sqrt(), 0.0),
40 C64::new(1.0 / 2.0_f64.sqrt(), 0.0),
41 C64::new(-1.0 / 2.0_f64.sqrt(), 0.0),
42 ];
43 let h_tensor = Tensor::new(
44 h_data,
45 vec![2, 2],
46 vec!["h_in".to_string(), "h_out".to_string()],
47 );
48
49 // Build tensor network
50 let mut tn = TensorNetwork::new();
51 let id_idx = tn.add_tensor(identity);
52 let h_idx = tn.add_tensor(h_tensor);
53
54 // Connect tensors
55 tn.add_bond(id_idx, "out".to_string(), h_idx, "h_in".to_string())?;
56
57 println!("Built tensor network with {} tensors and {} bonds", 2, 1);
58 println!();
59
60 Ok(())
61}
62
63fn demo_circuit_compression() -> quantrs2_core::error::QuantRS2Result<()> {
64 println!("--- Circuit Compression ---");
65
66 // Create a circuit with repetitive structure
67 let mut circuit = Circuit::<4>::new();
68
69 // Add many gates
70 for i in 0..3 {
71 circuit.add_gate(Hadamard { target: QubitId(i) })?;
72 }
73
74 for i in 0..3 {
75 circuit.add_gate(CNOT {
76 control: QubitId(i),
77 target: QubitId(i + 1),
78 })?;
79 }
80
81 for i in 0..4 {
82 circuit.add_gate(T { target: QubitId(i) })?;
83 }
84
85 for i in (1..4).rev() {
86 circuit.add_gate(CNOT {
87 control: QubitId(i - 1),
88 target: QubitId(i),
89 })?;
90 }
91
92 println!("Original circuit: {} gates", circuit.num_gates());
93
94 // Compress using tensor networks
95 let compressor = TensorNetworkCompressor::new(16); // max bond dimension
96 let compressed = compressor.compress(&circuit)?;
97
98 println!(
99 "Compression ratio: {:.2}%",
100 compressed.compression_ratio() * 100.0
101 );
102
103 // Check fidelity
104 let fidelity = compressed.fidelity(&circuit)?;
105 println!("Fidelity with original: {:.6}", fidelity);
106
107 println!();
108 Ok(())
109}
110
111fn demo_mps_representation() -> quantrs2_core::error::QuantRS2Result<()> {
112 println!("--- Matrix Product State Representation ---");
113
114 // Create a circuit that generates an interesting entangled state
115 let mut circuit = Circuit::<6>::new();
116
117 // Create W state: (|100000⟩ + |010000⟩ + |001000⟩ + |000100⟩ + |000010⟩ + |000001⟩)/√6
118 circuit.add_gate(Hadamard { target: QubitId(0) })?;
119 circuit.add_gate(RotationZ {
120 target: QubitId(0),
121 theta: std::f64::consts::PI / 3.0,
122 })?;
123
124 for i in 0..5 {
125 circuit.add_gate(CNOT {
126 control: QubitId(i),
127 target: QubitId(i + 1),
128 })?;
129 }
130
131 println!("Created circuit for W state preparation");
132
133 // Convert to MPS
134 let mps = MatrixProductState::from_circuit(&circuit)?;
135 println!("Converted to MPS representation");
136
137 // Compress with different bond dimensions
138 let bond_dims = vec![2, 4, 8, 16];
139
140 for &max_bond in &bond_dims {
141 let mut mps_copy = MatrixProductState::from_circuit(&circuit)?;
142 mps_copy.compress(max_bond, 1e-10)?;
143
144 // In a real implementation, would calculate actual compression metrics
145 println!("Max bond dimension {}: compression successful", max_bond);
146 }
147
148 println!();
149 Ok(())
150}
151
152fn demo_compression_methods() -> quantrs2_core::error::QuantRS2Result<()> {
153 println!("--- Different Compression Methods ---");
154
155 let mut circuit = Circuit::<5>::new();
156
157 // Build a deep circuit
158 for _ in 0..5 {
159 for i in 0..5 {
160 circuit.add_gate(Hadamard { target: QubitId(i) })?;
161 }
162 for i in 0..4 {
163 circuit.add_gate(CNOT {
164 control: QubitId(i),
165 target: QubitId(i + 1),
166 })?;
167 }
168 }
169
170 println!("Built deep circuit with {} gates", circuit.num_gates());
171
172 // Test different compression methods
173 let methods = vec![
174 CompressionMethod::SVD,
175 CompressionMethod::DMRG,
176 CompressionMethod::TEBD,
177 ];
178
179 for method in methods {
180 let compressor = TensorNetworkCompressor::new(32).with_method(method.clone());
181
182 let compressed = compressor.compress(&circuit)?;
183
184 println!("\n{:?} compression:", method);
185 println!(
186 " Compression ratio: {:.2}%",
187 compressed.compression_ratio() * 100.0
188 );
189
190 // Try to decompress
191 let decompressed = compressed.decompress()?;
192 println!(" Decompressed to {} gates", decompressed.num_gates());
193 }
194
195 println!();
196 Ok(())
197}
198
199fn demo_tensor_contraction() -> quantrs2_core::error::QuantRS2Result<()> {
200 println!("--- Tensor Contraction Optimization ---");
201
202 // Create a circuit with specific structure
203 let mut circuit = Circuit::<4>::new();
204
205 // Layer 1: Single-qubit gates
206 for i in 0..4 {
207 circuit.add_gate(Hadamard { target: QubitId(i) })?;
208 }
209
210 // Layer 2: Entangling gates
211 circuit.add_gate(CNOT {
212 control: QubitId(0),
213 target: QubitId(1),
214 })?;
215 circuit.add_gate(CNOT {
216 control: QubitId(2),
217 target: QubitId(3),
218 })?;
219
220 // Layer 3: Cross entangling
221 circuit.add_gate(CNOT {
222 control: QubitId(1),
223 target: QubitId(2),
224 })?;
225
226 // Convert to tensor network
227 let converter = CircuitToTensorNetwork::<4>::new()
228 .with_max_bond_dim(8)
229 .with_tolerance(1e-12);
230
231 let tn = converter.convert(&circuit)?;
232
233 println!("Converted circuit to tensor network");
234 println!("Network has {} tensors", circuit.num_gates());
235
236 // Contract the network
237 let result = tn.contract_all()?;
238 println!("Contracted to single tensor of rank {}", result.rank());
239
240 println!();
241 Ok(())
242}
Sourcepub fn size(&self) -> usize
pub fn size(&self) -> usize
Get the total number of elements
Examples found in repository?
examples/tensor_network_demo.rs (line 33)
25fn demo_basic_tensor_network() -> quantrs2_core::error::QuantRS2Result<()> {
26 println!("--- Basic Tensor Network Construction ---");
27
28 // Create simple tensors
29 let identity = Tensor::identity(2, "in".to_string(), "out".to_string());
30 println!(
31 "Created identity tensor: rank={}, size={}",
32 identity.rank(),
33 identity.size()
34 );
35
36 // Create Hadamard tensor
37 let h_data = vec![
38 C64::new(1.0 / 2.0_f64.sqrt(), 0.0),
39 C64::new(1.0 / 2.0_f64.sqrt(), 0.0),
40 C64::new(1.0 / 2.0_f64.sqrt(), 0.0),
41 C64::new(-1.0 / 2.0_f64.sqrt(), 0.0),
42 ];
43 let h_tensor = Tensor::new(
44 h_data,
45 vec![2, 2],
46 vec!["h_in".to_string(), "h_out".to_string()],
47 );
48
49 // Build tensor network
50 let mut tn = TensorNetwork::new();
51 let id_idx = tn.add_tensor(identity);
52 let h_idx = tn.add_tensor(h_tensor);
53
54 // Connect tensors
55 tn.add_bond(id_idx, "out".to_string(), h_idx, "h_in".to_string())?;
56
57 println!("Built tensor network with {} tensors and {} bonds", 2, 1);
58 println!();
59
60 Ok(())
61}
Trait Implementations§
Auto Trait Implementations§
impl Freeze for Tensor
impl RefUnwindSafe for Tensor
impl Send for Tensor
impl Sync for Tensor
impl Unpin for Tensor
impl UnwindSafe for Tensor
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self>
fn into_either(self, into_left: bool) -> Either<Self, Self>
Converts
self
into a Left
variant of Either<Self, Self>
if into_left
is true
.
Converts self
into a Right
variant of Either<Self, Self>
otherwise. Read moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
Converts
self
into a Left
variant of Either<Self, Self>
if into_left(&self)
returns true
.
Converts self
into a Right
variant of Either<Self, Self>
otherwise. Read moreSource§impl<T> Pointable for T
impl<T> Pointable for T
Source§impl<SS, SP> SupersetOf<SS> for SPwhere
SS: SubsetOf<SP>,
impl<SS, SP> SupersetOf<SS> for SPwhere
SS: SubsetOf<SP>,
Source§fn to_subset(&self) -> Option<SS>
fn to_subset(&self) -> Option<SS>
The inverse inclusion map: attempts to construct
self
from the equivalent element of its
superset. Read moreSource§fn is_in_subset(&self) -> bool
fn is_in_subset(&self) -> bool
Checks if
self
is actually part of its subset T
(and can be converted to it).Source§fn to_subset_unchecked(&self) -> SS
fn to_subset_unchecked(&self) -> SS
Use with care! Same as
self.to_subset
but without any property checks. Always succeeds.Source§fn from_subset(element: &SS) -> SP
fn from_subset(element: &SS) -> SP
The inclusion map: converts
self
to the equivalent element of its superset.