CircuitOptimizer2

Struct CircuitOptimizer2 

Source
pub struct CircuitOptimizer2<const N: usize> { /* private fields */ }
Expand description

Main optimization interface

Implementations§

Source§

impl<const N: usize> CircuitOptimizer2<N>

Source

pub fn new() -> Self

Create a new optimizer with default settings

Examples found in repository?
examples/optimization_demo.rs (line 154)
131fn demo_custom_optimization(circuit: &Circuit<4>) {
132    println!("\nDemo 3: Custom Optimization Pipeline");
133    println!("------------------------------------");
134
135    // Create a custom pass manager
136    let mut pass_manager = PassManager::new();
137
138    // Configure with specific passes
139    let config = PassConfig {
140        max_iterations: 5,
141        aggressive: true,
142        level: OptimizationLevel::Custom,
143        ..Default::default()
144    };
145    pass_manager.configure(config.clone());
146
147    // Add specific passes in a custom order
148    pass_manager.add_pass(Box::new(GateCancellation::new(true)));
149    pass_manager.add_pass(Box::new(RotationMerging::new(1e-10)));
150    pass_manager.add_pass(Box::new(GateCommutation::new(10)));
151    pass_manager.add_pass(Box::new(TemplateMatching::new()));
152
153    // Create optimizer with custom configuration
154    let mut optimizer = CircuitOptimizer2::<4>::new();
155    optimizer.configure(config);
156
157    match optimizer.optimize(circuit) {
158        Ok(report) => {
159            println!("Custom optimization results:");
160            report.print_summary();
161        }
162        Err(e) => {
163            println!("Custom optimization failed: {:?}", e);
164        }
165    }
166}
Source

pub fn with_level(level: OptimizationLevel) -> Self

Create an optimizer with a specific optimization level

Examples found in repository?
examples/optimization_demo.rs (line 77)
62fn demo_optimization_levels(circuit: &Circuit<4>) {
63    println!("Demo 1: Optimization Levels");
64    println!("----------------------------");
65
66    let levels = [
67        OptimizationLevel::None,
68        OptimizationLevel::Light,
69        OptimizationLevel::Medium,
70        OptimizationLevel::Heavy,
71    ];
72
73    for level in levels {
74        println!("\nOptimization Level: {:?}", level);
75
76        let start = Instant::now();
77        let mut optimizer = CircuitOptimizer2::<4>::with_level(level);
78
79        match optimizer.optimize(circuit) {
80            Ok(report) => {
81                let duration = start.elapsed();
82                println!("  Optimization time: {:?}", duration);
83                println!("  Initial gates: {}", report.initial_metrics.gate_count);
84                println!("  Final gates: {}", report.final_metrics.gate_count);
85                println!("  Gate reduction: {:.1}%", report.improvement().gate_count);
86                println!("  Applied passes: {:?}", report.applied_passes);
87            }
88            Err(e) => {
89                println!("  Optimization failed: {:?}", e);
90            }
91        }
92    }
93    println!();
94}
95
96fn demo_hardware_optimization(circuit: &Circuit<4>) {
97    println!("\nDemo 2: Hardware-Specific Optimization");
98    println!("--------------------------------------");
99
100    let backends = ["ibm", "google", "aws"];
101
102    for backend in backends {
103        println!("\nBackend: {}", backend);
104
105        let mut optimizer = CircuitOptimizer2::<4>::for_hardware(backend);
106
107        match optimizer.optimize(circuit) {
108            Ok(report) => {
109                println!(
110                    "  Initial cost: {:.2}",
111                    report.initial_metrics.execution_time
112                );
113                println!("  Final cost: {:.2}", report.final_metrics.execution_time);
114                println!(
115                    "  Time reduction: {:.1}%",
116                    report.improvement().execution_time
117                );
118                println!(
119                    "  Error reduction: {:.1}%",
120                    report.improvement().total_error
121                );
122            }
123            Err(e) => {
124                println!("  Optimization failed: {:?}", e);
125            }
126        }
127    }
128    println!();
129}
130
131fn demo_custom_optimization(circuit: &Circuit<4>) {
132    println!("\nDemo 3: Custom Optimization Pipeline");
133    println!("------------------------------------");
134
135    // Create a custom pass manager
136    let mut pass_manager = PassManager::new();
137
138    // Configure with specific passes
139    let config = PassConfig {
140        max_iterations: 5,
141        aggressive: true,
142        level: OptimizationLevel::Custom,
143        ..Default::default()
144    };
145    pass_manager.configure(config.clone());
146
147    // Add specific passes in a custom order
148    pass_manager.add_pass(Box::new(GateCancellation::new(true)));
149    pass_manager.add_pass(Box::new(RotationMerging::new(1e-10)));
150    pass_manager.add_pass(Box::new(GateCommutation::new(10)));
151    pass_manager.add_pass(Box::new(TemplateMatching::new()));
152
153    // Create optimizer with custom configuration
154    let mut optimizer = CircuitOptimizer2::<4>::new();
155    optimizer.configure(config);
156
157    match optimizer.optimize(circuit) {
158        Ok(report) => {
159            println!("Custom optimization results:");
160            report.print_summary();
161        }
162        Err(e) => {
163            println!("Custom optimization failed: {:?}", e);
164        }
165    }
166}
167
168fn demo_gate_properties() {
169    println!("\nDemo 4: Gate Properties");
170    println!("-----------------------");
171
172    // Show properties of various gates
173    let gates = vec!["H", "X", "CNOT", "Toffoli"];
174
175    for gate_name in gates {
176        let props = match gate_name {
177            "H" | "X" => GateProperties::single_qubit(gate_name),
178            "CNOT" => GateProperties::two_qubit(gate_name),
179            "Toffoli" => GateProperties::multi_qubit(gate_name, 3),
180            _ => continue,
181        };
182
183        println!("\n{} Gate Properties:", gate_name);
184        println!("  Native: {}", props.is_native);
185        println!("  Duration: {:.1} ns", props.cost.duration_ns);
186        println!("  Error rate: {:.6}", props.error.error_rate);
187        println!("  Self-inverse: {}", props.is_self_inverse);
188        println!("  Diagonal: {}", props.is_diagonal);
189        println!("  Decompositions: {}", props.decompositions.len());
190    }
191
192    // Show commutation relations
193    println!("\nCommutation Relations:");
194    let comm_table = CommutationTable::new();
195
196    let gate_pairs = vec![
197        ("X", "Y"),
198        ("X", "Z"),
199        ("Z", "Z"),
200        ("Z", "RZ"),
201        ("CNOT", "CNOT"),
202    ];
203
204    for (g1, g2) in gate_pairs {
205        println!(
206            "  {} ↔ {}: {}",
207            g1,
208            g2,
209            if comm_table.commutes(g1, g2) {
210                "✓"
211            } else {
212                "✗"
213            }
214        );
215    }
216    println!();
217}
218
219fn benchmark_optimization_passes(circuit: &Circuit<4>) {
220    println!("\nDemo 5: Pass Benchmarking");
221    println!("-------------------------");
222
223    // Benchmark individual passes
224    let passes: Vec<(&str, Box<dyn OptimizationPass>)> = vec![
225        ("Gate Cancellation", Box::new(GateCancellation::new(false))),
226        ("Rotation Merging", Box::new(RotationMerging::new(1e-10))),
227        ("Gate Commutation", Box::new(GateCommutation::new(5))),
228        ("Template Matching", Box::new(TemplateMatching::new())),
229        (
230            "Two-Qubit Opt",
231            Box::new(TwoQubitOptimization::new(false, true)),
232        ),
233    ];
234
235    let cost_model = AbstractCostModel::default();
236
237    for (name, pass) in passes {
238        let start = Instant::now();
239
240        match pass.apply(circuit, &cost_model) {
241            Ok(_) => {
242                let duration = start.elapsed();
243                println!("  {}: {:?}", name, duration);
244            }
245            Err(e) => {
246                println!("  {} failed: {:?}", name, e);
247            }
248        }
249    }
250
251    // Benchmark full optimization
252    println!("\nFull Optimization Benchmark:");
253    let start = Instant::now();
254    let mut optimizer = CircuitOptimizer2::<4>::with_level(OptimizationLevel::Heavy);
255
256    match optimizer.optimize(circuit) {
257        Ok(report) => {
258            let duration = start.elapsed();
259            println!("  Total time: {:?}", duration);
260            println!(
261                "  Gates reduced: {} → {}",
262                report.initial_metrics.gate_count, report.final_metrics.gate_count
263            );
264
265            // Show detailed report
266            println!("\nDetailed Report:");
267            println!("{}", report.detailed_report());
268        }
269        Err(e) => {
270            println!("  Benchmark failed: {:?}", e);
271        }
272    }
273}
Source

pub fn for_hardware(hardware: &str) -> Self

Create an optimizer for specific hardware

Examples found in repository?
examples/optimization_demo.rs (line 105)
96fn demo_hardware_optimization(circuit: &Circuit<4>) {
97    println!("\nDemo 2: Hardware-Specific Optimization");
98    println!("--------------------------------------");
99
100    let backends = ["ibm", "google", "aws"];
101
102    for backend in backends {
103        println!("\nBackend: {}", backend);
104
105        let mut optimizer = CircuitOptimizer2::<4>::for_hardware(backend);
106
107        match optimizer.optimize(circuit) {
108            Ok(report) => {
109                println!(
110                    "  Initial cost: {:.2}",
111                    report.initial_metrics.execution_time
112                );
113                println!("  Final cost: {:.2}", report.final_metrics.execution_time);
114                println!(
115                    "  Time reduction: {:.1}%",
116                    report.improvement().execution_time
117                );
118                println!(
119                    "  Error reduction: {:.1}%",
120                    report.improvement().total_error
121                );
122            }
123            Err(e) => {
124                println!("  Optimization failed: {:?}", e);
125            }
126        }
127    }
128    println!();
129}
Source

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

Optimize a circuit

Examples found in repository?
examples/optimization_demo.rs (line 79)
62fn demo_optimization_levels(circuit: &Circuit<4>) {
63    println!("Demo 1: Optimization Levels");
64    println!("----------------------------");
65
66    let levels = [
67        OptimizationLevel::None,
68        OptimizationLevel::Light,
69        OptimizationLevel::Medium,
70        OptimizationLevel::Heavy,
71    ];
72
73    for level in levels {
74        println!("\nOptimization Level: {:?}", level);
75
76        let start = Instant::now();
77        let mut optimizer = CircuitOptimizer2::<4>::with_level(level);
78
79        match optimizer.optimize(circuit) {
80            Ok(report) => {
81                let duration = start.elapsed();
82                println!("  Optimization time: {:?}", duration);
83                println!("  Initial gates: {}", report.initial_metrics.gate_count);
84                println!("  Final gates: {}", report.final_metrics.gate_count);
85                println!("  Gate reduction: {:.1}%", report.improvement().gate_count);
86                println!("  Applied passes: {:?}", report.applied_passes);
87            }
88            Err(e) => {
89                println!("  Optimization failed: {:?}", e);
90            }
91        }
92    }
93    println!();
94}
95
96fn demo_hardware_optimization(circuit: &Circuit<4>) {
97    println!("\nDemo 2: Hardware-Specific Optimization");
98    println!("--------------------------------------");
99
100    let backends = ["ibm", "google", "aws"];
101
102    for backend in backends {
103        println!("\nBackend: {}", backend);
104
105        let mut optimizer = CircuitOptimizer2::<4>::for_hardware(backend);
106
107        match optimizer.optimize(circuit) {
108            Ok(report) => {
109                println!(
110                    "  Initial cost: {:.2}",
111                    report.initial_metrics.execution_time
112                );
113                println!("  Final cost: {:.2}", report.final_metrics.execution_time);
114                println!(
115                    "  Time reduction: {:.1}%",
116                    report.improvement().execution_time
117                );
118                println!(
119                    "  Error reduction: {:.1}%",
120                    report.improvement().total_error
121                );
122            }
123            Err(e) => {
124                println!("  Optimization failed: {:?}", e);
125            }
126        }
127    }
128    println!();
129}
130
131fn demo_custom_optimization(circuit: &Circuit<4>) {
132    println!("\nDemo 3: Custom Optimization Pipeline");
133    println!("------------------------------------");
134
135    // Create a custom pass manager
136    let mut pass_manager = PassManager::new();
137
138    // Configure with specific passes
139    let config = PassConfig {
140        max_iterations: 5,
141        aggressive: true,
142        level: OptimizationLevel::Custom,
143        ..Default::default()
144    };
145    pass_manager.configure(config.clone());
146
147    // Add specific passes in a custom order
148    pass_manager.add_pass(Box::new(GateCancellation::new(true)));
149    pass_manager.add_pass(Box::new(RotationMerging::new(1e-10)));
150    pass_manager.add_pass(Box::new(GateCommutation::new(10)));
151    pass_manager.add_pass(Box::new(TemplateMatching::new()));
152
153    // Create optimizer with custom configuration
154    let mut optimizer = CircuitOptimizer2::<4>::new();
155    optimizer.configure(config);
156
157    match optimizer.optimize(circuit) {
158        Ok(report) => {
159            println!("Custom optimization results:");
160            report.print_summary();
161        }
162        Err(e) => {
163            println!("Custom optimization failed: {:?}", e);
164        }
165    }
166}
167
168fn demo_gate_properties() {
169    println!("\nDemo 4: Gate Properties");
170    println!("-----------------------");
171
172    // Show properties of various gates
173    let gates = vec!["H", "X", "CNOT", "Toffoli"];
174
175    for gate_name in gates {
176        let props = match gate_name {
177            "H" | "X" => GateProperties::single_qubit(gate_name),
178            "CNOT" => GateProperties::two_qubit(gate_name),
179            "Toffoli" => GateProperties::multi_qubit(gate_name, 3),
180            _ => continue,
181        };
182
183        println!("\n{} Gate Properties:", gate_name);
184        println!("  Native: {}", props.is_native);
185        println!("  Duration: {:.1} ns", props.cost.duration_ns);
186        println!("  Error rate: {:.6}", props.error.error_rate);
187        println!("  Self-inverse: {}", props.is_self_inverse);
188        println!("  Diagonal: {}", props.is_diagonal);
189        println!("  Decompositions: {}", props.decompositions.len());
190    }
191
192    // Show commutation relations
193    println!("\nCommutation Relations:");
194    let comm_table = CommutationTable::new();
195
196    let gate_pairs = vec![
197        ("X", "Y"),
198        ("X", "Z"),
199        ("Z", "Z"),
200        ("Z", "RZ"),
201        ("CNOT", "CNOT"),
202    ];
203
204    for (g1, g2) in gate_pairs {
205        println!(
206            "  {} ↔ {}: {}",
207            g1,
208            g2,
209            if comm_table.commutes(g1, g2) {
210                "✓"
211            } else {
212                "✗"
213            }
214        );
215    }
216    println!();
217}
218
219fn benchmark_optimization_passes(circuit: &Circuit<4>) {
220    println!("\nDemo 5: Pass Benchmarking");
221    println!("-------------------------");
222
223    // Benchmark individual passes
224    let passes: Vec<(&str, Box<dyn OptimizationPass>)> = vec![
225        ("Gate Cancellation", Box::new(GateCancellation::new(false))),
226        ("Rotation Merging", Box::new(RotationMerging::new(1e-10))),
227        ("Gate Commutation", Box::new(GateCommutation::new(5))),
228        ("Template Matching", Box::new(TemplateMatching::new())),
229        (
230            "Two-Qubit Opt",
231            Box::new(TwoQubitOptimization::new(false, true)),
232        ),
233    ];
234
235    let cost_model = AbstractCostModel::default();
236
237    for (name, pass) in passes {
238        let start = Instant::now();
239
240        match pass.apply(circuit, &cost_model) {
241            Ok(_) => {
242                let duration = start.elapsed();
243                println!("  {}: {:?}", name, duration);
244            }
245            Err(e) => {
246                println!("  {} failed: {:?}", name, e);
247            }
248        }
249    }
250
251    // Benchmark full optimization
252    println!("\nFull Optimization Benchmark:");
253    let start = Instant::now();
254    let mut optimizer = CircuitOptimizer2::<4>::with_level(OptimizationLevel::Heavy);
255
256    match optimizer.optimize(circuit) {
257        Ok(report) => {
258            let duration = start.elapsed();
259            println!("  Total time: {:?}", duration);
260            println!(
261                "  Gates reduced: {} → {}",
262                report.initial_metrics.gate_count, report.final_metrics.gate_count
263            );
264
265            // Show detailed report
266            println!("\nDetailed Report:");
267            println!("{}", report.detailed_report());
268        }
269        Err(e) => {
270            println!("  Benchmark failed: {:?}", e);
271        }
272    }
273}
Source

pub fn add_pass(&mut self, pass: Box<dyn OptimizationPass>)

Add a custom optimization pass

Source

pub fn set_cost_model(&mut self, cost_model: Box<dyn CostModel>)

Set a custom cost model

Source

pub fn configure(&mut self, config: PassConfig)

Configure the optimizer

Examples found in repository?
examples/optimization_demo.rs (line 155)
131fn demo_custom_optimization(circuit: &Circuit<4>) {
132    println!("\nDemo 3: Custom Optimization Pipeline");
133    println!("------------------------------------");
134
135    // Create a custom pass manager
136    let mut pass_manager = PassManager::new();
137
138    // Configure with specific passes
139    let config = PassConfig {
140        max_iterations: 5,
141        aggressive: true,
142        level: OptimizationLevel::Custom,
143        ..Default::default()
144    };
145    pass_manager.configure(config.clone());
146
147    // Add specific passes in a custom order
148    pass_manager.add_pass(Box::new(GateCancellation::new(true)));
149    pass_manager.add_pass(Box::new(RotationMerging::new(1e-10)));
150    pass_manager.add_pass(Box::new(GateCommutation::new(10)));
151    pass_manager.add_pass(Box::new(TemplateMatching::new()));
152
153    // Create optimizer with custom configuration
154    let mut optimizer = CircuitOptimizer2::<4>::new();
155    optimizer.configure(config);
156
157    match optimizer.optimize(circuit) {
158        Ok(report) => {
159            println!("Custom optimization results:");
160            report.print_summary();
161        }
162        Err(e) => {
163            println!("Custom optimization failed: {:?}", e);
164        }
165    }
166}

Trait Implementations§

Source§

impl<const N: usize> Default for CircuitOptimizer2<N>

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

§

impl<const N: usize> Freeze for CircuitOptimizer2<N>

§

impl<const N: usize> !RefUnwindSafe for CircuitOptimizer2<N>

§

impl<const N: usize> Send for CircuitOptimizer2<N>

§

impl<const N: usize> Sync for CircuitOptimizer2<N>

§

impl<const N: usize> Unpin for CircuitOptimizer2<N>

§

impl<const N: usize> !UnwindSafe for CircuitOptimizer2<N>

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,