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

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