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

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