QuantumBoltzmannMachine

Struct QuantumBoltzmannMachine 

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

Quantum Boltzmann Machine

Implementations§

Source§

impl QuantumBoltzmannMachine

Source

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

pub fn energy(&self, state: &Array1<f64>) -> f64

Compute energy of a configuration

Examples found in repository?
examples/quantum_boltzmann.rs (line 180)
159fn energy_landscape_demo() -> Result<()> {
160    // Create small QBM for visualization
161    let qbm = QuantumBoltzmannMachine::new(
162        2,    // visible units (for 2D visualization)
163        1,    // hidden unit
164        0.5,  // temperature
165        0.01, // learning rate
166    )?;
167
168    println!("   Analyzing energy landscape of 2-unit system");
169
170    // Compute energy for all 4 possible states
171    let states = [
172        Array1::from_vec(vec![0.0, 0.0]),
173        Array1::from_vec(vec![0.0, 1.0]),
174        Array1::from_vec(vec![1.0, 0.0]),
175        Array1::from_vec(vec![1.0, 1.0]),
176    ];
177
178    println!("\n   State energies:");
179    for (i, state) in states.iter().enumerate() {
180        let energy = qbm.energy(state);
181        let prob = (-energy / qbm.temperature()).exp();
182        println!(
183            "   State [{:.0}, {:.0}]: E = {:.3}, P ∝ {:.3}",
184            state[0], state[1], energy, prob
185        );
186    }
187
188    // Show coupling matrix
189    println!("\n   Coupling matrix:");
190    for i in 0..3 {
191        print!("   [");
192        for j in 0..3 {
193            print!("{:6.3} ", qbm.couplings()[[i, j]]);
194        }
195        println!("]");
196    }
197
198    Ok(())
199}
Source

pub fn create_gibbs_circuit(&self) -> Result<()>

Create quantum circuit for Gibbs state preparation

Source

pub fn sample(&self, num_samples: usize) -> Result<Array2<f64>>

Sample from the Boltzmann distribution

Examples found in repository?
examples/quantum_boltzmann.rs (line 63)
40fn basic_qbm_demo() -> Result<()> {
41    // Create a small QBM
42    let mut qbm = QuantumBoltzmannMachine::new(
43        4,    // visible units
44        2,    // hidden units
45        1.0,  // temperature
46        0.01, // learning rate
47    )?;
48
49    println!("   Created QBM with 4 visible and 2 hidden units");
50
51    // Generate synthetic binary data
52    let data = generate_binary_patterns(100, 4);
53
54    // Train the QBM
55    println!("   Training on binary patterns...");
56    let losses = qbm.train(&data, 50, 10)?;
57
58    println!("   Training complete:");
59    println!("   - Initial loss: {:.4}", losses[0]);
60    println!("   - Final loss: {:.4}", losses.last().unwrap());
61
62    // Sample from trained model
63    let samples = qbm.sample(5)?;
64    println!("\n   Generated samples:");
65    for (i, sample) in samples.outer_iter().enumerate() {
66        print!("   Sample {}: [", i + 1);
67        for val in sample {
68            print!("{val:.0} ");
69        }
70        println!("]");
71    }
72
73    Ok(())
74}
Source

pub fn compute_gradients( &self, data: &Array2<f64>, ) -> Result<(Array2<f64>, Array1<f64>)>

Compute gradients using contrastive divergence

Source

pub fn sample_hidden_given_visible( &self, visible: &ArrayView1<'_, f64>, ) -> Result<Array1<f64>>

Sample hidden units given visible units

Examples found in repository?
examples/quantum_boltzmann.rs (line 362)
357fn complete_pattern(rbm: &QuantumRBM, partial: &Array1<f64>) -> Result<Array1<f64>> {
358    // Use Gibbs sampling to complete pattern
359    let mut current = partial.clone();
360
361    for _ in 0..10 {
362        let hidden = rbm.qbm().sample_hidden_given_visible(&current.view())?;
363        current = rbm.qbm().sample_visible_given_hidden(&hidden)?;
364    }
365
366    Ok(current)
367}
Source

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 56)
40fn basic_qbm_demo() -> Result<()> {
41    // Create a small QBM
42    let mut qbm = QuantumBoltzmannMachine::new(
43        4,    // visible units
44        2,    // hidden units
45        1.0,  // temperature
46        0.01, // learning rate
47    )?;
48
49    println!("   Created QBM with 4 visible and 2 hidden units");
50
51    // Generate synthetic binary data
52    let data = generate_binary_patterns(100, 4);
53
54    // Train the QBM
55    println!("   Training on binary patterns...");
56    let losses = qbm.train(&data, 50, 10)?;
57
58    println!("   Training complete:");
59    println!("   - Initial loss: {:.4}", losses[0]);
60    println!("   - Final loss: {:.4}", losses.last().unwrap());
61
62    // Sample from trained model
63    let samples = qbm.sample(5)?;
64    println!("\n   Generated samples:");
65    for (i, sample) in samples.outer_iter().enumerate() {
66        print!("   Sample {}: [", i + 1);
67        for val in sample {
68            print!("{val:.0} ");
69        }
70        println!("]");
71    }
72
73    Ok(())
74}
Source

pub fn reconstruct(&self, visible: &Array2<f64>) -> Result<Array2<f64>>

Reconstruct visible units

Examples found in repository?
examples/quantum_boltzmann.rs (line 110)
77fn rbm_demo() -> Result<()> {
78    // Create RBM with annealing
79    let annealing = AnnealingSchedule::new(2.0, 0.5, 100);
80
81    let mut rbm = QuantumRBM::new(
82        6,    // visible units
83        3,    // hidden units
84        2.0,  // initial temperature
85        0.01, // learning rate
86    )?
87    .with_annealing(annealing);
88
89    println!("   Created Quantum RBM with annealing schedule");
90
91    // Generate correlated binary data
92    let data = generate_correlated_data(200, 6);
93
94    // Train with PCD
95    println!("   Training with Persistent Contrastive Divergence...");
96    let losses = rbm.train_pcd(
97        &data, 100, // epochs
98        20,  // batch size
99        50,  // persistent chains
100    )?;
101
102    // Analyze training
103    let improvement = (losses[0] - losses.last().unwrap()) / losses[0] * 100.0;
104    println!("   Training statistics:");
105    println!("   - Loss reduction: {improvement:.1}%");
106    println!("   - Final temperature: 0.5");
107
108    // Test reconstruction
109    let test_data = data.slice(s![0..5, ..]).to_owned();
110    let reconstructed = rbm.qbm().reconstruct(&test_data)?;
111
112    println!("\n   Reconstruction quality:");
113    for i in 0..3 {
114        print!("   Original:      [");
115        for val in test_data.row(i) {
116            print!("{val:.0} ");
117        }
118        print!("]  →  Reconstructed: [");
119        for val in reconstructed.row(i) {
120            print!("{val:.0} ");
121        }
122        println!("]");
123    }
124
125    Ok(())
126}
Source

pub fn sample_visible_given_hidden( &self, hidden: &Array1<f64>, ) -> Result<Array1<f64>>

Sample visible units given hidden units

Examples found in repository?
examples/quantum_boltzmann.rs (line 363)
357fn complete_pattern(rbm: &QuantumRBM, partial: &Array1<f64>) -> Result<Array1<f64>> {
358    // Use Gibbs sampling to complete pattern
359    let mut current = partial.clone();
360
361    for _ in 0..10 {
362        let hidden = rbm.qbm().sample_hidden_given_visible(&current.view())?;
363        current = rbm.qbm().sample_visible_given_hidden(&hidden)?;
364    }
365
366    Ok(current)
367}
Source

pub fn temperature(&self) -> f64

Get temperature

Examples found in repository?
examples/quantum_boltzmann.rs (line 181)
159fn energy_landscape_demo() -> Result<()> {
160    // Create small QBM for visualization
161    let qbm = QuantumBoltzmannMachine::new(
162        2,    // visible units (for 2D visualization)
163        1,    // hidden unit
164        0.5,  // temperature
165        0.01, // learning rate
166    )?;
167
168    println!("   Analyzing energy landscape of 2-unit system");
169
170    // Compute energy for all 4 possible states
171    let states = [
172        Array1::from_vec(vec![0.0, 0.0]),
173        Array1::from_vec(vec![0.0, 1.0]),
174        Array1::from_vec(vec![1.0, 0.0]),
175        Array1::from_vec(vec![1.0, 1.0]),
176    ];
177
178    println!("\n   State energies:");
179    for (i, state) in states.iter().enumerate() {
180        let energy = qbm.energy(state);
181        let prob = (-energy / qbm.temperature()).exp();
182        println!(
183            "   State [{:.0}, {:.0}]: E = {:.3}, P ∝ {:.3}",
184            state[0], state[1], energy, prob
185        );
186    }
187
188    // Show coupling matrix
189    println!("\n   Coupling matrix:");
190    for i in 0..3 {
191        print!("   [");
192        for j in 0..3 {
193            print!("{:6.3} ", qbm.couplings()[[i, j]]);
194        }
195        println!("]");
196    }
197
198    Ok(())
199}
Source

pub fn couplings(&self) -> &Array2<f64>

Get couplings matrix

Examples found in repository?
examples/quantum_boltzmann.rs (line 193)
159fn energy_landscape_demo() -> Result<()> {
160    // Create small QBM for visualization
161    let qbm = QuantumBoltzmannMachine::new(
162        2,    // visible units (for 2D visualization)
163        1,    // hidden unit
164        0.5,  // temperature
165        0.01, // learning rate
166    )?;
167
168    println!("   Analyzing energy landscape of 2-unit system");
169
170    // Compute energy for all 4 possible states
171    let states = [
172        Array1::from_vec(vec![0.0, 0.0]),
173        Array1::from_vec(vec![0.0, 1.0]),
174        Array1::from_vec(vec![1.0, 0.0]),
175        Array1::from_vec(vec![1.0, 1.0]),
176    ];
177
178    println!("\n   State energies:");
179    for (i, state) in states.iter().enumerate() {
180        let energy = qbm.energy(state);
181        let prob = (-energy / qbm.temperature()).exp();
182        println!(
183            "   State [{:.0}, {:.0}]: E = {:.3}, P ∝ {:.3}",
184            state[0], state[1], energy, prob
185        );
186    }
187
188    // Show coupling matrix
189    println!("\n   Coupling matrix:");
190    for i in 0..3 {
191        print!("   [");
192        for j in 0..3 {
193            print!("{:6.3} ", qbm.couplings()[[i, j]]);
194        }
195        println!("]");
196    }
197
198    Ok(())
199}

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