pub enum DynamicCircuit {
Circuit1(Circuit<1>),
Circuit2(Circuit<2>),
Circuit4(Circuit<4>),
Circuit8(Circuit<8>),
Circuit16(Circuit<16>),
Circuit32(Circuit<32>),
Circuit64(Circuit<64>),
}Expand description
Dynamic circuit representation for trait objects
Variants§
Circuit1(Circuit<1>)
Circuit2(Circuit<2>)
Circuit4(Circuit<4>)
Circuit8(Circuit<8>)
Circuit16(Circuit<16>)
Circuit32(Circuit<32>)
Circuit64(Circuit<64>)
Implementations§
Source§impl DynamicCircuit
impl DynamicCircuit
Sourcepub fn from_circuit<const N: usize>(circuit: Circuit<N>) -> Result<Self>
pub fn from_circuit<const N: usize>(circuit: Circuit<N>) -> Result<Self>
Create from a generic circuit
Examples found in repository?
examples/tensorflow_quantum_demo.rs (line 181)
13fn main() -> Result<()> {
14 println!("=== TensorFlow Quantum Compatibility Demo ===\n");
15
16 // Step 1: Create TFQ-style quantum circuits
17 println!("1. Creating TensorFlow Quantum style circuits...");
18
19 let (circuits, circuit_symbols) = create_tfq_circuits()?;
20 println!(
21 " - Created {} parameterized quantum circuits",
22 circuits.len()
23 );
24 println!(" - Circuit symbols: {:?}", circuit_symbols);
25
26 // Step 2: Build TFQ-style model with PQC layers
27 println!("\n2. Building TFQ-compatible model...");
28
29 let mut model = TFQModel::new(vec![4, 1]); // input_shape: [batch_size, features]
30
31 // Add quantum circuit layer (equivalent to tfq.layers.PQC)
32 // Note: QuantumCircuitLayer does not implement TFQLayer in current API
33 // model.add_layer(Box::new(QuantumCircuitLayer::new(
34 // circuits[0].clone(),
35 // circuit_symbols.clone(),
36 // Observable::PauliZ(vec![0]),
37 // Arc::new(StatevectorBackend::new(8))
38 // )));
39 println!(" - Quantum circuit layer placeholder added");
40
41 // Add classical preprocessing layer
42 // Note: TFQDenseLayer not implemented in current API
43 // model.add_layer(Box::new(TFQDenseLayer::new(
44 // 4, 8,
45 // ActivationFunction::ReLU,
46 // ParameterInitStrategy::XavierUniform
47 // )?));
48
49 // Add PQC layer with different observable
50 // Note: PQCLayer not implemented in current API
51 // model.add_layer(Box::new(PQCLayer::new(
52 // circuits[1].clone(),
53 // Observable::PauliZ(vec![1]),
54 // RegularizationType::L2(0.01)
55 // )?));
56
57 // Add quantum convolutional layer
58 // Note: QuantumConvolutionalLayer not implemented in current API
59 // model.add_layer(Box::new(QuantumConvolutionalLayer::new(
60 // circuits[2].clone(),
61 // (2, 2), // kernel_size
62 // PaddingType::Valid,
63 // 2 // stride
64 // )?));
65
66 // Final output layer
67 // Note: TFQDenseLayer not implemented in current API
68 // model.add_layer(Box::new(TFQDenseLayer::new(
69 // 8, 2,
70 // ActivationFunction::Softmax,
71 // ParameterInitStrategy::HeNormal
72 // )?));
73
74 println!(" Model architecture:");
75 // model.summary(); // Not implemented in current API
76
77 // Step 3: Create TFQ-style quantum dataset
78 println!("\n3. Creating TensorFlow Quantum dataset...");
79
80 let quantum_dataset = create_tfq_quantum_dataset()?;
81 // println!(" - Dataset size: {}", quantum_dataset.size());
82 // println!(" - Data encoding: {:?}", quantum_dataset.encoding_type());
83 // println!(" - Batch size: {}", quantum_dataset.batch_size());
84 println!(" - Quantum dataset created successfully");
85
86 // Step 4: Configure TFQ-style training
87 println!("\n4. Configuring TFQ training setup...");
88
89 let optimizer = TFQOptimizer::Adam {
90 learning_rate: 0.001,
91 beta1: 0.9,
92 beta2: 0.999,
93 epsilon: 1e-7,
94 };
95
96 let loss_function = TFQLossFunction::CategoricalCrossentropy;
97
98 model.compile()?;
99
100 println!(" - Optimizer: Adam");
101 println!(" - Loss: Sparse Categorical Crossentropy");
102 println!(" - Metrics: Accuracy, Precision, Recall");
103
104 // Step 5: Train with TFQ-style fit method
105 println!("\n5. Training with TensorFlow Quantum style...");
106
107 // Note: fit method not fully implemented in current API
108 // let history = model.fit(
109 // &quantum_dataset,
110 // 15, // epochs
111 // 0.2, // validation_split
112 // 1, // verbose
113 // vec![
114 // Box::new(EarlyStoppingCallback::new(3, "val_loss")), // patience, monitor
115 // Box::new(ReduceLROnPlateauCallback::new(0.5, 2)), // factor, patience
116 // ]
117 // )?;
118 println!(" Training setup configured (fit method placeholder)");
119
120 // println!(" Training completed!");
121 // println!(" - Final training accuracy: {:.3}", history.final_metric("accuracy"));
122 // println!(" - Final validation accuracy: {:.3}", history.final_metric("val_accuracy"));
123 // println!(" - Best epoch: {}", history.best_epoch());
124 println!(" Training placeholder completed");
125
126 // Step 6: Evaluate model performance
127 println!("\n6. Model evaluation...");
128
129 let test_dataset = create_tfq_test_dataset()?;
130 // let evaluation_results = model.evaluate(&test_dataset, 1)?; // verbose
131 //
132 // println!(" Test Results:");
133 // for (metric, value) in evaluation_results.iter() {
134 // println!(" - {}: {:.4}", metric, value);
135 // }
136 println!(" Test dataset created successfully");
137
138 // Step 7: Quantum circuit analysis
139 println!("\n7. Quantum circuit analysis...");
140
141 // let circuit_analysis = model.analyze_quantum_circuits()?;
142 // println!(" Circuit Properties:");
143 // println!(" - Total quantum parameters: {}", circuit_analysis.total_quantum_params);
144 // println!(" - Circuit depth: {}", circuit_analysis.max_circuit_depth);
145 // println!(" - Gate types used: {:?}", circuit_analysis.gate_types);
146 // println!(" - Entangling gates: {}", circuit_analysis.entangling_gate_count);
147 println!(" Circuit analysis placeholder completed");
148
149 // Step 8: Parameter shift gradients (TFQ-style)
150 println!("\n8. Computing parameter shift gradients...");
151
152 // let sample_input = quantum_dataset.get_batch(0)?;
153 // let gradients = model.compute_parameter_shift_gradients(&sample_input)?;
154 println!(" Parameter shift gradients placeholder");
155
156 // println!(" Gradient Analysis:");
157 // println!(" - Quantum gradients computed: {}", gradients.quantum_gradients.len());
158 // println!(" - Classical gradients computed: {}", gradients.classical_gradients.len());
159 // println!(" - Max quantum gradient: {:.6}",
160 // gradients.quantum_gradients.iter().fold(0.0f64, |a, &b| a.max(b.abs())));
161 // println!(" - Gradient variance: {:.6}",
162 // compute_gradient_variance(&gradients.quantum_gradients));
163 println!(" Gradient analysis placeholder completed");
164
165 // Step 9: Quantum expectation values
166 println!("\n9. Computing quantum expectation values...");
167
168 let observables = vec![Observable::PauliZ(vec![0]), Observable::PauliZ(vec![1])];
169
170 // let expectation_values = model.compute_expectation_values(&sample_input, &observables)?;
171 // println!(" Expectation Values:");
172 // for (i, (obs, val)) in observables.iter().zip(expectation_values.iter()).enumerate() {
173 // println!(" - Observable {}: {:.4}", i, val);
174 // }
175 println!(" Expectation values placeholder completed");
176
177 // Step 10: TFQ utils demonstrations
178 println!("\n10. TensorFlow Quantum utilities...");
179
180 // Circuit conversion
181 let dynamic_circuit = DynamicCircuit::from_circuit(circuits[0].clone())?;
182 let tfq_format_circuit = tfq_utils::circuit_to_tfq_format(&dynamic_circuit)?;
183 println!(" - Converted circuit to TFQ format (placeholder)");
184
185 // Batch circuit execution
186 // let batch_circuits = vec![circuits[0].clone(), circuits[1].clone()];
187 // let batch_params = Array2::from_shape_fn((2, 4), |(i, j)| (i + j) as f64 * 0.1);
188 // let batch_results = tfq_utils::batch_execute_circuits(&batch_circuits, &batch_params, &observables, &backend)?;
189 // println!(" - Batch execution results shape: {:?}", batch_results.dim());
190 println!(" - Batch execution placeholder completed");
191
192 // Data encoding utilities
193 let classical_data = Array2::from_shape_fn((10, 4), |(i, j)| (i + j) as f64 * 0.2);
194 // let encoded_circuits = tfq_utils::encode_data_to_circuits(
195 // &classical_data,
196 // DataEncodingType::Angle
197 // )?;
198 let encoded_circuits = vec![tfq_utils::create_data_encoding_circuit(
199 4,
200 DataEncodingType::Angle,
201 )?];
202 println!(
203 " - Encoded {} data points to quantum circuits",
204 encoded_circuits.len()
205 );
206
207 // Step 11: Compare with TensorFlow classical model
208 println!("\n11. Comparing with TensorFlow classical equivalent...");
209
210 let classical_model = create_tensorflow_classical_model()?;
211 // let classical_accuracy = train_classical_tensorflow_model(classical_model, &quantum_dataset)?;
212 //
213 // let quantum_accuracy = evaluation_results.get("accuracy").unwrap_or(&0.0);
214 // println!(" - Quantum TFQ model accuracy: {:.3}", quantum_accuracy);
215 // println!(" - Classical TF model accuracy: {:.3}", classical_accuracy);
216 // println!(" - Quantum advantage: {:.3}", quantum_accuracy - classical_accuracy);
217 println!(" - Classical comparison placeholder completed");
218
219 // Step 12: Model export (TFQ format)
220 println!("\n12. Exporting model in TFQ format...");
221
222 // model.save_tfq_format("quantum_model_tfq.pb")?;
223 // println!(" - Model exported to: quantum_model_tfq.pb");
224 //
225 // // Export to TensorFlow SavedModel format
226 // model.export_savedmodel("quantum_model_savedmodel/")?;
227 // println!(" - SavedModel exported to: quantum_model_savedmodel/");
228 println!(" - Model export placeholder completed");
229
230 // Step 13: Advanced TFQ features
231 println!("\n13. Advanced TensorFlow Quantum features...");
232
233 // Quantum data augmentation
234 // let augmented_dataset = quantum_dataset.augment_with_noise(0.05)?;
235 // println!(" - Created augmented dataset with noise level 0.05");
236 //
237 // // Circuit optimization for hardware
238 // let optimized_circuits = tfq_utils::optimize_circuits_for_hardware(
239 // &circuits,
240 // HardwareType::IonQ
241 // )?;
242 // println!(" - Optimized {} circuits for IonQ hardware", optimized_circuits.len());
243 //
244 // // Barren plateau analysis
245 // let plateau_analysis = analyze_barren_plateaus(&model, &quantum_dataset)?;
246 // println!(" - Barren plateau risk: {:.3}", plateau_analysis.risk_score);
247 // println!(" - Recommended mitigation: {}", plateau_analysis.mitigation_strategy);
248 println!(" - Advanced features placeholder completed");
249
250 println!("\n=== TensorFlow Quantum Demo Complete ===");
251
252 Ok(())
253}Sourcepub fn num_qubits(&self) -> usize
pub fn num_qubits(&self) -> usize
Get the number of qubits
Trait Implementations§
Source§impl Clone for DynamicCircuit
impl Clone for DynamicCircuit
Source§fn clone(&self) -> DynamicCircuit
fn clone(&self) -> DynamicCircuit
Returns a duplicate of the value. Read more
1.0.0 · Source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
Performs copy-assignment from
source. Read moreAuto Trait Implementations§
impl Freeze for DynamicCircuit
impl !RefUnwindSafe for DynamicCircuit
impl Send for DynamicCircuit
impl Sync for DynamicCircuit
impl Unpin for DynamicCircuit
impl !UnwindSafe for DynamicCircuit
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.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.