QuantumGAN

Struct QuantumGAN 

Source
pub struct QuantumGAN {
    pub generator: QuantumGenerator,
    pub discriminator: QuantumDiscriminator,
    pub training_history: GANTrainingHistory,
}
Expand description

Quantum Generative Adversarial Network

Fields§

§generator: QuantumGenerator

Generator model

§discriminator: QuantumDiscriminator

Discriminator model

§training_history: GANTrainingHistory

Training history

Implementations§

Source§

impl QuantumGAN

Source

pub fn new( num_qubits_gen: usize, num_qubits_disc: usize, latent_dim: usize, data_dim: usize, generator_type: GeneratorType, discriminator_type: DiscriminatorType, ) -> Result<Self>

Creates a new quantum GAN

Examples found in repository?
examples/quantum_gan.rs (lines 25-32)
8fn main() -> Result<()> {
9    println!("Quantum Generative Adversarial Network Example");
10    println!("=============================================");
11
12    // GAN parameters
13    let num_qubits_gen = 6;
14    let num_qubits_disc = 6;
15    let latent_dim = 4;
16    let data_dim = 8;
17
18    println!("Creating Quantum GAN...");
19    println!("  Generator: {num_qubits_gen} qubits");
20    println!("  Discriminator: {num_qubits_disc} qubits");
21    println!("  Latent dimension: {latent_dim}");
22    println!("  Data dimension: {data_dim}");
23
24    // Create quantum GAN
25    let mut qgan = QuantumGAN::new(
26        num_qubits_gen,
27        num_qubits_disc,
28        latent_dim,
29        data_dim,
30        GeneratorType::HybridClassicalQuantum,
31        DiscriminatorType::HybridQuantumFeatures,
32    )?;
33
34    // Generate synthetic data for training
35    println!("Generating synthetic data for training...");
36    let real_data = generate_sine_wave_data(500, data_dim);
37
38    // Train GAN
39    println!("Training quantum GAN...");
40    let training_params = [
41        (50, 32, 0.01, 0.01, 1), // (epochs, batch_size, lr_gen, lr_disc, disc_steps)
42    ];
43
44    for (epochs, batch_size, lr_gen, lr_disc, disc_steps) in training_params {
45        println!("Training with parameters:");
46        println!("  Epochs: {epochs}");
47        println!("  Batch size: {batch_size}");
48        println!("  Generator learning rate: {lr_gen}");
49        println!("  Discriminator learning rate: {lr_disc}");
50        println!("  Discriminator steps per iteration: {disc_steps}");
51
52        let start = Instant::now();
53        let history = qgan.train(&real_data, epochs, batch_size, lr_gen, lr_disc, disc_steps)?;
54
55        println!("Training completed in {:.2?}", start.elapsed());
56        println!("Final losses:");
57        println!(
58            "  Generator: {:.4}",
59            history.gen_losses.last().unwrap_or(&0.0)
60        );
61        println!(
62            "  Discriminator: {:.4}",
63            history.disc_losses.last().unwrap_or(&0.0)
64        );
65    }
66
67    // Generate samples
68    println!("\nGenerating samples from trained GAN...");
69    let num_samples = 10;
70    let generated_samples = qgan.generate(num_samples)?;
71
72    println!("Generated {num_samples} samples");
73    println!("First sample:");
74    print_sample(
75        &generated_samples
76            .slice(scirs2_core::ndarray::s![0, ..])
77            .to_owned(),
78    );
79
80    // Evaluate GAN
81    println!("\nEvaluating GAN quality...");
82    let eval_metrics = qgan.evaluate(&real_data, num_samples)?;
83
84    println!("Evaluation metrics:");
85    println!(
86        "  Real data accuracy: {:.2}%",
87        eval_metrics.real_accuracy * 100.0
88    );
89    println!(
90        "  Fake data accuracy: {:.2}%",
91        eval_metrics.fake_accuracy * 100.0
92    );
93    println!(
94        "  Overall discriminator accuracy: {:.2}%",
95        eval_metrics.overall_accuracy * 100.0
96    );
97    println!("  JS Divergence: {:.4}", eval_metrics.js_divergence);
98
99    // Use physics-specific GAN
100    println!("\nCreating specialized particle physics GAN...");
101    let particle_gan = quantrs2_ml::gan::physics_gan::ParticleGAN::new(
102        num_qubits_gen,
103        num_qubits_disc,
104        latent_dim,
105        data_dim,
106    )?;
107
108    println!("Particle GAN created successfully");
109
110    Ok(())
111}
Source

pub fn train( &mut self, real_data: &Array2<f64>, epochs: usize, batch_size: usize, gen_learning_rate: f64, disc_learning_rate: f64, disc_steps: usize, ) -> Result<&GANTrainingHistory>

Trains the GAN on a dataset

Examples found in repository?
examples/quantum_gan.rs (line 53)
8fn main() -> Result<()> {
9    println!("Quantum Generative Adversarial Network Example");
10    println!("=============================================");
11
12    // GAN parameters
13    let num_qubits_gen = 6;
14    let num_qubits_disc = 6;
15    let latent_dim = 4;
16    let data_dim = 8;
17
18    println!("Creating Quantum GAN...");
19    println!("  Generator: {num_qubits_gen} qubits");
20    println!("  Discriminator: {num_qubits_disc} qubits");
21    println!("  Latent dimension: {latent_dim}");
22    println!("  Data dimension: {data_dim}");
23
24    // Create quantum GAN
25    let mut qgan = QuantumGAN::new(
26        num_qubits_gen,
27        num_qubits_disc,
28        latent_dim,
29        data_dim,
30        GeneratorType::HybridClassicalQuantum,
31        DiscriminatorType::HybridQuantumFeatures,
32    )?;
33
34    // Generate synthetic data for training
35    println!("Generating synthetic data for training...");
36    let real_data = generate_sine_wave_data(500, data_dim);
37
38    // Train GAN
39    println!("Training quantum GAN...");
40    let training_params = [
41        (50, 32, 0.01, 0.01, 1), // (epochs, batch_size, lr_gen, lr_disc, disc_steps)
42    ];
43
44    for (epochs, batch_size, lr_gen, lr_disc, disc_steps) in training_params {
45        println!("Training with parameters:");
46        println!("  Epochs: {epochs}");
47        println!("  Batch size: {batch_size}");
48        println!("  Generator learning rate: {lr_gen}");
49        println!("  Discriminator learning rate: {lr_disc}");
50        println!("  Discriminator steps per iteration: {disc_steps}");
51
52        let start = Instant::now();
53        let history = qgan.train(&real_data, epochs, batch_size, lr_gen, lr_disc, disc_steps)?;
54
55        println!("Training completed in {:.2?}", start.elapsed());
56        println!("Final losses:");
57        println!(
58            "  Generator: {:.4}",
59            history.gen_losses.last().unwrap_or(&0.0)
60        );
61        println!(
62            "  Discriminator: {:.4}",
63            history.disc_losses.last().unwrap_or(&0.0)
64        );
65    }
66
67    // Generate samples
68    println!("\nGenerating samples from trained GAN...");
69    let num_samples = 10;
70    let generated_samples = qgan.generate(num_samples)?;
71
72    println!("Generated {num_samples} samples");
73    println!("First sample:");
74    print_sample(
75        &generated_samples
76            .slice(scirs2_core::ndarray::s![0, ..])
77            .to_owned(),
78    );
79
80    // Evaluate GAN
81    println!("\nEvaluating GAN quality...");
82    let eval_metrics = qgan.evaluate(&real_data, num_samples)?;
83
84    println!("Evaluation metrics:");
85    println!(
86        "  Real data accuracy: {:.2}%",
87        eval_metrics.real_accuracy * 100.0
88    );
89    println!(
90        "  Fake data accuracy: {:.2}%",
91        eval_metrics.fake_accuracy * 100.0
92    );
93    println!(
94        "  Overall discriminator accuracy: {:.2}%",
95        eval_metrics.overall_accuracy * 100.0
96    );
97    println!("  JS Divergence: {:.4}", eval_metrics.js_divergence);
98
99    // Use physics-specific GAN
100    println!("\nCreating specialized particle physics GAN...");
101    let particle_gan = quantrs2_ml::gan::physics_gan::ParticleGAN::new(
102        num_qubits_gen,
103        num_qubits_disc,
104        latent_dim,
105        data_dim,
106    )?;
107
108    println!("Particle GAN created successfully");
109
110    Ok(())
111}
Source

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

Generates samples from the trained generator

Examples found in repository?
examples/quantum_gan.rs (line 70)
8fn main() -> Result<()> {
9    println!("Quantum Generative Adversarial Network Example");
10    println!("=============================================");
11
12    // GAN parameters
13    let num_qubits_gen = 6;
14    let num_qubits_disc = 6;
15    let latent_dim = 4;
16    let data_dim = 8;
17
18    println!("Creating Quantum GAN...");
19    println!("  Generator: {num_qubits_gen} qubits");
20    println!("  Discriminator: {num_qubits_disc} qubits");
21    println!("  Latent dimension: {latent_dim}");
22    println!("  Data dimension: {data_dim}");
23
24    // Create quantum GAN
25    let mut qgan = QuantumGAN::new(
26        num_qubits_gen,
27        num_qubits_disc,
28        latent_dim,
29        data_dim,
30        GeneratorType::HybridClassicalQuantum,
31        DiscriminatorType::HybridQuantumFeatures,
32    )?;
33
34    // Generate synthetic data for training
35    println!("Generating synthetic data for training...");
36    let real_data = generate_sine_wave_data(500, data_dim);
37
38    // Train GAN
39    println!("Training quantum GAN...");
40    let training_params = [
41        (50, 32, 0.01, 0.01, 1), // (epochs, batch_size, lr_gen, lr_disc, disc_steps)
42    ];
43
44    for (epochs, batch_size, lr_gen, lr_disc, disc_steps) in training_params {
45        println!("Training with parameters:");
46        println!("  Epochs: {epochs}");
47        println!("  Batch size: {batch_size}");
48        println!("  Generator learning rate: {lr_gen}");
49        println!("  Discriminator learning rate: {lr_disc}");
50        println!("  Discriminator steps per iteration: {disc_steps}");
51
52        let start = Instant::now();
53        let history = qgan.train(&real_data, epochs, batch_size, lr_gen, lr_disc, disc_steps)?;
54
55        println!("Training completed in {:.2?}", start.elapsed());
56        println!("Final losses:");
57        println!(
58            "  Generator: {:.4}",
59            history.gen_losses.last().unwrap_or(&0.0)
60        );
61        println!(
62            "  Discriminator: {:.4}",
63            history.disc_losses.last().unwrap_or(&0.0)
64        );
65    }
66
67    // Generate samples
68    println!("\nGenerating samples from trained GAN...");
69    let num_samples = 10;
70    let generated_samples = qgan.generate(num_samples)?;
71
72    println!("Generated {num_samples} samples");
73    println!("First sample:");
74    print_sample(
75        &generated_samples
76            .slice(scirs2_core::ndarray::s![0, ..])
77            .to_owned(),
78    );
79
80    // Evaluate GAN
81    println!("\nEvaluating GAN quality...");
82    let eval_metrics = qgan.evaluate(&real_data, num_samples)?;
83
84    println!("Evaluation metrics:");
85    println!(
86        "  Real data accuracy: {:.2}%",
87        eval_metrics.real_accuracy * 100.0
88    );
89    println!(
90        "  Fake data accuracy: {:.2}%",
91        eval_metrics.fake_accuracy * 100.0
92    );
93    println!(
94        "  Overall discriminator accuracy: {:.2}%",
95        eval_metrics.overall_accuracy * 100.0
96    );
97    println!("  JS Divergence: {:.4}", eval_metrics.js_divergence);
98
99    // Use physics-specific GAN
100    println!("\nCreating specialized particle physics GAN...");
101    let particle_gan = quantrs2_ml::gan::physics_gan::ParticleGAN::new(
102        num_qubits_gen,
103        num_qubits_disc,
104        latent_dim,
105        data_dim,
106    )?;
107
108    println!("Particle GAN created successfully");
109
110    Ok(())
111}
Source

pub fn generate_conditional( &self, num_samples: usize, conditions: &[(usize, f64)], ) -> Result<Array2<f64>>

Generates samples with specific conditions

Source

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

Evaluates the GAN model

Examples found in repository?
examples/quantum_gan.rs (line 82)
8fn main() -> Result<()> {
9    println!("Quantum Generative Adversarial Network Example");
10    println!("=============================================");
11
12    // GAN parameters
13    let num_qubits_gen = 6;
14    let num_qubits_disc = 6;
15    let latent_dim = 4;
16    let data_dim = 8;
17
18    println!("Creating Quantum GAN...");
19    println!("  Generator: {num_qubits_gen} qubits");
20    println!("  Discriminator: {num_qubits_disc} qubits");
21    println!("  Latent dimension: {latent_dim}");
22    println!("  Data dimension: {data_dim}");
23
24    // Create quantum GAN
25    let mut qgan = QuantumGAN::new(
26        num_qubits_gen,
27        num_qubits_disc,
28        latent_dim,
29        data_dim,
30        GeneratorType::HybridClassicalQuantum,
31        DiscriminatorType::HybridQuantumFeatures,
32    )?;
33
34    // Generate synthetic data for training
35    println!("Generating synthetic data for training...");
36    let real_data = generate_sine_wave_data(500, data_dim);
37
38    // Train GAN
39    println!("Training quantum GAN...");
40    let training_params = [
41        (50, 32, 0.01, 0.01, 1), // (epochs, batch_size, lr_gen, lr_disc, disc_steps)
42    ];
43
44    for (epochs, batch_size, lr_gen, lr_disc, disc_steps) in training_params {
45        println!("Training with parameters:");
46        println!("  Epochs: {epochs}");
47        println!("  Batch size: {batch_size}");
48        println!("  Generator learning rate: {lr_gen}");
49        println!("  Discriminator learning rate: {lr_disc}");
50        println!("  Discriminator steps per iteration: {disc_steps}");
51
52        let start = Instant::now();
53        let history = qgan.train(&real_data, epochs, batch_size, lr_gen, lr_disc, disc_steps)?;
54
55        println!("Training completed in {:.2?}", start.elapsed());
56        println!("Final losses:");
57        println!(
58            "  Generator: {:.4}",
59            history.gen_losses.last().unwrap_or(&0.0)
60        );
61        println!(
62            "  Discriminator: {:.4}",
63            history.disc_losses.last().unwrap_or(&0.0)
64        );
65    }
66
67    // Generate samples
68    println!("\nGenerating samples from trained GAN...");
69    let num_samples = 10;
70    let generated_samples = qgan.generate(num_samples)?;
71
72    println!("Generated {num_samples} samples");
73    println!("First sample:");
74    print_sample(
75        &generated_samples
76            .slice(scirs2_core::ndarray::s![0, ..])
77            .to_owned(),
78    );
79
80    // Evaluate GAN
81    println!("\nEvaluating GAN quality...");
82    let eval_metrics = qgan.evaluate(&real_data, num_samples)?;
83
84    println!("Evaluation metrics:");
85    println!(
86        "  Real data accuracy: {:.2}%",
87        eval_metrics.real_accuracy * 100.0
88    );
89    println!(
90        "  Fake data accuracy: {:.2}%",
91        eval_metrics.fake_accuracy * 100.0
92    );
93    println!(
94        "  Overall discriminator accuracy: {:.2}%",
95        eval_metrics.overall_accuracy * 100.0
96    );
97    println!("  JS Divergence: {:.4}", eval_metrics.js_divergence);
98
99    // Use physics-specific GAN
100    println!("\nCreating specialized particle physics GAN...");
101    let particle_gan = quantrs2_ml::gan::physics_gan::ParticleGAN::new(
102        num_qubits_gen,
103        num_qubits_disc,
104        latent_dim,
105        data_dim,
106    )?;
107
108    println!("Particle GAN created successfully");
109
110    Ok(())
111}

Trait Implementations§

Source§

impl Clone for QuantumGAN

Source§

fn clone(&self) -> QuantumGAN

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 QuantumGAN

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