DynamicCircuit

Enum DynamicCircuit 

Source
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

Source

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

pub fn num_qubits(&self) -> usize

Get the number of qubits

Source

pub fn num_gates(&self) -> usize

Get the number of gates (placeholder implementation)

Source

pub fn depth(&self) -> usize

Get circuit depth (placeholder implementation)

Source

pub fn gates(&self) -> Vec<&dyn GateOp>

Get gates (placeholder implementation)

Trait Implementations§

Source§

impl Clone for DynamicCircuit

Source§

fn clone(&self) -> DynamicCircuit

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for DynamicCircuit

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> DynClone for T
where T: Clone,

Source§

fn __clone_box(&self, _: Private) -> *mut ()

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

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 more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

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 more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<SS, SP> SupersetOf<SS> for SP
where SS: SubsetOf<SP>,

Source§

fn to_subset(&self) -> Option<SS>

The inverse inclusion map: attempts to construct self from the equivalent element of its superset. Read more
Source§

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

Use with care! Same as self.to_subset but without any property checks. Always succeeds.
Source§

fn from_subset(element: &SS) -> SP

The inclusion map: converts self to the equivalent element of its superset.
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V