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