pub struct QuantumBoltzmannMachine { /* private fields */ }Expand description
Quantum Boltzmann Machine
Implementations§
Source§impl QuantumBoltzmannMachine
impl QuantumBoltzmannMachine
Sourcepub fn new(
num_visible: usize,
num_hidden: usize,
temperature: f64,
learning_rate: f64,
) -> Result<Self>
pub fn new( num_visible: usize, num_hidden: usize, temperature: f64, learning_rate: f64, ) -> Result<Self>
Create a new Quantum Boltzmann Machine
Examples found in repository?
examples/quantum_boltzmann.rs (lines 41-46)
39fn basic_qbm_demo() -> Result<()> {
40 // Create a small QBM
41 let mut qbm = QuantumBoltzmannMachine::new(
42 4, // visible units
43 2, // hidden units
44 1.0, // temperature
45 0.01, // learning rate
46 )?;
47
48 println!(" Created QBM with 4 visible and 2 hidden units");
49
50 // Generate synthetic binary data
51 let data = generate_binary_patterns(100, 4);
52
53 // Train the QBM
54 println!(" Training on binary patterns...");
55 let losses = qbm.train(&data, 50, 10)?;
56
57 println!(" Training complete:");
58 println!(" - Initial loss: {:.4}", losses[0]);
59 println!(" - Final loss: {:.4}", losses.last().unwrap());
60
61 // Sample from trained model
62 let samples = qbm.sample(5)?;
63 println!("\n Generated samples:");
64 for (i, sample) in samples.outer_iter().enumerate() {
65 print!(" Sample {}: [", i + 1);
66 for val in sample {
67 print!("{val:.0} ");
68 }
69 println!("]");
70 }
71
72 Ok(())
73}
74
75/// RBM demonstration with persistent contrastive divergence
76fn rbm_demo() -> Result<()> {
77 // Create RBM with annealing
78 let annealing = AnnealingSchedule::new(2.0, 0.5, 100);
79
80 let mut rbm = QuantumRBM::new(
81 6, // visible units
82 3, // hidden units
83 2.0, // initial temperature
84 0.01, // learning rate
85 )?
86 .with_annealing(annealing);
87
88 println!(" Created Quantum RBM with annealing schedule");
89
90 // Generate correlated binary data
91 let data = generate_correlated_data(200, 6);
92
93 // Train with PCD
94 println!(" Training with Persistent Contrastive Divergence...");
95 let losses = rbm.train_pcd(
96 &data, 100, // epochs
97 20, // batch size
98 50, // persistent chains
99 )?;
100
101 // Analyze training
102 let improvement = (losses[0] - losses.last().unwrap()) / losses[0] * 100.0;
103 println!(" Training statistics:");
104 println!(" - Loss reduction: {improvement:.1}%");
105 println!(" - Final temperature: 0.5");
106
107 // Test reconstruction
108 let test_data = data.slice(s![0..5, ..]).to_owned();
109 let reconstructed = rbm.qbm().reconstruct(&test_data)?;
110
111 println!("\n Reconstruction quality:");
112 for i in 0..3 {
113 print!(" Original: [");
114 for val in test_data.row(i) {
115 print!("{val:.0} ");
116 }
117 print!("] → Reconstructed: [");
118 for val in reconstructed.row(i) {
119 print!("{val:.0} ");
120 }
121 println!("]");
122 }
123
124 Ok(())
125}
126
127/// Deep Boltzmann Machine demonstration
128fn deep_boltzmann_demo() -> Result<()> {
129 // Create a 3-layer DBM
130 let layer_sizes = vec![8, 4, 2];
131 let mut dbm = DeepBoltzmannMachine::new(
132 layer_sizes.clone(),
133 1.0, // temperature
134 0.01, // learning rate
135 )?;
136
137 println!(" Created Deep Boltzmann Machine:");
138 println!(" - Architecture: {layer_sizes:?}");
139 println!(" - Total layers: {}", dbm.rbms().len());
140
141 // Generate hierarchical data
142 let data = generate_hierarchical_data(300, 8);
143
144 // Layer-wise pretraining
145 println!("\n Performing layer-wise pretraining...");
146 dbm.pretrain(
147 &data, 50, // epochs per layer
148 30, // batch size
149 )?;
150
151 println!("\n Pretraining complete!");
152 println!(" Each layer learned increasingly abstract features");
153
154 Ok(())
155}
156
157/// Energy landscape visualization
158fn energy_landscape_demo() -> Result<()> {
159 // Create small QBM for visualization
160 let qbm = QuantumBoltzmannMachine::new(
161 2, // visible units (for 2D visualization)
162 1, // hidden unit
163 0.5, // temperature
164 0.01, // learning rate
165 )?;
166
167 println!(" Analyzing energy landscape of 2-unit system");
168
169 // Compute energy for all 4 possible states
170 let states = [
171 Array1::from_vec(vec![0.0, 0.0]),
172 Array1::from_vec(vec![0.0, 1.0]),
173 Array1::from_vec(vec![1.0, 0.0]),
174 Array1::from_vec(vec![1.0, 1.0]),
175 ];
176
177 println!("\n State energies:");
178 for (i, state) in states.iter().enumerate() {
179 let energy = qbm.energy(state);
180 let prob = (-energy / qbm.temperature()).exp();
181 println!(
182 " State [{:.0}, {:.0}]: E = {:.3}, P ∝ {:.3}",
183 state[0], state[1], energy, prob
184 );
185 }
186
187 // Show coupling matrix
188 println!("\n Coupling matrix:");
189 for i in 0..3 {
190 print!(" [");
191 for j in 0..3 {
192 print!("{:6.3} ", qbm.couplings()[[i, j]]);
193 }
194 println!("]");
195 }
196
197 Ok(())
198}Sourcepub fn energy(&self, state: &Array1<f64>) -> f64
pub fn energy(&self, state: &Array1<f64>) -> f64
Compute energy of a configuration
Examples found in repository?
examples/quantum_boltzmann.rs (line 179)
158fn energy_landscape_demo() -> Result<()> {
159 // Create small QBM for visualization
160 let qbm = QuantumBoltzmannMachine::new(
161 2, // visible units (for 2D visualization)
162 1, // hidden unit
163 0.5, // temperature
164 0.01, // learning rate
165 )?;
166
167 println!(" Analyzing energy landscape of 2-unit system");
168
169 // Compute energy for all 4 possible states
170 let states = [
171 Array1::from_vec(vec![0.0, 0.0]),
172 Array1::from_vec(vec![0.0, 1.0]),
173 Array1::from_vec(vec![1.0, 0.0]),
174 Array1::from_vec(vec![1.0, 1.0]),
175 ];
176
177 println!("\n State energies:");
178 for (i, state) in states.iter().enumerate() {
179 let energy = qbm.energy(state);
180 let prob = (-energy / qbm.temperature()).exp();
181 println!(
182 " State [{:.0}, {:.0}]: E = {:.3}, P ∝ {:.3}",
183 state[0], state[1], energy, prob
184 );
185 }
186
187 // Show coupling matrix
188 println!("\n Coupling matrix:");
189 for i in 0..3 {
190 print!(" [");
191 for j in 0..3 {
192 print!("{:6.3} ", qbm.couplings()[[i, j]]);
193 }
194 println!("]");
195 }
196
197 Ok(())
198}Sourcepub fn create_gibbs_circuit(&self) -> Result<()>
pub fn create_gibbs_circuit(&self) -> Result<()>
Create quantum circuit for Gibbs state preparation
Sourcepub fn sample(&self, num_samples: usize) -> Result<Array2<f64>>
pub fn sample(&self, num_samples: usize) -> Result<Array2<f64>>
Sample from the Boltzmann distribution
Examples found in repository?
examples/quantum_boltzmann.rs (line 62)
39fn basic_qbm_demo() -> Result<()> {
40 // Create a small QBM
41 let mut qbm = QuantumBoltzmannMachine::new(
42 4, // visible units
43 2, // hidden units
44 1.0, // temperature
45 0.01, // learning rate
46 )?;
47
48 println!(" Created QBM with 4 visible and 2 hidden units");
49
50 // Generate synthetic binary data
51 let data = generate_binary_patterns(100, 4);
52
53 // Train the QBM
54 println!(" Training on binary patterns...");
55 let losses = qbm.train(&data, 50, 10)?;
56
57 println!(" Training complete:");
58 println!(" - Initial loss: {:.4}", losses[0]);
59 println!(" - Final loss: {:.4}", losses.last().unwrap());
60
61 // Sample from trained model
62 let samples = qbm.sample(5)?;
63 println!("\n Generated samples:");
64 for (i, sample) in samples.outer_iter().enumerate() {
65 print!(" Sample {}: [", i + 1);
66 for val in sample {
67 print!("{val:.0} ");
68 }
69 println!("]");
70 }
71
72 Ok(())
73}Sourcepub fn compute_gradients(
&self,
data: &Array2<f64>,
) -> Result<(Array2<f64>, Array1<f64>)>
pub fn compute_gradients( &self, data: &Array2<f64>, ) -> Result<(Array2<f64>, Array1<f64>)>
Compute gradients using contrastive divergence
Sourcepub fn train(
&mut self,
data: &Array2<f64>,
epochs: usize,
batch_size: usize,
) -> Result<Vec<f64>>
pub fn train( &mut self, data: &Array2<f64>, epochs: usize, batch_size: usize, ) -> Result<Vec<f64>>
Train the Boltzmann machine
Examples found in repository?
examples/quantum_boltzmann.rs (line 55)
39fn basic_qbm_demo() -> Result<()> {
40 // Create a small QBM
41 let mut qbm = QuantumBoltzmannMachine::new(
42 4, // visible units
43 2, // hidden units
44 1.0, // temperature
45 0.01, // learning rate
46 )?;
47
48 println!(" Created QBM with 4 visible and 2 hidden units");
49
50 // Generate synthetic binary data
51 let data = generate_binary_patterns(100, 4);
52
53 // Train the QBM
54 println!(" Training on binary patterns...");
55 let losses = qbm.train(&data, 50, 10)?;
56
57 println!(" Training complete:");
58 println!(" - Initial loss: {:.4}", losses[0]);
59 println!(" - Final loss: {:.4}", losses.last().unwrap());
60
61 // Sample from trained model
62 let samples = qbm.sample(5)?;
63 println!("\n Generated samples:");
64 for (i, sample) in samples.outer_iter().enumerate() {
65 print!(" Sample {}: [", i + 1);
66 for val in sample {
67 print!("{val:.0} ");
68 }
69 println!("]");
70 }
71
72 Ok(())
73}Sourcepub fn reconstruct(&self, visible: &Array2<f64>) -> Result<Array2<f64>>
pub fn reconstruct(&self, visible: &Array2<f64>) -> Result<Array2<f64>>
Reconstruct visible units
Examples found in repository?
examples/quantum_boltzmann.rs (line 109)
76fn rbm_demo() -> Result<()> {
77 // Create RBM with annealing
78 let annealing = AnnealingSchedule::new(2.0, 0.5, 100);
79
80 let mut rbm = QuantumRBM::new(
81 6, // visible units
82 3, // hidden units
83 2.0, // initial temperature
84 0.01, // learning rate
85 )?
86 .with_annealing(annealing);
87
88 println!(" Created Quantum RBM with annealing schedule");
89
90 // Generate correlated binary data
91 let data = generate_correlated_data(200, 6);
92
93 // Train with PCD
94 println!(" Training with Persistent Contrastive Divergence...");
95 let losses = rbm.train_pcd(
96 &data, 100, // epochs
97 20, // batch size
98 50, // persistent chains
99 )?;
100
101 // Analyze training
102 let improvement = (losses[0] - losses.last().unwrap()) / losses[0] * 100.0;
103 println!(" Training statistics:");
104 println!(" - Loss reduction: {improvement:.1}%");
105 println!(" - Final temperature: 0.5");
106
107 // Test reconstruction
108 let test_data = data.slice(s![0..5, ..]).to_owned();
109 let reconstructed = rbm.qbm().reconstruct(&test_data)?;
110
111 println!("\n Reconstruction quality:");
112 for i in 0..3 {
113 print!(" Original: [");
114 for val in test_data.row(i) {
115 print!("{val:.0} ");
116 }
117 print!("] → Reconstructed: [");
118 for val in reconstructed.row(i) {
119 print!("{val:.0} ");
120 }
121 println!("]");
122 }
123
124 Ok(())
125}Sourcepub fn temperature(&self) -> f64
pub fn temperature(&self) -> f64
Get temperature
Examples found in repository?
examples/quantum_boltzmann.rs (line 180)
158fn energy_landscape_demo() -> Result<()> {
159 // Create small QBM for visualization
160 let qbm = QuantumBoltzmannMachine::new(
161 2, // visible units (for 2D visualization)
162 1, // hidden unit
163 0.5, // temperature
164 0.01, // learning rate
165 )?;
166
167 println!(" Analyzing energy landscape of 2-unit system");
168
169 // Compute energy for all 4 possible states
170 let states = [
171 Array1::from_vec(vec![0.0, 0.0]),
172 Array1::from_vec(vec![0.0, 1.0]),
173 Array1::from_vec(vec![1.0, 0.0]),
174 Array1::from_vec(vec![1.0, 1.0]),
175 ];
176
177 println!("\n State energies:");
178 for (i, state) in states.iter().enumerate() {
179 let energy = qbm.energy(state);
180 let prob = (-energy / qbm.temperature()).exp();
181 println!(
182 " State [{:.0}, {:.0}]: E = {:.3}, P ∝ {:.3}",
183 state[0], state[1], energy, prob
184 );
185 }
186
187 // Show coupling matrix
188 println!("\n Coupling matrix:");
189 for i in 0..3 {
190 print!(" [");
191 for j in 0..3 {
192 print!("{:6.3} ", qbm.couplings()[[i, j]]);
193 }
194 println!("]");
195 }
196
197 Ok(())
198}Sourcepub fn couplings(&self) -> &Array2<f64>
pub fn couplings(&self) -> &Array2<f64>
Get couplings matrix
Examples found in repository?
examples/quantum_boltzmann.rs (line 192)
158fn energy_landscape_demo() -> Result<()> {
159 // Create small QBM for visualization
160 let qbm = QuantumBoltzmannMachine::new(
161 2, // visible units (for 2D visualization)
162 1, // hidden unit
163 0.5, // temperature
164 0.01, // learning rate
165 )?;
166
167 println!(" Analyzing energy landscape of 2-unit system");
168
169 // Compute energy for all 4 possible states
170 let states = [
171 Array1::from_vec(vec![0.0, 0.0]),
172 Array1::from_vec(vec![0.0, 1.0]),
173 Array1::from_vec(vec![1.0, 0.0]),
174 Array1::from_vec(vec![1.0, 1.0]),
175 ];
176
177 println!("\n State energies:");
178 for (i, state) in states.iter().enumerate() {
179 let energy = qbm.energy(state);
180 let prob = (-energy / qbm.temperature()).exp();
181 println!(
182 " State [{:.0}, {:.0}]: E = {:.3}, P ∝ {:.3}",
183 state[0], state[1], energy, prob
184 );
185 }
186
187 // Show coupling matrix
188 println!("\n Coupling matrix:");
189 for i in 0..3 {
190 print!(" [");
191 for j in 0..3 {
192 print!("{:6.3} ", qbm.couplings()[[i, j]]);
193 }
194 println!("]");
195 }
196
197 Ok(())
198}Auto Trait Implementations§
impl Freeze for QuantumBoltzmannMachine
impl RefUnwindSafe for QuantumBoltzmannMachine
impl Send for QuantumBoltzmannMachine
impl Sync for QuantumBoltzmannMachine
impl Unpin for QuantumBoltzmannMachine
impl UnwindSafe for QuantumBoltzmannMachine
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> 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.