MLCircuitOptimizer

Struct MLCircuitOptimizer 

Source
pub struct MLCircuitOptimizer { /* private fields */ }
Expand description

ML-based optimizer

Implementations§

Source§

impl MLCircuitOptimizer

Source

pub fn new(strategy: MLStrategy) -> Self

Create a new ML optimizer

Examples found in repository?
examples/advanced_features_demo.rs (line 62)
18fn main() -> Result<(), Box<dyn std::error::Error>> {
19    println!("=== QuantRS2 Circuit Advanced Features Demo ===\n");
20
21    // 1. Basic circuit creation
22    println!("1. Creating a basic quantum circuit:");
23    let mut circuit = Circuit::<3>::new();
24    circuit.add_gate(Hadamard { target: QubitId(0) })?;
25    circuit.add_gate(CNOT {
26        control: QubitId(0),
27        target: QubitId(1),
28    })?;
29    circuit.add_gate(CNOT {
30        control: QubitId(1),
31        target: QubitId(2),
32    })?;
33    println!("   Circuit with {} gates created", circuit.gates().len());
34
35    // 2. ZX-calculus optimization
36    println!("\n2. ZX-calculus optimization:");
37    let zx_optimizer = ZXOptimizer::new();
38    let zx_diagram = zx_optimizer.circuit_to_zx(&circuit)?;
39    println!(
40        "   ZX diagram with {} nodes created",
41        zx_diagram.nodes.len()
42    );
43
44    // 3. SciRS2 graph analysis
45    println!("\n3. SciRS2 graph analysis:");
46    let mut analyzer = SciRS2CircuitAnalyzer::new();
47    let analysis = analyzer.analyze_circuit(&circuit)?;
48    println!(
49        "   Graph metrics: {} nodes, {} edges",
50        analysis.metrics.num_nodes, analysis.metrics.num_edges
51    );
52    println!("   Communities detected: {}", analysis.communities.len());
53
54    // 4. ML-based optimization
55    println!("\n4. ML-based circuit optimization:");
56    let ml_strategy = MLStrategy::NeuralNetwork {
57        architecture: vec![32, 16, 8],
58        learning_rate: 0.001,
59        epochs: 10,
60        batch_size: 16,
61    };
62    let mut ml_optimizer = MLCircuitOptimizer::new(ml_strategy);
63    let ml_result = ml_optimizer.optimize(&circuit)?;
64    println!(
65        "   ML optimization completed in {:?}",
66        ml_result.optimization_time
67    );
68
69    // 5. Fault-tolerant compilation
70    println!("\n5. Fault-tolerant compilation:");
71    let code = QECCode::SteaneCode;
72    let ft_compiler = FaultTolerantCompiler::new(code);
73    let ft_circuit = ft_compiler.compile(&circuit)?;
74    println!(
75        "   Fault-tolerant circuit: {} physical qubits, {} magic states",
76        ft_circuit.physical_qubit_count, ft_circuit.magic_state_requirements
77    );
78
79    // 6. Photonic circuit conversion
80    println!("\n6. Photonic quantum computation:");
81    let photonic_circuit = PhotonicConverter::quantum_to_photonic(&circuit)?;
82    println!(
83        "   Photonic circuit: {} modes, {} gates",
84        photonic_circuit.num_modes,
85        photonic_circuit.gates.len()
86    );
87
88    // 7. Topological quantum computation
89    println!("\n7. Topological quantum computation:");
90    let anyon_model = AnyonModel::fibonacci();
91    let topo_compiler = TopologicalCompiler::new(anyon_model);
92    let topo_circuit = topo_compiler.compile_quantum_circuit(&circuit)?;
93    println!(
94        "   Topological circuit: {} anyons, {} braiding operations",
95        topo_circuit.anyon_count(),
96        topo_circuit.total_braiding_operations()
97    );
98
99    // 8. Circuit-to-simulator interface
100    println!("\n8. Circuit compilation for simulators:");
101    let mut compiler = CircuitCompiler::new();
102    compiler.add_target(CompilationTarget {
103        backend: SimulatorBackend::StateVector {
104            max_qubits: 20,
105            use_gpu: false,
106            memory_optimization: MemoryOptimization::Basic,
107        },
108        optimization_level: SimulatorOptimizationLevel::Basic,
109        instruction_set: InstructionSet::Universal,
110        parallel_execution: true,
111        batch_size: Some(10),
112    });
113
114    let compiled = compiler.compile(&circuit)?;
115    println!(
116        "   Compiled circuit: {} instructions, estimated memory: {} bytes",
117        compiled.instructions.len(),
118        compiled.resources.memory_bytes
119    );
120
121    // 9. Mid-circuit measurements and feed-forward
122    println!("\n9. Mid-circuit measurements and feed-forward:");
123    let mut measurement_circuit = MeasurementCircuit::<2>::new();
124    measurement_circuit.add_gate(Box::new(Hadamard { target: QubitId(0) }))?;
125    let bit = measurement_circuit.measure(QubitId(0))?;
126
127    let condition = ClassicalCondition::equals(
128        ClassicalValue::Integer(bit as u64),
129        ClassicalValue::Integer(1),
130    );
131    measurement_circuit.add_conditional(condition, Box::new(PauliX { target: QubitId(1) }))?;
132    println!(
133        "   Measurement circuit with {} operations created",
134        measurement_circuit.num_operations()
135    );
136
137    // 10. Cross-talk aware scheduling
138    println!("\n10. Cross-talk aware scheduling:");
139    let crosstalk_model = CrosstalkModel::uniform(3, 0.05);
140    let scheduler = CrosstalkScheduler::new(crosstalk_model);
141    let schedule = scheduler.schedule(&circuit)?;
142    println!(
143        "   Scheduled into {} time slices, total crosstalk: {:.3}",
144        schedule.time_slices.len(),
145        schedule.total_crosstalk
146    );
147
148    println!("\n=== Demo completed successfully! ===");
149    Ok(())
150}
Source

pub fn with_config(strategy: MLStrategy, config: MLOptimizerConfig) -> Self

Create optimizer with custom configuration

Source

pub fn optimize<const N: usize>( &mut self, circuit: &Circuit<N>, ) -> QuantRS2Result<MLOptimizationResult<N>>

Optimize a circuit using ML

Examples found in repository?
examples/advanced_features_demo.rs (line 63)
18fn main() -> Result<(), Box<dyn std::error::Error>> {
19    println!("=== QuantRS2 Circuit Advanced Features Demo ===\n");
20
21    // 1. Basic circuit creation
22    println!("1. Creating a basic quantum circuit:");
23    let mut circuit = Circuit::<3>::new();
24    circuit.add_gate(Hadamard { target: QubitId(0) })?;
25    circuit.add_gate(CNOT {
26        control: QubitId(0),
27        target: QubitId(1),
28    })?;
29    circuit.add_gate(CNOT {
30        control: QubitId(1),
31        target: QubitId(2),
32    })?;
33    println!("   Circuit with {} gates created", circuit.gates().len());
34
35    // 2. ZX-calculus optimization
36    println!("\n2. ZX-calculus optimization:");
37    let zx_optimizer = ZXOptimizer::new();
38    let zx_diagram = zx_optimizer.circuit_to_zx(&circuit)?;
39    println!(
40        "   ZX diagram with {} nodes created",
41        zx_diagram.nodes.len()
42    );
43
44    // 3. SciRS2 graph analysis
45    println!("\n3. SciRS2 graph analysis:");
46    let mut analyzer = SciRS2CircuitAnalyzer::new();
47    let analysis = analyzer.analyze_circuit(&circuit)?;
48    println!(
49        "   Graph metrics: {} nodes, {} edges",
50        analysis.metrics.num_nodes, analysis.metrics.num_edges
51    );
52    println!("   Communities detected: {}", analysis.communities.len());
53
54    // 4. ML-based optimization
55    println!("\n4. ML-based circuit optimization:");
56    let ml_strategy = MLStrategy::NeuralNetwork {
57        architecture: vec![32, 16, 8],
58        learning_rate: 0.001,
59        epochs: 10,
60        batch_size: 16,
61    };
62    let mut ml_optimizer = MLCircuitOptimizer::new(ml_strategy);
63    let ml_result = ml_optimizer.optimize(&circuit)?;
64    println!(
65        "   ML optimization completed in {:?}",
66        ml_result.optimization_time
67    );
68
69    // 5. Fault-tolerant compilation
70    println!("\n5. Fault-tolerant compilation:");
71    let code = QECCode::SteaneCode;
72    let ft_compiler = FaultTolerantCompiler::new(code);
73    let ft_circuit = ft_compiler.compile(&circuit)?;
74    println!(
75        "   Fault-tolerant circuit: {} physical qubits, {} magic states",
76        ft_circuit.physical_qubit_count, ft_circuit.magic_state_requirements
77    );
78
79    // 6. Photonic circuit conversion
80    println!("\n6. Photonic quantum computation:");
81    let photonic_circuit = PhotonicConverter::quantum_to_photonic(&circuit)?;
82    println!(
83        "   Photonic circuit: {} modes, {} gates",
84        photonic_circuit.num_modes,
85        photonic_circuit.gates.len()
86    );
87
88    // 7. Topological quantum computation
89    println!("\n7. Topological quantum computation:");
90    let anyon_model = AnyonModel::fibonacci();
91    let topo_compiler = TopologicalCompiler::new(anyon_model);
92    let topo_circuit = topo_compiler.compile_quantum_circuit(&circuit)?;
93    println!(
94        "   Topological circuit: {} anyons, {} braiding operations",
95        topo_circuit.anyon_count(),
96        topo_circuit.total_braiding_operations()
97    );
98
99    // 8. Circuit-to-simulator interface
100    println!("\n8. Circuit compilation for simulators:");
101    let mut compiler = CircuitCompiler::new();
102    compiler.add_target(CompilationTarget {
103        backend: SimulatorBackend::StateVector {
104            max_qubits: 20,
105            use_gpu: false,
106            memory_optimization: MemoryOptimization::Basic,
107        },
108        optimization_level: SimulatorOptimizationLevel::Basic,
109        instruction_set: InstructionSet::Universal,
110        parallel_execution: true,
111        batch_size: Some(10),
112    });
113
114    let compiled = compiler.compile(&circuit)?;
115    println!(
116        "   Compiled circuit: {} instructions, estimated memory: {} bytes",
117        compiled.instructions.len(),
118        compiled.resources.memory_bytes
119    );
120
121    // 9. Mid-circuit measurements and feed-forward
122    println!("\n9. Mid-circuit measurements and feed-forward:");
123    let mut measurement_circuit = MeasurementCircuit::<2>::new();
124    measurement_circuit.add_gate(Box::new(Hadamard { target: QubitId(0) }))?;
125    let bit = measurement_circuit.measure(QubitId(0))?;
126
127    let condition = ClassicalCondition::equals(
128        ClassicalValue::Integer(bit as u64),
129        ClassicalValue::Integer(1),
130    );
131    measurement_circuit.add_conditional(condition, Box::new(PauliX { target: QubitId(1) }))?;
132    println!(
133        "   Measurement circuit with {} operations created",
134        measurement_circuit.num_operations()
135    );
136
137    // 10. Cross-talk aware scheduling
138    println!("\n10. Cross-talk aware scheduling:");
139    let crosstalk_model = CrosstalkModel::uniform(3, 0.05);
140    let scheduler = CrosstalkScheduler::new(crosstalk_model);
141    let schedule = scheduler.schedule(&circuit)?;
142    println!(
143        "   Scheduled into {} time slices, total crosstalk: {:.3}",
144        schedule.time_slices.len(),
145        schedule.total_crosstalk
146    );
147
148    println!("\n=== Demo completed successfully! ===");
149    Ok(())
150}
Source

pub fn add_training_example(&mut self, example: TrainingExample)

Add training example

Source

pub fn train_models(&mut self) -> QuantRS2Result<()>

Train models with current data

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> 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, 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

Source§

impl<T> Ungil for T
where T: Send,